@ninsei-labs/sdk 0.58.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -487,6 +487,14 @@ export declare function probeMoneroNode(options: {
487
487
  /** The watch key form that matches the address's view public key, or null when none does. */
488
488
  export declare function viewKeyFormForAddress(viewSecret: string, expectedViewPubHex: string): string | null;
489
489
 
490
+ /** Whether the view and spend keys belong to the primary address they are scanned for, and the one scalar form to use. */
491
+ export declare function watchedAddressVerdict(watched: {
492
+ address: string;
493
+ viewSecret: string | bigint;
494
+ spendPub: string;
495
+ }): { readonly ok: true; readonly viewSecret: bigint; readonly spendPub: string; readonly form: string }
496
+ | { readonly ok: false; readonly code: string; readonly field?: string; readonly why?: string };
497
+
490
498
  /** A boundary height derived from a later unlock_time, or null when the time names no height. */
491
499
  export declare function laterBoundary(...args: unknown[]): unknown;
492
500
 
@@ -21,7 +21,7 @@ export {
21
21
  } from "../../engine/monero/address.js";
22
22
 
23
23
  // THE BLOCK WALK A WATCHER RUNS: the same scanner the page uses, without a wallet.
24
- export { laterBoundary, scanRange, viewKeyFormForAddress } from "../../engine/monero/scan.js";
24
+ export { laterBoundary, scanRange, viewKeyFormForAddress, watchedAddressVerdict } from "../../engine/monero/scan.js";
25
25
 
26
26
  export { createHalves } from "../../engine/atomic/halves.js";
27
27
  export { createDleq2 } from "../../engine/atomic/dleq2.js";
@@ -1,25 +1,58 @@
1
- // THE ONE PLACE THE QUOTE LIFETIME AND ITS START MARGIN ARE NAMED.
1
+ // THE ONE PLACE THE QUOTE LIFETIME, ITS START MARGIN AND THE CLIENT'S PREPARATION TIME ARE NAMED.
2
2
  //
3
- // A firm quote is signed with `validUntil`, and the SDK refuses to start a swap when less than the start margin is left.
4
- // A node that signs a shorter life than that margin is refusing its own quotes before the wallet is opened. The node
5
- // imports this default and may override it with its own setting; the SDK keeps the value here so the two cannot drift.
3
+ // A firm quote is signed with `validUntil`. On a buy (`ask`) the SDK refuses to show a quote unless enough life is
4
+ // left to finish the proof, the record and the lock; on a sell (`bid`) the node has already funded the escrow before
5
+ // it answers, so the client opens no wallet and the lock margin protects nothing there.
6
+ //
7
+ // A node that signs a shorter life than the start rule is refusing its own quotes before the wallet is opened. The
8
+ // node imports these values and may override the lifetime with its own setting; the SDK keeps the values here so the
9
+ // two cannot drift.
6
10
  export const LOCK_START_MARGIN_SEC = 30;
7
11
 
12
+ // THE TIME THE CLIENT NEEDS BEFORE THE LOCK. The proof, the record and the chain reads each cost seconds on a
13
+ // desktop and several times longer on a phone without a JIT. The start margin alone covers only the next block; this
14
+ // allowance covers the SDK's own preparation, so a quote shown to a person still has time to be clicked.
15
+ export const START_PREP_SEC = 15;
16
+
8
17
  /** The default firm quote lifetime, in seconds. A node may override it, but the default is this value. */
9
18
  export const DEFAULT_ORDER_QUOTE_TTL_SEC = 60;
10
19
 
11
20
  /**
12
- * THE QUOTE MUST STILL HAVE ITS START MARGIN WHEN IT ARRIVES. The lock check runs seconds later, after the proof and
13
- * the record work; a quote that is already at the margin is refused here, before the caller shows a confirmation.
14
- * Returns `ok:false` for an unreadable clock too: an unknown lifetime is not a reason to show a quote.
21
+ * THE QUOTE MUST HAVE ENOUGH LIFE LEFT WHEN IT ARRIVES.
22
+ *
23
+ * A buy is checked against the start margin plus the preparation allowance: the proof and the record work take
24
+ * seconds, and refusing at the lock would show the person a confirmation that was never going to reach the wallet.
25
+ * A sell is checked only against its own expiry: the node has already funded the escrow, so there is no local lock
26
+ * to prepare and a short remaining life must not abandon that escrow.
27
+ *
28
+ * Returns `ok:false` for an unreadable clock too: an unknown lifetime is not a reason to show a quote. `confirmBySec`
29
+ * is the last second at which a buy can still be started; the host may disable its button after it.
15
30
  */
16
- export function quoteLifeVerdict({ validUntil, nowSec, marginSec = LOCK_START_MARGIN_SEC } = {}) {
31
+ export function quoteLifeVerdict({ validUntil, nowSec, side = "ask", marginSec = LOCK_START_MARGIN_SEC, prepSec = START_PREP_SEC } = {}) {
17
32
  const until = Number(validUntil);
18
33
  const now = Number(nowSec);
19
34
  const margin = Number(marginSec);
20
- if (!Number.isSafeInteger(until) || !Number.isSafeInteger(now) || !Number.isSafeInteger(margin) || margin < 0) {
21
- return { ok: false, code: "quote-too-short", remainingSec: null, marginSec: Number.isSafeInteger(margin) ? margin : null };
35
+ const prepare = Number(prepSec);
36
+ if (!Number.isSafeInteger(until) || !Number.isSafeInteger(now)) {
37
+ return { ok: false, code: "quote-too-short", remainingSec: null, marginSec: null, prepSec: null, confirmBySec: null };
22
38
  }
23
39
  const remainingSec = until - now;
24
- return { ok: remainingSec > margin, code: remainingSec > margin ? null : "quote-too-short", remainingSec, marginSec: margin };
40
+ const bid = side === "bid";
41
+ if (bid) {
42
+ const ok = remainingSec > 0;
43
+ return { ok, code: ok ? null : "quote-too-short", remainingSec, marginSec: 0, prepSec: 0, confirmBySec: until };
44
+ }
45
+ if (!Number.isSafeInteger(margin) || !Number.isSafeInteger(prepare) || margin < 0 || prepare < 0) {
46
+ return { ok: false, code: "quote-too-short", remainingSec, marginSec: null, prepSec: null, confirmBySec: null };
47
+ }
48
+ const requiredSec = margin + prepare;
49
+ const ok = remainingSec > requiredSec;
50
+ return {
51
+ ok,
52
+ code: ok ? null : "quote-too-short",
53
+ remainingSec,
54
+ marginSec: margin,
55
+ prepSec: prepare,
56
+ confirmBySec: until - requiredSec,
57
+ };
25
58
  }
package/src/quotes.mjs CHANGED
@@ -10,6 +10,7 @@ import { claimGasGiftWei } from "../engine/evm/claimGas.js";
10
10
  import { takerHalvesV2, recoverySaltOf } from "./recovery-key.mjs";
11
11
  import { acceptCounterpartyChunked, buildOwnSideFromHalvesChunked, jointAddress } from "./order.mjs";
12
12
  import { requestFirmQuote } from "./relayFirmClient.mjs";
13
+ import { predictEscrow } from "./predictEscrow.mjs";
13
14
  import { readReadyWindow } from "./readyWindow.mjs";
14
15
  import { quoteLifeVerdict } from "./quotePolicy.mjs";
15
16
  // THE CHAIN READ NEEDED TO ASK THE REGISTRY WHO OWNS THE KEY. The selector is COMPUTED from the signature, not
@@ -108,7 +109,7 @@ export function claimTipVerdict({ claimTipWei = 0, baseFeeWei = null, priorityFe
108
109
  }
109
110
 
110
111
  export function createQuotes({ config, now = () => Date.now(), evmCall = null, evmCode = null, evmBlock = null,
111
- providerAllowed = null, knownFactoryCodes = null, knownImplementationCodes = null, denylist = null }) {
112
+ providerAllowed = null, knownFactoryCodes = null, knownImplementationCodes = null, denylist = null, fetchImpl = null }) {
112
113
  // THE INTERFACE'S FACTORY POLICY (#103): the code hashes of factories it is willing to trade through
113
114
  // (extcodehash semantics = keccak256 of the runtime code). An EMPTY list is "no policy" (like
114
115
  // allowedProviders); a NON-EMPTY one refuses any factory whose code is not on it. Lower-cased once.
@@ -225,7 +226,7 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
225
226
  const result = await requestFirmQuote({
226
227
  relayUrl: request.relayUrl,
227
228
  partner: request.partner,
228
- fetchImpl: request.fetchImpl,
229
+ fetchImpl: request.fetchImpl || fetchImpl,
229
230
  timeoutMs: request.timeoutMs,
230
231
  features,
231
232
  terms: {
@@ -246,15 +247,6 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
246
247
  side,
247
248
  });
248
249
  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
- }
258
250
  requirePinnedCashier(quote, "relay", config);
259
251
  // THE NODE HALF IS NOT A DECORATION. The answer's proof must stand in THIS order's context and the proven
260
252
  // point must be the one the quote commits to. For ask that is the claimer's commitment; for bid the node
@@ -299,11 +291,7 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
299
291
  : { commitHalfLocker: nodeHalf.commitHalf, edPointLocker: nodeHalf.edPoint, edViewPointLocker: result.edViewPointLocker };
300
292
  let escrow = null;
301
293
  try {
302
- const predicted = await evmCall({
303
- to: quote.factory,
304
- data: engine.evm.encodePredict({ ...result.orderQuote, ...lockerHalf, signature: result.orderQuote.signature }),
305
- });
306
- escrow = engine.evm.decodeAddress(predicted);
294
+ escrow = await predictEscrow({ quote: result.orderQuote, lockerHalf, call: evmCall });
307
295
  } catch {
308
296
  fail("quote-escrow-unchecked", { step: "factory", why: "predict-failed", factory: quote.factory });
309
297
  }
@@ -381,7 +369,20 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
381
369
  const marketAsset = request.market && String(request.market).includes(":")
382
370
  ? String(request.market).split(":").slice(1).join(":") : null;
383
371
  const asset = String(order.asset || marketAsset || "").trim();
372
+ // THE LIFE CHECK RUNS AFTER ALL THE WORK THE ANSWER NEEDS. The proof, the predict and the registry reads
373
+ // happen first; a quote that had 31 s on arrival has less by now, and showing a confirmation would waste the
374
+ // person's time only to refuse at the lock. A sell (bid) is checked by its own expiry alone: its escrow is
375
+ // already funded, so there is no local lock to prepare and no margin to reserve.
376
+ const answerNowSec = Math.floor(Number(now()) / 1000);
377
+ const life = quoteLifeVerdict({ validUntil: quote.validUntil, nowSec: answerNowSec, side });
378
+ if (!life.ok) {
379
+ fail("quote-too-short", { step: "answer", side,
380
+ validUntil: Number.isFinite(Number(quote.validUntil)) ? Number(quote.validUntil) : null,
381
+ now: answerNowSec, remainingSec: life.remainingSec, marginSec: life.marginSec,
382
+ prepSec: life.prepSec, confirmBySec: life.confirmBySec });
383
+ }
384
384
  const startQuote = { ...quote, viewHalfClaimer: derived.makerViewHalf, xmrAmount: signedAtomic, readyWindow,
385
+ escrow, remainingSec: life.remainingSec, confirmBySec: life.confirmBySec,
385
386
  ...(asset ? { asset, token: asset.toLowerCase() } : {}),
386
387
  // A STABLE ID FOR THE PENDING-FUNDING RECORD. The signed nonce is the one value every relay answer carries.
387
388
  ...(quote.nonce !== undefined && quote.nonce !== null ? { id: String(quote.nonce) } : {}) };
@@ -408,7 +409,10 @@ export function createQuotes({ config, now = () => Date.now(), evmCall = null, e
408
409
  counterparty: startCounterparty,
409
410
  recoveryKey: request.recoveryKey,
410
411
  recoverySalt: order.salt,
412
+ escrow,
411
413
  },
414
+ remainingSec: life.remainingSec,
415
+ confirmBySec: life.confirmBySec,
412
416
  // THE SHAPE `swaps.start` TAKES: the proof and the claimer commitment travel with the view half, so a
413
417
  // caller can pass this object as `counterparty` without rebuilding the relay fields.
414
418
  counterparty: startCounterparty,
package/src/record.mjs CHANGED
@@ -64,6 +64,10 @@ export function createRecord(input, { order = null, side: knownSide = null, stor
64
64
  if (atomic <= 0n) throw new SdkError("bad-input", { field: "expectedAtomic" });
65
65
  escrow.expectedAtomic = atomic.toString();
66
66
  }
67
+ // THE ORDER IDENTITY SURVIVES A RELOAD. Pending funding is resumed only for the same chain, factory and predicted
68
+ // escrow; the salt alone does not prove that a record belongs to this start.
69
+ if (input.chainId !== undefined && input.chainId !== null) escrow.chainId = String(input.chainId);
70
+ if (input.factory !== undefined && input.factory !== null) escrow.factory = String(input.factory);
67
71
  // THE SIDE'S ENCRYPTION KEY - only the public one: the private one stays with the side and never enters the record.
68
72
  if (side.enc && side.enc.pub) escrow.encPub = norm(side.enc.pub);
69
73
  const record = { ...swap, escrow };
@@ -139,12 +139,30 @@ export async function requestFirmQuote({
139
139
  || wireText(published.relayId, "relay.relayId") !== wireText(response.body.relay, "relay")) {
140
140
  throw new SdkError("quote-refused", { step: "relay-info", why: "relay" });
141
141
  }
142
+ // THE OPERATOR'S OWN CLAIM SENDER. `GET /v1/relay` publishes the address the relay submits claims from; it is the
143
+ // first entry in the seller's ordered list. A malformed value is refused here rather than handed to a claim path.
144
+ let claimSender = null;
145
+ const publishedSender = published.claimSender;
146
+ if (publishedSender !== undefined && publishedSender !== null) {
147
+ // A NON-STRING IS NOT AN ADDRESS. Check the type before any coercion: `String({toString: null})` throws before
148
+ // the refusal can be named, and the caller would see a raw TypeError instead of quote-refused/claim-sender.
149
+ if (typeof publishedSender !== "string") {
150
+ throw new SdkError("quote-refused", { step: "relay-info", why: "claim-sender" });
151
+ }
152
+ if (publishedSender.trim() !== "") {
153
+ claimSender = publishedSender.trim().toLowerCase();
154
+ if (!/^0x[0-9a-f]{40}$/.test(claimSender)) {
155
+ throw new SdkError("quote-refused", { step: "relay-info", why: "claim-sender" });
156
+ }
157
+ }
158
+ }
142
159
  return {
143
160
  ...verified,
144
161
  // THE ORIGIN THAT ANSWERED, KEPT FOR THE LATER CLAIM. The seller has no wallet, so the claim goes back to the
145
162
  // same relay through `swaps.claimViaRelay`; the record stores this value and a different origin is refused.
146
163
  relayUrl: base,
147
164
  relay: response.body.relay ?? null,
165
+ claimSender,
148
166
  offered: response.body.offered ?? null,
149
167
  forwarded: response.body.forwarded ?? null,
150
168
  answer,