@ninsei-labs/sdk 0.57.2 → 0.59.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 (53) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +82 -32
  3. package/THIRD_PARTY_NOTICES.md +7 -4
  4. package/assets/vendors/MANIFEST.json +1 -9
  5. package/assets/vendors/sdk/sdk-browser.js +4 -6
  6. package/engine/core/config.js +5 -24
  7. package/engine/core/deployments.generated.js +33 -0
  8. package/engine/core/rfqSource.js +6 -133
  9. package/engine/core/swap.js +1 -1
  10. package/engine/evm/index.js +3 -2
  11. package/engine/evm/session.js +46 -277
  12. package/engine/monero/address.js +15 -33
  13. package/engine/monero/keys.js +124 -0
  14. package/engine/monero/mnemonic.js +104 -0
  15. package/engine/monero/scan.js +79 -17
  16. package/engine/monero/wallet.js +31 -68
  17. package/engine/monero/wordlist.en.js +210 -0
  18. package/engine/recovery/restore.js +1 -1
  19. package/engine/sdk/bridge.js +7 -182
  20. package/engine/ui/walletModal.js +7 -27
  21. package/index.d.ts +248 -254
  22. package/package.json +6 -7
  23. package/src/codes.mjs +12 -0
  24. package/src/config.mjs +16 -54
  25. package/src/engine.mjs +3 -0
  26. package/src/index.mjs +25 -46
  27. package/src/order.mjs +2 -2
  28. package/src/public/networks.d.ts +9 -0
  29. package/src/public/networks.mjs +1 -0
  30. package/src/public/recovery.d.ts +17 -1
  31. package/src/public/recovery.mjs +1 -0
  32. package/src/public/xmr.d.ts +8 -0
  33. package/src/public/xmr.mjs +1 -1
  34. package/src/quotePolicy.mjs +58 -0
  35. package/src/quotes.mjs +30 -753
  36. package/src/readyWindow.mjs +76 -0
  37. package/src/record.mjs +4 -0
  38. package/src/recovery-key.mjs +39 -2
  39. package/src/recovery.mjs +11 -28
  40. package/src/relayClaim.mjs +132 -0
  41. package/src/relayFirmClient.mjs +3 -0
  42. package/src/relayQuote.mjs +5 -1
  43. package/src/swap-flow.mjs +49 -5
  44. package/src/swaps.mjs +530 -317
  45. package/src/sweep-action.mjs +73 -0
  46. package/src/sweep.mjs +7 -1
  47. package/src/version.mjs +1 -1
  48. package/src/witness-slice.mjs +84 -0
  49. package/src/xmr-arrival.mjs +378 -9
  50. package/src/xmrAmountPolicy.mjs +35 -0
  51. package/assets/vendors/monero/monero-js-browser.js +0 -58
  52. package/assets/vendors/monero-js/LICENSE +0 -9
  53. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
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 { quoteLifeVerdict } 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
@@ -39,6 +40,10 @@ import * as xmrArrival from "./xmr-arrival.mjs";
39
40
  // `compliance` status is an observation on the wire, not a second source this file trusts; the detectors and the
40
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
  //
@@ -108,45 +113,6 @@ const LOCKED_STATUS = "xmr_locked";
108
113
  // WHAT IS DELIBERATELY ABSENT HERE: a waiting policy of its own inside the step. How long to wait for the XMR to
109
114
  // arrive is the caller's decision, so the watch is exposed as a separate method (`swaps.watch`) with a timeout from
110
115
  // the configuration.
111
- const MARK_FIELDS = ["id", "network", "escrow", "quoteId", "providerId", "hashlock", "amount", "t0", "t1", "sdkVersion"];
112
- // THE FIELDS OF THE FACTORY WATCH RECORD - the same whitelist as the page client's
113
- // (www/js/core/chainSource.js:33, ALLOWED_SESSION_FIELDS). The body is assembled FROM IT anew, so neither the spend
114
- // half nor the spend key can get into the request, even if someone adds them to the record "just in case".
115
- const ALLOWED_SESSION_FIELDS = ["swapId", "network", "address", "viewKey", "expectedAmountXmr", "restoreHeight", "chain"];
116
-
117
- /**
118
- * The mark body from the swap record. THE FIELDS ARE THE SAME AND WITH THE SAME MEANING as the interface's
119
- * (auth.js:114-125), not a private list: only public data goes out (the escrow address, amounts, deadlines, the
120
- * quote reference), and nothing secret - the spend key never leaves the browser under any configuration.
121
- */
122
- export function markBodyOf(swap, escrow, order = null) {
123
- const e = (swap && swap.escrow) || {};
124
- const o = order && typeof order === "object" ? order : {};
125
- // A BIGINT AS A STRING: the order amount in wei comes both as a string and as a BigInt number (the order terms),
126
- // and the request body is serialized to JSON, where a BigInt does not live at all (a TypeError on the very first
127
- // call). The app expects a string.
128
- const first = (...vals) => {
129
- for (const v of vals) {
130
- if (v === undefined || v === null || v === "") continue;
131
- return typeof v === "bigint" ? v.toString() : v;
132
- }
133
- return null;
134
- };
135
-
136
- return {
137
- id: swap.id || null,
138
- network: swap.network || swap.chain || null,
139
- escrow: escrow || e.address || null,
140
- quoteId: first(swap.orderQuoteId, e.quoteId),
141
- providerId: first(swap.providerId, e.providerId),
142
- hashlock: first(e.hashlock, swap.hashlock),
143
- amount: first(e.amountWei, o.amount, swap.amountWei),
144
- t0: first(e.t0, o.t0),
145
- t1: first(e.t1, o.t1),
146
- sdkVersion: SDK_VERSION,
147
- };
148
- }
149
-
150
116
  /**
151
117
  * THE VIEW KEY OF THE JOINT ADDRESS - THE SUM OF TWO HALVES. That is how the interface assembles it
152
118
  * (www/js/ui/views/confirm.js:559; math - www/js/monero/swapKeys.js, watchViewSeedHex), and only with it does the
@@ -168,32 +134,6 @@ export function jointViewKey(swap) {
168
134
  * field at all, and "the field is absent" and "zero" are different things (zero means "nothing arrived", absence -
169
135
  * "not read"). We return null if this is not a watch response at all - emptiness must not be taken for data.
170
136
  */
171
- export function incomingOf(session) {
172
- if (!session || typeof session !== "object") return null;
173
- const received = Number(session.receivedXmr);
174
- if (!Number.isFinite(received)) return null;
175
- const confirmations = Number(session.confirmations);
176
- // LOCKED FUNDS ARE ON THE ADDRESS BUT ARE NOT AN ARRIVAL THE SWAP CAN USE: the sender set unlock_time, and the
177
- // service names that state. `receivedXmr` counts only what can be spent; the barred sum is `lockedXmr`, and the
178
- // boundary (a height or a date) travels as `lockedUntil` so the interface can say until WHEN.
179
- const locked = session.status === LOCKED_STATUS;
180
- const lockedXmr = num(session.lockedXmr);
181
- return {
182
- id: session.id || null,
183
- address: session.address || null,
184
- status: session.status || null,
185
- expectedXmr: num(session.expectedAmountXmr),
186
- receivedXmr: received,
187
- confirmations: Number.isFinite(confirmations) ? confirmations : 0,
188
- txids: Array.isArray(session.fundingTxids) ? session.fundingTxids : [],
189
- locked,
190
- lockedXmr: lockedXmr === null ? 0 : lockedXmr,
191
- lockedUntil: session.lockedUntil || null,
192
- // AN ARRIVAL IS MONEY AT THE ADDRESS THAT IS NOT BARRED BY unlock_time. Zero, or locked, means none.
193
- seen: received > 0 && !locked,
194
- };
195
- }
196
-
197
137
  /** Translating the engine's record into the contract state: our names, the engine's meaning. */
198
138
  export function toState(swap) {
199
139
  if (!swap || typeof swap !== "object" || !swap.id) throw new SdkError("bad-input", { field: "swap" });
@@ -326,8 +266,13 @@ export const recordInputOf = (request, xmrNetwork = null) => {
326
266
  expectedAtomic: quoteAtomic !== null ? quoteAtomic : (orderAtomic !== null ? orderAtomic : undefined),
327
267
  // THE ORDER-QUOTE ID IS PART OF THE RECORD, NOT A DETAIL OF THE SCREEN (a defect found): our service uses it to
328
268
  // tie the created escrow to the provider node's record, and without it the node cannot take the ETH
329
- // (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).
330
270
  orderQuoteId: pass(quote.id),
271
+ // THE PENDING-FUNDING IDENTITY. A retry without the relay answer still has to prove that the record it found
272
+ // belongs to the same order; the salt alone is not enough, so the chain, the factory and the predicted escrow
273
+ // are stored beside it.
274
+ chainId: pass((request.order && request.order.chainId) ?? (request.orderQuote && request.orderQuote.chainId)),
275
+ factory: pass((request.order && request.order.factory) ?? (request.orderQuote && request.orderQuote.factory)),
331
276
  // WHERE TO WITHDRAW XMR: part of the record, not a detail of the screen - the progress screen exports the file by it.
332
277
  receiveAddress: pass(request.receiveTo),
333
278
  // WHAT THE PERSON SAW: the maker, its spread, the fee, the rate and the quote signature. Screen data, but it must
@@ -381,15 +326,99 @@ export function sellWatchTimeoutMs({ configuredMs = 1_200_000, readyBySec = null
381
326
  return Math.max(configured, (readyAt - now + SELL_WATCH_MARGIN_SEC) * 1000);
382
327
  }
383
328
 
384
- export function createSwaps({ preflight, http, createRecord, mode = null, xmrNetwork = null, call = null, now = null, evmBlock = null, store = engine.store,
385
- // THE PATHS AND LIMITS ARE BROUGHT BY THE CONFIGURATION: the "server" step's paths are named by names (config.route),
386
- // and the timeout and rate of the watch polling - in config.limits. Without the configuration the step answers with a
387
- // code rather than following invented paths.
329
+ // A PENDING FUNDING IS RESUMED ONLY FOR THE SAME ORDER, NOT MERELY THE SAME NONCE. The quote nonce is the maker's
330
+ // value and a second offer can reuse it. The identity is the client's salt together with the chain, the factory and
331
+ // the predicted escrow: those four values are the order the record was built for. A record that names no predicted
332
+ // escrow cannot prove it is the same order and is not resumed.
333
+ const pendingSalt = (value) => String(value === undefined || value === null ? "" : value).replace(/^0x/i, "").toLowerCase();
334
+ const pendingAddress = (value) => String(value === undefined || value === null ? "" : value).replace(/^0x/i, "").toLowerCase();
335
+ function pendingFundingIdentity(swap) {
336
+ const escrow = swap && swap.escrow && typeof swap.escrow === "object" ? swap.escrow : {};
337
+ const order = swap && swap.order && typeof swap.order === "object" ? swap.order : {};
338
+ const quote = swap && swap.quote && typeof swap.quote === "object" ? swap.quote : {};
339
+ return {
340
+ salt: pendingSalt(escrow.salt ?? (swap && swap.recoverySalt)),
341
+ chainId: Number(order.chainId ?? quote.chainId ?? (swap && swap.chainId) ?? escrow.chainId),
342
+ factory: pendingAddress(order.factory ?? quote.factory ?? (swap && swap.factory) ?? escrow.factory),
343
+ escrow: pendingAddress(escrow.address ?? (swap && swap.predictedEscrow)),
344
+ };
345
+ }
346
+
347
+ // THE PENDING ROW CAN BE FOUND WITHOUT ITS ESCROW. A reloaded retry has the salt, chain and factory, but it has
348
+ // no request escrow; the address must be predicted from the signed quote before the row can prove it is the same
349
+ // order. This base match only selects a row that *might* be resumed; it never authorises a send.
350
+ function samePendingBase(swap, identity = {}) {
351
+ if (!swap || !(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
352
+ const recorded = pendingFundingIdentity(swap);
353
+ const wanted = {
354
+ salt: pendingSalt(identity.salt),
355
+ chainId: Number(identity.chainId),
356
+ factory: pendingAddress(identity.factory),
357
+ };
358
+ if (!wanted.salt || !wanted.factory || !Number.isSafeInteger(wanted.chainId) || wanted.chainId <= 0) return false;
359
+ // Records written before the identity gained chain/factory still have the salt. They may be matched on what they
360
+ // have, but the caller still has to name the same predicted address; a partial record is never a free pass.
361
+ if (recorded.salt !== wanted.salt) return false;
362
+ if (recorded.factory && recorded.factory !== wanted.factory) return false;
363
+ if (Number.isSafeInteger(recorded.chainId) && recorded.chainId > 0 && recorded.chainId !== wanted.chainId) return false;
364
+ return true;
365
+ }
366
+
367
+ export function samePendingFunding(swap, identity = {}) {
368
+ if (!swap || !(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
369
+ const recorded = pendingFundingIdentity(swap);
370
+ const wanted = {
371
+ salt: pendingSalt(identity.salt),
372
+ chainId: Number(identity.chainId),
373
+ factory: pendingAddress(identity.factory),
374
+ escrow: pendingAddress(identity.escrow),
375
+ };
376
+ if (!wanted.salt || !wanted.factory || !wanted.escrow || !Number.isSafeInteger(wanted.chainId) || wanted.chainId <= 0) return false;
377
+ if (recorded.salt !== wanted.salt || recorded.escrow !== wanted.escrow) return false;
378
+ // A RECORD WRITTEN BEFORE THE IDENTITY FIELDS STILL HAS ONE OPINION: its salt and its escrow address. Missing
379
+ // chain/factory fields are wildcards only for that old shape; a record that carries them must match them exactly.
380
+ if (Number.isSafeInteger(recorded.chainId) && recorded.chainId > 0 && recorded.chainId !== wanted.chainId) return false;
381
+ if (recorded.factory && recorded.factory !== wanted.factory) return false;
382
+ return true;
383
+ }
384
+
385
+ /**
386
+ * WHAT A PENDING RECORD MEANS FOR THIS START.
387
+ * `salt-required` is the expensive branch made loud: a caller that knows only the nonce of a pending record cannot
388
+ * prove it is the same order, and falling through would build a second deposit. The caller must bring the full
389
+ * identity (salt, chain, factory, predicted escrow), not guess.
390
+ */
391
+ export function pendingFundingVerdict(swap, identity = {}) {
392
+ const pending = Boolean(swap && (swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true)));
393
+ if (!pending) return "not-pending";
394
+ const salt = pendingSalt(identity.salt);
395
+ const quoteId = String(identity.quoteId === undefined || identity.quoteId === null ? "" : identity.quoteId);
396
+ if (!salt) {
397
+ // THE QUOTE ID CAN SELECT THE RECORD, BUT IT CANNOT PROVE THE ORDER. Only a record that the caller named by the
398
+ // same quote id is this branch; an unrelated pending record must not block a new start.
399
+ return !quoteId || String(swap.orderQuoteId || "") === quoteId ? "salt-required" : "different";
400
+ }
401
+ return samePendingFunding(swap, identity) ? "resume" : "different";
402
+ }
403
+
404
+ // THE RECORD OF A SALE, FOUND BY ITS ESCROW. `sellWatch` is called from a reloaded page with the address in hand,
405
+ // so the window stored by `startSell` must be readable without a second argument. A record the store cannot read
406
+ // is not a reason to invent a local window; the caller gets the store's refusal at the point it matters.
407
+ function swapByEscrow(store, escrow) {
408
+ try {
409
+ const state = store.loadState();
410
+ const wanted = String(escrow || "").toLowerCase();
411
+ for (const swap of Object.values((state && state.swaps) || {})) {
412
+ if (swap && swap.escrow && String(swap.escrow.address || "").toLowerCase() === wanted) return swap;
413
+ }
414
+ } catch { /* the caller names the missing window */ }
415
+ return null;
416
+ }
417
+
418
+ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork = null, call = null, fetchImpl = null, now = null, sleep = null, evmBlock = null, store = engine.store,
419
+ // THE MONERO TIMINGS ARE BROUGHT BY THE CONFIGURATION: the watch's rate and timeout live in config.limits. There is
420
+ // no server step and no route table to consult.
388
421
  config = null,
389
- // 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
390
- // adapter (send/receipt): windows and message signatures remain the interface's. A READY pass arrives here (as
391
- // www/js/evm/auth.js, signIn obtains it today), and the core merely presents it.
392
- auth = null,
393
422
  // THE INTERFACE'S ADDRESS DENYLIST (issue #16), a Set of lower-cased addresses already assembled by the facade.
394
423
  // The check on the ACTUAL sender is done in start() below, ONE place, right before the send - the wallet adapter
395
424
  // only HANDS OUT the current account (`address()`), it does not carry the policy.
@@ -404,6 +433,40 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
404
433
  // substitute your own. Otherwise the lock step could not be checked beyond predicting the address - and "the address
405
434
  // from the receipt" would remain an argument on trust, not a verified property.
406
435
  const reader = typeof call === "function" ? call : engine.evm.readContract;
436
+ // A RELOADED RETRY DOES NOT CARRY THE ESCROW. It still carries the signed order quote and the order terms, so the
437
+ // same factory predict() the send would use can name the address before the pending row is compared. A missing
438
+ // quote or a failed read is a refusal by name, never permission to send a second deposit.
439
+ const predictedEscrowForRetry = async (request) => {
440
+ const quote = request && request.orderQuote;
441
+ const order = request && request.order;
442
+ if (!quote || typeof quote !== "object" || !quote.signature) return null;
443
+ const factory = (order && order.factory) || quote.factory;
444
+ if (!factory) return null;
445
+ const lockerHalf = {
446
+ commitHalfLocker: (order && order.commitHalfLocker) ?? quote.commitHalfLocker,
447
+ edPointLocker: (order && order.edPointLocker) ?? quote.edPointLocker,
448
+ edViewPointLocker: (order && order.edViewPointLocker) ?? quote.edViewPointLocker,
449
+ };
450
+ if (!lockerHalf.commitHalfLocker || !lockerHalf.edPointLocker || !lockerHalf.edViewPointLocker) return null;
451
+ try {
452
+ const raw = await reader({ to: factory, data: engine.evm.encodePredict({ ...quote, ...lockerHalf, factory }) });
453
+ return engine.evm.decodeAddress(raw);
454
+ } catch {
455
+ return null;
456
+ }
457
+ };
458
+ // THE INSTANCE TRANSPORT IS THE DEFAULT, NOT BACKGROUND MAGIC. A per-call `fetch` still wins; otherwise every
459
+ // network read made by this client (height probes, relay quote/claim, witness verification) uses `fetchImpl`.
460
+ const withDefaultFetch = (request) => (fetchImpl && request && typeof request === "object"
461
+ && typeof request.fetch !== "function" ? { ...request, fetch: fetchImpl } : request);
462
+ // THE SLOT CLOCK IS A SEAM. A real caller uses wall time and a timer; a check can advance both, so a 15-30 s
463
+ // slot is exercised without making the suite wait for it.
464
+ const clockMs = () => {
465
+ const value = typeof now === "function" ? Number(now()) : Date.now();
466
+ return Number.isFinite(value) ? value : Date.now();
467
+ };
468
+ const sleepFor = typeof sleep === "function" ? sleep
469
+ : (ms) => new Promise((resolve) => setTimeout(resolve, ms));
407
470
  // ONE BLOCK FOR THE SELL GATE. A block read is a seam like the contract read: `evmBlock` from the interface
408
471
  // wins, then the wallet's own provider. The number pins every escrow read below to the same state; the
409
472
  // timestamp is the chain's clock, not the device's.
@@ -430,10 +493,6 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
430
493
  // MARKING READY GOES THROUGH THE SAME READ SEAM as the lock: checking the slots and signing must go one way,
431
494
  // otherwise part of the check goes past the wallet and part does not (see actions.mjs).
432
495
  const actions = createActions({ call: typeof call === "function" ? call : null });
433
- const routeOf = (name, params) => {
434
- if (!config || typeof config.route !== "function") throw new SdkError("bad-input", { field: "config", step: "server" });
435
- return config.route(name, params);
436
- };
437
496
  const limitOf = (name, fallback) => {
438
497
  const value = config && config.limits ? config.limits[name] : null;
439
498
  return Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
@@ -448,7 +507,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
448
507
  const listed = Array.isArray(request.xmrNodes) ? request.xmrNodes
449
508
  : (config && typeof config.nodesFor === "function" ? config.nodesFor(moneroNetwork) : []);
450
509
  return startHeightFromNodes({ nodes: listed, network: moneroNetwork,
451
- fetchImpl: request.fetchImpl || (typeof fetch === "function" ? fetch : null) });
510
+ fetchImpl: request.fetchImpl || fetchImpl || (typeof fetch === "function" ? fetch : null) });
452
511
  }
453
512
  const records = () => {
454
513
  const state = store.loadState();
@@ -458,19 +517,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
458
517
  // A START THAT ENDED WITH A SENT TRANSACTION AND NO RECEIPT IS RESUMED, NOT RESENT. The transaction hash and the
459
518
  // predicted escrow are kept on the record; a retry of the same quote reads that receipt instead of building a
460
519
  // second side and sending a second deposit.
461
- const pendingFundingOf = (quoteId, salt) => {
462
- const id = String(quoteId || "");
463
- const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
464
- if (!id && !saltHex) return null;
465
- return records().find((swap) => {
466
- if (!(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
467
- if (id && String(swap.orderQuoteId || "") === id) return true;
468
- // THE RELAY ANSWER MAY CARRY NO ORDER ID. The salt is the client's own binding to the same escrow: it is
469
- // written into the terms and the predicted address is derived from it, so it identifies the pending record
470
- // without inventing an id or asking the factory again.
471
- const recordedSalt = String((swap.escrow && swap.escrow.salt) || swap.recoverySalt || "").replace(/^0x/i, "").toLowerCase();
472
- return Boolean(saltHex && recordedSalt === saltHex);
473
- }) || null;
520
+ const pendingFundingOf = (identity) => {
521
+ const salt = pendingSalt(identity && identity.salt);
522
+ const quoteId = String(identity && identity.quoteId !== undefined && identity.quoteId !== null ? identity.quoteId : "");
523
+ // WITHOUT EITHER HANDLE NOTHING CAN SELECT A RECORD. With a quote id the loop below can still name the record and
524
+ // refuse it as salt-required instead of silently starting a second deposit.
525
+ if (!salt && !quoteId) return null;
526
+ for (const swap of records()) {
527
+ const verdict = pendingFundingVerdict(swap, identity);
528
+ if (verdict === "salt-required") {
529
+ throw new SdkError("bad-input", { field: "recoverySalt", why: "required-for-pending-funding" });
530
+ }
531
+ if (verdict === "resume") return swap;
532
+ }
533
+ return null;
474
534
  };
475
535
  async function resumePendingFunding(record, request) {
476
536
  const swap = record.swap || record;
@@ -524,7 +584,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
524
584
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
525
585
  return { id: swap.id || null, escrow,
526
586
  address: (record.swapWallet && record.swapWallet.address) || null,
527
- step: "xmr-incoming", server: null, watch: null, next: "watch" };
587
+ step: "xmr-incoming", next: "watch" };
528
588
  }
529
589
  return { id: swap.id || null, escrow: escrowRecord.address || null,
530
590
  address: (record.swapWallet && record.swapWallet.address) || null,
@@ -589,104 +649,6 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
589
649
  return options;
590
650
  }
591
651
 
592
- /**
593
- * RECORDING THE SWAP WITH US. The path and body are the interface's (see the step description above). A refusal is
594
- * called by a CODE and carries the service's response in full: the connection never got through - server-unavailable,
595
- * the service answered and did not accept - server-refused (with the status and ITS reason). The code is named so the
596
- * interface itself decides whether to abort the swap: today it does not abort it (www/js/evm/auth.js:15-16), and that
597
- * is its decision, not the core's silence.
598
- */
599
- async function markOnServer(swap, escrow, order) {
600
- if (!http || typeof http.tryJson !== "function") throw new SdkError("bad-input", { field: "http", step: "mark" });
601
- const mark = markBodyOf(swap, escrow, order);
602
- // THE BROWSER SDK LINE IS PART OF THE BODY. The node's body routes read it before any work; a mark request
603
- // without it is refused as sdk-version-absent even though the swap is already funded.
604
- const body = JSON.stringify(Object.fromEntries(MARK_FIELDS.map((field) => [field, mark[field]])));
605
- const headers = { "content-type": "application/json" };
606
- // THE PASS IS ASKED EVERY TIME, NOT CACHED: it is short-lived (an hour: app/server.mjs, AUTH_TOKEN_TTL_MS), and a
607
- // cached pass would give a 401 at a step that does not move money itself but shows the swap to the service.
608
- if (typeof auth === "function") {
609
- let token = null;
610
- try { token = await auth(); } catch { token = null; }
611
- if (typeof token === "string" && token) headers.authorization = "Bearer " + token;
612
- }
613
- let answer = null;
614
- try { answer = await http.tryJson(routeOf("evmSwaps"), { method: "POST", headers, body }); }
615
- catch (error) { throw new SdkError("server-unavailable", { step: "mark", why: (error && error.code) || "fetch" }); }
616
- if (!answer || answer.ok !== true) {
617
- throw new SdkError("server-refused", {
618
- step: "mark", status: answer ? answer.status : null,
619
- why: (answer && answer.body && (answer.body.error || answer.body.detail)) || null,
620
- });
621
- }
622
- return { marked: true, httpStatus: answer.status, orderBinding: (answer.body && answer.body.orderBinding) || null };
623
- }
624
-
625
- /**
626
- * THE FACTORY WATCH RECORD with our service: by the same POST /api/swaps the page makes
627
- * (www/js/ui/views/confirm.js:581). The address and the VIEW KEY go out - that is enough to see incoming payments,
628
- * and not enough to spend them.
629
- */
630
- async function openWatch(swap, order) {
631
- if (!http || typeof http.tryJson !== "function") throw new SdkError("bad-input", { field: "http", step: "watch" });
632
- const e = (swap && swap.escrow) || {};
633
- const address = e.moneroAddress || (swap.swapWallet && swap.swapWallet.address) || null;
634
- if (!address) throw new SdkError("bad-input", { field: "moneroAddress" });
635
- // THE EXPECTED AMOUNT IS MANDATORY, and this is not a formality: without it the watch cannot check the sufficiency of
636
- // the arrival, and the app does not accept such a record (app/store.mjs:85-94). A refusal is more honest than a
637
- // silent record by which an underpayment would look like a completed swap.
638
- const expectedXmr = num(order && order.xmrAmount !== undefined ? order.xmrAmount : swap.xmrAmount);
639
- if (!(expectedXmr > 0)) throw new SdkError("bad-input", { field: "expectedAmountXmr" });
640
- const network = swap.moneroNetwork || xmrNetwork || null;
641
- if (!network) throw new SdkError("bad-input", { field: "moneroNetwork" });
642
- const restoreHeight = Number(swap.restoreHeight) > 0 ? Number(swap.restoreHeight)
643
- : (Number(e.moneroRestoreHeight) > 0 ? Number(e.moneroRestoreHeight) : null);
644
- if (!(restoreHeight > 0)) throw new SdkError("bad-input", { field: "restoreHeight", step: "watch" });
645
- const wanted = {
646
- swapId: swap.id || null, network, address, viewKey: jointViewKey(swap), expectedAmountXmr: expectedXmr,
647
- // THE RESTORE HEIGHT - THE MONERO HEIGHT, NEVER THE EVM BLOCK. It is measured before the file is handed
648
- // over and kept on the record; `birthHeight`/`evmBirthBlock` is a settlement-chain block for log search and
649
- // is far above any Monero tip, so using it here opened the watch nowhere near the money.
650
- restoreHeight,
651
- chain: swap.network || swap.chain || null,
652
- };
653
- const body = { sdkVersion: SDK_VERSION };
654
- for (const field of ALLOWED_SESSION_FIELDS) if (wanted[field] !== undefined && wanted[field] !== null) body[field] = wanted[field];
655
- // THE VIEW KEY IS NOT NEEDED BY THE SERVICE FOR THE DECISION ANY MORE: since the arrival is checked by the
656
- // client (verifyArrival), the backend may keep a watch only for notifications, and even that it can do from
657
- // the maker's txid. So sending the key is an OPTION: `watch.sendViewKeyToServer === false` drops it from the
658
- // record. The default keeps the current backend flow working until it stops deciding on its own.
659
- if (watchOptions && watchOptions.sendViewKeyToServer === false) delete body.viewKey;
660
- let answer = null;
661
- try { answer = await http.tryJson(routeOf("swaps"), { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); }
662
- catch (error) { throw new SdkError("server-unavailable", { step: "watch", why: (error && error.code) || "fetch" }); }
663
- if (!answer || answer.ok !== true) {
664
- throw new SdkError("server-refused", {
665
- step: "watch", status: answer ? answer.status : null,
666
- why: (answer && answer.body && (answer.body.error || answer.body.detail)) || null,
667
- });
668
- }
669
- const session = incomingOf(answer.body);
670
- if (!session) throw new SdkError("server-unavailable", { step: "watch", why: "bad-response" });
671
- return { registered: true, httpStatus: answer.status, ...session,
672
- expectedXmr: session.expectedXmr !== null ? session.expectedXmr : expectedXmr };
673
- }
674
-
675
- /** THE WATCH STATE: GET /api/swaps/{id} - the same path as the page's (chainSource.js:184). */
676
- async function readWatch(id) {
677
- if (!http || typeof http.tryJson !== "function") throw new SdkError("bad-input", { field: "http", step: "watch" });
678
- let answer = null;
679
- try { answer = await http.tryJson(routeOf("swap", { id }), { method: "GET" }); }
680
- catch (error) { throw new SdkError("server-unavailable", { step: "watch", why: (error && error.code) || "fetch" }); }
681
- if (!answer || answer.ok !== true) {
682
- throw new SdkError("server-refused", {
683
- step: "watch", status: answer ? answer.status : null, id,
684
- why: (answer && answer.body && (answer.body.error || answer.body.detail)) || null,
685
- });
686
- }
687
- return answer.body;
688
- }
689
-
690
652
  // A SELL SENDS XMR ONLY INTO AN ESCROW THE CHAIN ALREADY HOLDS. The relay answer proves the maker signed the
691
653
  // terms; it does not prove that the maker funded them. Read the escrow itself (code, status, slots and
692
654
  // deadlines), compare the slots with the halves this offer verified, and refuse before `send-xmr`.
@@ -824,42 +786,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
824
786
  return true;
825
787
  },
826
788
 
827
- /**
828
- * THE SERVICE'S SWAP LIST, MERGED INTO THE LOCAL ONE. The path and the body are the page's
829
- * (www/js/evm/auth.js, loadServerSwaps: GET /api/evm-swaps, the address ties the list to the wallet). The
830
- * merge rule is the ENGINE'S (core/swap.js, addServerSwaps): a local record always wins, the service only
831
- * adds what this browser does not have, and the rules are not written a second time here. The pass is
832
- * obtained by the interface and only presented by the core (the `auth` seam), so an unauthenticated call is
833
- * the service's own refusal with a code, not a silent empty list.
834
- */
835
- async sync() {
836
- if (!http || typeof http.tryJson !== "function") throw new SdkError("bad-input", { field: "http", step: "sync" });
837
- const headers = {};
838
- if (typeof auth === "function") {
839
- let token = null;
840
- try { token = await auth(); } catch { token = null; }
841
- if (typeof token === "string" && token) headers.authorization = "Bearer " + token;
842
- }
843
- let answer = null;
844
- try { answer = await http.tryJson(routeOf("evmSwaps"), { method: "GET", headers }); }
845
- catch (error) { throw new SdkError("server-unavailable", { step: "sync", why: (error && error.code) || "fetch" }); }
846
- if (!answer || answer.ok !== true) {
847
- throw new SdkError("server-refused", {
848
- step: "sync", status: answer ? answer.status : null,
849
- why: (answer && answer.body && (answer.body.error || answer.body.detail)) || null,
850
- });
851
- }
852
- // A GARBAGE ANSWER IS A REFUSAL, NOT AN EMPTY LIST: a non-JSON body (an SPA fallback, a proxy error page) must
853
- // not look like "the service has no swaps" - the two are different, and only one of them means "synced".
854
- const body = answer.body;
855
- if (!body || !Array.isArray(body.swaps)) throw new SdkError("server-unavailable", { step: "sync", why: "bad-response" });
856
- const added = engine.swap.addServerSwaps(body.swaps, store);
857
- return { ok: true, added, seen: body.swaps.length };
858
- },
859
-
860
789
  // THE ARRIVAL VERDICT WITHOUT THE WATCH LOOP, and the deadline check as a separate call: an interface may
861
790
  // want to run both itself. The watch uses exactly these, so there is one decision, not two.
862
- verifyArrival: (request) => xmrArrival.verifyArrival(request),
791
+ verifyArrival: (request) => xmrArrival.verifyArrival(withDefaultFetch(request)),
792
+ /**
793
+ * SHADOW THE FIXED-SLICE WITNESS WITHOUT CHANGING THE DECISION. It runs the exact check and the witness-v1
794
+ * slice check and returns both; `witnessNodes` must carry `{protocol: "witness-v1"}`. Nothing here opens
795
+ * `ready` or refunds. It exists so the protocol can be exercised before an independent operator serves it.
796
+ */
797
+ verifyArrivalShadow: (request) => xmrArrival.verifyArrivalShadow(withDefaultFetch(request)),
863
798
  assertTimeForConfirmations: (request) => xmrArrival.assertTimeForConfirmations(request),
864
799
 
865
800
  /**
@@ -873,16 +808,18 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
873
808
  * and found no matching transaction). `pending` with a transaction, `one-node`, and every failure to check are NOT
874
809
  * "no money": the helper refuses to sign, so a lagging or busy witness can never look like an empty address.
875
810
  *
876
- * IT FIRES ONLY WHEN LESS THAN THE CONFIRMATIONS' TIME IS LEFT before `readyBy`
877
- * (`minConfirmations * blockTimeSec`, overridable with `leadSec`): refunding earlier would abandon a maker who
878
- * still has time to deliver. The refund goes through the same action seam as the screen (actions.refund), and
879
- * the order expectations are mandatory.
811
+ * IT FIRES ONLY WHEN LESS THAN THE NODE'S REFUND LEAD IS LEFT before `readyBy` (`readyLeadSec` of the window
812
+ * stored with the record, overridable with `leadSec`): refunding earlier would abandon a maker who still has
813
+ * time to deliver. The lead is the window's own headroom, not the retired `minConfirmations * blockTimeSec`.
814
+ * The refund goes through the same action seam as the screen (actions.refund), and the order expectations are
815
+ * mandatory.
880
816
  *
881
817
  * The seams `deps.verify` / `deps.refund` / `deps.now` exist for the checks; in production they are the real
882
818
  * arrival check and the real refund.
883
819
  */
884
820
  async refundIfXmrMissing(request = {}, deps = {}) {
885
- const verify = typeof deps.verify === "function" ? deps.verify : xmrArrival.verifyArrival;
821
+ const verify = typeof deps.verify === "function" ? deps.verify
822
+ : (request) => xmrArrival.verifyArrival(withDefaultFetch(request));
886
823
  const refund = typeof deps.refund === "function" ? deps.refund : actions.refund;
887
824
  const nowOf = typeof deps.now === "function" ? deps.now : () => Math.floor(Date.now() / 1000);
888
825
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -911,10 +848,12 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
911
848
  if (!Number.isFinite(readyBy) || readyBy <= 0) throw new SdkError("bad-input", { field: "readyBySec" });
912
849
  const minConfirmations = Number.isFinite(Number(request.minConfirmations)) && Number(request.minConfirmations) > 0
913
850
  ? Math.trunc(Number(request.minConfirmations)) : limitOf("xmrConfirmations", 10);
914
- const blockTimeSec = Number.isFinite(Number(request.blockTimeSec)) && Number(request.blockTimeSec) > 0
915
- ? Number(request.blockTimeSec) : limitOf("xmrBlockTimeSec", 120);
916
851
  const leadSec = Number.isFinite(Number(request.leadSec)) && Number(request.leadSec) >= 0
917
- ? Number(request.leadSec) : minConfirmations * blockTimeSec;
852
+ ? Number(request.leadSec) : (() => {
853
+ const window = request.readyWindow || (swap && (swap.readyWindow || swap.sellWindow));
854
+ if (!window) throw new SdkError("bad-input", { field: "readyWindow", why: "not-in-record" });
855
+ return readyLeadSec(readReadyWindow(window, { field: "readyWindow" }));
856
+ })();
918
857
  // THE WALK STARTS AT THE SWAP'S BIRTH, NEVER AT GENESIS. A missing height used to become block 0, so a refund
919
858
  // check on a real chain would walk every block ever mined. The record carries the measured height; a caller
920
859
  // that has neither an explicit height nor a record height is refused rather than given a scan of the whole chain.
@@ -985,10 +924,44 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
985
924
 
986
925
  // RESUME BEFORE ANY NEW SIDE OR SEND. The previous start may have sent the deposit and lost the receipt;
987
926
  // reusing its hash is the only way to learn the escrow without a second payment.
988
- const quoteForResume = (request.orderQuote && request.orderQuote.id) || (request.quote && request.quote.id) || null;
989
927
  const saltForResume = request.recoverySalt || (request.order && request.order.salt) ||
990
928
  (request.orderQuote && request.orderQuote.salt) || null;
991
- const pendingRecord = pendingFundingOf(quoteForResume, saltForResume);
929
+ const resumeIdentity = {
930
+ salt: saltForResume,
931
+ // THE QUOTE ID IS ONLY A SELECTOR. It lets a salt-less retry name the pending row and be refused loudly, but
932
+ // it never replaces the salt/chain/factory/escrow proof below.
933
+ quoteId: (request.orderQuote && request.orderQuote.id) || (request.quote && request.quote.id) || null,
934
+ chainId: (request.order && request.order.chainId) ?? (request.orderQuote && request.orderQuote.chainId)
935
+ ?? (request.quote && request.quote.chainId),
936
+ factory: (request.order && request.order.factory) ?? (request.orderQuote && request.orderQuote.factory)
937
+ ?? (request.quote && request.quote.factory),
938
+ escrow: request.escrow || request.predictedEscrow || (request.quote && request.quote.escrow)
939
+ || (request.orderQuote && request.orderQuote.escrow) || null,
940
+ };
941
+ // A RELOADED RETRY HAS NO ESCROW FIELD. Find the pending row by the part it does have, then let the factory
942
+ // predict the address from the same signed terms the send uses. If that address cannot be named, the retry is
943
+ // refused by name; it must not fall through to a new deposit.
944
+ let pendingRecord = null;
945
+ if (records().some((swap) => samePendingBase(swap, resumeIdentity))) {
946
+ const predicted = await predictedEscrowForRetry(request);
947
+ if (!predicted) {
948
+ throw new SdkError("bad-input", { field: "escrow", why: "required-for-pending-funding" });
949
+ }
950
+ const named = pendingAddress(resumeIdentity.escrow);
951
+ if (resumeIdentity.escrow && !named) {
952
+ throw new SdkError("bad-input", { field: "escrow", why: "unreadable" });
953
+ }
954
+ if (named && named !== pendingAddress(predicted)) {
955
+ throw new SdkError("bad-input", { field: "escrow", why: "escrow-mismatch" });
956
+ }
957
+ resumeIdentity.escrow = predicted;
958
+ pendingRecord = pendingFundingOf(resumeIdentity);
959
+ if (!pendingRecord) {
960
+ throw new SdkError("bad-input", { field: "escrow", why: "pending-funding-unresolved" });
961
+ }
962
+ } else {
963
+ pendingRecord = pendingFundingOf(resumeIdentity);
964
+ }
992
965
  if (pendingRecord) {
993
966
  const resumed = await resumePendingFunding(pendingRecord, request);
994
967
  if (resumed) return resumed;
@@ -1110,6 +1083,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1110
1083
  // side comes from outside; in the sandbox the engine builds it as a stand-in, but on a live chain a stand-in would
1111
1084
  // mean the money goes against a non-existent side, so there it is a refusal.
1112
1085
  let record = made;
1086
+ // THE NODE'S WINDOW IS PART OF THE RECORD. It is read from the signed features and later decides how long a
1087
+ // sale may wait and when a depositor may still refund; a record without it is refused when that decision is
1088
+ // made, never filled with the old local constants.
1089
+ const readyWindowRaw = request.readyWindow || (request.quote && request.quote.readyWindow) || null;
1090
+ let readyWindow = null;
1091
+ if (readyWindowRaw) {
1092
+ readyWindow = readReadyWindow(readyWindowRaw, { side: "ask", field: "readyWindow" });
1093
+ record.swap.readyWindow = readyWindow;
1094
+ }
1113
1095
  // THE ORDER SIDE BUILT BY THE CORE STAYS UNTIL THE END OF THE START: the points and commitments for the lock terms
1114
1096
  // are taken from it - otherwise the record and the order would diverge, and the slot check against the chain would
1115
1097
  // go red (and rightly so). There is no second build of the side here.
@@ -1234,8 +1216,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1234
1216
  // THE CLOCK IS THE SDK'S OWN SEAM, IN MILLISECONDS, LIKE EVERY OTHER NOW IN THE FACADE.
1235
1217
  const nowMs = typeof now === "function" ? Number(now()) : Date.now();
1236
1218
  const nowSec = Math.floor(nowMs / 1000);
1237
- if (!Number.isSafeInteger(until) || !Number.isSafeInteger(nowSec) || until <= nowSec + 30) {
1238
- throw new SdkError("quote-expired", { validUntil: Number.isFinite(until) ? until : null, now: Number.isFinite(nowSec) ? nowSec : null, marginSec: 30, step: "lock" });
1219
+ // THE PREPARATION WAS ALREADY PAID FOR AT THE ANSWER. This check runs after the proof, the record and the
1220
+ // chain reads; requiring START_PREP_SEC again would refuse a quote that the answer accepted and spent those
1221
+ // seconds on. Only the next-block margin remains between here and the send.
1222
+ const life = quoteLifeVerdict({ validUntil: until, nowSec, side: "ask", prepSec: 0 });
1223
+ if (!life.ok) {
1224
+ throw new SdkError("quote-expired", {
1225
+ validUntil: Number.isFinite(until) ? until : null,
1226
+ now: Number.isFinite(nowSec) ? nowSec : null,
1227
+ remainingSec: life.remainingSec,
1228
+ marginSec: life.marginSec,
1229
+ prepSec: life.prepSec,
1230
+ confirmBySec: life.confirmBySec,
1231
+ step: "lock",
1232
+ });
1239
1233
  }
1240
1234
  }
1241
1235
  lockRequest.quote = request.orderQuote || null;
@@ -1283,7 +1277,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1283
1277
  return { id: record.swap.id || null, escrow: record.swap.escrow.address || null,
1284
1278
  address: (record.swapWallet && record.swapWallet.address) || null,
1285
1279
  step: "funding-pending", txHash: pendingTx,
1286
- reason: funded.pendingReason || "no-receipt", predictedEscrow: predicted, next: "receipt" };
1280
+ reason: funded.pendingReason || "no-receipt", predictedEscrow: predicted, next: "receipt",
1281
+ readyWindow };
1287
1282
  }
1288
1283
  // THE ESCROW ADDRESS IS TAKEN FROM THE RECEIPT (lock.send does this), not from a prediction. It is also written
1289
1284
  // into the swap: otherwise the progress screen and the explorer link would show an address that is not on the
@@ -1300,35 +1295,25 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1300
1295
  // THE SALT IS THE RECOVERY BINDING; there is no index reservation to commit here.
1301
1296
  }
1302
1297
 
1303
- // 5. A BACKEND IS OPTIONAL AND NEVER A DEFAULT. When the caller configured an API base, the swap is recorded
1304
- // there and the watch row is opened. Without one, the SDK returns the local state and the joint address: the
1305
- // caller watches the chain itself. The owner's rule: no request to the page's own origin.
1306
- let server = null;
1307
- let watch = null;
1308
- if (config && config.apiBase) {
1309
- server = await markOnServer(record.swap, escrowAddress, request.order);
1310
- watch = await openWatch(record.swap, request.order);
1311
- }
1298
+ // THE START ENDS AT THE JOINT ADDRESS. There is no backend step any more: the retired node routes are gone,
1299
+ // and the caller watches the chain through `swaps.watch` with its own node list.
1312
1300
  // THE STATE IS NAMED, NOT PASSED OFF AS COMPLETION: the swap reached exactly "waiting for XMR at the joint address",
1313
1301
  // and there is no arrival yet - `receivedXmr` is never implied by zero.
1314
1302
  return {
1315
1303
  id: record.swap.id || null,
1316
1304
  escrow: escrowAddress,
1317
- address: (watch && watch.address) || (record.swapWallet && record.swapWallet.address) || null,
1305
+ address: (record.swapWallet && record.swapWallet.address) || null,
1318
1306
  step: "xmr-incoming",
1319
- server,
1320
- watch,
1321
1307
  next: "watch",
1308
+ readyWindow,
1322
1309
  };
1323
1310
  },
1324
1311
 
1325
1312
  /**
1326
1313
  * WAIT FOR THE XMR TO ARRIVE AT THE JOINT ADDRESS - the whole point of opening the watch.
1327
1314
  *
1328
- * The CLIENT checks the arrival from the Monero nodes (`verify`); there is no backend poll by default. The rate
1329
- * and the timeout come from the configuration (config.limits.watchPollMs/watchTimeoutMs) and are overridable here.
1330
- * A caller that explicitly configured `apiBase` may still read the old watch row, but that row is only an
1331
- * observation: it never declares readiness or a decline.
1315
+ * The CLIENT checks the arrival from the Monero nodes (`verify`); there is no backend watcher. The rate and the
1316
+ * timeout come from the configuration (config.limits.watchPollMs/watchTimeoutMs) and are overridable here.
1332
1317
  * IT ARRIVED - we return the FACT (the amount, the confirmations, the txid); WE DID NOT WAIT - a refusal with the
1333
1318
  * code `xmr-timeout`, separate from the others, so "the wait expired" is confused with neither a breakdown nor an
1334
1319
  * empty response. XMR ON THE ADDRESS BUT BARRED BY unlock_time is a THIRD answer with its own code `xmr-locked`
@@ -1350,6 +1335,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1350
1335
  const wantWallet = request.wallet !== undefined && request.wallet !== null;
1351
1336
  if (wantExpect !== wantWallet) throw new SdkError("bad-input", { field: wantExpect ? "wallet" : "expect" });
1352
1337
  if (wantExpect && !(request.escrow || request.address)) throw new SdkError("bad-input", { field: "escrow" });
1338
+ const storedSwap = (() => { try { return engine.swap.getSwap(id, store); } catch { return null; } })();
1339
+ const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
1353
1340
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0 ? Number(request.pollMs) : limitOf("watchPollMs", 5000);
1354
1341
  const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
1355
1342
  // THE CONFIRMATION TARGET - FROM THE CONFIGURATION (one number, the owner's decision: 10).
@@ -1366,15 +1353,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1366
1353
  : null;
1367
1354
  // LESS TIME LEFT THAN THE CONFIRMATIONS TAKE - NAMED AND NOT STARTED (issue #85, the owner's decision).
1368
1355
  if (verifyRequest) {
1356
+ if (!readyWindowRaw) throw new SdkError("bad-input", { field: "readyWindow", why: "not-in-record" });
1357
+ const readyWindow = readReadyWindow(readyWindowRaw, { side: "ask", field: "readyWindow" });
1369
1358
  const readyBy = request.readyBySec !== undefined && request.readyBySec !== null ? Number(request.readyBySec)
1370
1359
  : (request.deadline && request.deadline.readyBy !== undefined ? Number(request.deadline.readyBy) : null);
1371
- if (readyBy) xmrArrival.assertTimeForConfirmations({ readyBySec: readyBy, nowSec: Math.floor(Date.now() / 1000), minConfirmations, blockTimeSec: limitOf("xmrBlockTimeSec", 120) });
1360
+ if (readyBy) xmrArrival.assertTimeForConfirmations({
1361
+ readyBySec: readyBy, nowSec: Math.floor(Date.now() / 1000), minConfirmations,
1362
+ blockTimeSec: limitOf("xmrBlockTimeSec", 120),
1363
+ minLeadSec: readyLateSec(readyWindow),
1364
+ });
1372
1365
  }
1373
- const hasBackend = Boolean(config && config.apiBase);
1374
- // THE WATCH DOES NOT CALL A BACKEND BY DEFAULT. The client-side arrival check needs the joint address, the view
1375
- // secret and the spend public key; without them, and without an explicitly configured backend, there is nothing
1376
- // to wait on. That is a named refusal, not a request to the page's own origin.
1377
- if (!verifyRequest && !hasBackend) throw new SdkError("bad-input", { field: "verify", why: "no-backend" });
1366
+ // THE WATCH IS A CLIENT-SIDE CHECK AND NOTHING ELSE. It needs the joint address, the joint view secret and
1367
+ // the spend public key. Without them there is nothing to wait on: a named refusal, not a request to the
1368
+ // page's own origin and not a fallback to a retired backend.
1369
+ if (!verifyRequest) throw new SdkError("bad-input", { field: "verify", why: "required" });
1378
1370
  const started = Date.now();
1379
1371
  // --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL (issue #40). -------------------------------------
1380
1372
  // A decline leaves the escrow `refunded`, so nothing in the state says "do not wait any longer": without
@@ -1382,13 +1374,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1382
1374
  // CLOSED and whose ETH is already back - or, worse, the app offers the recovery file and a manual refund
1383
1375
  // for money nobody can recover.
1384
1376
  //
1385
- // THE DECLINE IS ASKED WITH TWO INDEPENDENT SOURCES AND EITHER ONE ENDS THE WAIT:
1386
- // * THE CHAIN - the escrow's own `Declined` event, through the same log reader the rest of the core uses;
1387
- // * THE WIRE - the status the service answers with is an observation, not a decision; it never writes the
1388
- // decline.
1389
- // A CHAIN READ THAT FAILS is neither a decline nor a refusal of the swap: the wait goes on and the wire may
1390
- // still answer. What the chain read did is carried out with the result (`chain.checked` / `chain.error`), so
1391
- // a broken reader is visible instead of silent.
1377
+ // THE DECLINE IS READ FROM THE CHAIN: the escrow's own `Declined` event, through the same log reader the rest
1378
+ // of the core uses. A CHAIN READ THAT FAILS is neither a decline nor a refusal of the swap: the wait goes on,
1379
+ // and what the chain read did is carried out with the result (`chain.checked` / `chain.error`), so a broken
1380
+ // reader is visible instead of silent.
1392
1381
  // A STORAGE THAT CANNOT BE READ IS NOT A REASON TO REFUSE THE WAIT: the record is what makes the state
1393
1382
  // durable, and the escrow may also arrive in the request. The watch is not a new user of the store - and it
1394
1383
  // must not start failing where it did not before.
@@ -1420,7 +1409,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1420
1409
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "decline" }); }
1421
1410
  };
1422
1411
  // THE STATE THE WATCH REPORTS FOR A DECLINE: no arrival, the state's own code, the node's own token and
1423
- // WHERE it was seen ("event", "status", or "record" when it was already written down). NO reason, category
1412
+ // WHERE it was seen ("event" or "record" when it was already written down). NO reason, category
1424
1413
  // or provider travels here - the node names none, and the sentence a person reads is the interface's.
1425
1414
  const declineResult = ({ source, at, waitedMs, address, chainChecked, chainError }) => ({
1426
1415
  id,
@@ -1443,40 +1432,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1443
1432
  let last = null;
1444
1433
  for (;;) {
1445
1434
  await readDeclineLogs();
1446
- // THE CLIENT-SIDE CHECK DOES NOT ASK THE SERVICE. Only a watch without `verify` and with an explicitly
1447
- // configured backend reads the watch row.
1448
- const body = verifyRequest ? {} : await readWatch(id);
1449
- last = verifyRequest
1450
- ? { address: request.address || escrowAddress, expectedXmr: request.expectedXmr ?? null, status: null }
1451
- : incomingOf(body);
1435
+ last = { address: request.address || escrowAddress, expectedXmr: request.expectedXmr ?? null, status: null };
1452
1436
  // THE DECLINE IS THE ESCROW'S EVENT, NOT THE SERVICE'S WORD. The legacy backend's `declined` status used
1453
1437
  // to become a settlement and end the wait; it no longer does. A service answer is at most a notification.
1454
1438
  const declineNow = declineOf({ logs: chainDecline.logs, escrow: escrowAddress, at: Date.now() });
1455
1439
  if (declineNow.declined) {
1456
1440
  settleDecline(record, declineNow.at);
1457
1441
  return declineResult({ source: declineNow.source, at: declineNow.at, waitedMs: Date.now() - started,
1458
- address: body && body.address, chainChecked: chainDecline.checked, chainError: chainDecline.error });
1459
- }
1460
- // AN EMPTY OR FOREIGN RESPONSE IS NOT AN ARRIVAL: counting it as incoming would mean declaring money that was
1461
- // never seen. This is a named refusal, not "let us wait some more".
1462
- if (!last) throw new SdkError("server-unavailable", { step: "watch", why: "bad-response", id });
1463
- // XMR IS ON THE ADDRESS BUT LOCKED BY THE TRANSACTION'S unlock_time: a NAMED refusal, not "keep waiting".
1464
- // The ready mark hands the escrow to the maker; under funds that cannot be spent the maker would take the
1465
- // ETH and the XMR would stay locked (issue #84), so nothing is signed. The boundary is in `until`.
1466
- if (last.locked) {
1467
- const until = last.lockedUntil || {};
1468
- throw new SdkError("xmr-locked", { id, address: last.address, status: last.status,
1469
- expectedXmr: last.expectedXmr, receivedXmr: last.receivedXmr, lockedXmr: last.lockedXmr,
1470
- // The boundary goes as NUMBERS and their kind - a block height or unix seconds - never as text:
1471
- // turning them into a date the person reads is the interface's dictionary (www/js/sdk/codes.js).
1472
- untilHeight: until.untilHeight ?? null, untilTime: until.untilTime ?? null,
1473
- waitedMs: Date.now() - started });
1442
+ address: last && last.address, chainChecked: chainDecline.checked, chainError: chainDecline.error });
1474
1443
  }
1475
1444
  // THE CLIENT'S OWN ANSWER COMES FIRST AND DECIDES. The backend's `seen` may still be false (it no longer
1476
1445
  // holds the view key), so it is not consulted when the client verifies. A disagreement or locked money
1477
1446
  // throws its own code above and closes the button; one operator / few confirmations name a WAITING state.
1478
1447
  if (verifyRequest) {
1479
- const verdict = await xmrArrival.verifyArrival({ ...verifyRequest, nowSec: Math.floor(Date.now() / 1000) });
1448
+ const verdict = await xmrArrival.verifyArrival(withDefaultFetch({ ...verifyRequest, nowSec: Math.floor(Date.now() / 1000) }));
1480
1449
  last.verify = verdict;
1481
1450
  if (!verdict.seen) {
1482
1451
  if (Date.now() - started >= timeoutMs) {
@@ -1499,28 +1468,14 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1499
1468
  }
1500
1469
  return verified;
1501
1470
  }
1502
- if (last.seen) {
1503
- // THE SERVICE MAY OBSERVE MONEY, BUT IT DOES NOT DECLARE AN ARRIVAL. Readiness hands a foreign address
1504
- // the settlement, and only the client's own two-node check may do that. The observation is returned with
1505
- // `seen: false` and the next step named; no mark is ever signed from this body.
1506
- return { seen: false, observed: { id: last.id, address: last.address, status: last.status,
1507
- expectedXmr: last.expectedXmr, receivedXmr: last.receivedXmr, confirmations: last.confirmations,
1508
- txids: last.txids }, id, address: last.address, expectedXmr: last.expectedXmr,
1509
- next: "verify", source: "service" };
1510
- }
1511
- if (Date.now() - started >= timeoutMs) {
1512
- throw new SdkError("xmr-timeout", { id, address: last.address, expectedXmr: last.expectedXmr,
1513
- receivedXmr: last.receivedXmr, confirmations: last.confirmations, waitedMs: Date.now() - started,
1514
- timeoutMs, pollMs });
1515
- }
1516
- await new Promise((resolve) => setTimeout(resolve, pollMs));
1517
1471
  }
1518
1472
  },
1519
1473
 
1520
1474
  /**
1521
1475
  * START A SELL FROM A VERIFIED RELAY OFFER. The offer is the result of `quotes.firmRelay` for the bid side;
1522
- * the record keeps the one-time address, the escrow, our half and the order expectations, so a reload can
1523
- * continue with `get` + `sellWatch` + `sellClaim`. This method sends nothing.
1476
+ * the record keeps the one-time address, the escrow, our half, the order expectations and the relay origin, so a
1477
+ * reload can continue with `get` + `sellWatch` + `sellClaim`. The optional `claimSender` is a legacy
1478
+ * single-sender fallback; `claimViaRelay` takes the client's ordered list at claim time. This method sends nothing.
1524
1479
  */
1525
1480
  async startSell(request) {
1526
1481
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -1531,6 +1486,16 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1531
1486
  if (!order || !quote) throw new SdkError("bad-input", { field: "offer", missing: ["order", "quote"] });
1532
1487
  if (typeof offer.jointAddress !== "string" || !offer.jointAddress) throw new SdkError("bad-input", { field: "offer.jointAddress" });
1533
1488
  if (typeof offer.escrow !== "string" || !offer.escrow) throw new SdkError("bad-input", { field: "offer.escrow" });
1489
+ // THE RELAY ORIGIN IS PART OF THE OFFER. It is stored with the record so a later claim goes back to the relay
1490
+ // that answered this quote; an origin that is present but not https is refused here, not at claim time.
1491
+ const offerRelay = offer.relayUrl === undefined || offer.relayUrl === null || offer.relayUrl === ""
1492
+ ? null : relayOriginOf(offer.relayUrl);
1493
+ // THE NODE'S WINDOW IS PART OF THE OFFER. `firmRelay` took it from the signed features; a hand-built offer
1494
+ // without one is stored as null, and `sellWatch`/`refundIfXmrMissing` refuse by name instead of using the
1495
+ // old local 1200 s or 20-minute numbers.
1496
+ const offerWindowRaw = offer.readyWindow || (quote && quote.readyWindow) || null;
1497
+ const offerWindow = offerWindowRaw
1498
+ ? readReadyWindow(offerWindowRaw, { side: "bid", field: "offer.readyWindow" }) : null;
1534
1499
  // THE RECORD'S ROLE IS THE BID ROLE. The node is the locker and the person is the claimer; a quote whose
1535
1500
  // addresses or factory disagree with the order is not the offer this record describes.
1536
1501
  const sameValue = (a, b) => String(a || "").replace(/^0x/, "").toLowerCase() === String(b || "").replace(/^0x/, "").toLowerCase();
@@ -1539,6 +1504,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1539
1504
  || !sameValue(quote.factory, order.factory) || Number(quote.chainId) !== Number(order.chainId)) {
1540
1505
  throw new SdkError("quote-refused", { step: "sell-record", why: "terms" });
1541
1506
  }
1507
+ // THE SENDER IS CHOSEN BY THE CLIENT, NOT THE DEAL'S MAKER. The record keeps it so a reload claims through
1508
+ // the same node; a sender naming the maker or the quote key owner would reveal the half to the party that
1509
+ // must never receive it.
1510
+ const dealMaker = addressTextOf(quote.provider, "provider");
1511
+ const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1512
+ || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1513
+ const requestedSender = request.claimSender === undefined || request.claimSender === null
1514
+ || String(request.claimSender).trim() === "" ? null : addressTextOf(request.claimSender, "claimSender");
1515
+ if (requestedSender && requestedSender === dealMaker) {
1516
+ throw new SdkError("bad-input", { field: "claimSender", why: "is-deal-maker" });
1517
+ }
1518
+ if (requestedSender && quoteKeyOwner && requestedSender === quoteKeyOwner) {
1519
+ throw new SdkError("bad-input", { field: "claimSender", why: "is-quote-key" });
1520
+ }
1542
1521
  // THE RECORD IS FOUND BEFORE A SECOND ONE IS MADE. The same offer retried after a reload yields the same
1543
1522
  // one-time address and escrow; a second record would be a second promise about one deal.
1544
1523
  const quoteId = quote.id || quote.nonce || null;
@@ -1555,11 +1534,46 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1555
1534
  || !same(existing.escrow && existing.escrow.moneroAddress, offer.jointAddress)) {
1556
1535
  throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
1557
1536
  }
1537
+ const storedSender = existing.claimSender ? addressTextOf(existing.claimSender, "claimSender") : null;
1538
+ // THE OLD SCALAR IS NOT A PIN. A reload may name another sender or bring the ordered list at claim time; the
1539
+ // record keeps the latest scalar only for callers that still use it.
1540
+ if (requestedSender && requestedSender !== storedSender) {
1541
+ existing.claimSender = requestedSender;
1542
+ delete existing.claimSenders;
1543
+ try { engine.swap.saveSwap(existing, store); }
1544
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
1545
+ }
1546
+ // THE RELAY IS PART OF THE VERIFIED OFFER. A claim later goes to the origin that answered this quote, so
1547
+ // a resumed offer naming another origin is a different offer; one that now names the same origin fills a
1548
+ // record made before the origin was kept.
1549
+ const storedRelay = existing.relayUrl ? relayOriginOf(existing.relayUrl) : null;
1550
+ if (offerRelay && storedRelay && offerRelay !== storedRelay) {
1551
+ throw new SdkError("quote-refused", { step: "sell-record", why: "relay-changed" });
1552
+ }
1558
1553
  await sellEscrowGate((existing.escrow && existing.escrow.address) || offer.escrow, existing.expect || null, request.wallet);
1554
+ if (offerRelay && !storedRelay) {
1555
+ existing.relayUrl = offerRelay;
1556
+ try { engine.swap.saveSwap(existing, store); }
1557
+ catch { throw new SdkError("storage-unavailable", { step: "save-relay" }); }
1558
+ }
1559
+ const storedWindow = existing.readyWindow || existing.sellWindow || null;
1560
+ if (offerWindow && storedWindow) {
1561
+ const a = readReadyWindow(storedWindow, { side: "bid", field: "readyWindow" });
1562
+ if (a.readyMinSeconds !== offerWindow.readyMinSeconds || a.readyMaxSeconds !== offerWindow.readyMaxSeconds) {
1563
+ throw new SdkError("quote-refused", { step: "sell-record", why: "window-changed" });
1564
+ }
1565
+ }
1566
+ if (offerWindow && !storedWindow) {
1567
+ existing.readyWindow = offerWindow;
1568
+ try { engine.swap.saveSwap(existing, store); }
1569
+ catch { throw new SdkError("storage-unavailable", { step: "save-window" }); }
1570
+ }
1559
1571
  return { id: existing.id, side: "sell", escrow: (existing.escrow && existing.escrow.address) || offer.escrow,
1560
1572
  address: (existing.escrow && existing.escrow.moneroAddress) || offer.jointAddress,
1561
1573
  xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
1562
1574
  claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
1575
+ claimSender: existing.claimSender || null,
1576
+ readyWindow: existing.readyWindow || existing.sellWindow || null,
1563
1577
  resumed: true, next: "send-xmr" };
1564
1578
  }
1565
1579
  const storage = store.storage();
@@ -1628,6 +1642,9 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1628
1642
  swap.orderQuote = offer.orderQuote || null;
1629
1643
  swap.quote = quote;
1630
1644
  swap.claimTip = quote.claimTip || null;
1645
+ // THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping it means a reload cannot silently
1646
+ // send the half to a different node than the one the client selected.
1647
+ if (requestedSender) swap.claimSender = requestedSender;
1631
1648
  swap.expect = {
1632
1649
  chainId, factory: order.factory, locker: order.locker, claimer: order.claimer, amount: String(order.amount),
1633
1650
  readyBy: order.readyBy, t1: order.t1, salt: order.salt,
@@ -1647,6 +1664,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1647
1664
  commitHalfLocker: (offer.nodeHalf && offer.nodeHalf.commitHalf) || null,
1648
1665
  orderContext: offer.context || null, xmrAmount: quote.xmrAmount || null,
1649
1666
  };
1667
+ // KEPT WITH THE RECORD, NOT BUILT LATER: the claim and the watch use the relay and window that signed this
1668
+ // offer, not a value the page chose after the quote.
1669
+ if (offerRelay) swap.relayUrl = offerRelay;
1670
+ if (offerWindow) swap.readyWindow = offerWindow;
1650
1671
  // THE RECORD IS NOT A RECEIPT FOR A GATE THAT FAILED. createRecord has already written it, so a refusal
1651
1672
  // from the escrow/deadline/slot gate must remove it again; otherwise the interface lists send-xmr for an
1652
1673
  // order the SDK never checked.
@@ -1659,7 +1680,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1659
1680
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1660
1681
  return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
1661
1682
  xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
1662
- resumed: false, next: "send-xmr" };
1683
+ claimSender: swap.claimSender || null,
1684
+ readyWindow: swap.readyWindow || null, resumed: false, next: "send-xmr" };
1663
1685
  },
1664
1686
 
1665
1687
  /**
@@ -1682,6 +1704,188 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1682
1704
  expect, onStep: request.onStep }, wallet);
1683
1705
  },
1684
1706
 
1707
+ /**
1708
+ * CLAIM THE ETH ON A SELL WITHOUT A WALLET.
1709
+ *
1710
+ * The seller holds XMR and no ETH, so the escrow pays the signed `claimTip` to whoever submits the claim.
1711
+ * `claimSenders` is the client's ordered list: the relay's own sender first, then the listed makers. The SDK
1712
+ * sends the half to one sender at a time through `POST /v1/claims/{sender}/{escrow}`; a refusal moves on at once,
1713
+ * a txid or unknown answer is followed by reading the escrow for the rest of that sender's 15-30 s slot, and
1714
+ * only `claimed` on chain is success. An exhausted list returns `state: "claim-yourself"` with the time left
1715
+ * before `t1`. The deal's maker and its quote-key owner are refused before the half leaves the client. This
1716
+ * method never creates or uses a wallet and never signs a chain transaction; `sellClaim` remains that path.
1717
+ */
1718
+ async claimViaRelay(request = {}) {
1719
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1720
+ const id = String(request.id === undefined || request.id === null ? "" : request.id).trim();
1721
+ if (!id) throw new SdkError("bad-input", { field: "id" });
1722
+ let swap = null;
1723
+ try { swap = engine.swap.getSwap(id, store); } catch { swap = null; }
1724
+ if (!swap || swap.side !== "sell") throw new SdkError("bad-input", { field: "id", why: "sell-not-found" });
1725
+
1726
+ // THE TIP PAYS THE SENDER. A zero tip is not a claim the relay can make: the node would pay the gas for
1727
+ // nothing, and the request would be refused after the half had already left the client. Refuse here.
1728
+ let tip = 0n;
1729
+ try { tip = BigInt(swap.claimTip === undefined || swap.claimTip === null || swap.claimTip === "" ? 0 : swap.claimTip); }
1730
+ catch { throw new SdkError("bad-input", { field: "claimTip", why: "unreadable" }); }
1731
+ if (tip <= 0n) throw new SdkError("bad-input", { field: "claimTip", why: "not-positive" });
1732
+
1733
+ // THE DEAL'S MAKER IS THE ONE PARTY THAT MUST NOT RECEIVE THE HALF. It is the quote's provider and, on a
1734
+ // sell, the order's locker. The sender is a different node, chosen by the client; a record with no sender
1735
+ // cannot be claimed through a guess.
1736
+ const quote = swap.quote && typeof swap.quote === "object" ? swap.quote : {};
1737
+ const order = swap.order && typeof swap.order === "object" ? swap.order : {};
1738
+ const escrowRecord = swap.escrow && typeof swap.escrow === "object" ? swap.escrow : {};
1739
+ const makerRaw = quote.provider !== undefined && quote.provider !== null ? quote.provider
1740
+ : (escrowRecord.providerId !== undefined && escrowRecord.providerId !== null ? escrowRecord.providerId : order.locker);
1741
+ if (makerRaw === undefined || makerRaw === null || makerRaw === "") {
1742
+ throw new SdkError("bad-input", { field: "provider", why: "not-in-record" });
1743
+ }
1744
+ const maker = addressTextOf(makerRaw, "provider");
1745
+ for (const [field, value] of [["order.locker", order.locker], ["quote.locker", quote.locker]]) {
1746
+ if (value !== undefined && value !== null && String(value) !== "") {
1747
+ if (addressTextOf(value, field) !== maker) {
1748
+ throw new SdkError("quote-refused", { step: "relay-claim", why: "provider" });
1749
+ }
1750
+ }
1751
+ }
1752
+ const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1753
+ || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1754
+ const storedSenderRaw = swap.claimSender === undefined || swap.claimSender === null
1755
+ || String(swap.claimSender).trim() === "" ? null : swap.claimSender;
1756
+ const requestedSenderRaw = request.claimSender === undefined || request.claimSender === null
1757
+ || String(request.claimSender).trim() === "" ? null : request.claimSender;
1758
+ // THE ORDER IS THE CLIENT'S, NOT THE RECORD'S. A list passed now wins; the old scalar and the stored value are
1759
+ // only one-element fallbacks for callers written before the list existed. Neither is a pin: the next sender is
1760
+ // tried when this one refuses or its slot ends.
1761
+ if (request.claimSenders !== undefined && !Array.isArray(request.claimSenders)) {
1762
+ throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
1763
+ }
1764
+ const explicitList = Array.isArray(request.claimSenders) ? request.claimSenders : null;
1765
+ if (explicitList && explicitList.length === 0) {
1766
+ throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1767
+ }
1768
+ if (explicitList && requestedSenderRaw) {
1769
+ throw new SdkError("bad-input", { field: "claimSenders", why: "with-claim-sender" });
1770
+ }
1771
+ const rawSenders = explicitList || (requestedSenderRaw ? [requestedSenderRaw] : null)
1772
+ || (Array.isArray(swap.claimSenders) ? swap.claimSenders : null)
1773
+ || (storedSenderRaw ? [storedSenderRaw] : []);
1774
+ if (!rawSenders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
1775
+ const senders = [];
1776
+ for (const raw of rawSenders) {
1777
+ if (raw === undefined || raw === null || String(raw).trim() === "") {
1778
+ throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1779
+ }
1780
+ const sender = addressTextOf(raw, "claimSenders");
1781
+ if (sender === maker) throw new SdkError("bad-input", { field: "claimSenders", why: "is-deal-maker" });
1782
+ if (quoteKeyOwner && sender === quoteKeyOwner) {
1783
+ throw new SdkError("bad-input", { field: "claimSenders", why: "is-quote-key" });
1784
+ }
1785
+ if (!senders.includes(sender)) senders.push(sender);
1786
+ }
1787
+ if (!senders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
1788
+ if (escrowRecord.address === undefined || escrowRecord.address === null || escrowRecord.address === "") {
1789
+ throw new SdkError("bad-input", { field: "escrow", why: "not-in-record" });
1790
+ }
1791
+ const escrow = addressTextOf(escrowRecord.address, "escrow");
1792
+ const halfClaimer = halfTextOf(escrowRecord.half);
1793
+ // THE ORIGIN IS THE QUOTE'S, NOT THE CALLER'S. The record stores the relay that answered; a request may
1794
+ // repeat it (with a trailing slash), but may not choose another one after the quote.
1795
+ if (swap.relayUrl === undefined || swap.relayUrl === null || swap.relayUrl === "") {
1796
+ throw new SdkError("bad-input", { field: "relayUrl", why: "not-in-record" });
1797
+ }
1798
+ const relayUrl = relayOriginOf(swap.relayUrl);
1799
+ if (request.relayUrl !== undefined && request.relayUrl !== null && String(request.relayUrl).trim() !== "") {
1800
+ if (relayOriginOf(request.relayUrl) !== relayUrl) {
1801
+ throw new SdkError("bad-input", { field: "relayUrl", why: "foreign-relay" });
1802
+ }
1803
+ }
1804
+ // A LIST IS NOT A PIN. It is saved only as the fallback for a reload whose caller no longer has the relay's
1805
+ // answer; a later request that brings its own order ignores it.
1806
+ if (!Array.isArray(swap.claimSenders) || swap.claimSenders.length !== senders.length
1807
+ || swap.claimSenders.some((value, index) => String(value).toLowerCase() !== senders[index])) {
1808
+ swap.claimSenders = senders;
1809
+ swap.claimSender = senders[0];
1810
+ try { engine.swap.saveSwap(swap, store); }
1811
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1812
+ }
1813
+
1814
+ const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
1815
+ ? Number(request.timeoutMs) : 20_000;
1816
+ // ONE SENDER AT A TIME, EACH WITH ITS OWN SLOT. Refusal moves on immediately; an accepted/unknown answer is
1817
+ // followed by reading the escrow until it says claimed or the slot ends. A txid alone is never success.
1818
+ const slotMs = Number.isFinite(Number(request.slotMs)) && Number(request.slotMs) > 0
1819
+ ? Math.min(30_000, Math.max(15_000, Number(request.slotMs))) : 20_000;
1820
+ const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
1821
+ ? Math.min(slotMs, Number(request.pollMs)) : 2_000;
1822
+ const readStatus = async () => {
1823
+ try { return await flow.orderStatus(escrow, { call: reader }); } catch { return null; }
1824
+ };
1825
+ const t1Raw = order.t1 ?? (swap.expect && swap.expect.t1);
1826
+ const t1 = Number.isSafeInteger(Number(t1Raw)) && Number(t1Raw) > 0 ? Number(t1Raw) : null;
1827
+ const secondsLeft = () => (t1 === null ? null : Math.max(0, t1 - Math.floor(clockMs() / 1000)));
1828
+ const claimedByEscrow = (sender = null, answer = null, tried = []) => ({
1829
+ id, state: "claimed", provider: sender, claimSender: sender, escrow, relayUrl,
1830
+ txid: answer ? answer.txid : null, from: (answer && answer.from) || null,
1831
+ tipWei: (answer && answer.tipWei) || tip.toString(), tried,
1832
+ });
1833
+ // A CLAIM THAT ALREADY LANDED IS NOT A REASON TO SEND THE HALF AGAIN. The caller may have lost the answer on
1834
+ // the previous attempt; read the escrow before the first POST, and read it once more before returning
1835
+ // `claim-yourself`, so a late claim cannot be reported as "claim yourself".
1836
+ const initial = await readStatus();
1837
+ if (initial && initial.isClaimed) return claimedByEscrow();
1838
+ let refunded = Boolean(initial && initial.isRefunded);
1839
+ const tried = [];
1840
+ if (!refunded) for (const sender of senders) {
1841
+ let answer = null;
1842
+ let failure = null;
1843
+ try {
1844
+ answer = await postRelayClaim({
1845
+ relayUrl, provider: sender, escrow, halfClaimer, expectedTipWei: tip,
1846
+ fetchImpl: request.fetchImpl || fetchImpl || null, timeoutMs,
1847
+ });
1848
+ } catch (error) {
1849
+ failure = error;
1850
+ }
1851
+ // A REFUSAL IS THE SENDER'S ANSWER, NOT A CLAIM IN FLIGHT. Move to the next one at once; only an unknown
1852
+ // outcome (or a txid, which is not yet a claim on chain) deserves the slot.
1853
+ if (failure && failure.code !== "claim-unknown") {
1854
+ tried.push({ sender, outcome: "refused", code: failure.code || "unknown",
1855
+ params: failure.params || null });
1856
+ continue;
1857
+ }
1858
+ const slotEnd = clockMs() + slotMs;
1859
+ for (;;) {
1860
+ const status = await readStatus();
1861
+ if (status && status.isClaimed) {
1862
+ swap.claimSender = sender;
1863
+ try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
1864
+ return claimedByEscrow(sender, answer, tried);
1865
+ }
1866
+ if (status && status.isRefunded) { refunded = true; break; }
1867
+ const left = slotEnd - clockMs();
1868
+ if (left <= 0) break;
1869
+ await sleepFor(Math.min(pollMs, left));
1870
+ }
1871
+ tried.push({ sender, outcome: failure ? "unknown" : "unconfirmed",
1872
+ txid: answer ? answer.txid : null, code: failure ? failure.code : null });
1873
+ if (refunded) break;
1874
+ }
1875
+
1876
+ // THE LAST LOOK BEFORE THE FALLBACK. A claim can land after the last slot ended or while a later sender is
1877
+ // refusing; the seller must not be sent to `sellClaim` on an escrow that is already closed as claimed.
1878
+ const finalStatus = await readStatus();
1879
+ if (finalStatus && finalStatus.isClaimed) {
1880
+ try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
1881
+ return claimedByEscrow(null, null, tried);
1882
+ }
1883
+ if (finalStatus && finalStatus.isRefunded) refunded = true;
1884
+ return { id, state: "claim-yourself", reason: refunded ? "escrow-refunded" : "senders-exhausted",
1885
+ provider: null, claimSender: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
1886
+ t1, secondsLeft: secondsLeft(), tried };
1887
+ },
1888
+
1685
1889
  /**
1686
1890
  * WAIT FOR THE NODE'S SIDE ON A SELL. The client sends XMR to the one-time joint address; the node (the
1687
1891
  * locker) must mark the order ready before the claimer can take the ETH. This reads the escrow itself - no
@@ -1691,18 +1895,27 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1691
1895
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1692
1896
  const escrow = String(request.escrow || "").trim();
1693
1897
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
1694
- // THE WAIT IS BOUNDED BY THE ORDER'S OWN READY DEADLINE, NOT BY A FIXED 20 MINUTES. Ten confirmations
1695
- // average about twenty minutes, so the old default timed out roughly half of honest sales. A request may
1696
- // still set an explicit timeout; otherwise the wait covers the remaining time to readyBy plus a margin.
1898
+ // THE NODE'S WINDOW IS READ FROM THE RECORD BY THE ESCROW. A reload keeps only the address in hand; the
1899
+ // stored `startSell` record carries the range the maker signed, so the wait is not the old fixed 20 minutes.
1900
+ const storedSwap = swapByEscrow(store, escrow);
1901
+ const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
1697
1902
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
1698
1903
  ? Number(request.pollMs) : limitOf("watchPollMs", 6_000);
1699
- let timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
1700
- ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
1701
- if (!(Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0)) {
1904
+ const explicitTimeout = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0;
1905
+ const readyWindow = !explicitTimeout && readyWindowRaw
1906
+ ? readReadyWindow(readyWindowRaw, { side: "bid", field: "readyWindow" }) : null;
1907
+ if (!readyWindow && !explicitTimeout) {
1908
+ throw new SdkError("bad-input", { field: "readyWindow", why: "not-in-record" });
1909
+ }
1910
+ let timeoutMs = explicitTimeout ? Number(request.timeoutMs) : null;
1911
+ if (!explicitTimeout) {
1702
1912
  try {
1703
1913
  const deadlines = await flow.orderDeadlines(escrow, { call: reader });
1704
- timeoutMs = sellWatchTimeoutMs({ configuredMs: timeoutMs, readyBySec: deadlines.readyBy });
1705
- } catch { /* no deadline read: keep the configured wait */ }
1914
+ timeoutMs = sellWatchTimeoutMs({ configuredMs: readyWindowMs(readyWindow), readyBySec: deadlines.readyBy });
1915
+ } catch {
1916
+ // NO DEADLINE READ: the node's own maximum horizon is the bound, not a second local 20-minute number.
1917
+ timeoutMs = readyWindowMs(readyWindow);
1918
+ }
1706
1919
  }
1707
1920
  // THE CLAIM OPENS AT readyBy WITHOUT A MARK. The deadline comes from the escrow once; the clock is the
1708
1921
  // facade's own millisecond seam, so a simulation and a caller that controls time agree with the rest of