@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/advanced.cjs CHANGED
@@ -179,18 +179,38 @@ var init_coverage = __esm({
179
179
  }
180
180
  });
181
181
 
182
+ // src/repository.ts
183
+ function assertRfqSwapPageFilter(filter) {
184
+ if (filter.since !== void 0 && (!Number.isSafeInteger(filter.since) || filter.since < 0)) {
185
+ throw new RangeError("RFQ history since must be non-negative Unix seconds");
186
+ }
187
+ }
188
+ var import_sdk, collectAssetSwaps, collectRfqSwaps, collectSwapRecords;
189
+ var init_repository = __esm({
190
+ "src/repository.ts"() {
191
+ "use strict";
192
+ import_sdk = require("@arkade-os/sdk");
193
+ collectAssetSwaps = (repository) => (0, import_sdk.collectPages)((page) => repository.getAssetSwapsPage(page));
194
+ collectRfqSwaps = (repository, filter = {}) => (0, import_sdk.collectPages)(
195
+ (page) => repository.getRfqSwapsPage(filter, page)
196
+ );
197
+ collectSwapRecords = (repository) => (0, import_sdk.collectPages)((page) => repository.getSwapRecordsPage(page));
198
+ }
199
+ });
200
+
182
201
  // src/store.ts
183
- var import_base, import_sha2, import_sdk, BTC_ASSET_ID, byNewest, getAssetSwapsOrThrow, getAssetSwaps, saveSwapOrThrow, updateAssetSwap, updateAssetSwapBestEffort, swapSecretsToRecord, decodeHex32, PreimageNotRecoverableError, preimageForSwapRecord;
202
+ var import_base, import_sha2, import_sdk2, BTC_ASSET_ID, byNewest, getAssetSwapsOrThrow, getAssetSwaps, saveSwapOrThrow, updateAssetSwap, updateAssetSwapBestEffort, swapSecretsToRecord, decodeHex32, PreimageNotRecoverableError, preimageForSwapRecord;
184
203
  var init_store = __esm({
185
204
  "src/store.ts"() {
186
205
  "use strict";
187
206
  import_base = require("@scure/base");
188
207
  import_sha2 = require("@noble/hashes/sha2.js");
189
- import_sdk = require("@arkade-os/sdk");
208
+ import_sdk2 = require("@arkade-os/sdk");
209
+ init_repository();
190
210
  BTC_ASSET_ID = "btc";
191
211
  byNewest = (a, b) => b.createdAt - a.createdAt;
192
212
  getAssetSwapsOrThrow = async (repository) => {
193
- return (await repository.getAllSwaps()).filter(
213
+ return (await collectAssetSwaps(repository)).filter(
194
214
  (s) => s && typeof s.id === "string" && // offer swaps carry the TLV; onchain-corridor swaps carry
195
215
  // the payment hash instead — either marks a valid record
196
216
  (typeof s.offerHex === "string" || typeof s.paymentHash === "string")
@@ -271,7 +291,7 @@ var init_store = __esm({
271
291
  }
272
292
  let preimage;
273
293
  try {
274
- preimage = await (0, import_sdk.contractPreimage)(wallet, record.signingDescriptor, { stored, salt });
294
+ preimage = await (0, import_sdk2.contractPreimage)(wallet, record.signingDescriptor, { stored, salt });
275
295
  } catch (cause) {
276
296
  throw new PreimageNotRecoverableError(
277
297
  "not-derivable",
@@ -336,7 +356,7 @@ function swapProgramBinding(offer, operatorPubkey) {
336
356
  }
337
357
  function offerContract(offer, operatorPubkey) {
338
358
  const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
339
- return new import_sdk2.arkade.ArkadeProgramScript(program, args, keys);
359
+ return new import_sdk3.arkade.ArkadeProgramScript(program, args, keys);
340
360
  }
341
361
  function u64(name, value) {
342
362
  if (value < BigInt(0) || value >> BigInt(64) > BigInt(0)) {
@@ -430,9 +450,7 @@ function decodeOffer(data) {
430
450
  }
431
451
  const need = (name) => {
432
452
  const v = fields[name];
433
- const len = FIELDS[name].width;
434
- if (!v || len !== void 0 && v.length !== len)
435
- throw new Error(`missing/invalid ${name}`);
453
+ if (!v) throw new Error(`missing/invalid ${name}`);
436
454
  return v;
437
455
  };
438
456
  const amount = need("wantAmount");
@@ -454,8 +472,8 @@ function decodeOffer(data) {
454
472
  return {
455
473
  swapPkScript: need("swapPkScript"),
456
474
  wantAmount: readU64(amount),
457
- ...fields.wantAsset && { wantAsset: import_sdk2.asset.AssetId.fromBytes(fields.wantAsset) },
458
- ...fields.offerAsset && { offerAsset: import_sdk2.asset.AssetId.fromBytes(fields.offerAsset) },
475
+ ...fields.wantAsset && { wantAsset: import_sdk3.asset.AssetId.fromBytes(fields.wantAsset) },
476
+ ...fields.offerAsset && { offerAsset: import_sdk3.asset.AssetId.fromBytes(fields.offerAsset) },
459
477
  makerPkScript: need("makerPkScript"),
460
478
  makerPublicKey: need("makerPublicKey"),
461
479
  emulatorPubkey: need("emulatorPubkey"),
@@ -471,20 +489,7 @@ function decodeExitDelay(value) {
471
489
  }
472
490
  async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript) {
473
491
  const contractManager = await wallet.getContractManager();
474
- const client = await import_sdk2.arkade.Arkade.connect({
475
- // Registration derives and persists; it never broadcasts and never
476
- // reads UTXOs, so the only thing the client needs off the server is the
477
- // info the caller already resolved. Handing that back — rather than a
478
- // provider built from a URL — is what lets `createOffer` take just a
479
- // wallet, and spares a second `/v1/info` round-trip.
480
- arkade: { getInfo: async () => info },
481
- identity: wallet.identity,
482
- // without this the row's `address` would be derived against the SDK's
483
- // default network while its script is right — a row that disagrees with
484
- // the address the user is about to fund
485
- network: (0, import_sdk2.networkFromArkadeInfo)(info),
486
- contractManager
487
- });
492
+ const client = await derivingClient(wallet, info, contractManager);
488
493
  await contractManager.createContract(
489
494
  offerContractParams(client, binding, operatorPubkey, expectedPkScript)
490
495
  );
@@ -492,7 +497,7 @@ async function registerOfferContract(wallet, info, binding, operatorPubkey, expe
492
497
  }
493
498
  function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
494
499
  const { program, args, keys } = swapProgramBinding(binding, operatorPubkey);
495
- const contract = new import_sdk2.arkade.ArkadeContract(client, program, args, keys);
500
+ const contract = new import_sdk3.arkade.ArkadeContract(client, program, args, keys);
496
501
  if (import_base2.hex.encode(contract.pkScript) !== import_base2.hex.encode(expectedPkScript)) {
497
502
  throw new Error("derived covenant does not match the offer's swapPkScript");
498
503
  }
@@ -511,47 +516,69 @@ function serverExitDelay(delay) {
511
516
  return assertExitDelay({ value: delay, type: delay < BigInt(512) ? "blocks" : "seconds" });
512
517
  }
513
518
  async function createOffer(wallet, params) {
519
+ const derived = await deriveOffer(wallet, params);
520
+ await registerDerivedOffer(wallet, derived);
521
+ return {
522
+ offerHex: derived.offerHex,
523
+ extension: derived.extension,
524
+ address: derived.address,
525
+ swapPkScript: derived.swapPkScript
526
+ };
527
+ }
528
+ async function deriveOffer(wallet, params) {
514
529
  if (Boolean(params.wantAsset) === Boolean(params.offerAsset)) {
515
530
  throw new Error("set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC)");
516
531
  }
517
- const [info, makerAddress, makerPublicKey] = await Promise.all([
518
- // requireLive: this info binds signerPubkey into the covenant — a
519
- // snapshot could derive an address the operator no longer co-signs
520
- // for, so an unreachable operator fails the call instead (fail closed,
521
- // the same behaviour the pre-#734 caller-held provider had)
522
- wallet.getArkadeInfo({ requireLive: true }),
523
- wallet.getAddress(),
524
- wallet.identity.xOnlyPublicKey()
532
+ const [info, maker] = await Promise.all([
533
+ // requireLive: this binds signerPubkey into the covenant, and a snapshot could derive an
534
+ // address the operator no longer co-signs for — fail closed instead
535
+ params.info ?? wallet.getArkadeInfo({ requireLive: true }),
536
+ params.maker ?? (async () => {
537
+ const [address, publicKey] = await Promise.all([
538
+ wallet.getAddress(),
539
+ wallet.identity.xOnlyPublicKey()
540
+ ]);
541
+ return { pkScript: import_sdk3.ArkAddress.decode(address).pkScript, publicKey };
542
+ })()
525
543
  ]);
526
- const operatorPubKey = import_base2.hex.decode((0, import_sdk2.toXOnlySignerHex)(info.signerPubkey));
527
- const network = (0, import_sdk2.networkFromArkadeInfo)(info);
544
+ const operatorPubKey = import_base2.hex.decode((0, import_sdk3.toXOnlySignerHex)(info.signerPubkey));
545
+ const network = (0, import_sdk3.networkFromArkadeInfo)(info);
528
546
  const emuKey = import_base2.hex.decode(
529
- (0, import_sdk2.toXOnlySignerHex)((0, import_sdk2.resolveEmulatorPubkey)(network, params.emulatorPubkey))
547
+ (0, import_sdk3.toXOnlySignerHex)((0, import_sdk3.resolveEmulatorPubkey)(network, params.emulatorPubkey))
530
548
  );
531
- const binding = {
549
+ const binding = Object.freeze({
532
550
  wantAmount: params.wantAmount,
533
551
  wantAsset: params.wantAsset,
534
552
  offerAsset: params.offerAsset,
535
- makerPkScript: import_sdk2.ArkAddress.decode(makerAddress).pkScript,
536
- makerPublicKey,
553
+ makerPkScript: maker.pkScript,
554
+ makerPublicKey: maker.publicKey,
537
555
  emulatorPubkey: emuKey,
538
- // checked HERE, before the covenant is derived and registered below:
539
- // deferring it to `encodeOffer` leaves a registered contract behind for
540
- // an offer that then fails to encode. @see assertExitDelay
556
+ // checked before registration below. @see assertExitDelay
541
557
  exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
542
- };
558
+ });
543
559
  const script = offerContract(binding, operatorPubKey);
544
560
  const offer = { ...binding, swapPkScript: script.pkScript };
545
- await registerOfferContract(wallet, info, binding, operatorPubKey, script.pkScript);
546
561
  const payload = encodeOffer(offer);
547
- return {
562
+ return Object.freeze({
548
563
  offerHex: import_base2.hex.encode(payload),
549
564
  extension: { type: OFFER_PACKET_TYPE, payload },
550
565
  // the contract's .address() builds the address; assembling an ArkAddress
551
566
  // from tweakedPublicKey here would silently miss any future step it gains
552
567
  address: script.address(network.hrp, operatorPubKey).encode(),
553
- swapPkScript: script.pkScript
554
- };
568
+ swapPkScript: script.pkScript,
569
+ binding,
570
+ info,
571
+ operatorPubkey: operatorPubKey
572
+ });
573
+ }
574
+ async function registerDerivedOffer(wallet, derived) {
575
+ await registerOfferContract(
576
+ wallet,
577
+ derived.info,
578
+ derived.binding,
579
+ derived.operatorPubkey,
580
+ derived.swapPkScript
581
+ );
555
582
  }
556
583
  async function prepareOfferCancel(wallet, offerHex, opts) {
557
584
  const { fundingTxid, swapAddress } = opts;
@@ -562,32 +589,27 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
562
589
  wallet.getArkadeReader(),
563
590
  wallet.getArkadeBroadcaster()
564
591
  ]);
565
- const client = await import_sdk2.arkade.Arkade.connect({
566
- // info the wallet already holds, plus its broadcast pair — the shape
567
- // `ArkadeServerProvider` describes, without a second `/v1/info`
592
+ const client = await import_sdk3.arkade.Arkade.connect({
568
593
  arkade: { getInfo: async () => info, ...broadcaster },
569
594
  indexer: reader,
570
595
  identity: wallet.identity,
571
- // registered offers resolve their VTXOs from the contract repository
572
- // instead of a direct indexer query; the indexer above stays as the
573
- // fallback for offers created before registration existed
596
+ // registered offers resolve VTXOs from the contract repository; the indexer is the fallback
597
+ // for offers created before registration existed
574
598
  contractManager
575
- // no `network`, unlike registerOfferContract: the row lookup is by
576
- // script and the payout script comes from wallet.getAddress(), so the
577
- // client's network (which only shapes address derivation) is unused here
599
+ // no `network`: the row lookup is by script and the payout comes from wallet.getAddress()
578
600
  });
579
- const operatorPubkey = swapAddress ? import_sdk2.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
601
+ const operatorPubkey = swapAddress ? import_sdk3.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
580
602
  const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
581
603
  let rebuilt;
582
604
  try {
583
- rebuilt = new import_sdk2.arkade.ArkadeProgramScript(program, args, keys);
605
+ rebuilt = new import_sdk3.arkade.ArkadeProgramScript(program, args, keys);
584
606
  } catch (cause) {
585
607
  throw new OfferCovenantMismatchError(import_base2.hex.encode(offer.swapPkScript), { cause });
586
608
  }
587
609
  if (import_base2.hex.encode(rebuilt.pkScript) !== import_base2.hex.encode(offer.swapPkScript)) {
588
610
  throw new OfferCovenantMismatchError(import_base2.hex.encode(offer.swapPkScript));
589
611
  }
590
- const contract = new import_sdk2.arkade.ArkadeContract(client, program, args, keys);
612
+ const contract = new import_sdk3.arkade.ArkadeContract(client, program, args, keys);
591
613
  const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
592
614
  if (!fundingTxid && vtxos.length > 1) {
593
615
  throw new Error(
@@ -596,7 +618,7 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
596
618
  }
597
619
  const vtxo = fundingTxid ? vtxos.find((v) => v.txid === fundingTxid) : vtxos[0];
598
620
  if (!vtxo) throw new NoSpendableDepositError();
599
- const makerPkScript = import_sdk2.ArkAddress.decode(makerAddress).pkScript;
621
+ const makerPkScript = import_sdk3.ArkAddress.decode(makerAddress).pkScript;
600
622
  const cancel = contract.functions.cancel().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).to(makerPkScript, BigInt(vtxo.value));
601
623
  for (const a of vtxo.assets ?? []) {
602
624
  cancel.withAsset({
@@ -611,20 +633,20 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
611
633
  send: async () => (await cancel.send()).txid
612
634
  };
613
635
  }
614
- var import_base2, import_utils, import_sdk2, swapPrograms, OFFER_PACKET_TYPE, FIELDS, EXIT_TYPES, NAMES, readU64, setRatio, OFFER_CONTRACT_LABEL, OFFER_CONTRACT_KIND, OFFER_COVENANT_MISMATCH, NoSpendableDepositError, OfferCovenantMismatchError, ASSET_CARRIER_SATS;
636
+ var import_base2, import_utils, import_sdk3, swapPrograms, OFFER_PACKET_TYPE, FIELDS, EXIT_TYPES, NAMES, readU64, setRatio, OFFER_CONTRACT_LABEL, OFFER_CONTRACT_KIND, derivingClient, NoSpendableDepositError, OfferCovenantMismatchError, ASSET_CARRIER_SATS;
615
637
  var init_offer = __esm({
616
638
  "src/offer.ts"() {
617
639
  "use strict";
618
640
  import_base2 = require("@scure/base");
619
641
  import_utils = require("@scure/btc-signer/utils.js");
620
- import_sdk2 = require("@arkade-os/sdk");
642
+ import_sdk3 = require("@arkade-os/sdk");
621
643
  init_swap_want_asset_program();
622
644
  init_swap_want_btc_program();
623
645
  init_coverage();
624
646
  init_store();
625
647
  swapPrograms = {
626
- wantAsset: import_sdk2.arkade.parseArtifact(swap_want_asset_program_default),
627
- wantBtc: import_sdk2.arkade.parseArtifact(swap_want_btc_program_default)
648
+ wantAsset: import_sdk3.arkade.parseArtifact(swap_want_asset_program_default),
649
+ wantBtc: import_sdk3.arkade.parseArtifact(swap_want_btc_program_default)
628
650
  };
629
651
  OFFER_PACKET_TYPE = 3;
630
652
  FIELDS = {
@@ -649,7 +671,12 @@ var init_offer = __esm({
649
671
  };
650
672
  OFFER_CONTRACT_LABEL = "Arkade swap offer";
651
673
  OFFER_CONTRACT_KIND = "asset-swap-offer";
652
- OFFER_COVENANT_MISMATCH = "rebuilt covenant does not match the offer's swapPkScript";
674
+ derivingClient = (wallet, info, contractManager) => import_sdk3.arkade.Arkade.connect({
675
+ arkade: { getInfo: async () => info },
676
+ identity: wallet.identity,
677
+ network: (0, import_sdk3.networkFromArkadeInfo)(info),
678
+ contractManager
679
+ });
653
680
  NoSpendableDepositError = class extends Error {
654
681
  name = "NoSpendableDepositError";
655
682
  constructor(options) {
@@ -659,7 +686,7 @@ var init_offer = __esm({
659
686
  OfferCovenantMismatchError = class extends Error {
660
687
  constructor(swapPkScript, options) {
661
688
  super(
662
- `${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`,
689
+ "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",
663
690
  options
664
691
  );
665
692
  this.swapPkScript = swapPkScript;
@@ -667,7 +694,7 @@ var init_offer = __esm({
667
694
  swapPkScript;
668
695
  name = "OfferCovenantMismatchError";
669
696
  };
670
- ASSET_CARRIER_SATS = BigInt(import_sdk2.ASSET_CARRIER_SATS);
697
+ ASSET_CARRIER_SATS = BigInt(import_sdk3.ASSET_CARRIER_SATS);
671
698
  }
672
699
  });
673
700
 
@@ -676,7 +703,7 @@ async function registerLockupContract(contracts, script, address) {
676
703
  try {
677
704
  await contracts.createContract({
678
705
  type: SWAP_LOCKUP_CONTRACT_TYPE,
679
- params: import_sdk3.VHTLCV2ContractHandler.serializeParams(script.options),
706
+ params: import_sdk4.VHTLCV2ContractHandler.serializeParams(script.options),
680
707
  script: import_base3.hex.encode(script.pkScript),
681
708
  address,
682
709
  label: SWAP_LOCKUP_CONTRACT_LABEL,
@@ -687,17 +714,17 @@ async function registerLockupContract(contracts, script, address) {
687
714
  }
688
715
  }
689
716
  async function lockupContractParams(contracts, lockupAddress) {
690
- const script = import_base3.hex.encode(import_sdk3.ArkAddress.decode(lockupAddress).pkScript);
717
+ const script = import_base3.hex.encode(import_sdk4.ArkAddress.decode(lockupAddress).pkScript);
691
718
  const [row] = await contracts.getContracts({ script });
692
719
  if (!row) throw new LockupContractMissing(lockupAddress, script);
693
720
  return row.params;
694
721
  }
695
- var import_base3, import_sdk3, SWAP_LOCKUP_CONTRACT_TYPE, SWAP_LOCKUP_CONTRACT_LABEL, SWAP_LOCKUP_CONTRACT_KIND, LockupContractMissing, LockupRegistrationFailed;
722
+ var import_base3, import_sdk4, SWAP_LOCKUP_CONTRACT_TYPE, SWAP_LOCKUP_CONTRACT_LABEL, SWAP_LOCKUP_CONTRACT_KIND, LockupContractMissing, LockupRegistrationFailed;
696
723
  var init_lockupContract = __esm({
697
724
  "src/lockupContract.ts"() {
698
725
  "use strict";
699
726
  import_base3 = require("@scure/base");
700
- import_sdk3 = require("@arkade-os/sdk");
727
+ import_sdk4 = require("@arkade-os/sdk");
701
728
  SWAP_LOCKUP_CONTRACT_TYPE = "vhtlc-v2";
702
729
  SWAP_LOCKUP_CONTRACT_LABEL = "Arkade RFQ swap lockup";
703
730
  SWAP_LOCKUP_CONTRACT_KIND = "rfq-swap-lockup";
@@ -719,8 +746,8 @@ var init_lockupContract = __esm({
719
746
  /** The lockup address that was never registered — never fund it: nothing
720
747
  * is watching it. */
721
748
  address;
722
- /** The covenant the row would have been written from — the other half of
723
- * `registerLockupContract`, so the write is retryable without a quote. */
749
+ /** The covenant the row would have been written from, so the write is retryable without a
750
+ * quote. */
724
751
  script;
725
752
  constructor(script, address, cause) {
726
753
  super(`failed to register the lockup contract for ${address}`, { cause });
@@ -810,11 +837,10 @@ function extractPreimage(txHex, paymentHash) {
810
837
  async function claimOnchainFill(chain, input) {
811
838
  const now = input.now ?? Math.floor(Date.now() / 1e3);
812
839
  if (input.htlc.refundLocktime - now < ONCHAIN_CLAIM_MARGIN_SECONDS) {
813
- const error = new Error(
840
+ throw gateError(
841
+ "claim_window_closed",
814
842
  "refund leaf opens too soon to claim safely \u2014 take the covenant refund instead"
815
843
  );
816
- error.reason = "claim_window_closed";
817
- throw error;
818
844
  }
819
845
  const spend = await buildHtlcClaim(input);
820
846
  const txid = await chain.broadcast(spend.txHex);
@@ -844,7 +870,7 @@ async function classifyOnchainHtlc(chain, input) {
844
870
  if (mtp >= input.htlc.refundLocktime) return { phase: "refundable", utxo: best };
845
871
  return { phase: "claimable", utxo: best };
846
872
  }
847
- var import_base4, import_sha22, import_legacy, btc, ONCHAIN_ORDER_MARGIN_SECONDS, ONCHAIN_CLAIM_MARGIN_SECONDS, MAX_MIN_CONFIRMATIONS, LOCKTIME_THRESHOLD, ONCHAIN_SECONDS_PER_BLOCK, ONCHAIN_DUST_SATS, ONCHAIN_CLAIM_VSIZE, paymentHashOf, h160FromPaymentHash, L1_NETWORKS, l1ScriptForAddress, buildLeafSpend, buildHtlcClaim;
873
+ var import_base4, import_sha22, import_legacy, btc, ONCHAIN_ORDER_MARGIN_SECONDS, ONCHAIN_CLAIM_MARGIN_SECONDS, MAX_MIN_CONFIRMATIONS, LOCKTIME_THRESHOLD, ONCHAIN_SECONDS_PER_BLOCK, ONCHAIN_DUST_SATS, ONCHAIN_CLAIM_VSIZE, paymentHashOf, h160FromPaymentHash, assertPreimageMatches, gateError, L1_NETWORKS, l1ScriptForAddress, buildLeafSpend, buildHtlcClaim;
848
874
  var init_onchainHtlc = __esm({
849
875
  "src/onchainHtlc.ts"() {
850
876
  "use strict";
@@ -861,6 +887,16 @@ var init_onchainHtlc = __esm({
861
887
  ONCHAIN_CLAIM_VSIZE = 152;
862
888
  paymentHashOf = (preimage) => import_base4.hex.encode((0, import_sha22.sha256)(preimage));
863
889
  h160FromPaymentHash = (paymentHash) => (0, import_legacy.ripemd160)(import_base4.hex.decode(paymentHash));
890
+ assertPreimageMatches = (preimage, preimageHash) => {
891
+ if (import_base4.hex.encode((0, import_legacy.ripemd160)((0, import_sha22.sha256)(preimage))) !== import_base4.hex.encode(preimageHash)) {
892
+ throw new Error("preimage does not match the covenant's payment hash");
893
+ }
894
+ };
895
+ gateError = (reason, message) => {
896
+ const error = new Error(message);
897
+ error.reason = reason;
898
+ return error;
899
+ };
864
900
  L1_NETWORKS = {
865
901
  bitcoin: btc.NETWORK,
866
902
  testnet: btc.TEST_NETWORK,
@@ -950,10 +986,7 @@ async function sealWithEntropy(input, ephemeralKey, nonce) {
950
986
  const key = (0, import_hkdf.hkdf)(import_sha23.sha256, sharedX, ephemeralPub, HKDF_INFO, 32);
951
987
  if (nonce.length !== 12) throw new Error("nonce must be 12 bytes");
952
988
  const sealed = (0, import_aes.gcm)(key, nonce, ephemeralPub).encrypt(input.preimage);
953
- const ciphertext = new Uint8Array(33 + 12 + sealed.length);
954
- ciphertext.set(ephemeralPub, 0);
955
- ciphertext.set(nonce, 33);
956
- ciphertext.set(sealed, 45);
989
+ const ciphertext = (0, import_utils2.concatBytes)(ephemeralPub, nonce, sealed);
957
990
  return {
958
991
  ciphertext: import_base6.base64.encode(ciphertext),
959
992
  packet: import_base6.base64.encode(
@@ -983,27 +1016,12 @@ var init_claimPacket = __esm({
983
1016
 
984
1017
  // src/rfq.ts
985
1018
  function lightningSendContract(params) {
986
- const seconds = (value) => ({
987
- type: "seconds",
988
- value: BigInt(value)
989
- });
990
- return new import_sdk5.VHTLC.ScriptV2({
1019
+ return suiteVhtlc(params, {
991
1020
  sender: params.senderPubkey,
992
1021
  receiver: params.solverPubkey,
993
- server: params.operatorPubkey,
994
- preimageHash: (0, import_legacy2.ripemd160)(import_base7.hex.decode(params.paymentHash)),
995
- refundLocktime: BigInt(params.refundLocktime),
996
- unilateralClaimDelay: seconds(params.claimDelay),
997
- unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
998
- unilateralRefundWithoutReceiverDelay: seconds(
999
- params.refundWithoutReceiverDelay ?? unilateralRefundWithoutReceiverDelay(params.claimDelay)
1000
- ),
1001
- nonInteractiveParameters: {
1002
- receiverPkScript: params.receiverPkScript,
1003
- senderPkScript: params.refundPkScript,
1004
- emulatorPubkey: params.emulatorPubkey,
1005
- ...params.legacy !== void 0 && { legacy: params.legacy }
1006
- }
1022
+ senderPkScript: params.refundPkScript,
1023
+ receiverPkScript: params.receiverPkScript,
1024
+ refundWithoutReceiverDelay: params.refundWithoutReceiverDelay
1007
1025
  });
1008
1026
  }
1009
1027
  function deriveLightningSend(input) {
@@ -1026,7 +1044,7 @@ function deriveLightningSend(input) {
1026
1044
  throw new Error("lightning-send quote is missing profile.receiver_pk_script");
1027
1045
  }
1028
1046
  const contractParams = {
1029
- solverPubkey: (0, import_sdk5.toXOnly)(import_base7.hex.decode(quote.solver_pubkey), "solver key"),
1047
+ solverPubkey: (0, import_sdk6.toXOnly)(import_base7.hex.decode(quote.solver_pubkey), "solver key"),
1030
1048
  refundLocktime: quote.refund_locktime,
1031
1049
  operatorPubkey: input.operatorPubkey,
1032
1050
  paymentHash: input.paymentHash,
@@ -1067,7 +1085,7 @@ function deriveOnchainSend(input) {
1067
1085
  throw new Error("onchain-send quote is missing a binding field");
1068
1086
  }
1069
1087
  const contractParams = {
1070
- solverPubkey: (0, import_sdk5.toXOnly)(import_base7.hex.decode(quote.solver_pubkey), "solver key"),
1088
+ solverPubkey: (0, import_sdk6.toXOnly)(import_base7.hex.decode(quote.solver_pubkey), "solver key"),
1071
1089
  refundLocktime,
1072
1090
  operatorPubkey: input.operatorPubkey,
1073
1091
  paymentHash: input.paymentHash,
@@ -1075,7 +1093,7 @@ function deriveOnchainSend(input) {
1075
1093
  emulatorPubkey: input.emulatorPubkey,
1076
1094
  senderPubkey: input.senderPubkey,
1077
1095
  receiverPkScript: solverHex(receiverPkScriptHex, "profile.receiver_pk_script"),
1078
- refundPkScript: import_sdk5.ArkAddress.decode(input.refundAddress).pkScript
1096
+ refundPkScript: import_sdk6.ArkAddress.decode(input.refundAddress).pkScript
1079
1097
  };
1080
1098
  const { script, address } = matchQuotedLockup(
1081
1099
  quote,
@@ -1086,7 +1104,7 @@ function deriveOnchainSend(input) {
1086
1104
  const htlcParams = {
1087
1105
  paymentHash: input.paymentHash,
1088
1106
  claimKey: input.payoutPubkey,
1089
- refundKey: (0, import_sdk5.toXOnly)(import_base7.hex.decode(htlcPubkey), "solver L1 htlc key"),
1107
+ refundKey: (0, import_sdk6.toXOnly)(import_base7.hex.decode(htlcPubkey), "solver L1 htlc key"),
1090
1108
  refundLocktime: htlcLocktime
1091
1109
  };
1092
1110
  const htlc = onchainHtlcScript(htlcParams, input.l1Network);
@@ -1105,27 +1123,11 @@ function deriveOnchainSend(input) {
1105
1123
  };
1106
1124
  }
1107
1125
  function lightningReceiveContract(params) {
1108
- const seconds = (value) => ({
1109
- type: "seconds",
1110
- value: BigInt(value)
1111
- });
1112
- return new import_sdk5.VHTLC.ScriptV2({
1126
+ return suiteVhtlc(params, {
1113
1127
  sender: params.solverPubkey,
1114
1128
  receiver: params.payoutPubkey,
1115
- server: params.operatorPubkey,
1116
- preimageHash: (0, import_legacy2.ripemd160)(import_base7.hex.decode(params.paymentHash)),
1117
- refundLocktime: BigInt(params.refundLocktime),
1118
- unilateralClaimDelay: seconds(params.claimDelay),
1119
- unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
1120
- unilateralRefundWithoutReceiverDelay: seconds(
1121
- unilateralRefundWithoutReceiverDelay(params.claimDelay)
1122
- ),
1123
- nonInteractiveParameters: {
1124
- receiverPkScript: params.payoutPkScript,
1125
- senderPkScript: params.solverRefundPkScript,
1126
- emulatorPubkey: params.emulatorPubkey,
1127
- ...params.legacy !== void 0 && { legacy: params.legacy }
1128
- }
1129
+ senderPkScript: params.solverRefundPkScript,
1130
+ receiverPkScript: params.payoutPkScript
1129
1131
  });
1130
1132
  }
1131
1133
  function deriveLightningReceive(input) {
@@ -1137,22 +1139,10 @@ function deriveLightningReceive(input) {
1137
1139
  if (refundLocktime === void 0 || invoice === void 0 || solverRefundPkScriptHex === void 0) {
1138
1140
  throw new Error("lightning-receive quote is missing a binding field");
1139
1141
  }
1140
- const contractParams = {
1141
- solverPubkey: (0, import_sdk5.toXOnly)(import_base7.hex.decode(quote.solver_pubkey), "solver key"),
1142
+ const { contractParams, matched } = matchReceiveLockup(
1143
+ input,
1142
1144
  refundLocktime,
1143
- operatorPubkey: input.operatorPubkey,
1144
- paymentHash: input.paymentHash,
1145
- claimDelay: input.claimDelay,
1146
- emulatorPubkey: input.emulatorPubkey,
1147
- solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
1148
- payoutPubkey: input.payoutPubkey,
1149
- payoutPkScript: import_sdk5.ArkAddress.decode(input.payoutAddress).pkScript
1150
- };
1151
- const matched = matchQuotedLockup(
1152
- quote,
1153
- input.hrp,
1154
- input.operatorPubkey,
1155
- (legacy) => lightningReceiveContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
1145
+ solverRefundPkScriptHex
1156
1146
  );
1157
1147
  return {
1158
1148
  address: matched.address,
@@ -1166,17 +1156,17 @@ function deriveLightningReceive(input) {
1166
1156
  }
1167
1157
  };
1168
1158
  }
1169
- var import_base7, import_solver_discovery, import_legacy2, import_sdk5, import_sdk6, solverHex, quoteSats, quoteAmountSats, quoteExpectedSats, ARKADE_BTC, LIGHTNING_BTC, ONCHAIN_BTC, rfqPair, LIGHTNING_SEND_PAIR, LIGHTNING_RECEIVE_PAIR, ONCHAIN_SEND_PAIR, ONCHAIN_RECEIVE_PAIR, RFQ_REFUSAL_ERROR_CODES, isRfqRefusalErrorCode, REFUSAL_FIELDS, REFUSAL_UNITS, safeInteger, safeRefusalDetail, refusalMessage, SwapRefusal, AddressMismatch, newRfqId, lightningSendRequest, MIN_HEADROOM_SECONDS, gateError, assertFinite, MAX_PAIR_LENGTH, assertPairLength, verifyLockupAddress, LOCKUP_SHAPE_VARIANTS, matchQuotedLockup, assertFundable, expectQuote, pairOf, SEQUENCE_GRANULARITY_SECONDS, SOLO_REFUND_HEADROOM_SECONDS, unilateralClaimDelay, unilateralRefundDelay, unilateralRefundWithoutReceiverDelay, l1NetworkFromArk, onchainSendRequest, lightningReceiveRequest, MIN_CLAIM_WINDOW_SECONDS, assertReceivable;
1159
+ var import_base7, import_solver_discovery, import_legacy2, import_sdk6, import_sdk7, solverHex, quoteSats, quoteAmountSats, quoteExpectedSats, ARKADE_BTC, LIGHTNING_BTC, ONCHAIN_BTC, arkadeAssetLeg, rfqPair, LIGHTNING_SEND_PAIR, LIGHTNING_RECEIVE_PAIR, ONCHAIN_SEND_PAIR, ONCHAIN_RECEIVE_PAIR, RFQ_REFUSAL_ERROR_CODES, isRfqRefusalErrorCode, REFUSAL_FIELDS, REFUSAL_UNITS, safeInteger, safeRefusalDetail, refusalMessage, SwapRefusal, AddressMismatch, newRfqId, lightningSendRequest, arkadeSwapRequest, canonicalAssetAmount, normalizeHexBytes, normalizeMakerPkScript, normalizeMakerPublicKey, MIN_HEADROOM_SECONDS, assertFinite, MAX_PAIR_LENGTH, assertPairLength, verifyLockupAddress, LOCKUP_SHAPE_VARIANTS, matchQuotedLockup, assertFundable, expectQuote, pairOf, SEQUENCE_GRANULARITY_SECONDS, SOLO_REFUND_HEADROOM_SECONDS, unilateralClaimDelay, unilateralRefundDelay, unilateralRefundWithoutReceiverDelay, seconds, suiteVhtlc, offerTermsFromQuote, verifyOfferAddress, quoteCarrierSats, l1NetworkFromArk, onchainSendRequest, lightningReceiveRequest, MIN_CLAIM_WINDOW_SECONDS, assertReceivable, matchReceiveLockup;
1170
1160
  var init_rfq = __esm({
1171
1161
  "src/rfq.ts"() {
1172
1162
  "use strict";
1173
1163
  import_base7 = require("@scure/base");
1174
1164
  import_solver_discovery = require("@arkade-os/solver-discovery");
1175
1165
  import_legacy2 = require("@noble/hashes/legacy.js");
1176
- import_sdk5 = require("@arkade-os/sdk");
1166
+ import_sdk6 = require("@arkade-os/sdk");
1177
1167
  init_onchainHtlc();
1178
1168
  init_onchainHtlc();
1179
- import_sdk6 = require("@arkade-os/sdk");
1169
+ import_sdk7 = require("@arkade-os/sdk");
1180
1170
  init_claimPacket();
1181
1171
  init_lockupContract();
1182
1172
  init_offer();
@@ -1208,6 +1198,7 @@ var init_rfq = __esm({
1208
1198
  ARKADE_BTC = "arkade:BTC";
1209
1199
  LIGHTNING_BTC = "lightning:BTC";
1210
1200
  ONCHAIN_BTC = "onchain:BTC";
1201
+ arkadeAssetLeg = (id) => `arkade:${id.toString()}`;
1211
1202
  rfqPair = (from, to) => `${from}->${to}`;
1212
1203
  LIGHTNING_SEND_PAIR = rfqPair(ARKADE_BTC, LIGHTNING_BTC);
1213
1204
  LIGHTNING_RECEIVE_PAIR = rfqPair(LIGHTNING_BTC, ARKADE_BTC);
@@ -1266,8 +1257,7 @@ var init_rfq = __esm({
1266
1257
  };
1267
1258
  SwapRefusal = class extends Error {
1268
1259
  /** Literal-typed so the v2 error taxonomy's union discriminates on `name`
1269
- * — a `string` here collapses the discriminant for every member. Same value
1270
- * the constructor has always set, moved to a field initializer. */
1260
+ * — a `string` here collapses the discriminant for every member. */
1271
1261
  name = "SwapRefusal";
1272
1262
  reason;
1273
1263
  rfqId;
@@ -1313,12 +1303,74 @@ var init_rfq = __esm({
1313
1303
  client_refund_pubkey: import_base7.hex.encode(input.senderPubkey)
1314
1304
  }
1315
1305
  });
1316
- MIN_HEADROOM_SECONDS = 90 * 60;
1317
- gateError = (reason, message) => {
1318
- const error = new Error(message);
1319
- error.reason = reason;
1320
- return error;
1306
+ arkadeSwapRequest = (input) => {
1307
+ if (!input.wantAsset && !input.offerAsset) {
1308
+ throw new Error(
1309
+ "set at least one of wantAsset or offerAsset \u2014 with neither set both legs are BTC, which is not a swap"
1310
+ );
1311
+ }
1312
+ const pair = rfqPair(
1313
+ input.offerAsset ? arkadeAssetLeg(input.offerAsset) : ARKADE_BTC,
1314
+ input.wantAsset ? arkadeAssetLeg(input.wantAsset) : ARKADE_BTC
1315
+ );
1316
+ assertPairLength(pair);
1317
+ return {
1318
+ v: 1,
1319
+ type: "rfq_request",
1320
+ rfq_id: input.rfqId,
1321
+ pair,
1322
+ amount_side: input.amountSide ?? "from",
1323
+ amount: canonicalAssetAmount(input.amount),
1324
+ // The solver's `.strict()` schema refuses any undeclared key as `unsupported_payload`.
1325
+ profile: {
1326
+ maker_pk_script: normalizeMakerPkScript(input.makerPkScript),
1327
+ maker_public_key: normalizeMakerPublicKey(input.makerPublicKey)
1328
+ }
1329
+ };
1330
+ };
1331
+ canonicalAssetAmount = (amount) => {
1332
+ if (typeof amount === "bigint") {
1333
+ if (amount <= 0n) throw new Error(`amount must be positive, got ${amount}`);
1334
+ return amount.toString();
1335
+ }
1336
+ if (typeof amount === "number") {
1337
+ if (!Number.isSafeInteger(amount) || amount <= 0) {
1338
+ throw new Error(`amount must be a positive safe integer, got ${amount}`);
1339
+ }
1340
+ return String(amount);
1341
+ }
1342
+ if (!/^(0|[1-9][0-9]*)$/.test(amount) || BigInt(amount) <= 0n) {
1343
+ throw new Error(`amount must be a canonical decimal string of atomic units, got ${amount}`);
1344
+ }
1345
+ return amount;
1321
1346
  };
1347
+ normalizeHexBytes = (value, expectedBytes, label) => {
1348
+ if (value === void 0 || value === null) {
1349
+ throw new Error(`${label} is required`);
1350
+ }
1351
+ const bytes = typeof value === "string" ? solverHex(value, label) : value;
1352
+ if (!(bytes instanceof Uint8Array) || bytes.length !== expectedBytes) {
1353
+ const got = bytes instanceof Uint8Array ? bytes.length : typeof bytes;
1354
+ throw new Error(`${label} must be ${expectedBytes} bytes, got ${got}`);
1355
+ }
1356
+ return import_base7.hex.encode(bytes);
1357
+ };
1358
+ normalizeMakerPkScript = (value) => {
1359
+ const encoded = normalizeHexBytes(value, 34, "maker_pk_script");
1360
+ if (!encoded.startsWith("5100") && !encoded.startsWith("5120")) {
1361
+ throw new Error("maker_pk_script must be a taproot scriptPubKey (OP_1 <32-byte program>)");
1362
+ }
1363
+ return encoded;
1364
+ };
1365
+ normalizeMakerPublicKey = (value) => {
1366
+ const raw = typeof value === "string" ? value : import_base7.hex.encode(value);
1367
+ const bytes = solverHex(raw, "maker_public_key");
1368
+ if (bytes.length === 33) {
1369
+ throw new Error("maker_public_key must be x-only (32 bytes), not compressed (33 bytes)");
1370
+ }
1371
+ return normalizeHexBytes(bytes, 32, "maker_public_key");
1372
+ };
1373
+ MIN_HEADROOM_SECONDS = 90 * 60;
1322
1374
  assertFinite = (value, reason, label) => {
1323
1375
  if (value !== void 0 && !Number.isFinite(value)) {
1324
1376
  throw gateError(reason, `${label} is not a finite number (${String(value)})`);
@@ -1468,6 +1520,58 @@ var init_rfq = __esm({
1468
1520
  };
1469
1521
  unilateralRefundDelay = (claimDelay) => claimDelay;
1470
1522
  unilateralRefundWithoutReceiverDelay = (claimDelay) => claimDelay + SOLO_REFUND_HEADROOM_SECONDS;
1523
+ seconds = (value) => ({
1524
+ type: "seconds",
1525
+ value: BigInt(value)
1526
+ });
1527
+ suiteVhtlc = (params, roles) => new import_sdk6.VHTLC.ScriptV2({
1528
+ sender: roles.sender,
1529
+ receiver: roles.receiver,
1530
+ server: params.operatorPubkey,
1531
+ preimageHash: (0, import_legacy2.ripemd160)(import_base7.hex.decode(params.paymentHash)),
1532
+ refundLocktime: BigInt(params.refundLocktime),
1533
+ unilateralClaimDelay: seconds(params.claimDelay),
1534
+ unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
1535
+ unilateralRefundWithoutReceiverDelay: seconds(
1536
+ roles.refundWithoutReceiverDelay ?? unilateralRefundWithoutReceiverDelay(params.claimDelay)
1537
+ ),
1538
+ nonInteractiveParameters: {
1539
+ receiverPkScript: roles.receiverPkScript,
1540
+ senderPkScript: roles.senderPkScript,
1541
+ emulatorPubkey: params.emulatorPubkey,
1542
+ ...params.legacy !== void 0 && { legacy: params.legacy }
1543
+ }
1544
+ });
1545
+ offerTermsFromQuote = (quote, assets) => {
1546
+ if (!assets.wantAsset && !assets.offerAsset) {
1547
+ throw new Error("set at least one of wantAsset or offerAsset");
1548
+ }
1549
+ const wantAmount = BigInt(quote.to_amount);
1550
+ if (assets.wantAsset) return { wantAmount, wantAsset: assets.wantAsset };
1551
+ return { wantAmount, offerAsset: assets.offerAsset };
1552
+ };
1553
+ verifyOfferAddress = (quote, derived) => {
1554
+ const quotedAddress = quote.profile?.offer_address;
1555
+ const quotedScript = quote.profile?.offer_pk_script;
1556
+ const derivedScript = import_base7.hex.encode(derived.swapPkScript);
1557
+ if (quotedAddress !== derived.address || quotedScript !== derivedScript) {
1558
+ throw new AddressMismatch([derived.address], quotedAddress);
1559
+ }
1560
+ return derived;
1561
+ };
1562
+ quoteCarrierSats = (quote) => {
1563
+ const raw = quote.carrier_sats;
1564
+ if (raw === void 0) return ASSET_CARRIER_SATS;
1565
+ const canonical = typeof raw === "number" ? Number.isSafeInteger(raw) && raw >= 0 : /^(0|[1-9][0-9]*)$/.test(raw);
1566
+ if (!canonical) {
1567
+ throw gateError(
1568
+ "carrier_malformed",
1569
+ `quote carrier_sats ${String(raw)} is not a non-negative integer`
1570
+ );
1571
+ }
1572
+ const published = BigInt(raw);
1573
+ return published > 0n ? published : ASSET_CARRIER_SATS;
1574
+ };
1471
1575
  l1NetworkFromArk = (network) => network === "bitcoin" ? "bitcoin" : network === "regtest" ? "regtest" : "testnet";
1472
1576
  onchainSendRequest = (input) => ({
1473
1577
  v: 1,
@@ -1524,6 +1628,26 @@ var init_rfq = __esm({
1524
1628
  );
1525
1629
  }
1526
1630
  };
1631
+ matchReceiveLockup = (input, refundLocktime, solverRefundPkScriptHex) => {
1632
+ const contractParams = {
1633
+ solverPubkey: (0, import_sdk6.toXOnly)(import_base7.hex.decode(input.quote.solver_pubkey), "solver key"),
1634
+ refundLocktime,
1635
+ operatorPubkey: input.operatorPubkey,
1636
+ paymentHash: input.paymentHash,
1637
+ claimDelay: input.claimDelay,
1638
+ emulatorPubkey: input.emulatorPubkey,
1639
+ solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
1640
+ payoutPubkey: input.payoutPubkey,
1641
+ payoutPkScript: import_sdk6.ArkAddress.decode(input.payoutAddress).pkScript
1642
+ };
1643
+ const matched = matchQuotedLockup(
1644
+ input.quote,
1645
+ input.hrp,
1646
+ input.operatorPubkey,
1647
+ (legacy) => lightningReceiveContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
1648
+ );
1649
+ return { contractParams, matched };
1650
+ };
1527
1651
  }
1528
1652
  });
1529
1653
 
@@ -1590,9 +1714,7 @@ var init_nostr = __esm({
1590
1714
  if (!rfqId) return;
1591
1715
  waiters.get(rfqId)?.resolve(payload);
1592
1716
  },
1593
- // subscribeMany calls this once every relay has closed. Nothing will
1594
- // arrive after it, so failing now beats waiting out the timeout — and
1595
- // it names the real cause instead of implicating the solver.
1717
+ // Called once every relay has closed: fail now with the real cause, not at timeout.
1596
1718
  onclose(reasons) {
1597
1719
  if (closed) return;
1598
1720
  const error = new RelayUnavailable(closeReasons(reasons));
@@ -1741,6 +1863,7 @@ __export(advanced_exports, {
1741
1863
  familyOfSwapId: () => familyOfSwapId,
1742
1864
  fateMoved: () => fateMoved,
1743
1865
  feedFetch: () => feedFetch,
1866
+ feedSpread: () => feedSpread,
1744
1867
  formatAssetId: () => formatAssetId,
1745
1868
  fromAtomicDecimal: () => fromAtomicDecimal,
1746
1869
  fromRfqAmountSide: () => fromRfqAmountSide,
@@ -1804,7 +1927,10 @@ __export(advanced_exports, {
1804
1927
  toRfqAmountSide: () => toRfqAmountSide,
1805
1928
  toSafeNumber: () => toSafeNumber,
1806
1929
  usableMarkets: () => usableMarkets,
1930
+ verifiedCarrierSats: () => verifiedCarrierSats,
1931
+ verifyCrossAssetAmount: () => verifyCrossAssetAmount,
1807
1932
  verifyPair: () => verifyPair,
1933
+ verifyPlanLegs: () => verifyPlanLegs,
1808
1934
  verifyQuoteTtl: () => verifyQuoteTtl,
1809
1935
  verifyQuotedAmount: () => verifyQuotedAmount,
1810
1936
  verifyReceiveInvoiceFacts: () => verifyReceiveInvoiceFacts,
@@ -1822,7 +1948,7 @@ module.exports = __toCommonJS(advanced_exports);
1822
1948
 
1823
1949
  // src/client/accept.ts
1824
1950
  var import_base8 = require("@scure/base");
1825
- var import_sdk9 = require("@arkade-os/sdk");
1951
+ var import_sdk10 = require("@arkade-os/sdk");
1826
1952
  init_offer();
1827
1953
  init_lockupContract();
1828
1954
 
@@ -1840,20 +1966,12 @@ var RfqCorridorRegistry = class {
1840
1966
  }
1841
1967
  this.handlers.set(handler.kind, handler);
1842
1968
  }
1843
- /** Takes a bare `string`, deliberately, where {@link RfqCorridorHandler.kind}
1844
- * is the manager's union: a lookup key comes off a record a backend handed
1845
- * back, and that it typechecks as a `kind` is a claim about the type, not
1846
- * about what was stored. Narrowing this would read as a check already made. */
1969
+ /** A bare `string` on purpose: the key comes off a stored record, and narrowing it to the
1970
+ * `kind` union would read as a check already made. */
1847
1971
  get(kind) {
1848
1972
  return this.handlers.get(kind);
1849
1973
  }
1850
- /**
1851
- * The handler for a kind, or a loud failure.
1852
- *
1853
- * A record whose corridor is not registered cannot be restored, and
1854
- * guessing would monitor a swap with no idea how to drive it. Names the
1855
- * registered kinds so a missing `register()` call is obvious.
1856
- */
1974
+ /** The handler for a kind, or a loud failure naming the registered kinds. */
1857
1975
  getOrThrow(kind) {
1858
1976
  const handler = this.get(kind);
1859
1977
  if (!handler) {
@@ -1863,9 +1981,6 @@ var RfqCorridorRegistry = class {
1863
1981
  }
1864
1982
  return handler;
1865
1983
  }
1866
- has(kind) {
1867
- return this.handlers.has(kind);
1868
- }
1869
1984
  registeredKinds() {
1870
1985
  return [...this.handlers.keys()];
1871
1986
  }
@@ -1965,15 +2080,12 @@ var LightningSendCorridor = {
1965
2080
  kind: "lightning_send",
1966
2081
  project: () => ({}),
1967
2082
  hydrate: (profile) => hydrateHashlock(profile)
1968
- // No `claimSecret`, deliberately: `provisionRefundKey` mints no preimage at
1969
- // all, and deriving one off the refund descriptor would fail the payment
1970
- // hash check — a `hash-mismatch` on a swap that was never broken.
2083
+ // No `claimSecret`: no preimage was minted, and one derived off the refund descriptor would
2084
+ // fail the payment hash check on a swap that was never broken.
1971
2085
  };
1972
2086
  var LightningReceiveCorridor = {
1973
2087
  kind: "lightning_receive",
1974
- // What the manager holds: the amount gate, and its own claim once it lands.
1975
- // `payoutAddress` comes from the request result and never changes, so the
1976
- // caller writes it once and this leaves it alone.
2088
+ // `payoutAddress` is written once by the caller from the request result; left alone here.
1977
2089
  project: (swap) => {
1978
2090
  const receive2 = swap;
1979
2091
  return {
@@ -1994,8 +2106,6 @@ var LightningReceiveCorridor = {
1994
2106
  // We are the claimant here, so the preimage material on the hashlock is
1995
2107
  // ours to use.
1996
2108
  claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
1997
- // The other half of claiming: where it pays. Written once at request time
1998
- // and left alone by `project` above, so this hands back what was stored.
1999
2109
  claimDestination: (profile) => profile.payoutAddress,
2000
2110
  activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
2001
2111
  };
@@ -2013,9 +2123,7 @@ function onchainSendProfile(result) {
2013
2123
  }
2014
2124
  var OnchainSendCorridor = {
2015
2125
  kind: "onchain_send",
2016
- // The L1 keys and the network are only in the request result — nothing on
2017
- // `OnchainSendSwap` carries them — so the caller writes them once. What the
2018
- // manager learns as it drives the swap is the fill and our own claim.
2126
+ // The L1 keys and network are written once by the caller; the manager learns fill and claim.
2019
2127
  project: (swap) => {
2020
2128
  const send = swap;
2021
2129
  return {
@@ -2043,10 +2151,8 @@ var OnchainSendCorridor = {
2043
2151
  }
2044
2152
  const htlc = onchainHtlcScript(
2045
2153
  {
2046
- // From the profile, not the covenant: the lockup commits to
2047
- // `hash160(P)`, and the HTLC needs `sha256(P)`. One P
2048
- // unlocks both legs, but only one of the two hashes of it
2049
- // is recoverable here.
2154
+ // From the profile, not the covenant: the lockup commits to `hash160(P)`, the
2155
+ // HTLC needs `sha256(P)`.
2050
2156
  paymentHash,
2051
2157
  claimKey: import_base5.hex.decode(profile.claimKey),
2052
2158
  refundKey: import_base5.hex.decode(profile.refundKey),
@@ -2074,9 +2180,7 @@ var OnchainSendCorridor = {
2074
2180
  // The trader claims the L1 HTLC with P, so this leg's preimage material is
2075
2181
  // ours.
2076
2182
  claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
2077
- // Our own L1 claim only. `funding` is the SOLVER's fill into the HTLC —
2078
- // not a transaction of ours, so grouping it would claim a row this wallet
2079
- // never made.
2183
+ // Our own L1 claim only: `funding` is the solver's tx, not a row this wallet made.
2080
2184
  activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
2081
2185
  };
2082
2186
  rfqCorridorHandlers.register(LightningSendCorridor);
@@ -2087,7 +2191,7 @@ rfqCorridorHandlers.register(OnchainSendCorridor);
2087
2191
  init_store();
2088
2192
 
2089
2193
  // src/client/assetId.ts
2090
- var import_sdk4 = require("@arkade-os/sdk");
2194
+ var import_sdk5 = require("@arkade-os/sdk");
2091
2195
  var RAILS = ["arkade", "bitcoin", "bolt11", "eip155"];
2092
2196
  var BITCOIN_RAILS = ["arkade", "bitcoin", "bolt11"];
2093
2197
  var BTC_ASSET_PART = "slip44:0";
@@ -2107,10 +2211,8 @@ var REFERENCE_RULE = {
2107
2211
  /** The 68-lowercase-hex identity form; `asset.AssetId` then re-validates it. */
2108
2212
  asset: /^[0-9a-f]{68}$/,
2109
2213
  /**
2110
- * Reserved for §9. Lowercase, never EIP-55: a checksum belongs on an
2111
- * address a human types, and an id here comes out of the alias table or a
2112
- * market card. Mixed case would be two spellings of one asset comparing
2113
- * unequal in a pair string, a record and a cache key.
2214
+ * Reserved for §9. Lowercase, never EIP-55: mixed case would be two spellings of one asset
2215
+ * comparing unequal in a pair string, a record and a cache key.
2114
2216
  */
2115
2217
  erc20: /^0x[0-9a-f]{40}$/
2116
2218
  };
@@ -2118,7 +2220,7 @@ var CHAIN_REFERENCE = /^[-_a-z0-9]{1,32}$/;
2118
2220
  var CHAIN_ID = /^(0|[1-9][0-9]*)$/;
2119
2221
  var ASSET_REFERENCE = /^[-.%a-z0-9]{1,128}$/;
2120
2222
  var isRail = (value) => RAILS.includes(value);
2121
- var isNetworkRef = (value) => Object.hasOwn(import_sdk4.networks, value);
2223
+ var isNetworkRef = (value) => Object.hasOwn(import_sdk5.networks, value);
2122
2224
  var parseAssetId = (value) => {
2123
2225
  if (/[A-Z]/.test(value)) {
2124
2226
  throw new AssetIdError(
@@ -2183,7 +2285,7 @@ var parseAssetId = (value) => {
2183
2285
  }
2184
2286
  if (namespace === ARKADE_ASSET_NAMESPACE) {
2185
2287
  try {
2186
- import_sdk4.asset.AssetId.fromString(assetReference);
2288
+ import_sdk5.asset.AssetId.fromString(assetReference);
2187
2289
  } catch (cause) {
2188
2290
  throw new AssetIdError(
2189
2291
  "invalid_asset_reference",
@@ -2223,14 +2325,13 @@ var sameAsset = (a, b) => {
2223
2325
  return left.reference === right.reference && left.assetNamespace === right.assetNamespace && left.assetReference === right.assetReference;
2224
2326
  };
2225
2327
  var btcOn = (rail, network) => (
2226
- // The checker will not resolve the conditional against an unbound `R`; the
2227
- // assertion is confined to this expression and never reaches a call site.
2328
+ // TS won't resolve the conditional against an unbound `R`; the cast stays in this expression.
2228
2329
  `${rail}:${network}/${BTC_ASSET_PART}`
2229
2330
  );
2230
2331
  var arkadeAsset = (network, id) => `arkade:${network}/${ARKADE_ASSET_NAMESPACE}:${id.toString()}`;
2231
2332
  var issuanceOf = (id) => {
2232
2333
  const { assetNamespace, assetReference } = parseAssetId(id);
2233
- return assetNamespace === ARKADE_ASSET_NAMESPACE ? import_sdk4.asset.AssetId.fromString(assetReference) : void 0;
2334
+ return assetNamespace === ARKADE_ASSET_NAMESPACE ? import_sdk5.asset.AssetId.fromString(assetReference) : void 0;
2234
2335
  };
2235
2336
 
2236
2337
  // src/client/aliases.ts
@@ -2308,10 +2409,10 @@ var QuoteExpired = class extends Error {
2308
2409
  name = "QuoteExpired";
2309
2410
  };
2310
2411
  var MaxFeeExceeded = class extends Error {
2311
- constructor(quoteId, asset6, fee, maxFee) {
2312
- super(`fee ${fee} of ${asset6} exceeds the ${maxFee} ceiling`);
2412
+ constructor(quoteId, asset7, fee, maxFee) {
2413
+ super(`fee ${fee} of ${asset7} exceeds the ${maxFee} ceiling`);
2313
2414
  this.quoteId = quoteId;
2314
- this.asset = asset6;
2415
+ this.asset = asset7;
2315
2416
  this.fee = fee;
2316
2417
  this.maxFee = maxFee;
2317
2418
  }
@@ -2322,11 +2423,11 @@ var MaxFeeExceeded = class extends Error {
2322
2423
  name = "MaxFeeExceeded";
2323
2424
  };
2324
2425
  var InsufficientFunds = class extends Error {
2325
- constructor(asset6, required, available) {
2426
+ constructor(asset7, required, available) {
2326
2427
  super(
2327
- `funding needs ${required} of ${asset6}` + (available === void 0 ? "" : `, wallet holds ${available}`)
2428
+ `funding needs ${required} of ${asset7}` + (available === void 0 ? "" : `, wallet holds ${available}`)
2328
2429
  );
2329
- this.asset = asset6;
2430
+ this.asset = asset7;
2330
2431
  this.required = required;
2331
2432
  this.available = available;
2332
2433
  }
@@ -2364,9 +2465,9 @@ var NotCancellable = class extends Error {
2364
2465
  name = "NotCancellable";
2365
2466
  };
2366
2467
  var InconsistentRoute = class extends Error {
2367
- constructor(asset6, destination) {
2368
- super(`destination ${JSON.stringify(destination)} is not on ${asset6}'s chain`);
2369
- this.asset = asset6;
2468
+ constructor(asset7, destination) {
2469
+ super(`destination ${JSON.stringify(destination)} is not on ${asset7}'s chain`);
2470
+ this.asset = asset7;
2370
2471
  this.destination = destination;
2371
2472
  }
2372
2473
  asset;
@@ -2419,24 +2520,24 @@ function isSwapError(e, name) {
2419
2520
  // src/client/aliases.ts
2420
2521
  var toDiscoveryLeg = (id) => {
2421
2522
  const { rail, assetNamespace, assetReference } = parseAssetId(id);
2422
- const asset6 = `${assetNamespace}:${assetReference}`;
2523
+ const asset7 = `${assetNamespace}:${assetReference}`;
2423
2524
  if (rail === "arkade") {
2424
- if (asset6 === BTC_ASSET_PART)
2525
+ if (asset7 === BTC_ASSET_PART)
2425
2526
  return { corridor: "arkade", assetId: BTC_ASSET_ID, marketId: id };
2426
2527
  if (assetNamespace === ARKADE_ASSET_NAMESPACE) {
2427
2528
  return { corridor: "arkade", assetId: assetReference, marketId: id };
2428
2529
  }
2429
- throw new UnsupportedRoute(`the arkade corridor has no ${asset6}`);
2530
+ throw new UnsupportedRoute(`the arkade corridor has no ${asset7}`);
2430
2531
  }
2431
2532
  if (rail === "bolt11") {
2432
- if (asset6 === BTC_ASSET_PART)
2533
+ if (asset7 === BTC_ASSET_PART)
2433
2534
  return { corridor: "lightning", assetId: BTC_ASSET_ID, marketId: id };
2434
- throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset6}`);
2535
+ throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset7}`);
2435
2536
  }
2436
2537
  if (rail === "bitcoin") {
2437
- if (asset6 === BTC_ASSET_PART)
2538
+ if (asset7 === BTC_ASSET_PART)
2438
2539
  return { corridor: "onchain", assetId: BTC_ASSET_ID, marketId: id };
2439
- throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset6}`);
2540
+ throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset7}`);
2440
2541
  }
2441
2542
  throw new UnsupportedRoute(`no corridor serves ${id}`);
2442
2543
  };
@@ -2468,7 +2569,7 @@ var canonicalAssetId = (input, table) => {
2468
2569
  };
2469
2570
 
2470
2571
  // src/client/corridors/lightning.ts
2471
- var import_sdk7 = require("@arkade-os/sdk");
2572
+ var import_sdk8 = require("@arkade-os/sdk");
2472
2573
  var INVOICE_HRPS = [
2473
2574
  ["lnbcrt", ["regtest"]],
2474
2575
  ["lntbs", ["signet", "mutinynet"]],
@@ -2498,7 +2599,7 @@ var lightningCorridor = Object.assign(
2498
2599
  deps,
2499
2600
  drive: LIGHTNING_DRIVE,
2500
2601
  matches(raw) {
2501
- const invoice = (0, import_sdk7.invoiceTarget)(raw);
2602
+ const invoice = (0, import_sdk8.invoiceTarget)(raw);
2502
2603
  if (invoice === void 0) return void 0;
2503
2604
  const networks2 = networksOfInvoiceHrp(invoice);
2504
2605
  if (networks2 === void 0) {
@@ -2544,11 +2645,11 @@ var lightningCorridor = Object.assign(
2544
2645
  };
2545
2646
  }
2546
2647
  }),
2547
- { target: import_sdk7.invoiceTarget }
2648
+ { target: import_sdk8.invoiceTarget }
2548
2649
  );
2549
2650
 
2550
2651
  // src/client/corridors/onchain.ts
2551
- var import_sdk8 = require("@arkade-os/sdk");
2652
+ var import_sdk9 = require("@arkade-os/sdk");
2552
2653
  var btc2 = __toESM(require("@scure/btc-signer"), 1);
2553
2654
  init_onchainHtlc();
2554
2655
  init_rfq();
@@ -2570,14 +2671,14 @@ var onchainCorridor = Object.assign(
2570
2671
  deps,
2571
2672
  drive: ONCHAIN_DRIVE,
2572
2673
  matches(raw) {
2573
- const target = (0, import_sdk8.btcTarget)(raw);
2674
+ const target = (0, import_sdk9.btcTarget)(raw);
2574
2675
  if (target === void 0) return void 0;
2575
2676
  try {
2576
2677
  btc2.Address(L1_NETWORKS[l1]).decode(target);
2577
2678
  } catch {
2578
2679
  return { refused: `this is not a ${l1} address` };
2579
2680
  }
2580
- const amount = import_sdk8.BIP21.amountSats(raw);
2681
+ const amount = import_sdk9.BIP21.amountSats(raw);
2581
2682
  return {
2582
2683
  claimed: {
2583
2684
  kind: "address",
@@ -2588,7 +2689,7 @@ var onchainCorridor = Object.assign(
2588
2689
  }
2589
2690
  };
2590
2691
  },
2591
- { target: import_sdk8.btcTarget }
2692
+ { target: import_sdk9.btcTarget }
2592
2693
  );
2593
2694
 
2594
2695
  // src/client/outcome.ts
@@ -2615,18 +2716,14 @@ var CORRIDOR_OUTCOME = {
2615
2716
  failed: at("failed")
2616
2717
  },
2617
2718
  solver: {
2618
- // The solver has funded nothing yet: the invoice is shown and unpaid,
2619
- // which is what makes this `open` where the trader's side is `funded`.
2719
+ // The solver has funded nothing yet: the invoice is shown and unpaid.
2620
2720
  pending: at("open"),
2621
2721
  claimable: at("funded"),
2622
2722
  claimed: at("funded"),
2623
2723
  needs_counterparty: at("needs_recovery"),
2624
- // The trader's OWN claim, matched by the hash and not by our txid — so
2625
- // a claim that lands without us still counts.
2724
+ // Matched by the hash, not our txid, so a claim that lands without us counts.
2626
2725
  settled: at("claimed"),
2627
- // The one inversion this whole module exists for: every non-claim leaf
2628
- // of a receive covenant is the solver's, so a lockup spent by one is
2629
- // the trader's incoming payment never arriving.
2726
+ // The inversion: a receive lockup's non-claim leaves are all the solver's.
2630
2727
  refunded: at("lapsed"),
2631
2728
  failed: at("failed")
2632
2729
  }
@@ -2637,8 +2734,7 @@ var OFFER_OUTCOME = {
2637
2734
  cancelling: "cancelling",
2638
2735
  cancelled: "cancelled",
2639
2736
  fulfilled: "filled",
2640
- // A swept deposit: still the trader's money, at a script no offchain spend
2641
- // can reach until it is recovered into a fresh batch.
2737
+ // A swept deposit: still the trader's money, unreachable until recovered into a batch.
2642
2738
  recoverable: "needs_recovery",
2643
2739
  awaiting_fill: "needs_recovery",
2644
2740
  claimable: "needs_recovery",
@@ -2656,10 +2752,8 @@ var ACTIVITY_TOKEN = {
2656
2752
  funding: "pending",
2657
2753
  funded: "pending",
2658
2754
  open: "pending",
2659
- // The drive's in-flight states have no user-visible phase distinct from
2660
- // "pending"; `needs_recovery` is different in kind — the swap is BLOCKED —
2661
- // and collapsing it here is the same deliberate choice v1 made, which the
2662
- // opaque-token design permits because apps map tokens themselves.
2755
+ // `needs_recovery` (BLOCKED) collapses to pending deliberately, as in v1; apps map
2756
+ // tokens themselves.
2663
2757
  needs_recovery: "pending",
2664
2758
  refunding: "pending",
2665
2759
  cancelling: "pending",
@@ -2705,20 +2799,13 @@ var Amount = {
2705
2799
  /**
2706
2800
  * A human decimal into atomic units.
2707
2801
  *
2708
- * `string` only, and no exponent. Accepting a `number` is the whole v1
2709
- * footgun: it makes `100000` ambiguous between sats and whole BTC, and by
2710
- * the time the ambiguity resolves the offer is funded. Exponent form goes
2711
- * for the same reason — a UI never produces `1e-4`, so accepting it only
2712
- * widens what a mistake can look like.
2713
- *
2714
- * Refuses rather than rounds when the input is finer than the asset: a
2715
- * silently truncated amount is a swap for the wrong size, and nothing
2716
- * downstream can tell it was ever a different number. Refuses too when the
2717
- * result would not survive the record boundary, so one law holds in both
2718
- * directions.
2802
+ * `string` only, no exponent: a `number` makes `100000` ambiguous between sats and BTC, and the
2803
+ * ambiguity resolves only after funding. Refuses rather than rounds input finer than the asset
2804
+ * (a truncated amount is a swap for the wrong size), and refuses results that would not survive
2805
+ * the record boundary.
2719
2806
  */
2720
- parse(display, asset6) {
2721
- assertDecimals(asset6.decimals);
2807
+ parse(display, asset7) {
2808
+ assertDecimals(asset7.decimals);
2722
2809
  const parts = SCALED_DECIMAL.exec(display);
2723
2810
  if (!parts) {
2724
2811
  throw new AmountFormatError(
@@ -2727,32 +2814,28 @@ var Amount = {
2727
2814
  );
2728
2815
  }
2729
2816
  const [, whole, fraction = ""] = parts;
2730
- if (fraction.length > asset6.decimals) {
2817
+ if (fraction.length > asset7.decimals) {
2731
2818
  throw new AmountFormatError(
2732
2819
  "too_precise",
2733
- `${display} has more precision than ${asset6.decimals} decimals allow`
2820
+ `${display} has more precision than ${asset7.decimals} decimals allow`
2734
2821
  );
2735
2822
  }
2736
2823
  if (whole.length + fraction.length > MAX_SIGNIFICANT_DIGITS) {
2737
2824
  throw new AmountFormatError("too_large", `${display} has too many digits`);
2738
2825
  }
2739
- const value = (0, import_solver_discovery3.toAtomic)(display, asset6.decimals);
2740
- assertRepresentable(value, `${display} at ${asset6.decimals} decimals`);
2826
+ const value = (0, import_solver_discovery3.toAtomic)(display, asset7.decimals);
2827
+ assertRepresentable(value, `${display} at ${asset7.decimals} decimals`);
2741
2828
  return value;
2742
2829
  },
2743
- /**
2744
- * Atomic units into a human decimal, trailing zeros trimmed.
2745
- *
2746
- * Refuses a negative: every amount on this surface is an obligation, and a
2747
- * negative one is a defect upstream rather than a number to render.
2748
- */
2749
- format(value, asset6) {
2750
- assertDecimals(asset6.decimals);
2830
+ /** Atomic units into a human decimal, trailing zeros trimmed. Refuses a negative: every amount
2831
+ * here is an obligation, so a negative one is an upstream defect. */
2832
+ format(value, asset7) {
2833
+ assertDecimals(asset7.decimals);
2751
2834
  if (value < 0n) {
2752
2835
  throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
2753
2836
  }
2754
2837
  assertRepresentable(value, `${value}`);
2755
- return (0, import_solver_discovery3.fromAtomic)(value, asset6.decimals);
2838
+ return (0, import_solver_discovery3.fromAtomic)(value, asset7.decimals);
2756
2839
  }
2757
2840
  };
2758
2841
  var toAtomicDecimal = (value) => {
@@ -2805,8 +2888,6 @@ var decodeRfqAmount = (raw, field) => {
2805
2888
  throw new AmountEncodingUnsupported(
2806
2889
  field,
2807
2890
  `${raw}`,
2808
- // Past 2^53 the number arrived already rounded — there is no
2809
- // "narrow carefully" branch, only a wrong amount.
2810
2891
  "a JSON number amount is only readable as a non-negative safe integer"
2811
2892
  );
2812
2893
  }
@@ -2834,7 +2915,10 @@ var assetSwapIdOf = (family, quoteId) => `${family}:${quoteId}`;
2834
2915
  var OFFER_SWAP_ID_PREFIX = "offer:";
2835
2916
  var RFQ_SWAP_ID_PREFIX = "rfq:";
2836
2917
  var familyOfSwapId = (swapId) => swapId.startsWith(OFFER_SWAP_ID_PREFIX) ? "offer" : swapId.startsWith(RFQ_SWAP_ID_PREFIX) ? "rfq" : void 0;
2837
- var quoteIdOfSwapId = (swapId) => swapId.startsWith(OFFER_SWAP_ID_PREFIX) ? swapId.slice(OFFER_SWAP_ID_PREFIX.length) : swapId.startsWith(RFQ_SWAP_ID_PREFIX) ? swapId.slice(RFQ_SWAP_ID_PREFIX.length) : swapId;
2918
+ var quoteIdOfSwapId = (swapId) => {
2919
+ const family = familyOfSwapId(swapId);
2920
+ return family === void 0 ? swapId : swapId.slice(`${family}:`.length);
2921
+ };
2838
2922
  var recordEndpoint = (endpoint2) => ({
2839
2923
  corridor: endpoint2.corridor,
2840
2924
  asset: endpoint2.asset,
@@ -2917,8 +3001,7 @@ var swapOf = (record, outcome) => ({
2917
3001
  fee: legOf(record.fee),
2918
3002
  market: record.market,
2919
3003
  ...record.solver === void 0 ? {} : { solver: record.solver },
2920
- ...record.family === "rfq" ? { lock: record.lock } : {},
2921
- ...record.family === "rfq" ? { refundLocktime: record.refundLocktime } : {},
3004
+ ...record.family === "rfq" ? { lock: record.lock, refundLocktime: record.refundLocktime } : {},
2922
3005
  ...record.artifact === void 0 ? {} : { artifact: artifactOf(record.artifact) },
2923
3006
  expiresAt: record.expiresAt,
2924
3007
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
@@ -3002,15 +3085,7 @@ var marketSourceOf = (market) => market.kind === "card" ? market.source : void 0
3002
3085
  var assertFundable2 = async (wallet, quote) => {
3003
3086
  const give = quote.give;
3004
3087
  const balance = await wallet.getBalance();
3005
- if (assetPartOf(give.asset) === BTC_ASSET_PART) {
3006
- const available2 = BigInt(balance.available);
3007
- if (available2 < give.amount) {
3008
- throw new InsufficientFunds(give.asset, give.amount, available2);
3009
- }
3010
- return;
3011
- }
3012
- const held = balance.availableAssets.find((a) => give.asset.endsWith(a.assetId));
3013
- const available = held?.amount ?? 0n;
3088
+ const available = assetPartOf(give.asset) === BTC_ASSET_PART ? BigInt(balance.available) : balance.availableAssets.find((a) => give.asset.endsWith(a.assetId))?.amount ?? 0n;
3014
3089
  if (available < give.amount) {
3015
3090
  throw new InsufficientFunds(give.asset, give.amount, available);
3016
3091
  }
@@ -3039,7 +3114,7 @@ var corridorRecord = (quote, preparation, now) => {
3039
3114
  ...commonOf(quote, now),
3040
3115
  family: "rfq",
3041
3116
  state: "pending",
3042
- kind: kindOf(preparation),
3117
+ kind: KIND_OF[preparation.route],
3043
3118
  rfqId: preparation.rfqId,
3044
3119
  lockupAddress: preparation.lockup.address,
3045
3120
  lockupPkScript: import_base8.hex.encode(preparation.lockup.pkScript),
@@ -3048,15 +3123,10 @@ var corridorRecord = (quote, preparation, now) => {
3048
3123
  profile: profileOf(preparation, quote.lock.hash)
3049
3124
  };
3050
3125
  };
3051
- var kindOf = (preparation) => {
3052
- switch (preparation.route) {
3053
- case "arkade->lightning":
3054
- return "lightning_send";
3055
- case "lightning->arkade":
3056
- return "lightning_receive";
3057
- case "arkade->onchain":
3058
- return "onchain_send";
3059
- }
3126
+ var KIND_OF = {
3127
+ "arkade->lightning": "lightning_send",
3128
+ "lightning->arkade": "lightning_receive",
3129
+ "arkade->onchain": "onchain_send"
3060
3130
  };
3061
3131
  var profileOf = (preparation, paymentHash) => {
3062
3132
  const secrets = rfqSecretsProfile(preparation.secrets, paymentHash);
@@ -3113,7 +3183,7 @@ var acceptQuoteBody = async (input) => {
3113
3183
  }
3114
3184
  const funds = fundsFromWallet(quote.route);
3115
3185
  if (funds) await assertFundable2(wallet, quote);
3116
- const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
3186
+ const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : preparation.route === "arkade->arkade" ? await registeredAssetRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
3117
3187
  await repository.saveSwapRecord(record);
3118
3188
  if (!funds) return answer(record);
3119
3189
  return answer(await fundAndStamp({ wallet, now }, record, repository));
@@ -3126,7 +3196,7 @@ var registeredOfferRecord = async (input, preparation) => {
3126
3196
  const offer = await createOffer(wallet, {
3127
3197
  // Keyed on the receive side: the covenant binds what the fill delivers.
3128
3198
  wantAmount: plan.receive.atomic,
3129
- ...receiveIsBtc ? { offerAsset: import_sdk9.asset.AssetId.fromString(plan.deposit.asset.id) } : { wantAsset: import_sdk9.asset.AssetId.fromString(plan.receive.asset.id) },
3199
+ ...receiveIsBtc ? { offerAsset: import_sdk10.asset.AssetId.fromString(plan.deposit.asset.id) } : { wantAsset: import_sdk10.asset.AssetId.fromString(plan.receive.asset.id) },
3130
3200
  emulatorPubkey: arkade2.emulatorPubkey
3131
3201
  });
3132
3202
  return {
@@ -3138,6 +3208,18 @@ var registeredOfferRecord = async (input, preparation) => {
3138
3208
  swapPkScript: import_base8.hex.encode(offer.swapPkScript)
3139
3209
  };
3140
3210
  };
3211
+ var registeredAssetRecord = async (input, preparation) => {
3212
+ await registerDerivedOffer(input.wallet, preparation.offer);
3213
+ return {
3214
+ ...commonOf(input.quote, input.now),
3215
+ family: "offer",
3216
+ status: "pending",
3217
+ offerHex: preparation.offer.offerHex,
3218
+ swapAddress: preparation.offer.address,
3219
+ swapPkScript: import_base8.hex.encode(preparation.offer.swapPkScript),
3220
+ ...preparation.carrierSats === void 0 ? {} : { carrierSats: preparation.carrierSats.toString() }
3221
+ };
3222
+ };
3141
3223
  var registeredCorridorRecord = async (input, preparation) => {
3142
3224
  const contracts = await input.wallet.getContractManager();
3143
3225
  await registerLockupContract(contracts, preparation.lockup.script, preparation.lockup.address);
@@ -3163,9 +3245,10 @@ var fund = async (input, record) => {
3163
3245
  const depositIsBtc = assetPartOf(record.route.give.asset) === BTC_ASSET_PART;
3164
3246
  return wallet.send({
3165
3247
  address: record.swapAddress,
3166
- // An asset deposit rides the SDK's dust-sat carrier, so the sats
3167
- // amount is left to the default rather than set here.
3248
+ // An asset deposit rides a dust-sat carrier: the solver's published one when the record
3249
+ // names it (the fill is priced against it), else the SDK default.
3168
3250
  ...depositIsBtc ? { amount: toSafeNumber(amount, "give.amount") } : {
3251
+ ...record.carrierSats === void 0 ? {} : { amount: toSafeNumber(BigInt(record.carrierSats), "carrierSats") },
3169
3252
  assets: [
3170
3253
  { assetId: toDiscoveryLeg(record.route.give.asset).assetId, amount }
3171
3254
  ]
@@ -3189,7 +3272,7 @@ var reconcileFunding = async (input, record) => {
3189
3272
  const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
3190
3273
  const expected = BigInt(record.give.amount);
3191
3274
  const reader = await input.wallet.getArkadeReader();
3192
- const vtxos = await (0, import_sdk9.getAllNormalizedVtxos)(reader, [script]);
3275
+ const vtxos = await (0, import_sdk10.getAllNormalizedVtxos)(reader, [script]);
3193
3276
  const deposit = vtxos.find((vtxo) => depositMatches(vtxo, record, expected));
3194
3277
  return deposit?.txid;
3195
3278
  };
@@ -3217,9 +3300,9 @@ var LEGACY_CORRIDORS = {
3217
3300
  };
3218
3301
  var assetOf = (market, side) => side === "base" ? market.base_asset : market.quote_asset;
3219
3302
  var marketAssetId = (market, side) => {
3220
- const asset6 = assetOf(market, side);
3221
- if (typeof asset6?.caip19_id === "string") return asset6.caip19_id;
3222
- return typeof asset6?.id === "string" ? asset6.id : void 0;
3303
+ const asset7 = assetOf(market, side);
3304
+ if (typeof asset7?.caip19_id === "string") return asset7.caip19_id;
3305
+ return typeof asset7?.id === "string" ? asset7.id : void 0;
3223
3306
  };
3224
3307
  var chainNamespaceOf = (id) => {
3225
3308
  if (id === void 0) return void 0;
@@ -3291,11 +3374,13 @@ var scopedToRail = (table, rail) => ({
3291
3374
 
3292
3375
  // src/client/client.ts
3293
3376
  var import_base19 = require("@scure/base");
3377
+ init_repository();
3294
3378
 
3295
3379
  // src/refund.ts
3296
3380
  var import_base9 = require("@scure/base");
3297
3381
  var import_sha24 = require("@noble/hashes/sha2.js");
3298
- var import_sdk10 = require("@arkade-os/sdk");
3382
+ var import_sdk11 = require("@arkade-os/sdk");
3383
+ init_onchainHtlc();
3299
3384
  init_rfq();
3300
3385
  var walletOperator = (wallet) => {
3301
3386
  let broadcaster;
@@ -3312,15 +3397,8 @@ var LockupNeedsRecoveryError = class extends Error {
3312
3397
  /** `txid:vout` for each output that must be recovered first. */
3313
3398
  outpoints;
3314
3399
  /**
3315
- * The contract's `refundLocktime`. Recovering before this matures is the
3316
- * hazard described above: `recoverVtxos()` sweeps EVERY recoverable output
3317
- * into one settlement with no CLTV awareness, so an early attempt can fail
3318
- * the whole batch — including unrelated outputs that were otherwise fine.
3319
- *
3320
- * Exposed as a value, not only inside the message, so a caller can skip
3321
- * pre-CLTV recoverable outputs without parsing prose. Seconds-based
3322
- * locktimes mature against the chain tip's timestamp rather than wall
3323
- * clock, so treat this as a floor to wait past, not an exact alarm.
3400
+ * The contract's `refundLocktime`; do not recover before it (see above). Seconds-based
3401
+ * locktimes mature against chain time, not wall clock, so treat this as a floor.
3324
3402
  */
3325
3403
  recoverableAfter;
3326
3404
  constructor(outpoints, recoverableAfter) {
@@ -3339,7 +3417,7 @@ async function findLockupVtxos(contracts, swapPkScript) {
3339
3417
  const out = [];
3340
3418
  for (const vtxo of row?.vtxos ?? []) {
3341
3419
  if (vtxo.isUnrolled) continue;
3342
- if ((0, import_sdk10.hasTerminalSpend)(vtxo)) continue;
3420
+ if ((0, import_sdk11.isVtxoSpent)(vtxo)) continue;
3343
3421
  const key = `${vtxo.txid}:${vtxo.vout}`;
3344
3422
  if (seen.has(key)) continue;
3345
3423
  seen.add(key);
@@ -3347,8 +3425,6 @@ async function findLockupVtxos(contracts, swapPkScript) {
3347
3425
  txid: vtxo.txid,
3348
3426
  vout: vtxo.vout,
3349
3427
  value: Number(vtxo.value),
3350
- // The manager's canonical `isSwept` fact; no coercion, because the
3351
- // normalized row guarantees a boolean.
3352
3428
  recoverable: vtxo.isSwept
3353
3429
  });
3354
3430
  }
@@ -3356,14 +3432,14 @@ async function findLockupVtxos(contracts, swapPkScript) {
3356
3432
  }
3357
3433
  var hashesTo = (candidate, paymentHash) => import_base9.hex.encode((0, import_sha24.sha256)(candidate)) === paymentHash;
3358
3434
  var candidateWitnessItems = (tx, inputIndex) => [
3359
- ...(0, import_sdk10.getArkPsbtFields)(tx, inputIndex, import_sdk10.ConditionWitness).flat(),
3435
+ ...(0, import_sdk11.getArkPsbtFields)(tx, inputIndex, import_sdk11.ConditionWitness).flat(),
3360
3436
  ...tx.getInput(inputIndex).finalScriptWitness ?? []
3361
3437
  ];
3362
3438
  async function readLockupFate(indexer, input) {
3363
3439
  const { vtxos } = await indexer.getVtxos({ scripts: [import_base9.hex.encode(input.swapPkScript)] });
3364
3440
  const all = vtxos ?? [];
3365
3441
  if (all.length === 0) return { fate: "unknown" };
3366
- const exited = all.filter((vtxo) => vtxo.isUnrolled && !(0, import_sdk10.hasTerminalSpend)(vtxo));
3442
+ const exited = all.filter((vtxo) => vtxo.isUnrolled && !(0, import_sdk11.isVtxoSpent)(vtxo));
3367
3443
  if (exited.length > 0) {
3368
3444
  return {
3369
3445
  fate: "exited",
@@ -3373,7 +3449,7 @@ async function readLockupFate(indexer, input) {
3373
3449
  const spentBy = /* @__PURE__ */ new Map();
3374
3450
  let everySpendNamed = true;
3375
3451
  for (const vtxo of all) {
3376
- if (!(0, import_sdk10.hasTerminalSpend)(vtxo)) return { fate: "open" };
3452
+ if (!(0, import_sdk11.isVtxoSpent)(vtxo)) return { fate: "open" };
3377
3453
  if (vtxo.spentBy)
3378
3454
  spentBy.set(vtxo.spentBy, {
3379
3455
  checkpointTxid: vtxo.spentBy,
@@ -3387,7 +3463,7 @@ async function readLockupFate(indexer, input) {
3387
3463
  for (const raw of txs) {
3388
3464
  let tx;
3389
3465
  try {
3390
- tx = import_sdk10.Transaction.fromPSBT(import_base9.base64.decode(raw));
3466
+ tx = import_sdk11.Transaction.fromPSBT(import_base9.base64.decode(raw));
3391
3467
  } catch {
3392
3468
  continue;
3393
3469
  }
@@ -3406,49 +3482,58 @@ async function readLockupFate(indexer, input) {
3406
3482
  }
3407
3483
  return everySpendNamed && observed.size === spentBy.size ? { fate: "returned", spends } : { fate: "unknown" };
3408
3484
  }
3409
- async function pushRefundWithoutReceiver(operator, input) {
3410
- if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
3411
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
3485
+ var assertNoneSwept = (vtxos, contract) => {
3486
+ const swept = vtxos.filter((vtxo) => vtxo.recoverable);
3412
3487
  if (swept.length > 0) {
3413
3488
  throw new LockupNeedsRecoveryError(
3414
3489
  swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
3415
- input.contract.options.refundLocktime
3490
+ contract.options.refundLocktime
3416
3491
  );
3417
3492
  }
3493
+ };
3494
+ var operatorUnrollScript = async (operator, network) => {
3495
+ const info = await operator.getInfo();
3496
+ return (0, import_sdk11.assertValidServerUnrollScript)(
3497
+ info.checkpointTapscript,
3498
+ (0, import_sdk11.resolveCheckpointExitDelayPolicy)(network ?? (0, import_sdk11.networkFromArkadeInfo)(info), {
3499
+ advertisedForfeitPubkey: (0, import_sdk11.toXOnly)(import_base9.hex.decode(info.forfeitPubkey), "forfeit key")
3500
+ })
3501
+ );
3502
+ };
3503
+ var lockupInputs = (vtxos, contract, leaf) => {
3504
+ const tapTree = contract.encode();
3505
+ return vtxos.map((vtxo) => ({
3506
+ txid: vtxo.txid,
3507
+ vout: vtxo.vout,
3508
+ value: vtxo.value,
3509
+ tapLeafScript: leaf,
3510
+ tapTree
3511
+ }));
3512
+ };
3513
+ async function pushRefundWithoutReceiver(operator, input) {
3514
+ if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
3515
+ assertNoneSwept(input.vtxos, input.contract);
3418
3516
  const refundPkScript = input.refundPkScript ?? input.contract.options.nonInteractiveParameters?.senderPkScript;
3419
3517
  if (!refundPkScript) {
3420
3518
  throw new Error(
3421
3519
  "no refund destination: the contract carries no emulator covenant suite, so pass refundPkScript explicitly"
3422
3520
  );
3423
3521
  }
3424
- const info = await operator.getInfo();
3425
- let operatorUnrollScript;
3426
- try {
3427
- operatorUnrollScript = import_sdk10.CSVMultisigTapscript.decode(import_base9.hex.decode(info.checkpointTapscript));
3428
- } catch {
3429
- throw new Error("invalid checkpointTapscript from the operator");
3430
- }
3522
+ const serverUnrollScript = await operatorUnrollScript(operator, input.network);
3431
3523
  const leaf = input.contract.refundWithoutReceiver();
3432
- const tapTree = input.contract.encode();
3433
3524
  const amount = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
3434
- const { arkTx: tx, checkpoints } = (0, import_sdk10.buildOffchainTx)(
3435
- input.vtxos.map((vtxo) => ({
3436
- txid: vtxo.txid,
3437
- vout: vtxo.vout,
3438
- value: vtxo.value,
3439
- tapLeafScript: leaf,
3440
- tapTree
3441
- })),
3525
+ const { arkTx: tx, checkpoints } = (0, import_sdk11.buildOffchainTx)(
3526
+ lockupInputs(input.vtxos, input.contract, leaf),
3442
3527
  [{ script: refundPkScript, amount: BigInt(amount) }],
3443
- operatorUnrollScript
3528
+ serverUnrollScript
3444
3529
  );
3445
3530
  const signedTx = await input.sender.sign(tx);
3446
3531
  const submitted = await operator.submitTx(
3447
3532
  import_base9.base64.encode(signedTx.toPSBT()),
3448
3533
  checkpoints.map((c) => import_base9.base64.encode(c.toPSBT()))
3449
3534
  );
3450
- (0, import_sdk10.assertSubmittedArkTxid)(submitted, signedTx, "refundWithoutReceiver");
3451
- const matched = (0, import_sdk10.matchServerCheckpoints)(
3535
+ (0, import_sdk11.assertSubmittedArkTxid)(submitted, signedTx, "refundWithoutReceiver");
3536
+ const matched = (0, import_sdk11.matchServerCheckpoints)(
3452
3537
  submitted.signedCheckpointTxs,
3453
3538
  checkpoints,
3454
3539
  "refundWithoutReceiver"
@@ -3464,10 +3549,10 @@ async function pushRefundWithoutReceiver(operator, input) {
3464
3549
  var REFUND_MTP_LAG_SECONDS = 2 * 60 * 60;
3465
3550
 
3466
3551
  // src/client/corridors/registry.ts
3467
- var import_sdk14 = require("@arkade-os/sdk");
3552
+ var import_sdk15 = require("@arkade-os/sdk");
3468
3553
 
3469
3554
  // src/client/corridors/arkade.ts
3470
- var import_sdk11 = require("@arkade-os/sdk");
3555
+ var import_sdk12 = require("@arkade-os/sdk");
3471
3556
  var ARKADE_DRIVE = {};
3472
3557
  var messageOf = (error) => error instanceof Error ? error.message : String(error);
3473
3558
  var arkadeCorridor = Object.assign(
@@ -3476,11 +3561,11 @@ var arkadeCorridor = Object.assign(
3476
3561
  deps,
3477
3562
  drive: ARKADE_DRIVE,
3478
3563
  matches(raw) {
3479
- const target = (0, import_sdk11.arkTarget)(raw);
3564
+ const target = (0, import_sdk12.arkTarget)(raw);
3480
3565
  if (target === void 0) return void 0;
3481
3566
  try {
3482
- const address = import_sdk11.ArkAddress.decode(target);
3483
- (0, import_sdk11.assertRecipientArkadeAddress)(target, address, {
3567
+ const address = import_sdk12.ArkAddress.decode(target);
3568
+ (0, import_sdk12.assertRecipientArkadeAddress)(target, address, {
3484
3569
  hrp: deps.network.hrp,
3485
3570
  signerSet: deps.signerSet
3486
3571
  });
@@ -3490,11 +3575,11 @@ var arkadeCorridor = Object.assign(
3490
3575
  return { claimed: { kind: "address", address: target } };
3491
3576
  }
3492
3577
  }),
3493
- { target: import_sdk11.arkTarget }
3578
+ { target: import_sdk12.arkTarget }
3494
3579
  );
3495
3580
 
3496
3581
  // src/client/corridors/deps.ts
3497
- var import_sdk13 = require("@arkade-os/sdk");
3582
+ var import_sdk14 = require("@arkade-os/sdk");
3498
3583
  init_onchainHtlc();
3499
3584
  init_rfq();
3500
3585
 
@@ -3504,7 +3589,6 @@ var DEFAULT_INVOICE_EXPIRY_SECONDS = 3600;
3504
3589
  var valueOf = (decoded, name) => decoded.sections.find(
3505
3590
  (section) => section.name === name
3506
3591
  )?.value;
3507
- var PAYMENT_HASH2 = /^[0-9a-f]{64}$/;
3508
3592
  var decodeBolt11 = (invoice) => {
3509
3593
  const decoded = import_light_bolt11_decoder.default.decode(invoice);
3510
3594
  const timestamp = valueOf(decoded, "timestamp");
@@ -3514,7 +3598,7 @@ var decodeBolt11 = (invoice) => {
3514
3598
  const expiry = valueOf(decoded, "expiry");
3515
3599
  const expiresAt = timestamp + (typeof expiry === "number" ? expiry : DEFAULT_INVOICE_EXPIRY_SECONDS);
3516
3600
  const paymentHash = valueOf(decoded, "payment_hash");
3517
- if (typeof paymentHash !== "string" || !PAYMENT_HASH2.test(paymentHash)) {
3601
+ if (typeof paymentHash !== "string" || !PAYMENT_HASH.test(paymentHash)) {
3518
3602
  throw new Error("bolt11 invoice carries no payment hash");
3519
3603
  }
3520
3604
  const millisats = valueOf(decoded, "amount");
@@ -3528,7 +3612,7 @@ var decodeBolt11 = (invoice) => {
3528
3612
  // src/client/corridors/chainSource.ts
3529
3613
  var import_base10 = require("@scure/base");
3530
3614
  var btc3 = __toESM(require("@scure/btc-signer"), 1);
3531
- var import_sdk12 = require("@arkade-os/sdk");
3615
+ var import_sdk13 = require("@arkade-os/sdk");
3532
3616
  var addressOfScript = (script, network) => btc3.Address(network).encode(btc3.OutScript.decode(script));
3533
3617
  var chainSourceOver = (backend, network) => {
3534
3618
  const spenderFromVins = async (txid, vout, pkScript) => {
@@ -3555,11 +3639,8 @@ var chainSourceOver = (backend, network) => {
3555
3639
  return coins.map((coin) => ({
3556
3640
  txid: coin.txid,
3557
3641
  vout: coin.vout,
3558
- // `Coin.value` is `number` sats; the HTLC's is `bigint`.
3559
3642
  amount: BigInt(coin.value),
3560
- // `Coin` carries a height, never a depth, so the tip is the
3561
- // second half of the answer. A confirmed coin is one deep, not
3562
- // zero — the block it landed in counts.
3643
+ // A confirmed coin is one deep, not zero: its own block counts.
3563
3644
  confirmations: coin.status.confirmed && coin.status.block_height !== void 0 ? Math.max(0, tip.height - coin.status.block_height + 1) : 0
3564
3645
  }));
3565
3646
  },
@@ -3593,7 +3674,7 @@ var esploraTip = async (esploraUrl, fetchImpl) => {
3593
3674
  };
3594
3675
  var esploraChainSource = (input) => chainSourceOver(
3595
3676
  {
3596
- provider: new import_sdk12.EsploraProvider(input.esploraUrl),
3677
+ provider: new import_sdk13.EsploraProvider(input.esploraUrl),
3597
3678
  tip: () => esploraTip(input.esploraUrl, input.fetchImpl)
3598
3679
  },
3599
3680
  input.network
@@ -3611,12 +3692,18 @@ var refusedIfNull = (value, corridor, dep) => {
3611
3692
  if (value === null) throw new MissingCorridorDep(corridor, dep);
3612
3693
  return value;
3613
3694
  };
3695
+ var refusedIfMalformed = (value, dep) => {
3696
+ if (value !== void 0 && value !== null && !(Number.isFinite(value) && value > 0)) {
3697
+ throw new MissingCorridorDep("onchain", dep);
3698
+ }
3699
+ return value;
3700
+ };
3614
3701
  var emulatorPubkeyFor = (base) => {
3615
3702
  if (base.emulatorPubkey !== void 0) {
3616
- return (0, import_sdk13.resolveEmulatorPubkey)(base.network, base.emulatorPubkey);
3703
+ return (0, import_sdk14.resolveEmulatorPubkey)(base.network, base.emulatorPubkey);
3617
3704
  }
3618
3705
  try {
3619
- return (0, import_sdk13.defaultEmulatorPubkey)(base.network);
3706
+ return (0, import_sdk14.defaultEmulatorPubkey)(base.network);
3620
3707
  } catch {
3621
3708
  throw new MissingCorridorDep(
3622
3709
  "arkade",
@@ -3652,26 +3739,20 @@ function resolveCorridorDeps(corridor, overrides, base) {
3652
3739
  case "onchain": {
3653
3740
  const chain = refusedIfNull(overrides?.onchain?.chain, "onchain", "chain source");
3654
3741
  const claim = refusedIfNull(overrides?.onchain?.claim, "onchain", "L1 claim callback");
3655
- const feeRateOverride = overrides?.onchain?.claimFeeRateSatVb;
3656
- if (feeRateOverride !== void 0 && feeRateOverride !== null && !(Number.isFinite(feeRateOverride) && feeRateOverride > 0)) {
3657
- throw new MissingCorridorDep("onchain", "L1 claim fee rate");
3658
- }
3742
+ const feeRateOverride = refusedIfMalformed(
3743
+ overrides?.onchain?.claimFeeRateSatVb,
3744
+ "L1 claim fee rate"
3745
+ );
3659
3746
  const claimFeeRateSatVb = feeRateOverride === null ? void 0 : feeRateOverride ?? ONCHAIN_CLAIM_FEE_RATE_SATVB[base.networkName];
3660
- const vsizeOverride = overrides?.onchain?.claimVsize;
3661
- if (vsizeOverride !== void 0 && vsizeOverride !== null && !(Number.isFinite(vsizeOverride) && vsizeOverride > 0)) {
3662
- throw new MissingCorridorDep("onchain", "L1 claim vsize");
3663
- }
3664
- const claimVsize = vsizeOverride === null ? ONCHAIN_CLAIM_VSIZE : vsizeOverride ?? ONCHAIN_CLAIM_VSIZE;
3747
+ const claimVsize = refusedIfMalformed(overrides?.onchain?.claimVsize, "L1 claim vsize") ?? ONCHAIN_CLAIM_VSIZE;
3665
3748
  return {
3666
3749
  networkName: base.networkName,
3667
3750
  chain: esploraChainSource({
3668
- esploraUrl: chain?.esploraUrl ?? import_sdk13.ESPLORA_URL[base.networkName],
3751
+ esploraUrl: chain?.esploraUrl ?? import_sdk14.ESPLORA_URL[base.networkName],
3669
3752
  network: L1_NETWORKS[l1NetworkFromArk(base.networkName)],
3670
3753
  fetchImpl: base.fetchImpl
3671
3754
  }),
3672
3755
  ...claim === void 0 ? {} : { claim },
3673
- // Absent-on-an-unknown-network and explicitly-off read the
3674
- // same: no default claim path, manual mode.
3675
3756
  ...claimFeeRateSatVb === void 0 ? {} : { claimFeeRateSatVb },
3676
3757
  claimVsize
3677
3758
  };
@@ -3696,8 +3777,8 @@ var resolveCorridorBase = async (input) => {
3696
3777
  wallet: input.wallet,
3697
3778
  operator: input.operator,
3698
3779
  networkName,
3699
- network: (0, import_sdk13.getNetwork)(networkName),
3700
- signerSet: (0, import_sdk13.signerSetFromInfo)(info),
3780
+ network: (0, import_sdk14.getNetwork)(networkName),
3781
+ signerSet: (0, import_sdk14.signerSetFromInfo)(info),
3701
3782
  emulatorPubkey: input.emulatorPubkey,
3702
3783
  fetchImpl: input.fetchImpl,
3703
3784
  repository: input.repository
@@ -3727,7 +3808,7 @@ var corridorSet = (base, overrides) => {
3727
3808
  (corridor) => CORRIDOR_FACTORIES[corridor].target(raw) !== void 0
3728
3809
  );
3729
3810
  if (owners.length === 0) {
3730
- if ((0, import_sdk14.isLnurl)(raw)) return void 0;
3811
+ if ((0, import_sdk15.isLnurl)(raw)) return void 0;
3731
3812
  throw new AmbiguousDestination(raw, "no corridor recognises this destination");
3732
3813
  }
3733
3814
  const claims = [];
@@ -3755,7 +3836,7 @@ var import_solver_discovery6 = require("@arkade-os/solver-discovery");
3755
3836
 
3756
3837
  // src/markets.ts
3757
3838
  var import_solver_discovery5 = require("@arkade-os/solver-discovery");
3758
- var import_sdk15 = require("@arkade-os/sdk");
3839
+ var import_sdk16 = require("@arkade-os/sdk");
3759
3840
  init_store();
3760
3841
  var QUOTE_OPTIONS = { safetyBps: 0 };
3761
3842
  var makeCachedFeedFetch = (ttlMs = 3e4, fetchImpl = fetch) => {
@@ -3875,8 +3956,7 @@ var discoveryIndex = (input) => {
3875
3956
  markets: cached.markets,
3876
3957
  ref: {
3877
3958
  fetchedAt: cached.fetchedAt,
3878
- // The cards were read back out of local storage, whatever their
3879
- // age: nothing here can attest that a registry ever served them.
3959
+ // Whatever its age: nothing attests a registry ever served these cards.
3880
3960
  live: false,
3881
3961
  source: "cache",
3882
3962
  registry: url
@@ -3937,13 +4017,13 @@ var discoveryIndex = (input) => {
3937
4017
 
3938
4018
  // src/client/cancel.ts
3939
4019
  var import_base12 = require("@scure/base");
3940
- var import_sdk18 = require("@arkade-os/sdk");
4020
+ var import_sdk19 = require("@arkade-os/sdk");
3941
4021
  init_coverage();
3942
4022
  init_offer();
3943
4023
 
3944
4024
  // src/restore.ts
3945
4025
  var import_base11 = require("@scure/base");
3946
- var import_sdk16 = require("@arkade-os/sdk");
4026
+ var import_sdk17 = require("@arkade-os/sdk");
3947
4027
  init_offer();
3948
4028
  init_store();
3949
4029
  var TXS_PER_REQUEST = 50;
@@ -3961,7 +4041,7 @@ async function fetchParsedTxs(indexer, txids) {
3961
4041
  if (result.status !== "fulfilled") continue;
3962
4042
  for (const psbt of result.value) {
3963
4043
  try {
3964
- const parsed = import_sdk16.Transaction.fromPSBT(import_base11.base64.decode(psbt));
4044
+ const parsed = import_sdk17.Transaction.fromPSBT(import_base11.base64.decode(psbt));
3965
4045
  parsedByTxid.set(parsed.id, parsed);
3966
4046
  } catch {
3967
4047
  }
@@ -3978,8 +4058,7 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
3978
4058
  const script = offerContract(offer, operatorPubkey);
3979
4059
  if (import_base11.hex.encode(script.pkScript) !== import_base11.hex.encode(offer.swapPkScript)) return "indeterminate";
3980
4060
  leaves = {
3981
- // both routes that hand the deposit back; `exit` is absent on an
3982
- // offer that carries no exit closure, and drops out here
4061
+ // `exit` is absent on an offer with no exit closure, and drops out here
3983
4062
  returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
3984
4063
  fulfill: script.functionByName("fulfill")?.leafScript
3985
4064
  };
@@ -3991,7 +4070,7 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
3991
4070
  if (!input.txid || input.index !== deposit.vout) continue;
3992
4071
  if (import_base11.hex.encode(input.txid) !== deposit.txid) continue;
3993
4072
  for (const leaf of input.tapLeafScript ?? []) {
3994
- const spent = import_base11.hex.encode((0, import_sdk16.scriptFromTapLeafScript)(leaf));
4073
+ const spent = import_base11.hex.encode((0, import_sdk17.scriptFromTapLeafScript)(leaf));
3995
4074
  if (leaves.returned.some((back) => spent === import_base11.hex.encode(back))) return "cancelled";
3996
4075
  if (leaves.fulfill && spent === import_base11.hex.encode(leaves.fulfill)) return "fulfilled";
3997
4076
  }
@@ -4039,7 +4118,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
4039
4118
  if (!fundingTx) continue;
4040
4119
  fetchedTxids.push(txid);
4041
4120
  try {
4042
- const packet = import_sdk16.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
4121
+ const packet = import_sdk17.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
4043
4122
  if (!packet) continue;
4044
4123
  const payload = packet.serialize();
4045
4124
  found.push({
@@ -4135,17 +4214,19 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
4135
4214
  spentTxid,
4136
4215
  status,
4137
4216
  createdAt: fundingTx.createdAt ? fundingTx.createdAt * 1e3 : vtxo.createdAt.getTime(),
4138
- // the completion time is the caller's record of the spend, if it
4139
- // has one — the psbt that classified it carries no timestamp
4140
4217
  ...completion
4141
4218
  });
4142
4219
  }
4143
4220
  return { restored, scannedTxids: fetchedTxids.filter((id) => !unresolved.has(id)) };
4144
4221
  }
4145
4222
 
4223
+ // src/client/cancel.ts
4224
+ init_repository();
4225
+
4146
4226
  // src/client/driveRecords.ts
4227
+ init_repository();
4147
4228
  init_store();
4148
- var import_sdk17 = require("@arkade-os/sdk");
4229
+ var import_sdk18 = require("@arkade-os/sdk");
4149
4230
  var splitRecords = (records) => {
4150
4231
  const corridor = [];
4151
4232
  const offer = [];
@@ -4164,12 +4245,15 @@ var rfqRecordOf = (record) => ({
4164
4245
  state: record.state,
4165
4246
  createdAt: record.createdAt,
4166
4247
  updatedAt: record.updatedAt,
4167
- ...record.refundTxid === void 0 ? {} : { refundTxid: record.refundTxid },
4168
- ...record.lockupSpendTxids?.length ? { lockupSpendTxids: [...record.lockupSpendTxids] } : {},
4169
- ...record.settlementPreimageHex === void 0 ? {} : { settlementPreimageHex: record.settlementPreimageHex },
4170
- ...record.failure === void 0 ? {} : { failure: record.failure },
4171
- ...record.claimFailure === void 0 ? {} : { claimFailure: record.claimFailure },
4172
- ...record.blockedReason === void 0 ? {} : { blockedReason: record.blockedReason }
4248
+ ...mutableHalfOf(record)
4249
+ });
4250
+ var mutableHalfOf = (from) => ({
4251
+ ...from.refundTxid === void 0 ? {} : { refundTxid: from.refundTxid },
4252
+ ...from.lockupSpendTxids?.length ? { lockupSpendTxids: [...from.lockupSpendTxids] } : {},
4253
+ ...from.settlementPreimageHex === void 0 ? {} : { settlementPreimageHex: from.settlementPreimageHex },
4254
+ ...from.failure === void 0 ? {} : { failure: from.failure },
4255
+ ...from.claimFailure === void 0 ? {} : { claimFailure: from.claimFailure },
4256
+ ...from.blockedReason === void 0 ? {} : { blockedReason: from.blockedReason }
4173
4257
  });
4174
4258
  var withRfqState = (record, state) => {
4175
4259
  const {
@@ -4186,12 +4270,7 @@ var withRfqState = (record, state) => {
4186
4270
  state: state.state,
4187
4271
  profile: state.profile,
4188
4272
  updatedAt: state.updatedAt,
4189
- ...state.refundTxid === void 0 ? {} : { refundTxid: state.refundTxid },
4190
- ...state.lockupSpendTxids?.length ? { lockupSpendTxids: [...state.lockupSpendTxids] } : {},
4191
- ...state.settlementPreimageHex === void 0 ? {} : { settlementPreimageHex: state.settlementPreimageHex },
4192
- ...state.failure === void 0 ? {} : { failure: state.failure },
4193
- ...state.claimFailure === void 0 ? {} : { claimFailure: state.claimFailure },
4194
- ...state.blockedReason === void 0 ? {} : { blockedReason: state.blockedReason }
4273
+ ...mutableHalfOf(state)
4195
4274
  };
4196
4275
  };
4197
4276
  var corridorRecordStore = (repository, onRecord = () => {
@@ -4206,7 +4285,7 @@ var corridorRecordStore = (repository, onRecord = () => {
4206
4285
  const record = await repository.getSwapRecord(known);
4207
4286
  if (record?.family === "rfq") return record;
4208
4287
  }
4209
- const { corridor } = splitRecords(await repository.getAllSwapRecords());
4288
+ const { corridor } = splitRecords(await collectSwapRecords(repository));
4210
4289
  for (const record of corridor) index(record);
4211
4290
  const found = byRfqId.get(rfqId);
4212
4291
  return found === void 0 ? void 0 : corridor.find((r) => r.id === found);
@@ -4214,10 +4293,20 @@ var corridorRecordStore = (repository, onRecord = () => {
4214
4293
  return {
4215
4294
  index,
4216
4295
  quoteIdOf: (rfqId) => byRfqId.get(rfqId),
4217
- async getAllRfqSwaps() {
4218
- const { corridor } = splitRecords(await repository.getAllSwapRecords());
4296
+ async getRfqSwapsPage(filter, page) {
4297
+ (0, import_sdk18.assertPageRequest)(page);
4298
+ assertRfqSwapPageFilter(filter);
4299
+ const { corridor } = splitRecords(await collectSwapRecords(repository));
4219
4300
  for (const record of corridor) index(record);
4220
- return corridor.filter(admits).map(rfqRecordOf);
4301
+ const rows = corridor.filter(admits).map(rfqRecordOf).filter(
4302
+ (record) => (filter.state === void 0 || record.state === filter.state) && (filter.since === void 0 || record.updatedAt >= filter.since) && (!page.after || record.updatedAt > page.after.updatedAt || record.updatedAt === page.after.updatedAt && record.rfqId > page.after.rfqId)
4303
+ ).sort(
4304
+ (a, b) => a.updatedAt - b.updatedAt || (a.rfqId < b.rfqId ? -1 : a.rfqId > b.rfqId ? 1 : 0)
4305
+ ).slice(0, page.limit + 1);
4306
+ return (0, import_sdk18.pageResult)(rows, page.limit, (record) => ({
4307
+ updatedAt: record.updatedAt,
4308
+ rfqId: record.rfqId
4309
+ }));
4221
4310
  },
4222
4311
  async getRfqSwap(rfqId) {
4223
4312
  const record = await recordFor(rfqId);
@@ -4245,15 +4334,14 @@ var offerFactsOf = (record) => ({
4245
4334
  swapPkScript: record.swapPkScript,
4246
4335
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
4247
4336
  ...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
4248
- // Milliseconds: `coverage.ts` marks issuance with `Date.now()`, and a
4249
- // seconds value compared against it leaves every issued script outstanding
4250
- // for the life of the process.
4337
+ // milliseconds: `coverage.ts` compares against `Date.now()`, and seconds would leave every
4338
+ // issued script outstanding for the life of the process
4251
4339
  createdAt: record.createdAt * 1e3
4252
4340
  });
4253
4341
  var offerRecordSource = (repository, onRecord = () => {
4254
4342
  }, now = () => Math.floor(Date.now() / 1e3)) => {
4255
4343
  const list = async () => {
4256
- const { offer } = splitRecords(await repository.getAllSwapRecords());
4344
+ const { offer } = splitRecords(await collectSwapRecords(repository));
4257
4345
  return offer.map(offerFactsOf);
4258
4346
  };
4259
4347
  return {
@@ -4282,8 +4370,7 @@ var applyOfferSpend = (record, changes, now) => ({
4282
4370
  ...record,
4283
4371
  status: changes.status,
4284
4372
  spentTxid: changes.spentTxid,
4285
- // The watcher's `completedAt` comes off a contract event's timestamp, in
4286
- // milliseconds; this record's timestamps are unix seconds.
4373
+ // event timestamps are milliseconds; this record's are unix seconds
4287
4374
  ...changes.completedAt === void 0 ? {} : { completedAt: Math.floor(changes.completedAt / 1e3) },
4288
4375
  updatedAt: now
4289
4376
  });
@@ -4309,7 +4396,7 @@ var restoredOfferRecord = (swap, network, now) => {
4309
4396
  },
4310
4397
  give: { asset: give, amount: toAtomicDecimal(BigInt(swap.fromAmount)) },
4311
4398
  take: { asset: take, amount: toAtomicDecimal(BigInt(swap.toAmount)) },
4312
- fee: { asset: take, amount: toAtomicDecimal(BigInt(0)) },
4399
+ fee: { asset: take, amount: toAtomicDecimal(0n) },
4313
4400
  market: { kind: "restored", backend: "feed" },
4314
4401
  expiresAt: createdAt,
4315
4402
  status: swap.status,
@@ -4324,7 +4411,7 @@ var restoredOfferRecord = (swap, network, now) => {
4324
4411
  now
4325
4412
  );
4326
4413
  };
4327
- var restoredAssetId = (network, id) => id === BTC_ASSET_ID ? btcOn("arkade", network) : arkadeAsset(network, import_sdk17.asset.AssetId.fromString(id));
4414
+ var restoredAssetId = (network, id) => id === BTC_ASSET_ID ? btcOn("arkade", network) : arkadeAsset(network, import_sdk18.asset.AssetId.fromString(id));
4328
4415
  var walletLockupIndexer = (wallet) => {
4329
4416
  let reader;
4330
4417
  const reading = () => reader ??= wallet.getArkadeReader();
@@ -4340,15 +4427,12 @@ var walletLockupIndexer = (wallet) => {
4340
4427
  };
4341
4428
 
4342
4429
  // src/client/cancel.ts
4343
- var OFFER_TERMINAL = (record) => record.status === "cancelled" || record.status === "fulfilled";
4344
4430
  var cancelSwap = async (input) => {
4345
4431
  const { wallet, repository, record, drive, indexer } = input;
4346
4432
  const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
4347
- if (OFFER_TERMINAL(record)) {
4348
- return { outcome: record.status === "cancelled" ? "cancelled" : "filled" };
4349
- }
4350
- if (offerOutcome(record.status) === "needs_recovery") {
4351
- return { outcome: "needs_recovery" };
4433
+ const outcome = offerOutcome(record.status);
4434
+ if (outcome === "cancelled" || outcome === "filled" || outcome === "needs_recovery") {
4435
+ return { outcome };
4352
4436
  }
4353
4437
  const gated2 = withStatus(record, "cancelling", now());
4354
4438
  await repository.saveSwapRecord(gated2);
@@ -4373,7 +4457,7 @@ var cancelSwap = async (input) => {
4373
4457
  drive.ingest(rolledBack);
4374
4458
  throw error;
4375
4459
  }
4376
- if (isMissingVtxo(error)) {
4460
+ if (error instanceof NoSpendableDepositError) {
4377
4461
  const reconciled = await reconcileDepositSpend(record, indexer);
4378
4462
  if (reconciled === void 0) {
4379
4463
  return { outcome: "needs_recovery" };
@@ -4414,12 +4498,12 @@ var reconcileDepositSpend = async (record, indexer) => {
4414
4498
  const { txs } = await indexer.getVirtualTxs(candidates);
4415
4499
  const parsed = txs.map((psbt) => {
4416
4500
  try {
4417
- return import_sdk18.Transaction.fromPSBT(import_base12.base64.decode(psbt));
4501
+ return import_sdk19.Transaction.fromPSBT(import_base12.base64.decode(psbt));
4418
4502
  } catch {
4419
4503
  return void 0;
4420
4504
  }
4421
4505
  }).filter((tx) => tx !== void 0);
4422
- const operatorPubkey = import_sdk18.ArkAddress.decode(record.swapAddress).serverPubKey;
4506
+ const operatorPubkey = import_sdk19.ArkAddress.decode(record.swapAddress).serverPubKey;
4423
4507
  const kind = classifyDepositSpend(offer, operatorPubkey, parsed, {
4424
4508
  txid: deposit.txid,
4425
4509
  vout: deposit.vout
@@ -4445,7 +4529,7 @@ var persistBestEffort = async (repository, record) => {
4445
4529
  };
4446
4530
  var retireOfferScripts = async (wallet, repository, record) => {
4447
4531
  try {
4448
- const { offer } = splitRecords(await repository.getAllSwapRecords());
4532
+ const { offer } = splitRecords(await collectSwapRecords(repository));
4449
4533
  await retireOfferContract(
4450
4534
  await wallet.getContractManager(),
4451
4535
  offer.map(offerFactsOf),
@@ -4455,17 +4539,14 @@ var retireOfferScripts = async (wallet, repository, record) => {
4455
4539
  console.warn(`[swap] could not retire offer script for ${record.id}`, error);
4456
4540
  }
4457
4541
  };
4458
- var isMissingVtxo = (error) => error instanceof NoSpendableDepositError;
4459
4542
 
4460
4543
  // src/client/drive.ts
4461
- var import_sdk24 = require("@arkade-os/sdk");
4544
+ var import_sdk27 = require("@arkade-os/sdk");
4462
4545
  var import_base17 = require("@scure/base");
4463
4546
 
4464
4547
  // src/claim.ts
4465
- var import_base13 = require("@scure/base");
4466
- var import_legacy3 = require("@noble/hashes/legacy.js");
4467
- var import_sha25 = require("@noble/hashes/sha2.js");
4468
- var import_sdk19 = require("@arkade-os/sdk");
4548
+ var import_sdk20 = require("@arkade-os/sdk");
4549
+ init_onchainHtlc();
4469
4550
  var LockupAmountMismatchError = class extends Error {
4470
4551
  name = "LockupAmountMismatchError";
4471
4552
  reason = "amount_mismatch";
@@ -4481,19 +4562,11 @@ var LockupAmountMismatchError = class extends Error {
4481
4562
  };
4482
4563
  var assertFiniteAmount = (value, reason, label) => {
4483
4564
  if (Number.isFinite(value)) return;
4484
- const error = new Error(`${label} is not a finite number (${String(value)})`);
4485
- error.reason = reason;
4486
- throw error;
4565
+ throw gateError(reason, `${label} is not a finite number (${String(value)})`);
4487
4566
  };
4488
4567
  async function pushClaim(operator, input) {
4489
4568
  if (input.vtxos.length === 0) throw new Error("nothing to claim: no funded outputs");
4490
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
4491
- if (swept.length > 0) {
4492
- throw new LockupNeedsRecoveryError(
4493
- swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
4494
- input.contract.options.refundLocktime
4495
- );
4496
- }
4569
+ assertNoneSwept(input.vtxos, input.contract);
4497
4570
  const locked = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
4498
4571
  assertFiniteAmount(locked, "lockup_malformed", "the lockup's summed value");
4499
4572
  if (!input.partiallyClaimed) {
@@ -4502,33 +4575,16 @@ async function pushClaim(operator, input) {
4502
4575
  throw new LockupAmountMismatchError(input.expectedAmount, locked);
4503
4576
  }
4504
4577
  }
4505
- const committed = input.contract.options.preimageHash;
4506
- if (import_base13.hex.encode((0, import_legacy3.ripemd160)((0, import_sha25.sha256)(input.preimage))) !== import_base13.hex.encode(committed)) {
4507
- throw new Error("preimage does not match the covenant's payment hash");
4508
- }
4509
- const info = await operator.getInfo();
4510
- let operatorUnrollScript;
4511
- try {
4512
- operatorUnrollScript = import_sdk19.CSVMultisigTapscript.decode(import_base13.hex.decode(info.checkpointTapscript));
4513
- } catch {
4514
- throw new Error("invalid checkpointTapscript from the operator");
4515
- }
4578
+ assertPreimageMatches(input.preimage, input.contract.options.preimageHash);
4579
+ const serverUnrollScript = await operatorUnrollScript(operator, input.network);
4516
4580
  const leaf = input.contract.claim();
4517
- const tapTree = input.contract.encode();
4518
- const txid = await (0, import_sdk19.signAndSubmitOffchainTx)({
4519
- identity: (0, import_sdk19.claimWithPreimageIdentity)(input.receiver, input.preimage),
4581
+ const txid = await (0, import_sdk20.signAndSubmitOffchainTx)({
4582
+ identity: (0, import_sdk20.claimWithPreimageIdentity)(input.receiver, input.preimage),
4520
4583
  provider: operator,
4521
- inputs: input.vtxos.map((vtxo) => ({
4522
- txid: vtxo.txid,
4523
- vout: vtxo.vout,
4524
- value: vtxo.value,
4525
- tapLeafScript: leaf,
4526
- tapTree
4527
- })),
4528
- // One aggregate output: unlike the covenant refund, this leaf inspects
4529
- // nothing about the output set.
4584
+ inputs: lockupInputs(input.vtxos, input.contract, leaf),
4585
+ // One aggregate output: this leaf inspects nothing about the output set.
4530
4586
  outputs: [{ script: input.destinationPkScript, amount: BigInt(locked) }],
4531
- serverUnrollScript: operatorUnrollScript,
4587
+ serverUnrollScript,
4532
4588
  verifyServerSignatures: { serverPubkey: input.contract.options.server }
4533
4589
  });
4534
4590
  return { txid, amount: locked };
@@ -4540,7 +4596,7 @@ init_coverage();
4540
4596
  init_lockupContract();
4541
4597
 
4542
4598
  // src/refundBlocked.ts
4543
- var import_sdk20 = require("@arkade-os/sdk");
4599
+ var import_sdk21 = require("@arkade-os/sdk");
4544
4600
  var RefundNotLocallyPossibleError = class extends Error {
4545
4601
  constructor(reason, message, options) {
4546
4602
  super(message, options);
@@ -4557,16 +4613,16 @@ async function senderIdentityForSwapRecord(wallet, record) {
4557
4613
  );
4558
4614
  }
4559
4615
  try {
4560
- return await (0, import_sdk20.contractSigner)(wallet, record.signingDescriptor);
4616
+ return await (0, import_sdk21.contractSigner)(wallet, record.signingDescriptor);
4561
4617
  } catch (cause) {
4562
- if (cause instanceof import_sdk20.WalletCannotSignError) {
4618
+ if (cause instanceof import_sdk21.WalletCannotSignError) {
4563
4619
  throw new RefundNotLocallyPossibleError(
4564
4620
  "unsignable-wallet",
4565
4621
  `this wallet holds ${record.signingDescriptor} but cannot sign with it; attach its signer`,
4566
4622
  { cause }
4567
4623
  );
4568
4624
  }
4569
- if (cause instanceof import_sdk20.ForeignDescriptorError) {
4625
+ if (cause instanceof import_sdk21.ForeignDescriptorError) {
4570
4626
  throw new RefundNotLocallyPossibleError(
4571
4627
  "foreign-descriptor",
4572
4628
  `this wallet cannot derive ${record.signingDescriptor}; the swap was created on another wallet`,
@@ -4596,16 +4652,27 @@ function arkadeRefunder(deps) {
4596
4652
  );
4597
4653
  }
4598
4654
  const sender = await senderIdentityForSwapRecord(deps.wallet, rfqSignerOf(record) ?? {});
4599
- return pushRefundWithoutReceiver(deps.operator, { contract, sender, vtxos });
4655
+ return pushRefundWithoutReceiver(deps.operator, {
4656
+ contract,
4657
+ sender,
4658
+ vtxos,
4659
+ network: await deps.network?.()
4660
+ });
4600
4661
  };
4601
4662
  }
4602
4663
 
4603
4664
  // src/rfqRecord.ts
4604
- var import_sdk21 = require("@arkade-os/sdk");
4605
- var import_base14 = require("@scure/base");
4665
+ var import_sdk22 = require("@arkade-os/sdk");
4666
+ var import_base13 = require("@scure/base");
4606
4667
 
4607
4668
  // src/rfqSwapState.ts
4608
4669
  var RFQ_SWAP_TERMINAL_STATES = ["settled", "refunded", "failed"];
4670
+ var RFQ_SWAP_ACTIVE_STATES = [
4671
+ "pending",
4672
+ "claimable",
4673
+ "claimed",
4674
+ "needs_counterparty"
4675
+ ];
4609
4676
  var isRfqSwapTerminal = (state) => RFQ_SWAP_TERMINAL_STATES.includes(state);
4610
4677
 
4611
4678
  // src/rfqRecord.ts
@@ -4629,17 +4696,20 @@ function normalizeRfqSwapRecord(record) {
4629
4696
  ...legacyClaim ? { profile: renameLegacyClaimTxid(record.profile) } : {}
4630
4697
  };
4631
4698
  }
4699
+ var mutableFields = (from) => ({
4700
+ ...from.refundTxid ? { refundTxid: from.refundTxid } : {},
4701
+ ...from.lockupSpendTxids?.length ? { lockupSpendTxids: [...from.lockupSpendTxids] } : {},
4702
+ ...from.settlementPreimageHex ? { settlementPreimageHex: from.settlementPreimageHex } : {},
4703
+ ...from.failure ? { failure: from.failure } : {},
4704
+ ...from.claimFailure ? { claimFailure: from.claimFailure } : {},
4705
+ ...from.blockedReason ? { blockedReason: from.blockedReason } : {}
4706
+ });
4632
4707
  var managerState = (swap) => ({
4633
4708
  rfqId: swap.rfqId,
4634
4709
  state: swap.state,
4635
4710
  createdAt: swap.createdAt,
4636
4711
  updatedAt: swap.updatedAt,
4637
- ...swap.refundTxid ? { refundTxid: swap.refundTxid } : {},
4638
- ...swap.lockupSpendTxids?.length ? { lockupSpendTxids: [...swap.lockupSpendTxids] } : {},
4639
- ...swap.settlementPreimageHex ? { settlementPreimageHex: swap.settlementPreimageHex } : {},
4640
- ...swap.failure ? { failure: swap.failure } : {},
4641
- ...swap.claimFailure ? { claimFailure: swap.claimFailure } : {},
4642
- ...swap.blockedReason ? { blockedReason: swap.blockedReason } : {}
4712
+ ...mutableFields(swap)
4643
4713
  });
4644
4714
  function assertSameSwap(origin, swap) {
4645
4715
  if (origin.kind !== swap.kind) {
@@ -4647,8 +4717,8 @@ function assertSameSwap(origin, swap) {
4647
4717
  `rfq swap record is a ${origin.kind} origin paired with a ${swap.kind} swap`
4648
4718
  );
4649
4719
  }
4650
- const funded = import_base14.hex.encode(import_sdk21.ArkAddress.decode(origin.lockupAddress).pkScript);
4651
- const watched = import_base14.hex.encode(swap.lockupPkScript);
4720
+ const funded = import_base13.hex.encode(import_sdk22.ArkAddress.decode(origin.lockupAddress).pkScript);
4721
+ const watched = import_base13.hex.encode(swap.lockupPkScript);
4652
4722
  if (funded !== watched) {
4653
4723
  throw new Error(
4654
4724
  `rfq swap record's lockup address holds ${funded}, but the swap watches ${watched} \u2014 these are not the same swap`
@@ -4661,8 +4731,6 @@ function createRfqSwapRecord(origin, swap) {
4661
4731
  return {
4662
4732
  ...origin,
4663
4733
  ...managerState(swap),
4664
- // The caller wrote what only the request result knows; the handler adds
4665
- // what the live swap already carries.
4666
4734
  profile: { ...origin.profile, ...handler.project(swap) }
4667
4735
  };
4668
4736
  }
@@ -4696,11 +4764,11 @@ function rfqSwapOriginOf(record) {
4696
4764
  };
4697
4765
  }
4698
4766
  function lockupScript(params, lockupAddress) {
4699
- const script = import_sdk21.VHTLCV2ContractHandler.createScript(params);
4700
- const funded = import_sdk21.ArkAddress.decode(lockupAddress).pkScript;
4701
- if (import_base14.hex.encode(funded) !== import_base14.hex.encode(script.pkScript)) {
4767
+ const script = import_sdk22.VHTLCV2ContractHandler.createScript(params);
4768
+ const funded = import_sdk22.ArkAddress.decode(lockupAddress).pkScript;
4769
+ if (import_base13.hex.encode(funded) !== import_base13.hex.encode(script.pkScript)) {
4702
4770
  throw new Error(
4703
- `rfq swap covenant params derive ${import_base14.hex.encode(script.pkScript)}, but the record's lockup address holds ${import_base14.hex.encode(funded)} \u2014 these params are not this swap's`
4771
+ `rfq swap covenant params derive ${import_base13.hex.encode(script.pkScript)}, but the record's lockup address holds ${import_base13.hex.encode(funded)} \u2014 these params are not this swap's`
4704
4772
  );
4705
4773
  }
4706
4774
  return script;
@@ -4718,12 +4786,7 @@ function rebuildRfqSwap(record, params) {
4718
4786
  refundLocktime: Number(script.options.refundLocktime),
4719
4787
  createdAt: stored.createdAt,
4720
4788
  updatedAt: stored.updatedAt,
4721
- ...stored.refundTxid ? { refundTxid: stored.refundTxid } : {},
4722
- ...stored.lockupSpendTxids?.length ? { lockupSpendTxids: [...stored.lockupSpendTxids] } : {},
4723
- ...stored.settlementPreimageHex ? { settlementPreimageHex: stored.settlementPreimageHex } : {},
4724
- ...stored.failure ? { failure: stored.failure } : {},
4725
- ...stored.claimFailure ? { claimFailure: stored.claimFailure } : {},
4726
- ...stored.blockedReason ? { blockedReason: stored.blockedReason } : {}
4789
+ ...mutableFields(stored)
4727
4790
  };
4728
4791
  const handler = rfqCorridorHandlers.getOrThrow(stored.kind);
4729
4792
  return {
@@ -4737,14 +4800,34 @@ function shouldRetainRfqSwap(record, now) {
4737
4800
  return now - record.updatedAt < RFQ_SWAP_RETENTION_SECONDS;
4738
4801
  }
4739
4802
 
4803
+ // src/registerRestore.ts
4804
+ var import_base14 = require("@scure/base");
4805
+ var import_sdk24 = require("@arkade-os/sdk");
4806
+
4807
+ // src/restoreRepository.ts
4808
+ var import_sdk23 = require("@arkade-os/sdk");
4809
+ init_offer();
4810
+ init_store();
4811
+
4812
+ // src/registerRestore.ts
4813
+ var toRestoreTx = (tx) => ({
4814
+ type: tx.type.toLowerCase(),
4815
+ redeemTxid: tx.key.arkTxid,
4816
+ boardingTxid: tx.key.boardingTxid,
4817
+ roundTxid: tx.key.commitmentTxid,
4818
+ createdAt: Math.floor(tx.createdAt / 1e3)
4819
+ });
4820
+
4740
4821
  // src/client/drive.ts
4741
4822
  init_store();
4823
+ init_repository();
4742
4824
 
4743
4825
  // src/swapManager.ts
4744
4826
  var import_base15 = require("@scure/base");
4745
- var import_sdk22 = require("@arkade-os/sdk");
4827
+ var import_sdk25 = require("@arkade-os/sdk");
4746
4828
  init_onchainHtlc();
4747
4829
  init_lockupContract();
4830
+ init_repository();
4748
4831
  init_coverage();
4749
4832
  function nextOnchainAction(input) {
4750
4833
  switch (input.phase.phase) {
@@ -4789,7 +4872,8 @@ var notify = (listeners, call) => {
4789
4872
  }
4790
4873
  }
4791
4874
  };
4792
- var RfqSwapManager = class {
4875
+ var RfqSwapManager = class _RfqSwapManager {
4876
+ static POLL_CONCURRENCY = 16;
4793
4877
  deps;
4794
4878
  config;
4795
4879
  callbacks = null;
@@ -4798,62 +4882,40 @@ var RfqSwapManager = class {
4798
4882
  swapFailedListeners = /* @__PURE__ */ new Set();
4799
4883
  actionExecutedListeners = /* @__PURE__ */ new Set();
4800
4884
  monitored = /* @__PURE__ */ new Map();
4801
- /** Monitored swaps by lockup script hex, so a contract event — which names
4802
- * a script and nothing else — can find the swap it belongs to. */
4885
+ /** Monitored swaps by lockup script hex: a contract event names only a script. */
4803
4886
  byLockupScript = /* @__PURE__ */ new Map();
4804
4887
  /**
4805
- * Swaps whose lockup registration has been SETTLED one way or another,
4806
- * mapped to whether a contract row actually resulted. Membership is what
4807
- * stops a per-pass retry from becoming a per-pass round trip; the value is
4808
- * what keeps a swap that could never be registered from later trying to
4809
- * retire a row that does not exist, which would report a spurious failure
4810
- * on a swap that in fact succeeded.
4888
+ * Swaps whose lockup registration has SETTLED, mapped to whether a contract row
4889
+ * resulted. Membership stops per-pass round trips; the value stops a never-registered
4890
+ * swap from retiring a nonexistent row and reporting a spurious failure.
4811
4891
  */
4812
4892
  registered = /* @__PURE__ */ new Map();
4813
4893
  /**
4814
- * Swaps whose `refundArkade` answered {@link RefundNotLocallyPossibleError}
4815
- * in this process. Membership stops the push from being re-issued every
4816
- * pass — it cannot start working on its own, and re-issuing it is the
4817
- * grind `needs_counterparty` exists to remove. Only
4818
- * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it, so a caller
4819
- * with no probe learns again on the next start, when the wallet that can
4820
- * sign may well have been restored.
4894
+ * Swaps whose `refundArkade` threw {@link RefundNotLocallyPossibleError} in this
4895
+ * process, so the push is not re-issued every pass. Only
4896
+ * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it.
4821
4897
  */
4822
4898
  refundRefused = /* @__PURE__ */ new Set();
4823
4899
  /**
4824
- * The lockup outpoints a receive swap's claim callback has already been
4825
- * handed, by rfqId.
4826
- *
4827
- * What this exists to prevent: a claim SUCCEEDS, and for the next few
4828
- * passes the indexer still lists those outputs as unspent. Without a
4829
- * record of what was already claimed, every one of those passes would
4830
- * re-submit the same spend, fail against the server, and report a swap
4831
- * that in fact worked as failing. With one, a re-claim happens only when
4832
- * an outpoint appears that was never claimed — a lockup funded piecemeal,
4833
- * which is legitimate and which `partiallyClaimed` exists for.
4834
- *
4835
- * Process-local: after a restart a swap with a live claim tries once more.
4836
- * That is the recovery case rather than the spam one — a claim that never
4837
- * landed leaves its outputs unspent, and one that did leaves a single
4838
- * rejection.
4900
+ * Lockup outpoints already handed to a receive swap's claim callback, by rfqId. After a
4901
+ * claim SUCCEEDS the indexer may still list its outputs as unspent; without this each
4902
+ * pass would re-submit and report a working swap as failing. Process-local: a restart
4903
+ * costs at most one rejected re-claim.
4839
4904
  */
4840
4905
  claimedOutpoints = /* @__PURE__ */ new Map();
4841
4906
  /** Live `onContractEvent` subscription, held so `stop()` can drop it. */
4842
4907
  unsubscribeContracts = null;
4843
- /** Terminal records, kept so a late {@link waitForSwapCompletion} still
4844
- * answers instead of throwing "not found". Cleared by {@link removeSwap}. */
4908
+ /** Recent terminal swaps; older durable outcomes are read from the record store on demand. */
4845
4909
  finished = /* @__PURE__ */ new Map();
4910
+ /** Explicit removals stay suppressed for this manager lifetime; normal completions never enter this set.
4911
+ * Each maps to its removal sequence, so restore can tell a removal made during its rebuild. */
4912
+ removed = /* @__PURE__ */ new Map();
4913
+ removalSeq = 0;
4846
4914
  waiters = /* @__PURE__ */ new Map();
4847
4915
  /**
4848
- * The request-time origin of each swap the manager may have to CREATE a
4849
- * record for, by rfqId.
4850
- *
4851
- * Needed only for a swap the store has never seen: once a record exists,
4852
- * `updateRfqSwapRecord` carries the origin half through and the map is
4853
- * redundant. It is kept anyway for the swap's whole life, so a record the
4854
- * store loses between passes is rewritten rather than lost — and dropped
4855
- * by {@link removeSwap} and by retention, which are the two places a swap
4856
- * stops being this manager's business.
4916
+ * The request-time origin of each swap, by rfqId, needed to CREATE a record. Kept for
4917
+ * the swap's whole life so a record the store loses is rewritten; dropped by
4918
+ * {@link removeSwap} and by retention.
4857
4919
  */
4858
4920
  origins = /* @__PURE__ */ new Map();
4859
4921
  /** Records changed during the current pass, flushed to the repository and
@@ -4861,6 +4923,8 @@ var RfqSwapManager = class {
4861
4923
  dirty = /* @__PURE__ */ new Set();
4862
4924
  /** Race guard: one action at a time per swap. */
4863
4925
  inProgress = /* @__PURE__ */ new Set();
4926
+ activePolls = 0;
4927
+ pollWaiters = /* @__PURE__ */ new Set();
4864
4928
  timer = null;
4865
4929
  running = false;
4866
4930
  constructor(deps, config = {}) {
@@ -4879,9 +4943,8 @@ var RfqSwapManager = class {
4879
4943
  this.actionExecutedListeners.add(config.events.onActionExecuted);
4880
4944
  }
4881
4945
  }
4882
- /** Wire the money-moving half. Without it the manager only watches. The
4883
- * two claims may be omitted for a consumer that drives no kind reaching
4884
- * them — see {@link AvailableRfqSwapManagerCallbacks}. */
4946
+ /** Wire the money-moving half. Without it the manager only watches. See
4947
+ * {@link AvailableRfqSwapManagerCallbacks}. */
4885
4948
  setCallbacks(callbacks) {
4886
4949
  this.callbacks = callbacks;
4887
4950
  }
@@ -4902,41 +4965,21 @@ var RfqSwapManager = class {
4902
4965
  return () => this.actionExecutedListeners.delete(listener);
4903
4966
  }
4904
4967
  /**
4905
- * Rebuild every stored swap and take over monitoring them.
4906
- *
4907
- * The composition a consumer otherwise writes by hand, and the one place
4908
- * all four pieces meet: retention decides what to keep
4909
- * (`shouldRetainRfqSwap`), the lockup's contract row supplies the covenant
4910
- * (`lockupContractParams`), `rebuildRfqSwap` turns a record back into a
4911
- * live swap, and each rebuilt swap arrives with its own origin, so nothing
4912
- * is asked of the caller.
4913
- *
4914
- * **Deliberately not part of {@link start}.** A consumer that wants to
4915
- * look at its records — count them, show them, prune and stop — is not
4916
- * forced to start driving money to do it. Call this first and `start()`
4917
- * after; a manager already running polls the restored swaps at once.
4918
- *
4919
- * Retention runs BEFORE the rebuild, so a record past
4920
- * `RFQ_SWAP_RETENTION_SECONDS` costs no contract lookup on its way to being
4921
- * dropped.
4922
- *
4923
- * **A record that cannot be rebuilt is reported, never swallowed and never
4924
- * fatal.** `rebuildRfqSwap` throws by design when the covenant params do
4925
- * not derive the funded address, and `lockupContractParams` throws
4926
- * `LockupContractMissing` when the wallet has no row for the lockup — both
4927
- * say something true about that one record, and neither is a reason to
4928
- * strand the others. They come back in {@link RfqRestoreResult.failed}.
4968
+ * Rebuild stored swaps and take over monitoring them. By default only active states
4969
+ * are read; terminal history stays stored and a late completion lookup reads one record
4970
+ * by key (`includeTerminal` loads everything). Deliberately not part of {@link start},
4971
+ * so records can be inspected without driving money. An unrebuildable record lands in
4972
+ * {@link RfqRestoreResult.failed}, never fatal to the others.
4929
4973
  */
4930
4974
  async restoreFromRepository(options = {}) {
4931
4975
  const repository = this.requireRepository("restoreFromRepository");
4932
4976
  const params = options.params ?? this.paramsFromContracts();
4933
- const records = await repository.getAllRfqSwaps();
4934
- const pruned = await this.dropRetired(repository, records);
4935
- const retired = new Set(pruned);
4936
4977
  const restored = [];
4937
4978
  const failed = [];
4938
- for (const record of records) {
4939
- if (retired.has(record.rfqId)) continue;
4979
+ const restore = async (record) => {
4980
+ if (!options.includeTerminal && isRfqSwapTerminal(record.state)) return;
4981
+ if (this.monitored.has(record.rfqId)) return;
4982
+ const removedAt = this.removed.get(record.rfqId);
4940
4983
  let swap;
4941
4984
  try {
4942
4985
  swap = rebuildRfqSwap(record, await params(record));
@@ -4945,38 +4988,37 @@ var RfqSwapManager = class {
4945
4988
  rfqId: record.rfqId,
4946
4989
  error: error instanceof Error ? error : new Error(errorMessage(error))
4947
4990
  });
4948
- continue;
4991
+ return;
4992
+ }
4993
+ if (this.monitored.has(record.rfqId)) return;
4994
+ if (this.removed.get(record.rfqId) !== removedAt) return;
4995
+ this.removed.delete(record.rfqId);
4996
+ if (isRfqSwapTerminal(swap.state)) this.rememberFinished(swap, true);
4997
+ else {
4998
+ this.origins.set(record.rfqId, rfqSwapOriginOf(record));
4999
+ this.track(swap);
4949
5000
  }
4950
- this.origins.set(record.rfqId, rfqSwapOriginOf(record));
4951
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
4952
- else this.track(swap);
4953
5001
  restored.push(swap);
5002
+ };
5003
+ const states = options.includeTerminal ? [void 0] : RFQ_SWAP_ACTIVE_STATES;
5004
+ for (const state of states) {
5005
+ for (const record of await collectRfqSwaps(repository, { state }))
5006
+ await restore(record);
4954
5007
  }
4955
5008
  if (this.running) {
4956
- await Promise.allSettled(
4957
- restored.filter((swap) => this.monitored.has(swap.rfqId)).map((swap) => this.pollSwap(swap))
4958
- );
5009
+ await this.pollMany(restored.filter((swap) => this.monitored.has(swap.rfqId)));
4959
5010
  }
4960
- return { restored, failed, pruned };
5011
+ return { restored, failed, pruned: [] };
4961
5012
  }
4962
5013
  /**
4963
- * Drop stored records that are terminal and past
4964
- * `RFQ_SWAP_RETENTION_SECONDS`, and return their ids.
4965
- *
4966
- * `needs_counterparty` is never dropped, however old: the money is still at
4967
- * the lockup and the counterparty's move still ends the swap. That rule
4968
- * lives in `shouldRetainRfqSwap`, which this defers to rather than
4969
- * restating.
4970
- *
4971
- * Public because retention is a caller's cadence, not the manager's: a
4972
- * long-lived process wants it on a timer of its own, a mobile app wants it
4973
- * at boot. {@link restoreFromRepository} runs it first, so the boot path
4974
- * needs no separate call.
5014
+ * Drop stored records that are terminal and past `RFQ_SWAP_RETENTION_SECONDS` (per
5015
+ * `shouldRetainRfqSwap`), and return their ids. Explicit only: restore keeps history.
5016
+ * Loads every stored record; no backend offers indexed deletion.
4975
5017
  */
4976
5018
  async pruneRetiredSwaps() {
4977
5019
  const repository = this.deps.repository;
4978
5020
  if (!repository) return [];
4979
- return this.dropRetired(repository, await repository.getAllRfqSwaps());
5021
+ return this.dropRetired(repository, await collectRfqSwaps(repository));
4980
5022
  }
4981
5023
  async dropRetired(repository, records) {
4982
5024
  const now = this.config.now();
@@ -4984,12 +5026,15 @@ var RfqSwapManager = class {
4984
5026
  for (const record of records) {
4985
5027
  if (shouldRetainRfqSwap(record, now)) continue;
4986
5028
  await repository.removeRfqSwap(record.rfqId);
4987
- this.finished.delete(record.rfqId);
4988
- if (!this.monitored.has(record.rfqId)) this.origins.delete(record.rfqId);
5029
+ this.forgetRetired(record.rfqId);
4989
5030
  dropped.push(record.rfqId);
4990
5031
  }
4991
5032
  return dropped;
4992
5033
  }
5034
+ forgetRetired(rfqId) {
5035
+ this.finished.delete(rfqId);
5036
+ if (!this.monitored.has(rfqId)) this.origins.delete(rfqId);
5037
+ }
4993
5038
  requireRepository(method) {
4994
5039
  const repository = this.deps.repository;
4995
5040
  if (!repository) {
@@ -4999,9 +5044,7 @@ var RfqSwapManager = class {
4999
5044
  }
5000
5045
  return repository;
5001
5046
  }
5002
- /** The default covenant source: the wallet's own contract row for each
5003
- * lockup, which is where registration put it before the address could be
5004
- * funded. */
5047
+ /** The default covenant source: the wallet's own contract row for each lockup. */
5005
5048
  paramsFromContracts() {
5006
5049
  const contracts = this.deps.contracts;
5007
5050
  if (!contracts) {
@@ -5012,28 +5055,23 @@ var RfqSwapManager = class {
5012
5055
  return (record) => lockupContractParams(contracts, record.lockupAddress);
5013
5056
  }
5014
5057
  /**
5015
- * Load records and begin monitoring. Runs one pass immediately — a caller
5016
- * resuming after a restart may be well past a deadline already — then
5017
- * every `pollIntervalMs`. Records that are already terminal are kept only
5018
- * so {@link waitForSwapCompletion} can answer for them.
5019
- *
5020
- * Calling it again while running loads the records and returns rather than
5021
- * re-arming — dropping them silently would strand a funded swap on a
5022
- * caller's harmless double-start.
5058
+ * Load records and begin monitoring: one pass immediately (a restart may already be
5059
+ * past a deadline), then every `pollIntervalMs`. Terminal outcomes in a repository are
5060
+ * read on demand. Calling it again while running loads the records without re-arming,
5061
+ * so a double-start never strands a funded swap.
5023
5062
  *
5024
- * The signature is unchanged with a {@link RfqSwapManagerDeps.repository}
5025
- * wired; the origins are resolved from the store instead, by the same rule
5026
- * {@link addSwap} applies. A swap the store has never seen throws
5027
- * {@link RfqSwapOriginRequired} — hand that one to `addSwap` with its
5028
- * origin, or restore the whole set with {@link restoreFromRepository},
5029
- * which needs no caller input at all. Every swap is checked before any is
5030
- * tracked, so a bad one in the list does not leave a half-loaded manager.
5063
+ * With a repository wired, a swap the store has never seen throws
5064
+ * {@link RfqSwapOriginRequired} (use {@link addSwap} with its origin, or
5065
+ * {@link restoreFromRepository}). Every swap is checked before any is tracked.
5031
5066
  */
5032
5067
  async start(swaps = []) {
5033
5068
  for (const swap of swaps) await this.admit(swap);
5034
5069
  for (const swap of swaps) {
5035
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
5036
- else this.track(swap);
5070
+ this.removed.delete(swap.rfqId);
5071
+ if (isRfqSwapTerminal(swap.state)) {
5072
+ this.rememberFinished(swap);
5073
+ this.origins.delete(swap.rfqId);
5074
+ } else this.track(swap);
5037
5075
  }
5038
5076
  if (this.running) return;
5039
5077
  this.running = true;
@@ -5042,16 +5080,10 @@ var RfqSwapManager = class {
5042
5080
  this.arm();
5043
5081
  }
5044
5082
  /**
5045
- * Stop monitoring and clear the timer. In-flight actions are not
5046
- * cancellable and run to completion; outstanding
5047
- * {@link waitForSwapCompletion} promises are left pending, since
5048
- * stop/start is a pause rather than a cancellation.
5049
- *
5050
- * The contract subscription is dropped too — an open stream with nothing
5051
- * reacting to it is a leak, and {@link start} puts it back. What is NOT
5052
- * undone is the contract registration: those rows are the wallet's, they
5053
- * outlive this manager's lifecycle, and dropping them would unwatch a
5054
- * lockup that is still funded.
5083
+ * Stop monitoring: clear the timer and drop the contract subscription. In-flight
5084
+ * actions run to completion and {@link waitForSwapCompletion} promises stay pending
5085
+ * (stop/start is a pause). Contract registrations are NOT undone: they are the
5086
+ * wallet's, and dropping them would unwatch a still-funded lockup.
5055
5087
  */
5056
5088
  async stop() {
5057
5089
  this.running = false;
@@ -5063,35 +5095,26 @@ var RfqSwapManager = class {
5063
5095
  this.unsubscribeContracts = null;
5064
5096
  }
5065
5097
  /**
5066
- * Begin monitoring a swap. Polled immediately when the manager is running,
5067
- * so a just-funded swap does not wait out a whole interval.
5098
+ * Begin monitoring a swap; polled immediately when the manager is running.
5068
5099
  *
5069
- * `origin` is the request-time half a live swap cannot carry — the corridor,
5070
- * the funded address, the corridor's profile, the funding txid — and it is
5071
- * what lets the manager write this swap's FIRST record. Supply it whenever
5072
- * a {@link RfqSwapManagerDeps.repository} is wired and the swap is new. It
5073
- * may be omitted for a swap the store already holds a record for, which is
5074
- * then read to confirm it; omitting it for one the store has never seen
5075
- * throws {@link RfqSwapOriginRequired} rather than admitting a swap whose
5076
- * record could never be written. With no repository wired the parameter is
5077
- * inert.
5100
+ * @param origin - The request-time half a live swap cannot carry, needed to write its
5101
+ * FIRST record. Required with a repository wired unless the store already holds the
5102
+ * record (else {@link RfqSwapOriginRequired}). Inert without a repository.
5078
5103
  */
5079
5104
  async addSwap(swap, origin) {
5080
5105
  await this.admit(swap, origin);
5106
+ this.removed.delete(swap.rfqId);
5081
5107
  if (isRfqSwapTerminal(swap.state)) {
5082
- this.finished.set(swap.rfqId, swap);
5108
+ this.rememberFinished(swap);
5109
+ this.origins.delete(swap.rfqId);
5083
5110
  return;
5084
5111
  }
5085
5112
  this.track(swap);
5086
5113
  if (this.running) await this.pollSwap(swap);
5087
5114
  }
5088
5115
  /**
5089
- * Settle where this swap's record will come from, before it is monitored.
5090
- *
5091
- * Three ways it can be answered, in order: the caller passed an origin, one
5092
- * is already remembered from an earlier `addSwap`, or the store holds a
5093
- * record — which is the origin, already written. Only the last costs a read,
5094
- * and only when the first two are absent.
5116
+ * Settle where this swap's record will come from, before it is monitored: a passed
5117
+ * origin, one remembered from an earlier `addSwap`, or the stored record (one read).
5095
5118
  */
5096
5119
  async admit(swap, origin) {
5097
5120
  if (origin) {
@@ -5108,13 +5131,10 @@ var RfqSwapManager = class {
5108
5131
  if (!stored) throw new RfqSwapOriginRequired(swap.rfqId);
5109
5132
  this.origins.set(swap.rfqId, rfqSwapOriginOf(stored));
5110
5133
  }
5111
- /** Forget a swap entirely, monitored or finished.
5112
- *
5113
- * Its contract row is left alone: registration is a wallet-level fact about
5114
- * a script that may still hold money, and this call says only that THIS
5115
- * manager stops driving the swap. Retiring the row is reserved for a swap
5116
- * that reached a terminal state, where the lockup is provably done. */
5134
+ /** Forget a swap entirely, monitored or finished. Its contract row is left alone: the
5135
+ * script may still hold money, and only a terminal swap's row is retired. */
5117
5136
  async removeSwap(rfqId) {
5137
+ this.removed.set(rfqId, ++this.removalSeq);
5118
5138
  this.untrack(rfqId);
5119
5139
  this.finished.delete(rfqId);
5120
5140
  this.registered.delete(rfqId);
@@ -5132,14 +5152,8 @@ var RfqSwapManager = class {
5132
5152
  return [...this.monitored.values()];
5133
5153
  }
5134
5154
  /**
5135
- * Every swap this manager holds — {@link getPendingSwaps} plus the ones
5136
- * that already ended. The two sets are disjoint: a swap leaves `monitored`
5137
- * as it enters `finished`.
5138
- *
5139
- * The finished half is what this process has seen, which after
5140
- * {@link restoreFromRepository} is the stored history minus what retention
5141
- * pruned. A manager that has restored nothing answers with the live swaps
5142
- * alone.
5155
+ * Every swap this manager holds: {@link getPendingSwaps} plus the finished ones this
5156
+ * process has seen (after {@link restoreFromRepository}, the retained history).
5143
5157
  */
5144
5158
  async getAllSwaps() {
5145
5159
  return [...this.monitored.values(), ...this.finished.values()];
@@ -5151,6 +5165,7 @@ var RfqSwapManager = class {
5151
5165
  async isProcessing(rfqId) {
5152
5166
  return this.inProgress.has(rfqId);
5153
5167
  }
5168
+ /** `finishedSwaps` counts terminal swaps cached in memory, not those only in the repository. */
5154
5169
  async getStats() {
5155
5170
  return {
5156
5171
  isRunning: this.running,
@@ -5161,34 +5176,54 @@ var RfqSwapManager = class {
5161
5176
  };
5162
5177
  }
5163
5178
  /**
5164
- * Run one monitoring pass over every swap now.
5165
- *
5166
- * {@link start} calls this on an interval, but it is public on purpose: a
5167
- * caller that sleeps its process (a mobile app resuming, a service worker
5168
- * waking) wants a pass on that event rather than at the next tick. Passes
5169
- * do not overlap per swap — the in-progress lock makes a concurrent call a
5170
- * no-op for any swap already being worked on.
5179
+ * Run one monitoring pass over every swap now, e.g. when a mobile app resumes. Passes
5180
+ * do not overlap per swap: a concurrent call is a no-op for a swap already in progress.
5171
5181
  */
5172
5182
  async poll() {
5173
- await Promise.allSettled([...this.monitored.values()].map((swap) => this.pollSwap(swap)));
5183
+ await this.pollMany([...this.monitored.values()]);
5184
+ }
5185
+ async pollMany(swaps) {
5186
+ for (let i = 0; i < swaps.length; i += _RfqSwapManager.POLL_CONCURRENCY) {
5187
+ await Promise.allSettled(
5188
+ swaps.slice(i, i + _RfqSwapManager.POLL_CONCURRENCY).map((swap) => this.pollSwap(swap))
5189
+ );
5190
+ }
5191
+ }
5192
+ async acquirePollSlot() {
5193
+ if (this.activePolls < _RfqSwapManager.POLL_CONCURRENCY) {
5194
+ this.activePolls++;
5195
+ } else {
5196
+ await new Promise((resolve) => this.pollWaiters.add(resolve));
5197
+ }
5198
+ return () => {
5199
+ const next = this.pollWaiters.values().next().value;
5200
+ if (next) {
5201
+ this.pollWaiters.delete(next);
5202
+ next();
5203
+ } else {
5204
+ this.activePolls--;
5205
+ }
5206
+ };
5174
5207
  }
5175
5208
  /**
5176
- * Resolve once this swap's PAYOUT is decided — which for onchain-send is
5177
- * the L1 claim, not the end of the record's life: once `claimTxid` is set
5178
- * the trader has the coins it swapped for, and what remains is the manager
5179
- * watching the Arkade lockup close. That holds however the record is
5180
- * labelled afterwards, `needs_counterparty` included. Lightning-send has no
5181
- * such split and resolves at `settled`/`refunded`, and so does lightning
5182
- * receive — see {@link isPayoutDecided} for why its own claim txid does not
5183
- * decide it.
5209
+ * Resolve once this swap's PAYOUT is decided: for onchain-send that is the L1 claim
5210
+ * (`claimTxid` set), whatever the record's later label; otherwise `settled`/`refunded`
5211
+ * (see {@link isPayoutDecided}).
5184
5212
  *
5185
- * Rejects only on `failed`. `refunded` resolves: on a send leg a refund is
5186
- * an outcome the caller asked this manager to drive, not an exception. On a
5187
- * receive leg it is the swap being lost, which is still an answer and not
5188
- * an error — read `state`, do not infer success from resolution.
5213
+ * Rejects only on `failed`. `refunded` resolves, and on a receive leg it means the swap
5214
+ * was lost — read `state`, do not infer success from resolution.
5189
5215
  */
5190
5216
  async waitForSwapCompletion(rfqId) {
5191
5217
  const swap = this.monitored.get(rfqId) ?? this.finished.get(rfqId);
5218
+ if (!swap && !this.removed.has(rfqId) && this.deps.repository) {
5219
+ const record = await this.deps.repository.getRfqSwap(rfqId);
5220
+ if (record && !this.removed.has(rfqId) && isRfqSwapTerminal(record.state)) {
5221
+ if (record.state === "failed") {
5222
+ throw new Error(record.failure ?? `swap ${rfqId} failed`);
5223
+ }
5224
+ return outcomeOfRecord(record);
5225
+ }
5226
+ }
5192
5227
  if (!swap) throw new Error(`swap ${rfqId} is not monitored`);
5193
5228
  if (swap.state === "failed") throw new Error(swap.failure ?? `swap ${rfqId} failed`);
5194
5229
  if (isPayoutDecided(swap)) return outcomeOf(swap);
@@ -5203,11 +5238,8 @@ var RfqSwapManager = class {
5203
5238
  this.monitored.set(swap.rfqId, swap);
5204
5239
  this.byLockupScript.set(import_base15.hex.encode(swap.lockupPkScript), swap);
5205
5240
  }
5206
- /** Drops the swap from BOTH indexes. The event index is the one that stops
5207
- * a late event finding a swap that is gone; `pollSwap`'s own
5208
- * `monitored` check would also catch it, and deliberately still does —
5209
- * either alone is sufficient, which is what keeps a future change to one of
5210
- * them from silently re-driving a cancelled swap. */
5241
+ /** Drops the swap from BOTH indexes. `pollSwap`'s `monitored` check also stops a late
5242
+ * event, deliberately redundant so neither change alone re-drives a removed swap. */
5211
5243
  untrack(rfqId) {
5212
5244
  const swap = this.monitored.get(rfqId);
5213
5245
  if (swap) this.byLockupScript.delete(import_base15.hex.encode(swap.lockupPkScript));
@@ -5216,23 +5248,14 @@ var RfqSwapManager = class {
5216
5248
  this.claimedOutpoints.delete(rfqId);
5217
5249
  }
5218
5250
  /**
5219
- * Turn the indexer's push into an extra reason to run a pass — and nothing
5220
- * more.
5251
+ * Turn the indexer's push into an extra reason to run a pass — and nothing more.
5221
5252
  *
5222
- * **This is deliberately not a source of truth.** An event names a script;
5223
- * the reaction is to run the ordinary pass for the swap at that script, and
5224
- * that pass re-reads the lockup through {@link readLockupFate} exactly as
5225
- * the timer's pass does. So an event that is missed, duplicated, reordered
5226
- * or outright FORGED can only cost or save latency — it can never change
5227
- * what this manager believes about a swap, and it can never on its own
5228
- * cause a claim or a refund. That property is what makes it safe to bolt a
5229
- * best-effort stream onto a money path, and it must survive any future
5230
- * change here: the moment an event is BELIEVED rather than merely acted on,
5231
- * a relay outage becomes a correctness problem instead of a latency one.
5232
- *
5233
- * The timer stays armed regardless, and is the failsafe. Every deadline
5234
- * that moves money — `refundLocktime`, the L1 claim window — is an absolute
5235
- * timelock that passes whether or not a single event ever arrives.
5253
+ * **Deliberately not a source of truth.** The pass re-reads the lockup via
5254
+ * {@link readLockupFate}, so a missed, duplicated, reordered or FORGED event only
5255
+ * changes latency, never beliefs, and never causes a claim or refund on its own. This
5256
+ * must survive future changes: a BELIEVED event turns a relay outage into a correctness
5257
+ * bug. The timer stays armed as the failsafe; every money deadline is an absolute
5258
+ * timelock.
5236
5259
  */
5237
5260
  subscribe() {
5238
5261
  if (!this.deps.contracts || this.unsubscribeContracts) return;
@@ -5242,7 +5265,7 @@ var RfqSwapManager = class {
5242
5265
  });
5243
5266
  return;
5244
5267
  }
5245
- if (!(0, import_sdk22.isContractVtxoEvent)(event)) return;
5268
+ if (!(0, import_sdk25.isContractVtxoEvent)(event)) return;
5246
5269
  const swap = this.byLockupScript.get(event.contractScript);
5247
5270
  if (!swap) return;
5248
5271
  void this.pollSwap(swap).catch(() => {
@@ -5250,19 +5273,12 @@ var RfqSwapManager = class {
5250
5273
  });
5251
5274
  }
5252
5275
  /**
5253
- * Register this swap's lockup with the wallet's contract manager, once.
5254
- *
5255
- * The backstop, not the primary site: `requestLightningSend` /
5256
- * `requestOnchainSend` register before the caller can fund, so this covers
5257
- * swaps whose records predate that — and costs nothing when it does not,
5258
- * since `createContract` is first-writer-wins.
5276
+ * Register this swap's lockup with the wallet's contract manager, once. A backstop:
5277
+ * the request entrypoints register before funding, and `createContract` is
5278
+ * first-writer-wins.
5259
5279
  *
5260
- * Best-effort by design: a failure here is reported and retried on the next
5261
- * pass, and never aborts the pass it is part of. Registration buys latency
5262
- * and puts the lockup in the wallet's contract set; it decides nothing. The
5263
- * money path below it reads the indexer directly and is gated on timelocks
5264
- * that a missing contract row has no bearing on, so failing the pass over
5265
- * this would trade a real deadline for a bookkeeping one.
5280
+ * Best-effort: a failure is reported and retried next pass, never aborting this one.
5281
+ * Failing the pass over bookkeeping would trade a real timelock deadline for it.
5266
5282
  */
5267
5283
  async ensureRegistered(swap) {
5268
5284
  const contracts = this.deps.contracts;
@@ -5309,11 +5325,8 @@ var RfqSwapManager = class {
5309
5325
  this.emitFailed(swap, error);
5310
5326
  }
5311
5327
  }
5312
- /** Stop watching a finished swap's lockup. Retained, not deleted: the row
5313
- * is what keeps the lockup's own VTXOs annotatable and its history
5314
- * readable, while `retained` is what drops it from the subscription and
5315
- * the poll — a settled swap that stayed watched would cost the wallet a
5316
- * script for its whole life. Best-effort — the swap is over either way. */
5328
+ /** Stop watching a finished swap's lockup. `retained`, not deleted: the row keeps the
5329
+ * lockup's history readable while leaving the subscription and poll. Best-effort. */
5317
5330
  retireContract(swap) {
5318
5331
  if (!this.deps.contracts || !this.registered.get(swap.rfqId)) return;
5319
5332
  if (!LOCKUP_RETIRABLE.includes(swap.state)) return;
@@ -5328,90 +5341,36 @@ var RfqSwapManager = class {
5328
5341
  }, this.config.pollIntervalMs);
5329
5342
  }
5330
5343
  /*
5331
- * Runs one serialized monitoring pass for a single swap.
5332
- *
5333
- * Flow
5334
- *
5335
- * 1. Prevents concurrent work
5336
- * - Returns immediately if the swap is already in inProgress.
5337
- * - Returns if the swap is no longer in monitored.
5338
- * - Adds the swap ID to inProgress.
5339
- *
5340
- * 2. Runs the state machine
5341
- * - Calls runPass(swap).
5342
- * - runPass checks the lockup fate, drives claims, and may initiate refunds.
5343
- *
5344
- * 3. Persists changes
5345
- * - If the pass marked the swap dirty, calls save(swap).
5346
- * - A swap is considered persisted only if all configured sinks succeed:
5347
- * - the repository, and
5348
- * - callbacks.saveSwap, if provided.
5349
- *
5350
- * 4. Completes waiters and finalizes
5351
- * - If persistence succeeds:
5352
- * - clears the dirty flag,
5353
- * - settles waitForSwapCompletion waiters,
5354
- * - moves terminal swaps from monitored to finished,
5355
- * - emits completion or failure notifications through finalize.
5344
+ * One serialized monitoring pass for a single swap. The per-swap lock is released only
5345
+ * after all async work, so overlapping polls cannot submit duplicate claims or refunds.
5356
5346
  *
5357
- * 5. Releases the per-swap lock
5358
- * - Deletes the swap ID from inProgress only after all asynchronous work completes.
5359
- * - This prevents overlapping poll() calls from submitting duplicate claims or refunds.
5360
- *
5361
- * The important safety property is that terminal state is not finalized until its updated record has been
5362
- * successfully persisted. A failed save leaves the swap dirty and monitored so a later poll can retry.
5347
+ * Safety property: terminal state is not finalized until its record is persisted to
5348
+ * every configured sink. A failed save leaves the swap dirty and monitored for retry.
5363
5349
  */
5364
5350
  async pollSwap(swap) {
5365
5351
  if (this.inProgress.has(swap.rfqId)) return;
5366
5352
  if (!this.monitored.has(swap.rfqId)) return;
5367
5353
  this.inProgress.add(swap.rfqId);
5354
+ const release = await this.acquirePollSlot();
5368
5355
  try {
5369
- await this.runPass(swap);
5356
+ if (this.monitored.has(swap.rfqId)) await this.runPass(swap);
5370
5357
  } finally {
5371
- const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
5372
- if (persisted) {
5373
- this.dirty.delete(swap.rfqId);
5374
- this.settleWaiters(swap);
5375
- if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
5358
+ try {
5359
+ const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
5360
+ if (persisted) {
5361
+ this.dirty.delete(swap.rfqId);
5362
+ this.settleWaiters(swap);
5363
+ if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
5364
+ }
5365
+ } finally {
5366
+ this.inProgress.delete(swap.rfqId);
5367
+ release();
5376
5368
  }
5377
- this.inProgress.delete(swap.rfqId);
5378
5369
  }
5379
5370
  }
5380
5371
  /*
5381
- * executes one monitoring/state-machine pass for a swap.
5382
- *
5383
- * Flow
5384
- * 1. Registers the lockup
5385
- * - Calls ensureRegistered(swap).
5386
- * - Registration is best effort and does not prevent the rest of the pass from running.
5387
- *
5388
- * 2. Reads the Arkade lockup fate
5389
- * - Calls readLockupFate.
5390
- * - A hash-verified claim is treated as claimed.
5391
- * - A fully observed non-claim spend is treated as returned.
5392
- * - Indexer errors become unknown, allowing deadline-driven logic to continue.
5393
- * - For claimed or returned, it:
5394
- * - records spend transaction IDs,
5395
- * - records the settlement preimage when applicable,
5396
- * - sets the swap state to settled or refunded,
5397
- * - ends the pass.
5398
- *
5399
- * 3. Handles unilateral exits
5400
- * - On receive swaps, an exited lockup is blocked immediately.
5401
- * - On send swaps, the L1 half continues to be monitored because an exit only describes the Arkade side.
5402
- *
5403
- * 4. Drives the trader’s claim
5404
- * - For lightning_receive, calls driveReceiveClaim and ends the pass.
5405
- * - For onchain_send, calls driveOnchain to classify and potentially claim the L1 HTLC.
5406
- * - A handled L1 action ends the pass; otherwise processing continues.
5407
- *
5408
- * 5. Drives an Arkade refund
5409
- * - For send swaps whose lockup remains unresolved, calls driveArkadeRefund.
5410
- * - This is gated by the refund timelock and local refund capability.
5411
- * - Receive swaps never reach this step because their refund path belongs to the solver.
5412
- *
5413
- * runPass only decides and performs state-machine actions. Persistence, waiter settlement, terminal finalization,
5414
- * and the per-swap lock are handled by pollSwap.
5372
+ * One state-machine pass (steps as in the class doc). Persistence, waiters,
5373
+ * finalization and the per-swap lock belong to `pollSwap`.
5415
5374
  */
5416
5375
  async runPass(swap) {
5417
5376
  await this.ensureRegistered(swap);
@@ -5447,15 +5406,9 @@ var RfqSwapManager = class {
5447
5406
  await this.driveArkadeRefund(swap);
5448
5407
  }
5449
5408
  /**
5450
- * The lockup was unilaterally exited: its outputs sit onchain under the
5451
- * VHTLC script, where no offchain claim or refund can reach them.
5452
- *
5453
- * `needs_counterparty` rather than a terminal state, because the money still
5454
- * needs action and the swap can still end either way — an onchain claim can
5455
- * reveal the preimage, an onchain refund can return it — and that state is
5456
- * documented as re-checked every pass. It must be set from HERE and not from
5457
- * inside `driveArkadeRefund`, whose two `unblock` calls would lift it again
5458
- * on the very next pass.
5409
+ * The lockup was unilaterally exited: its outputs sit onchain, beyond any offchain
5410
+ * spend. `needs_counterparty`, not terminal: it can still end either way onchain. Set
5411
+ * here, not in `driveArkadeRefund`, whose `unblock` calls would lift it next pass.
5459
5412
  */
5460
5413
  blockExitedLockup(swap, fate) {
5461
5414
  this.block(
@@ -5464,25 +5417,15 @@ var RfqSwapManager = class {
5464
5417
  );
5465
5418
  }
5466
5419
  /**
5467
- * The receive leg's whole state machine: claim the solver-funded lockup
5468
- * while the window is open, and recognise the shapes in which it can be
5469
- * lost.
5420
+ * The receive leg's whole state machine: claim the solver-funded lockup while the
5421
+ * window is open, and recognise the shapes in which it can be lost.
5470
5422
  *
5471
- * **The window closes at `refundLocktime`, on wall clock, with no margin.**
5472
- * Both halves of that are deliberate. It closes there because publishing
5473
- * `P` into the solver's live refund window risks losing the race and
5474
- * handing over the preimage anyway — the hazard `ONCHAIN_CLAIM_MARGIN_SECONDS`
5475
- * guards on the L1 side. It takes no margin because the two situations are
5476
- * not alike: that one budgets for confirmation depth, while this claim is an
5477
- * offchain spend that lands in seconds. Wall clock is already the
5478
- * conservative reading — the solver's leaf is a CLTV, which matures against
5479
- * median-time-past, and MTP trails wall clock — so the real window extends
5480
- * PAST this deadline rather than ending before it. Every second of margin
5481
- * subtracted here is a second of live claim window given away for nothing.
5423
+ * **The window closes at `refundLocktime`, on wall clock, with no margin.** Publishing
5424
+ * `P` into the solver's live refund window risks losing the race. No margin (unlike
5425
+ * `ONCHAIN_CLAIM_MARGIN_SECONDS`, which budgets for confirmations): this offchain claim
5426
+ * lands in seconds, and the solver's CLTV matures on MTP, which trails wall clock.
5482
5427
  *
5483
- * **The trader has no move after it.** Nothing here can take the lockup
5484
- * back, so once the window shuts the swap is the solver's to resolve and
5485
- * this manager's job is to watch it happen and then stop.
5428
+ * After the window the trader has no move; the manager only watches.
5486
5429
  */
5487
5430
  async driveReceiveClaim(swap) {
5488
5431
  const now = this.config.now();
@@ -5509,14 +5452,8 @@ var RfqSwapManager = class {
5509
5452
  }
5510
5453
  this.setState(swap, "refunded");
5511
5454
  }
5512
- /**
5513
- * Claim what the solver funded, once it is enough.
5514
- *
5515
- * The value gate here decides WHEN to act. `pushClaim`'s decides whether
5516
- * `P` is published, and runs with nothing between it and the signature —
5517
- * the check that matters is the inner one, and this is not a reason to
5518
- * relax it.
5519
- */
5455
+ /** Claim what the solver funded, once it is enough (the inner gate that matters is
5456
+ * `pushClaim`'s; see {@link RfqSwapManagerCallbacks.claimLockup}). */
5520
5457
  async claimIfFunded(swap, vtxos) {
5521
5458
  if (vtxos.length === 0) return this.unblock(swap);
5522
5459
  const partiallyClaimed = swap.claimTxid !== void 0;
@@ -5555,6 +5492,14 @@ var RfqSwapManager = class {
5555
5492
  this.setState(swap, "claimed");
5556
5493
  this.emitAction(swap, "claimLockup");
5557
5494
  } catch (error) {
5495
+ const ark = (0, import_sdk25.isArkError)(error) ? error : (0, import_sdk25.maybeArkError)(error);
5496
+ if ((0, import_sdk25.isArkError)(ark, import_sdk25.ArkErrorName.VTXO_ALREADY_SPENT)) {
5497
+ if (swap.claimFailure !== void 0) {
5498
+ delete swap.claimFailure;
5499
+ this.touch(swap);
5500
+ }
5501
+ return;
5502
+ }
5558
5503
  swap.claimFailure = errorMessage(error);
5559
5504
  this.touch(swap);
5560
5505
  this.emitFailed(swap, error);
@@ -5674,8 +5619,8 @@ var RfqSwapManager = class {
5674
5619
  }
5675
5620
  }
5676
5621
  }
5677
- /** Whether any of these outputs has never been handed to the claim
5678
- * callback — the only reason to claim a lockup a second time. */
5622
+ /** Whether any output was never handed to the claim callback (the only reason to
5623
+ * claim twice). */
5679
5624
  hasUnclaimedOutpoint(rfqId, vtxos) {
5680
5625
  const claimed = this.claimedOutpoints.get(rfqId);
5681
5626
  if (!claimed) return true;
@@ -5687,20 +5632,15 @@ var RfqSwapManager = class {
5687
5632
  this.claimedOutpoints.set(rfqId, claimed);
5688
5633
  }
5689
5634
  /**
5690
- * L1 progress, which past the refund window must not overwrite a refusal.
5691
- * The two halves are independent — a claimed fill says nothing about
5692
- * whether this wallet can take the Arkade lockup back — and `claimed` is
5693
- * re-asserted from chain on every pass, so without this a blocked swap
5694
- * would flip between the two states forever. The claim itself always runs;
5695
- * only the label defers, and only once the refund is the live half.
5635
+ * L1 progress, which past the refund window must not overwrite a refusal: `claimed` is
5636
+ * re-asserted from chain every pass, so a blocked swap would flip forever. Only the
5637
+ * label defers; the claim itself always runs.
5696
5638
  */
5697
5639
  setOnchainState(swap, state) {
5698
5640
  if (swap.state === "needs_counterparty" && this.config.now() >= swap.refundLocktime) return;
5699
5641
  this.setState(swap, state);
5700
5642
  }
5701
- /** The probe's refusal reason, or `undefined` when a local refund is
5702
- * possible as far as anyone here can tell. A probe that throws is treated
5703
- * as a refusal: a capability check that cannot answer is not a yes. */
5643
+ /** The probe's refusal reason, or `undefined`. A throwing probe is a refusal. */
5704
5644
  async probeRefusal(swap) {
5705
5645
  const probe = this.callbacks?.canRefundArkade;
5706
5646
  if (!probe) return void 0;
@@ -5719,25 +5659,16 @@ var RfqSwapManager = class {
5719
5659
  }
5720
5660
  this.setState(swap, "needs_counterparty");
5721
5661
  }
5722
- /** The way back out, taken as soon as the swap becomes actionable again.
5723
- * Back to what the record can prove, not to `pending` unconditionally: a
5724
- * swap that already made its claim has a txid for it, and reporting that
5725
- * swap as `pending` would un-say something true. */
5662
+ /** The way back out once actionable: to `claimed` if a claim txid exists, else
5663
+ * `pending`. */
5726
5664
  unblock(swap) {
5727
5665
  if (swap.state !== "needs_counterparty") return;
5728
5666
  this.setState(swap, traderClaimTxid(swap) ? "claimed" : "pending");
5729
5667
  }
5730
5668
  /**
5731
- * Record which ark transactions ended the lockup.
5732
- *
5733
- * Only the ones the indexer actually named: `LockupSpend.txid` is
5734
- * optional, and a checkpoint txid is not what history correlates on — a
5735
- * record carrying one would name a transaction the wallet's own activity
5736
- * never shows. Fewer txids is the right failure here.
5737
- *
5738
- * Assigned rather than merged: the fate is one read of the whole lockup,
5739
- * so it is the complete answer for this swap, and a swap only reaches a
5740
- * verdict once.
5669
+ * Record which ark transactions ended the lockup. Only named ark txids: a checkpoint
5670
+ * txid would name a transaction the wallet's activity never shows. Assigned, not
5671
+ * merged: the fate is one complete read, reached once.
5741
5672
  */
5742
5673
  stampLockupSpends(swap, spends) {
5743
5674
  const txids = spends.map((spend) => spend.txid).filter((txid) => txid !== void 0);
@@ -5746,12 +5677,8 @@ var RfqSwapManager = class {
5746
5677
  this.touch(swap);
5747
5678
  }
5748
5679
  /**
5749
- * Keep the preimage that settled a Lightning send.
5750
- *
5751
- * Only that leg. A receive's `claimed` verdict reveals the wallet's own
5752
- * claim secret and an onchain send's reveals the one it minted — both
5753
- * already recoverable from `profile`, so stamping either would be a second
5754
- * home for a secret that has one.
5680
+ * Keep the preimage that settled a Lightning send. Only that leg: the others' preimages
5681
+ * are the wallet's own secrets, already recoverable from `profile`.
5755
5682
  */
5756
5683
  stampSettlementPreimage(swap, preimage) {
5757
5684
  if (swap.kind !== "lightning_send") return;
@@ -5785,24 +5712,9 @@ var RfqSwapManager = class {
5785
5712
  notify(this.actionExecutedListeners, (listener) => listener(swap, action));
5786
5713
  }
5787
5714
  /**
5788
- * Flush a changed record to every sink that is wired, and say whether all
5789
- * of them took it.
5790
- *
5791
- * Up to two writes, in this order: the canonical `RfqSwapRecord` to
5792
- * {@link RfqSwapManagerDeps.repository}, then
5793
- * {@link RfqSwapManagerCallbacks.saveSwap}. Both gate — a rejection from
5794
- * either leaves the record dirty and monitored, so waiters stay unsettled
5795
- * and a terminal swap is not finalized until the write it claims lands.
5796
- * That is exactly today's rule for `saveSwap`, applied to whichever sinks
5797
- * exist; wiring the repository does not weaken it.
5798
- *
5799
- * The canonical write goes FIRST and a failure there skips the second.
5800
- * `saveSwap` is a projection of the record, and projecting a state the
5801
- * record of record has just refused would leave the secondary sink ahead
5802
- * of the primary — the one ordering that survives no restart.
5803
- *
5804
- * With neither wired the state is process-local, which is what a manager
5805
- * with no callbacks has always done.
5715
+ * Flush a changed record to every wired sink; true only if all took it (else it stays
5716
+ * dirty and unfinalized). The canonical repository write goes FIRST and a failure skips
5717
+ * `saveSwap`, so the secondary sink never gets ahead of the primary.
5806
5718
  */
5807
5719
  async save(swap) {
5808
5720
  if (!await this.saveRecord(swap)) return false;
@@ -5834,18 +5746,15 @@ var RfqSwapManager = class {
5834
5746
  if (!origin) throw new RfqSwapOriginRequired(swap.rfqId);
5835
5747
  return origin;
5836
5748
  }
5837
- /**
5838
- * Drop a terminal swap from monitoring and report it exactly once.
5839
- *
5840
- * `onSwapCompleted` and `onSwapFailed` are mutually exclusive here: a
5841
- * listener named "completed" that also fires on failure is a trap, so a
5842
- * swap that leaves monitoring reports through exactly one of them.
5843
- */
5749
+ /** Drop a terminal swap from monitoring and report it exactly once, through either
5750
+ * `onSwapCompleted` or `onSwapFailed`. */
5844
5751
  finalize(swap) {
5845
5752
  if (!this.monitored.has(swap.rfqId)) return;
5846
5753
  this.untrack(swap.rfqId);
5847
- this.finished.set(swap.rfqId, swap);
5754
+ this.rememberFinished(swap, true);
5848
5755
  this.retireContract(swap);
5756
+ this.registered.delete(swap.rfqId);
5757
+ this.origins.delete(swap.rfqId);
5849
5758
  if (swap.state === "failed") {
5850
5759
  notify(
5851
5760
  this.swapFailedListeners,
@@ -5855,6 +5764,10 @@ var RfqSwapManager = class {
5855
5764
  }
5856
5765
  notify(this.swapCompletedListeners, (listener) => listener(swap));
5857
5766
  }
5767
+ rememberFinished(swap, durable = false) {
5768
+ if (durable && this.deps.repository) this.finished.delete(swap.rfqId);
5769
+ else this.finished.set(swap.rfqId, swap);
5770
+ }
5858
5771
  settleWaiters(swap) {
5859
5772
  const waiting = this.waiters.get(swap.rfqId);
5860
5773
  if (!waiting) return;
@@ -5870,16 +5783,7 @@ var RfqSwapManager = class {
5870
5783
  this.waiters.delete(swap.rfqId);
5871
5784
  }
5872
5785
  };
5873
- var traderClaimTxid = (swap) => {
5874
- switch (swap.kind) {
5875
- case "onchain_send":
5876
- return swap.claimTxid;
5877
- case "lightning_receive":
5878
- return swap.claimTxid;
5879
- default:
5880
- return void 0;
5881
- }
5882
- };
5786
+ var traderClaimTxid = (swap) => swap.kind === "onchain_send" || swap.kind === "lightning_receive" ? swap.claimTxid : void 0;
5883
5787
  var isPayoutDecided = (swap) => swap.state === "settled" || swap.state === "refunded" || swap.kind === "onchain_send" && swap.claimTxid !== void 0;
5884
5788
  var outcomeOf = (swap) => {
5885
5789
  const lostReceive = swap.kind === "lightning_receive" && swap.state === "refunded";
@@ -5888,12 +5792,21 @@ var outcomeOf = (swap) => {
5888
5792
  txid: lostReceive ? swap.refundTxid : traderClaimTxid(swap) ?? swap.refundTxid
5889
5793
  };
5890
5794
  };
5795
+ var outcomeOfRecord = (stored) => {
5796
+ const record = normalizeRfqSwapRecord(stored);
5797
+ const profileClaim = record.kind === "onchain_send" || record.kind === "lightning_receive" ? record.profile.claimTxid : void 0;
5798
+ const claimTxid = typeof profileClaim === "string" ? profileClaim : void 0;
5799
+ return {
5800
+ state: record.state,
5801
+ txid: record.kind === "lightning_receive" && record.state === "refunded" ? record.refundTxid : claimTxid ?? record.refundTxid
5802
+ };
5803
+ };
5891
5804
  var errorMessage = (error) => error instanceof Error ? error.message : String(error);
5892
5805
  var outpointKey = (vtxo) => `${vtxo.txid}:${vtxo.vout}`;
5893
5806
 
5894
5807
  // src/watch.ts
5895
5808
  var import_base16 = require("@scure/base");
5896
- var import_sdk23 = require("@arkade-os/sdk");
5809
+ var import_sdk26 = require("@arkade-os/sdk");
5897
5810
  init_coverage();
5898
5811
  init_offer();
5899
5812
  init_store();
@@ -5928,7 +5841,7 @@ async function watchOfferSwaps({
5928
5841
  wallet.getAddress(),
5929
5842
  wallet.getArkadeReader()
5930
5843
  ]);
5931
- const operatorPubkey = import_sdk23.ArkAddress.decode(address).serverPubKey;
5844
+ const operatorPubkey = import_sdk26.ArkAddress.decode(address).serverPubKey;
5932
5845
  let queue = Promise.resolve();
5933
5846
  const enqueue = (task) => {
5934
5847
  queue = queue.then(task).catch(() => {
@@ -5943,7 +5856,7 @@ async function watchOfferSwaps({
5943
5856
  return classifyDepositSpend(
5944
5857
  decodeOffer(import_base16.hex.decode(swap.offerHex)),
5945
5858
  operatorPubkey,
5946
- txs.map((psbt) => import_sdk23.Transaction.fromPSBT(import_base16.base64.decode(psbt))),
5859
+ txs.map((psbt) => import_sdk26.Transaction.fromPSBT(import_base16.base64.decode(psbt))),
5947
5860
  { txid: vtxo.txid, vout: vtxo.vout }
5948
5861
  );
5949
5862
  } catch {
@@ -5971,7 +5884,7 @@ async function watchOfferSwaps({
5971
5884
  }
5972
5885
  };
5973
5886
  const unsubscribe = manager.onContractEvent((event) => {
5974
- if (!(0, import_sdk23.isContractVtxoEvent)(event) || event.type !== "vtxo_spent") return;
5887
+ if (!(0, import_sdk26.isContractVtxoEvent)(event) || event.type !== "vtxo_spent") return;
5975
5888
  enqueue(() => handleSpend(event));
5976
5889
  });
5977
5890
  return {
@@ -6050,15 +5963,9 @@ var createSwapDrive = (config) => {
6050
5963
  const corridorStore = () => bridge ??= corridorRecordStore(
6051
5964
  storage(),
6052
5965
  remember,
6053
- // Terminal records are readable but never driven: excluding them
6054
- // here is what keeps `restoreFromRepository` from rebuilding each
6055
- // one — a covenant derivation and a contract row lookup per
6056
- // record — only to file it in the manager's `finished` set. The
6057
- // exclusion is on the manager's read, not the record: the drive's
6058
- // own `records` registry keeps every readable record, and the
6059
- // index still learns an excluded record's `rfqId` (see
6060
- // `getAllRfqSwaps`), so a consumer handing its swap to the manager
6061
- // directly keeps resolving.
5966
+ // Terminal records stay readable but are excluded from the manager's read, sparing
5967
+ // a rebuild per record just to file it `finished`. The index still learns their
5968
+ // `rfqId` (see `getRfqSwapsPage`).
6062
5969
  (r) => !undrivable.has(r.id) && !isRfqSwapTerminal(r.state)
6063
5970
  );
6064
5971
  const effectiveState = (swap) => {
@@ -6154,7 +6061,7 @@ var createSwapDrive = (config) => {
6154
6061
  const secret = rfqClaimSecretOf(record);
6155
6062
  if (!secret) throw new Error(`rfq swap ${swap.rfqId} carries no claim secret`);
6156
6063
  const preimage = await preimageForSwapRecord(wallet, secret);
6157
- const signer = await (0, import_sdk24.contractSigner)(wallet, await (0, import_sdk24.identityDescriptor)(wallet.identity));
6064
+ const signer = await (0, import_sdk27.contractSigner)(wallet, await (0, import_sdk27.identityDescriptor)(wallet.identity));
6158
6065
  const claimKey = record.profile.claimKey;
6159
6066
  if (typeof claimKey === "string") {
6160
6067
  const held = import_base17.hex.encode(await signer.xOnlyPublicKey());
@@ -6198,6 +6105,7 @@ var createSwapDrive = (config) => {
6198
6105
  }
6199
6106
  };
6200
6107
  const drivable = async (record) => !readsChain(record.kind) || await resolveOnchain();
6108
+ const pinnedNetwork = async () => (0, import_sdk27.getNetwork)(await config.network());
6201
6109
  const claimLockup = async (swap, vtxos, { partiallyClaimed }) => {
6202
6110
  const record = await corridorStore().getRfqSwap(swap.rfqId);
6203
6111
  if (!record) throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
@@ -6212,16 +6120,14 @@ var createSwapDrive = (config) => {
6212
6120
  return track(
6213
6121
  pushClaim(operator, {
6214
6122
  contract: script,
6215
- receiver: await (0, import_sdk24.contractSigner)(wallet, secret.signingDescriptor),
6123
+ receiver: await (0, import_sdk27.contractSigner)(wallet, secret.signingDescriptor),
6216
6124
  preimage: await preimageForSwapRecord(wallet, secret),
6217
6125
  vtxos,
6218
- destinationPkScript: import_sdk24.ArkAddress.decode(payoutAddress).pkScript,
6219
- // Passed straight through, both of them: the manager's own value
6220
- // check decides WHEN to act, `pushClaim`'s decides whether `P` is
6221
- // published, and it is the one with nothing between it and the
6222
- // signature.
6126
+ destinationPkScript: import_sdk27.ArkAddress.decode(payoutAddress).pkScript,
6127
+ // Passed through: `pushClaim`'s own value check decides whether `P` is published.
6223
6128
  expectedAmount: swap.expectedAmount,
6224
- partiallyClaimed
6129
+ partiallyClaimed,
6130
+ network: await pinnedNetwork()
6225
6131
  })
6226
6132
  );
6227
6133
  };
@@ -6250,7 +6156,8 @@ var createSwapDrive = (config) => {
6250
6156
  operator,
6251
6157
  contracts: lockupSource,
6252
6158
  wallet,
6253
- repository: corridorStore()
6159
+ repository: corridorStore(),
6160
+ network: pinnedNetwork
6254
6161
  });
6255
6162
  manager.setCallbacks({
6256
6163
  refundArkade: async (swap) => {
@@ -6282,23 +6189,15 @@ var createSwapDrive = (config) => {
6282
6189
  wallet.getAddress(),
6283
6190
  config.network()
6284
6191
  ]);
6285
- const txs = history.map((tx) => ({
6286
- // `TxType` is `"SENT"`/`"RECEIVED"`; the scan filters on `"sent"`.
6287
- type: String(tx.type).toLowerCase(),
6288
- redeemTxid: tx.key.arkTxid,
6289
- ...tx.key.boardingTxid ? { boardingTxid: tx.key.boardingTxid } : {},
6290
- ...tx.key.commitmentTxid ? { roundTxid: tx.key.commitmentTxid } : {},
6291
- // The scan reads unix SECONDS; a wallet transaction carries ms.
6292
- ...tx.createdAt ? { createdAt: Math.floor(tx.createdAt / 1e3) } : {}
6293
- }));
6294
- const { hrp, serverPubKey: operatorPubkey } = import_sdk24.ArkAddress.decode(address);
6192
+ const txs = history.map(toRestoreTx);
6193
+ const { hrp, serverPubKey: operatorPubkey } = import_sdk27.ArkAddress.decode(address);
6295
6194
  const cursor = reopen === void 0 ? scanned : new Set([...scanned].filter((txid) => txid !== reopen));
6296
6195
  const { restored, scannedTxids } = await restoreAssetSwaps(indexer, txs, /* @__PURE__ */ new Set(), {
6297
6196
  operatorPubkey,
6298
6197
  scanned: cursor,
6299
6198
  hrp
6300
6199
  });
6301
- const { offer } = splitRecords(await store.getAllSwapRecords());
6200
+ const { offer } = splitRecords(await collectSwapRecords(store));
6302
6201
  const current = new Map(offer.map((record) => [record.id, record]));
6303
6202
  const byDeposit = new Map(
6304
6203
  offer.filter((record) => record.fundingTxid !== void 0).map((record) => [`${record.swapPkScript}:${record.fundingTxid}`, record])
@@ -6378,7 +6277,7 @@ var createSwapDrive = (config) => {
6378
6277
  wireCallbacks();
6379
6278
  await manager.start();
6380
6279
  await markPassed();
6381
- if (!watcher && repository) {
6280
+ if (!watcher) {
6382
6281
  watcher = await watchOfferSwaps({
6383
6282
  wallet,
6384
6283
  source: offers(),
@@ -6388,7 +6287,7 @@ var createSwapDrive = (config) => {
6388
6287
  };
6389
6288
  const restore = async () => {
6390
6289
  if (!repository) return;
6391
- const all = await repository.getAllSwapRecords();
6290
+ const all = await collectSwapRecords(repository);
6392
6291
  const { corridor, offer } = splitRecords(all.filter(readableRecord));
6393
6292
  for (const record of [...corridor, ...offer]) records.set(record.id, record);
6394
6293
  const liveCorridor = corridor.filter((record) => !isRfqSwapTerminal(record.state));
@@ -6577,6 +6476,7 @@ var createSwapDrive = (config) => {
6577
6476
 
6578
6477
  // src/client/quoteOffer.ts
6579
6478
  var import_solver_discovery8 = require("@arkade-os/solver-discovery");
6479
+ init_offer();
6580
6480
 
6581
6481
  // src/client/market.ts
6582
6482
  var import_solver_discovery7 = require("@arkade-os/solver-discovery");
@@ -6590,8 +6490,9 @@ var marketKeyOf = (card) => {
6590
6490
  }
6591
6491
  return base <= quote ? `${base}/${quote}` : `${quote}/${base}`;
6592
6492
  };
6593
- var isAddressable = (card) => !(0, import_solver_discovery7.isRfqMarket)(card) || typeof card.discovery_pubkey === "string" && (card.transports?.nostr?.relays?.length ?? 0) > 0;
6594
- var marketBackendOf = (card) => (0, import_solver_discovery7.isRfqMarket)(card) ? "rfq" : "feed";
6493
+ var hasRendezvous = (card) => typeof card.discovery_pubkey === "string" && (card.transports?.nostr?.relays?.length ?? 0) > 0;
6494
+ var isAddressable = (card) => !(0, import_solver_discovery7.isRfqMarket)(card) || hasRendezvous(card);
6495
+ var marketBackendOf = (card) => (0, import_solver_discovery7.isRfqMarket)(card) || hasRendezvous(card) ? "rfq" : "feed";
6595
6496
  var usableMarkets = (snapshot, policy) => {
6596
6497
  const allowed = policy?.allowedRegistries;
6597
6498
  return (allowed ? snapshot.markets.filter((card) => allowed.includes(card.source)) : snapshot.markets).filter(isAddressable);
@@ -6604,8 +6505,7 @@ var eligibleMarkets = (snapshot, legs, policy, takeAmount) => {
6604
6505
  const base = side === "base" ? give : take;
6605
6506
  const quote = side === "base" ? take : give;
6606
6507
  const selection = {
6607
- // The trader receives the take leg, so that side must be one the
6608
- // solver can pay out; a direction nobody solves yields no market.
6508
+ // The trader receives the take leg, so the solver must be able to pay that side out.
6609
6509
  wantSide: side === "base" ? "quote" : "base",
6610
6510
  ...takeAmount === void 0 ? {} : { wantAmount: takeAmount }
6611
6511
  };
@@ -6619,9 +6519,7 @@ var eligibleMarkets = (snapshot, legs, policy, takeAmount) => {
6619
6519
  quoteId: `${quote.corridor}:${quote.assetId}`,
6620
6520
  ...selection
6621
6521
  });
6622
- const selected = [...canonical, ...legacy].filter(
6623
- (card, index, all) => all.indexOf(card) === index
6624
- );
6522
+ const selected = [.../* @__PURE__ */ new Set([...canonical, ...legacy])];
6625
6523
  return selected.map((card) => ({
6626
6524
  card,
6627
6525
  give: side,
@@ -6674,16 +6572,16 @@ var assembleRoute = (give, take) => {
6674
6572
  }
6675
6573
  return { give, take };
6676
6574
  };
6677
- var endpoint = (corridor, asset6, instrument) => ({
6575
+ var endpoint = (corridor, asset7, instrument) => ({
6678
6576
  corridor,
6679
- asset: asset6,
6577
+ asset: asset7,
6680
6578
  ...instrument === void 0 ? {} : { instrument }
6681
6579
  });
6682
- var legFor = (asset6, expected) => {
6683
- const leg = toDiscoveryLeg(asset6);
6580
+ var legFor = (asset7, expected) => {
6581
+ const leg = toDiscoveryLeg(asset7);
6684
6582
  if (expected !== void 0 && leg.corridor !== expected) {
6685
6583
  throw new UnsupportedRoute(
6686
- `${asset6} settles on ${leg.corridor}, and this leg is ${expected}`,
6584
+ `${asset7} settles on ${leg.corridor}, and this leg is ${expected}`,
6687
6585
  { give: leg.corridor, take: expected }
6688
6586
  );
6689
6587
  }
@@ -6765,11 +6663,9 @@ var resolveRoute = async (input, deps) => {
6765
6663
  aliases
6766
6664
  };
6767
6665
  };
6768
- var isCorridor = (value) => value === "arkade" || value === "lightning" || value === "onchain";
6666
+ var isCorridor = (value) => CORRIDORS.includes(value);
6769
6667
  var assetFor = (ref, corridor, network, aliases) => ref === void 0 ? btcOn(railOfCorridor(corridor), network) : (
6770
- // Scoped to the leg's rail, because BTC has one id per rail and a
6771
- // whole-table lookup would refuse `"BTC"` as ambiguous on any snapshot
6772
- // carrying a corridor market — see `scopedToRail`.
6668
+ // Rail-scoped: BTC has one id per rail, so a whole-table `"BTC"` is ambiguous.
6773
6669
  canonicalAssetId(ref, scopedToRail(aliases, railOfCorridor(corridor)))
6774
6670
  );
6775
6671
  var pinAmount = (input, takeInstrument) => {
@@ -6943,22 +6839,48 @@ var verifyQuoteTtl = (input) => {
6943
6839
  }
6944
6840
  };
6945
6841
  var verifyQuotedAmount = (input) => {
6946
- const quoted = input.pinned.on === "give" ? input.give : input.take;
6947
- if (quoted !== input.pinned.value) {
6842
+ verifyPinnedAmount(input);
6843
+ if (input.take > input.give) {
6948
6844
  throw new QuoteVerificationFailed(
6949
6845
  "pair",
6950
- `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
6951
- `${input.pair} ${input.pinned.on}=${quoted}`
6846
+ `${input.pair} give >= take`,
6847
+ `give=${input.give} take=${input.take}`
6952
6848
  );
6953
6849
  }
6954
- if (input.take > input.give) {
6850
+ };
6851
+ var verifyCrossAssetAmount = (input) => {
6852
+ verifyPinnedAmount(input);
6853
+ if (input.give <= 0n || input.take <= 0n) {
6955
6854
  throw new QuoteVerificationFailed(
6956
6855
  "pair",
6957
- `${input.pair} give >= take`,
6856
+ `${input.pair} give > 0 take > 0`,
6958
6857
  `give=${input.give} take=${input.take}`
6959
6858
  );
6960
6859
  }
6961
6860
  };
6861
+ var verifiedCarrierSats = (quote) => {
6862
+ try {
6863
+ return quoteCarrierSats(quote);
6864
+ } catch (error) {
6865
+ if (reasonOf(error) !== "carrier_malformed") throw error;
6866
+ throw new QuoteVerificationFailed(
6867
+ "pair",
6868
+ "carrier_sats a non-negative integer",
6869
+ String(quote.carrier_sats),
6870
+ { cause: error }
6871
+ );
6872
+ }
6873
+ };
6874
+ var verifyPinnedAmount = (input) => {
6875
+ const quoted = input.pinned.on === "give" ? input.give : input.take;
6876
+ if (quoted !== input.pinned.value) {
6877
+ throw new QuoteVerificationFailed(
6878
+ "pair",
6879
+ `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
6880
+ `${input.pair} ${input.pinned.on}=${quoted}`
6881
+ );
6882
+ }
6883
+ };
6962
6884
 
6963
6885
  // src/client/quoteOffer.ts
6964
6886
  var FEED_TTL_MS = 3e4;
@@ -6978,6 +6900,9 @@ var quoteFromFeed = async (input) => {
6978
6900
  const plan = await (0, import_solver_discovery8.quoteOffer)(candidate.card, {
6979
6901
  give: candidate.give,
6980
6902
  ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
6903
+ // What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
6904
+ // for it back in a BTC payout, and charges it where the card declares a delivered carrier.
6905
+ carrierSats: ASSET_CARRIER_SATS,
6981
6906
  ...QUOTE_OPTIONS,
6982
6907
  fetchImpl: input.feed.fetch
6983
6908
  });
@@ -7001,12 +6926,21 @@ var quoteFromFeed = async (input) => {
7001
6926
  take: { asset: input.endpoints.take.asset, amount: plan.receive.atomic },
7002
6927
  market: input.market,
7003
6928
  expiresAt,
7004
- fee: { amount: spreadOf(plan), asset: input.endpoints.take.asset }
6929
+ fee: {
6930
+ // The plan's payout returns the deposit's carrier; that part is not proceeds.
6931
+ amount: feedSpread(
6932
+ plan,
6933
+ plan.receive.atomic,
6934
+ sellsAssetForBtc(input.endpoints) ? ASSET_CARRIER_SATS : 0n
6935
+ ),
6936
+ asset: input.endpoints.take.asset
6937
+ }
7005
6938
  },
7006
6939
  preparation: { backend: "feed", card: candidate.card, plan, give: candidate.give }
7007
6940
  };
7008
6941
  };
7009
- var spreadOf = (plan) => {
6942
+ var feedSpread = (plan, take, carrierSats = 0n) => {
6943
+ const payout = take > carrierSats ? take - carrierSats : 0n;
7010
6944
  const fair = (0, import_solver_discovery8.computeWantAmount)({
7011
6945
  deposit: plan.deposit.atomic,
7012
6946
  give: plan.give,
@@ -7014,35 +6948,44 @@ var spreadOf = (plan) => {
7014
6948
  feeBps: 0,
7015
6949
  safetyBps: 0
7016
6950
  });
7017
- const spread = fair - plan.receive.atomic;
6951
+ const spread = fair - payout;
7018
6952
  return spread > 0n ? spread : 0n;
7019
6953
  };
6954
+ var sellsAssetForBtc = (endpoints) => assetPartOf(endpoints.give.asset) !== BTC_ASSET_PART && assetPartOf(endpoints.take.asset) === BTC_ASSET_PART;
7020
6955
  var feedExpiry = (card, feed, now) => {
7021
6956
  const readAt = card.price_feed === void 0 ? void 0 : feed.fetchedAt(card.price_feed);
7022
6957
  const from = readAt === void 0 ? now : Math.floor(readAt / 1e3);
7023
6958
  return from + FEED_TTL_MS / 1e3;
7024
6959
  };
7025
6960
  var verifyPlanLegs = (plan, legs, give) => {
7026
- const expected = `${legs.give.assetId}->${legs.take.assetId}`;
7027
- const priced = `${plan.deposit.asset.id}->${plan.receive.asset.id}`;
7028
- if (expected !== priced || plan.give !== give) {
7029
- throw new QuoteVerificationFailed("pair", expected, priced);
6961
+ const take = give === "base" ? "quote" : "base";
6962
+ const spelled = (side) => (0, import_solver_discovery8.marketLegKey)(plan.market, side);
6963
+ const names = (side, leg) => spelled(side) === leg.marketId || spelled(side) === `${leg.corridor}:${leg.assetId}`;
6964
+ if (plan.give !== give || !names(give, legs.give) || !names(take, legs.take)) {
6965
+ throw new QuoteVerificationFailed(
6966
+ "pair",
6967
+ `${legs.give.marketId}->${legs.take.marketId}`,
6968
+ `${spelled(give)}->${spelled(take)}`
6969
+ );
7030
6970
  }
7031
6971
  };
7032
6972
 
7033
6973
  // src/client/quoteRfq.ts
7034
6974
  var import_base18 = require("@scure/base");
7035
- var import_sdk27 = require("@arkade-os/sdk");
6975
+ var import_sdk30 = require("@arkade-os/sdk");
6976
+ var import_solver_discovery9 = require("@arkade-os/solver-discovery");
7036
6977
  init_claimPacket();
6978
+ init_offer();
6979
+ init_store();
7037
6980
  init_onchainHtlc();
7038
6981
  init_onchainHtlc();
7039
6982
 
7040
6983
  // src/payment/onchainSwap.ts
7041
- var import_sdk26 = require("@arkade-os/sdk");
6984
+ var import_sdk29 = require("@arkade-os/sdk");
7042
6985
  init_onchainHtlc();
7043
6986
 
7044
6987
  // src/payment/swapRail.ts
7045
- var import_sdk25 = require("@arkade-os/sdk");
6988
+ var import_sdk28 = require("@arkade-os/sdk");
7046
6989
 
7047
6990
  // src/client/sats.ts
7048
6991
  var satsOf = (value, field) => {
@@ -7093,15 +7036,19 @@ var parseRfqQuote = (quote) => ({
7093
7036
  });
7094
7037
 
7095
7038
  // src/client/quoteRfq.ts
7039
+ var lockupOf = (derived) => ({
7040
+ address: derived.address,
7041
+ script: derived.script,
7042
+ pkScript: derived.swapPkScript
7043
+ });
7096
7044
  var covenantInputs = (input) => {
7097
- const network = (0, import_sdk27.networkFromArkadeInfo)(input.info);
7045
+ const network = (0, import_sdk30.networkFromArkadeInfo)(input.info);
7098
7046
  const arkade2 = input.corridors.get("arkade").deps;
7099
7047
  return {
7100
- operatorPubkey: (0, import_sdk27.toXOnly)(import_base18.hex.decode(input.info.signerPubkey), "ark signer key"),
7101
- // The per-network pin the arkade module already resolved, never a key
7102
- // the operator reports about itself: this one ends up in a covenant leaf
7048
+ operatorPubkey: (0, import_sdk30.toXOnly)(import_base18.hex.decode(input.info.signerPubkey), "ark signer key"),
7049
+ // The resolved per-network pin, never operator-reported: it lands in a covenant leaf
7103
7050
  // that decides who can move the funds.
7104
- emulatorPubkey: (0, import_sdk27.toXOnly)(import_base18.hex.decode(arkade2.emulatorPubkey), "emulator signer key"),
7051
+ emulatorPubkey: (0, import_sdk30.toXOnly)(import_base18.hex.decode(arkade2.emulatorPubkey), "emulator signer key"),
7105
7052
  claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
7106
7053
  hrp: network.hrp
7107
7054
  };
@@ -7130,6 +7077,8 @@ var quoteViaRfq = async (input) => {
7130
7077
  pinnable: input.market.snapshot.live
7131
7078
  });
7132
7079
  switch (input.route) {
7080
+ case "arkade->arkade":
7081
+ return quoteArkadeAsset(input);
7133
7082
  case "arkade->lightning":
7134
7083
  return quoteLightningSend(input);
7135
7084
  case "lightning->arkade":
@@ -7138,6 +7087,113 @@ var quoteViaRfq = async (input) => {
7138
7087
  return quoteOnchainSend(input);
7139
7088
  }
7140
7089
  };
7090
+ var quoteArkadeAsset = async (input) => {
7091
+ const pinned = pinnedFor(input);
7092
+ if (pinned.on !== "give") {
7093
+ throw new Error(
7094
+ "an asset swap is exact-in: pin the amount on the give leg. The legs carry different assets, so there is no spread to price a take-side pin back through \u2014 the solver answers `exact_out_unsupported`"
7095
+ );
7096
+ }
7097
+ const sides = assetSidesOf(input.legs);
7098
+ if (input.candidate.card.price_feed === void 0) {
7099
+ throw new UnsupportedRoute(
7100
+ `card ${input.candidate.card.solver} advertises no price feed to measure an asset swap's fee against`,
7101
+ { give: "arkade", take: "arkade" }
7102
+ );
7103
+ }
7104
+ const pair = rfqPairFor(input.legs.give, input.legs.take);
7105
+ const rfqId = newRfqId();
7106
+ const maker = await makerPosition(input.wallet);
7107
+ const wire = await input.transport.requestQuote(
7108
+ arkadeSwapRequest({
7109
+ rfqId,
7110
+ ...sides,
7111
+ amount: pinned.value,
7112
+ makerPkScript: maker.pkScript,
7113
+ makerPublicKey: maker.publicKey
7114
+ })
7115
+ );
7116
+ verifyPair(wire.pair, pair);
7117
+ const parsed = parseRfqQuote(wire);
7118
+ verifyCrossAssetAmount({ pair, pinned, give: parsed.give, take: parsed.take });
7119
+ verifyQuoteTtl({
7120
+ quoteId: input.quoteId,
7121
+ expiresAt: parsed.validUntil,
7122
+ now: input.now,
7123
+ floorSeconds: input.policy?.quoteTtlFloorSeconds
7124
+ });
7125
+ const carrierSats = sides.offerAsset === void 0 ? void 0 : verifiedCarrierSats(wire);
7126
+ const reference = await (0, import_solver_discovery9.quoteOffer)(input.candidate.card, {
7127
+ give: input.candidate.give,
7128
+ giveAmount: parsed.give,
7129
+ ...carrierSats === void 0 ? {} : { carrierSats },
7130
+ ...QUOTE_OPTIONS,
7131
+ fetchImpl: input.feed.fetch
7132
+ });
7133
+ verifyPlanLegs(reference, input.legs, input.candidate.give);
7134
+ const terms = offerTermsFromQuote(wire, sides);
7135
+ const offer = await deriveOffer(input.wallet, {
7136
+ wantAmount: terms.wantAmount,
7137
+ ...terms.wantAsset === void 0 ? {} : { wantAsset: terms.wantAsset },
7138
+ ...terms.offerAsset === void 0 ? {} : { offerAsset: terms.offerAsset },
7139
+ emulatorPubkey: input.corridors.get("arkade").deps.emulatorPubkey,
7140
+ maker,
7141
+ info: input.info
7142
+ });
7143
+ verifyingDerivation(() => verifyOfferAddress(wire, offer));
7144
+ return {
7145
+ quote: {
7146
+ id: input.quoteId,
7147
+ route: assembleRoute(
7148
+ { ...input.endpoints.give, instrument: { kind: "wallet" } },
7149
+ { ...input.endpoints.take, instrument: { kind: "wallet" } }
7150
+ ),
7151
+ give: { asset: input.endpoints.give.asset, amount: parsed.give },
7152
+ take: { asset: input.endpoints.take.asset, amount: parsed.take },
7153
+ market: input.market,
7154
+ solver: parsed.solver,
7155
+ expiresAt: parsed.validUntil,
7156
+ // Exactly one leg is BTC, so an asset deposit's carrier is on the payout's unit.
7157
+ fee: {
7158
+ amount: feedSpread(reference, parsed.take, carrierSats),
7159
+ asset: input.endpoints.take.asset
7160
+ }
7161
+ },
7162
+ preparation: {
7163
+ backend: "rfq",
7164
+ route: "arkade->arkade",
7165
+ card: input.candidate.card,
7166
+ rfqId,
7167
+ wire: parsed,
7168
+ offer,
7169
+ ...carrierSats === void 0 ? {} : { carrierSats }
7170
+ }
7171
+ };
7172
+ };
7173
+ var assetSidesOf = (legs) => {
7174
+ const giveIsBtc = legs.give.assetId === BTC_ASSET_ID;
7175
+ const takeIsBtc = legs.take.assetId === BTC_ASSET_ID;
7176
+ if (giveIsBtc && takeIsBtc) {
7177
+ throw new UnsupportedRoute("arkade:BTC -> arkade:BTC moves one asset, it swaps nothing", {
7178
+ give: "arkade",
7179
+ take: "arkade"
7180
+ });
7181
+ }
7182
+ if (!giveIsBtc && !takeIsBtc) {
7183
+ throw new UnsupportedRoute(
7184
+ `arkade:${legs.give.assetId} -> arkade:${legs.take.assetId}: an asset swap prices one asset against BTC, so exactly one leg must be BTC`,
7185
+ { give: "arkade", take: "arkade" }
7186
+ );
7187
+ }
7188
+ return giveIsBtc ? { wantAsset: import_sdk30.asset.AssetId.fromString(legs.take.assetId) } : { offerAsset: import_sdk30.asset.AssetId.fromString(legs.give.assetId) };
7189
+ };
7190
+ var makerPosition = async (wallet) => {
7191
+ const [address, publicKey] = await Promise.all([
7192
+ wallet.getAddress(),
7193
+ wallet.identity.xOnlyPublicKey()
7194
+ ]);
7195
+ return { pkScript: import_sdk30.ArkAddress.decode(address).pkScript, publicKey };
7196
+ };
7141
7197
  var quoteLightningSend = async (input) => {
7142
7198
  const invoice = input.endpoints.take.instrument;
7143
7199
  if (invoice?.kind !== "invoice" || invoice.amount === void 0) {
@@ -7145,7 +7201,7 @@ var quoteLightningSend = async (input) => {
7145
7201
  }
7146
7202
  const pair = rfqPairFor(input.legs.give, input.legs.take);
7147
7203
  const rfqId = newRfqId();
7148
- const secrets = await (0, import_sdk27.provisionRefundKey)(input.wallet);
7204
+ const secrets = await (0, import_sdk30.provisionRefundKey)(input.wallet);
7149
7205
  const wire = await input.transport.requestQuote(
7150
7206
  lightningSendRequest({
7151
7207
  rfqId,
@@ -7202,11 +7258,7 @@ var quoteLightningSend = async (input) => {
7202
7258
  card: input.candidate.card,
7203
7259
  rfqId,
7204
7260
  wire: parsed,
7205
- lockup: {
7206
- address: derived.address,
7207
- script: derived.script,
7208
- pkScript: derived.swapPkScript
7209
- },
7261
+ lockup: lockupOf(derived),
7210
7262
  contractParams: derived.contractParams,
7211
7263
  secrets,
7212
7264
  refundAddress: secrets.address,
@@ -7218,7 +7270,7 @@ var quoteLightningReceive = async (input) => {
7218
7270
  const pinned = pinnedFor(input);
7219
7271
  const pair = rfqPairFor(input.legs.give, input.legs.take);
7220
7272
  const rfqId = newRfqId();
7221
- const secrets = await (0, import_sdk27.provisionClaimSecret)(input.wallet);
7273
+ const secrets = await (0, import_sdk30.provisionClaimSecret)(input.wallet);
7222
7274
  const paymentHash = import_base18.hex.encode(secrets.paymentHash);
7223
7275
  const payoutAddress = await input.wallet.getAddress();
7224
7276
  const lightning = input.corridors.get("lightning").deps;
@@ -7232,9 +7284,7 @@ var quoteLightningReceive = async (input) => {
7232
7284
  payoutAddress,
7233
7285
  payoutPubkey: secrets.pubkey,
7234
7286
  claimPacket: claimPacket?.packet,
7235
- // Placeholder: the v1 builders type this field `number`, and the
7236
- // wire adapter re-encodes it as the canonical decimal string.
7237
- // Encoding it here as well would put the decision in two places.
7287
+ // Placeholder: `withCanonicalAmount` writes the canonical decimal string.
7238
7288
  amount: 0,
7239
7289
  amountSide: toRfqAmountSide(pinned.on)
7240
7290
  }),
@@ -7251,10 +7301,7 @@ var quoteLightningReceive = async (input) => {
7251
7301
  paymentHash,
7252
7302
  payoutPubkey: secrets.pubkey,
7253
7303
  payoutAddress,
7254
- operatorPubkey: covenant.operatorPubkey,
7255
- emulatorPubkey: covenant.emulatorPubkey,
7256
- claimDelay: covenant.claimDelay,
7257
- hrp: covenant.hrp
7304
+ ...covenant
7258
7305
  })
7259
7306
  );
7260
7307
  const { payDeadline } = verifyReceiveInvoiceFacts({
@@ -7272,9 +7319,7 @@ var quoteLightningReceive = async (input) => {
7272
7319
  });
7273
7320
  verifyQuoteTtl({
7274
7321
  quoteId: input.quoteId,
7275
- // The hold invoice's window is minutes where the quote's is an hour, so
7276
- // the deadline that binds this leg is the earlier of the two — which is
7277
- // what `payDeadline` already is.
7322
+ // The hold invoice's window (minutes) binds, not the quote's (an hour).
7278
7323
  expiresAt: payDeadline,
7279
7324
  now: input.now,
7280
7325
  floorSeconds: input.policy?.quoteTtlFloorSeconds
@@ -7312,11 +7357,7 @@ var quoteLightningReceive = async (input) => {
7312
7357
  card: input.candidate.card,
7313
7358
  rfqId,
7314
7359
  wire: parsed,
7315
- lockup: {
7316
- address: derived.address,
7317
- script: derived.script,
7318
- pkScript: derived.swapPkScript
7319
- },
7360
+ lockup: lockupOf(derived),
7320
7361
  contractParams: derived.contractParams,
7321
7362
  secrets,
7322
7363
  payoutAddress,
@@ -7341,8 +7382,8 @@ var quoteOnchainSend = async (input) => {
7341
7382
  claimVsize: onchain.claimVsize
7342
7383
  }) : void 0;
7343
7384
  const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
7344
- const secrets = await (0, import_sdk27.provisionClaimSecret)(input.wallet);
7345
- const payoutKey = await (0, import_sdk27.provisionRefundKey)(input.wallet);
7385
+ const secrets = await (0, import_sdk30.provisionClaimSecret)(input.wallet);
7386
+ const payoutKey = await (0, import_sdk30.provisionRefundKey)(input.wallet);
7346
7387
  const paymentHash = import_base18.hex.encode(secrets.paymentHash);
7347
7388
  const wire = await input.transport.requestQuote(
7348
7389
  withCanonicalAmount(
@@ -7355,9 +7396,6 @@ var quoteOnchainSend = async (input) => {
7355
7396
  amount: 0,
7356
7397
  amountSide: toRfqAmountSide(pinned.on)
7357
7398
  }),
7358
- // The grossed pin, when one is active — see above. The solver's
7359
- // obligation is the HTLC amount; the recipient's own amount is
7360
- // that minus the claim's fee.
7361
7399
  quoted.value
7362
7400
  )
7363
7401
  );
@@ -7378,10 +7416,7 @@ var quoteOnchainSend = async (input) => {
7378
7416
  quote: wire,
7379
7417
  paymentHash,
7380
7418
  payoutPubkey: payoutKey.pubkey,
7381
- operatorPubkey: covenant.operatorPubkey,
7382
- emulatorPubkey: covenant.emulatorPubkey,
7383
- claimDelay: covenant.claimDelay,
7384
- hrp: covenant.hrp,
7419
+ ...covenant,
7385
7420
  l1Network,
7386
7421
  refundAddress: payoutKey.address,
7387
7422
  senderPubkey: secrets.pubkey
@@ -7403,8 +7438,8 @@ var quoteOnchainSend = async (input) => {
7403
7438
  now: input.now,
7404
7439
  floorSeconds: input.policy?.quoteTtlFloorSeconds
7405
7440
  });
7406
- const reportedTake = claimFee === void 0 ? parsed.take : parsed.take - claimFee;
7407
- const reportedFee = claimFee === void 0 ? parsed.give - parsed.take : parsed.give - parsed.take + claimFee;
7441
+ const reportedTake = parsed.take - (claimFee ?? 0n);
7442
+ const reportedFee = parsed.give - parsed.take + (claimFee ?? 0n);
7408
7443
  return {
7409
7444
  quote: {
7410
7445
  id: input.quoteId,
@@ -7418,9 +7453,7 @@ var quoteOnchainSend = async (input) => {
7418
7453
  market: input.market,
7419
7454
  solver: parsed.solver,
7420
7455
  expiresAt: parsed.validUntil,
7421
- // Read off the derivation and not off the wire: the field is
7422
- // optional there, a solver may carry it in the profile instead, and
7423
- // the derivation is what settles which one this covenant used.
7456
+ // Off the derivation, not the wire: it settles which locktime this covenant used.
7424
7457
  refundLocktime: derived.refundLocktime,
7425
7458
  fee: { amount: reportedFee, asset: input.endpoints.give.asset }
7426
7459
  },
@@ -7430,17 +7463,11 @@ var quoteOnchainSend = async (input) => {
7430
7463
  card: input.candidate.card,
7431
7464
  rfqId,
7432
7465
  wire: parsed,
7433
- lockup: {
7434
- address: derived.address,
7435
- script: derived.script,
7436
- pkScript: derived.swapPkScript
7437
- },
7466
+ lockup: lockupOf(derived),
7438
7467
  secrets,
7439
7468
  refundAddress: payoutKey.address,
7440
7469
  fundAmount: parsed.give,
7441
- // The gross wire leg, not `reportedTake`: the claim fee comes out of
7442
- // the HTLC output, so netting it here would accept an HTLC funded
7443
- // short by exactly that fee.
7470
+ // Gross, not `reportedTake`: netting would accept an HTLC short by the fee.
7444
7471
  expectedAmount: parsed.take,
7445
7472
  payoutKey,
7446
7473
  payoutPkScript,
@@ -7453,7 +7480,7 @@ var quoteOnchainSend = async (input) => {
7453
7480
  };
7454
7481
 
7455
7482
  // src/client/verbs.ts
7456
- var import_sdk28 = require("@arkade-os/sdk");
7483
+ var import_sdk31 = require("@arkade-os/sdk");
7457
7484
  var enforceFeeCeiling = (quote, call, policy) => {
7458
7485
  let ceiling;
7459
7486
  for (const [source, limit] of [
@@ -7478,9 +7505,9 @@ var settle = async (deps, input, maxFee) => {
7478
7505
  return deps.accept(quote);
7479
7506
  };
7480
7507
  var pay = async (deps, destination, options = {}) => {
7481
- const arkade2 = (0, import_sdk28.arkTarget)(destination);
7508
+ const arkade2 = (0, import_sdk31.arkTarget)(destination);
7482
7509
  if (arkade2 !== void 0) {
7483
- const amount = (0, import_sdk28.resolveSendAmount)(
7510
+ const amount = (0, import_sdk31.resolveSendAmount)(
7484
7511
  "ark",
7485
7512
  destination,
7486
7513
  options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
@@ -7491,9 +7518,7 @@ var pay = async (deps, destination, options = {}) => {
7491
7518
  deps,
7492
7519
  {
7493
7520
  to: destination,
7494
- // `amountOn: "take"` because the number a caller writes beside a
7495
- // destination is what the recipient gets. An invoice pins the same
7496
- // leg by existing, which is why passing both is `AmountMismatch`.
7521
+ // The amount beside a destination is what the recipient gets.
7497
7522
  ...options.amount === void 0 ? {} : { amount: options.amount, amountOn: "take" }
7498
7523
  },
7499
7524
  options.maxFee
@@ -7507,8 +7532,7 @@ var receive = async (deps, options) => {
7507
7532
  via: options.via,
7508
7533
  ...options.asset === void 0 ? {} : { take: options.asset },
7509
7534
  amount: options.amount,
7510
- // The trader's side is the take leg: `receive({ amount })` is
7511
- // "credit me this much", not "let the payer send this much".
7535
+ // "Credit me this much", not "let the payer send this much".
7512
7536
  amountOn: "take"
7513
7537
  },
7514
7538
  options.maxFee
@@ -7601,10 +7625,8 @@ var createSwapClient = (config) => {
7601
7625
  };
7602
7626
  const remember = (id, preparation) => {
7603
7627
  preparations.set(id, preparation);
7604
- while (preparations.size > PREPARATIONS_HELD) {
7605
- const oldest = preparations.keys().next();
7606
- if (oldest.done) break;
7607
- preparations.delete(oldest.value);
7628
+ if (preparations.size > PREPARATIONS_HELD) {
7629
+ preparations.delete(preparations.keys().next().value);
7608
7630
  }
7609
7631
  };
7610
7632
  const client = {
@@ -7638,7 +7660,7 @@ var createSwapClient = (config) => {
7638
7660
  corridors.get(resolvedRoute.legs.take.corridor);
7639
7661
  const quoteId = mintQuoteId();
7640
7662
  const now = Math.floor(Date.now() / 1e3);
7641
- if (resolvedRoute.pair === "arkade->arkade") {
7663
+ if (market.backend === "feed") {
7642
7664
  const { quote, preparation } = await quoteFromFeed({
7643
7665
  quoteId,
7644
7666
  candidate: market,
@@ -7676,6 +7698,7 @@ var createSwapClient = (config) => {
7676
7698
  info,
7677
7699
  corridors,
7678
7700
  transport,
7701
+ feed,
7679
7702
  ...config.policy === void 0 ? {} : { policy: config.policy },
7680
7703
  now
7681
7704
  });
@@ -7723,7 +7746,7 @@ var createSwapClient = (config) => {
7723
7746
  if (repository === void 0) return [];
7724
7747
  const drive2 = driving();
7725
7748
  await drive2.ready;
7726
- const records = await repository.getAllSwapRecords();
7749
+ const records = await collectSwapRecords(repository);
7727
7750
  const swaps = [];
7728
7751
  for (const record of records) {
7729
7752
  if (!readableRecord(record)) continue;
@@ -7763,9 +7786,7 @@ var createSwapClient = (config) => {
7763
7786
  ensureLive("ready");
7764
7787
  return driving().ready;
7765
7788
  },
7766
- // `async`, so the refusal is a rejection rather than a synchronous
7767
- // throw: these are declared `Promise<void>` and a caller is entitled to
7768
- // `.catch()` them.
7789
+ // `async` so the refusal is a rejection, as the `Promise<void>` signature promises
7769
7790
  start: async () => {
7770
7791
  ensureLive("start");
7771
7792
  return driving().start();
@@ -7799,10 +7820,9 @@ var createSwapClient = (config) => {
7799
7820
 
7800
7821
  // src/reveal.ts
7801
7822
  var import_base20 = require("@scure/base");
7802
- var import_legacy4 = require("@noble/hashes/legacy.js");
7803
- var import_sha26 = require("@noble/hashes/sha2.js");
7804
- var import_sdk29 = require("@arkade-os/sdk");
7823
+ var import_sdk32 = require("@arkade-os/sdk");
7805
7824
  init_claimPacket();
7825
+ init_onchainHtlc();
7806
7826
  var CovclaimdRevealError = class extends Error {
7807
7827
  name = "CovclaimdRevealError";
7808
7828
  status;
@@ -7906,12 +7926,10 @@ function revealFieldsFromScript(script) {
7906
7926
  }
7907
7927
  async function revealClaimPacket(client, input) {
7908
7928
  const fields = revealFieldsFromScript(input.script);
7909
- if (import_base20.hex.encode(import_sdk29.ArkAddress.decode(input.address).pkScript) !== import_base20.hex.encode(input.script.pkScript)) {
7929
+ if (import_base20.hex.encode(import_sdk32.ArkAddress.decode(input.address).pkScript) !== import_base20.hex.encode(input.script.pkScript)) {
7910
7930
  throw new Error("address does not belong to this covenant");
7911
7931
  }
7912
- if (import_base20.hex.encode((0, import_legacy4.ripemd160)((0, import_sha26.sha256)(input.preimage))) !== import_base20.hex.encode(input.script.options.preimageHash)) {
7913
- throw new Error("preimage does not match the covenant's payment hash");
7914
- }
7932
+ assertPreimageMatches(input.preimage, input.script.options.preimageHash);
7915
7933
  const { ciphertext } = await sealClaimPacket({
7916
7934
  preimage: input.preimage,
7917
7935
  covclaimdPubkey: (await client.info()).covclaimdPubkey
@@ -7999,6 +8017,7 @@ async function revealClaimPacket(client, input) {
7999
8017
  familyOfSwapId,
8000
8018
  fateMoved,
8001
8019
  feedFetch,
8020
+ feedSpread,
8002
8021
  formatAssetId,
8003
8022
  fromAtomicDecimal,
8004
8023
  fromRfqAmountSide,
@@ -8062,7 +8081,10 @@ async function revealClaimPacket(client, input) {
8062
8081
  toRfqAmountSide,
8063
8082
  toSafeNumber,
8064
8083
  usableMarkets,
8084
+ verifiedCarrierSats,
8085
+ verifyCrossAssetAmount,
8065
8086
  verifyPair,
8087
+ verifyPlanLegs,
8066
8088
  verifyQuoteTtl,
8067
8089
  verifyQuotedAmount,
8068
8090
  verifyReceiveInvoiceFacts,