@ninsei-labs/sdk 0.56.1 → 0.58.0

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 (73) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +78 -28
  4. package/THIRD_PARTY_NOTICES.md +176 -2
  5. package/assets/vendors/MANIFEST.json +1 -13
  6. package/assets/vendors/sdk/sdk-browser.js +5 -4
  7. package/engine/atomic/dleq2.js +116 -15
  8. package/engine/atomic/order.js +21 -3
  9. package/engine/core/config.js +20 -46
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/rfqSource.js +6 -133
  12. package/engine/core/swap.js +8 -8
  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 +11 -6
  17. package/engine/evm/funding.js +8 -3
  18. package/engine/evm/index.js +5 -6
  19. package/engine/evm/session.js +48 -279
  20. package/engine/monero/address.js +15 -33
  21. package/engine/monero/keys.js +124 -0
  22. package/engine/monero/mnemonic.js +104 -0
  23. package/engine/monero/scan.js +121 -28
  24. package/engine/monero/wallet.js +31 -68
  25. package/engine/monero/wordlist.en.js +210 -0
  26. package/engine/recovery/restore.js +9 -9
  27. package/engine/sdk/bridge.js +9 -187
  28. package/engine/ui/walletModal.js +7 -27
  29. package/index.d.ts +234 -262
  30. package/package.json +7 -6
  31. package/src/actions.mjs +8 -5
  32. package/src/codes.mjs +17 -0
  33. package/src/config.mjs +17 -54
  34. package/src/engine.mjs +9 -6
  35. package/src/feeEstimate.mjs +11 -4
  36. package/src/http.mjs +4 -1
  37. package/src/index.mjs +24 -45
  38. package/src/legs/kyber.mjs +23 -0
  39. package/src/lock.mjs +1 -0
  40. package/src/order.mjs +110 -22
  41. package/src/primitives.mjs +4 -5
  42. package/src/probes.mjs +9 -3
  43. package/src/public/networks.d.ts +45 -0
  44. package/src/public/networks.mjs +10 -1
  45. package/src/public/recovery.d.ts +17 -1
  46. package/src/public/recovery.mjs +1 -0
  47. package/src/public/xmr.mjs +1 -1
  48. package/src/quotePolicy.mjs +25 -0
  49. package/src/quotes.mjs +109 -765
  50. package/src/readyWindow.mjs +76 -0
  51. package/src/recovery-key.mjs +71 -16
  52. package/src/recovery.mjs +11 -28
  53. package/src/relayClaim.mjs +132 -0
  54. package/src/relayFeatures.mjs +25 -13
  55. package/src/relayFirmClient.mjs +36 -7
  56. package/src/relayQuote.mjs +92 -11
  57. package/src/relayView.mjs +3 -3
  58. package/src/swap-flow.mjs +146 -60
  59. package/src/swaps.mjs +521 -357
  60. package/src/sweep-action.mjs +73 -0
  61. package/src/sweep-restore.mjs +8 -4
  62. package/src/sweep.mjs +12 -2
  63. package/src/version.mjs +1 -1
  64. package/src/xmr-arrival.mjs +328 -29
  65. package/src/xmrAmountPolicy.mjs +35 -0
  66. package/assets/vendors/atomic/atomic-browser.js +0 -24
  67. package/assets/vendors/monero/monero-js-browser.js +0 -58
  68. package/assets/vendors/monero-js/LICENSE +0 -9
  69. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
  70. package/engine/atomic/order-client.js +0 -56
  71. package/engine/atomic/order-worker.js +0 -156
  72. package/engine/evm/asyncExec.js +0 -577
  73. package/engine/evm/asyncLegs.js +0 -308
package/src/swaps.mjs CHANGED
@@ -5,6 +5,7 @@
5
5
  // order and halves -> server -> watching the Monero address. A lock without a recovery file is a lock with nothing
6
6
  // to open it with if the browser is lost, so the confirmation stands BEFORE anything that locks funds.
7
7
  import { SdkError } from "./errors.mjs";
8
+ import { LOCK_START_MARGIN_SEC } from "./quotePolicy.mjs";
8
9
  import { SDK_VERSION } from "./version.mjs";
9
10
  import * as engine from "./engine.mjs";
10
11
  // The name is NOT `record`: inside start there is a variable with that name, and referencing the module before it
@@ -13,7 +14,7 @@ import * as engine from "./engine.mjs";
13
14
  import * as recordModule from "./record.mjs";
14
15
  // The order: our own side is built by the engine's builder, the counterparty's side is verified and accepted, and
15
16
  // 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";
17
+ import { buildOwnSideFromHalvesKnown, contextOf, halfHex, norm, normalizeCounterpartyView, orderStepChunked } from "./order.mjs";
17
18
  // Locking the funds: sending goes through the already-finished step (`lock.send`), the wallet is an adapter from outside.
18
19
  import * as lock from "./lock.mjs";
19
20
  import * as flow from "./swap-flow.mjs";
@@ -21,7 +22,7 @@ import { fundingReceiptVerdict } from "../engine/evm/funding.js";
21
22
  import { vmOfChain, legFor } from "./legs/index.mjs";
22
23
  // THE VIEW HALVES - from the core's primitives: the sum of two halves is the key the wallet sees incoming payments
23
24
  // 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";
25
+ import { primitives } from "./primitives.mjs";
25
26
  import { probeMoneroNode } from "./probes.mjs";
26
27
  // MARKING READY - A FINISHED STEP, NOT A SECOND IMPLEMENTATION OF IT: it requires the order expectations and checks
27
28
  // the slots against the chain BEFORE signing (actions.markReady). The watch must call exactly it, otherwise "we saw
@@ -35,10 +36,14 @@ import {
35
36
  } from "./recovery-key.mjs";
36
37
  // THE XMR ARRIVAL CHECK ON TWO NODES (issue #85) - IN THE CORE, from the same mirrored rule and block parser.
37
38
  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.
39
+ // THE MAKER'S DECLINE (issue #40): the escrow's `Declined` event is the decision. The node's `declined` +
40
+ // `compliance` status is an observation on the wire, not a second source this file trusts; the detectors and the
41
+ // neutral vocabulary live in one module, so this file names the state instead of re-reading either.
41
42
  import { declineOf, logReaderOf, blockBoundaryOf, DECLINED_TOPIC0, DECLINED_TERMINAL, DECLINED_CODE } from "./decline.mjs";
43
+ import { readReadyWindow, readyLeadSec, readyLateSec, readyWindowMs } from "./readyWindow.mjs";
44
+ // THE NO-WALLET CLAIM: the seller's half goes to the relay that answered the quote, which sends `claim` for the
45
+ // signed tip. This module speaks that one wire; swaps.mjs decides which record may be claimed.
46
+ import { relayOriginOf, addressTextOf, halfTextOf, postRelayClaim } from "./relayClaim.mjs";
42
47
 
43
48
  // THE ENGINE'S SETTLEMENT KINDS -> THE CONTRACT'S CODES: THE KEY IS THE KIND THE ENGINE REALLY WRITES.
44
49
  //
@@ -74,7 +79,13 @@ const TERMINAL = {
74
79
  [DECLINED_TERMINAL]: DECLINED_TERMINAL,
75
80
  };
76
81
 
77
- const num = (v) => { const n = Number(v); return Number.isFinite(n) ? n : null; };
82
+ const num = (v) => {
83
+ // NULL/UNDEFINED/EMPTY IS NOT ZERO. `Number(null)` is 0, which made every unknown amount look measured as empty;
84
+ // a missing number is a missing fact and the state/interface must see null.
85
+ if (v === null || v === undefined || v === "") return null;
86
+ const n = Number(v);
87
+ return Number.isFinite(n) ? n : null;
88
+ };
78
89
 
79
90
  // THE SERVICE'S NAMED STATE FOR FUNDS THAT ARE ON THE ADDRESS BUT BARRED BY THE TRANSACTION'S unlock_time
80
91
  // (app/store.mjs, app/watcher.mjs; the rule itself is app/indexer.mjs, unlockStateOf). "Has the XMR arrived" is
@@ -102,45 +113,6 @@ const LOCKED_STATUS = "xmr_locked";
102
113
  // WHAT IS DELIBERATELY ABSENT HERE: a waiting policy of its own inside the step. How long to wait for the XMR to
103
114
  // arrive is the caller's decision, so the watch is exposed as a separate method (`swaps.watch`) with a timeout from
104
115
  // the configuration.
105
- const MARK_FIELDS = ["id", "network", "escrow", "quoteId", "providerId", "hashlock", "amount", "t0", "t1", "sdkVersion"];
106
- // THE FIELDS OF THE FACTORY WATCH RECORD - the same whitelist as the page client's
107
- // (www/js/core/chainSource.js:33, ALLOWED_SESSION_FIELDS). The body is assembled FROM IT anew, so neither the spend
108
- // half nor the spend key can get into the request, even if someone adds them to the record "just in case".
109
- const ALLOWED_SESSION_FIELDS = ["swapId", "network", "address", "viewKey", "expectedAmountXmr", "restoreHeight", "chain"];
110
-
111
- /**
112
- * The mark body from the swap record. THE FIELDS ARE THE SAME AND WITH THE SAME MEANING as the interface's
113
- * (auth.js:114-125), not a private list: only public data goes out (the escrow address, amounts, deadlines, the
114
- * quote reference), and nothing secret - the spend key never leaves the browser under any configuration.
115
- */
116
- export function markBodyOf(swap, escrow, order = null) {
117
- const e = (swap && swap.escrow) || {};
118
- const o = order && typeof order === "object" ? order : {};
119
- // A BIGINT AS A STRING: the order amount in wei comes both as a string and as a BigInt number (the order terms),
120
- // and the request body is serialized to JSON, where a BigInt does not live at all (a TypeError on the very first
121
- // call). The app expects a string.
122
- const first = (...vals) => {
123
- for (const v of vals) {
124
- if (v === undefined || v === null || v === "") continue;
125
- return typeof v === "bigint" ? v.toString() : v;
126
- }
127
- return null;
128
- };
129
-
130
- return {
131
- id: swap.id || null,
132
- network: swap.network || swap.chain || null,
133
- escrow: escrow || e.address || null,
134
- quoteId: first(swap.orderQuoteId, e.quoteId),
135
- providerId: first(swap.providerId, e.providerId),
136
- hashlock: first(e.hashlock, swap.hashlock),
137
- amount: first(e.amountWei, o.amount, swap.amountWei),
138
- t0: first(e.t0, o.t0),
139
- t1: first(e.t1, o.t1),
140
- sdkVersion: SDK_VERSION,
141
- };
142
- }
143
-
144
116
  /**
145
117
  * THE VIEW KEY OF THE JOINT ADDRESS - THE SUM OF TWO HALVES. That is how the interface assembles it
146
118
  * (www/js/ui/views/confirm.js:559; math - www/js/monero/swapKeys.js, watchViewSeedHex), and only with it does the
@@ -162,32 +134,6 @@ export function jointViewKey(swap) {
162
134
  * field at all, and "the field is absent" and "zero" are different things (zero means "nothing arrived", absence -
163
135
  * "not read"). We return null if this is not a watch response at all - emptiness must not be taken for data.
164
136
  */
165
- export function incomingOf(session) {
166
- if (!session || typeof session !== "object") return null;
167
- const received = Number(session.receivedXmr);
168
- if (!Number.isFinite(received)) return null;
169
- const confirmations = Number(session.confirmations);
170
- // LOCKED FUNDS ARE ON THE ADDRESS BUT ARE NOT AN ARRIVAL THE SWAP CAN USE: the sender set unlock_time, and the
171
- // service names that state. `receivedXmr` counts only what can be spent; the barred sum is `lockedXmr`, and the
172
- // boundary (a height or a date) travels as `lockedUntil` so the interface can say until WHEN.
173
- const locked = session.status === LOCKED_STATUS;
174
- const lockedXmr = num(session.lockedXmr);
175
- return {
176
- id: session.id || null,
177
- address: session.address || null,
178
- status: session.status || null,
179
- expectedXmr: num(session.expectedAmountXmr),
180
- receivedXmr: received,
181
- confirmations: Number.isFinite(confirmations) ? confirmations : 0,
182
- txids: Array.isArray(session.fundingTxids) ? session.fundingTxids : [],
183
- locked,
184
- lockedXmr: lockedXmr === null ? 0 : lockedXmr,
185
- lockedUntil: session.lockedUntil || null,
186
- // AN ARRIVAL IS MONEY AT THE ADDRESS THAT IS NOT BARRED BY unlock_time. Zero, or locked, means none.
187
- seen: received > 0 && !locked,
188
- };
189
- }
190
-
191
137
  /** Translating the engine's record into the contract state: our names, the engine's meaning. */
192
138
  export function toState(swap) {
193
139
  if (!swap || typeof swap !== "object" || !swap.id) throw new SdkError("bad-input", { field: "swap" });
@@ -236,11 +182,16 @@ export function toState(swap) {
236
182
  // WHAT HAS ALREADY MOVED ON THE SWAP - the two signs the removal prompt warns about. Computed HERE from the
237
183
  // record: the screen must not reach into it for them.
238
184
  funds: {
239
- receivedXmr: num(d.xmrAmount && d.xmrAmount.seen) ?? 0,
185
+ // UNKNOWN IS NULL, NOT ZERO. Zero is a measured empty amount; an absent field is a different fact and the
186
+ // interface must be able to show a dash instead of claiming that nothing arrived. The engine's xmrView
187
+ // materialises a zero when it has no session, so the evidence is checked before its `seen`.
188
+ receivedXmr: (swap.xmrSession !== null && swap.xmrSession !== undefined)
189
+ || (swap.xmr && (swap.xmr.received !== undefined || swap.xmr.arrived !== undefined))
190
+ ? num(d.xmrAmount && d.xmrAmount.seen) : null,
240
191
  escrowLocked: !!(swap.escrow && (swap.escrow.fundTx || swap.escrow.secret)),
241
192
  },
242
- pay: { token: swap.payToken || "eth", amount: num(swap.payAmount) ?? 0 },
243
- get: { xmr: num(swap.xmrAmount) ?? 0 },
193
+ pay: { token: swap.payToken || "eth", amount: num(swap.payAmount) },
194
+ get: { xmr: num(swap.xmrAmount) },
244
195
  step: active.code,
245
196
  steps,
246
197
  deadlines: {
@@ -292,6 +243,13 @@ const MIN_PASSPHRASE = 12;
292
243
  export const recordInputOf = (request, xmrNetwork = null) => {
293
244
  const quote = request && request.quote && typeof request.quote === "object" ? request.quote : {};
294
245
  const pass = (v) => (v === undefined || v === null || v === "" ? undefined : v);
246
+ const orderAtomic = request && request.order && request.order.xmrAmount !== undefined && request.order.xmrAmount !== null
247
+ ? String(request.order.xmrAmount) : null;
248
+ const quoteAtomic = request && request.orderQuote && request.orderQuote.xmrAmount !== undefined && request.orderQuote.xmrAmount !== null
249
+ ? String(request.orderQuote.xmrAmount) : null;
250
+ if (orderAtomic !== null && quoteAtomic !== null && orderAtomic !== quoteAtomic) {
251
+ throw new SdkError("bad-input", { field: "xmrAmount", why: "order-vs-quote" });
252
+ }
295
253
  return {
296
254
  side: request.side || "buy",
297
255
  network: quote.chain ? quote.chain : undefined,
@@ -305,13 +263,10 @@ export const recordInputOf = (request, xmrNetwork = null) => {
305
263
  // order's `xmrAmount` is the exact atomic value the maker will pay, and the arrival check compares that one.
306
264
  // THE SIGNED FIGURE, NEVER A DISPLAY ONE. The firm path puts the quote's signed `xmrAmount` on the order it
307
265
  // returns; a bare `quote.size` is a rounded screen number and must not reach the arrival check.
308
- expectedAtomic: request.order && request.order.xmrAmount !== undefined && request.order.xmrAmount !== null
309
- ? String(request.order.xmrAmount)
310
- : (request.orderQuote && request.orderQuote.xmrAmount !== undefined && request.orderQuote.xmrAmount !== null
311
- ? String(request.orderQuote.xmrAmount) : undefined),
266
+ expectedAtomic: quoteAtomic !== null ? quoteAtomic : (orderAtomic !== null ? orderAtomic : undefined),
312
267
  // THE ORDER-QUOTE ID IS PART OF THE RECORD, NOT A DETAIL OF THE SCREEN (a defect found): our service uses it to
313
268
  // tie the created escrow to the provider node's record, and without it the node cannot take the ETH
314
- // (sdk/src/swap-flow.mjs: quoteId: quote.id -> swap.orderQuoteId; markBodyOf reads exactly this field).
269
+ // (sdk/src/swap-flow.mjs: quoteId: quote.id -> swap.orderQuoteId).
315
270
  orderQuoteId: pass(quote.id),
316
271
  // WHERE TO WITHDRAW XMR: part of the record, not a detail of the screen - the progress screen exports the file by it.
317
272
  receiveAddress: pass(request.receiveTo),
@@ -366,15 +321,53 @@ export function sellWatchTimeoutMs({ configuredMs = 1_200_000, readyBySec = null
366
321
  return Math.max(configured, (readyAt - now + SELL_WATCH_MARGIN_SEC) * 1000);
367
322
  }
368
323
 
369
- export function createSwaps({ preflight, http, createRecord, mode = null, xmrNetwork = null, call = null, store = engine.store,
370
- // THE PATHS AND LIMITS ARE BROUGHT BY THE CONFIGURATION: the "server" step's paths are named by names (config.route),
371
- // and the timeout and rate of the watch polling - in config.limits. Without the configuration the step answers with a
372
- // code rather than following invented paths.
324
+ // A PENDING FUNDING IS RESUMED ONLY FOR THE SAME QUOTE, NOT MERELY THE SAME NONCE. The quote id is the maker's
325
+ // nonce; a second offer can reuse it. The salt is the client's own binding to the terms and the predicted escrow,
326
+ // so an id match without the same salt is a different order.
327
+ export function samePendingFunding(swap, quoteId, salt) {
328
+ if (!swap || !(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
329
+ const id = String(quoteId || "");
330
+ const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
331
+ if (!id && !saltHex) return false;
332
+ const recordedId = String(swap.orderQuoteId || "");
333
+ const recordedSalt = String((swap.escrow && swap.escrow.salt) || swap.recoverySalt || "").replace(/^0x/i, "").toLowerCase();
334
+ if (id && recordedId === id) return Boolean(saltHex && recordedSalt === saltHex);
335
+ return Boolean(saltHex && recordedSalt === saltHex);
336
+ }
337
+
338
+ /**
339
+ * WHAT A PENDING RECORD MEANS FOR THIS START.
340
+ * `salt-required` is the expensive branch made loud: a caller that knows only the nonce of a pending record cannot
341
+ * prove it is the same order, and falling through would build a second deposit. The caller must bring the salt (or
342
+ * let the record be resolved by its own salt), not guess.
343
+ */
344
+ export function pendingFundingVerdict(swap, quoteId, salt) {
345
+ const pending = Boolean(swap && (swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true)));
346
+ if (!pending) return "not-pending";
347
+ const id = String(quoteId || "");
348
+ const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
349
+ if (id && String(swap.orderQuoteId || "") === id && !saltHex) return "salt-required";
350
+ return samePendingFunding(swap, id, saltHex) ? "resume" : "different";
351
+ }
352
+
353
+ // THE RECORD OF A SALE, FOUND BY ITS ESCROW. `sellWatch` is called from a reloaded page with the address in hand,
354
+ // so the window stored by `startSell` must be readable without a second argument. A record the store cannot read
355
+ // is not a reason to invent a local window; the caller gets the store's refusal at the point it matters.
356
+ function swapByEscrow(store, escrow) {
357
+ try {
358
+ const state = store.loadState();
359
+ const wanted = String(escrow || "").toLowerCase();
360
+ for (const swap of Object.values((state && state.swaps) || {})) {
361
+ if (swap && swap.escrow && String(swap.escrow.address || "").toLowerCase() === wanted) return swap;
362
+ }
363
+ } catch { /* the caller names the missing window */ }
364
+ return null;
365
+ }
366
+
367
+ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork = null, call = null, now = null, evmBlock = null, store = engine.store,
368
+ // THE MONERO TIMINGS ARE BROUGHT BY THE CONFIGURATION: the watch's rate and timeout live in config.limits. There is
369
+ // no server step and no route table to consult.
373
370
  config = null,
374
- // A SIGN-IN PASS - A SEAM FROM OUTSIDE. Only a wallet can sign the sign-in message, and its role in the core is an
375
- // adapter (send/receipt): windows and message signatures remain the interface's. A READY pass arrives here (as
376
- // www/js/evm/auth.js, signIn obtains it today), and the core merely presents it.
377
- auth = null,
378
371
  // THE INTERFACE'S ADDRESS DENYLIST (issue #16), a Set of lower-cased addresses already assembled by the facade.
379
372
  // The check on the ACTUAL sender is done in start() below, ONE place, right before the send - the wallet adapter
380
373
  // only HANDS OUT the current account (`address()`), it does not carry the policy.
@@ -389,15 +382,32 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
389
382
  // substitute your own. Otherwise the lock step could not be checked beyond predicting the address - and "the address
390
383
  // from the receipt" would remain an argument on trust, not a verified property.
391
384
  const reader = typeof call === "function" ? call : engine.evm.readContract;
385
+ // ONE BLOCK FOR THE SELL GATE. A block read is a seam like the contract read: `evmBlock` from the interface
386
+ // wins, then the wallet's own provider. The number pins every escrow read below to the same state; the
387
+ // timestamp is the chain's clock, not the device's.
388
+ const chainSnapshot = async (wallet = null) => {
389
+ let block = null;
390
+ if (typeof evmBlock === "function") {
391
+ block = await evmBlock("latest");
392
+ } else if (wallet && typeof wallet.driver === "function") {
393
+ const provider = wallet.driver();
394
+ if (provider && typeof provider.request === "function") {
395
+ const tag = await provider.request({ method: "eth_blockNumber" });
396
+ if (typeof tag === "string" && /^0x[0-9a-f]+$/i.test(tag)) {
397
+ block = await provider.request({ method: "eth_getBlockByNumber", params: [tag, false] });
398
+ }
399
+ }
400
+ }
401
+ const number = block && Number(block.number);
402
+ const timestamp = block && Number(block.timestamp);
403
+ if (!Number.isSafeInteger(number) || number < 0 || !Number.isFinite(timestamp) || timestamp <= 0) return null;
404
+ return { blockTag: "0x" + number.toString(16), timestamp };
405
+ };
392
406
  // THE SAME RULE FOR THE LOGS: one reader per facade, chosen once.
393
407
  const logReader = logReaderOf(chainLogs);
394
408
  // MARKING READY GOES THROUGH THE SAME READ SEAM as the lock: checking the slots and signing must go one way,
395
409
  // otherwise part of the check goes past the wallet and part does not (see actions.mjs).
396
410
  const actions = createActions({ call: typeof call === "function" ? call : null });
397
- const routeOf = (name, params) => {
398
- if (!config || typeof config.route !== "function") throw new SdkError("bad-input", { field: "config", step: "server" });
399
- return config.route(name, params);
400
- };
401
411
  const limitOf = (name, fallback) => {
402
412
  const value = config && config.limits ? config.limits[name] : null;
403
413
  return Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
@@ -422,11 +432,18 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
422
432
  // A START THAT ENDED WITH A SENT TRANSACTION AND NO RECEIPT IS RESUMED, NOT RESENT. The transaction hash and the
423
433
  // predicted escrow are kept on the record; a retry of the same quote reads that receipt instead of building a
424
434
  // second side and sending a second deposit.
425
- const pendingFundingOf = (quoteId) => {
435
+ const pendingFundingOf = (quoteId, salt) => {
426
436
  const id = String(quoteId || "");
427
- if (!id) return null;
428
- return records().find((swap) => String(swap.orderQuoteId || "") === id &&
429
- (swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) || null;
437
+ const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
438
+ if (!id && !saltHex) return null;
439
+ for (const swap of records()) {
440
+ const verdict = pendingFundingVerdict(swap, id, saltHex);
441
+ if (verdict === "salt-required") {
442
+ throw new SdkError("bad-input", { field: "recoverySalt", why: "required-for-pending-funding" });
443
+ }
444
+ if (verdict === "resume") return swap;
445
+ }
446
+ return null;
430
447
  };
431
448
  async function resumePendingFunding(record, request) {
432
449
  const swap = record.swap || record;
@@ -437,7 +454,23 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
437
454
  // so its own status() is asked before the start is left pending forever. A failed read is not "not funded".
438
455
  let onChain = null;
439
456
  if (escrowRecord.address) {
440
- try { onChain = await flow.orderStatus(escrowRecord.address, { call: reader }); } catch { onChain = null; }
457
+ try { onChain = await flow.orderStatus(escrowRecord.address, { call: reader }); }
458
+ catch (error) {
459
+ // AN EMPTY status() ANSWER IS A SUCCESSFUL READ OF AN ADDRESS WITH NO CONTRACT, not an unreadable chain.
460
+ // Anything else leaves `onChain` null and the record pending: a failed read must never authorise a resend.
461
+ if (/short .*status\(\)/.test(String((error && error.message) || error))) onChain = { isFunded: false, absent: true };
462
+ else onChain = null;
463
+ }
464
+ }
465
+ // A PROCESS THAT DIED BETWEEN THE PRE-SEND RECORD AND THE WALLET CALL LEFT "not-sent" BEHIND. The chain was
466
+ // read and the escrow is not funded, so no transaction can be in flight: clear the mark and let the caller
467
+ // build the same salt/address again. If the read failed, the record stays pending - never resend blind.
468
+ if (!txHash && onChain && !onChain.isFunded && escrowRecord.fundingReason === "not-sent") {
469
+ delete swap.fundingPending;
470
+ swap.escrow = { ...escrowRecord, fundingPending: false, fundingReason: "send-not-started" };
471
+ try { engine.swap.saveSwap(swap, store); }
472
+ catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
473
+ return null;
441
474
  }
442
475
  if (!txHash && !(onChain && onChain.isFunded)) {
443
476
  return { id: swap.id || null, escrow: escrowRecord.address || null,
@@ -464,7 +497,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
464
497
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
465
498
  return { id: swap.id || null, escrow,
466
499
  address: (record.swapWallet && record.swapWallet.address) || null,
467
- step: "xmr-incoming", server: null, watch: null, next: "watch" };
500
+ step: "xmr-incoming", next: "watch" };
468
501
  }
469
502
  return { id: swap.id || null, escrow: escrowRecord.address || null,
470
503
  address: (record.swapWallet && record.swapWallet.address) || null,
@@ -529,128 +562,40 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
529
562
  return options;
530
563
  }
531
564
 
532
- /**
533
- * RECORDING THE SWAP WITH US. The path and body are the interface's (see the step description above). A refusal is
534
- * called by a CODE and carries the service's response in full: the connection never got through - server-unavailable,
535
- * the service answered and did not accept - server-refused (with the status and ITS reason). The code is named so the
536
- * interface itself decides whether to abort the swap: today it does not abort it (www/js/evm/auth.js:15-16), and that
537
- * is its decision, not the core's silence.
538
- */
539
- async function markOnServer(swap, escrow, order) {
540
- if (!http || typeof http.tryJson !== "function") throw new SdkError("bad-input", { field: "http", step: "mark" });
541
- const mark = markBodyOf(swap, escrow, order);
542
- // THE BROWSER SDK LINE IS PART OF THE BODY. The node's body routes read it before any work; a mark request
543
- // without it is refused as sdk-version-absent even though the swap is already funded.
544
- const body = JSON.stringify(Object.fromEntries(MARK_FIELDS.map((field) => [field, mark[field]])));
545
- const headers = { "content-type": "application/json" };
546
- // THE PASS IS ASKED EVERY TIME, NOT CACHED: it is short-lived (an hour: app/server.mjs, AUTH_TOKEN_TTL_MS), and a
547
- // cached pass would give a 401 at a step that does not move money itself but shows the swap to the service.
548
- if (typeof auth === "function") {
549
- let token = null;
550
- try { token = await auth(); } catch { token = null; }
551
- if (typeof token === "string" && token) headers.authorization = "Bearer " + token;
552
- }
553
- let answer = null;
554
- try { answer = await http.tryJson(routeOf("evmSwaps"), { method: "POST", headers, body }); }
555
- catch (error) { throw new SdkError("server-unavailable", { step: "mark", why: (error && error.code) || "fetch" }); }
556
- if (!answer || answer.ok !== true) {
557
- throw new SdkError("server-refused", {
558
- step: "mark", status: answer ? answer.status : null,
559
- why: (answer && answer.body && (answer.body.error || answer.body.detail)) || null,
560
- });
561
- }
562
- return { marked: true, httpStatus: answer.status, orderBinding: (answer.body && answer.body.orderBinding) || null };
563
- }
564
-
565
- /**
566
- * THE FACTORY WATCH RECORD with our service: by the same POST /api/swaps the page makes
567
- * (www/js/ui/views/confirm.js:581). The address and the VIEW KEY go out - that is enough to see incoming payments,
568
- * and not enough to spend them.
569
- */
570
- async function openWatch(swap, order) {
571
- if (!http || typeof http.tryJson !== "function") throw new SdkError("bad-input", { field: "http", step: "watch" });
572
- const e = (swap && swap.escrow) || {};
573
- const address = e.moneroAddress || (swap.swapWallet && swap.swapWallet.address) || null;
574
- if (!address) throw new SdkError("bad-input", { field: "moneroAddress" });
575
- // THE EXPECTED AMOUNT IS MANDATORY, and this is not a formality: without it the watch cannot check the sufficiency of
576
- // the arrival, and the app does not accept such a record (app/store.mjs:85-94). A refusal is more honest than a
577
- // silent record by which an underpayment would look like a completed swap.
578
- const expectedXmr = num(order && order.xmrAmount !== undefined ? order.xmrAmount : swap.xmrAmount);
579
- if (!(expectedXmr > 0)) throw new SdkError("bad-input", { field: "expectedAmountXmr" });
580
- const network = swap.moneroNetwork || xmrNetwork || null;
581
- if (!network) throw new SdkError("bad-input", { field: "moneroNetwork" });
582
- const restoreHeight = Number(swap.restoreHeight) > 0 ? Number(swap.restoreHeight)
583
- : (Number(e.moneroRestoreHeight) > 0 ? Number(e.moneroRestoreHeight) : null);
584
- if (!(restoreHeight > 0)) throw new SdkError("bad-input", { field: "restoreHeight", step: "watch" });
585
- const wanted = {
586
- swapId: swap.id || null, network, address, viewKey: jointViewKey(swap), expectedAmountXmr: expectedXmr,
587
- // THE RESTORE HEIGHT - THE MONERO HEIGHT, NEVER THE EVM BLOCK. It is measured before the file is handed
588
- // over and kept on the record; `birthHeight`/`evmBirthBlock` is a settlement-chain block for log search and
589
- // is far above any Monero tip, so using it here opened the watch nowhere near the money.
590
- restoreHeight,
591
- chain: swap.network || swap.chain || null,
592
- };
593
- const body = { sdkVersion: SDK_VERSION };
594
- for (const field of ALLOWED_SESSION_FIELDS) if (wanted[field] !== undefined && wanted[field] !== null) body[field] = wanted[field];
595
- // THE VIEW KEY IS NOT NEEDED BY THE SERVICE FOR THE DECISION ANY MORE: since the arrival is checked by the
596
- // client (verifyArrival), the backend may keep a watch only for notifications, and even that it can do from
597
- // the maker's txid. So sending the key is an OPTION: `watch.sendViewKeyToServer === false` drops it from the
598
- // record. The default keeps the current backend flow working until it stops deciding on its own.
599
- if (watchOptions && watchOptions.sendViewKeyToServer === false) delete body.viewKey;
600
- let answer = null;
601
- try { answer = await http.tryJson(routeOf("swaps"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); }
602
- catch (error) { throw new SdkError("server-unavailable", { step: "watch", why: (error && error.code) || "fetch" }); }
603
- if (!answer || answer.ok !== true) {
604
- throw new SdkError("server-refused", {
605
- step: "watch", status: answer ? answer.status : null,
606
- why: (answer && answer.body && (answer.body.error || answer.body.detail)) || null,
607
- });
608
- }
609
- const session = incomingOf(answer.body);
610
- if (!session) throw new SdkError("server-unavailable", { step: "watch", why: "bad-response" });
611
- return { registered: true, httpStatus: answer.status, ...session,
612
- expectedXmr: session.expectedXmr !== null ? session.expectedXmr : expectedXmr };
613
- }
614
-
615
- /** THE WATCH STATE: GET /api/swaps/{id} - the same path as the page's (chainSource.js:184). */
616
- async function readWatch(id) {
617
- if (!http || typeof http.tryJson !== "function") throw new SdkError("bad-input", { field: "http", step: "watch" });
618
- let answer = null;
619
- try { answer = await http.tryJson(routeOf("swap", { id }), { method: "GET" }); }
620
- catch (error) { throw new SdkError("server-unavailable", { step: "watch", why: (error && error.code) || "fetch" }); }
621
- if (!answer || answer.ok !== true) {
622
- throw new SdkError("server-refused", {
623
- step: "watch", status: answer ? answer.status : null, id,
624
- why: (answer && answer.body && (answer.body.error || answer.body.detail)) || null,
625
- });
626
- }
627
- return answer.body;
628
- }
629
-
630
565
  // A SELL SENDS XMR ONLY INTO AN ESCROW THE CHAIN ALREADY HOLDS. The relay answer proves the maker signed the
631
566
  // terms; it does not prove that the maker funded them. Read the escrow itself (code, status, slots and
632
567
  // deadlines), compare the slots with the halves this offer verified, and refuse before `send-xmr`.
633
- async function sellEscrowGate(escrow, expect) {
568
+ async function sellEscrowGate(escrow, expect, wallet = null) {
634
569
  if (!escrow || !expect) throw new SdkError("bad-input", { field: "escrow" });
570
+ let snapshot = null;
571
+ try { snapshot = await chainSnapshot(wallet); }
572
+ catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "block-unreadable" }); }
573
+ // Compatibility with a caller that has neither a wallet nor a block seam: the reads still go to `latest`,
574
+ // and the deadline falls back to the documented `now` seam. A live sell carries one of the two.
575
+ const gate = { call: reader, blockTag: snapshot ? snapshot.blockTag : "latest" };
576
+ const chainNow = snapshot ? snapshot.timestamp : Math.floor((typeof now === "function" ? now() : Date.now()) / 1000);
635
577
  let status = null;
636
- try { status = await flow.orderStatus(escrow, { call: reader }); }
578
+ try { status = await flow.orderStatus(escrow, gate); }
637
579
  catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "escrow-unreadable" }); }
638
580
  if (!status || status.isFunded !== true || status.isClaimed === true || status.isRefunded === true) {
639
581
  throw new SdkError("quote-refused", { step: "send-xmr", why: "escrow-not-open" });
640
582
  }
641
583
  let deadlines = null;
642
- try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
584
+ try { deadlines = await flow.orderDeadlines(escrow, gate); }
643
585
  catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "deadline-unreadable" }); }
644
586
  if (Number(deadlines.readyBy) !== Number(expect.readyBy) || Number(deadlines.t1) !== Number(expect.t1)) {
645
587
  throw new SdkError("quote-refused", { step: "send-xmr", why: "terms-mismatch" });
646
588
  }
647
- // Leave time for the XMR to be sent and confirmed before the maker's ready mark closes. The lead is a
648
- // node setting (`limits.sellReadyLeadSec`), not a second protocol constant.
649
- const leadSec = Number(limitOf("sellReadyLeadSec", 600));
650
- if (Math.floor(Date.now() / 1000) + leadSec >= Number(deadlines.readyBy)) {
589
+ // Leave time for the XMR to be sent and confirmed before the maker's ready mark closes. The lead follows the
590
+ // confirmation setting; an explicit `limits.sellReadyLeadSec` can override it for a stand.
591
+ const confirmations = Math.max(1, Number(limitOf("xmrConfirmations", 10)));
592
+ const blockTimeSec = Math.max(1, Number(limitOf("xmrBlockTimeSec", 120)));
593
+ const configuredLead = Number(limitOf("sellReadyLeadSec", 0));
594
+ const leadSec = Number.isFinite(configuredLead) && configuredLead > 0 ? configuredLead : confirmations * blockTimeSec;
595
+ if (chainNow + leadSec >= Number(deadlines.readyBy)) {
651
596
  throw new SdkError("quote-refused", { step: "send-xmr", why: "deadline-too-close" });
652
597
  }
653
- try { await flow.assertOrderSlots(escrow, expect, "send-xmr", { call: reader }); }
598
+ try { await flow.assertOrderSlots(escrow, expect, "send-xmr", gate); }
654
599
  catch (e) {
655
600
  if (e && e.code === "contract-reverted") throw e;
656
601
  throw new SdkError("quote-refused", { step: "send-xmr", why: "slots-unreadable" });
@@ -754,42 +699,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
754
699
  return true;
755
700
  },
756
701
 
757
- /**
758
- * THE SERVICE'S SWAP LIST, MERGED INTO THE LOCAL ONE. The path and the body are the page's
759
- * (www/js/evm/auth.js, loadServerSwaps: GET /api/evm-swaps, the address ties the list to the wallet). The
760
- * merge rule is the ENGINE'S (core/swap.js, addServerSwaps): a local record always wins, the service only
761
- * adds what this browser does not have, and the rules are not written a second time here. The pass is
762
- * obtained by the interface and only presented by the core (the `auth` seam), so an unauthenticated call is
763
- * the service's own refusal with a code, not a silent empty list.
764
- */
765
- async sync() {
766
- if (!http || typeof http.tryJson !== "function") throw new SdkError("bad-input", { field: "http", step: "sync" });
767
- const headers = {};
768
- if (typeof auth === "function") {
769
- let token = null;
770
- try { token = await auth(); } catch { token = null; }
771
- if (typeof token === "string" && token) headers.authorization = "Bearer " + token;
772
- }
773
- let answer = null;
774
- try { answer = await http.tryJson(routeOf("evmSwaps"), { method: "GET", headers }); }
775
- catch (error) { throw new SdkError("server-unavailable", { step: "sync", why: (error && error.code) || "fetch" }); }
776
- if (!answer || answer.ok !== true) {
777
- throw new SdkError("server-refused", {
778
- step: "sync", status: answer ? answer.status : null,
779
- why: (answer && answer.body && (answer.body.error || answer.body.detail)) || null,
780
- });
781
- }
782
- // A GARBAGE ANSWER IS A REFUSAL, NOT AN EMPTY LIST: a non-JSON body (an SPA fallback, a proxy error page) must
783
- // not look like "the service has no swaps" - the two are different, and only one of them means "synced".
784
- const body = answer.body;
785
- if (!body || !Array.isArray(body.swaps)) throw new SdkError("server-unavailable", { step: "sync", why: "bad-response" });
786
- const added = engine.swap.addServerSwaps(body.swaps, store);
787
- return { ok: true, added, seen: body.swaps.length };
788
- },
789
-
790
702
  // THE ARRIVAL VERDICT WITHOUT THE WATCH LOOP, and the deadline check as a separate call: an interface may
791
703
  // want to run both itself. The watch uses exactly these, so there is one decision, not two.
792
704
  verifyArrival: (request) => xmrArrival.verifyArrival(request),
705
+ /**
706
+ * SHADOW THE FIXED-SLICE WITNESS WITHOUT CHANGING THE DECISION. It runs the exact check and the witness-v1
707
+ * slice check and returns both; `witnessNodes` must carry `{protocol: "witness-v1"}`. Nothing here opens
708
+ * `ready` or refunds. It exists so the protocol can be exercised before an independent operator serves it.
709
+ */
710
+ verifyArrivalShadow: (request) => xmrArrival.verifyArrivalShadow(request),
793
711
  assertTimeForConfirmations: (request) => xmrArrival.assertTimeForConfirmations(request),
794
712
 
795
713
  /**
@@ -799,14 +717,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
799
717
  * uses (xmr-arrival.verifyArrival): two nodes of different operators on one block, and money barred by
800
718
  * unlock_time is not an arrival.
801
719
  *
802
- * ONLY A POSITIVE "NOT ARRIVED" REFUNDS (state `pending` or `one-node`). A failure to check - no reachable
803
- * node, a disagreement, an underpayment, locked money - is NOT "no money": verifyArrival throws its own code
804
- * and NOTHING is signed, so a broken or lagging witness can never look like an empty address.
720
+ * ONLY A POSITIVE "NOT ARRIVED" REFUNDS (`absent: true`, returned only when two operators completed the walk
721
+ * and found no matching transaction). `pending` with a transaction, `one-node`, and every failure to check are NOT
722
+ * "no money": the helper refuses to sign, so a lagging or busy witness can never look like an empty address.
805
723
  *
806
- * IT FIRES ONLY WHEN LESS THAN THE CONFIRMATIONS' TIME IS LEFT before `readyBy`
807
- * (`minConfirmations * blockTimeSec`, overridable with `leadSec`): refunding earlier would abandon a maker who
808
- * still has time to deliver. The refund goes through the same action seam as the screen (actions.refund), and
809
- * the order expectations are mandatory.
724
+ * IT FIRES ONLY WHEN LESS THAN THE NODE'S REFUND LEAD IS LEFT before `readyBy` (`readyLeadSec` of the window
725
+ * stored with the record, overridable with `leadSec`): refunding earlier would abandon a maker who still has
726
+ * time to deliver. The lead is the window's own headroom, not the retired `minConfirmations * blockTimeSec`.
727
+ * The refund goes through the same action seam as the screen (actions.refund), and the order expectations are
728
+ * mandatory.
810
729
  *
811
730
  * The seams `deps.verify` / `deps.refund` / `deps.now` exist for the checks; in production they are the real
812
731
  * arrival check and the real refund.
@@ -831,20 +750,31 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
831
750
  const spendPub = request.spendPub || e.moneroSpendPub || null;
832
751
  if (!spendPub) throw new SdkError("bad-input", { field: "spendPub" });
833
752
  // THE EXPECTED SUM IN ATOMIC UNITS. Given explicitly, or derived from the record's XMR amount (1 XMR = 10^12).
834
- let expectedAtomic = request.expectedAtomic !== undefined && request.expectedAtomic !== null
753
+ // THE AMOUNT MUST BE THE SIGNED ONE. `swap.xmrAmount` is a display figure; deriving the arrival amount from
754
+ // it would let a rounded number decide whether a payment is short. A record without the signed value is
755
+ // refused instead of guessed.
756
+ const expectedAtomic = request.expectedAtomic !== undefined && request.expectedAtomic !== null
835
757
  ? request.expectedAtomic : (e.expectedAtomic !== undefined && e.expectedAtomic !== null ? e.expectedAtomic : null);
836
- if (expectedAtomic === null && swap && Number.isFinite(Number(swap.xmrAmount))) {
837
- expectedAtomic = BigInt(Math.round(Number(swap.xmrAmount) * 1e12)).toString();
838
- }
839
- if (expectedAtomic === null) throw new SdkError("bad-input", { field: "expectedAtomic" });
758
+ if (expectedAtomic === null) throw new SdkError("bad-input", { field: "expectedAtomic", why: "unsigned-amount" });
840
759
  const readyBy = Number(request.readyBySec !== undefined && request.readyBySec !== null ? request.readyBySec : e.readyBy);
841
760
  if (!Number.isFinite(readyBy) || readyBy <= 0) throw new SdkError("bad-input", { field: "readyBySec" });
842
761
  const minConfirmations = Number.isFinite(Number(request.minConfirmations)) && Number(request.minConfirmations) > 0
843
762
  ? Math.trunc(Number(request.minConfirmations)) : limitOf("xmrConfirmations", 10);
844
- const blockTimeSec = Number.isFinite(Number(request.blockTimeSec)) && Number(request.blockTimeSec) > 0
845
- ? Number(request.blockTimeSec) : limitOf("xmrBlockTimeSec", 120);
846
763
  const leadSec = Number.isFinite(Number(request.leadSec)) && Number(request.leadSec) >= 0
847
- ? Number(request.leadSec) : minConfirmations * blockTimeSec;
764
+ ? Number(request.leadSec) : (() => {
765
+ const window = request.readyWindow || (swap && (swap.readyWindow || swap.sellWindow));
766
+ if (!window) throw new SdkError("bad-input", { field: "readyWindow", why: "not-in-record" });
767
+ return readyLeadSec(readReadyWindow(window, { field: "readyWindow" }));
768
+ })();
769
+ // THE WALK STARTS AT THE SWAP'S BIRTH, NEVER AT GENESIS. A missing height used to become block 0, so a refund
770
+ // check on a real chain would walk every block ever mined. The record carries the measured height; a caller
771
+ // that has neither an explicit height nor a record height is refused rather than given a scan of the whole chain.
772
+ const fromHeight = request.fromHeight !== undefined && request.fromHeight !== null
773
+ ? Number(request.fromHeight)
774
+ : Number(swap && (swap.restoreHeight ?? e.moneroRestoreHeight ?? e.restoreHeight));
775
+ if (!Number.isSafeInteger(fromHeight) || fromHeight <= 0) {
776
+ throw new SdkError("bad-input", { field: "fromHeight", why: "missing" });
777
+ }
848
778
  const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : nowOf();
849
779
  const leftSec = Math.floor(readyBy - nowSec);
850
780
  // PAST `readyBy` THE EARLY WINDOW IS GONE and the claim window is open: refunding is no longer ours to open.
@@ -852,16 +782,31 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
852
782
  // TIME STILL LEFT BEYOND THE RESERVE - the maker has room to deliver; a refund now would abandon a live trade.
853
783
  if (leftSec > leadSec) return { refunded: false, state: "waiting", leftSec, needSec: leadSec, readyBy, nowSec };
854
784
 
855
- const verdict = await verify({
856
- nodes: request.nodes, address, viewSecret, spendPub, expectedAtomic, minConfirmations,
857
- txid: request.txid || null, fromHeight: request.fromHeight === undefined ? null : request.fromHeight,
858
- timeoutMs: request.timeoutMs, nowSec,
859
- });
785
+ let verdict = null;
786
+ try {
787
+ verdict = await verify({
788
+ nodes: request.nodes, address, viewSecret, spendPub, expectedAtomic, minConfirmations,
789
+ txid: request.txid || null, fromHeight,
790
+ timeoutMs: request.timeoutMs, nowSec,
791
+ });
792
+ } catch (error) {
793
+ // A SHORT PAYMENT OR A LOCKED OUTPUT IS NOT AN EMPTY ADDRESS. It is also not a completed arrival: return
794
+ // the named state and sign nothing. The caller can wait for the remainder or the lock to mature.
795
+ if (error && error.code === "xmr-underpaid") {
796
+ return { refunded: false, state: "arrival-underpaid", leftSec, verdict: null, error: error.params || null };
797
+ }
798
+ if (error && error.code === "xmr-locked") {
799
+ return { refunded: false, state: "arrival-locked", leftSec, verdict: null, error: error.params || null };
800
+ }
801
+ throw error;
802
+ }
860
803
  // THE XMR IS THERE - NOTHING IS REFUNDED. This is the decisive condition of the guard: without it the
861
804
  // client would take the ETH back from under a maker who has already sent the XMR.
862
805
  if (verdict.seen) return { refunded: false, state: "arrived", leftSec, verdict };
863
- // NOT ARRIVED (pending / one-node) - the depositor takes the ETH back through the same action seam as the
864
- // screen. A throw from `verify` above never reaches here and signs nothing.
806
+ // A TRANSACTION THAT IS THERE BUT NOT YET SETTLED IS NOT AN EMPTY ADDRESS. `pending` with a txid or height,
807
+ // and `one-node`, mean the money was seen; only the explicit absence marker proves there is nothing to wait
808
+ // for. A throw from `verify` above never reaches here and signs nothing either.
809
+ if (!verdict || verdict.absent !== true) return { refunded: false, state: "arrival-pending", leftSec, verdict };
865
810
  const res = await refund({ escrow, halfLocker, expect: request.expect, onStep: request.onStep }, request.wallet);
866
811
  return { refunded: true, state: "refunded", hash: (res && res.hash) || null, leftSec, verified: verdict };
867
812
  },
@@ -892,8 +837,13 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
892
837
  // RESUME BEFORE ANY NEW SIDE OR SEND. The previous start may have sent the deposit and lost the receipt;
893
838
  // reusing its hash is the only way to learn the escrow without a second payment.
894
839
  const quoteForResume = (request.orderQuote && request.orderQuote.id) || (request.quote && request.quote.id) || null;
895
- const pendingRecord = pendingFundingOf(quoteForResume);
896
- if (pendingRecord) return await resumePendingFunding(pendingRecord, request);
840
+ const saltForResume = request.recoverySalt || (request.order && request.order.salt) ||
841
+ (request.orderQuote && request.orderQuote.salt) || null;
842
+ const pendingRecord = pendingFundingOf(quoteForResume, saltForResume);
843
+ if (pendingRecord) {
844
+ const resumed = await resumePendingFunding(pendingRecord, request);
845
+ if (resumed) return resumed;
846
+ }
897
847
  // A NEW START USES A PER-ORDER SALT. When the caller brings no `recoverySalt`, the order's own salt is the
898
848
  // client salt; a missing salt is drawn here and written into the order before its context is built.
899
849
  if (request.recoverySalt === undefined || request.recoverySalt === null) {
@@ -942,9 +892,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
942
892
  // values: the DLEQ proof would then be bound to nothing.
943
893
  const orderContext = contextOf(request.order);
944
894
 
945
- // THE KEY RECORD, THE NUMBER AND THE SIDE. A key is made once and kept through the SDK's store; the
946
- // number is reserved before the order is built, and it is retired only after the order exists on chain.
947
- // No per-swap file is assembled on this path.
895
+ // THE KEY RECORD AND THE SIDE. A key is made once and kept through the SDK's store; this path uses the
896
+ // per-order salt, and no per-swap file is assembled here.
948
897
  let recovery = null;
949
898
  {
950
899
  const storage = store.storage();
@@ -974,7 +923,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
974
923
  if (salt !== orderSalt) throw new SdkError("bad-input", { field: "recoverySalt", why: "order-salt" });
975
924
  const derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: request.order.factory, salt });
976
925
  recovery = { storage, key, salt, derivation: "salt-v2", newKey: !saved || saved.backupConfirmed !== true };
977
- keySide = buildOwnSideFromHalves(request.order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf }).side;
926
+ keySide = buildOwnSideFromHalvesKnown(request.order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf }).side;
978
927
  // THE MAKER'S VIEW HALF IS DERIVED FROM THE KEY, NOT CHOSEN BY THE NODE. Without this binding a
979
928
  // signed quote could carry another view half; the funded address would differ from the one the twelve
980
929
  // words rebuild, and `sweep.fromOrder` would refuse after the funds were locked.
@@ -1012,12 +961,21 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1012
961
  // side comes from outside; in the sandbox the engine builds it as a stand-in, but on a live chain a stand-in would
1013
962
  // mean the money goes against a non-existent side, so there it is a refusal.
1014
963
  let record = made;
964
+ // THE NODE'S WINDOW IS PART OF THE RECORD. It is read from the signed features and later decides how long a
965
+ // sale may wait and when a depositor may still refund; a record without it is refused when that decision is
966
+ // made, never filled with the old local constants.
967
+ const readyWindowRaw = request.readyWindow || (request.quote && request.quote.readyWindow) || null;
968
+ let readyWindow = null;
969
+ if (readyWindowRaw) {
970
+ readyWindow = readReadyWindow(readyWindowRaw, { side: "ask", field: "readyWindow" });
971
+ record.swap.readyWindow = readyWindow;
972
+ }
1015
973
  // THE ORDER SIDE BUILT BY THE CORE STAYS UNTIL THE END OF THE START: the points and commitments for the lock terms
1016
974
  // are taken from it - otherwise the record and the order would diverge, and the slot check against the chain would
1017
975
  // go red (and rightly so). There is no second build of the side here.
1018
976
  let builtSide = null;
1019
977
  if (!record.swapWallet) {
1020
- const step = orderStep({
978
+ const step = await orderStepChunked({
1021
979
  order: request.order, side: made.side || null, counterparty: request.counterparty || null,
1022
980
  standIn: mode !== "live", network: (record.swap.moneroNetwork || xmrNetwork || null),
1023
981
  });
@@ -1125,10 +1083,46 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1125
1083
  throw new SdkError("quote-refused", { step: "quote-binding", why: "counterparty-half" });
1126
1084
  }
1127
1085
  }
1086
+ // THE SIGNED QUOTE MUST STILL BE VALID WHEN THE MONEY MOVES. The proof and the record work take seconds; a
1087
+ // quote that expired in that window would reach the wallet and revert at the factory. Check the signed field
1088
+ // immediately before the send, with a small margin for the next block.
1089
+ const validUntil = request.orderQuote && request.orderQuote.validUntil !== undefined
1090
+ ? request.orderQuote.validUntil
1091
+ : undefined;
1092
+ if (validUntil !== undefined && validUntil !== null) {
1093
+ const until = Number(validUntil);
1094
+ // THE CLOCK IS THE SDK'S OWN SEAM, IN MILLISECONDS, LIKE EVERY OTHER NOW IN THE FACADE.
1095
+ const nowMs = typeof now === "function" ? Number(now()) : Date.now();
1096
+ const nowSec = Math.floor(nowMs / 1000);
1097
+ if (!Number.isSafeInteger(until) || !Number.isSafeInteger(nowSec) || until <= nowSec + LOCK_START_MARGIN_SEC) {
1098
+ throw new SdkError("quote-expired", { validUntil: Number.isFinite(until) ? until : null, now: Number.isFinite(nowSec) ? nowSec : null, marginSec: LOCK_START_MARGIN_SEC, step: "lock" });
1099
+ }
1100
+ }
1128
1101
  lockRequest.quote = request.orderQuote || null;
1102
+ // THE PENDING RECORD EXISTS BEFORE THE SEND, NOT AFTER THE RECEIPT WAIT. If the receipt arrives late (or the
1103
+ // process dies while waiting), a retry must find the predicted escrow and read it instead of asking for a
1104
+ // second deposit. `fundOrder` calls this after its state guard and immediately before `eth_sendTransaction`.
1105
+ const notePredicted = async ({ escrow: predicted, salt }) => {
1106
+ if (!predicted || !/^0x[0-9a-fA-F]{40}$/.test(String(predicted))) return;
1107
+ const escrowRecord = record.swap.escrow && typeof record.swap.escrow === "object" ? record.swap.escrow : {};
1108
+ record.swap.fundingPending = true;
1109
+ record.swap.escrow = { ...escrowRecord, address: predicted, salt: salt || escrowRecord.salt || null,
1110
+ fundingPending: true, fundingReason: "not-sent" };
1111
+ try { engine.swap.saveSwap(record.swap, store); }
1112
+ catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
1113
+ };
1129
1114
  let funded = null;
1130
- try { funded = await lock.send(lockRequest, wallet, { call: reader }); }
1115
+ try { funded = await lock.send(lockRequest, wallet, { call: reader, onPredicted: notePredicted }); }
1131
1116
  catch (error) {
1117
+ // A REJECTION BEFORE BROADCAST MUST NOT LEAVE THE SWAP STUCK IN funding-pending. The pre-send record exists
1118
+ // for a process that dies while the send is in flight; an explicit wallet refusal is the other case, and the
1119
+ // retry has to be allowed to sign again. A transaction that was already mined is caught by the escrow's own
1120
+ // state guard; one still in the mempool is not, and the resend can revert and cost gas - never a second deposit.
1121
+ if (record.swap.escrow && record.swap.escrow.fundingReason === "not-sent") {
1122
+ delete record.swap.fundingPending;
1123
+ record.swap.escrow = { ...record.swap.escrow, fundingPending: false, fundingReason: "send-rejected" };
1124
+ try { engine.swap.saveSwap(record.swap, store); } catch { /* the pending record stays; never resend blind */ }
1125
+ }
1132
1126
  if (error && typeof error.code === "string") throw error;
1133
1127
  throw new SdkError("server-unavailable", { step: "lock" });
1134
1128
  }
@@ -1149,7 +1143,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1149
1143
  return { id: record.swap.id || null, escrow: record.swap.escrow.address || null,
1150
1144
  address: (record.swapWallet && record.swapWallet.address) || null,
1151
1145
  step: "funding-pending", txHash: pendingTx,
1152
- reason: funded.pendingReason || "no-receipt", predictedEscrow: predicted, next: "receipt" };
1146
+ reason: funded.pendingReason || "no-receipt", predictedEscrow: predicted, next: "receipt",
1147
+ readyWindow };
1153
1148
  }
1154
1149
  // THE ESCROW ADDRESS IS TAKEN FROM THE RECEIPT (lock.send does this), not from a prediction. It is also written
1155
1150
  // into the swap: otherwise the progress screen and the explorer link would show an address that is not on the
@@ -1166,35 +1161,25 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1166
1161
  // THE SALT IS THE RECOVERY BINDING; there is no index reservation to commit here.
1167
1162
  }
1168
1163
 
1169
- // 5. A BACKEND IS OPTIONAL AND NEVER A DEFAULT. When the caller configured an API base, the swap is recorded
1170
- // there and the watch row is opened. Without one, the SDK returns the local state and the joint address: the
1171
- // caller watches the chain itself. The owner's rule: no request to the page's own origin.
1172
- let server = null;
1173
- let watch = null;
1174
- if (config && config.apiBase) {
1175
- server = await markOnServer(record.swap, escrowAddress, request.order);
1176
- watch = await openWatch(record.swap, request.order);
1177
- }
1164
+ // THE START ENDS AT THE JOINT ADDRESS. There is no backend step any more: the retired node routes are gone,
1165
+ // and the caller watches the chain through `swaps.watch` with its own node list.
1178
1166
  // THE STATE IS NAMED, NOT PASSED OFF AS COMPLETION: the swap reached exactly "waiting for XMR at the joint address",
1179
1167
  // and there is no arrival yet - `receivedXmr` is never implied by zero.
1180
1168
  return {
1181
1169
  id: record.swap.id || null,
1182
1170
  escrow: escrowAddress,
1183
- address: (watch && watch.address) || (record.swapWallet && record.swapWallet.address) || null,
1171
+ address: (record.swapWallet && record.swapWallet.address) || null,
1184
1172
  step: "xmr-incoming",
1185
- server,
1186
- watch,
1187
1173
  next: "watch",
1174
+ readyWindow,
1188
1175
  };
1189
1176
  },
1190
1177
 
1191
1178
  /**
1192
1179
  * WAIT FOR THE XMR TO ARRIVE AT THE JOINT ADDRESS - the whole point of opening the watch.
1193
1180
  *
1194
- * The CLIENT checks the arrival from the Monero nodes (`verify`); there is no backend poll by default. The rate
1195
- * and the timeout come from the configuration (config.limits.watchPollMs/watchTimeoutMs) and are overridable here.
1196
- * A caller that explicitly configured `apiBase` may still read the old watch row, but that row is only an
1197
- * observation: it never declares readiness or a decline.
1181
+ * The CLIENT checks the arrival from the Monero nodes (`verify`); there is no backend watcher. The rate and the
1182
+ * timeout come from the configuration (config.limits.watchPollMs/watchTimeoutMs) and are overridable here.
1198
1183
  * IT ARRIVED - we return the FACT (the amount, the confirmations, the txid); WE DID NOT WAIT - a refusal with the
1199
1184
  * code `xmr-timeout`, separate from the others, so "the wait expired" is confused with neither a breakdown nor an
1200
1185
  * empty response. XMR ON THE ADDRESS BUT BARRED BY unlock_time is a THIRD answer with its own code `xmr-locked`
@@ -1216,6 +1201,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1216
1201
  const wantWallet = request.wallet !== undefined && request.wallet !== null;
1217
1202
  if (wantExpect !== wantWallet) throw new SdkError("bad-input", { field: wantExpect ? "wallet" : "expect" });
1218
1203
  if (wantExpect && !(request.escrow || request.address)) throw new SdkError("bad-input", { field: "escrow" });
1204
+ const storedSwap = (() => { try { return engine.swap.getSwap(id, store); } catch { return null; } })();
1205
+ const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
1219
1206
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0 ? Number(request.pollMs) : limitOf("watchPollMs", 5000);
1220
1207
  const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
1221
1208
  // THE CONFIRMATION TARGET - FROM THE CONFIGURATION (one number, the owner's decision: 10).
@@ -1232,15 +1219,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1232
1219
  : null;
1233
1220
  // LESS TIME LEFT THAN THE CONFIRMATIONS TAKE - NAMED AND NOT STARTED (issue #85, the owner's decision).
1234
1221
  if (verifyRequest) {
1222
+ if (!readyWindowRaw) throw new SdkError("bad-input", { field: "readyWindow", why: "not-in-record" });
1223
+ const readyWindow = readReadyWindow(readyWindowRaw, { side: "ask", field: "readyWindow" });
1235
1224
  const readyBy = request.readyBySec !== undefined && request.readyBySec !== null ? Number(request.readyBySec)
1236
1225
  : (request.deadline && request.deadline.readyBy !== undefined ? Number(request.deadline.readyBy) : null);
1237
- if (readyBy) xmrArrival.assertTimeForConfirmations({ readyBySec: readyBy, nowSec: Math.floor(Date.now() / 1000), minConfirmations, blockTimeSec: limitOf("xmrBlockTimeSec", 120) });
1226
+ if (readyBy) xmrArrival.assertTimeForConfirmations({
1227
+ readyBySec: readyBy, nowSec: Math.floor(Date.now() / 1000), minConfirmations,
1228
+ blockTimeSec: limitOf("xmrBlockTimeSec", 120),
1229
+ minLeadSec: readyLateSec(readyWindow),
1230
+ });
1238
1231
  }
1239
- const hasBackend = Boolean(config && config.apiBase);
1240
- // THE WATCH DOES NOT CALL A BACKEND BY DEFAULT. The client-side arrival check needs the joint address, the view
1241
- // secret and the spend public key; without them, and without an explicitly configured backend, there is nothing
1242
- // to wait on. That is a named refusal, not a request to the page's own origin.
1243
- if (!verifyRequest && !hasBackend) throw new SdkError("bad-input", { field: "verify", why: "no-backend" });
1232
+ // THE WATCH IS A CLIENT-SIDE CHECK AND NOTHING ELSE. It needs the joint address, the joint view secret and
1233
+ // the spend public key. Without them there is nothing to wait on: a named refusal, not a request to the
1234
+ // page's own origin and not a fallback to a retired backend.
1235
+ if (!verifyRequest) throw new SdkError("bad-input", { field: "verify", why: "required" });
1244
1236
  const started = Date.now();
1245
1237
  // --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL (issue #40). -------------------------------------
1246
1238
  // A decline leaves the escrow `refunded`, so nothing in the state says "do not wait any longer": without
@@ -1248,12 +1240,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1248
1240
  // CLOSED and whose ETH is already back - or, worse, the app offers the recovery file and a manual refund
1249
1241
  // for money nobody can recover.
1250
1242
  //
1251
- // THE DECLINE IS ASKED WITH TWO INDEPENDENT SOURCES AND EITHER ONE ENDS THE WAIT:
1252
- // * THE CHAIN - the escrow's own `Declined` event, through the same log reader the rest of the core uses;
1253
- // * THE WIRE - the status the service answers with (`declined` with the code `compliance`).
1254
- // A CHAIN READ THAT FAILS is neither a decline nor a refusal of the swap: the wait goes on and the wire may
1255
- // still answer. What the chain read did is carried out with the result (`chain.checked` / `chain.error`), so
1256
- // a broken reader is visible instead of silent.
1243
+ // THE DECLINE IS READ FROM THE CHAIN: the escrow's own `Declined` event, through the same log reader the rest
1244
+ // of the core uses. A CHAIN READ THAT FAILS is neither a decline nor a refusal of the swap: the wait goes on,
1245
+ // and what the chain read did is carried out with the result (`chain.checked` / `chain.error`), so a broken
1246
+ // reader is visible instead of silent.
1257
1247
  // A STORAGE THAT CANNOT BE READ IS NOT A REASON TO REFUSE THE WAIT: the record is what makes the state
1258
1248
  // durable, and the escrow may also arrive in the request. The watch is not a new user of the store - and it
1259
1249
  // must not start failing where it did not before.
@@ -1285,7 +1275,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1285
1275
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "decline" }); }
1286
1276
  };
1287
1277
  // THE STATE THE WATCH REPORTS FOR A DECLINE: no arrival, the state's own code, the node's own token and
1288
- // WHERE it was seen ("event", "status", or "record" when it was already written down). NO reason, category
1278
+ // WHERE it was seen ("event" or "record" when it was already written down). NO reason, category
1289
1279
  // or provider travels here - the node names none, and the sentence a person reads is the interface's.
1290
1280
  const declineResult = ({ source, at, waitedMs, address, chainChecked, chainError }) => ({
1291
1281
  id,
@@ -1308,34 +1298,14 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1308
1298
  let last = null;
1309
1299
  for (;;) {
1310
1300
  await readDeclineLogs();
1311
- // THE CLIENT-SIDE CHECK DOES NOT ASK THE SERVICE. Only a watch without `verify` and with an explicitly
1312
- // configured backend reads the watch row.
1313
- const body = verifyRequest ? {} : await readWatch(id);
1314
- last = verifyRequest
1315
- ? { address: request.address || escrowAddress, expectedXmr: request.expectedXmr ?? null, status: null }
1316
- : incomingOf(body);
1301
+ last = { address: request.address || escrowAddress, expectedXmr: request.expectedXmr ?? null, status: null };
1317
1302
  // THE DECLINE IS THE ESCROW'S EVENT, NOT THE SERVICE'S WORD. The legacy backend's `declined` status used
1318
1303
  // to become a settlement and end the wait; it no longer does. A service answer is at most a notification.
1319
1304
  const declineNow = declineOf({ logs: chainDecline.logs, escrow: escrowAddress, at: Date.now() });
1320
1305
  if (declineNow.declined) {
1321
1306
  settleDecline(record, declineNow.at);
1322
1307
  return declineResult({ source: declineNow.source, at: declineNow.at, waitedMs: Date.now() - started,
1323
- address: body && body.address, chainChecked: chainDecline.checked, chainError: chainDecline.error });
1324
- }
1325
- // AN EMPTY OR FOREIGN RESPONSE IS NOT AN ARRIVAL: counting it as incoming would mean declaring money that was
1326
- // never seen. This is a named refusal, not "let us wait some more".
1327
- if (!last) throw new SdkError("server-unavailable", { step: "watch", why: "bad-response", id });
1328
- // XMR IS ON THE ADDRESS BUT LOCKED BY THE TRANSACTION'S unlock_time: a NAMED refusal, not "keep waiting".
1329
- // The ready mark hands the escrow to the maker; under funds that cannot be spent the maker would take the
1330
- // ETH and the XMR would stay locked (issue #84), so nothing is signed. The boundary is in `until`.
1331
- if (last.locked) {
1332
- const until = last.lockedUntil || {};
1333
- throw new SdkError("xmr-locked", { id, address: last.address, status: last.status,
1334
- expectedXmr: last.expectedXmr, receivedXmr: last.receivedXmr, lockedXmr: last.lockedXmr,
1335
- // The boundary goes as NUMBERS and their kind - a block height or unix seconds - never as text:
1336
- // turning them into a date the person reads is the interface's dictionary (www/js/sdk/codes.js).
1337
- untilHeight: until.untilHeight ?? null, untilTime: until.untilTime ?? null,
1338
- waitedMs: Date.now() - started });
1308
+ address: last && last.address, chainChecked: chainDecline.checked, chainError: chainDecline.error });
1339
1309
  }
1340
1310
  // THE CLIENT'S OWN ANSWER COMES FIRST AND DECIDES. The backend's `seen` may still be false (it no longer
1341
1311
  // holds the view key), so it is not consulted when the client verifies. A disagreement or locked money
@@ -1364,28 +1334,13 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1364
1334
  }
1365
1335
  return verified;
1366
1336
  }
1367
- if (last.seen) {
1368
- // THE SERVICE MAY OBSERVE MONEY, BUT IT DOES NOT DECLARE AN ARRIVAL. Readiness hands a foreign address
1369
- // the settlement, and only the client's own two-node check may do that. The observation is returned with
1370
- // `seen: false` and the next step named; no mark is ever signed from this body.
1371
- return { seen: false, observed: { id: last.id, address: last.address, status: last.status,
1372
- expectedXmr: last.expectedXmr, receivedXmr: last.receivedXmr, confirmations: last.confirmations,
1373
- txids: last.txids }, id, address: last.address, expectedXmr: last.expectedXmr,
1374
- next: "verify", source: "service" };
1375
- }
1376
- if (Date.now() - started >= timeoutMs) {
1377
- throw new SdkError("xmr-timeout", { id, address: last.address, expectedXmr: last.expectedXmr,
1378
- receivedXmr: last.receivedXmr, confirmations: last.confirmations, waitedMs: Date.now() - started,
1379
- timeoutMs, pollMs });
1380
- }
1381
- await new Promise((resolve) => setTimeout(resolve, pollMs));
1382
1337
  }
1383
1338
  },
1384
1339
 
1385
1340
  /**
1386
1341
  * START A SELL FROM A VERIFIED RELAY OFFER. The offer is the result of `quotes.firmRelay` for the bid side;
1387
- * the record keeps the one-time address, the escrow, our half and the order expectations, so a reload can
1388
- * continue with `get` + `sellWatch` + `sellClaim`. This method sends nothing.
1342
+ * the record keeps the one-time address, the escrow, our half, the chosen claim sender and the order
1343
+ * expectations, so a reload can continue with `get` + `sellWatch` + `sellClaim`. This method sends nothing.
1389
1344
  */
1390
1345
  async startSell(request) {
1391
1346
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -1396,6 +1351,16 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1396
1351
  if (!order || !quote) throw new SdkError("bad-input", { field: "offer", missing: ["order", "quote"] });
1397
1352
  if (typeof offer.jointAddress !== "string" || !offer.jointAddress) throw new SdkError("bad-input", { field: "offer.jointAddress" });
1398
1353
  if (typeof offer.escrow !== "string" || !offer.escrow) throw new SdkError("bad-input", { field: "offer.escrow" });
1354
+ // THE RELAY ORIGIN IS PART OF THE OFFER. It is stored with the record so a later claim goes back to the relay
1355
+ // that answered this quote; an origin that is present but not https is refused here, not at claim time.
1356
+ const offerRelay = offer.relayUrl === undefined || offer.relayUrl === null || offer.relayUrl === ""
1357
+ ? null : relayOriginOf(offer.relayUrl);
1358
+ // THE NODE'S WINDOW IS PART OF THE OFFER. `firmRelay` took it from the signed features; a hand-built offer
1359
+ // without one is stored as null, and `sellWatch`/`refundIfXmrMissing` refuse by name instead of using the
1360
+ // old local 1200 s or 20-minute numbers.
1361
+ const offerWindowRaw = offer.readyWindow || (quote && quote.readyWindow) || null;
1362
+ const offerWindow = offerWindowRaw
1363
+ ? readReadyWindow(offerWindowRaw, { side: "bid", field: "offer.readyWindow" }) : null;
1399
1364
  // THE RECORD'S ROLE IS THE BID ROLE. The node is the locker and the person is the claimer; a quote whose
1400
1365
  // addresses or factory disagree with the order is not the offer this record describes.
1401
1366
  const sameValue = (a, b) => String(a || "").replace(/^0x/, "").toLowerCase() === String(b || "").replace(/^0x/, "").toLowerCase();
@@ -1404,6 +1369,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1404
1369
  || !sameValue(quote.factory, order.factory) || Number(quote.chainId) !== Number(order.chainId)) {
1405
1370
  throw new SdkError("quote-refused", { step: "sell-record", why: "terms" });
1406
1371
  }
1372
+ // THE SENDER IS CHOSEN BY THE CLIENT, NOT THE DEAL'S MAKER. The record keeps it so a reload claims through
1373
+ // the same node; a sender naming the maker or the quote key owner would reveal the half to the party that
1374
+ // must never receive it.
1375
+ const dealMaker = addressTextOf(quote.provider, "provider");
1376
+ const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1377
+ || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1378
+ const requestedSender = request.claimSender === undefined || request.claimSender === null
1379
+ || String(request.claimSender).trim() === "" ? null : addressTextOf(request.claimSender, "claimSender");
1380
+ if (requestedSender && requestedSender === dealMaker) {
1381
+ throw new SdkError("bad-input", { field: "claimSender", why: "is-deal-maker" });
1382
+ }
1383
+ if (requestedSender && quoteKeyOwner && requestedSender === quoteKeyOwner) {
1384
+ throw new SdkError("bad-input", { field: "claimSender", why: "is-quote-key" });
1385
+ }
1407
1386
  // THE RECORD IS FOUND BEFORE A SECOND ONE IS MADE. The same offer retried after a reload yields the same
1408
1387
  // one-time address and escrow; a second record would be a second promise about one deal.
1409
1388
  const quoteId = quote.id || quote.nonce || null;
@@ -1420,11 +1399,46 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1420
1399
  || !same(existing.escrow && existing.escrow.moneroAddress, offer.jointAddress)) {
1421
1400
  throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
1422
1401
  }
1423
- await sellEscrowGate((existing.escrow && existing.escrow.address) || offer.escrow, existing.expect || null);
1402
+ const storedSender = existing.claimSender ? addressTextOf(existing.claimSender, "claimSender") : null;
1403
+ if (requestedSender && storedSender && requestedSender !== storedSender) {
1404
+ throw new SdkError("quote-refused", { step: "sell-record", why: "claim-sender-changed" });
1405
+ }
1406
+ // THE RELAY IS PART OF THE VERIFIED OFFER. A claim later goes to the origin that answered this quote, so
1407
+ // a resumed offer naming another origin is a different offer; one that now names the same origin fills a
1408
+ // record made before the origin was kept.
1409
+ const storedRelay = existing.relayUrl ? relayOriginOf(existing.relayUrl) : null;
1410
+ if (offerRelay && storedRelay && offerRelay !== storedRelay) {
1411
+ throw new SdkError("quote-refused", { step: "sell-record", why: "relay-changed" });
1412
+ }
1413
+ await sellEscrowGate((existing.escrow && existing.escrow.address) || offer.escrow, existing.expect || null, request.wallet);
1414
+ if (offerRelay && !storedRelay) {
1415
+ existing.relayUrl = offerRelay;
1416
+ try { engine.swap.saveSwap(existing, store); }
1417
+ catch { throw new SdkError("storage-unavailable", { step: "save-relay" }); }
1418
+ }
1419
+ if (requestedSender && !storedSender) {
1420
+ existing.claimSender = requestedSender;
1421
+ try { engine.swap.saveSwap(existing, store); }
1422
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
1423
+ }
1424
+ const storedWindow = existing.readyWindow || existing.sellWindow || null;
1425
+ if (offerWindow && storedWindow) {
1426
+ const a = readReadyWindow(storedWindow, { side: "bid", field: "readyWindow" });
1427
+ if (a.readyMinSeconds !== offerWindow.readyMinSeconds || a.readyMaxSeconds !== offerWindow.readyMaxSeconds) {
1428
+ throw new SdkError("quote-refused", { step: "sell-record", why: "window-changed" });
1429
+ }
1430
+ }
1431
+ if (offerWindow && !storedWindow) {
1432
+ existing.readyWindow = offerWindow;
1433
+ try { engine.swap.saveSwap(existing, store); }
1434
+ catch { throw new SdkError("storage-unavailable", { step: "save-window" }); }
1435
+ }
1424
1436
  return { id: existing.id, side: "sell", escrow: (existing.escrow && existing.escrow.address) || offer.escrow,
1425
1437
  address: (existing.escrow && existing.escrow.moneroAddress) || offer.jointAddress,
1426
1438
  xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
1427
1439
  claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
1440
+ claimSender: existing.claimSender || null,
1441
+ readyWindow: existing.readyWindow || existing.sellWindow || null,
1428
1442
  resumed: true, next: "send-xmr" };
1429
1443
  }
1430
1444
  const storage = store.storage();
@@ -1436,6 +1450,23 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1436
1450
  if (!saved && !supplied) throw new SdkError("bad-input", { field: "recoveryKey" });
1437
1451
  const key = saved || importRecoveryKey(supplied);
1438
1452
  if (!saved) saveRecoveryKey(storage, { ...key, backupConfirmed: false });
1453
+ // A SELL CARRIES THE SAME KEY AS A BUY, SO IT NEEDS THE SAME BACKUP GATE. The one-time XMR address is the
1454
+ // moment the seller can lose money; handing it out before the twelve words are saved turns a closed tab into
1455
+ // an unrecoverable sale. The buy path already refuses to fund until this flag is true.
1456
+ if (!saved || saved.backupConfirmed !== true) {
1457
+ if (typeof request.onRecoveryKey !== "function") throw new SdkError("bad-input", { field: "onRecoveryKey" });
1458
+ let file = null;
1459
+ try {
1460
+ file = {
1461
+ name: recoveryKeyFileName(key),
1462
+ contents: await createRecoveryKeyFile({ mnemonic: key.mnemonic, createdAt: key.createdAt, passphrase: request.passphrase }),
1463
+ };
1464
+ } catch { throw new SdkError("recovery-failed", { step: "encrypt-key" }); }
1465
+ const confirmed = await request.onRecoveryKey(file);
1466
+ if (confirmed !== true) throw new SdkError("recovery-declined", { key: key.fingerprint });
1467
+ try { saveRecoveryKey(storage, { ...key, backupConfirmed: true }); }
1468
+ catch { throw new SdkError("storage-unavailable", { step: "save-recovery-key" }); }
1469
+ }
1439
1470
  const chainId = Number(order.chainId);
1440
1471
  if (!Number.isSafeInteger(chainId) || chainId <= 0) throw new SdkError("bad-input", { field: "order.chainId" });
1441
1472
  if (!order.factory || order.salt === undefined || order.salt === null) throw new SdkError("bad-input", { field: "order" });
@@ -1443,17 +1474,16 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1443
1474
  try { salt = recoverySaltOf(offer.recovery && offer.recovery.salt ? offer.recovery.salt : order.salt); }
1444
1475
  catch { throw new SdkError("bad-input", { field: "offer.recovery" }); }
1445
1476
  const derived = takerHalvesV2({ mnemonic: key.mnemonic, chainId, factory: order.factory, salt });
1446
- const own = buildOwnSideFromHalves(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
1477
+ const own = buildOwnSideFromHalvesKnown(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
1447
1478
  // THE OFFER MUST NAME THE HALF THIS KEY ACTUALLY PRODUCES. The relay already checked the proof; the record
1448
1479
  // needs the same point and commitment, otherwise a later claim would reveal a half the escrow rejects.
1449
- const ownCommit = (() => {
1450
- try {
1451
- const point = secp256k1.Point.fromHex(own.side.proof.XA);
1452
- return "0x" + Array.from(keccak256(point.toBytes(false).slice(1)), (b) => b.toString(16).padStart(2, "0")).join("");
1453
- } catch { return null; }
1454
- })();
1455
- const low160 = (v) => String(v || "").replace(/^0x/, "").toLowerCase().slice(-40);
1456
- if (!ownCommit || low160(ownCommit) !== low160(quote.commitHalfClaimer)) {
1480
+ // THE COMMITMENT COMES FROM THE HALF, NOT FROM A SECOND PROOF. `buildOwnSideFromHalvesKnown` derives it with
1481
+ // the same builder the contract mirrors; the side carries no proof because the firm answer already did.
1482
+ const ownCommit = own.commitHalf;
1483
+ // THE WHOLE COMMITMENT, NOT ITS LOW 160 BITS. `findSwaps` compares all 32 bytes, so a bid whose high 96 bits
1484
+ // differ would be invisible to a words-only search while `startSell` accepted it.
1485
+ const fullHex = (v) => String(v || "").replace(/^0x/, "").toLowerCase();
1486
+ if (!ownCommit || fullHex(ownCommit) !== fullHex(quote.commitHalfClaimer)) {
1457
1487
  throw new SdkError("quote-refused", { step: "sell-record", why: "commitment" });
1458
1488
  }
1459
1489
  if (String(own.spendPoint).toLowerCase() !== String(quote.edPointClaimer || "").toLowerCase()) {
@@ -1477,6 +1507,9 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1477
1507
  swap.orderQuote = offer.orderQuote || null;
1478
1508
  swap.quote = quote;
1479
1509
  swap.claimTip = quote.claimTip || null;
1510
+ // THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping it means a reload cannot silently
1511
+ // send the half to a different node than the one the client selected.
1512
+ if (requestedSender) swap.claimSender = requestedSender;
1480
1513
  swap.expect = {
1481
1514
  chainId, factory: order.factory, locker: order.locker, claimer: order.claimer, amount: String(order.amount),
1482
1515
  readyBy: order.readyBy, t1: order.t1, salt: order.salt,
@@ -1496,11 +1529,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1496
1529
  commitHalfLocker: (offer.nodeHalf && offer.nodeHalf.commitHalf) || null,
1497
1530
  orderContext: offer.context || null, xmrAmount: quote.xmrAmount || null,
1498
1531
  };
1532
+ // KEPT WITH THE RECORD, NOT BUILT LATER: the claim and the watch use the relay and window that signed this
1533
+ // offer, not a value the page chose after the quote.
1534
+ if (offerRelay) swap.relayUrl = offerRelay;
1535
+ if (offerWindow) swap.readyWindow = offerWindow;
1499
1536
  // THE RECORD IS NOT A RECEIPT FOR A GATE THAT FAILED. createRecord has already written it, so a refusal
1500
1537
  // from the escrow/deadline/slot gate must remove it again; otherwise the interface lists send-xmr for an
1501
1538
  // order the SDK never checked.
1502
1539
  try {
1503
- await sellEscrowGate(offer.escrow, swap.expect);
1540
+ await sellEscrowGate(offer.escrow, swap.expect, request.wallet);
1504
1541
  } catch (error) {
1505
1542
  try { engine.swap.forgetSwap(swap.id, store); } catch { /* the gate's refusal is the actionable one */ }
1506
1543
  throw error;
@@ -1508,7 +1545,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1508
1545
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1509
1546
  return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
1510
1547
  xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
1511
- resumed: false, next: "send-xmr" };
1548
+ claimSender: swap.claimSender || null,
1549
+ readyWindow: swap.readyWindow || null, resumed: false, next: "send-xmr" };
1512
1550
  },
1513
1551
 
1514
1552
  /**
@@ -1531,6 +1569,104 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1531
1569
  expect, onStep: request.onStep }, wallet);
1532
1570
  },
1533
1571
 
1572
+ /**
1573
+ * CLAIM THE ETH ON A SELL WITHOUT A WALLET.
1574
+ *
1575
+ * The seller holds XMR and no ETH, so the escrow pays the signed `claimTip` to whoever submits the claim.
1576
+ * This method sends the half to the sender the client chose - a listed maker other than the deal's maker - and
1577
+ * the relay posts it to `POST /v1/claims/{sender}/{escrow}`. It NEVER creates or uses a wallet and never signs a
1578
+ * chain transaction; `sellClaim` remains the own-wallet path.
1579
+ *
1580
+ * A record must come from `startSell`, carry a POSITIVE `claimTip`, and name the sender, escrow and half. The
1581
+ * sender is stored by `startSell`; a request may supply `claimSender` only when the record has none, and may
1582
+ * never name the deal's maker. `relayUrl` is only a restatement of the stored origin: a different one is refused
1583
+ * rather than obeyed. A vanished answer is `claim-unknown` (the claim may have been sent), never success; only a
1584
+ * real txid returns.
1585
+ */
1586
+ async claimViaRelay(request = {}) {
1587
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1588
+ const id = String(request.id === undefined || request.id === null ? "" : request.id).trim();
1589
+ if (!id) throw new SdkError("bad-input", { field: "id" });
1590
+ let swap = null;
1591
+ try { swap = engine.swap.getSwap(id, store); } catch { swap = null; }
1592
+ if (!swap || swap.side !== "sell") throw new SdkError("bad-input", { field: "id", why: "sell-not-found" });
1593
+
1594
+ // THE TIP PAYS THE SENDER. A zero tip is not a claim the relay can make: the node would pay the gas for
1595
+ // nothing, and the request would be refused after the half had already left the client. Refuse here.
1596
+ let tip = 0n;
1597
+ try { tip = BigInt(swap.claimTip === undefined || swap.claimTip === null || swap.claimTip === "" ? 0 : swap.claimTip); }
1598
+ catch { throw new SdkError("bad-input", { field: "claimTip", why: "unreadable" }); }
1599
+ if (tip <= 0n) throw new SdkError("bad-input", { field: "claimTip", why: "not-positive" });
1600
+
1601
+ // THE DEAL'S MAKER IS THE ONE PARTY THAT MUST NOT RECEIVE THE HALF. It is the quote's provider and, on a
1602
+ // sell, the order's locker. The sender is a different node, chosen by the client; a record with no sender
1603
+ // cannot be claimed through a guess.
1604
+ const quote = swap.quote && typeof swap.quote === "object" ? swap.quote : {};
1605
+ const order = swap.order && typeof swap.order === "object" ? swap.order : {};
1606
+ const escrowRecord = swap.escrow && typeof swap.escrow === "object" ? swap.escrow : {};
1607
+ const makerRaw = quote.provider !== undefined && quote.provider !== null ? quote.provider
1608
+ : (escrowRecord.providerId !== undefined && escrowRecord.providerId !== null ? escrowRecord.providerId : order.locker);
1609
+ if (makerRaw === undefined || makerRaw === null || makerRaw === "") {
1610
+ throw new SdkError("bad-input", { field: "provider", why: "not-in-record" });
1611
+ }
1612
+ const maker = addressTextOf(makerRaw, "provider");
1613
+ for (const [field, value] of [["order.locker", order.locker], ["quote.locker", quote.locker]]) {
1614
+ if (value !== undefined && value !== null && String(value) !== "") {
1615
+ if (addressTextOf(value, field) !== maker) {
1616
+ throw new SdkError("quote-refused", { step: "relay-claim", why: "provider" });
1617
+ }
1618
+ }
1619
+ }
1620
+ const storedSenderRaw = swap.claimSender === undefined || swap.claimSender === null
1621
+ || String(swap.claimSender).trim() === "" ? null : swap.claimSender;
1622
+ const requestedSenderRaw = request.claimSender === undefined || request.claimSender === null
1623
+ || String(request.claimSender).trim() === "" ? null : request.claimSender;
1624
+ const storedSender = storedSenderRaw ? addressTextOf(storedSenderRaw, "claimSender") : null;
1625
+ const requestedSender = requestedSenderRaw ? addressTextOf(requestedSenderRaw, "claimSender") : null;
1626
+ if (storedSender && requestedSender && storedSender !== requestedSender) {
1627
+ throw new SdkError("bad-input", { field: "claimSender", why: "different-from-record" });
1628
+ }
1629
+ const sender = storedSender || requestedSender;
1630
+ if (!sender) throw new SdkError("bad-input", { field: "claimSender", why: "not-in-record" });
1631
+ if (sender === maker) throw new SdkError("bad-input", { field: "claimSender", why: "is-deal-maker" });
1632
+ const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1633
+ || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1634
+ if (quoteKeyOwner && sender === quoteKeyOwner) {
1635
+ throw new SdkError("bad-input", { field: "claimSender", why: "is-quote-key" });
1636
+ }
1637
+ // AN OLDER RECORD KEEPS THE SENDER ONCE IT IS USED. A reload must not be forced to remember a second input.
1638
+ if (!storedSender && requestedSender) {
1639
+ swap.claimSender = requestedSender;
1640
+ try { engine.swap.saveSwap(swap, store); }
1641
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
1642
+ }
1643
+ if (escrowRecord.address === undefined || escrowRecord.address === null || escrowRecord.address === "") {
1644
+ throw new SdkError("bad-input", { field: "escrow", why: "not-in-record" });
1645
+ }
1646
+ const escrow = addressTextOf(escrowRecord.address, "escrow");
1647
+ const halfClaimer = halfTextOf(escrowRecord.half);
1648
+
1649
+ // THE ORIGIN IS THE QUOTE'S, NOT THE CALLER'S. The record stores the relay that answered; a request may
1650
+ // repeat it (with a trailing slash), but may not choose another one after the quote.
1651
+ if (swap.relayUrl === undefined || swap.relayUrl === null || swap.relayUrl === "") {
1652
+ throw new SdkError("bad-input", { field: "relayUrl", why: "not-in-record" });
1653
+ }
1654
+ const relayUrl = relayOriginOf(swap.relayUrl);
1655
+ if (request.relayUrl !== undefined && request.relayUrl !== null && String(request.relayUrl).trim() !== "") {
1656
+ if (relayOriginOf(request.relayUrl) !== relayUrl) {
1657
+ throw new SdkError("bad-input", { field: "relayUrl", why: "foreign-relay" });
1658
+ }
1659
+ }
1660
+
1661
+ const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
1662
+ ? Number(request.timeoutMs) : 20_000;
1663
+ const claimed = await postRelayClaim({
1664
+ relayUrl, provider: sender, escrow, halfClaimer, expectedTipWei: tip,
1665
+ fetchImpl: request.fetchImpl || null, timeoutMs,
1666
+ });
1667
+ return { id, provider: sender, claimSender: sender, escrow, relayUrl, txid: claimed.txid, from: claimed.from, tipWei: claimed.tipWei };
1668
+ },
1669
+
1534
1670
  /**
1535
1671
  * WAIT FOR THE NODE'S SIDE ON A SELL. The client sends XMR to the one-time joint address; the node (the
1536
1672
  * locker) must mark the order ready before the claimer can take the ETH. This reads the escrow itself - no
@@ -1540,19 +1676,38 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1540
1676
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1541
1677
  const escrow = String(request.escrow || "").trim();
1542
1678
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
1543
- // THE WAIT IS BOUNDED BY THE ORDER'S OWN READY DEADLINE, NOT BY A FIXED 20 MINUTES. Ten confirmations
1544
- // average about twenty minutes, so the old default timed out roughly half of honest sales. A request may
1545
- // still set an explicit timeout; otherwise the wait covers the remaining time to readyBy plus a margin.
1679
+ // THE NODE'S WINDOW IS READ FROM THE RECORD BY THE ESCROW. A reload keeps only the address in hand; the
1680
+ // stored `startSell` record carries the range the maker signed, so the wait is not the old fixed 20 minutes.
1681
+ const storedSwap = swapByEscrow(store, escrow);
1682
+ const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
1546
1683
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
1547
1684
  ? Number(request.pollMs) : limitOf("watchPollMs", 6_000);
1548
- let timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
1549
- ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
1550
- if (!(Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0)) {
1685
+ const explicitTimeout = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0;
1686
+ const readyWindow = !explicitTimeout && readyWindowRaw
1687
+ ? readReadyWindow(readyWindowRaw, { side: "bid", field: "readyWindow" }) : null;
1688
+ if (!readyWindow && !explicitTimeout) {
1689
+ throw new SdkError("bad-input", { field: "readyWindow", why: "not-in-record" });
1690
+ }
1691
+ let timeoutMs = explicitTimeout ? Number(request.timeoutMs) : null;
1692
+ if (!explicitTimeout) {
1551
1693
  try {
1552
1694
  const deadlines = await flow.orderDeadlines(escrow, { call: reader });
1553
- timeoutMs = sellWatchTimeoutMs({ configuredMs: timeoutMs, readyBySec: deadlines.readyBy });
1554
- } catch { /* no deadline read: keep the configured wait */ }
1695
+ timeoutMs = sellWatchTimeoutMs({ configuredMs: readyWindowMs(readyWindow), readyBySec: deadlines.readyBy });
1696
+ } catch {
1697
+ // NO DEADLINE READ: the node's own maximum horizon is the bound, not a second local 20-minute number.
1698
+ timeoutMs = readyWindowMs(readyWindow);
1699
+ }
1555
1700
  }
1701
+ // THE CLAIM OPENS AT readyBy WITHOUT A MARK. The deadline comes from the escrow once; the clock is the
1702
+ // facade's own millisecond seam, so a simulation and a caller that controls time agree with the rest of
1703
+ // the SDK. A failed deadline read does not invent a claim window.
1704
+ let deadlines = null;
1705
+ try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
1706
+ catch { /* no deadline: the wait keeps its configured timeout and never reports claim-open */ }
1707
+ const nowSec = () => {
1708
+ const at = typeof now === "function" ? Number(now()) : Date.now();
1709
+ return Number.isFinite(at) ? Math.floor(at / 1000) : null;
1710
+ };
1556
1711
  const started = Date.now();
1557
1712
  let lastStatus = null;
1558
1713
  let lastError = null;
@@ -1562,7 +1717,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1562
1717
  if (lastStatus && (lastStatus.isClaimed || lastStatus.isRefunded)) {
1563
1718
  return { escrow, state: lastStatus.isClaimed ? "claimed" : "refunded",
1564
1719
  funded: lastStatus.isFunded, claimed: lastStatus.isClaimed, refunded: lastStatus.isRefunded,
1565
- ready: null, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1720
+ ready: null, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1566
1721
  }
1567
1722
  if (lastStatus && lastStatus.isFunded) {
1568
1723
  let ready = null;
@@ -1573,7 +1728,16 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1573
1728
  } catch (error) { lastError = (error && error.code) || "ready-unread"; }
1574
1729
  if (ready === true) {
1575
1730
  return { escrow, state: "ready", funded: true, claimed: false, refunded: false,
1576
- ready: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1731
+ ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1732
+ }
1733
+ }
1734
+ // AFTER readyBy THE CLAIM IS OPEN EVEN WITHOUT THE NODE'S READY MARK. The order is funded, no terminal
1735
+ // action was seen, and the escrow's own deadline has passed; the seller can claim the ETH now.
1736
+ if (lastStatus && lastStatus.isFunded && deadlines && Number.isSafeInteger(Number(deadlines.readyBy))) {
1737
+ const at = nowSec();
1738
+ if (at !== null && at >= Number(deadlines.readyBy)) {
1739
+ return { escrow, state: "claim-open", funded: true, claimed: false, refunded: false,
1740
+ ready: false, claimOpen: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1577
1741
  }
1578
1742
  }
1579
1743
  if (Date.now() - started >= timeoutMs) {