@ninsei-labs/sdk 0.60.0 → 0.61.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 (56) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +28 -16
  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 +0 -4
  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 +0 -4
  14. package/engine/core/finality.js +0 -4
  15. package/engine/core/format.js +0 -4
  16. package/engine/core/preSignGuards.js +0 -4
  17. package/engine/core/rfqSource.js +0 -3
  18. package/engine/core/sellWindow.js +0 -4
  19. package/engine/core/store.js +0 -4
  20. package/engine/core/swap.js +0 -4
  21. package/engine/evm/amounts.js +0 -4
  22. package/engine/evm/asyncRoute.js +0 -4
  23. package/engine/evm/auth.js +0 -4
  24. package/engine/evm/claimGas.js +2 -6
  25. package/engine/evm/dex.js +0 -4
  26. package/engine/evm/escrow.js +0 -4
  27. package/engine/evm/factory.js +0 -4
  28. package/engine/evm/fees.js +0 -4
  29. package/engine/evm/funding.js +2 -5
  30. package/engine/evm/gasReserve.js +0 -4
  31. package/engine/evm/index.js +5 -9
  32. package/engine/evm/injected.js +0 -4
  33. package/engine/evm/permit.js +0 -4
  34. package/engine/evm/prices.js +0 -4
  35. package/engine/evm/session.js +0 -4
  36. package/engine/mock/chain.js +0 -4
  37. package/engine/monero/address.js +0 -3
  38. package/engine/monero/halvesSweep.js +0 -4
  39. package/engine/monero/node.js +0 -4
  40. package/engine/monero/swapKeys.js +0 -4
  41. package/engine/monero/unlock.js +2 -6
  42. package/engine/monero/wallet.js +0 -3
  43. package/engine/recovery/recoveryFile.js +0 -4
  44. package/engine/recovery/restore.js +0 -4
  45. package/engine/sdk/bridge.js +3 -7
  46. package/engine/ui/dom.js +0 -4
  47. package/engine/ui/walletModal.js +0 -4
  48. package/index.d.ts +24 -23
  49. package/package.json +3 -2
  50. package/src/engine.mjs +17 -26
  51. package/src/public/recovery.d.ts +1 -1
  52. package/src/relayClaim.mjs +17 -3
  53. package/src/swap-flow.mjs +7 -10
  54. package/src/swaps.mjs +157 -70
  55. package/src/version.mjs +1 -1
  56. package/src/xmr-arrival.mjs +14 -16
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@ninsei-labs/sdk",
3
- "version": "0.60.0",
3
+ "version": "0.61.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
7
7
  },
8
- "packageManager": "pnpm@12.11.2",
8
+ "packageManager": "pnpm@12.21.0",
9
9
  "description": "XMR <-> EVM swap engine: quotes, guards, order steps, recovery (no DOM, no user-facing strings)",
10
10
  "license": "(MIT AND LGPL-3.0-only)",
11
11
  "type": "module",
@@ -21,6 +21,7 @@
21
21
  "check:pack": "node tools/check.mjs --only=pack",
22
22
  "check:pack-teeth": "node tools/run-teeth-isolated.mjs tools/check-pack-teeth.mjs",
23
23
  "check:guard-teeth": "node tools/run-teeth-isolated.mjs tools/check-guard-teeth.mjs",
24
+ "check:claim-teeth": "node tools/run-teeth-isolated.mjs tools/check-claim-teeth.mjs",
24
25
  "check:secrets": "node tools/check.mjs --only=secrets",
25
26
  "check:vendor-bundles": "node tools/check.mjs --only=vendor-bundles",
26
27
  "check:dleq-vectors": "node tools/check-dleq-vectors.mjs",
package/src/engine.mjs CHANGED
@@ -1,18 +1,11 @@
1
- // THE ENGINE SEAM, NOW SELF-CONTAINED.
1
+ // THE ENGINE SEAM.
2
2
  //
3
- // The engine modules the core depends on are mirrored under sdk/engine/ - byte-for-byte copies kept in
4
- // sync by tools/build-sdk-engine.mjs and guarded by tools/check-sdk-engine.mjs. This file is the ONLY
5
- // place that knows where the engine lives; no other SDK module does.
3
+ // The engine modules live under engine/. This file is the only place that knows where they live; no other SDK
4
+ // module does. The SDK is the source of truth for these modules: do not regenerate them from another repository.
6
5
  //
7
- // WHY A VERIFIED MIRROR, NOT A MOVE. The very same modules are loaded by the demo page in the browser
8
- // (www/js), and the production web root is www/ alone - the sdk/ directory is not served there (see
9
- // tools/serve.mjs). Lifting the files out of www/js would 404 every engine import on the live site, and
10
- // dozens of repository checks read those sources by their www/js path. So the single source of truth
11
- // stays www/js and the SDK carries a copy: any drift reddens check-sdk-engine, so it cannot diverge
12
- // silently (the same rule build-sweep uses for the sweep/rfq copies).
13
- //
14
- // The mirror is generated - never edit sdk/engine/ by hand. Change www/js, then run:
15
- // node tools/build-sdk-engine.mjs
6
+ // The page reaches the same protocol rules through its own bridge, but the package does not depend on the page's
7
+ // source tree. A rule that would be copied into both places must live here, in the package, and the bridge must
8
+ // read it from the package.
16
9
  export * as config from "../engine/core/config.js";
17
10
  export * as guards from "../engine/core/preSignGuards.js";
18
11
  export * as restore from "../engine/recovery/restore.js";
@@ -32,27 +25,25 @@ export * as halfenc from "../engine/atomic/halfenc.js";
32
25
  // The engine's EVM layer: talking to the chain (order terms, sending, reading) - through this seam.
33
26
  export * as evm from "../engine/evm/index.js";
34
27
  // THE DEX LEG'S OWN GUARDS - THROUGH THE SAME SEAM. priceGateVerdict ("the price is not the market") and
35
- // dexLegVerdict (amount coverage + price) live in www/js/evm/dex.js and are re-exported here so a route provider
28
+ // dexLegVerdict (amount coverage + price) live in engine/evm/dex.js and are re-exported here so a route provider
36
29
  // that is NOT the declared Uniswap path (CoWSwap, an aggregator) applies THE SAME guards rather than lookalikes.
37
30
  export * as dex from "../engine/evm/dex.js";
38
- // THE DEAL ENGINE NO LONGER LIVES IN www/js (#32, wave 3): the order flow moved into the package
39
- // (sdk/src/swap-flow.mjs) and is declared in sdk/index.d.ts. The page reaches it through the bridge, so the
40
- // mirror no longer carries core/swap-flow.js - what stays in the seam is the ORDER QUOTE source and the shared
41
- // CLAIM GAS LIMIT that the moved flow reads through this same seam. The order side is built by engine/atomic/order.js.
31
+ // THE DEAL ENGINE LIVES IN THE PACKAGE: the order flow is sdk/src/swap-flow.mjs and is declared in sdk/index.d.ts.
32
+ // The page reaches it through the bridge. What stays in the seam is the ORDER QUOTE source and the shared CLAIM
33
+ // GAS LIMIT that the flow reads through this same seam. The order side is built by engine/atomic/order.js.
42
34
 
43
35
  export * as rfqSource from "../engine/core/rfqSource.js";
44
36
  export * as claimGas from "../engine/evm/claimGas.js";
45
37
  export * as escrow from "../engine/evm/escrow.js";
46
38
  export * as halvesSweep from "../engine/monero/halvesSweep.js";
47
- // MONERO ADDRESSES - THROUGH THE SAME MODULE THE DEMO USES. The format, the network prefixes and the address
48
- // check live in www/js/monero/address.js (checkAddress: base58 + keccak256 + network), and the page uses it
49
- // too. The wallet adapter needs exactly networkFromShape: its own address must belong to the network named by
50
- // the core, and that is checked by the same code, not by a private prefix table.
39
+ // MONERO ADDRESSES. The format, the network prefixes and the address check live in engine/monero/address.js
40
+ // (checkAddress: base58 + keccak256 + network); the page uses the same module through its bridge. The wallet
41
+ // adapter needs exactly networkFromShape: its own address must belong to the network named by the core, and that
42
+ // is checked by the same code, not by a private prefix table.
51
43
  export * as xmrAddress from "../engine/monero/address.js";
52
- // THE unlock_time RULE AND THE BLOCK READER - FROM THE SAME MIRROR, NOT A COPY. A second copy of "the output
53
- // is barred until a boundary" would be a second truth about money, so the rule lives under www/js
54
- // (monero/unlock.js) together with the Monero block parser (monero/scan.js), and the SDK reads them through
55
- // the engine mirror. check-sdk-engine reddens on any drift, so the two cannot diverge silently.
44
+ // THE unlock_time RULE AND THE BLOCK READER. A second copy of "the output is barred until a boundary" would be a
45
+ // second truth about money, so the rule lives in engine/monero/unlock.js together with the Monero block parser
46
+ // (engine/monero/scan.js), and the SDK reads them through the engine seam. There is no external source to drift from.
56
47
  export * as xmrUnlock from "../engine/monero/unlock.js";
57
48
  export * as xmrScan from "../engine/monero/scan.js";
58
49
  // THE ADDRESS AND ITS PUBLIC KEYS, for the arrival check: the view secret and spend key are bound to the address,
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // src/public/recovery.mjs only NAMES what the engine already offers; these declarations NAME the same thing for a
5
5
  // TypeScript consumer. Every signature is copied from the module the barrel re-exports
6
- // (`engine/recovery/recoveryFile.js`, itself a generated byte-for-byte copy of the engine source), and a symbol
6
+ // (`engine/recovery/recoveryFile.js`, the SDK's engine source for the recovery envelope), and a symbol
7
7
  // the barrel does not re-export is not declared here.
8
8
  //
9
9
  // NO DOM AND NO ARGUMENTS: the module touches WebCrypto (`crypto.subtle`), `btoa`/`atob` and the text encoders,
@@ -11,6 +11,10 @@ const ADDRESS = /^0x[0-9a-f]{40}$/;
11
11
  const HALF = /^[0-9a-f]{64}$/;
12
12
  const TXID = /^0x[0-9a-f]{64}$/;
13
13
  const DECIMAL = /^(0|[1-9][0-9]*)$/;
14
+ // RELAY-LEVEL ANSWERS ARE NOT THE SENDER'S REFUSAL. A rate limit, a malformed request or a version/quote problem
15
+ // describes the hop, not the sender; the half may not have been forwarded. They keep the conservative unknown
16
+ // outcome so the sender's slot is still read, instead of marking that sender as refused for good.
17
+ const RELAY_LEVEL_CODES = new Set(["rate_limited", "bad_request", "unsupported_version", "no_quote"]);
14
18
 
15
19
  /**
16
20
  * THE RELAY ORIGIN, NORMALISED ONCE. A claim is bound to the origin that answered the quote, so a trailing slash
@@ -42,9 +46,11 @@ export function halfTextOf(value) {
42
46
  * POST the half to the relay that answered the quote.
43
47
  *
44
48
  * A refusal from the relay is `quote-refused` with the provider's own code kept in `params.code`; the provider's
45
- * message is deliberately NOT copied, because it is not this package's user-facing text. A lost answer is
46
- * `claim-unknown`: the claim may have been sent, so a second call must begin by reading the escrow, never by
47
- * assuming that nothing happened. Only a validated transaction hash is a success.
49
+ * message is deliberately NOT copied, because it is not this package's user-facing text. A relay-level answer
50
+ * (`rate_limited`, `bad_request`, `unsupported_version`, `no_quote`) is `claim-unknown`: it names the hop, not the
51
+ * sender, and the half may not have been forwarded. A lost answer is `claim-unknown`: the claim may have been sent,
52
+ * so a second call must begin by reading the escrow, never by assuming that nothing happened. Only a validated
53
+ * transaction hash is a success.
48
54
  */
49
55
  export async function postRelayClaim({
50
56
  relayUrl,
@@ -88,6 +94,10 @@ export async function postRelayClaim({
88
94
  if (code === "claim-unknown" || code === "claim_unknown") {
89
95
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-timeout", code, status: response.status, outcome: "unknown" });
90
96
  }
97
+ if (code && RELAY_LEVEL_CODES.has(code)) {
98
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-" + code,
99
+ code, status: response.status, outcome: "unknown" });
100
+ }
91
101
  if (code && version === 1) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
92
102
  // AN UNVERSIONED NON-2XX IS NOT A REFUSAL WE CAN READ. The claim may still have been sent, so it is unknown.
93
103
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-status", status: response.status, outcome: "unknown" });
@@ -95,6 +105,10 @@ export async function postRelayClaim({
95
105
  if (!answer || version !== 1) {
96
106
  throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer", outcome: "unknown" });
97
107
  }
108
+ if (code && RELAY_LEVEL_CODES.has(code)) {
109
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-" + code,
110
+ code, status: response.status, outcome: "unknown" });
111
+ }
98
112
  if (code) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
99
113
 
100
114
  // ONLY A REAL TRANSACTION HASH IS A CLAIM. A body without one leaves the outcome unknown, whether the claim never
package/src/swap-flow.mjs CHANGED
@@ -17,15 +17,12 @@
17
17
  // no such function - the payable constructor moves the money - and there is no envelope in the order. Nor
18
18
  // does the escrow have a separate funding function: an order is either born with money or not born at all.
19
19
  //
20
- // THE CRYPTOGRAPHY LIVES UNDER www/js/atomic/* (mirrored as ../engine/atomic/*) AND IS CALLED ONLY THROUGH
21
- // THE IN-PROCESS ORDER BUILDER. There is no crypto here - here is the order.
20
+ // THE CRYPTOGRAPHY LIVES UNDER engine/atomic/* AND IS CALLED ONLY THROUGH THE IN-PROCESS ORDER BUILDER.
21
+ // There is no crypto here - here is the order.
22
22
  //
23
- // WHY IT IS IN THE PACKAGE NOW. The page used to import this module straight from www/js/core/swap-flow.js; the
24
- // core (www/js, mirrored under ../engine/) was the second home of the deal flow. That is exactly the debt
25
- // issue #32 pays off: the deal engine is business logic, so it belongs to the package (@ninsei-labs/sdk), and
26
- // the page reaches it through ONE seam (www/js/sdk/bridge.js) by module name, not by pulling a file out of
27
- // www/js. The engine modules it needs are still read through the same verified mirror (./engine.mjs); what moved
28
- // is the RULES, not the crypto.
23
+ // WHY IT IS IN THE PACKAGE. The deal engine is business logic, so it belongs to the package (@ninsei-labs/sdk).
24
+ // The page reaches it through ONE seam (its bridge) by module name. The engine modules it needs are read through
25
+ // ./engine.mjs; what lives here is the RULES, not the crypto.
29
26
  import { SdkError } from "./errors.mjs";
30
27
  import * as engine from "./engine.mjs";
31
28
  // THE HALF'S COMMITMENT, COMPUTED LOCALLY. The escrow checks the low 160 bits of `keccak256(x||y)` of `half*G`
@@ -52,8 +49,8 @@ const {
52
49
  } = engine.escrow;
53
50
  // THE COUNTERPARTY GUARDS: whether a stand-in may be signed on this chain.
54
51
  const { liveOrderSlotsVerdict, counterpartyVerdict } = engine.guards;
55
- // THE ORDER CONTEXT, THE ORDER QUOTE AND THE SHARED CLAIM GAS LIMIT - all through the mirror, so the page and
56
- // the package never keep a second copy of these rules.
52
+ // THE ORDER CONTEXT, THE ORDER QUOTE AND THE SHARED CLAIM GAS LIMIT - all through the engine seam, so the page
53
+ // and the package never keep a second copy of these rules.
57
54
  const { orderContextString } = engine.orderContext;
58
55
  const { requestOrderQuote, checkOrderQuoteShape } = engine.rfqSource;
59
56
  const { CLAIM_GAS_LIMIT } = engine.claimGas;
package/src/swaps.mjs CHANGED
@@ -471,6 +471,24 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
471
471
  };
472
472
  const sleepFor = typeof sleep === "function" ? sleep
473
473
  : (ms) => new Promise((resolve) => setTimeout(resolve, ms));
474
+ // THE CLAIM WINDOW USES THE CHAIN CLOCK, NOT THE DEVICE CLOCK. `evmBlock` is the same block-read seam the
475
+ // sell-side gate uses; an explicitly injected `now` remains a test seam only when no chain seam is configured.
476
+ // Without either, a half-revealing send must refuse rather than silently use Date.now().
477
+ let observedNowSec = null;
478
+ const chainNowSec = async () => {
479
+ const snapshot = await chainSnapshot();
480
+ if (snapshot && Number.isSafeInteger(Number(snapshot.timestamp)) && Number(snapshot.timestamp) > 0) {
481
+ return Number(snapshot.timestamp);
482
+ }
483
+ // A CONFIGURED CHAIN SEAM THAT IS UNREADABLE IS A REFUSAL, NOT A DEVICE CLOCK. The explicit `now` seam is only
484
+ // for hosts that did not configure `evmBlock` at all (simulation and tests).
485
+ if (typeof evmBlock === "function") return null;
486
+ if (typeof now === "function") {
487
+ const value = Math.floor(clockMs() / 1000);
488
+ return Number.isSafeInteger(value) && value > 0 ? value : null;
489
+ }
490
+ return null;
491
+ };
474
492
  // ONE BLOCK FOR THE SELL GATE. A block read is a seam like the contract read: `evmBlock` from the interface
475
493
  // wins, then the wallet's own provider. The number pins every escrow read below to the same state; the
476
494
  // timestamp is the chain's clock, not the device's.
@@ -1358,7 +1376,14 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1358
1376
  // the result; `request.address` was never part of the public watch request.
1359
1377
  const record = (() => { try { return engine.swap.getSwap(id, store); } catch { return null; } })();
1360
1378
  const storedSwap = record;
1361
- const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
1379
+ const sameAddress = (a, b) => String(a || "").replace(/^0x/, "").toLowerCase()
1380
+ === String(b || "").replace(/^0x/, "").toLowerCase();
1381
+ const recordEscrow = record && record.escrow && record.escrow.address;
1382
+ if (request.escrow !== undefined && request.escrow !== null && String(request.escrow).trim()
1383
+ && recordEscrow && !sameAddress(request.escrow, recordEscrow)) {
1384
+ throw new SdkError("bad-input", { field: "escrow", why: "record-mismatch" });
1385
+ }
1386
+ const escrowAddress = request.escrow || recordEscrow || null;
1362
1387
  if (wantExpect && !escrowAddress) throw new SdkError("bad-input", { field: "escrow" });
1363
1388
  const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
1364
1389
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0 ? Number(request.pollMs) : limitOf("watchPollMs", 5000);
@@ -1397,6 +1422,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1397
1422
  const moneroAddress = typeof verifyRequest.address === "string" && verifyRequest.address
1398
1423
  ? verifyRequest.address
1399
1424
  : (record && record.escrow && record.escrow.moneroAddress) || null;
1425
+ if (verifyRequest.address && record && record.escrow && record.escrow.moneroAddress
1426
+ && String(verifyRequest.address) !== String(record.escrow.moneroAddress)) {
1427
+ throw new SdkError("bad-input", { field: "verify.address", why: "record-mismatch" });
1428
+ }
1400
1429
  if (!moneroAddress) throw new SdkError("bad-input", { field: "verify.address", why: "not-in-record" });
1401
1430
  const started = Date.now();
1402
1431
  // --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL (issue #40). -------------------------------------
@@ -1502,8 +1531,8 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1502
1531
  /**
1503
1532
  * START A SELL FROM A VERIFIED RELAY OFFER. The offer is the result of `quotes.firmRelay` for the bid side;
1504
1533
  * 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.
1534
+ * reload can continue with `get` + `sellWatch` + `sellClaim`. The ordered `claimSenders` list is the only
1535
+ * sender source; it is stored for the later claim. This method sends nothing.
1507
1536
  */
1508
1537
  async startSell(request) {
1509
1538
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -1532,14 +1561,16 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1532
1561
  || !sameValue(quote.factory, order.factory) || Number(quote.chainId) !== Number(order.chainId)) {
1533
1562
  throw new SdkError("quote-refused", { step: "sell-record", why: "terms" });
1534
1563
  }
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.
1564
+ // THE SENDER IS CHOSEN BY THE CLIENT, NOT THE DEAL'S MAKER. The record keeps the list so a reload claims
1565
+ // through the same node; a sender naming the maker or the quote key owner would reveal the half to the party
1566
+ // that must never receive it. The old scalar is retired: it is not a second source and is refused by name.
1538
1567
  const dealMaker = addressTextOf(quote.provider, "provider");
1539
1568
  const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1540
1569
  || 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");
1570
+ if (request.claimSender !== undefined && request.claimSender !== null
1571
+ && String(request.claimSender).trim() !== "") {
1572
+ throw new SdkError("bad-input", { field: "claimSender", why: "retired" });
1573
+ }
1543
1574
  const requestedList = request.claimSenders === undefined || request.claimSenders === null
1544
1575
  ? null : request.claimSenders;
1545
1576
  if (requestedList !== null && !Array.isArray(requestedList)) {
@@ -1548,20 +1579,11 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1548
1579
  if (requestedList && requestedList.length === 0) {
1549
1580
  throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1550
1581
  }
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
1582
  const offerSender = offer.claimSender === undefined || offer.claimSender === null
1561
1583
  || 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);
1584
+ // THE STORED LIST IS BUILT HERE, ONCE. An explicit list wins; otherwise the relay's published claimSender is
1585
+ // the only fallback, as a one-element list. There is no legacy request scalar.
1586
+ const explicitSenders = requestedList;
1565
1587
  const rawSenders = explicitSenders || (offerSender ? [offerSender] : []);
1566
1588
  const claimSenders = [];
1567
1589
  for (const raw of rawSenders) {
@@ -1598,12 +1620,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1598
1620
  if (explicitSenders && claimSenders.length && (!storedList || storedList.length !== claimSenders.length
1599
1621
  || storedList.some((value, index) => String(value).toLowerCase() !== claimSenders[index]))) {
1600
1622
  existing.claimSenders = claimSenders;
1601
- existing.claimSender = claimSenders[0];
1602
1623
  try { engine.swap.saveSwap(existing, store); }
1603
1624
  catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1604
1625
  } else if (!explicitSenders && !storedList && claimSenders.length) {
1605
1626
  existing.claimSenders = claimSenders;
1606
- existing.claimSender = claimSenders[0];
1607
1627
  try { engine.swap.saveSwap(existing, store); }
1608
1628
  catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1609
1629
  }
@@ -1636,7 +1656,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1636
1656
  address: (existing.escrow && existing.escrow.moneroAddress) || offer.jointAddress,
1637
1657
  xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
1638
1658
  claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
1639
- claimSender: existing.claimSender || null,
1640
1659
  claimSenders: Array.isArray(existing.claimSenders) ? existing.claimSenders : [],
1641
1660
  readyWindow: existing.readyWindow || existing.sellWindow || null,
1642
1661
  resumed: true, next: "send-xmr" };
@@ -1709,10 +1728,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1709
1728
  swap.claimTip = quote.claimTip || null;
1710
1729
  // THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping the list means a reload cannot silently
1711
1730
  // 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
- }
1731
+ if (claimSenders.length) swap.claimSenders = claimSenders;
1716
1732
  swap.expect = {
1717
1733
  chainId, factory: order.factory, locker: order.locker, claimer: order.claimer, amount: String(order.amount),
1718
1734
  readyBy: order.readyBy, t1: order.t1, salt: order.salt,
@@ -1748,7 +1764,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1748
1764
  try { engine.swap.saveSwap(swap, store); } catch { throw new SdkError("storage-unavailable", { step: "save-swap" }); }
1749
1765
  return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
1750
1766
  xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
1751
- claimSender: swap.claimSender || null,
1752
1767
  claimSenders: Array.isArray(swap.claimSenders) ? swap.claimSenders : [],
1753
1768
  readyWindow: swap.readyWindow || null, resumed: false, next: "send-xmr" };
1754
1769
  },
@@ -1820,13 +1835,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1820
1835
  }
1821
1836
  const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1822
1837
  || 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.
1838
+ if (request.claimSender !== undefined && request.claimSender !== null
1839
+ && String(request.claimSender).trim() !== "") {
1840
+ throw new SdkError("bad-input", { field: "claimSender", why: "retired" });
1841
+ }
1842
+ // THE ORDER IS THE CLIENT'S, NOT THE RECORD'S. A list passed now wins; otherwise the stored list is the
1843
+ // fallback for an id-only reload. There is no legacy scalar and no second source.
1830
1844
  if (request.claimSenders !== undefined && !Array.isArray(request.claimSenders)) {
1831
1845
  throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
1832
1846
  }
@@ -1834,12 +1848,10 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1834
1848
  if (explicitList && explicitList.length === 0) {
1835
1849
  throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1836
1850
  }
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] : []);
1851
+ const legacyStored = swap.claimSender === undefined || swap.claimSender === null
1852
+ || String(swap.claimSender).trim() === "" ? null : swap.claimSender;
1853
+ const rawSenders = explicitList || (Array.isArray(swap.claimSenders) && swap.claimSenders.length
1854
+ ? swap.claimSenders : (legacyStored ? [legacyStored] : []));
1843
1855
  if (!rawSenders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
1844
1856
  const senders = [];
1845
1857
  for (const raw of rawSenders) {
@@ -1871,11 +1883,19 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1871
1883
  }
1872
1884
  }
1873
1885
  // 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.
1886
+ // answer; a later request that brings its own order ignores it. The retired scalar is removed even when the
1887
+ // list already matches, so a migrated record cannot keep two sources.
1888
+ let sendersChanged = false;
1875
1889
  if (!Array.isArray(swap.claimSenders) || swap.claimSenders.length !== senders.length
1876
1890
  || swap.claimSenders.some((value, index) => String(value).toLowerCase() !== senders[index])) {
1877
1891
  swap.claimSenders = senders;
1878
- swap.claimSender = senders[0];
1892
+ sendersChanged = true;
1893
+ }
1894
+ if (Object.prototype.hasOwnProperty.call(swap, "claimSender")) {
1895
+ delete swap.claimSender;
1896
+ sendersChanged = true;
1897
+ }
1898
+ if (sendersChanged) {
1879
1899
  try { engine.swap.saveSwap(swap, store); }
1880
1900
  catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1881
1901
  }
@@ -1901,7 +1921,8 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1901
1921
  };
1902
1922
  const t1Raw = order.t1 ?? (swap.expect && swap.expect.t1);
1903
1923
  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)));
1924
+ // THE TIME LEFT IS THE CHAIN'S TIME. It is null until the same clock used by windowOf has been read.
1925
+ const secondsLeft = () => (t1 === null || observedNowSec === null ? null : Math.max(0, t1 - observedNowSec));
1905
1926
  // THE CLAIM WINDOW BELONGS TO THE CONTRACT, NOT TO THE RELAY. The relay can forward any half it is given, so
1906
1927
  // the client must refuse to hand it over before `readyBy` without the ready mark, after `t1`, and inside the
1907
1928
  // settlement margin when neither a sender nor the seller's own claim can still land. The check reads the
@@ -1910,15 +1931,23 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1910
1931
  const CLAIM_MARGIN_SEC = 120;
1911
1932
  const SELLER_CLAIM_SEC = 60;
1912
1933
  const windowOf = async () => {
1934
+ let nowSec;
1935
+ try { nowSec = await chainNowSec(); }
1936
+ catch { nowSec = null; }
1937
+ if (!Number.isSafeInteger(nowSec) || nowSec <= 0) {
1938
+ observedNowSec = null;
1939
+ return { ok: false, reason: "unreadable" };
1940
+ }
1941
+ observedNowSec = nowSec;
1913
1942
  let deadlines;
1914
1943
  try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
1915
1944
  catch { return { ok: false, reason: "unreadable" }; }
1916
1945
  const t1Sec = Number(deadlines.t1);
1917
1946
  const readyBySec = Number(deadlines.readyBy);
1918
- const nowSec = Math.floor(clockMs() / 1000);
1919
- if (![t1Sec, readyBySec, nowSec].every(Number.isSafeInteger)) {
1947
+ if (![t1Sec, readyBySec].every(Number.isSafeInteger)) {
1920
1948
  return { ok: false, reason: "unreadable" };
1921
1949
  }
1950
+ if (Number.isSafeInteger(t1Sec)) t1 = t1Sec;
1922
1951
  let marked;
1923
1952
  try {
1924
1953
  const raw = await reader({ to: escrow, data: engine.evm.encodeRead("ready") });
@@ -1934,7 +1963,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1934
1963
  return { ok: true, t1: t1Sec, readyBy: readyBySec, nowSec };
1935
1964
  };
1936
1965
  const windowResult = (reason, tried) => ({
1937
- id, state: "claim-window", reason, provider: null, claimSender: null, escrow, relayUrl,
1966
+ id, state: "claim-window", reason, provider: null, escrow, relayUrl,
1938
1967
  txid: null, from: null, tipWei: tip.toString(), t1, secondsLeft: secondsLeft(), tried,
1939
1968
  });
1940
1969
  const STOP_ESCROW_CODES = new Set([
@@ -1942,46 +1971,93 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1942
1971
  "claim-not-funded", "claim-already-closed", "claim-half-invalid",
1943
1972
  ]);
1944
1973
  const claimedByEscrow = (sender = null, answer = null, tried = []) => ({
1945
- id, state: "claimed", provider: sender, claimSender: sender, escrow, relayUrl,
1974
+ id, state: "claimed", provider: sender, escrow, relayUrl,
1946
1975
  txid: answer ? answer.txid : null, from: (answer && answer.from) || null,
1947
1976
  tipWei: (answer && answer.tipWei) || tip.toString(), tried,
1948
1977
  });
1978
+ // A WINDOW STOP AFTER SENDS IS NOT A BLIND STOP. The last sender's claim can land just after its slot; before
1979
+ // reporting a closing window, read the escrow once more and let a claimed/refunded/defunded state win.
1980
+ const windowStop = async (reason, currentTried) => {
1981
+ let status;
1982
+ try {
1983
+ status = await readStatus();
1984
+ } catch {
1985
+ // THE WINDOW STOP MUST STAY A RESULT. If the escrow cannot be read, the caller still needs the named
1986
+ // window state; throwing here would change a pre-existing `claim-window` answer into an exception.
1987
+ return windowResult(reason, currentTried);
1988
+ }
1989
+ if (status.isClaimed) {
1990
+ try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
1991
+ return claimedByEscrow(null, null, currentTried);
1992
+ }
1993
+ if (status.isRefunded) return windowResult("escrow-refunded", currentTried);
1994
+ if (!status.isFunded) return windowResult("not-funded", currentTried);
1995
+ return windowResult(reason, currentTried);
1996
+ };
1949
1997
  // A CLAIM THAT ALREADY LANDED IS NOT A REASON TO SEND THE HALF AGAIN. The caller may have lost the answer on
1950
1998
  // the previous attempt; read the escrow before the first POST, and read it once more before returning
1951
1999
  // `claim-yourself`, so a late claim cannot be reported as "claim yourself".
1952
- const initial = await readStatus();
2000
+ const priorAttempts = Array.isArray(swap.claimAttempts) ? swap.claimAttempts : [];
2001
+ let initial;
2002
+ try {
2003
+ initial = await readStatus();
2004
+ } catch (error) {
2005
+ // NOTHING HAS BEEN SENT IN THIS CALL. Without an earlier attempt this is a pre-send refusal, not "the claim
2006
+ // may already have been sent"; the window result says the clock/escrow could not be read.
2007
+ if (!priorAttempts.length && error && error.code === "claim-unknown"
2008
+ && error.params && error.params.why === "escrow-unread") {
2009
+ return windowResult("unreadable", []);
2010
+ }
2011
+ throw error;
2012
+ }
1953
2013
  if (initial.isClaimed) return claimedByEscrow();
1954
2014
  if (!initial.isFunded) return windowResult("not-funded", []);
1955
2015
  let refunded = Boolean(initial.isRefunded);
1956
2016
  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()));
2017
+ // A SENDER THAT MAY HAVE RECEIVED THE HALF IS NOT A DONE MARK. The record gets the sender before the POST, so
2018
+ // a crash or a lost answer leaves a durable trace; a later call reads the escrow and may try the same sender
2019
+ // again. Only a sender whose slot is still running is held back, and even then the slot is polled rather than
2020
+ // allowed to block the list forever.
1963
2021
  const priorTried = priorAttempts.map((entry) => ({
1964
2022
  sender: entry.sender, outcome: entry.outcome || "unknown", code: entry.code || null,
1965
2023
  params: entry.params || null, txid: entry.txid || null,
1966
2024
  }));
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 };
2025
+ const latest = priorAttempts[priorAttempts.length - 1];
2026
+ if (latest && (latest.outcome === "sending" || latest.outcome === "unknown")
2027
+ && Number.isFinite(Number(latest.at))) {
2028
+ const gate = await windowOf();
2029
+ if (!gate.ok) {
2030
+ // A PRIOR ATTEMPT MAY HAVE SENT THE HALF. The same late-read rule as the sender loop applies here: do not
2031
+ // report a closing window without one last escrow read.
2032
+ return priorTried.length ? windowStop(gate.reason, priorTried)
2033
+ : windowResult(gate.reason, priorTried);
2034
+ }
2035
+ // AN OLD RECORD MAY CARRY A DEVICE-CLOCK `at` AHEAD OF CHAIN TIME. A slot is 15-30 s by construction, so cap
2036
+ // the wait at one slot from the chain clock instead of trusting a future timestamp indefinitely.
2037
+ const slotEnd = Math.min(Number(latest.at) + Math.ceil(slotMs / 1000),
2038
+ observedNowSec + Math.ceil(slotMs / 1000));
2039
+ while (observedNowSec !== null && observedNowSec < slotEnd) {
2040
+ const status = await readStatus();
2041
+ if (status && status.isClaimed) return claimedByEscrow(latest.sender, null, priorTried);
2042
+ if (status && status.isRefunded) return windowResult("escrow-refunded", priorTried);
2043
+ const waitMs = Math.max(1, Math.min(pollMs, (slotEnd - observedNowSec) * 1000));
2044
+ await sleepFor(waitMs);
2045
+ const next = await chainNowSec();
2046
+ if (!Number.isSafeInteger(next) || next <= 0) {
2047
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "clock-unreadable" });
2048
+ }
2049
+ observedNowSec = next;
2050
+ }
1977
2051
  }
2052
+ if (refunded) return windowResult("escrow-refunded", priorTried);
1978
2053
  const persistAttempts = (entry, outcome, extra = {}) => {
1979
2054
  if (entry) Object.assign(entry, { outcome, ...extra });
1980
2055
  try { engine.swap.saveSwap(swap, store); }
1981
2056
  catch { throw new SdkError("storage-unavailable", { step: "save-claim-attempt" }); }
1982
2057
  };
1983
2058
  const beginAttempt = (sender) => {
1984
- const entry = { sender, at: Math.floor(clockMs() / 1000), outcome: "sending" };
2059
+ const at = Number.isSafeInteger(observedNowSec) ? observedNowSec : Math.floor(clockMs() / 1000);
2060
+ const entry = { sender, at, outcome: "sending" };
1985
2061
  swap.claimAttempts = [...(Array.isArray(swap.claimAttempts) ? swap.claimAttempts : []), entry];
1986
2062
  persistAttempts(entry, "sending");
1987
2063
  return entry;
@@ -1989,9 +2065,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1989
2065
  const finishAttempt = (entry, outcome, extra = {}) => {
1990
2066
  try { persistAttempts(entry, outcome, extra); } catch { /* the chain answer is already known */ }
1991
2067
  };
1992
- if (!refunded) for (const sender of pendingSenders) {
2068
+ if (!refunded) for (const sender of senders) {
1993
2069
  const gate = await windowOf();
1994
- if (!gate.ok) return windowResult(gate.reason, tried);
2070
+ if (!gate.ok) {
2071
+ if (tried.length || priorTried.length) return windowStop(gate.reason, tried);
2072
+ return windowResult(gate.reason, tried);
2073
+ }
1995
2074
  if (gate.t1 !== null) t1 = gate.t1;
1996
2075
  const attempt = beginAttempt(sender);
1997
2076
  // THE SLOT STARTS WHEN THE SENDER IS ENTERED, NOT WHEN ITS POST RETURNS. A slow POST must not stretch the
@@ -2028,7 +2107,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
2028
2107
  for (;;) {
2029
2108
  const status = await readStatus();
2030
2109
  if (status && status.isClaimed) {
2031
- swap.claimSender = sender;
2032
2110
  finishAttempt(attempt, "claimed", { txid: answer ? answer.txid : null });
2033
2111
  try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
2034
2112
  return claimedByEscrow(sender, answer, tried);
@@ -2058,7 +2136,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
2058
2136
  const finalGate = await windowOf();
2059
2137
  if (!finalGate.ok) return windowResult(finalGate.reason, tried);
2060
2138
  return { id, state: "claim-yourself", reason: "senders-exhausted",
2061
- provider: null, claimSender: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
2139
+ provider: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
2062
2140
  t1, secondsLeft: secondsLeft(), tried };
2063
2141
  },
2064
2142
 
@@ -2122,6 +2200,15 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
2122
2200
  ready = hex.length > 0 && BigInt("0x" + hex) !== 0n;
2123
2201
  } catch (error) { lastError = (error && error.code) || "ready-unread"; }
2124
2202
  if (ready === true) {
2203
+ // A ready mark after t1 is not a usable sell window: the contract's claim is already closed. Name it
2204
+ // as a claim-window state instead of returning `ready` and letting the host promise a claim.
2205
+ const t1 = deadlines ? Number(deadlines.t1) : null;
2206
+ const at = nowSec();
2207
+ if (Number.isSafeInteger(t1) && at !== null && at >= t1) {
2208
+ return { escrow, state: "claim-window-closed", funded: true, claimed: false, refunded: false,
2209
+ ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
2210
+ t1, secondsLeft: 0 };
2211
+ }
2125
2212
  return { escrow, state: "ready", funded: true, claimed: false, refunded: false,
2126
2213
  ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
2127
2214
  }
package/src/version.mjs CHANGED
@@ -6,4 +6,4 @@
6
6
  // tools/sync-version.mjs. Do not edit it by hand - set the version in package.json and run `npm run sync:version`.
7
7
  // The `version` check in tools/check.mjs refuses a mismatch, and refuses a runtime read of package.json here.
8
8
 
9
- export const SDK_VERSION = "0.60.0";
9
+ export const SDK_VERSION = "0.61.0";