@ninsei-labs/sdk 0.56.1 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +78 -28
  4. package/THIRD_PARTY_NOTICES.md +176 -2
  5. package/assets/vendors/MANIFEST.json +1 -13
  6. package/assets/vendors/sdk/sdk-browser.js +5 -4
  7. package/engine/atomic/dleq2.js +116 -15
  8. package/engine/atomic/order.js +21 -3
  9. package/engine/core/config.js +20 -46
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/rfqSource.js +6 -133
  12. package/engine/core/swap.js +8 -8
  13. package/engine/evm/asyncRoute.js +1 -1
  14. package/engine/evm/claimGas.js +2 -1
  15. package/engine/evm/escrow.js +13 -8
  16. package/engine/evm/factory.js +11 -6
  17. package/engine/evm/funding.js +8 -3
  18. package/engine/evm/index.js +5 -6
  19. package/engine/evm/session.js +48 -279
  20. package/engine/monero/address.js +15 -33
  21. package/engine/monero/keys.js +124 -0
  22. package/engine/monero/mnemonic.js +104 -0
  23. package/engine/monero/scan.js +121 -28
  24. package/engine/monero/wallet.js +31 -68
  25. package/engine/monero/wordlist.en.js +210 -0
  26. package/engine/recovery/restore.js +9 -9
  27. package/engine/sdk/bridge.js +9 -187
  28. package/engine/ui/walletModal.js +7 -27
  29. package/index.d.ts +234 -262
  30. package/package.json +7 -6
  31. package/src/actions.mjs +8 -5
  32. package/src/codes.mjs +17 -0
  33. package/src/config.mjs +17 -54
  34. package/src/engine.mjs +9 -6
  35. package/src/feeEstimate.mjs +11 -4
  36. package/src/http.mjs +4 -1
  37. package/src/index.mjs +24 -45
  38. package/src/legs/kyber.mjs +23 -0
  39. package/src/lock.mjs +1 -0
  40. package/src/order.mjs +110 -22
  41. package/src/primitives.mjs +4 -5
  42. package/src/probes.mjs +9 -3
  43. package/src/public/networks.d.ts +45 -0
  44. package/src/public/networks.mjs +10 -1
  45. package/src/public/recovery.d.ts +17 -1
  46. package/src/public/recovery.mjs +1 -0
  47. package/src/public/xmr.mjs +1 -1
  48. package/src/quotePolicy.mjs +25 -0
  49. package/src/quotes.mjs +109 -765
  50. package/src/readyWindow.mjs +76 -0
  51. package/src/recovery-key.mjs +71 -16
  52. package/src/recovery.mjs +11 -28
  53. package/src/relayClaim.mjs +132 -0
  54. package/src/relayFeatures.mjs +25 -13
  55. package/src/relayFirmClient.mjs +36 -7
  56. package/src/relayQuote.mjs +92 -11
  57. package/src/relayView.mjs +3 -3
  58. package/src/swap-flow.mjs +146 -60
  59. package/src/swaps.mjs +521 -357
  60. package/src/sweep-action.mjs +73 -0
  61. package/src/sweep-restore.mjs +8 -4
  62. package/src/sweep.mjs +12 -2
  63. package/src/version.mjs +1 -1
  64. package/src/xmr-arrival.mjs +328 -29
  65. package/src/xmrAmountPolicy.mjs +35 -0
  66. package/assets/vendors/atomic/atomic-browser.js +0 -24
  67. package/assets/vendors/monero/monero-js-browser.js +0 -58
  68. package/assets/vendors/monero-js/LICENSE +0 -9
  69. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
  70. package/engine/atomic/order-client.js +0 -56
  71. package/engine/atomic/order-worker.js +0 -156
  72. package/engine/evm/asyncExec.js +0 -577
  73. package/engine/evm/asyncLegs.js +0 -308
@@ -0,0 +1,76 @@
1
+ // THE NODE'S READY WINDOW, READ ONCE.
2
+ //
3
+ // A maker advertises the range in which it will accept `readyBy` for one side: `readyMinSeconds` is the shortest
4
+ // horizon it can finish in, `readyMaxSeconds` the longest it will sign. The SDK used to keep its own 1200 s and
5
+ // 20-minute numbers, so a node configured differently and the client disagreed about when a sale still had time.
6
+ //
7
+ // The lead a depositor leaves the maker is derived, not guessed: the window's spare room above the minimum is
8
+ // `max - min`; the client waits until `min - (max - min)` remains. The default node window is 2400..3000 s, so
9
+ // the lead is 1800 s: the node's settlement margin, not the old 1200 s. A narrower window gives a shorter lead,
10
+ // never less than the time the required confirmations need.
11
+ import { SdkError } from "./errors.mjs";
12
+
13
+ const int = (value) => {
14
+ const n = Number(value);
15
+ return Number.isSafeInteger(n) ? n : null;
16
+ };
17
+
18
+ /** Read and validate one `FirmWindow` from the signed features, or refuse by name. */
19
+ export function readReadyWindow(value, { side = null, field = "readyWindow" } = {}) {
20
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
21
+ throw new SdkError("bad-input", { field, why: "missing" });
22
+ }
23
+ const min = int(value.readyMinSeconds);
24
+ const max = int(value.readyMaxSeconds);
25
+ if (min === null || max === null || min <= 0 || max < min) {
26
+ throw new SdkError("bad-input", { field, why: "bounds" });
27
+ }
28
+ if (side !== null && value.side !== undefined && String(value.side) !== String(side)) {
29
+ throw new SdkError("bad-input", { field, why: "side" });
30
+ }
31
+ return Object.freeze({
32
+ market: value.market === undefined || value.market === null ? null : String(value.market),
33
+ side: value.side === undefined || value.side === null ? null : String(value.side),
34
+ xmrNetwork: value.xmrNetwork === undefined || value.xmrNetwork === null ? null : String(value.xmrNetwork),
35
+ readyMinSeconds: min,
36
+ readyMaxSeconds: max,
37
+ settlementMinSeconds: int(value.settlementMinSeconds),
38
+ settlementMaxSeconds: int(value.settlementMaxSeconds),
39
+ quoteTtlSeconds: int(value.quoteTtlSeconds),
40
+ });
41
+ }
42
+
43
+ /**
44
+ * HOW LONG BEFORE `readyBy` THE DEPOSITOR MAY STILL REFUND.
45
+ *
46
+ * The maker's own settlement margin is not a wire field; the advertised window carries it implicitly. The node
47
+ * publishes `[min, max]` where `max - min` is the headroom it keeps above the minimum, and that headroom is the
48
+ * time the depositor must leave for the payout to settle before a refund. The default 2400..3000 window therefore
49
+ * gives 600 s, not the retired 1200 s: the old reserve woke the helper while a payout could still be confirming.
50
+ */
51
+ export function readyLeadSec(window) {
52
+ const ready = readReadyWindow(window);
53
+ const headroom = ready.readyMaxSeconds - ready.readyMinSeconds;
54
+ // A window with more headroom than its minimum cannot make the depositor refund before the quote exists; cap
55
+ // the lead at the minimum instead of letting a degenerate signed range move it into the past.
56
+ return Math.max(0, Math.min(headroom, ready.readyMinSeconds));
57
+ }
58
+
59
+ /** The node's own settlement margin: the latest point at which it can still pay before `readyBy`. The advertised
60
+ * `settlementMinSeconds/MaxSeconds` describe `t1 - readyBy` (the claim window), not this payout margin, so they
61
+ * are carried for callers but do not decide the late boundary. */
62
+ export function readyLateSec(window) {
63
+ const ready = readReadyWindow(window);
64
+ const headroom = ready.readyMaxSeconds - ready.readyMinSeconds;
65
+ const derived = ready.readyMinSeconds - headroom;
66
+ // A range whose headroom swallows its minimum cannot advertise "pay immediately"; keep the minimum as the
67
+ // conservative boundary rather than disabling the check with a zero.
68
+ return Math.max(0, derived > 0 ? derived : ready.readyMinSeconds);
69
+ }
70
+
71
+ /** The longest wait a quote from this window can ask for, without inventing a second client-side deadline. */
72
+ export function readyWindowMs(window, marginSec = 300) {
73
+ const ready = readReadyWindow(window);
74
+ const margin = Number.isFinite(Number(marginSec)) && Number(marginSec) >= 0 ? Number(marginSec) : 300;
75
+ return (ready.readyMaxSeconds + margin) * 1000;
76
+ }
@@ -247,6 +247,10 @@ export async function createRecoveryKeyFile({ mnemonic, createdAt, passphrase =
247
247
  const salt = crypto.getRandomValues(new Uint8Array(16));
248
248
  const iv = crypto.getRandomValues(new Uint8Array(12));
249
249
  const header = {
250
+ // THE ENCRYPTED FILE NAMES ITSELF TOO. The plain file has its magic line; without a `kind` the JSON backup was
251
+ // indistinguishable from any other ciphertext object. It is outside the AAD (which carries the same constant),
252
+ // so older files without it still open.
253
+ kind: "ninsei-recovery-key",
250
254
  v: RECOVERY_KEY_ENVELOPE_VERSION,
251
255
  alg: RECOVERY_KEY_ALG,
252
256
  iter: RECOVERY_KEY_ITER,
@@ -289,9 +293,11 @@ export async function openRecoveryKeyFile(contents, passphrase = "") {
289
293
  } catch {
290
294
  throw failed("parse");
291
295
  }
292
- if (!envelope || envelope.v !== RECOVERY_KEY_ENVELOPE_VERSION || envelope.alg !== RECOVERY_KEY_ALG) throw failed("parse");
296
+ if (!envelope || (envelope.kind !== undefined && envelope.kind !== "ninsei-recovery-key")
297
+ || envelope.v !== RECOVERY_KEY_ENVELOPE_VERSION || envelope.alg !== RECOVERY_KEY_ALG) throw failed("parse");
293
298
  for (const field of ["salt", "iv", "ciphertext"]) if (typeof envelope[field] !== "string" || !envelope[field]) throw failed("parse");
294
- const iter = Number(envelope.iter);
299
+ let iter = null;
300
+ try { iter = Number(envelope.iter); } catch { iter = null; }
295
301
  if (!Number.isInteger(iter) || iter < ITER_MIN || iter > ITER_MAX) throw failed("parse");
296
302
  if (passphrase.length < 12) throw failed("passphrase");
297
303
 
@@ -363,12 +369,18 @@ function topicAddress(address) {
363
369
  }
364
370
 
365
371
  function decodeOrderLog(log) {
366
- const topics = Array.isArray(log && log.topics) ? log.topics : [];
367
- const topic0 = String(topics[0] || "").toLowerCase();
368
- if (topics.length < 4 || !ORDER_CREATED_TOPICS.includes(topic0)) return null;
369
- const data = String(log.data || "").replace(/^0x/, "");
372
+ if (!log || typeof log !== "object") return null;
373
+ const topics = Array.isArray(log.topics) ? log.topics : [];
374
+ if (topics.length < 4 || topics.some((topic) => typeof topic !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(topic))) return null;
375
+ const topic0 = topics[0].toLowerCase();
376
+ if (!ORDER_CREATED_TOPICS.includes(topic0)) return null;
377
+ if (typeof log.data !== "string" || !/^0x[0-9a-fA-F]*$/.test(log.data)) return null;
378
+ const data = log.data.slice(2);
370
379
  const modern = topic0 === ORDER_CREATED_TOPIC;
371
- if (data.length < 64 * (modern ? 13 : 12)) return null;
380
+ if (data.length < 64 * (modern ? 13 : 12) || data.length % 64 !== 0) return null;
381
+ if (log.transactionHash !== undefined && log.transactionHash !== null && typeof log.transactionHash !== "string") return null;
382
+ if (log.blockNumber !== undefined && log.blockNumber !== null && typeof log.blockNumber !== "number" && typeof log.blockNumber !== "string") return null;
383
+ if (log.logIndex !== undefined && log.logIndex !== null && typeof log.logIndex !== "number" && typeof log.logIndex !== "string") return null;
372
384
  const word = (i) => "0x" + data.slice(i * 64, (i + 1) * 64).toLowerCase();
373
385
  // THE FIELD OFFSETS MOVED WHEN `xmrAmount` JOINED THE EVENT. The old topic has no XMR amount; its orders fall
374
386
  // back to the clone read, and a caller can still tell why from `xmrAmountReason`.
@@ -390,15 +402,15 @@ function decodeOrderLog(log) {
390
402
  registry: "0x" + data.slice((9 + shift) * 64 + 24, (10 + shift) * 64),
391
403
  provider: "0x" + data.slice((10 + shift) * 64 + 24, (11 + shift) * 64),
392
404
  quoteKey: "0x" + data.slice((11 + shift) * 64 + 24, (12 + shift) * 64),
393
- transactionHash: log.transactionHash || null,
405
+ transactionHash: typeof log.transactionHash === "string" ? log.transactionHash : null,
394
406
  blockNumber: log.blockNumber != null ? Number(log.blockNumber) : null,
395
407
  logIndex: log.logIndex != null ? Number(log.logIndex) : null,
396
408
  };
397
409
  }
398
410
 
399
- // THE CLONE CARRIES THE ORDER, INCLUDING THE XMR AMOUNT. OrderCreated does not repeat `xmrAmount`, and the clone
400
- // has no getter for it, but word 18 of the condition blob is in its code. Read it only from a clone of the exact
401
- // shape: a contract of another size is not this order and must not yield a guessed number.
411
+ // THE CLONE CARRIES THE ORDER, INCLUDING THE XMR AMOUNT. The legacy OrderCreated has no `xmrAmount`; the modern
412
+ // event carries it, while a clone has no getter, but word 18 of the condition blob is in its code. Read the clone
413
+ // only from the exact shape: a contract of another size is not this order and must not yield a guessed number.
402
414
  const CLONE_CODE_BYTES = 877;
403
415
  const XMR_AMOUNT_WORD = 18;
404
416
  const CLONE_PROXY_BYTES = 45;
@@ -471,6 +483,26 @@ export async function readEscrowEvents({ escrows, evmLogs, fromBlock = "earliest
471
483
  fromBlock,
472
484
  toBlock,
473
485
  });
486
+ return decodeEscrowEvents(logs);
487
+ }
488
+
489
+ /**
490
+ * Read the same settlement events WITHOUT naming any escrow to the RPC.
491
+ *
492
+ * The three events carry the escrow in `log.address`, so a client that must not disclose which swaps belong to a
493
+ * visitor can ask for the topics over a block range and filter the returned events locally by `escrow`. The
494
+ * decoder is the same one `readEscrowEvents` uses; this function only builds a request without an address filter.
495
+ */
496
+ export async function readEscrowEventsByTopic({ evmLogs, fromBlock = "earliest", toBlock = "latest" } = {}) {
497
+ const logs = await readLogs(evmLogs, {
498
+ topics: [[ESCROW_EVENT_TOPICS.halfRevealed, ESCROW_EVENT_TOPICS.ready, ESCROW_EVENT_TOPICS.declined]],
499
+ fromBlock,
500
+ toBlock,
501
+ });
502
+ return decodeEscrowEvents(logs);
503
+ }
504
+
505
+ function decodeEscrowEvents(logs) {
474
506
  const events = [];
475
507
  for (const log of logs) {
476
508
  if (!log || typeof log !== "object") continue;
@@ -625,7 +657,7 @@ async function recoveredStartHeight(order, { evmBlockTime, moneroTip, moneroBloc
625
657
  */
626
658
  export async function findSwaps({ mnemonic, chainId, factory = null, factories = null, address = null, evmLogs,
627
659
  fromBlock = null, deploymentBlock = null, toBlock = "latest",
628
- evmBlockTime = null, evmCode = null, moneroTip = null, moneroBlockTimestamp = null,
660
+ evmBlockTime = null, evmBlockTimes = null, evmCode = null, moneroTip = null, moneroBlockTimestamp = null,
629
661
  xmrNodes = null, moneroNetwork = null, fetchImpl = globalThis.fetch } = {}) {
630
662
  // FACTORY HISTORY IS PART OF THE SEARCH. A chain can have more than one factory after a contract change;
631
663
  // searching only the newest one hides every older order. Callers may pass `factories` as addresses or as
@@ -668,11 +700,17 @@ export async function findSwaps({ mnemonic, chainId, factory = null, factories =
668
700
  logs = await readLogs(evmLogs, { ...base, topics: [ORDER_CREATED_TOPICS] });
669
701
  }
670
702
  for (const log of logs) {
671
- const id = `${target.factory}:${log.address || ""}:${log.transactionHash || ""}:${log.logIndex ?? ""}`;
703
+ if (!log || typeof log !== "object") continue;
704
+ const logAddress = typeof log.address === "string" ? log.address : "";
705
+ const logTx = typeof log.transactionHash === "string" ? log.transactionHash : "";
706
+ const logIndex = typeof log.logIndex === "number" || typeof log.logIndex === "string" ? log.logIndex : "";
707
+ const id = `${target.factory}:${logAddress}:${logTx}:${logIndex}`;
672
708
  if (seenLogs.has(id)) continue;
709
+ let order = null;
710
+ try { order = decodeOrderLog(log); } catch { order = null; }
711
+ if (!order) continue;
673
712
  seenLogs.add(id);
674
- const order = decodeOrderLog(log);
675
- if (order) orders.push({ ...order, factory: target.factory });
713
+ orders.push({ ...order, factory: target.factory });
676
714
  }
677
715
  }
678
716
  const orderKey = (order) => `${order.factory || ""}:${order.transactionHash || ""}:${order.logIndex ?? ""}`;
@@ -702,6 +740,23 @@ export async function findSwaps({ mnemonic, chainId, factory = null, factories =
702
740
  // EACH FOUND ORDER CARRIES THE MONERO HEIGHT ITS WITHDRAWAL MAY START FROM. The rule lives here, not in a
703
741
  // page: a widget and the recovery page must not derive two different answers from one chain.
704
742
  const cache = new Map();
743
+ let readBlockTime = evmBlockTime;
744
+ if (typeof evmBlockTimes === "function") {
745
+ const blocks = [...new Set(found.map((order) => order.blockNumber).filter((block) => block !== null && block !== undefined))];
746
+ let timestamps;
747
+ try {
748
+ timestamps = blocks.length ? await evmBlockTimes(blocks) : new Map();
749
+ if (!timestamps || typeof timestamps.get !== "function") throw new Error("block-time-read");
750
+ } catch {
751
+ timestamps = new Map(blocks.map((block) => [block, new Error("block-time-read")]));
752
+ }
753
+ // Never fall back to per-order RPC after the caller chose a batch, including failed or missing items.
754
+ readBlockTime = async (block) => {
755
+ const value = timestamps.get(block);
756
+ if (value !== null && value !== undefined && typeof value !== "number") throw new Error("block-time-read");
757
+ return value;
758
+ };
759
+ }
705
760
  let tip = moneroTip;
706
761
  let header = moneroBlockTimestamp;
707
762
  let readersReason = "no-height-readers";
@@ -720,7 +775,7 @@ export async function findSwaps({ mnemonic, chainId, factory = null, factories =
720
775
  order.payTokenReason = "not-on-chain";
721
776
  }
722
777
  for (const order of found) {
723
- Object.assign(order, await recoveredStartHeight(order, { evmBlockTime, moneroTip: tip, moneroBlockTimestamp: header, cache, readersReason }));
778
+ Object.assign(order, await recoveredStartHeight(order, { evmBlockTime: readBlockTime, moneroTip: tip, moneroBlockTimestamp: header, cache, readersReason }));
724
779
  }
725
780
  // THE XMR AMOUNT COMES FROM THE EVENT IN THE CURRENT FACTORY. The previous event has no field; those orders fall
726
781
  // back to the clone read, where word 18 is read only from a clone of the exact shape. This is data, not a
package/src/recovery.mjs CHANGED
@@ -4,11 +4,9 @@
4
4
  // The file arrives from the interface as a string or as `{ contents }`: the SDK knows neither about
5
5
  // <input type=file> nor about buffers - that is the interface's business.
6
6
  //
7
- // THE RESTORE HEIGHT IS A RULE, NOT A LOOKUP THE PAGE PERFORMS. Two sources exist: the height written into the
8
- // file when it was issued, and the height the service learned when it registered the wallet (it watches the
9
- // address, so its row is often more precise). The order between them is the package's: the service's height wins
10
- // when it is known, the file's is the fallback, and NO height is a named state - not a refusal, because the
11
- // person can still type one.
7
+ // THE RESTORE HEIGHT COMES FROM THE FILE. The retired node route that used to answer by address is gone: the
8
+ // height written into the file is the only source the SDK reads, and no height is a named state - not a refusal,
9
+ // because the person can still type one.
12
10
  import * as engine from "./engine.mjs";
13
11
  import { SdkError } from "./errors.mjs";
14
12
 
@@ -18,7 +16,7 @@ const contentsOf = (file) => {
18
16
  return null;
19
17
  };
20
18
 
21
- export function createRecovery({ http = null, config = null } = {}) {
19
+ export function createRecovery() {
22
20
  return {
23
21
  async open(file, passphrase) {
24
22
  const contents = contentsOf(file);
@@ -86,34 +84,19 @@ export function createRecovery({ http = null, config = null } = {}) {
86
84
  const address = typeof wallet.address === "string" && wallet.address ? wallet.address : null;
87
85
  const fileHeight = Number(wallet.restoreHeight) || 0;
88
86
 
89
- let appHeight = 0;
90
- let appAsked = false;
91
- let appProblem = null;
92
- if (http && config && address) {
93
- appAsked = true;
94
- try {
95
- const answer = await http.json(config.route("swaps"));
96
- const rows = Array.isArray(answer) ? answer : ((answer && answer.swaps) || []);
97
- const row = rows.find((x) => String((x && x.address) || "") === String(address)) || null;
98
- appHeight = Number(row && row.restoreHeight) || 0;
99
- if (!row) appProblem = "no-row";
100
- } catch {
101
- appProblem = "unreachable";
102
- }
103
- }
104
-
105
- const height = appHeight > 0 ? appHeight : fileHeight;
106
- const source = appHeight > 0 ? "app" : (fileHeight > 0 ? "file" : "none");
87
+ const height = fileHeight;
88
+ const source = fileHeight > 0 ? "file" : "none";
107
89
  return {
108
90
  address,
109
91
  height,
110
92
  source,
111
93
  fileHeight,
112
- appHeight,
113
- appAsked,
94
+ appHeight: 0,
95
+ appAsked: false,
114
96
  // Why there is no height, when there is none: a token the interface turns into words. Null when a height
115
- // was found, so a reader cannot mistake "found" for "asked and failed".
116
- appProblem: source === "none" ? (appProblem || "no-height") : null,
97
+ // was found, so a reader cannot mistake "found" for "asked and failed". The service is not asked any more:
98
+ // the retired node routes are not part of the SDK.
99
+ appProblem: source === "none" ? "no-height" : null,
117
100
  };
118
101
  },
119
102
  };
@@ -0,0 +1,132 @@
1
+ // ONE HTTP HOP TO A RELAY CLAIM.
2
+ //
3
+ // A seller on a bid holds XMR and no ETH. The escrow pays the signed `claimTip` out of the payout, so a sender can
4
+ // submit the seller's one-time half and be repaid from the claim itself. This module joins the stored sale record
5
+ // to that wire: it builds the exact body, sends it once to the relay that answered the quote, and returns a claim
6
+ // ONLY when the answer carries a real transaction hash. No wallet is created, used or signed here.
7
+ import { SdkError } from "./errors.mjs";
8
+ import { createHttp } from "./http.mjs";
9
+
10
+ const ADDRESS = /^0x[0-9a-f]{40}$/;
11
+ const HALF = /^[0-9a-f]{64}$/;
12
+ const TXID = /^0x[0-9a-f]{64}$/;
13
+ const DECIMAL = /^(0|[1-9][0-9]*)$/;
14
+
15
+ /**
16
+ * THE RELAY ORIGIN, NORMALISED ONCE. A claim is bound to the origin that answered the quote, so a trailing slash
17
+ * is not a different relay. Plain http is refused for the same reason a quote refuses it: the half must not travel
18
+ * through a hop any middlebox can read and change.
19
+ */
20
+ export function relayOriginOf(value) {
21
+ const base = String(value === undefined || value === null ? "" : value).trim().replace(/\/+$/, "");
22
+ if (!base) throw new SdkError("bad-input", { field: "relayUrl" });
23
+ if (!/^https:\/\//i.test(base)) throw new SdkError("bad-input", { field: "relayUrl", why: "not-https" });
24
+ return base;
25
+ }
26
+
27
+ /** A 20-byte address, lower-cased for the path and for comparison. */
28
+ export function addressTextOf(value, field) {
29
+ const text = String(value === undefined || value === null ? "" : value).trim().toLowerCase();
30
+ if (!ADDRESS.test(text)) throw new SdkError("bad-input", { field });
31
+ return text;
32
+ }
33
+
34
+ /** The seller's half in the one form the relay accepts: `0x` and exactly 64 hex digits. */
35
+ export function halfTextOf(value) {
36
+ const text = String(value === undefined || value === null ? "" : value).trim().toLowerCase().replace(/^0x/, "");
37
+ if (!HALF.test(text)) throw new SdkError("bad-input", { field: "halfClaimer", why: "not-in-record" });
38
+ return "0x" + text;
39
+ }
40
+
41
+ /**
42
+ * POST the half to the relay that answered the quote.
43
+ *
44
+ * A refusal from the relay is `quote-refused` with the provider's own code kept in `params.code`; the provider's
45
+ * message is deliberately NOT copied, because it is not this package's user-facing text. A lost answer is
46
+ * `claim-unknown`: the claim may have been sent, so a second call must begin by reading the escrow, never by
47
+ * assuming that nothing happened. Only a validated transaction hash is a success.
48
+ */
49
+ export async function postRelayClaim({
50
+ relayUrl,
51
+ provider,
52
+ escrow,
53
+ halfClaimer,
54
+ expectedTipWei,
55
+ fetchImpl = null,
56
+ timeoutMs = 20_000,
57
+ } = {}) {
58
+ const base = relayOriginOf(relayUrl);
59
+ const to = addressTextOf(provider, "provider");
60
+ const at = addressTextOf(escrow, "escrow");
61
+ const half = halfTextOf(halfClaimer);
62
+ const http = createHttp({ apiBase: base, fetchImpl, timeoutMs });
63
+ const body = JSON.stringify({ version: 1, halfClaimer: half });
64
+
65
+ let response;
66
+ try {
67
+ response = await http.tryJson(`/v1/claims/${to}/${at}`, {
68
+ method: "POST",
69
+ headers: { "content-type": "application/json" },
70
+ body,
71
+ });
72
+ } catch (error) {
73
+ // A missing fetch is a caller's input problem, not an unknown claim. Everything else that prevented an answer
74
+ // leaves the outcome UNKNOWN: the request may have reached the relay and the claim may already be sent.
75
+ if (error instanceof SdkError && error.code === "bad-input") throw error;
76
+ throw new SdkError("claim-unknown", {
77
+ step: "relay-claim",
78
+ why: (error && error.params && error.params.why) || "answer-lost",
79
+ outcome: "unknown",
80
+ });
81
+ }
82
+
83
+ const answer = response.body && typeof response.body === "object" ? response.body : null;
84
+ const version = answer ? Number(answer.version) : null;
85
+ const code = answer && typeof answer.code === "string" && answer.code ? answer.code : null;
86
+
87
+ if (!response.ok) {
88
+ if (code === "claim-unknown" || code === "claim_unknown") {
89
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "relay-timeout", code, status: response.status, outcome: "unknown" });
90
+ }
91
+ if (code && version === 1) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
92
+ // AN UNVERSIONED NON-2XX IS NOT A REFUSAL WE CAN READ. The claim may still have been sent, so it is unknown.
93
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-status", status: response.status, outcome: "unknown" });
94
+ }
95
+ if (!answer || version !== 1) {
96
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer", outcome: "unknown" });
97
+ }
98
+ if (code) throw new SdkError("quote-refused", { step: "relay-claim", code, status: response.status });
99
+
100
+ // ONLY A REAL TRANSACTION HASH IS A CLAIM. A body without one leaves the outcome unknown, whether the claim never
101
+ // left the relay or its answer was cut off.
102
+ const txid = String(answer.txid === undefined || answer.txid === null ? "" : answer.txid).trim().toLowerCase();
103
+ if (!TXID.test(txid)) {
104
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-txid", outcome: "unknown" });
105
+ }
106
+ const from = String(answer.from === undefined || answer.from === null ? "" : answer.from).trim().toLowerCase();
107
+ if (!ADDRESS.test(from)) {
108
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-from", outcome: "unknown" });
109
+ }
110
+ const tipWei = String(answer.tipWei === undefined || answer.tipWei === null ? "" : answer.tipWei).trim();
111
+ if (!DECIMAL.test(tipWei)) {
112
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-tip", outcome: "unknown" });
113
+ }
114
+
115
+ // THE ANSWER IS BOUND TO THE REQUEST. A relay that answers for another provider, escrow or tip has not reported
116
+ // this sale, and the txid it names is not evidence about this claim.
117
+ const answerProvider = String(answer.provider === undefined || answer.provider === null ? "" : answer.provider).trim().toLowerCase();
118
+ const answerEscrow = String(answer.escrow === undefined || answer.escrow === null ? "" : answer.escrow).trim().toLowerCase();
119
+ if (!answerProvider || !answerEscrow) {
120
+ throw new SdkError("claim-unknown", { step: "relay-claim", why: "answer-binding", outcome: "unknown" });
121
+ }
122
+ if (answerProvider !== to) {
123
+ throw new SdkError("quote-refused", { step: "relay-claim", why: "answer-provider" });
124
+ }
125
+ if (answerEscrow !== at) {
126
+ throw new SdkError("quote-refused", { step: "relay-claim", why: "answer-escrow" });
127
+ }
128
+ if (BigInt(tipWei) !== BigInt(expectedTipWei)) {
129
+ throw new SdkError("quote-refused", { step: "relay-claim", why: "tip", tipWei, expectedTipWei: String(expectedTipWei) });
130
+ }
131
+ return { txid, from, tipWei };
132
+ }
@@ -42,7 +42,19 @@ export const NODE_FEATURES_FIELDS = [
42
42
  ["nonce", "bytes32"],
43
43
  ];
44
44
 
45
- const utf8 = (value) => new TextEncoder().encode(String(value));
45
+ const wireText = (value, field) => {
46
+ if (typeof value === "string") return value;
47
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
48
+ if (typeof value === "bigint") return String(value);
49
+ throw new SdkError("bad-input", { field });
50
+ };
51
+ const wireNumber = (value, field) => {
52
+ let n = null;
53
+ try { n = Number(value); } catch { n = null; }
54
+ if (!Number.isFinite(n)) throw new SdkError("bad-input", { field });
55
+ return n;
56
+ };
57
+ const utf8 = (value, field = "text") => new TextEncoder().encode(wireText(value, field));
46
58
  const concat = (...arrays) => {
47
59
  const total = arrays.reduce((n, a) => n + a.length, 0);
48
60
  const out = new Uint8Array(total);
@@ -51,7 +63,7 @@ const concat = (...arrays) => {
51
63
  return out;
52
64
  };
53
65
  const hexBytes = (value, field, width) => {
54
- const text = String(value === undefined || value === null ? "" : value).replace(/^0x/, "");
66
+ const text = wireText(value === undefined || value === null ? "" : value, field).replace(/^0x/, "");
55
67
  if (!new RegExp("^[0-9a-fA-F]{" + width * 2 + "}$").test(text)) {
56
68
  throw new SdkError("bad-input", { field });
57
69
  }
@@ -68,13 +80,13 @@ const numberWord = (value, field, bits) => {
68
80
  return out;
69
81
  };
70
82
  const addressWord = (value, field) => {
71
- const text = String(value === undefined || value === null ? "" : value).trim();
83
+ const text = wireText(value === undefined || value === null ? "" : value, field).trim();
72
84
  if (!/^(0x)?[0-9a-fA-F]{40}$/.test(text)) throw new SdkError("bad-input", { field });
73
85
  const out = new Uint8Array(32);
74
86
  out.set(hexBytes(text, field, 20), 12);
75
87
  return out;
76
88
  };
77
- const stringWord = (value) => keccak256(utf8(value === undefined || value === null ? "" : value));
89
+ const stringWord = (value, field) => keccak256(utf8(value === undefined || value === null ? "" : value, field));
78
90
  const arrayWord = (values, field, hashOf) => {
79
91
  if (!Array.isArray(values)) throw new SdkError("bad-input", { field });
80
92
  const parts = values.map((value) => hashOf(value));
@@ -85,7 +97,7 @@ function firmWindowHash(window) {
85
97
  if (!window || typeof window !== "object") throw new SdkError("bad-input", { field: "firmWindows" });
86
98
  const parts = [keccak256(utf8(FIRM_WINDOW_TYPE))];
87
99
  for (const [field, type] of FIRM_WINDOW_FIELDS) {
88
- parts.push(type === "string" ? stringWord(window[field]) : numberWord(window[field], "firmWindows." + field, 32));
100
+ parts.push(type === "string" ? stringWord(window[field], "firmWindows." + field) : numberWord(window[field], "firmWindows." + field, 32));
89
101
  }
90
102
  return keccak256(concat(...parts));
91
103
  }
@@ -94,11 +106,11 @@ export function nodeFeaturesStructHash(features) {
94
106
  if (!features || typeof features !== "object") throw new SdkError("bad-input", { field: "features" });
95
107
  const parts = [keccak256(utf8(NODE_FEATURES_TYPE))];
96
108
  for (const [field, type] of NODE_FEATURES_FIELDS) {
97
- if (type === "string") parts.push(stringWord(features[field]));
109
+ if (type === "string") parts.push(stringWord(features[field], "features." + field));
98
110
  else if (type === "address") parts.push(addressWord(features[field], "features." + field));
99
111
  else if (type === "bytes32") parts.push(hexBytes(features[field], "features." + field, 32));
100
112
  else if (type === "uint64") parts.push(numberWord(features[field], "features." + field, 64));
101
- else if (type === "string[]") parts.push(arrayWord(features[field], "features." + field, (value) => stringWord(value)));
113
+ else if (type === "string[]") parts.push(arrayWord(features[field], "features." + field, (value) => stringWord(value, "features." + field)));
102
114
  else if (type === "FirmWindow[]") parts.push(arrayWord(features[field], "features." + field, firmWindowHash));
103
115
  else throw new SdkError("bad-input", { field: "features." + field });
104
116
  }
@@ -124,7 +136,7 @@ const bytesToHex = (bytes) => {
124
136
  };
125
137
 
126
138
  function recoverAddress(digest, signature) {
127
- const sig = String(signature || "").replace(/^0x/, "");
139
+ const sig = wireText(signature === undefined || signature === null ? "" : signature, "signature").replace(/^0x/, "");
128
140
  if (!/^[0-9a-fA-F]{130}$/.test(sig)) return null;
129
141
  let v = parseInt(sig.slice(128, 130), 16);
130
142
  if (v >= 27) v -= 27;
@@ -147,16 +159,16 @@ function recoverAddress(digest, signature) {
147
159
  */
148
160
  export function verifyNodeFeatures({ features, terms = null } = {}) {
149
161
  if (!features || typeof features !== "object") throw new SdkError("bad-input", { field: "features" });
150
- if (features.type !== "node_features" || Number(features.version) !== 1) {
162
+ if (features.type !== "node_features" || wireNumber(features.version, "features.version") !== 1) {
151
163
  throw new SdkError("quote-refused", { step: "features", why: "version" });
152
164
  }
153
165
  const digest = nodeFeaturesDigest(features);
154
166
  const recovered = recoverAddress(digest, features.signature);
155
- const quoteKey = String(features.quoteKey || "").toLowerCase();
167
+ const quoteKey = wireText(features.quoteKey === undefined || features.quoteKey === null ? "" : features.quoteKey, "features.quoteKey").toLowerCase();
156
168
  if (recovered === null || recovered !== quoteKey) {
157
169
  throw new SdkError("quote-refused", { step: "features", why: "signature" });
158
170
  }
159
- const hpkeKey = String(features.hpkeKey || "").replace(/^0x/, "").toLowerCase();
171
+ const hpkeKey = wireText(features.hpkeKey === undefined || features.hpkeKey === null ? "" : features.hpkeKey, "features.hpkeKey").replace(/^0x/, "").toLowerCase();
160
172
  if (!/^[0-9a-f]{64}$/.test(hpkeKey) || /^0+$/.test(hpkeKey)) {
161
173
  throw new SdkError("quote-refused", { step: "features", why: "hpke-key" });
162
174
  }
@@ -164,8 +176,8 @@ export function verifyNodeFeatures({ features, terms = null } = {}) {
164
176
  throw new SdkError("quote-refused", { step: "features", why: "windows" });
165
177
  }
166
178
  if (terms) {
167
- if (String(features.provider || "").toLowerCase() !== String(terms.maker || "").toLowerCase()
168
- || String(features.registry || "").toLowerCase() !== String(terms.registry || "").toLowerCase()) {
179
+ if (wireText(features.provider === undefined || features.provider === null ? "" : features.provider, "features.provider").toLowerCase() !== String(terms.maker || "").toLowerCase()
180
+ || wireText(features.registry === undefined || features.registry === null ? "" : features.registry, "features.registry").toLowerCase() !== String(terms.registry || "").toLowerCase()) {
169
181
  throw new SdkError("quote-refused", { step: "features", why: "identity" });
170
182
  }
171
183
  const market = String(terms.market || "");
@@ -6,7 +6,7 @@
6
6
  import { SdkError } from "./errors.mjs";
7
7
  import { createHttp } from "./http.mjs";
8
8
  import { buildFirmRequest } from "./relayRequest.mjs";
9
- import { verifyFirmAnswer } from "./relayQuote.mjs";
9
+ import { verifyFirmAnswer, verifyRelayForwarded } from "./relayQuote.mjs";
10
10
 
11
11
  const REFUSAL_CODES = new Set([
12
12
  "compliance",
@@ -17,7 +17,14 @@ const REFUSAL_CODES = new Set([
17
17
  "bad_request",
18
18
  "price_changed",
19
19
  ]);
20
- const sameRelay = (a, b) => String(a === undefined || a === null ? "" : a) === String(b === undefined || b === null ? "" : b);
20
+ const wireText = (value, field) => {
21
+ if (typeof value === "string") return value;
22
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
23
+ if (typeof value === "bigint") return String(value);
24
+ throw new SdkError("bad-input", { field });
25
+ };
26
+ const sameRelay = (a, b) => (a === undefined || a === null ? "" : wireText(a, "relay")) ===
27
+ (b === undefined || b === null ? "" : wireText(b, "relay"));
21
28
 
22
29
  /**
23
30
  * Request a firm quote from a relay.
@@ -37,6 +44,9 @@ export async function requestFirmQuote({
37
44
  } = {}) {
38
45
  const base = String(relayUrl === undefined || relayUrl === null ? "" : relayUrl).trim().replace(/\/+$/, "");
39
46
  if (!base) throw new SdkError("bad-input", { field: "relayUrl" });
47
+ // A QUOTE IS SIGNED FOR A RELAY ORIGIN, NOT FOR A PLAIN-TEXT HOP. An http:// base would let any middlebox read
48
+ // the sealed view material and change the relay's answer before the signature check.
49
+ if (!/^https:\/\//i.test(base)) throw new SdkError("bad-input", { field: "relayUrl", why: "not-https" });
40
50
 
41
51
  const built = await buildFirmRequest(request);
42
52
  const body = JSON.stringify({
@@ -86,7 +96,9 @@ export async function requestFirmQuote({
86
96
  }
87
97
 
88
98
  const answer = response.body && response.body.answer;
89
- if (!response.body || Number(response.body.version) !== 1 || !answer) {
99
+ let envelopeVersion = null;
100
+ try { envelopeVersion = response.body ? Number(response.body.version) : null; } catch { envelopeVersion = null; }
101
+ if (!response.body || envelopeVersion !== 1 || !answer) {
90
102
  throw new SdkError("quote-refused", { step: "answer", why: "envelope" });
91
103
  }
92
104
  if (typeof response.body.relay !== "string" || !response.body.relay
@@ -97,24 +109,41 @@ export async function requestFirmQuote({
97
109
  throw new SdkError("quote-refused", { step: "answer", why: "relay" });
98
110
  }
99
111
 
112
+ // THE RELAY'S OWN FORWARDED FRAME IS SIGNED AND BOUND TO THE CLIENT'S EXACT PAYLOAD. Checking it here, before
113
+ // the answer is used, closes the gap where a relay changed the forwarded payload/provider but returned a valid
114
+ // answer for another request.
115
+ verifyRelayForwarded({
116
+ forwarded: response.body.forwarded,
117
+ relayKey: published.relayKey,
118
+ payload: built.payload,
119
+ provider: request.features.provider,
120
+ requestHash: answer.requestHash === undefined || answer.requestHash === null ? "" : answer.requestHash,
121
+ });
100
122
  const verified = verifyFirmAnswer({
101
123
  answer,
102
124
  features: request.features,
103
125
  request: built,
104
126
  });
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();
127
+ const publishedRecipient = wireText(published.feeRecipient === undefined || published.feeRecipient === null ? "" : published.feeRecipient, "relay.feeRecipient").toLowerCase();
128
+ const quoteRecipient = wireText(verified.quote.feeRecipient === undefined || verified.quote.feeRecipient === null ? "" : verified.quote.feeRecipient, "quote.feeRecipient").toLowerCase();
107
129
  if (!publishedRecipient || publishedRecipient !== quoteRecipient) {
108
130
  throw new SdkError("quote-refused", { step: "fee", why: "fee-recipient" });
109
131
  }
110
- if (!partner && String(published.feeBps) !== String(verified.quote.feeBps)) {
132
+ if (!partner && wireText(published.feeBps === undefined || published.feeBps === null ? "" : published.feeBps, "relay.feeBps") !==
133
+ wireText(verified.quote.feeBps === undefined || verified.quote.feeBps === null ? "" : verified.quote.feeBps, "quote.feeBps")) {
111
134
  throw new SdkError("quote-refused", { step: "fee", why: "fee-bps" });
112
135
  }
113
- if (published.relayId !== undefined && published.relayId !== null && String(published.relayId) !== String(response.body.relay)) {
136
+ // THE RELAY MUST NAME ITSELF. A missing id on GET /v1/relay is not "nothing to compare": the answer's relay
137
+ // label would then be accepted without the one check that binds it.
138
+ if (published.relayId === undefined || published.relayId === null
139
+ || wireText(published.relayId, "relay.relayId") !== wireText(response.body.relay, "relay")) {
114
140
  throw new SdkError("quote-refused", { step: "relay-info", why: "relay" });
115
141
  }
116
142
  return {
117
143
  ...verified,
144
+ // THE ORIGIN THAT ANSWERED, KEPT FOR THE LATER CLAIM. The seller has no wallet, so the claim goes back to the
145
+ // same relay through `swaps.claimViaRelay`; the record stores this value and a different origin is refused.
146
+ relayUrl: base,
118
147
  relay: response.body.relay ?? null,
119
148
  offered: response.body.offered ?? null,
120
149
  forwarded: response.body.forwarded ?? null,