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

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 (30) hide show
  1. package/README.md +2 -2
  2. package/dist/advanced.cjs +249 -65
  3. package/dist/advanced.d.cts +10 -8
  4. package/dist/advanced.d.ts +10 -8
  5. package/dist/advanced.js +10 -2
  6. package/dist/{chunk-RX3WPV5D.js → chunk-CIIJT5O4.js} +17 -3
  7. package/dist/{chunk-4WPDXLXH.js → chunk-QJ2MUUDO.js} +173 -41
  8. package/dist/{errors-BcOgFV-F.d.ts → errors-CUKl1fFo.d.ts} +4 -3
  9. package/dist/{errors-n6IHTG-Z.d.cts → errors-DQ-J_lgV.d.cts} +4 -3
  10. package/dist/index.cjs +235 -93
  11. package/dist/index.d.cts +6 -6
  12. package/dist/index.d.ts +6 -6
  13. package/dist/index.js +8 -2
  14. package/dist/{lockupContract-ZsftgqMc.d.cts → lockupContract-CWR83JvL.d.cts} +4 -2
  15. package/dist/{lockupContract-B_jNbjrG.d.ts → lockupContract-iI7QGIEr.d.ts} +4 -2
  16. package/dist/{offer--1zVkNsV.d.ts → offer-CJzNPS5H.d.ts} +1 -1
  17. package/dist/{offer-DsP1q6GE.d.cts → offer-DCaE0YNp.d.cts} +1 -1
  18. package/dist/protocol.cjs +18 -4
  19. package/dist/protocol.d.cts +5 -5
  20. package/dist/protocol.d.ts +5 -5
  21. package/dist/protocol.js +2 -2
  22. package/dist/repositories/realm/index.d.cts +1 -1
  23. package/dist/repositories/realm/index.d.ts +1 -1
  24. package/dist/repositories/sqlite/index.d.cts +1 -1
  25. package/dist/repositories/sqlite/index.d.ts +1 -1
  26. package/dist/{repository-C32GKpR5.d.cts → repository-S2OS6Yl-.d.cts} +30 -3
  27. package/dist/{repository-BY6GUQiW.d.ts → repository-V98jQmTD.d.ts} +30 -3
  28. package/dist/{watch-D8uzWrHc.d.ts → watch-3pNJbc4T.d.ts} +1 -1
  29. package/dist/{watch-Cejw5cNQ.d.cts → watch-BFMXLQV-.d.cts} +1 -1
  30. package/package.json +2 -2
package/README.md CHANGED
@@ -27,7 +27,7 @@ Each is one `quote` → `accept` chain. `quote` returns binding, verified terms
27
27
  durable; `accept` writes the record, then funds.
28
28
 
29
29
  ```ts
30
- const BTC = btcOn("arkade", "bitcoin"); // arkade:bitcoin/slip44:0
30
+ const BTC = btcOn("arkade", "bitcoin"); // arkade:bitcoin/slip44:0 (slip44:1 on test networks)
31
31
  const USDT = "arkade:bitcoin/asset:…";
32
32
 
33
33
  // arkade -> lightning: pay an invoice. The amount is the invoice's.
@@ -98,7 +98,7 @@ Asset ids are CAIP-19 with the rail as the CAIP-2 namespace, `<rail>:<network>/<
98
98
  ```ts
99
99
  const asset = canonicalAssetId("BTC", {
100
100
  network: "regtest",
101
- assets: [{ ticker: "BTC", id: "arkade:regtest/slip44:0" }],
101
+ assets: [{ ticker: "BTC", id: "arkade:regtest/slip44:1" }],
102
102
  });
103
103
  ```
104
104
 
package/dist/advanced.cjs CHANGED
@@ -507,6 +507,46 @@ function offerContractParams(client, binding, operatorPubkey, expectedPkScript)
507
507
  metadata: { genericallySpendable: false, kind: OFFER_CONTRACT_KIND }
508
508
  };
509
509
  }
510
+ async function restoreOfferCoverage(wallet, swaps) {
511
+ const live = swaps.filter((swap) => !RETIRABLE.includes(swap.status));
512
+ if (live.length === 0) return;
513
+ const [info, contractManager] = await Promise.all([
514
+ wallet.getArkadeInfo({ requireLive: true }),
515
+ wallet.getContractManager()
516
+ ]);
517
+ const operatorPubkey = import_base2.hex.decode((0, import_sdk3.toXOnlySignerHex)(info.signerPubkey));
518
+ const client = await derivingClient(wallet, info, contractManager);
519
+ const seen = /* @__PURE__ */ new Set();
520
+ const covenants = [];
521
+ for (const swap of live) {
522
+ if (seen.has(swap.swapPkScript)) continue;
523
+ seen.add(swap.swapPkScript);
524
+ try {
525
+ const { swapPkScript: _, ...binding } = decodeOffer(import_base2.hex.decode(swap.offerHex));
526
+ covenants.push({
527
+ script: swap.swapPkScript,
528
+ issued: swap.createdAt,
529
+ params: offerContractParams(
530
+ client,
531
+ binding,
532
+ operatorPubkey,
533
+ import_base2.hex.decode(swap.swapPkScript)
534
+ )
535
+ });
536
+ } catch (error) {
537
+ console.warn(`[swap] could not restore coverage for ${swap.swapPkScript}`, error);
538
+ }
539
+ }
540
+ const params = covenants.map((covenant) => covenant.params);
541
+ if (contractManager.createContracts) {
542
+ await contractManager.createContracts(params);
543
+ } else {
544
+ for (const contract of params) await contractManager.createContract(contract);
545
+ }
546
+ for (const covenant of covenants) {
547
+ await promoteOfferContract(contractManager, covenant.script, covenant.issued);
548
+ }
549
+ }
510
550
  function serverExitDelay(delay) {
511
551
  if (typeof delay !== "bigint" || delay <= BigInt(0)) {
512
552
  throw new Error(
@@ -1837,6 +1877,7 @@ __export(advanced_exports, {
1837
1877
  assetSwapIdOf: () => assetSwapIdOf,
1838
1878
  attesting: () => attesting,
1839
1879
  bitcoinNetworkOf: () => bitcoinNetworkOf,
1880
+ btcAssetPart: () => btcAssetPart,
1840
1881
  btcOn: () => btcOn,
1841
1882
  cancelSwap: () => cancelSwap,
1842
1883
  canonicalAssetId: () => canonicalAssetId,
@@ -1872,6 +1913,8 @@ __export(advanced_exports, {
1872
1913
  isAddressable: () => isAddressable,
1873
1914
  isAssetId: () => isAssetId,
1874
1915
  isAtomicDecimal: () => isAtomicDecimal,
1916
+ isBtcAsset: () => isBtcAsset,
1917
+ isBtcAssetLenient: () => isBtcAssetLenient,
1875
1918
  isCardMarket: () => isCardMarket,
1876
1919
  isIndexedNetwork: () => isIndexedNetwork,
1877
1920
  isNetworkRef: () => isNetworkRef,
@@ -1890,6 +1933,7 @@ __export(advanced_exports, {
1890
1933
  offerOutcome: () => offerOutcome,
1891
1934
  offerRecordSource: () => offerRecordSource,
1892
1935
  onchainCorridor: () => onchainCorridor,
1936
+ pageRfqRecords: () => pageRfqRecords,
1893
1937
  parseAssetId: () => parseAssetId,
1894
1938
  parseRfqQuote: () => parseRfqQuote,
1895
1939
  pay: () => pay,
@@ -2324,10 +2368,20 @@ var sameAsset = (a, b) => {
2324
2368
  const right = parseAssetId(b);
2325
2369
  return left.reference === right.reference && left.assetNamespace === right.assetNamespace && left.assetReference === right.assetReference;
2326
2370
  };
2371
+ var btcAssetPart = (network) => network === "bitcoin" ? "slip44:0" : "slip44:1";
2327
2372
  var btcOn = (rail, network) => (
2328
2373
  // TS won't resolve the conditional against an unbound `R`; the cast stays in this expression.
2329
- `${rail}:${network}/${BTC_ASSET_PART}`
2374
+ `${rail}:${network}/${btcAssetPart(network)}`
2330
2375
  );
2376
+ var isBtcAsset = (id) => {
2377
+ const { rail, reference, assetNamespace, assetReference } = parseAssetId(id);
2378
+ return rail !== "eip155" && `${assetNamespace}:${assetReference}` === btcAssetPart(reference);
2379
+ };
2380
+ var isBtcAssetLenient = (id) => {
2381
+ if (isBtcAsset(id)) return true;
2382
+ const { rail, assetNamespace, assetReference } = parseAssetId(id);
2383
+ return rail !== "eip155" && assetNamespace === "slip44" && assetReference === "0";
2384
+ };
2331
2385
  var arkadeAsset = (network, id) => `arkade:${network}/${ARKADE_ASSET_NAMESPACE}:${id.toString()}`;
2332
2386
  var issuanceOf = (id) => {
2333
2387
  const { assetNamespace, assetReference } = parseAssetId(id);
@@ -2519,24 +2573,26 @@ function isSwapError(e, name) {
2519
2573
 
2520
2574
  // src/client/aliases.ts
2521
2575
  var toDiscoveryLeg = (id) => {
2522
- const { rail, assetNamespace, assetReference } = parseAssetId(id);
2576
+ const { rail, reference, assetNamespace, assetReference } = parseAssetId(id);
2523
2577
  const asset7 = `${assetNamespace}:${assetReference}`;
2578
+ const isBtc = isBtcAsset(id);
2579
+ if (!isBtc && rail !== "eip155" && (asset7 === "slip44:0" || asset7 === "slip44:1")) {
2580
+ const expected = btcOn(rail, reference);
2581
+ throw new UnsupportedRoute(`${id} is not BTC on ${reference}: BTC there is ${expected}`);
2582
+ }
2524
2583
  if (rail === "arkade") {
2525
- if (asset7 === BTC_ASSET_PART)
2526
- return { corridor: "arkade", assetId: BTC_ASSET_ID, marketId: id };
2584
+ if (isBtc) return { corridor: "arkade", assetId: BTC_ASSET_ID, marketId: id };
2527
2585
  if (assetNamespace === ARKADE_ASSET_NAMESPACE) {
2528
2586
  return { corridor: "arkade", assetId: assetReference, marketId: id };
2529
2587
  }
2530
2588
  throw new UnsupportedRoute(`the arkade corridor has no ${asset7}`);
2531
2589
  }
2532
2590
  if (rail === "bolt11") {
2533
- if (asset7 === BTC_ASSET_PART)
2534
- return { corridor: "lightning", assetId: BTC_ASSET_ID, marketId: id };
2591
+ if (isBtc) return { corridor: "lightning", assetId: BTC_ASSET_ID, marketId: id };
2535
2592
  throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset7}`);
2536
2593
  }
2537
2594
  if (rail === "bitcoin") {
2538
- if (asset7 === BTC_ASSET_PART)
2539
- return { corridor: "onchain", assetId: BTC_ASSET_ID, marketId: id };
2595
+ if (isBtc) return { corridor: "onchain", assetId: BTC_ASSET_ID, marketId: id };
2540
2596
  throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset7}`);
2541
2597
  }
2542
2598
  throw new UnsupportedRoute(`no corridor serves ${id}`);
@@ -3085,7 +3141,7 @@ var marketSourceOf = (market) => market.kind === "card" ? market.source : void 0
3085
3141
  var assertFundable2 = async (wallet, quote) => {
3086
3142
  const give = quote.give;
3087
3143
  const balance = await wallet.getBalance();
3088
- const available = assetPartOf(give.asset) === BTC_ASSET_PART ? BigInt(balance.available) : balance.availableAssets.find((a) => give.asset.endsWith(a.assetId))?.amount ?? 0n;
3144
+ const available = isBtcAsset(give.asset) ? BigInt(balance.available) : balance.availableAssets.find((a) => give.asset.endsWith(a.assetId))?.amount ?? 0n;
3089
3145
  if (available < give.amount) {
3090
3146
  throw new InsufficientFunds(give.asset, give.amount, available);
3091
3147
  }
@@ -3242,7 +3298,7 @@ var fund = async (input, record) => {
3242
3298
  const { wallet } = input;
3243
3299
  if (record.family === "offer") {
3244
3300
  const amount = fromAtomicDecimal(record.give.amount);
3245
- const depositIsBtc = assetPartOf(record.route.give.asset) === BTC_ASSET_PART;
3301
+ const depositIsBtc = isBtcAssetLenient(record.route.give.asset);
3246
3302
  return wallet.send({
3247
3303
  address: record.swapAddress,
3248
3304
  // An asset deposit rides a dust-sat carrier: the solver's published one when the record
@@ -3278,7 +3334,7 @@ var reconcileFunding = async (input, record) => {
3278
3334
  };
3279
3335
  var depositMatches = (vtxo, record, expected) => {
3280
3336
  const giveAsset = record.route.give.asset;
3281
- if (assetPartOf(giveAsset) === BTC_ASSET_PART) {
3337
+ if (isBtcAssetLenient(giveAsset)) {
3282
3338
  return BigInt(vtxo.value) === expected;
3283
3339
  }
3284
3340
  return (vtxo.assets ?? []).some(
@@ -4086,7 +4142,13 @@ function classifyDepositSpend(offer, operatorPubkey, spendTxs, deposit) {
4086
4142
  return "indeterminate";
4087
4143
  }
4088
4144
  async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
4089
- const { operatorPubkey, scanned = /* @__PURE__ */ new Set(), reopen = [], hrp } = opts;
4145
+ const {
4146
+ operatorPubkey,
4147
+ scanned = /* @__PURE__ */ new Set(),
4148
+ reopen = [],
4149
+ hrp,
4150
+ recoveredIn = /* @__PURE__ */ new Set()
4151
+ } = opts;
4090
4152
  const reopened = [];
4091
4153
  for (const swap of reopen) {
4092
4154
  try {
@@ -4166,9 +4228,17 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
4166
4228
  continue;
4167
4229
  }
4168
4230
  const fromAmount = depositAmount.toString();
4169
- const spentTxid = vtxo.isSpent ? vtxo.arkTxId || vtxo.spentBy : void 0;
4231
+ const recovered = vtxo.isSpent && vtxo.isSwept && !!vtxo.settledBy && spendTxidsOf(vtxo).length === 0;
4232
+ const spentTxid = vtxo.isSpent ? vtxo.arkTxId || vtxo.spentBy || (recovered ? vtxo.settledBy : void 0) : void 0;
4170
4233
  let status = "pending";
4171
- if (vtxo.isSwept) status = "recoverable";
4234
+ if (recovered) {
4235
+ const ours = recoveredIn.has(vtxo.settledBy) || txByAnyId.has(vtxo.settledBy);
4236
+ if (!ours) {
4237
+ unresolved.add(fundingTx.redeemTxid);
4238
+ continue;
4239
+ }
4240
+ status = "cancelled";
4241
+ } else if (vtxo.isSwept && !vtxo.isSpent) status = "recoverable";
4172
4242
  else if (vtxo.isSpent) {
4173
4243
  const spendTxs = spendTxidsOf(vtxo).map((id) => spendTxByTxid.get(id)).filter((tx) => tx !== void 0);
4174
4244
  const kind = classifyDepositSpend(offer, operatorPubkey, spendTxs, {
@@ -4273,6 +4343,17 @@ var withRfqState = (record, state) => {
4273
4343
  ...mutableHalfOf(state)
4274
4344
  };
4275
4345
  };
4346
+ var pageRfqRecords = (records, filter, page) => {
4347
+ const rows = records.filter(
4348
+ (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)
4349
+ ).sort(
4350
+ (a, b) => a.updatedAt - b.updatedAt || (a.rfqId < b.rfqId ? -1 : a.rfqId > b.rfqId ? 1 : 0)
4351
+ ).slice(0, page.limit + 1);
4352
+ return (0, import_sdk18.pageResult)(rows, page.limit, (record) => ({
4353
+ updatedAt: record.updatedAt,
4354
+ rfqId: record.rfqId
4355
+ }));
4356
+ };
4276
4357
  var corridorRecordStore = (repository, onRecord = () => {
4277
4358
  }, admits = () => true) => {
4278
4359
  const byRfqId = /* @__PURE__ */ new Map();
@@ -4298,15 +4379,7 @@ var corridorRecordStore = (repository, onRecord = () => {
4298
4379
  assertRfqSwapPageFilter(filter);
4299
4380
  const { corridor } = splitRecords(await collectSwapRecords(repository));
4300
4381
  for (const record of corridor) index(record);
4301
- const rows = corridor.filter(admits).map(rfqRecordOf).filter(
4302
- (record) => (filter.state === void 0 || record.state === filter.state) && (filter.since === void 0 || record.updatedAt >= filter.since) && (!page.after || record.updatedAt > page.after.updatedAt || record.updatedAt === page.after.updatedAt && record.rfqId > page.after.rfqId)
4303
- ).sort(
4304
- (a, b) => a.updatedAt - b.updatedAt || (a.rfqId < b.rfqId ? -1 : a.rfqId > b.rfqId ? 1 : 0)
4305
- ).slice(0, page.limit + 1);
4306
- return (0, import_sdk18.pageResult)(rows, page.limit, (record) => ({
4307
- updatedAt: record.updatedAt,
4308
- rfqId: record.rfqId
4309
- }));
4382
+ return pageRfqRecords(corridor.filter(admits).map(rfqRecordOf), filter, page);
4310
4383
  },
4311
4384
  async getRfqSwap(rfqId) {
4312
4385
  const record = await recordFor(rfqId);
@@ -4541,7 +4614,7 @@ var retireOfferScripts = async (wallet, repository, record) => {
4541
4614
  };
4542
4615
 
4543
4616
  // src/client/drive.ts
4544
- var import_sdk27 = require("@arkade-os/sdk");
4617
+ var import_sdk28 = require("@arkade-os/sdk");
4545
4618
  var import_base17 = require("@scure/base");
4546
4619
 
4547
4620
  // src/claim.ts
@@ -4593,6 +4666,7 @@ async function pushClaim(operator, input) {
4593
4666
  // src/client/drive.ts
4594
4667
  init_onchainHtlc();
4595
4668
  init_coverage();
4669
+ init_offer();
4596
4670
  init_lockupContract();
4597
4671
 
4598
4672
  // src/refundBlocked.ts
@@ -5893,6 +5967,70 @@ async function watchOfferSwaps({
5893
5967
  };
5894
5968
  }
5895
5969
 
5970
+ // src/client/legacyRecords.ts
5971
+ var import_sdk27 = require("@arkade-os/sdk");
5972
+ init_repository();
5973
+ var readLegacyRfqSwaps = async (repository, filter = {}) => {
5974
+ try {
5975
+ return await collectRfqSwaps(repository, filter);
5976
+ } catch (error) {
5977
+ console.warn("[swap] the v1 rfq swaps could not be read", error);
5978
+ return [];
5979
+ }
5980
+ };
5981
+ var legacyLiveRfqSwaps = async (repository) => (await readLegacyRfqSwaps(repository)).filter((record) => !isRfqSwapTerminal(record.state));
5982
+ var withLegacyRfqSwaps = (bridge, repository, admits) => {
5983
+ const legacy = /* @__PURE__ */ new Set();
5984
+ return {
5985
+ index: bridge.index,
5986
+ quoteIdOf: bridge.quoteIdOf,
5987
+ async getRfqSwapsPage(filter, page) {
5988
+ (0, import_sdk27.assertPageRequest)(page);
5989
+ assertRfqSwapPageFilter(filter);
5990
+ const v2 = await collectRfqSwaps(bridge, filter);
5991
+ const held = new Set(
5992
+ splitRecords(await collectSwapRecords(repository)).corridor.map((r) => r.rfqId)
5993
+ );
5994
+ const v1 = (await readLegacyRfqSwaps(repository, filter)).filter(
5995
+ (record) => !held.has(record.rfqId) && admits(record)
5996
+ );
5997
+ for (const record of v1) legacy.add(record.rfqId);
5998
+ return pageRfqRecords([...v2, ...v1], filter, page);
5999
+ },
6000
+ async getRfqSwap(rfqId) {
6001
+ if (!legacy.has(rfqId)) {
6002
+ const record2 = await bridge.getRfqSwap(rfqId);
6003
+ if (record2 !== void 0) return record2;
6004
+ }
6005
+ const record = await repository.getRfqSwap(rfqId);
6006
+ if (record !== void 0) legacy.add(rfqId);
6007
+ return record;
6008
+ },
6009
+ async saveRfqSwap(record) {
6010
+ if (legacy.has(record.rfqId)) await repository.saveRfqSwap(record);
6011
+ else await bridge.saveRfqSwap(record);
6012
+ },
6013
+ removeRfqSwap: (rfqId) => bridge.removeRfqSwap(rfqId)
6014
+ };
6015
+ };
6016
+ var readLegacyAssetSwaps = async (repository) => {
6017
+ try {
6018
+ return await collectAssetSwaps(repository);
6019
+ } catch (error) {
6020
+ console.warn("[swap] the v1 swaps could not be read", error);
6021
+ return [];
6022
+ }
6023
+ };
6024
+ var legacyOfferDepositsToReopen = async (repository) => {
6025
+ const live = (await readLegacyAssetSwaps(repository)).filter(
6026
+ (swap) => !!swap.offerHex && !!swap.fundingTxid && (swap.status === "pending" || swap.status === "cancelling" || swap.status === "recoverable")
6027
+ );
6028
+ if (live.length === 0) return /* @__PURE__ */ new Set();
6029
+ const { offer } = splitRecords(await collectSwapRecords(repository));
6030
+ const adopted = new Set(offer.map((record) => record.fundingTxid));
6031
+ return new Set(live.map((swap) => swap.fundingTxid).filter((txid) => !adopted.has(txid)));
6032
+ };
6033
+
5896
6034
  // src/client/drive.ts
5897
6035
  var SwapDriveRefusedError = class extends Error {
5898
6036
  constructor(reason, detail, swapId) {
@@ -5921,6 +6059,7 @@ var createSwapDrive = (config) => {
5921
6059
  const live = /* @__PURE__ */ new Map();
5922
6060
  const refunding = /* @__PURE__ */ new Set();
5923
6061
  const swept = /* @__PURE__ */ new Map();
6062
+ const recoveredIn = /* @__PURE__ */ new Set();
5924
6063
  const passed = /* @__PURE__ */ new Set();
5925
6064
  const delivered = /* @__PURE__ */ new Map();
5926
6065
  const listeners = /* @__PURE__ */ new Set();
@@ -5959,14 +6098,23 @@ var createSwapDrive = (config) => {
5959
6098
  return repository;
5960
6099
  };
5961
6100
  const undrivable = /* @__PURE__ */ new Set();
6101
+ const undrivableLegacy = /* @__PURE__ */ new Set();
5962
6102
  let bridge;
5963
- const corridorStore = () => bridge ??= corridorRecordStore(
5964
- storage(),
5965
- remember,
5966
- // Terminal records stay readable but are excluded from the manager's read, sparing
5967
- // a rebuild per record just to file it `finished`. The index still learns their
5968
- // `rfqId` (see `getRfqSwapsPage`).
5969
- (r) => !undrivable.has(r.id) && !isRfqSwapTerminal(r.state)
6103
+ let readThrough;
6104
+ const corridorStore = () => (
6105
+ // LEGACY(v1): unwrap to `bridge` alone once the read-through goes.
6106
+ readThrough ??= withLegacyRfqSwaps(
6107
+ bridge ??= corridorRecordStore(
6108
+ storage(),
6109
+ remember,
6110
+ // Terminal records stay readable but are excluded from the manager's read, sparing
6111
+ // a rebuild per record just to file it `finished`. The index still learns their
6112
+ // `rfqId` (see `getRfqSwapsPage`).
6113
+ (r) => !undrivable.has(r.id) && !isRfqSwapTerminal(r.state)
6114
+ ),
6115
+ storage(),
6116
+ (r) => !undrivableLegacy.has(r.rfqId) && !isRfqSwapTerminal(r.state)
6117
+ )
5970
6118
  );
5971
6119
  const effectiveState = (swap) => {
5972
6120
  if (mode === "auto") return swap.state;
@@ -6061,7 +6209,7 @@ var createSwapDrive = (config) => {
6061
6209
  const secret = rfqClaimSecretOf(record);
6062
6210
  if (!secret) throw new Error(`rfq swap ${swap.rfqId} carries no claim secret`);
6063
6211
  const preimage = await preimageForSwapRecord(wallet, secret);
6064
- const signer = await (0, import_sdk27.contractSigner)(wallet, await (0, import_sdk27.identityDescriptor)(wallet.identity));
6212
+ const signer = await (0, import_sdk28.contractSigner)(wallet, await (0, import_sdk28.identityDescriptor)(wallet.identity));
6065
6213
  const claimKey = record.profile.claimKey;
6066
6214
  if (typeof claimKey === "string") {
6067
6215
  const held = import_base17.hex.encode(await signer.xOnlyPublicKey());
@@ -6105,7 +6253,7 @@ var createSwapDrive = (config) => {
6105
6253
  }
6106
6254
  };
6107
6255
  const drivable = async (record) => !readsChain(record.kind) || await resolveOnchain();
6108
- const pinnedNetwork = async () => (0, import_sdk27.getNetwork)(await config.network());
6256
+ const pinnedNetwork = async () => (0, import_sdk28.getNetwork)(await config.network());
6109
6257
  const claimLockup = async (swap, vtxos, { partiallyClaimed }) => {
6110
6258
  const record = await corridorStore().getRfqSwap(swap.rfqId);
6111
6259
  if (!record) throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
@@ -6120,10 +6268,10 @@ var createSwapDrive = (config) => {
6120
6268
  return track(
6121
6269
  pushClaim(operator, {
6122
6270
  contract: script,
6123
- receiver: await (0, import_sdk27.contractSigner)(wallet, secret.signingDescriptor),
6271
+ receiver: await (0, import_sdk28.contractSigner)(wallet, secret.signingDescriptor),
6124
6272
  preimage: await preimageForSwapRecord(wallet, secret),
6125
6273
  vtxos,
6126
- destinationPkScript: import_sdk27.ArkAddress.decode(payoutAddress).pkScript,
6274
+ destinationPkScript: import_sdk28.ArkAddress.decode(payoutAddress).pkScript,
6127
6275
  // Passed through: `pushClaim`'s own value check decides whether `P` is published.
6128
6276
  expectedAmount: swap.expectedAmount,
6129
6277
  partiallyClaimed,
@@ -6181,7 +6329,7 @@ var createSwapDrive = (config) => {
6181
6329
  };
6182
6330
  let offerSource;
6183
6331
  const offers = () => offerSource ??= offerRecordSource(storage(), remember, now);
6184
- const restoreOfferDeposits = async (reopen) => {
6332
+ const restoreOfferDeposits = async (reopen = []) => {
6185
6333
  const store = storage();
6186
6334
  const [history, scanned, address, network] = await Promise.all([
6187
6335
  wallet.getTransactionHistory(),
@@ -6190,12 +6338,15 @@ var createSwapDrive = (config) => {
6190
6338
  config.network()
6191
6339
  ]);
6192
6340
  const txs = history.map(toRestoreTx);
6193
- const { hrp, serverPubKey: operatorPubkey } = import_sdk27.ArkAddress.decode(address);
6194
- const cursor = reopen === void 0 ? scanned : new Set([...scanned].filter((txid) => txid !== reopen));
6341
+ const { hrp, serverPubKey: operatorPubkey } = import_sdk28.ArkAddress.decode(address);
6342
+ const reopened = await legacyOfferDepositsToReopen(store);
6343
+ for (const txid of reopen) reopened.add(txid);
6344
+ const cursor = reopened.size === 0 ? scanned : new Set([...scanned].filter((txid) => !reopened.has(txid)));
6195
6345
  const { restored, scannedTxids } = await restoreAssetSwaps(indexer, txs, /* @__PURE__ */ new Set(), {
6196
6346
  operatorPubkey,
6197
6347
  scanned: cursor,
6198
- hrp
6348
+ hrp,
6349
+ recoveredIn
6199
6350
  });
6200
6351
  const { offer } = splitRecords(await collectSwapRecords(store));
6201
6352
  const current = new Map(offer.map((record) => [record.id, record]));
@@ -6293,12 +6444,16 @@ var createSwapDrive = (config) => {
6293
6444
  const liveCorridor = corridor.filter((record) => !isRfqSwapTerminal(record.state));
6294
6445
  const store = corridorStore();
6295
6446
  for (const record of liveCorridor) store.index(record);
6296
- if (liveCorridor.length > 0) {
6447
+ const liveLegacy = await legacyLiveRfqSwaps(repository);
6448
+ if (liveCorridor.length > 0 || liveLegacy.length > 0) {
6297
6449
  try {
6298
6450
  await contractsOf();
6299
6451
  for (const record of liveCorridor) {
6300
6452
  if (!await drivable(record)) undrivable.add(record.id);
6301
6453
  }
6454
+ for (const record of liveLegacy) {
6455
+ if (!await drivable(record)) undrivableLegacy.add(record.rfqId);
6456
+ }
6302
6457
  managerDeps.repository = store;
6303
6458
  const result = await manager.restoreFromRepository();
6304
6459
  for (const swap of result.restored) {
@@ -6317,7 +6472,11 @@ var createSwapDrive = (config) => {
6317
6472
  }
6318
6473
  let offers2 = offer;
6319
6474
  try {
6320
- offers2 = await restoreOfferDeposits();
6475
+ offers2 = await restoreOfferDeposits(
6476
+ offer.flatMap(
6477
+ (record) => record.status === "recoverable" && record.fundingTxid !== void 0 ? [record.fundingTxid] : []
6478
+ )
6479
+ );
6321
6480
  } catch (error) {
6322
6481
  console.warn("[swap] the offer deposit restore did not complete", error);
6323
6482
  }
@@ -6384,8 +6543,8 @@ var createSwapDrive = (config) => {
6384
6543
  );
6385
6544
  }
6386
6545
  const txid2 = await track((await recoverer()).recoverVtxos());
6387
- const after2 = await recoverableAt(script);
6388
- const still = new Set(after2.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`));
6546
+ const after = await recoverableAt(script);
6547
+ const still = new Set(after.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`));
6389
6548
  const recovered2 = before.every((vtxo) => !still.has(`${vtxo.txid}:${vtxo.vout}`));
6390
6549
  if (recovered2) swept.delete(id);
6391
6550
  await manager.poll();
@@ -6399,10 +6558,31 @@ var createSwapDrive = (config) => {
6399
6558
  id
6400
6559
  );
6401
6560
  }
6402
- const txid = await track((await recoverer()).recoverVtxos());
6403
- await restoreOfferDeposits(record.fundingTxid);
6404
- const after = records.get(id);
6405
- const recovered = after?.family === "offer" && after.status !== "recoverable";
6561
+ const wentHome = async () => {
6562
+ await restoreOfferDeposits(
6563
+ record.fundingTxid === void 0 ? [] : [record.fundingTxid]
6564
+ );
6565
+ const after = records.get(id);
6566
+ return after?.family === "offer" && after.status !== "recoverable";
6567
+ };
6568
+ try {
6569
+ if (await wentHome()) return { recovered: true, swap: swapView(id) };
6570
+ } catch (error) {
6571
+ console.warn(`[swap] could not re-read offer ${id} before recovering it`, error);
6572
+ }
6573
+ const vtxoManager = await recoverer();
6574
+ await restoreOfferCoverage(wallet, [offerFactsOf(record)]);
6575
+ const txid = await track(vtxoManager.recoverVtxos());
6576
+ recoveredIn.add(txid);
6577
+ let recovered = false;
6578
+ try {
6579
+ recovered = await wentHome();
6580
+ } catch (error) {
6581
+ console.warn(
6582
+ `[swap] recovered offer ${id} in ${txid}, but could not re-read it`,
6583
+ error
6584
+ );
6585
+ }
6406
6586
  return { recovered, txid, swap: swapView(id) };
6407
6587
  };
6408
6588
  const swapView = (id) => {
@@ -6951,7 +7131,7 @@ var feedSpread = (plan, take, carrierSats = 0n) => {
6951
7131
  const spread = fair - payout;
6952
7132
  return spread > 0n ? spread : 0n;
6953
7133
  };
6954
- var sellsAssetForBtc = (endpoints) => assetPartOf(endpoints.give.asset) !== BTC_ASSET_PART && assetPartOf(endpoints.take.asset) === BTC_ASSET_PART;
7134
+ var sellsAssetForBtc = (endpoints) => !isBtcAsset(endpoints.give.asset) && isBtcAsset(endpoints.take.asset);
6955
7135
  var feedExpiry = (card, feed, now) => {
6956
7136
  const readAt = card.price_feed === void 0 ? void 0 : feed.fetchedAt(card.price_feed);
6957
7137
  const from = readAt === void 0 ? now : Math.floor(readAt / 1e3);
@@ -6972,7 +7152,7 @@ var verifyPlanLegs = (plan, legs, give) => {
6972
7152
 
6973
7153
  // src/client/quoteRfq.ts
6974
7154
  var import_base18 = require("@scure/base");
6975
- var import_sdk30 = require("@arkade-os/sdk");
7155
+ var import_sdk31 = require("@arkade-os/sdk");
6976
7156
  var import_solver_discovery9 = require("@arkade-os/solver-discovery");
6977
7157
  init_claimPacket();
6978
7158
  init_offer();
@@ -6981,11 +7161,11 @@ init_onchainHtlc();
6981
7161
  init_onchainHtlc();
6982
7162
 
6983
7163
  // src/payment/onchainSwap.ts
6984
- var import_sdk29 = require("@arkade-os/sdk");
7164
+ var import_sdk30 = require("@arkade-os/sdk");
6985
7165
  init_onchainHtlc();
6986
7166
 
6987
7167
  // src/payment/swapRail.ts
6988
- var import_sdk28 = require("@arkade-os/sdk");
7168
+ var import_sdk29 = require("@arkade-os/sdk");
6989
7169
 
6990
7170
  // src/client/sats.ts
6991
7171
  var satsOf = (value, field) => {
@@ -7042,13 +7222,13 @@ var lockupOf = (derived) => ({
7042
7222
  pkScript: derived.swapPkScript
7043
7223
  });
7044
7224
  var covenantInputs = (input) => {
7045
- const network = (0, import_sdk30.networkFromArkadeInfo)(input.info);
7225
+ const network = (0, import_sdk31.networkFromArkadeInfo)(input.info);
7046
7226
  const arkade2 = input.corridors.get("arkade").deps;
7047
7227
  return {
7048
- operatorPubkey: (0, import_sdk30.toXOnly)(import_base18.hex.decode(input.info.signerPubkey), "ark signer key"),
7228
+ operatorPubkey: (0, import_sdk31.toXOnly)(import_base18.hex.decode(input.info.signerPubkey), "ark signer key"),
7049
7229
  // The resolved per-network pin, never operator-reported: it lands in a covenant leaf
7050
7230
  // that decides who can move the funds.
7051
- emulatorPubkey: (0, import_sdk30.toXOnly)(import_base18.hex.decode(arkade2.emulatorPubkey), "emulator signer key"),
7231
+ emulatorPubkey: (0, import_sdk31.toXOnly)(import_base18.hex.decode(arkade2.emulatorPubkey), "emulator signer key"),
7052
7232
  claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
7053
7233
  hrp: network.hrp
7054
7234
  };
@@ -7185,14 +7365,14 @@ var assetSidesOf = (legs) => {
7185
7365
  { give: "arkade", take: "arkade" }
7186
7366
  );
7187
7367
  }
7188
- return giveIsBtc ? { wantAsset: import_sdk30.asset.AssetId.fromString(legs.take.assetId) } : { offerAsset: import_sdk30.asset.AssetId.fromString(legs.give.assetId) };
7368
+ return giveIsBtc ? { wantAsset: import_sdk31.asset.AssetId.fromString(legs.take.assetId) } : { offerAsset: import_sdk31.asset.AssetId.fromString(legs.give.assetId) };
7189
7369
  };
7190
7370
  var makerPosition = async (wallet) => {
7191
7371
  const [address, publicKey] = await Promise.all([
7192
7372
  wallet.getAddress(),
7193
7373
  wallet.identity.xOnlyPublicKey()
7194
7374
  ]);
7195
- return { pkScript: import_sdk30.ArkAddress.decode(address).pkScript, publicKey };
7375
+ return { pkScript: import_sdk31.ArkAddress.decode(address).pkScript, publicKey };
7196
7376
  };
7197
7377
  var quoteLightningSend = async (input) => {
7198
7378
  const invoice = input.endpoints.take.instrument;
@@ -7201,7 +7381,7 @@ var quoteLightningSend = async (input) => {
7201
7381
  }
7202
7382
  const pair = rfqPairFor(input.legs.give, input.legs.take);
7203
7383
  const rfqId = newRfqId();
7204
- const secrets = await (0, import_sdk30.provisionRefundKey)(input.wallet);
7384
+ const secrets = await (0, import_sdk31.provisionRefundKey)(input.wallet);
7205
7385
  const wire = await input.transport.requestQuote(
7206
7386
  lightningSendRequest({
7207
7387
  rfqId,
@@ -7270,7 +7450,7 @@ var quoteLightningReceive = async (input) => {
7270
7450
  const pinned = pinnedFor(input);
7271
7451
  const pair = rfqPairFor(input.legs.give, input.legs.take);
7272
7452
  const rfqId = newRfqId();
7273
- const secrets = await (0, import_sdk30.provisionClaimSecret)(input.wallet);
7453
+ const secrets = await (0, import_sdk31.provisionClaimSecret)(input.wallet);
7274
7454
  const paymentHash = import_base18.hex.encode(secrets.paymentHash);
7275
7455
  const payoutAddress = await input.wallet.getAddress();
7276
7456
  const lightning = input.corridors.get("lightning").deps;
@@ -7382,8 +7562,8 @@ var quoteOnchainSend = async (input) => {
7382
7562
  claimVsize: onchain.claimVsize
7383
7563
  }) : void 0;
7384
7564
  const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
7385
- const secrets = await (0, import_sdk30.provisionClaimSecret)(input.wallet);
7386
- const payoutKey = await (0, import_sdk30.provisionRefundKey)(input.wallet);
7565
+ const secrets = await (0, import_sdk31.provisionClaimSecret)(input.wallet);
7566
+ const payoutKey = await (0, import_sdk31.provisionRefundKey)(input.wallet);
7387
7567
  const paymentHash = import_base18.hex.encode(secrets.paymentHash);
7388
7568
  const wire = await input.transport.requestQuote(
7389
7569
  withCanonicalAmount(
@@ -7480,7 +7660,7 @@ var quoteOnchainSend = async (input) => {
7480
7660
  };
7481
7661
 
7482
7662
  // src/client/verbs.ts
7483
- var import_sdk31 = require("@arkade-os/sdk");
7663
+ var import_sdk32 = require("@arkade-os/sdk");
7484
7664
  var enforceFeeCeiling = (quote, call, policy) => {
7485
7665
  let ceiling;
7486
7666
  for (const [source, limit] of [
@@ -7505,9 +7685,9 @@ var settle = async (deps, input, maxFee) => {
7505
7685
  return deps.accept(quote);
7506
7686
  };
7507
7687
  var pay = async (deps, destination, options = {}) => {
7508
- const arkade2 = (0, import_sdk31.arkTarget)(destination);
7688
+ const arkade2 = (0, import_sdk32.arkTarget)(destination);
7509
7689
  if (arkade2 !== void 0) {
7510
- const amount = (0, import_sdk31.resolveSendAmount)(
7690
+ const amount = (0, import_sdk32.resolveSendAmount)(
7511
7691
  "ark",
7512
7692
  destination,
7513
7693
  options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
@@ -7820,7 +8000,7 @@ var createSwapClient = (config) => {
7820
8000
 
7821
8001
  // src/reveal.ts
7822
8002
  var import_base20 = require("@scure/base");
7823
- var import_sdk32 = require("@arkade-os/sdk");
8003
+ var import_sdk33 = require("@arkade-os/sdk");
7824
8004
  init_claimPacket();
7825
8005
  init_onchainHtlc();
7826
8006
  var CovclaimdRevealError = class extends Error {
@@ -7926,7 +8106,7 @@ function revealFieldsFromScript(script) {
7926
8106
  }
7927
8107
  async function revealClaimPacket(client, input) {
7928
8108
  const fields = revealFieldsFromScript(input.script);
7929
- if (import_base20.hex.encode(import_sdk32.ArkAddress.decode(input.address).pkScript) !== import_base20.hex.encode(input.script.pkScript)) {
8109
+ if (import_base20.hex.encode(import_sdk33.ArkAddress.decode(input.address).pkScript) !== import_base20.hex.encode(input.script.pkScript)) {
7930
8110
  throw new Error("address does not belong to this covenant");
7931
8111
  }
7932
8112
  assertPreimageMatches(input.preimage, input.script.options.preimageHash);
@@ -7991,6 +8171,7 @@ async function revealClaimPacket(client, input) {
7991
8171
  assetSwapIdOf,
7992
8172
  attesting,
7993
8173
  bitcoinNetworkOf,
8174
+ btcAssetPart,
7994
8175
  btcOn,
7995
8176
  cancelSwap,
7996
8177
  canonicalAssetId,
@@ -8026,6 +8207,8 @@ async function revealClaimPacket(client, input) {
8026
8207
  isAddressable,
8027
8208
  isAssetId,
8028
8209
  isAtomicDecimal,
8210
+ isBtcAsset,
8211
+ isBtcAssetLenient,
8029
8212
  isCardMarket,
8030
8213
  isIndexedNetwork,
8031
8214
  isNetworkRef,
@@ -8044,6 +8227,7 @@ async function revealClaimPacket(client, input) {
8044
8227
  offerOutcome,
8045
8228
  offerRecordSource,
8046
8229
  onchainCorridor,
8230
+ pageRfqRecords,
8047
8231
  parseAssetId,
8048
8232
  parseRfqQuote,
8049
8233
  pay,