@arkade-os/swap 0.1.0-rc.26 → 0.1.0-rc.28

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 (38) hide show
  1. package/dist/advanced.cjs +475 -149
  2. package/dist/advanced.d.cts +9 -8
  3. package/dist/advanced.d.ts +9 -8
  4. package/dist/advanced.js +5 -3
  5. package/dist/{chunk-DHFKCTER.js → chunk-4X56MN56.js} +11 -2
  6. package/dist/{chunk-6O3L4AVI.js → chunk-DGHBRLCF.js} +42 -15
  7. package/dist/{chunk-XBMWEK43.js → chunk-ZF57EAJQ.js} +195 -126
  8. package/dist/index.cjs +473 -149
  9. package/dist/index.d.cts +7 -6
  10. package/dist/index.d.ts +7 -6
  11. package/dist/index.js +3 -3
  12. package/dist/{lockupContract-BTCGwjRH.d.cts → lockupContract-BE_tSx8i.d.cts} +1 -1
  13. package/dist/{lockupContract-BTCE7g83.d.ts → lockupContract-CYSMMrv4.d.ts} +1 -1
  14. package/dist/node/index.d.cts +9 -3
  15. package/dist/node/index.d.ts +9 -3
  16. package/dist/nostr.cjs +238 -86
  17. package/dist/nostr.d.cts +34 -2
  18. package/dist/nostr.d.ts +34 -2
  19. package/dist/nostr.js +227 -80
  20. package/dist/{offer-CsXgroM0.d.cts → offer-C_rgJU7J.d.cts} +1 -1
  21. package/dist/{offer-DYCiKDm6.d.ts → offer-Cr7AaLt-.d.ts} +1 -1
  22. package/dist/{offerFillPlan-CFT8qgTV.d.cts → offerFillPlan-B88PzcLr.d.cts} +13 -17
  23. package/dist/{offerFillPlan-BQnzburi.d.ts → offerFillPlan-DFMl7D3Q.d.ts} +13 -17
  24. package/dist/protocol.cjs +434 -209
  25. package/dist/protocol.d.cts +25 -39
  26. package/dist/protocol.d.ts +25 -39
  27. package/dist/protocol.js +8 -8
  28. package/dist/repositories/realm/index.d.cts +2 -2
  29. package/dist/repositories/realm/index.d.ts +2 -2
  30. package/dist/repositories/sqlite/index.d.cts +2 -2
  31. package/dist/repositories/sqlite/index.d.ts +2 -2
  32. package/dist/{repository-CSJXRd5N.d.ts → repository-CFNZUy2y.d.ts} +55 -103
  33. package/dist/{repository-Bgn0apiL.d.cts → repository-Cs60kDRs.d.cts} +55 -103
  34. package/dist/{rfq-m9tCbQx7.d.cts → rfq-CRiAHBBH.d.cts} +14 -2
  35. package/dist/{rfq-m9tCbQx7.d.ts → rfq-CRiAHBBH.d.ts} +14 -2
  36. package/dist/{watch-CLJXFpMq.d.cts → watch-BEgoHfHu.d.cts} +1 -1
  37. package/dist/{watch-D0R7YhYg.d.ts → watch-C7zGV8zh.d.ts} +1 -1
  38. package/package.json +4 -4
package/dist/advanced.cjs CHANGED
@@ -1399,6 +1399,13 @@ function onchainHtlcScript(params, network) {
1399
1399
  refundLocktime: params.refundLocktime
1400
1400
  };
1401
1401
  }
1402
+ function nextClaimFeeRate(input) {
1403
+ const last = input.lastSatVb;
1404
+ const estimate = Number.isFinite(input.estimateSatVb) ? input.estimateSatVb : 0;
1405
+ const wanted = last === void 0 ? Math.max(input.configuredSatVb, estimate) : input.bump ? Math.max(Math.ceil(last * 1.5), last + 1, estimate) : Math.max(last, estimate);
1406
+ const affordable = Number((input.utxoAmount - ONCHAIN_DUST_SATS) / BigInt(ONCHAIN_CLAIM_VSIZE));
1407
+ return Math.max(last ?? input.configuredSatVb, Math.min(wanted, affordable));
1408
+ }
1402
1409
  function extractPreimage(txHex, paymentHash) {
1403
1410
  let raw;
1404
1411
  try {
@@ -1415,7 +1422,7 @@ function extractPreimage(txHex, paymentHash) {
1415
1422
  }
1416
1423
  async function claimOnchainFill(chain, input) {
1417
1424
  const now = input.now ?? Math.floor(Date.now() / 1e3);
1418
- if (input.htlc.refundLocktime - now < ONCHAIN_CLAIM_MARGIN_SECONDS) {
1425
+ if (!input.republish && input.htlc.refundLocktime - now < ONCHAIN_CLAIM_MARGIN_SECONDS) {
1419
1426
  throw gateError(
1420
1427
  "claim_window_closed",
1421
1428
  "refund leaf opens too soon to claim safely \u2014 take the covenant refund instead"
@@ -1449,7 +1456,7 @@ async function classifyOnchainHtlc(chain, input) {
1449
1456
  if (mtp >= input.htlc.refundLocktime) return { phase: "refundable", utxo: best };
1450
1457
  return { phase: "claimable", utxo: best };
1451
1458
  }
1452
- var import_base4, import_sha22, import_legacy, btc, import_sdk5, ONCHAIN_ORDER_MARGIN_SECONDS, ONCHAIN_CLAIM_MARGIN_SECONDS, MAX_MIN_CONFIRMATIONS, LOCKTIME_THRESHOLD, ONCHAIN_SECONDS_PER_BLOCK, ONCHAIN_DUST_SATS, ONCHAIN_CLAIM_VSIZE, paymentHashOf, h160FromPaymentHash, assertPreimageMatches, gateError, L1_NETWORKS, l1ScriptForAddress, buildLeafSpend, buildHtlcClaim, buildHtlcRefund;
1459
+ var import_base4, import_sha22, import_legacy, btc, import_sdk5, ONCHAIN_ORDER_MARGIN_SECONDS, ONCHAIN_CLAIM_MARGIN_SECONDS, ONCHAIN_CLAIM_BUMP_SECONDS, MAX_MIN_CONFIRMATIONS, LOCKTIME_THRESHOLD, ONCHAIN_SECONDS_PER_BLOCK, ONCHAIN_DUST_SATS, ONCHAIN_CLAIM_VSIZE, paymentHashOf, h160FromPaymentHash, assertPreimageMatches, gateError, L1_NETWORKS, l1ScriptForAddress, buildLeafSpend, buildHtlcClaim, buildHtlcRefund;
1453
1460
  var init_onchainHtlc = __esm({
1454
1461
  "src/onchainHtlc.ts"() {
1455
1462
  "use strict";
@@ -1460,6 +1467,7 @@ var init_onchainHtlc = __esm({
1460
1467
  import_sdk5 = require("@arkade-os/sdk");
1461
1468
  ONCHAIN_ORDER_MARGIN_SECONDS = 2 * 60 * 60;
1462
1469
  ONCHAIN_CLAIM_MARGIN_SECONDS = 90 * 60;
1470
+ ONCHAIN_CLAIM_BUMP_SECONDS = 20 * 60;
1463
1471
  MAX_MIN_CONFIRMATIONS = 6;
1464
1472
  LOCKTIME_THRESHOLD = 5e8;
1465
1473
  ONCHAIN_SECONDS_PER_BLOCK = 600;
@@ -2317,30 +2325,153 @@ var init_closeOnceWebSocket = __esm({
2317
2325
  }
2318
2326
  });
2319
2327
 
2328
+ // src/nostrPool.ts
2329
+ var import_nostr_tools, import_utils3, shared, IDLE_CLOSE_MS, NEVER_IDLE_MS, PUBLISH_TIMED_OUT, POOL_DESTROYED, urlKey, SharedPool, createNostrPool, sharedNostrPool, closeSharedNostrPool;
2330
+ var init_nostrPool = __esm({
2331
+ "src/nostrPool.ts"() {
2332
+ "use strict";
2333
+ import_nostr_tools = require("nostr-tools");
2334
+ import_utils3 = require("nostr-tools/utils");
2335
+ init_closeOnceWebSocket();
2336
+ IDLE_CLOSE_MS = 3e4;
2337
+ NEVER_IDLE_MS = 2 ** 31 - 1;
2338
+ PUBLISH_TIMED_OUT = "publish timed out";
2339
+ POOL_DESTROYED = "nostr pool destroyed";
2340
+ urlKey = (url) => {
2341
+ try {
2342
+ return (0, import_utils3.normalizeURL)(url);
2343
+ } catch {
2344
+ return url;
2345
+ }
2346
+ };
2347
+ SharedPool = class extends import_nostr_tools.SimplePool {
2348
+ #users = /* @__PURE__ */ new Map();
2349
+ #idle = /* @__PURE__ */ new Map();
2350
+ #destroyed = false;
2351
+ /** Count one user on each relay; the returned release is idempotent. */
2352
+ #hold(urls) {
2353
+ const held = [...new Set(urls.map(urlKey))];
2354
+ for (const url of held) {
2355
+ clearTimeout(this.#idle.get(url));
2356
+ this.#idle.delete(url);
2357
+ this.#users.set(url, (this.#users.get(url) ?? 0) + 1);
2358
+ }
2359
+ let released = false;
2360
+ return () => {
2361
+ if (released) return;
2362
+ released = true;
2363
+ for (const url of held) {
2364
+ const left = (this.#users.get(url) ?? 1) - 1;
2365
+ if (left > 0) {
2366
+ this.#users.set(url, left);
2367
+ continue;
2368
+ }
2369
+ this.#users.delete(url);
2370
+ const timer = setTimeout(() => {
2371
+ this.#idle.delete(url);
2372
+ if (!this.#users.has(url)) this.close([url]);
2373
+ }, IDLE_CLOSE_MS);
2374
+ timer.unref?.();
2375
+ this.#idle.set(url, timer);
2376
+ }
2377
+ };
2378
+ }
2379
+ /**
2380
+ * A destroyed pool would otherwise reconnect for anyone still holding it (a transport that
2381
+ * outlived closeSharedNostrPool()), opening a socket no one can close. Refused here, a
2382
+ * subscription reports every relay lost and a publish a connection failure.
2383
+ */
2384
+ async ensureRelay(...args) {
2385
+ if (this.#destroyed) throw new Error(POOL_DESTROYED);
2386
+ return super.ensureRelay(...args);
2387
+ }
2388
+ subscribeMap(...[requests, params]) {
2389
+ const release = this.#hold(requests.map((request) => request.url));
2390
+ const closer = super.subscribeMap(requests, {
2391
+ ...params,
2392
+ // Every relay dropped it: nothing is left to hold the sockets for.
2393
+ onclose: (reasons) => {
2394
+ release();
2395
+ params.onclose?.(reasons);
2396
+ }
2397
+ });
2398
+ let closed = false;
2399
+ return {
2400
+ close: (reason) => {
2401
+ if (closed) return;
2402
+ closed = true;
2403
+ release();
2404
+ closer.close(reason);
2405
+ }
2406
+ };
2407
+ }
2408
+ publish(...[relays, event, params]) {
2409
+ const release = this.#hold(relays);
2410
+ const sent = super.publish(relays, event, params);
2411
+ sent.forEach((publish, i) => {
2412
+ publish.catch((error) => {
2413
+ if (error instanceof Error && error.message === PUBLISH_TIMED_OUT)
2414
+ this.close([relays[i]]);
2415
+ });
2416
+ });
2417
+ void Promise.allSettled(sent).then(release);
2418
+ return sent;
2419
+ }
2420
+ destroy() {
2421
+ this.#destroyed = true;
2422
+ for (const timer of this.#idle.values()) clearTimeout(timer);
2423
+ this.#idle.clear();
2424
+ this.#users.clear();
2425
+ super.destroy();
2426
+ }
2427
+ };
2428
+ createNostrPool = () => (
2429
+ // SimplePool forwards every option at runtime; its declared options just omit most of them.
2430
+ new SharedPool({
2431
+ enablePing: true,
2432
+ idleTimeout: NEVER_IDLE_MS,
2433
+ ...CloseOnceWebSocket ? { websocketImplementation: CloseOnceWebSocket } : {}
2434
+ })
2435
+ );
2436
+ sharedNostrPool = () => shared ??= createNostrPool();
2437
+ closeSharedNostrPool = () => {
2438
+ const pool = shared;
2439
+ shared = void 0;
2440
+ if (!pool) return;
2441
+ try {
2442
+ pool.destroy();
2443
+ } catch {
2444
+ }
2445
+ };
2446
+ }
2447
+ });
2448
+
2320
2449
  // src/nostr.ts
2321
2450
  var nostr_exports = {};
2322
2451
  __export(nostr_exports, {
2323
2452
  RFQ_DIRECTED_KIND: () => RFQ_DIRECTED_KIND,
2324
2453
  RelayUnavailable: () => RelayUnavailable,
2325
2454
  TransportClosed: () => TransportClosed,
2455
+ closeSharedNostrPool: () => closeSharedNostrPool,
2456
+ createNostrPool: () => createNostrPool,
2326
2457
  nostrCardFetcher: () => nostrCardFetcher,
2327
- nostrRfqTransport: () => nostrRfqTransport
2458
+ nostrRfqTransport: () => nostrRfqTransport,
2459
+ sharedNostrPool: () => sharedNostrPool
2328
2460
  });
2329
- var import_solver_discovery7, import_sdk19, import_nostr_tools, RFQ_DIRECTED_KIND, DEFAULT_TIMEOUT_MS, CARD_FETCH_TIMEOUT_MS, newPool, RelayUnavailable, TransportClosed, closeReasons, nostrRfqTransport, isNewer, nostrCardFetcher;
2461
+ var import_solver_discovery7, import_sdk19, import_nostr_tools2, RFQ_DIRECTED_KIND, DEFAULT_TIMEOUT_MS, CONNECTION_FAILURE, CARD_FETCH_TIMEOUT_MS, RelayUnavailable, TransportClosed, closeReasons, nostrRfqTransport, isNewer, nostrCardFetcher;
2330
2462
  var init_nostr = __esm({
2331
2463
  "src/nostr.ts"() {
2332
2464
  "use strict";
2333
2465
  import_solver_discovery7 = require("@arkade-os/solver-discovery");
2334
2466
  init_rfq();
2335
- init_closeOnceWebSocket();
2467
+ init_nostrPool();
2336
2468
  import_sdk19 = require("@arkade-os/sdk");
2337
- import_nostr_tools = require("nostr-tools");
2469
+ import_nostr_tools2 = require("nostr-tools");
2470
+ init_nostrPool();
2338
2471
  RFQ_DIRECTED_KIND = 24859;
2339
2472
  DEFAULT_TIMEOUT_MS = 3e4;
2473
+ CONNECTION_FAILURE = "connection failure";
2340
2474
  CARD_FETCH_TIMEOUT_MS = 5e3;
2341
- newPool = () => new import_nostr_tools.SimplePool(
2342
- CloseOnceWebSocket ? { websocketImplementation: CloseOnceWebSocket } : void 0
2343
- );
2344
2475
  RelayUnavailable = class extends Error {
2345
2476
  reasons;
2346
2477
  constructor(reasons) {
@@ -2364,13 +2495,13 @@ var init_nostr = __esm({
2364
2495
  (0, import_sdk19.assertTimerMs)("timeoutMs", options.timeoutMs);
2365
2496
  const relays = options.relays;
2366
2497
  const solverPubkey = options.solverPubkey;
2367
- const secretKey = options.secretKey ?? (0, import_nostr_tools.generateSecretKey)();
2368
- const pubkey = (0, import_nostr_tools.getPublicKey)(secretKey);
2369
- const pool = options.pool ?? newPool();
2370
- const ownsPool = !options.pool;
2498
+ const secretKey = options.secretKey ?? (0, import_nostr_tools2.generateSecretKey)();
2499
+ const pubkey = (0, import_nostr_tools2.getPublicKey)(secretKey);
2500
+ const pool = options.pool ?? sharedNostrPool();
2371
2501
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
2372
- const conversationKey = import_nostr_tools.nip44.v2.utils.getConversationKey(secretKey, solverPubkey);
2502
+ const conversationKey = import_nostr_tools2.nip44.v2.utils.getConversationKey(secretKey, solverPubkey);
2373
2503
  let closed = false;
2504
+ let lost;
2374
2505
  const waiters = /* @__PURE__ */ new Map();
2375
2506
  const subscription = pool.subscribeMany(
2376
2507
  relays,
@@ -2379,7 +2510,7 @@ var init_nostr = __esm({
2379
2510
  onevent(event) {
2380
2511
  let payload;
2381
2512
  try {
2382
- payload = JSON.parse(import_nostr_tools.nip44.v2.decrypt(event.content, conversationKey));
2513
+ payload = JSON.parse(import_nostr_tools2.nip44.v2.decrypt(event.content, conversationKey));
2383
2514
  } catch {
2384
2515
  return;
2385
2516
  }
@@ -2391,64 +2522,83 @@ var init_nostr = __esm({
2391
2522
  onclose(reasons) {
2392
2523
  if (closed) return;
2393
2524
  const error = new RelayUnavailable(closeReasons(reasons));
2525
+ lost = error;
2394
2526
  for (const waiter of waiters.values()) waiter.reject(error);
2395
2527
  waiters.clear();
2396
2528
  }
2397
2529
  }
2398
2530
  );
2399
2531
  const send = async (payload) => {
2400
- const event = (0, import_nostr_tools.finalizeEvent)(
2532
+ const event = (0, import_nostr_tools2.finalizeEvent)(
2401
2533
  {
2402
2534
  kind: RFQ_DIRECTED_KIND,
2403
2535
  created_at: Math.floor(Date.now() / 1e3),
2404
2536
  tags: [["p", solverPubkey]],
2405
- content: import_nostr_tools.nip44.v2.encrypt(JSON.stringify(payload), conversationKey)
2537
+ content: import_nostr_tools2.nip44.v2.encrypt(JSON.stringify(payload), conversationKey)
2406
2538
  },
2407
2539
  secretKey
2408
2540
  );
2409
2541
  const results = await Promise.allSettled(pool.publish(relays, event));
2410
- if (!results.some((r) => r.status === "fulfilled")) {
2411
- throw new Error("no relay accepted the RFQ message");
2412
- }
2542
+ const reasons = results.map(
2543
+ (r) => r.status === "rejected" ? String(r.reason) : String(r.value)
2544
+ );
2545
+ const accepted = results.some(
2546
+ (r) => r.status === "fulfilled" && !String(r.value).startsWith(CONNECTION_FAILURE)
2547
+ );
2548
+ if (!accepted) throw new Error(`no relay accepted the RFQ message: ${reasons.join("; ")}`);
2413
2549
  };
2414
- const awaitReply = (rfqId) => new Promise((resolve, reject) => {
2415
- const timer = setTimeout(() => {
2416
- waiters.delete(rfqId);
2417
- reject(new Error(`no solver reply within ${timeoutMs}ms`));
2418
- }, timeoutMs);
2419
- waiters.set(rfqId, {
2420
- resolve: (payload) => {
2421
- clearTimeout(timer);
2550
+ const awaitReply = (rfqId) => {
2551
+ const reply = new Promise((resolve, reject) => {
2552
+ const timer = setTimeout(() => {
2422
2553
  waiters.delete(rfqId);
2423
- resolve(payload);
2424
- },
2425
- reject: (error) => {
2426
- clearTimeout(timer);
2427
- waiters.delete(rfqId);
2428
- reject(error);
2429
- }
2554
+ reject(new Error(`no solver reply within ${timeoutMs}ms`));
2555
+ }, timeoutMs);
2556
+ waiters.set(rfqId, {
2557
+ resolve: (payload) => {
2558
+ clearTimeout(timer);
2559
+ waiters.delete(rfqId);
2560
+ resolve(payload);
2561
+ },
2562
+ reject: (error) => {
2563
+ clearTimeout(timer);
2564
+ waiters.delete(rfqId);
2565
+ reject(error);
2566
+ }
2567
+ });
2430
2568
  });
2431
- });
2569
+ reply.catch(() => {
2570
+ });
2571
+ return reply;
2572
+ };
2573
+ const ask = async (rfqId, payload) => {
2574
+ if (closed) throw new TransportClosed();
2575
+ if (lost) throw lost;
2576
+ const reply = awaitReply(rfqId);
2577
+ try {
2578
+ await send(payload);
2579
+ } catch (error) {
2580
+ waiters.get(rfqId)?.reject(error);
2581
+ throw error;
2582
+ }
2583
+ return reply;
2584
+ };
2432
2585
  return {
2433
2586
  async requestQuote(payload) {
2434
2587
  const rfqId = String(payload.rfq_id);
2435
- const reply = awaitReply(rfqId);
2436
- await send(payload);
2437
- return expectQuote(await reply, rfqId, pairOf(payload));
2588
+ return expectQuote(await ask(rfqId, payload), rfqId, pairOf(payload));
2438
2589
  },
2439
2590
  async status(rfqId) {
2440
- const reply = awaitReply(rfqId);
2441
- await send({ v: 1, type: "rfq_status_request", rfq_id: rfqId });
2591
+ const reply = ask(rfqId, { v: 1, type: "rfq_status_request", rfq_id: rfqId });
2442
2592
  const payload = await reply;
2443
2593
  if (payload?.type !== "rfq_status") return null;
2444
2594
  return payload;
2445
2595
  },
2446
2596
  async close() {
2597
+ if (closed) return;
2447
2598
  closed = true;
2448
2599
  for (const waiter of waiters.values()) waiter.reject(new TransportClosed());
2449
2600
  waiters.clear();
2450
- if (ownsPool) pool.close(relays);
2451
- else subscription.close();
2601
+ subscription.close();
2452
2602
  }
2453
2603
  };
2454
2604
  };
@@ -2457,6 +2607,7 @@ var init_nostr = __esm({
2457
2607
  (0, import_sdk19.assertTimerMs)("timeoutMs", options.timeoutMs);
2458
2608
  if (options.timeoutMs === 0) throw new Error("timeoutMs must be positive");
2459
2609
  const seen = /* @__PURE__ */ new Map();
2610
+ const inflight = /* @__PURE__ */ new Map();
2460
2611
  return {
2461
2612
  async fetch(solvers, network) {
2462
2613
  const asked = new Set(solvers.map((solver) => solver.discovery_pubkey));
@@ -2465,55 +2616,65 @@ var init_nostr = __esm({
2465
2616
  ...new Set(solvers.flatMap((solver) => solver.transports?.nostr?.relays ?? []))
2466
2617
  ];
2467
2618
  if (authors.length === 0 || relays.length === 0) return [];
2468
- const timeoutMs = options.timeoutMs ?? CARD_FETCH_TIMEOUT_MS;
2469
- const pool = options.pool ?? newPool();
2470
- const latest = /* @__PURE__ */ new Map();
2471
- let subscription;
2472
- let timer;
2473
- try {
2474
- await new Promise((resolve) => {
2475
- timer = setTimeout(resolve, timeoutMs);
2476
- subscription = pool.subscribeMany(
2477
- relays,
2478
- { kinds: [import_solver_discovery7.SOLVER_CARD_KIND], authors, "#d": [network] },
2479
- {
2480
- // Relays are untrusted: re-check the filter and the signature, so a stray
2481
- // or forged later event cannot shadow the real card.
2482
- onevent(event) {
2483
- if (event.kind !== import_solver_discovery7.SOLVER_CARD_KIND || !asked.has(event.pubkey))
2484
- return;
2485
- if (!(0, import_nostr_tools.verifyEvent)(event)) return;
2486
- if (event.tags.find((tag) => tag[0] === "d")?.[1] !== network)
2487
- return;
2488
- if (isNewer(event, latest.get(event.pubkey)))
2489
- latest.set(event.pubkey, event);
2490
- },
2491
- oneose: () => resolve(),
2492
- onclose: () => resolve()
2493
- }
2494
- );
2495
- });
2496
- } finally {
2497
- clearTimeout(timer);
2498
- if (options.pool) subscription?.close();
2499
- else pool.close(relays);
2500
- }
2501
- for (const author of authors) {
2502
- const key = `${network}:${author}`;
2503
- const event = latest.get(author);
2504
- if (event && isNewer(event, seen.get(key))) seen.set(key, event);
2505
- const best = seen.get(key);
2506
- if (best) latest.set(author, best);
2507
- }
2508
- const cards = [];
2509
- for (const event of latest.values()) {
2619
+ const key = `${network}:${[...asked].sort().join(",")}@${[...relays].sort().join(",")}`;
2620
+ const pending = inflight.get(key);
2621
+ if (pending) return pending;
2622
+ const task = (async () => {
2623
+ const timeoutMs = options.timeoutMs ?? CARD_FETCH_TIMEOUT_MS;
2624
+ const pool = options.pool ?? sharedNostrPool();
2625
+ const latest = /* @__PURE__ */ new Map();
2626
+ let subscription;
2627
+ let timer;
2510
2628
  try {
2511
- const card = JSON.parse(event.content);
2512
- cards.push({ pubkey: event.pubkey, createdAt: event.created_at, card });
2513
- } catch {
2629
+ await new Promise((resolve) => {
2630
+ timer = setTimeout(resolve, timeoutMs);
2631
+ subscription = pool.subscribeMany(
2632
+ relays,
2633
+ { kinds: [import_solver_discovery7.SOLVER_CARD_KIND], authors, "#d": [network] },
2634
+ {
2635
+ // Relays are untrusted: re-check the filter and the signature, so a stray
2636
+ // or forged later event cannot shadow the real card.
2637
+ onevent(event) {
2638
+ if (event.kind !== import_solver_discovery7.SOLVER_CARD_KIND || !asked.has(event.pubkey))
2639
+ return;
2640
+ if (!(0, import_nostr_tools2.verifyEvent)(event)) return;
2641
+ if (event.tags.find((tag) => tag[0] === "d")?.[1] !== network)
2642
+ return;
2643
+ if (isNewer(event, latest.get(event.pubkey)))
2644
+ latest.set(event.pubkey, event);
2645
+ },
2646
+ oneose: () => resolve(),
2647
+ onclose: () => resolve()
2648
+ }
2649
+ );
2650
+ });
2651
+ } finally {
2652
+ clearTimeout(timer);
2653
+ subscription?.close();
2654
+ }
2655
+ for (const author of authors) {
2656
+ const seenKey = `${network}:${author}`;
2657
+ const event = latest.get(author);
2658
+ if (event && isNewer(event, seen.get(seenKey))) seen.set(seenKey, event);
2659
+ const best = seen.get(seenKey);
2660
+ if (best) latest.set(author, best);
2514
2661
  }
2662
+ const cards = [];
2663
+ for (const event of latest.values()) {
2664
+ try {
2665
+ const card = JSON.parse(event.content);
2666
+ cards.push({ pubkey: event.pubkey, createdAt: event.created_at, card });
2667
+ } catch {
2668
+ }
2669
+ }
2670
+ return cards;
2671
+ })();
2672
+ inflight.set(key, task);
2673
+ try {
2674
+ return await task;
2675
+ } finally {
2676
+ if (inflight.get(key) === task) inflight.delete(key);
2515
2677
  }
2516
- return cards;
2517
2678
  }
2518
2679
  };
2519
2680
  };
@@ -2593,6 +2754,7 @@ __export(advanced_exports, {
2593
2754
  corridorRecordStore: () => corridorRecordStore,
2594
2755
  corridorSet: () => corridorSet,
2595
2756
  covclaimdClient: () => covclaimdClient,
2757
+ createNostrTransportFactory: () => createNostrTransportFactory,
2596
2758
  createSwapClient: () => createSwapClient,
2597
2759
  createSwapDrive: () => createSwapDrive,
2598
2760
  decodeBolt11: () => decodeBolt11,
@@ -2780,7 +2942,9 @@ var OnchainSendCorridor = {
2780
2942
  return {
2781
2943
  expectedAmount: send.expectedAmount,
2782
2944
  ...send.funding ? { funding: send.funding } : {},
2783
- ...send.claimTxid ? { claimTxid: send.claimTxid } : {}
2945
+ ...send.claimTxid ? { claimTxid: send.claimTxid } : {},
2946
+ ...send.claimFeeRateSatVb === void 0 ? {} : { claimFeeRateSatVb: send.claimFeeRateSatVb },
2947
+ ...send.claimBroadcastAt === void 0 ? {} : { claimBroadcastAt: send.claimBroadcastAt }
2784
2948
  };
2785
2949
  },
2786
2950
  hydrate(profile) {
@@ -2825,7 +2989,9 @@ var OnchainSendCorridor = {
2825
2989
  // record would strand the refund it is still owed.
2826
2990
  ...profile.payoutPkScript ? { payoutPkScript: import_base5.hex.decode(profile.payoutPkScript) } : {},
2827
2991
  ...profile.funding ? { funding: profile.funding } : {},
2828
- ...profile.claimTxid ? { claimTxid: profile.claimTxid } : {}
2992
+ ...profile.claimTxid ? { claimTxid: profile.claimTxid } : {},
2993
+ ...typeof profile.claimFeeRateSatVb === "number" ? { claimFeeRateSatVb: profile.claimFeeRateSatVb } : {},
2994
+ ...typeof profile.claimBroadcastAt === "number" ? { claimBroadcastAt: profile.claimBroadcastAt } : {}
2829
2995
  };
2830
2996
  },
2831
2997
  // The trader claims the L1 HTLC with P, so this leg's preimage material is
@@ -4613,6 +4779,19 @@ var candidateWitnessItems = (tx, inputIndex) => [
4613
4779
  ...(0, import_sdk14.getArkPsbtFields)(tx, inputIndex, import_sdk14.ConditionWitness).flat(),
4614
4780
  ...tx.getInput(inputIndex).finalScriptWitness ?? []
4615
4781
  ];
4782
+ var spendsRefundLeaf = (tx, inputIndex) => {
4783
+ const input = tx.getInput(inputIndex);
4784
+ const witness = input.finalScriptWitness;
4785
+ const leaves = input.tapLeafScript ?? [];
4786
+ const script = witness && witness.length >= 2 ? witness[witness.length - 2] : leaves.length === 1 ? (0, import_sdk14.scriptFromTapLeafScript)(leaves[0]) : void 0;
4787
+ if (!script) return false;
4788
+ try {
4789
+ const { type } = (0, import_sdk14.decodeTapscript)(script);
4790
+ return type === "multisig" || type === "csv-multisig" || type === "cltv-multisig";
4791
+ } catch {
4792
+ return false;
4793
+ }
4794
+ };
4616
4795
  async function readLockupFate(indexer, input) {
4617
4796
  const { vtxos } = await indexer.getVtxos({ scripts: [import_base10.hex.encode(input.swapPkScript)] });
4618
4797
  const all = vtxos ?? [];
@@ -4626,8 +4805,13 @@ async function readLockupFate(indexer, input) {
4626
4805
  }
4627
4806
  const spentBy = /* @__PURE__ */ new Map();
4628
4807
  let everySpendNamed = true;
4808
+ let sweptLeft = false;
4629
4809
  for (const vtxo of all) {
4630
- if (!(0, import_sdk14.isVtxoSpent)(vtxo)) return { fate: "open" };
4810
+ if (!(0, import_sdk14.isVtxoSpent)(vtxo)) {
4811
+ if (!(input.receiver && vtxo.isSwept)) return { fate: "open" };
4812
+ sweptLeft = true;
4813
+ continue;
4814
+ }
4631
4815
  if (vtxo.spentBy)
4632
4816
  spentBy.set(vtxo.spentBy, {
4633
4817
  checkpointTxid: vtxo.spentBy,
@@ -4637,7 +4821,7 @@ async function readLockupFate(indexer, input) {
4637
4821
  }
4638
4822
  const spends = [...spentBy.values()];
4639
4823
  const { txs } = await indexer.getVirtualTxs([...spentBy.keys()]);
4640
- const observed = /* @__PURE__ */ new Set();
4824
+ const refunded = /* @__PURE__ */ new Set();
4641
4825
  for (const raw of txs) {
4642
4826
  let tx;
4643
4827
  try {
@@ -4645,20 +4829,25 @@ async function readLockupFate(indexer, input) {
4645
4829
  } catch {
4646
4830
  continue;
4647
4831
  }
4648
- if (spentBy.has(tx.id)) observed.add(tx.id);
4832
+ if (!spentBy.has(tx.id)) continue;
4649
4833
  for (let i = 0; i < tx.inputsLength; i++) {
4650
4834
  const spent = tx.getInput(i);
4651
4835
  if (!spent.txid) continue;
4652
4836
  const txid = import_base10.hex.encode(spent.txid);
4653
- if (!all.some((vtxo) => vtxo.txid === txid && vtxo.vout === spent.index)) continue;
4837
+ const vtxo = all.find(
4838
+ (vtxo2) => vtxo2.txid === txid && vtxo2.vout === spent.index && vtxo2.spentBy === tx.id
4839
+ );
4840
+ if (!vtxo) continue;
4654
4841
  for (const candidate of candidateWitnessItems(tx, i)) {
4655
4842
  if (hashesTo(candidate, input.paymentHash)) {
4656
4843
  return { fate: "claimed", preimage: candidate, spends };
4657
4844
  }
4658
4845
  }
4846
+ if (spendsRefundLeaf(tx, i)) refunded.add(`${vtxo.txid}:${vtxo.vout}`);
4659
4847
  }
4660
4848
  }
4661
- return everySpendNamed && observed.size === spentBy.size ? { fate: "returned", spends } : { fate: "unknown" };
4849
+ if (sweptLeft) return { fate: "open" };
4850
+ return everySpendNamed && all.every((vtxo) => refunded.has(`${vtxo.txid}:${vtxo.vout}`)) ? { fate: "returned", spends } : { fate: "unknown" };
4662
4851
  }
4663
4852
  var assertNoneSwept = (vtxos, contract) => {
4664
4853
  const swept = vtxos.filter((vtxo) => vtxo.recoverable);
@@ -4678,6 +4867,8 @@ var operatorUnrollScript = async (operator, network) => {
4678
4867
  })
4679
4868
  );
4680
4869
  };
4870
+ var MAX_LOCKUP_SPEND_INPUTS = 16;
4871
+ var boundedLockupSpend = (vtxos) => [...vtxos].sort((a, b) => b.value - a.value).slice(0, MAX_LOCKUP_SPEND_INPUTS);
4681
4872
  var lockupInputs = (vtxos, contract, leaf) => {
4682
4873
  const tapTree = contract.encode();
4683
4874
  return vtxos.map((vtxo) => ({
@@ -4699,9 +4890,10 @@ async function pushRefundWithoutReceiver(operator, input) {
4699
4890
  }
4700
4891
  const serverUnrollScript = await operatorUnrollScript(operator, input.network);
4701
4892
  const leaf = input.contract.refundWithoutReceiver();
4702
- const amount = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
4893
+ const vtxos = boundedLockupSpend(input.vtxos);
4894
+ const amount = vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
4703
4895
  const { arkTx: tx, checkpoints } = (0, import_sdk14.buildOffchainTx)(
4704
- lockupInputs(input.vtxos, input.contract, leaf),
4896
+ lockupInputs(vtxos, input.contract, leaf),
4705
4897
  [{ script: refundPkScript, amount: BigInt(amount) }],
4706
4898
  serverUnrollScript
4707
4899
  );
@@ -4722,7 +4914,12 @@ async function pushRefundWithoutReceiver(operator, input) {
4722
4914
  )
4723
4915
  );
4724
4916
  await operator.finalizeTx(submitted.arkTxid, finalCheckpoints);
4725
- return { txid: submitted.arkTxid, amount };
4917
+ return {
4918
+ txid: submitted.arkTxid,
4919
+ amount,
4920
+ left: input.vtxos.length - vtxos.length,
4921
+ spent: vtxos
4922
+ };
4726
4923
  }
4727
4924
  var REFUND_MTP_LAG_SECONDS = 2 * 60 * 60;
4728
4925
 
@@ -4835,6 +5032,12 @@ var chainSourceOver = (backend, network) => {
4835
5032
  },
4836
5033
  async getMtp() {
4837
5034
  return (await backend.tip()).mtp;
5035
+ },
5036
+ async getTxStatus(txid) {
5037
+ return (await backend.provider.getTxStatus(txid)).confirmed ? "confirmed" : "unconfirmed";
5038
+ },
5039
+ getFeeRate() {
5040
+ return backend.provider.getFeeRate();
4838
5041
  }
4839
5042
  };
4840
5043
  };
@@ -6047,28 +6250,31 @@ var assertFiniteAmount = (value, reason, label) => {
6047
6250
  };
6048
6251
  async function pushClaim(operator, input) {
6049
6252
  if (input.vtxos.length === 0) throw new Error("nothing to claim: no funded outputs");
6050
- assertNoneSwept(input.vtxos, input.contract);
6051
- const locked = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
6052
- assertFiniteAmount(locked, "lockup_malformed", "the lockup's summed value");
6253
+ const live = input.vtxos.filter((vtxo) => !vtxo.recoverable);
6254
+ if (live.length === 0) assertNoneSwept(input.vtxos, input.contract);
6255
+ const funded = live.reduce((sum, vtxo) => sum + vtxo.value, 0);
6256
+ assertFiniteAmount(funded, "lockup_malformed", "the lockup's summed value");
6053
6257
  if (!input.partiallyClaimed) {
6054
6258
  assertFiniteAmount(input.expectedAmount, "invalid_gate_input", "expectedAmount");
6055
- if (locked < input.expectedAmount) {
6056
- throw new LockupAmountMismatchError(input.expectedAmount, locked);
6259
+ if (funded < input.expectedAmount) {
6260
+ throw new LockupAmountMismatchError(input.expectedAmount, funded);
6057
6261
  }
6058
6262
  }
6263
+ const vtxos = boundedLockupSpend(live);
6264
+ const locked = vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
6059
6265
  assertPreimageMatches(input.preimage, input.contract.options.preimageHash);
6060
6266
  const serverUnrollScript = await operatorUnrollScript(operator, input.network);
6061
6267
  const leaf = input.contract.claim();
6062
6268
  const txid = await (0, import_sdk25.signAndSubmitOffchainTx)({
6063
6269
  identity: (0, import_sdk25.claimWithPreimageIdentity)(input.receiver, input.preimage),
6064
6270
  provider: operator,
6065
- inputs: lockupInputs(input.vtxos, input.contract, leaf),
6271
+ inputs: lockupInputs(vtxos, input.contract, leaf),
6066
6272
  // One aggregate output: this leaf inspects nothing about the output set.
6067
6273
  outputs: [{ script: input.destinationPkScript, amount: BigInt(locked) }],
6068
6274
  serverUnrollScript,
6069
6275
  verifyServerSignatures: { serverPubkey: input.contract.options.server }
6070
6276
  });
6071
- return { txid, amount: locked };
6277
+ return { txid, amount: locked, left: live.length - vtxos.length, spent: vtxos };
6072
6278
  }
6073
6279
 
6074
6280
  // src/client/drive.ts
@@ -6118,6 +6324,8 @@ async function senderIdentityForSwapRecord(wallet, record) {
6118
6324
  // src/arkadeRefunder.ts
6119
6325
  init_rfqProfileParts();
6120
6326
  function arkadeRefunder(deps) {
6327
+ const spentBy = /* @__PURE__ */ new Map();
6328
+ const keyOf = (vtxo) => `${vtxo.txid}:${vtxo.vout}`;
6121
6329
  return async (swap) => {
6122
6330
  const contract = swap.lockup?.script;
6123
6331
  if (!contract) {
@@ -6125,7 +6333,10 @@ function arkadeRefunder(deps) {
6125
6333
  `swap ${swap.rfqId} carries no lockup covenant, so its refund cannot be built`
6126
6334
  );
6127
6335
  }
6128
- const vtxos = await findLockupVtxos(deps.contracts, swap.lockupPkScript);
6336
+ const done = spentBy.get(swap.rfqId);
6337
+ const vtxos = (await findLockupVtxos(deps.contracts, swap.lockupPkScript)).filter(
6338
+ (vtxo) => !done?.has(keyOf(vtxo))
6339
+ );
6129
6340
  if (vtxos.length === 0) return null;
6130
6341
  const record = await deps.repository.getRfqSwap(swap.rfqId);
6131
6342
  if (!record) {
@@ -6135,12 +6346,16 @@ function arkadeRefunder(deps) {
6135
6346
  );
6136
6347
  }
6137
6348
  const sender = await senderIdentityForSwapRecord(deps.wallet, rfqSignerOf(record) ?? {});
6138
- return pushRefundWithoutReceiver(deps.operator, {
6349
+ const result = await pushRefundWithoutReceiver(deps.operator, {
6139
6350
  contract,
6140
6351
  sender,
6141
6352
  vtxos,
6142
6353
  network: await deps.network?.()
6143
6354
  });
6355
+ if (result.left > 0 || done) {
6356
+ spentBy.set(swap.rfqId, /* @__PURE__ */ new Set([...done ?? [], ...result.spent.map(keyOf)]));
6357
+ }
6358
+ return result;
6144
6359
  };
6145
6360
  }
6146
6361
 
@@ -6587,7 +6802,7 @@ var RfqSwapManager = class _RfqSwapManager {
6587
6802
  }
6588
6803
  if (!swap) throw new Error(`swap ${rfqId} is not monitored`);
6589
6804
  if (swap.state === "failed") throw new Error(swap.failure ?? `swap ${rfqId} failed`);
6590
- if (isPayoutDecided(swap)) return outcomeOf(swap);
6805
+ if (isPayoutDecided(swap, this.reportsConfirmations)) return outcomeOf(swap);
6591
6806
  return new Promise((resolve, reject) => {
6592
6807
  const set = this.waiters.get(rfqId) ?? /* @__PURE__ */ new Set();
6593
6808
  set.add({ resolve, reject });
@@ -6739,7 +6954,8 @@ var RfqSwapManager = class _RfqSwapManager {
6739
6954
  try {
6740
6955
  fate = await readLockupFate(this.deps.indexer, {
6741
6956
  swapPkScript: swap.lockupPkScript,
6742
- paymentHash: swap.paymentHash
6957
+ paymentHash: swap.paymentHash,
6958
+ receiver: swap.kind === "lightning_receive" || swap.kind === "onchain_receive"
6743
6959
  });
6744
6960
  } catch {
6745
6961
  fate = { fate: "unknown" };
@@ -6748,6 +6964,9 @@ var RfqSwapManager = class _RfqSwapManager {
6748
6964
  if (fate.fate === "claimed" || fate.fate === "returned") {
6749
6965
  this.stampLockupSpends(swap, fate.spends);
6750
6966
  if (fate.fate === "claimed") this.stampSettlementPreimage(swap, fate.preimage);
6967
+ if (swap.kind === "onchain_send" && fate.fate === "claimed" && this.deps.chain) {
6968
+ return this.driveOnchainPayout(swap);
6969
+ }
6751
6970
  this.setState(swap, fate.fate === "claimed" ? "settled" : "refunded");
6752
6971
  return;
6753
6972
  }
@@ -6757,7 +6976,7 @@ var RfqSwapManager = class _RfqSwapManager {
6757
6976
  if (this.config.now() >= swap.refundLocktime) return this.driveReceiveClaim(swap);
6758
6977
  return;
6759
6978
  }
6760
- if (swap.kind === "onchain_send" && swap.state !== "claimed") {
6979
+ if (swap.kind === "onchain_send") {
6761
6980
  if (await this.driveOnchain(swap) === "handled") return;
6762
6981
  }
6763
6982
  if (fate.fate === "exited") {
@@ -6819,7 +7038,8 @@ var RfqSwapManager = class _RfqSwapManager {
6819
7038
  async claimIfFunded(swap, vtxos) {
6820
7039
  if (vtxos.length === 0) return this.unblock(swap);
6821
7040
  const partiallyClaimed = swap.claimTxid !== void 0;
6822
- if (partiallyClaimed && !this.hasUnclaimedOutpoint(swap.rfqId, vtxos)) {
7041
+ const toClaim = partiallyClaimed ? this.unclaimed(swap.rfqId, vtxos) : vtxos;
7042
+ if (toClaim.length === 0) {
6823
7043
  return;
6824
7044
  }
6825
7045
  if (!partiallyClaimed) {
@@ -6846,9 +7066,11 @@ var RfqSwapManager = class _RfqSwapManager {
6846
7066
  this.setState(swap, "claimable");
6847
7067
  if (!this.config.enableAutoActions) return;
6848
7068
  try {
6849
- const { txid } = await this.callbacks.claimLockup(swap, vtxos, { partiallyClaimed });
7069
+ const { txid, spent } = await this.callbacks.claimLockup(swap, toClaim, {
7070
+ partiallyClaimed
7071
+ });
6850
7072
  delete swap.claimFailure;
6851
- this.rememberClaimed(swap.rfqId, vtxos);
7073
+ this.rememberClaimed(swap.rfqId, spent ?? toClaim);
6852
7074
  swap.claimTxid = txid;
6853
7075
  this.touch(swap);
6854
7076
  this.setState(swap, "claimed");
@@ -6955,7 +7177,51 @@ var RfqSwapManager = class _RfqSwapManager {
6955
7177
  }
6956
7178
  return { verdict: "live", attempted: true };
6957
7179
  }
6958
- /** `handled` ends the pass; `continue` falls through to the refund gate. */
7180
+ /** The solver has `P` and the lockup; the trader's payout is the L1 claim alone. */
7181
+ async driveOnchainPayout(swap) {
7182
+ const l1 = await this.driveOnchain(swap);
7183
+ if (isRfqSwapTerminal(swap.state)) return;
7184
+ if (l1 === "swept") {
7185
+ return this.fail(
7186
+ swap,
7187
+ new Error(
7188
+ `the solver claimed the Arkade lockup and its L1 refund took the fill \u2014 the claim ${swap.claimTxid ?? ""} was replaced before it confirmed`
7189
+ )
7190
+ );
7191
+ }
7192
+ const confirmed = await this.readClaimConfirmed(swap);
7193
+ if (this.reportsConfirmations ? confirmed !== true : confirmed === false) return;
7194
+ this.setState(swap, "settled");
7195
+ }
7196
+ get reportsConfirmations() {
7197
+ return this.deps.chain?.getTxStatus !== void 0;
7198
+ }
7199
+ async claimVanished(txid) {
7200
+ const chain = this.deps.chain;
7201
+ if (!chain?.getTxStatus) return false;
7202
+ try {
7203
+ return await chain.getTxStatus(txid) === "missing";
7204
+ } catch {
7205
+ return true;
7206
+ }
7207
+ }
7208
+ /** Stamped on the swap for {@link isPayoutDecided}; `undefined` when it cannot be read. */
7209
+ async readClaimConfirmed(swap) {
7210
+ const chain = this.deps.chain;
7211
+ if (!chain?.getTxStatus || !swap.claimTxid) return void 0;
7212
+ let confirmed;
7213
+ try {
7214
+ confirmed = await chain.getTxStatus(swap.claimTxid) === "confirmed";
7215
+ } catch {
7216
+ confirmed = false;
7217
+ }
7218
+ if (confirmed !== swap.claimConfirmed) {
7219
+ swap.claimConfirmed = confirmed;
7220
+ this.touch(swap);
7221
+ }
7222
+ return confirmed;
7223
+ }
7224
+ /** `handled` ends the pass; `continue` and `swept` fall through to the refund gate. */
6959
7225
  async driveOnchain(swap) {
6960
7226
  if (!this.deps.chain) {
6961
7227
  this.fail(
@@ -6976,17 +7242,27 @@ var RfqSwapManager = class _RfqSwapManager {
6976
7242
  } catch {
6977
7243
  return "continue";
6978
7244
  }
6979
- if ("utxo" in phase && !swap.funding) {
6980
- swap.funding = { txid: phase.utxo.txid, vout: phase.utxo.vout };
7245
+ if ("utxo" in phase && swap.funding?.amount === void 0) {
7246
+ swap.funding = {
7247
+ txid: phase.utxo.txid,
7248
+ vout: phase.utxo.vout,
7249
+ amount: Number(phase.utxo.amount)
7250
+ };
6981
7251
  this.touch(swap);
6982
7252
  }
7253
+ if (swap.claimTxid && (phase.phase === "claimable" || phase.phase === "refundable")) {
7254
+ const due = this.reportsConfirmations && this.config.now() - (swap.claimBroadcastAt ?? 0) >= ONCHAIN_CLAIM_BUMP_SECONDS;
7255
+ if (due || await this.claimVanished(swap.claimTxid)) {
7256
+ await this.pushOnchainClaim(swap, phase.utxo, due);
7257
+ }
7258
+ return "continue";
7259
+ }
6983
7260
  const action = nextOnchainAction({
6984
7261
  phase,
6985
7262
  htlcLocktime: swap.htlc.refundLocktime,
6986
7263
  now: this.config.now()
6987
7264
  });
6988
7265
  if (action === "claim" && phase.phase === "claimable") {
6989
- if (swap.claimTxid) return "continue";
6990
7266
  if (!Number.isSafeInteger(swap.expectedAmount) || swap.expectedAmount <= 0) {
6991
7267
  this.block(
6992
7268
  swap,
@@ -7007,26 +7283,55 @@ var RfqSwapManager = class _RfqSwapManager {
7007
7283
  return "handled";
7008
7284
  }
7009
7285
  this.setOnchainState(swap, "claimable");
7010
- if (!this.config.enableAutoActions || !this.callbacks?.claimOnchain) return "handled";
7011
- try {
7012
- const { txid } = await this.callbacks.claimOnchain(swap, phase.utxo);
7013
- swap.claimTxid = txid;
7014
- this.setOnchainState(swap, "claimed");
7015
- this.emitAction(swap, "claimOnchain");
7016
- } catch (error) {
7017
- this.emitFailed(swap, error);
7018
- }
7019
- return "handled";
7286
+ return this.pushOnchainClaim(swap, phase.utxo, false);
7020
7287
  }
7021
7288
  if (action === "claimed" && phase.phase === "claimed") {
7022
- if (!swap.claimTxid) {
7289
+ if (swap.claimTxid !== phase.txid) {
7023
7290
  swap.claimTxid = phase.txid;
7024
7291
  this.touch(swap);
7025
7292
  }
7026
7293
  this.setOnchainState(swap, "claimed");
7294
+ await this.bumpOnchainClaim(swap);
7295
+ return "continue";
7027
7296
  }
7297
+ if (phase.phase === "swept") return "swept";
7028
7298
  return "continue";
7029
7299
  }
7300
+ /** Build and broadcast a claim. The bump clock restarts on every broadcast, same-txid
7301
+ * re-publications included, or a claim at the dust ceiling would go out every pass. */
7302
+ async pushOnchainClaim(swap, utxo, bump) {
7303
+ if (!this.config.enableAutoActions || !this.callbacks?.claimOnchain) return "handled";
7304
+ try {
7305
+ const { txid, feeRateSatVb } = await this.callbacks.claimOnchain(
7306
+ swap,
7307
+ utxo,
7308
+ bump ? { bump } : void 0
7309
+ );
7310
+ swap.claimTxid = txid;
7311
+ swap.claimBroadcastAt = this.config.now();
7312
+ delete swap.claimConfirmed;
7313
+ if (feeRateSatVb !== void 0) swap.claimFeeRateSatVb = feeRateSatVb;
7314
+ this.touch(swap);
7315
+ this.setOnchainState(swap, "claimed");
7316
+ this.emitAction(swap, "claimOnchain");
7317
+ } catch (error) {
7318
+ this.emitFailed(swap, error);
7319
+ }
7320
+ return "handled";
7321
+ }
7322
+ /** Replace a claim that is not confirming, before median-time-past opens the solver's
7323
+ * refund leaf. Needs `getTxStatus`: blind, it would replace claims that already landed. */
7324
+ async bumpOnchainClaim(swap) {
7325
+ if (await this.readClaimConfirmed(swap) !== false) return;
7326
+ const funding = swap.funding;
7327
+ if (funding?.amount === void 0) return;
7328
+ if (this.config.now() - (swap.claimBroadcastAt ?? 0) < ONCHAIN_CLAIM_BUMP_SECONDS) return;
7329
+ await this.pushOnchainClaim(
7330
+ swap,
7331
+ { ...funding, amount: BigInt(funding.amount), confirmations: 0 },
7332
+ true
7333
+ );
7334
+ }
7030
7335
  async driveArkadeRefund(swap) {
7031
7336
  const now = this.config.now();
7032
7337
  const refusal = await this.probeRefusal(swap);
@@ -7052,6 +7357,7 @@ var RfqSwapManager = class _RfqSwapManager {
7052
7357
  if (pushed) {
7053
7358
  swap.refundTxid = pushed.txid;
7054
7359
  this.touch(swap);
7360
+ if (pushed.left) return;
7055
7361
  } else if (now < swap.refundLocktime + REFUND_MTP_LAG_SECONDS) {
7056
7362
  return;
7057
7363
  }
@@ -7062,6 +7368,8 @@ var RfqSwapManager = class _RfqSwapManager {
7062
7368
  this.refundRefused.add(swap.rfqId);
7063
7369
  return this.block(swap, error.message);
7064
7370
  }
7371
+ const ark = (0, import_sdk27.isArkError)(error) ? error : (0, import_sdk27.maybeArkError)(error);
7372
+ if ((0, import_sdk27.isArkError)(ark, import_sdk27.ArkErrorName.VTXO_ALREADY_SPENT)) return;
7065
7373
  this.emitFailed(swap, error);
7066
7374
  if (now >= swap.refundLocktime + REFUND_MTP_LAG_SECONDS) {
7067
7375
  swap.failure = errorMessage(error);
@@ -7069,12 +7377,10 @@ var RfqSwapManager = class _RfqSwapManager {
7069
7377
  }
7070
7378
  }
7071
7379
  }
7072
- /** Whether any output was never handed to the claim callback (the only reason to
7073
- * claim twice). */
7074
- hasUnclaimedOutpoint(rfqId, vtxos) {
7380
+ /** The outputs no claim of ours has taken yet (the only reason to claim twice). */
7381
+ unclaimed(rfqId, vtxos) {
7075
7382
  const claimed = this.claimedOutpoints.get(rfqId);
7076
- if (!claimed) return true;
7077
- return vtxos.some((vtxo) => !claimed.has(outpointKey(vtxo)));
7383
+ return claimed ? vtxos.filter((vtxo) => !claimed.has(outpointKey(vtxo))) : vtxos;
7078
7384
  }
7079
7385
  rememberClaimed(rfqId, vtxos) {
7080
7386
  const claimed = this.claimedOutpoints.get(rfqId) ?? /* @__PURE__ */ new Set();
@@ -7224,7 +7530,7 @@ var RfqSwapManager = class _RfqSwapManager {
7224
7530
  if (swap.state === "failed") {
7225
7531
  const error = new Error(swap.failure ?? `swap ${swap.rfqId} failed`);
7226
7532
  for (const waiter of waiting) waiter.reject(error);
7227
- } else if (isPayoutDecided(swap)) {
7533
+ } else if (isPayoutDecided(swap, this.reportsConfirmations)) {
7228
7534
  const outcome = outcomeOf(swap);
7229
7535
  for (const waiter of waiting) waiter.resolve(outcome);
7230
7536
  } else {
@@ -7234,7 +7540,7 @@ var RfqSwapManager = class _RfqSwapManager {
7234
7540
  }
7235
7541
  };
7236
7542
  var traderClaimTxid = (swap) => swap.kind === "lightning_send" ? void 0 : swap.claimTxid;
7237
- var isPayoutDecided = (swap) => swap.state === "settled" || swap.state === "refunded" || swap.kind === "onchain_send" && swap.claimTxid !== void 0;
7543
+ var isPayoutDecided = (swap, confirmations = false) => swap.state === "settled" || swap.state === "refunded" || swap.kind === "onchain_send" && swap.claimTxid !== void 0 && (confirmations ? swap.claimConfirmed === true : true);
7238
7544
  var outcomeOf = (swap) => {
7239
7545
  const lostReceive = (swap.kind === "lightning_receive" || swap.kind === "onchain_receive") && swap.state === "refunded";
7240
7546
  return {
@@ -7599,8 +7905,15 @@ var createSwapDrive = (config) => {
7599
7905
  touch(swap.rfqId, swap);
7600
7906
  });
7601
7907
  let onchainSeams;
7908
+ const liveFeeRate = async (chain) => {
7909
+ try {
7910
+ return await chain.getFeeRate?.();
7911
+ } catch {
7912
+ return void 0;
7913
+ }
7914
+ };
7602
7915
  const defaultOnchainClaim = (chain, feeRateSatVb) => {
7603
- return async (swap, utxo) => {
7916
+ return async (swap, utxo, options) => {
7604
7917
  const record = await corridorStore().getRfqSwap(swap.rfqId);
7605
7918
  if (!record) {
7606
7919
  throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
@@ -7621,17 +7934,25 @@ var createSwapDrive = (config) => {
7621
7934
  if (!swap.payoutPkScript) {
7622
7935
  throw new Error(`rfq swap ${swap.rfqId} carries no claim payout script`);
7623
7936
  }
7937
+ const rate = nextClaimFeeRate({
7938
+ configuredSatVb: feeRateSatVb,
7939
+ utxoAmount: utxo.amount,
7940
+ estimateSatVb: await liveFeeRate(chain),
7941
+ ...swap.claimFeeRateSatVb === void 0 ? {} : { lastSatVb: swap.claimFeeRateSatVb },
7942
+ ...options?.bump ? { bump: true } : {}
7943
+ });
7624
7944
  const { txid } = await track(
7625
7945
  claimOnchainFill(chain, {
7626
7946
  htlc: swap.htlc,
7627
7947
  utxo,
7628
7948
  preimage,
7629
7949
  payoutPkScript: swap.payoutPkScript,
7630
- feeRateSatVb,
7631
- sign: (sighash) => signer.signMessage(sighash, "schnorr")
7950
+ feeRateSatVb: rate,
7951
+ sign: (sighash) => signer.signMessage(sighash, "schnorr"),
7952
+ ...swap.claimTxid ? { republish: true } : {}
7632
7953
  })
7633
7954
  );
7634
- return { txid };
7955
+ return { txid, feeRateSatVb: rate };
7635
7956
  };
7636
7957
  };
7637
7958
  const defaultOnchainRefund = (chain, feeRateSatVb) => {
@@ -9537,16 +9858,20 @@ var exchange = async (deps, options) => settle(
9537
9858
 
9538
9859
  // src/client/transport.ts
9539
9860
  var attesting = (transport, responder) => Object.assign(transport, { attestedResponder: responder });
9540
- var nostrTransportFactory = async (rendezvous) => {
9541
- const { nostrRfqTransport: nostrRfqTransport2 } = await Promise.resolve().then(() => (init_nostr(), nostr_exports));
9542
- return attesting(
9543
- nostrRfqTransport2({
9544
- relays: [...rendezvous.relays],
9545
- solverPubkey: rendezvous.solverPubkey
9546
- }),
9547
- rendezvous.solverPubkey
9548
- );
9861
+ var createNostrTransportFactory = (pool) => {
9862
+ return async (rendezvous) => {
9863
+ const { nostrRfqTransport: nostrRfqTransport2 } = await Promise.resolve().then(() => (init_nostr(), nostr_exports));
9864
+ return attesting(
9865
+ nostrRfqTransport2({
9866
+ relays: [...rendezvous.relays],
9867
+ solverPubkey: rendezvous.solverPubkey,
9868
+ ...pool === void 0 ? {} : { pool }
9869
+ }),
9870
+ rendezvous.solverPubkey
9871
+ );
9872
+ };
9549
9873
  };
9874
+ var nostrTransportFactory = createNostrTransportFactory();
9550
9875
 
9551
9876
  // src/client/client.ts
9552
9877
  var PREPARATIONS_HELD = 64;
@@ -10370,6 +10695,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
10370
10695
  corridorRecordStore,
10371
10696
  corridorSet,
10372
10697
  covclaimdClient,
10698
+ createNostrTransportFactory,
10373
10699
  createSwapClient,
10374
10700
  createSwapDrive,
10375
10701
  decodeBolt11,