@ninsei-labs/sdk 0.57.2 → 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 (46) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +64 -27
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/assets/vendors/MANIFEST.json +1 -9
  5. package/assets/vendors/sdk/sdk-browser.js +4 -4
  6. package/engine/core/config.js +3 -22
  7. package/engine/core/rfqSource.js +6 -133
  8. package/engine/core/swap.js +1 -1
  9. package/engine/evm/index.js +3 -2
  10. package/engine/evm/session.js +46 -277
  11. package/engine/monero/address.js +15 -33
  12. package/engine/monero/keys.js +124 -0
  13. package/engine/monero/mnemonic.js +104 -0
  14. package/engine/monero/scan.js +23 -9
  15. package/engine/monero/wallet.js +31 -68
  16. package/engine/monero/wordlist.en.js +210 -0
  17. package/engine/recovery/restore.js +1 -1
  18. package/engine/sdk/bridge.js +7 -182
  19. package/engine/ui/walletModal.js +7 -27
  20. package/index.d.ts +187 -252
  21. package/package.json +4 -5
  22. package/src/codes.mjs +12 -0
  23. package/src/config.mjs +16 -54
  24. package/src/engine.mjs +3 -0
  25. package/src/index.mjs +24 -45
  26. package/src/order.mjs +2 -2
  27. package/src/public/recovery.d.ts +17 -1
  28. package/src/public/recovery.mjs +1 -0
  29. package/src/quotePolicy.mjs +25 -0
  30. package/src/quotes.mjs +21 -751
  31. package/src/readyWindow.mjs +76 -0
  32. package/src/recovery-key.mjs +39 -2
  33. package/src/recovery.mjs +11 -28
  34. package/src/relayClaim.mjs +132 -0
  35. package/src/relayFirmClient.mjs +3 -0
  36. package/src/relayQuote.mjs +5 -1
  37. package/src/swap-flow.mjs +49 -5
  38. package/src/swaps.mjs +301 -307
  39. package/src/sweep-action.mjs +73 -0
  40. package/src/sweep.mjs +7 -1
  41. package/src/version.mjs +1 -1
  42. package/src/xmr-arrival.mjs +275 -7
  43. package/src/xmrAmountPolicy.mjs +35 -0
  44. package/assets/vendors/monero/monero-js-browser.js +0 -58
  45. package/assets/vendors/monero-js/LICENSE +0 -9
  46. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
package/src/quotes.mjs CHANGED
@@ -1,29 +1,17 @@
1
- // LIVE INDICATIVE QUOTES: the SDK's own quote client.
1
+ // FIRM QUOTES THROUGH A RELAY: the SDK's only quote path.
2
2
  //
3
- // WHY OUR OWN AND NOT THE ENGINE'S. The package must work without `www/js`: the consumer does not have it. The
4
- // rules for reading the quote book are a specification (docs 41 and 54), not foreign code, so they are embodied
5
- // here anew and pinned by a run on fixtures next to the engine implementation. For now the demo screen computes
6
- // with its own copy: it is a test bench, and it is not scary for it to diverge from the SDK - the bench exists
7
- // precisely to notice that.
8
- //
9
- // WHAT MUST NOT BE LOST HERE (all three rules cost the project mistakes):
10
- // 1) a row has TWO rates: rateQuote - as written in the pair, rate - how much non-XMR per 1 XMR. This is not
11
- // duplication but different orientations; zero means "no direction", and it is NEVER divided and never
12
- // becomes a price;
13
- // 2) the size is requested in the units of the pair's ASSET (the first element): for a buy that is XMR, for a
14
- // sell - the token; a size outside the provider's grid is not accepted, so the size is snapped to the grid
15
- // DOWN, not to the nearest;
16
- // 3) a quote older than its own ttlMs is not shown, and a row that contradicts itself (the named sides disagree
17
- // with the pair's name) is not read at all.
3
+ // The old direct node client is gone with its routes. A quote now starts from one recovery key, goes through a
4
+ // relay, and comes back as a signed order quote plus the maker's view half. Every check that used to guard the
5
+ // direct answer - the signature, the registry/provider binding, the cashier pin, the factory and implementation
6
+ // code, the claim tip - still runs here, against the same signed fields.
18
7
  import { fail } from "./errors.mjs";
19
- import { SDK_VERSION } from "./version.mjs";
20
8
  import * as engine from "./engine.mjs";
21
- import { orderQuoteMissingFields, recoverOrderQuoteKey } from "./quoteEip712.mjs";
22
9
  import { claimGasGiftWei } from "../engine/evm/claimGas.js";
23
- import { parseXmr } from "../engine/core/xmrAmount.js";
24
10
  import { takerHalvesV2, recoverySaltOf } from "./recovery-key.mjs";
25
11
  import { acceptCounterpartyChunked, buildOwnSideFromHalvesChunked, jointAddress } from "./order.mjs";
26
12
  import { requestFirmQuote } from "./relayFirmClient.mjs";
13
+ import { readReadyWindow } from "./readyWindow.mjs";
14
+ import { quoteLifeVerdict } from "./quotePolicy.mjs";
27
15
  // THE CHAIN READ NEEDED TO ASK THE REGISTRY WHO OWNS THE KEY. The selector is COMPUTED from the signature, not
28
16
  // remembered: a single wrong hex digit would call another function and return a zero address - and a zero
29
17
  // address is exactly the answer "nobody owns this key", which the caller would take as the truth.
@@ -71,197 +59,6 @@ const requirePinnedCashier = (quote, step, config) => {
71
59
  if (got !== pin) fail("quote-cashier-mismatch", { step, got: got || null, want: pin });
72
60
  };
73
61
 
74
- const num = (v) => (v === undefined || v === null || v === "" ? null : (Number.isFinite(Number(v)) ? Number(v) : null));
75
- const pairAsset = (pair) => String(pair || "").split("/")[0].toUpperCase();
76
- const pairCurrency = (pair) => String(pair || "").split("/")[1] ? String(pair).split("/")[1].toUpperCase() : "";
77
-
78
- /** The pair the user sees: buying XMR - looking at XMR/<token>, selling - at the reverse. */
79
- export const pairFacingUser = (direction, token) =>
80
- (direction === "sell" ? String(token).toUpperCase() + "/XMR" : "XMR/" + String(token).toUpperCase());
81
-
82
- /** Reading one quote row. The shape comes from the specification; networks are NOT filled in. */
83
- export function readQuote(pair, raw, owner = {}, data = {}) {
84
- const q = raw && typeof raw === "object" ? raw : {};
85
- const text = String(pair || q.pair || "").trim().toUpperCase();
86
- if (!text.includes("/")) return null;
87
- const statedAsset = q.asset ? String(q.asset).toUpperCase() : null;
88
- const statedCurrency = q.currency ? String(q.currency).toUpperCase() : null;
89
- const asset = pairAsset(text);
90
- const currency = pairCurrency(text);
91
- const givenRateQuote = num(q.rateQuote);
92
- const givenRate = num(q.rate);
93
- const rateQuote = givenRateQuote !== null ? givenRateQuote : givenRate;
94
- let rate = null;
95
- if (givenRateQuote !== null) rate = givenRate;
96
- else if (rateQuote !== null) rate = currency === "XMR" ? (rateQuote > 0 ? 1 / rateQuote : null) : rateQuote;
97
- const contradicts = (statedAsset && statedAsset !== asset) || (statedCurrency && statedCurrency !== currency);
98
- const at = num(q.at);
99
- return {
100
- providerId: String(owner.providerId || q.providerId || "").trim(),
101
- displayName: owner.displayName || q.displayName || null,
102
- // THE PROVIDER'S MATURITY LEVEL RIDES WITH THE OFFER: a person chooses not only by price but also by how long
103
- // to wait. No field - no value either, not an invented default.
104
- finality: owner.finality || q.finality || null,
105
- pair: text,
106
- asset: statedAsset || asset,
107
- currency: statedCurrency || currency,
108
- assetNetwork: q.assetNetwork ? String(q.assetNetwork) : null,
109
- currencyNetwork: q.currencyNetwork ? String(q.currencyNetwork) : null,
110
- rateQuote,
111
- rate,
112
- // THE CLAIM TIP IS IN THE MAKER'S NATIVE TOKEN (wei). A sale is ranked by what the seller receives AFTER it;
113
- // the value is kept as a string, because a wei amount does not fit a float reliably.
114
- claimTip: (() => {
115
- if (q.claimTip === undefined || q.claimTip === null || q.claimTip === "") return "0";
116
- try { const n = BigInt(q.claimTip); return n < 0n ? "0" : n.toString(); }
117
- catch { return "0"; }
118
- })(),
119
- min: num(q.min),
120
- max: num(q.max),
121
- step: num(q.step),
122
- ttlMs: num(q.ttlMs) && num(q.ttlMs) > 0 ? num(q.ttlMs) : null,
123
- at,
124
- why: q.why ? String(q.why) : null,
125
- disabled: q.disabled === true || (givenRate !== null && !(givenRate > 0)),
126
- // NETWORKS NOT NAMED / FILLED IN BY THE RECEIVER - this is a FACT ABOUT THE QUOTE, and it is visible apart
127
- // from "named and matched": the screen must say "nothing to check against" rather than attribute our network
128
- // to the quote.
129
- networksUnnamed: q.networksUnnamed === true,
130
- networksDerived: q.networksDerived === true,
131
- seq: num(q.seq) !== null ? num(q.seq) : (num(owner.seq) !== null ? num(owner.seq) : num(data.seq)),
132
- signature: q.signature || owner.signature || null,
133
- keyId: q.keyId || null,
134
- networkStated: Boolean(q.assetNetwork || q.currencyNetwork),
135
- contradicts,
136
- ageMs: at === null ? null : Math.max(0, Date.now() - at),
137
- };
138
- }
139
-
140
- /**
141
- * THE BEST OFFER IS THE ONE THAT PAYS THE MOST, NOT THE ONE WITH THE HIGHEST RATE. On a sale the maker may move
142
- * its margin into `claimTip`: the escrow pays that tip out of the seller's payout, so a higher rate with a larger
143
- * tip can leave the seller with less. With no amount there is nothing to compare beyond the rate, and a buy has
144
- * no tip. Native-token wei are converted at 18 decimals: a sale settles in the chain's native coin.
145
- */
146
- export function rankOffers(offers = [], { direction = "buy", amount = null } = {}) {
147
- const list = Array.isArray(offers) ? offers.filter((offer) => offer && Number(offer.rate) > 0) : [];
148
- const amountXmr = Number(amount);
149
- const score = (offer) => {
150
- const rate = Number(offer.rate);
151
- if (direction !== "sell" || !(amountXmr > 0)) return rate;
152
- let tip = 0;
153
- try { tip = Number(BigInt(offer.claimTip || "0")) / 1e18; } catch { tip = 0; }
154
- return amountXmr * rate - tip;
155
- };
156
- const ranked = list.map((offer) => ({ offer, net: score(offer) }))
157
- .sort((a, b) => (b.net - a.net) || (Number(b.offer.rate) - Number(a.offer.rate)));
158
- return { best: ranked.length ? ranked[0].offer : null, net: ranked.length ? ranked[0].net : null, ranked };
159
- }
160
-
161
- /**
162
- * Parsing the book in one place. The envelope is accepted in three forms (a map by pairs, a list of rows, a list
163
- * of providers) and is brought to a single list: the screen must not know which form the answer came in.
164
- * Refusals are named separately from offers: "no direction" and "the quote is stale" are not emptiness.
165
- */
166
- export function readBook(data, now = Date.now()) {
167
- const quotes = data && data.quotes;
168
- const rows = [];
169
- const add = (pair, raw, owner) => { const row = readQuote(pair, raw, owner, data || {}); if (row) rows.push(row); };
170
- if (Array.isArray(quotes)) {
171
- for (const row of quotes) {
172
- if (!row || typeof row !== "object") continue;
173
- const nested = row.quotes && !Array.isArray(row.quotes) && typeof row.quotes === "object" ? row.quotes : null;
174
- if (nested) for (const [pair, q] of Object.entries(nested)) add(pair, q, row);
175
- else add(row.pair, row, row);
176
- }
177
- } else if (quotes && typeof quotes === "object") {
178
- for (const [pair, q] of Object.entries(quotes)) add(pair, q, q && typeof q === "object" ? q : {});
179
- }
180
- // ONE QUOTE PER PAIR PER PROVIDER: if several arrived, we keep the fresh one rather than choosing arbitrarily
181
- // (these are two different offers under one name).
182
- const byKey = new Map();
183
- for (const row of rows) {
184
- const key = (row.providerId || "?") + "|" + row.pair;
185
- const prev = byKey.get(key);
186
- if (!prev || Number(row.at) > Number(prev.at)) byKey.set(key, row);
187
- }
188
- const offers = [];
189
- const refused = [];
190
- for (const row of byKey.values()) {
191
- if (row.contradicts) { refused.push({ ...row, code: "malformed" }); continue; }
192
- if (row.rateQuote === null && row.rate === null) { refused.push({ ...row, code: "malformed" }); continue; }
193
- if (row.disabled || !(row.rate > 0)) { refused.push({ ...row, code: "disabled" }); continue; }
194
- if (row.ttlMs && row.ageMs !== null && row.ageMs > row.ttlMs) { refused.push({ ...row, code: "stale" }); continue; }
195
- offers.push(row);
196
- }
197
- const best = offers.slice().sort((a, b) => b.rate - a.rate)[0] || null;
198
- return { offers, refused, best, at: now };
199
- }
200
-
201
- /**
202
- * The size is snapped to the provider's grid DOWN. A size refusal is not aligned: a size outside the range is a
203
- * provider's refusal and must reach the interface as a code, not turn into permission.
204
- */
205
- export function snapToGrid(size, { min = null, max = null, step = null } = {}) {
206
- const s = Number(size);
207
- if (!Number.isFinite(s) || s <= 0) return { size: null, asked: size, snapped: false, code: "bad-size" };
208
- const st = Number(step);
209
- const lo = Number.isFinite(Number(min)) && min !== null && min !== "" ? Number(min) : 0;
210
- const hi = Number.isFinite(Number(max)) && max !== null && max !== "" ? Number(max) : null;
211
- if (s < lo) return { size: s, asked: s, snapped: false, code: "below-min" };
212
- if (hi !== null && s > hi) return { size: s, asked: s, snapped: false, code: "above-max" };
213
- if (!Number.isFinite(st) || st <= 0) return { size: s, asked: s, snapped: false, code: null };
214
- const steps = Math.floor((s - lo) / st + 1e-9);
215
- let snapped = Number((lo + steps * st).toFixed(12));
216
- if (snapped < lo) snapped = lo;
217
- return { size: snapped, asked: s, snapped: Math.abs(snapped - s) > 1e-12, code: null };
218
- }
219
-
220
- /**
221
- * What the user will receive and what they pay for it, by the best offer and its rate.
222
- * buy: they pay with the token and receive XMR, so the size (the ASSET of the pair XMR/<token>) is XMR.
223
- * sell: they give XMR and receive the token, the ASSET of the pair <token>/XMR is the token itself.
224
- */
225
- export function derivedFor(offer, direction, amount, now = Date.now()) {
226
- const rate = offer && Number.isFinite(Number(offer.rate)) && Number(offer.rate) > 0 ? Number(offer.rate) : null;
227
- const size = direction === "sell" ? (rate !== null && amount > 0 ? amount * rate : null)
228
- : (rate !== null && amount > 0 ? amount / rate : null);
229
- if (size === null) return { rate, size: null, unit: null, code: "no-offer", xmr: null };
230
- const settled = snapToGrid(size, offer || {});
231
- return {
232
- rate,
233
- size: settled.size,
234
- unit: direction === "sell" ? String(offer.currency || "").toUpperCase() || null : "XMR",
235
- snapped: settled.snapped,
236
- code: settled.code,
237
- // HOW MUCH XMR FOR THE REQUESTED SIZE. For a buy this is the size, for a sell - the amount the person gives.
238
- xmr: direction === "sell" ? amount : (Number.isFinite(Number(settled.size)) ? Number(settled.size) : null),
239
- };
240
- }
241
-
242
- // THE ROW FIELDS THAT GO OUT. This is a translation of the SHAPE, not a recomputation: the values are taken from
243
- // the read row and are not changed. The fields are listed explicitly (and not `...row`) so that internal parsing
244
- // markers do not leak out. Selection and priority are done by readBook above: a row gets here only if it has
245
- // already been recognised as an offer.
246
- const compactOffer = (o) => ({
247
- providerId: o.providerId, displayName: o.displayName, pair: o.pair, rate: o.rate, rateQuote: o.rateQuote,
248
- min: o.min, max: o.max, step: o.step, ttlMs: o.ttlMs, at: o.at, seq: o.seq,
249
- // THE MATURITY LEVEL IS PART OF THE CHOICE: one provider gives a better price but only on finalized, another is
250
- // pricier but faster. No field - null, not an invented default.
251
- finality: o.finality || null,
252
- // THE PAIR'S SIDES AND BOTH NETWORKS: the network is part of the market's identity, and the display must
253
- // distinguish arbitrum from arbitrum-sepolia. `networks` is kept as the assembled view of the same values.
254
- asset: o.asset, currency: o.currency,
255
- assetNetwork: o.assetNetwork, currencyNetwork: o.currencyNetwork, networkStated: o.networkStated,
256
- networksDerived: o.networksDerived === true, networksUnnamed: o.networksUnnamed === true,
257
- // THE REASON (in the provider's words), THE PACKAGE'S SIGNATURE AND KEY, THE AGE BY ITS OWN MARK.
258
- claimTip: o.claimTip, why: o.why, signature: o.signature, keyId: o.keyId, ageMs: o.ageMs,
259
- networks: { asset: o.assetNetwork, currency: o.currencyNetwork, stated: o.networkStated },
260
- });
261
-
262
- // A REFUSAL IS THE SAME ROW PLUS A REASON CODE. The fields are not trimmed: the interface needs the range and
263
- // the price of the failed row to tell the person WHY there is no offer (and not just "none").
264
- const compactRefusal = (r) => ({ ...compactOffer(r), code: r.code, why: r.why });
265
62
 
266
63
  /**
267
64
  * A CLAIM TIP IS SIZED BY THE CLAIM, NOT BY THE MAKER'S MOOD. The node's own estimate uses the chain's current
@@ -310,7 +107,7 @@ export function claimTipVerdict({ claimTipWei = 0, baseFeeWei = null, priorityFe
310
107
  return { ok: true, tipWei: tip.toString(), estimateWei: estimate.toString(), ceilingWei: ceiling.toString() };
311
108
  }
312
109
 
313
- export function createQuotes({ config, http, now = () => Date.now(), evmCall = null, evmCode = null, evmBlock = null,
110
+ export function createQuotes({ config, now = () => Date.now(), evmCall = null, evmCode = null, evmBlock = null,
314
111
  providerAllowed = null, knownFactoryCodes = null, knownImplementationCodes = null, denylist = null }) {
315
112
  // THE INTERFACE'S FACTORY POLICY (#103): the code hashes of factories it is willing to trade through
316
113
  // (extcodehash semantics = keccak256 of the runtime code). An EMPTY list is "no policy" (like
@@ -324,546 +121,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
324
121
  const implementationPolicy = Array.isArray(knownImplementationCodes) && knownImplementationCodes.length
325
122
  ? knownImplementationCodes.map((h) => String(h).toLowerCase()).filter(Boolean)
326
123
  : null;
327
- const listeners = new Set();
328
- let timer = null;
329
- let size = 1; // the request size in units of the pair's ASSET; we start from one, as the engine does
330
- let state = null;
331
- let request = { direction: "buy", token: null, amount: null };
332
- let inFlight = false;
333
-
334
- const emit = () => { for (const handler of listeners) handler(state); };
335
-
336
- const tick = async () => {
337
- if (inFlight) return;
338
- inFlight = true;
339
- try {
340
- // THE REQUEST SIZE. Usually it is derived from the person's amount (amount) and refined on the next tick.
341
- // But the caller can name it HIMSELF (size) - then it is taken AS IS rather than derived anew: it is the
342
- // same size the interface has already aligned to the provider's grid. There is no second size rule here.
343
- const explicit = Number.isFinite(Number(request.size)) && Number(request.size) > 0;
344
- const asked = explicit ? Number(request.size) : size;
345
- const data = await http.json("/rate?amount=" + encodeURIComponent(asked) + "&side=" + encodeURIComponent(request.direction));
346
- const book = readBook(data, now());
347
- const amount = Number.isFinite(Number(request.amount)) ? Number(request.amount) : null;
348
- // A SALE IS RANKED BY THE PAYOUT AFTER THE TIP; a buy has no tip. Without an amount the rate is the only
349
- // comparable number, and the service's own best remains the fallback.
350
- const ranked = rankOffers(book.offers, { direction: request.direction, amount });
351
- const offer = ranked.best || book.best;
352
- // The size derived from the person's amount becomes the size of the NEXT request: the price does not depend
353
- // on volume, and the volume is needed by the provider to say whether it takes such a size. With a named size
354
- // there is nothing to derive - it stays what it was asked as.
355
- const derived = offer && amount !== null && !explicit ? derivedFor(offer, request.direction, amount, now()) : null;
356
- if (derived && derived.size !== null) size = derived.size;
357
- // THE UNIT with a named size: a buy is measured in XMR (the ASSET of the pair XMR/<token>), a sell - in the token.
358
- const unitFromOffer = offer ? (String(offer.currency || "").toUpperCase() || null) : null;
359
- const settled = explicit ? (offer ? snapToGrid(asked, offer) : null) : null;
360
- state = {
361
- direction: request.direction,
362
- token: request.token,
363
- amount,
364
- size: explicit ? asked : size,
365
- unit: explicit ? (request.direction === "sell" ? unitFromOffer : "XMR") : (derived ? derived.unit : null),
366
- rate: explicit ? (offer ? Number(offer.rate) : null) : (derived ? derived.rate : null),
367
- xmr: derived ? derived.xmr : null,
368
- at: now(),
369
- providerId: offer ? offer.providerId : null,
370
- sizeOk: explicit ? Boolean(settled && settled.code === null) : Boolean(derived && derived.code === null),
371
- sizeCode: explicit ? (settled ? settled.code : "no-offer") : (derived ? derived.code : "no-offer"),
372
- seq: book.offers.length ? (book.offers.find((o) => o.seq !== null) || {}).seq ?? null : null,
373
- // THE BEST, AS THE SERVICE NAMED IT (for the requested volume and side). The core does NOT recompute it:
374
- // these are response data the interface needs to confirm its own "best" mark by pair and provider.
375
- best: data && data.best && typeof data.best === "object"
376
- ? { providerId: String(data.best.providerId || ""), pair: String(data.best.pair || "") } : null,
377
- offers: book.offers.map(compactOffer),
378
- refused: book.refused.map(compactRefusal),
379
- references: Array.isArray(data && data.references) ? data.references.map((r) => ({ source: r.source, value: num(r.value), at: num(r.at) })) : [],
380
- ok: book.offers.length > 0,
381
- };
382
- emit();
383
- } catch (error) {
384
- // A REFUSAL IS NOT REPLACED BY PAST NUMBERS: showing a stale price as live is worse than saying the connection
385
- // is gone. The data is kept, but ok is cleared, and the interface sees it.
386
- state = { ...(state || { direction: request.direction, token: request.token, amount: null, size, unit: null, rate: null, xmr: null,
387
- at: now(), providerId: null, sizeOk: false, sizeCode: null, seq: null, best: null, offers: [], refused: [], references: [] }),
388
- at: now(), ok: false, error: { code: error && error.code === "server-unavailable" ? "quote-unavailable" : "unknown" } };
389
- emit();
390
- } finally {
391
- inFlight = false;
392
- }
393
- };
394
-
395
- const restart = () => {
396
- if (timer) clearInterval(timer);
397
- timer = null;
398
- if (listeners.size > 0) {
399
- void tick();
400
- timer = setInterval(() => { void tick(); }, config.limits.quotePollMs);
401
- }
402
- };
403
-
404
124
  return {
405
- watch(next, onSnapshot) {
406
- if (typeof onSnapshot !== "function") fail("bad-input", { field: "onSnapshot" });
407
- const direction = next && next.direction === "sell" ? "sell" : "buy";
408
- const token = next && typeof next.token === "string" && next.token ? next.token.toLowerCase() : config.settlement.chain.nativeSymbol.toLowerCase();
409
- request = {
410
- direction,
411
- token,
412
- amount: next && next.amount !== undefined ? next.amount : null,
413
- // A NAMED SIZE (in units of `unit`): an interface that has already aligned the volume to the provider's
414
- // grid hands it here, and the core asks for EXACTLY it rather than deriving it from the amount anew.
415
- size: next && Number.isFinite(Number(next.size)) && Number(next.size) > 0 ? Number(next.size) : null,
416
- };
417
- size = 1;
418
- state = null;
419
- listeners.add(onSnapshot);
420
- restart();
421
- return () => {
422
- listeners.delete(onSnapshot);
423
- if (listeners.size === 0) {
424
- if (timer) clearInterval(timer);
425
- timer = null;
426
- }
427
- };
428
- },
429
- // WHAT THE SDK KNOWS RIGHT NOW: a snapshot without waiting. Needed by an interface that subscribed later than
430
- // the first poll happened.
431
- snapshot: () => state,
432
- // A FIRM QUOTE FOR AN ORDER. It carries a commitment under keys, so THE PROVIDER'S SIGNATURE IS CONFIRMED
433
- // HERE, BY RECOVERING THE ADDRESS FROM THE EIP-712 SIGNATURE - not taken on trust from a flag the backend
434
- // reports. A quote that cannot be verified is not "probably fine": a missing field, a missing signature or
435
- // an unusable domain is REFUSED, never accepted (the rule the old flag carried is kept). The digest is
436
- // built from the quote's own fields, so nothing signed can be swapped afterwards; the named quoteKey is
437
- // matched against the recovered address. THEN THE CHAIN IS ASKED WHO OWNS THE KEY (providerOf): the
438
- // signature alone certifies itself, because a key can sign anything and call itself any provider. The
439
- // registry is read from the quote/order conditions - never from SDK settings: any registry can be deployed
440
- // by anyone, and the order carries which one it is (the field is signed and bound into the terms). Finally
441
- // the interface's allow-list, when it supplied one, is applied as policy (who is admitted at all).
442
- //
443
- // The path and the body are the same as the engine's (`requestOrderQuote` in www/js/core/rfqSource.js): POST to
444
- // the named path, body { providerId, order }. The path is named by name, so it is overridable by options.
445
- // A REVERSE-MODE TICKET. The maker sells XMR; the node answers with a signed order quote that carries the claim
446
- // tip. The tip is checked HERE, on the ticket's own signed figure, with the same formula the node used: base fee
447
- // plus the priority part of the gas price. A buy quote has no tip; a sale is the only route where one exists.
448
- async sale(request) {
449
- if (!request || typeof request !== "object") fail("bad-input", { field: "request" });
450
- // THE NODE GATES THE THREE BROWSER BODY ROUTES ON THE CLIENT'S SDK LINE. The value is the package's own
451
- // baked-in version, not a caller field: a caller cannot claim a line it was not built from.
452
- // THE ENVELOPE IS THE REQUEST. The node accepts both `{ request: {...} }` and a bare body; every check below
453
- // must read the same object the node priced, not the outer envelope that carries only `sdkVersion`.
454
- const saleRequest = request.request && typeof request.request === "object" ? request.request : request;
455
- const payload = { ...(request.request && typeof request.request === "object" ? request : { request }), sdkVersion: SDK_VERSION };
456
- let res = null;
457
- try {
458
- res = await http.tryJson(config.route("orderSell"), {
459
- method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload),
460
- });
461
- } catch (error) {
462
- if (error && error.code === "bad-input") throw error;
463
- fail("server-unavailable", { step: "order-sell" });
464
- }
465
- if (!res || res.ok !== true || !res.body || res.body.ok !== true) fail("quote-refused", { step: "order-sell" });
466
- const ticket = res.body;
467
- const quote = (ticket.handoff && ticket.handoff.quote) || ticket.quote || null;
468
- if (!quote || typeof quote !== "object") fail("quote-field-unbound", { step: "order-sell", field: "quote" });
469
- requirePinnedCashier(quote, "order-sell", config);
470
- // THE SALE TICKET IS A SIGNED QUOTE, AND IT GETS THE SAME GATES AS `firm`: every field of the signed set,
471
- // its expiry, the EIP-712 signature and the named key, the registry's provider mapping, the interface's
472
- // allow-list, and the factory/implementation policy. The one difference is the binding below: a sale has no
473
- // caller-supplied order terms, so its context is checked against `ticket.order` when the node returns it.
474
- // A MISSING FIELD OF THE SIGNED SET IS NOT "PROBABLY ZERO": the digest cannot be built, so the quote is
475
- // not verifiable and is refused (its own code, so the interface can say which field is unbound).
476
- const missingFields = orderQuoteMissingFields(quote);
477
- if (missingFields.length) fail("quote-field-unbound", { step: "signature", missing: missingFields });
478
- // THE QUOTE'S OWN EXPIRY, checked against the clock the core already has. It is bound in the signature too,
479
- // but a stale quote is refused by its own code rather than looking like a signature failure.
480
- const validUntil = Number(quote.validUntil);
481
- // THE SCALE IS SECONDS: the same as the order's deadlines and block.timestamp. The core's clock is in
482
- // milliseconds (Date.now), so exactly ONE boundary is converted - "now", not the quote value itself: one
483
- // unit for the value, one conversion at the input.
484
- const nowSec = Math.floor(now() / 1000);
485
- // THE TTL IS MANDATORY AND MUST BE IN THE FUTURE. Zero, a fraction, an unsafe integer and a missing value are
486
- // not "never expires": the relay path already requires a safe future integer, and a direct quote must not be
487
- // weaker than the same quote after it crosses the relay.
488
- if (!Number.isSafeInteger(validUntil) || validUntil <= nowSec) {
489
- fail("quote-expired", { step: "signature", validUntil: quote.validUntil });
490
- }
491
- // RECOVER, THEN MATCH THE NAMED KEY. A signature that does not recover is one refusal; a valid signature
492
- // that recovers to a DIFFERENT address is another (the quote names a key that did not sign it).
493
- const recoveredKey = recoverOrderQuoteKey(quote);
494
- if (recoveredKey === null) fail("quote-signature-invalid", { step: "signature" });
495
- const declaredKey = String(quote.quoteKey).toLowerCase();
496
- if (recoveredKey !== declaredKey) fail("quote-key-mismatch", { step: "signature", got: recoveredKey, want: declaredKey });
497
- // WHO OWNS THE KEY - ASKED OF THE REGISTRY NAMED BY THE QUOTE. Both fields are part of the signed set, so
498
- // they cannot be swapped after signing; this is what turns "a key signed it" into "this provider's key
499
- // signed it". No chain-read seam - refuse rather than take the signature on trust.
500
- const registry = String(quote.registry || "").toLowerCase();
501
- if (!/^0x[0-9a-f]{40}$/.test(registry) || registry === ZERO_ADDRESS) {
502
- fail("quote-field-unbound", { step: "registry", field: "registry" });
503
- }
504
- const declaredProvider = String(quote.provider || "").toLowerCase();
505
- if (!/^0x[0-9a-f]{40}$/.test(declaredProvider) || declaredProvider === ZERO_ADDRESS) {
506
- fail("quote-field-unbound", { step: "registry", field: "provider" });
507
- }
508
- if (typeof evmCall !== "function") fail("quote-registry-unchecked", { step: "registry", why: "no-chain-read" });
509
- let mappedProvider = null;
510
- try {
511
- mappedProvider = addressFromWord(await evmCall({ to: registry, data: providerOfData(declaredKey) }));
512
- } catch {
513
- fail("quote-registry-unchecked", { step: "registry", why: "read-failed", registry });
514
- }
515
- if (mappedProvider === null || mappedProvider === ZERO_ADDRESS) {
516
- fail("quote-key-unknown", { step: "registry", registry, quoteKey: declaredKey });
517
- }
518
- if (mappedProvider !== declaredProvider) {
519
- fail("quote-provider-mismatch", { step: "registry", got: mappedProvider, want: declaredProvider });
520
- }
521
- // THE INTERFACE'S OWN ADMISSION LIST - POLICY, NOT PROOF. The chain says whose key it is; whether this
522
- // interface trades with that provider at all is the interface's decision, and it rides as a hook.
523
- if (typeof providerAllowed === "function" && providerAllowed(declaredProvider) !== true) {
524
- fail("quote-provider-not-allowed", { step: "policy", provider: declaredProvider });
525
- }
526
- // THE FACTORY: NAMED BY THE PROVIDER'S RECORD, CHECKED BY ITS CODE (#103). The factory will verify the
527
- // quote in EVM (it is the EIP-712 verifyingContract), so it must be the one the record names AND its
528
- // code must be a build this interface knows. The record lookup always runs; the code check runs when a
529
- // policy list was supplied (nothing to pin against otherwise).
530
- const declaredFactory = String(quote.factory || "").toLowerCase();
531
- if (!/^0x[0-9a-f]{40}$/.test(declaredFactory) || declaredFactory === ZERO_ADDRESS) {
532
- fail("quote-field-unbound", { step: "factory", field: "factory" });
533
- }
534
- let recordedFactory = null;
535
- try {
536
- recordedFactory = addressFromWord(await evmCall({ to: registry, data: factoryOfData(declaredProvider) }));
537
- } catch {
538
- fail("quote-factory-unchecked", { step: "factory", why: "read-failed", registry });
539
- }
540
- if (recordedFactory === null || recordedFactory === ZERO_ADDRESS) {
541
- fail("quote-factory-unknown", { step: "factory", registry, provider: declaredProvider });
542
- }
543
- if (recordedFactory !== declaredFactory) {
544
- fail("quote-factory-mismatch", { step: "factory", got: declaredFactory, want: recordedFactory });
545
- }
546
- if (factoryPolicy) {
547
- if (typeof evmCode !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-code-read" });
548
- let codeHex = null;
549
- try { codeHex = await evmCode(declaredFactory); } catch { fail("quote-factory-unchecked", { step: "factory", why: "code-read-failed", factory: declaredFactory }); }
550
- const codeBytes = hexToBytesQ(codeHex);
551
- // EXTCODEHASH SEMANTICS: keccak256 of the runtime code. An address with no code (empty/0x) hashes to
552
- // the keccak of empty, which is not on any build list - refused like any unknown build.
553
- const codeHash = bytesToHexQ(keccak256(codeBytes || new Uint8Array(0)));
554
- if (!factoryPolicy.includes(codeHash)) {
555
- fail("quote-factory-code-unknown", { step: "factory", factory: declaredFactory, codeHash });
556
- }
557
- }
558
- // THE IMPLEMENTATION THE CLONES WILL EXECUTE (#114). A pinned factory CODE is not enough on its own: the
559
- // implementation ADDRESS lives in the factory's STORAGE, so the client re-reads the pair the factory itself
560
- // checks (implementation() / implementationCodeHash()) and the CODE at that address, then applies the same
561
- // verdict (verifyFactoryImplementationOnChain). A delegatecall to an address WITHOUT code SUCCEEDS, so a
562
- // clone without an implementation would take the ETH and its markReady/claim/refund would appear to go
563
- // through while doing nothing - that is exactly the case this refuses. The live code is re-hashed here, so
564
- // the verdict does not trust the factory's own answer alone.
565
- if (implementationPolicy) {
566
- if (typeof evmCall !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-chain-read" });
567
- if (typeof evmCode !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-code-read" });
568
- const verdict = await engine.evm.verifyFactoryImplementationOnChain({
569
- factory: declaredFactory,
570
- read: evmCall,
571
- code: (address) => evmCode(address),
572
- policy: implementationPolicy,
573
- hashCode: (codeHex) => bytesToHexQ(keccak256(hexToBytesQ(codeHex) || new Uint8Array(0))),
574
- });
575
- if (!verdict.ok) {
576
- const unknown = verdict.why === "implementation-code-unknown" ||
577
- verdict.why === "implementation-code-mismatch" || verdict.why === "implementation-has-no-code";
578
- fail(unknown ? "quote-factory-code-unknown" : "quote-factory-unchecked",
579
- { step: "factory", why: verdict.why, factory: declaredFactory, implementation: verdict.implementation || null });
580
- }
581
- }
582
- // THE PERSON SELLING IS THE CLAIMER. The interface's denylist is applied to that address, not to a
583
- // caller-chosen value: a ticket that names a denied claimer must not reach the funding step.
584
- const saleClaimer = String((saleRequest && saleRequest.claimer) || quote.claimer || "").toLowerCase();
585
- if (saleClaimer && denylist && denylist.has(saleClaimer)) fail("address-denied", { step: "order-sell" });
586
- if (saleRequest && saleRequest.claimer && quote.claimer && String(saleRequest.claimer).toLowerCase() !== String(quote.claimer).toLowerCase()) {
587
- fail("quote-refused", { step: "order-sell", why: "claimer-not-bound" });
588
- }
589
- // THE XMR THE CALLER ASKED FOR IS THE XMR THE QUOTE SIGNED. A ticket is paid against the signed `xmrAmount`;
590
- // accepting a different requested amount shows one figure and settles another.
591
- const requestedXmr = saleRequest && (saleRequest.xmr !== undefined ? saleRequest.xmr
592
- : (saleRequest.xmrAmount !== undefined ? saleRequest.xmrAmount : null));
593
- if (requestedXmr !== null && requestedXmr !== undefined) {
594
- let wanted = null;
595
- try { wanted = BigInt(String(requestedXmr)); } catch { wanted = null; }
596
- // A whole-XMR request (the public `xmr` field) is converted with the package's own parser; digits are
597
- // already atomic. A value that cannot be read is a refusal, not a skipped check.
598
- if (wanted === null || wanted < 10n ** 12n) {
599
- try { wanted = parseXmr(String(requestedXmr)); } catch { wanted = null; }
600
- }
601
- let signedAtomic = null;
602
- try { signedAtomic = quote.xmrAmount === undefined || quote.xmrAmount === null || quote.xmrAmount === ""
603
- ? null : BigInt(String(quote.xmrAmount)); } catch { signedAtomic = null; }
604
- if (signedAtomic === null || wanted === null || wanted !== signedAtomic) {
605
- fail("quote-refused", { step: "order-sell", why: "xmr-amount" });
606
- }
607
- }
608
- // THE CONTEXT WHEN THE TICKET CARRIES ITS ORDER. The signed quote binds the order terms; when the node
609
- // returns the order it priced, recompute the context with our own engine and refuse a mismatch.
610
- if (ticket.order && typeof ticket.order === "object") {
611
- // THE RETURNED ORDER MUST BE THE SIGNED ONE FIELD BY FIELD. `quote.context` is a derived label, not a
612
- // signed field; comparing only it lets a node return another amount with a matching relabelled context.
613
- const sameValue = (a, b) => String(a === undefined || a === null ? "" : a).replace(/^0x/i, "").toLowerCase()
614
- === String(b === undefined || b === null ? "" : b).replace(/^0x/i, "").toLowerCase();
615
- for (const name of ["locker", "claimer", "amount", "readyBy", "t1", "salt"]) {
616
- if (!sameValue(ticket.order[name], quote[name])) {
617
- fail("quote-refused", { step: "order-sell", why: "other-terms", field: name });
618
- }
619
- }
620
- // The context remains a useful cross-check when both sides carry it.
621
- if (quote.context) {
622
- let expectedSaleContext = null;
623
- try { expectedSaleContext = engine.orderContext.orderContextString(ticket.order); } catch { expectedSaleContext = null; }
624
- if (expectedSaleContext !== null && String(quote.context) !== expectedSaleContext) {
625
- fail("quote-refused", { step: "order-sell", why: "other-terms", field: "context" });
626
- }
627
- }
628
- }
629
- // THE TICKET'S TIP MUST BE THE SIGNED ONE. The node returns both the ticket's `claimTip` object and the quote it
630
- // signed; a difference means the figure shown to the person is not the figure the escrow will pay.
631
- const shown = ticket.claimTip && ticket.claimTip.wei !== undefined && ticket.claimTip.wei !== null
632
- ? String(ticket.claimTip.wei) : null;
633
- if (shown === null) fail("quote-field-unbound", { step: "claimTip", field: "claimTip" });
634
- if (ticket.claimTip.signed !== true) fail("quote-field-unbound", { step: "claimTip", field: "signed" });
635
- let signedTip = null;
636
- try { signedTip = quote.claimTip === undefined || quote.claimTip === null || quote.claimTip === "" ? "0" : BigInt(quote.claimTip).toString(); }
637
- catch { fail("quote-field-unbound", { step: "claimTip", field: "claimTip" }); }
638
- let shownBig = null;
639
- try { shownBig = BigInt(shown); } catch { fail("quote-tip-unreadable", { step: "claimTip" }); }
640
- if (signedTip === null || shownBig < 0n || BigInt(signedTip) !== shownBig) {
641
- fail("quote-refused", { step: "claimTip", why: "not-the-signed-tip" });
642
- }
643
- if (shownBig > 0n) {
644
- if (typeof evmBlock !== "function") fail("quote-tip-unchecked", { step: "claimTip", why: "no-block-read" });
645
- let block = null;
646
- try { block = await evmBlock("latest"); } catch { fail("quote-tip-unchecked", { step: "claimTip", why: "block-read-failed" }); }
647
- const baseFeeWei = block && (block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei);
648
- // THE NODE SIZES THE TIP FROM THE GAS PRICE, PRIORITY INCLUDED. The SDK used to pass only the base fee, so an
649
- // honest L1 tip (or a base fee that dropped between sizing and checking) was refused.
650
- const priorityFeeWei = priorityFeeOfBlock(block);
651
- const verdict = claimTipVerdict({ claimTipWei: shownBig, baseFeeWei, priorityFeeWei });
652
- if (!verdict.ok) fail(verdict.code, { step: "claimTip", ...verdict });
653
- }
654
- return ticket;
655
- },
656
- async firm(request) {
657
- if (!request || typeof request !== "object") fail("bad-input", { field: "request" });
658
- if (typeof request.providerId !== "string" || !request.providerId) fail("bad-input", { field: "providerId" });
659
- if (!request.order || typeof request.order !== "object") fail("bad-input", { field: "order" });
660
- // THE INTERFACE'S OWN ADDRESS DENYLIST (issue #16): POLICY, not proof - the interface refuses to ask for a
661
- // quote for an address on its own list, and does it BEFORE any request is made. `order.locker` is the
662
- // address the funds come from on a purchase (the claimer there is the node's own address, so it is
663
- // deliberately not checked). An empty/absent list is "no policy"; the comparison is WITHOUT CASE.
664
- if (denylist && typeof request.order.locker === "string" && denylist.has(request.order.locker.toLowerCase())) {
665
- fail("address-denied", { step: "order-quote" });
666
- }
667
- let res = null;
668
- const viewHalfClaimer = request.viewHalfClaimer === undefined || request.viewHalfClaimer === null || request.viewHalfClaimer === ""
669
- ? null : String(request.viewHalfClaimer);
670
- try {
671
- // THE ANSWER IS READ AS A VALUE (tryJson), NOT AS AN EXCEPTION: "did not answer" and "answered and
672
- // refused" must stay different, and a refusal's own body carries the reason. `json` throws
673
- // server-unavailable and LOSES that body.
674
- res = await http.tryJson(config.route("orderQuote"), {
675
- method: "POST",
676
- headers: { "content-type": "application/json" },
677
- body: JSON.stringify({ providerId: request.providerId, order: request.order,
678
- ...(viewHalfClaimer === null ? {} : { viewHalfClaimer }), sdkVersion: SDK_VERSION }),
679
- });
680
- } catch (error) {
681
- if (error && error.code === "bad-input") throw error;
682
- fail("server-unavailable", { step: "order-quote" });
683
- }
684
- // A NODE'S DENYLIST REFUSAL REACHES THE APP UNDER ITS OWN NEUTRAL SDK CODE, WITHOUT the `why` text and
685
- // WITHOUT the address: the node names both (the maker's denylist and the address), and the interface shows
686
- // the person its own neutral message. Every other refusal keeps its existing code (quote-refused etc.).
687
- const refusedCode = res && res.body && typeof res.body.code === "string" ? res.body.code : null;
688
- if (refusedCode === "denied-address") fail("address-denied", { step: "order-quote" });
689
- if (!res || res.ok !== true || !res.body || res.body.ok !== true || !res.body.quote) {
690
- fail("quote-refused", { step: "order-quote" });
691
- }
692
- const body = res.body;
693
- const quote = body.quote;
694
- requirePinnedCashier(quote, "order-quote", config);
695
- // THE MAKER'S VIEW HALF IS OURS, NOT THE NODE'S CHOICE. When the caller supplies it, the quote must carry the
696
- // same scalar back; otherwise the maker used another half and the joint view key cannot be rebuilt from the key.
697
- if (viewHalfClaimer !== null) {
698
- const echoed = quote.viewHalfClaimer;
699
- if (echoed === undefined || echoed === null || echoed === "") {
700
- fail("quote-field-unbound", { step: "viewHalfClaimer", field: "viewHalfClaimer" });
701
- }
702
- if (String(echoed).toLowerCase() !== viewHalfClaimer.toLowerCase()) {
703
- fail("quote-refused", { step: "viewHalfClaimer", why: "not-echoed" });
704
- }
705
- }
706
- // A MISSING FIELD OF THE SIGNED SET IS NOT "PROBABLY ZERO": the digest cannot be built, so the quote is
707
- // not verifiable and is refused (its own code, so the interface can say which field is unbound).
708
- const missingFields = orderQuoteMissingFields(quote);
709
- if (missingFields.length) fail("quote-field-unbound", { step: "signature", missing: missingFields });
710
- // THE QUOTE'S OWN EXPIRY, checked against the clock the core already has. It is bound in the signature too,
711
- // but a stale quote is refused by its own code rather than looking like a signature failure.
712
- const validUntil = Number(quote.validUntil);
713
- // THE SCALE IS SECONDS: the same as the order's deadlines and block.timestamp. The core's clock is in
714
- // milliseconds (Date.now), so exactly ONE boundary is converted - "now", not the quote value itself: one
715
- // unit for the value, one conversion at the input.
716
- const nowSec = Math.floor(now() / 1000);
717
- // THE TTL IS MANDATORY AND MUST BE IN THE FUTURE. Zero, a fraction, an unsafe integer and a missing value are
718
- // not "never expires": the relay path already requires a safe future integer, and a direct quote must not be
719
- // weaker than the same quote after it crosses the relay.
720
- if (!Number.isSafeInteger(validUntil) || validUntil <= nowSec) {
721
- fail("quote-expired", { step: "signature", validUntil: quote.validUntil });
722
- }
723
- // RECOVER, THEN MATCH THE NAMED KEY. A signature that does not recover is one refusal; a valid signature
724
- // that recovers to a DIFFERENT address is another (the quote names a key that did not sign it).
725
- const recoveredKey = recoverOrderQuoteKey(quote);
726
- if (recoveredKey === null) fail("quote-signature-invalid", { step: "signature" });
727
- const declaredKey = String(quote.quoteKey).toLowerCase();
728
- if (recoveredKey !== declaredKey) fail("quote-key-mismatch", { step: "signature", got: recoveredKey, want: declaredKey });
729
- // WHO OWNS THE KEY - ASKED OF THE REGISTRY NAMED BY THE QUOTE. Both fields are part of the signed set, so
730
- // they cannot be swapped after signing; this is what turns "a key signed it" into "this provider's key
731
- // signed it". No chain-read seam - refuse rather than take the signature on trust.
732
- const registry = String(quote.registry || "").toLowerCase();
733
- if (!/^0x[0-9a-f]{40}$/.test(registry) || registry === ZERO_ADDRESS) {
734
- fail("quote-field-unbound", { step: "registry", field: "registry" });
735
- }
736
- const declaredProvider = String(quote.provider || "").toLowerCase();
737
- if (!/^0x[0-9a-f]{40}$/.test(declaredProvider) || declaredProvider === ZERO_ADDRESS) {
738
- fail("quote-field-unbound", { step: "registry", field: "provider" });
739
- }
740
- if (typeof evmCall !== "function") fail("quote-registry-unchecked", { step: "registry", why: "no-chain-read" });
741
- let mappedProvider = null;
742
- try {
743
- mappedProvider = addressFromWord(await evmCall({ to: registry, data: providerOfData(declaredKey) }));
744
- } catch {
745
- fail("quote-registry-unchecked", { step: "registry", why: "read-failed", registry });
746
- }
747
- if (mappedProvider === null || mappedProvider === ZERO_ADDRESS) {
748
- fail("quote-key-unknown", { step: "registry", registry, quoteKey: declaredKey });
749
- }
750
- if (mappedProvider !== declaredProvider) {
751
- fail("quote-provider-mismatch", { step: "registry", got: mappedProvider, want: declaredProvider });
752
- }
753
- // THE INTERFACE'S OWN ADMISSION LIST - POLICY, NOT PROOF. The chain says whose key it is; whether this
754
- // interface trades with that provider at all is the interface's decision, and it rides as a hook.
755
- if (typeof providerAllowed === "function" && providerAllowed(declaredProvider) !== true) {
756
- fail("quote-provider-not-allowed", { step: "policy", provider: declaredProvider });
757
- }
758
- // THE FACTORY: NAMED BY THE PROVIDER'S RECORD, CHECKED BY ITS CODE (#103). The factory will verify the
759
- // quote in EVM (it is the EIP-712 verifyingContract), so it must be the one the record names AND its
760
- // code must be a build this interface knows. The record lookup always runs; the code check runs when a
761
- // policy list was supplied (nothing to pin against otherwise).
762
- const declaredFactory = String(quote.factory || "").toLowerCase();
763
- if (!/^0x[0-9a-f]{40}$/.test(declaredFactory) || declaredFactory === ZERO_ADDRESS) {
764
- fail("quote-field-unbound", { step: "factory", field: "factory" });
765
- }
766
- let recordedFactory = null;
767
- try {
768
- recordedFactory = addressFromWord(await evmCall({ to: registry, data: factoryOfData(declaredProvider) }));
769
- } catch {
770
- fail("quote-factory-unchecked", { step: "factory", why: "read-failed", registry });
771
- }
772
- if (recordedFactory === null || recordedFactory === ZERO_ADDRESS) {
773
- fail("quote-factory-unknown", { step: "factory", registry, provider: declaredProvider });
774
- }
775
- if (recordedFactory !== declaredFactory) {
776
- fail("quote-factory-mismatch", { step: "factory", got: declaredFactory, want: recordedFactory });
777
- }
778
- if (factoryPolicy) {
779
- if (typeof evmCode !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-code-read" });
780
- let codeHex = null;
781
- try { codeHex = await evmCode(declaredFactory); } catch { fail("quote-factory-unchecked", { step: "factory", why: "code-read-failed", factory: declaredFactory }); }
782
- const codeBytes = hexToBytesQ(codeHex);
783
- // EXTCODEHASH SEMANTICS: keccak256 of the runtime code. An address with no code (empty/0x) hashes to
784
- // the keccak of empty, which is not on any build list - refused like any unknown build.
785
- const codeHash = bytesToHexQ(keccak256(codeBytes || new Uint8Array(0)));
786
- if (!factoryPolicy.includes(codeHash)) {
787
- fail("quote-factory-code-unknown", { step: "factory", factory: declaredFactory, codeHash });
788
- }
789
- }
790
- // THE IMPLEMENTATION THE CLONES WILL EXECUTE (#114). A pinned factory CODE is not enough on its own: the
791
- // implementation ADDRESS lives in the factory's STORAGE, so the client re-reads the pair the factory itself
792
- // checks (implementation() / implementationCodeHash()) and the CODE at that address, then applies the same
793
- // verdict (verifyFactoryImplementationOnChain). A delegatecall to an address WITHOUT code SUCCEEDS, so a
794
- // clone without an implementation would take the ETH and its markReady/claim/refund would appear to go
795
- // through while doing nothing - that is exactly the case this refuses. The live code is re-hashed here, so
796
- // the verdict does not trust the factory's own answer alone.
797
- if (implementationPolicy) {
798
- if (typeof evmCall !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-chain-read" });
799
- if (typeof evmCode !== "function") fail("quote-factory-unchecked", { step: "factory", why: "no-code-read" });
800
- const verdict = await engine.evm.verifyFactoryImplementationOnChain({
801
- factory: declaredFactory,
802
- read: evmCall,
803
- code: (address) => evmCode(address),
804
- policy: implementationPolicy,
805
- hashCode: (codeHex) => bytesToHexQ(keccak256(hexToBytesQ(codeHex) || new Uint8Array(0))),
806
- });
807
- if (!verdict.ok) {
808
- const unknown = verdict.why === "implementation-code-unknown" ||
809
- verdict.why === "implementation-code-mismatch" || verdict.why === "implementation-has-no-code";
810
- fail(unknown ? "quote-factory-code-unknown" : "quote-factory-unchecked",
811
- { step: "factory", why: verdict.why, factory: declaredFactory, implementation: verdict.implementation || null });
812
- }
813
- }
814
- // BINDING THE QUOTE TO OUR TERMS. The signature confirms the provider signed THIS quote, but not that it is
815
- // about our swap: we are responsible for the binding. The context string is computed by OUR engine module
816
- // (format ninsei-order-v3; the field order is part of the protocol and must not be rearranged). There is
817
- // deliberately no copy of the format here: a copy would silently drift from the protocol.
818
- //
819
- // THE ORDER OF THE GATES: signature first, then binding. So a refusal names the nearest reason, not the first
820
- // one at hand.
821
- // THE PROVIDER MAY NAME THE CLAIMER HIMSELF, AND THAT IS ALSO AN ASSEMBLED CONTEXT (a defect found). The
822
- // provider may be the claimer: then it substitutes ITS OWN address into the order terms and signs the context
823
- // with it already in place. Requiring the context from the caller in that case is impossible - they do not
824
- // know the provider's address, and then the quote cannot be obtained at all (the live contour answered this
825
- // with bad-input {field:"order"} BEFORE any network). So if the sent terms had no claimer, the context is
826
- // computed from the terms WITH HIS value from the quote - exactly as the engine does it
827
- // (sdk/src/swap-flow.mjs: `{ ...orderBase, claimer: claimerResolved }`). No OPTIONAL checks appeared here:
828
- // a mismatched string is still a refusal (quote-refused { step: "context" }).
829
- let expectedContext = null;
830
- try { expectedContext = engine.orderContext.orderContextString(request.order); }
831
- catch { expectedContext = null; }
832
- if (expectedContext === null) {
833
- const providerClaimer = quote && quote.claimer;
834
- if (providerClaimer) {
835
- try { expectedContext = engine.orderContext.orderContextString({ ...request.order, claimer: providerClaimer }); }
836
- catch { fail("bad-input", { field: "order" }); }
837
- } else {
838
- fail("bad-input", { field: "order" });
839
- }
840
- }
841
- const quoted = quote.context || "";
842
- if (String(quoted) !== expectedContext) {
843
- fail("quote-refused", { step: "context", why: quoted ? "other-terms" : "not-reported" });
844
- }
845
- // THE CLAIM TIP: the seller pays it out of the payout, so a quote that asks for more than the claim can
846
- // cost is refused before it is signed. The chain's base fee is read through the caller's block seam; a
847
- // missing seam or an unreadable base fee is a named refusal, never a silently accepted tip.
848
- const tipCheck = (() => {
849
- try { return claimTipVerdict({ claimTipWei: quote.claimTip }); }
850
- catch { return { ok: true, tipWei: "0" }; }
851
- })();
852
- if (!tipCheck.ok && tipCheck.code === "quote-tip-unreadable") {
853
- fail("quote-field-unbound", { step: "claimTip", field: "claimTip" });
854
- }
855
- if (tipCheck.tipWei !== "0") {
856
- if (typeof evmBlock !== "function") fail("quote-tip-unchecked", { step: "claimTip", why: "no-block-read" });
857
- let block = null;
858
- try { block = await evmBlock("latest"); } catch { fail("quote-tip-unchecked", { step: "claimTip", why: "block-read-failed" }); }
859
- const baseFeeWei = block && (block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei);
860
- const priorityFeeWei = priorityFeeOfBlock(block);
861
- const verdict = claimTipVerdict({ claimTipWei: quote.claimTip, baseFeeWei, priorityFeeWei });
862
- if (!verdict.ok) fail(verdict.code, { step: "claimTip", ...verdict });
863
- }
864
- return quote;
865
- },
866
-
867
125
  /**
868
126
  * A firm quote through the relay, starting from the one recovery key.
869
127
  *
@@ -934,6 +192,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
934
192
  if (!market) fail("bad-input", { field: "market" });
935
193
  const window = windows.find((entry) => entry.market === market) || null;
936
194
  if (!window) fail("quote-refused", { step: "features", why: "window" });
195
+ const readyWindow = readReadyWindow(window, { side, field: "features.firmWindows" });
937
196
  const xmrNetwork = request.xmrNetwork !== undefined ? String(request.xmrNetwork) : window.xmrNetwork;
938
197
  if (!xmrNetwork) fail("bad-input", { field: "xmrNetwork" });
939
198
  if (request.xmrAmount === undefined || request.xmrAmount === null || request.xmrAmount === "") {
@@ -987,6 +246,15 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
987
246
  side,
988
247
  });
989
248
  const quote = result.quote;
249
+ // A QUOTE THAT IS ALREADY AT THE START MARGIN CANNOT BECOME A SWAP. The proof and the record work take
250
+ // seconds; refusing at the lock would show the person a confirmation that was never going to reach the wallet.
251
+ // The check is here, on arrival, with its own code so the caller asks again without showing confirm.
252
+ const answerNowSec = Math.floor(Number(now()) / 1000);
253
+ const life = quoteLifeVerdict({ validUntil: quote.validUntil, nowSec: answerNowSec });
254
+ if (!life.ok) {
255
+ fail("quote-too-short", { step: "answer", validUntil: Number.isFinite(Number(quote.validUntil)) ? Number(quote.validUntil) : null,
256
+ now: answerNowSec, remainingSec: life.remainingSec, marginSec: life.marginSec });
257
+ }
990
258
  requirePinnedCashier(quote, "relay", config);
991
259
  // THE NODE HALF IS NOT A DECORATION. The answer's proof must stand in THIS order's context and the proven
992
260
  // point must be the one the quote commits to. For ask that is the claimer's commitment; for bid the node
@@ -1113,7 +381,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
1113
381
  const marketAsset = request.market && String(request.market).includes(":")
1114
382
  ? String(request.market).split(":").slice(1).join(":") : null;
1115
383
  const asset = String(order.asset || marketAsset || "").trim();
1116
- const startQuote = { ...quote, viewHalfClaimer: derived.makerViewHalf, xmrAmount: signedAtomic,
384
+ const startQuote = { ...quote, viewHalfClaimer: derived.makerViewHalf, xmrAmount: signedAtomic, readyWindow,
1117
385
  ...(asset ? { asset, token: asset.toLowerCase() } : {}),
1118
386
  // A STABLE ID FOR THE PENDING-FUNDING RECORD. The signed nonce is the one value every relay answer carries.
1119
387
  ...(quote.nonce !== undefined && quote.nonce !== null ? { id: String(quote.nonce) } : {}) };
@@ -1130,6 +398,8 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
1130
398
  ...result,
1131
399
  quote: startQuote,
1132
400
  order: startOrder,
401
+ // THE NODE'S WINDOW TRAVELS WITH THE ANSWER, SO A SALE CAN USE THE SAME NUMBERS THE MAKER SIGNED.
402
+ readyWindow,
1133
403
  // THE CALLER ADDS ITS WALLET, `receiveTo` AND THE HEIGHT; everything the relay can know is here.
1134
404
  startRequest: {
1135
405
  quote: startQuote,