@ninsei-labs/sdk 0.59.0 → 0.60.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.
package/src/swaps.mjs CHANGED
@@ -15,6 +15,7 @@ import * as recordModule from "./record.mjs";
15
15
  // The order: our own side is built by the engine's builder, the counterparty's side is verified and accepted, and
16
16
  // the joint address is assembled from the halves. There are no formulas of our own in the core - see order.mjs.
17
17
  import { buildOwnSideFromHalvesKnown, contextOf, halfHex, norm, normalizeCounterpartyView, orderStepChunked } from "./order.mjs";
18
+ import { predictEscrow } from "./predictEscrow.mjs";
18
19
  // Locking the funds: sending goes through the already-finished step (`lock.send`), the wallet is an adapter from outside.
19
20
  import * as lock from "./lock.mjs";
20
21
  import * as flow from "./swap-flow.mjs";
@@ -449,10 +450,13 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
449
450
  };
450
451
  if (!lockerHalf.commitHalfLocker || !lockerHalf.edPointLocker || !lockerHalf.edViewPointLocker) return null;
451
452
  try {
452
- const raw = await reader({ to: factory, data: engine.evm.encodePredict({ ...quote, ...lockerHalf, factory }) });
453
- return engine.evm.decodeAddress(raw);
454
- } catch {
455
- return null;
453
+ return await predictEscrow({ quote, order, call: reader });
454
+ } catch (error) {
455
+ // A RETRY MUST NOT REPORT A CHAIN READ AS A MISSING ARGUMENT. The caller already brought the signed quote;
456
+ // "bring an escrow" cannot fix a factory that did not answer. A coded refusal keeps its own identity; a bare
457
+ // transport/decode failure becomes the factory check that could not be made.
458
+ if (error instanceof SdkError) throw error;
459
+ throw new SdkError("quote-factory-unchecked", { step: "factory", why: "predict-failed" });
456
460
  }
457
461
  };
458
462
  // THE INSTANCE TRANSPORT IS THE DEFAULT, NOT BACKGROUND MAGIC. A per-call `fetch` still wins; otherwise every
@@ -924,8 +928,24 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
924
928
 
925
929
  // RESUME BEFORE ANY NEW SIDE OR SEND. The previous start may have sent the deposit and lost the receipt;
926
930
  // reusing its hash is the only way to learn the escrow without a second payment.
927
- const saltForResume = request.recoverySalt || (request.order && request.order.salt) ||
931
+ const explicitSalt = request.recoverySalt;
932
+ const rawSaltForResume = request.recoverySalt || (request.order && request.order.salt) ||
928
933
  (request.orderQuote && request.orderQuote.salt) || null;
934
+ // THE SALT THAT MATCHES THE PENDING ROW IS THE CANONICAL ONE. A caller may pass a number or a bigint
935
+ // (`StartRequest.recoverySalt` allows all three); the record holds hex, so the raw value would miss the row
936
+ // after a reload and start a second deposit. Canonicalise once, before the identity lookup.
937
+ let saltForResume = null;
938
+ try {
939
+ saltForResume = rawSaltForResume === null || rawSaltForResume === undefined || rawSaltForResume === ""
940
+ ? null : recoverySaltOf(rawSaltForResume);
941
+ } catch {
942
+ // AN INVALID SALT THE CALLER NAMED IS A REFUSAL, NOT "NO SALT". Falling through to the salt-less path
943
+ // would hide a malformed input behind a different diagnosis; an absent salt is the only case that may.
944
+ if (explicitSalt !== undefined && explicitSalt !== null && String(explicitSalt).trim() !== "") {
945
+ throw new SdkError("bad-input", { field: "recoverySalt", why: "unreadable" });
946
+ }
947
+ saltForResume = null;
948
+ }
929
949
  const resumeIdentity = {
930
950
  salt: saltForResume,
931
951
  // THE QUOTE ID IS ONLY A SELECTOR. It lets a salt-less retry name the pending row and be refused loudly, but
@@ -1334,17 +1354,21 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1334
1354
  const wantExpect = request.expect !== undefined && request.expect !== null;
1335
1355
  const wantWallet = request.wallet !== undefined && request.wallet !== null;
1336
1356
  if (wantExpect !== wantWallet) throw new SdkError("bad-input", { field: wantExpect ? "wallet" : "expect" });
1337
- if (wantExpect && !(request.escrow || request.address)) throw new SdkError("bad-input", { field: "escrow" });
1338
- const storedSwap = (() => { try { return engine.swap.getSwap(id, store); } catch { return null; } })();
1357
+ // THE RECORD IS READ ONCE. It supplies the escrow for the auto ready-mark and the joint Monero address for
1358
+ // the result; `request.address` was never part of the public watch request.
1359
+ const record = (() => { try { return engine.swap.getSwap(id, store); } catch { return null; } })();
1360
+ const storedSwap = record;
1361
+ const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
1362
+ if (wantExpect && !escrowAddress) throw new SdkError("bad-input", { field: "escrow" });
1339
1363
  const readyWindowRaw = request.readyWindow || (storedSwap && (storedSwap.readyWindow || storedSwap.sellWindow)) || null;
1340
1364
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0 ? Number(request.pollMs) : limitOf("watchPollMs", 5000);
1341
1365
  const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : limitOf("watchTimeoutMs", 1_200_000);
1342
1366
  // THE CONFIRMATION TARGET - FROM THE CONFIGURATION (one number, the owner's decision: 10).
1343
1367
  const minConfirmations = Number.isFinite(Number(request.minConfirmations)) && Number(request.minConfirmations) > 0
1344
1368
  ? Math.trunc(Number(request.minConfirmations)) : limitOf("xmrConfirmations", 10);
1345
- // THE CLIENT-SIDE CHECK IS OPT-IN BY ITS DATA: it needs the joint address, the joint view secret and the
1346
- // joint spend public key - all of which the client has and the backend no longer needs. Without them the
1347
- // watch keeps the service's answer (notifications only); with them the CLIENT decides.
1369
+ // THE CLIENT-SIDE CHECK IS THE WATCH: it needs the joint address, the joint view secret and the joint spend
1370
+ // public key - all of which the client has and the backend no longer needs. Without them the wait is refused
1371
+ // by name (`bad-input`/`verify`); the retired service answer is not a fallback.
1348
1372
  const verifyRequest = request.verify && typeof request.verify === "object"
1349
1373
  ? { ...request.verify,
1350
1374
  nodes: Array.isArray(request.verify.nodes) ? request.verify.nodes
@@ -1367,6 +1391,13 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1367
1391
  // the spend public key. Without them there is nothing to wait on: a named refusal, not a request to the
1368
1392
  // page's own origin and not a fallback to a retired backend.
1369
1393
  if (!verifyRequest) throw new SdkError("bad-input", { field: "verify", why: "required" });
1394
+ // THE JOINT MONERO ADDRESS IS THE ONE THE CLIENT CHECKS, NOT THE ESCROW. `verify.address` is the joint address;
1395
+ // the record's `moneroAddress` is the same value after a reload. The EVM escrow never leaves this method as
1396
+ // the XMR address, and it is the only address the auto ready-mark may receive.
1397
+ const moneroAddress = typeof verifyRequest.address === "string" && verifyRequest.address
1398
+ ? verifyRequest.address
1399
+ : (record && record.escrow && record.escrow.moneroAddress) || null;
1400
+ if (!moneroAddress) throw new SdkError("bad-input", { field: "verify.address", why: "not-in-record" });
1370
1401
  const started = Date.now();
1371
1402
  // --- THE MAKER'S DECLINE: THE WAIT IS NOT STARTED AT ALL (issue #40). -------------------------------------
1372
1403
  // A decline leaves the escrow `refunded`, so nothing in the state says "do not wait any longer": without
@@ -1381,9 +1412,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1381
1412
  // A STORAGE THAT CANNOT BE READ IS NOT A REASON TO REFUSE THE WAIT: the record is what makes the state
1382
1413
  // durable, and the escrow may also arrive in the request. The watch is not a new user of the store - and it
1383
1414
  // must not start failing where it did not before.
1384
- let record = null;
1385
- try { record = engine.swap.getSwap(id, store); } catch { record = null; }
1386
- const escrowAddress = request.escrow || (record && record.escrow && record.escrow.address) || null;
1387
1415
  // FROM THE ESCROW'S BIRTH HEIGHT when the record knows it: the event cannot be older than the funding, and
1388
1416
  // walking the whole chain every tick is a cost with no answer behind it.
1389
1417
  const fromBlock = blockBoundaryOf(record && record.escrow
@@ -1432,7 +1460,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1432
1460
  let last = null;
1433
1461
  for (;;) {
1434
1462
  await readDeclineLogs();
1435
- last = { address: request.address || escrowAddress, expectedXmr: request.expectedXmr ?? null, status: null };
1463
+ last = { address: moneroAddress, expectedXmr: request.expectedXmr ?? null, status: null };
1436
1464
  // THE DECLINE IS THE ESCROW'S EVENT, NOT THE SERVICE'S WORD. The legacy backend's `declined` status used
1437
1465
  // to become a settlement and end the wait; it no longer does. A service answer is at most a notification.
1438
1466
  const declineNow = declineOf({ logs: chainDecline.logs, escrow: escrowAddress, at: Date.now() });
@@ -1462,7 +1490,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1462
1490
  source: "client" };
1463
1491
  if (wantExpect && wantWallet) {
1464
1492
  verified.marked = await actions.markReady(
1465
- { escrow: request.escrow || last.address, expect: request.expect, onStep: request.onStep }, request.wallet);
1493
+ { escrow: escrowAddress, expect: request.expect, onStep: request.onStep }, request.wallet);
1466
1494
  } else {
1467
1495
  verified.next = "mark-ready";
1468
1496
  }
@@ -1512,12 +1540,41 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1512
1540
  || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1513
1541
  const requestedSender = request.claimSender === undefined || request.claimSender === null
1514
1542
  || String(request.claimSender).trim() === "" ? null : addressTextOf(request.claimSender, "claimSender");
1543
+ const requestedList = request.claimSenders === undefined || request.claimSenders === null
1544
+ ? null : request.claimSenders;
1545
+ if (requestedList !== null && !Array.isArray(requestedList)) {
1546
+ throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
1547
+ }
1548
+ if (requestedList && requestedList.length === 0) {
1549
+ throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1550
+ }
1551
+ if (requestedList && requestedSender) {
1552
+ throw new SdkError("bad-input", { field: "claimSenders", why: "with-claim-sender" });
1553
+ }
1515
1554
  if (requestedSender && requestedSender === dealMaker) {
1516
1555
  throw new SdkError("bad-input", { field: "claimSender", why: "is-deal-maker" });
1517
1556
  }
1518
1557
  if (requestedSender && quoteKeyOwner && requestedSender === quoteKeyOwner) {
1519
1558
  throw new SdkError("bad-input", { field: "claimSender", why: "is-quote-key" });
1520
1559
  }
1560
+ const offerSender = offer.claimSender === undefined || offer.claimSender === null
1561
+ || 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);
1565
+ const rawSenders = explicitSenders || (offerSender ? [offerSender] : []);
1566
+ const claimSenders = [];
1567
+ for (const raw of rawSenders) {
1568
+ if (raw === undefined || raw === null || String(raw).trim() === "") {
1569
+ throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1570
+ }
1571
+ const sender = addressTextOf(raw, "claimSenders");
1572
+ if (sender === dealMaker) throw new SdkError("bad-input", { field: "claimSenders", why: "is-deal-maker" });
1573
+ if (quoteKeyOwner && sender === quoteKeyOwner) {
1574
+ throw new SdkError("bad-input", { field: "claimSenders", why: "is-quote-key" });
1575
+ }
1576
+ if (!claimSenders.includes(sender)) claimSenders.push(sender);
1577
+ }
1521
1578
  // THE RECORD IS FOUND BEFORE A SECOND ONE IS MADE. The same offer retried after a reload yields the same
1522
1579
  // one-time address and escrow; a second record would be a second promise about one deal.
1523
1580
  const quoteId = quote.id || quote.nonce || null;
@@ -1534,14 +1591,21 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1534
1591
  || !same(existing.escrow && existing.escrow.moneroAddress, offer.jointAddress)) {
1535
1592
  throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
1536
1593
  }
1537
- const storedSender = existing.claimSender ? addressTextOf(existing.claimSender, "claimSender") : null;
1594
+ const storedList = Array.isArray(existing.claimSenders) ? existing.claimSenders : null;
1538
1595
  // THE OLD SCALAR IS NOT A PIN. A reload may name another sender or bring the ordered list at claim time; the
1539
- // record keeps the latest scalar only for callers that still use it.
1540
- if (requestedSender && requestedSender !== storedSender) {
1541
- existing.claimSender = requestedSender;
1542
- delete existing.claimSenders;
1596
+ // record keeps the latest list and its first sender for callers that still use the scalar. An offer-only
1597
+ // sender fills a record that has no list; it never replaces a list the client already chose.
1598
+ if (explicitSenders && claimSenders.length && (!storedList || storedList.length !== claimSenders.length
1599
+ || storedList.some((value, index) => String(value).toLowerCase() !== claimSenders[index]))) {
1600
+ existing.claimSenders = claimSenders;
1601
+ existing.claimSender = claimSenders[0];
1602
+ try { engine.swap.saveSwap(existing, store); }
1603
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1604
+ } else if (!explicitSenders && !storedList && claimSenders.length) {
1605
+ existing.claimSenders = claimSenders;
1606
+ existing.claimSender = claimSenders[0];
1543
1607
  try { engine.swap.saveSwap(existing, store); }
1544
- catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
1608
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1545
1609
  }
1546
1610
  // THE RELAY IS PART OF THE VERIFIED OFFER. A claim later goes to the origin that answered this quote, so
1547
1611
  // a resumed offer naming another origin is a different offer; one that now names the same origin fills a
@@ -1573,6 +1637,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1573
1637
  xmrAmount: (existing.escrow && existing.escrow.xmrAmount) || quote.xmrAmount,
1574
1638
  claimTip: existing.claimTip || quote.claimTip, orderQuote: existing.orderQuote || offer.orderQuote,
1575
1639
  claimSender: existing.claimSender || null,
1640
+ claimSenders: Array.isArray(existing.claimSenders) ? existing.claimSenders : [],
1576
1641
  readyWindow: existing.readyWindow || existing.sellWindow || null,
1577
1642
  resumed: true, next: "send-xmr" };
1578
1643
  }
@@ -1642,9 +1707,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1642
1707
  swap.orderQuote = offer.orderQuote || null;
1643
1708
  swap.quote = quote;
1644
1709
  swap.claimTip = quote.claimTip || null;
1645
- // THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping it means a reload cannot silently
1710
+ // THE CLAIM SENDER IS PART OF THE OFFER, NOT A LATER CHOICE. Keeping the list means a reload cannot silently
1646
1711
  // send the half to a different node than the one the client selected.
1647
- if (requestedSender) swap.claimSender = requestedSender;
1712
+ if (claimSenders.length) {
1713
+ swap.claimSenders = claimSenders;
1714
+ swap.claimSender = claimSenders[0];
1715
+ }
1648
1716
  swap.expect = {
1649
1717
  chainId, factory: order.factory, locker: order.locker, claimer: order.claimer, amount: String(order.amount),
1650
1718
  readyBy: order.readyBy, t1: order.t1, salt: order.salt,
@@ -1681,6 +1749,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1681
1749
  return { id: swap.id, side: "sell", escrow: offer.escrow, address: offer.jointAddress,
1682
1750
  xmrAmount: quote.xmrAmount, claimTip: quote.claimTip || null, orderQuote: offer.orderQuote || null,
1683
1751
  claimSender: swap.claimSender || null,
1752
+ claimSenders: Array.isArray(swap.claimSenders) ? swap.claimSenders : [],
1684
1753
  readyWindow: swap.readyWindow || null, resumed: false, next: "send-xmr" };
1685
1754
  },
1686
1755
 
@@ -1812,19 +1881,66 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1812
1881
  }
1813
1882
 
1814
1883
  const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
1815
- ? Number(request.timeoutMs) : 20_000;
1884
+ ? Math.min(120_000, Number(request.timeoutMs)) : 20_000;
1816
1885
  // ONE SENDER AT A TIME, EACH WITH ITS OWN SLOT. Refusal moves on immediately; an accepted/unknown answer is
1817
1886
  // followed by reading the escrow until it says claimed or the slot ends. A txid alone is never success.
1818
1887
  const slotMs = Number.isFinite(Number(request.slotMs)) && Number(request.slotMs) > 0
1819
1888
  ? Math.min(30_000, Math.max(15_000, Number(request.slotMs))) : 20_000;
1889
+ // A POLL UNDER 250 ms only burns chain reads, and a timeout above two minutes would hide a stuck sender
1890
+ // behind a wait the caller does not expect.
1820
1891
  const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
1821
- ? Math.min(slotMs, Number(request.pollMs)) : 2_000;
1892
+ ? Math.min(slotMs, Math.max(250, Number(request.pollMs))) : 2_000;
1822
1893
  const readStatus = async () => {
1823
- try { return await flow.orderStatus(escrow, { call: reader }); } catch { return null; }
1894
+ try { return await flow.orderStatus(escrow, { call: reader }); }
1895
+ catch (error) {
1896
+ // AN UNREAD ESCROW IS NOT AN OPEN ONE. The caller must not be told to claim a sale whose state we could
1897
+ // not read; the half may already have landed. This is the same unknown state as a lost relay answer.
1898
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "escrow-unread",
1899
+ detail: String((error && error.message) || error).slice(0, 160) });
1900
+ }
1824
1901
  };
1825
1902
  const t1Raw = order.t1 ?? (swap.expect && swap.expect.t1);
1826
- const t1 = Number.isSafeInteger(Number(t1Raw)) && Number(t1Raw) > 0 ? Number(t1Raw) : null;
1903
+ let t1 = Number.isSafeInteger(Number(t1Raw)) && Number(t1Raw) > 0 ? Number(t1Raw) : null;
1827
1904
  const secondsLeft = () => (t1 === null ? null : Math.max(0, t1 - Math.floor(clockMs() / 1000)));
1905
+ // THE CLAIM WINDOW BELONGS TO THE CONTRACT, NOT TO THE RELAY. The relay can forward any half it is given, so
1906
+ // the client must refuse to hand it over before `readyBy` without the ready mark, after `t1`, and inside the
1907
+ // settlement margin when neither a sender nor the seller's own claim can still land. The check reads the
1908
+ // escrow's ready mark and both deadlines for EVERY sender, not once for the whole list: a slot can cross a
1909
+ // boundary while the previous sender is being polled.
1910
+ const CLAIM_MARGIN_SEC = 120;
1911
+ const SELLER_CLAIM_SEC = 60;
1912
+ const windowOf = async () => {
1913
+ let deadlines;
1914
+ try { deadlines = await flow.orderDeadlines(escrow, { call: reader }); }
1915
+ catch { return { ok: false, reason: "unreadable" }; }
1916
+ const t1Sec = Number(deadlines.t1);
1917
+ const readyBySec = Number(deadlines.readyBy);
1918
+ const nowSec = Math.floor(clockMs() / 1000);
1919
+ if (![t1Sec, readyBySec, nowSec].every(Number.isSafeInteger)) {
1920
+ return { ok: false, reason: "unreadable" };
1921
+ }
1922
+ let marked;
1923
+ try {
1924
+ const raw = await reader({ to: escrow, data: engine.evm.encodeRead("ready") });
1925
+ marked = BigInt(String(raw || "").replace(/^0x/, "") || "0") !== 0n;
1926
+ } catch { return { ok: false, reason: "unreadable" }; }
1927
+ if (nowSec >= t1Sec) return { ok: false, reason: "window-closed" };
1928
+ // A SEND LANDS IN A LATER BLOCK. The last 120 s belong to the relay's settlement margin, and the seller
1929
+ // still needs a slot plus time for their own claim if the relay cannot land it.
1930
+ if (nowSec + CLAIM_MARGIN_SEC + Math.ceil(slotMs / 1000) + SELLER_CLAIM_SEC >= t1Sec) {
1931
+ return { ok: false, reason: "settlement-margin" };
1932
+ }
1933
+ if (nowSec < readyBySec && !marked) return { ok: false, reason: "not-ready" };
1934
+ return { ok: true, t1: t1Sec, readyBy: readyBySec, nowSec };
1935
+ };
1936
+ const windowResult = (reason, tried) => ({
1937
+ id, state: "claim-window", reason, provider: null, claimSender: null, escrow, relayUrl,
1938
+ txid: null, from: null, tipWei: tip.toString(), t1, secondsLeft: secondsLeft(), tried,
1939
+ });
1940
+ const STOP_ESCROW_CODES = new Set([
1941
+ "claim-not-ready", "claim-window-closed", "claim-settlement-margin",
1942
+ "claim-not-funded", "claim-already-closed", "claim-half-invalid",
1943
+ ]);
1828
1944
  const claimedByEscrow = (sender = null, answer = null, tried = []) => ({
1829
1945
  id, state: "claimed", provider: sender, claimSender: sender, escrow, relayUrl,
1830
1946
  txid: answer ? answer.txid : null, from: (answer && answer.from) || null,
@@ -1834,10 +1950,53 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1834
1950
  // the previous attempt; read the escrow before the first POST, and read it once more before returning
1835
1951
  // `claim-yourself`, so a late claim cannot be reported as "claim yourself".
1836
1952
  const initial = await readStatus();
1837
- if (initial && initial.isClaimed) return claimedByEscrow();
1838
- let refunded = Boolean(initial && initial.isRefunded);
1953
+ if (initial.isClaimed) return claimedByEscrow();
1954
+ if (!initial.isFunded) return windowResult("not-funded", []);
1955
+ let refunded = Boolean(initial.isRefunded);
1839
1956
  const tried = [];
1840
- if (!refunded) for (const sender of senders) {
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()));
1963
+ const priorTried = priorAttempts.map((entry) => ({
1964
+ sender: entry.sender, outcome: entry.outcome || "unknown", code: entry.code || null,
1965
+ params: entry.params || null, txid: entry.txid || null,
1966
+ }));
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 };
1977
+ }
1978
+ const persistAttempts = (entry, outcome, extra = {}) => {
1979
+ if (entry) Object.assign(entry, { outcome, ...extra });
1980
+ try { engine.swap.saveSwap(swap, store); }
1981
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-attempt" }); }
1982
+ };
1983
+ const beginAttempt = (sender) => {
1984
+ const entry = { sender, at: Math.floor(clockMs() / 1000), outcome: "sending" };
1985
+ swap.claimAttempts = [...(Array.isArray(swap.claimAttempts) ? swap.claimAttempts : []), entry];
1986
+ persistAttempts(entry, "sending");
1987
+ return entry;
1988
+ };
1989
+ const finishAttempt = (entry, outcome, extra = {}) => {
1990
+ try { persistAttempts(entry, outcome, extra); } catch { /* the chain answer is already known */ }
1991
+ };
1992
+ if (!refunded) for (const sender of pendingSenders) {
1993
+ const gate = await windowOf();
1994
+ if (!gate.ok) return windowResult(gate.reason, tried);
1995
+ if (gate.t1 !== null) t1 = gate.t1;
1996
+ const attempt = beginAttempt(sender);
1997
+ // THE SLOT STARTS WHEN THE SENDER IS ENTERED, NOT WHEN ITS POST RETURNS. A slow POST must not stretch the
1998
+ // 15-30 s slot into twice the advertised time.
1999
+ const slotStartedAt = clockMs();
1841
2000
  let answer = null;
1842
2001
  let failure = null;
1843
2002
  try {
@@ -1849,17 +2008,28 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1849
2008
  failure = error;
1850
2009
  }
1851
2010
  // A REFUSAL IS THE SENDER'S ANSWER, NOT A CLAIM IN FLIGHT. Move to the next one at once; only an unknown
1852
- // outcome (or a txid, which is not yet a claim on chain) deserves the slot.
2011
+ // outcome (or a txid, which is not yet a claim on chain) deserves the slot. An escrow-state refusal is
2012
+ // different: it says the order itself is closed, so trying another sender would publish the half for no
2013
+ // reason. Read the escrow and stop.
1853
2014
  if (failure && failure.code !== "claim-unknown") {
1854
- tried.push({ sender, outcome: "refused", code: failure.code || "unknown",
1855
- params: failure.params || null });
2015
+ const refused = { sender, outcome: "refused", code: failure.code || "unknown",
2016
+ params: failure.params || null };
2017
+ tried.push(refused);
2018
+ finishAttempt(attempt, "refused", { code: refused.code, params: refused.params });
2019
+ if (STOP_ESCROW_CODES.has(String((failure.params && failure.params.code) || ""))) {
2020
+ const stopped = await readStatus();
2021
+ if (stopped.isClaimed) return claimedByEscrow(sender, null, tried);
2022
+ if (stopped.isRefunded) return windowResult("escrow-refunded", tried);
2023
+ return windowResult("escrow-refused", tried);
2024
+ }
1856
2025
  continue;
1857
2026
  }
1858
- const slotEnd = clockMs() + slotMs;
2027
+ const slotEnd = slotStartedAt + slotMs;
1859
2028
  for (;;) {
1860
2029
  const status = await readStatus();
1861
2030
  if (status && status.isClaimed) {
1862
2031
  swap.claimSender = sender;
2032
+ finishAttempt(attempt, "claimed", { txid: answer ? answer.txid : null });
1863
2033
  try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
1864
2034
  return claimedByEscrow(sender, answer, tried);
1865
2035
  }
@@ -1868,20 +2038,26 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1868
2038
  if (left <= 0) break;
1869
2039
  await sleepFor(Math.min(pollMs, left));
1870
2040
  }
1871
- tried.push({ sender, outcome: failure ? "unknown" : "unconfirmed",
1872
- txid: answer ? answer.txid : null, code: failure ? failure.code : null });
2041
+ const ended = { sender, outcome: failure ? "unknown" : "unconfirmed",
2042
+ txid: answer ? answer.txid : null, code: failure ? failure.code : null };
2043
+ tried.push(ended);
2044
+ finishAttempt(attempt, ended.outcome, { txid: ended.txid, code: ended.code });
1873
2045
  if (refunded) break;
1874
2046
  }
1875
2047
 
1876
2048
  // THE LAST LOOK BEFORE THE FALLBACK. A claim can land after the last slot ended or while a later sender is
1877
2049
  // refusing; the seller must not be sent to `sellClaim` on an escrow that is already closed as claimed.
1878
2050
  const finalStatus = await readStatus();
1879
- if (finalStatus && finalStatus.isClaimed) {
2051
+ if (finalStatus.isClaimed) {
1880
2052
  try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
1881
2053
  return claimedByEscrow(null, null, tried);
1882
2054
  }
1883
- if (finalStatus && finalStatus.isRefunded) refunded = true;
1884
- return { id, state: "claim-yourself", reason: refunded ? "escrow-refunded" : "senders-exhausted",
2055
+ if (finalStatus.isRefunded) refunded = true;
2056
+ if (!finalStatus.isFunded) return windowResult("not-funded", tried);
2057
+ if (refunded) return windowResult("escrow-refunded", tried);
2058
+ const finalGate = await windowOf();
2059
+ if (!finalGate.ok) return windowResult(finalGate.reason, tried);
2060
+ return { id, state: "claim-yourself", reason: "senders-exhausted",
1885
2061
  provider: null, claimSender: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
1886
2062
  t1, secondsLeft: secondsLeft(), tried };
1887
2063
  },
@@ -1950,13 +2126,23 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1950
2126
  ready: true, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
1951
2127
  }
1952
2128
  }
1953
- // AFTER readyBy THE CLAIM IS OPEN EVEN WITHOUT THE NODE'S READY MARK. The order is funded, no terminal
1954
- // action was seen, and the escrow's own deadline has passed; the seller can claim the ETH now.
1955
- if (lastStatus && lastStatus.isFunded && deadlines && Number.isSafeInteger(Number(deadlines.readyBy))) {
2129
+ // AFTER readyBy THE CLAIM IS OPEN EVEN WITHOUT THE NODE'S READY MARK - BUT ONLY BEFORE t1. Without a
2130
+ // readable t1 the SDK cannot promise a claim window, so it keeps waiting instead of opening one on a
2131
+ // guess. The last 60 s are closed because a claim lands in a later block.
2132
+ if (lastStatus && lastStatus.isFunded && deadlines) {
2133
+ const readyBy = Number(deadlines.readyBy);
2134
+ const t1 = Number(deadlines.t1);
1956
2135
  const at = nowSec();
1957
- if (at !== null && at >= Number(deadlines.readyBy)) {
2136
+ if (Number.isSafeInteger(readyBy) && Number.isSafeInteger(t1) && at !== null && at >= readyBy) {
2137
+ const secondsLeft = Math.max(0, t1 - at);
2138
+ if (at + 60 >= t1) {
2139
+ return { escrow, state: "claim-window-closed", funded: true, claimed: false, refunded: false,
2140
+ ready: false, claimOpen: false, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
2141
+ t1, secondsLeft };
2142
+ }
1958
2143
  return { escrow, state: "claim-open", funded: true, claimed: false, refunded: false,
1959
- ready: false, claimOpen: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started };
2144
+ ready: false, claimOpen: true, balanceWei: String(lastStatus.balance), waitedMs: Date.now() - started,
2145
+ t1, secondsLeft };
1960
2146
  }
1961
2147
  }
1962
2148
  if (Date.now() - started >= timeoutMs) {
package/src/sweep.mjs CHANGED
@@ -175,7 +175,7 @@ const feeOf = async (wallet, signed) => {
175
175
  return /^\d+$/.test(text) ? text : null;
176
176
  };
177
177
 
178
- export function createSweep({ call = null }) {
178
+ export function createSweep({ call = null, fetchImpl = null } = {}) {
179
179
  // THE NAME IS NEEDED BY THE OBJECT ITSELF: `run` calls `api.plan(...)` - the step order is held by the plan and
180
180
  // the withdrawal living in one object, not in two copies. During a manual merge of branches the object was left
181
181
  // unnamed, and the withdrawal failed with "api is not defined": not a refusal, but a breakdown. `node --check`
@@ -336,7 +336,14 @@ export function createSweep({ call = null }) {
336
336
  // spendable - re-check the spent status once. The wallet is the same withdrawal adapter `sign` takes; the page
337
337
  // no longer decides when a second pass is needed.
338
338
  async restore(request) {
339
- return await restoreWallet(request || {});
339
+ const merged = { ...(request || {}) };
340
+ if (merged.fetchImpl !== undefined && merged.fetchImpl !== null && typeof merged.fetchImpl !== "function") {
341
+ throw new SdkError("bad-input", { field: "fetchImpl" });
342
+ }
343
+ // THE INSTANCE TRANSPORT REACHES THE WINDOW AND KEY-IMAGE READS TOO. A per-call `fetchImpl` still wins;
344
+ // without this fallback a Tor/proxy caller's restore would silently use the page's global fetch.
345
+ if (typeof merged.fetchImpl !== "function" && typeof fetchImpl === "function") merged.fetchImpl = fetchImpl;
346
+ return await restoreWallet(merged);
340
347
  },
341
348
 
342
349
  // THE WITHDRAWAL ITSELF. The wallet arrives as an adapter (the WASM and the worker live with whoever builds the
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.59.0";
9
+ export const SDK_VERSION = "0.60.0";
@@ -490,6 +490,7 @@ async function locateInSlices(node, { expectedAtomic, address, viewSecret, spend
490
490
  const last = witnessSliceIndex(Math.min(toHeight, target));
491
491
  let best = null;
492
492
  let completed = false;
493
+ let servedTop = null;
493
494
  let failure = null;
494
495
  for (let index = first; index <= last; index++) {
495
496
  let slice;
@@ -506,6 +507,9 @@ async function locateInSlices(node, { expectedAtomic, address, viewSecret, spend
506
507
  failure = error;
507
508
  break;
508
509
  }
510
+ // THE HIGHEST BLOCK THE WITNESS ACTUALLY SERVED. A newer tip can arrive inside the last slice; the caller
511
+ // uses this to raise the common target, so a walk that stopped at 115 cannot complete a target of 116.
512
+ servedTop = servedTop === null ? slice.to : Math.max(servedTop, slice.to);
509
513
  for (const block of slice.blocks) {
510
514
  // THE SLICE IS A FIXED WINDOW; THE SWAP STARTS AT `fromHeight`. Blocks before the birth height may contain
511
515
  // an earlier transfer to the same address, and counting them would make the slice walk disagree with the
@@ -536,7 +540,7 @@ async function locateInSlices(node, { expectedAtomic, address, viewSecret, spend
536
540
  }
537
541
  if (index === last) completed = slice.to >= target;
538
542
  }
539
- return { located: best, completed, failure };
543
+ return { located: best, completed, servedTop, failure };
540
544
  }
541
545
 
542
546
  /**
@@ -612,9 +616,7 @@ export async function verifyArrivalShadow(request) {
612
616
  highestTop = highestTop === null ? top : Math.max(highestTop, top);
613
617
  readable.push({ node, top, entry });
614
618
  }
615
- let located = null;
616
- let completed = false;
617
- const completedWitnessOperators = new Set();
619
+ const walkResults = [];
618
620
  for (const { node, top, entry } of readable) {
619
621
  const targetTop = highestTop === null ? top : Math.max(top, highestTop);
620
622
  try {
@@ -623,33 +625,52 @@ export async function verifyArrivalShadow(request) {
623
625
  targetTop,
624
626
  nowSec, network, fetchImpl, timeoutMs,
625
627
  });
626
- completed = completed || found.completed;
627
- if (found.completed) completedWitnessOperators.add(node.operator || node.url);
628
- if (found.failure) {
629
- failed.push(failureOf(found.failure, node));
630
- entry.state = "error";
631
- } else if (!found.completed) entry.state = found.located ? "partial" : "behind";
632
- if (found.located) {
633
- observations.push({
634
- operator: node.operator || node.url, url: node.url, seen: true, completed: found.completed,
635
- txid: found.located.txid, height: found.located.height, blockHash: found.located.blockHash,
636
- amountAtomic: found.located.amountAtomic.toString(), locked: found.located.locked === true,
637
- });
638
- if (!located || found.located.score > located.score) {
639
- located = found.located;
640
- located.operator = node.operator;
641
- located.url = node.url;
642
- }
643
- } else if (found.completed) {
644
- observations.push({ operator: node.operator || node.url, url: node.url, seen: false, completed: true,
645
- txid: null, height: null, blockHash: null, amountAtomic: null, locked: null });
646
- }
628
+ walkResults.push({ node, top, entry, found });
647
629
  } catch (error) {
648
630
  entry.state = "error";
649
631
  failed.push(failureOf(error, node));
650
632
  }
651
633
  }
652
634
 
635
+ // THE TARGET CAN MOVE DURING THE WALK. A witness may serve a tip newer than every `get_info` top, and the
636
+ // parser accepts it; the earlier target would let the other witnesses complete against a block they never read.
637
+ // Raise the target to the highest served tip and judge completion again, after every walk.
638
+ for (const { found } of walkResults) {
639
+ if (found.servedTop === null || found.servedTop === undefined) continue;
640
+ highestTop = highestTop === null ? found.servedTop : Math.max(highestTop, found.servedTop);
641
+ }
642
+
643
+ let located = null;
644
+ let completed = false;
645
+ const completedWitnessOperators = new Set();
646
+ for (const { node, entry, found } of walkResults) {
647
+ const finalCompleted = Boolean(found.completed && found.servedTop !== null
648
+ && highestTop !== null && found.servedTop >= highestTop);
649
+ if (found.failure) {
650
+ failed.push(failureOf(found.failure, node));
651
+ entry.state = "error";
652
+ } else {
653
+ entry.state = finalCompleted ? "ok" : (found.located ? "partial" : "behind");
654
+ }
655
+ completed = completed || finalCompleted;
656
+ if (finalCompleted) completedWitnessOperators.add(node.operator || node.url);
657
+ if (found.located) {
658
+ observations.push({
659
+ operator: node.operator || node.url, url: node.url, seen: true, completed: finalCompleted,
660
+ txid: found.located.txid, height: found.located.height, blockHash: found.located.blockHash,
661
+ amountAtomic: found.located.amountAtomic.toString(), locked: found.located.locked === true,
662
+ });
663
+ if (!located || found.located.score > located.score) {
664
+ located = found.located;
665
+ located.operator = node.operator;
666
+ located.url = node.url;
667
+ }
668
+ } else if (finalCompleted) {
669
+ observations.push({ operator: node.operator || node.url, url: node.url, seen: false, completed: true,
670
+ txid: null, height: null, blockHash: null, amountAtomic: null, locked: null });
671
+ }
672
+ }
673
+
653
674
  if (!located) failed.push(...staleWitnesses);
654
675
  const completedOperators = [...completedWitnessOperators];
655
676
  const independentOperators = completedOperators.filter((operator) => String(operator).toLowerCase() !== "ninsei");
@@ -734,6 +755,7 @@ export async function verifyArrivalShadow(request) {
734
755
  witnessDisagreements.push({ operators: [observation.operator], field: "amountAtomic", against: "exact" });
735
756
  }
736
757
  }
758
+ if (checked.some((entry) => entry.state !== "ok")) add("witness:not-completed");
737
759
  if (witnessDisagreements.length) add("witness:disagreement");
738
760
  agrees = problems.length === 0;
739
761
  } else if (located) {