@ninsei-labs/sdk 0.55.4 → 0.56.1

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.
@@ -2,9 +2,9 @@
2
2
  //
3
3
  // The taker used to make a random secret per swap and ask a person to save a file before funding. One BIP39 key,
4
4
  // made once and saved once, removes that step. The seeds of this module are the ONLY source of the taker's
5
- // halves: the spend and view halves for swap number i come from halfFromSeed with a binding that is known at
6
- // recovery time. The factory is deliberately not part of the binding: numbers then run across a redeployment,
7
- // and the search reads every factory the caller names.
5
+ // halves: the spend and view halves for an order come from halfFromSeed with a v2 binding that names the chain,
6
+ // the role, the public order salt and the factory. The factory is part of the binding, so a redeployment produces
7
+ // different halves; recovery must read the factory the order names.
8
8
  //
9
9
  // THE KEY NEVER LEAVES THE CLIENT. The search sends an address and the OrderCreated topic to a log reader; it
10
10
  // never sends the words, the seed, a half or a commitment. A service that answered "which of these are mine"
@@ -27,22 +27,11 @@ const halves = createHalves({ ed25519, secp256k1, keccak256, randomBytes });
27
27
  /** A BIP39 mnemonic with 128 bits of entropy: twelve words. */
28
28
  export const RECOVERY_KEY_VERSION = 1;
29
29
  export const RECOVERY_KEY_WORDS = 12;
30
- // The allocator's ceiling. Discovery must use the same range: a search that stops earlier can miss an order
31
- // whose number was skipped by an abandoned start or by a swap on another chain.
32
- export const RECOVERY_INDEX_MAX = 100000;
33
- // A DISCOVERY SCAN IS BOUNDED BY DEFAULT. The allocator can reach 100,000, but deriving a secp256k1 point for
34
- // every number on a phone is not a page-open cost. One thousand indices keeps the common case inside a short
35
- // call and, more importantly, the result NAMES that it stopped: the caller can continue from `nextIndex`.
36
- export const RECOVERY_SCAN_DEFAULT = 1000;
37
- // The scan yields to the event loop between chunks. A page must be able to paint and answer a cancel click even
38
- // when a caller explicitly asks for a large range; a synchronous loop of 100,000 derivations froze the page.
39
- export const RECOVERY_SCAN_YIELD_EVERY = 64;
40
30
  export const RECOVERY_KEY_STORE = "ninsei.recovery.key.v1";
41
31
  export const RECOVERY_KEY_FILE_MAGIC = "NINSEI RECOVERY KEY";
42
- export const RECOVERY_KEY_DOMAIN = "ninsei-taker-v1";
43
- // THE SALT-BASED VERSION. A v1 number is the same at every factory and every device; a v2 binding names the fresh
44
- // order salt, the factory and the role, so two orders cannot share a taker half even when the words are restored
45
- // elsewhere. The salt is already public in `OrderCreated`; recovery reads it back instead of reserving a number.
32
+ // ONE DERIVATION: the binding names the fresh order salt, the factory and the role, so two orders cannot share a
33
+ // taker half even when the words are restored elsewhere. The salt is already public in `OrderCreated`; recovery
34
+ // reads it back instead of reserving a number.
46
35
  export const RECOVERY_KEY_DOMAIN_V2 = "ninsei-taker-v2";
47
36
  // The counterparty's view half is derived from the SAME ONE KEY, in a domain of its own. The taker sends this
48
37
  // number to the maker (the node), which uses it as its own view half; the taker keeps it, so the joint view key
@@ -124,21 +113,6 @@ function numberField(value, field) {
124
113
  return n;
125
114
  }
126
115
 
127
- /** The binding a swap number is derived from. The chain id keeps testnet and mainnet keys apart. */
128
- export function recoveryBinding(chainId, index) {
129
- return `${RECOVERY_KEY_DOMAIN}|${numberField(chainId, "chainId")}|${numberField(index, "index")}`;
130
- }
131
-
132
- /**
133
- * The taker's two halves for swap number `index`.
134
- *
135
- * The halves are returned as 0x-prefixed scalars (64 hex digits), not BigInt: every crossing of JSON in this
136
- * package is a hex string, and a BigInt that reaches JSON.stringify fails the whole record.
137
- */
138
- export function takerHalves({ mnemonic, chainId, index }) {
139
- return takerHalvesFromSeed(seedOf(mnemonic), chainId, index);
140
- }
141
-
142
116
  // THE SAME KEY, A PUBLIC PER-ORDER SALT. The factory and role are in the binding, so the same words, chain and
143
117
  // salt at another factory produce another half. `role` is fixed for the taker's side; the maker's view half is
144
118
  // separated by its own domain. Salt is the `salt` word from `OrderCreated`, never a secret.
@@ -153,7 +127,6 @@ export function takerHalvesV2({ mnemonic, chainId, factory, role = "taker", salt
153
127
  const binding = recoveryBindingV2({ chainId, factory, role, salt: normalized });
154
128
  return {
155
129
  ...halvesFromBinding(seedOf(mnemonic), binding),
156
- index: null,
157
130
  derivation: "salt-v2",
158
131
  factory: factory.toLowerCase(),
159
132
  role,
@@ -161,12 +134,6 @@ export function takerHalvesV2({ mnemonic, chainId, factory, role = "taker", salt
161
134
  };
162
135
  }
163
136
 
164
- // Discovery derives thousands of numbers from one mnemonic. The BIP39 seed is the expensive part (PBKDF2), so it
165
- // is computed once by the caller and passed here; the per-number work is only HMAC and a curve point.
166
- function takerHalvesFromSeed(seed, chainId, index) {
167
- return { index: numberField(index, "index"), ...halvesFromBinding(seed, recoveryBinding(chainId, index)) };
168
- }
169
-
170
137
  function halvesFromBinding(seed, binding) {
171
138
  const spendHalf = halves.halfFromSeed(seed, binding, halves.HALF_DOMAIN);
172
139
  const viewHalf = halves.halfFromSeed(seed, binding, halves.VIEW_HALF_DOMAIN);
@@ -188,14 +155,6 @@ function halvesFromBinding(seed, binding) {
188
155
  };
189
156
  }
190
157
 
191
- // DISCOVERY NEEDS ONE COMMITMENT, NOT THREE POINTS. The view and maker-view halves are not compared during a
192
- // search, and their Edwards points are the expensive part of `takerHalves`; deriving only the spend scalar keeps
193
- // a full-range scan practical.
194
- function spendCommitmentFromSeed(seed, chainId, index) {
195
- const spendHalf = halves.halfFromSeed(seed, recoveryBinding(chainId, index), halves.HALF_DOMAIN);
196
- return halfCommitmentHex(spendHalf, secp256k1, keccak256).toLowerCase();
197
- }
198
-
199
158
  function spendCommitmentFromSeedV2(seed, { chainId, factory, role = "taker", salt }) {
200
159
  const binding = recoveryBindingV2({ chainId, factory, role, salt });
201
160
  const spendHalf = halves.halfFromSeed(seed, binding, halves.HALF_DOMAIN);
@@ -317,7 +276,11 @@ export async function openRecoveryKeyFile(contents, passphrase = "") {
317
276
  if (lines[0].trim() !== RECOVERY_KEY_FILE_MAGIC) throw failed("parse");
318
277
  const words = lines.slice(1).map((line) => line.trim()).find((line) => line && validateMnemonic(line.toLowerCase(), wordlist));
319
278
  if (!words) throw failed("parse");
320
- return recoveryKeyOf(words);
279
+ // THE HEADER DATE IS PART OF THE FILE. The header carries a day, not a time, so the opened key gets that day
280
+ // at 00:00 UTC; a caller can then search from the key's creation instead of parsing the file itself.
281
+ const stamp = lines.map((line) => line.trim()).find((line) => /^Key [0-9a-f]{4}, created \d{4}-\d{2}-\d{2}$/.test(line));
282
+ const createdAt = stamp ? stamp.slice(stamp.lastIndexOf(" ") + 1) : undefined;
283
+ return recoveryKeyOf(words, createdAt);
321
284
  }
322
285
 
323
286
  let envelope;
@@ -344,7 +307,11 @@ export async function openRecoveryKeyFile(contents, passphrase = "") {
344
307
  } catch {
345
308
  throw failed("decrypt");
346
309
  }
347
- const key = recoveryKeyOf(payload && payload.mnemonic);
310
+ // THE SEALED METADATA IS AUTHENTICATED BY THE AAD. Keep its full creation time; the password file promised
311
+ // more precision than the plain header and the opener must not replace it with the time of opening.
312
+ let key;
313
+ try { key = recoveryKeyOf(payload && payload.mnemonic, envelope.meta && envelope.meta.createdAt); }
314
+ catch { throw failed("parse"); }
348
315
  if (envelope.meta && envelope.meta.fingerprint && envelope.meta.fingerprint !== key.fingerprint) throw failed("fingerprint");
349
316
  return key;
350
317
  }
@@ -376,8 +343,7 @@ const writeStore = (storage, value) => {
376
343
  /** Save the key next to the swap records. The words are the secret; the store is the caller's. */
377
344
  export function saveRecoveryKey(storage, key) {
378
345
  const checked = recoveryKeyOf(key && key.mnemonic, key && key.createdAt);
379
- writeStore(storage, { ...checked, nextIndex: Number(key.nextIndex) || 0,
380
- reserved: key.reserved || {}, retired: key.retired || {}, backupConfirmed: key.backupConfirmed === true });
346
+ writeStore(storage, { ...checked, backupConfirmed: key.backupConfirmed === true });
381
347
  return checked;
382
348
  }
383
349
 
@@ -387,52 +353,6 @@ export function loadRecoveryKey(storage) {
387
353
  return { ...value, fingerprint: value.fingerprint || fingerprintOf(value.mnemonic) };
388
354
  }
389
355
 
390
- /**
391
- * Reserve a number for a request. A reservation is not a spent number: if the request is abandoned, the caller
392
- * releases it and the same number is used again. The chain check belongs to the caller: a number is retired only
393
- * when an order with its commitment exists.
394
- */
395
- export function reserveRecoveryIndex(storage, { chainId, swapId = null } = {}) {
396
- const key = loadRecoveryKey(storage);
397
- if (!key) throw failed("key-missing");
398
- const chain = String(numberField(chainId, "chainId"));
399
- const reserved = { ...(key.reserved || {}) };
400
- const retired = { ...(key.retired || {}) };
401
- const index = Number(key.nextIndex) || 0;
402
- // Holes left by RELEASED numbers are reused; a retired number was seen on chain and is never reused.
403
- for (let i = 0; i < index; i += 1) {
404
- if (!Object.prototype.hasOwnProperty.call(reserved, i) && !Object.prototype.hasOwnProperty.call(retired, i)) {
405
- reserved[i] = { chainId: chain, swapId, at: new Date().toISOString() };
406
- writeStore(storage, { ...key, reserved, retired });
407
- return i;
408
- }
409
- }
410
- if (index >= RECOVERY_INDEX_MAX) throw failed("index-exhausted");
411
- reserved[index] = { chainId: chain, swapId, at: new Date().toISOString() };
412
- writeStore(storage, { ...key, nextIndex: index + 1, reserved, retired });
413
- return index;
414
- }
415
-
416
- export function releaseRecoveryIndex(storage, index) {
417
- const key = loadRecoveryKey(storage);
418
- if (!key) throw failed("key-missing");
419
- const reserved = { ...(key.reserved || {}) };
420
- delete reserved[String(numberField(index, "index"))];
421
- writeStore(storage, { ...key, reserved });
422
- }
423
-
424
- /** Retire a number after its order exists on chain: it is never reused, so a later scan has no collision. */
425
- export function commitRecoveryIndex(storage, index) {
426
- const key = loadRecoveryKey(storage);
427
- if (!key) throw failed("key-missing");
428
- const reserved = { ...(key.reserved || {}) };
429
- const retired = { ...(key.retired || {}) };
430
- const n = numberField(index, "index");
431
- delete reserved[String(n)];
432
- retired[String(n)] = true;
433
- writeStore(storage, { ...key, reserved, retired });
434
- }
435
-
436
356
  // ---------------------------------------------------------------------------------------------------
437
357
  // THE SEARCH
438
358
  // ---------------------------------------------------------------------------------------------------
@@ -509,23 +429,70 @@ async function readLogs(evmLogs, request) {
509
429
  return logs;
510
430
  }
511
431
 
432
+ // THE SETTLEMENT EVENTS A RECOVERY PAGE NEEDS, READ IN ONE RPC. Asking status() and revealedHalf() per order
433
+ // names every escrow to the public RPC operator next to the visitor's IP. One eth_getLogs with an address list and
434
+ // the three event topics returns the same facts without the per-order calls.
435
+ const eventTopic = (signature) => "0x" + Array.from(keccak256(new TextEncoder().encode(signature)),
436
+ (byte) => byte.toString(16).padStart(2, "0")).join("");
437
+ export const ESCROW_EVENT_TOPICS = Object.freeze({
438
+ halfRevealed: eventTopic("HalfRevealed(bytes32,bool)"),
439
+ ready: eventTopic("Ready(address)"),
440
+ declined: eventTopic("Declined(address)"),
441
+ });
442
+ const ESCROW_EVENT_NAMES = new Map([
443
+ [ESCROW_EVENT_TOPICS.halfRevealed, "HalfRevealed"],
444
+ [ESCROW_EVENT_TOPICS.ready, "Ready"],
445
+ [ESCROW_EVENT_TOPICS.declined, "Declined"],
446
+ ]);
447
+ const wordOf = (data, index) => {
448
+ const body = String(data || "").replace(/^0x/, "");
449
+ return body.length >= (index + 1) * 64 ? body.slice(index * 64, (index + 1) * 64) : null;
450
+ };
451
+ const addressTopic = (topic) => {
452
+ const body = String(topic || "").replace(/^0x/, "");
453
+ return body.length === 64 ? "0x" + body.slice(24).toLowerCase() : null;
454
+ };
455
+
512
456
  /**
513
- * Is this number already held by an order on chain?
514
- *
515
- * A browser store is per device. The same twelve words opened on a second device, or restored before any search, start
516
- * at number 0 again; two swaps would then share the taker's halves, and a refund of one publishes a half the other's
517
- * maker can use. The check is the factory's own `OrderCreated` log, matched by the spend commitment the number derives.
457
+ * Read settlement events for a list of escrows in one `eth_getLogs` call.
518
458
  *
519
- * The caller owns the log transport, as everywhere else in this module. An unreadable log request is a refusal, not
520
- * "free": the number is not reserved on a guess.
459
+ * `evmLogs` is the caller's seam and must accept an address array, a topic array and a block range. A page can
460
+ * use the result to rebuild the revealed half, the ready mark and a decline without asking the public RPC about
461
+ * each order separately. An unreadable request is a named `recovery-failed { step: "logs" }`, not an empty list.
521
462
  */
522
- export async function recoveryIndexTaken({ mnemonic, chainId, index, factory, evmLogs, fromBlock = 0, toBlock = "latest" } = {}) {
523
- if (typeof factory !== "string" || !ADDRESS_RE.test(factory)) throw bad("factory");
524
- const own = takerHalves({ mnemonic, chainId, index });
525
- const logs = await readLogs(evmLogs, { address: factory, topics: [ORDER_CREATED_TOPICS], fromBlock, toBlock });
526
- return logs.map(decodeOrderLog).filter(Boolean).some((order) =>
527
- order.commitHalfLocker.toLowerCase() === own.spendCommitment.toLowerCase() ||
528
- order.commitHalfClaimer.toLowerCase() === own.spendCommitment.toLowerCase());
463
+ export async function readEscrowEvents({ escrows, evmLogs, fromBlock = "earliest", toBlock = "latest" } = {}) {
464
+ if (!Array.isArray(escrows) || !escrows.length) throw bad("escrows");
465
+ for (const escrow of escrows) {
466
+ if (typeof escrow !== "string" || !ADDRESS_RE.test(escrow)) throw bad("escrows");
467
+ }
468
+ const logs = await readLogs(evmLogs, {
469
+ address: [...new Set(escrows.map((escrow) => escrow.toLowerCase()))],
470
+ topics: [[ESCROW_EVENT_TOPICS.halfRevealed, ESCROW_EVENT_TOPICS.ready, ESCROW_EVENT_TOPICS.declined]],
471
+ fromBlock,
472
+ toBlock,
473
+ });
474
+ const events = [];
475
+ for (const log of logs) {
476
+ if (!log || typeof log !== "object") continue;
477
+ const topics = Array.isArray(log.topics) ? log.topics : [];
478
+ const topic0 = String(topics[0] || "").toLowerCase();
479
+ const name = ESCROW_EVENT_NAMES.get(topic0);
480
+ if (!name) continue;
481
+ const escrow = String(log.address || "").toLowerCase();
482
+ if (!ADDRESS_RE.test(escrow)) continue;
483
+ const common = { escrow, event: name, blockNumber: log.blockNumber ?? null, transactionHash: log.transactionHash || null,
484
+ logIndex: log.logIndex ?? null };
485
+ if (name === "HalfRevealed") {
486
+ const half = wordOf(log.data, 0);
487
+ const flag = wordOf(log.data, 1);
488
+ if (!half || !flag) continue;
489
+ events.push({ ...common, half: "0x" + half.toLowerCase(), byClaimer: BigInt("0x" + flag) !== 0n });
490
+ } else {
491
+ const by = addressTopic(topics[1]);
492
+ if (by) events.push({ ...common, by });
493
+ }
494
+ }
495
+ return events.sort((a, b) => Number(a.blockNumber || 0) - Number(b.blockNumber || 0) || Number(a.logIndex || 0) - Number(b.logIndex || 0));
529
496
  }
530
497
 
531
498
  // THE MONERO HEIGHT A RECOVERED ORDER STARTED AT. With one key there is no per-swap file to carry it, so it is
@@ -656,64 +623,70 @@ async function recoveredStartHeight(order, { evmBlockTime, moneroTip, moneroBloc
656
623
  * search asks for it as the locker and as the claimer (two queries; the RPC topic filter cannot say OR across two
657
624
  * positions) and merges the answers. Without one, every OrderCreated of the factory is read and matched locally.
658
625
  */
659
- export async function findSwaps({ mnemonic, chainId, factory, address = null, evmLogs,
660
- fromBlock = null, deploymentBlock = null, toBlock = "latest", gap = 5,
661
- fromIndex = 0, maxIndex = RECOVERY_SCAN_DEFAULT,
662
- signal = null, onProgress = null,
626
+ export async function findSwaps({ mnemonic, chainId, factory = null, factories = null, address = null, evmLogs,
627
+ fromBlock = null, deploymentBlock = null, toBlock = "latest",
663
628
  evmBlockTime = null, evmCode = null, moneroTip = null, moneroBlockTimestamp = null,
664
629
  xmrNodes = null, moneroNetwork = null, fetchImpl = globalThis.fetch } = {}) {
665
- if (typeof factory !== "string" || !ADDRESS_RE.test(factory)) throw bad("factory");
666
- const chain = numberField(chainId, "chainId");
667
- // `gap` is retained in the signature for callers of the old API, but it is deliberately NOT used: five empty
668
- // numbers are ordinary when a start was abandoned or the key was used on another chain, and stopping there
669
- // hides a funded order whose log is already in `logs`.
670
- void gap;
671
- const startIndex = numberField(fromIndex, "fromIndex");
672
- if (startIndex < 0 || startIndex >= RECOVERY_INDEX_MAX) throw bad("fromIndex");
673
- const asked = numberField(maxIndex, "maxIndex");
674
- const max = Math.min(asked, RECOVERY_INDEX_MAX - startIndex);
675
- // THE CHAIN SAYS WHERE ITS ORDERS CAN START. An explicit fromBlock wins; otherwise the caller can pass the
676
- // factory's deployment block (the SDK's chain registry exposes it as escrow.deploymentBlock). Zero remains the
677
- // last resort for a caller that knows the factory existed at genesis.
678
- if (deploymentBlock !== null && deploymentBlock !== undefined && !Number.isSafeInteger(Number(deploymentBlock))) {
679
- throw bad("deploymentBlock");
630
+ // FACTORY HISTORY IS PART OF THE SEARCH. A chain can have more than one factory after a contract change;
631
+ // searching only the newest one hides every older order. Callers may pass `factories` as addresses or as
632
+ // `{ address|factory, deploymentBlock }`; a single `factory`/`deploymentBlock` remains the compatible form.
633
+ let targets = [];
634
+ if (Array.isArray(factories) && factories.length) {
635
+ targets = factories.map((entry) => {
636
+ const target = typeof entry === "string" ? entry : entry && (entry.factory || entry.address);
637
+ if (typeof target !== "string" || !ADDRESS_RE.test(target)) throw bad("factories");
638
+ const block = typeof entry === "object" && entry ? entry.deploymentBlock : null;
639
+ if (block !== null && block !== undefined && !Number.isSafeInteger(Number(block))) throw bad("factories.deploymentBlock");
640
+ return { factory: target, deploymentBlock: block === null || block === undefined ? null : Number(block) };
641
+ });
642
+ } else {
643
+ if (typeof factory !== "string" || !ADDRESS_RE.test(factory)) throw bad("factory");
644
+ if (deploymentBlock !== null && deploymentBlock !== undefined && !Number.isSafeInteger(Number(deploymentBlock))) {
645
+ throw bad("deploymentBlock");
646
+ }
647
+ targets = [{ factory, deploymentBlock: deploymentBlock === null || deploymentBlock === undefined ? null : Number(deploymentBlock) }];
680
648
  }
681
- const startBlock = fromBlock === null || fromBlock === undefined
682
- ? (deploymentBlock === null || deploymentBlock === undefined ? 0 : Number(deploymentBlock))
683
- : fromBlock;
684
- const base = { address: factory, fromBlock: startBlock, toBlock };
685
- let logs = [];
686
- if (address) {
687
- const padded = topicAddress(address);
688
- const [asLocker, asClaimer] = await Promise.all([
689
- readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS, null, padded, null] }),
690
- readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS, null, null, padded] }),
691
- ]);
692
- const seen = new Set();
693
- for (const log of asLocker.concat(asClaimer)) {
694
- const id = `${log.transactionHash || ""}:${log.logIndex ?? ""}`;
695
- if (seen.has(id)) continue;
696
- seen.add(id);
697
- logs.push(log);
649
+ const chain = numberField(chainId, "chainId");
650
+ let orders = [];
651
+ const seenLogs = new Set();
652
+ for (const target of targets) {
653
+ // THE CHAIN SAYS WHERE ITS ORDERS CAN START. An explicit fromBlock wins; otherwise the factory's own
654
+ // deployment block is used. Zero remains the last resort for a caller that knows the factory existed at genesis.
655
+ const startBlock = fromBlock === null || fromBlock === undefined
656
+ ? (target.deploymentBlock === null ? 0 : target.deploymentBlock)
657
+ : fromBlock;
658
+ const base = { address: target.factory, fromBlock: startBlock, toBlock };
659
+ let logs = [];
660
+ if (address) {
661
+ const padded = topicAddress(address);
662
+ const [asLocker, asClaimer] = await Promise.all([
663
+ readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS, null, padded, null] }),
664
+ readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS, null, null, padded] }),
665
+ ]);
666
+ logs = asLocker.concat(asClaimer);
667
+ } else {
668
+ logs = await readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS] });
669
+ }
670
+ for (const log of logs) {
671
+ const id = `${target.factory}:${log.address || ""}:${log.transactionHash || ""}:${log.logIndex ?? ""}`;
672
+ if (seenLogs.has(id)) continue;
673
+ seenLogs.add(id);
674
+ const order = decodeOrderLog(log);
675
+ if (order) orders.push({ ...order, factory: target.factory });
698
676
  }
699
- } else {
700
- logs = await readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS] });
701
677
  }
702
- const orders = logs.map(decodeOrderLog).filter(Boolean);
703
- for (const order of orders) order.factory = factory;
704
- const orderKey = (order) => `${order.transactionHash || ""}:${order.logIndex ?? ""}`;
678
+ const orderKey = (order) => `${order.factory || ""}:${order.transactionHash || ""}:${order.logIndex ?? ""}`;
705
679
  const seed = seedOf(mnemonic);
706
680
  const found = [];
707
681
  const foundKeys = new Set();
708
- const v2Matched = new Set();
709
682
 
710
683
  // A V2 ORDER IS FOUND FROM ITS OWN SALT. No index is reserved and no range is scanned: the binding names the
711
684
  // factory, the role and the public `OrderCreated` salt, so the same words on another device or at another
712
- // factory produce a different half. The v2 pass runs first; v1 orders are left for the index scan below.
685
+ // factory produce a different half.
713
686
  for (const order of orders) {
714
687
  let commitment;
715
688
  try {
716
- commitment = spendCommitmentFromSeedV2(seed, { chainId: chain, factory, role: "taker", salt: order.salt });
689
+ commitment = spendCommitmentFromSeedV2(seed, { chainId: chain, factory: order.factory, role: "taker", salt: order.salt });
717
690
  } catch {
718
691
  continue;
719
692
  }
@@ -724,67 +697,7 @@ export async function findSwaps({ mnemonic, chainId, factory, address = null, ev
724
697
  const key = orderKey(order);
725
698
  if (foundKeys.has(key)) continue;
726
699
  foundKeys.add(key);
727
- v2Matched.add(key);
728
- found.push({ ...order, index: null, derivation: "salt-v2", side });
729
- }
730
-
731
- // MATCH V1 BY COMMITMENT, NOT BY A DENSE INDEX RANGE. The logs are already in hand; the only cost of a missing
732
- // index is one derivation. Building the map first also keeps each order from being compared against every
733
- // index.
734
- const byCommit = new Map();
735
- for (const order of orders) {
736
- if (v2Matched.has(orderKey(order))) continue;
737
- const locker = order.commitHalfLocker.toLowerCase();
738
- const claimer = order.commitHalfClaimer.toLowerCase();
739
- if (locker) {
740
- if (!byCommit.has(locker)) byCommit.set(locker, []);
741
- byCommit.get(locker).push({ order, side: "locker" });
742
- }
743
- if (claimer && claimer !== locker) {
744
- if (!byCommit.has(claimer)) byCommit.set(claimer, []);
745
- byCommit.get(claimer).push({ order, side: "claimer" });
746
- }
747
- }
748
- const v1Keys = orders.filter((order) => !v2Matched.has(orderKey(order))).map(orderKey);
749
- const v1Needed = v1Keys.length > 0;
750
- const remaining = new Set(v1Keys);
751
- let scanned = 0;
752
- let stoppedBy = null;
753
- if (onProgress !== null && typeof onProgress !== "function") throw bad("onProgress");
754
- if (v1Needed && signal && signal.aborted === true) stoppedBy = "aborted";
755
- if (v1Needed && stoppedBy === null) {
756
- for (let offset = 0; offset < max; offset += 1) {
757
- const index = startIndex + offset;
758
- scanned = offset + 1;
759
- const commitment = spendCommitmentFromSeed(seed, chain, index);
760
- const matches = byCommit.get(commitment) || [];
761
- for (const { order, side } of matches) {
762
- const key = orderKey(order);
763
- if (foundKeys.has(key)) continue;
764
- foundKeys.add(key);
765
- remaining.delete(key);
766
- found.push({ ...order, index, derivation: "index-v1", side });
767
- }
768
- // EVERY MATCHED ORDER ENDS ITS OWN SEARCH. A key with only its own orders in the logs does not pay for
769
- // the rest of the bound once the last one is found. A shared factory keeps the unrelated logs, so the
770
- // scan continues to the requested bound and reports that it stopped there.
771
- const final = remaining.size === 0 || offset === max - 1;
772
- if (final || scanned % RECOVERY_SCAN_YIELD_EVERY === 0) {
773
- // Progress is advisory: a page callback that throws must not turn a completed scan into a failed one.
774
- if (typeof onProgress === "function") {
775
- try { onProgress({ scanned, index }); } catch { /* progress is not the result */ }
776
- }
777
- }
778
- // A CALLER CAN CANCEL. The check is after the progress callback, so a worker that aborts from its
779
- // progress handler stops at this chunk instead of finishing the requested range.
780
- if (signal && signal.aborted === true) { stoppedBy = "aborted"; break; }
781
- if (remaining.size === 0) break;
782
- // A LARGE CALLER-SUPPLIED BOUND MUST NOT OWN THE MAIN THREAD. The scan yields between chunks so the page
783
- // can paint, and a later call can continue from `nextIndex`.
784
- if (scanned % RECOVERY_SCAN_YIELD_EVERY === 0) {
785
- await new Promise((resolve) => setTimeout(resolve, 0));
786
- }
787
- }
700
+ found.push({ ...order, derivation: "salt-v2", side });
788
701
  }
789
702
  // EACH FOUND ORDER CARRIES THE MONERO HEIGHT ITS WITHDRAWAL MAY START FROM. The rule lives here, not in a
790
703
  // page: a widget and the recovery page must not derive two different answers from one chain.
@@ -834,17 +747,10 @@ export async function findSwaps({ mnemonic, chainId, factory, address = null, ev
834
747
  order.xmrAmount = read.value;
835
748
  order.xmrAmountReason = read.reason;
836
749
  }
837
- const searchedUpTo = scanned ? startIndex + scanned - 1 : null;
838
- const complete = !v1Needed || remaining.size === 0 || startIndex + scanned >= RECOVERY_INDEX_MAX;
839
- const nextIndex = complete ? null : startIndex + scanned;
840
750
  return {
841
751
  swaps: found,
842
- scanned,
843
- // A CALLER MUST NOT READ "NO SWAPS" AS "THE WHOLE RANGE WAS SEARCHED". The allocator ceiling is the only
844
- // complete range; a smaller caller-supplied bound says where the search stopped. A result made only of v2
845
- // orders has no range to search and is complete by construction.
846
- searchedUpTo,
847
- complete,
848
- ...(complete ? {} : { incompleteReason: stoppedBy || "max-index", nextIndex }),
752
+ // EVERY ORDER IN THE LOGS WAS READ. There is no index range to exhaust, so a result cannot be partial by
753
+ // construction; an unreadable log request is a refusal from `readLogs`, not an incomplete answer.
754
+ complete: true,
849
755
  };
850
756
  }
@@ -24,14 +24,15 @@ const sameRelay = (a, b) => String(a === undefined || a === null ? "" : a) === S
24
24
  *
25
25
  * `relayUrl` is the relay origin (for example `https://relay.example`), `partner` is the optional partner
26
26
  * label and every other option is passed to `buildFirmRequest`. A transport error is
27
- * `server-unavailable`; a relay refusal keeps its code in `quote-refused`. A timeout is not retried here:
28
- * the salt is part of the signed terms, so a retry needs the caller's decision and a fresh proof.
27
+ * `server-unavailable`; a relay refusal keeps its code in `quote-refused`. A timeout is retried once with the
28
+ * same bytes (the same salt, proof and body); a network failure or a refusal is not.
29
29
  */
30
30
  export async function requestFirmQuote({
31
31
  relayUrl,
32
32
  partner = null,
33
33
  fetchImpl = null,
34
34
  timeoutMs = 20_000,
35
+ retryTimeouts = 1,
35
36
  ...request
36
37
  } = {}) {
37
38
  const base = String(relayUrl === undefined || relayUrl === null ? "" : relayUrl).trim().replace(/\/+$/, "");
@@ -45,11 +46,36 @@ export async function requestFirmQuote({
45
46
  });
46
47
 
47
48
  const http = createHttp({ apiBase: base, fetchImpl, timeoutMs });
48
- const response = await http.tryJson("/v1/quote", {
49
+ // THE RELAY'S PUBLISHED FEE IS PART OF THE VERDICT. `GET /v1/relay` is unauthenticated and names the operator's
50
+ // recipient and rate; without comparing the signed quote with it, a relay can put an arbitrary fee recipient into
51
+ // the escrow terms. Partner rates are private, so only the recipient is compared when a partner key is used.
52
+ let published = null;
53
+ try {
54
+ const info = await http.tryJson("/v1/relay");
55
+ if (!info || info.ok !== true || !info.body || typeof info.body !== "object") {
56
+ throw new SdkError("quote-refused", { step: "relay-info", why: "unavailable" });
57
+ }
58
+ published = info.body;
59
+ } catch (error) {
60
+ if (error instanceof SdkError) throw error;
61
+ throw new SdkError("quote-refused", { step: "relay-info", why: "unavailable" });
62
+ }
63
+ const sendQuote = () => http.tryJson("/v1/quote", {
49
64
  method: "POST",
50
65
  headers: { "content-type": "application/json" },
51
66
  body,
52
67
  });
68
+ let response;
69
+ try {
70
+ response = await sendQuote();
71
+ } catch (error) {
72
+ // A TIMEOUT IS RETRIED WITH THE EXACT SAME BYTES. The salt and proof are already in `body`; reusing them is
73
+ // what makes the retry idempotent for a relay that keys by request hash. A network failure or a refusal is
74
+ // not retried here: the caller has to decide, and a second quote could move the terms.
75
+ if (retryTimeouts > 0 && error && error.code === "server-unavailable" && error.params && error.params.why === "timeout") {
76
+ response = await sendQuote();
77
+ } else throw error;
78
+ }
53
79
 
54
80
  if (!response.ok) {
55
81
  const code = response.body && response.body.code ? String(response.body.code) : null;
@@ -76,6 +102,17 @@ export async function requestFirmQuote({
76
102
  features: request.features,
77
103
  request: built,
78
104
  });
105
+ const publishedRecipient = String(published.feeRecipient === undefined || published.feeRecipient === null ? "" : published.feeRecipient).toLowerCase();
106
+ const quoteRecipient = String(verified.quote.feeRecipient === undefined || verified.quote.feeRecipient === null ? "" : verified.quote.feeRecipient).toLowerCase();
107
+ if (!publishedRecipient || publishedRecipient !== quoteRecipient) {
108
+ throw new SdkError("quote-refused", { step: "fee", why: "fee-recipient" });
109
+ }
110
+ if (!partner && String(published.feeBps) !== String(verified.quote.feeBps)) {
111
+ throw new SdkError("quote-refused", { step: "fee", why: "fee-bps" });
112
+ }
113
+ if (published.relayId !== undefined && published.relayId !== null && String(published.relayId) !== String(response.body.relay)) {
114
+ throw new SdkError("quote-refused", { step: "relay-info", why: "relay" });
115
+ }
79
116
  return {
80
117
  ...verified,
81
118
  relay: response.body.relay ?? null,
@@ -164,7 +164,7 @@ export function verifyFirmAnswer({ answer, features, request, now = null } = {})
164
164
  if (!payload || typeof payload !== "object" || !payload.quote) {
165
165
  throw new SdkError("quote-refused", { step: "answer", why: "payload" });
166
166
  }
167
- if (payload.contextVersion !== "ninsei-order-v3" || Number(payload.quoteVersion) !== 9) {
167
+ if (payload.contextVersion !== "ninsei-order-v3" || Number(payload.quoteVersion) !== 10) {
168
168
  throw new SdkError("quote-refused", { step: "answer", why: "version" });
169
169
  }
170
170
  if (!same(payload.factory, request.terms.order.factory)) {
@@ -13,7 +13,7 @@ import { relayViewInfo, sealViewEnvelope } from "./relayView.mjs";
13
13
  import { firmTermsDigest, firmTermsMissingFields } from "./relayTerms.mjs";
14
14
 
15
15
  const hexToBytes = (value, field, width) => {
16
- const text = String(value === undefined || value === null ? "" : value).replace(/^0x/, "");
16
+ const text = String(value === undefined || value === null ? "" : value).replace(/^0x/i, "");
17
17
  if (!new RegExp("^[0-9a-fA-F]{" + width * 2 + "}$").test(text)) {
18
18
  throw new SdkError("bad-input", { field });
19
19
  }
@@ -46,7 +46,7 @@ const assertPoint = (value, field) => {
46
46
  return hex(bytes);
47
47
  };
48
48
 
49
- const PROOF_FIELDS = ["XA", "XB", "proofs"];
49
+ const PROOF_FIELDS = ["XA", "XB", "pokA", "pokB", "proofs"];
50
50
  function normaliseProof(proof) {
51
51
  if (!proof || typeof proof !== "object") throw new SdkError("bad-input", { field: "clientHalf.proof" });
52
52
  for (const field of PROOF_FIELDS) {
@@ -59,6 +59,15 @@ function normaliseProof(proof) {
59
59
  }
60
60
  const xa = normHex(proof.XA, 33, "clientHalf.proof.XA");
61
61
  const xb = normHex(proof.XB, 32, "clientHalf.proof.XB");
62
+ const pok = (entry, label, width) => {
63
+ if (!entry || typeof entry !== "object") throw new SdkError("bad-input", { field: "clientHalf.proof." + label });
64
+ return {
65
+ R: normHex(entry.R, width, "clientHalf.proof." + label + ".R"),
66
+ s: normHex(entry.s, 32, "clientHalf.proof." + label + ".s"),
67
+ };
68
+ };
69
+ const pokA = pok(proof.pokA, "pokA", 33);
70
+ const pokB = pok(proof.pokB, "pokB", 32);
62
71
  const proofs = proof.proofs.map((entry, index) => {
63
72
  if (!entry || typeof entry !== "object" || !entry.sig) {
64
73
  throw new SdkError("bad-input", { field: "clientHalf.proof.proofs." + index });
@@ -73,7 +82,7 @@ function normaliseProof(proof) {
73
82
  sig,
74
83
  };
75
84
  });
76
- return { XA: xa, XB: xb, proofs };
85
+ return { XA: xa, XB: xb, pokA, pokB, proofs };
77
86
  }
78
87
 
79
88
  /**