@ninsei-labs/sdk 0.55.4 → 0.57.2

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 (68) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +51 -24
  4. package/THIRD_PARTY_NOTICES.md +174 -0
  5. package/assets/vendors/MANIFEST.json +18 -0
  6. package/assets/vendors/sdk/sdk-browser.js +2059 -2
  7. package/engine/atomic/dleq2.js +187 -22
  8. package/engine/atomic/order.js +21 -3
  9. package/engine/core/config.js +17 -24
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/store.js +25 -4
  12. package/engine/core/swap.js +54 -52
  13. package/engine/evm/asyncRoute.js +1 -1
  14. package/engine/evm/claimGas.js +2 -1
  15. package/engine/evm/escrow.js +13 -8
  16. package/engine/evm/factory.js +24 -26
  17. package/engine/evm/funding.js +8 -3
  18. package/engine/evm/index.js +2 -4
  19. package/engine/evm/session.js +3 -3
  20. package/engine/monero/scan.js +101 -22
  21. package/engine/recovery/restore.js +8 -8
  22. package/engine/sdk/bridge.js +3 -6
  23. package/index.d.ts +57 -27
  24. package/package.json +25 -8
  25. package/src/actions.mjs +52 -9
  26. package/src/adapters/evm-wallet.mjs +24 -5
  27. package/src/adapters/index.d.ts +66 -0
  28. package/src/adapters/index.mjs +0 -6
  29. package/src/codes.mjs +14 -0
  30. package/src/config.mjs +1 -0
  31. package/src/engine.mjs +6 -6
  32. package/src/feeEstimate.mjs +11 -4
  33. package/src/http.mjs +4 -1
  34. package/src/index.mjs +4 -3
  35. package/src/legs/kyber.mjs +23 -0
  36. package/src/lock.mjs +2 -1
  37. package/src/order.mjs +108 -20
  38. package/src/primitives.mjs +4 -5
  39. package/src/probes.mjs +9 -3
  40. package/src/provider/envFile.mjs +11 -1
  41. package/src/public/networks.d.ts +45 -0
  42. package/src/public/networks.mjs +10 -1
  43. package/src/public/order.d.ts +4 -0
  44. package/src/public/recovery.d.ts +40 -54
  45. package/src/public/recovery.mjs +2 -8
  46. package/src/public/xmr.d.ts +14 -3
  47. package/src/public/xmr.mjs +1 -1
  48. package/src/quoteEip712Spec.mjs +9 -1
  49. package/src/quotes.mjs +118 -49
  50. package/src/record.mjs +3 -3
  51. package/src/recovery-key.mjs +161 -237
  52. package/src/relayFeatures.mjs +25 -13
  53. package/src/relayFirmClient.mjs +69 -6
  54. package/src/relayQuote.mjs +87 -10
  55. package/src/relayRequest.mjs +12 -3
  56. package/src/relayView.mjs +3 -3
  57. package/src/swap-flow.mjs +153 -67
  58. package/src/swaps.mjs +346 -174
  59. package/src/sweep-restore.mjs +14 -6
  60. package/src/sweep.mjs +34 -11
  61. package/src/version.mjs +1 -1
  62. package/src/xmr-arrival.mjs +55 -24
  63. package/assets/vendors/atomic/atomic-browser.js +0 -24
  64. package/engine/atomic/order-client.js +0 -56
  65. package/engine/atomic/order-worker.js +0 -156
  66. package/engine/evm/asyncExec.js +0 -577
  67. package/engine/evm/asyncLegs.js +0 -308
  68. package/src/adapters/node-test-evm-wallet.mjs +0 -357
package/src/swaps.mjs CHANGED
@@ -13,7 +13,7 @@ import * as engine from "./engine.mjs";
13
13
  import * as recordModule from "./record.mjs";
14
14
  // The order: our own side is built by the engine's builder, the counterparty's side is verified and accepted, and
15
15
  // the joint address is assembled from the halves. There are no formulas of our own in the core - see order.mjs.
16
- import { buildOwnSideFromHalves, contextOf, halfHex, norm, normalizeCounterpartyView, orderStep } from "./order.mjs";
16
+ import { buildOwnSideFromHalvesKnown, contextOf, halfHex, norm, normalizeCounterpartyView, orderStepChunked } from "./order.mjs";
17
17
  // Locking the funds: sending goes through the already-finished step (`lock.send`), the wallet is an adapter from outside.
18
18
  import * as lock from "./lock.mjs";
19
19
  import * as flow from "./swap-flow.mjs";
@@ -21,7 +21,7 @@ import { fundingReceiptVerdict } from "../engine/evm/funding.js";
21
21
  import { vmOfChain, legFor } from "./legs/index.mjs";
22
22
  // THE VIEW HALVES - from the core's primitives: the sum of two halves is the key the wallet sees incoming payments
23
23
  // with. There is no arithmetic of the core's own here either (see order.mjs) - we use the same halves builder.
24
- import { keccak256, primitives, secp256k1 } from "./primitives.mjs";
24
+ import { primitives } from "./primitives.mjs";
25
25
  import { probeMoneroNode } from "./probes.mjs";
26
26
  // MARKING READY - A FINISHED STEP, NOT A SECOND IMPLEMENTATION OF IT: it requires the order expectations and checks
27
27
  // the slots against the chain BEFORE signing (actions.markReady). The watch must call exactly it, otherwise "we saw
@@ -29,15 +29,15 @@ import { probeMoneroNode } from "./probes.mjs";
29
29
  import { createActions } from "./actions.mjs";
30
30
  // THE ONE RECOVERY KEY (sdk#76): the taker's halves come from it, not from a fresh random pair per swap.
31
31
  import {
32
- commitRecoveryIndex, createRecoveryKeyFile, importRecoveryKey, loadRecoveryKey,
33
- recoveryIndexTaken, recoveryKeyFileName, recoverySaltOf, reserveRecoveryIndex, saveRecoveryKey,
34
- newRecoverySalt, takerHalves, takerHalvesV2,
32
+ createRecoveryKeyFile, importRecoveryKey, loadRecoveryKey,
33
+ recoveryKeyFileName, recoverySaltOf, saveRecoveryKey,
34
+ newRecoverySalt, takerHalvesV2,
35
35
  } from "./recovery-key.mjs";
36
36
  // THE XMR ARRIVAL CHECK ON TWO NODES (issue #85) - IN THE CORE, from the same mirrored rule and block parser.
37
37
  import * as xmrArrival from "./xmr-arrival.mjs";
38
- // THE MAKER'S DECLINE (issue #40): the escrow's `Declined` event and the node's `declined` + `compliance` status
39
- // are TWO independent sources of the same state, and either one is enough. The detectors and the neutral
40
- // vocabulary live in one module, so this file names the state instead of re-reading the two.
38
+ // THE MAKER'S DECLINE (issue #40): the escrow's `Declined` event is the decision. The node's `declined` +
39
+ // `compliance` status is an observation on the wire, not a second source this file trusts; the detectors and the
40
+ // neutral vocabulary live in one module, so this file names the state instead of re-reading either.
41
41
  import { declineOf, logReaderOf, blockBoundaryOf, DECLINED_TOPIC0, DECLINED_TERMINAL, DECLINED_CODE } from "./decline.mjs";
42
42
 
43
43
  // THE ENGINE'S SETTLEMENT KINDS -> THE CONTRACT'S CODES: THE KEY IS THE KIND THE ENGINE REALLY WRITES.
@@ -74,7 +74,13 @@ const TERMINAL = {
74
74
  [DECLINED_TERMINAL]: DECLINED_TERMINAL,
75
75
  };
76
76
 
77
- const num = (v) => { const n = Number(v); return Number.isFinite(n) ? n : null; };
77
+ const num = (v) => {
78
+ // NULL/UNDEFINED/EMPTY IS NOT ZERO. `Number(null)` is 0, which made every unknown amount look measured as empty;
79
+ // a missing number is a missing fact and the state/interface must see null.
80
+ if (v === null || v === undefined || v === "") return null;
81
+ const n = Number(v);
82
+ return Number.isFinite(n) ? n : null;
83
+ };
78
84
 
79
85
  // THE SERVICE'S NAMED STATE FOR FUNDS THAT ARE ON THE ADDRESS BUT BARRED BY THE TRANSACTION'S unlock_time
80
86
  // (app/store.mjs, app/watcher.mjs; the rule itself is app/indexer.mjs, unlockStateOf). "Has the XMR arrived" is
@@ -236,11 +242,16 @@ export function toState(swap) {
236
242
  // WHAT HAS ALREADY MOVED ON THE SWAP - the two signs the removal prompt warns about. Computed HERE from the
237
243
  // record: the screen must not reach into it for them.
238
244
  funds: {
239
- receivedXmr: num(d.xmrAmount && d.xmrAmount.seen) ?? 0,
245
+ // UNKNOWN IS NULL, NOT ZERO. Zero is a measured empty amount; an absent field is a different fact and the
246
+ // interface must be able to show a dash instead of claiming that nothing arrived. The engine's xmrView
247
+ // materialises a zero when it has no session, so the evidence is checked before its `seen`.
248
+ receivedXmr: (swap.xmrSession !== null && swap.xmrSession !== undefined)
249
+ || (swap.xmr && (swap.xmr.received !== undefined || swap.xmr.arrived !== undefined))
250
+ ? num(d.xmrAmount && d.xmrAmount.seen) : null,
240
251
  escrowLocked: !!(swap.escrow && (swap.escrow.fundTx || swap.escrow.secret)),
241
252
  },
242
- pay: { token: swap.payToken || "eth", amount: num(swap.payAmount) ?? 0 },
243
- get: { xmr: num(swap.xmrAmount) ?? 0 },
253
+ pay: { token: swap.payToken || "eth", amount: num(swap.payAmount) },
254
+ get: { xmr: num(swap.xmrAmount) },
244
255
  step: active.code,
245
256
  steps,
246
257
  deadlines: {
@@ -289,12 +300,22 @@ const MIN_PASSPHRASE = 12;
289
300
  // `receiveAddress`.
290
301
  // Exported for the relay/record seam check: the function is the only place that decides which amount reaches
291
302
  // the arrival check, and a unit test of createRecord alone cannot see that decision.
292
- export const recordInputOf = (request) => {
303
+ export const recordInputOf = (request, xmrNetwork = null) => {
293
304
  const quote = request && request.quote && typeof request.quote === "object" ? request.quote : {};
294
305
  const pass = (v) => (v === undefined || v === null || v === "" ? undefined : v);
306
+ const orderAtomic = request && request.order && request.order.xmrAmount !== undefined && request.order.xmrAmount !== null
307
+ ? String(request.order.xmrAmount) : null;
308
+ const quoteAtomic = request && request.orderQuote && request.orderQuote.xmrAmount !== undefined && request.orderQuote.xmrAmount !== null
309
+ ? String(request.orderQuote.xmrAmount) : null;
310
+ if (orderAtomic !== null && quoteAtomic !== null && orderAtomic !== quoteAtomic) {
311
+ throw new SdkError("bad-input", { field: "xmrAmount", why: "order-vs-quote" });
312
+ }
295
313
  return {
296
314
  side: request.side || "buy",
297
315
  network: quote.chain ? quote.chain : undefined,
316
+ // THE RECORD'S MONERO NETWORK COMES FROM THE INSTANCE, NOT THE DEMO CONSTANT. A testnet instance that recorded
317
+ // stagenet made the recovery file and the start-height probe disagree with the node it was configured for.
318
+ moneroNetwork: request.moneroNetwork || xmrNetwork || undefined,
298
319
  payToken: quote.asset ? String(quote.asset).toLowerCase() : undefined,
299
320
  payAmount: quote.amount !== undefined ? quote.amount : undefined,
300
321
  xmrAmount: quote.size !== undefined ? quote.size : undefined,
@@ -302,10 +323,7 @@ export const recordInputOf = (request) => {
302
323
  // order's `xmrAmount` is the exact atomic value the maker will pay, and the arrival check compares that one.
303
324
  // THE SIGNED FIGURE, NEVER A DISPLAY ONE. The firm path puts the quote's signed `xmrAmount` on the order it
304
325
  // returns; a bare `quote.size` is a rounded screen number and must not reach the arrival check.
305
- expectedAtomic: request.order && request.order.xmrAmount !== undefined && request.order.xmrAmount !== null
306
- ? String(request.order.xmrAmount)
307
- : (request.orderQuote && request.orderQuote.xmrAmount !== undefined && request.orderQuote.xmrAmount !== null
308
- ? String(request.orderQuote.xmrAmount) : undefined),
326
+ expectedAtomic: quoteAtomic !== null ? quoteAtomic : (orderAtomic !== null ? orderAtomic : undefined),
309
327
  // THE ORDER-QUOTE ID IS PART OF THE RECORD, NOT A DETAIL OF THE SCREEN (a defect found): our service uses it to
310
328
  // tie the created escrow to the provider node's record, and without it the node cannot take the ETH
311
329
  // (sdk/src/swap-flow.mjs: quoteId: quote.id -> swap.orderQuoteId; markBodyOf reads exactly this field).
@@ -335,13 +353,35 @@ export async function startHeightFromNodes({ nodes = [], network = null, fetchIm
335
353
  try { return await probeMoneroNode({ url, fetchImpl }); }
336
354
  catch { return { ok: false, why: "unreachable" }; }
337
355
  }));
338
- const good = answers.find((answer) => answer.ok === true && (!network || answer.network === network));
339
- if (good) return good.height;
356
+ const good = answers.filter((answer) => answer.ok === true && (!network || answer.network === network));
357
+ if (good.length) {
358
+ // A LAGGING NODE MUST NOT HIDE THE TRANSFER. The scan starts at the OLDEST height any good witness reports, so
359
+ // a node that answers too high cannot move the walk past the arrival. A large spread means the witnesses do not
360
+ // agree on the chain: refuse the measurement instead of choosing one and calling it the chain's height.
361
+ const heights = good.map((answer) => Number(answer.height)).filter((height) => Number.isSafeInteger(height) && height >= 0);
362
+ if (!heights.length) throw new SdkError("xmr-no-nodes", { step: "restore-height", network: network || null, why: "no-height" });
363
+ const low = Math.min(...heights);
364
+ const high = Math.max(...heights);
365
+ if (high - low > 100) throw new SdkError("xmr-no-nodes", { step: "restore-height", network: network || null, why: "disagree", low, high });
366
+ return low;
367
+ }
340
368
  const why = answers.find((answer) => answer.ok === true) ? "network" : (answers[0] && answers[0].why) || "no-node";
341
369
  throw new SdkError("xmr-no-nodes", { step: "restore-height", network: network || null, why });
342
370
  }
343
371
 
344
- export function createSwaps({ preflight, http, createRecord, mode = null, xmrNetwork = null, call = null,
372
+ // THE SELL WAIT MUST OUTLIVE THE READY DEADLINE. The old fixed 20-minute wait equalled the mean time of ten
373
+ // Monero blocks, so about half of honest sales expired before `ready`. A caller may set an explicit timeout;
374
+ // otherwise the configured wait is extended to cover the remaining time to `readyBy` plus one confirmation margin.
375
+ const SELL_WATCH_MARGIN_SEC = 300;
376
+ export function sellWatchTimeoutMs({ configuredMs = 1_200_000, readyBySec = null, nowSec = Math.floor(Date.now() / 1000) } = {}) {
377
+ const configured = Number.isFinite(Number(configuredMs)) && Number(configuredMs) > 0 ? Number(configuredMs) : 1_200_000;
378
+ const readyAt = Number(readyBySec);
379
+ const now = Number(nowSec);
380
+ if (!Number.isSafeInteger(readyAt) || !Number.isSafeInteger(now) || readyAt <= now) return configured;
381
+ return Math.max(configured, (readyAt - now + SELL_WATCH_MARGIN_SEC) * 1000);
382
+ }
383
+
384
+ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNetwork = null, call = null, now = null, evmBlock = null, store = engine.store,
345
385
  // THE PATHS AND LIMITS ARE BROUGHT BY THE CONFIGURATION: the "server" step's paths are named by names (config.route),
346
386
  // and the timeout and rate of the watch polling - in config.limits. Without the configuration the step answers with a
347
387
  // code rather than following invented paths.
@@ -364,6 +404,27 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
364
404
  // substitute your own. Otherwise the lock step could not be checked beyond predicting the address - and "the address
365
405
  // from the receipt" would remain an argument on trust, not a verified property.
366
406
  const reader = typeof call === "function" ? call : engine.evm.readContract;
407
+ // ONE BLOCK FOR THE SELL GATE. A block read is a seam like the contract read: `evmBlock` from the interface
408
+ // wins, then the wallet's own provider. The number pins every escrow read below to the same state; the
409
+ // timestamp is the chain's clock, not the device's.
410
+ const chainSnapshot = async (wallet = null) => {
411
+ let block = null;
412
+ if (typeof evmBlock === "function") {
413
+ block = await evmBlock("latest");
414
+ } else if (wallet && typeof wallet.driver === "function") {
415
+ const provider = wallet.driver();
416
+ if (provider && typeof provider.request === "function") {
417
+ const tag = await provider.request({ method: "eth_blockNumber" });
418
+ if (typeof tag === "string" && /^0x[0-9a-f]+$/i.test(tag)) {
419
+ block = await provider.request({ method: "eth_getBlockByNumber", params: [tag, false] });
420
+ }
421
+ }
422
+ }
423
+ const number = block && Number(block.number);
424
+ const timestamp = block && Number(block.timestamp);
425
+ if (!Number.isSafeInteger(number) || number < 0 || !Number.isFinite(timestamp) || timestamp <= 0) return null;
426
+ return { blockTag: "0x" + number.toString(16), timestamp };
427
+ };
367
428
  // THE SAME RULE FOR THE LOGS: one reader per facade, chosen once.
368
429
  const logReader = logReaderOf(chainLogs);
369
430
  // MARKING READY GOES THROUGH THE SAME READ SEAM as the lock: checking the slots and signing must go one way,
@@ -390,31 +451,62 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
390
451
  fetchImpl: request.fetchImpl || (typeof fetch === "function" ? fetch : null) });
391
452
  }
392
453
  const records = () => {
393
- const state = engine.store.loadState();
454
+ const state = store.loadState();
394
455
  const all = Object.values((state && state.swaps) || {}).filter((s) => s && s.id);
395
456
  return all.sort((a, b) => Number(b.createdAt || 0) - Number(a.createdAt || 0));
396
457
  };
397
458
  // A START THAT ENDED WITH A SENT TRANSACTION AND NO RECEIPT IS RESUMED, NOT RESENT. The transaction hash and the
398
459
  // predicted escrow are kept on the record; a retry of the same quote reads that receipt instead of building a
399
460
  // second side and sending a second deposit.
400
- const pendingFundingOf = (quoteId) => {
461
+ const pendingFundingOf = (quoteId, salt) => {
401
462
  const id = String(quoteId || "");
402
- if (!id) return null;
403
- return records().find((swap) => String(swap.orderQuoteId || "") === id &&
404
- (swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) || null;
463
+ const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
464
+ if (!id && !saltHex) return null;
465
+ return records().find((swap) => {
466
+ if (!(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
467
+ if (id && String(swap.orderQuoteId || "") === id) return true;
468
+ // THE RELAY ANSWER MAY CARRY NO ORDER ID. The salt is the client's own binding to the same escrow: it is
469
+ // written into the terms and the predicted address is derived from it, so it identifies the pending record
470
+ // without inventing an id or asking the factory again.
471
+ const recordedSalt = String((swap.escrow && swap.escrow.salt) || swap.recoverySalt || "").replace(/^0x/i, "").toLowerCase();
472
+ return Boolean(saltHex && recordedSalt === saltHex);
473
+ }) || null;
405
474
  };
406
475
  async function resumePendingFunding(record, request) {
407
476
  const swap = record.swap || record;
408
477
  const escrowRecord = swap.escrow && typeof swap.escrow === "object" ? swap.escrow : {};
409
478
  const txHash = escrowRecord.fundTx || swap.fundTx || null;
410
- if (!txHash) {
479
+ // THE RECEIPT IS A HANDLE, NOT THE ONLY SOURCE OF TRUTH. A Safe over WalletConnect, a sped-up transaction or
480
+ // a provider that lost the receipt can hide a funded escrow; the predicted address is already on the record,
481
+ // so its own status() is asked before the start is left pending forever. A failed read is not "not funded".
482
+ let onChain = null;
483
+ if (escrowRecord.address) {
484
+ try { onChain = await flow.orderStatus(escrowRecord.address, { call: reader }); }
485
+ catch (error) {
486
+ // AN EMPTY status() ANSWER IS A SUCCESSFUL READ OF AN ADDRESS WITH NO CONTRACT, not an unreadable chain.
487
+ // Anything else leaves `onChain` null and the record pending: a failed read must never authorise a resend.
488
+ if (/short .*status\(\)/.test(String((error && error.message) || error))) onChain = { isFunded: false, absent: true };
489
+ else onChain = null;
490
+ }
491
+ }
492
+ // A PROCESS THAT DIED BETWEEN THE PRE-SEND RECORD AND THE WALLET CALL LEFT "not-sent" BEHIND. The chain was
493
+ // read and the escrow is not funded, so no transaction can be in flight: clear the mark and let the caller
494
+ // build the same salt/address again. If the read failed, the record stays pending - never resend blind.
495
+ if (!txHash && onChain && !onChain.isFunded && escrowRecord.fundingReason === "not-sent") {
496
+ delete swap.fundingPending;
497
+ swap.escrow = { ...escrowRecord, fundingPending: false, fundingReason: "send-not-started" };
498
+ try { engine.swap.saveSwap(swap, store); }
499
+ catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
500
+ return null;
501
+ }
502
+ if (!txHash && !(onChain && onChain.isFunded)) {
411
503
  return { id: swap.id || null, escrow: escrowRecord.address || null,
412
504
  address: (record.swapWallet && record.swapWallet.address) || null,
413
505
  step: "funding-pending", txHash: null, reason: "no-transaction-hash", next: "receipt" };
414
506
  }
415
507
  const wallet = request.wallet;
416
508
  let receipt = null;
417
- if (wallet && typeof wallet.receipt === "function") {
509
+ if (txHash && wallet && typeof wallet.receipt === "function") {
418
510
  try { receipt = await wallet.receipt(txHash); } catch { receipt = null; }
419
511
  }
420
512
  const order = request.order && typeof request.order === "object" ? request.order : {};
@@ -423,12 +515,14 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
423
515
  expectedEscrow: escrowRecord.address || null,
424
516
  });
425
517
  if (verdict.status === "reverted") throw new SdkError("contract-reverted", { step: "funding" });
426
- if (verdict.status === "funded") {
427
- swap.escrow = { ...escrowRecord, address: verdict.escrow, fundingPending: false,
518
+ if (verdict.status === "funded" || (onChain && onChain.isFunded)) {
519
+ const escrow = verdict.status === "funded" ? verdict.escrow : escrowRecord.address;
520
+ if (!escrow) throw new SdkError("funding-pending", { reason: "no-escrow-address" });
521
+ swap.escrow = { ...escrowRecord, address: escrow, fundingPending: false,
428
522
  evmBirthBlock: Number(verdict.birthBlock) > 0 ? Number(verdict.birthBlock) : (escrowRecord.evmBirthBlock ?? null) };
429
523
  delete swap.fundingPending;
430
- try { engine.swap.saveSwap(swap); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
431
- return { id: swap.id || null, escrow: verdict.escrow,
524
+ try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
525
+ return { id: swap.id || null, escrow,
432
526
  address: (record.swapWallet && record.swapWallet.address) || null,
433
527
  step: "xmr-incoming", server: null, watch: null, next: "watch" };
434
528
  }
@@ -596,27 +690,37 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
596
690
  // A SELL SENDS XMR ONLY INTO AN ESCROW THE CHAIN ALREADY HOLDS. The relay answer proves the maker signed the
597
691
  // terms; it does not prove that the maker funded them. Read the escrow itself (code, status, slots and
598
692
  // deadlines), compare the slots with the halves this offer verified, and refuse before `send-xmr`.
599
- async function sellEscrowGate(escrow, expect) {
693
+ async function sellEscrowGate(escrow, expect, wallet = null) {
600
694
  if (!escrow || !expect) throw new SdkError("bad-input", { field: "escrow" });
695
+ let snapshot = null;
696
+ try { snapshot = await chainSnapshot(wallet); }
697
+ catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "block-unreadable" }); }
698
+ // Compatibility with a caller that has neither a wallet nor a block seam: the reads still go to `latest`,
699
+ // and the deadline falls back to the documented `now` seam. A live sell carries one of the two.
700
+ const gate = { call: reader, blockTag: snapshot ? snapshot.blockTag : "latest" };
701
+ const chainNow = snapshot ? snapshot.timestamp : Math.floor((typeof now === "function" ? now() : Date.now()) / 1000);
601
702
  let status = null;
602
- try { status = await flow.orderStatus(escrow, { call: reader }); }
703
+ try { status = await flow.orderStatus(escrow, gate); }
603
704
  catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "escrow-unreadable" }); }
604
705
  if (!status || status.isFunded !== true || status.isClaimed === true || status.isRefunded === true) {
605
706
  throw new SdkError("quote-refused", { step: "send-xmr", why: "escrow-not-open" });
606
707
  }
607
708
  let deadlines = null;
608
- try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
709
+ try { deadlines = await flow.orderDeadlines(escrow, gate); }
609
710
  catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "deadline-unreadable" }); }
610
711
  if (Number(deadlines.readyBy) !== Number(expect.readyBy) || Number(deadlines.t1) !== Number(expect.t1)) {
611
712
  throw new SdkError("quote-refused", { step: "send-xmr", why: "terms-mismatch" });
612
713
  }
613
- // Leave time for the XMR to be sent and confirmed before the maker's ready mark closes. The lead is a
614
- // node setting (`limits.sellReadyLeadSec`), not a second protocol constant.
615
- const leadSec = Number(limitOf("sellReadyLeadSec", 600));
616
- if (Math.floor(Date.now() / 1000) + leadSec >= Number(deadlines.readyBy)) {
714
+ // Leave time for the XMR to be sent and confirmed before the maker's ready mark closes. The lead follows the
715
+ // confirmation setting; an explicit `limits.sellReadyLeadSec` can override it for a stand.
716
+ const confirmations = Math.max(1, Number(limitOf("xmrConfirmations", 10)));
717
+ const blockTimeSec = Math.max(1, Number(limitOf("xmrBlockTimeSec", 120)));
718
+ const configuredLead = Number(limitOf("sellReadyLeadSec", 0));
719
+ const leadSec = Number.isFinite(configuredLead) && configuredLead > 0 ? configuredLead : confirmations * blockTimeSec;
720
+ if (chainNow + leadSec >= Number(deadlines.readyBy)) {
617
721
  throw new SdkError("quote-refused", { step: "send-xmr", why: "deadline-too-close" });
618
722
  }
619
- try { await flow.assertOrderSlots(escrow, expect, "send-xmr", { call: reader }); }
723
+ try { await flow.assertOrderSlots(escrow, expect, "send-xmr", gate); }
620
724
  catch (e) {
621
725
  if (e && e.code === "contract-reverted") throw e;
622
726
  throw new SdkError("quote-refused", { step: "send-xmr", why: "slots-unreadable" });
@@ -646,7 +750,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
646
750
  */
647
751
  async progress(id) {
648
752
  if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
649
- const swap = engine.swap.getSwap(id);
753
+ const swap = engine.swap.getSwap(id, store);
650
754
  if (!swap) return null;
651
755
  return {
652
756
  id: String(swap.id || id),
@@ -669,15 +773,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
669
773
  */
670
774
  async confirmReady(id) {
671
775
  if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
672
- return engine.swap.confirmReady(id);
776
+ return engine.swap.confirmReady(id, store);
673
777
  },
674
778
  async refundEth(id, by = "you") {
675
779
  if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
676
- return engine.swap.refundEth(id, by);
780
+ return engine.swap.refundEth(id, by, store);
677
781
  },
678
782
  async sweepNow(id) {
679
783
  if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
680
- return engine.swap.sweepNow(id);
784
+ return engine.swap.sweepNow(id, store);
681
785
  },
682
786
 
683
787
  /**
@@ -688,10 +792,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
688
792
  async setDestination(id, address) {
689
793
  if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
690
794
  if (typeof address !== "string" || !address) throw new SdkError("bad-input", { field: "address" });
691
- const swap = engine.swap.getSwap(id);
795
+ const swap = engine.swap.getSwap(id, store);
692
796
  if (!swap) return null;
693
797
  swap.receiveAddress = address;
694
- return engine.swap.saveSwap(swap);
798
+ return engine.swap.saveSwap(swap, store);
695
799
  },
696
800
 
697
801
  /**
@@ -712,11 +816,11 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
712
816
  async forget(id) {
713
817
  if (typeof id !== "string" || !id) throw new SdkError("bad-input", { field: "id" });
714
818
  let state = null;
715
- try { state = engine.store.loadState(); } catch { throw new SdkError("storage-unavailable", { step: "forget" }); }
819
+ try { state = store.loadState(); } catch { throw new SdkError("storage-unavailable", { step: "forget" }); }
716
820
  const swaps = state && state.swaps;
717
821
  if (!swaps || !swaps[id]) return false;
718
822
  delete swaps[id];
719
- try { engine.store.saveState(state); } catch { throw new SdkError("storage-unavailable", { step: "forget" }); }
823
+ try { store.saveState(state); } catch { throw new SdkError("storage-unavailable", { step: "forget" }); }
720
824
  return true;
721
825
  },
722
826
 
@@ -749,7 +853,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
749
853
  // not look like "the service has no swaps" - the two are different, and only one of them means "synced".
750
854
  const body = answer.body;
751
855
  if (!body || !Array.isArray(body.swaps)) throw new SdkError("server-unavailable", { step: "sync", why: "bad-response" });
752
- const added = engine.swap.addServerSwaps(body.swaps);
856
+ const added = engine.swap.addServerSwaps(body.swaps, store);
753
857
  return { ok: true, added, seen: body.swaps.length };
754
858
  },
755
859
 
@@ -765,9 +869,9 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
765
869
  * uses (xmr-arrival.verifyArrival): two nodes of different operators on one block, and money barred by
766
870
  * unlock_time is not an arrival.
767
871
  *
768
- * ONLY A POSITIVE "NOT ARRIVED" REFUNDS (state `pending` or `one-node`). A failure to check - no reachable
769
- * node, a disagreement, an underpayment, locked money - is NOT "no money": verifyArrival throws its own code
770
- * and NOTHING is signed, so a broken or lagging witness can never look like an empty address.
872
+ * ONLY A POSITIVE "NOT ARRIVED" REFUNDS (`absent: true`, returned only when two operators completed the walk
873
+ * and found no matching transaction). `pending` with a transaction, `one-node`, and every failure to check are NOT
874
+ * "no money": the helper refuses to sign, so a lagging or busy witness can never look like an empty address.
771
875
  *
772
876
  * IT FIRES ONLY WHEN LESS THAN THE CONFIRMATIONS' TIME IS LEFT before `readyBy`
773
877
  * (`minConfirmations * blockTimeSec`, overridable with `leadSec`): refunding earlier would abandon a maker who
@@ -797,12 +901,12 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
797
901
  const spendPub = request.spendPub || e.moneroSpendPub || null;
798
902
  if (!spendPub) throw new SdkError("bad-input", { field: "spendPub" });
799
903
  // THE EXPECTED SUM IN ATOMIC UNITS. Given explicitly, or derived from the record's XMR amount (1 XMR = 10^12).
800
- let expectedAtomic = request.expectedAtomic !== undefined && request.expectedAtomic !== null
904
+ // THE AMOUNT MUST BE THE SIGNED ONE. `swap.xmrAmount` is a display figure; deriving the arrival amount from
905
+ // it would let a rounded number decide whether a payment is short. A record without the signed value is
906
+ // refused instead of guessed.
907
+ const expectedAtomic = request.expectedAtomic !== undefined && request.expectedAtomic !== null
801
908
  ? request.expectedAtomic : (e.expectedAtomic !== undefined && e.expectedAtomic !== null ? e.expectedAtomic : null);
802
- if (expectedAtomic === null && swap && Number.isFinite(Number(swap.xmrAmount))) {
803
- expectedAtomic = BigInt(Math.round(Number(swap.xmrAmount) * 1e12)).toString();
804
- }
805
- if (expectedAtomic === null) throw new SdkError("bad-input", { field: "expectedAtomic" });
909
+ if (expectedAtomic === null) throw new SdkError("bad-input", { field: "expectedAtomic", why: "unsigned-amount" });
806
910
  const readyBy = Number(request.readyBySec !== undefined && request.readyBySec !== null ? request.readyBySec : e.readyBy);
807
911
  if (!Number.isFinite(readyBy) || readyBy <= 0) throw new SdkError("bad-input", { field: "readyBySec" });
808
912
  const minConfirmations = Number.isFinite(Number(request.minConfirmations)) && Number(request.minConfirmations) > 0
@@ -811,6 +915,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
811
915
  ? Number(request.blockTimeSec) : limitOf("xmrBlockTimeSec", 120);
812
916
  const leadSec = Number.isFinite(Number(request.leadSec)) && Number(request.leadSec) >= 0
813
917
  ? Number(request.leadSec) : minConfirmations * blockTimeSec;
918
+ // THE WALK STARTS AT THE SWAP'S BIRTH, NEVER AT GENESIS. A missing height used to become block 0, so a refund
919
+ // check on a real chain would walk every block ever mined. The record carries the measured height; a caller
920
+ // that has neither an explicit height nor a record height is refused rather than given a scan of the whole chain.
921
+ const fromHeight = request.fromHeight !== undefined && request.fromHeight !== null
922
+ ? Number(request.fromHeight)
923
+ : Number(swap && (swap.restoreHeight ?? e.moneroRestoreHeight ?? e.restoreHeight));
924
+ if (!Number.isSafeInteger(fromHeight) || fromHeight <= 0) {
925
+ throw new SdkError("bad-input", { field: "fromHeight", why: "missing" });
926
+ }
814
927
  const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : nowOf();
815
928
  const leftSec = Math.floor(readyBy - nowSec);
816
929
  // PAST `readyBy` THE EARLY WINDOW IS GONE and the claim window is open: refunding is no longer ours to open.
@@ -818,16 +931,31 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
818
931
  // TIME STILL LEFT BEYOND THE RESERVE - the maker has room to deliver; a refund now would abandon a live trade.
819
932
  if (leftSec > leadSec) return { refunded: false, state: "waiting", leftSec, needSec: leadSec, readyBy, nowSec };
820
933
 
821
- const verdict = await verify({
822
- nodes: request.nodes, address, viewSecret, spendPub, expectedAtomic, minConfirmations,
823
- txid: request.txid || null, fromHeight: request.fromHeight === undefined ? null : request.fromHeight,
824
- timeoutMs: request.timeoutMs, nowSec,
825
- });
934
+ let verdict = null;
935
+ try {
936
+ verdict = await verify({
937
+ nodes: request.nodes, address, viewSecret, spendPub, expectedAtomic, minConfirmations,
938
+ txid: request.txid || null, fromHeight,
939
+ timeoutMs: request.timeoutMs, nowSec,
940
+ });
941
+ } catch (error) {
942
+ // A SHORT PAYMENT OR A LOCKED OUTPUT IS NOT AN EMPTY ADDRESS. It is also not a completed arrival: return
943
+ // the named state and sign nothing. The caller can wait for the remainder or the lock to mature.
944
+ if (error && error.code === "xmr-underpaid") {
945
+ return { refunded: false, state: "arrival-underpaid", leftSec, verdict: null, error: error.params || null };
946
+ }
947
+ if (error && error.code === "xmr-locked") {
948
+ return { refunded: false, state: "arrival-locked", leftSec, verdict: null, error: error.params || null };
949
+ }
950
+ throw error;
951
+ }
826
952
  // THE XMR IS THERE - NOTHING IS REFUNDED. This is the decisive condition of the guard: without it the
827
953
  // client would take the ETH back from under a maker who has already sent the XMR.
828
954
  if (verdict.seen) return { refunded: false, state: "arrived", leftSec, verdict };
829
- // NOT ARRIVED (pending / one-node) - the depositor takes the ETH back through the same action seam as the
830
- // screen. A throw from `verify` above never reaches here and signs nothing.
955
+ // A TRANSACTION THAT IS THERE BUT NOT YET SETTLED IS NOT AN EMPTY ADDRESS. `pending` with a txid or height,
956
+ // and `one-node`, mean the money was seen; only the explicit absence marker proves there is nothing to wait
957
+ // for. A throw from `verify` above never reaches here and signs nothing either.
958
+ if (!verdict || verdict.absent !== true) return { refunded: false, state: "arrival-pending", leftSec, verdict };
831
959
  const res = await refund({ escrow, halfLocker, expect: request.expect, onStep: request.onStep }, request.wallet);
832
960
  return { refunded: true, state: "refunded", hash: (res && res.hash) || null, leftSec, verified: verdict };
833
961
  },
@@ -851,21 +979,23 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
851
979
  // A START WITHOUT THE SIGNED XMR AMOUNT IS NOT A START. `quote.size` is a rounded display value and the relay
852
980
  // answer does not carry it; the arrival check needs the exact integer the order quote signed. Refuse here, before
853
981
  // a wallet or a funding send, instead of recording an incomplete swap that later reads "no amount".
854
- if (!recordInputOf(request).expectedAtomic) {
982
+ if (!recordInputOf(request, xmrNetwork).expectedAtomic) {
855
983
  throw new SdkError("bad-input", { field: "expectedAtomic", why: "signed-amount-missing" });
856
984
  }
857
985
 
858
986
  // RESUME BEFORE ANY NEW SIDE OR SEND. The previous start may have sent the deposit and lost the receipt;
859
987
  // reusing its hash is the only way to learn the escrow without a second payment.
860
988
  const quoteForResume = (request.orderQuote && request.orderQuote.id) || (request.quote && request.quote.id) || null;
861
- const pendingRecord = pendingFundingOf(quoteForResume);
862
- if (pendingRecord) return await resumePendingFunding(pendingRecord, request);
863
- // A NEW START USES A PER-ORDER SALT, NOT A RECOVERY INDEX. A v1 index is the same at every factory and on
864
- // every device, so two devices can derive one half. When the caller brings no `recoverySalt`, the order's own
865
- // salt is the client salt; a missing salt is drawn here and written into the order before its context is built.
866
- // An explicit `recoveryIndex` keeps the legacy path for restoring an old order; it is not a new-start default.
867
- const explicitRecoveryIndex = request.recoveryIndex !== undefined && request.recoveryIndex !== null;
868
- if ((request.recoverySalt === undefined || request.recoverySalt === null) && !explicitRecoveryIndex) {
989
+ const saltForResume = request.recoverySalt || (request.order && request.order.salt) ||
990
+ (request.orderQuote && request.orderQuote.salt) || null;
991
+ const pendingRecord = pendingFundingOf(quoteForResume, saltForResume);
992
+ if (pendingRecord) {
993
+ const resumed = await resumePendingFunding(pendingRecord, request);
994
+ if (resumed) return resumed;
995
+ }
996
+ // A NEW START USES A PER-ORDER SALT. When the caller brings no `recoverySalt`, the order's own salt is the
997
+ // client salt; a missing salt is drawn here and written into the order before its context is built.
998
+ if (request.recoverySalt === undefined || request.recoverySalt === null) {
869
999
  if (!request.order || typeof request.order !== "object") throw new SdkError("bad-input", { field: "order" });
870
1000
  if (request.order.salt === undefined || request.order.salt === null || request.order.salt === "") {
871
1001
  request.order = { ...request.order, salt: newRecoverySalt() };
@@ -902,7 +1032,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
902
1032
  let keySide = null;
903
1033
  let derivedViewHalf = null;
904
1034
  const makeRecord = typeof createRecord === "function" ? createRecord
905
- : async (req) => recordModule.createRecord(recordInputOf(req), { order: req.order, side: keySide });
1035
+ : async (req) => recordModule.createRecord(recordInputOf(req, xmrNetwork), { order: req.order, side: keySide, store });
906
1036
  const passphrase = typeof request.passphrase === "string" ? request.passphrase : "";
907
1037
  if (typeof passphrase !== "string") throw new SdkError("bad-input", { field: "passphrase" });
908
1038
  if (passphrase.length > 0 && passphrase.length < MIN_PASSPHRASE) throw new SdkError("bad-input", { field: "passphrase", min: MIN_PASSPHRASE });
@@ -911,12 +1041,11 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
911
1041
  // values: the DLEQ proof would then be bound to nothing.
912
1042
  const orderContext = contextOf(request.order);
913
1043
 
914
- // THE KEY RECORD, THE NUMBER AND THE SIDE. A key is made once and kept through the SDK's store; the
915
- // number is reserved before the order is built, and it is retired only after the order exists on chain.
916
- // No per-swap file is assembled on this path.
1044
+ // THE KEY RECORD AND THE SIDE. A key is made once and kept through the SDK's store; this path uses the
1045
+ // per-order salt, and no per-swap file is assembled here.
917
1046
  let recovery = null;
918
1047
  {
919
- const storage = engine.store.storage();
1048
+ const storage = store.storage();
920
1049
  const supplied = typeof request.recoveryKey === "string"
921
1050
  ? request.recoveryKey
922
1051
  : request.recoveryKey && typeof request.recoveryKey.mnemonic === "string" ? request.recoveryKey.mnemonic : null;
@@ -927,57 +1056,23 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
927
1056
  if (!saved && !supplied) throw new SdkError("bad-input", { field: "recoveryKey" });
928
1057
  const key = saved || importRecoveryKey(supplied);
929
1058
  // THE KEY IS SAVED, BUT NOT YET BACKED UP. `backupConfirmed` is its own fact: a key in storage is not a
930
- // key the person has saved. Saving it here is needed for index reservations; funding waits for the flag.
1059
+ // key the person has saved. Saving it here keeps the key across a refresh; funding waits for the flag.
931
1060
  if (!saved) saveRecoveryKey(storage, { ...key, backupConfirmed: false });
932
1061
  const chainId = request.order.chainId;
933
- const explicit = request.recoveryIndex !== undefined && request.recoveryIndex !== null;
934
- const saltRequested = request.recoverySalt !== undefined && request.recoverySalt !== null;
935
- let derived;
936
- if (saltRequested) {
937
- // THE CLIENT OWNS THE SALT. A maker that chose it could hand the same salt to the same client twice, so
938
- // the caller composes the signed quote with this value and passes it here. The order's own salt must be
939
- // the same bytes; a mismatch means the quote is not the one being started.
940
- if (explicit) throw new SdkError("bad-input", { field: "recoverySalt", why: "with-recovery-index" });
941
- if (typeof request.order.factory !== "string" || !request.order.factory) {
942
- throw new SdkError("bad-input", { field: "order.factory" });
943
- }
944
- let salt;
945
- try { salt = recoverySaltOf(request.recoverySalt); } catch { throw new SdkError("bad-input", { field: "recoverySalt" }); }
946
- let orderSalt;
947
- try { orderSalt = recoverySaltOf(request.order.salt); } catch { throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" }); }
948
- if (salt !== orderSalt) throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" });
949
- derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: request.order.factory, salt });
950
- recovery = { storage, key, salt, derivation: "salt-v2", newKey: !saved || saved.backupConfirmed !== true };
951
- } else {
952
- let index = explicit ? Number(request.recoveryIndex) : reserveRecoveryIndex(storage, { chainId });
953
- if (!Number.isSafeInteger(index) || index < 0) throw new SdkError("bad-input", { field: "recoveryIndex" });
954
- // A BROWSER STORE IS PER DEVICE. The same words opened elsewhere start at the same number, so the factory's own
955
- // log is asked before the number is used; a taken number is retired locally and the next one is reserved.
956
- // Without a log seam the previous behaviour is kept - the caller cannot be asked to invent a chain read.
957
- if (typeof chainLogs === "function" && request.order.factory) {
958
- // THE CHAIN'S BIRTH HEIGHT IS THE DEFAULT START, NOT ZERO. The factory's own log cannot hold an order
959
- // before it existed; asking from zero is tens of log queries per number on a public RPC. An explicit
960
- // `fromBlock` still wins, including the literal zero.
961
- const chain = config && Array.isArray(config.chains)
962
- ? config.chains.find((entry) => Number(entry.chainId) === Number(chainId)) : null;
963
- const deploymentBlock = chain && chain.escrow ? chain.escrow.deploymentBlock : null;
964
- const fromBlock = request.fromBlock !== undefined
965
- ? request.fromBlock
966
- : (Number.isSafeInteger(deploymentBlock) ? deploymentBlock : 0);
967
- let hops = 0;
968
- while (await recoveryIndexTaken({ mnemonic: key.mnemonic, chainId, index, factory: request.order.factory,
969
- evmLogs: chainLogs, fromBlock })) {
970
- if (explicit) throw new SdkError("bad-input", { field: "recoveryIndex", why: "on-chain" });
971
- commitRecoveryIndex(storage, index);
972
- index = reserveRecoveryIndex(storage, { chainId });
973
- hops += 1;
974
- if (!Number.isSafeInteger(index) || index < 0 || hops > 1000) throw new SdkError("bad-input", { field: "recoveryIndex", why: "exhausted" });
975
- }
976
- }
977
- derived = takerHalves({ mnemonic: key.mnemonic, chainId, index });
978
- recovery = { storage, key, index, derivation: "index-v1", newKey: !saved || saved.backupConfirmed !== true };
1062
+ // THE CLIENT OWNS THE SALT. A maker that chose it could hand the same salt to the same client twice, so
1063
+ // the caller composes the signed quote with this value and passes it here. The order's own salt must be
1064
+ // the same bytes; a mismatch means the quote is not the one being started.
1065
+ if (typeof request.order.factory !== "string" || !request.order.factory) {
1066
+ throw new SdkError("bad-input", { field: "order.factory" });
979
1067
  }
980
- keySide = buildOwnSideFromHalves(request.order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf }).side;
1068
+ let salt;
1069
+ try { salt = recoverySaltOf(request.recoverySalt); } catch { throw new SdkError("bad-input", { field: "recoverySalt" }); }
1070
+ let orderSalt;
1071
+ try { orderSalt = recoverySaltOf(request.order.salt); } catch { throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" }); }
1072
+ if (salt !== orderSalt) throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" });
1073
+ const derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: request.order.factory, salt });
1074
+ recovery = { storage, key, salt, derivation: "salt-v2", newKey: !saved || saved.backupConfirmed !== true };
1075
+ keySide = buildOwnSideFromHalvesKnown(request.order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf }).side;
981
1076
  // THE MAKER'S VIEW HALF IS DERIVED FROM THE KEY, NOT CHOSEN BY THE NODE. Without this binding a
982
1077
  // signed quote could carry another view half; the funded address would differ from the one the twelve
983
1078
  // words rebuild, and `sweep.fromOrder` would refuse after the funds were locked.
@@ -1020,7 +1115,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1020
1115
  // go red (and rightly so). There is no second build of the side here.
1021
1116
  let builtSide = null;
1022
1117
  if (!record.swapWallet) {
1023
- const step = orderStep({
1118
+ const step = await orderStepChunked({
1024
1119
  order: request.order, side: made.side || null, counterparty: request.counterparty || null,
1025
1120
  standIn: mode !== "live", network: (record.swap.moneroNetwork || xmrNetwork || null),
1026
1121
  });
@@ -1036,7 +1131,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1036
1131
  moneroNetwork: step.wallet.network, standIn: step.counterparty.standIn,
1037
1132
  providerId: step.counterparty.providerId, orderContext: step.context,
1038
1133
  };
1039
- try { engine.swap.saveSwap(record.swap); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1134
+ try { engine.swap.saveSwap(record.swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1040
1135
  record = { ...record, swapWallet: engine.swap.halvesWalletOf(record.swap) };
1041
1136
  if (!record.swapWallet) throw new SdkError("bad-input", { field: "swapWallet" });
1042
1137
  builtSide = step;
@@ -1049,7 +1144,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1049
1144
  record.swap.restoreHeight = measuredHeight;
1050
1145
  record.restoreHeight = measuredHeight;
1051
1146
  record.swap.escrow = { ...(record.swap.escrow || {}), moneroRestoreHeight: measuredHeight };
1052
- try { engine.swap.saveSwap(record.swap); } catch { throw new SdkError("storage-unavailable", { step: "save-restore-height" }); }
1147
+ try { engine.swap.saveSwap(record.swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-restore-height" }); }
1053
1148
 
1054
1149
  // 2a. THE KEY IS CONFIRMED ONCE. The same twelve words cover every swap, and a person who already saved them
1055
1150
  // is not asked again. A new key is shown before the money moves - no saved key, no funding.
@@ -1064,12 +1159,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1064
1159
  } catch { throw new SdkError("recovery-failed", { step: "encrypt-key" }); }
1065
1160
  const confirmed = await request.onRecoveryKey(file);
1066
1161
  if (confirmed !== true) throw new SdkError("recovery-declined", { key: recovery.key.fingerprint });
1067
- // ONLY THE PERSON'S TRUE ANSWER MAKES THE KEY "BACKED UP". The record already exists for reservations;
1068
- // this flag is what a later start reads. A failed write is a refusal before any funds move.
1162
+ // ONLY THE PERSON'S TRUE ANSWER MAKES THE KEY "BACKED UP". The record already exists; this flag is what a
1163
+ // later start reads. A failed write is a refusal before any funds move.
1069
1164
  try {
1070
- const stored = loadRecoveryKey(recovery.storage) || {};
1071
- saveRecoveryKey(recovery.storage, { ...recovery.key, nextIndex: stored.nextIndex,
1072
- reserved: stored.reserved, retired: stored.retired, backupConfirmed: true });
1165
+ saveRecoveryKey(recovery.storage, { ...recovery.key, backupConfirmed: true });
1073
1166
  recovery.key = { ...recovery.key, backupConfirmed: true };
1074
1167
  } catch { throw new SdkError("storage-unavailable", { step: "save-recovery-key" }); }
1075
1168
  }
@@ -1130,10 +1223,46 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1130
1223
  throw new SdkError("quote-refused", { step: "quote-binding", why: "counterparty-half" });
1131
1224
  }
1132
1225
  }
1226
+ // THE SIGNED QUOTE MUST STILL BE VALID WHEN THE MONEY MOVES. The proof and the record work take seconds; a
1227
+ // quote that expired in that window would reach the wallet and revert at the factory. Check the signed field
1228
+ // immediately before the send, with a small margin for the next block.
1229
+ const validUntil = request.orderQuote && request.orderQuote.validUntil !== undefined
1230
+ ? request.orderQuote.validUntil
1231
+ : undefined;
1232
+ if (validUntil !== undefined && validUntil !== null) {
1233
+ const until = Number(validUntil);
1234
+ // THE CLOCK IS THE SDK'S OWN SEAM, IN MILLISECONDS, LIKE EVERY OTHER NOW IN THE FACADE.
1235
+ const nowMs = typeof now === "function" ? Number(now()) : Date.now();
1236
+ const nowSec = Math.floor(nowMs / 1000);
1237
+ if (!Number.isSafeInteger(until) || !Number.isSafeInteger(nowSec) || until <= nowSec + 30) {
1238
+ throw new SdkError("quote-expired", { validUntil: Number.isFinite(until) ? until : null, now: Number.isFinite(nowSec) ? nowSec : null, marginSec: 30, step: "lock" });
1239
+ }
1240
+ }
1133
1241
  lockRequest.quote = request.orderQuote || null;
1242
+ // THE PENDING RECORD EXISTS BEFORE THE SEND, NOT AFTER THE RECEIPT WAIT. If the receipt arrives late (or the
1243
+ // process dies while waiting), a retry must find the predicted escrow and read it instead of asking for a
1244
+ // second deposit. `fundOrder` calls this after its state guard and immediately before `eth_sendTransaction`.
1245
+ const notePredicted = async ({ escrow: predicted, salt }) => {
1246
+ if (!predicted || !/^0x[0-9a-fA-F]{40}$/.test(String(predicted))) return;
1247
+ const escrowRecord = record.swap.escrow && typeof record.swap.escrow === "object" ? record.swap.escrow : {};
1248
+ record.swap.fundingPending = true;
1249
+ record.swap.escrow = { ...escrowRecord, address: predicted, salt: salt || escrowRecord.salt || null,
1250
+ fundingPending: true, fundingReason: "not-sent" };
1251
+ try { engine.swap.saveSwap(record.swap, store); }
1252
+ catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
1253
+ };
1134
1254
  let funded = null;
1135
- try { funded = await lock.send(lockRequest, wallet, { call: reader }); }
1255
+ try { funded = await lock.send(lockRequest, wallet, { call: reader, onPredicted: notePredicted }); }
1136
1256
  catch (error) {
1257
+ // A REJECTION BEFORE BROADCAST MUST NOT LEAVE THE SWAP STUCK IN funding-pending. The pre-send record exists
1258
+ // for a process that dies while the send is in flight; an explicit wallet refusal is the other case, and the
1259
+ // retry has to be allowed to sign again. A transaction that was already mined is caught by the escrow's own
1260
+ // state guard; one still in the mempool is not, and the resend can revert and cost gas - never a second deposit.
1261
+ if (record.swap.escrow && record.swap.escrow.fundingReason === "not-sent") {
1262
+ delete record.swap.fundingPending;
1263
+ record.swap.escrow = { ...record.swap.escrow, fundingPending: false, fundingReason: "send-rejected" };
1264
+ try { engine.swap.saveSwap(record.swap, store); } catch { /* the pending record stays; never resend blind */ }
1265
+ }
1137
1266
  if (error && typeof error.code === "string") throw error;
1138
1267
  throw new SdkError("server-unavailable", { step: "lock" });
1139
1268
  }
@@ -1150,7 +1279,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1150
1279
  record.swap.escrow = { ...escrowRecord, address: predicted || escrowRecord.address || null,
1151
1280
  fundTx: pendingTx || escrowRecord.fundTx || null, fundingPending: true,
1152
1281
  fundingReason: funded.pendingReason || "no-receipt" };
1153
- try { engine.swap.saveSwap(record.swap); } catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
1282
+ try { engine.swap.saveSwap(record.swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
1154
1283
  return { id: record.swap.id || null, escrow: record.swap.escrow.address || null,
1155
1284
  address: (record.swapWallet && record.swapWallet.address) || null,
1156
1285
  step: "funding-pending", txHash: pendingTx,
@@ -1167,12 +1296,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1167
1296
  // watch and the recovery file take the Monero height measured above. The old name `birthHeight` stays
1168
1297
  // readable on records written before this split.
1169
1298
  evmBirthBlock: Number(funded.birthBlock) > 0 ? Number(funded.birthBlock) : (escrowRecord.evmBirthBlock ?? escrowRecord.birthHeight ?? null) };
1170
- try { engine.swap.saveSwap(record.swap); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
1171
- // THE NUMBER IS SPENT ONLY NOW, WHEN THE ORDER EXISTS ON CHAIN. A failed or abandoned start keeps the
1172
- // reservation, so a retry uses the same number and the later search has no gap.
1173
- if (recovery && recovery.index !== undefined) {
1174
- try { commitRecoveryIndex(recovery.storage, recovery.index); } catch { /* the reservation stays; the key still works */ }
1175
- }
1299
+ try { engine.swap.saveSwap(record.swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
1300
+ // THE SALT IS THE RECOVERY BINDING; there is no index reservation to commit here.
1176
1301
  }
1177
1302
 
1178
1303
  // 5. A BACKEND IS OPTIONAL AND NEVER A DEFAULT. When the caller configured an API base, the swap is recorded
@@ -1259,7 +1384,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1259
1384
  //
1260
1385
  // THE DECLINE IS ASKED WITH TWO INDEPENDENT SOURCES AND EITHER ONE ENDS THE WAIT:
1261
1386
  // * THE CHAIN - the escrow's own `Declined` event, through the same log reader the rest of the core uses;
1262
- // * THE WIRE - the status the service answers with (`declined` with the code `compliance`).
1387
+ // * THE WIRE - the status the service answers with is an observation, not a decision; it never writes the
1388
+ // decline.
1263
1389
  // A CHAIN READ THAT FAILS is neither a decline nor a refusal of the swap: the wait goes on and the wire may
1264
1390
  // still answer. What the chain read did is carried out with the result (`chain.checked` / `chain.error`), so
1265
1391
  // a broken reader is visible instead of silent.
@@ -1267,7 +1393,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1267
1393
  // durable, and the escrow may also arrive in the request. The watch is not a new user of the store - and it
1268
1394
  // must not start failing where it did not before.
1269
1395
  let record = null;
1270
- try { record = engine.swap.getSwap(id); } catch { record = null; }
1396
+ try { record = engine.swap.getSwap(id, store); } catch { record = null; }
1271
1397
  const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
1272
1398
  // FROM THE ESCROW'S BIRTH HEIGHT when the record knows it: the event cannot be older than the funding, and
1273
1399
  // walking the whole chain every tick is a cost with no answer behind it.
@@ -1291,7 +1417,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1291
1417
  const settleDecline = (swap, at) => {
1292
1418
  if (!swap || swap.settlement) return;
1293
1419
  swap.settlement = { kind: DECLINED_TERMINAL, phase: DECLINED_TERMINAL, at };
1294
- try { engine.swap.saveSwap(swap); } catch { throw new SdkError("storage-unavailable", { step: "decline" }); }
1420
+ try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "decline" }); }
1295
1421
  };
1296
1422
  // THE STATE THE WATCH REPORTS FOR A DECLINE: no arrival, the state's own code, the node's own token and
1297
1423
  // WHERE it was seen ("event", "status", or "record" when it was already written down). NO reason, category
@@ -1429,14 +1555,14 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1429
1555
  || !same(existing.escrow && existing.escrow.moneroAddress, offer.jointAddress)) {
1430
1556
  throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
1431
1557
  }
1432
- await sellEscrowGate((existing.escrow && existing.escrow.address) || offer.escrow, existing.expect || null);
1558
+ await sellEscrowGate((existing.escrow && existing.escrow.address) || offer.escrow, existing.expect || null, request.wallet);
1433
1559
  return { id: existing.id, side: "sell", escrow: (existing.escrow && existing.escrow.address) || offer.escrow,
1434
1560
  address: (existing.escrow && existing.escrow.moneroAddress) || offer.jointAddress,
1435
1561
  xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
1436
1562
  claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
1437
1563
  resumed: true, next: "send-xmr" };
1438
1564
  }
1439
- const storage = engine.store.storage();
1565
+ const storage = store.storage();
1440
1566
  const supplied = typeof request.recoveryKey === "string"
1441
1567
  ? request.recoveryKey
1442
1568
  : request.recoveryKey && typeof request.recoveryKey.mnemonic === "string" ? request.recoveryKey.mnemonic : null;
@@ -1445,31 +1571,40 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1445
1571
  if (!saved && !supplied) throw new SdkError("bad-input", { field: "recoveryKey" });
1446
1572
  const key = saved || importRecoveryKey(supplied);
1447
1573
  if (!saved) saveRecoveryKey(storage, { ...key, backupConfirmed: false });
1574
+ // A SELL CARRIES THE SAME KEY AS A BUY, SO IT NEEDS THE SAME BACKUP GATE. The one-time XMR address is the
1575
+ // moment the seller can lose money; handing it out before the twelve words are saved turns a closed tab into
1576
+ // an unrecoverable sale. The buy path already refuses to fund until this flag is true.
1577
+ if (!saved || saved.backupConfirmed !== true) {
1578
+ if (typeof request.onRecoveryKey !== "function") throw new SdkError("bad-input", { field: "onRecoveryKey" });
1579
+ let file = null;
1580
+ try {
1581
+ file = {
1582
+ name: recoveryKeyFileName(key),
1583
+ contents: await createRecoveryKeyFile({ mnemonic: key.mnemonic, createdAt: key.createdAt, passphrase: request.passphrase }),
1584
+ };
1585
+ } catch { throw new SdkError("recovery-failed", { step: "encrypt-key" }); }
1586
+ const confirmed = await request.onRecoveryKey(file);
1587
+ if (confirmed !== true) throw new SdkError("recovery-declined", { key: key.fingerprint });
1588
+ try { saveRecoveryKey(storage, { ...key, backupConfirmed: true }); }
1589
+ catch { throw new SdkError("storage-unavailable", { step: "save-recovery-key" }); }
1590
+ }
1448
1591
  const chainId = Number(order.chainId);
1449
1592
  if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new SdkError("bad-input", { field: "order.chainId" });
1450
1593
  if (!order.factory || order.salt === undefined || order.salt === null) throw new SdkError("bad-input", { field: "order" });
1451
- let derived = null;
1452
- if (offer.recovery && offer.recovery.kind === "index-v1") {
1453
- const index = Number(offer.recovery.index);
1454
- if (!Number.isSafeInteger(index) || index < 0) throw new SdkError("bad-input", { field: "offer.recovery" });
1455
- derived = takerHalves({ mnemonic: key.mnemonic, chainId, index });
1456
- } else {
1457
- let salt = null;
1458
- try { salt = recoverySaltOf(offer.recovery && offer.recovery.salt ? offer.recovery.salt : order.salt); }
1459
- catch { throw new SdkError("bad-input", { field: "offer.recovery" }); }
1460
- derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: order.factory, salt });
1461
- }
1462
- const own = buildOwnSideFromHalves(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
1594
+ let salt = null;
1595
+ try { salt = recoverySaltOf(offer.recovery && offer.recovery.salt ? offer.recovery.salt : order.salt); }
1596
+ catch { throw new SdkError("bad-input", { field: "offer.recovery" }); }
1597
+ const derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: order.factory, salt });
1598
+ const own = buildOwnSideFromHalvesKnown(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
1463
1599
  // THE OFFER MUST NAME THE HALF THIS KEY ACTUALLY PRODUCES. The relay already checked the proof; the record
1464
1600
  // needs the same point and commitment, otherwise a later claim would reveal a half the escrow rejects.
1465
- const ownCommit = (() => {
1466
- try {
1467
- const point = secp256k1.Point.fromHex(own.side.proof.XA);
1468
- return "0x" + Array.from(keccak256(point.toBytes(false).slice(1)), (b) => b.toString(16).padStart(2, "0")).join("");
1469
- } catch { return null; }
1470
- })();
1471
- const low160 = (v) => String(v || "").replace(/^0x/, "").toLowerCase().slice(-40);
1472
- if (!ownCommit || low160(ownCommit) !== low160(quote.commitHalfClaimer)) {
1601
+ // THE COMMITMENT COMES FROM THE HALF, NOT FROM A SECOND PROOF. `buildOwnSideFromHalvesKnown` derives it with
1602
+ // the same builder the contract mirrors; the side carries no proof because the firm answer already did.
1603
+ const ownCommit = own.commitHalf;
1604
+ // THE WHOLE COMMITMENT, NOT ITS LOW 160 BITS. `findSwaps` compares all 32 bytes, so a bid whose high 96 bits
1605
+ // differ would be invisible to a words-only search while `startSell` accepted it.
1606
+ const fullHex = (v) => String(v || "").replace(/^0x/, "").toLowerCase();
1607
+ if (!ownCommit || fullHex(ownCommit) !== fullHex(quote.commitHalfClaimer)) {
1473
1608
  throw new SdkError("quote-refused", { step: "sell-record", why: "commitment" });
1474
1609
  }
1475
1610
  if (String(own.spendPoint).toLowerCase() !== String(quote.edPointClaimer || "").toLowerCase()) {
@@ -1480,12 +1615,13 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1480
1615
  }
1481
1616
  const made = recordModule.createRecord({
1482
1617
  side: "sell", network: String(order.chainId),
1618
+ moneroNetwork: xmrNetwork || undefined,
1483
1619
  payToken: order.asset || quote.asset || undefined,
1484
1620
  payAmount: quote.amount, xmrAmount: Number(quote.xmrAmount) / 1e12,
1485
1621
  orderQuoteId: quoteId || undefined,
1486
1622
  receiveAddress: order.claimer,
1487
1623
  makerId: quote.provider || null,
1488
- }, { order, side: own.side });
1624
+ }, { order, side: own.side, store });
1489
1625
  const swap = made.swap;
1490
1626
  swap.side = "sell";
1491
1627
  swap.order = order;
@@ -1511,8 +1647,16 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1511
1647
  commitHalfLocker: (offer.nodeHalf && offer.nodeHalf.commitHalf) || null,
1512
1648
  orderContext: offer.context || null, xmrAmount: quote.xmrAmount || null,
1513
1649
  };
1514
- await sellEscrowGate(offer.escrow, swap.expect);
1515
- try { engine.swap.saveSwap(swap); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1650
+ // THE RECORD IS NOT A RECEIPT FOR A GATE THAT FAILED. createRecord has already written it, so a refusal
1651
+ // from the escrow/deadline/slot gate must remove it again; otherwise the interface lists send-xmr for an
1652
+ // order the SDK never checked.
1653
+ try {
1654
+ await sellEscrowGate(offer.escrow, swap.expect, request.wallet);
1655
+ } catch (error) {
1656
+ try { engine.swap.forgetSwap(swap.id, store); } catch { /* the gate's refusal is the actionable one */ }
1657
+ throw error;
1658
+ }
1659
+ try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1516
1660
  return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
1517
1661
  xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
1518
1662
  resumed: false, next: "send-xmr" };
@@ -1527,7 +1671,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1527
1671
  const id = String(request.id || "").trim();
1528
1672
  if (!id) throw new SdkError("bad-input", { field: "id" });
1529
1673
  let swap = null;
1530
- try { swap = engine.swap.getSwap(id); } catch { swap = null; }
1674
+ try { swap = engine.swap.getSwap(id, store); } catch { swap = null; }
1531
1675
  if (!swap || swap.side !== "sell") throw new SdkError("bad-input", { field: "id", why: "sell-not-found" });
1532
1676
  const escrow = request.escrow || (swap.escrow && swap.escrow.address) || null;
1533
1677
  const halfClaimer = request.halfClaimer || (swap.escrow && swap.escrow.half) || null;
@@ -1547,10 +1691,29 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1547
1691
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1548
1692
  const escrow = String(request.escrow || "").trim();
1549
1693
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
1550
- const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
1551
- ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
1694
+ // THE WAIT IS BOUNDED BY THE ORDER'S OWN READY DEADLINE, NOT BY A FIXED 20 MINUTES. Ten confirmations
1695
+ // average about twenty minutes, so the old default timed out roughly half of honest sales. A request may
1696
+ // still set an explicit timeout; otherwise the wait covers the remaining time to readyBy plus a margin.
1552
1697
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
1553
1698
  ? Number(request.pollMs) : limitOf("watchPollMs", 6_000);
1699
+ let timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
1700
+ ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
1701
+ if (!(Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0)) {
1702
+ try {
1703
+ const deadlines = await flow.orderDeadlines(escrow, { call: reader });
1704
+ timeoutMs = sellWatchTimeoutMs({ configuredMs: timeoutMs, readyBySec: deadlines.readyBy });
1705
+ } catch { /* no deadline read: keep the configured wait */ }
1706
+ }
1707
+ // THE CLAIM OPENS AT readyBy WITHOUT A MARK. The deadline comes from the escrow once; the clock is the
1708
+ // facade's own millisecond seam, so a simulation and a caller that controls time agree with the rest of
1709
+ // the SDK. A failed deadline read does not invent a claim window.
1710
+ let deadlines = null;
1711
+ try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
1712
+ catch { /* no deadline: the wait keeps its configured timeout and never reports claim-open */ }
1713
+ const nowSec = () => {
1714
+ const at = typeof now === "function" ? Number(now()) : Date.now();
1715
+ return Number.isFinite(at) ? Math.floor(at / 1000) : null;
1716
+ };
1554
1717
  const started = Date.now();
1555
1718
  let lastStatus = null;
1556
1719
  let lastError = null;
@@ -1560,7 +1723,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1560
1723
  if (lastStatus && (lastStatus.isClaimed || lastStatus.isRefunded)) {
1561
1724
  return { escrow, state: lastStatus.isClaimed ? "claimed" : "refunded",
1562
1725
  funded: lastStatus.isFunded, claimed: lastStatus.isClaimed, refunded: lastStatus.isRefunded,
1563
- ready: null, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1726
+ ready: null, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1564
1727
  }
1565
1728
  if (lastStatus && lastStatus.isFunded) {
1566
1729
  let ready = null;
@@ -1571,7 +1734,16 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1571
1734
  } catch (error) { lastError = (error && error.code) || "ready-unread"; }
1572
1735
  if (ready === true) {
1573
1736
  return { escrow, state: "ready", funded: true, claimed: false, refunded: false,
1574
- ready: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1737
+ ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1738
+ }
1739
+ }
1740
+ // AFTER readyBy THE CLAIM IS OPEN EVEN WITHOUT THE NODE'S READY MARK. The order is funded, no terminal
1741
+ // action was seen, and the escrow's own deadline has passed; the seller can claim the ETH now.
1742
+ if (lastStatus && lastStatus.isFunded && deadlines && Number.isSafeInteger(Number(deadlines.readyBy))) {
1743
+ const at = nowSec();
1744
+ if (at !== null && at >= Number(deadlines.readyBy)) {
1745
+ return { escrow, state: "claim-open", funded: true, claimed: false, refunded: false,
1746
+ ready: false, claimOpen: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1575
1747
  }
1576
1748
  }
1577
1749
  if (Date.now() - started >= timeoutMs) {