@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
@@ -8,18 +8,25 @@ import {
8
8
  PreimageNotRecoverableError,
9
9
  RETIRABLE,
10
10
  RFQ_TERMINAL_STATES,
11
+ assertPreimageMatches,
11
12
  classifyOnchainHtlc,
12
13
  decodeOffer,
14
+ gateError,
13
15
  getAssetSwaps,
14
16
  l1NetworkFromArk,
15
17
  lockupContractParams,
16
18
  offerContract,
17
19
  onchainHtlcScript,
20
+ pollUntil,
18
21
  registerLockupContract,
19
22
  retireOfferContract,
23
+ sleep,
20
24
  swapSecretsToRecord,
21
25
  updateAssetSwapBestEffort
22
- } from "./chunk-KRXPQQJ7.js";
26
+ } from "./chunk-BBP25BWH.js";
27
+ import {
28
+ collectRfqSwaps
29
+ } from "./chunk-A3SHHRX4.js";
23
30
 
24
31
  // src/rfqCorridor.ts
25
32
  var RfqCorridorRegistry = class {
@@ -32,20 +39,12 @@ var RfqCorridorRegistry = class {
32
39
  }
33
40
  this.handlers.set(handler.kind, handler);
34
41
  }
35
- /** Takes a bare `string`, deliberately, where {@link RfqCorridorHandler.kind}
36
- * is the manager's union: a lookup key comes off a record a backend handed
37
- * back, and that it typechecks as a `kind` is a claim about the type, not
38
- * about what was stored. Narrowing this would read as a check already made. */
42
+ /** A bare `string` on purpose: the key comes off a stored record, and narrowing it to the
43
+ * `kind` union would read as a check already made. */
39
44
  get(kind) {
40
45
  return this.handlers.get(kind);
41
46
  }
42
- /**
43
- * The handler for a kind, or a loud failure.
44
- *
45
- * A record whose corridor is not registered cannot be restored, and
46
- * guessing would monitor a swap with no idea how to drive it. Names the
47
- * registered kinds so a missing `register()` call is obvious.
48
- */
47
+ /** The handler for a kind, or a loud failure naming the registered kinds. */
49
48
  getOrThrow(kind) {
50
49
  const handler = this.get(kind);
51
50
  if (!handler) {
@@ -55,9 +54,6 @@ var RfqCorridorRegistry = class {
55
54
  }
56
55
  return handler;
57
56
  }
58
- has(kind) {
59
- return this.handlers.has(kind);
60
- }
61
57
  registeredKinds() {
62
58
  return [...this.handlers.keys()];
63
59
  }
@@ -156,15 +152,12 @@ var LightningSendCorridor = {
156
152
  kind: "lightning_send",
157
153
  project: () => ({}),
158
154
  hydrate: (profile) => hydrateHashlock(profile)
159
- // No `claimSecret`, deliberately: `provisionRefundKey` mints no preimage at
160
- // all, and deriving one off the refund descriptor would fail the payment
161
- // hash check — a `hash-mismatch` on a swap that was never broken.
155
+ // No `claimSecret`: no preimage was minted, and one derived off the refund descriptor would
156
+ // fail the payment hash check on a swap that was never broken.
162
157
  };
163
158
  var LightningReceiveCorridor = {
164
159
  kind: "lightning_receive",
165
- // What the manager holds: the amount gate, and its own claim once it lands.
166
- // `payoutAddress` comes from the request result and never changes, so the
167
- // caller writes it once and this leaves it alone.
160
+ // `payoutAddress` is written once by the caller from the request result; left alone here.
168
161
  project: (swap) => {
169
162
  const receive = swap;
170
163
  return {
@@ -185,8 +178,6 @@ var LightningReceiveCorridor = {
185
178
  // We are the claimant here, so the preimage material on the hashlock is
186
179
  // ours to use.
187
180
  claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
188
- // The other half of claiming: where it pays. Written once at request time
189
- // and left alone by `project` above, so this hands back what was stored.
190
181
  claimDestination: (profile) => profile.payoutAddress,
191
182
  activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
192
183
  };
@@ -204,9 +195,7 @@ function onchainSendProfile(result) {
204
195
  }
205
196
  var OnchainSendCorridor = {
206
197
  kind: "onchain_send",
207
- // The L1 keys and the network are only in the request result — nothing on
208
- // `OnchainSendSwap` carries them — so the caller writes them once. What the
209
- // manager learns as it drives the swap is the fill and our own claim.
198
+ // The L1 keys and network are written once by the caller; the manager learns fill and claim.
210
199
  project: (swap) => {
211
200
  const send = swap;
212
201
  return {
@@ -234,10 +223,8 @@ var OnchainSendCorridor = {
234
223
  }
235
224
  const htlc = onchainHtlcScript(
236
225
  {
237
- // From the profile, not the covenant: the lockup commits to
238
- // `hash160(P)`, and the HTLC needs `sha256(P)`. One P
239
- // unlocks both legs, but only one of the two hashes of it
240
- // is recoverable here.
226
+ // From the profile, not the covenant: the lockup commits to `hash160(P)`, the
227
+ // HTLC needs `sha256(P)`.
241
228
  paymentHash,
242
229
  claimKey: hex.decode(profile.claimKey),
243
230
  refundKey: hex.decode(profile.refundKey),
@@ -265,9 +252,7 @@ var OnchainSendCorridor = {
265
252
  // The trader claims the L1 HTLC with P, so this leg's preimage material is
266
253
  // ours.
267
254
  claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
268
- // Our own L1 claim only. `funding` is the SOLVER's fill into the HTLC —
269
- // not a transaction of ours, so grouping it would claim a row this wallet
270
- // never made.
255
+ // Our own L1 claim only: `funding` is the solver's tx, not a row this wallet made.
271
256
  activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
272
257
  };
273
258
  rfqCorridorHandlers.register(LightningSendCorridor);
@@ -420,18 +405,14 @@ var CORRIDOR_OUTCOME = {
420
405
  failed: at("failed")
421
406
  },
422
407
  solver: {
423
- // The solver has funded nothing yet: the invoice is shown and unpaid,
424
- // which is what makes this `open` where the trader's side is `funded`.
408
+ // The solver has funded nothing yet: the invoice is shown and unpaid.
425
409
  pending: at("open"),
426
410
  claimable: at("funded"),
427
411
  claimed: at("funded"),
428
412
  needs_counterparty: at("needs_recovery"),
429
- // The trader's OWN claim, matched by the hash and not by our txid — so
430
- // a claim that lands without us still counts.
413
+ // Matched by the hash, not our txid, so a claim that lands without us counts.
431
414
  settled: at("claimed"),
432
- // The one inversion this whole module exists for: every non-claim leaf
433
- // of a receive covenant is the solver's, so a lockup spent by one is
434
- // the trader's incoming payment never arriving.
415
+ // The inversion: a receive lockup's non-claim leaves are all the solver's.
435
416
  refunded: at("lapsed"),
436
417
  failed: at("failed")
437
418
  }
@@ -442,8 +423,7 @@ var OFFER_OUTCOME = {
442
423
  cancelling: "cancelling",
443
424
  cancelled: "cancelled",
444
425
  fulfilled: "filled",
445
- // A swept deposit: still the trader's money, at a script no offchain spend
446
- // can reach until it is recovered into a fresh batch.
426
+ // A swept deposit: still the trader's money, unreachable until recovered into a batch.
447
427
  recoverable: "needs_recovery",
448
428
  awaiting_fill: "needs_recovery",
449
429
  claimable: "needs_recovery",
@@ -461,10 +441,8 @@ var ACTIVITY_TOKEN = {
461
441
  funding: "pending",
462
442
  funded: "pending",
463
443
  open: "pending",
464
- // The drive's in-flight states have no user-visible phase distinct from
465
- // "pending"; `needs_recovery` is different in kind — the swap is BLOCKED —
466
- // and collapsing it here is the same deliberate choice v1 made, which the
467
- // opaque-token design permits because apps map tokens themselves.
444
+ // `needs_recovery` (BLOCKED) collapses to pending deliberately, as in v1; apps map
445
+ // tokens themselves.
468
446
  needs_recovery: "pending",
469
447
  refunding: "pending",
470
448
  cancelling: "pending",
@@ -481,33 +459,31 @@ var ACTIVITY_TOKEN = {
481
459
  import { base64, hex as hex2 } from "@scure/base";
482
460
  import { sha256 } from "@noble/hashes/sha2.js";
483
461
  import {
484
- CSVMultisigTapscript,
485
462
  ConditionWitness,
486
463
  Transaction,
487
464
  assertSubmittedArkTxid,
465
+ assertValidServerUnrollScript,
488
466
  buildOffchainTx,
489
467
  getArkPsbtFields,
490
- hasTerminalSpend,
491
- matchServerCheckpoints
468
+ isVtxoSpent,
469
+ matchServerCheckpoints,
470
+ networkFromArkadeInfo,
471
+ resolveCheckpointExitDelayPolicy,
472
+ toXOnly
492
473
  } from "@arkade-os/sdk";
493
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
494
474
  var isRfqTerminal = (state) => RFQ_TERMINAL_STATES.includes(state);
495
475
  var RFQ_RESOLVED_STATES = ["settled", "refunded"];
496
476
  var isResolved = (state) => RFQ_RESOLVED_STATES.includes(state);
497
477
  async function awaitRfqResolution(transport, rfqId, options = {}) {
498
- const pollMs = options.pollMs ?? 5e3;
499
- for (; ; ) {
500
- const status = await transport.status(rfqId);
501
- if (status && isRfqTerminal(status.state)) return status;
502
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
503
- const error = new Error(
504
- `rfq ${rfqId} did not reach a terminal state before the deadline`
505
- );
506
- error.reason = "status_timeout";
507
- throw error;
508
- }
509
- await sleep(pollMs);
510
- }
478
+ return pollUntil(
479
+ async () => {
480
+ const status = await transport.status(rfqId);
481
+ return status && isRfqTerminal(status.state) ? status : void 0;
482
+ },
483
+ options,
484
+ "status_timeout",
485
+ `rfq ${rfqId} did not reach a terminal state before the deadline`
486
+ );
511
487
  }
512
488
  var walletOperator = (wallet) => {
513
489
  let broadcaster;
@@ -524,15 +500,8 @@ var LockupNeedsRecoveryError = class extends Error {
524
500
  /** `txid:vout` for each output that must be recovered first. */
525
501
  outpoints;
526
502
  /**
527
- * The contract's `refundLocktime`. Recovering before this matures is the
528
- * hazard described above: `recoverVtxos()` sweeps EVERY recoverable output
529
- * into one settlement with no CLTV awareness, so an early attempt can fail
530
- * the whole batch — including unrelated outputs that were otherwise fine.
531
- *
532
- * Exposed as a value, not only inside the message, so a caller can skip
533
- * pre-CLTV recoverable outputs without parsing prose. Seconds-based
534
- * locktimes mature against the chain tip's timestamp rather than wall
535
- * clock, so treat this as a floor to wait past, not an exact alarm.
503
+ * The contract's `refundLocktime`; do not recover before it (see above). Seconds-based
504
+ * locktimes mature against chain time, not wall clock, so treat this as a floor.
536
505
  */
537
506
  recoverableAfter;
538
507
  constructor(outpoints, recoverableAfter) {
@@ -551,7 +520,7 @@ async function findLockupVtxos(contracts, swapPkScript) {
551
520
  const out = [];
552
521
  for (const vtxo of row?.vtxos ?? []) {
553
522
  if (vtxo.isUnrolled) continue;
554
- if (hasTerminalSpend(vtxo)) continue;
523
+ if (isVtxoSpent(vtxo)) continue;
555
524
  const key = `${vtxo.txid}:${vtxo.vout}`;
556
525
  if (seen.has(key)) continue;
557
526
  seen.add(key);
@@ -559,8 +528,6 @@ async function findLockupVtxos(contracts, swapPkScript) {
559
528
  txid: vtxo.txid,
560
529
  vout: vtxo.vout,
561
530
  value: Number(vtxo.value),
562
- // The manager's canonical `isSwept` fact; no coercion, because the
563
- // normalized row guarantees a boolean.
564
531
  recoverable: vtxo.isSwept
565
532
  });
566
533
  }
@@ -575,7 +542,7 @@ async function readLockupFate(indexer, input) {
575
542
  const { vtxos } = await indexer.getVtxos({ scripts: [hex2.encode(input.swapPkScript)] });
576
543
  const all = vtxos ?? [];
577
544
  if (all.length === 0) return { fate: "unknown" };
578
- const exited = all.filter((vtxo) => vtxo.isUnrolled && !hasTerminalSpend(vtxo));
545
+ const exited = all.filter((vtxo) => vtxo.isUnrolled && !isVtxoSpent(vtxo));
579
546
  if (exited.length > 0) {
580
547
  return {
581
548
  fate: "exited",
@@ -585,7 +552,7 @@ async function readLockupFate(indexer, input) {
585
552
  const spentBy = /* @__PURE__ */ new Map();
586
553
  let everySpendNamed = true;
587
554
  for (const vtxo of all) {
588
- if (!hasTerminalSpend(vtxo)) return { fate: "open" };
555
+ if (!isVtxoSpent(vtxo)) return { fate: "open" };
589
556
  if (vtxo.spentBy)
590
557
  spentBy.set(vtxo.spentBy, {
591
558
  checkpointTxid: vtxo.spentBy,
@@ -618,41 +585,50 @@ async function readLockupFate(indexer, input) {
618
585
  }
619
586
  return everySpendNamed && observed.size === spentBy.size ? { fate: "returned", spends } : { fate: "unknown" };
620
587
  }
621
- async function pushRefundWithoutReceiver(operator, input) {
622
- if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
623
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
588
+ var assertNoneSwept = (vtxos, contract) => {
589
+ const swept = vtxos.filter((vtxo) => vtxo.recoverable);
624
590
  if (swept.length > 0) {
625
591
  throw new LockupNeedsRecoveryError(
626
592
  swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
627
- input.contract.options.refundLocktime
593
+ contract.options.refundLocktime
628
594
  );
629
595
  }
596
+ };
597
+ var operatorUnrollScript = async (operator, network) => {
598
+ const info = await operator.getInfo();
599
+ return assertValidServerUnrollScript(
600
+ info.checkpointTapscript,
601
+ resolveCheckpointExitDelayPolicy(network ?? networkFromArkadeInfo(info), {
602
+ advertisedForfeitPubkey: toXOnly(hex2.decode(info.forfeitPubkey), "forfeit key")
603
+ })
604
+ );
605
+ };
606
+ var lockupInputs = (vtxos, contract, leaf) => {
607
+ const tapTree = contract.encode();
608
+ return vtxos.map((vtxo) => ({
609
+ txid: vtxo.txid,
610
+ vout: vtxo.vout,
611
+ value: vtxo.value,
612
+ tapLeafScript: leaf,
613
+ tapTree
614
+ }));
615
+ };
616
+ async function pushRefundWithoutReceiver(operator, input) {
617
+ if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
618
+ assertNoneSwept(input.vtxos, input.contract);
630
619
  const refundPkScript = input.refundPkScript ?? input.contract.options.nonInteractiveParameters?.senderPkScript;
631
620
  if (!refundPkScript) {
632
621
  throw new Error(
633
622
  "no refund destination: the contract carries no emulator covenant suite, so pass refundPkScript explicitly"
634
623
  );
635
624
  }
636
- const info = await operator.getInfo();
637
- let operatorUnrollScript;
638
- try {
639
- operatorUnrollScript = CSVMultisigTapscript.decode(hex2.decode(info.checkpointTapscript));
640
- } catch {
641
- throw new Error("invalid checkpointTapscript from the operator");
642
- }
625
+ const serverUnrollScript = await operatorUnrollScript(operator, input.network);
643
626
  const leaf = input.contract.refundWithoutReceiver();
644
- const tapTree = input.contract.encode();
645
627
  const amount = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
646
628
  const { arkTx: tx, checkpoints } = buildOffchainTx(
647
- input.vtxos.map((vtxo) => ({
648
- txid: vtxo.txid,
649
- vout: vtxo.vout,
650
- value: vtxo.value,
651
- tapLeafScript: leaf,
652
- tapTree
653
- })),
629
+ lockupInputs(input.vtxos, input.contract, leaf),
654
630
  [{ script: refundPkScript, amount: BigInt(amount) }],
655
- operatorUnrollScript
631
+ serverUnrollScript
656
632
  );
657
633
  const signedTx = await input.sender.sign(tx);
658
634
  const submitted = await operator.submitTx(
@@ -959,8 +935,7 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
959
935
  const script = offerContract(offer, operatorPubkey);
960
936
  if (hex3.encode(script.pkScript) !== hex3.encode(offer.swapPkScript)) return "indeterminate";
961
937
  leaves = {
962
- // both routes that hand the deposit back; `exit` is absent on an
963
- // offer that carries no exit closure, and drops out here
938
+ // `exit` is absent on an offer with no exit closure, and drops out here
964
939
  returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
965
940
  fulfill: script.functionByName("fulfill")?.leafScript
966
941
  };
@@ -1116,8 +1091,6 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
1116
1091
  spentTxid,
1117
1092
  status,
1118
1093
  createdAt: fundingTx.createdAt ? fundingTx.createdAt * 1e3 : vtxo.createdAt.getTime(),
1119
- // the completion time is the caller's record of the spend, if it
1120
- // has one — the psbt that classified it carries no timestamp
1121
1094
  ...completion
1122
1095
  });
1123
1096
  }
@@ -1125,15 +1098,10 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
1125
1098
  }
1126
1099
 
1127
1100
  // src/claim.ts
1128
- import { hex as hex4 } from "@scure/base";
1129
- import { ripemd160 } from "@noble/hashes/legacy.js";
1130
- import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
1131
1101
  import {
1132
- CSVMultisigTapscript as CSVMultisigTapscript2,
1133
1102
  claimWithPreimageIdentity,
1134
1103
  signAndSubmitOffchainTx
1135
1104
  } from "@arkade-os/sdk";
1136
- var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1137
1105
  var LockupAmountMismatchError = class extends Error {
1138
1106
  name = "LockupAmountMismatchError";
1139
1107
  reason = "amount_mismatch";
@@ -1149,19 +1117,11 @@ var LockupAmountMismatchError = class extends Error {
1149
1117
  };
1150
1118
  var assertFiniteAmount = (value, reason, label) => {
1151
1119
  if (Number.isFinite(value)) return;
1152
- const error = new Error(`${label} is not a finite number (${String(value)})`);
1153
- error.reason = reason;
1154
- throw error;
1120
+ throw gateError(reason, `${label} is not a finite number (${String(value)})`);
1155
1121
  };
1156
1122
  async function pushClaim(operator, input) {
1157
1123
  if (input.vtxos.length === 0) throw new Error("nothing to claim: no funded outputs");
1158
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
1159
- if (swept.length > 0) {
1160
- throw new LockupNeedsRecoveryError(
1161
- swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
1162
- input.contract.options.refundLocktime
1163
- );
1164
- }
1124
+ assertNoneSwept(input.vtxos, input.contract);
1165
1125
  const locked = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
1166
1126
  assertFiniteAmount(locked, "lockup_malformed", "the lockup's summed value");
1167
1127
  if (!input.partiallyClaimed) {
@@ -1170,64 +1130,35 @@ async function pushClaim(operator, input) {
1170
1130
  throw new LockupAmountMismatchError(input.expectedAmount, locked);
1171
1131
  }
1172
1132
  }
1173
- const committed = input.contract.options.preimageHash;
1174
- if (hex4.encode(ripemd160(sha2562(input.preimage))) !== hex4.encode(committed)) {
1175
- throw new Error("preimage does not match the covenant's payment hash");
1176
- }
1177
- const info = await operator.getInfo();
1178
- let operatorUnrollScript;
1179
- try {
1180
- operatorUnrollScript = CSVMultisigTapscript2.decode(hex4.decode(info.checkpointTapscript));
1181
- } catch {
1182
- throw new Error("invalid checkpointTapscript from the operator");
1183
- }
1133
+ assertPreimageMatches(input.preimage, input.contract.options.preimageHash);
1134
+ const serverUnrollScript = await operatorUnrollScript(operator, input.network);
1184
1135
  const leaf = input.contract.claim();
1185
- const tapTree = input.contract.encode();
1186
1136
  const txid = await signAndSubmitOffchainTx({
1187
1137
  identity: claimWithPreimageIdentity(input.receiver, input.preimage),
1188
1138
  provider: operator,
1189
- inputs: input.vtxos.map((vtxo) => ({
1190
- txid: vtxo.txid,
1191
- vout: vtxo.vout,
1192
- value: vtxo.value,
1193
- tapLeafScript: leaf,
1194
- tapTree
1195
- })),
1196
- // One aggregate output: unlike the covenant refund, this leaf inspects
1197
- // nothing about the output set.
1139
+ inputs: lockupInputs(input.vtxos, input.contract, leaf),
1140
+ // One aggregate output: this leaf inspects nothing about the output set.
1198
1141
  outputs: [{ script: input.destinationPkScript, amount: BigInt(locked) }],
1199
- serverUnrollScript: operatorUnrollScript,
1142
+ serverUnrollScript,
1200
1143
  verifyServerSignatures: { serverPubkey: input.contract.options.server }
1201
1144
  });
1202
1145
  return { txid, amount: locked };
1203
1146
  }
1204
1147
  async function awaitLockupFunding(contracts, swapPkScript, options = {}) {
1205
- const pollMs = options.pollMs ?? 5e3;
1206
- for (; ; ) {
1207
- const vtxos = await findLockupVtxos(contracts, swapPkScript);
1208
- if (vtxos.length > 0) return vtxos;
1209
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
1210
- const error = new Error("the lockup never appeared at the covenant script");
1211
- error.reason = "lockup_timeout";
1212
- throw error;
1213
- }
1214
- await sleep2(pollMs);
1215
- }
1148
+ return pollUntil(
1149
+ async () => {
1150
+ const vtxos = await findLockupVtxos(contracts, swapPkScript);
1151
+ return vtxos.length > 0 ? vtxos : void 0;
1152
+ },
1153
+ options,
1154
+ "lockup_timeout",
1155
+ "the lockup never appeared at the covenant script"
1156
+ );
1216
1157
  }
1217
1158
  async function claimReceiveLockup(contracts, operator, input) {
1218
- const vtxos = await awaitLockupFunding(contracts, input.swapPkScript, {
1219
- pollMs: input.pollMs,
1220
- deadline: input.deadline
1221
- });
1222
- return pushClaim(operator, {
1223
- contract: input.contract,
1224
- receiver: input.receiver,
1225
- preimage: input.preimage,
1226
- vtxos,
1227
- destinationPkScript: input.destinationPkScript,
1228
- expectedAmount: input.expectedAmount,
1229
- partiallyClaimed: input.partiallyClaimed
1230
- });
1159
+ const { swapPkScript, pollMs, deadline, ...claim } = input;
1160
+ const vtxos = await awaitLockupFunding(contracts, swapPkScript, { pollMs, deadline });
1161
+ return pushClaim(operator, { ...claim, vtxos });
1231
1162
  }
1232
1163
 
1233
1164
  // src/refundBlocked.ts
@@ -1291,17 +1222,28 @@ function arkadeRefunder(deps) {
1291
1222
  );
1292
1223
  }
1293
1224
  const sender = await senderIdentityForSwapRecord(deps.wallet, rfqSignerOf(record) ?? {});
1294
- return pushRefundWithoutReceiver(deps.operator, { contract, sender, vtxos });
1225
+ return pushRefundWithoutReceiver(deps.operator, {
1226
+ contract,
1227
+ sender,
1228
+ vtxos,
1229
+ network: await deps.network?.()
1230
+ });
1295
1231
  };
1296
1232
  }
1297
1233
 
1298
1234
  // src/rfqSwapState.ts
1299
1235
  var RFQ_SWAP_TERMINAL_STATES = ["settled", "refunded", "failed"];
1236
+ var RFQ_SWAP_ACTIVE_STATES = [
1237
+ "pending",
1238
+ "claimable",
1239
+ "claimed",
1240
+ "needs_counterparty"
1241
+ ];
1300
1242
  var isRfqSwapTerminal = (state) => RFQ_SWAP_TERMINAL_STATES.includes(state);
1301
1243
 
1302
1244
  // src/rfqRecord.ts
1303
1245
  import { ArkAddress, VHTLCV2ContractHandler } from "@arkade-os/sdk";
1304
- import { hex as hex5 } from "@scure/base";
1246
+ import { hex as hex4 } from "@scure/base";
1305
1247
  var RFQ_SWAP_RETENTION_SECONDS = 30 * 24 * 60 * 60;
1306
1248
  function renameLegacyClaimTxid(profile) {
1307
1249
  const { claimArkTxid, ...rest } = profile;
@@ -1322,17 +1264,20 @@ function normalizeRfqSwapRecord(record) {
1322
1264
  ...legacyClaim ? { profile: renameLegacyClaimTxid(record.profile) } : {}
1323
1265
  };
1324
1266
  }
1267
+ var mutableFields = (from) => ({
1268
+ ...from.refundTxid ? { refundTxid: from.refundTxid } : {},
1269
+ ...from.lockupSpendTxids?.length ? { lockupSpendTxids: [...from.lockupSpendTxids] } : {},
1270
+ ...from.settlementPreimageHex ? { settlementPreimageHex: from.settlementPreimageHex } : {},
1271
+ ...from.failure ? { failure: from.failure } : {},
1272
+ ...from.claimFailure ? { claimFailure: from.claimFailure } : {},
1273
+ ...from.blockedReason ? { blockedReason: from.blockedReason } : {}
1274
+ });
1325
1275
  var managerState = (swap) => ({
1326
1276
  rfqId: swap.rfqId,
1327
1277
  state: swap.state,
1328
1278
  createdAt: swap.createdAt,
1329
1279
  updatedAt: swap.updatedAt,
1330
- ...swap.refundTxid ? { refundTxid: swap.refundTxid } : {},
1331
- ...swap.lockupSpendTxids?.length ? { lockupSpendTxids: [...swap.lockupSpendTxids] } : {},
1332
- ...swap.settlementPreimageHex ? { settlementPreimageHex: swap.settlementPreimageHex } : {},
1333
- ...swap.failure ? { failure: swap.failure } : {},
1334
- ...swap.claimFailure ? { claimFailure: swap.claimFailure } : {},
1335
- ...swap.blockedReason ? { blockedReason: swap.blockedReason } : {}
1280
+ ...mutableFields(swap)
1336
1281
  });
1337
1282
  function assertSameSwap(origin, swap) {
1338
1283
  if (origin.kind !== swap.kind) {
@@ -1340,8 +1285,8 @@ function assertSameSwap(origin, swap) {
1340
1285
  `rfq swap record is a ${origin.kind} origin paired with a ${swap.kind} swap`
1341
1286
  );
1342
1287
  }
1343
- const funded = hex5.encode(ArkAddress.decode(origin.lockupAddress).pkScript);
1344
- const watched = hex5.encode(swap.lockupPkScript);
1288
+ const funded = hex4.encode(ArkAddress.decode(origin.lockupAddress).pkScript);
1289
+ const watched = hex4.encode(swap.lockupPkScript);
1345
1290
  if (funded !== watched) {
1346
1291
  throw new Error(
1347
1292
  `rfq swap record's lockup address holds ${funded}, but the swap watches ${watched} \u2014 these are not the same swap`
@@ -1354,8 +1299,6 @@ function createRfqSwapRecord(origin, swap) {
1354
1299
  return {
1355
1300
  ...origin,
1356
1301
  ...managerState(swap),
1357
- // The caller wrote what only the request result knows; the handler adds
1358
- // what the live swap already carries.
1359
1302
  profile: { ...origin.profile, ...handler.project(swap) }
1360
1303
  };
1361
1304
  }
@@ -1391,9 +1334,9 @@ function rfqSwapOriginOf(record) {
1391
1334
  function lockupScript(params, lockupAddress) {
1392
1335
  const script = VHTLCV2ContractHandler.createScript(params);
1393
1336
  const funded = ArkAddress.decode(lockupAddress).pkScript;
1394
- if (hex5.encode(funded) !== hex5.encode(script.pkScript)) {
1337
+ if (hex4.encode(funded) !== hex4.encode(script.pkScript)) {
1395
1338
  throw new Error(
1396
- `rfq swap covenant params derive ${hex5.encode(script.pkScript)}, but the record's lockup address holds ${hex5.encode(funded)} \u2014 these params are not this swap's`
1339
+ `rfq swap covenant params derive ${hex4.encode(script.pkScript)}, but the record's lockup address holds ${hex4.encode(funded)} \u2014 these params are not this swap's`
1397
1340
  );
1398
1341
  }
1399
1342
  return script;
@@ -1411,12 +1354,7 @@ function rebuildRfqSwap(record, params) {
1411
1354
  refundLocktime: Number(script.options.refundLocktime),
1412
1355
  createdAt: stored.createdAt,
1413
1356
  updatedAt: stored.updatedAt,
1414
- ...stored.refundTxid ? { refundTxid: stored.refundTxid } : {},
1415
- ...stored.lockupSpendTxids?.length ? { lockupSpendTxids: [...stored.lockupSpendTxids] } : {},
1416
- ...stored.settlementPreimageHex ? { settlementPreimageHex: stored.settlementPreimageHex } : {},
1417
- ...stored.failure ? { failure: stored.failure } : {},
1418
- ...stored.claimFailure ? { claimFailure: stored.claimFailure } : {},
1419
- ...stored.blockedReason ? { blockedReason: stored.blockedReason } : {}
1357
+ ...mutableFields(stored)
1420
1358
  };
1421
1359
  const handler = rfqCorridorHandlers.getOrThrow(stored.kind);
1422
1360
  return {
@@ -1431,9 +1369,12 @@ function shouldRetainRfqSwap(record, now) {
1431
1369
  }
1432
1370
 
1433
1371
  // src/swapManager.ts
1434
- import { hex as hex6 } from "@scure/base";
1372
+ import { hex as hex5 } from "@scure/base";
1435
1373
  import {
1436
- isContractVtxoEvent
1374
+ ArkErrorName,
1375
+ isArkError,
1376
+ isContractVtxoEvent,
1377
+ maybeArkError
1437
1378
  } from "@arkade-os/sdk";
1438
1379
  function nextOnchainAction(input) {
1439
1380
  switch (input.phase.phase) {
@@ -1478,7 +1419,8 @@ var notify = (listeners, call) => {
1478
1419
  }
1479
1420
  }
1480
1421
  };
1481
- var RfqSwapManager = class {
1422
+ var RfqSwapManager = class _RfqSwapManager {
1423
+ static POLL_CONCURRENCY = 16;
1482
1424
  deps;
1483
1425
  config;
1484
1426
  callbacks = null;
@@ -1487,62 +1429,40 @@ var RfqSwapManager = class {
1487
1429
  swapFailedListeners = /* @__PURE__ */ new Set();
1488
1430
  actionExecutedListeners = /* @__PURE__ */ new Set();
1489
1431
  monitored = /* @__PURE__ */ new Map();
1490
- /** Monitored swaps by lockup script hex, so a contract event — which names
1491
- * a script and nothing else — can find the swap it belongs to. */
1432
+ /** Monitored swaps by lockup script hex: a contract event names only a script. */
1492
1433
  byLockupScript = /* @__PURE__ */ new Map();
1493
1434
  /**
1494
- * Swaps whose lockup registration has been SETTLED one way or another,
1495
- * mapped to whether a contract row actually resulted. Membership is what
1496
- * stops a per-pass retry from becoming a per-pass round trip; the value is
1497
- * what keeps a swap that could never be registered from later trying to
1498
- * retire a row that does not exist, which would report a spurious failure
1499
- * on a swap that in fact succeeded.
1435
+ * Swaps whose lockup registration has SETTLED, mapped to whether a contract row
1436
+ * resulted. Membership stops per-pass round trips; the value stops a never-registered
1437
+ * swap from retiring a nonexistent row and reporting a spurious failure.
1500
1438
  */
1501
1439
  registered = /* @__PURE__ */ new Map();
1502
1440
  /**
1503
- * Swaps whose `refundArkade` answered {@link RefundNotLocallyPossibleError}
1504
- * in this process. Membership stops the push from being re-issued every
1505
- * pass — it cannot start working on its own, and re-issuing it is the
1506
- * grind `needs_counterparty` exists to remove. Only
1507
- * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it, so a caller
1508
- * with no probe learns again on the next start, when the wallet that can
1509
- * sign may well have been restored.
1441
+ * Swaps whose `refundArkade` threw {@link RefundNotLocallyPossibleError} in this
1442
+ * process, so the push is not re-issued every pass. Only
1443
+ * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it.
1510
1444
  */
1511
1445
  refundRefused = /* @__PURE__ */ new Set();
1512
1446
  /**
1513
- * The lockup outpoints a receive swap's claim callback has already been
1514
- * handed, by rfqId.
1515
- *
1516
- * What this exists to prevent: a claim SUCCEEDS, and for the next few
1517
- * passes the indexer still lists those outputs as unspent. Without a
1518
- * record of what was already claimed, every one of those passes would
1519
- * re-submit the same spend, fail against the server, and report a swap
1520
- * that in fact worked as failing. With one, a re-claim happens only when
1521
- * an outpoint appears that was never claimed — a lockup funded piecemeal,
1522
- * which is legitimate and which `partiallyClaimed` exists for.
1523
- *
1524
- * Process-local: after a restart a swap with a live claim tries once more.
1525
- * That is the recovery case rather than the spam one — a claim that never
1526
- * landed leaves its outputs unspent, and one that did leaves a single
1527
- * rejection.
1447
+ * Lockup outpoints already handed to a receive swap's claim callback, by rfqId. After a
1448
+ * claim SUCCEEDS the indexer may still list its outputs as unspent; without this each
1449
+ * pass would re-submit and report a working swap as failing. Process-local: a restart
1450
+ * costs at most one rejected re-claim.
1528
1451
  */
1529
1452
  claimedOutpoints = /* @__PURE__ */ new Map();
1530
1453
  /** Live `onContractEvent` subscription, held so `stop()` can drop it. */
1531
1454
  unsubscribeContracts = null;
1532
- /** Terminal records, kept so a late {@link waitForSwapCompletion} still
1533
- * answers instead of throwing "not found". Cleared by {@link removeSwap}. */
1455
+ /** Recent terminal swaps; older durable outcomes are read from the record store on demand. */
1534
1456
  finished = /* @__PURE__ */ new Map();
1457
+ /** Explicit removals stay suppressed for this manager lifetime; normal completions never enter this set.
1458
+ * Each maps to its removal sequence, so restore can tell a removal made during its rebuild. */
1459
+ removed = /* @__PURE__ */ new Map();
1460
+ removalSeq = 0;
1535
1461
  waiters = /* @__PURE__ */ new Map();
1536
1462
  /**
1537
- * The request-time origin of each swap the manager may have to CREATE a
1538
- * record for, by rfqId.
1539
- *
1540
- * Needed only for a swap the store has never seen: once a record exists,
1541
- * `updateRfqSwapRecord` carries the origin half through and the map is
1542
- * redundant. It is kept anyway for the swap's whole life, so a record the
1543
- * store loses between passes is rewritten rather than lost — and dropped
1544
- * by {@link removeSwap} and by retention, which are the two places a swap
1545
- * stops being this manager's business.
1463
+ * The request-time origin of each swap, by rfqId, needed to CREATE a record. Kept for
1464
+ * the swap's whole life so a record the store loses is rewritten; dropped by
1465
+ * {@link removeSwap} and by retention.
1546
1466
  */
1547
1467
  origins = /* @__PURE__ */ new Map();
1548
1468
  /** Records changed during the current pass, flushed to the repository and
@@ -1550,6 +1470,8 @@ var RfqSwapManager = class {
1550
1470
  dirty = /* @__PURE__ */ new Set();
1551
1471
  /** Race guard: one action at a time per swap. */
1552
1472
  inProgress = /* @__PURE__ */ new Set();
1473
+ activePolls = 0;
1474
+ pollWaiters = /* @__PURE__ */ new Set();
1553
1475
  timer = null;
1554
1476
  running = false;
1555
1477
  constructor(deps, config = {}) {
@@ -1568,9 +1490,8 @@ var RfqSwapManager = class {
1568
1490
  this.actionExecutedListeners.add(config.events.onActionExecuted);
1569
1491
  }
1570
1492
  }
1571
- /** Wire the money-moving half. Without it the manager only watches. The
1572
- * two claims may be omitted for a consumer that drives no kind reaching
1573
- * them — see {@link AvailableRfqSwapManagerCallbacks}. */
1493
+ /** Wire the money-moving half. Without it the manager only watches. See
1494
+ * {@link AvailableRfqSwapManagerCallbacks}. */
1574
1495
  setCallbacks(callbacks) {
1575
1496
  this.callbacks = callbacks;
1576
1497
  }
@@ -1591,41 +1512,21 @@ var RfqSwapManager = class {
1591
1512
  return () => this.actionExecutedListeners.delete(listener);
1592
1513
  }
1593
1514
  /**
1594
- * Rebuild every stored swap and take over monitoring them.
1595
- *
1596
- * The composition a consumer otherwise writes by hand, and the one place
1597
- * all four pieces meet: retention decides what to keep
1598
- * (`shouldRetainRfqSwap`), the lockup's contract row supplies the covenant
1599
- * (`lockupContractParams`), `rebuildRfqSwap` turns a record back into a
1600
- * live swap, and each rebuilt swap arrives with its own origin, so nothing
1601
- * is asked of the caller.
1602
- *
1603
- * **Deliberately not part of {@link start}.** A consumer that wants to
1604
- * look at its records — count them, show them, prune and stop — is not
1605
- * forced to start driving money to do it. Call this first and `start()`
1606
- * after; a manager already running polls the restored swaps at once.
1607
- *
1608
- * Retention runs BEFORE the rebuild, so a record past
1609
- * `RFQ_SWAP_RETENTION_SECONDS` costs no contract lookup on its way to being
1610
- * dropped.
1611
- *
1612
- * **A record that cannot be rebuilt is reported, never swallowed and never
1613
- * fatal.** `rebuildRfqSwap` throws by design when the covenant params do
1614
- * not derive the funded address, and `lockupContractParams` throws
1615
- * `LockupContractMissing` when the wallet has no row for the lockup — both
1616
- * say something true about that one record, and neither is a reason to
1617
- * strand the others. They come back in {@link RfqRestoreResult.failed}.
1515
+ * Rebuild stored swaps and take over monitoring them. By default only active states
1516
+ * are read; terminal history stays stored and a late completion lookup reads one record
1517
+ * by key (`includeTerminal` loads everything). Deliberately not part of {@link start},
1518
+ * so records can be inspected without driving money. An unrebuildable record lands in
1519
+ * {@link RfqRestoreResult.failed}, never fatal to the others.
1618
1520
  */
1619
1521
  async restoreFromRepository(options = {}) {
1620
1522
  const repository = this.requireRepository("restoreFromRepository");
1621
1523
  const params = options.params ?? this.paramsFromContracts();
1622
- const records = await repository.getAllRfqSwaps();
1623
- const pruned = await this.dropRetired(repository, records);
1624
- const retired = new Set(pruned);
1625
1524
  const restored = [];
1626
1525
  const failed = [];
1627
- for (const record of records) {
1628
- if (retired.has(record.rfqId)) continue;
1526
+ const restore = async (record) => {
1527
+ if (!options.includeTerminal && isRfqSwapTerminal(record.state)) return;
1528
+ if (this.monitored.has(record.rfqId)) return;
1529
+ const removedAt = this.removed.get(record.rfqId);
1629
1530
  let swap;
1630
1531
  try {
1631
1532
  swap = rebuildRfqSwap(record, await params(record));
@@ -1634,38 +1535,37 @@ var RfqSwapManager = class {
1634
1535
  rfqId: record.rfqId,
1635
1536
  error: error instanceof Error ? error : new Error(errorMessage(error))
1636
1537
  });
1637
- continue;
1538
+ return;
1539
+ }
1540
+ if (this.monitored.has(record.rfqId)) return;
1541
+ if (this.removed.get(record.rfqId) !== removedAt) return;
1542
+ this.removed.delete(record.rfqId);
1543
+ if (isRfqSwapTerminal(swap.state)) this.rememberFinished(swap, true);
1544
+ else {
1545
+ this.origins.set(record.rfqId, rfqSwapOriginOf(record));
1546
+ this.track(swap);
1638
1547
  }
1639
- this.origins.set(record.rfqId, rfqSwapOriginOf(record));
1640
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
1641
- else this.track(swap);
1642
1548
  restored.push(swap);
1549
+ };
1550
+ const states = options.includeTerminal ? [void 0] : RFQ_SWAP_ACTIVE_STATES;
1551
+ for (const state of states) {
1552
+ for (const record of await collectRfqSwaps(repository, { state }))
1553
+ await restore(record);
1643
1554
  }
1644
1555
  if (this.running) {
1645
- await Promise.allSettled(
1646
- restored.filter((swap) => this.monitored.has(swap.rfqId)).map((swap) => this.pollSwap(swap))
1647
- );
1556
+ await this.pollMany(restored.filter((swap) => this.monitored.has(swap.rfqId)));
1648
1557
  }
1649
- return { restored, failed, pruned };
1558
+ return { restored, failed, pruned: [] };
1650
1559
  }
1651
1560
  /**
1652
- * Drop stored records that are terminal and past
1653
- * `RFQ_SWAP_RETENTION_SECONDS`, and return their ids.
1654
- *
1655
- * `needs_counterparty` is never dropped, however old: the money is still at
1656
- * the lockup and the counterparty's move still ends the swap. That rule
1657
- * lives in `shouldRetainRfqSwap`, which this defers to rather than
1658
- * restating.
1659
- *
1660
- * Public because retention is a caller's cadence, not the manager's: a
1661
- * long-lived process wants it on a timer of its own, a mobile app wants it
1662
- * at boot. {@link restoreFromRepository} runs it first, so the boot path
1663
- * needs no separate call.
1561
+ * Drop stored records that are terminal and past `RFQ_SWAP_RETENTION_SECONDS` (per
1562
+ * `shouldRetainRfqSwap`), and return their ids. Explicit only: restore keeps history.
1563
+ * Loads every stored record; no backend offers indexed deletion.
1664
1564
  */
1665
1565
  async pruneRetiredSwaps() {
1666
1566
  const repository = this.deps.repository;
1667
1567
  if (!repository) return [];
1668
- return this.dropRetired(repository, await repository.getAllRfqSwaps());
1568
+ return this.dropRetired(repository, await collectRfqSwaps(repository));
1669
1569
  }
1670
1570
  async dropRetired(repository, records) {
1671
1571
  const now = this.config.now();
@@ -1673,12 +1573,15 @@ var RfqSwapManager = class {
1673
1573
  for (const record of records) {
1674
1574
  if (shouldRetainRfqSwap(record, now)) continue;
1675
1575
  await repository.removeRfqSwap(record.rfqId);
1676
- this.finished.delete(record.rfqId);
1677
- if (!this.monitored.has(record.rfqId)) this.origins.delete(record.rfqId);
1576
+ this.forgetRetired(record.rfqId);
1678
1577
  dropped.push(record.rfqId);
1679
1578
  }
1680
1579
  return dropped;
1681
1580
  }
1581
+ forgetRetired(rfqId) {
1582
+ this.finished.delete(rfqId);
1583
+ if (!this.monitored.has(rfqId)) this.origins.delete(rfqId);
1584
+ }
1682
1585
  requireRepository(method) {
1683
1586
  const repository = this.deps.repository;
1684
1587
  if (!repository) {
@@ -1688,9 +1591,7 @@ var RfqSwapManager = class {
1688
1591
  }
1689
1592
  return repository;
1690
1593
  }
1691
- /** The default covenant source: the wallet's own contract row for each
1692
- * lockup, which is where registration put it before the address could be
1693
- * funded. */
1594
+ /** The default covenant source: the wallet's own contract row for each lockup. */
1694
1595
  paramsFromContracts() {
1695
1596
  const contracts = this.deps.contracts;
1696
1597
  if (!contracts) {
@@ -1701,28 +1602,23 @@ var RfqSwapManager = class {
1701
1602
  return (record) => lockupContractParams(contracts, record.lockupAddress);
1702
1603
  }
1703
1604
  /**
1704
- * Load records and begin monitoring. Runs one pass immediately — a caller
1705
- * resuming after a restart may be well past a deadline already — then
1706
- * every `pollIntervalMs`. Records that are already terminal are kept only
1707
- * so {@link waitForSwapCompletion} can answer for them.
1708
- *
1709
- * Calling it again while running loads the records and returns rather than
1710
- * re-arming — dropping them silently would strand a funded swap on a
1711
- * caller's harmless double-start.
1605
+ * Load records and begin monitoring: one pass immediately (a restart may already be
1606
+ * past a deadline), then every `pollIntervalMs`. Terminal outcomes in a repository are
1607
+ * read on demand. Calling it again while running loads the records without re-arming,
1608
+ * so a double-start never strands a funded swap.
1712
1609
  *
1713
- * The signature is unchanged with a {@link RfqSwapManagerDeps.repository}
1714
- * wired; the origins are resolved from the store instead, by the same rule
1715
- * {@link addSwap} applies. A swap the store has never seen throws
1716
- * {@link RfqSwapOriginRequired} — hand that one to `addSwap` with its
1717
- * origin, or restore the whole set with {@link restoreFromRepository},
1718
- * which needs no caller input at all. Every swap is checked before any is
1719
- * tracked, so a bad one in the list does not leave a half-loaded manager.
1610
+ * With a repository wired, a swap the store has never seen throws
1611
+ * {@link RfqSwapOriginRequired} (use {@link addSwap} with its origin, or
1612
+ * {@link restoreFromRepository}). Every swap is checked before any is tracked.
1720
1613
  */
1721
1614
  async start(swaps = []) {
1722
1615
  for (const swap of swaps) await this.admit(swap);
1723
1616
  for (const swap of swaps) {
1724
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
1725
- else this.track(swap);
1617
+ this.removed.delete(swap.rfqId);
1618
+ if (isRfqSwapTerminal(swap.state)) {
1619
+ this.rememberFinished(swap);
1620
+ this.origins.delete(swap.rfqId);
1621
+ } else this.track(swap);
1726
1622
  }
1727
1623
  if (this.running) return;
1728
1624
  this.running = true;
@@ -1731,16 +1627,10 @@ var RfqSwapManager = class {
1731
1627
  this.arm();
1732
1628
  }
1733
1629
  /**
1734
- * Stop monitoring and clear the timer. In-flight actions are not
1735
- * cancellable and run to completion; outstanding
1736
- * {@link waitForSwapCompletion} promises are left pending, since
1737
- * stop/start is a pause rather than a cancellation.
1738
- *
1739
- * The contract subscription is dropped too — an open stream with nothing
1740
- * reacting to it is a leak, and {@link start} puts it back. What is NOT
1741
- * undone is the contract registration: those rows are the wallet's, they
1742
- * outlive this manager's lifecycle, and dropping them would unwatch a
1743
- * lockup that is still funded.
1630
+ * Stop monitoring: clear the timer and drop the contract subscription. In-flight
1631
+ * actions run to completion and {@link waitForSwapCompletion} promises stay pending
1632
+ * (stop/start is a pause). Contract registrations are NOT undone: they are the
1633
+ * wallet's, and dropping them would unwatch a still-funded lockup.
1744
1634
  */
1745
1635
  async stop() {
1746
1636
  this.running = false;
@@ -1752,35 +1642,26 @@ var RfqSwapManager = class {
1752
1642
  this.unsubscribeContracts = null;
1753
1643
  }
1754
1644
  /**
1755
- * Begin monitoring a swap. Polled immediately when the manager is running,
1756
- * so a just-funded swap does not wait out a whole interval.
1645
+ * Begin monitoring a swap; polled immediately when the manager is running.
1757
1646
  *
1758
- * `origin` is the request-time half a live swap cannot carry — the corridor,
1759
- * the funded address, the corridor's profile, the funding txid — and it is
1760
- * what lets the manager write this swap's FIRST record. Supply it whenever
1761
- * a {@link RfqSwapManagerDeps.repository} is wired and the swap is new. It
1762
- * may be omitted for a swap the store already holds a record for, which is
1763
- * then read to confirm it; omitting it for one the store has never seen
1764
- * throws {@link RfqSwapOriginRequired} rather than admitting a swap whose
1765
- * record could never be written. With no repository wired the parameter is
1766
- * inert.
1647
+ * @param origin - The request-time half a live swap cannot carry, needed to write its
1648
+ * FIRST record. Required with a repository wired unless the store already holds the
1649
+ * record (else {@link RfqSwapOriginRequired}). Inert without a repository.
1767
1650
  */
1768
1651
  async addSwap(swap, origin) {
1769
1652
  await this.admit(swap, origin);
1653
+ this.removed.delete(swap.rfqId);
1770
1654
  if (isRfqSwapTerminal(swap.state)) {
1771
- this.finished.set(swap.rfqId, swap);
1655
+ this.rememberFinished(swap);
1656
+ this.origins.delete(swap.rfqId);
1772
1657
  return;
1773
1658
  }
1774
1659
  this.track(swap);
1775
1660
  if (this.running) await this.pollSwap(swap);
1776
1661
  }
1777
1662
  /**
1778
- * Settle where this swap's record will come from, before it is monitored.
1779
- *
1780
- * Three ways it can be answered, in order: the caller passed an origin, one
1781
- * is already remembered from an earlier `addSwap`, or the store holds a
1782
- * record — which is the origin, already written. Only the last costs a read,
1783
- * and only when the first two are absent.
1663
+ * Settle where this swap's record will come from, before it is monitored: a passed
1664
+ * origin, one remembered from an earlier `addSwap`, or the stored record (one read).
1784
1665
  */
1785
1666
  async admit(swap, origin) {
1786
1667
  if (origin) {
@@ -1797,13 +1678,10 @@ var RfqSwapManager = class {
1797
1678
  if (!stored) throw new RfqSwapOriginRequired(swap.rfqId);
1798
1679
  this.origins.set(swap.rfqId, rfqSwapOriginOf(stored));
1799
1680
  }
1800
- /** Forget a swap entirely, monitored or finished.
1801
- *
1802
- * Its contract row is left alone: registration is a wallet-level fact about
1803
- * a script that may still hold money, and this call says only that THIS
1804
- * manager stops driving the swap. Retiring the row is reserved for a swap
1805
- * that reached a terminal state, where the lockup is provably done. */
1681
+ /** Forget a swap entirely, monitored or finished. Its contract row is left alone: the
1682
+ * script may still hold money, and only a terminal swap's row is retired. */
1806
1683
  async removeSwap(rfqId) {
1684
+ this.removed.set(rfqId, ++this.removalSeq);
1807
1685
  this.untrack(rfqId);
1808
1686
  this.finished.delete(rfqId);
1809
1687
  this.registered.delete(rfqId);
@@ -1821,14 +1699,8 @@ var RfqSwapManager = class {
1821
1699
  return [...this.monitored.values()];
1822
1700
  }
1823
1701
  /**
1824
- * Every swap this manager holds — {@link getPendingSwaps} plus the ones
1825
- * that already ended. The two sets are disjoint: a swap leaves `monitored`
1826
- * as it enters `finished`.
1827
- *
1828
- * The finished half is what this process has seen, which after
1829
- * {@link restoreFromRepository} is the stored history minus what retention
1830
- * pruned. A manager that has restored nothing answers with the live swaps
1831
- * alone.
1702
+ * Every swap this manager holds: {@link getPendingSwaps} plus the finished ones this
1703
+ * process has seen (after {@link restoreFromRepository}, the retained history).
1832
1704
  */
1833
1705
  async getAllSwaps() {
1834
1706
  return [...this.monitored.values(), ...this.finished.values()];
@@ -1840,6 +1712,7 @@ var RfqSwapManager = class {
1840
1712
  async isProcessing(rfqId) {
1841
1713
  return this.inProgress.has(rfqId);
1842
1714
  }
1715
+ /** `finishedSwaps` counts terminal swaps cached in memory, not those only in the repository. */
1843
1716
  async getStats() {
1844
1717
  return {
1845
1718
  isRunning: this.running,
@@ -1850,34 +1723,54 @@ var RfqSwapManager = class {
1850
1723
  };
1851
1724
  }
1852
1725
  /**
1853
- * Run one monitoring pass over every swap now.
1854
- *
1855
- * {@link start} calls this on an interval, but it is public on purpose: a
1856
- * caller that sleeps its process (a mobile app resuming, a service worker
1857
- * waking) wants a pass on that event rather than at the next tick. Passes
1858
- * do not overlap per swap — the in-progress lock makes a concurrent call a
1859
- * no-op for any swap already being worked on.
1726
+ * Run one monitoring pass over every swap now, e.g. when a mobile app resumes. Passes
1727
+ * do not overlap per swap: a concurrent call is a no-op for a swap already in progress.
1860
1728
  */
1861
1729
  async poll() {
1862
- await Promise.allSettled([...this.monitored.values()].map((swap) => this.pollSwap(swap)));
1730
+ await this.pollMany([...this.monitored.values()]);
1731
+ }
1732
+ async pollMany(swaps) {
1733
+ for (let i = 0; i < swaps.length; i += _RfqSwapManager.POLL_CONCURRENCY) {
1734
+ await Promise.allSettled(
1735
+ swaps.slice(i, i + _RfqSwapManager.POLL_CONCURRENCY).map((swap) => this.pollSwap(swap))
1736
+ );
1737
+ }
1738
+ }
1739
+ async acquirePollSlot() {
1740
+ if (this.activePolls < _RfqSwapManager.POLL_CONCURRENCY) {
1741
+ this.activePolls++;
1742
+ } else {
1743
+ await new Promise((resolve) => this.pollWaiters.add(resolve));
1744
+ }
1745
+ return () => {
1746
+ const next = this.pollWaiters.values().next().value;
1747
+ if (next) {
1748
+ this.pollWaiters.delete(next);
1749
+ next();
1750
+ } else {
1751
+ this.activePolls--;
1752
+ }
1753
+ };
1863
1754
  }
1864
1755
  /**
1865
- * Resolve once this swap's PAYOUT is decided — which for onchain-send is
1866
- * the L1 claim, not the end of the record's life: once `claimTxid` is set
1867
- * the trader has the coins it swapped for, and what remains is the manager
1868
- * watching the Arkade lockup close. That holds however the record is
1869
- * labelled afterwards, `needs_counterparty` included. Lightning-send has no
1870
- * such split and resolves at `settled`/`refunded`, and so does lightning
1871
- * receive — see {@link isPayoutDecided} for why its own claim txid does not
1872
- * decide it.
1756
+ * Resolve once this swap's PAYOUT is decided: for onchain-send that is the L1 claim
1757
+ * (`claimTxid` set), whatever the record's later label; otherwise `settled`/`refunded`
1758
+ * (see {@link isPayoutDecided}).
1873
1759
  *
1874
- * Rejects only on `failed`. `refunded` resolves: on a send leg a refund is
1875
- * an outcome the caller asked this manager to drive, not an exception. On a
1876
- * receive leg it is the swap being lost, which is still an answer and not
1877
- * an error — read `state`, do not infer success from resolution.
1760
+ * Rejects only on `failed`. `refunded` resolves, and on a receive leg it means the swap
1761
+ * was lost — read `state`, do not infer success from resolution.
1878
1762
  */
1879
1763
  async waitForSwapCompletion(rfqId) {
1880
1764
  const swap = this.monitored.get(rfqId) ?? this.finished.get(rfqId);
1765
+ if (!swap && !this.removed.has(rfqId) && this.deps.repository) {
1766
+ const record = await this.deps.repository.getRfqSwap(rfqId);
1767
+ if (record && !this.removed.has(rfqId) && isRfqSwapTerminal(record.state)) {
1768
+ if (record.state === "failed") {
1769
+ throw new Error(record.failure ?? `swap ${rfqId} failed`);
1770
+ }
1771
+ return outcomeOfRecord(record);
1772
+ }
1773
+ }
1881
1774
  if (!swap) throw new Error(`swap ${rfqId} is not monitored`);
1882
1775
  if (swap.state === "failed") throw new Error(swap.failure ?? `swap ${rfqId} failed`);
1883
1776
  if (isPayoutDecided(swap)) return outcomeOf(swap);
@@ -1890,38 +1783,26 @@ var RfqSwapManager = class {
1890
1783
  // ── internals ────────────────────────────────────────────────────────────
1891
1784
  track(swap) {
1892
1785
  this.monitored.set(swap.rfqId, swap);
1893
- this.byLockupScript.set(hex6.encode(swap.lockupPkScript), swap);
1786
+ this.byLockupScript.set(hex5.encode(swap.lockupPkScript), swap);
1894
1787
  }
1895
- /** Drops the swap from BOTH indexes. The event index is the one that stops
1896
- * a late event finding a swap that is gone; `pollSwap`'s own
1897
- * `monitored` check would also catch it, and deliberately still does —
1898
- * either alone is sufficient, which is what keeps a future change to one of
1899
- * them from silently re-driving a cancelled swap. */
1788
+ /** Drops the swap from BOTH indexes. `pollSwap`'s `monitored` check also stops a late
1789
+ * event, deliberately redundant so neither change alone re-drives a removed swap. */
1900
1790
  untrack(rfqId) {
1901
1791
  const swap = this.monitored.get(rfqId);
1902
- if (swap) this.byLockupScript.delete(hex6.encode(swap.lockupPkScript));
1792
+ if (swap) this.byLockupScript.delete(hex5.encode(swap.lockupPkScript));
1903
1793
  this.monitored.delete(rfqId);
1904
1794
  this.refundRefused.delete(rfqId);
1905
1795
  this.claimedOutpoints.delete(rfqId);
1906
1796
  }
1907
1797
  /**
1908
- * Turn the indexer's push into an extra reason to run a pass — and nothing
1909
- * more.
1798
+ * Turn the indexer's push into an extra reason to run a pass — and nothing more.
1910
1799
  *
1911
- * **This is deliberately not a source of truth.** An event names a script;
1912
- * the reaction is to run the ordinary pass for the swap at that script, and
1913
- * that pass re-reads the lockup through {@link readLockupFate} exactly as
1914
- * the timer's pass does. So an event that is missed, duplicated, reordered
1915
- * or outright FORGED can only cost or save latency — it can never change
1916
- * what this manager believes about a swap, and it can never on its own
1917
- * cause a claim or a refund. That property is what makes it safe to bolt a
1918
- * best-effort stream onto a money path, and it must survive any future
1919
- * change here: the moment an event is BELIEVED rather than merely acted on,
1920
- * a relay outage becomes a correctness problem instead of a latency one.
1921
- *
1922
- * The timer stays armed regardless, and is the failsafe. Every deadline
1923
- * that moves money — `refundLocktime`, the L1 claim window — is an absolute
1924
- * timelock that passes whether or not a single event ever arrives.
1800
+ * **Deliberately not a source of truth.** The pass re-reads the lockup via
1801
+ * {@link readLockupFate}, so a missed, duplicated, reordered or FORGED event only
1802
+ * changes latency, never beliefs, and never causes a claim or refund on its own. This
1803
+ * must survive future changes: a BELIEVED event turns a relay outage into a correctness
1804
+ * bug. The timer stays armed as the failsafe; every money deadline is an absolute
1805
+ * timelock.
1925
1806
  */
1926
1807
  subscribe() {
1927
1808
  if (!this.deps.contracts || this.unsubscribeContracts) return;
@@ -1939,19 +1820,12 @@ var RfqSwapManager = class {
1939
1820
  });
1940
1821
  }
1941
1822
  /**
1942
- * Register this swap's lockup with the wallet's contract manager, once.
1943
- *
1944
- * The backstop, not the primary site: `requestLightningSend` /
1945
- * `requestOnchainSend` register before the caller can fund, so this covers
1946
- * swaps whose records predate that — and costs nothing when it does not,
1947
- * since `createContract` is first-writer-wins.
1823
+ * Register this swap's lockup with the wallet's contract manager, once. A backstop:
1824
+ * the request entrypoints register before funding, and `createContract` is
1825
+ * first-writer-wins.
1948
1826
  *
1949
- * Best-effort by design: a failure here is reported and retried on the next
1950
- * pass, and never aborts the pass it is part of. Registration buys latency
1951
- * and puts the lockup in the wallet's contract set; it decides nothing. The
1952
- * money path below it reads the indexer directly and is gated on timelocks
1953
- * that a missing contract row has no bearing on, so failing the pass over
1954
- * this would trade a real deadline for a bookkeeping one.
1827
+ * Best-effort: a failure is reported and retried next pass, never aborting this one.
1828
+ * Failing the pass over bookkeeping would trade a real timelock deadline for it.
1955
1829
  */
1956
1830
  async ensureRegistered(swap) {
1957
1831
  const contracts = this.deps.contracts;
@@ -1961,7 +1835,7 @@ var RfqSwapManager = class {
1961
1835
  if (!lockup) {
1962
1836
  try {
1963
1837
  const [existing] = await contracts.getContracts({
1964
- script: hex6.encode(swap.lockupPkScript)
1838
+ script: hex5.encode(swap.lockupPkScript)
1965
1839
  });
1966
1840
  if (existing) {
1967
1841
  this.registered.set(swap.rfqId, true);
@@ -1980,13 +1854,13 @@ var RfqSwapManager = class {
1980
1854
  );
1981
1855
  return;
1982
1856
  }
1983
- const script = hex6.encode(lockup.script.pkScript);
1984
- if (script !== hex6.encode(swap.lockupPkScript)) {
1857
+ const script = hex5.encode(lockup.script.pkScript);
1858
+ if (script !== hex5.encode(swap.lockupPkScript)) {
1985
1859
  this.registered.set(swap.rfqId, false);
1986
1860
  this.emitFailed(
1987
1861
  swap,
1988
1862
  new Error(
1989
- `swap ${swap.rfqId} lockup script ${script} does not match its lockupPkScript ${hex6.encode(swap.lockupPkScript)}`
1863
+ `swap ${swap.rfqId} lockup script ${script} does not match its lockupPkScript ${hex5.encode(swap.lockupPkScript)}`
1990
1864
  )
1991
1865
  );
1992
1866
  return;
@@ -1998,15 +1872,12 @@ var RfqSwapManager = class {
1998
1872
  this.emitFailed(swap, error);
1999
1873
  }
2000
1874
  }
2001
- /** Stop watching a finished swap's lockup. Retained, not deleted: the row
2002
- * is what keeps the lockup's own VTXOs annotatable and its history
2003
- * readable, while `retained` is what drops it from the subscription and
2004
- * the poll — a settled swap that stayed watched would cost the wallet a
2005
- * script for its whole life. Best-effort — the swap is over either way. */
1875
+ /** Stop watching a finished swap's lockup. `retained`, not deleted: the row keeps the
1876
+ * lockup's history readable while leaving the subscription and poll. Best-effort. */
2006
1877
  retireContract(swap) {
2007
1878
  if (!this.deps.contracts || !this.registered.get(swap.rfqId)) return;
2008
1879
  if (!LOCKUP_RETIRABLE.includes(swap.state)) return;
2009
- void this.deps.contracts.setContractWatchState(hex6.encode(swap.lockupPkScript), "retained").catch((error) => this.emitFailed(swap, error));
1880
+ void this.deps.contracts.setContractWatchState(hex5.encode(swap.lockupPkScript), "retained").catch((error) => this.emitFailed(swap, error));
2010
1881
  }
2011
1882
  arm() {
2012
1883
  if (!this.running) return;
@@ -2017,90 +1888,36 @@ var RfqSwapManager = class {
2017
1888
  }, this.config.pollIntervalMs);
2018
1889
  }
2019
1890
  /*
2020
- * Runs one serialized monitoring pass for a single swap.
2021
- *
2022
- * Flow
2023
- *
2024
- * 1. Prevents concurrent work
2025
- * - Returns immediately if the swap is already in inProgress.
2026
- * - Returns if the swap is no longer in monitored.
2027
- * - Adds the swap ID to inProgress.
2028
- *
2029
- * 2. Runs the state machine
2030
- * - Calls runPass(swap).
2031
- * - runPass checks the lockup fate, drives claims, and may initiate refunds.
2032
- *
2033
- * 3. Persists changes
2034
- * - If the pass marked the swap dirty, calls save(swap).
2035
- * - A swap is considered persisted only if all configured sinks succeed:
2036
- * - the repository, and
2037
- * - callbacks.saveSwap, if provided.
2038
- *
2039
- * 4. Completes waiters and finalizes
2040
- * - If persistence succeeds:
2041
- * - clears the dirty flag,
2042
- * - settles waitForSwapCompletion waiters,
2043
- * - moves terminal swaps from monitored to finished,
2044
- * - emits completion or failure notifications through finalize.
2045
- *
2046
- * 5. Releases the per-swap lock
2047
- * - Deletes the swap ID from inProgress only after all asynchronous work completes.
2048
- * - This prevents overlapping poll() calls from submitting duplicate claims or refunds.
1891
+ * One serialized monitoring pass for a single swap. The per-swap lock is released only
1892
+ * after all async work, so overlapping polls cannot submit duplicate claims or refunds.
2049
1893
  *
2050
- * The important safety property is that terminal state is not finalized until its updated record has been
2051
- * successfully persisted. A failed save leaves the swap dirty and monitored so a later poll can retry.
1894
+ * Safety property: terminal state is not finalized until its record is persisted to
1895
+ * every configured sink. A failed save leaves the swap dirty and monitored for retry.
2052
1896
  */
2053
1897
  async pollSwap(swap) {
2054
1898
  if (this.inProgress.has(swap.rfqId)) return;
2055
1899
  if (!this.monitored.has(swap.rfqId)) return;
2056
1900
  this.inProgress.add(swap.rfqId);
1901
+ const release = await this.acquirePollSlot();
2057
1902
  try {
2058
- await this.runPass(swap);
1903
+ if (this.monitored.has(swap.rfqId)) await this.runPass(swap);
2059
1904
  } finally {
2060
- const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
2061
- if (persisted) {
2062
- this.dirty.delete(swap.rfqId);
2063
- this.settleWaiters(swap);
2064
- if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
1905
+ try {
1906
+ const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
1907
+ if (persisted) {
1908
+ this.dirty.delete(swap.rfqId);
1909
+ this.settleWaiters(swap);
1910
+ if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
1911
+ }
1912
+ } finally {
1913
+ this.inProgress.delete(swap.rfqId);
1914
+ release();
2065
1915
  }
2066
- this.inProgress.delete(swap.rfqId);
2067
1916
  }
2068
1917
  }
2069
1918
  /*
2070
- * executes one monitoring/state-machine pass for a swap.
2071
- *
2072
- * Flow
2073
- * 1. Registers the lockup
2074
- * - Calls ensureRegistered(swap).
2075
- * - Registration is best effort and does not prevent the rest of the pass from running.
2076
- *
2077
- * 2. Reads the Arkade lockup fate
2078
- * - Calls readLockupFate.
2079
- * - A hash-verified claim is treated as claimed.
2080
- * - A fully observed non-claim spend is treated as returned.
2081
- * - Indexer errors become unknown, allowing deadline-driven logic to continue.
2082
- * - For claimed or returned, it:
2083
- * - records spend transaction IDs,
2084
- * - records the settlement preimage when applicable,
2085
- * - sets the swap state to settled or refunded,
2086
- * - ends the pass.
2087
- *
2088
- * 3. Handles unilateral exits
2089
- * - On receive swaps, an exited lockup is blocked immediately.
2090
- * - On send swaps, the L1 half continues to be monitored because an exit only describes the Arkade side.
2091
- *
2092
- * 4. Drives the trader’s claim
2093
- * - For lightning_receive, calls driveReceiveClaim and ends the pass.
2094
- * - For onchain_send, calls driveOnchain to classify and potentially claim the L1 HTLC.
2095
- * - A handled L1 action ends the pass; otherwise processing continues.
2096
- *
2097
- * 5. Drives an Arkade refund
2098
- * - For send swaps whose lockup remains unresolved, calls driveArkadeRefund.
2099
- * - This is gated by the refund timelock and local refund capability.
2100
- * - Receive swaps never reach this step because their refund path belongs to the solver.
2101
- *
2102
- * runPass only decides and performs state-machine actions. Persistence, waiter settlement, terminal finalization,
2103
- * and the per-swap lock are handled by pollSwap.
1919
+ * One state-machine pass (steps as in the class doc). Persistence, waiters,
1920
+ * finalization and the per-swap lock belong to `pollSwap`.
2104
1921
  */
2105
1922
  async runPass(swap) {
2106
1923
  await this.ensureRegistered(swap);
@@ -2136,15 +1953,9 @@ var RfqSwapManager = class {
2136
1953
  await this.driveArkadeRefund(swap);
2137
1954
  }
2138
1955
  /**
2139
- * The lockup was unilaterally exited: its outputs sit onchain under the
2140
- * VHTLC script, where no offchain claim or refund can reach them.
2141
- *
2142
- * `needs_counterparty` rather than a terminal state, because the money still
2143
- * needs action and the swap can still end either way — an onchain claim can
2144
- * reveal the preimage, an onchain refund can return it — and that state is
2145
- * documented as re-checked every pass. It must be set from HERE and not from
2146
- * inside `driveArkadeRefund`, whose two `unblock` calls would lift it again
2147
- * on the very next pass.
1956
+ * The lockup was unilaterally exited: its outputs sit onchain, beyond any offchain
1957
+ * spend. `needs_counterparty`, not terminal: it can still end either way onchain. Set
1958
+ * here, not in `driveArkadeRefund`, whose `unblock` calls would lift it next pass.
2148
1959
  */
2149
1960
  blockExitedLockup(swap, fate) {
2150
1961
  this.block(
@@ -2153,25 +1964,15 @@ var RfqSwapManager = class {
2153
1964
  );
2154
1965
  }
2155
1966
  /**
2156
- * The receive leg's whole state machine: claim the solver-funded lockup
2157
- * while the window is open, and recognise the shapes in which it can be
2158
- * lost.
1967
+ * The receive leg's whole state machine: claim the solver-funded lockup while the
1968
+ * window is open, and recognise the shapes in which it can be lost.
2159
1969
  *
2160
- * **The window closes at `refundLocktime`, on wall clock, with no margin.**
2161
- * Both halves of that are deliberate. It closes there because publishing
2162
- * `P` into the solver's live refund window risks losing the race and
2163
- * handing over the preimage anyway — the hazard `ONCHAIN_CLAIM_MARGIN_SECONDS`
2164
- * guards on the L1 side. It takes no margin because the two situations are
2165
- * not alike: that one budgets for confirmation depth, while this claim is an
2166
- * offchain spend that lands in seconds. Wall clock is already the
2167
- * conservative reading — the solver's leaf is a CLTV, which matures against
2168
- * median-time-past, and MTP trails wall clock — so the real window extends
2169
- * PAST this deadline rather than ending before it. Every second of margin
2170
- * subtracted here is a second of live claim window given away for nothing.
1970
+ * **The window closes at `refundLocktime`, on wall clock, with no margin.** Publishing
1971
+ * `P` into the solver's live refund window risks losing the race. No margin (unlike
1972
+ * `ONCHAIN_CLAIM_MARGIN_SECONDS`, which budgets for confirmations): this offchain claim
1973
+ * lands in seconds, and the solver's CLTV matures on MTP, which trails wall clock.
2171
1974
  *
2172
- * **The trader has no move after it.** Nothing here can take the lockup
2173
- * back, so once the window shuts the swap is the solver's to resolve and
2174
- * this manager's job is to watch it happen and then stop.
1975
+ * After the window the trader has no move; the manager only watches.
2175
1976
  */
2176
1977
  async driveReceiveClaim(swap) {
2177
1978
  const now = this.config.now();
@@ -2198,14 +1999,8 @@ var RfqSwapManager = class {
2198
1999
  }
2199
2000
  this.setState(swap, "refunded");
2200
2001
  }
2201
- /**
2202
- * Claim what the solver funded, once it is enough.
2203
- *
2204
- * The value gate here decides WHEN to act. `pushClaim`'s decides whether
2205
- * `P` is published, and runs with nothing between it and the signature —
2206
- * the check that matters is the inner one, and this is not a reason to
2207
- * relax it.
2208
- */
2002
+ /** Claim what the solver funded, once it is enough (the inner gate that matters is
2003
+ * `pushClaim`'s; see {@link RfqSwapManagerCallbacks.claimLockup}). */
2209
2004
  async claimIfFunded(swap, vtxos) {
2210
2005
  if (vtxos.length === 0) return this.unblock(swap);
2211
2006
  const partiallyClaimed = swap.claimTxid !== void 0;
@@ -2244,6 +2039,14 @@ var RfqSwapManager = class {
2244
2039
  this.setState(swap, "claimed");
2245
2040
  this.emitAction(swap, "claimLockup");
2246
2041
  } catch (error) {
2042
+ const ark = isArkError(error) ? error : maybeArkError(error);
2043
+ if (isArkError(ark, ArkErrorName.VTXO_ALREADY_SPENT)) {
2044
+ if (swap.claimFailure !== void 0) {
2045
+ delete swap.claimFailure;
2046
+ this.touch(swap);
2047
+ }
2048
+ return;
2049
+ }
2247
2050
  swap.claimFailure = errorMessage(error);
2248
2051
  this.touch(swap);
2249
2052
  this.emitFailed(swap, error);
@@ -2363,8 +2166,8 @@ var RfqSwapManager = class {
2363
2166
  }
2364
2167
  }
2365
2168
  }
2366
- /** Whether any of these outputs has never been handed to the claim
2367
- * callback — the only reason to claim a lockup a second time. */
2169
+ /** Whether any output was never handed to the claim callback (the only reason to
2170
+ * claim twice). */
2368
2171
  hasUnclaimedOutpoint(rfqId, vtxos) {
2369
2172
  const claimed = this.claimedOutpoints.get(rfqId);
2370
2173
  if (!claimed) return true;
@@ -2376,20 +2179,15 @@ var RfqSwapManager = class {
2376
2179
  this.claimedOutpoints.set(rfqId, claimed);
2377
2180
  }
2378
2181
  /**
2379
- * L1 progress, which past the refund window must not overwrite a refusal.
2380
- * The two halves are independent — a claimed fill says nothing about
2381
- * whether this wallet can take the Arkade lockup back — and `claimed` is
2382
- * re-asserted from chain on every pass, so without this a blocked swap
2383
- * would flip between the two states forever. The claim itself always runs;
2384
- * only the label defers, and only once the refund is the live half.
2182
+ * L1 progress, which past the refund window must not overwrite a refusal: `claimed` is
2183
+ * re-asserted from chain every pass, so a blocked swap would flip forever. Only the
2184
+ * label defers; the claim itself always runs.
2385
2185
  */
2386
2186
  setOnchainState(swap, state) {
2387
2187
  if (swap.state === "needs_counterparty" && this.config.now() >= swap.refundLocktime) return;
2388
2188
  this.setState(swap, state);
2389
2189
  }
2390
- /** The probe's refusal reason, or `undefined` when a local refund is
2391
- * possible as far as anyone here can tell. A probe that throws is treated
2392
- * as a refusal: a capability check that cannot answer is not a yes. */
2190
+ /** The probe's refusal reason, or `undefined`. A throwing probe is a refusal. */
2393
2191
  async probeRefusal(swap) {
2394
2192
  const probe = this.callbacks?.canRefundArkade;
2395
2193
  if (!probe) return void 0;
@@ -2408,25 +2206,16 @@ var RfqSwapManager = class {
2408
2206
  }
2409
2207
  this.setState(swap, "needs_counterparty");
2410
2208
  }
2411
- /** The way back out, taken as soon as the swap becomes actionable again.
2412
- * Back to what the record can prove, not to `pending` unconditionally: a
2413
- * swap that already made its claim has a txid for it, and reporting that
2414
- * swap as `pending` would un-say something true. */
2209
+ /** The way back out once actionable: to `claimed` if a claim txid exists, else
2210
+ * `pending`. */
2415
2211
  unblock(swap) {
2416
2212
  if (swap.state !== "needs_counterparty") return;
2417
2213
  this.setState(swap, traderClaimTxid(swap) ? "claimed" : "pending");
2418
2214
  }
2419
2215
  /**
2420
- * Record which ark transactions ended the lockup.
2421
- *
2422
- * Only the ones the indexer actually named: `LockupSpend.txid` is
2423
- * optional, and a checkpoint txid is not what history correlates on — a
2424
- * record carrying one would name a transaction the wallet's own activity
2425
- * never shows. Fewer txids is the right failure here.
2426
- *
2427
- * Assigned rather than merged: the fate is one read of the whole lockup,
2428
- * so it is the complete answer for this swap, and a swap only reaches a
2429
- * verdict once.
2216
+ * Record which ark transactions ended the lockup. Only named ark txids: a checkpoint
2217
+ * txid would name a transaction the wallet's activity never shows. Assigned, not
2218
+ * merged: the fate is one complete read, reached once.
2430
2219
  */
2431
2220
  stampLockupSpends(swap, spends) {
2432
2221
  const txids = spends.map((spend) => spend.txid).filter((txid) => txid !== void 0);
@@ -2435,16 +2224,12 @@ var RfqSwapManager = class {
2435
2224
  this.touch(swap);
2436
2225
  }
2437
2226
  /**
2438
- * Keep the preimage that settled a Lightning send.
2439
- *
2440
- * Only that leg. A receive's `claimed` verdict reveals the wallet's own
2441
- * claim secret and an onchain send's reveals the one it minted — both
2442
- * already recoverable from `profile`, so stamping either would be a second
2443
- * home for a secret that has one.
2227
+ * Keep the preimage that settled a Lightning send. Only that leg: the others' preimages
2228
+ * are the wallet's own secrets, already recoverable from `profile`.
2444
2229
  */
2445
2230
  stampSettlementPreimage(swap, preimage) {
2446
2231
  if (swap.kind !== "lightning_send") return;
2447
- swap.settlementPreimageHex = hex6.encode(preimage);
2232
+ swap.settlementPreimageHex = hex5.encode(preimage);
2448
2233
  this.touch(swap);
2449
2234
  }
2450
2235
  touch(swap) {
@@ -2474,24 +2259,9 @@ var RfqSwapManager = class {
2474
2259
  notify(this.actionExecutedListeners, (listener) => listener(swap, action));
2475
2260
  }
2476
2261
  /**
2477
- * Flush a changed record to every sink that is wired, and say whether all
2478
- * of them took it.
2479
- *
2480
- * Up to two writes, in this order: the canonical `RfqSwapRecord` to
2481
- * {@link RfqSwapManagerDeps.repository}, then
2482
- * {@link RfqSwapManagerCallbacks.saveSwap}. Both gate — a rejection from
2483
- * either leaves the record dirty and monitored, so waiters stay unsettled
2484
- * and a terminal swap is not finalized until the write it claims lands.
2485
- * That is exactly today's rule for `saveSwap`, applied to whichever sinks
2486
- * exist; wiring the repository does not weaken it.
2487
- *
2488
- * The canonical write goes FIRST and a failure there skips the second.
2489
- * `saveSwap` is a projection of the record, and projecting a state the
2490
- * record of record has just refused would leave the secondary sink ahead
2491
- * of the primary — the one ordering that survives no restart.
2492
- *
2493
- * With neither wired the state is process-local, which is what a manager
2494
- * with no callbacks has always done.
2262
+ * Flush a changed record to every wired sink; true only if all took it (else it stays
2263
+ * dirty and unfinalized). The canonical repository write goes FIRST and a failure skips
2264
+ * `saveSwap`, so the secondary sink never gets ahead of the primary.
2495
2265
  */
2496
2266
  async save(swap) {
2497
2267
  if (!await this.saveRecord(swap)) return false;
@@ -2523,18 +2293,15 @@ var RfqSwapManager = class {
2523
2293
  if (!origin) throw new RfqSwapOriginRequired(swap.rfqId);
2524
2294
  return origin;
2525
2295
  }
2526
- /**
2527
- * Drop a terminal swap from monitoring and report it exactly once.
2528
- *
2529
- * `onSwapCompleted` and `onSwapFailed` are mutually exclusive here: a
2530
- * listener named "completed" that also fires on failure is a trap, so a
2531
- * swap that leaves monitoring reports through exactly one of them.
2532
- */
2296
+ /** Drop a terminal swap from monitoring and report it exactly once, through either
2297
+ * `onSwapCompleted` or `onSwapFailed`. */
2533
2298
  finalize(swap) {
2534
2299
  if (!this.monitored.has(swap.rfqId)) return;
2535
2300
  this.untrack(swap.rfqId);
2536
- this.finished.set(swap.rfqId, swap);
2301
+ this.rememberFinished(swap, true);
2537
2302
  this.retireContract(swap);
2303
+ this.registered.delete(swap.rfqId);
2304
+ this.origins.delete(swap.rfqId);
2538
2305
  if (swap.state === "failed") {
2539
2306
  notify(
2540
2307
  this.swapFailedListeners,
@@ -2544,6 +2311,10 @@ var RfqSwapManager = class {
2544
2311
  }
2545
2312
  notify(this.swapCompletedListeners, (listener) => listener(swap));
2546
2313
  }
2314
+ rememberFinished(swap, durable = false) {
2315
+ if (durable && this.deps.repository) this.finished.delete(swap.rfqId);
2316
+ else this.finished.set(swap.rfqId, swap);
2317
+ }
2547
2318
  settleWaiters(swap) {
2548
2319
  const waiting = this.waiters.get(swap.rfqId);
2549
2320
  if (!waiting) return;
@@ -2559,16 +2330,7 @@ var RfqSwapManager = class {
2559
2330
  this.waiters.delete(swap.rfqId);
2560
2331
  }
2561
2332
  };
2562
- var traderClaimTxid = (swap) => {
2563
- switch (swap.kind) {
2564
- case "onchain_send":
2565
- return swap.claimTxid;
2566
- case "lightning_receive":
2567
- return swap.claimTxid;
2568
- default:
2569
- return void 0;
2570
- }
2571
- };
2333
+ var traderClaimTxid = (swap) => swap.kind === "onchain_send" || swap.kind === "lightning_receive" ? swap.claimTxid : void 0;
2572
2334
  var isPayoutDecided = (swap) => swap.state === "settled" || swap.state === "refunded" || swap.kind === "onchain_send" && swap.claimTxid !== void 0;
2573
2335
  var outcomeOf = (swap) => {
2574
2336
  const lostReceive = swap.kind === "lightning_receive" && swap.state === "refunded";
@@ -2577,11 +2339,20 @@ var outcomeOf = (swap) => {
2577
2339
  txid: lostReceive ? swap.refundTxid : traderClaimTxid(swap) ?? swap.refundTxid
2578
2340
  };
2579
2341
  };
2342
+ var outcomeOfRecord = (stored) => {
2343
+ const record = normalizeRfqSwapRecord(stored);
2344
+ const profileClaim = record.kind === "onchain_send" || record.kind === "lightning_receive" ? record.profile.claimTxid : void 0;
2345
+ const claimTxid = typeof profileClaim === "string" ? profileClaim : void 0;
2346
+ return {
2347
+ state: record.state,
2348
+ txid: record.kind === "lightning_receive" && record.state === "refunded" ? record.refundTxid : claimTxid ?? record.refundTxid
2349
+ };
2350
+ };
2580
2351
  var errorMessage = (error) => error instanceof Error ? error.message : String(error);
2581
2352
  var outpointKey = (vtxo) => `${vtxo.txid}:${vtxo.vout}`;
2582
2353
 
2583
2354
  // src/watch.ts
2584
- import { base64 as base643, hex as hex7 } from "@scure/base";
2355
+ import { base64 as base643, hex as hex6 } from "@scure/base";
2585
2356
  import {
2586
2357
  ArkAddress as ArkAddress2,
2587
2358
  isContractVtxoEvent as isContractVtxoEvent2,
@@ -2631,7 +2402,7 @@ async function watchOfferSwaps({
2631
2402
  if (candidates.length === 0) return "indeterminate";
2632
2403
  const { txs } = await indexer.getVirtualTxs(candidates);
2633
2404
  return classifyDepositSpend(
2634
- decodeOffer(hex7.decode(swap.offerHex)),
2405
+ decodeOffer(hex6.decode(swap.offerHex)),
2635
2406
  operatorPubkey,
2636
2407
  txs.map((psbt) => Transaction3.fromPSBT(base643.decode(psbt))),
2637
2408
  { txid: vtxo.txid, vout: vtxo.vout }
@@ -2679,6 +2450,7 @@ export {
2679
2450
  onchainSendProfile,
2680
2451
  INVOICE_HRPS,
2681
2452
  networksOfInvoiceHrp,
2453
+ PAYMENT_HASH,
2682
2454
  LIGHTNING_DRIVE,
2683
2455
  lightningCorridor,
2684
2456
  ONCHAIN_DRIVE,