@ninsei-labs/sdk 0.57.2 → 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 (46) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +64 -27
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/assets/vendors/MANIFEST.json +1 -9
  5. package/assets/vendors/sdk/sdk-browser.js +4 -4
  6. package/engine/core/config.js +3 -22
  7. package/engine/core/rfqSource.js +6 -133
  8. package/engine/core/swap.js +1 -1
  9. package/engine/evm/index.js +3 -2
  10. package/engine/evm/session.js +46 -277
  11. package/engine/monero/address.js +15 -33
  12. package/engine/monero/keys.js +124 -0
  13. package/engine/monero/mnemonic.js +104 -0
  14. package/engine/monero/scan.js +23 -9
  15. package/engine/monero/wallet.js +31 -68
  16. package/engine/monero/wordlist.en.js +210 -0
  17. package/engine/recovery/restore.js +1 -1
  18. package/engine/sdk/bridge.js +7 -182
  19. package/engine/ui/walletModal.js +7 -27
  20. package/index.d.ts +187 -252
  21. package/package.json +4 -5
  22. package/src/codes.mjs +12 -0
  23. package/src/config.mjs +16 -54
  24. package/src/engine.mjs +3 -0
  25. package/src/index.mjs +24 -45
  26. package/src/order.mjs +2 -2
  27. package/src/public/recovery.d.ts +17 -1
  28. package/src/public/recovery.mjs +1 -0
  29. package/src/quotePolicy.mjs +25 -0
  30. package/src/quotes.mjs +21 -751
  31. package/src/readyWindow.mjs +76 -0
  32. package/src/recovery-key.mjs +39 -2
  33. package/src/recovery.mjs +11 -28
  34. package/src/relayClaim.mjs +132 -0
  35. package/src/relayFirmClient.mjs +3 -0
  36. package/src/relayQuote.mjs +5 -1
  37. package/src/swap-flow.mjs +49 -5
  38. package/src/swaps.mjs +301 -307
  39. package/src/sweep-action.mjs +73 -0
  40. package/src/sweep.mjs +7 -1
  41. package/src/version.mjs +1 -1
  42. package/src/xmr-arrival.mjs +275 -7
  43. package/src/xmrAmountPolicy.mjs +35 -0
  44. package/assets/vendors/monero/monero-js-browser.js +0 -58
  45. package/assets/vendors/monero-js/LICENSE +0 -9
  46. 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 { 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
@@ -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,7 +266,7 @@ 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),
331
271
  // WHERE TO WITHDRAW XMR: part of the record, not a detail of the screen - the progress screen exports the file by it.
332
272
  receiveAddress: pass(request.receiveTo),
@@ -381,15 +321,53 @@ export function sellWatchTimeoutMs({ configuredMs = 1_200_000, readyBySec = null
381
321
  return Math.max(configured, (readyAt - now + SELL_WATCH_MARGIN_SEC) * 1000);
382
322
  }
383
323
 
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.
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.
388
370
  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
371
  // THE INTERFACE'S ADDRESS DENYLIST (issue #16), a Set of lower-cased addresses already assembled by the facade.
394
372
  // The check on the ACTUAL sender is done in start() below, ONE place, right before the send - the wallet adapter
395
373
  // only HANDS OUT the current account (`address()`), it does not carry the policy.
@@ -430,10 +408,6 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
430
408
  // MARKING READY GOES THROUGH THE SAME READ SEAM as the lock: checking the slots and signing must go one way,
431
409
  // otherwise part of the check goes past the wallet and part does not (see actions.mjs).
432
410
  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
411
  const limitOf = (name, fallback) => {
438
412
  const value = config && config.limits ? config.limits[name] : null;
439
413
  return Number.isFinite(Number(value)) && Number(value) > 0 ? Number(value) : fallback;
@@ -462,15 +436,14 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
462
436
  const id = String(quoteId || "");
463
437
  const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
464
438
  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;
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;
474
447
  };
475
448
  async function resumePendingFunding(record, request) {
476
449
  const swap = record.swap || record;
@@ -524,7 +497,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
524
497
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-escrow" }); }
525
498
  return { id: swap.id || null, escrow,
526
499
  address: (record.swapWallet && record.swapWallet.address) || null,
527
- step: "xmr-incoming", server: null, watch: null, next: "watch" };
500
+ step: "xmr-incoming", next: "watch" };
528
501
  }
529
502
  return { id: swap.id || null, escrow: escrowRecord.address || null,
530
503
  address: (record.swapWallet && record.swapWallet.address) || null,
@@ -589,104 +562,6 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
589
562
  return options;
590
563
  }
591
564
 
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
565
  // A SELL SENDS XMR ONLY INTO AN ESCROW THE CHAIN ALREADY HOLDS. The relay answer proves the maker signed the
691
566
  // terms; it does not prove that the maker funded them. Read the escrow itself (code, status, slots and
692
567
  // deadlines), compare the slots with the halves this offer verified, and refuse before `send-xmr`.
@@ -824,42 +699,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
824
699
  return true;
825
700
  },
826
701
 
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
702
  // THE ARRIVAL VERDICT WITHOUT THE WATCH LOOP, and the deadline check as a separate call: an interface may
861
703
  // want to run both itself. The watch uses exactly these, so there is one decision, not two.
862
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),
863
711
  assertTimeForConfirmations: (request) => xmrArrival.assertTimeForConfirmations(request),
864
712
 
865
713
  /**
@@ -873,10 +721,11 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
873
721
  * and found no matching transaction). `pending` with a transaction, `one-node`, and every failure to check are NOT
874
722
  * "no money": the helper refuses to sign, so a lagging or busy witness can never look like an empty address.
875
723
  *
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.
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.
880
729
  *
881
730
  * The seams `deps.verify` / `deps.refund` / `deps.now` exist for the checks; in production they are the real
882
731
  * arrival check and the real refund.
@@ -911,10 +760,12 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
911
760
  if (!Number.isFinite(readyBy) || readyBy <= 0) throw new SdkError("bad-input", { field: "readyBySec" });
912
761
  const minConfirmations = Number.isFinite(Number(request.minConfirmations)) && Number(request.minConfirmations) > 0
913
762
  ? 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
763
  const leadSec = Number.isFinite(Number(request.leadSec)) && Number(request.leadSec) >= 0
917
- ? 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
+ })();
918
769
  // THE WALK STARTS AT THE SWAP'S BIRTH, NEVER AT GENESIS. A missing height used to become block 0, so a refund
919
770
  // check on a real chain would walk every block ever mined. The record carries the measured height; a caller
920
771
  // that has neither an explicit height nor a record height is refused rather than given a scan of the whole chain.
@@ -1110,6 +961,15 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1110
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
1111
962
  // mean the money goes against a non-existent side, so there it is a refusal.
1112
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
+ }
1113
973
  // THE ORDER SIDE BUILT BY THE CORE STAYS UNTIL THE END OF THE START: the points and commitments for the lock terms
1114
974
  // are taken from it - otherwise the record and the order would diverge, and the slot check against the chain would
1115
975
  // go red (and rightly so). There is no second build of the side here.
@@ -1234,8 +1094,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1234
1094
  // THE CLOCK IS THE SDK'S OWN SEAM, IN MILLISECONDS, LIKE EVERY OTHER NOW IN THE FACADE.
1235
1095
  const nowMs = typeof now === "function" ? Number(now()) : Date.now();
1236
1096
  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" });
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" });
1239
1099
  }
1240
1100
  }
1241
1101
  lockRequest.quote = request.orderQuote || null;
@@ -1283,7 +1143,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1283
1143
  return { id: record.swap.id || null, escrow: record.swap.escrow.address || null,
1284
1144
  address: (record.swapWallet && record.swapWallet.address) || null,
1285
1145
  step: "funding-pending", txHash: pendingTx,
1286
- reason: funded.pendingReason || "no-receipt", predictedEscrow: predicted, next: "receipt" };
1146
+ reason: funded.pendingReason || "no-receipt", predictedEscrow: predicted, next: "receipt",
1147
+ readyWindow };
1287
1148
  }
1288
1149
  // THE ESCROW ADDRESS IS TAKEN FROM THE RECEIPT (lock.send does this), not from a prediction. It is also written
1289
1150
  // into the swap: otherwise the progress screen and the explorer link would show an address that is not on the
@@ -1300,35 +1161,25 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1300
1161
  // THE SALT IS THE RECOVERY BINDING; there is no index reservation to commit here.
1301
1162
  }
1302
1163
 
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
- }
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.
1312
1166
  // THE STATE IS NAMED, NOT PASSED OFF AS COMPLETION: the swap reached exactly "waiting for XMR at the joint address",
1313
1167
  // and there is no arrival yet - `receivedXmr` is never implied by zero.
1314
1168
  return {
1315
1169
  id: record.swap.id || null,
1316
1170
  escrow: escrowAddress,
1317
- address: (watch && watch.address) || (record.swapWallet && record.swapWallet.address) || null,
1171
+ address: (record.swapWallet && record.swapWallet.address) || null,
1318
1172
  step: "xmr-incoming",
1319
- server,
1320
- watch,
1321
1173
  next: "watch",
1174
+ readyWindow,
1322
1175
  };
1323
1176
  },
1324
1177
 
1325
1178
  /**
1326
1179
  * WAIT FOR THE XMR TO ARRIVE AT THE JOINT ADDRESS - the whole point of opening the watch.
1327
1180
  *
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.
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.
1332
1183
  * IT ARRIVED - we return the FACT (the amount, the confirmations, the txid); WE DID NOT WAIT - a refusal with the
1333
1184
  * code `xmr-timeout`, separate from the others, so "the wait expired" is confused with neither a breakdown nor an
1334
1185
  * empty response. XMR ON THE ADDRESS BUT BARRED BY unlock_time is a THIRD answer with its own code `xmr-locked`
@@ -1350,6 +1201,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1350
1201
  const wantWallet = request.wallet !== undefined && request.wallet !== null;
1351
1202
  if (wantExpect !== wantWallet) throw new SdkError("bad-input", { field: wantExpect ? "wallet" : "expect" });
1352
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;
1353
1206
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0 ? Number(request.pollMs) : limitOf("watchPollMs", 5000);
1354
1207
  const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
1355
1208
  // THE CONFIRMATION TARGET - FROM THE CONFIGURATION (one number, the owner's decision: 10).
@@ -1366,15 +1219,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1366
1219
  : null;
1367
1220
  // LESS TIME LEFT THAN THE CONFIRMATIONS TAKE - NAMED AND NOT STARTED (issue #85, the owner's decision).
1368
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" });
1369
1224
  const readyBy = request.readyBySec !== undefined && request.readyBySec !== null ? Number(request.readyBySec)
1370
1225
  : (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) });
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
+ });
1372
1231
  }
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" });
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" });
1378
1236
  const started = Date.now();
1379
1237
  // --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL (issue #40). -------------------------------------
1380
1238
  // A decline leaves the escrow `refunded`, so nothing in the state says "do not wait any longer": without
@@ -1382,13 +1240,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1382
1240
  // CLOSED and whose ETH is already back - or, worse, the app offers the recovery file and a manual refund
1383
1241
  // for money nobody can recover.
1384
1242
  //
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.
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.
1392
1247
  // A STORAGE THAT CANNOT BE READ IS NOT A REASON TO REFUSE THE WAIT: the record is what makes the state
1393
1248
  // durable, and the escrow may also arrive in the request. The watch is not a new user of the store - and it
1394
1249
  // must not start failing where it did not before.
@@ -1420,7 +1275,7 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1420
1275
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "decline" }); }
1421
1276
  };
1422
1277
  // 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
1278
+ // WHERE it was seen ("event" or "record" when it was already written down). NO reason, category
1424
1279
  // or provider travels here - the node names none, and the sentence a person reads is the interface's.
1425
1280
  const declineResult = ({ source, at, waitedMs, address, chainChecked, chainError }) => ({
1426
1281
  id,
@@ -1443,34 +1298,14 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1443
1298
  let last = null;
1444
1299
  for (;;) {
1445
1300
  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);
1301
+ last = { address: request.address || escrowAddress, expectedXmr: request.expectedXmr ?? null, status: null };
1452
1302
  // THE DECLINE IS THE ESCROW'S EVENT, NOT THE SERVICE'S WORD. The legacy backend's `declined` status used
1453
1303
  // to become a settlement and end the wait; it no longer does. A service answer is at most a notification.
1454
1304
  const declineNow = declineOf({ logs: chainDecline.logs, escrow: escrowAddress, at: Date.now() });
1455
1305
  if (declineNow.declined) {
1456
1306
  settleDecline(record, declineNow.at);
1457
1307
  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 });
1308
+ address: last && last.address, chainChecked: chainDecline.checked, chainError: chainDecline.error });
1474
1309
  }
1475
1310
  // THE CLIENT'S OWN ANSWER COMES FIRST AND DECIDES. The backend's `seen` may still be false (it no longer
1476
1311
  // holds the view key), so it is not consulted when the client verifies. A disagreement or locked money
@@ -1499,28 +1334,13 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1499
1334
  }
1500
1335
  return verified;
1501
1336
  }
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
1337
  }
1518
1338
  },
1519
1339
 
1520
1340
  /**
1521
1341
  * 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.
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.
1524
1344
  */
1525
1345
  async startSell(request) {
1526
1346
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -1531,6 +1351,16 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1531
1351
  if (!order || !quote) throw new SdkError("bad-input", { field: "offer", missing: ["order", "quote"] });
1532
1352
  if (typeof offer.jointAddress !== "string" || !offer.jointAddress) throw new SdkError("bad-input", { field: "offer.jointAddress" });
1533
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;
1534
1364
  // THE RECORD'S ROLE IS THE BID ROLE. The node is the locker and the person is the claimer; a quote whose
1535
1365
  // addresses or factory disagree with the order is not the offer this record describes.
1536
1366
  const sameValue = (a, b) => String(a || "").replace(/^0x/, "").toLowerCase() === String(b || "").replace(/^0x/, "").toLowerCase();
@@ -1539,6 +1369,20 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1539
1369
  || !sameValue(quote.factory, order.factory) || Number(quote.chainId) !== Number(order.chainId)) {
1540
1370
  throw new SdkError("quote-refused", { step: "sell-record", why: "terms" });
1541
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
+ }
1542
1386
  // THE RECORD IS FOUND BEFORE A SECOND ONE IS MADE. The same offer retried after a reload yields the same
1543
1387
  // one-time address and escrow; a second record would be a second promise about one deal.
1544
1388
  const quoteId = quote.id || quote.nonce || null;
@@ -1555,11 +1399,46 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1555
1399
  || !same(existing.escrow && existing.escrow.moneroAddress, offer.jointAddress)) {
1556
1400
  throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
1557
1401
  }
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
+ }
1558
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
+ }
1559
1436
  return { id: existing.id, side: "sell", escrow: (existing.escrow && existing.escrow.address) || offer.escrow,
1560
1437
  address: (existing.escrow && existing.escrow.moneroAddress) || offer.jointAddress,
1561
1438
  xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
1562
1439
  claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
1440
+ claimSender: existing.claimSender || null,
1441
+ readyWindow: existing.readyWindow || existing.sellWindow || null,
1563
1442
  resumed: true, next: "send-xmr" };
1564
1443
  }
1565
1444
  const storage = store.storage();
@@ -1628,6 +1507,9 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1628
1507
  swap.orderQuote = offer.orderQuote || null;
1629
1508
  swap.quote = quote;
1630
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;
1631
1513
  swap.expect = {
1632
1514
  chainId, factory: order.factory, locker: order.locker, claimer: order.claimer, amount: String(order.amount),
1633
1515
  readyBy: order.readyBy, t1: order.t1, salt: order.salt,
@@ -1647,6 +1529,10 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1647
1529
  commitHalfLocker: (offer.nodeHalf && offer.nodeHalf.commitHalf) || null,
1648
1530
  orderContext: offer.context || null, xmrAmount: quote.xmrAmount || null,
1649
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;
1650
1536
  // THE RECORD IS NOT A RECEIPT FOR A GATE THAT FAILED. createRecord has already written it, so a refusal
1651
1537
  // from the escrow/deadline/slot gate must remove it again; otherwise the interface lists send-xmr for an
1652
1538
  // order the SDK never checked.
@@ -1659,7 +1545,8 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1659
1545
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1660
1546
  return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
1661
1547
  xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
1662
- resumed: false, next: "send-xmr" };
1548
+ claimSender: swap.claimSender || null,
1549
+ readyWindow: swap.readyWindow || null, resumed: false, next: "send-xmr" };
1663
1550
  },
1664
1551
 
1665
1552
  /**
@@ -1682,6 +1569,104 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1682
1569
  expect, onStep: request.onStep }, wallet);
1683
1570
  },
1684
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
+
1685
1670
  /**
1686
1671
  * WAIT FOR THE NODE'S SIDE ON A SELL. The client sends XMR to the one-time joint address; the node (the
1687
1672
  * locker) must mark the order ready before the claimer can take the ETH. This reads the escrow itself - no
@@ -1691,18 +1676,27 @@ export function createSwaps({ preflight, http, createRecord, mode = null, xmrNet
1691
1676
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
1692
1677
  const escrow = String(request.escrow || "").trim();
1693
1678
  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.
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;
1697
1683
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
1698
1684
  ? 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)) {
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) {
1702
1693
  try {
1703
1694
  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 */ }
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
+ }
1706
1700
  }
1707
1701
  // THE CLAIM OPENS AT readyBy WITHOUT A MARK. The deadline comes from the escrow once; the clock is the
1708
1702
  // facade's own millisecond seam, so a simulation and a caller that controls time agree with the rest of