@ninsei-labs/sdk 0.57.2 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +82 -32
  3. package/THIRD_PARTY_NOTICES.md +7 -4
  4. package/assets/vendors/MANIFEST.json +1 -9
  5. package/assets/vendors/sdk/sdk-browser.js +4 -6
  6. package/engine/core/config.js +5 -24
  7. package/engine/core/deployments.generated.js +33 -0
  8. package/engine/core/rfqSource.js +6 -133
  9. package/engine/core/swap.js +1 -1
  10. package/engine/evm/index.js +3 -2
  11. package/engine/evm/session.js +46 -277
  12. package/engine/monero/address.js +15 -33
  13. package/engine/monero/keys.js +124 -0
  14. package/engine/monero/mnemonic.js +104 -0
  15. package/engine/monero/scan.js +79 -17
  16. package/engine/monero/wallet.js +31 -68
  17. package/engine/monero/wordlist.en.js +210 -0
  18. package/engine/recovery/restore.js +1 -1
  19. package/engine/sdk/bridge.js +7 -182
  20. package/engine/ui/walletModal.js +7 -27
  21. package/index.d.ts +248 -254
  22. package/package.json +6 -7
  23. package/src/codes.mjs +12 -0
  24. package/src/config.mjs +16 -54
  25. package/src/engine.mjs +3 -0
  26. package/src/index.mjs +25 -46
  27. package/src/order.mjs +2 -2
  28. package/src/public/networks.d.ts +9 -0
  29. package/src/public/networks.mjs +1 -0
  30. package/src/public/recovery.d.ts +17 -1
  31. package/src/public/recovery.mjs +1 -0
  32. package/src/public/xmr.d.ts +8 -0
  33. package/src/public/xmr.mjs +1 -1
  34. package/src/quotePolicy.mjs +58 -0
  35. package/src/quotes.mjs +30 -753
  36. package/src/readyWindow.mjs +76 -0
  37. package/src/record.mjs +4 -0
  38. package/src/recovery-key.mjs +39 -2
  39. package/src/recovery.mjs +11 -28
  40. package/src/relayClaim.mjs +132 -0
  41. package/src/relayFirmClient.mjs +3 -0
  42. package/src/relayQuote.mjs +5 -1
  43. package/src/swap-flow.mjs +49 -5
  44. package/src/swaps.mjs +530 -317
  45. package/src/sweep-action.mjs +73 -0
  46. package/src/sweep.mjs +7 -1
  47. package/src/version.mjs +1 -1
  48. package/src/witness-slice.mjs +84 -0
  49. package/src/xmr-arrival.mjs +378 -9
  50. package/src/xmrAmountPolicy.mjs +35 -0
  51. package/assets/vendors/monero/monero-js-browser.js +0 -58
  52. package/assets/vendors/monero-js/LICENSE +0 -9
  53. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
@@ -0,0 +1,73 @@
1
+ // THE ORDER ACTION A RECOVERED HALF AUTHORIZES.
2
+ //
3
+ // A recovery caller finds an order on chain and needs two things: the half it can present, and the
4
+ // expectations the action's slot check compares against the live escrow. Both are derived here from the same
5
+ // found order and taker halves `sweep.fromOrder` already uses, so a page does not assemble a second copy of the
6
+ // order fields.
7
+ //
8
+ // THIS MODULE DECIDES NO STATE AND NO TIME. Whether the refund or claim window is open belongs to the caller:
9
+ // it reads the escrow's events and the order's deadlines. This function only says which action the half can
10
+ // authorize and what the live order must look like before signing.
11
+
12
+ import { SdkError } from "./errors.mjs";
13
+
14
+ const ADDRESS_RE = /^0x[0-9a-fA-F]{40}$/;
15
+ const FIELD_RE = /^0x[0-9a-fA-F]{64}$/;
16
+ const INTEGER_RE = /^\d+$/;
17
+
18
+ const addressOf = (value) => (typeof value === "string" && ADDRESS_RE.test(value) ? value.toLowerCase() : null);
19
+ const fieldOf = (value) => (typeof value === "string" && FIELD_RE.test(value) ? value.toLowerCase() : null);
20
+
21
+ export function actionMaterialOf({ order = null, chainId = null, half = null } = {}) {
22
+ if (!order || typeof order !== "object") throw new SdkError("bad-input", { field: "order" });
23
+ const chain = Number(chainId);
24
+ if (!Number.isSafeInteger(chain) || chain <= 0) throw new SdkError("bad-input", { field: "chainId" });
25
+ const side = order.side;
26
+ if (side !== "locker" && side !== "claimer") throw new SdkError("bad-input", { field: "order.side" });
27
+
28
+ const escrow = addressOf(order.escrow);
29
+ const locker = addressOf(order.locker);
30
+ const claimer = addressOf(order.claimer);
31
+ const factory = addressOf(order.factory);
32
+ const salt = fieldOf(order.salt);
33
+ const commitHalfLocker = fieldOf(order.commitHalfLocker);
34
+ const commitHalfClaimer = fieldOf(order.commitHalfClaimer);
35
+ const edPointLocker = fieldOf(order.edPointLocker);
36
+ const edPointClaimer = fieldOf(order.edPointClaimer);
37
+ const edViewPointLocker = fieldOf(order.edViewPointLocker);
38
+ const ownHalf = fieldOf(half);
39
+ const amount = typeof order.amount === "string" ? order.amount
40
+ : typeof order.amount === "bigint" ? order.amount.toString() : null;
41
+ const readyBy = Number(order.readyBy);
42
+ const t1 = Number(order.t1);
43
+
44
+ const missing = [];
45
+ if (!escrow) missing.push("escrow");
46
+ if (!locker) missing.push("locker");
47
+ if (!claimer) missing.push("claimer");
48
+ if (!factory) missing.push("factory");
49
+ if (!salt) missing.push("salt");
50
+ if (!commitHalfLocker) missing.push("commitHalfLocker");
51
+ if (!commitHalfClaimer) missing.push("commitHalfClaimer");
52
+ if (!edPointLocker) missing.push("edPointLocker");
53
+ if (!edPointClaimer) missing.push("edPointClaimer");
54
+ if (!edViewPointLocker) missing.push("edViewPointLocker");
55
+ if (!ownHalf) missing.push("half");
56
+ if (!amount || !INTEGER_RE.test(amount) || BigInt(amount) <= 0n) missing.push("amount");
57
+ if (!Number.isSafeInteger(readyBy) || readyBy <= 0) missing.push("readyBy");
58
+ if (!Number.isSafeInteger(t1) || t1 <= 0) missing.push("t1");
59
+ if (missing.length) throw new SdkError("bad-input", { field: "order", missing });
60
+
61
+ return Object.freeze({
62
+ side,
63
+ kind: side === "locker" ? "refund" : "claim",
64
+ escrow,
65
+ half: ownHalf,
66
+ claimer,
67
+ expect: Object.freeze({
68
+ chainId: chain,
69
+ factory, locker, claimer, amount, readyBy, t1, salt,
70
+ commitHalfLocker, commitHalfClaimer, edPointLocker, edPointClaimer, edViewPointLocker,
71
+ }),
72
+ });
73
+ }
package/src/sweep.mjs CHANGED
@@ -5,6 +5,7 @@
5
5
  // address, ask the app for the restore height (on the page it is taken by address) and say aloud what is missing
6
6
  // so the withdrawal can go. Funds do not move at this step.
7
7
  import { SdkError } from "./errors.mjs";
8
+ import { actionMaterialOf } from "./sweep-action.mjs";
8
9
  import { primitives } from "./primitives.mjs";
9
10
  import * as engine from "./engine.mjs";
10
11
  import { restoreWallet } from "./sweep-restore.mjs";
@@ -129,10 +130,15 @@ const payloadFromOrder = async (request) => {
129
130
  receiveAddress: null,
130
131
  restoreHeight: Number(order.startHeight) > 0 ? Number(order.startHeight) : null,
131
132
  });
133
+ // THE ETH ACTION MATERIAL COMES FROM THE SAME DERIVATION. The half and the order expectations are what
134
+ // `actions.refund` / `actions.claim` need; returning them here keeps the page from rebuilding the order fields.
135
+ // A found order from `findSwaps` carries every field; an incomplete order is refused before a half can be used.
136
+ const action = actionMaterialOf({ order, chainId, half: halves.spendHalf });
132
137
  return {
133
138
  payload,
134
139
  contents: await engine.recoveryFile.createRecoveryFile(payload, passphrase),
135
140
  address: joint.address,
141
+ ...action,
136
142
  };
137
143
  };
138
144
 
@@ -169,7 +175,7 @@ const feeOf = async (wallet, signed) => {
169
175
  return /^\d+$/.test(text) ? text : null;
170
176
  };
171
177
 
172
- export function createSweep({ http, config, call = null }) {
178
+ export function createSweep({ call = null }) {
173
179
  // THE NAME IS NEEDED BY THE OBJECT ITSELF: `run` calls `api.plan(...)` - the step order is held by the plan and
174
180
  // the withdrawal living in one object, not in two copies. During a manual merge of branches the object was left
175
181
  // unnamed, and the withdrawal failed with "api is not defined": not a refusal, but a breakdown. `node --check`
package/src/version.mjs CHANGED
@@ -6,4 +6,4 @@
6
6
  // tools/sync-version.mjs. Do not edit it by hand - set the version in package.json and run `npm run sync:version`.
7
7
  // The `version` check in tools/check.mjs refuses a mismatch, and refuses a runtime read of package.json here.
8
8
 
9
- export const SDK_VERSION = "0.57.2";
9
+ export const SDK_VERSION = "0.59.0";
@@ -0,0 +1,84 @@
1
+ // THE WITNESS-V1 SLICE ANSWER. The parser lives apart from the arrival check so the wire format can be tested
2
+ // against a real witness service without importing the wallet engine.
3
+ import { SdkError } from "./errors.mjs";
4
+
5
+ export const WITNESS_SLICE_BLOCKS = 20;
6
+
7
+ export function witnessSliceIndex(height) {
8
+ const value = Number(height);
9
+ if (!Number.isSafeInteger(value) || value < 0) throw new SdkError("bad-input", { field: "height" });
10
+ return Math.floor(value / WITNESS_SLICE_BLOCKS);
11
+ }
12
+
13
+ export function witnessSliceStart(index) {
14
+ const value = Number(index);
15
+ if (!Number.isSafeInteger(value) || value < 0) throw new SdkError("bad-input", { field: "slice" });
16
+ return value * WITNESS_SLICE_BLOCKS;
17
+ }
18
+
19
+ export function witnessSliceEnd(index) {
20
+ return witnessSliceStart(index) + WITNESS_SLICE_BLOCKS - 1;
21
+ }
22
+
23
+ const witnessHash = (value) => {
24
+ const text = String(value || "").replace(/^0x/, "").toLowerCase();
25
+ return /^[0-9a-f]{64}$/.test(text) ? text : null;
26
+ };
27
+
28
+ /**
29
+ * A full slice below the tip has `grid` blocks. The tip slice ends at the top block, sets `complete: false`, and
30
+ * names that block in `tip`. A partial answer is accepted when its last block is at or above the top the caller
31
+ * read: a newer tip is a block that arrived during the walk, while a tip below it shows a witness that is behind.
32
+ */
33
+ export function parseWitnessSliceBody(body, { network, index, tipHeight = null }) {
34
+ if (!body || typeof body !== "object") throw new SdkError("xmr-no-nodes", { why: "bad-witness-slice" });
35
+ if (Number(body.version) !== 1) throw new SdkError("xmr-no-nodes", { why: "bad-witness-version" });
36
+ if (String(body.network) !== String(network)) throw new SdkError("xmr-no-nodes", { why: "witness-network" });
37
+ if (Number(body.grid) !== WITNESS_SLICE_BLOCKS) throw new SdkError("xmr-no-nodes", { why: "witness-grid" });
38
+ if (Number(body.slice) !== index) throw new SdkError("xmr-no-nodes", { why: "witness-slice" });
39
+ const start = witnessSliceStart(index);
40
+ const sliceEnd = witnessSliceEnd(index);
41
+ const to = Number(body.to);
42
+ if (Number(body.from) !== start || !Number.isSafeInteger(to) || to < start || to > sliceEnd) {
43
+ throw new SdkError("xmr-no-nodes", { why: "witness-bounds" });
44
+ }
45
+ if (typeof body.complete !== "boolean" || body.complete !== (to === sliceEnd)) {
46
+ throw new SdkError("xmr-no-nodes", { why: "witness-complete" });
47
+ }
48
+ const count = to - start + 1;
49
+ if (!Array.isArray(body.blocks) || body.blocks.length !== count) {
50
+ throw new SdkError("xmr-no-nodes", { why: "witness-block-count" });
51
+ }
52
+ const blocks = body.blocks.map((block, i) => {
53
+ if (!block || Number(block.height) !== start + i) {
54
+ throw new SdkError("xmr-no-nodes", { why: "witness-height" });
55
+ }
56
+ const hash = witnessHash(block.hash);
57
+ if (!hash) throw new SdkError("xmr-no-nodes", { why: "witness-hash" });
58
+ if (!Array.isArray(block.txids)) throw new SdkError("xmr-no-nodes", { why: "witness-txids" });
59
+ const txids = block.txids.map((txid) => {
60
+ const value = witnessHash(txid);
61
+ if (!value) throw new SdkError("xmr-no-nodes", { why: "witness-txid" });
62
+ return value;
63
+ });
64
+ return { height: Number(block.height), hash, txids };
65
+ });
66
+ let tip = null;
67
+ if (body.complete) {
68
+ if (body.tip !== null && body.tip !== undefined) throw new SdkError("xmr-no-nodes", { why: "witness-tip" });
69
+ } else {
70
+ const value = body.tip;
71
+ if (!value || typeof value !== "object" || Number(value.height) !== to || !witnessHash(value.hash)
72
+ || String(value.hash).toLowerCase() !== blocks[count - 1].hash) {
73
+ throw new SdkError("xmr-no-nodes", { why: "witness-tip" });
74
+ }
75
+ // A TIP AT OR ABOVE THE TOP IS A BLOCK THAT ARRIVED DURING THE WALK. A tip below it is a witness that is
76
+ // behind the chain the caller already read, and that cannot be evidence of absence.
77
+ if (tipHeight !== null && Number(value.height) < Number(tipHeight)) {
78
+ throw new SdkError("xmr-no-nodes", { why: "witness-tip-height" });
79
+ }
80
+ tip = { height: Number(value.height), hash: witnessHash(value.hash) };
81
+ }
82
+ return { version: 1, network: String(network), grid: WITNESS_SLICE_BLOCKS, slice: index,
83
+ from: start, to, complete: body.complete, blocks, tip };
84
+ }
@@ -28,6 +28,9 @@
28
28
  // client scans blocks from the swap's birth height (a few dozen blocks).
29
29
  import { SdkError } from "./errors.mjs";
30
30
  import * as engine from "./engine.mjs";
31
+ import {
32
+ WITNESS_SLICE_BLOCKS, parseWitnessSliceBody, witnessSliceEnd, witnessSliceIndex, witnessSliceStart,
33
+ } from "./witness-slice.mjs";
31
34
 
32
35
  const isStr = (v) => typeof v === "string" && v.length > 0;
33
36
  const intOf = (v) => { const n = Number(v); return Number.isFinite(n) ? Math.trunc(n) : null; };
@@ -57,6 +60,9 @@ const failureOf = (error, node) => {
57
60
  // A NODE LIST IS A LIST OF {url, operator}. The operator is what makes two nodes two witnesses: two nodes of one
58
61
  // operator are one opinion. A plain string is accepted and its operator is the host - a user who adds their own
59
62
  // node is the operator of it.
63
+ //
64
+ // `protocol` is an OPTIONAL capability, not a role. It is kept here so a slice-only witness can be named on the
65
+ // same list without inferring an endpoint from a standard daemon URL.
60
66
  export function normalizeNodes(nodes) {
61
67
  if (!Array.isArray(nodes)) throw new SdkError("bad-input", { field: "nodes" });
62
68
  const out = [];
@@ -66,7 +72,12 @@ export function normalizeNodes(nodes) {
66
72
  out.push({ url, operator: hostOf(url) });
67
73
  } else if (raw && typeof raw === "object" && isStr(raw.url)) {
68
74
  const url = raw.url.replace(/\/+$/, "");
69
- out.push({ url, operator: isStr(raw.operator) ? raw.operator : hostOf(url) });
75
+ const node = { url, operator: isStr(raw.operator) ? raw.operator : hostOf(url) };
76
+ if (raw.protocol !== undefined && raw.protocol !== null) {
77
+ if (!isStr(raw.protocol)) throw new SdkError("bad-input", { field: "nodes.protocol" });
78
+ node.protocol = raw.protocol;
79
+ }
80
+ out.push(node);
70
81
  } else {
71
82
  throw new SdkError("bad-input", { field: "nodes", why: "each-node-is-url-or-url+operator" });
72
83
  }
@@ -110,7 +121,9 @@ async function getInfo(node, fetchImpl, timeoutMs) {
110
121
  if (r.busy === true || r.busy_syncing === true || (typeof r.status === "string" && r.status && r.status !== "OK")) {
111
122
  throw new SdkError("xmr-no-nodes", { node: node.url, why: "busy" });
112
123
  }
113
- return { height: Number(r.height), synced: r.synchronized !== false, nettype: r.nettype || null };
124
+ // A MISSING `synchronized` FIELD IS NOT A SYNCHRONIZED NODE. Only an explicit true lets an empty walk count as
125
+ // evidence of absence.
126
+ return { height: Number(r.height), synced: r.synchronized === true, nettype: r.nettype || null };
114
127
  }
115
128
 
116
129
  // THE WHOLE BLOCK: its hash and ALL of its transaction hashes. This is the only form a public node is asked in.
@@ -222,7 +235,18 @@ export async function verifyArrival(request) {
222
235
  const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : Math.floor(Date.now() / 1000);
223
236
  const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : 20000;
224
237
  const txidHint = txidOf(request.txid);
225
- const watched = { address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub };
238
+ // THE KEY MUST BELONG TO THE ADDRESS, AND THE RULE LIVES IN THE ENGINE. Both facade paths call the same binding;
239
+ // a public `scanRange` cannot accept the other byte-order reading while the facade refuses it.
240
+ const bound = engine.xmrScan.watchedAddressVerdict({
241
+ address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub,
242
+ });
243
+ if (!bound.ok) {
244
+ if (bound.code === "bad-input") throw new SdkError("bad-input", { field: bound.field || "address", why: bound.why });
245
+ throw new SdkError(bound.code, { field: bound.field || "address", address: request.address });
246
+ }
247
+ const viewSecret = bound.viewSecret;
248
+ const spendPub = bound.spendPub;
249
+ const watched = { address: request.address, viewSecret, spendPub };
226
250
 
227
251
  // 1. THE TIP, and with it the first proof that ANY node answers. All nodes down is a named refusal, not silence.
228
252
  const live = [];
@@ -243,9 +267,18 @@ export async function verifyArrival(request) {
243
267
  // 2. LOCATE: from the birth height, by whole blocks. The first reachable node does the walk.
244
268
  let located = null;
245
269
  const completedOperators = new Set();
246
- for (const { node } of live) {
270
+ const staleWitnesses = [];
271
+ for (const { node, info } of live) {
272
+ // A WITNESS THAT IS NOT SYNCHRONIZED HAS NOT SEEN THE RANGE. Counting its empty walk as absence would let two
273
+ // nodes that restarted behind the payout height refund a paid swap; the same rule already guards the positive
274
+ // branch below. The stale entry is reported only when it is evidence about absence; an arrived verdict has a
275
+ // synced witness and must not carry a stale one as a failure.
276
+ if (!info.synced) {
277
+ staleWitnesses.push({ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" });
278
+ continue;
279
+ }
247
280
  try {
248
- located = await locate(node, { expectedAtomic, address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub, fromHeight: request.fromHeight, toHeight: top, nowSec, fetchImpl, timeoutMs });
281
+ located = await locate(node, { expectedAtomic, address: request.address, viewSecret, spendPub, fromHeight: request.fromHeight, toHeight: top, nowSec, fetchImpl, timeoutMs });
249
282
  if (!located) completedOperators.add(node.operator);
250
283
  } catch (error) {
251
284
  failed.push(failureOf(error, node));
@@ -254,11 +287,20 @@ export async function verifyArrival(request) {
254
287
  if (located) break;
255
288
  }
256
289
  if (!located) {
290
+ failed.push(...staleWitnesses);
257
291
  // ABSENCE IS A CLAIM ABOUT MONEY, SO IT NEEDS TWO OPERATORS. One node can withhold a transaction and make
258
292
  // this walk look empty; a refund signed on that answer would take the depositor's ETH from a maker who paid.
259
293
  // Only when no node finished the walk is every node unreachable.
260
- if (!completedOperators.size) throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
261
- return { seen: false, state: "pending", absent: completedOperators.size >= 2, txid: txidHint, tip, completedOperators: [...completedOperators], checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height })), failed };
294
+ if (!completedOperators.size) {
295
+ // A LIVE BUT UNSYNCHRONIZED NODE IS UNKNOWN, NOT ABSENT. Returning pending keeps the refund closed while
296
+ // naming the stale witness in `failed`; xmr-no-nodes would say the nodes did not answer, which they did.
297
+ if (live.some((entry) => !entry.info.synced)) {
298
+ return { seen: false, state: "pending", absent: false, txid: txidHint, tip,
299
+ completedOperators: [], checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height, synchronized: l.info.synced })), failed };
300
+ }
301
+ throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
302
+ }
303
+ return { seen: false, state: "pending", absent: completedOperators.size >= 2, txid: txidHint, tip, completedOperators: [...completedOperators], checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height, synchronized: l.info.synced })), failed };
262
304
  }
263
305
 
264
306
  // 3. VERIFY ON EVERY NODE: the SAME block hash, the SAME transaction inside it, the confirmations and the money.
@@ -387,18 +429,345 @@ export async function verifyArrival(request) {
387
429
  operators: [...best.operators], agreedBy, checked: seen, failed };
388
430
  }
389
431
 
432
+ // ---------------------------------------------------------------------------
433
+ // WITNESS-V1: FIXED BLOCK SLICES FOR THE SHADOW CHECK
434
+ // ---------------------------------------------------------------------------
435
+ //
436
+ // This is the client side of the read-only slice endpoint. It is deliberately a SEPARATE call from
437
+ // `verifyArrival`: the production decision still uses the exact walk until an independent operator serves
438
+ // witness-v1. `verifyArrivalShadow` runs both and compares them without changing ready, refund or any swap state.
439
+
440
+ export { WITNESS_SLICE_BLOCKS, witnessSliceEnd, witnessSliceIndex, witnessSliceStart, parseWitnessSliceBody };
441
+
442
+ async function readWitnessSlice(node, index, { network, fetchImpl, timeoutMs, tipHeight = null }) {
443
+ if (node.protocol !== "witness-v1") throw new SdkError("xmr-no-nodes", { node: node.url, why: "no-slice-witness" });
444
+ const body = await call(node, "/v1/witness/slice",
445
+ { version: 1, network, grid: WITNESS_SLICE_BLOCKS, slice: index }, fetchImpl, timeoutMs);
446
+ return parseWitnessSliceBody(body, { network, index, tipHeight });
447
+ }
448
+
449
+ // ALL THE TRANSACTIONS OF A SLICE, IN ONE REQUEST. The request names the whole slice's txids, not the one
450
+ // transaction an order is looking for.
451
+ async function readSliceTransactions(node, slice, { fetchImpl, timeoutMs }) {
452
+ const txids = [...new Set(slice.blocks.flatMap((block) => block.txids))];
453
+ if (!txids.length) return new Map();
454
+ if (txids.length > 4096) throw new SdkError("xmr-no-nodes", { node: node.url, why: "slice-too-large", count: txids.length });
455
+ const txs = await getBlockTxs(node, txids, fetchImpl, timeoutMs);
456
+ return new Map(txs.map((tx) => [String(tx.tx_hash || "").toLowerCase(), tx]));
457
+ }
458
+
459
+ // THE TOP THE WALK MUST REACH. A witness may be behind the exact nodes, and a walk that stops at the witness's
460
+ // own top must not count as a completed walk: the blocks above it were never read by any source that claimed
461
+ // absence. The exact `verifyArrival` reports its tip on the absence path and the checked heights on the arrived
462
+ // path; both are the highest top the exact sources actually read.
463
+ function exactTopOf(exact) {
464
+ if (!exact || typeof exact !== "object") return null;
465
+ // THE HEIGHTS THAT BELONG TO A SYNCED EXACT NODE. A stale node can report a height far above the chain it has
466
+ // actually read; using its number as the target would keep every honest witness below it. Prefer the checked
467
+ // heights when they exist, and fall back to the tip only for an answer that carries no checked entries.
468
+ const heights = Array.isArray(exact.checked)
469
+ ? exact.checked
470
+ .filter((entry) => entry && entry.synchronized !== false && entry.state !== "stale" && entry.state !== "down")
471
+ .map((entry) => intOf(entry.height))
472
+ .filter((height) => height !== null && height > 0)
473
+ : [];
474
+ if (Array.isArray(exact.checked) && exact.checked.length) {
475
+ return heights.length ? Math.max(0, Math.max(...heights) - 1) : null;
476
+ }
477
+ const tip = intOf(exact.tip);
478
+ if (tip !== null && tip > 0) return Math.max(0, tip - 1);
479
+ return null;
480
+ }
481
+
482
+ // FIND A PAYMENT THROUGH SLICES. The exact `fromHeight` is local: the witness sees only slice indexes.
483
+ async function locateInSlices(node, { expectedAtomic, address, viewSecret, spendPub, fromHeight, toHeight, targetTop = toHeight, nowSec, network, fetchImpl, timeoutMs }) {
484
+ const target = intOf(targetTop);
485
+ if (target === null) throw new SdkError("bad-input", { field: "targetTop" });
486
+ // A WITNESS BEHIND THE FIRST BLOCK HAS NOT READ THE RANGE. The slice walk below would otherwise mark its last
487
+ // slice complete and let a lagging witness vouch for a payment it never saw.
488
+ if (target < fromHeight || toHeight < fromHeight) return { located: null, completed: false };
489
+ const first = witnessSliceIndex(fromHeight);
490
+ const last = witnessSliceIndex(Math.min(toHeight, target));
491
+ let best = null;
492
+ let completed = false;
493
+ let failure = null;
494
+ for (let index = first; index <= last; index++) {
495
+ let slice;
496
+ let txs;
497
+ try {
498
+ // The witness reads its tip at slice time, so a block can arrive between the tip read and this request. The
499
+ // parser accepts a newer tip and rejects one below the top the walk started from.
500
+ slice = await readWitnessSlice(node, index, { network, fetchImpl, timeoutMs, tipHeight: toHeight });
501
+ txs = await readSliceTransactions(node, slice, { fetchImpl, timeoutMs });
502
+ } catch (error) {
503
+ // A CANDIDATE FOUND BEFORE THE FAILURE IS STILL A CANDIDATE. The slice walk is evidence, and a later
504
+ // refused slice does not erase the transaction already read from an earlier one. The caller records the
505
+ // failure beside the located candidate; an absence still requires the whole walk.
506
+ failure = error;
507
+ break;
508
+ }
509
+ for (const block of slice.blocks) {
510
+ // THE SLICE IS A FIXED WINDOW; THE SWAP STARTS AT `fromHeight`. Blocks before the birth height may contain
511
+ // an earlier transfer to the same address, and counting them would make the slice walk disagree with the
512
+ // exact walk that starts at the birth height.
513
+ if (block.height < fromHeight) continue;
514
+ for (const txid of block.txids) {
515
+ const tx = txs.get(txid);
516
+ if (!tx) continue;
517
+ const hit = engine.xmrScan.matchTransaction(tx, [{ address, viewSecret, spendPub }], {
518
+ height: block.height, tipHeight: Math.max(0, toHeight), nowSec,
519
+ });
520
+ if (!hit.length) continue;
521
+ const amountAtomic = sumOutputs(hit[0]);
522
+ const amountVerified = hit[0].outputs.every((o) => o.amountVerified === true);
523
+ const locked = hit[0].unlock && hit[0].unlock.locked === true;
524
+ const score = (amountAtomic >= expectedAtomic ? 4 : 0) + (amountVerified ? 2 : 0) + (locked ? 0 : 1);
525
+ const candidate = { txid, height: block.height, blockHash: block.hash, amountAtomic, locked, score };
526
+ if (!best || score > best.score || (score === best.score && amountAtomic > best.amountAtomic)) best = candidate;
527
+ }
528
+ }
529
+ // THE WHOLE SLICE WAS READ. A perfect candidate lets the walk stop after this slice, not after a block:
530
+ // the last witness request is still a fixed slice, never the payout height. Completion is judged by the
531
+ // LAST BLOCK the witness actually served, not by the slice index: a witness can stop inside the same
532
+ // 20-block window as the target and still be behind it.
533
+ if (best && best.score === 7) {
534
+ completed = slice.to >= target;
535
+ break;
536
+ }
537
+ if (index === last) completed = slice.to >= target;
538
+ }
539
+ return { located: best, completed, failure };
540
+ }
541
+
542
+ /**
543
+ * RUN THE PRODUCTION CHECK AND THE SLICE CHECK SIDE BY SIDE.
544
+ *
545
+ * This is a shadow: it returns the exact verdict, the slice reading and the differences. It never flips
546
+ * `ready`, signs anything or changes a swap. It is the first step before a slice-only default.
547
+ *
548
+ * `witnessNodes` must name at least one `{url, operator, protocol: "witness-v1"}` node. A URL without the
549
+ * protocol is not guessed into an endpoint.
550
+ */
551
+ export async function verifyArrivalShadow(request) {
552
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
553
+ if (request.witnessNodes === undefined || request.witnessNodes === null) {
554
+ throw new SdkError("bad-input", { field: "witnessNodes", why: "required" });
555
+ }
556
+ const witnessNodes = normalizeNodes(request.witnessNodes);
557
+ if (!witnessNodes.some((node) => node.protocol === "witness-v1")) {
558
+ throw new SdkError("bad-input", { field: "witnessNodes", why: "no-witness-v1" });
559
+ }
560
+ // THE SAME ENGINE BINDING AS `verifyArrival`. The shadow path does not carry a second copy of the view/spend rule.
561
+ if (!isStr(request.address)) throw new SdkError("bad-input", { field: "address" });
562
+ if (!isStr(request.spendPub)) throw new SdkError("bad-input", { field: "spendPub" });
563
+ if (request.viewSecret === undefined || request.viewSecret === null) throw new SdkError("bad-input", { field: "viewSecret" });
564
+ const bound = engine.xmrScan.watchedAddressVerdict({
565
+ address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub,
566
+ });
567
+ if (!bound.ok) {
568
+ if (bound.code === "bad-input") throw new SdkError("bad-input", { field: bound.field || "address", why: bound.why });
569
+ throw new SdkError(bound.code, { field: bound.field || "address", address: request.address });
570
+ }
571
+ const network = request.network || bound.keys.network;
572
+ const viewSecret = bound.viewSecret;
573
+ const spendPub = bound.spendPub;
574
+ const fetchImpl = typeof request.fetch === "function" ? request.fetch : globalThis.fetch;
575
+ if (typeof fetchImpl !== "function") throw new SdkError("bad-input", { field: "fetch" });
576
+ const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : 20000;
577
+ const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : Math.floor(Date.now() / 1000);
578
+ const fromHeight = Number(request.fromHeight);
579
+ if (!Number.isSafeInteger(fromHeight) || fromHeight <= 0) throw new SdkError("bad-input", { field: "fromHeight" });
580
+ let expectedAtomic;
581
+ try { expectedAtomic = BigInt(request.expectedAtomic); } catch { throw new SdkError("bad-input", { field: "expectedAtomic" }); }
582
+ if (expectedAtomic <= 0n) throw new SdkError("bad-input", { field: "expectedAtomic" });
583
+
584
+ let exact = null;
585
+ let exactError = null;
586
+ try { exact = await verifyArrival(request); }
587
+ catch (error) { exactError = { code: error && error.code ? error.code : "unknown", params: (error && error.params) || {} }; }
588
+
589
+ const checked = [];
590
+ const failed = [];
591
+ const staleWitnesses = [];
592
+ const readable = [];
593
+ const observations = [];
594
+ // THE WALK MUST REACH THE HIGHEST TOP ANY SOURCE READ. A witness that is behind the exact nodes OR behind another
595
+ // witness cannot prove absence in the blocks it has not seen; its own `toHeight` is therefore not the completion
596
+ // target. Collect every top first, then walk against the common target.
597
+ const exactTop = exactTopOf(exact);
598
+ let highestTop = exactTop;
599
+ for (const node of witnessNodes) {
600
+ if (node.protocol !== "witness-v1") { failed.push({ url: node.url, operator: node.operator, code: "no-slice-witness" }); continue; }
601
+ let info;
602
+ try { info = await getInfo(node, fetchImpl, timeoutMs); }
603
+ catch (error) { failed.push(failureOf(error, node)); checked.push({ url: node.url, operator: node.operator, state: "down" }); continue; }
604
+ if (!info.synced) {
605
+ staleWitnesses.push({ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" });
606
+ checked.push({ url: node.url, operator: node.operator, state: "stale", height: info.height });
607
+ continue;
608
+ }
609
+ const top = Math.max(0, info.height - 1);
610
+ const entry = { url: node.url, operator: node.operator, state: "ok", height: info.height };
611
+ checked.push(entry);
612
+ highestTop = highestTop === null ? top : Math.max(highestTop, top);
613
+ readable.push({ node, top, entry });
614
+ }
615
+ let located = null;
616
+ let completed = false;
617
+ const completedWitnessOperators = new Set();
618
+ for (const { node, top, entry } of readable) {
619
+ const targetTop = highestTop === null ? top : Math.max(top, highestTop);
620
+ try {
621
+ const found = await locateInSlices(node, {
622
+ expectedAtomic, address: request.address, viewSecret, spendPub, fromHeight, toHeight: top,
623
+ targetTop,
624
+ nowSec, network, fetchImpl, timeoutMs,
625
+ });
626
+ completed = completed || found.completed;
627
+ if (found.completed) completedWitnessOperators.add(node.operator || node.url);
628
+ if (found.failure) {
629
+ failed.push(failureOf(found.failure, node));
630
+ entry.state = "error";
631
+ } else if (!found.completed) entry.state = found.located ? "partial" : "behind";
632
+ if (found.located) {
633
+ observations.push({
634
+ operator: node.operator || node.url, url: node.url, seen: true, completed: found.completed,
635
+ txid: found.located.txid, height: found.located.height, blockHash: found.located.blockHash,
636
+ amountAtomic: found.located.amountAtomic.toString(), locked: found.located.locked === true,
637
+ });
638
+ if (!located || found.located.score > located.score) {
639
+ located = found.located;
640
+ located.operator = node.operator;
641
+ located.url = node.url;
642
+ }
643
+ } else if (found.completed) {
644
+ observations.push({ operator: node.operator || node.url, url: node.url, seen: false, completed: true,
645
+ txid: null, height: null, blockHash: null, amountAtomic: null, locked: null });
646
+ }
647
+ } catch (error) {
648
+ entry.state = "error";
649
+ failed.push(failureOf(error, node));
650
+ }
651
+ }
652
+
653
+ if (!located) failed.push(...staleWitnesses);
654
+ const completedOperators = [...completedWitnessOperators];
655
+ const independentOperators = completedOperators.filter((operator) => String(operator).toLowerCase() !== "ninsei");
656
+ const required = 2;
657
+ const witnessQuorum = { required, completed: completedOperators, independent: independentOperators,
658
+ ok: (network === "mainnet" ? independentOperators.length : completedOperators.length) >= required };
659
+
660
+ // ONE OPINION PER OPERATOR, THEN COMPARE THE OPINIONS. A second instance of the same operator may repeat the
661
+ // first, but it may not silently contradict it; a different operator that reports another block, amount or
662
+ // unlock state is a disagreement even when its own walk completed. Without this the first matching candidate
663
+ // hid the contradiction only because of its score or iteration order.
664
+ const normalizedObservation = (observation) => ({
665
+ operator: String(observation.operator || observation.url || ""),
666
+ seen: observation.seen === true,
667
+ txid: observation.txid === null || observation.txid === undefined ? null : String(observation.txid).toLowerCase(),
668
+ height: observation.height === null || observation.height === undefined ? null : Number(observation.height),
669
+ blockHash: observation.blockHash === null || observation.blockHash === undefined
670
+ ? null : String(observation.blockHash).toLowerCase(),
671
+ amountAtomic: observation.amountAtomic === null || observation.amountAtomic === undefined
672
+ ? null : String(observation.amountAtomic),
673
+ locked: observation.locked === null || observation.locked === undefined ? null : observation.locked === true,
674
+ });
675
+ const observationField = (a, b) => {
676
+ for (const field of ["seen", "txid", "height", "blockHash", "amountAtomic", "locked"]) {
677
+ if (a[field] !== b[field]) return field;
678
+ }
679
+ return null;
680
+ };
681
+ const groups = new Map();
682
+ for (const observation of observations) {
683
+ const normalized = normalizedObservation(observation);
684
+ const key = normalized.operator.toLowerCase();
685
+ if (!groups.has(key)) groups.set(key, []);
686
+ groups.get(key).push(normalized);
687
+ }
688
+ const witnessDisagreements = [];
689
+ for (const [operator, entries] of groups) {
690
+ for (let i = 1; i < entries.length; i += 1) {
691
+ const field = observationField(entries[0], entries[i]);
692
+ if (field) witnessDisagreements.push({ operators: [operator], field, against: "same-operator" });
693
+ }
694
+ }
695
+ const representatives = [...groups.values()].map((entries) => entries[0]);
696
+ for (let i = 1; i < representatives.length; i += 1) {
697
+ const field = observationField(representatives[0], representatives[i]);
698
+ if (field) witnessDisagreements.push({ operators: [representatives[0].operator, representatives[i].operator], field });
699
+ }
700
+ const witnessEvidence = { observations: representatives, disagreements: witnessDisagreements };
701
+
702
+ const witness = located
703
+ ? { state: "seen", txid: located.txid, height: located.height, blockHash: located.blockHash,
704
+ amountAtomic: located.amountAtomic.toString(), operator: located.operator, url: located.url, completed, checked, failed,
705
+ ...witnessEvidence, quorum: witnessQuorum }
706
+ : { state: "pending", txid: null, height: null, blockHash: null, amountAtomic: null, completed, checked, failed,
707
+ ...witnessEvidence, quorum: witnessQuorum };
708
+
709
+ const problems = [];
710
+ let agrees = null;
711
+ if (exactError) problems.push("exact:" + exactError.code);
712
+ if (located && exact && exact.txid) {
713
+ const add = (token) => { if (!problems.includes(token)) problems.push(token); };
714
+ for (const observation of representatives) {
715
+ if (!observation.seen) {
716
+ add("witness:txid");
717
+ witnessDisagreements.push({ operators: [observation.operator], field: "seen", against: "exact" });
718
+ continue;
719
+ }
720
+ if (String(exact.txid).toLowerCase() !== observation.txid) {
721
+ add("txid");
722
+ witnessDisagreements.push({ operators: [observation.operator], field: "txid", against: "exact" });
723
+ }
724
+ if (Number(exact.height) !== observation.height) {
725
+ add("height");
726
+ witnessDisagreements.push({ operators: [observation.operator], field: "height", against: "exact" });
727
+ }
728
+ if (String(exact.blockHash || "").toLowerCase() !== observation.blockHash) {
729
+ add("blockHash");
730
+ witnessDisagreements.push({ operators: [observation.operator], field: "blockHash", against: "exact" });
731
+ }
732
+ if (String(exact.amountAtomic ?? "") !== observation.amountAtomic) {
733
+ add("amount");
734
+ witnessDisagreements.push({ operators: [observation.operator], field: "amountAtomic", against: "exact" });
735
+ }
736
+ }
737
+ if (witnessDisagreements.length) add("witness:disagreement");
738
+ agrees = problems.length === 0;
739
+ } else if (located) {
740
+ problems.push("exact:no-transaction");
741
+ agrees = false;
742
+ } else if (exact && exact.absent === true) {
743
+ // ABSENCE NEEDS THE WHOLE SLICE WALK AND TWO DISTINCT OPERATORS. A server that is down, stale or answered a
744
+ // partial slice has not shown that the money is absent; one completed operator is also not the exact path's
745
+ // quorum and must not become agreement. Two instances of one operator count once.
746
+ if (witness.completed && witness.failed.length === 0 && witness.quorum.ok && !witnessDisagreements.length) agrees = true;
747
+ else {
748
+ agrees = false;
749
+ problems.push(witness.completed && witness.failed.length === 0 ? "witness:no-quorum" : "witness:not-completed");
750
+ if (witnessDisagreements.length) problems.push("witness:disagreement");
751
+ }
752
+ }
753
+ return { exact, exactError, witness, agrees, problems };
754
+ }
755
+
390
756
  /**
391
757
  * IS THERE STILL TIME FOR THE CONFIRMATIONS? Ten confirmations of Monero are about twenty minutes, and the ready
392
758
  * deadline does not move. If less than that is left, the client must NAME it and not start - waiting silently would
393
759
  * start a trade that cannot be finished in time. Returns seconds left; refuses with `xmr-too-late` otherwise.
394
760
  */
395
- export function assertTimeForConfirmations({ readyBySec, nowSec, minConfirmations, blockTimeSec } = {}) {
761
+ export function assertTimeForConfirmations({ readyBySec, nowSec, minConfirmations, blockTimeSec, minLeadSec = null } = {}) {
396
762
  const readyBy = Number(readyBySec);
397
763
  const now = Number.isFinite(Number(nowSec)) ? Number(nowSec) : Math.floor(Date.now() / 1000);
398
764
  const count = Math.max(1, intOf(minConfirmations) ?? 1);
399
765
  const block = Number.isFinite(Number(blockTimeSec)) && Number(blockTimeSec) > 0 ? Number(blockTimeSec) : 120;
400
766
  if (!Number.isFinite(readyBy) || readyBy <= 0) return null; // no deadline known - nothing to compare against
401
- const needSec = count * block;
767
+ // THE NODE'S LEAD WINS WHEN IT IS LONGER. A maker that advertises a 2400 s minimum cannot be paid in the old
768
+ // 1200 s; the client uses the longer of the two so its own confirmations and the maker's settlement both fit.
769
+ const nodeLead = Number.isFinite(Number(minLeadSec)) && Number(minLeadSec) > 0 ? Number(minLeadSec) : 0;
770
+ const needSec = Math.max(count * block, nodeLead);
402
771
  const leftSec = Math.floor(readyBy - now);
403
772
  if (leftSec < needSec) throw new SdkError("xmr-too-late", { needSec, leftSec, minConfirmations: count, readyBy: Math.floor(readyBy) });
404
773
  return leftSec;