@ninsei-labs/sdk 0.60.0 → 0.62.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 (96) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +81 -18
  3. package/assets/vendors/MANIFEST.json +1 -1
  4. package/assets/vendors/sdk/sdk-browser.js +4 -4
  5. package/engine/atomic/dleq2.js +0 -4
  6. package/engine/atomic/halfenc.js +6 -10
  7. package/engine/atomic/halves.js +0 -4
  8. package/engine/atomic/order.js +0 -4
  9. package/engine/atomic/orderContext.js +0 -4
  10. package/engine/atomic/orderHalfCommit.js +0 -4
  11. package/engine/core/chainSource.js +0 -4
  12. package/engine/core/clock.js +0 -4
  13. package/engine/core/config.js +17 -42
  14. package/engine/core/finality.js +0 -4
  15. package/engine/core/format.js +1 -5
  16. package/engine/core/preSignGuards.js +0 -4
  17. package/engine/core/rfqSource.js +0 -3
  18. package/engine/core/sellWindow.js +1 -5
  19. package/engine/core/store.js +11 -7
  20. package/engine/core/swap.js +3 -7
  21. package/engine/evm/amounts.js +2 -6
  22. package/engine/evm/asyncRoute.js +3 -7
  23. package/engine/evm/auth.js +0 -4
  24. package/engine/evm/claimGas.js +2 -6
  25. package/engine/evm/dex.js +1 -5
  26. package/engine/evm/escrow.js +0 -4
  27. package/engine/evm/factory.js +1 -5
  28. package/engine/evm/fees.js +62 -4
  29. package/engine/evm/funding.js +73 -71
  30. package/engine/evm/gasReserve.js +10 -4
  31. package/engine/evm/index.js +7 -11
  32. package/engine/evm/injected.js +0 -4
  33. package/engine/evm/permit.js +0 -4
  34. package/engine/evm/prices.js +3 -4
  35. package/engine/evm/session.js +1 -5
  36. package/engine/mock/chain.js +0 -4
  37. package/engine/monero/address.js +4 -5
  38. package/engine/monero/arrivalRead.js +15 -2
  39. package/engine/monero/halvesSweep.js +0 -4
  40. package/engine/monero/keyImage.js +146 -0
  41. package/engine/monero/keys.js +1 -0
  42. package/engine/monero/mnemonic.js +2 -1
  43. package/engine/monero/node.js +1 -4
  44. package/engine/monero/scan.js +12 -2
  45. package/engine/monero/swapKeys.js +0 -4
  46. package/engine/monero/unlock.js +2 -6
  47. package/engine/monero/wallet.js +0 -3
  48. package/engine/recovery/recoveryFile.js +31 -89
  49. package/engine/recovery/restore.js +0 -4
  50. package/engine/sdk/bridge.js +24 -58
  51. package/engine/ui/dom.js +0 -4
  52. package/engine/ui/walletModal.js +0 -4
  53. package/index.d.ts +436 -42
  54. package/package.json +22 -3
  55. package/src/actions.mjs +72 -6
  56. package/src/addressGuard.mjs +16 -0
  57. package/src/codes.mjs +26 -9
  58. package/src/config.mjs +56 -3
  59. package/src/decline.mjs +23 -74
  60. package/src/engine.mjs +17 -26
  61. package/src/firmRequest.mjs +80 -0
  62. package/src/index.mjs +17 -28
  63. package/src/legs/cow.mjs +2 -2
  64. package/src/legs/evm.mjs +20 -12
  65. package/src/legs/kyber-spec.mjs +2 -2
  66. package/src/legs/kyber.mjs +1 -1
  67. package/src/legs/shape.mjs +1 -1
  68. package/src/legs/uniswaprelay.mjs +16 -4
  69. package/src/legs/uniswapx.mjs +29 -7
  70. package/src/levelsWalkSpec.mjs +1 -1
  71. package/src/lock.mjs +18 -37
  72. package/src/provider/envFile.mjs +3 -3
  73. package/src/provider/sign.mjs +3 -3
  74. package/src/public/evm.d.ts +84 -0
  75. package/src/public/evm.mjs +20 -0
  76. package/src/public/order.mjs +1 -1
  77. package/src/public/provider.mjs +1 -1
  78. package/src/public/recovery.d.ts +4 -3
  79. package/src/public/recovery.mjs +1 -1
  80. package/src/public/xmr.d.ts +2 -2
  81. package/src/quoteEip712Spec.mjs +4 -4
  82. package/src/quotes.mjs +52 -11
  83. package/src/recovery-key.mjs +7 -3
  84. package/src/relayClaim.mjs +17 -3
  85. package/src/relayFirmClient.mjs +4 -0
  86. package/src/relayQuote.mjs +1 -0
  87. package/src/sim.mjs +1 -1
  88. package/src/swap-flow.mjs +28 -41
  89. package/src/swaps.mjs +217 -123
  90. package/src/sweep-inputs.mjs +61 -0
  91. package/src/sweep-reconcile.mjs +71 -0
  92. package/src/sweep-restore.mjs +38 -9
  93. package/src/sweep.mjs +164 -10
  94. package/src/version.mjs +1 -1
  95. package/src/wallet.mjs +1 -1
  96. package/src/xmr-arrival.mjs +1053 -57
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 { checkAddressOrThrow } from "./addressGuard.mjs";
8
9
  import { quoteLifeVerdict } from "./quotePolicy.mjs";
9
10
  import { SDK_VERSION } from "./version.mjs";
10
11
  import * as engine from "./engine.mjs";
@@ -28,16 +29,16 @@ import { probeMoneroNode } from "./probes.mjs";
28
29
  // MARKING READY - A FINISHED STEP, NOT A SECOND IMPLEMENTATION OF IT: it requires the order expectations and checks
29
30
  // the slots against the chain BEFORE signing (actions.markReady). The watch must call exactly it, otherwise "we saw
30
31
  // the XMR" and "we allowed the settlement to be taken" would diverge.
31
- import { createActions } from "./actions.mjs";
32
- // THE ONE RECOVERY KEY (sdk#76): the taker's halves come from it, not from a fresh random pair per swap.
32
+ import { createActions, walletError } from "./actions.mjs";
33
+ // THE ONE RECOVERY KEY: the taker's halves come from it, not from a fresh random pair per swap.
33
34
  import {
34
35
  createRecoveryKeyFile, importRecoveryKey, loadRecoveryKey,
35
36
  recoveryKeyFileName, recoverySaltOf, saveRecoveryKey,
36
37
  newRecoverySalt, takerHalvesV2,
37
38
  } from "./recovery-key.mjs";
38
- // THE XMR ARRIVAL CHECK ON TWO NODES (issue #85) - IN THE CORE, from the same mirrored rule and block parser.
39
+ // THE XMR ARRIVAL CHECK ON TWO NODES - IN THE CORE, from the same mirrored rule and block parser.
39
40
  import * as xmrArrival from "./xmr-arrival.mjs";
40
- // THE MAKER'S DECLINE (issue #40): the escrow's `Declined` event is the decision. The node's `declined` +
41
+ // THE MAKER'S DECLINE: the escrow's `Declined` event is the decision. The node's `declined` +
41
42
  // `compliance` status is an observation on the wire, not a second source this file trusts; the detectors and the
42
43
  // neutral vocabulary live in one module, so this file names the state instead of re-reading either.
43
44
  import { declineOf, logReaderOf, blockBoundaryOf, DECLINED_TOPIC0, DECLINED_TERMINAL, DECLINED_CODE } from "./decline.mjs";
@@ -46,34 +47,9 @@ import { readReadyWindow, readyLeadSec, readyLateSec, readyWindowMs } from "./re
46
47
  // signed tip. This module speaks that one wire; swaps.mjs decides which record may be claimed.
47
48
  import { relayOriginOf, addressTextOf, halfTextOf, postRelayClaim } from "./relayClaim.mjs";
48
49
 
49
- // THE ENGINE'S SETTLEMENT KINDS -> THE CONTRACT'S CODES: THE KEY IS THE KIND THE ENGINE REALLY WRITES.
50
- //
51
- // The map used to be keyed by names no code path writes - `refunded` for a refund (the engine writes
52
- // `kind: "refund_eth"`), and `xmr_returned` and `closed`, for which no settlement with that kind is written
53
- // anywhere in the engine or in this package. A REFUND therefore never met its key and fell into the fallback:
54
- // get/list/progress told the app `closed` about an order whose ETH was already back in the wallet - the very
55
- // distinction that became load-bearing once the maker's decline was made a state of its own (issue #40).
56
- //
57
- // WHAT CAN BE A KIND, EXHAUSTIVELY. The record's settlement belongs to the engine (engine/core/swap.js, the only
58
- // module that assigns swap.settlement), and `declined` is the one kind written by us (src/decline.mjs):
59
- // `success` - the swap completed and the XMR is on the depositor's address (sweepNow and the auto-sweep in the
60
- // ticker; the SDK does not take it from a backend session);
61
- // `refund_eth` - the ETH went back to the depositor. TWO WRITERS, ONE KIND: the person's own refund (refundEth)
62
- // and the watchtower inside the ticker both write `kind: "refund_eth"` with the phase
63
- // `refunded_eth`, so there is exactly ONE refund-shaped kind here and nothing is collapsed;
64
- // `declined` - the maker refused a funded order. Not the engine's: the escrow reads `refunded` either way, so
65
- // the engine cannot tell a decline from a refund, and the SDK writes this kind itself when it SEES
66
- // the decline (src/decline.mjs). From then on every surface that reads the record reports it
67
- // without asking the chain again.
68
- //
69
- // AND WHAT IS NOT A KEY: an unknown kind is named, not invented - it comes out as "closed", the fallback in
70
- // toState below, which is why `closed` is a code here and not a key (no settlement carries that kind; the string
71
- // `closed` in the engine is the XMR SESSION's status vocabulary, not a settlement). The maker taking the XMR back
72
- // without a ready mark is NOT a kind either: it does not end a swap - the depositor's ETH is still in the escrow -
73
- // so it is a PHASE of a live swap (`xmr_reclaimed`, engine/core/swap.js, told apart by that code from the maker who
74
- // never locked), and the swap ends later as `refunded_eth`. `xmr_returned`, which stood in the engine's terminal
75
- // table and in the `TerminalCode` type as a state nothing could produce, is gone with it. Every one of these facts
76
- // is asserted by the `terminal` check rather than left to a reader.
50
+ // The engine writes `success` and `refund_eth`. The SDK writes `declined` when it sees the maker's decline.
51
+ // An unknown kind is not invented: it becomes `closed` in toState. `closed` is a code, not a settlement kind.
52
+ // The `terminal` check asserts these facts.
77
53
  const TERMINAL = {
78
54
  success: "success",
79
55
  refund_eth: "refunded_eth",
@@ -81,8 +57,7 @@ const TERMINAL = {
81
57
  };
82
58
 
83
59
  const num = (v) => {
84
- // NULL/UNDEFINED/EMPTY IS NOT ZERO. `Number(null)` is 0, which made every unknown amount look measured as empty;
85
- // a missing number is a missing fact and the state/interface must see null.
60
+ // Null, undefined and empty are not zero. A missing number is a missing fact, and the state must see null.
86
61
  if (v === null || v === undefined || v === "") return null;
87
62
  const n = Number(v);
88
63
  return Number.isFinite(n) ? n : null;
@@ -217,7 +192,7 @@ export function toState(swap) {
217
192
  status: d.phase || null,
218
193
  txs: (swap.escrow && (swap.escrow.txids || swap.escrow.txs)) || [],
219
194
  },
220
- // A DECLINED ORDER OFFERS NOTHING, AND THAT IS THE POINT OF THE STATE (issue #40). The ETH - the fee
195
+ // A DECLINED ORDER OFFERS NOTHING, AND THAT IS THE POINT OF THE STATE. The ETH - the fee
221
196
  // included - is already back in the depositor's wallet and no half was revealed, so there is no ready mark to
222
197
  // place, no XMR to sweep and NO REFUND TO SIGN: the flags are OFF rather than left to whatever the engine's
223
198
  // `can` says about an order whose escrow merely reads `refunded`. The app needs no second source for "there
@@ -417,15 +392,16 @@ function swapByEscrow(store, escrow) {
417
392
  }
418
393
 
419
394
  export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork = null, call = null, fetchImpl = null, now = null, sleep = null, evmBlock = null, store = engine.store,
395
+ chunkOptions = null,
420
396
  // THE MONERO TIMINGS ARE BROUGHT BY THE CONFIGURATION: the watch's rate and timeout live in config.limits. There is
421
397
  // no server step and no route table to consult.
422
398
  config = null,
423
- // THE INTERFACE'S ADDRESS DENYLIST (issue #16), a Set of lower-cased addresses already assembled by the facade.
399
+ // THE INTERFACE'S ADDRESS DENYLIST, a Set of lower-cased addresses already assembled by the facade.
424
400
  // The check on the ACTUAL sender is done in start() below, ONE place, right before the send - the wallet adapter
425
401
  // only HANDS OUT the current account (`address()`), it does not carry the policy.
426
402
  denylist = null,
427
403
  watch: watchOptions = null,
428
- // THE CHAIN LOG READER FOR THE DECLINE CHECK (issue #40). A seam, as the chain read is: by default the logs are
404
+ // THE CHAIN LOG READER FOR THE DECLINE CHECK. A seam, as the chain read is: by default the logs are
429
405
  // read through the page's wallet (`readDeclinedLogs`), and from outside a caller brings its own
430
406
  // ({ address, topics, fromBlock, toBlock }) -> logs. It is a READ of the escrow's own event, not a node
431
407
  // substitution - the address is the escrow of the swap being watched.
@@ -471,6 +447,26 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
471
447
  };
472
448
  const sleepFor = typeof sleep === "function" ? sleep
473
449
  : (ms) => new Promise((resolve) => setTimeout(resolve, ms));
450
+ // THE CLAIM WINDOW USES THE CHAIN CLOCK, NOT THE DEVICE CLOCK. `evmBlock` is the same block-read seam the
451
+ // sell-side gate uses; an explicitly injected `now` remains a test seam only when no chain seam is configured.
452
+ // Without either, a half-revealing send must refuse rather than silently use Date.now().
453
+ let observedNowSec = null;
454
+ const chainNowSec = async () => {
455
+ const snapshot = await chainSnapshot();
456
+ if (snapshot && Number.isSafeInteger(Number(snapshot.timestamp)) && Number(snapshot.timestamp) > 0) {
457
+ return Number(snapshot.timestamp);
458
+ }
459
+ // A CONFIGURED CHAIN SEAM THAT IS UNREADABLE IS A REFUSAL, NOT A DEVICE CLOCK. The explicit `now` seam is only
460
+ // for hosts that did not configure `evmBlock` at all (simulation and tests).
461
+ if (typeof evmBlock === "function") return null;
462
+ if (typeof now === "function") {
463
+ // AN INJECTED CLOCK THAT IS NOT A NUMBER IS NOT A DEVICE CLOCK. The old `clockMs` fallback turned NaN into
464
+ // Date.now(), so a broken caller clock silently became a valid one.
465
+ const value = Math.floor(Number(now()) / 1000);
466
+ return Number.isSafeInteger(value) && value > 0 ? value : null;
467
+ }
468
+ return null;
469
+ };
474
470
  // ONE BLOCK FOR THE SELL GATE. A block read is a seam like the contract read: `evmBlock` from the interface
475
471
  // wins, then the wallet's own provider. The number pins every escrow read below to the same state; the
476
472
  // timestamp is the chain's clock, not the device's.
@@ -664,7 +660,15 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
664
660
  // Compatibility with a caller that has neither a wallet nor a block seam: the reads still go to `latest`,
665
661
  // and the deadline falls back to the documented `now` seam. A live sell carries one of the two.
666
662
  const gate = { call: reader, blockTag: snapshot ? snapshot.blockTag : "latest" };
667
- const chainNow = snapshot ? snapshot.timestamp : Math.floor((typeof now === "function" ? now() : Date.now()) / 1000);
663
+ let chainNow = snapshot && Number.isSafeInteger(Number(snapshot.timestamp)) && Number(snapshot.timestamp) > 0
664
+ ? Number(snapshot.timestamp) : null;
665
+ if (chainNow === null) {
666
+ const raw = typeof now === "function" ? Number(now()) : Date.now();
667
+ chainNow = Number.isFinite(raw) ? Math.floor(raw / 1000) : null;
668
+ }
669
+ if (!Number.isSafeInteger(chainNow) || chainNow <= 0) {
670
+ throw new SdkError("quote-refused", { step: "send-xmr", why: "clock-unreadable" });
671
+ }
668
672
  let status = null;
669
673
  try { status = await flow.orderStatus(escrow, gate); }
670
674
  catch (e) { throw new SdkError("quote-refused", { step: "send-xmr", why: "escrow-unreadable" }); }
@@ -793,6 +797,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
793
797
  // THE ARRIVAL VERDICT WITHOUT THE WATCH LOOP, and the deadline check as a separate call: an interface may
794
798
  // want to run both itself. The watch uses exactly these, so there is one decision, not two.
795
799
  verifyArrival: (request) => xmrArrival.verifyArrival(withDefaultFetch(request)),
800
+ verifyArrivalFromRead: (request) => xmrArrival.verifyArrivalFromRead(withDefaultFetch(request)),
801
+ verifyRecovery: (request) => xmrArrival.verifyRecovery(withDefaultFetch(request)),
802
+ readRecovery: (request) => xmrArrival.readRecovery(withDefaultFetch(request)),
803
+ readRecoveryWitness: (request) => xmrArrival.readRecoveryWitness(withDefaultFetch(request)),
796
804
  /**
797
805
  * SHADOW THE FIXED-SLICE WITNESS WITHOUT CHANGING THE DECISION. It runs the exact check and the witness-v1
798
806
  * slice check and returns both; `witnessNodes` must carry `{protocol: "witness-v1"}`. Nothing here opens
@@ -802,7 +810,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
802
810
  assertTimeForConfirmations: (request) => xmrArrival.assertTimeForConfirmations(request),
803
811
 
804
812
  /**
805
- * THE CLIENT'S OWN EARLY REFUND WHEN THE XMR DID NOT ARRIVE (issue #88). After `readyBy` the maker may claim
813
+ * THE CLIENT'S OWN EARLY REFUND WHEN THE XMR DID NOT ARRIVE. After `readyBy` the maker may claim
806
814
  * even without the ready mark, and the early-refund window closes; so while the interface is open a depositor
807
815
  * who sees no XMR must take the ETH back BEFORE `readyBy`. The arrival is decided by THE SAME rule the watch
808
816
  * uses (xmr-arrival.verifyArrival): two nodes of different operators on one block, and money barred by
@@ -912,13 +920,16 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
912
920
  if (request.side === "sell") {
913
921
  throw new SdkError("bad-input", { field: "side", why: "sell-not-supported", surface: "swaps.start" });
914
922
  }
923
+ if (!request.receiveTo || typeof request.receiveTo !== "string") throw new SdkError("bad-input", { field: "receiveTo" });
924
+ // THE RECIPIENT IS CHECKED BEFORE THE QUOTE, THE RECOVERY KEY OR THE CHAIN. A bad checksum or another Monero
925
+ // network would otherwise be recorded into the swap and only discovered at withdrawal, after the XMR had arrived.
926
+ await checkAddressOrThrow(request.receiveTo, xmrNetwork, "receiveTo");
915
927
  if (!request.quote || typeof request.quote !== "object") throw new SdkError("bad-input", { field: "quote" });
916
928
  // THE PER-SWAP FILE PATH IS GONE. One key covers every swap, and a per-swap file issued before funding cannot
917
929
  // name the escrow (it does not exist yet), so `sweep.plan` could not read the revealed half from it.
918
930
  if (request.recoveryKey === undefined || request.recoveryKey === null) {
919
931
  throw new SdkError("bad-input", { field: "recoveryKey", why: "required" });
920
932
  }
921
- if (!request.receiveTo || typeof request.receiveTo !== "string") throw new SdkError("bad-input", { field: "receiveTo" });
922
933
  // A START WITHOUT THE SIGNED XMR AMOUNT IS NOT A START. `quote.size` is a rounded display value and the relay
923
934
  // answer does not carry it; the arrival check needs the exact integer the order quote signed. Refuse here, before
924
935
  // a wallet or a funding send, instead of recording an incomplete swap that later reads "no amount".
@@ -1120,6 +1131,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1120
1131
  const step = await orderStepChunked({
1121
1132
  order: request.order, side: made.side || null, counterparty: request.counterparty || null,
1122
1133
  standIn: mode !== "live", network: (record.swap.moneroNetwork || xmrNetwork || null),
1134
+ options: chunkOptions || {},
1123
1135
  });
1124
1136
  // THE RECORD FIELDS ARE UNDER THE VERY NAMES THE ENGINE READS. So the record, after a page reload, again yields a
1125
1137
  // wallet from the halves (`halvesWalletOf`), rather than losing the address together with the tab.
@@ -1178,7 +1190,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1178
1190
  if (!wallet || typeof wallet.send !== "function" || typeof wallet.receipt !== "function") {
1179
1191
  throw new SdkError("bad-input", { field: "wallet", missing: ["send", "receipt"], surface: "swaps.start", step: "lock" });
1180
1192
  }
1181
- // THE INTERFACE'S ADDRESS DENYLIST, ON THE ACTUAL SENDER (issue #16). The person may have switched accounts
1193
+ // THE INTERFACE'S ADDRESS DENYLIST, ON THE ACTUAL SENDER. The person may have switched accounts
1182
1194
  // in the wallet, so what matters is the address the funding transaction will really be sent from AT THIS
1183
1195
  // MOMENT, not `order.locker` checked earlier. The wallet adapter hands out the current account (the adapter's
1184
1196
  // `address()` reads `eth_accounts[0]`); the comparison lives HERE, one place, right before the send - not
@@ -1209,7 +1221,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1209
1221
  } : {};
1210
1222
  const lockRequest = { ...request.order, ...derived, amountWei: request.order.amount };
1211
1223
  // THE SIGNED QUOTE: the fee, the registry address and the provider live in IT, not in the factory
1212
- // (decision #76). The caller brings it (the interface got it from the maker); without it the lock is not signed.
1224
+ //. The caller brings it (the interface got it from the maker); without it the lock is not signed.
1213
1225
  // THE QUOTE MUST NAME THE SAME COUNTERPARTY HALF THAT WAS VERIFIED. `orderStep` verifies
1214
1226
  // `request.counterparty`, while funding encodes `request.orderQuote`; a caller that brings both can otherwise
1215
1227
  // prove one point and fund another. The same comparison is repeated in funding.js, at the money boundary.
@@ -1227,23 +1239,33 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1227
1239
  }
1228
1240
  // THE SIGNED QUOTE MUST STILL BE VALID WHEN THE MONEY MOVES. The proof and the record work take seconds; a
1229
1241
  // quote that expired in that window would reach the wallet and revert at the factory. Check the signed field
1230
- // immediately before the send, with a small margin for the next block.
1242
+ // immediately before the send, against the CHAIN clock, with a small margin for the next block.
1243
+ let lockNowSec = null;
1231
1244
  const validUntil = request.orderQuote && request.orderQuote.validUntil !== undefined
1232
1245
  ? request.orderQuote.validUntil
1233
1246
  : undefined;
1234
1247
  if (validUntil !== undefined && validUntil !== null) {
1235
1248
  const until = Number(validUntil);
1236
- // THE CLOCK IS THE SDK'S OWN SEAM, IN MILLISECONDS, LIKE EVERY OTHER NOW IN THE FACADE.
1237
- const nowMs = typeof now === "function" ? Number(now()) : Date.now();
1238
- const nowSec = Math.floor(nowMs / 1000);
1249
+ // AN UNREADABLE BLOCK IS A NAMED REFUSAL, NOT AN UNCODED ERROR. The sell gate already maps this failure to
1250
+ // `block-unreadable`; the lock path must speak the same vocabulary.
1251
+ let snapshot = null;
1252
+ try { snapshot = await chainSnapshot(wallet); }
1253
+ catch { throw new SdkError("quote-unchecked", { step: "lock", why: "clock-unreadable" }); }
1254
+ lockNowSec = snapshot && Number.isSafeInteger(Number(snapshot.timestamp)) && Number(snapshot.timestamp) > 0
1255
+ ? Number(snapshot.timestamp)
1256
+ : (typeof evmBlock === "function" ? null
1257
+ : Math.floor(Number(typeof now === "function" ? now() : Date.now()) / 1000));
1258
+ if (!Number.isSafeInteger(lockNowSec) || lockNowSec <= 0) {
1259
+ throw new SdkError("quote-unchecked", { step: "lock", why: "clock-unreadable" });
1260
+ }
1239
1261
  // THE PREPARATION WAS ALREADY PAID FOR AT THE ANSWER. This check runs after the proof, the record and the
1240
1262
  // chain reads; requiring START_PREP_SEC again would refuse a quote that the answer accepted and spent those
1241
1263
  // seconds on. Only the next-block margin remains between here and the send.
1242
- const life = quoteLifeVerdict({ validUntil: until, nowSec, side: "ask", prepSec: 0 });
1264
+ const life = quoteLifeVerdict({ validUntil: until, nowSec: lockNowSec, side: "ask", prepSec: 0 });
1243
1265
  if (!life.ok) {
1244
1266
  throw new SdkError("quote-expired", {
1245
1267
  validUntil: Number.isFinite(until) ? until : null,
1246
- now: Number.isFinite(nowSec) ? nowSec : null,
1268
+ now: lockNowSec,
1247
1269
  remainingSec: life.remainingSec,
1248
1270
  marginSec: life.marginSec,
1249
1271
  prepSec: life.prepSec,
@@ -1266,7 +1288,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1266
1288
  catch { throw new SdkError("storage-unavailable", { step: "save-pending" }); }
1267
1289
  };
1268
1290
  let funded = null;
1269
- try { funded = await lock.send(lockRequest, wallet, { call: reader, onPredicted: notePredicted }); }
1291
+ try { funded = await lock.send(lockRequest, wallet, { call: reader, nowSec: lockNowSec, onPredicted: notePredicted }); }
1270
1292
  catch (error) {
1271
1293
  // A REJECTION BEFORE BROADCAST MUST NOT LEAVE THE SWAP STUCK IN funding-pending. The pre-send record exists
1272
1294
  // for a process that dies while the send is in flight; an explicit wallet refusal is the other case, and the
@@ -1277,8 +1299,9 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1277
1299
  record.swap.escrow = { ...record.swap.escrow, fundingPending: false, fundingReason: "send-rejected" };
1278
1300
  try { engine.swap.saveSwap(record.swap, store); } catch { /* the pending record stays; never resend blind */ }
1279
1301
  }
1280
- if (error && typeof error.code === "string") throw error;
1281
- throw new SdkError("server-unavailable", { step: "lock" });
1302
+ // A NUMERIC WALLET ERROR IS NOT A SERVER FAILURE. Use the same classifier as markReady/claim/refund:
1303
+ // 4001 stays a rejection, 4100/-32002/transport stay wallet-side, and only a real revert is a chain answer.
1304
+ throw walletError(error, "lock");
1282
1305
  }
1283
1306
  // A SENT TRANSACTION IS NOT A FUNDED ESCROW. Without a status-1 receipt and the expected OrderCreated, the
1284
1307
  // address is unknown and calling the step xmr-incoming would make the person wait for XMR at a guess. Keep
@@ -1358,7 +1381,14 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1358
1381
  // the result; `request.address` was never part of the public watch request.
1359
1382
  const record = (() => { try { return engine.swap.getSwap(id, store); } catch { return null; } })();
1360
1383
  const storedSwap = record;
1361
- const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
1384
+ const sameAddress = (a, b) => String(a || "").replace(/^0x/, "").toLowerCase()
1385
+ === String(b || "").replace(/^0x/, "").toLowerCase();
1386
+ const recordEscrow = record && record.escrow && record.escrow.address;
1387
+ if (request.escrow !== undefined && request.escrow !== null && String(request.escrow).trim()
1388
+ && recordEscrow && !sameAddress(request.escrow, recordEscrow)) {
1389
+ throw new SdkError("bad-input", { field: "escrow", why: "record-mismatch" });
1390
+ }
1391
+ const escrowAddress = request.escrow || recordEscrow || null;
1362
1392
  if (wantExpect && !escrowAddress) throw new SdkError("bad-input", { field: "escrow" });
1363
1393
  const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
1364
1394
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0 ? Number(request.pollMs) : limitOf("watchPollMs", 5000);
@@ -1375,7 +1405,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1375
1405
  : (config && typeof config.nodesFor === "function" ? config.nodesFor(request.verify.network || request.network || xmrNetwork) : []),
1376
1406
  minConfirmations }
1377
1407
  : null;
1378
- // LESS TIME LEFT THAN THE CONFIRMATIONS TAKE - NAMED AND NOT STARTED (issue #85, the owner's decision).
1408
+ // LESS TIME LEFT THAN THE CONFIRMATIONS TAKE - NAMED AND NOT STARTED.
1379
1409
  if (verifyRequest) {
1380
1410
  if (!readyWindowRaw) throw new SdkError("bad-input", { field: "readyWindow", why: "not-in-record" });
1381
1411
  const readyWindow = readReadyWindow(readyWindowRaw, { side: "ask", field: "readyWindow" });
@@ -1397,9 +1427,13 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1397
1427
  const moneroAddress = typeof verifyRequest.address === "string" && verifyRequest.address
1398
1428
  ? verifyRequest.address
1399
1429
  : (record && record.escrow && record.escrow.moneroAddress) || null;
1430
+ if (verifyRequest.address && record && record.escrow && record.escrow.moneroAddress
1431
+ && String(verifyRequest.address) !== String(record.escrow.moneroAddress)) {
1432
+ throw new SdkError("bad-input", { field: "verify.address", why: "record-mismatch" });
1433
+ }
1400
1434
  if (!moneroAddress) throw new SdkError("bad-input", { field: "verify.address", why: "not-in-record" });
1401
1435
  const started = Date.now();
1402
- // --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL (issue #40). -------------------------------------
1436
+ // --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL. -------------------------------------
1403
1437
  // A decline leaves the escrow `refunded`, so nothing in the state says "do not wait any longer": without
1404
1438
  // this, the wait runs to its timeout and the app is told the generic `xmr-timeout` about an order that is
1405
1439
  // CLOSED and whose ETH is already back - or, worse, the app offers the recovery file and a manual refund
@@ -1502,8 +1536,8 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1502
1536
  /**
1503
1537
  * START A SELL FROM A VERIFIED RELAY OFFER. The offer is the result of `quotes.firmRelay` for the bid side;
1504
1538
  * the record keeps the one-time address, the escrow, our half, the order expectations and the relay origin, so a
1505
- * reload can continue with `get` + `sellWatch` + `sellClaim`. The optional `claimSender` is a legacy
1506
- * single-sender fallback; `claimViaRelay` takes the client's ordered list at claim time. This method sends nothing.
1539
+ * reload can continue with `get` + `sellWatch` + `sellClaim`. The ordered `claimSenders` list is the only
1540
+ * sender source; it is stored for the later claim. This method sends nothing.
1507
1541
  */
1508
1542
  async startSell(request) {
1509
1543
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -1532,14 +1566,16 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1532
1566
  || !sameValue(quote.factory, order.factory) || Number(quote.chainId) !== Number(order.chainId)) {
1533
1567
  throw new SdkError("quote-refused", { step: "sell-record", why: "terms" });
1534
1568
  }
1535
- // THE SENDER IS CHOSEN BY THE CLIENT, NOT THE DEAL'S MAKER. The record keeps it so a reload claims through
1536
- // the same node; a sender naming the maker or the quote key owner would reveal the half to the party that
1537
- // must never receive it.
1569
+ // THE SENDER IS CHOSEN BY THE CLIENT, NOT THE DEAL'S MAKER. The record keeps the list so a reload claims
1570
+ // through the same node; a sender naming the maker or the quote key owner would reveal the half to the party
1571
+ // that must never receive it. The old scalar is retired: it is not a second source and is refused by name.
1538
1572
  const dealMaker = addressTextOf(quote.provider, "provider");
1539
1573
  const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1540
1574
  || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1541
- const requestedSender = request.claimSender === undefined || request.claimSender === null
1542
- || String(request.claimSender).trim() === "" ? null : addressTextOf(request.claimSender, "claimSender");
1575
+ if (request.claimSender !== undefined && request.claimSender !== null
1576
+ && String(request.claimSender).trim() !== "") {
1577
+ throw new SdkError("bad-input", { field: "claimSender", why: "retired" });
1578
+ }
1543
1579
  const requestedList = request.claimSenders === undefined || request.claimSenders === null
1544
1580
  ? null : request.claimSenders;
1545
1581
  if (requestedList !== null && !Array.isArray(requestedList)) {
@@ -1548,20 +1584,11 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1548
1584
  if (requestedList && requestedList.length === 0) {
1549
1585
  throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1550
1586
  }
1551
- if (requestedList && requestedSender) {
1552
- throw new SdkError("bad-input", { field: "claimSenders", why: "with-claim-sender" });
1553
- }
1554
- if (requestedSender && requestedSender === dealMaker) {
1555
- throw new SdkError("bad-input", { field: "claimSender", why: "is-deal-maker" });
1556
- }
1557
- if (requestedSender && quoteKeyOwner && requestedSender === quoteKeyOwner) {
1558
- throw new SdkError("bad-input", { field: "claimSender", why: "is-quote-key" });
1559
- }
1560
1587
  const offerSender = offer.claimSender === undefined || offer.claimSender === null
1561
1588
  || String(offer.claimSender).trim() === "" ? null : addressTextOf(offer.claimSender, "offer.claimSender");
1562
- // THE STORED LIST IS BUILT HERE, ONCE. The relay's published claimSender is the default first sender; a caller
1563
- // that brings its own ordered list owns the order. The scalar remains a one-element fallback for older callers.
1564
- const explicitSenders = requestedList || (requestedSender ? [requestedSender] : null);
1589
+ // THE STORED LIST IS BUILT HERE, ONCE. An explicit list wins; otherwise the relay's published claimSender is
1590
+ // the only fallback, as a one-element list. There is no legacy request scalar.
1591
+ const explicitSenders = requestedList;
1565
1592
  const rawSenders = explicitSenders || (offerSender ? [offerSender] : []);
1566
1593
  const claimSenders = [];
1567
1594
  for (const raw of rawSenders) {
@@ -1598,12 +1625,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1598
1625
  if (explicitSenders && claimSenders.length && (!storedList || storedList.length !== claimSenders.length
1599
1626
  || storedList.some((value, index) => String(value).toLowerCase() !== claimSenders[index]))) {
1600
1627
  existing.claimSenders = claimSenders;
1601
- existing.claimSender = claimSenders[0];
1602
1628
  try { engine.swap.saveSwap(existing, store); }
1603
1629
  catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1604
1630
  } else if (!explicitSenders && !storedList && claimSenders.length) {
1605
1631
  existing.claimSenders = claimSenders;
1606
- existing.claimSender = claimSenders[0];
1607
1632
  try { engine.swap.saveSwap(existing, store); }
1608
1633
  catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1609
1634
  }
@@ -1636,7 +1661,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1636
1661
  address: (existing.escrow && existing.escrow.moneroAddress) || offer.jointAddress,
1637
1662
  xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
1638
1663
  claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
1639
- claimSender: existing.claimSender || null,
1640
1664
  claimSenders: Array.isArray(existing.claimSenders) ? existing.claimSenders : [],
1641
1665
  readyWindow: existing.readyWindow || existing.sellWindow || null,
1642
1666
  resumed: true, next: "send-xmr" };
@@ -1709,10 +1733,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1709
1733
  swap.claimTip = quote.claimTip || null;
1710
1734
  // THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping the list means a reload cannot silently
1711
1735
  // send the half to a different node than the one the client selected.
1712
- if (claimSenders.length) {
1713
- swap.claimSenders = claimSenders;
1714
- swap.claimSender = claimSenders[0];
1715
- }
1736
+ if (claimSenders.length) swap.claimSenders = claimSenders;
1716
1737
  swap.expect = {
1717
1738
  chainId, factory: order.factory, locker: order.locker, claimer: order.claimer, amount: String(order.amount),
1718
1739
  readyBy: order.readyBy, t1: order.t1, salt: order.salt,
@@ -1748,7 +1769,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1748
1769
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1749
1770
  return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
1750
1771
  xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
1751
- claimSender: swap.claimSender || null,
1752
1772
  claimSenders: Array.isArray(swap.claimSenders) ? swap.claimSenders : [],
1753
1773
  readyWindow: swap.readyWindow || null, resumed: false, next: "send-xmr" };
1754
1774
  },
@@ -1820,13 +1840,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1820
1840
  }
1821
1841
  const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1822
1842
  || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1823
- const storedSenderRaw = swap.claimSender === undefined || swap.claimSender === null
1824
- || String(swap.claimSender).trim() === "" ? null : swap.claimSender;
1825
- const requestedSenderRaw = request.claimSender === undefined || request.claimSender === null
1826
- || String(request.claimSender).trim() === "" ? null : request.claimSender;
1827
- // THE ORDER IS THE CLIENT'S, NOT THE RECORD'S. A list passed now wins; the old scalar and the stored value are
1828
- // only one-element fallbacks for callers written before the list existed. Neither is a pin: the next sender is
1829
- // tried when this one refuses or its slot ends.
1843
+ if (request.claimSender !== undefined && request.claimSender !== null
1844
+ && String(request.claimSender).trim() !== "") {
1845
+ throw new SdkError("bad-input", { field: "claimSender", why: "retired" });
1846
+ }
1847
+ // THE ORDER IS THE CLIENT'S, NOT THE RECORD'S. A list passed now wins; otherwise the stored list is the
1848
+ // fallback for an id-only reload. There is no legacy scalar and no second source.
1830
1849
  if (request.claimSenders !== undefined && !Array.isArray(request.claimSenders)) {
1831
1850
  throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
1832
1851
  }
@@ -1834,12 +1853,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1834
1853
  if (explicitList && explicitList.length === 0) {
1835
1854
  throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1836
1855
  }
1837
- if (explicitList && requestedSenderRaw) {
1838
- throw new SdkError("bad-input", { field: "claimSenders", why: "with-claim-sender" });
1839
- }
1840
- const rawSenders = explicitList || (requestedSenderRaw ? [requestedSenderRaw] : null)
1841
- || (Array.isArray(swap.claimSenders) ? swap.claimSenders : null)
1842
- || (storedSenderRaw ? [storedSenderRaw] : []);
1856
+ const legacyStored = swap.claimSender === undefined || swap.claimSender === null
1857
+ || String(swap.claimSender).trim() === "" ? null : swap.claimSender;
1858
+ const rawSenders = explicitList || (Array.isArray(swap.claimSenders) && swap.claimSenders.length
1859
+ ? swap.claimSenders : (legacyStored ? [legacyStored] : []));
1843
1860
  if (!rawSenders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
1844
1861
  const senders = [];
1845
1862
  for (const raw of rawSenders) {
@@ -1871,11 +1888,19 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1871
1888
  }
1872
1889
  }
1873
1890
  // A LIST IS NOT A PIN. It is saved only as the fallback for a reload whose caller no longer has the relay's
1874
- // answer; a later request that brings its own order ignores it.
1891
+ // answer; a later request that brings its own order ignores it. The retired scalar is removed even when the
1892
+ // list already matches, so a migrated record cannot keep two sources.
1893
+ let sendersChanged = false;
1875
1894
  if (!Array.isArray(swap.claimSenders) || swap.claimSenders.length !== senders.length
1876
1895
  || swap.claimSenders.some((value, index) => String(value).toLowerCase() !== senders[index])) {
1877
1896
  swap.claimSenders = senders;
1878
- swap.claimSender = senders[0];
1897
+ sendersChanged = true;
1898
+ }
1899
+ if (Object.prototype.hasOwnProperty.call(swap, "claimSender")) {
1900
+ delete swap.claimSender;
1901
+ sendersChanged = true;
1902
+ }
1903
+ if (sendersChanged) {
1879
1904
  try { engine.swap.saveSwap(swap, store); }
1880
1905
  catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1881
1906
  }
@@ -1901,7 +1926,8 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1901
1926
  };
1902
1927
  const t1Raw = order.t1 ?? (swap.expect && swap.expect.t1);
1903
1928
  let t1 = Number.isSafeInteger(Number(t1Raw)) && Number(t1Raw) > 0 ? Number(t1Raw) : null;
1904
- const secondsLeft = () => (t1 === null ? null : Math.max(0, t1 - Math.floor(clockMs() / 1000)));
1929
+ // THE TIME LEFT IS THE CHAIN'S TIME. It is null until the same clock used by windowOf has been read.
1930
+ const secondsLeft = () => (t1 === null || observedNowSec === null ? null : Math.max(0, t1 - observedNowSec));
1905
1931
  // THE CLAIM WINDOW BELONGS TO THE CONTRACT, NOT TO THE RELAY. The relay can forward any half it is given, so
1906
1932
  // the client must refuse to hand it over before `readyBy` without the ready mark, after `t1`, and inside the
1907
1933
  // settlement margin when neither a sender nor the seller's own claim can still land. The check reads the
@@ -1910,15 +1936,23 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1910
1936
  const CLAIM_MARGIN_SEC = 120;
1911
1937
  const SELLER_CLAIM_SEC = 60;
1912
1938
  const windowOf = async () => {
1939
+ let nowSec;
1940
+ try { nowSec = await chainNowSec(); }
1941
+ catch { nowSec = null; }
1942
+ if (!Number.isSafeInteger(nowSec) || nowSec <= 0) {
1943
+ observedNowSec = null;
1944
+ return { ok: false, reason: "unreadable" };
1945
+ }
1946
+ observedNowSec = nowSec;
1913
1947
  let deadlines;
1914
1948
  try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
1915
1949
  catch { return { ok: false, reason: "unreadable" }; }
1916
1950
  const t1Sec = Number(deadlines.t1);
1917
1951
  const readyBySec = Number(deadlines.readyBy);
1918
- const nowSec = Math.floor(clockMs() / 1000);
1919
- if (![t1Sec, readyBySec, nowSec].every(Number.isSafeInteger)) {
1952
+ if (![t1Sec, readyBySec].every(Number.isSafeInteger)) {
1920
1953
  return { ok: false, reason: "unreadable" };
1921
1954
  }
1955
+ if (Number.isSafeInteger(t1Sec)) t1 = t1Sec;
1922
1956
  let marked;
1923
1957
  try {
1924
1958
  const raw = await reader({ to: escrow, data: engine.evm.encodeRead("ready") });
@@ -1934,7 +1968,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1934
1968
  return { ok: true, t1: t1Sec, readyBy: readyBySec, nowSec };
1935
1969
  };
1936
1970
  const windowResult = (reason, tried) => ({
1937
- id, state: "claim-window", reason, provider: null, claimSender: null, escrow, relayUrl,
1971
+ id, state: "claim-window", reason, provider: null, escrow, relayUrl,
1938
1972
  txid: null, from: null, tipWei: tip.toString(), t1, secondsLeft: secondsLeft(), tried,
1939
1973
  });
1940
1974
  const STOP_ESCROW_CODES = new Set([
@@ -1942,46 +1976,95 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1942
1976
  "claim-not-funded", "claim-already-closed", "claim-half-invalid",
1943
1977
  ]);
1944
1978
  const claimedByEscrow = (sender = null, answer = null, tried = []) => ({
1945
- id, state: "claimed", provider: sender, claimSender: sender, escrow, relayUrl,
1979
+ id, state: "claimed", provider: sender, escrow, relayUrl,
1946
1980
  txid: answer ? answer.txid : null, from: (answer && answer.from) || null,
1947
1981
  tipWei: (answer && answer.tipWei) || tip.toString(), tried,
1948
1982
  });
1983
+ // A WINDOW STOP AFTER SENDS IS NOT A BLIND STOP. The last sender's claim can land just after its slot; before
1984
+ // reporting a closing window, read the escrow once more and let a claimed/refunded/defunded state win.
1985
+ const windowStop = async (reason, currentTried) => {
1986
+ let status;
1987
+ try {
1988
+ status = await readStatus();
1989
+ } catch {
1990
+ // THE WINDOW STOP MUST STAY A RESULT. If the escrow cannot be read, the caller still needs the named
1991
+ // window state; throwing here would change a pre-existing `claim-window` answer into an exception.
1992
+ return windowResult(reason, currentTried);
1993
+ }
1994
+ if (status.isClaimed) {
1995
+ try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
1996
+ return claimedByEscrow(null, null, currentTried);
1997
+ }
1998
+ if (status.isRefunded) return windowResult("escrow-refunded", currentTried);
1999
+ if (!status.isFunded) return windowResult("not-funded", currentTried);
2000
+ return windowResult(reason, currentTried);
2001
+ };
1949
2002
  // A CLAIM THAT ALREADY LANDED IS NOT A REASON TO SEND THE HALF AGAIN. The caller may have lost the answer on
1950
2003
  // the previous attempt; read the escrow before the first POST, and read it once more before returning
1951
2004
  // `claim-yourself`, so a late claim cannot be reported as "claim yourself".
1952
- const initial = await readStatus();
2005
+ const priorAttempts = Array.isArray(swap.claimAttempts) ? swap.claimAttempts : [];
2006
+ let initial;
2007
+ try {
2008
+ initial = await readStatus();
2009
+ } catch (error) {
2010
+ // NOTHING HAS BEEN SENT IN THIS CALL. Without an earlier attempt this is a pre-send refusal, not "the claim
2011
+ // may already have been sent"; the window result says the clock/escrow could not be read.
2012
+ if (!priorAttempts.length && error && error.code === "claim-unknown"
2013
+ && error.params && error.params.why === "escrow-unread") {
2014
+ return windowResult("unreadable", []);
2015
+ }
2016
+ throw error;
2017
+ }
1953
2018
  if (initial.isClaimed) return claimedByEscrow();
1954
2019
  if (!initial.isFunded) return windowResult("not-funded", []);
1955
2020
  let refunded = Boolean(initial.isRefunded);
1956
2021
  const tried = [];
1957
- // A SENDER THAT MAY HAVE RECEIVED THE HALF IS NOT TRIED AGAIN AFTER A RELOAD. The record gets the sender
1958
- // before the POST, so a crash or a lost answer leaves a durable trace. A refused sender may be skipped; an
1959
- // attempt left in flight or unknown stops the list with claim-unknown, because the half may already be out.
1960
- const priorAttempts = Array.isArray(swap.claimAttempts) ? swap.claimAttempts : [];
1961
- const attempted = new Set(priorAttempts.map((entry) => String(entry && entry.sender || "").toLowerCase()));
1962
- const pendingSenders = senders.filter((sender) => !attempted.has(String(sender).toLowerCase()));
2022
+ // A SENDER THAT MAY HAVE RECEIVED THE HALF IS NOT A DONE MARK. The record gets the sender before the POST, so
2023
+ // a crash or a lost answer leaves a durable trace; a later call reads the escrow and may try the same sender
2024
+ // again. Only a sender whose slot is still running is held back, and even then the slot is polled rather than
2025
+ // allowed to block the list forever.
1963
2026
  const priorTried = priorAttempts.map((entry) => ({
1964
2027
  sender: entry.sender, outcome: entry.outcome || "unknown", code: entry.code || null,
1965
2028
  params: entry.params || null, txid: entry.txid || null,
1966
2029
  }));
1967
- if (priorAttempts.some((entry) => entry && (entry.outcome === "sending" || entry.outcome === "unknown"))) {
1968
- throw new SdkError("claim-unknown", { step: "relay-claim", why: "previous-sender-unknown" });
1969
- }
1970
- if (!pendingSenders.length) {
1971
- // THE RESUME PATH MUST NAME A REFUND LIKE THE FINAL PATH DOES. All senders may already be recorded as tried
1972
- // when the escrow moves to refunded; `claim-yourself` would send the seller to `sellClaim` on a closed order.
1973
- if (refunded) return windowResult("escrow-refunded", priorTried);
1974
- return { id, state: "claim-yourself", reason: "senders-exhausted",
1975
- provider: null, claimSender: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
1976
- t1, secondsLeft: secondsLeft(), tried: priorTried };
2030
+ const latest = priorAttempts[priorAttempts.length - 1];
2031
+ // A PREVIOUS ATTEMPT OWNS ITS SLOT EVEN WHEN IT REFUSED. The refusal proves that THIS POST sent nothing, but
2032
+ // the next call still starts after the slot closes: the retry is bounded by the same clock as a first run and
2033
+ // cannot race a request whose answer was lost or still in flight.
2034
+ if (latest && Number.isFinite(Number(latest.at))) {
2035
+ const gate = await windowOf();
2036
+ if (!gate.ok) {
2037
+ // A PRIOR ATTEMPT MAY HAVE SENT THE HALF. The same late-read rule as the sender loop applies here: do not
2038
+ // report a closing window without one last escrow read.
2039
+ return priorTried.length ? windowStop(gate.reason, priorTried)
2040
+ : windowResult(gate.reason, priorTried);
2041
+ }
2042
+ // AN OLD RECORD MAY CARRY A DEVICE-CLOCK `at` AHEAD OF CHAIN TIME. A slot is 15-30 s by construction, so cap
2043
+ // the wait at one slot from the chain clock instead of trusting a future timestamp indefinitely.
2044
+ const slotEnd = Math.min(Number(latest.at) + Math.ceil(slotMs / 1000),
2045
+ observedNowSec + Math.ceil(slotMs / 1000));
2046
+ while (observedNowSec !== null && observedNowSec < slotEnd) {
2047
+ const status = await readStatus();
2048
+ if (status && status.isClaimed) return claimedByEscrow(latest.sender, null, priorTried);
2049
+ if (status && status.isRefunded) return windowResult("escrow-refunded", priorTried);
2050
+ const waitMs = Math.max(1, Math.min(pollMs, (slotEnd - observedNowSec) * 1000));
2051
+ await sleepFor(waitMs);
2052
+ const next = await chainNowSec();
2053
+ if (!Number.isSafeInteger(next) || next <= 0) {
2054
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "clock-unreadable" });
2055
+ }
2056
+ observedNowSec = next;
2057
+ }
1977
2058
  }
2059
+ if (refunded) return windowResult("escrow-refunded", priorTried);
1978
2060
  const persistAttempts = (entry, outcome, extra = {}) => {
1979
2061
  if (entry) Object.assign(entry, { outcome, ...extra });
1980
2062
  try { engine.swap.saveSwap(swap, store); }
1981
2063
  catch { throw new SdkError("storage-unavailable", { step: "save-claim-attempt" }); }
1982
2064
  };
1983
2065
  const beginAttempt = (sender) => {
1984
- const entry = { sender, at: Math.floor(clockMs() / 1000), outcome: "sending" };
2066
+ const at = Number.isSafeInteger(observedNowSec) ? observedNowSec : Math.floor(clockMs() / 1000);
2067
+ const entry = { sender, at, outcome: "sending" };
1985
2068
  swap.claimAttempts = [...(Array.isArray(swap.claimAttempts) ? swap.claimAttempts : []), entry];
1986
2069
  persistAttempts(entry, "sending");
1987
2070
  return entry;
@@ -1989,9 +2072,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1989
2072
  const finishAttempt = (entry, outcome, extra = {}) => {
1990
2073
  try { persistAttempts(entry, outcome, extra); } catch { /* the chain answer is already known */ }
1991
2074
  };
1992
- if (!refunded) for (const sender of pendingSenders) {
2075
+ if (!refunded) for (const sender of senders) {
1993
2076
  const gate = await windowOf();
1994
- if (!gate.ok) return windowResult(gate.reason, tried);
2077
+ if (!gate.ok) {
2078
+ if (tried.length || priorTried.length) return windowStop(gate.reason, tried);
2079
+ return windowResult(gate.reason, tried);
2080
+ }
1995
2081
  if (gate.t1 !== null) t1 = gate.t1;
1996
2082
  const attempt = beginAttempt(sender);
1997
2083
  // THE SLOT STARTS WHEN THE SENDER IS ENTERED, NOT WHEN ITS POST RETURNS. A slow POST must not stretch the
@@ -2028,7 +2114,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
2028
2114
  for (;;) {
2029
2115
  const status = await readStatus();
2030
2116
  if (status && status.isClaimed) {
2031
- swap.claimSender = sender;
2032
2117
  finishAttempt(attempt, "claimed", { txid: answer ? answer.txid : null });
2033
2118
  try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
2034
2119
  return claimedByEscrow(sender, answer, tried);
@@ -2058,7 +2143,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
2058
2143
  const finalGate = await windowOf();
2059
2144
  if (!finalGate.ok) return windowResult(finalGate.reason, tried);
2060
2145
  return { id, state: "claim-yourself", reason: "senders-exhausted",
2061
- provider: null, claimSender: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
2146
+ provider: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
2062
2147
  t1, secondsLeft: secondsLeft(), tried };
2063
2148
  },
2064
2149
 
@@ -2122,6 +2207,15 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
2122
2207
  ready = hex.length > 0 && BigInt("0x" + hex) !== 0n;
2123
2208
  } catch (error) { lastError = (error && error.code) || "ready-unread"; }
2124
2209
  if (ready === true) {
2210
+ // A ready mark after t1 is not a usable sell window: the contract's claim is already closed. Name it
2211
+ // as a claim-window state instead of returning `ready` and letting the host promise a claim.
2212
+ const t1 = deadlines ? Number(deadlines.t1) : null;
2213
+ const at = nowSec();
2214
+ if (Number.isSafeInteger(t1) && at !== null && at >= t1) {
2215
+ return { escrow, state: "claim-window-closed", funded: true, claimed: false, refunded: false,
2216
+ ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
2217
+ t1, secondsLeft: 0 };
2218
+ }
2125
2219
  return { escrow, state: "ready", funded: true, claimed: false, refunded: false,
2126
2220
  ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
2127
2221
  }