@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
@@ -2,6 +2,7 @@ import {
2
2
  LOCKUP_OWNER,
3
3
  LockupNeedsRecoveryError,
4
4
  MARKETS_CACHE_TTL_MS,
5
+ PAYMENT_HASH,
5
6
  QUOTE_OPTIONS,
6
7
  RefundNotLocallyPossibleError,
7
8
  RfqSwapManager,
@@ -33,9 +34,10 @@ import {
33
34
  spendTxidsOf,
34
35
  walletOperator,
35
36
  watchOfferSwaps
36
- } from "./chunk-ZDFMD4FA.js";
37
+ } from "./chunk-RX3WPV5D.js";
37
38
  import {
38
39
  ARKADE_BTC,
40
+ ASSET_CARRIER_SATS,
39
41
  AddressMismatch,
40
42
  BTC_ASSET_ID,
41
43
  L1_NETWORKS,
@@ -47,6 +49,7 @@ import {
47
49
  ONCHAIN_DUST_SATS,
48
50
  OfferCovenantMismatchError,
49
51
  SwapRefusal,
52
+ arkadeSwapRequest,
50
53
  assertFundable,
51
54
  assertPairLength,
52
55
  assertReceivable,
@@ -55,23 +58,34 @@ import {
55
58
  decodeOffer,
56
59
  deriveLightningReceive,
57
60
  deriveLightningSend,
61
+ deriveOffer,
58
62
  deriveOnchainSend,
63
+ getAssetSwapsOrThrow,
59
64
  l1NetworkFromArk,
60
65
  l1ScriptForAddress,
61
66
  lightningReceiveRequest,
62
67
  lightningSendRequest,
63
68
  lockupContractParams,
64
69
  newRfqId,
70
+ offerTermsFromQuote,
65
71
  onchainSendRequest,
66
72
  preimageForSwapRecord,
67
73
  prepareOfferCancel,
74
+ quoteCarrierSats,
75
+ registerDerivedOffer,
68
76
  registerLockupContract,
77
+ restoreOfferCoverage,
69
78
  retireOfferContract,
70
79
  retireSettledOfferContracts,
71
80
  rfqPair,
72
81
  sealClaimPacket,
73
- unilateralClaimDelay
74
- } from "./chunk-KRXPQQJ7.js";
82
+ unilateralClaimDelay,
83
+ verifyOfferAddress
84
+ } from "./chunk-BBP25BWH.js";
85
+ import {
86
+ assertRfqSwapPageFilter,
87
+ collectSwapRecords
88
+ } from "./chunk-A3SHHRX4.js";
75
89
 
76
90
  // src/client/assetId.ts
77
91
  import { asset, networks } from "@arkade-os/sdk";
@@ -94,10 +108,8 @@ var REFERENCE_RULE = {
94
108
  /** The 68-lowercase-hex identity form; `asset.AssetId` then re-validates it. */
95
109
  asset: /^[0-9a-f]{68}$/,
96
110
  /**
97
- * Reserved for §9. Lowercase, never EIP-55: a checksum belongs on an
98
- * address a human types, and an id here comes out of the alias table or a
99
- * market card. Mixed case would be two spellings of one asset comparing
100
- * unequal in a pair string, a record and a cache key.
111
+ * Reserved for §9. Lowercase, never EIP-55: mixed case would be two spellings of one asset
112
+ * comparing unequal in a pair string, a record and a cache key.
101
113
  */
102
114
  erc20: /^0x[0-9a-f]{40}$/
103
115
  };
@@ -210,8 +222,7 @@ var sameAsset = (a, b) => {
210
222
  return left.reference === right.reference && left.assetNamespace === right.assetNamespace && left.assetReference === right.assetReference;
211
223
  };
212
224
  var btcOn = (rail, network) => (
213
- // The checker will not resolve the conditional against an unbound `R`; the
214
- // assertion is confined to this expression and never reaches a call site.
225
+ // TS won't resolve the conditional against an unbound `R`; the cast stays in this expression.
215
226
  `${rail}:${network}/${BTC_ASSET_PART}`
216
227
  );
217
228
  var arkadeAsset = (network, id) => `arkade:${network}/${ARKADE_ASSET_NAMESPACE}:${id.toString()}`;
@@ -290,10 +301,10 @@ var QuoteExpired = class extends Error {
290
301
  name = "QuoteExpired";
291
302
  };
292
303
  var MaxFeeExceeded = class extends Error {
293
- constructor(quoteId, asset4, fee, maxFee) {
294
- super(`fee ${fee} of ${asset4} exceeds the ${maxFee} ceiling`);
304
+ constructor(quoteId, asset5, fee, maxFee) {
305
+ super(`fee ${fee} of ${asset5} exceeds the ${maxFee} ceiling`);
295
306
  this.quoteId = quoteId;
296
- this.asset = asset4;
307
+ this.asset = asset5;
297
308
  this.fee = fee;
298
309
  this.maxFee = maxFee;
299
310
  }
@@ -304,11 +315,11 @@ var MaxFeeExceeded = class extends Error {
304
315
  name = "MaxFeeExceeded";
305
316
  };
306
317
  var InsufficientFunds = class extends Error {
307
- constructor(asset4, required, available) {
318
+ constructor(asset5, required, available) {
308
319
  super(
309
- `funding needs ${required} of ${asset4}` + (available === void 0 ? "" : `, wallet holds ${available}`)
320
+ `funding needs ${required} of ${asset5}` + (available === void 0 ? "" : `, wallet holds ${available}`)
310
321
  );
311
- this.asset = asset4;
322
+ this.asset = asset5;
312
323
  this.required = required;
313
324
  this.available = available;
314
325
  }
@@ -346,9 +357,9 @@ var NotCancellable = class extends Error {
346
357
  name = "NotCancellable";
347
358
  };
348
359
  var InconsistentRoute = class extends Error {
349
- constructor(asset4, destination) {
350
- super(`destination ${JSON.stringify(destination)} is not on ${asset4}'s chain`);
351
- this.asset = asset4;
360
+ constructor(asset5, destination) {
361
+ super(`destination ${JSON.stringify(destination)} is not on ${asset5}'s chain`);
362
+ this.asset = asset5;
352
363
  this.destination = destination;
353
364
  }
354
365
  asset;
@@ -402,24 +413,24 @@ function isSwapError(e, name) {
402
413
  import { NETWORKS, isNetwork } from "@arkade-os/solver-discovery";
403
414
  var toDiscoveryLeg = (id) => {
404
415
  const { rail, assetNamespace, assetReference } = parseAssetId(id);
405
- const asset4 = `${assetNamespace}:${assetReference}`;
416
+ const asset5 = `${assetNamespace}:${assetReference}`;
406
417
  if (rail === "arkade") {
407
- if (asset4 === BTC_ASSET_PART)
418
+ if (asset5 === BTC_ASSET_PART)
408
419
  return { corridor: "arkade", assetId: BTC_ASSET_ID, marketId: id };
409
420
  if (assetNamespace === ARKADE_ASSET_NAMESPACE) {
410
421
  return { corridor: "arkade", assetId: assetReference, marketId: id };
411
422
  }
412
- throw new UnsupportedRoute(`the arkade corridor has no ${asset4}`);
423
+ throw new UnsupportedRoute(`the arkade corridor has no ${asset5}`);
413
424
  }
414
425
  if (rail === "bolt11") {
415
- if (asset4 === BTC_ASSET_PART)
426
+ if (asset5 === BTC_ASSET_PART)
416
427
  return { corridor: "lightning", assetId: BTC_ASSET_ID, marketId: id };
417
- throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset4}`);
428
+ throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset5}`);
418
429
  }
419
430
  if (rail === "bitcoin") {
420
- if (asset4 === BTC_ASSET_PART)
431
+ if (asset5 === BTC_ASSET_PART)
421
432
  return { corridor: "onchain", assetId: BTC_ASSET_ID, marketId: id };
422
- throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset4}`);
433
+ throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset5}`);
423
434
  }
424
435
  throw new UnsupportedRoute(`no corridor serves ${id}`);
425
436
  };
@@ -489,20 +500,13 @@ var Amount = {
489
500
  /**
490
501
  * A human decimal into atomic units.
491
502
  *
492
- * `string` only, and no exponent. Accepting a `number` is the whole v1
493
- * footgun: it makes `100000` ambiguous between sats and whole BTC, and by
494
- * the time the ambiguity resolves the offer is funded. Exponent form goes
495
- * for the same reason — a UI never produces `1e-4`, so accepting it only
496
- * widens what a mistake can look like.
497
- *
498
- * Refuses rather than rounds when the input is finer than the asset: a
499
- * silently truncated amount is a swap for the wrong size, and nothing
500
- * downstream can tell it was ever a different number. Refuses too when the
501
- * result would not survive the record boundary, so one law holds in both
502
- * directions.
503
+ * `string` only, no exponent: a `number` makes `100000` ambiguous between sats and BTC, and the
504
+ * ambiguity resolves only after funding. Refuses rather than rounds input finer than the asset
505
+ * (a truncated amount is a swap for the wrong size), and refuses results that would not survive
506
+ * the record boundary.
503
507
  */
504
- parse(display, asset4) {
505
- assertDecimals(asset4.decimals);
508
+ parse(display, asset5) {
509
+ assertDecimals(asset5.decimals);
506
510
  const parts = SCALED_DECIMAL.exec(display);
507
511
  if (!parts) {
508
512
  throw new AmountFormatError(
@@ -511,32 +515,28 @@ var Amount = {
511
515
  );
512
516
  }
513
517
  const [, whole, fraction = ""] = parts;
514
- if (fraction.length > asset4.decimals) {
518
+ if (fraction.length > asset5.decimals) {
515
519
  throw new AmountFormatError(
516
520
  "too_precise",
517
- `${display} has more precision than ${asset4.decimals} decimals allow`
521
+ `${display} has more precision than ${asset5.decimals} decimals allow`
518
522
  );
519
523
  }
520
524
  if (whole.length + fraction.length > MAX_SIGNIFICANT_DIGITS) {
521
525
  throw new AmountFormatError("too_large", `${display} has too many digits`);
522
526
  }
523
- const value = toAtomic(display, asset4.decimals);
524
- assertRepresentable(value, `${display} at ${asset4.decimals} decimals`);
527
+ const value = toAtomic(display, asset5.decimals);
528
+ assertRepresentable(value, `${display} at ${asset5.decimals} decimals`);
525
529
  return value;
526
530
  },
527
- /**
528
- * Atomic units into a human decimal, trailing zeros trimmed.
529
- *
530
- * Refuses a negative: every amount on this surface is an obligation, and a
531
- * negative one is a defect upstream rather than a number to render.
532
- */
533
- format(value, asset4) {
534
- assertDecimals(asset4.decimals);
531
+ /** Atomic units into a human decimal, trailing zeros trimmed. Refuses a negative: every amount
532
+ * here is an obligation, so a negative one is an upstream defect. */
533
+ format(value, asset5) {
534
+ assertDecimals(asset5.decimals);
535
535
  if (value < 0n) {
536
536
  throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
537
537
  }
538
538
  assertRepresentable(value, `${value}`);
539
- return fromAtomic(value, asset4.decimals);
539
+ return fromAtomic(value, asset5.decimals);
540
540
  }
541
541
  };
542
542
  var toAtomicDecimal = (value) => {
@@ -589,8 +589,6 @@ var decodeRfqAmount = (raw, field) => {
589
589
  throw new AmountEncodingUnsupported(
590
590
  field,
591
591
  `${raw}`,
592
- // Past 2^53 the number arrived already rounded — there is no
593
- // "narrow carefully" branch, only a wrong amount.
594
592
  "a JSON number amount is only readable as a non-negative safe integer"
595
593
  );
596
594
  }
@@ -618,7 +616,10 @@ var assetSwapIdOf = (family, quoteId) => `${family}:${quoteId}`;
618
616
  var OFFER_SWAP_ID_PREFIX = "offer:";
619
617
  var RFQ_SWAP_ID_PREFIX = "rfq:";
620
618
  var familyOfSwapId = (swapId) => swapId.startsWith(OFFER_SWAP_ID_PREFIX) ? "offer" : swapId.startsWith(RFQ_SWAP_ID_PREFIX) ? "rfq" : void 0;
621
- 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;
619
+ var quoteIdOfSwapId = (swapId) => {
620
+ const family = familyOfSwapId(swapId);
621
+ return family === void 0 ? swapId : swapId.slice(`${family}:`.length);
622
+ };
622
623
  var recordEndpoint = (endpoint2) => ({
623
624
  corridor: endpoint2.corridor,
624
625
  asset: endpoint2.asset,
@@ -701,8 +702,7 @@ var swapOf = (record, outcome) => ({
701
702
  fee: legOf(record.fee),
702
703
  market: record.market,
703
704
  ...record.solver === void 0 ? {} : { solver: record.solver },
704
- ...record.family === "rfq" ? { lock: record.lock } : {},
705
- ...record.family === "rfq" ? { refundLocktime: record.refundLocktime } : {},
705
+ ...record.family === "rfq" ? { lock: record.lock, refundLocktime: record.refundLocktime } : {},
706
706
  ...record.artifact === void 0 ? {} : { artifact: artifactOf(record.artifact) },
707
707
  expiresAt: record.expiresAt,
708
708
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
@@ -788,15 +788,7 @@ var marketSourceOf = (market) => market.kind === "card" ? market.source : void 0
788
788
  var assertFundable2 = async (wallet, quote) => {
789
789
  const give = quote.give;
790
790
  const balance = await wallet.getBalance();
791
- if (assetPartOf(give.asset) === BTC_ASSET_PART) {
792
- const available2 = BigInt(balance.available);
793
- if (available2 < give.amount) {
794
- throw new InsufficientFunds(give.asset, give.amount, available2);
795
- }
796
- return;
797
- }
798
- const held = balance.availableAssets.find((a) => give.asset.endsWith(a.assetId));
799
- const available = held?.amount ?? 0n;
791
+ const available = assetPartOf(give.asset) === BTC_ASSET_PART ? BigInt(balance.available) : balance.availableAssets.find((a) => give.asset.endsWith(a.assetId))?.amount ?? 0n;
800
792
  if (available < give.amount) {
801
793
  throw new InsufficientFunds(give.asset, give.amount, available);
802
794
  }
@@ -825,7 +817,7 @@ var corridorRecord = (quote, preparation, now) => {
825
817
  ...commonOf(quote, now),
826
818
  family: "rfq",
827
819
  state: "pending",
828
- kind: kindOf(preparation),
820
+ kind: KIND_OF[preparation.route],
829
821
  rfqId: preparation.rfqId,
830
822
  lockupAddress: preparation.lockup.address,
831
823
  lockupPkScript: hex.encode(preparation.lockup.pkScript),
@@ -834,15 +826,10 @@ var corridorRecord = (quote, preparation, now) => {
834
826
  profile: profileOf(preparation, quote.lock.hash)
835
827
  };
836
828
  };
837
- var kindOf = (preparation) => {
838
- switch (preparation.route) {
839
- case "arkade->lightning":
840
- return "lightning_send";
841
- case "lightning->arkade":
842
- return "lightning_receive";
843
- case "arkade->onchain":
844
- return "onchain_send";
845
- }
829
+ var KIND_OF = {
830
+ "arkade->lightning": "lightning_send",
831
+ "lightning->arkade": "lightning_receive",
832
+ "arkade->onchain": "onchain_send"
846
833
  };
847
834
  var profileOf = (preparation, paymentHash) => {
848
835
  const secrets = rfqSecretsProfile(preparation.secrets, paymentHash);
@@ -899,7 +886,7 @@ var acceptQuoteBody = async (input) => {
899
886
  }
900
887
  const funds = fundsFromWallet(quote.route);
901
888
  if (funds) await assertFundable2(wallet, quote);
902
- const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
889
+ const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : preparation.route === "arkade->arkade" ? await registeredAssetRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
903
890
  await repository.saveSwapRecord(record);
904
891
  if (!funds) return answer(record);
905
892
  return answer(await fundAndStamp({ wallet, now }, record, repository));
@@ -924,6 +911,18 @@ var registeredOfferRecord = async (input, preparation) => {
924
911
  swapPkScript: hex.encode(offer.swapPkScript)
925
912
  };
926
913
  };
914
+ var registeredAssetRecord = async (input, preparation) => {
915
+ await registerDerivedOffer(input.wallet, preparation.offer);
916
+ return {
917
+ ...commonOf(input.quote, input.now),
918
+ family: "offer",
919
+ status: "pending",
920
+ offerHex: preparation.offer.offerHex,
921
+ swapAddress: preparation.offer.address,
922
+ swapPkScript: hex.encode(preparation.offer.swapPkScript),
923
+ ...preparation.carrierSats === void 0 ? {} : { carrierSats: preparation.carrierSats.toString() }
924
+ };
925
+ };
927
926
  var registeredCorridorRecord = async (input, preparation) => {
928
927
  const contracts = await input.wallet.getContractManager();
929
928
  await registerLockupContract(contracts, preparation.lockup.script, preparation.lockup.address);
@@ -949,9 +948,10 @@ var fund = async (input, record) => {
949
948
  const depositIsBtc = assetPartOf(record.route.give.asset) === BTC_ASSET_PART;
950
949
  return wallet.send({
951
950
  address: record.swapAddress,
952
- // An asset deposit rides the SDK's dust-sat carrier, so the sats
953
- // amount is left to the default rather than set here.
951
+ // An asset deposit rides a dust-sat carrier: the solver's published one when the record
952
+ // names it (the fill is priced against it), else the SDK default.
954
953
  ...depositIsBtc ? { amount: toSafeNumber(amount, "give.amount") } : {
954
+ ...record.carrierSats === void 0 ? {} : { amount: toSafeNumber(BigInt(record.carrierSats), "carrierSats") },
955
955
  assets: [
956
956
  { assetId: toDiscoveryLeg(record.route.give.asset).assetId, amount }
957
957
  ]
@@ -1069,7 +1069,6 @@ var DEFAULT_INVOICE_EXPIRY_SECONDS = 3600;
1069
1069
  var valueOf = (decoded, name) => decoded.sections.find(
1070
1070
  (section) => section.name === name
1071
1071
  )?.value;
1072
- var PAYMENT_HASH = /^[0-9a-f]{64}$/;
1073
1072
  var decodeBolt11 = (invoice) => {
1074
1073
  const decoded = bolt11.decode(invoice);
1075
1074
  const timestamp = valueOf(decoded, "timestamp");
@@ -1120,11 +1119,8 @@ var chainSourceOver = (backend, network) => {
1120
1119
  return coins.map((coin) => ({
1121
1120
  txid: coin.txid,
1122
1121
  vout: coin.vout,
1123
- // `Coin.value` is `number` sats; the HTLC's is `bigint`.
1124
1122
  amount: BigInt(coin.value),
1125
- // `Coin` carries a height, never a depth, so the tip is the
1126
- // second half of the answer. A confirmed coin is one deep, not
1127
- // zero — the block it landed in counts.
1123
+ // A confirmed coin is one deep, not zero: its own block counts.
1128
1124
  confirmations: coin.status.confirmed && coin.status.block_height !== void 0 ? Math.max(0, tip.height - coin.status.block_height + 1) : 0
1129
1125
  }));
1130
1126
  },
@@ -1183,6 +1179,12 @@ var refusedIfNull = (value, corridor, dep) => {
1183
1179
  if (value === null) throw new MissingCorridorDep(corridor, dep);
1184
1180
  return value;
1185
1181
  };
1182
+ var refusedIfMalformed = (value, dep) => {
1183
+ if (value !== void 0 && value !== null && !(Number.isFinite(value) && value > 0)) {
1184
+ throw new MissingCorridorDep("onchain", dep);
1185
+ }
1186
+ return value;
1187
+ };
1186
1188
  var emulatorPubkeyFor = (base) => {
1187
1189
  if (base.emulatorPubkey !== void 0) {
1188
1190
  return resolveEmulatorPubkey(base.network, base.emulatorPubkey);
@@ -1224,16 +1226,12 @@ function resolveCorridorDeps(corridor, overrides, base) {
1224
1226
  case "onchain": {
1225
1227
  const chain = refusedIfNull(overrides?.onchain?.chain, "onchain", "chain source");
1226
1228
  const claim = refusedIfNull(overrides?.onchain?.claim, "onchain", "L1 claim callback");
1227
- const feeRateOverride = overrides?.onchain?.claimFeeRateSatVb;
1228
- if (feeRateOverride !== void 0 && feeRateOverride !== null && !(Number.isFinite(feeRateOverride) && feeRateOverride > 0)) {
1229
- throw new MissingCorridorDep("onchain", "L1 claim fee rate");
1230
- }
1229
+ const feeRateOverride = refusedIfMalformed(
1230
+ overrides?.onchain?.claimFeeRateSatVb,
1231
+ "L1 claim fee rate"
1232
+ );
1231
1233
  const claimFeeRateSatVb = feeRateOverride === null ? void 0 : feeRateOverride ?? ONCHAIN_CLAIM_FEE_RATE_SATVB[base.networkName];
1232
- const vsizeOverride = overrides?.onchain?.claimVsize;
1233
- if (vsizeOverride !== void 0 && vsizeOverride !== null && !(Number.isFinite(vsizeOverride) && vsizeOverride > 0)) {
1234
- throw new MissingCorridorDep("onchain", "L1 claim vsize");
1235
- }
1236
- const claimVsize = vsizeOverride === null ? ONCHAIN_CLAIM_VSIZE : vsizeOverride ?? ONCHAIN_CLAIM_VSIZE;
1234
+ const claimVsize = refusedIfMalformed(overrides?.onchain?.claimVsize, "L1 claim vsize") ?? ONCHAIN_CLAIM_VSIZE;
1237
1235
  return {
1238
1236
  networkName: base.networkName,
1239
1237
  chain: esploraChainSource({
@@ -1242,8 +1240,6 @@ function resolveCorridorDeps(corridor, overrides, base) {
1242
1240
  fetchImpl: base.fetchImpl
1243
1241
  }),
1244
1242
  ...claim === void 0 ? {} : { claim },
1245
- // Absent-on-an-unknown-network and explicitly-off read the
1246
- // same: no default claim path, manual mode.
1247
1243
  ...claimFeeRateSatVb === void 0 ? {} : { claimFeeRateSatVb },
1248
1244
  claimVsize
1249
1245
  };
@@ -1399,8 +1395,7 @@ var discoveryIndex = (input) => {
1399
1395
  markets: cached.markets,
1400
1396
  ref: {
1401
1397
  fetchedAt: cached.fetchedAt,
1402
- // The cards were read back out of local storage, whatever their
1403
- // age: nothing here can attest that a registry ever served them.
1398
+ // Whatever its age: nothing attests a registry ever served these cards.
1404
1399
  live: false,
1405
1400
  source: "cache",
1406
1401
  registry: url
@@ -1460,7 +1455,7 @@ var discoveryIndex = (input) => {
1460
1455
  };
1461
1456
 
1462
1457
  // src/client/driveRecords.ts
1463
- import { asset as asset3 } from "@arkade-os/sdk";
1458
+ import { asset as asset3, assertPageRequest, pageResult } from "@arkade-os/sdk";
1464
1459
  var splitRecords = (records) => {
1465
1460
  const corridor = [];
1466
1461
  const offer = [];
@@ -1479,12 +1474,15 @@ var rfqRecordOf = (record) => ({
1479
1474
  state: record.state,
1480
1475
  createdAt: record.createdAt,
1481
1476
  updatedAt: record.updatedAt,
1482
- ...record.refundTxid === void 0 ? {} : { refundTxid: record.refundTxid },
1483
- ...record.lockupSpendTxids?.length ? { lockupSpendTxids: [...record.lockupSpendTxids] } : {},
1484
- ...record.settlementPreimageHex === void 0 ? {} : { settlementPreimageHex: record.settlementPreimageHex },
1485
- ...record.failure === void 0 ? {} : { failure: record.failure },
1486
- ...record.claimFailure === void 0 ? {} : { claimFailure: record.claimFailure },
1487
- ...record.blockedReason === void 0 ? {} : { blockedReason: record.blockedReason }
1477
+ ...mutableHalfOf(record)
1478
+ });
1479
+ var mutableHalfOf = (from) => ({
1480
+ ...from.refundTxid === void 0 ? {} : { refundTxid: from.refundTxid },
1481
+ ...from.lockupSpendTxids?.length ? { lockupSpendTxids: [...from.lockupSpendTxids] } : {},
1482
+ ...from.settlementPreimageHex === void 0 ? {} : { settlementPreimageHex: from.settlementPreimageHex },
1483
+ ...from.failure === void 0 ? {} : { failure: from.failure },
1484
+ ...from.claimFailure === void 0 ? {} : { claimFailure: from.claimFailure },
1485
+ ...from.blockedReason === void 0 ? {} : { blockedReason: from.blockedReason }
1488
1486
  });
1489
1487
  var withRfqState = (record, state) => {
1490
1488
  const {
@@ -1501,12 +1499,7 @@ var withRfqState = (record, state) => {
1501
1499
  state: state.state,
1502
1500
  profile: state.profile,
1503
1501
  updatedAt: state.updatedAt,
1504
- ...state.refundTxid === void 0 ? {} : { refundTxid: state.refundTxid },
1505
- ...state.lockupSpendTxids?.length ? { lockupSpendTxids: [...state.lockupSpendTxids] } : {},
1506
- ...state.settlementPreimageHex === void 0 ? {} : { settlementPreimageHex: state.settlementPreimageHex },
1507
- ...state.failure === void 0 ? {} : { failure: state.failure },
1508
- ...state.claimFailure === void 0 ? {} : { claimFailure: state.claimFailure },
1509
- ...state.blockedReason === void 0 ? {} : { blockedReason: state.blockedReason }
1502
+ ...mutableHalfOf(state)
1510
1503
  };
1511
1504
  };
1512
1505
  var corridorRecordStore = (repository, onRecord = () => {
@@ -1521,7 +1514,7 @@ var corridorRecordStore = (repository, onRecord = () => {
1521
1514
  const record = await repository.getSwapRecord(known);
1522
1515
  if (record?.family === "rfq") return record;
1523
1516
  }
1524
- const { corridor } = splitRecords(await repository.getAllSwapRecords());
1517
+ const { corridor } = splitRecords(await collectSwapRecords(repository));
1525
1518
  for (const record of corridor) index(record);
1526
1519
  const found = byRfqId.get(rfqId);
1527
1520
  return found === void 0 ? void 0 : corridor.find((r) => r.id === found);
@@ -1529,10 +1522,20 @@ var corridorRecordStore = (repository, onRecord = () => {
1529
1522
  return {
1530
1523
  index,
1531
1524
  quoteIdOf: (rfqId) => byRfqId.get(rfqId),
1532
- async getAllRfqSwaps() {
1533
- const { corridor } = splitRecords(await repository.getAllSwapRecords());
1525
+ async getRfqSwapsPage(filter, page) {
1526
+ assertPageRequest(page);
1527
+ assertRfqSwapPageFilter(filter);
1528
+ const { corridor } = splitRecords(await collectSwapRecords(repository));
1534
1529
  for (const record of corridor) index(record);
1535
- return corridor.filter(admits).map(rfqRecordOf);
1530
+ const rows = corridor.filter(admits).map(rfqRecordOf).filter(
1531
+ (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)
1532
+ ).sort(
1533
+ (a, b) => a.updatedAt - b.updatedAt || (a.rfqId < b.rfqId ? -1 : a.rfqId > b.rfqId ? 1 : 0)
1534
+ ).slice(0, page.limit + 1);
1535
+ return pageResult(rows, page.limit, (record) => ({
1536
+ updatedAt: record.updatedAt,
1537
+ rfqId: record.rfqId
1538
+ }));
1536
1539
  },
1537
1540
  async getRfqSwap(rfqId) {
1538
1541
  const record = await recordFor(rfqId);
@@ -1560,15 +1563,14 @@ var offerFactsOf = (record) => ({
1560
1563
  swapPkScript: record.swapPkScript,
1561
1564
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
1562
1565
  ...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
1563
- // Milliseconds: `coverage.ts` marks issuance with `Date.now()`, and a
1564
- // seconds value compared against it leaves every issued script outstanding
1565
- // for the life of the process.
1566
+ // milliseconds: `coverage.ts` compares against `Date.now()`, and seconds would leave every
1567
+ // issued script outstanding for the life of the process
1566
1568
  createdAt: record.createdAt * 1e3
1567
1569
  });
1568
1570
  var offerRecordSource = (repository, onRecord = () => {
1569
1571
  }, now = () => Math.floor(Date.now() / 1e3)) => {
1570
1572
  const list = async () => {
1571
- const { offer } = splitRecords(await repository.getAllSwapRecords());
1573
+ const { offer } = splitRecords(await collectSwapRecords(repository));
1572
1574
  return offer.map(offerFactsOf);
1573
1575
  };
1574
1576
  return {
@@ -1597,8 +1599,7 @@ var applyOfferSpend = (record, changes, now) => ({
1597
1599
  ...record,
1598
1600
  status: changes.status,
1599
1601
  spentTxid: changes.spentTxid,
1600
- // The watcher's `completedAt` comes off a contract event's timestamp, in
1601
- // milliseconds; this record's timestamps are unix seconds.
1602
+ // event timestamps are milliseconds; this record's are unix seconds
1602
1603
  ...changes.completedAt === void 0 ? {} : { completedAt: Math.floor(changes.completedAt / 1e3) },
1603
1604
  updatedAt: now
1604
1605
  });
@@ -1624,7 +1625,7 @@ var restoredOfferRecord = (swap, network, now) => {
1624
1625
  },
1625
1626
  give: { asset: give, amount: toAtomicDecimal(BigInt(swap.fromAmount)) },
1626
1627
  take: { asset: take, amount: toAtomicDecimal(BigInt(swap.toAmount)) },
1627
- fee: { asset: take, amount: toAtomicDecimal(BigInt(0)) },
1628
+ fee: { asset: take, amount: toAtomicDecimal(0n) },
1628
1629
  market: { kind: "restored", backend: "feed" },
1629
1630
  expiresAt: createdAt,
1630
1631
  status: swap.status,
@@ -1657,15 +1658,12 @@ var walletLockupIndexer = (wallet) => {
1657
1658
  // src/client/cancel.ts
1658
1659
  import { base64, hex as hex3 } from "@scure/base";
1659
1660
  import { ArkAddress as ArkAddress2, Transaction } from "@arkade-os/sdk";
1660
- var OFFER_TERMINAL = (record) => record.status === "cancelled" || record.status === "fulfilled";
1661
1661
  var cancelSwap = async (input) => {
1662
1662
  const { wallet, repository, record, drive, indexer } = input;
1663
1663
  const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
1664
- if (OFFER_TERMINAL(record)) {
1665
- return { outcome: record.status === "cancelled" ? "cancelled" : "filled" };
1666
- }
1667
- if (offerOutcome(record.status) === "needs_recovery") {
1668
- return { outcome: "needs_recovery" };
1664
+ const outcome = offerOutcome(record.status);
1665
+ if (outcome === "cancelled" || outcome === "filled" || outcome === "needs_recovery") {
1666
+ return { outcome };
1669
1667
  }
1670
1668
  const gated2 = withStatus(record, "cancelling", now());
1671
1669
  await repository.saveSwapRecord(gated2);
@@ -1690,7 +1688,7 @@ var cancelSwap = async (input) => {
1690
1688
  drive.ingest(rolledBack);
1691
1689
  throw error;
1692
1690
  }
1693
- if (isMissingVtxo(error)) {
1691
+ if (error instanceof NoSpendableDepositError) {
1694
1692
  const reconciled = await reconcileDepositSpend(record, indexer);
1695
1693
  if (reconciled === void 0) {
1696
1694
  return { outcome: "needs_recovery" };
@@ -1762,7 +1760,7 @@ var persistBestEffort = async (repository, record) => {
1762
1760
  };
1763
1761
  var retireOfferScripts = async (wallet, repository, record) => {
1764
1762
  try {
1765
- const { offer } = splitRecords(await repository.getAllSwapRecords());
1763
+ const { offer } = splitRecords(await collectSwapRecords(repository));
1766
1764
  await retireOfferContract(
1767
1765
  await wallet.getContractManager(),
1768
1766
  offer.map(offerFactsOf),
@@ -1772,15 +1770,135 @@ var retireOfferScripts = async (wallet, repository, record) => {
1772
1770
  console.warn(`[swap] could not retire offer script for ${record.id}`, error);
1773
1771
  }
1774
1772
  };
1775
- var isMissingVtxo = (error) => error instanceof NoSpendableDepositError;
1773
+
1774
+ // src/restoreRepository.ts
1775
+ import { ArkAddress as ArkAddress3 } from "@arkade-os/sdk";
1776
+ var isOpen = (swap) => swap.status === "pending" || swap.status === "cancelling";
1777
+ var isOfferSwap = (swap) => typeof swap.offerHex === "string";
1778
+ var restoreCoverage = async (wallet, swaps) => {
1779
+ const offers = swaps.filter(isOfferSwap);
1780
+ if (offers.length > 0) await restoreOfferCoverage(wallet, offers);
1781
+ };
1782
+ var aborted = (swaps) => ({
1783
+ swaps,
1784
+ changes: [],
1785
+ scannedTxids: [],
1786
+ aborted: true
1787
+ });
1788
+ async function restoreAssetSwapRepository(opts) {
1789
+ const { wallet, indexer, repository, txs, operatorPubkey, prepareNew, signal } = opts;
1790
+ const [existing, scanned, address] = await Promise.all([
1791
+ getAssetSwapsOrThrow(repository),
1792
+ repository.getScannedTxids(),
1793
+ wallet.getAddress()
1794
+ ]);
1795
+ if (signal?.aborted) return aborted(existing);
1796
+ let scan;
1797
+ try {
1798
+ scan = await restoreAssetSwaps(indexer, txs, new Set(existing.map((swap) => swap.id)), {
1799
+ operatorPubkey,
1800
+ scanned,
1801
+ reopen: existing.filter((swap) => isOpen(swap) && isOfferSwap(swap)),
1802
+ hrp: ArkAddress3.decode(address).hrp
1803
+ });
1804
+ } catch (scanError) {
1805
+ if (!signal?.aborted) {
1806
+ try {
1807
+ await restoreCoverage(wallet, existing);
1808
+ } catch (coverageError2) {
1809
+ throw new AggregateError(
1810
+ [scanError, coverageError2],
1811
+ "asset-swap scan and covenant coverage restore both failed"
1812
+ );
1813
+ }
1814
+ }
1815
+ throw scanError;
1816
+ }
1817
+ if (signal?.aborted) return aborted(existing);
1818
+ const before = new Map(existing.map((swap) => [swap.id, swap]));
1819
+ const changes = [];
1820
+ const cancelledAfterCommit = async (scannedTxids = []) => ({
1821
+ swaps: await getAssetSwapsOrThrow(repository),
1822
+ changes,
1823
+ scannedTxids,
1824
+ aborted: true
1825
+ });
1826
+ for (const restored of scan.restored) {
1827
+ if (signal?.aborted) return cancelledAfterCommit();
1828
+ const previous = before.get(restored.id);
1829
+ const current = previous !== void 0 || !prepareNew ? restored : await prepareNew(restored);
1830
+ if (current.id !== restored.id) {
1831
+ throw new Error("prepareNew must not change an asset swap id");
1832
+ }
1833
+ if (signal?.aborted) return cancelledAfterCommit();
1834
+ await repository.saveSwap(current);
1835
+ changes.push(previous ? { previous, current } : { current });
1836
+ }
1837
+ if (signal?.aborted) return cancelledAfterCommit();
1838
+ if (scan.scannedTxids.length > 0) {
1839
+ await repository.markTxidsScanned(scan.scannedTxids);
1840
+ }
1841
+ const swaps = await getAssetSwapsOrThrow(repository);
1842
+ if (signal?.aborted) return cancelledAfterCommit(scan.scannedTxids);
1843
+ let coverageError;
1844
+ try {
1845
+ await restoreCoverage(wallet, swaps);
1846
+ } catch (error) {
1847
+ coverageError = error;
1848
+ }
1849
+ return {
1850
+ swaps,
1851
+ changes,
1852
+ scannedTxids: scan.scannedTxids,
1853
+ aborted: false,
1854
+ ...coverageError === void 0 ? {} : { coverageError }
1855
+ };
1856
+ }
1857
+
1858
+ // src/registerRestore.ts
1859
+ import { hex as hex4 } from "@scure/base";
1860
+ import {
1861
+ registerWalletRestoreHook,
1862
+ toXOnlySignerHex
1863
+ } from "@arkade-os/sdk";
1864
+ var toRestoreTx = (tx) => ({
1865
+ type: tx.type.toLowerCase(),
1866
+ redeemTxid: tx.key.arkTxid,
1867
+ boardingTxid: tx.key.boardingTxid,
1868
+ roundTxid: tx.key.commitmentTxid,
1869
+ createdAt: Math.floor(tx.createdAt / 1e3)
1870
+ });
1871
+ function registerAssetSwapRestore(wallet, options) {
1872
+ return registerWalletRestoreHook(wallet, {
1873
+ id: "arkade-os:asset-swap",
1874
+ restore: async (restoredWallet) => {
1875
+ const [history, indexer, info] = await Promise.all([
1876
+ restoredWallet.getTransactionHistory(),
1877
+ options.indexer ?? restoredWallet.getArkadeReader(),
1878
+ options.operatorPubkey ? void 0 : restoredWallet.getArkadeInfo({ requireLive: true })
1879
+ ]);
1880
+ const operatorPubkey = options.operatorPubkey ?? hex4.decode(toXOnlySignerHex(info.signerPubkey));
1881
+ const result = await restoreAssetSwapRepository({
1882
+ wallet: restoredWallet,
1883
+ indexer,
1884
+ repository: options.repository,
1885
+ txs: history.map(toRestoreTx),
1886
+ operatorPubkey,
1887
+ prepareNew: options.prepareNew
1888
+ });
1889
+ await options.onResult?.(result);
1890
+ }
1891
+ });
1892
+ }
1776
1893
 
1777
1894
  // src/client/drive.ts
1778
1895
  import {
1779
- ArkAddress as ArkAddress3,
1896
+ ArkAddress as ArkAddress4,
1780
1897
  contractSigner,
1898
+ getNetwork as getNetwork2,
1781
1899
  identityDescriptor
1782
1900
  } from "@arkade-os/sdk";
1783
- import { hex as hex4 } from "@scure/base";
1901
+ import { hex as hex5 } from "@scure/base";
1784
1902
  var SwapDriveRefusedError = class extends Error {
1785
1903
  constructor(reason, detail, swapId) {
1786
1904
  super(detail);
@@ -1850,15 +1968,9 @@ var createSwapDrive = (config) => {
1850
1968
  const corridorStore = () => bridge ??= corridorRecordStore(
1851
1969
  storage(),
1852
1970
  remember,
1853
- // Terminal records are readable but never driven: excluding them
1854
- // here is what keeps `restoreFromRepository` from rebuilding each
1855
- // one — a covenant derivation and a contract row lookup per
1856
- // record — only to file it in the manager's `finished` set. The
1857
- // exclusion is on the manager's read, not the record: the drive's
1858
- // own `records` registry keeps every readable record, and the
1859
- // index still learns an excluded record's `rfqId` (see
1860
- // `getAllRfqSwaps`), so a consumer handing its swap to the manager
1861
- // directly keeps resolving.
1971
+ // Terminal records stay readable but are excluded from the manager's read, sparing
1972
+ // a rebuild per record just to file it `finished`. The index still learns their
1973
+ // `rfqId` (see `getRfqSwapsPage`).
1862
1974
  (r) => !undrivable.has(r.id) && !isRfqSwapTerminal(r.state)
1863
1975
  );
1864
1976
  const effectiveState = (swap) => {
@@ -1957,7 +2069,7 @@ var createSwapDrive = (config) => {
1957
2069
  const signer = await contractSigner(wallet, await identityDescriptor(wallet.identity));
1958
2070
  const claimKey = record.profile.claimKey;
1959
2071
  if (typeof claimKey === "string") {
1960
- const held = hex4.encode(await signer.xOnlyPublicKey());
2072
+ const held = hex5.encode(await signer.xOnlyPublicKey());
1961
2073
  if (held !== claimKey) {
1962
2074
  throw new Error(
1963
2075
  `this wallet's identity key ${held} is not the payout key ${claimKey} rfq swap ${swap.rfqId} was quoted against \u2014 a wrong seed, or key provisioning has drifted from the identity key`
@@ -1998,6 +2110,7 @@ var createSwapDrive = (config) => {
1998
2110
  }
1999
2111
  };
2000
2112
  const drivable = async (record) => !readsChain(record.kind) || await resolveOnchain();
2113
+ const pinnedNetwork = async () => getNetwork2(await config.network());
2001
2114
  const claimLockup = async (swap, vtxos, { partiallyClaimed }) => {
2002
2115
  const record = await corridorStore().getRfqSwap(swap.rfqId);
2003
2116
  if (!record) throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
@@ -2015,13 +2128,11 @@ var createSwapDrive = (config) => {
2015
2128
  receiver: await contractSigner(wallet, secret.signingDescriptor),
2016
2129
  preimage: await preimageForSwapRecord(wallet, secret),
2017
2130
  vtxos,
2018
- destinationPkScript: ArkAddress3.decode(payoutAddress).pkScript,
2019
- // Passed straight through, both of them: the manager's own value
2020
- // check decides WHEN to act, `pushClaim`'s decides whether `P` is
2021
- // published, and it is the one with nothing between it and the
2022
- // signature.
2131
+ destinationPkScript: ArkAddress4.decode(payoutAddress).pkScript,
2132
+ // Passed through: `pushClaim`'s own value check decides whether `P` is published.
2023
2133
  expectedAmount: swap.expectedAmount,
2024
- partiallyClaimed
2134
+ partiallyClaimed,
2135
+ network: await pinnedNetwork()
2025
2136
  })
2026
2137
  );
2027
2138
  };
@@ -2050,7 +2161,8 @@ var createSwapDrive = (config) => {
2050
2161
  operator,
2051
2162
  contracts: lockupSource,
2052
2163
  wallet,
2053
- repository: corridorStore()
2164
+ repository: corridorStore(),
2165
+ network: pinnedNetwork
2054
2166
  });
2055
2167
  manager.setCallbacks({
2056
2168
  refundArkade: async (swap) => {
@@ -2082,23 +2194,15 @@ var createSwapDrive = (config) => {
2082
2194
  wallet.getAddress(),
2083
2195
  config.network()
2084
2196
  ]);
2085
- const txs = history.map((tx) => ({
2086
- // `TxType` is `"SENT"`/`"RECEIVED"`; the scan filters on `"sent"`.
2087
- type: String(tx.type).toLowerCase(),
2088
- redeemTxid: tx.key.arkTxid,
2089
- ...tx.key.boardingTxid ? { boardingTxid: tx.key.boardingTxid } : {},
2090
- ...tx.key.commitmentTxid ? { roundTxid: tx.key.commitmentTxid } : {},
2091
- // The scan reads unix SECONDS; a wallet transaction carries ms.
2092
- ...tx.createdAt ? { createdAt: Math.floor(tx.createdAt / 1e3) } : {}
2093
- }));
2094
- const { hrp, serverPubKey: operatorPubkey } = ArkAddress3.decode(address);
2197
+ const txs = history.map(toRestoreTx);
2198
+ const { hrp, serverPubKey: operatorPubkey } = ArkAddress4.decode(address);
2095
2199
  const cursor = reopen === void 0 ? scanned : new Set([...scanned].filter((txid) => txid !== reopen));
2096
2200
  const { restored, scannedTxids } = await restoreAssetSwaps(indexer, txs, /* @__PURE__ */ new Set(), {
2097
2201
  operatorPubkey,
2098
2202
  scanned: cursor,
2099
2203
  hrp
2100
2204
  });
2101
- const { offer } = splitRecords(await store.getAllSwapRecords());
2205
+ const { offer } = splitRecords(await collectSwapRecords(store));
2102
2206
  const current = new Map(offer.map((record) => [record.id, record]));
2103
2207
  const byDeposit = new Map(
2104
2208
  offer.filter((record) => record.fundingTxid !== void 0).map((record) => [`${record.swapPkScript}:${record.fundingTxid}`, record])
@@ -2178,7 +2282,7 @@ var createSwapDrive = (config) => {
2178
2282
  wireCallbacks();
2179
2283
  await manager.start();
2180
2284
  await markPassed();
2181
- if (!watcher && repository) {
2285
+ if (!watcher) {
2182
2286
  watcher = await watchOfferSwaps({
2183
2287
  wallet,
2184
2288
  source: offers(),
@@ -2188,7 +2292,7 @@ var createSwapDrive = (config) => {
2188
2292
  };
2189
2293
  const restore = async () => {
2190
2294
  if (!repository) return;
2191
- const all = await repository.getAllSwapRecords();
2295
+ const all = await collectSwapRecords(repository);
2192
2296
  const { corridor, offer } = splitRecords(all.filter(readableRecord));
2193
2297
  for (const record of [...corridor, ...offer]) records.set(record.id, record);
2194
2298
  const liveCorridor = corridor.filter((record) => !isRfqSwapTerminal(record.state));
@@ -2275,7 +2379,7 @@ var createSwapDrive = (config) => {
2275
2379
  id
2276
2380
  );
2277
2381
  }
2278
- const script = hex4.decode(record.lockupPkScript);
2382
+ const script = hex5.decode(record.lockupPkScript);
2279
2383
  const before = await recoverableAt(script);
2280
2384
  if (before.length === 0) {
2281
2385
  throw new SwapDriveRefusedError(
@@ -2392,8 +2496,9 @@ var marketKeyOf = (card) => {
2392
2496
  }
2393
2497
  return base <= quote ? `${base}/${quote}` : `${quote}/${base}`;
2394
2498
  };
2395
- var isAddressable = (card) => !isRfqMarket2(card) || typeof card.discovery_pubkey === "string" && (card.transports?.nostr?.relays?.length ?? 0) > 0;
2396
- var marketBackendOf = (card) => isRfqMarket2(card) ? "rfq" : "feed";
2499
+ var hasRendezvous = (card) => typeof card.discovery_pubkey === "string" && (card.transports?.nostr?.relays?.length ?? 0) > 0;
2500
+ var isAddressable = (card) => !isRfqMarket2(card) || hasRendezvous(card);
2501
+ var marketBackendOf = (card) => isRfqMarket2(card) || hasRendezvous(card) ? "rfq" : "feed";
2397
2502
  var usableMarkets = (snapshot, policy) => {
2398
2503
  const allowed = policy?.allowedRegistries;
2399
2504
  return (allowed ? snapshot.markets.filter((card) => allowed.includes(card.source)) : snapshot.markets).filter(isAddressable);
@@ -2406,8 +2511,7 @@ var eligibleMarkets = (snapshot, legs, policy, takeAmount) => {
2406
2511
  const base = side === "base" ? give : take;
2407
2512
  const quote = side === "base" ? take : give;
2408
2513
  const selection = {
2409
- // The trader receives the take leg, so that side must be one the
2410
- // solver can pay out; a direction nobody solves yields no market.
2514
+ // The trader receives the take leg, so the solver must be able to pay that side out.
2411
2515
  wantSide: side === "base" ? "quote" : "base",
2412
2516
  ...takeAmount === void 0 ? {} : { wantAmount: takeAmount }
2413
2517
  };
@@ -2421,9 +2525,7 @@ var eligibleMarkets = (snapshot, legs, policy, takeAmount) => {
2421
2525
  quoteId: `${quote.corridor}:${quote.assetId}`,
2422
2526
  ...selection
2423
2527
  });
2424
- const selected = [...canonical, ...legacy].filter(
2425
- (card, index, all) => all.indexOf(card) === index
2426
- );
2528
+ const selected = [.../* @__PURE__ */ new Set([...canonical, ...legacy])];
2427
2529
  return selected.map((card) => ({
2428
2530
  card,
2429
2531
  give: side,
@@ -2476,16 +2578,16 @@ var assembleRoute = (give, take) => {
2476
2578
  }
2477
2579
  return { give, take };
2478
2580
  };
2479
- var endpoint = (corridor, asset4, instrument) => ({
2581
+ var endpoint = (corridor, asset5, instrument) => ({
2480
2582
  corridor,
2481
- asset: asset4,
2583
+ asset: asset5,
2482
2584
  ...instrument === void 0 ? {} : { instrument }
2483
2585
  });
2484
- var legFor = (asset4, expected) => {
2485
- const leg = toDiscoveryLeg(asset4);
2586
+ var legFor = (asset5, expected) => {
2587
+ const leg = toDiscoveryLeg(asset5);
2486
2588
  if (expected !== void 0 && leg.corridor !== expected) {
2487
2589
  throw new UnsupportedRoute(
2488
- `${asset4} settles on ${leg.corridor}, and this leg is ${expected}`,
2590
+ `${asset5} settles on ${leg.corridor}, and this leg is ${expected}`,
2489
2591
  { give: leg.corridor, take: expected }
2490
2592
  );
2491
2593
  }
@@ -2567,11 +2669,9 @@ var resolveRoute = async (input, deps) => {
2567
2669
  aliases
2568
2670
  };
2569
2671
  };
2570
- var isCorridor = (value) => value === "arkade" || value === "lightning" || value === "onchain";
2672
+ var isCorridor = (value) => CORRIDORS.includes(value);
2571
2673
  var assetFor = (ref, corridor, network, aliases) => ref === void 0 ? btcOn(railOfCorridor(corridor), network) : (
2572
- // Scoped to the leg's rail, because BTC has one id per rail and a
2573
- // whole-table lookup would refuse `"BTC"` as ambiguous on any snapshot
2574
- // carrying a corridor market — see `scopedToRail`.
2674
+ // Rail-scoped: BTC has one id per rail, so a whole-table `"BTC"` is ambiguous.
2575
2675
  canonicalAssetId(ref, scopedToRail(aliases, railOfCorridor(corridor)))
2576
2676
  );
2577
2677
  var pinAmount = (input, takeInstrument) => {
@@ -2744,26 +2844,53 @@ var verifyQuoteTtl = (input) => {
2744
2844
  }
2745
2845
  };
2746
2846
  var verifyQuotedAmount = (input) => {
2747
- const quoted = input.pinned.on === "give" ? input.give : input.take;
2748
- if (quoted !== input.pinned.value) {
2847
+ verifyPinnedAmount(input);
2848
+ if (input.take > input.give) {
2749
2849
  throw new QuoteVerificationFailed(
2750
2850
  "pair",
2751
- `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
2752
- `${input.pair} ${input.pinned.on}=${quoted}`
2851
+ `${input.pair} give >= take`,
2852
+ `give=${input.give} take=${input.take}`
2753
2853
  );
2754
2854
  }
2755
- if (input.take > input.give) {
2855
+ };
2856
+ var verifyCrossAssetAmount = (input) => {
2857
+ verifyPinnedAmount(input);
2858
+ if (input.give <= 0n || input.take <= 0n) {
2756
2859
  throw new QuoteVerificationFailed(
2757
2860
  "pair",
2758
- `${input.pair} give >= take`,
2861
+ `${input.pair} give > 0 take > 0`,
2759
2862
  `give=${input.give} take=${input.take}`
2760
2863
  );
2761
2864
  }
2762
2865
  };
2866
+ var verifiedCarrierSats = (quote) => {
2867
+ try {
2868
+ return quoteCarrierSats(quote);
2869
+ } catch (error) {
2870
+ if (reasonOf(error) !== "carrier_malformed") throw error;
2871
+ throw new QuoteVerificationFailed(
2872
+ "pair",
2873
+ "carrier_sats a non-negative integer",
2874
+ String(quote.carrier_sats),
2875
+ { cause: error }
2876
+ );
2877
+ }
2878
+ };
2879
+ var verifyPinnedAmount = (input) => {
2880
+ const quoted = input.pinned.on === "give" ? input.give : input.take;
2881
+ if (quoted !== input.pinned.value) {
2882
+ throw new QuoteVerificationFailed(
2883
+ "pair",
2884
+ `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
2885
+ `${input.pair} ${input.pinned.on}=${quoted}`
2886
+ );
2887
+ }
2888
+ };
2763
2889
 
2764
2890
  // src/client/quoteOffer.ts
2765
2891
  import {
2766
2892
  computeWantAmount,
2893
+ marketLegKey as marketLegKey2,
2767
2894
  quoteOffer
2768
2895
  } from "@arkade-os/solver-discovery";
2769
2896
  var FEED_TTL_MS = 3e4;
@@ -2783,6 +2910,9 @@ var quoteFromFeed = async (input) => {
2783
2910
  const plan = await quoteOffer(candidate.card, {
2784
2911
  give: candidate.give,
2785
2912
  ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
2913
+ // What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
2914
+ // for it back in a BTC payout, and charges it where the card declares a delivered carrier.
2915
+ carrierSats: ASSET_CARRIER_SATS,
2786
2916
  ...QUOTE_OPTIONS,
2787
2917
  fetchImpl: input.feed.fetch
2788
2918
  });
@@ -2806,12 +2936,21 @@ var quoteFromFeed = async (input) => {
2806
2936
  take: { asset: input.endpoints.take.asset, amount: plan.receive.atomic },
2807
2937
  market: input.market,
2808
2938
  expiresAt,
2809
- fee: { amount: spreadOf(plan), asset: input.endpoints.take.asset }
2939
+ fee: {
2940
+ // The plan's payout returns the deposit's carrier; that part is not proceeds.
2941
+ amount: feedSpread(
2942
+ plan,
2943
+ plan.receive.atomic,
2944
+ sellsAssetForBtc(input.endpoints) ? ASSET_CARRIER_SATS : 0n
2945
+ ),
2946
+ asset: input.endpoints.take.asset
2947
+ }
2810
2948
  },
2811
2949
  preparation: { backend: "feed", card: candidate.card, plan, give: candidate.give }
2812
2950
  };
2813
2951
  };
2814
- var spreadOf = (plan) => {
2952
+ var feedSpread = (plan, take, carrierSats = 0n) => {
2953
+ const payout = take > carrierSats ? take - carrierSats : 0n;
2815
2954
  const fair = computeWantAmount({
2816
2955
  deposit: plan.deposit.atomic,
2817
2956
  give: plan.give,
@@ -2819,19 +2958,25 @@ var spreadOf = (plan) => {
2819
2958
  feeBps: 0,
2820
2959
  safetyBps: 0
2821
2960
  });
2822
- const spread = fair - plan.receive.atomic;
2961
+ const spread = fair - payout;
2823
2962
  return spread > 0n ? spread : 0n;
2824
2963
  };
2964
+ var sellsAssetForBtc = (endpoints) => assetPartOf(endpoints.give.asset) !== BTC_ASSET_PART && assetPartOf(endpoints.take.asset) === BTC_ASSET_PART;
2825
2965
  var feedExpiry = (card, feed, now) => {
2826
2966
  const readAt = card.price_feed === void 0 ? void 0 : feed.fetchedAt(card.price_feed);
2827
2967
  const from = readAt === void 0 ? now : Math.floor(readAt / 1e3);
2828
2968
  return from + FEED_TTL_MS / 1e3;
2829
2969
  };
2830
2970
  var verifyPlanLegs = (plan, legs, give) => {
2831
- const expected = `${legs.give.assetId}->${legs.take.assetId}`;
2832
- const priced = `${plan.deposit.asset.id}->${plan.receive.asset.id}`;
2833
- if (expected !== priced || plan.give !== give) {
2834
- throw new QuoteVerificationFailed("pair", expected, priced);
2971
+ const take = give === "base" ? "quote" : "base";
2972
+ const spelled = (side) => marketLegKey2(plan.market, side);
2973
+ const names = (side, leg) => spelled(side) === leg.marketId || spelled(side) === `${leg.corridor}:${leg.assetId}`;
2974
+ if (plan.give !== give || !names(give, legs.give) || !names(take, legs.take)) {
2975
+ throw new QuoteVerificationFailed(
2976
+ "pair",
2977
+ `${legs.give.marketId}->${legs.take.marketId}`,
2978
+ `${spelled(give)}->${spelled(take)}`
2979
+ );
2835
2980
  }
2836
2981
  };
2837
2982
 
@@ -2852,8 +2997,7 @@ var PAYMENT_STATUS = {
2852
2997
  /** Persisted, funding not broadcast. */
2853
2998
  accepted: "pending",
2854
2999
  funding: "pending",
2855
- /** The lockup is funded. Nothing has emitted `"sent"` in core since the
2856
- * `onchain-swap` rail left with `packages/boltz-swap`. */
3000
+ /** The lockup is funded. */
2857
3001
  funded: "sent",
2858
3002
  /** Asset swaps only: an unfilled offer. */
2859
3003
  open: "pending",
@@ -2917,14 +3061,19 @@ var receiverExact = (railId, parts) => {
2917
3061
  total: satsOf(parts.total, `${railId}.total`)
2918
3062
  };
2919
3063
  };
3064
+ var quoteMeta = (quote) => ({
3065
+ quoteId: quote.id,
3066
+ expiresAt: quote.expiresAt,
3067
+ ...quote.refundLocktime === void 0 ? {} : { refundLocktime: quote.refundLocktime },
3068
+ ...quote.solver === void 0 ? {} : { solver: quote.solver },
3069
+ ...quote.lock === void 0 ? {} : { paymentHash: quote.lock.hash },
3070
+ ...quote.market.kind === "restored" ? {} : { market: quote.market.key }
3071
+ });
2920
3072
  var resultOf = (railId, swap) => ({
2921
3073
  railId,
2922
- // The tagged public form M6 minted — round-trippable to `client.swaps()`,
2923
- // which is where the outcomes past this handle's terminal one are read.
3074
+ // tagged, so it joins `client.swaps()`/`onUpdate` for outcomes past this handle's terminal one
2924
3075
  swapId: swap.id,
2925
- // The transaction that left THIS wallet, which is what `txid` means on
2926
- // every other rail. A swap's later legs — the solver's fill, the trader's
2927
- // L1 claim — are the client's to report, not the handle's.
3076
+ // the tx that left THIS wallet, as on every other rail; later legs are the client's to report
2928
3077
  ...swap.fundingTxid === void 0 ? {} : { txid: swap.fundingTxid }
2929
3078
  });
2930
3079
  var swapHandle = async (railId, client, quote) => makeHandle(railId, async (emit) => {
@@ -3004,8 +3153,7 @@ function onchainSwapRail(client, deps) {
3004
3153
  }
3005
3154
  const amounts = receiverExact(ONCHAIN_SWAP_RAIL, {
3006
3155
  amount: payout,
3007
- // Both halves of the cost, inside one number: the solver's
3008
- // spread, and the claim the trader pays for out of the payout.
3156
+ // The solver's spread plus the claim the trader pays out of the payout.
3009
3157
  fee: quote.fee.amount + claimFee,
3010
3158
  total: quote.give.amount
3011
3159
  });
@@ -3013,13 +3161,7 @@ function onchainSwapRail(client, deps) {
3013
3161
  railId: ONCHAIN_SWAP_RAIL,
3014
3162
  ...amounts,
3015
3163
  meta: {
3016
- quoteId: quote.id,
3017
- expiresAt: quote.expiresAt,
3018
- ...quote.refundLocktime === void 0 ? {} : { refundLocktime: quote.refundLocktime },
3019
- ...quote.solver === void 0 ? {} : { solver: quote.solver },
3020
- ...quote.lock === void 0 ? {} : { paymentHash: quote.lock.hash },
3021
- ...quote.market.kind === "restored" ? {} : { market: quote.market.key },
3022
- // The estimate folded into `fee`, so a caller can see it.
3164
+ ...quoteMeta(quote),
3023
3165
  claimFeeSats: Number(claimFee),
3024
3166
  // What the solver locks on L1, before the claim's fee.
3025
3167
  htlcAmountSats: Number(quote.take.amount)
@@ -3059,22 +3201,29 @@ var parseRfqQuote = (quote) => ({
3059
3201
  });
3060
3202
 
3061
3203
  // src/client/quoteRfq.ts
3062
- import { hex as hex5 } from "@scure/base";
3204
+ import { hex as hex6 } from "@scure/base";
3063
3205
  import {
3206
+ ArkAddress as ArkAddress5,
3207
+ asset as asset4,
3064
3208
  networkFromArkadeInfo,
3065
3209
  provisionClaimSecret,
3066
3210
  provisionRefundKey,
3067
3211
  toXOnly
3068
3212
  } from "@arkade-os/sdk";
3213
+ import { quoteOffer as quoteOffer2 } from "@arkade-os/solver-discovery";
3214
+ var lockupOf = (derived) => ({
3215
+ address: derived.address,
3216
+ script: derived.script,
3217
+ pkScript: derived.swapPkScript
3218
+ });
3069
3219
  var covenantInputs = (input) => {
3070
3220
  const network = networkFromArkadeInfo(input.info);
3071
3221
  const arkade = input.corridors.get("arkade").deps;
3072
3222
  return {
3073
- operatorPubkey: toXOnly(hex5.decode(input.info.signerPubkey), "ark signer key"),
3074
- // The per-network pin the arkade module already resolved, never a key
3075
- // the operator reports about itself: this one ends up in a covenant leaf
3223
+ operatorPubkey: toXOnly(hex6.decode(input.info.signerPubkey), "ark signer key"),
3224
+ // The resolved per-network pin, never operator-reported: it lands in a covenant leaf
3076
3225
  // that decides who can move the funds.
3077
- emulatorPubkey: toXOnly(hex5.decode(arkade.emulatorPubkey), "emulator signer key"),
3226
+ emulatorPubkey: toXOnly(hex6.decode(arkade.emulatorPubkey), "emulator signer key"),
3078
3227
  claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
3079
3228
  hrp: network.hrp
3080
3229
  };
@@ -3082,7 +3231,7 @@ var covenantInputs = (input) => {
3082
3231
  var sealingKey = (deps) => {
3083
3232
  const configured = deps.covclaimd?.pubkey;
3084
3233
  if (configured === void 0) return void 0;
3085
- const key = hex5.decode(configured);
3234
+ const key = hex6.decode(configured);
3086
3235
  if (key.length !== 33) {
3087
3236
  throw new Error(
3088
3237
  `the covclaimd deployment key must be 33-byte compressed hex, got ${key.length} bytes`
@@ -3103,6 +3252,8 @@ var quoteViaRfq = async (input) => {
3103
3252
  pinnable: input.market.snapshot.live
3104
3253
  });
3105
3254
  switch (input.route) {
3255
+ case "arkade->arkade":
3256
+ return quoteArkadeAsset(input);
3106
3257
  case "arkade->lightning":
3107
3258
  return quoteLightningSend(input);
3108
3259
  case "lightning->arkade":
@@ -3111,6 +3262,113 @@ var quoteViaRfq = async (input) => {
3111
3262
  return quoteOnchainSend(input);
3112
3263
  }
3113
3264
  };
3265
+ var quoteArkadeAsset = async (input) => {
3266
+ const pinned = pinnedFor(input);
3267
+ if (pinned.on !== "give") {
3268
+ throw new Error(
3269
+ "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`"
3270
+ );
3271
+ }
3272
+ const sides = assetSidesOf(input.legs);
3273
+ if (input.candidate.card.price_feed === void 0) {
3274
+ throw new UnsupportedRoute(
3275
+ `card ${input.candidate.card.solver} advertises no price feed to measure an asset swap's fee against`,
3276
+ { give: "arkade", take: "arkade" }
3277
+ );
3278
+ }
3279
+ const pair = rfqPairFor(input.legs.give, input.legs.take);
3280
+ const rfqId = newRfqId();
3281
+ const maker = await makerPosition(input.wallet);
3282
+ const wire = await input.transport.requestQuote(
3283
+ arkadeSwapRequest({
3284
+ rfqId,
3285
+ ...sides,
3286
+ amount: pinned.value,
3287
+ makerPkScript: maker.pkScript,
3288
+ makerPublicKey: maker.publicKey
3289
+ })
3290
+ );
3291
+ verifyPair(wire.pair, pair);
3292
+ const parsed = parseRfqQuote(wire);
3293
+ verifyCrossAssetAmount({ pair, pinned, give: parsed.give, take: parsed.take });
3294
+ verifyQuoteTtl({
3295
+ quoteId: input.quoteId,
3296
+ expiresAt: parsed.validUntil,
3297
+ now: input.now,
3298
+ floorSeconds: input.policy?.quoteTtlFloorSeconds
3299
+ });
3300
+ const carrierSats = sides.offerAsset === void 0 ? void 0 : verifiedCarrierSats(wire);
3301
+ const reference = await quoteOffer2(input.candidate.card, {
3302
+ give: input.candidate.give,
3303
+ giveAmount: parsed.give,
3304
+ ...carrierSats === void 0 ? {} : { carrierSats },
3305
+ ...QUOTE_OPTIONS,
3306
+ fetchImpl: input.feed.fetch
3307
+ });
3308
+ verifyPlanLegs(reference, input.legs, input.candidate.give);
3309
+ const terms = offerTermsFromQuote(wire, sides);
3310
+ const offer = await deriveOffer(input.wallet, {
3311
+ wantAmount: terms.wantAmount,
3312
+ ...terms.wantAsset === void 0 ? {} : { wantAsset: terms.wantAsset },
3313
+ ...terms.offerAsset === void 0 ? {} : { offerAsset: terms.offerAsset },
3314
+ emulatorPubkey: input.corridors.get("arkade").deps.emulatorPubkey,
3315
+ maker,
3316
+ info: input.info
3317
+ });
3318
+ verifyingDerivation(() => verifyOfferAddress(wire, offer));
3319
+ return {
3320
+ quote: {
3321
+ id: input.quoteId,
3322
+ route: assembleRoute(
3323
+ { ...input.endpoints.give, instrument: { kind: "wallet" } },
3324
+ { ...input.endpoints.take, instrument: { kind: "wallet" } }
3325
+ ),
3326
+ give: { asset: input.endpoints.give.asset, amount: parsed.give },
3327
+ take: { asset: input.endpoints.take.asset, amount: parsed.take },
3328
+ market: input.market,
3329
+ solver: parsed.solver,
3330
+ expiresAt: parsed.validUntil,
3331
+ // Exactly one leg is BTC, so an asset deposit's carrier is on the payout's unit.
3332
+ fee: {
3333
+ amount: feedSpread(reference, parsed.take, carrierSats),
3334
+ asset: input.endpoints.take.asset
3335
+ }
3336
+ },
3337
+ preparation: {
3338
+ backend: "rfq",
3339
+ route: "arkade->arkade",
3340
+ card: input.candidate.card,
3341
+ rfqId,
3342
+ wire: parsed,
3343
+ offer,
3344
+ ...carrierSats === void 0 ? {} : { carrierSats }
3345
+ }
3346
+ };
3347
+ };
3348
+ var assetSidesOf = (legs) => {
3349
+ const giveIsBtc = legs.give.assetId === BTC_ASSET_ID;
3350
+ const takeIsBtc = legs.take.assetId === BTC_ASSET_ID;
3351
+ if (giveIsBtc && takeIsBtc) {
3352
+ throw new UnsupportedRoute("arkade:BTC -> arkade:BTC moves one asset, it swaps nothing", {
3353
+ give: "arkade",
3354
+ take: "arkade"
3355
+ });
3356
+ }
3357
+ if (!giveIsBtc && !takeIsBtc) {
3358
+ throw new UnsupportedRoute(
3359
+ `arkade:${legs.give.assetId} -> arkade:${legs.take.assetId}: an asset swap prices one asset against BTC, so exactly one leg must be BTC`,
3360
+ { give: "arkade", take: "arkade" }
3361
+ );
3362
+ }
3363
+ return giveIsBtc ? { wantAsset: asset4.AssetId.fromString(legs.take.assetId) } : { offerAsset: asset4.AssetId.fromString(legs.give.assetId) };
3364
+ };
3365
+ var makerPosition = async (wallet) => {
3366
+ const [address, publicKey] = await Promise.all([
3367
+ wallet.getAddress(),
3368
+ wallet.identity.xOnlyPublicKey()
3369
+ ]);
3370
+ return { pkScript: ArkAddress5.decode(address).pkScript, publicKey };
3371
+ };
3114
3372
  var quoteLightningSend = async (input) => {
3115
3373
  const invoice = input.endpoints.take.instrument;
3116
3374
  if (invoice?.kind !== "invoice" || invoice.amount === void 0) {
@@ -3175,11 +3433,7 @@ var quoteLightningSend = async (input) => {
3175
3433
  card: input.candidate.card,
3176
3434
  rfqId,
3177
3435
  wire: parsed,
3178
- lockup: {
3179
- address: derived.address,
3180
- script: derived.script,
3181
- pkScript: derived.swapPkScript
3182
- },
3436
+ lockup: lockupOf(derived),
3183
3437
  contractParams: derived.contractParams,
3184
3438
  secrets,
3185
3439
  refundAddress: secrets.address,
@@ -3192,7 +3446,7 @@ var quoteLightningReceive = async (input) => {
3192
3446
  const pair = rfqPairFor(input.legs.give, input.legs.take);
3193
3447
  const rfqId = newRfqId();
3194
3448
  const secrets = await provisionClaimSecret(input.wallet);
3195
- const paymentHash = hex5.encode(secrets.paymentHash);
3449
+ const paymentHash = hex6.encode(secrets.paymentHash);
3196
3450
  const payoutAddress = await input.wallet.getAddress();
3197
3451
  const lightning = input.corridors.get("lightning").deps;
3198
3452
  const sealTo = sealingKey(lightning);
@@ -3205,9 +3459,7 @@ var quoteLightningReceive = async (input) => {
3205
3459
  payoutAddress,
3206
3460
  payoutPubkey: secrets.pubkey,
3207
3461
  claimPacket: claimPacket?.packet,
3208
- // Placeholder: the v1 builders type this field `number`, and the
3209
- // wire adapter re-encodes it as the canonical decimal string.
3210
- // Encoding it here as well would put the decision in two places.
3462
+ // Placeholder: `withCanonicalAmount` writes the canonical decimal string.
3211
3463
  amount: 0,
3212
3464
  amountSide: toRfqAmountSide(pinned.on)
3213
3465
  }),
@@ -3224,10 +3476,7 @@ var quoteLightningReceive = async (input) => {
3224
3476
  paymentHash,
3225
3477
  payoutPubkey: secrets.pubkey,
3226
3478
  payoutAddress,
3227
- operatorPubkey: covenant.operatorPubkey,
3228
- emulatorPubkey: covenant.emulatorPubkey,
3229
- claimDelay: covenant.claimDelay,
3230
- hrp: covenant.hrp
3479
+ ...covenant
3231
3480
  })
3232
3481
  );
3233
3482
  const { payDeadline } = verifyReceiveInvoiceFacts({
@@ -3245,9 +3494,7 @@ var quoteLightningReceive = async (input) => {
3245
3494
  });
3246
3495
  verifyQuoteTtl({
3247
3496
  quoteId: input.quoteId,
3248
- // The hold invoice's window is minutes where the quote's is an hour, so
3249
- // the deadline that binds this leg is the earlier of the two — which is
3250
- // what `payDeadline` already is.
3497
+ // The hold invoice's window (minutes) binds, not the quote's (an hour).
3251
3498
  expiresAt: payDeadline,
3252
3499
  now: input.now,
3253
3500
  floorSeconds: input.policy?.quoteTtlFloorSeconds
@@ -3285,11 +3532,7 @@ var quoteLightningReceive = async (input) => {
3285
3532
  card: input.candidate.card,
3286
3533
  rfqId,
3287
3534
  wire: parsed,
3288
- lockup: {
3289
- address: derived.address,
3290
- script: derived.script,
3291
- pkScript: derived.swapPkScript
3292
- },
3535
+ lockup: lockupOf(derived),
3293
3536
  contractParams: derived.contractParams,
3294
3537
  secrets,
3295
3538
  payoutAddress,
@@ -3316,7 +3559,7 @@ var quoteOnchainSend = async (input) => {
3316
3559
  const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
3317
3560
  const secrets = await provisionClaimSecret(input.wallet);
3318
3561
  const payoutKey = await provisionRefundKey(input.wallet);
3319
- const paymentHash = hex5.encode(secrets.paymentHash);
3562
+ const paymentHash = hex6.encode(secrets.paymentHash);
3320
3563
  const wire = await input.transport.requestQuote(
3321
3564
  withCanonicalAmount(
3322
3565
  onchainSendRequest({
@@ -3328,9 +3571,6 @@ var quoteOnchainSend = async (input) => {
3328
3571
  amount: 0,
3329
3572
  amountSide: toRfqAmountSide(pinned.on)
3330
3573
  }),
3331
- // The grossed pin, when one is active — see above. The solver's
3332
- // obligation is the HTLC amount; the recipient's own amount is
3333
- // that minus the claim's fee.
3334
3574
  quoted.value
3335
3575
  )
3336
3576
  );
@@ -3351,10 +3591,7 @@ var quoteOnchainSend = async (input) => {
3351
3591
  quote: wire,
3352
3592
  paymentHash,
3353
3593
  payoutPubkey: payoutKey.pubkey,
3354
- operatorPubkey: covenant.operatorPubkey,
3355
- emulatorPubkey: covenant.emulatorPubkey,
3356
- claimDelay: covenant.claimDelay,
3357
- hrp: covenant.hrp,
3594
+ ...covenant,
3358
3595
  l1Network,
3359
3596
  refundAddress: payoutKey.address,
3360
3597
  senderPubkey: secrets.pubkey
@@ -3376,8 +3613,8 @@ var quoteOnchainSend = async (input) => {
3376
3613
  now: input.now,
3377
3614
  floorSeconds: input.policy?.quoteTtlFloorSeconds
3378
3615
  });
3379
- const reportedTake = claimFee === void 0 ? parsed.take : parsed.take - claimFee;
3380
- const reportedFee = claimFee === void 0 ? parsed.give - parsed.take : parsed.give - parsed.take + claimFee;
3616
+ const reportedTake = parsed.take - (claimFee ?? 0n);
3617
+ const reportedFee = parsed.give - parsed.take + (claimFee ?? 0n);
3381
3618
  return {
3382
3619
  quote: {
3383
3620
  id: input.quoteId,
@@ -3391,9 +3628,7 @@ var quoteOnchainSend = async (input) => {
3391
3628
  market: input.market,
3392
3629
  solver: parsed.solver,
3393
3630
  expiresAt: parsed.validUntil,
3394
- // Read off the derivation and not off the wire: the field is
3395
- // optional there, a solver may carry it in the profile instead, and
3396
- // the derivation is what settles which one this covenant used.
3631
+ // Off the derivation, not the wire: it settles which locktime this covenant used.
3397
3632
  refundLocktime: derived.refundLocktime,
3398
3633
  fee: { amount: reportedFee, asset: input.endpoints.give.asset }
3399
3634
  },
@@ -3403,17 +3638,11 @@ var quoteOnchainSend = async (input) => {
3403
3638
  card: input.candidate.card,
3404
3639
  rfqId,
3405
3640
  wire: parsed,
3406
- lockup: {
3407
- address: derived.address,
3408
- script: derived.script,
3409
- pkScript: derived.swapPkScript
3410
- },
3641
+ lockup: lockupOf(derived),
3411
3642
  secrets,
3412
3643
  refundAddress: payoutKey.address,
3413
3644
  fundAmount: parsed.give,
3414
- // The gross wire leg, not `reportedTake`: the claim fee comes out of
3415
- // the HTLC output, so netting it here would accept an HTLC funded
3416
- // short by exactly that fee.
3645
+ // Gross, not `reportedTake`: netting would accept an HTLC short by the fee.
3417
3646
  expectedAmount: parsed.take,
3418
3647
  payoutKey,
3419
3648
  payoutPkScript,
@@ -3464,9 +3693,7 @@ var pay = async (deps, destination, options = {}) => {
3464
3693
  deps,
3465
3694
  {
3466
3695
  to: destination,
3467
- // `amountOn: "take"` because the number a caller writes beside a
3468
- // destination is what the recipient gets. An invoice pins the same
3469
- // leg by existing, which is why passing both is `AmountMismatch`.
3696
+ // The amount beside a destination is what the recipient gets.
3470
3697
  ...options.amount === void 0 ? {} : { amount: options.amount, amountOn: "take" }
3471
3698
  },
3472
3699
  options.maxFee
@@ -3480,8 +3707,7 @@ var receive = async (deps, options) => {
3480
3707
  via: options.via,
3481
3708
  ...options.asset === void 0 ? {} : { take: options.asset },
3482
3709
  amount: options.amount,
3483
- // The trader's side is the take leg: `receive({ amount })` is
3484
- // "credit me this much", not "let the payer send this much".
3710
+ // "Credit me this much", not "let the payer send this much".
3485
3711
  amountOn: "take"
3486
3712
  },
3487
3713
  options.maxFee
@@ -3518,9 +3744,9 @@ var nostrTransportFactory = async (rendezvous) => {
3518
3744
  };
3519
3745
 
3520
3746
  // src/client/client.ts
3521
- import { hex as hex6 } from "@scure/base";
3747
+ import { hex as hex7 } from "@scure/base";
3522
3748
  var PREPARATIONS_HELD = 64;
3523
- var mintQuoteId = () => hex6.encode(crypto.getRandomValues(new Uint8Array(16)));
3749
+ var mintQuoteId = () => hex7.encode(crypto.getRandomValues(new Uint8Array(16)));
3524
3750
  var createSwapClient = (config) => {
3525
3751
  const { wallet } = config;
3526
3752
  const operator = config.operator ?? walletOperator(wallet);
@@ -3575,10 +3801,8 @@ var createSwapClient = (config) => {
3575
3801
  };
3576
3802
  const remember = (id, preparation) => {
3577
3803
  preparations.set(id, preparation);
3578
- while (preparations.size > PREPARATIONS_HELD) {
3579
- const oldest = preparations.keys().next();
3580
- if (oldest.done) break;
3581
- preparations.delete(oldest.value);
3804
+ if (preparations.size > PREPARATIONS_HELD) {
3805
+ preparations.delete(preparations.keys().next().value);
3582
3806
  }
3583
3807
  };
3584
3808
  const client = {
@@ -3612,7 +3836,7 @@ var createSwapClient = (config) => {
3612
3836
  corridors.get(resolvedRoute.legs.take.corridor);
3613
3837
  const quoteId = mintQuoteId();
3614
3838
  const now = Math.floor(Date.now() / 1e3);
3615
- if (resolvedRoute.pair === "arkade->arkade") {
3839
+ if (market.backend === "feed") {
3616
3840
  const { quote, preparation } = await quoteFromFeed({
3617
3841
  quoteId,
3618
3842
  candidate: market,
@@ -3650,6 +3874,7 @@ var createSwapClient = (config) => {
3650
3874
  info,
3651
3875
  corridors,
3652
3876
  transport,
3877
+ feed,
3653
3878
  ...config.policy === void 0 ? {} : { policy: config.policy },
3654
3879
  now
3655
3880
  });
@@ -3697,7 +3922,7 @@ var createSwapClient = (config) => {
3697
3922
  if (repository === void 0) return [];
3698
3923
  const drive2 = driving();
3699
3924
  await drive2.ready;
3700
- const records = await repository.getAllSwapRecords();
3925
+ const records = await collectSwapRecords(repository);
3701
3926
  const swaps = [];
3702
3927
  for (const record of records) {
3703
3928
  if (!readableRecord(record)) continue;
@@ -3737,9 +3962,7 @@ var createSwapClient = (config) => {
3737
3962
  ensureLive("ready");
3738
3963
  return driving().ready;
3739
3964
  },
3740
- // `async`, so the refusal is a rejection rather than a synchronous
3741
- // throw: these are declared `Promise<void>` and a caller is entitled to
3742
- // `.catch()` them.
3965
+ // `async` so the refusal is a rejection, as the `Promise<void>` signature promises
3743
3966
  start: async () => {
3744
3967
  ensureLive("start");
3745
3968
  return driving().start();
@@ -3869,6 +4092,8 @@ export {
3869
4092
  restoredOfferRecord,
3870
4093
  walletLockupIndexer,
3871
4094
  cancelSwap,
4095
+ restoreAssetSwapRepository,
4096
+ registerAssetSwapRestore,
3872
4097
  SwapDriveRefusedError,
3873
4098
  readableRecord,
3874
4099
  createSwapDrive,
@@ -3892,9 +4117,13 @@ export {
3892
4117
  verifyReceiveInvoiceFacts,
3893
4118
  verifyQuoteTtl,
3894
4119
  verifyQuotedAmount,
4120
+ verifyCrossAssetAmount,
4121
+ verifiedCarrierSats,
3895
4122
  FEED_TTL_MS,
3896
4123
  feedFetch,
3897
4124
  quoteFromFeed,
4125
+ feedSpread,
4126
+ verifyPlanLegs,
3898
4127
  satsOf,
3899
4128
  PAYMENT_STATUS,
3900
4129
  paymentStatusOf,
@@ -3902,6 +4131,7 @@ export {
3902
4131
  SwapPaymentFailedError,
3903
4132
  railAvailable,
3904
4133
  receiverExact,
4134
+ quoteMeta,
3905
4135
  swapHandle,
3906
4136
  ONCHAIN_SWAP_RAIL,
3907
4137
  claimFeeSats,