@ninsei-labs/sdk 0.58.0 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/record.mjs CHANGED
@@ -64,6 +64,10 @@ export function createRecord(input, { order = null, side: knownSide = null, stor
64
64
  if (atomic <= 0n) throw new SdkError("bad-input", { field: "expectedAtomic" });
65
65
  escrow.expectedAtomic = atomic.toString();
66
66
  }
67
+ // THE ORDER IDENTITY SURVIVES A RELOAD. Pending funding is resumed only for the same chain, factory and predicted
68
+ // escrow; the salt alone does not prove that a record belongs to this start.
69
+ if (input.chainId !== undefined && input.chainId !== null) escrow.chainId = String(input.chainId);
70
+ if (input.factory !== undefined && input.factory !== null) escrow.factory = String(input.factory);
67
71
  // THE SIDE'S ENCRYPTION KEY - only the public one: the private one stays with the side and never enters the record.
68
72
  if (side.enc && side.enc.pub) escrow.encPub = norm(side.enc.pub);
69
73
  const record = { ...swap, escrow };
package/src/swaps.mjs CHANGED
@@ -5,7 +5,7 @@
5
5
  // order and halves -> server -> watching the Monero address. A lock without a recovery file is a lock with nothing
6
6
  // to open it with if the browser is lost, so the confirmation stands BEFORE anything that locks funds.
7
7
  import { SdkError } from "./errors.mjs";
8
- import { LOCK_START_MARGIN_SEC } from "./quotePolicy.mjs";
8
+ import { quoteLifeVerdict } from "./quotePolicy.mjs";
9
9
  import { SDK_VERSION } from "./version.mjs";
10
10
  import * as engine from "./engine.mjs";
11
11
  // The name is NOT `record`: inside start there is a variable with that name, and referencing the module before it
@@ -268,6 +268,11 @@ export const recordInputOf = (request, xmrNetwork = null) => {
268
268
  // tie the created escrow to the provider node's record, and without it the node cannot take the ETH
269
269
  // (sdk/src/swap-flow.mjs: quoteId: quote.id -> swap.orderQuoteId).
270
270
  orderQuoteId: pass(quote.id),
271
+ // THE PENDING-FUNDING IDENTITY. A retry without the relay answer still has to prove that the record it found
272
+ // belongs to the same order; the salt alone is not enough, so the chain, the factory and the predicted escrow
273
+ // are stored beside it.
274
+ chainId: pass((request.order && request.order.chainId) ?? (request.orderQuote && request.orderQuote.chainId)),
275
+ factory: pass((request.order && request.order.factory) ?? (request.orderQuote && request.orderQuote.factory)),
271
276
  // WHERE TO WITHDRAW XMR: part of the record, not a detail of the screen - the progress screen exports the file by it.
272
277
  receiveAddress: pass(request.receiveTo),
273
278
  // WHAT THE PERSON SAW: the maker, its spread, the fee, the rate and the quote signature. Screen data, but it must
@@ -321,33 +326,79 @@ export function sellWatchTimeoutMs({ configuredMs = 1_200_000, readyBySec = null
321
326
  return Math.max(configured, (readyAt - now + SELL_WATCH_MARGIN_SEC) * 1000);
322
327
  }
323
328
 
324
- // A PENDING FUNDING IS RESUMED ONLY FOR THE SAME QUOTE, NOT MERELY THE SAME NONCE. The quote id is the maker's
325
- // nonce; a second offer can reuse it. The salt is the client's own binding to the terms and the predicted escrow,
326
- // so an id match without the same salt is a different order.
327
- export function samePendingFunding(swap, quoteId, salt) {
329
+ // A PENDING FUNDING IS RESUMED ONLY FOR THE SAME ORDER, NOT MERELY THE SAME NONCE. The quote nonce is the maker's
330
+ // value and a second offer can reuse it. The identity is the client's salt together with the chain, the factory and
331
+ // the predicted escrow: those four values are the order the record was built for. A record that names no predicted
332
+ // escrow cannot prove it is the same order and is not resumed.
333
+ const pendingSalt = (value) => String(value === undefined || value === null ? "" : value).replace(/^0x/i, "").toLowerCase();
334
+ const pendingAddress = (value) => String(value === undefined || value === null ? "" : value).replace(/^0x/i, "").toLowerCase();
335
+ function pendingFundingIdentity(swap) {
336
+ const escrow = swap && swap.escrow && typeof swap.escrow === "object" ? swap.escrow : {};
337
+ const order = swap && swap.order && typeof swap.order === "object" ? swap.order : {};
338
+ const quote = swap && swap.quote && typeof swap.quote === "object" ? swap.quote : {};
339
+ return {
340
+ salt: pendingSalt(escrow.salt ?? (swap && swap.recoverySalt)),
341
+ chainId: Number(order.chainId ?? quote.chainId ?? (swap && swap.chainId) ?? escrow.chainId),
342
+ factory: pendingAddress(order.factory ?? quote.factory ?? (swap && swap.factory) ?? escrow.factory),
343
+ escrow: pendingAddress(escrow.address ?? (swap && swap.predictedEscrow)),
344
+ };
345
+ }
346
+
347
+ // THE PENDING ROW CAN BE FOUND WITHOUT ITS ESCROW. A reloaded retry has the salt, chain and factory, but it has
348
+ // no request escrow; the address must be predicted from the signed quote before the row can prove it is the same
349
+ // order. This base match only selects a row that *might* be resumed; it never authorises a send.
350
+ function samePendingBase(swap, identity = {}) {
351
+ if (!swap || !(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
352
+ const recorded = pendingFundingIdentity(swap);
353
+ const wanted = {
354
+ salt: pendingSalt(identity.salt),
355
+ chainId: Number(identity.chainId),
356
+ factory: pendingAddress(identity.factory),
357
+ };
358
+ if (!wanted.salt || !wanted.factory || !Number.isSafeInteger(wanted.chainId) || wanted.chainId <= 0) return false;
359
+ // Records written before the identity gained chain/factory still have the salt. They may be matched on what they
360
+ // have, but the caller still has to name the same predicted address; a partial record is never a free pass.
361
+ if (recorded.salt !== wanted.salt) return false;
362
+ if (recorded.factory && recorded.factory !== wanted.factory) return false;
363
+ if (Number.isSafeInteger(recorded.chainId) && recorded.chainId > 0 && recorded.chainId !== wanted.chainId) return false;
364
+ return true;
365
+ }
366
+
367
+ export function samePendingFunding(swap, identity = {}) {
328
368
  if (!swap || !(swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true))) return false;
329
- const id = String(quoteId || "");
330
- const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
331
- if (!id && !saltHex) return false;
332
- const recordedId = String(swap.orderQuoteId || "");
333
- const recordedSalt = String((swap.escrow && swap.escrow.salt) || swap.recoverySalt || "").replace(/^0x/i, "").toLowerCase();
334
- if (id && recordedId === id) return Boolean(saltHex && recordedSalt === saltHex);
335
- return Boolean(saltHex && recordedSalt === saltHex);
369
+ const recorded = pendingFundingIdentity(swap);
370
+ const wanted = {
371
+ salt: pendingSalt(identity.salt),
372
+ chainId: Number(identity.chainId),
373
+ factory: pendingAddress(identity.factory),
374
+ escrow: pendingAddress(identity.escrow),
375
+ };
376
+ if (!wanted.salt || !wanted.factory || !wanted.escrow || !Number.isSafeInteger(wanted.chainId) || wanted.chainId <= 0) return false;
377
+ if (recorded.salt !== wanted.salt || recorded.escrow !== wanted.escrow) return false;
378
+ // A RECORD WRITTEN BEFORE THE IDENTITY FIELDS STILL HAS ONE OPINION: its salt and its escrow address. Missing
379
+ // chain/factory fields are wildcards only for that old shape; a record that carries them must match them exactly.
380
+ if (Number.isSafeInteger(recorded.chainId) && recorded.chainId > 0 && recorded.chainId !== wanted.chainId) return false;
381
+ if (recorded.factory && recorded.factory !== wanted.factory) return false;
382
+ return true;
336
383
  }
337
384
 
338
385
  /**
339
386
  * WHAT A PENDING RECORD MEANS FOR THIS START.
340
387
  * `salt-required` is the expensive branch made loud: a caller that knows only the nonce of a pending record cannot
341
- * prove it is the same order, and falling through would build a second deposit. The caller must bring the salt (or
342
- * let the record be resolved by its own salt), not guess.
388
+ * prove it is the same order, and falling through would build a second deposit. The caller must bring the full
389
+ * identity (salt, chain, factory, predicted escrow), not guess.
343
390
  */
344
- export function pendingFundingVerdict(swap, quoteId, salt) {
391
+ export function pendingFundingVerdict(swap, identity = {}) {
345
392
  const pending = Boolean(swap && (swap.fundingPending === true || (swap.escrow && swap.escrow.fundingPending === true)));
346
393
  if (!pending) return "not-pending";
347
- const id = String(quoteId || "");
348
- const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
349
- if (id && String(swap.orderQuoteId || "") === id && !saltHex) return "salt-required";
350
- return samePendingFunding(swap, id, saltHex) ? "resume" : "different";
394
+ const salt = pendingSalt(identity.salt);
395
+ const quoteId = String(identity.quoteId === undefined || identity.quoteId === null ? "" : identity.quoteId);
396
+ if (!salt) {
397
+ // THE QUOTE ID CAN SELECT THE RECORD, BUT IT CANNOT PROVE THE ORDER. Only a record that the caller named by the
398
+ // same quote id is this branch; an unrelated pending record must not block a new start.
399
+ return !quoteId || String(swap.orderQuoteId || "") === quoteId ? "salt-required" : "different";
400
+ }
401
+ return samePendingFunding(swap, identity) ? "resume" : "different";
351
402
  }
352
403
 
353
404
  // THE RECORD OF A SALE, FOUND BY ITS ESCROW. `sellWatch` is called from a reloaded page with the address in hand,
@@ -364,7 +415,7 @@ function swapByEscrow(store, escrow) {
364
415
  return null;
365
416
  }
366
417
 
367
- export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork = null, call = null, now = null, evmBlock = null, store = engine.store,
418
+ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork = null, call = null, fetchImpl = null, now = null, sleep = null, evmBlock = null, store = engine.store,
368
419
  // THE MONERO TIMINGS ARE BROUGHT BY THE CONFIGURATION: the watch's rate and timeout live in config.limits. There is
369
420
  // no server step and no route table to consult.
370
421
  config = null,
@@ -382,6 +433,40 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
382
433
  // substitute your own. Otherwise the lock step could not be checked beyond predicting the address - and "the address
383
434
  // from the receipt" would remain an argument on trust, not a verified property.
384
435
  const reader = typeof call === "function" ? call : engine.evm.readContract;
436
+ // A RELOADED RETRY DOES NOT CARRY THE ESCROW. It still carries the signed order quote and the order terms, so the
437
+ // same factory predict() the send would use can name the address before the pending row is compared. A missing
438
+ // quote or a failed read is a refusal by name, never permission to send a second deposit.
439
+ const predictedEscrowForRetry = async (request) => {
440
+ const quote = request && request.orderQuote;
441
+ const order = request && request.order;
442
+ if (!quote || typeof quote !== "object" || !quote.signature) return null;
443
+ const factory = (order && order.factory) || quote.factory;
444
+ if (!factory) return null;
445
+ const lockerHalf = {
446
+ commitHalfLocker: (order && order.commitHalfLocker) ?? quote.commitHalfLocker,
447
+ edPointLocker: (order && order.edPointLocker) ?? quote.edPointLocker,
448
+ edViewPointLocker: (order && order.edViewPointLocker) ?? quote.edViewPointLocker,
449
+ };
450
+ if (!lockerHalf.commitHalfLocker || !lockerHalf.edPointLocker || !lockerHalf.edViewPointLocker) return null;
451
+ try {
452
+ const raw = await reader({ to: factory, data: engine.evm.encodePredict({ ...quote, ...lockerHalf, factory }) });
453
+ return engine.evm.decodeAddress(raw);
454
+ } catch {
455
+ return null;
456
+ }
457
+ };
458
+ // THE INSTANCE TRANSPORT IS THE DEFAULT, NOT BACKGROUND MAGIC. A per-call `fetch` still wins; otherwise every
459
+ // network read made by this client (height probes, relay quote/claim, witness verification) uses `fetchImpl`.
460
+ const withDefaultFetch = (request) => (fetchImpl && request && typeof request === "object"
461
+ && typeof request.fetch !== "function" ? { ...request, fetch: fetchImpl } : request);
462
+ // THE SLOT CLOCK IS A SEAM. A real caller uses wall time and a timer; a check can advance both, so a 15-30 s
463
+ // slot is exercised without making the suite wait for it.
464
+ const clockMs = () => {
465
+ const value = typeof now === "function" ? Number(now()) : Date.now();
466
+ return Number.isFinite(value) ? value : Date.now();
467
+ };
468
+ const sleepFor = typeof sleep === "function" ? sleep
469
+ : (ms) => new Promise((resolve) => setTimeout(resolve, ms));
385
470
  // ONE BLOCK FOR THE SELL GATE. A block read is a seam like the contract read: `evmBlock` from the interface
386
471
  // wins, then the wallet's own provider. The number pins every escrow read below to the same state; the
387
472
  // timestamp is the chain's clock, not the device's.
@@ -422,7 +507,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
422
507
  const listed = Array.isArray(request.xmrNodes) ? request.xmrNodes
423
508
  : (config && typeof config.nodesFor === "function" ? config.nodesFor(moneroNetwork) : []);
424
509
  return startHeightFromNodes({ nodes: listed, network: moneroNetwork,
425
- fetchImpl: request.fetchImpl || (typeof fetch === "function" ? fetch : null) });
510
+ fetchImpl: request.fetchImpl || fetchImpl || (typeof fetch === "function" ? fetch : null) });
426
511
  }
427
512
  const records = () => {
428
513
  const state = store.loadState();
@@ -432,12 +517,14 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
432
517
  // A START THAT ENDED WITH A SENT TRANSACTION AND NO RECEIPT IS RESUMED, NOT RESENT. The transaction hash and the
433
518
  // predicted escrow are kept on the record; a retry of the same quote reads that receipt instead of building a
434
519
  // second side and sending a second deposit.
435
- const pendingFundingOf = (quoteId, salt) => {
436
- const id = String(quoteId || "");
437
- const saltHex = String(salt || "").replace(/^0x/i, "").toLowerCase();
438
- if (!id && !saltHex) return null;
520
+ const pendingFundingOf = (identity) => {
521
+ const salt = pendingSalt(identity && identity.salt);
522
+ const quoteId = String(identity && identity.quoteId !== undefined && identity.quoteId !== null ? identity.quoteId : "");
523
+ // WITHOUT EITHER HANDLE NOTHING CAN SELECT A RECORD. With a quote id the loop below can still name the record and
524
+ // refuse it as salt-required instead of silently starting a second deposit.
525
+ if (!salt && !quoteId) return null;
439
526
  for (const swap of records()) {
440
- const verdict = pendingFundingVerdict(swap, id, saltHex);
527
+ const verdict = pendingFundingVerdict(swap, identity);
441
528
  if (verdict === "salt-required") {
442
529
  throw new SdkError("bad-input", { field: "recoverySalt", why: "required-for-pending-funding" });
443
530
  }
@@ -701,13 +788,13 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
701
788
 
702
789
  // THE ARRIVAL VERDICT WITHOUT THE WATCH LOOP, and the deadline check as a separate call: an interface may
703
790
  // want to run both itself. The watch uses exactly these, so there is one decision, not two.
704
- verifyArrival: (request) => xmrArrival.verifyArrival(request),
791
+ verifyArrival: (request) => xmrArrival.verifyArrival(withDefaultFetch(request)),
705
792
  /**
706
793
  * SHADOW THE FIXED-SLICE WITNESS WITHOUT CHANGING THE DECISION. It runs the exact check and the witness-v1
707
794
  * slice check and returns both; `witnessNodes` must carry `{protocol: "witness-v1"}`. Nothing here opens
708
795
  * `ready` or refunds. It exists so the protocol can be exercised before an independent operator serves it.
709
796
  */
710
- verifyArrivalShadow: (request) => xmrArrival.verifyArrivalShadow(request),
797
+ verifyArrivalShadow: (request) => xmrArrival.verifyArrivalShadow(withDefaultFetch(request)),
711
798
  assertTimeForConfirmations: (request) => xmrArrival.assertTimeForConfirmations(request),
712
799
 
713
800
  /**
@@ -731,7 +818,8 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
731
818
  * arrival check and the real refund.
732
819
  */
733
820
  async refundIfXmrMissing(request = {}, deps = {}) {
734
- const verify = typeof deps.verify === "function" ? deps.verify : xmrArrival.verifyArrival;
821
+ const verify = typeof deps.verify === "function" ? deps.verify
822
+ : (request) => xmrArrival.verifyArrival(withDefaultFetch(request));
735
823
  const refund = typeof deps.refund === "function" ? deps.refund : actions.refund;
736
824
  const nowOf = typeof deps.now === "function" ? deps.now : () => Math.floor(Date.now() / 1000);
737
825
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -836,10 +924,44 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
836
924
 
837
925
  // RESUME BEFORE ANY NEW SIDE OR SEND. The previous start may have sent the deposit and lost the receipt;
838
926
  // reusing its hash is the only way to learn the escrow without a second payment.
839
- const quoteForResume = (request.orderQuote && request.orderQuote.id) || (request.quote && request.quote.id) || null;
840
927
  const saltForResume = request.recoverySalt || (request.order && request.order.salt) ||
841
928
  (request.orderQuote && request.orderQuote.salt) || null;
842
- const pendingRecord = pendingFundingOf(quoteForResume, saltForResume);
929
+ const resumeIdentity = {
930
+ salt: saltForResume,
931
+ // THE QUOTE ID IS ONLY A SELECTOR. It lets a salt-less retry name the pending row and be refused loudly, but
932
+ // it never replaces the salt/chain/factory/escrow proof below.
933
+ quoteId: (request.orderQuote && request.orderQuote.id) || (request.quote && request.quote.id) || null,
934
+ chainId: (request.order && request.order.chainId) ?? (request.orderQuote && request.orderQuote.chainId)
935
+ ?? (request.quote && request.quote.chainId),
936
+ factory: (request.order && request.order.factory) ?? (request.orderQuote && request.orderQuote.factory)
937
+ ?? (request.quote && request.quote.factory),
938
+ escrow: request.escrow || request.predictedEscrow || (request.quote && request.quote.escrow)
939
+ || (request.orderQuote && request.orderQuote.escrow) || null,
940
+ };
941
+ // A RELOADED RETRY HAS NO ESCROW FIELD. Find the pending row by the part it does have, then let the factory
942
+ // predict the address from the same signed terms the send uses. If that address cannot be named, the retry is
943
+ // refused by name; it must not fall through to a new deposit.
944
+ let pendingRecord = null;
945
+ if (records().some((swap) => samePendingBase(swap, resumeIdentity))) {
946
+ const predicted = await predictedEscrowForRetry(request);
947
+ if (!predicted) {
948
+ throw new SdkError("bad-input", { field: "escrow", why: "required-for-pending-funding" });
949
+ }
950
+ const named = pendingAddress(resumeIdentity.escrow);
951
+ if (resumeIdentity.escrow && !named) {
952
+ throw new SdkError("bad-input", { field: "escrow", why: "unreadable" });
953
+ }
954
+ if (named && named !== pendingAddress(predicted)) {
955
+ throw new SdkError("bad-input", { field: "escrow", why: "escrow-mismatch" });
956
+ }
957
+ resumeIdentity.escrow = predicted;
958
+ pendingRecord = pendingFundingOf(resumeIdentity);
959
+ if (!pendingRecord) {
960
+ throw new SdkError("bad-input", { field: "escrow", why: "pending-funding-unresolved" });
961
+ }
962
+ } else {
963
+ pendingRecord = pendingFundingOf(resumeIdentity);
964
+ }
843
965
  if (pendingRecord) {
844
966
  const resumed = await resumePendingFunding(pendingRecord, request);
845
967
  if (resumed) return resumed;
@@ -1094,8 +1216,20 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1094
1216
  // THE CLOCK IS THE SDK'S OWN SEAM, IN MILLISECONDS, LIKE EVERY OTHER NOW IN THE FACADE.
1095
1217
  const nowMs = typeof now === "function" ? Number(now()) : Date.now();
1096
1218
  const nowSec = Math.floor(nowMs / 1000);
1097
- if (!Number.isSafeInteger(until) || !Number.isSafeInteger(nowSec) || until <= nowSec + LOCK_START_MARGIN_SEC) {
1098
- throw new SdkError("quote-expired", { validUntil: Number.isFinite(until) ? until : null, now: Number.isFinite(nowSec) ? nowSec : null, marginSec: LOCK_START_MARGIN_SEC, step: "lock" });
1219
+ // THE PREPARATION WAS ALREADY PAID FOR AT THE ANSWER. This check runs after the proof, the record and the
1220
+ // chain reads; requiring START_PREP_SEC again would refuse a quote that the answer accepted and spent those
1221
+ // seconds on. Only the next-block margin remains between here and the send.
1222
+ const life = quoteLifeVerdict({ validUntil: until, nowSec, side: "ask", prepSec: 0 });
1223
+ if (!life.ok) {
1224
+ throw new SdkError("quote-expired", {
1225
+ validUntil: Number.isFinite(until) ? until : null,
1226
+ now: Number.isFinite(nowSec) ? nowSec : null,
1227
+ remainingSec: life.remainingSec,
1228
+ marginSec: life.marginSec,
1229
+ prepSec: life.prepSec,
1230
+ confirmBySec: life.confirmBySec,
1231
+ step: "lock",
1232
+ });
1099
1233
  }
1100
1234
  }
1101
1235
  lockRequest.quote = request.orderQuote || null;
@@ -1311,7 +1445,7 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1311
1445
  // holds the view key), so it is not consulted when the client verifies. A disagreement or locked money
1312
1446
  // throws its own code above and closes the button; one operator / few confirmations name a WAITING state.
1313
1447
  if (verifyRequest) {
1314
- const verdict = await xmrArrival.verifyArrival({ ...verifyRequest, nowSec: Math.floor(Date.now() / 1000) });
1448
+ const verdict = await xmrArrival.verifyArrival(withDefaultFetch({ ...verifyRequest, nowSec: Math.floor(Date.now() / 1000) }));
1315
1449
  last.verify = verdict;
1316
1450
  if (!verdict.seen) {
1317
1451
  if (Date.now() - started >= timeoutMs) {
@@ -1339,8 +1473,9 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1339
1473
 
1340
1474
  /**
1341
1475
  * START A SELL FROM A VERIFIED RELAY OFFER. The offer is the result of `quotes.firmRelay` for the bid side;
1342
- * the record keeps the one-time address, the escrow, our half, the chosen claim sender and the order
1343
- * expectations, so a reload can continue with `get` + `sellWatch` + `sellClaim`. This method sends nothing.
1476
+ * the record keeps the one-time address, the escrow, our half, the order expectations and the relay origin, so a
1477
+ * reload can continue with `get` + `sellWatch` + `sellClaim`. The optional `claimSender` is a legacy
1478
+ * single-sender fallback; `claimViaRelay` takes the client's ordered list at claim time. This method sends nothing.
1344
1479
  */
1345
1480
  async startSell(request) {
1346
1481
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -1400,8 +1535,13 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1400
1535
  throw new SdkError("quote-refused", { step: "sell-record", why: "offer-changed" });
1401
1536
  }
1402
1537
  const storedSender = existing.claimSender ? addressTextOf(existing.claimSender, "claimSender") : null;
1403
- if (requestedSender && storedSender && requestedSender !== storedSender) {
1404
- throw new SdkError("quote-refused", { step: "sell-record", why: "claim-sender-changed" });
1538
+ // THE OLD SCALAR IS NOT A PIN. A reload may name another sender or bring the ordered list at claim time; the
1539
+ // record keeps the latest scalar only for callers that still use it.
1540
+ if (requestedSender && requestedSender !== storedSender) {
1541
+ existing.claimSender = requestedSender;
1542
+ delete existing.claimSenders;
1543
+ try { engine.swap.saveSwap(existing, store); }
1544
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
1405
1545
  }
1406
1546
  // THE RELAY IS PART OF THE VERIFIED OFFER. A claim later goes to the origin that answered this quote, so
1407
1547
  // a resumed offer naming another origin is a different offer; one that now names the same origin fills a
@@ -1416,11 +1556,6 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1416
1556
  try { engine.swap.saveSwap(existing, store); }
1417
1557
  catch { throw new SdkError("storage-unavailable", { step: "save-relay" }); }
1418
1558
  }
1419
- if (requestedSender && !storedSender) {
1420
- existing.claimSender = requestedSender;
1421
- try { engine.swap.saveSwap(existing, store); }
1422
- catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
1423
- }
1424
1559
  const storedWindow = existing.readyWindow || existing.sellWindow || null;
1425
1560
  if (offerWindow && storedWindow) {
1426
1561
  const a = readReadyWindow(storedWindow, { side: "bid", field: "readyWindow" });
@@ -1573,15 +1708,12 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1573
1708
  * CLAIM THE ETH ON A SELL WITHOUT A WALLET.
1574
1709
  *
1575
1710
  * The seller holds XMR and no ETH, so the escrow pays the signed `claimTip` to whoever submits the claim.
1576
- * This method sends the half to the sender the client chose - a listed maker other than the deal's maker - and
1577
- * the relay posts it to `POST /v1/claims/{sender}/{escrow}`. It NEVER creates or uses a wallet and never signs a
1578
- * chain transaction; `sellClaim` remains the own-wallet path.
1579
- *
1580
- * A record must come from `startSell`, carry a POSITIVE `claimTip`, and name the sender, escrow and half. The
1581
- * sender is stored by `startSell`; a request may supply `claimSender` only when the record has none, and may
1582
- * never name the deal's maker. `relayUrl` is only a restatement of the stored origin: a different one is refused
1583
- * rather than obeyed. A vanished answer is `claim-unknown` (the claim may have been sent), never success; only a
1584
- * real txid returns.
1711
+ * `claimSenders` is the client's ordered list: the relay's own sender first, then the listed makers. The SDK
1712
+ * sends the half to one sender at a time through `POST /v1/claims/{sender}/{escrow}`; a refusal moves on at once,
1713
+ * a txid or unknown answer is followed by reading the escrow for the rest of that sender's 15-30 s slot, and
1714
+ * only `claimed` on chain is success. An exhausted list returns `state: "claim-yourself"` with the time left
1715
+ * before `t1`. The deal's maker and its quote-key owner are refused before the half leaves the client. This
1716
+ * method never creates or uses a wallet and never signs a chain transaction; `sellClaim` remains that path.
1585
1717
  */
1586
1718
  async claimViaRelay(request = {}) {
1587
1719
  if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
@@ -1617,35 +1749,47 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1617
1749
  }
1618
1750
  }
1619
1751
  }
1752
+ const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1753
+ || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1620
1754
  const storedSenderRaw = swap.claimSender === undefined || swap.claimSender === null
1621
1755
  || String(swap.claimSender).trim() === "" ? null : swap.claimSender;
1622
1756
  const requestedSenderRaw = request.claimSender === undefined || request.claimSender === null
1623
1757
  || String(request.claimSender).trim() === "" ? null : request.claimSender;
1624
- const storedSender = storedSenderRaw ? addressTextOf(storedSenderRaw, "claimSender") : null;
1625
- const requestedSender = requestedSenderRaw ? addressTextOf(requestedSenderRaw, "claimSender") : null;
1626
- if (storedSender && requestedSender && storedSender !== requestedSender) {
1627
- throw new SdkError("bad-input", { field: "claimSender", why: "different-from-record" });
1758
+ // THE ORDER IS THE CLIENT'S, NOT THE RECORD'S. A list passed now wins; the old scalar and the stored value are
1759
+ // only one-element fallbacks for callers written before the list existed. Neither is a pin: the next sender is
1760
+ // tried when this one refuses or its slot ends.
1761
+ if (request.claimSenders !== undefined && !Array.isArray(request.claimSenders)) {
1762
+ throw new SdkError("bad-input", { field: "claimSenders", why: "not-an-array" });
1628
1763
  }
1629
- const sender = storedSender || requestedSender;
1630
- if (!sender) throw new SdkError("bad-input", { field: "claimSender", why: "not-in-record" });
1631
- if (sender === maker) throw new SdkError("bad-input", { field: "claimSender", why: "is-deal-maker" });
1632
- const quoteKeyOwner = quote.quoteKey === undefined || quote.quoteKey === null
1633
- || String(quote.quoteKey).trim() === "" ? null : addressTextOf(quote.quoteKey, "quoteKey");
1634
- if (quoteKeyOwner && sender === quoteKeyOwner) {
1635
- throw new SdkError("bad-input", { field: "claimSender", why: "is-quote-key" });
1764
+ const explicitList = Array.isArray(request.claimSenders) ? request.claimSenders : null;
1765
+ if (explicitList && explicitList.length === 0) {
1766
+ throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1636
1767
  }
1637
- // AN OLDER RECORD KEEPS THE SENDER ONCE IT IS USED. A reload must not be forced to remember a second input.
1638
- if (!storedSender && requestedSender) {
1639
- swap.claimSender = requestedSender;
1640
- try { engine.swap.saveSwap(swap, store); }
1641
- catch { throw new SdkError("storage-unavailable", { step: "save-claim-sender" }); }
1768
+ if (explicitList && requestedSenderRaw) {
1769
+ throw new SdkError("bad-input", { field: "claimSenders", why: "with-claim-sender" });
1770
+ }
1771
+ const rawSenders = explicitList || (requestedSenderRaw ? [requestedSenderRaw] : null)
1772
+ || (Array.isArray(swap.claimSenders) ? swap.claimSenders : null)
1773
+ || (storedSenderRaw ? [storedSenderRaw] : []);
1774
+ if (!rawSenders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
1775
+ const senders = [];
1776
+ for (const raw of rawSenders) {
1777
+ if (raw === undefined || raw === null || String(raw).trim() === "") {
1778
+ throw new SdkError("bad-input", { field: "claimSenders", why: "empty" });
1779
+ }
1780
+ const sender = addressTextOf(raw, "claimSenders");
1781
+ if (sender === maker) throw new SdkError("bad-input", { field: "claimSenders", why: "is-deal-maker" });
1782
+ if (quoteKeyOwner && sender === quoteKeyOwner) {
1783
+ throw new SdkError("bad-input", { field: "claimSenders", why: "is-quote-key" });
1784
+ }
1785
+ if (!senders.includes(sender)) senders.push(sender);
1642
1786
  }
1787
+ if (!senders.length) throw new SdkError("bad-input", { field: "claimSenders", why: "not-in-record" });
1643
1788
  if (escrowRecord.address === undefined || escrowRecord.address === null || escrowRecord.address === "") {
1644
1789
  throw new SdkError("bad-input", { field: "escrow", why: "not-in-record" });
1645
1790
  }
1646
1791
  const escrow = addressTextOf(escrowRecord.address, "escrow");
1647
1792
  const halfClaimer = halfTextOf(escrowRecord.half);
1648
-
1649
1793
  // THE ORIGIN IS THE QUOTE'S, NOT THE CALLER'S. The record stores the relay that answered; a request may
1650
1794
  // repeat it (with a trailing slash), but may not choose another one after the quote.
1651
1795
  if (swap.relayUrl === undefined || swap.relayUrl === null || swap.relayUrl === "") {
@@ -1657,14 +1801,89 @@ export function createSwaps({ preflight, createRecord, mode = null, xmrNetwork =
1657
1801
  throw new SdkError("bad-input", { field: "relayUrl", why: "foreign-relay" });
1658
1802
  }
1659
1803
  }
1804
+ // A LIST IS NOT A PIN. It is saved only as the fallback for a reload whose caller no longer has the relay's
1805
+ // answer; a later request that brings its own order ignores it.
1806
+ if (!Array.isArray(swap.claimSenders) || swap.claimSenders.length !== senders.length
1807
+ || swap.claimSenders.some((value, index) => String(value).toLowerCase() !== senders[index])) {
1808
+ swap.claimSenders = senders;
1809
+ swap.claimSender = senders[0];
1810
+ try { engine.swap.saveSwap(swap, store); }
1811
+ catch { throw new SdkError("storage-unavailable", { step: "save-claim-senders" }); }
1812
+ }
1660
1813
 
1661
1814
  const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0
1662
1815
  ? Number(request.timeoutMs) : 20_000;
1663
- const claimed = await postRelayClaim({
1664
- relayUrl, provider: sender, escrow, halfClaimer, expectedTipWei: tip,
1665
- fetchImpl: request.fetchImpl || null, timeoutMs,
1816
+ // ONE SENDER AT A TIME, EACH WITH ITS OWN SLOT. Refusal moves on immediately; an accepted/unknown answer is
1817
+ // followed by reading the escrow until it says claimed or the slot ends. A txid alone is never success.
1818
+ const slotMs = Number.isFinite(Number(request.slotMs)) && Number(request.slotMs) > 0
1819
+ ? Math.min(30_000, Math.max(15_000, Number(request.slotMs))) : 20_000;
1820
+ const pollMs = Number.isFinite(Number(request.pollMs)) && Number(request.pollMs) > 0
1821
+ ? Math.min(slotMs, Number(request.pollMs)) : 2_000;
1822
+ const readStatus = async () => {
1823
+ try { return await flow.orderStatus(escrow, { call: reader }); } catch { return null; }
1824
+ };
1825
+ const t1Raw = order.t1 ?? (swap.expect && swap.expect.t1);
1826
+ const t1 = Number.isSafeInteger(Number(t1Raw)) && Number(t1Raw) > 0 ? Number(t1Raw) : null;
1827
+ const secondsLeft = () => (t1 === null ? null : Math.max(0, t1 - Math.floor(clockMs() / 1000)));
1828
+ const claimedByEscrow = (sender = null, answer = null, tried = []) => ({
1829
+ id, state: "claimed", provider: sender, claimSender: sender, escrow, relayUrl,
1830
+ txid: answer ? answer.txid : null, from: (answer && answer.from) || null,
1831
+ tipWei: (answer && answer.tipWei) || tip.toString(), tried,
1666
1832
  });
1667
- return { id, provider: sender, claimSender: sender, escrow, relayUrl, txid: claimed.txid, from: claimed.from, tipWei: claimed.tipWei };
1833
+ // A CLAIM THAT ALREADY LANDED IS NOT A REASON TO SEND THE HALF AGAIN. The caller may have lost the answer on
1834
+ // the previous attempt; read the escrow before the first POST, and read it once more before returning
1835
+ // `claim-yourself`, so a late claim cannot be reported as "claim yourself".
1836
+ const initial = await readStatus();
1837
+ if (initial && initial.isClaimed) return claimedByEscrow();
1838
+ let refunded = Boolean(initial && initial.isRefunded);
1839
+ const tried = [];
1840
+ if (!refunded) for (const sender of senders) {
1841
+ let answer = null;
1842
+ let failure = null;
1843
+ try {
1844
+ answer = await postRelayClaim({
1845
+ relayUrl, provider: sender, escrow, halfClaimer, expectedTipWei: tip,
1846
+ fetchImpl: request.fetchImpl || fetchImpl || null, timeoutMs,
1847
+ });
1848
+ } catch (error) {
1849
+ failure = error;
1850
+ }
1851
+ // A REFUSAL IS THE SENDER'S ANSWER, NOT A CLAIM IN FLIGHT. Move to the next one at once; only an unknown
1852
+ // outcome (or a txid, which is not yet a claim on chain) deserves the slot.
1853
+ if (failure && failure.code !== "claim-unknown") {
1854
+ tried.push({ sender, outcome: "refused", code: failure.code || "unknown",
1855
+ params: failure.params || null });
1856
+ continue;
1857
+ }
1858
+ const slotEnd = clockMs() + slotMs;
1859
+ for (;;) {
1860
+ const status = await readStatus();
1861
+ if (status && status.isClaimed) {
1862
+ swap.claimSender = sender;
1863
+ try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
1864
+ return claimedByEscrow(sender, answer, tried);
1865
+ }
1866
+ if (status && status.isRefunded) { refunded = true; break; }
1867
+ const left = slotEnd - clockMs();
1868
+ if (left <= 0) break;
1869
+ await sleepFor(Math.min(pollMs, left));
1870
+ }
1871
+ tried.push({ sender, outcome: failure ? "unknown" : "unconfirmed",
1872
+ txid: answer ? answer.txid : null, code: failure ? failure.code : null });
1873
+ if (refunded) break;
1874
+ }
1875
+
1876
+ // THE LAST LOOK BEFORE THE FALLBACK. A claim can land after the last slot ended or while a later sender is
1877
+ // refusing; the seller must not be sent to `sellClaim` on an escrow that is already closed as claimed.
1878
+ const finalStatus = await readStatus();
1879
+ if (finalStatus && finalStatus.isClaimed) {
1880
+ try { engine.swap.saveSwap(swap, store); } catch { /* the chain already says claimed */ }
1881
+ return claimedByEscrow(null, null, tried);
1882
+ }
1883
+ if (finalStatus && finalStatus.isRefunded) refunded = true;
1884
+ return { id, state: "claim-yourself", reason: refunded ? "escrow-refunded" : "senders-exhausted",
1885
+ provider: null, claimSender: null, escrow, relayUrl, txid: null, from: null, tipWei: tip.toString(),
1886
+ t1, secondsLeft: secondsLeft(), tried };
1668
1887
  },
1669
1888
 
1670
1889
  /**
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.58.0";
9
+ export const SDK_VERSION = "0.59.0";
@@ -0,0 +1,84 @@
1
+ // THE WITNESS-V1 SLICE ANSWER. The parser lives apart from the arrival check so the wire format can be tested
2
+ // against a real witness service without importing the wallet engine.
3
+ import { SdkError } from "./errors.mjs";
4
+
5
+ export const WITNESS_SLICE_BLOCKS = 20;
6
+
7
+ export function witnessSliceIndex(height) {
8
+ const value = Number(height);
9
+ if (!Number.isSafeInteger(value) || value < 0) throw new SdkError("bad-input", { field: "height" });
10
+ return Math.floor(value / WITNESS_SLICE_BLOCKS);
11
+ }
12
+
13
+ export function witnessSliceStart(index) {
14
+ const value = Number(index);
15
+ if (!Number.isSafeInteger(value) || value < 0) throw new SdkError("bad-input", { field: "slice" });
16
+ return value * WITNESS_SLICE_BLOCKS;
17
+ }
18
+
19
+ export function witnessSliceEnd(index) {
20
+ return witnessSliceStart(index) + WITNESS_SLICE_BLOCKS - 1;
21
+ }
22
+
23
+ const witnessHash = (value) => {
24
+ const text = String(value || "").replace(/^0x/, "").toLowerCase();
25
+ return /^[0-9a-f]{64}$/.test(text) ? text : null;
26
+ };
27
+
28
+ /**
29
+ * A full slice below the tip has `grid` blocks. The tip slice ends at the top block, sets `complete: false`, and
30
+ * names that block in `tip`. A partial answer is accepted when its last block is at or above the top the caller
31
+ * read: a newer tip is a block that arrived during the walk, while a tip below it shows a witness that is behind.
32
+ */
33
+ export function parseWitnessSliceBody(body, { network, index, tipHeight = null }) {
34
+ if (!body || typeof body !== "object") throw new SdkError("xmr-no-nodes", { why: "bad-witness-slice" });
35
+ if (Number(body.version) !== 1) throw new SdkError("xmr-no-nodes", { why: "bad-witness-version" });
36
+ if (String(body.network) !== String(network)) throw new SdkError("xmr-no-nodes", { why: "witness-network" });
37
+ if (Number(body.grid) !== WITNESS_SLICE_BLOCKS) throw new SdkError("xmr-no-nodes", { why: "witness-grid" });
38
+ if (Number(body.slice) !== index) throw new SdkError("xmr-no-nodes", { why: "witness-slice" });
39
+ const start = witnessSliceStart(index);
40
+ const sliceEnd = witnessSliceEnd(index);
41
+ const to = Number(body.to);
42
+ if (Number(body.from) !== start || !Number.isSafeInteger(to) || to < start || to > sliceEnd) {
43
+ throw new SdkError("xmr-no-nodes", { why: "witness-bounds" });
44
+ }
45
+ if (typeof body.complete !== "boolean" || body.complete !== (to === sliceEnd)) {
46
+ throw new SdkError("xmr-no-nodes", { why: "witness-complete" });
47
+ }
48
+ const count = to - start + 1;
49
+ if (!Array.isArray(body.blocks) || body.blocks.length !== count) {
50
+ throw new SdkError("xmr-no-nodes", { why: "witness-block-count" });
51
+ }
52
+ const blocks = body.blocks.map((block, i) => {
53
+ if (!block || Number(block.height) !== start + i) {
54
+ throw new SdkError("xmr-no-nodes", { why: "witness-height" });
55
+ }
56
+ const hash = witnessHash(block.hash);
57
+ if (!hash) throw new SdkError("xmr-no-nodes", { why: "witness-hash" });
58
+ if (!Array.isArray(block.txids)) throw new SdkError("xmr-no-nodes", { why: "witness-txids" });
59
+ const txids = block.txids.map((txid) => {
60
+ const value = witnessHash(txid);
61
+ if (!value) throw new SdkError("xmr-no-nodes", { why: "witness-txid" });
62
+ return value;
63
+ });
64
+ return { height: Number(block.height), hash, txids };
65
+ });
66
+ let tip = null;
67
+ if (body.complete) {
68
+ if (body.tip !== null && body.tip !== undefined) throw new SdkError("xmr-no-nodes", { why: "witness-tip" });
69
+ } else {
70
+ const value = body.tip;
71
+ if (!value || typeof value !== "object" || Number(value.height) !== to || !witnessHash(value.hash)
72
+ || String(value.hash).toLowerCase() !== blocks[count - 1].hash) {
73
+ throw new SdkError("xmr-no-nodes", { why: "witness-tip" });
74
+ }
75
+ // A TIP AT OR ABOVE THE TOP IS A BLOCK THAT ARRIVED DURING THE WALK. A tip below it is a witness that is
76
+ // behind the chain the caller already read, and that cannot be evidence of absence.
77
+ if (tipHeight !== null && Number(value.height) < Number(tipHeight)) {
78
+ throw new SdkError("xmr-no-nodes", { why: "witness-tip-height" });
79
+ }
80
+ tip = { height: Number(value.height), hash: witnessHash(value.hash) };
81
+ }
82
+ return { version: 1, network: String(network), grid: WITNESS_SLICE_BLOCKS, slice: index,
83
+ from: start, to, complete: body.complete, blocks, tip };
84
+ }