@arkade-os/swap 0.1.0-rc.13 → 0.1.0-rc.15

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 (53) hide show
  1. package/README.md +11 -0
  2. package/dist/advanced.cjs +1028 -1006
  3. package/dist/advanced.d.cts +145 -279
  4. package/dist/advanced.d.ts +145 -279
  5. package/dist/advanced.js +14 -8
  6. package/dist/{chunk-SC3SAY3X.js → chunk-4WPDXLXH.js} +501 -271
  7. package/dist/chunk-A3SHHRX4.js +104 -0
  8. package/dist/{chunk-KRXPQQJ7.js → chunk-BBP25BWH.js} +198 -218
  9. package/dist/{chunk-ZDFMD4FA.js → chunk-RX3WPV5D.js} +356 -584
  10. package/dist/errors-BcOgFV-F.d.ts +1559 -0
  11. package/dist/errors-n6IHTG-Z.d.cts +1559 -0
  12. package/dist/index.cjs +1406 -1331
  13. package/dist/index.d.cts +69 -186
  14. package/dist/index.d.ts +69 -186
  15. package/dist/index.js +102 -158
  16. package/dist/lockupContract-B_jNbjrG.d.ts +215 -0
  17. package/dist/lockupContract-ZsftgqMc.d.cts +215 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +227 -600
  20. package/dist/node/index.d.ts +227 -600
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +11 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer--1zVkNsV.d.ts +261 -0
  27. package/dist/offer-DsP1q6GE.d.cts +261 -0
  28. package/dist/protocol.cjs +747 -1012
  29. package/dist/protocol.d.cts +120 -255
  30. package/dist/protocol.d.ts +120 -255
  31. package/dist/protocol.js +146 -149
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BY6GUQiW.d.ts +2233 -0
  41. package/dist/repository-C32GKpR5.d.cts +2233 -0
  42. package/dist/{rfq-BWE8qkV2.d.ts → rfq-60PGpQ_x.d.cts} +178 -408
  43. package/dist/{rfq-BWE8qkV2.d.cts → rfq-60PGpQ_x.d.ts} +178 -408
  44. package/dist/{watch-D8Z78RAV.d.ts → watch-Cejw5cNQ.d.cts} +12 -30
  45. package/dist/{watch-C4ReJR5z.d.cts → watch-D8uzWrHc.d.ts} +12 -30
  46. package/package.json +2 -2
  47. package/dist/chunk-U7VWWTL6.js +0 -66
  48. package/dist/errors-LXMcNhNS.d.ts +0 -2222
  49. package/dist/errors-XUs8r0LT.d.cts +0 -2222
  50. package/dist/lockupContract-BhMebZCb.d.cts +0 -650
  51. package/dist/lockupContract-CAiN97fX.d.ts +0 -650
  52. package/dist/repository-BJLuVFQ0.d.ts +0 -3436
  53. package/dist/repository-DsR3b0JJ.d.cts +0 -3436
package/dist/protocol.cjs CHANGED
@@ -161,12 +161,12 @@ __export(protocol_exports, {
161
161
  module.exports = __toCommonJS(protocol_exports);
162
162
 
163
163
  // src/activity.ts
164
- var import_sdk12 = require("@arkade-os/sdk");
164
+ var import_sdk13 = require("@arkade-os/sdk");
165
165
  var import_base11 = require("@scure/base");
166
166
 
167
167
  // src/swapManager.ts
168
168
  var import_base10 = require("@scure/base");
169
- var import_sdk9 = require("@arkade-os/sdk");
169
+ var import_sdk10 = require("@arkade-os/sdk");
170
170
 
171
171
  // src/onchainHtlc.ts
172
172
  var import_base = require("@scure/base");
@@ -182,6 +182,28 @@ var ONCHAIN_DUST_SATS = BigInt(330);
182
182
  var newPreimage = () => crypto.getRandomValues(new Uint8Array(32));
183
183
  var paymentHashOf = (preimage) => import_base.hex.encode((0, import_sha2.sha256)(preimage));
184
184
  var h160FromPaymentHash = (paymentHash) => (0, import_legacy.ripemd160)(import_base.hex.decode(paymentHash));
185
+ var assertPreimageMatches = (preimage, preimageHash) => {
186
+ if (import_base.hex.encode((0, import_legacy.ripemd160)((0, import_sha2.sha256)(preimage))) !== import_base.hex.encode(preimageHash)) {
187
+ throw new Error("preimage does not match the covenant's payment hash");
188
+ }
189
+ };
190
+ var gateError = (reason, message) => {
191
+ const error = new Error(message);
192
+ error.reason = reason;
193
+ return error;
194
+ };
195
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
196
+ async function pollUntil(probe, options, reason, message) {
197
+ const pollMs = options.pollMs ?? 5e3;
198
+ for (; ; ) {
199
+ const value = await probe();
200
+ if (value !== void 0) return value;
201
+ if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
202
+ throw gateError(reason, message);
203
+ }
204
+ await sleep(pollMs);
205
+ }
206
+ }
185
207
  var L1_NETWORKS = {
186
208
  bitcoin: btc.NETWORK,
187
209
  testnet: btc.TEST_NETWORK,
@@ -337,29 +359,24 @@ function extractPreimage(txHex, paymentHash) {
337
359
  }
338
360
  return null;
339
361
  }
340
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
341
362
  async function awaitOnchainFill(chain, htlc, minConfirmations, options = {}) {
342
- const pollMs = options.pollMs ?? 5e3;
343
- for (; ; ) {
344
- const utxos = await chain.getScriptUtxos(htlc.pkScript);
345
- const eligible = utxos.filter((u) => u.confirmations >= minConfirmations).sort((a, b) => b.amount > a.amount ? 1 : -1);
346
- if (eligible[0]) return eligible[0];
347
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
348
- const error = new Error("HTLC was not filled before the deadline");
349
- error.reason = "fill_timeout";
350
- throw error;
351
- }
352
- await sleep(pollMs);
353
- }
363
+ return pollUntil(
364
+ async () => {
365
+ const utxos = await chain.getScriptUtxos(htlc.pkScript);
366
+ return utxos.filter((u) => u.confirmations >= minConfirmations).sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
367
+ },
368
+ options,
369
+ "fill_timeout",
370
+ "HTLC was not filled before the deadline"
371
+ );
354
372
  }
355
373
  async function claimOnchainFill(chain, input) {
356
374
  const now = input.now ?? Math.floor(Date.now() / 1e3);
357
375
  if (input.htlc.refundLocktime - now < ONCHAIN_CLAIM_MARGIN_SECONDS) {
358
- const error = new Error(
376
+ throw gateError(
377
+ "claim_window_closed",
359
378
  "refund leaf opens too soon to claim safely \u2014 take the covenant refund instead"
360
379
  );
361
- error.reason = "claim_window_closed";
362
- throw error;
363
380
  }
364
381
  const spend = await buildHtlcClaim(input);
365
382
  const txid = await chain.broadcast(spend.txHex);
@@ -393,14 +410,14 @@ async function classifyOnchainHtlc(chain, input) {
393
410
  // src/refund.ts
394
411
  var import_base7 = require("@scure/base");
395
412
  var import_sha24 = require("@noble/hashes/sha2.js");
396
- var import_sdk6 = require("@arkade-os/sdk");
413
+ var import_sdk7 = require("@arkade-os/sdk");
397
414
 
398
415
  // src/rfq.ts
399
416
  var import_base6 = require("@scure/base");
400
417
  var import_solver_discovery = require("@arkade-os/solver-discovery");
401
418
  var import_legacy2 = require("@noble/hashes/legacy.js");
402
- var import_sdk4 = require("@arkade-os/sdk");
403
419
  var import_sdk5 = require("@arkade-os/sdk");
420
+ var import_sdk6 = require("@arkade-os/sdk");
404
421
 
405
422
  // src/claimPacket.ts
406
423
  var import_base2 = require("@scure/base");
@@ -427,10 +444,7 @@ async function sealWithEntropy(input, ephemeralKey, nonce) {
427
444
  const key = (0, import_hkdf.hkdf)(import_sha22.sha256, sharedX, ephemeralPub, HKDF_INFO, 32);
428
445
  if (nonce.length !== 12) throw new Error("nonce must be 12 bytes");
429
446
  const sealed = (0, import_aes.gcm)(key, nonce, ephemeralPub).encrypt(input.preimage);
430
- const ciphertext = new Uint8Array(33 + 12 + sealed.length);
431
- ciphertext.set(ephemeralPub, 0);
432
- ciphertext.set(nonce, 33);
433
- ciphertext.set(sealed, 45);
447
+ const ciphertext = (0, import_utils.concatBytes)(ephemeralPub, nonce, sealed);
434
448
  return {
435
449
  ciphertext: import_base2.base64.encode(ciphertext),
436
450
  packet: import_base2.base64.encode(
@@ -469,8 +483,8 @@ var LockupRegistrationFailed = class extends Error {
469
483
  /** The lockup address that was never registered — never fund it: nothing
470
484
  * is watching it. */
471
485
  address;
472
- /** The covenant the row would have been written from — the other half of
473
- * `registerLockupContract`, so the write is retryable without a quote. */
486
+ /** The covenant the row would have been written from, so the write is retryable without a
487
+ * quote. */
474
488
  script;
475
489
  constructor(script, address, cause) {
476
490
  super(`failed to register the lockup contract for ${address}`, { cause });
@@ -503,7 +517,7 @@ async function lockupContractParams(contracts, lockupAddress) {
503
517
  // src/offer.ts
504
518
  var import_base5 = require("@scure/base");
505
519
  var import_utils2 = require("@scure/btc-signer/utils.js");
506
- var import_sdk3 = require("@arkade-os/sdk");
520
+ var import_sdk4 = require("@arkade-os/sdk");
507
521
 
508
522
  // src/swap-want-asset.program.json
509
523
  var swap_want_asset_program_default = {
@@ -630,11 +644,20 @@ async function retireOfferContract(manager, swaps, script) {
630
644
  // src/store.ts
631
645
  var import_base4 = require("@scure/base");
632
646
  var import_sha23 = require("@noble/hashes/sha2.js");
647
+ var import_sdk3 = require("@arkade-os/sdk");
648
+
649
+ // src/repository.ts
633
650
  var import_sdk2 = require("@arkade-os/sdk");
651
+ var collectAssetSwaps = (repository) => (0, import_sdk2.collectPages)((page) => repository.getAssetSwapsPage(page));
652
+ var collectRfqSwaps = (repository, filter = {}) => (0, import_sdk2.collectPages)(
653
+ (page) => repository.getRfqSwapsPage(filter, page)
654
+ );
655
+
656
+ // src/store.ts
634
657
  var BTC_ASSET_ID = "btc";
635
658
  var byNewest = (a, b) => b.createdAt - a.createdAt;
636
659
  var getAssetSwapsOrThrow = async (repository) => {
637
- return (await repository.getAllSwaps()).filter(
660
+ return (await collectAssetSwaps(repository)).filter(
638
661
  (s) => s && typeof s.id === "string" && // offer swaps carry the TLV; onchain-corridor swaps carry
639
662
  // the payment hash instead — either marks a valid record
640
663
  (typeof s.offerHex === "string" || typeof s.paymentHash === "string")
@@ -724,7 +747,7 @@ var preimageForSwapRecord = async (wallet, record) => {
724
747
  }
725
748
  let preimage;
726
749
  try {
727
- preimage = await (0, import_sdk2.contractPreimage)(wallet, record.signingDescriptor, { stored, salt });
750
+ preimage = await (0, import_sdk3.contractPreimage)(wallet, record.signingDescriptor, { stored, salt });
728
751
  } catch (cause) {
729
752
  throw new PreimageNotRecoverableError(
730
753
  "not-derivable",
@@ -743,8 +766,8 @@ var preimageForSwapRecord = async (wallet, record) => {
743
766
 
744
767
  // src/offer.ts
745
768
  var swapPrograms = {
746
- wantAsset: import_sdk3.arkade.parseArtifact(swap_want_asset_program_default),
747
- wantBtc: import_sdk3.arkade.parseArtifact(swap_want_btc_program_default)
769
+ wantAsset: import_sdk4.arkade.parseArtifact(swap_want_asset_program_default),
770
+ wantBtc: import_sdk4.arkade.parseArtifact(swap_want_btc_program_default)
748
771
  };
749
772
  function withExitClosure(program, exit) {
750
773
  if (!exit) return program;
@@ -791,7 +814,7 @@ function swapProgramBinding(offer, operatorPubkey) {
791
814
  }
792
815
  function offerContract(offer, operatorPubkey) {
793
816
  const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
794
- return new import_sdk3.arkade.ArkadeProgramScript(program, args, keys);
817
+ return new import_sdk4.arkade.ArkadeProgramScript(program, args, keys);
795
818
  }
796
819
  var OFFER_PACKET_TYPE = 3;
797
820
  var FIELDS = {
@@ -906,9 +929,7 @@ function decodeOffer(data) {
906
929
  }
907
930
  const need = (name) => {
908
931
  const v = fields[name];
909
- const len = FIELDS[name].width;
910
- if (!v || len !== void 0 && v.length !== len)
911
- throw new Error(`missing/invalid ${name}`);
932
+ if (!v) throw new Error(`missing/invalid ${name}`);
912
933
  return v;
913
934
  };
914
935
  const amount = need("wantAmount");
@@ -930,8 +951,8 @@ function decodeOffer(data) {
930
951
  return {
931
952
  swapPkScript: need("swapPkScript"),
932
953
  wantAmount: readU64(amount),
933
- ...fields.wantAsset && { wantAsset: import_sdk3.asset.AssetId.fromBytes(fields.wantAsset) },
934
- ...fields.offerAsset && { offerAsset: import_sdk3.asset.AssetId.fromBytes(fields.offerAsset) },
954
+ ...fields.wantAsset && { wantAsset: import_sdk4.asset.AssetId.fromBytes(fields.wantAsset) },
955
+ ...fields.offerAsset && { offerAsset: import_sdk4.asset.AssetId.fromBytes(fields.offerAsset) },
935
956
  makerPkScript: need("makerPkScript"),
936
957
  makerPublicKey: need("makerPublicKey"),
937
958
  emulatorPubkey: need("emulatorPubkey"),
@@ -949,28 +970,21 @@ var OFFER_CONTRACT_LABEL = "Arkade swap offer";
949
970
  var OFFER_CONTRACT_KIND = "asset-swap-offer";
950
971
  async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript) {
951
972
  const contractManager = await wallet.getContractManager();
952
- const client = await import_sdk3.arkade.Arkade.connect({
953
- // Registration derives and persists; it never broadcasts and never
954
- // reads UTXOs, so the only thing the client needs off the server is the
955
- // info the caller already resolved. Handing that back — rather than a
956
- // provider built from a URL — is what lets `createOffer` take just a
957
- // wallet, and spares a second `/v1/info` round-trip.
958
- arkade: { getInfo: async () => info },
959
- identity: wallet.identity,
960
- // without this the row's `address` would be derived against the SDK's
961
- // default network while its script is right — a row that disagrees with
962
- // the address the user is about to fund
963
- network: (0, import_sdk3.networkFromArkadeInfo)(info),
964
- contractManager
965
- });
973
+ const client = await derivingClient(wallet, info, contractManager);
966
974
  await contractManager.createContract(
967
975
  offerContractParams(client, binding, operatorPubkey, expectedPkScript)
968
976
  );
969
977
  await promoteOfferContract(contractManager, import_base5.hex.encode(expectedPkScript));
970
978
  }
979
+ var derivingClient = (wallet, info, contractManager) => import_sdk4.arkade.Arkade.connect({
980
+ arkade: { getInfo: async () => info },
981
+ identity: wallet.identity,
982
+ network: (0, import_sdk4.networkFromArkadeInfo)(info),
983
+ contractManager
984
+ });
971
985
  function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
972
986
  const { program, args, keys } = swapProgramBinding(binding, operatorPubkey);
973
- const contract = new import_sdk3.arkade.ArkadeContract(client, program, args, keys);
987
+ const contract = new import_sdk4.arkade.ArkadeContract(client, program, args, keys);
974
988
  if (import_base5.hex.encode(contract.pkScript) !== import_base5.hex.encode(expectedPkScript)) {
975
989
  throw new Error("derived covenant does not match the offer's swapPkScript");
976
990
  }
@@ -989,47 +1003,69 @@ function serverExitDelay(delay) {
989
1003
  return assertExitDelay({ value: delay, type: delay < BigInt(512) ? "blocks" : "seconds" });
990
1004
  }
991
1005
  async function createOffer(wallet, params) {
1006
+ const derived = await deriveOffer(wallet, params);
1007
+ await registerDerivedOffer(wallet, derived);
1008
+ return {
1009
+ offerHex: derived.offerHex,
1010
+ extension: derived.extension,
1011
+ address: derived.address,
1012
+ swapPkScript: derived.swapPkScript
1013
+ };
1014
+ }
1015
+ async function deriveOffer(wallet, params) {
992
1016
  if (Boolean(params.wantAsset) === Boolean(params.offerAsset)) {
993
1017
  throw new Error("set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC)");
994
1018
  }
995
- const [info, makerAddress, makerPublicKey] = await Promise.all([
996
- // requireLive: this info binds signerPubkey into the covenant — a
997
- // snapshot could derive an address the operator no longer co-signs
998
- // for, so an unreachable operator fails the call instead (fail closed,
999
- // the same behaviour the pre-#734 caller-held provider had)
1000
- wallet.getArkadeInfo({ requireLive: true }),
1001
- wallet.getAddress(),
1002
- wallet.identity.xOnlyPublicKey()
1019
+ const [info, maker] = await Promise.all([
1020
+ // requireLive: this binds signerPubkey into the covenant, and a snapshot could derive an
1021
+ // address the operator no longer co-signs for — fail closed instead
1022
+ params.info ?? wallet.getArkadeInfo({ requireLive: true }),
1023
+ params.maker ?? (async () => {
1024
+ const [address, publicKey] = await Promise.all([
1025
+ wallet.getAddress(),
1026
+ wallet.identity.xOnlyPublicKey()
1027
+ ]);
1028
+ return { pkScript: import_sdk4.ArkAddress.decode(address).pkScript, publicKey };
1029
+ })()
1003
1030
  ]);
1004
- const operatorPubKey = import_base5.hex.decode((0, import_sdk3.toXOnlySignerHex)(info.signerPubkey));
1005
- const network = (0, import_sdk3.networkFromArkadeInfo)(info);
1031
+ const operatorPubKey = import_base5.hex.decode((0, import_sdk4.toXOnlySignerHex)(info.signerPubkey));
1032
+ const network = (0, import_sdk4.networkFromArkadeInfo)(info);
1006
1033
  const emuKey = import_base5.hex.decode(
1007
- (0, import_sdk3.toXOnlySignerHex)((0, import_sdk3.resolveEmulatorPubkey)(network, params.emulatorPubkey))
1034
+ (0, import_sdk4.toXOnlySignerHex)((0, import_sdk4.resolveEmulatorPubkey)(network, params.emulatorPubkey))
1008
1035
  );
1009
- const binding = {
1036
+ const binding = Object.freeze({
1010
1037
  wantAmount: params.wantAmount,
1011
1038
  wantAsset: params.wantAsset,
1012
1039
  offerAsset: params.offerAsset,
1013
- makerPkScript: import_sdk3.ArkAddress.decode(makerAddress).pkScript,
1014
- makerPublicKey,
1040
+ makerPkScript: maker.pkScript,
1041
+ makerPublicKey: maker.publicKey,
1015
1042
  emulatorPubkey: emuKey,
1016
- // checked HERE, before the covenant is derived and registered below:
1017
- // deferring it to `encodeOffer` leaves a registered contract behind for
1018
- // an offer that then fails to encode. @see assertExitDelay
1043
+ // checked before registration below. @see assertExitDelay
1019
1044
  exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
1020
- };
1045
+ });
1021
1046
  const script = offerContract(binding, operatorPubKey);
1022
1047
  const offer = { ...binding, swapPkScript: script.pkScript };
1023
- await registerOfferContract(wallet, info, binding, operatorPubKey, script.pkScript);
1024
1048
  const payload = encodeOffer(offer);
1025
- return {
1049
+ return Object.freeze({
1026
1050
  offerHex: import_base5.hex.encode(payload),
1027
1051
  extension: { type: OFFER_PACKET_TYPE, payload },
1028
1052
  // the contract's .address() builds the address; assembling an ArkAddress
1029
1053
  // from tweakedPublicKey here would silently miss any future step it gains
1030
1054
  address: script.address(network.hrp, operatorPubKey).encode(),
1031
- swapPkScript: script.pkScript
1032
- };
1055
+ swapPkScript: script.pkScript,
1056
+ binding,
1057
+ info,
1058
+ operatorPubkey: operatorPubKey
1059
+ });
1060
+ }
1061
+ async function registerDerivedOffer(wallet, derived) {
1062
+ await registerOfferContract(
1063
+ wallet,
1064
+ derived.info,
1065
+ derived.binding,
1066
+ derived.operatorPubkey,
1067
+ derived.swapPkScript
1068
+ );
1033
1069
  }
1034
1070
  async function cancelOffer(wallet, offerHex, opts) {
1035
1071
  const { repository, fundingTxid, swapAddress } = opts;
@@ -1057,7 +1093,6 @@ async function cancelOffer(wallet, offerHex, opts) {
1057
1093
  }
1058
1094
  return txid;
1059
1095
  }
1060
- var OFFER_COVENANT_MISMATCH = "rebuilt covenant does not match the offer's swapPkScript";
1061
1096
  var NoSpendableDepositError = class extends Error {
1062
1097
  name = "NoSpendableDepositError";
1063
1098
  constructor(options) {
@@ -1067,7 +1102,7 @@ var NoSpendableDepositError = class extends Error {
1067
1102
  var OfferCovenantMismatchError = class extends Error {
1068
1103
  constructor(swapPkScript, options) {
1069
1104
  super(
1070
- `${OFFER_COVENANT_MISMATCH} \u2014 the operator signing key pinned by the rebuild does not reproduce the funded covenant; the signing key has likely rotated since funding (pass swapAddress, the funded address, to pin the original key), or the record is corrupt`,
1105
+ "rebuilt covenant does not match the offer's swapPkScript \u2014 the operator signing key pinned by the rebuild does not reproduce the funded covenant; the signing key has likely rotated since funding (pass swapAddress, the funded address, to pin the original key), or the record is corrupt",
1071
1106
  options
1072
1107
  );
1073
1108
  this.swapPkScript = swapPkScript;
@@ -1084,32 +1119,27 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
1084
1119
  wallet.getArkadeReader(),
1085
1120
  wallet.getArkadeBroadcaster()
1086
1121
  ]);
1087
- const client = await import_sdk3.arkade.Arkade.connect({
1088
- // info the wallet already holds, plus its broadcast pair — the shape
1089
- // `ArkadeServerProvider` describes, without a second `/v1/info`
1122
+ const client = await import_sdk4.arkade.Arkade.connect({
1090
1123
  arkade: { getInfo: async () => info, ...broadcaster },
1091
1124
  indexer: reader,
1092
1125
  identity: wallet.identity,
1093
- // registered offers resolve their VTXOs from the contract repository
1094
- // instead of a direct indexer query; the indexer above stays as the
1095
- // fallback for offers created before registration existed
1126
+ // registered offers resolve VTXOs from the contract repository; the indexer is the fallback
1127
+ // for offers created before registration existed
1096
1128
  contractManager
1097
- // no `network`, unlike registerOfferContract: the row lookup is by
1098
- // script and the payout script comes from wallet.getAddress(), so the
1099
- // client's network (which only shapes address derivation) is unused here
1129
+ // no `network`: the row lookup is by script and the payout comes from wallet.getAddress()
1100
1130
  });
1101
- const operatorPubkey = swapAddress ? import_sdk3.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
1131
+ const operatorPubkey = swapAddress ? import_sdk4.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
1102
1132
  const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
1103
1133
  let rebuilt;
1104
1134
  try {
1105
- rebuilt = new import_sdk3.arkade.ArkadeProgramScript(program, args, keys);
1135
+ rebuilt = new import_sdk4.arkade.ArkadeProgramScript(program, args, keys);
1106
1136
  } catch (cause) {
1107
1137
  throw new OfferCovenantMismatchError(import_base5.hex.encode(offer.swapPkScript), { cause });
1108
1138
  }
1109
1139
  if (import_base5.hex.encode(rebuilt.pkScript) !== import_base5.hex.encode(offer.swapPkScript)) {
1110
1140
  throw new OfferCovenantMismatchError(import_base5.hex.encode(offer.swapPkScript));
1111
1141
  }
1112
- const contract = new import_sdk3.arkade.ArkadeContract(client, program, args, keys);
1142
+ const contract = new import_sdk4.arkade.ArkadeContract(client, program, args, keys);
1113
1143
  const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
1114
1144
  if (!fundingTxid && vtxos.length > 1) {
1115
1145
  throw new Error(
@@ -1118,7 +1148,7 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
1118
1148
  }
1119
1149
  const vtxo = fundingTxid ? vtxos.find((v) => v.txid === fundingTxid) : vtxos[0];
1120
1150
  if (!vtxo) throw new NoSpendableDepositError();
1121
- const makerPkScript = import_sdk3.ArkAddress.decode(makerAddress).pkScript;
1151
+ const makerPkScript = import_sdk4.ArkAddress.decode(makerAddress).pkScript;
1122
1152
  const cancel = contract.functions.cancel().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).to(makerPkScript, BigInt(vtxo.value));
1123
1153
  for (const a of vtxo.assets ?? []) {
1124
1154
  cancel.withAsset({
@@ -1133,7 +1163,7 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
1133
1163
  send: async () => (await cancel.send()).txid
1134
1164
  };
1135
1165
  }
1136
- var ASSET_CARRIER_SATS = BigInt(import_sdk3.ASSET_CARRIER_SATS);
1166
+ var ASSET_CARRIER_SATS = BigInt(import_sdk4.ASSET_CARRIER_SATS);
1137
1167
  async function fillOffer(wallet, arkServerUrl, offerHex, opts) {
1138
1168
  const {
1139
1169
  fund,
@@ -1161,29 +1191,25 @@ async function fillOffer(wallet, arkServerUrl, offerHex, opts) {
1161
1191
  }
1162
1192
  }
1163
1193
  const contractManager = await wallet.getContractManager();
1164
- const client = await import_sdk3.arkade.Arkade.connect({
1165
- arkade: new import_sdk3.RestArkProvider(arkServerUrl),
1166
- indexer: new import_sdk3.RestIndexerProvider(arkServerUrl),
1194
+ const client = await import_sdk4.arkade.Arkade.connect({
1195
+ arkade: new import_sdk4.RestArkProvider(arkServerUrl),
1196
+ indexer: new import_sdk4.RestIndexerProvider(arkServerUrl),
1167
1197
  identity: wallet.identity,
1168
1198
  contractManager,
1169
- // `fulfill` is a covenant path, so the emulator executes the arkade
1170
- // script and finalizes with arkd. Without it the spend is built and then
1171
- // refused at submission — there is no default to fall back on.
1172
- emulator: typeof emulator === "string" ? new import_sdk3.RestEmulatorProvider(emulator) : emulator,
1173
- // Only reached for the client's own emulatorKey, which this fill never
1174
- // derives against — the offer's own key is bound below. It still has to
1175
- // resolve, and on a network with no pinned key it throws without this.
1199
+ emulator: typeof emulator === "string" ? new import_sdk4.RestEmulatorProvider(emulator) : emulator,
1200
+ // only for the client's own emulatorKey, which this fill never derives against (the offer's
1201
+ // key is bound below) — but it must still resolve on a network with no pinned key
1176
1202
  ...emulatorPubkey ? { emulatorPubkey } : {}
1177
1203
  });
1178
- const serverKey = swapAddress ? import_sdk3.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
1204
+ const serverKey = swapAddress ? import_sdk4.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
1179
1205
  const { program, args, keys } = swapProgramBinding(offer, serverKey);
1180
- const rebuilt = new import_sdk3.arkade.ArkadeProgramScript(program, args, keys);
1206
+ const rebuilt = new import_sdk4.arkade.ArkadeProgramScript(program, args, keys);
1181
1207
  if (import_base5.hex.encode(rebuilt.pkScript) !== import_base5.hex.encode(offer.swapPkScript)) {
1182
1208
  throw new Error(
1183
1209
  "rebuilt covenant does not match the offer's swapPkScript \u2014 the server signing key has likely rotated since funding; pass swapAddress (the funded address) to pin the original key"
1184
1210
  );
1185
1211
  }
1186
- const contract = new import_sdk3.arkade.ArkadeContract(client, program, args, keys);
1212
+ const contract = new import_sdk4.arkade.ArkadeContract(client, program, args, keys);
1187
1213
  const [vtxos, takerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
1188
1214
  if (!fundingTxid && vtxos.length > 1) {
1189
1215
  throw new Error(
@@ -1201,7 +1227,7 @@ async function fillOffer(wallet, arkServerUrl, offerHex, opts) {
1201
1227
  );
1202
1228
  }
1203
1229
  }
1204
- const payout = payoutScript ?? import_sdk3.ArkAddress.decode(takerAddress).pkScript;
1230
+ const payout = payoutScript ?? import_sdk4.ArkAddress.decode(takerAddress).pkScript;
1205
1231
  const makerSats = wantedAssetId === void 0 ? offer.wantAmount : assetCarrierSats;
1206
1232
  const fill = contract.functions.fulfill().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).fund(fund).to(offer.makerPkScript, makerSats).change(payout);
1207
1233
  const held = /* @__PURE__ */ new Map();
@@ -1247,13 +1273,10 @@ async function fillOffer(wallet, arkServerUrl, offerHex, opts) {
1247
1273
  const { txid } = await fill.send();
1248
1274
  return txid;
1249
1275
  }
1250
- var amountOfAsset = (assets, assetId) => {
1251
- let total = BigInt(0);
1252
- for (const a of assets ?? []) {
1253
- if (a.assetId === assetId) total += BigInt(a.amount);
1254
- }
1255
- return total;
1256
- };
1276
+ var amountOfAsset = (assets, assetId) => (assets ?? []).reduce(
1277
+ (total, a) => a.assetId === assetId ? total + BigInt(a.amount) : total,
1278
+ BigInt(0)
1279
+ );
1257
1280
 
1258
1281
  // src/rfq.ts
1259
1282
  var solverHex = (value, field) => {
@@ -1344,8 +1367,7 @@ var refusalMessage = (reason, detail) => {
1344
1367
  };
1345
1368
  var SwapRefusal = class extends Error {
1346
1369
  /** Literal-typed so the v2 error taxonomy's union discriminates on `name`
1347
- * — a `string` here collapses the discriminant for every member. Same value
1348
- * the constructor has always set, moved to a field initializer. */
1370
+ * — a `string` here collapses the discriminant for every member. */
1349
1371
  name = "SwapRefusal";
1350
1372
  reason;
1351
1373
  rfqId;
@@ -1409,9 +1431,7 @@ var arkadeSwapRequest = (input) => {
1409
1431
  pair,
1410
1432
  amount_side: input.amountSide ?? "from",
1411
1433
  amount: canonicalAssetAmount(input.amount),
1412
- // The pair names the assets; the profile names the trader. Both are
1413
- // covenant parameters, and the solver's `.strict()` schema refuses
1414
- // anything else — an undeclared key is `unsupported_payload`.
1434
+ // The solver's `.strict()` schema refuses any undeclared key as `unsupported_payload`.
1415
1435
  profile: {
1416
1436
  maker_pk_script: normalizeMakerPkScript(input.makerPkScript),
1417
1437
  maker_public_key: normalizeMakerPublicKey(input.makerPublicKey)
@@ -1461,11 +1481,6 @@ var normalizeMakerPublicKey = (value) => {
1461
1481
  return normalizeHexBytes(bytes, 32, "maker_public_key");
1462
1482
  };
1463
1483
  var MIN_HEADROOM_SECONDS = 90 * 60;
1464
- var gateError = (reason, message) => {
1465
- const error = new Error(message);
1466
- error.reason = reason;
1467
- return error;
1468
- };
1469
1484
  var assertFinite = (value, reason, label) => {
1470
1485
  if (value !== void 0 && !Number.isFinite(value)) {
1471
1486
  throw gateError(reason, `${label} is not a finite number (${String(value)})`);
@@ -1734,28 +1749,35 @@ var unilateralClaimDelay = (operatorExitDelaySeconds) => {
1734
1749
  };
1735
1750
  var unilateralRefundDelay = (claimDelay) => claimDelay;
1736
1751
  var unilateralRefundWithoutReceiverDelay = (claimDelay) => claimDelay + SOLO_REFUND_HEADROOM_SECONDS;
1752
+ var seconds = (value) => ({
1753
+ type: "seconds",
1754
+ value: BigInt(value)
1755
+ });
1756
+ var suiteVhtlc = (params, roles) => new import_sdk5.VHTLC.ScriptV2({
1757
+ sender: roles.sender,
1758
+ receiver: roles.receiver,
1759
+ server: params.operatorPubkey,
1760
+ preimageHash: (0, import_legacy2.ripemd160)(import_base6.hex.decode(params.paymentHash)),
1761
+ refundLocktime: BigInt(params.refundLocktime),
1762
+ unilateralClaimDelay: seconds(params.claimDelay),
1763
+ unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
1764
+ unilateralRefundWithoutReceiverDelay: seconds(
1765
+ roles.refundWithoutReceiverDelay ?? unilateralRefundWithoutReceiverDelay(params.claimDelay)
1766
+ ),
1767
+ nonInteractiveParameters: {
1768
+ receiverPkScript: roles.receiverPkScript,
1769
+ senderPkScript: roles.senderPkScript,
1770
+ emulatorPubkey: params.emulatorPubkey,
1771
+ ...params.legacy !== void 0 && { legacy: params.legacy }
1772
+ }
1773
+ });
1737
1774
  function lightningSendContract(params) {
1738
- const seconds = (value) => ({
1739
- type: "seconds",
1740
- value: BigInt(value)
1741
- });
1742
- return new import_sdk4.VHTLC.ScriptV2({
1775
+ return suiteVhtlc(params, {
1743
1776
  sender: params.senderPubkey,
1744
1777
  receiver: params.solverPubkey,
1745
- server: params.operatorPubkey,
1746
- preimageHash: (0, import_legacy2.ripemd160)(import_base6.hex.decode(params.paymentHash)),
1747
- refundLocktime: BigInt(params.refundLocktime),
1748
- unilateralClaimDelay: seconds(params.claimDelay),
1749
- unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
1750
- unilateralRefundWithoutReceiverDelay: seconds(
1751
- params.refundWithoutReceiverDelay ?? unilateralRefundWithoutReceiverDelay(params.claimDelay)
1752
- ),
1753
- nonInteractiveParameters: {
1754
- receiverPkScript: params.receiverPkScript,
1755
- senderPkScript: params.refundPkScript,
1756
- emulatorPubkey: params.emulatorPubkey,
1757
- ...params.legacy !== void 0 && { legacy: params.legacy }
1758
- }
1778
+ senderPkScript: params.refundPkScript,
1779
+ receiverPkScript: params.receiverPkScript,
1780
+ refundWithoutReceiverDelay: params.refundWithoutReceiverDelay
1759
1781
  });
1760
1782
  }
1761
1783
  function deriveLightningSend(input) {
@@ -1778,7 +1800,7 @@ function deriveLightningSend(input) {
1778
1800
  throw new Error("lightning-send quote is missing profile.receiver_pk_script");
1779
1801
  }
1780
1802
  const contractParams = {
1781
- solverPubkey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(quote.solver_pubkey), "solver key"),
1803
+ solverPubkey: (0, import_sdk5.toXOnly)(import_base6.hex.decode(quote.solver_pubkey), "solver key"),
1782
1804
  refundLocktime: quote.refund_locktime,
1783
1805
  operatorPubkey: input.operatorPubkey,
1784
1806
  paymentHash: input.paymentHash,
@@ -1808,7 +1830,7 @@ function deriveLightningSend(input) {
1808
1830
  }
1809
1831
  async function requestLightningSend(wallet, transport, params) {
1810
1832
  const rfqId = params.rfqId ?? newRfqId();
1811
- const secrets = await (0, import_sdk5.provisionRefundKey)(wallet);
1833
+ const secrets = await (0, import_sdk6.provisionRefundKey)(wallet);
1812
1834
  const senderPubkey = secrets.pubkey;
1813
1835
  const refundAddress = secrets.address;
1814
1836
  const info = await wallet.getArkadeInfo({ requireLive: true });
@@ -1827,16 +1849,16 @@ async function requestLightningSend(wallet, transport, params) {
1827
1849
  `quote from_amount ${quote.from_amount} is below the invoice amount \u2014 a negative spread is not a quote`
1828
1850
  );
1829
1851
  }
1830
- const operatorPubkey = (0, import_sdk4.toXOnly)(import_base6.hex.decode(info.signerPubkey), "ark signer key");
1831
- const network = (0, import_sdk4.networkFromArkadeInfo)(info);
1852
+ const operatorPubkey = (0, import_sdk5.toXOnly)(import_base6.hex.decode(info.signerPubkey), "ark signer key");
1853
+ const network = (0, import_sdk5.networkFromArkadeInfo)(info);
1832
1854
  const derived = deriveLightningSend({
1833
1855
  quote,
1834
1856
  paymentHash: params.invoice.paymentHash,
1835
1857
  senderPubkey,
1836
1858
  refundPkScript: secrets.pkScript,
1837
1859
  operatorPubkey,
1838
- emulatorPubkey: (0, import_sdk4.toXOnly)(
1839
- import_base6.hex.decode((0, import_sdk4.resolveEmulatorPubkey)(network, params.emulatorPubkey)),
1860
+ emulatorPubkey: (0, import_sdk5.toXOnly)(
1861
+ import_base6.hex.decode((0, import_sdk5.resolveEmulatorPubkey)(network, params.emulatorPubkey)),
1840
1862
  "emulator signer key"
1841
1863
  ),
1842
1864
  claimDelay,
@@ -1854,8 +1876,6 @@ async function requestLightningSend(wallet, transport, params) {
1854
1876
  rfqId,
1855
1877
  quote,
1856
1878
  address,
1857
- // What the lockup must carry: the quote's `from_amount` — the invoice
1858
- // PLUS the corridor's fee, never the bare invoice amount.
1859
1879
  fundAmount: quoteSats(quote.from_amount, "from_amount"),
1860
1880
  swapPkScript: derived.swapPkScript,
1861
1881
  script,
@@ -1895,7 +1915,16 @@ var assertArkadeFundable = (input) => {
1895
1915
  }
1896
1916
  };
1897
1917
  var quoteCarrierSats = (quote) => {
1898
- const published = quote.carrier_sats === void 0 ? 0n : BigInt(quote.carrier_sats);
1918
+ const raw = quote.carrier_sats;
1919
+ if (raw === void 0) return ASSET_CARRIER_SATS;
1920
+ const canonical = typeof raw === "number" ? Number.isSafeInteger(raw) && raw >= 0 : /^(0|[1-9][0-9]*)$/.test(raw);
1921
+ if (!canonical) {
1922
+ throw gateError(
1923
+ "carrier_malformed",
1924
+ `quote carrier_sats ${String(raw)} is not a non-negative integer`
1925
+ );
1926
+ }
1927
+ const published = BigInt(raw);
1899
1928
  return published > 0n ? published : ASSET_CARRIER_SATS;
1900
1929
  };
1901
1930
  async function requestArkadeSwap(wallet, transport, params) {
@@ -1908,7 +1937,7 @@ async function requestArkadeSwap(wallet, transport, params) {
1908
1937
  wallet.getAddress(),
1909
1938
  wallet.identity.xOnlyPublicKey()
1910
1939
  ]);
1911
- const makerPkScript = import_sdk4.ArkAddress.decode(makerAddress).pkScript;
1940
+ const makerPkScript = import_sdk5.ArkAddress.decode(makerAddress).pkScript;
1912
1941
  const pair = rfqPair(
1913
1942
  params.offerAsset ? arkadeAssetLeg(params.offerAsset) : ARKADE_BTC,
1914
1943
  params.wantAsset ? arkadeAssetLeg(params.wantAsset) : ARKADE_BTC
@@ -1977,6 +2006,18 @@ async function requestArkadeSwap(wallet, transport, params) {
1977
2006
  };
1978
2007
  }
1979
2008
  var l1NetworkFromArk = (network) => network === "bitcoin" ? "bitcoin" : network === "regtest" ? "regtest" : "testnet";
2009
+ var serverTerms = (info, emulatorPubkey) => {
2010
+ const network = (0, import_sdk5.networkFromArkadeInfo)(info);
2011
+ return {
2012
+ operatorPubkey: (0, import_sdk5.toXOnly)(import_base6.hex.decode(info.signerPubkey), "ark signer key"),
2013
+ emulatorPubkey: (0, import_sdk5.toXOnly)(
2014
+ import_base6.hex.decode((0, import_sdk5.resolveEmulatorPubkey)(network, emulatorPubkey)),
2015
+ "emulator signer key"
2016
+ ),
2017
+ claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
2018
+ hrp: network.hrp
2019
+ };
2020
+ };
1980
2021
  var onchainSendRequest = (input) => ({
1981
2022
  v: 1,
1982
2023
  type: "rfq_request",
@@ -2033,7 +2074,7 @@ function deriveOnchainSend(input) {
2033
2074
  throw new Error("onchain-send quote is missing a binding field");
2034
2075
  }
2035
2076
  const contractParams = {
2036
- solverPubkey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(quote.solver_pubkey), "solver key"),
2077
+ solverPubkey: (0, import_sdk5.toXOnly)(import_base6.hex.decode(quote.solver_pubkey), "solver key"),
2037
2078
  refundLocktime,
2038
2079
  operatorPubkey: input.operatorPubkey,
2039
2080
  paymentHash: input.paymentHash,
@@ -2041,7 +2082,7 @@ function deriveOnchainSend(input) {
2041
2082
  emulatorPubkey: input.emulatorPubkey,
2042
2083
  senderPubkey: input.senderPubkey,
2043
2084
  receiverPkScript: solverHex(receiverPkScriptHex, "profile.receiver_pk_script"),
2044
- refundPkScript: import_sdk4.ArkAddress.decode(input.refundAddress).pkScript
2085
+ refundPkScript: import_sdk5.ArkAddress.decode(input.refundAddress).pkScript
2045
2086
  };
2046
2087
  const { script, address } = matchQuotedLockup(
2047
2088
  quote,
@@ -2052,7 +2093,7 @@ function deriveOnchainSend(input) {
2052
2093
  const htlcParams = {
2053
2094
  paymentHash: input.paymentHash,
2054
2095
  claimKey: input.payoutPubkey,
2055
- refundKey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(htlcPubkey), "solver L1 htlc key"),
2096
+ refundKey: (0, import_sdk5.toXOnly)(import_base6.hex.decode(htlcPubkey), "solver L1 htlc key"),
2056
2097
  refundLocktime: htlcLocktime
2057
2098
  };
2058
2099
  const htlc = onchainHtlcScript(htlcParams, input.l1Network);
@@ -2072,7 +2113,7 @@ function deriveOnchainSend(input) {
2072
2113
  }
2073
2114
  async function requestOnchainSend(wallet, transport, params) {
2074
2115
  const rfqId = params.rfqId ?? newRfqId();
2075
- const secrets = await (0, import_sdk5.provisionClaimSecret)(wallet, { preimage: params.preimage });
2116
+ const secrets = await (0, import_sdk6.provisionClaimSecret)(wallet, { preimage: params.preimage });
2076
2117
  if (secrets.mustPersistPreimage) {
2077
2118
  console.warn(
2078
2119
  "[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before funding"
@@ -2096,18 +2137,11 @@ async function requestOnchainSend(wallet, transport, params) {
2096
2137
  })
2097
2138
  );
2098
2139
  assertQuotedAmount(quote, params.amountSide, params.amount);
2099
- const network = (0, import_sdk4.networkFromArkadeInfo)(info);
2100
2140
  const derived = deriveOnchainSend({
2101
2141
  quote,
2102
2142
  paymentHash,
2103
2143
  payoutPubkey: params.payoutPubkey,
2104
- operatorPubkey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(info.signerPubkey), "ark signer key"),
2105
- emulatorPubkey: (0, import_sdk4.toXOnly)(
2106
- import_base6.hex.decode((0, import_sdk4.resolveEmulatorPubkey)(network, params.emulatorPubkey)),
2107
- "emulator signer key"
2108
- ),
2109
- claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
2110
- hrp: network.hrp,
2144
+ ...serverTerms(info, params.emulatorPubkey),
2111
2145
  l1Network: l1NetworkFromArk(info.network),
2112
2146
  refundAddress,
2113
2147
  senderPubkey
@@ -2212,40 +2246,16 @@ var assertReceivable = (input) => {
2212
2246
  }
2213
2247
  };
2214
2248
  function lightningReceiveContract(params) {
2215
- const seconds = (value) => ({
2216
- type: "seconds",
2217
- value: BigInt(value)
2218
- });
2219
- return new import_sdk4.VHTLC.ScriptV2({
2249
+ return suiteVhtlc(params, {
2220
2250
  sender: params.solverPubkey,
2221
2251
  receiver: params.payoutPubkey,
2222
- server: params.operatorPubkey,
2223
- preimageHash: (0, import_legacy2.ripemd160)(import_base6.hex.decode(params.paymentHash)),
2224
- refundLocktime: BigInt(params.refundLocktime),
2225
- unilateralClaimDelay: seconds(params.claimDelay),
2226
- unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
2227
- unilateralRefundWithoutReceiverDelay: seconds(
2228
- unilateralRefundWithoutReceiverDelay(params.claimDelay)
2229
- ),
2230
- nonInteractiveParameters: {
2231
- receiverPkScript: params.payoutPkScript,
2232
- senderPkScript: params.solverRefundPkScript,
2233
- emulatorPubkey: params.emulatorPubkey,
2234
- ...params.legacy !== void 0 && { legacy: params.legacy }
2235
- }
2252
+ senderPkScript: params.solverRefundPkScript,
2253
+ receiverPkScript: params.payoutPkScript
2236
2254
  });
2237
2255
  }
2238
- function deriveLightningReceive(input) {
2239
- const { quote } = input;
2240
- const profile = quote.profile ?? {};
2241
- const refundLocktime = quote.refund_locktime;
2242
- const invoice = profile.invoice;
2243
- const solverRefundPkScriptHex = profile.solver_refund_pk_script;
2244
- if (refundLocktime === void 0 || invoice === void 0 || solverRefundPkScriptHex === void 0) {
2245
- throw new Error("lightning-receive quote is missing a binding field");
2246
- }
2256
+ var matchReceiveLockup = (input, refundLocktime, solverRefundPkScriptHex) => {
2247
2257
  const contractParams = {
2248
- solverPubkey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(quote.solver_pubkey), "solver key"),
2258
+ solverPubkey: (0, import_sdk5.toXOnly)(import_base6.hex.decode(input.quote.solver_pubkey), "solver key"),
2249
2259
  refundLocktime,
2250
2260
  operatorPubkey: input.operatorPubkey,
2251
2261
  paymentHash: input.paymentHash,
@@ -2253,14 +2263,30 @@ function deriveLightningReceive(input) {
2253
2263
  emulatorPubkey: input.emulatorPubkey,
2254
2264
  solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
2255
2265
  payoutPubkey: input.payoutPubkey,
2256
- payoutPkScript: import_sdk4.ArkAddress.decode(input.payoutAddress).pkScript
2266
+ payoutPkScript: import_sdk5.ArkAddress.decode(input.payoutAddress).pkScript
2257
2267
  };
2258
2268
  const matched = matchQuotedLockup(
2259
- quote,
2269
+ input.quote,
2260
2270
  input.hrp,
2261
2271
  input.operatorPubkey,
2262
2272
  (legacy) => lightningReceiveContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
2263
2273
  );
2274
+ return { contractParams, matched };
2275
+ };
2276
+ function deriveLightningReceive(input) {
2277
+ const { quote } = input;
2278
+ const profile = quote.profile ?? {};
2279
+ const refundLocktime = quote.refund_locktime;
2280
+ const invoice = profile.invoice;
2281
+ const solverRefundPkScriptHex = profile.solver_refund_pk_script;
2282
+ if (refundLocktime === void 0 || invoice === void 0 || solverRefundPkScriptHex === void 0) {
2283
+ throw new Error("lightning-receive quote is missing a binding field");
2284
+ }
2285
+ const { contractParams, matched } = matchReceiveLockup(
2286
+ input,
2287
+ refundLocktime,
2288
+ solverRefundPkScriptHex
2289
+ );
2264
2290
  return {
2265
2291
  address: matched.address,
2266
2292
  swapPkScript: matched.script.pkScript,
@@ -2273,12 +2299,11 @@ function deriveLightningReceive(input) {
2273
2299
  }
2274
2300
  };
2275
2301
  }
2276
- async function requestLightningReceive(wallet, transport, params) {
2277
- const rfqId = params.rfqId ?? newRfqId();
2278
- const secrets = await (0, import_sdk5.provisionClaimSecret)(wallet);
2302
+ var provisionReceive = async (wallet, covclaimdPubkey, persistBefore) => {
2303
+ const secrets = await (0, import_sdk6.provisionClaimSecret)(wallet);
2279
2304
  if (secrets.mustPersistPreimage) {
2280
2305
  console.warn(
2281
- "[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before paying"
2306
+ `[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before ${persistBefore}`
2282
2307
  );
2283
2308
  }
2284
2309
  const preimage = secrets.preimage;
@@ -2288,10 +2313,12 @@ async function requestLightningReceive(wallet, transport, params) {
2288
2313
  wallet.getArkadeInfo({ requireLive: true }),
2289
2314
  wallet.getAddress()
2290
2315
  ]);
2291
- const claimPacket = params.covclaimdPubkey ? await sealClaimPacket({
2292
- preimage,
2293
- covclaimdPubkey: params.covclaimdPubkey
2294
- }) : void 0;
2316
+ const claimPacket = covclaimdPubkey ? await sealClaimPacket({ preimage, covclaimdPubkey }) : void 0;
2317
+ return { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket };
2318
+ };
2319
+ async function requestLightningReceive(wallet, transport, params) {
2320
+ const rfqId = params.rfqId ?? newRfqId();
2321
+ const { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket } = await provisionReceive(wallet, params.covclaimdPubkey, "paying");
2295
2322
  const quote = await transport.requestQuote(
2296
2323
  lightningReceiveRequest({
2297
2324
  rfqId,
@@ -2304,19 +2331,12 @@ async function requestLightningReceive(wallet, transport, params) {
2304
2331
  })
2305
2332
  );
2306
2333
  assertQuotedAmount(quote, params.amountSide, params.amount);
2307
- const network = (0, import_sdk4.networkFromArkadeInfo)(info);
2308
2334
  const derived = deriveLightningReceive({
2309
2335
  quote,
2310
2336
  paymentHash,
2311
2337
  payoutPubkey,
2312
2338
  payoutAddress,
2313
- operatorPubkey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(info.signerPubkey), "ark signer key"),
2314
- emulatorPubkey: (0, import_sdk4.toXOnly)(
2315
- import_base6.hex.decode((0, import_sdk4.resolveEmulatorPubkey)(network, params.emulatorPubkey)),
2316
- "emulator signer key"
2317
- ),
2318
- claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
2319
- hrp: network.hrp
2339
+ ...serverTerms(info, params.emulatorPubkey)
2320
2340
  });
2321
2341
  const now = Math.floor(Date.now() / 1e3);
2322
2342
  const { payDeadline } = verifyReceiveInvoice({
@@ -2359,30 +2379,15 @@ function deriveOnchainReceive(input) {
2359
2379
  if (refundLocktime === void 0 || claimPubkey === void 0 || htlcLocktime === void 0 || minConfirmations === void 0 || solverRefundPkScriptHex === void 0) {
2360
2380
  throw new Error("onchain-receive quote is missing a binding field");
2361
2381
  }
2362
- const contractParams = {
2363
- solverPubkey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(quote.solver_pubkey), "solver key"),
2382
+ const { script, address } = matchReceiveLockup(
2383
+ input,
2364
2384
  refundLocktime,
2365
- operatorPubkey: input.operatorPubkey,
2366
- paymentHash: input.paymentHash,
2367
- claimDelay: input.claimDelay,
2368
- emulatorPubkey: input.emulatorPubkey,
2369
- solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
2370
- payoutPubkey: input.payoutPubkey,
2371
- payoutPkScript: import_sdk4.ArkAddress.decode(input.payoutAddress).pkScript
2372
- };
2373
- const { script, address } = matchQuotedLockup(
2374
- quote,
2375
- input.hrp,
2376
- input.operatorPubkey,
2377
- (legacy) => lightningReceiveContract({
2378
- ...contractParams,
2379
- ...legacy !== void 0 && { legacy }
2380
- })
2381
- );
2385
+ solverRefundPkScriptHex
2386
+ ).matched;
2382
2387
  const htlc = onchainHtlcScript(
2383
2388
  {
2384
2389
  paymentHash: input.paymentHash,
2385
- claimKey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(claimPubkey), "solver L1 claim key"),
2390
+ claimKey: (0, import_sdk5.toXOnly)(import_base6.hex.decode(claimPubkey), "solver L1 claim key"),
2386
2391
  refundKey: input.refundPubkey,
2387
2392
  refundLocktime: htlcLocktime
2388
2393
  },
@@ -2401,23 +2406,7 @@ function deriveOnchainReceive(input) {
2401
2406
  }
2402
2407
  async function requestOnchainReceive(wallet, transport, params) {
2403
2408
  const rfqId = params.rfqId ?? newRfqId();
2404
- const secrets = await (0, import_sdk5.provisionClaimSecret)(wallet);
2405
- if (secrets.mustPersistPreimage) {
2406
- console.warn(
2407
- "[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before funding"
2408
- );
2409
- }
2410
- const preimage = secrets.preimage;
2411
- const paymentHash = import_base6.hex.encode(secrets.paymentHash);
2412
- const payoutPubkey = secrets.pubkey;
2413
- const [info, payoutAddress] = await Promise.all([
2414
- wallet.getArkadeInfo({ requireLive: true }),
2415
- wallet.getAddress()
2416
- ]);
2417
- const claimPacket = params.covclaimdPubkey ? await sealClaimPacket({
2418
- preimage,
2419
- covclaimdPubkey: params.covclaimdPubkey
2420
- }) : void 0;
2409
+ const { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket } = await provisionReceive(wallet, params.covclaimdPubkey, "funding");
2421
2410
  const quote = await transport.requestQuote(
2422
2411
  onchainReceiveRequest({
2423
2412
  rfqId,
@@ -2431,20 +2420,13 @@ async function requestOnchainReceive(wallet, transport, params) {
2431
2420
  })
2432
2421
  );
2433
2422
  assertQuotedAmount(quote, params.amountSide, params.amount);
2434
- const network = (0, import_sdk4.networkFromArkadeInfo)(info);
2435
2423
  const derived = deriveOnchainReceive({
2436
2424
  quote,
2437
2425
  paymentHash,
2438
2426
  payoutPubkey,
2439
2427
  payoutAddress,
2440
2428
  refundPubkey: params.refundPubkey,
2441
- operatorPubkey: (0, import_sdk4.toXOnly)(import_base6.hex.decode(info.signerPubkey), "ark signer key"),
2442
- emulatorPubkey: (0, import_sdk4.toXOnly)(
2443
- import_base6.hex.decode((0, import_sdk4.resolveEmulatorPubkey)(network, params.emulatorPubkey)),
2444
- "emulator signer key"
2445
- ),
2446
- claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
2447
- hrp: network.hrp,
2429
+ ...serverTerms(info, params.emulatorPubkey),
2448
2430
  l1Network: l1NetworkFromArk(info.network)
2449
2431
  });
2450
2432
  assertFundable({
@@ -2477,24 +2459,19 @@ async function requestOnchainReceive(wallet, transport, params) {
2477
2459
  }
2478
2460
 
2479
2461
  // src/refund.ts
2480
- var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2481
2462
  var isRfqTerminal = (state) => RFQ_TERMINAL_STATES.includes(state);
2482
2463
  var RFQ_RESOLVED_STATES = ["settled", "refunded"];
2483
2464
  var isResolved = (state) => RFQ_RESOLVED_STATES.includes(state);
2484
2465
  async function awaitRfqResolution(transport, rfqId, options = {}) {
2485
- const pollMs = options.pollMs ?? 5e3;
2486
- for (; ; ) {
2487
- const status = await transport.status(rfqId);
2488
- if (status && isRfqTerminal(status.state)) return status;
2489
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
2490
- const error = new Error(
2491
- `rfq ${rfqId} did not reach a terminal state before the deadline`
2492
- );
2493
- error.reason = "status_timeout";
2494
- throw error;
2495
- }
2496
- await sleep2(pollMs);
2497
- }
2466
+ return pollUntil(
2467
+ async () => {
2468
+ const status = await transport.status(rfqId);
2469
+ return status && isRfqTerminal(status.state) ? status : void 0;
2470
+ },
2471
+ options,
2472
+ "status_timeout",
2473
+ `rfq ${rfqId} did not reach a terminal state before the deadline`
2474
+ );
2498
2475
  }
2499
2476
  var LockupNeedsRecoveryError = class extends Error {
2500
2477
  name = "LockupNeedsRecoveryError";
@@ -2502,15 +2479,8 @@ var LockupNeedsRecoveryError = class extends Error {
2502
2479
  /** `txid:vout` for each output that must be recovered first. */
2503
2480
  outpoints;
2504
2481
  /**
2505
- * The contract's `refundLocktime`. Recovering before this matures is the
2506
- * hazard described above: `recoverVtxos()` sweeps EVERY recoverable output
2507
- * into one settlement with no CLTV awareness, so an early attempt can fail
2508
- * the whole batch — including unrelated outputs that were otherwise fine.
2509
- *
2510
- * Exposed as a value, not only inside the message, so a caller can skip
2511
- * pre-CLTV recoverable outputs without parsing prose. Seconds-based
2512
- * locktimes mature against the chain tip's timestamp rather than wall
2513
- * clock, so treat this as a floor to wait past, not an exact alarm.
2482
+ * The contract's `refundLocktime`; do not recover before it (see above). Seconds-based
2483
+ * locktimes mature against chain time, not wall clock, so treat this as a floor.
2514
2484
  */
2515
2485
  recoverableAfter;
2516
2486
  constructor(outpoints, recoverableAfter) {
@@ -2529,7 +2499,7 @@ async function findLockupVtxos(contracts, swapPkScript) {
2529
2499
  const out = [];
2530
2500
  for (const vtxo of row?.vtxos ?? []) {
2531
2501
  if (vtxo.isUnrolled) continue;
2532
- if ((0, import_sdk6.hasTerminalSpend)(vtxo)) continue;
2502
+ if ((0, import_sdk7.isVtxoSpent)(vtxo)) continue;
2533
2503
  const key = `${vtxo.txid}:${vtxo.vout}`;
2534
2504
  if (seen.has(key)) continue;
2535
2505
  seen.add(key);
@@ -2537,8 +2507,6 @@ async function findLockupVtxos(contracts, swapPkScript) {
2537
2507
  txid: vtxo.txid,
2538
2508
  vout: vtxo.vout,
2539
2509
  value: Number(vtxo.value),
2540
- // The manager's canonical `isSwept` fact; no coercion, because the
2541
- // normalized row guarantees a boolean.
2542
2510
  recoverable: vtxo.isSwept
2543
2511
  });
2544
2512
  }
@@ -2546,14 +2514,14 @@ async function findLockupVtxos(contracts, swapPkScript) {
2546
2514
  }
2547
2515
  var hashesTo = (candidate, paymentHash) => import_base7.hex.encode((0, import_sha24.sha256)(candidate)) === paymentHash;
2548
2516
  var candidateWitnessItems = (tx, inputIndex) => [
2549
- ...(0, import_sdk6.getArkPsbtFields)(tx, inputIndex, import_sdk6.ConditionWitness).flat(),
2517
+ ...(0, import_sdk7.getArkPsbtFields)(tx, inputIndex, import_sdk7.ConditionWitness).flat(),
2550
2518
  ...tx.getInput(inputIndex).finalScriptWitness ?? []
2551
2519
  ];
2552
2520
  async function readLockupFate(indexer, input) {
2553
2521
  const { vtxos } = await indexer.getVtxos({ scripts: [import_base7.hex.encode(input.swapPkScript)] });
2554
2522
  const all = vtxos ?? [];
2555
2523
  if (all.length === 0) return { fate: "unknown" };
2556
- const exited = all.filter((vtxo) => vtxo.isUnrolled && !(0, import_sdk6.hasTerminalSpend)(vtxo));
2524
+ const exited = all.filter((vtxo) => vtxo.isUnrolled && !(0, import_sdk7.isVtxoSpent)(vtxo));
2557
2525
  if (exited.length > 0) {
2558
2526
  return {
2559
2527
  fate: "exited",
@@ -2563,7 +2531,7 @@ async function readLockupFate(indexer, input) {
2563
2531
  const spentBy = /* @__PURE__ */ new Map();
2564
2532
  let everySpendNamed = true;
2565
2533
  for (const vtxo of all) {
2566
- if (!(0, import_sdk6.hasTerminalSpend)(vtxo)) return { fate: "open" };
2534
+ if (!(0, import_sdk7.isVtxoSpent)(vtxo)) return { fate: "open" };
2567
2535
  if (vtxo.spentBy)
2568
2536
  spentBy.set(vtxo.spentBy, {
2569
2537
  checkpointTxid: vtxo.spentBy,
@@ -2577,7 +2545,7 @@ async function readLockupFate(indexer, input) {
2577
2545
  for (const raw of txs) {
2578
2546
  let tx;
2579
2547
  try {
2580
- tx = import_sdk6.Transaction.fromPSBT(import_base7.base64.decode(raw));
2548
+ tx = import_sdk7.Transaction.fromPSBT(import_base7.base64.decode(raw));
2581
2549
  } catch {
2582
2550
  continue;
2583
2551
  }
@@ -2596,49 +2564,58 @@ async function readLockupFate(indexer, input) {
2596
2564
  }
2597
2565
  return everySpendNamed && observed.size === spentBy.size ? { fate: "returned", spends } : { fate: "unknown" };
2598
2566
  }
2599
- async function pushRefundWithoutReceiver(operator, input) {
2600
- if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
2601
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
2567
+ var assertNoneSwept = (vtxos, contract) => {
2568
+ const swept = vtxos.filter((vtxo) => vtxo.recoverable);
2602
2569
  if (swept.length > 0) {
2603
2570
  throw new LockupNeedsRecoveryError(
2604
2571
  swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
2605
- input.contract.options.refundLocktime
2572
+ contract.options.refundLocktime
2606
2573
  );
2607
2574
  }
2575
+ };
2576
+ var operatorUnrollScript = async (operator, network) => {
2577
+ const info = await operator.getInfo();
2578
+ return (0, import_sdk7.assertValidServerUnrollScript)(
2579
+ info.checkpointTapscript,
2580
+ (0, import_sdk7.resolveCheckpointExitDelayPolicy)(network ?? (0, import_sdk7.networkFromArkadeInfo)(info), {
2581
+ advertisedForfeitPubkey: (0, import_sdk7.toXOnly)(import_base7.hex.decode(info.forfeitPubkey), "forfeit key")
2582
+ })
2583
+ );
2584
+ };
2585
+ var lockupInputs = (vtxos, contract, leaf) => {
2586
+ const tapTree = contract.encode();
2587
+ return vtxos.map((vtxo) => ({
2588
+ txid: vtxo.txid,
2589
+ vout: vtxo.vout,
2590
+ value: vtxo.value,
2591
+ tapLeafScript: leaf,
2592
+ tapTree
2593
+ }));
2594
+ };
2595
+ async function pushRefundWithoutReceiver(operator, input) {
2596
+ if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
2597
+ assertNoneSwept(input.vtxos, input.contract);
2608
2598
  const refundPkScript = input.refundPkScript ?? input.contract.options.nonInteractiveParameters?.senderPkScript;
2609
2599
  if (!refundPkScript) {
2610
2600
  throw new Error(
2611
2601
  "no refund destination: the contract carries no emulator covenant suite, so pass refundPkScript explicitly"
2612
2602
  );
2613
2603
  }
2614
- const info = await operator.getInfo();
2615
- let operatorUnrollScript;
2616
- try {
2617
- operatorUnrollScript = import_sdk6.CSVMultisigTapscript.decode(import_base7.hex.decode(info.checkpointTapscript));
2618
- } catch {
2619
- throw new Error("invalid checkpointTapscript from the operator");
2620
- }
2604
+ const serverUnrollScript = await operatorUnrollScript(operator, input.network);
2621
2605
  const leaf = input.contract.refundWithoutReceiver();
2622
- const tapTree = input.contract.encode();
2623
2606
  const amount = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
2624
- const { arkTx: tx, checkpoints } = (0, import_sdk6.buildOffchainTx)(
2625
- input.vtxos.map((vtxo) => ({
2626
- txid: vtxo.txid,
2627
- vout: vtxo.vout,
2628
- value: vtxo.value,
2629
- tapLeafScript: leaf,
2630
- tapTree
2631
- })),
2607
+ const { arkTx: tx, checkpoints } = (0, import_sdk7.buildOffchainTx)(
2608
+ lockupInputs(input.vtxos, input.contract, leaf),
2632
2609
  [{ script: refundPkScript, amount: BigInt(amount) }],
2633
- operatorUnrollScript
2610
+ serverUnrollScript
2634
2611
  );
2635
2612
  const signedTx = await input.sender.sign(tx);
2636
2613
  const submitted = await operator.submitTx(
2637
2614
  import_base7.base64.encode(signedTx.toPSBT()),
2638
2615
  checkpoints.map((c) => import_base7.base64.encode(c.toPSBT()))
2639
2616
  );
2640
- (0, import_sdk6.assertSubmittedArkTxid)(submitted, signedTx, "refundWithoutReceiver");
2641
- const matched = (0, import_sdk6.matchServerCheckpoints)(
2617
+ (0, import_sdk7.assertSubmittedArkTxid)(submitted, signedTx, "refundWithoutReceiver");
2618
+ const matched = (0, import_sdk7.matchServerCheckpoints)(
2642
2619
  submitted.signedCheckpointTxs,
2643
2620
  checkpoints,
2644
2621
  "refundWithoutReceiver"
@@ -2697,16 +2674,22 @@ async function refundIfUnresolved(transport, operator, contracts, indexer, input
2697
2674
  if (now() >= attemptDeadline) throw error;
2698
2675
  }
2699
2676
  }
2700
- await sleep2(pollMs);
2677
+ await sleep(pollMs);
2701
2678
  }
2702
2679
  }
2703
2680
 
2704
2681
  // src/rfqRecord.ts
2705
- var import_sdk7 = require("@arkade-os/sdk");
2682
+ var import_sdk8 = require("@arkade-os/sdk");
2706
2683
  var import_base9 = require("@scure/base");
2707
2684
 
2708
2685
  // src/rfqSwapState.ts
2709
2686
  var RFQ_SWAP_TERMINAL_STATES = ["settled", "refunded", "failed"];
2687
+ var RFQ_SWAP_ACTIVE_STATES = [
2688
+ "pending",
2689
+ "claimable",
2690
+ "claimed",
2691
+ "needs_counterparty"
2692
+ ];
2710
2693
  var isRfqSwapTerminal = (state) => RFQ_SWAP_TERMINAL_STATES.includes(state);
2711
2694
 
2712
2695
  // src/rfqCorridor.ts
@@ -2720,20 +2703,12 @@ var RfqCorridorRegistry = class {
2720
2703
  }
2721
2704
  this.handlers.set(handler.kind, handler);
2722
2705
  }
2723
- /** Takes a bare `string`, deliberately, where {@link RfqCorridorHandler.kind}
2724
- * is the manager's union: a lookup key comes off a record a backend handed
2725
- * back, and that it typechecks as a `kind` is a claim about the type, not
2726
- * about what was stored. Narrowing this would read as a check already made. */
2706
+ /** A bare `string` on purpose: the key comes off a stored record, and narrowing it to the
2707
+ * `kind` union would read as a check already made. */
2727
2708
  get(kind) {
2728
2709
  return this.handlers.get(kind);
2729
2710
  }
2730
- /**
2731
- * The handler for a kind, or a loud failure.
2732
- *
2733
- * A record whose corridor is not registered cannot be restored, and
2734
- * guessing would monitor a swap with no idea how to drive it. Names the
2735
- * registered kinds so a missing `register()` call is obvious.
2736
- */
2711
+ /** The handler for a kind, or a loud failure naming the registered kinds. */
2737
2712
  getOrThrow(kind) {
2738
2713
  const handler = this.get(kind);
2739
2714
  if (!handler) {
@@ -2743,9 +2718,6 @@ var RfqCorridorRegistry = class {
2743
2718
  }
2744
2719
  return handler;
2745
2720
  }
2746
- has(kind) {
2747
- return this.handlers.has(kind);
2748
- }
2749
2721
  registeredKinds() {
2750
2722
  return [...this.handlers.keys()];
2751
2723
  }
@@ -2833,15 +2805,12 @@ var LightningSendCorridor = {
2833
2805
  kind: "lightning_send",
2834
2806
  project: () => ({}),
2835
2807
  hydrate: (profile) => hydrateHashlock(profile)
2836
- // No `claimSecret`, deliberately: `provisionRefundKey` mints no preimage at
2837
- // all, and deriving one off the refund descriptor would fail the payment
2838
- // hash check — a `hash-mismatch` on a swap that was never broken.
2808
+ // No `claimSecret`: no preimage was minted, and one derived off the refund descriptor would
2809
+ // fail the payment hash check on a swap that was never broken.
2839
2810
  };
2840
2811
  var LightningReceiveCorridor = {
2841
2812
  kind: "lightning_receive",
2842
- // What the manager holds: the amount gate, and its own claim once it lands.
2843
- // `payoutAddress` comes from the request result and never changes, so the
2844
- // caller writes it once and this leaves it alone.
2813
+ // `payoutAddress` is written once by the caller from the request result; left alone here.
2845
2814
  project: (swap) => {
2846
2815
  const receive = swap;
2847
2816
  return {
@@ -2862,8 +2831,6 @@ var LightningReceiveCorridor = {
2862
2831
  // We are the claimant here, so the preimage material on the hashlock is
2863
2832
  // ours to use.
2864
2833
  claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
2865
- // The other half of claiming: where it pays. Written once at request time
2866
- // and left alone by `project` above, so this hands back what was stored.
2867
2834
  claimDestination: (profile) => profile.payoutAddress,
2868
2835
  activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
2869
2836
  };
@@ -2881,9 +2848,7 @@ function onchainSendProfile(result) {
2881
2848
  }
2882
2849
  var OnchainSendCorridor = {
2883
2850
  kind: "onchain_send",
2884
- // The L1 keys and the network are only in the request result — nothing on
2885
- // `OnchainSendSwap` carries them — so the caller writes them once. What the
2886
- // manager learns as it drives the swap is the fill and our own claim.
2851
+ // The L1 keys and network are written once by the caller; the manager learns fill and claim.
2887
2852
  project: (swap) => {
2888
2853
  const send = swap;
2889
2854
  return {
@@ -2911,10 +2876,8 @@ var OnchainSendCorridor = {
2911
2876
  }
2912
2877
  const htlc = onchainHtlcScript(
2913
2878
  {
2914
- // From the profile, not the covenant: the lockup commits to
2915
- // `hash160(P)`, and the HTLC needs `sha256(P)`. One P
2916
- // unlocks both legs, but only one of the two hashes of it
2917
- // is recoverable here.
2879
+ // From the profile, not the covenant: the lockup commits to `hash160(P)`, the
2880
+ // HTLC needs `sha256(P)`.
2918
2881
  paymentHash,
2919
2882
  claimKey: import_base8.hex.decode(profile.claimKey),
2920
2883
  refundKey: import_base8.hex.decode(profile.refundKey),
@@ -2942,9 +2905,7 @@ var OnchainSendCorridor = {
2942
2905
  // The trader claims the L1 HTLC with P, so this leg's preimage material is
2943
2906
  // ours.
2944
2907
  claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
2945
- // Our own L1 claim only. `funding` is the SOLVER's fill into the HTLC —
2946
- // not a transaction of ours, so grouping it would claim a row this wallet
2947
- // never made.
2908
+ // Our own L1 claim only: `funding` is the solver's tx, not a row this wallet made.
2948
2909
  activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
2949
2910
  };
2950
2911
  rfqCorridorHandlers.register(LightningSendCorridor);
@@ -2972,17 +2933,20 @@ function normalizeRfqSwapRecord(record) {
2972
2933
  ...legacyClaim ? { profile: renameLegacyClaimTxid(record.profile) } : {}
2973
2934
  };
2974
2935
  }
2936
+ var mutableFields = (from) => ({
2937
+ ...from.refundTxid ? { refundTxid: from.refundTxid } : {},
2938
+ ...from.lockupSpendTxids?.length ? { lockupSpendTxids: [...from.lockupSpendTxids] } : {},
2939
+ ...from.settlementPreimageHex ? { settlementPreimageHex: from.settlementPreimageHex } : {},
2940
+ ...from.failure ? { failure: from.failure } : {},
2941
+ ...from.claimFailure ? { claimFailure: from.claimFailure } : {},
2942
+ ...from.blockedReason ? { blockedReason: from.blockedReason } : {}
2943
+ });
2975
2944
  var managerState = (swap) => ({
2976
2945
  rfqId: swap.rfqId,
2977
2946
  state: swap.state,
2978
2947
  createdAt: swap.createdAt,
2979
2948
  updatedAt: swap.updatedAt,
2980
- ...swap.refundTxid ? { refundTxid: swap.refundTxid } : {},
2981
- ...swap.lockupSpendTxids?.length ? { lockupSpendTxids: [...swap.lockupSpendTxids] } : {},
2982
- ...swap.settlementPreimageHex ? { settlementPreimageHex: swap.settlementPreimageHex } : {},
2983
- ...swap.failure ? { failure: swap.failure } : {},
2984
- ...swap.claimFailure ? { claimFailure: swap.claimFailure } : {},
2985
- ...swap.blockedReason ? { blockedReason: swap.blockedReason } : {}
2949
+ ...mutableFields(swap)
2986
2950
  });
2987
2951
  function assertSameSwap(origin, swap) {
2988
2952
  if (origin.kind !== swap.kind) {
@@ -2990,7 +2954,7 @@ function assertSameSwap(origin, swap) {
2990
2954
  `rfq swap record is a ${origin.kind} origin paired with a ${swap.kind} swap`
2991
2955
  );
2992
2956
  }
2993
- const funded = import_base9.hex.encode(import_sdk7.ArkAddress.decode(origin.lockupAddress).pkScript);
2957
+ const funded = import_base9.hex.encode(import_sdk8.ArkAddress.decode(origin.lockupAddress).pkScript);
2994
2958
  const watched = import_base9.hex.encode(swap.lockupPkScript);
2995
2959
  if (funded !== watched) {
2996
2960
  throw new Error(
@@ -3004,8 +2968,6 @@ function createRfqSwapRecord(origin, swap) {
3004
2968
  return {
3005
2969
  ...origin,
3006
2970
  ...managerState(swap),
3007
- // The caller wrote what only the request result knows; the handler adds
3008
- // what the live swap already carries.
3009
2971
  profile: { ...origin.profile, ...handler.project(swap) }
3010
2972
  };
3011
2973
  }
@@ -3039,8 +3001,8 @@ function rfqSwapOriginOf(record) {
3039
3001
  };
3040
3002
  }
3041
3003
  function lockupScript(params, lockupAddress) {
3042
- const script = import_sdk7.VHTLCV2ContractHandler.createScript(params);
3043
- const funded = import_sdk7.ArkAddress.decode(lockupAddress).pkScript;
3004
+ const script = import_sdk8.VHTLCV2ContractHandler.createScript(params);
3005
+ const funded = import_sdk8.ArkAddress.decode(lockupAddress).pkScript;
3044
3006
  if (import_base9.hex.encode(funded) !== import_base9.hex.encode(script.pkScript)) {
3045
3007
  throw new Error(
3046
3008
  `rfq swap covenant params derive ${import_base9.hex.encode(script.pkScript)}, but the record's lockup address holds ${import_base9.hex.encode(funded)} \u2014 these params are not this swap's`
@@ -3061,12 +3023,7 @@ function rebuildRfqSwap(record, params) {
3061
3023
  refundLocktime: Number(script.options.refundLocktime),
3062
3024
  createdAt: stored.createdAt,
3063
3025
  updatedAt: stored.updatedAt,
3064
- ...stored.refundTxid ? { refundTxid: stored.refundTxid } : {},
3065
- ...stored.lockupSpendTxids?.length ? { lockupSpendTxids: [...stored.lockupSpendTxids] } : {},
3066
- ...stored.settlementPreimageHex ? { settlementPreimageHex: stored.settlementPreimageHex } : {},
3067
- ...stored.failure ? { failure: stored.failure } : {},
3068
- ...stored.claimFailure ? { claimFailure: stored.claimFailure } : {},
3069
- ...stored.blockedReason ? { blockedReason: stored.blockedReason } : {}
3026
+ ...mutableFields(stored)
3070
3027
  };
3071
3028
  const handler = rfqCorridorHandlers.getOrThrow(stored.kind);
3072
3029
  return {
@@ -3081,7 +3038,7 @@ function shouldRetainRfqSwap(record, now) {
3081
3038
  }
3082
3039
 
3083
3040
  // src/refundBlocked.ts
3084
- var import_sdk8 = require("@arkade-os/sdk");
3041
+ var import_sdk9 = require("@arkade-os/sdk");
3085
3042
  var RefundNotLocallyPossibleError = class extends Error {
3086
3043
  constructor(reason, message, options) {
3087
3044
  super(message, options);
@@ -3098,16 +3055,16 @@ async function senderIdentityForSwapRecord(wallet, record) {
3098
3055
  );
3099
3056
  }
3100
3057
  try {
3101
- return await (0, import_sdk8.contractSigner)(wallet, record.signingDescriptor);
3058
+ return await (0, import_sdk9.contractSigner)(wallet, record.signingDescriptor);
3102
3059
  } catch (cause) {
3103
- if (cause instanceof import_sdk8.WalletCannotSignError) {
3060
+ if (cause instanceof import_sdk9.WalletCannotSignError) {
3104
3061
  throw new RefundNotLocallyPossibleError(
3105
3062
  "unsignable-wallet",
3106
3063
  `this wallet holds ${record.signingDescriptor} but cannot sign with it; attach its signer`,
3107
3064
  { cause }
3108
3065
  );
3109
3066
  }
3110
- if (cause instanceof import_sdk8.ForeignDescriptorError) {
3067
+ if (cause instanceof import_sdk9.ForeignDescriptorError) {
3111
3068
  throw new RefundNotLocallyPossibleError(
3112
3069
  "foreign-descriptor",
3113
3070
  `this wallet cannot derive ${record.signingDescriptor}; the swap was created on another wallet`,
@@ -3161,7 +3118,8 @@ var notify = (listeners, call) => {
3161
3118
  }
3162
3119
  }
3163
3120
  };
3164
- var RfqSwapManager = class {
3121
+ var RfqSwapManager = class _RfqSwapManager {
3122
+ static POLL_CONCURRENCY = 16;
3165
3123
  deps;
3166
3124
  config;
3167
3125
  callbacks = null;
@@ -3170,62 +3128,40 @@ var RfqSwapManager = class {
3170
3128
  swapFailedListeners = /* @__PURE__ */ new Set();
3171
3129
  actionExecutedListeners = /* @__PURE__ */ new Set();
3172
3130
  monitored = /* @__PURE__ */ new Map();
3173
- /** Monitored swaps by lockup script hex, so a contract event — which names
3174
- * a script and nothing else — can find the swap it belongs to. */
3131
+ /** Monitored swaps by lockup script hex: a contract event names only a script. */
3175
3132
  byLockupScript = /* @__PURE__ */ new Map();
3176
3133
  /**
3177
- * Swaps whose lockup registration has been SETTLED one way or another,
3178
- * mapped to whether a contract row actually resulted. Membership is what
3179
- * stops a per-pass retry from becoming a per-pass round trip; the value is
3180
- * what keeps a swap that could never be registered from later trying to
3181
- * retire a row that does not exist, which would report a spurious failure
3182
- * on a swap that in fact succeeded.
3134
+ * Swaps whose lockup registration has SETTLED, mapped to whether a contract row
3135
+ * resulted. Membership stops per-pass round trips; the value stops a never-registered
3136
+ * swap from retiring a nonexistent row and reporting a spurious failure.
3183
3137
  */
3184
3138
  registered = /* @__PURE__ */ new Map();
3185
3139
  /**
3186
- * Swaps whose `refundArkade` answered {@link RefundNotLocallyPossibleError}
3187
- * in this process. Membership stops the push from being re-issued every
3188
- * pass — it cannot start working on its own, and re-issuing it is the
3189
- * grind `needs_counterparty` exists to remove. Only
3190
- * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it, so a caller
3191
- * with no probe learns again on the next start, when the wallet that can
3192
- * sign may well have been restored.
3140
+ * Swaps whose `refundArkade` threw {@link RefundNotLocallyPossibleError} in this
3141
+ * process, so the push is not re-issued every pass. Only
3142
+ * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it.
3193
3143
  */
3194
3144
  refundRefused = /* @__PURE__ */ new Set();
3195
3145
  /**
3196
- * The lockup outpoints a receive swap's claim callback has already been
3197
- * handed, by rfqId.
3198
- *
3199
- * What this exists to prevent: a claim SUCCEEDS, and for the next few
3200
- * passes the indexer still lists those outputs as unspent. Without a
3201
- * record of what was already claimed, every one of those passes would
3202
- * re-submit the same spend, fail against the server, and report a swap
3203
- * that in fact worked as failing. With one, a re-claim happens only when
3204
- * an outpoint appears that was never claimed — a lockup funded piecemeal,
3205
- * which is legitimate and which `partiallyClaimed` exists for.
3206
- *
3207
- * Process-local: after a restart a swap with a live claim tries once more.
3208
- * That is the recovery case rather than the spam one — a claim that never
3209
- * landed leaves its outputs unspent, and one that did leaves a single
3210
- * rejection.
3146
+ * Lockup outpoints already handed to a receive swap's claim callback, by rfqId. After a
3147
+ * claim SUCCEEDS the indexer may still list its outputs as unspent; without this each
3148
+ * pass would re-submit and report a working swap as failing. Process-local: a restart
3149
+ * costs at most one rejected re-claim.
3211
3150
  */
3212
3151
  claimedOutpoints = /* @__PURE__ */ new Map();
3213
3152
  /** Live `onContractEvent` subscription, held so `stop()` can drop it. */
3214
3153
  unsubscribeContracts = null;
3215
- /** Terminal records, kept so a late {@link waitForSwapCompletion} still
3216
- * answers instead of throwing "not found". Cleared by {@link removeSwap}. */
3154
+ /** Recent terminal swaps; older durable outcomes are read from the record store on demand. */
3217
3155
  finished = /* @__PURE__ */ new Map();
3156
+ /** Explicit removals stay suppressed for this manager lifetime; normal completions never enter this set.
3157
+ * Each maps to its removal sequence, so restore can tell a removal made during its rebuild. */
3158
+ removed = /* @__PURE__ */ new Map();
3159
+ removalSeq = 0;
3218
3160
  waiters = /* @__PURE__ */ new Map();
3219
3161
  /**
3220
- * The request-time origin of each swap the manager may have to CREATE a
3221
- * record for, by rfqId.
3222
- *
3223
- * Needed only for a swap the store has never seen: once a record exists,
3224
- * `updateRfqSwapRecord` carries the origin half through and the map is
3225
- * redundant. It is kept anyway for the swap's whole life, so a record the
3226
- * store loses between passes is rewritten rather than lost — and dropped
3227
- * by {@link removeSwap} and by retention, which are the two places a swap
3228
- * stops being this manager's business.
3162
+ * The request-time origin of each swap, by rfqId, needed to CREATE a record. Kept for
3163
+ * the swap's whole life so a record the store loses is rewritten; dropped by
3164
+ * {@link removeSwap} and by retention.
3229
3165
  */
3230
3166
  origins = /* @__PURE__ */ new Map();
3231
3167
  /** Records changed during the current pass, flushed to the repository and
@@ -3233,6 +3169,8 @@ var RfqSwapManager = class {
3233
3169
  dirty = /* @__PURE__ */ new Set();
3234
3170
  /** Race guard: one action at a time per swap. */
3235
3171
  inProgress = /* @__PURE__ */ new Set();
3172
+ activePolls = 0;
3173
+ pollWaiters = /* @__PURE__ */ new Set();
3236
3174
  timer = null;
3237
3175
  running = false;
3238
3176
  constructor(deps, config = {}) {
@@ -3251,9 +3189,8 @@ var RfqSwapManager = class {
3251
3189
  this.actionExecutedListeners.add(config.events.onActionExecuted);
3252
3190
  }
3253
3191
  }
3254
- /** Wire the money-moving half. Without it the manager only watches. The
3255
- * two claims may be omitted for a consumer that drives no kind reaching
3256
- * them — see {@link AvailableRfqSwapManagerCallbacks}. */
3192
+ /** Wire the money-moving half. Without it the manager only watches. See
3193
+ * {@link AvailableRfqSwapManagerCallbacks}. */
3257
3194
  setCallbacks(callbacks) {
3258
3195
  this.callbacks = callbacks;
3259
3196
  }
@@ -3274,41 +3211,21 @@ var RfqSwapManager = class {
3274
3211
  return () => this.actionExecutedListeners.delete(listener);
3275
3212
  }
3276
3213
  /**
3277
- * Rebuild every stored swap and take over monitoring them.
3278
- *
3279
- * The composition a consumer otherwise writes by hand, and the one place
3280
- * all four pieces meet: retention decides what to keep
3281
- * (`shouldRetainRfqSwap`), the lockup's contract row supplies the covenant
3282
- * (`lockupContractParams`), `rebuildRfqSwap` turns a record back into a
3283
- * live swap, and each rebuilt swap arrives with its own origin, so nothing
3284
- * is asked of the caller.
3285
- *
3286
- * **Deliberately not part of {@link start}.** A consumer that wants to
3287
- * look at its records — count them, show them, prune and stop — is not
3288
- * forced to start driving money to do it. Call this first and `start()`
3289
- * after; a manager already running polls the restored swaps at once.
3290
- *
3291
- * Retention runs BEFORE the rebuild, so a record past
3292
- * `RFQ_SWAP_RETENTION_SECONDS` costs no contract lookup on its way to being
3293
- * dropped.
3294
- *
3295
- * **A record that cannot be rebuilt is reported, never swallowed and never
3296
- * fatal.** `rebuildRfqSwap` throws by design when the covenant params do
3297
- * not derive the funded address, and `lockupContractParams` throws
3298
- * `LockupContractMissing` when the wallet has no row for the lockup — both
3299
- * say something true about that one record, and neither is a reason to
3300
- * strand the others. They come back in {@link RfqRestoreResult.failed}.
3214
+ * Rebuild stored swaps and take over monitoring them. By default only active states
3215
+ * are read; terminal history stays stored and a late completion lookup reads one record
3216
+ * by key (`includeTerminal` loads everything). Deliberately not part of {@link start},
3217
+ * so records can be inspected without driving money. An unrebuildable record lands in
3218
+ * {@link RfqRestoreResult.failed}, never fatal to the others.
3301
3219
  */
3302
3220
  async restoreFromRepository(options = {}) {
3303
3221
  const repository = this.requireRepository("restoreFromRepository");
3304
3222
  const params = options.params ?? this.paramsFromContracts();
3305
- const records = await repository.getAllRfqSwaps();
3306
- const pruned = await this.dropRetired(repository, records);
3307
- const retired = new Set(pruned);
3308
3223
  const restored = [];
3309
3224
  const failed = [];
3310
- for (const record of records) {
3311
- if (retired.has(record.rfqId)) continue;
3225
+ const restore = async (record) => {
3226
+ if (!options.includeTerminal && isRfqSwapTerminal(record.state)) return;
3227
+ if (this.monitored.has(record.rfqId)) return;
3228
+ const removedAt = this.removed.get(record.rfqId);
3312
3229
  let swap;
3313
3230
  try {
3314
3231
  swap = rebuildRfqSwap(record, await params(record));
@@ -3317,38 +3234,37 @@ var RfqSwapManager = class {
3317
3234
  rfqId: record.rfqId,
3318
3235
  error: error instanceof Error ? error : new Error(errorMessage(error))
3319
3236
  });
3320
- continue;
3237
+ return;
3238
+ }
3239
+ if (this.monitored.has(record.rfqId)) return;
3240
+ if (this.removed.get(record.rfqId) !== removedAt) return;
3241
+ this.removed.delete(record.rfqId);
3242
+ if (isRfqSwapTerminal(swap.state)) this.rememberFinished(swap, true);
3243
+ else {
3244
+ this.origins.set(record.rfqId, rfqSwapOriginOf(record));
3245
+ this.track(swap);
3321
3246
  }
3322
- this.origins.set(record.rfqId, rfqSwapOriginOf(record));
3323
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
3324
- else this.track(swap);
3325
3247
  restored.push(swap);
3248
+ };
3249
+ const states = options.includeTerminal ? [void 0] : RFQ_SWAP_ACTIVE_STATES;
3250
+ for (const state of states) {
3251
+ for (const record of await collectRfqSwaps(repository, { state }))
3252
+ await restore(record);
3326
3253
  }
3327
3254
  if (this.running) {
3328
- await Promise.allSettled(
3329
- restored.filter((swap) => this.monitored.has(swap.rfqId)).map((swap) => this.pollSwap(swap))
3330
- );
3255
+ await this.pollMany(restored.filter((swap) => this.monitored.has(swap.rfqId)));
3331
3256
  }
3332
- return { restored, failed, pruned };
3257
+ return { restored, failed, pruned: [] };
3333
3258
  }
3334
3259
  /**
3335
- * Drop stored records that are terminal and past
3336
- * `RFQ_SWAP_RETENTION_SECONDS`, and return their ids.
3337
- *
3338
- * `needs_counterparty` is never dropped, however old: the money is still at
3339
- * the lockup and the counterparty's move still ends the swap. That rule
3340
- * lives in `shouldRetainRfqSwap`, which this defers to rather than
3341
- * restating.
3342
- *
3343
- * Public because retention is a caller's cadence, not the manager's: a
3344
- * long-lived process wants it on a timer of its own, a mobile app wants it
3345
- * at boot. {@link restoreFromRepository} runs it first, so the boot path
3346
- * needs no separate call.
3260
+ * Drop stored records that are terminal and past `RFQ_SWAP_RETENTION_SECONDS` (per
3261
+ * `shouldRetainRfqSwap`), and return their ids. Explicit only: restore keeps history.
3262
+ * Loads every stored record; no backend offers indexed deletion.
3347
3263
  */
3348
3264
  async pruneRetiredSwaps() {
3349
3265
  const repository = this.deps.repository;
3350
3266
  if (!repository) return [];
3351
- return this.dropRetired(repository, await repository.getAllRfqSwaps());
3267
+ return this.dropRetired(repository, await collectRfqSwaps(repository));
3352
3268
  }
3353
3269
  async dropRetired(repository, records) {
3354
3270
  const now = this.config.now();
@@ -3356,12 +3272,15 @@ var RfqSwapManager = class {
3356
3272
  for (const record of records) {
3357
3273
  if (shouldRetainRfqSwap(record, now)) continue;
3358
3274
  await repository.removeRfqSwap(record.rfqId);
3359
- this.finished.delete(record.rfqId);
3360
- if (!this.monitored.has(record.rfqId)) this.origins.delete(record.rfqId);
3275
+ this.forgetRetired(record.rfqId);
3361
3276
  dropped.push(record.rfqId);
3362
3277
  }
3363
3278
  return dropped;
3364
3279
  }
3280
+ forgetRetired(rfqId) {
3281
+ this.finished.delete(rfqId);
3282
+ if (!this.monitored.has(rfqId)) this.origins.delete(rfqId);
3283
+ }
3365
3284
  requireRepository(method) {
3366
3285
  const repository = this.deps.repository;
3367
3286
  if (!repository) {
@@ -3371,9 +3290,7 @@ var RfqSwapManager = class {
3371
3290
  }
3372
3291
  return repository;
3373
3292
  }
3374
- /** The default covenant source: the wallet's own contract row for each
3375
- * lockup, which is where registration put it before the address could be
3376
- * funded. */
3293
+ /** The default covenant source: the wallet's own contract row for each lockup. */
3377
3294
  paramsFromContracts() {
3378
3295
  const contracts = this.deps.contracts;
3379
3296
  if (!contracts) {
@@ -3384,28 +3301,23 @@ var RfqSwapManager = class {
3384
3301
  return (record) => lockupContractParams(contracts, record.lockupAddress);
3385
3302
  }
3386
3303
  /**
3387
- * Load records and begin monitoring. Runs one pass immediately — a caller
3388
- * resuming after a restart may be well past a deadline already — then
3389
- * every `pollIntervalMs`. Records that are already terminal are kept only
3390
- * so {@link waitForSwapCompletion} can answer for them.
3391
- *
3392
- * Calling it again while running loads the records and returns rather than
3393
- * re-arming — dropping them silently would strand a funded swap on a
3394
- * caller's harmless double-start.
3304
+ * Load records and begin monitoring: one pass immediately (a restart may already be
3305
+ * past a deadline), then every `pollIntervalMs`. Terminal outcomes in a repository are
3306
+ * read on demand. Calling it again while running loads the records without re-arming,
3307
+ * so a double-start never strands a funded swap.
3395
3308
  *
3396
- * The signature is unchanged with a {@link RfqSwapManagerDeps.repository}
3397
- * wired; the origins are resolved from the store instead, by the same rule
3398
- * {@link addSwap} applies. A swap the store has never seen throws
3399
- * {@link RfqSwapOriginRequired} — hand that one to `addSwap` with its
3400
- * origin, or restore the whole set with {@link restoreFromRepository},
3401
- * which needs no caller input at all. Every swap is checked before any is
3402
- * tracked, so a bad one in the list does not leave a half-loaded manager.
3309
+ * With a repository wired, a swap the store has never seen throws
3310
+ * {@link RfqSwapOriginRequired} (use {@link addSwap} with its origin, or
3311
+ * {@link restoreFromRepository}). Every swap is checked before any is tracked.
3403
3312
  */
3404
3313
  async start(swaps = []) {
3405
3314
  for (const swap of swaps) await this.admit(swap);
3406
3315
  for (const swap of swaps) {
3407
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
3408
- else this.track(swap);
3316
+ this.removed.delete(swap.rfqId);
3317
+ if (isRfqSwapTerminal(swap.state)) {
3318
+ this.rememberFinished(swap);
3319
+ this.origins.delete(swap.rfqId);
3320
+ } else this.track(swap);
3409
3321
  }
3410
3322
  if (this.running) return;
3411
3323
  this.running = true;
@@ -3414,16 +3326,10 @@ var RfqSwapManager = class {
3414
3326
  this.arm();
3415
3327
  }
3416
3328
  /**
3417
- * Stop monitoring and clear the timer. In-flight actions are not
3418
- * cancellable and run to completion; outstanding
3419
- * {@link waitForSwapCompletion} promises are left pending, since
3420
- * stop/start is a pause rather than a cancellation.
3421
- *
3422
- * The contract subscription is dropped too — an open stream with nothing
3423
- * reacting to it is a leak, and {@link start} puts it back. What is NOT
3424
- * undone is the contract registration: those rows are the wallet's, they
3425
- * outlive this manager's lifecycle, and dropping them would unwatch a
3426
- * lockup that is still funded.
3329
+ * Stop monitoring: clear the timer and drop the contract subscription. In-flight
3330
+ * actions run to completion and {@link waitForSwapCompletion} promises stay pending
3331
+ * (stop/start is a pause). Contract registrations are NOT undone: they are the
3332
+ * wallet's, and dropping them would unwatch a still-funded lockup.
3427
3333
  */
3428
3334
  async stop() {
3429
3335
  this.running = false;
@@ -3435,35 +3341,26 @@ var RfqSwapManager = class {
3435
3341
  this.unsubscribeContracts = null;
3436
3342
  }
3437
3343
  /**
3438
- * Begin monitoring a swap. Polled immediately when the manager is running,
3439
- * so a just-funded swap does not wait out a whole interval.
3344
+ * Begin monitoring a swap; polled immediately when the manager is running.
3440
3345
  *
3441
- * `origin` is the request-time half a live swap cannot carry — the corridor,
3442
- * the funded address, the corridor's profile, the funding txid — and it is
3443
- * what lets the manager write this swap's FIRST record. Supply it whenever
3444
- * a {@link RfqSwapManagerDeps.repository} is wired and the swap is new. It
3445
- * may be omitted for a swap the store already holds a record for, which is
3446
- * then read to confirm it; omitting it for one the store has never seen
3447
- * throws {@link RfqSwapOriginRequired} rather than admitting a swap whose
3448
- * record could never be written. With no repository wired the parameter is
3449
- * inert.
3346
+ * @param origin - The request-time half a live swap cannot carry, needed to write its
3347
+ * FIRST record. Required with a repository wired unless the store already holds the
3348
+ * record (else {@link RfqSwapOriginRequired}). Inert without a repository.
3450
3349
  */
3451
3350
  async addSwap(swap, origin) {
3452
3351
  await this.admit(swap, origin);
3352
+ this.removed.delete(swap.rfqId);
3453
3353
  if (isRfqSwapTerminal(swap.state)) {
3454
- this.finished.set(swap.rfqId, swap);
3354
+ this.rememberFinished(swap);
3355
+ this.origins.delete(swap.rfqId);
3455
3356
  return;
3456
3357
  }
3457
3358
  this.track(swap);
3458
3359
  if (this.running) await this.pollSwap(swap);
3459
3360
  }
3460
3361
  /**
3461
- * Settle where this swap's record will come from, before it is monitored.
3462
- *
3463
- * Three ways it can be answered, in order: the caller passed an origin, one
3464
- * is already remembered from an earlier `addSwap`, or the store holds a
3465
- * record — which is the origin, already written. Only the last costs a read,
3466
- * and only when the first two are absent.
3362
+ * Settle where this swap's record will come from, before it is monitored: a passed
3363
+ * origin, one remembered from an earlier `addSwap`, or the stored record (one read).
3467
3364
  */
3468
3365
  async admit(swap, origin) {
3469
3366
  if (origin) {
@@ -3480,13 +3377,10 @@ var RfqSwapManager = class {
3480
3377
  if (!stored) throw new RfqSwapOriginRequired(swap.rfqId);
3481
3378
  this.origins.set(swap.rfqId, rfqSwapOriginOf(stored));
3482
3379
  }
3483
- /** Forget a swap entirely, monitored or finished.
3484
- *
3485
- * Its contract row is left alone: registration is a wallet-level fact about
3486
- * a script that may still hold money, and this call says only that THIS
3487
- * manager stops driving the swap. Retiring the row is reserved for a swap
3488
- * that reached a terminal state, where the lockup is provably done. */
3380
+ /** Forget a swap entirely, monitored or finished. Its contract row is left alone: the
3381
+ * script may still hold money, and only a terminal swap's row is retired. */
3489
3382
  async removeSwap(rfqId) {
3383
+ this.removed.set(rfqId, ++this.removalSeq);
3490
3384
  this.untrack(rfqId);
3491
3385
  this.finished.delete(rfqId);
3492
3386
  this.registered.delete(rfqId);
@@ -3504,14 +3398,8 @@ var RfqSwapManager = class {
3504
3398
  return [...this.monitored.values()];
3505
3399
  }
3506
3400
  /**
3507
- * Every swap this manager holds — {@link getPendingSwaps} plus the ones
3508
- * that already ended. The two sets are disjoint: a swap leaves `monitored`
3509
- * as it enters `finished`.
3510
- *
3511
- * The finished half is what this process has seen, which after
3512
- * {@link restoreFromRepository} is the stored history minus what retention
3513
- * pruned. A manager that has restored nothing answers with the live swaps
3514
- * alone.
3401
+ * Every swap this manager holds: {@link getPendingSwaps} plus the finished ones this
3402
+ * process has seen (after {@link restoreFromRepository}, the retained history).
3515
3403
  */
3516
3404
  async getAllSwaps() {
3517
3405
  return [...this.monitored.values(), ...this.finished.values()];
@@ -3523,6 +3411,7 @@ var RfqSwapManager = class {
3523
3411
  async isProcessing(rfqId) {
3524
3412
  return this.inProgress.has(rfqId);
3525
3413
  }
3414
+ /** `finishedSwaps` counts terminal swaps cached in memory, not those only in the repository. */
3526
3415
  async getStats() {
3527
3416
  return {
3528
3417
  isRunning: this.running,
@@ -3533,34 +3422,54 @@ var RfqSwapManager = class {
3533
3422
  };
3534
3423
  }
3535
3424
  /**
3536
- * Run one monitoring pass over every swap now.
3537
- *
3538
- * {@link start} calls this on an interval, but it is public on purpose: a
3539
- * caller that sleeps its process (a mobile app resuming, a service worker
3540
- * waking) wants a pass on that event rather than at the next tick. Passes
3541
- * do not overlap per swap — the in-progress lock makes a concurrent call a
3542
- * no-op for any swap already being worked on.
3425
+ * Run one monitoring pass over every swap now, e.g. when a mobile app resumes. Passes
3426
+ * do not overlap per swap: a concurrent call is a no-op for a swap already in progress.
3543
3427
  */
3544
3428
  async poll() {
3545
- await Promise.allSettled([...this.monitored.values()].map((swap) => this.pollSwap(swap)));
3429
+ await this.pollMany([...this.monitored.values()]);
3430
+ }
3431
+ async pollMany(swaps) {
3432
+ for (let i = 0; i < swaps.length; i += _RfqSwapManager.POLL_CONCURRENCY) {
3433
+ await Promise.allSettled(
3434
+ swaps.slice(i, i + _RfqSwapManager.POLL_CONCURRENCY).map((swap) => this.pollSwap(swap))
3435
+ );
3436
+ }
3437
+ }
3438
+ async acquirePollSlot() {
3439
+ if (this.activePolls < _RfqSwapManager.POLL_CONCURRENCY) {
3440
+ this.activePolls++;
3441
+ } else {
3442
+ await new Promise((resolve) => this.pollWaiters.add(resolve));
3443
+ }
3444
+ return () => {
3445
+ const next = this.pollWaiters.values().next().value;
3446
+ if (next) {
3447
+ this.pollWaiters.delete(next);
3448
+ next();
3449
+ } else {
3450
+ this.activePolls--;
3451
+ }
3452
+ };
3546
3453
  }
3547
3454
  /**
3548
- * Resolve once this swap's PAYOUT is decided — which for onchain-send is
3549
- * the L1 claim, not the end of the record's life: once `claimTxid` is set
3550
- * the trader has the coins it swapped for, and what remains is the manager
3551
- * watching the Arkade lockup close. That holds however the record is
3552
- * labelled afterwards, `needs_counterparty` included. Lightning-send has no
3553
- * such split and resolves at `settled`/`refunded`, and so does lightning
3554
- * receive — see {@link isPayoutDecided} for why its own claim txid does not
3555
- * decide it.
3455
+ * Resolve once this swap's PAYOUT is decided: for onchain-send that is the L1 claim
3456
+ * (`claimTxid` set), whatever the record's later label; otherwise `settled`/`refunded`
3457
+ * (see {@link isPayoutDecided}).
3556
3458
  *
3557
- * Rejects only on `failed`. `refunded` resolves: on a send leg a refund is
3558
- * an outcome the caller asked this manager to drive, not an exception. On a
3559
- * receive leg it is the swap being lost, which is still an answer and not
3560
- * an error — read `state`, do not infer success from resolution.
3459
+ * Rejects only on `failed`. `refunded` resolves, and on a receive leg it means the swap
3460
+ * was lost — read `state`, do not infer success from resolution.
3561
3461
  */
3562
3462
  async waitForSwapCompletion(rfqId) {
3563
3463
  const swap = this.monitored.get(rfqId) ?? this.finished.get(rfqId);
3464
+ if (!swap && !this.removed.has(rfqId) && this.deps.repository) {
3465
+ const record = await this.deps.repository.getRfqSwap(rfqId);
3466
+ if (record && !this.removed.has(rfqId) && isRfqSwapTerminal(record.state)) {
3467
+ if (record.state === "failed") {
3468
+ throw new Error(record.failure ?? `swap ${rfqId} failed`);
3469
+ }
3470
+ return outcomeOfRecord(record);
3471
+ }
3472
+ }
3564
3473
  if (!swap) throw new Error(`swap ${rfqId} is not monitored`);
3565
3474
  if (swap.state === "failed") throw new Error(swap.failure ?? `swap ${rfqId} failed`);
3566
3475
  if (isPayoutDecided(swap)) return outcomeOf(swap);
@@ -3575,11 +3484,8 @@ var RfqSwapManager = class {
3575
3484
  this.monitored.set(swap.rfqId, swap);
3576
3485
  this.byLockupScript.set(import_base10.hex.encode(swap.lockupPkScript), swap);
3577
3486
  }
3578
- /** Drops the swap from BOTH indexes. The event index is the one that stops
3579
- * a late event finding a swap that is gone; `pollSwap`'s own
3580
- * `monitored` check would also catch it, and deliberately still does —
3581
- * either alone is sufficient, which is what keeps a future change to one of
3582
- * them from silently re-driving a cancelled swap. */
3487
+ /** Drops the swap from BOTH indexes. `pollSwap`'s `monitored` check also stops a late
3488
+ * event, deliberately redundant so neither change alone re-drives a removed swap. */
3583
3489
  untrack(rfqId) {
3584
3490
  const swap = this.monitored.get(rfqId);
3585
3491
  if (swap) this.byLockupScript.delete(import_base10.hex.encode(swap.lockupPkScript));
@@ -3588,23 +3494,14 @@ var RfqSwapManager = class {
3588
3494
  this.claimedOutpoints.delete(rfqId);
3589
3495
  }
3590
3496
  /**
3591
- * Turn the indexer's push into an extra reason to run a pass — and nothing
3592
- * more.
3497
+ * Turn the indexer's push into an extra reason to run a pass — and nothing more.
3593
3498
  *
3594
- * **This is deliberately not a source of truth.** An event names a script;
3595
- * the reaction is to run the ordinary pass for the swap at that script, and
3596
- * that pass re-reads the lockup through {@link readLockupFate} exactly as
3597
- * the timer's pass does. So an event that is missed, duplicated, reordered
3598
- * or outright FORGED can only cost or save latency — it can never change
3599
- * what this manager believes about a swap, and it can never on its own
3600
- * cause a claim or a refund. That property is what makes it safe to bolt a
3601
- * best-effort stream onto a money path, and it must survive any future
3602
- * change here: the moment an event is BELIEVED rather than merely acted on,
3603
- * a relay outage becomes a correctness problem instead of a latency one.
3604
- *
3605
- * The timer stays armed regardless, and is the failsafe. Every deadline
3606
- * that moves money — `refundLocktime`, the L1 claim window — is an absolute
3607
- * timelock that passes whether or not a single event ever arrives.
3499
+ * **Deliberately not a source of truth.** The pass re-reads the lockup via
3500
+ * {@link readLockupFate}, so a missed, duplicated, reordered or FORGED event only
3501
+ * changes latency, never beliefs, and never causes a claim or refund on its own. This
3502
+ * must survive future changes: a BELIEVED event turns a relay outage into a correctness
3503
+ * bug. The timer stays armed as the failsafe; every money deadline is an absolute
3504
+ * timelock.
3608
3505
  */
3609
3506
  subscribe() {
3610
3507
  if (!this.deps.contracts || this.unsubscribeContracts) return;
@@ -3614,7 +3511,7 @@ var RfqSwapManager = class {
3614
3511
  });
3615
3512
  return;
3616
3513
  }
3617
- if (!(0, import_sdk9.isContractVtxoEvent)(event)) return;
3514
+ if (!(0, import_sdk10.isContractVtxoEvent)(event)) return;
3618
3515
  const swap = this.byLockupScript.get(event.contractScript);
3619
3516
  if (!swap) return;
3620
3517
  void this.pollSwap(swap).catch(() => {
@@ -3622,19 +3519,12 @@ var RfqSwapManager = class {
3622
3519
  });
3623
3520
  }
3624
3521
  /**
3625
- * Register this swap's lockup with the wallet's contract manager, once.
3626
- *
3627
- * The backstop, not the primary site: `requestLightningSend` /
3628
- * `requestOnchainSend` register before the caller can fund, so this covers
3629
- * swaps whose records predate that — and costs nothing when it does not,
3630
- * since `createContract` is first-writer-wins.
3522
+ * Register this swap's lockup with the wallet's contract manager, once. A backstop:
3523
+ * the request entrypoints register before funding, and `createContract` is
3524
+ * first-writer-wins.
3631
3525
  *
3632
- * Best-effort by design: a failure here is reported and retried on the next
3633
- * pass, and never aborts the pass it is part of. Registration buys latency
3634
- * and puts the lockup in the wallet's contract set; it decides nothing. The
3635
- * money path below it reads the indexer directly and is gated on timelocks
3636
- * that a missing contract row has no bearing on, so failing the pass over
3637
- * this would trade a real deadline for a bookkeeping one.
3526
+ * Best-effort: a failure is reported and retried next pass, never aborting this one.
3527
+ * Failing the pass over bookkeeping would trade a real timelock deadline for it.
3638
3528
  */
3639
3529
  async ensureRegistered(swap) {
3640
3530
  const contracts = this.deps.contracts;
@@ -3681,11 +3571,8 @@ var RfqSwapManager = class {
3681
3571
  this.emitFailed(swap, error);
3682
3572
  }
3683
3573
  }
3684
- /** Stop watching a finished swap's lockup. Retained, not deleted: the row
3685
- * is what keeps the lockup's own VTXOs annotatable and its history
3686
- * readable, while `retained` is what drops it from the subscription and
3687
- * the poll — a settled swap that stayed watched would cost the wallet a
3688
- * script for its whole life. Best-effort — the swap is over either way. */
3574
+ /** Stop watching a finished swap's lockup. `retained`, not deleted: the row keeps the
3575
+ * lockup's history readable while leaving the subscription and poll. Best-effort. */
3689
3576
  retireContract(swap) {
3690
3577
  if (!this.deps.contracts || !this.registered.get(swap.rfqId)) return;
3691
3578
  if (!LOCKUP_RETIRABLE.includes(swap.state)) return;
@@ -3700,90 +3587,36 @@ var RfqSwapManager = class {
3700
3587
  }, this.config.pollIntervalMs);
3701
3588
  }
3702
3589
  /*
3703
- * Runs one serialized monitoring pass for a single swap.
3704
- *
3705
- * Flow
3706
- *
3707
- * 1. Prevents concurrent work
3708
- * - Returns immediately if the swap is already in inProgress.
3709
- * - Returns if the swap is no longer in monitored.
3710
- * - Adds the swap ID to inProgress.
3590
+ * One serialized monitoring pass for a single swap. The per-swap lock is released only
3591
+ * after all async work, so overlapping polls cannot submit duplicate claims or refunds.
3711
3592
  *
3712
- * 2. Runs the state machine
3713
- * - Calls runPass(swap).
3714
- * - runPass checks the lockup fate, drives claims, and may initiate refunds.
3715
- *
3716
- * 3. Persists changes
3717
- * - If the pass marked the swap dirty, calls save(swap).
3718
- * - A swap is considered persisted only if all configured sinks succeed:
3719
- * - the repository, and
3720
- * - callbacks.saveSwap, if provided.
3721
- *
3722
- * 4. Completes waiters and finalizes
3723
- * - If persistence succeeds:
3724
- * - clears the dirty flag,
3725
- * - settles waitForSwapCompletion waiters,
3726
- * - moves terminal swaps from monitored to finished,
3727
- * - emits completion or failure notifications through finalize.
3728
- *
3729
- * 5. Releases the per-swap lock
3730
- * - Deletes the swap ID from inProgress only after all asynchronous work completes.
3731
- * - This prevents overlapping poll() calls from submitting duplicate claims or refunds.
3732
- *
3733
- * The important safety property is that terminal state is not finalized until its updated record has been
3734
- * successfully persisted. A failed save leaves the swap dirty and monitored so a later poll can retry.
3593
+ * Safety property: terminal state is not finalized until its record is persisted to
3594
+ * every configured sink. A failed save leaves the swap dirty and monitored for retry.
3735
3595
  */
3736
3596
  async pollSwap(swap) {
3737
3597
  if (this.inProgress.has(swap.rfqId)) return;
3738
3598
  if (!this.monitored.has(swap.rfqId)) return;
3739
3599
  this.inProgress.add(swap.rfqId);
3600
+ const release = await this.acquirePollSlot();
3740
3601
  try {
3741
- await this.runPass(swap);
3602
+ if (this.monitored.has(swap.rfqId)) await this.runPass(swap);
3742
3603
  } finally {
3743
- const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
3744
- if (persisted) {
3745
- this.dirty.delete(swap.rfqId);
3746
- this.settleWaiters(swap);
3747
- if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
3604
+ try {
3605
+ const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
3606
+ if (persisted) {
3607
+ this.dirty.delete(swap.rfqId);
3608
+ this.settleWaiters(swap);
3609
+ if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
3610
+ }
3611
+ } finally {
3612
+ this.inProgress.delete(swap.rfqId);
3613
+ release();
3748
3614
  }
3749
- this.inProgress.delete(swap.rfqId);
3750
3615
  }
3751
3616
  }
3752
3617
  /*
3753
- * executes one monitoring/state-machine pass for a swap.
3754
- *
3755
- * Flow
3756
- * 1. Registers the lockup
3757
- * - Calls ensureRegistered(swap).
3758
- * - Registration is best effort and does not prevent the rest of the pass from running.
3759
- *
3760
- * 2. Reads the Arkade lockup fate
3761
- * - Calls readLockupFate.
3762
- * - A hash-verified claim is treated as claimed.
3763
- * - A fully observed non-claim spend is treated as returned.
3764
- * - Indexer errors become unknown, allowing deadline-driven logic to continue.
3765
- * - For claimed or returned, it:
3766
- * - records spend transaction IDs,
3767
- * - records the settlement preimage when applicable,
3768
- * - sets the swap state to settled or refunded,
3769
- * - ends the pass.
3770
- *
3771
- * 3. Handles unilateral exits
3772
- * - On receive swaps, an exited lockup is blocked immediately.
3773
- * - On send swaps, the L1 half continues to be monitored because an exit only describes the Arkade side.
3774
- *
3775
- * 4. Drives the trader’s claim
3776
- * - For lightning_receive, calls driveReceiveClaim and ends the pass.
3777
- * - For onchain_send, calls driveOnchain to classify and potentially claim the L1 HTLC.
3778
- * - A handled L1 action ends the pass; otherwise processing continues.
3779
- *
3780
- * 5. Drives an Arkade refund
3781
- * - For send swaps whose lockup remains unresolved, calls driveArkadeRefund.
3782
- * - This is gated by the refund timelock and local refund capability.
3783
- * - Receive swaps never reach this step because their refund path belongs to the solver.
3784
- *
3785
- * runPass only decides and performs state-machine actions. Persistence, waiter settlement, terminal finalization,
3786
- * and the per-swap lock are handled by pollSwap.
3618
+ * One state-machine pass (steps as in the class doc). Persistence, waiters,
3619
+ * finalization and the per-swap lock belong to `pollSwap`.
3787
3620
  */
3788
3621
  async runPass(swap) {
3789
3622
  await this.ensureRegistered(swap);
@@ -3819,15 +3652,9 @@ var RfqSwapManager = class {
3819
3652
  await this.driveArkadeRefund(swap);
3820
3653
  }
3821
3654
  /**
3822
- * The lockup was unilaterally exited: its outputs sit onchain under the
3823
- * VHTLC script, where no offchain claim or refund can reach them.
3824
- *
3825
- * `needs_counterparty` rather than a terminal state, because the money still
3826
- * needs action and the swap can still end either way — an onchain claim can
3827
- * reveal the preimage, an onchain refund can return it — and that state is
3828
- * documented as re-checked every pass. It must be set from HERE and not from
3829
- * inside `driveArkadeRefund`, whose two `unblock` calls would lift it again
3830
- * on the very next pass.
3655
+ * The lockup was unilaterally exited: its outputs sit onchain, beyond any offchain
3656
+ * spend. `needs_counterparty`, not terminal: it can still end either way onchain. Set
3657
+ * here, not in `driveArkadeRefund`, whose `unblock` calls would lift it next pass.
3831
3658
  */
3832
3659
  blockExitedLockup(swap, fate) {
3833
3660
  this.block(
@@ -3836,25 +3663,15 @@ var RfqSwapManager = class {
3836
3663
  );
3837
3664
  }
3838
3665
  /**
3839
- * The receive leg's whole state machine: claim the solver-funded lockup
3840
- * while the window is open, and recognise the shapes in which it can be
3841
- * lost.
3666
+ * The receive leg's whole state machine: claim the solver-funded lockup while the
3667
+ * window is open, and recognise the shapes in which it can be lost.
3842
3668
  *
3843
- * **The window closes at `refundLocktime`, on wall clock, with no margin.**
3844
- * Both halves of that are deliberate. It closes there because publishing
3845
- * `P` into the solver's live refund window risks losing the race and
3846
- * handing over the preimage anyway — the hazard `ONCHAIN_CLAIM_MARGIN_SECONDS`
3847
- * guards on the L1 side. It takes no margin because the two situations are
3848
- * not alike: that one budgets for confirmation depth, while this claim is an
3849
- * offchain spend that lands in seconds. Wall clock is already the
3850
- * conservative reading — the solver's leaf is a CLTV, which matures against
3851
- * median-time-past, and MTP trails wall clock — so the real window extends
3852
- * PAST this deadline rather than ending before it. Every second of margin
3853
- * subtracted here is a second of live claim window given away for nothing.
3669
+ * **The window closes at `refundLocktime`, on wall clock, with no margin.** Publishing
3670
+ * `P` into the solver's live refund window risks losing the race. No margin (unlike
3671
+ * `ONCHAIN_CLAIM_MARGIN_SECONDS`, which budgets for confirmations): this offchain claim
3672
+ * lands in seconds, and the solver's CLTV matures on MTP, which trails wall clock.
3854
3673
  *
3855
- * **The trader has no move after it.** Nothing here can take the lockup
3856
- * back, so once the window shuts the swap is the solver's to resolve and
3857
- * this manager's job is to watch it happen and then stop.
3674
+ * After the window the trader has no move; the manager only watches.
3858
3675
  */
3859
3676
  async driveReceiveClaim(swap) {
3860
3677
  const now = this.config.now();
@@ -3881,14 +3698,8 @@ var RfqSwapManager = class {
3881
3698
  }
3882
3699
  this.setState(swap, "refunded");
3883
3700
  }
3884
- /**
3885
- * Claim what the solver funded, once it is enough.
3886
- *
3887
- * The value gate here decides WHEN to act. `pushClaim`'s decides whether
3888
- * `P` is published, and runs with nothing between it and the signature —
3889
- * the check that matters is the inner one, and this is not a reason to
3890
- * relax it.
3891
- */
3701
+ /** Claim what the solver funded, once it is enough (the inner gate that matters is
3702
+ * `pushClaim`'s; see {@link RfqSwapManagerCallbacks.claimLockup}). */
3892
3703
  async claimIfFunded(swap, vtxos) {
3893
3704
  if (vtxos.length === 0) return this.unblock(swap);
3894
3705
  const partiallyClaimed = swap.claimTxid !== void 0;
@@ -3927,6 +3738,14 @@ var RfqSwapManager = class {
3927
3738
  this.setState(swap, "claimed");
3928
3739
  this.emitAction(swap, "claimLockup");
3929
3740
  } catch (error) {
3741
+ const ark = (0, import_sdk10.isArkError)(error) ? error : (0, import_sdk10.maybeArkError)(error);
3742
+ if ((0, import_sdk10.isArkError)(ark, import_sdk10.ArkErrorName.VTXO_ALREADY_SPENT)) {
3743
+ if (swap.claimFailure !== void 0) {
3744
+ delete swap.claimFailure;
3745
+ this.touch(swap);
3746
+ }
3747
+ return;
3748
+ }
3930
3749
  swap.claimFailure = errorMessage(error);
3931
3750
  this.touch(swap);
3932
3751
  this.emitFailed(swap, error);
@@ -4046,8 +3865,8 @@ var RfqSwapManager = class {
4046
3865
  }
4047
3866
  }
4048
3867
  }
4049
- /** Whether any of these outputs has never been handed to the claim
4050
- * callback — the only reason to claim a lockup a second time. */
3868
+ /** Whether any output was never handed to the claim callback (the only reason to
3869
+ * claim twice). */
4051
3870
  hasUnclaimedOutpoint(rfqId, vtxos) {
4052
3871
  const claimed = this.claimedOutpoints.get(rfqId);
4053
3872
  if (!claimed) return true;
@@ -4059,20 +3878,15 @@ var RfqSwapManager = class {
4059
3878
  this.claimedOutpoints.set(rfqId, claimed);
4060
3879
  }
4061
3880
  /**
4062
- * L1 progress, which past the refund window must not overwrite a refusal.
4063
- * The two halves are independent — a claimed fill says nothing about
4064
- * whether this wallet can take the Arkade lockup back — and `claimed` is
4065
- * re-asserted from chain on every pass, so without this a blocked swap
4066
- * would flip between the two states forever. The claim itself always runs;
4067
- * only the label defers, and only once the refund is the live half.
3881
+ * L1 progress, which past the refund window must not overwrite a refusal: `claimed` is
3882
+ * re-asserted from chain every pass, so a blocked swap would flip forever. Only the
3883
+ * label defers; the claim itself always runs.
4068
3884
  */
4069
3885
  setOnchainState(swap, state) {
4070
3886
  if (swap.state === "needs_counterparty" && this.config.now() >= swap.refundLocktime) return;
4071
3887
  this.setState(swap, state);
4072
3888
  }
4073
- /** The probe's refusal reason, or `undefined` when a local refund is
4074
- * possible as far as anyone here can tell. A probe that throws is treated
4075
- * as a refusal: a capability check that cannot answer is not a yes. */
3889
+ /** The probe's refusal reason, or `undefined`. A throwing probe is a refusal. */
4076
3890
  async probeRefusal(swap) {
4077
3891
  const probe = this.callbacks?.canRefundArkade;
4078
3892
  if (!probe) return void 0;
@@ -4091,25 +3905,16 @@ var RfqSwapManager = class {
4091
3905
  }
4092
3906
  this.setState(swap, "needs_counterparty");
4093
3907
  }
4094
- /** The way back out, taken as soon as the swap becomes actionable again.
4095
- * Back to what the record can prove, not to `pending` unconditionally: a
4096
- * swap that already made its claim has a txid for it, and reporting that
4097
- * swap as `pending` would un-say something true. */
3908
+ /** The way back out once actionable: to `claimed` if a claim txid exists, else
3909
+ * `pending`. */
4098
3910
  unblock(swap) {
4099
3911
  if (swap.state !== "needs_counterparty") return;
4100
3912
  this.setState(swap, traderClaimTxid(swap) ? "claimed" : "pending");
4101
3913
  }
4102
3914
  /**
4103
- * Record which ark transactions ended the lockup.
4104
- *
4105
- * Only the ones the indexer actually named: `LockupSpend.txid` is
4106
- * optional, and a checkpoint txid is not what history correlates on — a
4107
- * record carrying one would name a transaction the wallet's own activity
4108
- * never shows. Fewer txids is the right failure here.
4109
- *
4110
- * Assigned rather than merged: the fate is one read of the whole lockup,
4111
- * so it is the complete answer for this swap, and a swap only reaches a
4112
- * verdict once.
3915
+ * Record which ark transactions ended the lockup. Only named ark txids: a checkpoint
3916
+ * txid would name a transaction the wallet's activity never shows. Assigned, not
3917
+ * merged: the fate is one complete read, reached once.
4113
3918
  */
4114
3919
  stampLockupSpends(swap, spends) {
4115
3920
  const txids = spends.map((spend) => spend.txid).filter((txid) => txid !== void 0);
@@ -4118,12 +3923,8 @@ var RfqSwapManager = class {
4118
3923
  this.touch(swap);
4119
3924
  }
4120
3925
  /**
4121
- * Keep the preimage that settled a Lightning send.
4122
- *
4123
- * Only that leg. A receive's `claimed` verdict reveals the wallet's own
4124
- * claim secret and an onchain send's reveals the one it minted — both
4125
- * already recoverable from `profile`, so stamping either would be a second
4126
- * home for a secret that has one.
3926
+ * Keep the preimage that settled a Lightning send. Only that leg: the others' preimages
3927
+ * are the wallet's own secrets, already recoverable from `profile`.
4127
3928
  */
4128
3929
  stampSettlementPreimage(swap, preimage) {
4129
3930
  if (swap.kind !== "lightning_send") return;
@@ -4157,24 +3958,9 @@ var RfqSwapManager = class {
4157
3958
  notify(this.actionExecutedListeners, (listener) => listener(swap, action));
4158
3959
  }
4159
3960
  /**
4160
- * Flush a changed record to every sink that is wired, and say whether all
4161
- * of them took it.
4162
- *
4163
- * Up to two writes, in this order: the canonical `RfqSwapRecord` to
4164
- * {@link RfqSwapManagerDeps.repository}, then
4165
- * {@link RfqSwapManagerCallbacks.saveSwap}. Both gate — a rejection from
4166
- * either leaves the record dirty and monitored, so waiters stay unsettled
4167
- * and a terminal swap is not finalized until the write it claims lands.
4168
- * That is exactly today's rule for `saveSwap`, applied to whichever sinks
4169
- * exist; wiring the repository does not weaken it.
4170
- *
4171
- * The canonical write goes FIRST and a failure there skips the second.
4172
- * `saveSwap` is a projection of the record, and projecting a state the
4173
- * record of record has just refused would leave the secondary sink ahead
4174
- * of the primary — the one ordering that survives no restart.
4175
- *
4176
- * With neither wired the state is process-local, which is what a manager
4177
- * with no callbacks has always done.
3961
+ * Flush a changed record to every wired sink; true only if all took it (else it stays
3962
+ * dirty and unfinalized). The canonical repository write goes FIRST and a failure skips
3963
+ * `saveSwap`, so the secondary sink never gets ahead of the primary.
4178
3964
  */
4179
3965
  async save(swap) {
4180
3966
  if (!await this.saveRecord(swap)) return false;
@@ -4206,18 +3992,15 @@ var RfqSwapManager = class {
4206
3992
  if (!origin) throw new RfqSwapOriginRequired(swap.rfqId);
4207
3993
  return origin;
4208
3994
  }
4209
- /**
4210
- * Drop a terminal swap from monitoring and report it exactly once.
4211
- *
4212
- * `onSwapCompleted` and `onSwapFailed` are mutually exclusive here: a
4213
- * listener named "completed" that also fires on failure is a trap, so a
4214
- * swap that leaves monitoring reports through exactly one of them.
4215
- */
3995
+ /** Drop a terminal swap from monitoring and report it exactly once, through either
3996
+ * `onSwapCompleted` or `onSwapFailed`. */
4216
3997
  finalize(swap) {
4217
3998
  if (!this.monitored.has(swap.rfqId)) return;
4218
3999
  this.untrack(swap.rfqId);
4219
- this.finished.set(swap.rfqId, swap);
4000
+ this.rememberFinished(swap, true);
4220
4001
  this.retireContract(swap);
4002
+ this.registered.delete(swap.rfqId);
4003
+ this.origins.delete(swap.rfqId);
4221
4004
  if (swap.state === "failed") {
4222
4005
  notify(
4223
4006
  this.swapFailedListeners,
@@ -4227,6 +4010,10 @@ var RfqSwapManager = class {
4227
4010
  }
4228
4011
  notify(this.swapCompletedListeners, (listener) => listener(swap));
4229
4012
  }
4013
+ rememberFinished(swap, durable = false) {
4014
+ if (durable && this.deps.repository) this.finished.delete(swap.rfqId);
4015
+ else this.finished.set(swap.rfqId, swap);
4016
+ }
4230
4017
  settleWaiters(swap) {
4231
4018
  const waiting = this.waiters.get(swap.rfqId);
4232
4019
  if (!waiting) return;
@@ -4242,16 +4029,7 @@ var RfqSwapManager = class {
4242
4029
  this.waiters.delete(swap.rfqId);
4243
4030
  }
4244
4031
  };
4245
- var traderClaimTxid = (swap) => {
4246
- switch (swap.kind) {
4247
- case "onchain_send":
4248
- return swap.claimTxid;
4249
- case "lightning_receive":
4250
- return swap.claimTxid;
4251
- default:
4252
- return void 0;
4253
- }
4254
- };
4032
+ var traderClaimTxid = (swap) => swap.kind === "onchain_send" || swap.kind === "lightning_receive" ? swap.claimTxid : void 0;
4255
4033
  var isPayoutDecided = (swap) => swap.state === "settled" || swap.state === "refunded" || swap.kind === "onchain_send" && swap.claimTxid !== void 0;
4256
4034
  var outcomeOf = (swap) => {
4257
4035
  const lostReceive = swap.kind === "lightning_receive" && swap.state === "refunded";
@@ -4260,11 +4038,20 @@ var outcomeOf = (swap) => {
4260
4038
  txid: lostReceive ? swap.refundTxid : traderClaimTxid(swap) ?? swap.refundTxid
4261
4039
  };
4262
4040
  };
4041
+ var outcomeOfRecord = (stored) => {
4042
+ const record = normalizeRfqSwapRecord(stored);
4043
+ const profileClaim = record.kind === "onchain_send" || record.kind === "lightning_receive" ? record.profile.claimTxid : void 0;
4044
+ const claimTxid = typeof profileClaim === "string" ? profileClaim : void 0;
4045
+ return {
4046
+ state: record.state,
4047
+ txid: record.kind === "lightning_receive" && record.state === "refunded" ? record.refundTxid : claimTxid ?? record.refundTxid
4048
+ };
4049
+ };
4263
4050
  var errorMessage = (error) => error instanceof Error ? error.message : String(error);
4264
4051
  var outpointKey = (vtxo) => `${vtxo.txid}:${vtxo.vout}`;
4265
4052
 
4266
4053
  // src/client/corridors/lightning.ts
4267
- var import_sdk10 = require("@arkade-os/sdk");
4054
+ var import_sdk11 = require("@arkade-os/sdk");
4268
4055
  var INVOICE_HRPS = [
4269
4056
  ["lnbcrt", ["regtest"]],
4270
4057
  ["lntbs", ["signet", "mutinynet"]],
@@ -4294,7 +4081,7 @@ var lightningCorridor = Object.assign(
4294
4081
  deps,
4295
4082
  drive: LIGHTNING_DRIVE,
4296
4083
  matches(raw) {
4297
- const invoice = (0, import_sdk10.invoiceTarget)(raw);
4084
+ const invoice = (0, import_sdk11.invoiceTarget)(raw);
4298
4085
  if (invoice === void 0) return void 0;
4299
4086
  const networks = networksOfInvoiceHrp(invoice);
4300
4087
  if (networks === void 0) {
@@ -4340,11 +4127,11 @@ var lightningCorridor = Object.assign(
4340
4127
  };
4341
4128
  }
4342
4129
  }),
4343
- { target: import_sdk10.invoiceTarget }
4130
+ { target: import_sdk11.invoiceTarget }
4344
4131
  );
4345
4132
 
4346
4133
  // src/client/corridors/onchain.ts
4347
- var import_sdk11 = require("@arkade-os/sdk");
4134
+ var import_sdk12 = require("@arkade-os/sdk");
4348
4135
  var btc2 = __toESM(require("@scure/btc-signer"), 1);
4349
4136
  var ONCHAIN_DRIVE = {
4350
4137
  take: {
@@ -4364,14 +4151,14 @@ var onchainCorridor = Object.assign(
4364
4151
  deps,
4365
4152
  drive: ONCHAIN_DRIVE,
4366
4153
  matches(raw) {
4367
- const target = (0, import_sdk11.btcTarget)(raw);
4154
+ const target = (0, import_sdk12.btcTarget)(raw);
4368
4155
  if (target === void 0) return void 0;
4369
4156
  try {
4370
4157
  btc2.Address(L1_NETWORKS[l1]).decode(target);
4371
4158
  } catch {
4372
4159
  return { refused: `this is not a ${l1} address` };
4373
4160
  }
4374
- const amount = import_sdk11.BIP21.amountSats(raw);
4161
+ const amount = import_sdk12.BIP21.amountSats(raw);
4375
4162
  return {
4376
4163
  claimed: {
4377
4164
  kind: "address",
@@ -4382,7 +4169,7 @@ var onchainCorridor = Object.assign(
4382
4169
  }
4383
4170
  };
4384
4171
  },
4385
- { target: import_sdk11.btcTarget }
4172
+ { target: import_sdk12.btcTarget }
4386
4173
  );
4387
4174
 
4388
4175
  // src/client/outcome.ts
@@ -4408,18 +4195,14 @@ var CORRIDOR_OUTCOME = {
4408
4195
  failed: at("failed")
4409
4196
  },
4410
4197
  solver: {
4411
- // The solver has funded nothing yet: the invoice is shown and unpaid,
4412
- // which is what makes this `open` where the trader's side is `funded`.
4198
+ // The solver has funded nothing yet: the invoice is shown and unpaid.
4413
4199
  pending: at("open"),
4414
4200
  claimable: at("funded"),
4415
4201
  claimed: at("funded"),
4416
4202
  needs_counterparty: at("needs_recovery"),
4417
- // The trader's OWN claim, matched by the hash and not by our txid — so
4418
- // a claim that lands without us still counts.
4203
+ // Matched by the hash, not our txid, so a claim that lands without us counts.
4419
4204
  settled: at("claimed"),
4420
- // The one inversion this whole module exists for: every non-claim leaf
4421
- // of a receive covenant is the solver's, so a lockup spent by one is
4422
- // the trader's incoming payment never arriving.
4205
+ // The inversion: a receive lockup's non-claim leaves are all the solver's.
4423
4206
  refunded: at("lapsed"),
4424
4207
  failed: at("failed")
4425
4208
  }
@@ -4430,10 +4213,8 @@ var ACTIVITY_TOKEN = {
4430
4213
  funding: "pending",
4431
4214
  funded: "pending",
4432
4215
  open: "pending",
4433
- // The drive's in-flight states have no user-visible phase distinct from
4434
- // "pending"; `needs_recovery` is different in kind — the swap is BLOCKED —
4435
- // and collapsing it here is the same deliberate choice v1 made, which the
4436
- // opaque-token design permits because apps map tokens themselves.
4216
+ // `needs_recovery` (BLOCKED) collapses to pending deliberately, as in v1; apps map
4217
+ // tokens themselves.
4437
4218
  needs_recovery: "pending",
4438
4219
  refunding: "pending",
4439
4220
  cancelling: "pending",
@@ -4476,11 +4257,6 @@ function swapActivityResolver(deps) {
4476
4257
  groupId: `swap:${swap.rfqId}`,
4477
4258
  label: LABELS[swap.kind],
4478
4259
  kind: "swap",
4479
- // `"lost"` for a receive leg that ended `refunded` comes out
4480
- // of the translation rather than out of a branch here: that
4481
- // leg has no trader-side refund, every non-claim leaf of its
4482
- // covenant is the solver's, and the client's `lapsed` is
4483
- // that fact.
4484
4260
  outcome: outcomeToken(swap.kind, swap.state),
4485
4261
  metadata: { rfqId: swap.rfqId, swapKind: swap.kind }
4486
4262
  }
@@ -4489,8 +4265,16 @@ function swapActivityResolver(deps) {
4489
4265
  };
4490
4266
  }
4491
4267
  async function rfqSwapActivityInputs(deps) {
4492
- const records = await deps.repository.getAllRfqSwaps();
4493
- return Promise.all(records.map((record) => activityInputOf(record, deps.indexer)));
4268
+ const records = await collectRfqSwaps(deps.repository);
4269
+ const inputs = [];
4270
+ for (let i = 0; i < records.length; i += 16) {
4271
+ inputs.push(
4272
+ ...await Promise.all(
4273
+ records.slice(i, i + 16).map((record) => activityInputOf(record, deps.indexer))
4274
+ )
4275
+ );
4276
+ }
4277
+ return inputs;
4494
4278
  }
4495
4279
  async function activityInputOf(stored, indexer) {
4496
4280
  const record = normalizeRfqSwapRecord(stored);
@@ -4511,7 +4295,7 @@ async function activityInputOf(stored, indexer) {
4511
4295
  async function lockupTxids(indexer, record, wantFunding) {
4512
4296
  let script;
4513
4297
  try {
4514
- script = import_base11.hex.encode(import_sdk12.ArkAddress.decode(record.lockupAddress).pkScript);
4298
+ script = import_base11.hex.encode(import_sdk13.ArkAddress.decode(record.lockupAddress).pkScript);
4515
4299
  } catch {
4516
4300
  return [];
4517
4301
  }
@@ -4547,7 +4331,12 @@ function arkadeRefunder(deps) {
4547
4331
  );
4548
4332
  }
4549
4333
  const sender = await senderIdentityForSwapRecord(deps.wallet, rfqSignerOf(record) ?? {});
4550
- return pushRefundWithoutReceiver(deps.operator, { contract, sender, vtxos });
4334
+ return pushRefundWithoutReceiver(deps.operator, {
4335
+ contract,
4336
+ sender,
4337
+ vtxos,
4338
+ network: await deps.network?.()
4339
+ });
4551
4340
  };
4552
4341
  }
4553
4342
 
@@ -4595,11 +4384,7 @@ var chainSourceFrom = (provider, network) => {
4595
4384
  };
4596
4385
 
4597
4386
  // src/claim.ts
4598
- var import_base13 = require("@scure/base");
4599
- var import_legacy3 = require("@noble/hashes/legacy.js");
4600
- var import_sha25 = require("@noble/hashes/sha2.js");
4601
- var import_sdk13 = require("@arkade-os/sdk");
4602
- var sleep3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4387
+ var import_sdk14 = require("@arkade-os/sdk");
4603
4388
  var LockupAmountMismatchError = class extends Error {
4604
4389
  name = "LockupAmountMismatchError";
4605
4390
  reason = "amount_mismatch";
@@ -4615,19 +4400,11 @@ var LockupAmountMismatchError = class extends Error {
4615
4400
  };
4616
4401
  var assertFiniteAmount = (value, reason, label) => {
4617
4402
  if (Number.isFinite(value)) return;
4618
- const error = new Error(`${label} is not a finite number (${String(value)})`);
4619
- error.reason = reason;
4620
- throw error;
4403
+ throw gateError(reason, `${label} is not a finite number (${String(value)})`);
4621
4404
  };
4622
4405
  async function pushClaim(operator, input) {
4623
4406
  if (input.vtxos.length === 0) throw new Error("nothing to claim: no funded outputs");
4624
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
4625
- if (swept.length > 0) {
4626
- throw new LockupNeedsRecoveryError(
4627
- swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
4628
- input.contract.options.refundLocktime
4629
- );
4630
- }
4407
+ assertNoneSwept(input.vtxos, input.contract);
4631
4408
  const locked = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
4632
4409
  assertFiniteAmount(locked, "lockup_malformed", "the lockup's summed value");
4633
4410
  if (!input.partiallyClaimed) {
@@ -4636,69 +4413,40 @@ async function pushClaim(operator, input) {
4636
4413
  throw new LockupAmountMismatchError(input.expectedAmount, locked);
4637
4414
  }
4638
4415
  }
4639
- const committed = input.contract.options.preimageHash;
4640
- if (import_base13.hex.encode((0, import_legacy3.ripemd160)((0, import_sha25.sha256)(input.preimage))) !== import_base13.hex.encode(committed)) {
4641
- throw new Error("preimage does not match the covenant's payment hash");
4642
- }
4643
- const info = await operator.getInfo();
4644
- let operatorUnrollScript;
4645
- try {
4646
- operatorUnrollScript = import_sdk13.CSVMultisigTapscript.decode(import_base13.hex.decode(info.checkpointTapscript));
4647
- } catch {
4648
- throw new Error("invalid checkpointTapscript from the operator");
4649
- }
4416
+ assertPreimageMatches(input.preimage, input.contract.options.preimageHash);
4417
+ const serverUnrollScript = await operatorUnrollScript(operator, input.network);
4650
4418
  const leaf = input.contract.claim();
4651
- const tapTree = input.contract.encode();
4652
- const txid = await (0, import_sdk13.signAndSubmitOffchainTx)({
4653
- identity: (0, import_sdk13.claimWithPreimageIdentity)(input.receiver, input.preimage),
4419
+ const txid = await (0, import_sdk14.signAndSubmitOffchainTx)({
4420
+ identity: (0, import_sdk14.claimWithPreimageIdentity)(input.receiver, input.preimage),
4654
4421
  provider: operator,
4655
- inputs: input.vtxos.map((vtxo) => ({
4656
- txid: vtxo.txid,
4657
- vout: vtxo.vout,
4658
- value: vtxo.value,
4659
- tapLeafScript: leaf,
4660
- tapTree
4661
- })),
4662
- // One aggregate output: unlike the covenant refund, this leaf inspects
4663
- // nothing about the output set.
4422
+ inputs: lockupInputs(input.vtxos, input.contract, leaf),
4423
+ // One aggregate output: this leaf inspects nothing about the output set.
4664
4424
  outputs: [{ script: input.destinationPkScript, amount: BigInt(locked) }],
4665
- serverUnrollScript: operatorUnrollScript,
4425
+ serverUnrollScript,
4666
4426
  verifyServerSignatures: { serverPubkey: input.contract.options.server }
4667
4427
  });
4668
4428
  return { txid, amount: locked };
4669
4429
  }
4670
4430
  async function awaitLockupFunding(contracts, swapPkScript, options = {}) {
4671
- const pollMs = options.pollMs ?? 5e3;
4672
- for (; ; ) {
4673
- const vtxos = await findLockupVtxos(contracts, swapPkScript);
4674
- if (vtxos.length > 0) return vtxos;
4675
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
4676
- const error = new Error("the lockup never appeared at the covenant script");
4677
- error.reason = "lockup_timeout";
4678
- throw error;
4679
- }
4680
- await sleep3(pollMs);
4681
- }
4431
+ return pollUntil(
4432
+ async () => {
4433
+ const vtxos = await findLockupVtxos(contracts, swapPkScript);
4434
+ return vtxos.length > 0 ? vtxos : void 0;
4435
+ },
4436
+ options,
4437
+ "lockup_timeout",
4438
+ "the lockup never appeared at the covenant script"
4439
+ );
4682
4440
  }
4683
4441
  async function claimReceiveLockup(contracts, operator, input) {
4684
- const vtxos = await awaitLockupFunding(contracts, input.swapPkScript, {
4685
- pollMs: input.pollMs,
4686
- deadline: input.deadline
4687
- });
4688
- return pushClaim(operator, {
4689
- contract: input.contract,
4690
- receiver: input.receiver,
4691
- preimage: input.preimage,
4692
- vtxos,
4693
- destinationPkScript: input.destinationPkScript,
4694
- expectedAmount: input.expectedAmount,
4695
- partiallyClaimed: input.partiallyClaimed
4696
- });
4442
+ const { swapPkScript, pollMs, deadline, ...claim } = input;
4443
+ const vtxos = await awaitLockupFunding(contracts, swapPkScript, { pollMs, deadline });
4444
+ return pushClaim(operator, { ...claim, vtxos });
4697
4445
  }
4698
4446
 
4699
4447
  // src/markets.ts
4700
4448
  var import_solver_discovery2 = require("@arkade-os/solver-discovery");
4701
- var import_sdk14 = require("@arkade-os/sdk");
4449
+ var import_sdk15 = require("@arkade-os/sdk");
4702
4450
 
4703
4451
  // src/marketShape.ts
4704
4452
  var MARKET_CORRIDORS = ["arkade", "bolt11", "bitcoin", "eip155"];
@@ -4874,18 +4622,17 @@ var validatePlan = (plan, giveBalance, dust) => {
4874
4622
  const receiveIsBtc = plan.receive.asset.id === BTC_ASSET_ID;
4875
4623
  if (depositIsBtc || receiveIsBtc) {
4876
4624
  const btcSide = depositIsBtc ? plan.deposit.atomic : plan.receive.atomic;
4877
- if ((0, import_sdk14.isSubdust)(btcSide, dust)) return "below-dust";
4625
+ if ((0, import_sdk15.isSubdust)(btcSide, dust)) return "below-dust";
4878
4626
  }
4879
4627
  return void 0;
4880
4628
  };
4881
4629
 
4882
4630
  // src/payment/crossAsset.ts
4883
- var import_sdk15 = require("@arkade-os/sdk");
4631
+ var import_sdk16 = require("@arkade-os/sdk");
4884
4632
  var CROSS_ASSET_RAIL = "cross-asset";
4885
- var DEFAULT_CARRIER_SATS = 330;
4886
4633
  var parseAssetId = (assetId) => {
4887
4634
  try {
4888
- return import_sdk15.asset.AssetId.fromString(assetId);
4635
+ return import_sdk16.asset.AssetId.fromString(assetId);
4889
4636
  } catch {
4890
4637
  return void 0;
4891
4638
  }
@@ -4903,9 +4650,9 @@ function crossAssetRail(deps) {
4903
4650
  };
4904
4651
  return {
4905
4652
  id: CROSS_ASSET_RAIL,
4906
- match: (req) => (0, import_sdk15.arkTarget)(req.raw) !== void 0,
4653
+ match: (req) => (0, import_sdk16.arkTarget)(req.raw) !== void 0,
4907
4654
  available: async (req) => {
4908
- const assets = (0, import_sdk15.assetsOf)(req);
4655
+ const assets = (0, import_sdk16.assetsOf)(req);
4909
4656
  if (assets.length !== 1) return false;
4910
4657
  const [asset3] = assets;
4911
4658
  if (asset3.assetId === BTC_ASSET_ID) return false;
@@ -4915,8 +4662,8 @@ function crossAssetRail(deps) {
4915
4662
  return planned !== void 0 && planned.error === void 0;
4916
4663
  },
4917
4664
  quote: async (req, ctx) => {
4918
- const payTo = (0, import_sdk15.arkTarget)(req.raw);
4919
- const asset3 = (0, import_sdk15.resolveAssetAmount)(CROSS_ASSET_RAIL, req);
4665
+ const payTo = (0, import_sdk16.arkTarget)(req.raw);
4666
+ const asset3 = (0, import_sdk16.resolveAssetAmount)(CROSS_ASSET_RAIL, req);
4920
4667
  const wantAsset = parseAssetId(asset3.assetId);
4921
4668
  if (!wantAsset) {
4922
4669
  throw new Error(
@@ -4939,7 +4686,7 @@ function crossAssetRail(deps) {
4939
4686
  );
4940
4687
  }
4941
4688
  const depositSats = Number(plan.deposit.atomic);
4942
- const carrier = deps.carrierSats ?? DEFAULT_CARRIER_SATS;
4689
+ const carrier = deps.carrierSats ?? import_sdk16.ASSET_CARRIER_SATS;
4943
4690
  return {
4944
4691
  railId: CROSS_ASSET_RAIL,
4945
4692
  // OPEN QUESTION for review: `total = amount + fee` forces the
@@ -4957,7 +4704,7 @@ function crossAssetRail(deps) {
4957
4704
  priceDisplay: plan.priceDisplay,
4958
4705
  give: plan.give
4959
4706
  },
4960
- send: async () => (0, import_sdk15.makeHandle)(CROSS_ASSET_RAIL, async (emit) => {
4707
+ send: async () => (0, import_sdk16.makeHandle)(CROSS_ASSET_RAIL, async (emit) => {
4961
4708
  const offer = await createOffer(ctx.wallet, {
4962
4709
  wantAmount: asset3.amount,
4963
4710
  wantAsset,
@@ -5004,7 +4751,7 @@ function crossAssetRail(deps) {
5004
4751
 
5005
4752
  // src/payment/rendezvous.ts
5006
4753
  var import_solver_discovery3 = require("@arkade-os/solver-discovery");
5007
- var import_base14 = require("@scure/base");
4754
+ var import_base13 = require("@scure/base");
5008
4755
  var XONLY_HEX = /^[0-9a-f]{64}$/;
5009
4756
  var rendezvousOf = (market, pinned) => {
5010
4757
  const transports = { nostr: { relays: market.transports?.nostr?.relays ?? [] } };
@@ -5023,9 +4770,8 @@ var rendezvousOf = (market, pinned) => {
5023
4770
  };
5024
4771
  };
5025
4772
  var solverRendezvous = (markets, payoutCorridor, amountSats, fallbackEmulatorPubkey) => {
5026
- const encoded = fallbackEmulatorPubkey ? import_base14.hex.encode(fallbackEmulatorPubkey) : void 0;
5027
- if (encoded !== void 0 && !XONLY_HEX.test(encoded)) return void 0;
5028
- const pinned = encoded;
4773
+ const pinned = fallbackEmulatorPubkey ? import_base13.hex.encode(fallbackEmulatorPubkey) : void 0;
4774
+ if (pinned !== void 0 && !XONLY_HEX.test(pinned)) return void 0;
5029
4775
  const quoteCorridor = payoutCorridor === "lightning" ? "bolt11" : "bitcoin";
5030
4776
  const isBtc = (id) => id === "btc" || /^\w+:[^/]+\/slip44:(?:0|1)$/.test(id ?? "");
5031
4777
  const candidates = markets.filter(
@@ -5042,121 +4788,34 @@ var solverRendezvous = (markets, payoutCorridor, amountSats, fallbackEmulatorPub
5042
4788
  };
5043
4789
 
5044
4790
  // src/payment/solverLightning.ts
5045
- var import_sdk16 = require("@arkade-os/sdk");
5046
- var SOLVER_LIGHTNING_RAIL = "solver-lightning";
5047
- var factsOf = (raw, decode, now) => {
5048
- const invoice = (0, import_sdk16.invoiceTarget)(raw);
5049
- if (!invoice) return void 0;
5050
- let facts;
5051
- try {
5052
- facts = decode(invoice);
5053
- } catch {
5054
- return void 0;
5055
- }
5056
- if (!Number.isInteger(facts.amountSats) || facts.amountSats <= 0) return void 0;
5057
- if (facts.expiresAt <= now) return void 0;
5058
- return facts;
5059
- };
5060
- var solverLightningRendezvous = (markets, amountSats, fallbackEmulatorPubkey) => solverRendezvous(markets, "lightning", amountSats, fallbackEmulatorPubkey);
5061
- function solverLightningRail(deps) {
5062
- const rendezvousFor = async (amountSats) => solverLightningRendezvous(await deps.discover(), amountSats, deps.fallbackEmulatorPubkey);
5063
- return {
5064
- id: SOLVER_LIGHTNING_RAIL,
5065
- match: (req) => (0, import_sdk16.invoiceTarget)(req.raw) !== void 0,
5066
- available: async (req) => {
5067
- if ((0, import_sdk16.assetsOf)(req).length > 0) return false;
5068
- const facts = factsOf(req.raw, deps.decodeInvoice, Math.floor(Date.now() / 1e3));
5069
- if (!facts) return false;
5070
- if (req.amount !== void 0 && req.amount !== facts.amountSats) return false;
5071
- return await rendezvousFor(facts.amountSats) !== void 0;
5072
- },
5073
- quote: async (req, ctx) => {
5074
- (0, import_sdk16.assertNoAssets)(SOLVER_LIGHTNING_RAIL, req);
5075
- const facts = factsOf(req.raw, deps.decodeInvoice, Math.floor(Date.now() / 1e3));
5076
- if (!facts) {
5077
- throw new Error(
5078
- `${SOLVER_LIGHTNING_RAIL}: the request carries no payable BOLT11 invoice (amountless, expired, or undecodable)`
5079
- );
5080
- }
5081
- if (req.amount !== void 0 && req.amount !== facts.amountSats) {
5082
- throw new Error(
5083
- `${SOLVER_LIGHTNING_RAIL}: the request names ${req.amount} sats but the invoice is for ${facts.amountSats} \u2014 the payee is paid the invoice`
5084
- );
5085
- }
5086
- const rendezvous = await rendezvousFor(facts.amountSats);
5087
- if (!rendezvous) {
5088
- throw new Error(
5089
- `${SOLVER_LIGHTNING_RAIL}: no solver serves arkade:BTC -> lightning:BTC at ${facts.amountSats} sats`
5090
- );
5091
- }
5092
- const negotiated = await deps.connect(
5093
- rendezvous,
5094
- (transport) => requestLightningSend(ctx.wallet, transport, {
5095
- invoice: facts,
5096
- ...deps.emulatorPubkey ? { emulatorPubkey: deps.emulatorPubkey } : {}
5097
- })
5098
- );
5099
- const swap = { ...negotiated, invoice: facts, rendezvous };
5100
- return {
5101
- railId: SOLVER_LIGHTNING_RAIL,
5102
- // `requestLightningSend` refuses a quote that reprices the
5103
- // invoice, so the spread is a fee on top.
5104
- amount: facts.amountSats,
5105
- fee: swap.fundAmount - facts.amountSats,
5106
- total: swap.fundAmount,
5107
- // The invoice can lapse before the quote does; the earlier bound
5108
- // is the one a holder must observe.
5109
- validUntil: Math.min(swap.quote.valid_until, facts.expiresAt),
5110
- meta: {
5111
- rfqId: swap.rfqId,
5112
- validUntil: swap.quote.valid_until,
5113
- paymentHash: facts.paymentHash,
5114
- invoiceExpiresAt: facts.expiresAt,
5115
- solverPubkey: rendezvous.solverPubkey
5116
- },
5117
- send: async () => (0, import_sdk16.makeHandle)(SOLVER_LIGHTNING_RAIL, async (emit) => {
5118
- assertFundable({
5119
- quote: swap.quote,
5120
- invoiceExpiresAt: facts.expiresAt,
5121
- now: Math.floor(Date.now() / 1e3)
5122
- });
5123
- await deps.persist(swap);
5124
- await ctx.wallet.send({
5125
- address: swap.address,
5126
- amount: swap.fundAmount
5127
- });
5128
- emit({ status: "sent" });
5129
- const result = { railId: SOLVER_LIGHTNING_RAIL, swapId: swap.rfqId };
5130
- if (!deps.awaitSettlement) return result;
5131
- let preimage;
5132
- try {
5133
- ({ preimage } = await deps.awaitSettlement(swap));
5134
- } catch (e) {
5135
- console.warn(
5136
- `${SOLVER_LIGHTNING_RAIL}: settlement watch failed; the payment is sent`,
5137
- e
5138
- );
5139
- return result;
5140
- }
5141
- const settled = { ...result, ...preimage !== void 0 && { preimage } };
5142
- emit({ status: "settled", result: settled });
5143
- return settled;
5144
- })
5145
- };
5146
- }
5147
- };
5148
- }
4791
+ var import_sdk18 = require("@arkade-os/sdk");
5149
4792
 
5150
4793
  // src/payment/solverOnchain.ts
5151
4794
  var import_sdk17 = require("@arkade-os/sdk");
5152
4795
  var SOLVER_ONCHAIN_RAIL = "solver-onchain";
5153
4796
  var solverOnchainRendezvous = (markets, amountSats, fallbackEmulatorPubkey) => solverRendezvous(markets, "onchain", amountSats, fallbackEmulatorPubkey);
4797
+ async function fundSolverSend(railId, ctx, emit, deps, swap, settledFields) {
4798
+ await deps.persist(swap);
4799
+ await ctx.wallet.send({
4800
+ address: swap.address,
4801
+ amount: swap.fundAmount
4802
+ });
4803
+ emit({ status: "sent" });
4804
+ const result = { railId, swapId: swap.rfqId };
4805
+ if (!deps.awaitSettlement) return result;
4806
+ let fields;
4807
+ try {
4808
+ fields = settledFields(await deps.awaitSettlement(swap));
4809
+ } catch (e) {
4810
+ console.warn(`${railId}: settlement watch failed; the payment is sent`, e);
4811
+ return result;
4812
+ }
4813
+ const settled = { ...result, ...fields };
4814
+ emit({ status: "settled", result: settled });
4815
+ return settled;
4816
+ }
5154
4817
  function solverOnchainRail(deps) {
5155
- const rendezvousFor = async (amount) => {
5156
- if (amount === void 0) return void 0;
5157
- const markets = await deps.discover();
5158
- return solverOnchainRendezvous(markets, amount, deps.fallbackEmulatorPubkey);
5159
- };
4818
+ const rendezvousFor = async (amount) => solverOnchainRendezvous(await deps.discover(), amount, deps.fallbackEmulatorPubkey);
5160
4819
  return {
5161
4820
  id: SOLVER_ONCHAIN_RAIL,
5162
4821
  match: (req) => (0, import_sdk17.btcTarget)(req.raw) !== void 0,
@@ -5225,27 +4884,106 @@ function solverOnchainRail(deps) {
5225
4884
  direction: "send"
5226
4885
  }
5227
4886
  });
5228
- await deps.persist(swap);
5229
- await ctx.wallet.send({
5230
- address: swap.address,
5231
- amount: swap.fundAmount
4887
+ return fundSolverSend(
4888
+ SOLVER_ONCHAIN_RAIL,
4889
+ ctx,
4890
+ emit,
4891
+ deps,
4892
+ swap,
4893
+ ({ txid }) => ({ txid })
4894
+ );
4895
+ })
4896
+ };
4897
+ }
4898
+ };
4899
+ }
4900
+
4901
+ // src/payment/solverLightning.ts
4902
+ var SOLVER_LIGHTNING_RAIL = "solver-lightning";
4903
+ var factsOf = (raw, decode, now) => {
4904
+ const invoice = (0, import_sdk18.invoiceTarget)(raw);
4905
+ if (!invoice) return void 0;
4906
+ let facts;
4907
+ try {
4908
+ facts = decode(invoice);
4909
+ } catch {
4910
+ return void 0;
4911
+ }
4912
+ if (!Number.isInteger(facts.amountSats) || facts.amountSats <= 0) return void 0;
4913
+ if (facts.expiresAt <= now) return void 0;
4914
+ return facts;
4915
+ };
4916
+ var solverLightningRendezvous = (markets, amountSats, fallbackEmulatorPubkey) => solverRendezvous(markets, "lightning", amountSats, fallbackEmulatorPubkey);
4917
+ function solverLightningRail(deps) {
4918
+ const rendezvousFor = async (amountSats) => solverLightningRendezvous(await deps.discover(), amountSats, deps.fallbackEmulatorPubkey);
4919
+ return {
4920
+ id: SOLVER_LIGHTNING_RAIL,
4921
+ match: (req) => (0, import_sdk18.invoiceTarget)(req.raw) !== void 0,
4922
+ available: async (req) => {
4923
+ if ((0, import_sdk18.assetsOf)(req).length > 0) return false;
4924
+ const facts = factsOf(req.raw, deps.decodeInvoice, Math.floor(Date.now() / 1e3));
4925
+ if (!facts) return false;
4926
+ if (req.amount !== void 0 && req.amount !== facts.amountSats) return false;
4927
+ return await rendezvousFor(facts.amountSats) !== void 0;
4928
+ },
4929
+ quote: async (req, ctx) => {
4930
+ (0, import_sdk18.assertNoAssets)(SOLVER_LIGHTNING_RAIL, req);
4931
+ const facts = factsOf(req.raw, deps.decodeInvoice, Math.floor(Date.now() / 1e3));
4932
+ if (!facts) {
4933
+ throw new Error(
4934
+ `${SOLVER_LIGHTNING_RAIL}: the request carries no payable BOLT11 invoice (amountless, expired, or undecodable)`
4935
+ );
4936
+ }
4937
+ if (req.amount !== void 0 && req.amount !== facts.amountSats) {
4938
+ throw new Error(
4939
+ `${SOLVER_LIGHTNING_RAIL}: the request names ${req.amount} sats but the invoice is for ${facts.amountSats} \u2014 the payee is paid the invoice`
4940
+ );
4941
+ }
4942
+ const rendezvous = await rendezvousFor(facts.amountSats);
4943
+ if (!rendezvous) {
4944
+ throw new Error(
4945
+ `${SOLVER_LIGHTNING_RAIL}: no solver serves arkade:BTC -> lightning:BTC at ${facts.amountSats} sats`
4946
+ );
4947
+ }
4948
+ const negotiated = await deps.connect(
4949
+ rendezvous,
4950
+ (transport) => requestLightningSend(ctx.wallet, transport, {
4951
+ invoice: facts,
4952
+ ...deps.emulatorPubkey ? { emulatorPubkey: deps.emulatorPubkey } : {}
4953
+ })
4954
+ );
4955
+ const swap = { ...negotiated, invoice: facts, rendezvous };
4956
+ return {
4957
+ railId: SOLVER_LIGHTNING_RAIL,
4958
+ // `requestLightningSend` refuses a quote that reprices the
4959
+ // invoice, so the spread is a fee on top.
4960
+ amount: facts.amountSats,
4961
+ fee: swap.fundAmount - facts.amountSats,
4962
+ total: swap.fundAmount,
4963
+ // The invoice can lapse before the quote does; the earlier bound
4964
+ // is the one a holder must observe.
4965
+ validUntil: Math.min(swap.quote.valid_until, facts.expiresAt),
4966
+ meta: {
4967
+ rfqId: swap.rfqId,
4968
+ validUntil: swap.quote.valid_until,
4969
+ paymentHash: facts.paymentHash,
4970
+ invoiceExpiresAt: facts.expiresAt,
4971
+ solverPubkey: rendezvous.solverPubkey
4972
+ },
4973
+ send: async () => (0, import_sdk18.makeHandle)(SOLVER_LIGHTNING_RAIL, async (emit) => {
4974
+ assertFundable({
4975
+ quote: swap.quote,
4976
+ invoiceExpiresAt: facts.expiresAt,
4977
+ now: Math.floor(Date.now() / 1e3)
5232
4978
  });
5233
- emit({ status: "sent" });
5234
- const result = { railId: SOLVER_ONCHAIN_RAIL, swapId: swap.rfqId };
5235
- if (!deps.awaitSettlement) return result;
5236
- let txid;
5237
- try {
5238
- ({ txid } = await deps.awaitSettlement(swap));
5239
- } catch (e) {
5240
- console.warn(
5241
- `${SOLVER_ONCHAIN_RAIL}: settlement watch failed; the payment is sent`,
5242
- e
5243
- );
5244
- return result;
5245
- }
5246
- const settled = { ...result, txid };
5247
- emit({ status: "settled", result: settled });
5248
- return settled;
4979
+ return fundSolverSend(
4980
+ SOLVER_LIGHTNING_RAIL,
4981
+ ctx,
4982
+ emit,
4983
+ deps,
4984
+ swap,
4985
+ ({ preimage }) => ({ ...preimage !== void 0 && { preimage } })
4986
+ );
5249
4987
  })
5250
4988
  };
5251
4989
  }
@@ -5253,8 +4991,8 @@ function solverOnchainRail(deps) {
5253
4991
  }
5254
4992
 
5255
4993
  // src/restore.ts
5256
- var import_base15 = require("@scure/base");
5257
- var import_sdk18 = require("@arkade-os/sdk");
4994
+ var import_base14 = require("@scure/base");
4995
+ var import_sdk19 = require("@arkade-os/sdk");
5258
4996
  var TXS_PER_REQUEST = 50;
5259
4997
  async function fetchParsedTxs(indexer, txids) {
5260
4998
  const parsedByTxid = /* @__PURE__ */ new Map();
@@ -5270,7 +5008,7 @@ async function fetchParsedTxs(indexer, txids) {
5270
5008
  if (result.status !== "fulfilled") continue;
5271
5009
  for (const psbt of result.value) {
5272
5010
  try {
5273
- const parsed = import_sdk18.Transaction.fromPSBT(import_base15.base64.decode(psbt));
5011
+ const parsed = import_sdk19.Transaction.fromPSBT(import_base14.base64.decode(psbt));
5274
5012
  parsedByTxid.set(parsed.id, parsed);
5275
5013
  } catch {
5276
5014
  }
@@ -5285,10 +5023,9 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
5285
5023
  let leaves;
5286
5024
  try {
5287
5025
  const script = offerContract(offer, operatorPubkey);
5288
- if (import_base15.hex.encode(script.pkScript) !== import_base15.hex.encode(offer.swapPkScript)) return "indeterminate";
5026
+ if (import_base14.hex.encode(script.pkScript) !== import_base14.hex.encode(offer.swapPkScript)) return "indeterminate";
5289
5027
  leaves = {
5290
- // both routes that hand the deposit back; `exit` is absent on an
5291
- // offer that carries no exit closure, and drops out here
5028
+ // `exit` is absent on an offer with no exit closure, and drops out here
5292
5029
  returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
5293
5030
  fulfill: script.functionByName("fulfill")?.leafScript
5294
5031
  };
@@ -5298,11 +5035,11 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
5298
5035
  for (let i = 0; i < spendTx.inputsLength; i++) {
5299
5036
  const input = spendTx.getInput(i);
5300
5037
  if (!input.txid || input.index !== deposit.vout) continue;
5301
- if (import_base15.hex.encode(input.txid) !== deposit.txid) continue;
5038
+ if (import_base14.hex.encode(input.txid) !== deposit.txid) continue;
5302
5039
  for (const leaf of input.tapLeafScript ?? []) {
5303
- const spent = import_base15.hex.encode((0, import_sdk18.scriptFromTapLeafScript)(leaf));
5304
- if (leaves.returned.some((back) => spent === import_base15.hex.encode(back))) return "cancelled";
5305
- if (leaves.fulfill && spent === import_base15.hex.encode(leaves.fulfill)) return "fulfilled";
5040
+ const spent = import_base14.hex.encode((0, import_sdk19.scriptFromTapLeafScript)(leaf));
5041
+ if (leaves.returned.some((back) => spent === import_base14.hex.encode(back))) return "cancelled";
5042
+ if (leaves.fulfill && spent === import_base14.hex.encode(leaves.fulfill)) return "fulfilled";
5306
5043
  }
5307
5044
  }
5308
5045
  return "indeterminate";
@@ -5322,7 +5059,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
5322
5059
  try {
5323
5060
  reopened.push({
5324
5061
  fundingTx: { type: "sent", redeemTxid: swap.fundingTxid },
5325
- offer: decodeOffer(import_base15.hex.decode(swap.offerHex)),
5062
+ offer: decodeOffer(import_base14.hex.decode(swap.offerHex)),
5326
5063
  offerHex: swap.offerHex,
5327
5064
  existing: swap
5328
5065
  });
@@ -5348,19 +5085,19 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
5348
5085
  if (!fundingTx) continue;
5349
5086
  fetchedTxids.push(txid);
5350
5087
  try {
5351
- const packet = import_sdk18.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
5088
+ const packet = import_sdk19.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
5352
5089
  if (!packet) continue;
5353
5090
  const payload = packet.serialize();
5354
5091
  found.push({
5355
5092
  fundingTx,
5356
5093
  offer: decodeOffer(payload),
5357
- offerHex: import_base15.hex.encode(payload)
5094
+ offerHex: import_base14.hex.encode(payload)
5358
5095
  });
5359
5096
  } catch {
5360
5097
  }
5361
5098
  }
5362
5099
  if (found.length === 0) return { restored: [], scannedTxids: fetchedTxids };
5363
- const scripts = [...new Set(found.map((f) => import_base15.hex.encode(f.offer.swapPkScript)))];
5100
+ const scripts = [...new Set(found.map((f) => import_base14.hex.encode(f.offer.swapPkScript)))];
5364
5101
  const { vtxos } = await indexer.getVtxos({ scripts });
5365
5102
  const vtxoByScriptAndTxid = new Map(vtxos.map((v) => [`${v.script}:${v.txid}`, v]));
5366
5103
  const txByAnyId = /* @__PURE__ */ new Map();
@@ -5372,7 +5109,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
5372
5109
  const spendTxids = /* @__PURE__ */ new Set();
5373
5110
  for (const { fundingTx, offer } of found) {
5374
5111
  const vtxo = vtxoByScriptAndTxid.get(
5375
- `${import_base15.hex.encode(offer.swapPkScript)}:${fundingTx.redeemTxid}`
5112
+ `${import_base14.hex.encode(offer.swapPkScript)}:${fundingTx.redeemTxid}`
5376
5113
  );
5377
5114
  if (!vtxo?.isSpent) continue;
5378
5115
  for (const txid of spendTxidsOf(vtxo)) spendTxids.add(txid);
@@ -5381,7 +5118,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
5381
5118
  const restored = [];
5382
5119
  const unresolved = /* @__PURE__ */ new Set();
5383
5120
  for (const { fundingTx, offer, offerHex, existing } of found) {
5384
- const swapPkScript = import_base15.hex.encode(offer.swapPkScript);
5121
+ const swapPkScript = import_base14.hex.encode(offer.swapPkScript);
5385
5122
  const vtxo = vtxoByScriptAndTxid.get(`${swapPkScript}:${fundingTx.redeemTxid}`);
5386
5123
  if (!vtxo) {
5387
5124
  unresolved.add(fundingTx.redeemTxid);
@@ -5420,7 +5157,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
5420
5157
  let swapAddress = "";
5421
5158
  try {
5422
5159
  const compiled = offerContract(offer, operatorPubkey);
5423
- if (import_base15.hex.encode(compiled.pkScript) !== swapPkScript) {
5160
+ if (import_base14.hex.encode(compiled.pkScript) !== swapPkScript) {
5424
5161
  unresolved.add(fundingTx.redeemTxid);
5425
5162
  continue;
5426
5163
  }
@@ -5444,8 +5181,6 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
5444
5181
  spentTxid,
5445
5182
  status,
5446
5183
  createdAt: fundingTx.createdAt ? fundingTx.createdAt * 1e3 : vtxo.createdAt.getTime(),
5447
- // the completion time is the caller's record of the spend, if it
5448
- // has one — the psbt that classified it carries no timestamp
5449
5184
  ...completion
5450
5185
  });
5451
5186
  }
@@ -5453,8 +5188,8 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
5453
5188
  }
5454
5189
 
5455
5190
  // src/watch.ts
5456
- var import_base16 = require("@scure/base");
5457
- var import_sdk19 = require("@arkade-os/sdk");
5191
+ var import_base15 = require("@scure/base");
5192
+ var import_sdk20 = require("@arkade-os/sdk");
5458
5193
  var TERMINAL = ["fulfilled", "cancelled", "recoverable"];
5459
5194
  var assetSwapSource = (repository) => ({
5460
5195
  list: () => getAssetSwaps(repository),
@@ -5486,7 +5221,7 @@ async function watchOfferSwaps({
5486
5221
  wallet.getAddress(),
5487
5222
  wallet.getArkadeReader()
5488
5223
  ]);
5489
- const operatorPubkey = import_sdk19.ArkAddress.decode(address).serverPubKey;
5224
+ const operatorPubkey = import_sdk20.ArkAddress.decode(address).serverPubKey;
5490
5225
  let queue = Promise.resolve();
5491
5226
  const enqueue = (task) => {
5492
5227
  queue = queue.then(task).catch(() => {
@@ -5499,9 +5234,9 @@ async function watchOfferSwaps({
5499
5234
  if (candidates.length === 0) return "indeterminate";
5500
5235
  const { txs } = await indexer.getVirtualTxs(candidates);
5501
5236
  return classifyDepositSpend(
5502
- decodeOffer(import_base16.hex.decode(swap.offerHex)),
5237
+ decodeOffer(import_base15.hex.decode(swap.offerHex)),
5503
5238
  operatorPubkey,
5504
- txs.map((psbt) => import_sdk19.Transaction.fromPSBT(import_base16.base64.decode(psbt))),
5239
+ txs.map((psbt) => import_sdk20.Transaction.fromPSBT(import_base15.base64.decode(psbt))),
5505
5240
  { txid: vtxo.txid, vout: vtxo.vout }
5506
5241
  );
5507
5242
  } catch {
@@ -5529,7 +5264,7 @@ async function watchOfferSwaps({
5529
5264
  }
5530
5265
  };
5531
5266
  const unsubscribe = manager.onContractEvent((event) => {
5532
- if (!(0, import_sdk19.isContractVtxoEvent)(event) || event.type !== "vtxo_spent") return;
5267
+ if (!(0, import_sdk20.isContractVtxoEvent)(event) || event.type !== "vtxo_spent") return;
5533
5268
  enqueue(() => handleSpend(event));
5534
5269
  });
5535
5270
  return {