@ninsei-labs/sdk 0.56.1 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +78 -28
  4. package/THIRD_PARTY_NOTICES.md +176 -2
  5. package/assets/vendors/MANIFEST.json +1 -13
  6. package/assets/vendors/sdk/sdk-browser.js +5 -4
  7. package/engine/atomic/dleq2.js +116 -15
  8. package/engine/atomic/order.js +21 -3
  9. package/engine/core/config.js +20 -46
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/rfqSource.js +6 -133
  12. package/engine/core/swap.js +8 -8
  13. package/engine/evm/asyncRoute.js +1 -1
  14. package/engine/evm/claimGas.js +2 -1
  15. package/engine/evm/escrow.js +13 -8
  16. package/engine/evm/factory.js +11 -6
  17. package/engine/evm/funding.js +8 -3
  18. package/engine/evm/index.js +5 -6
  19. package/engine/evm/session.js +48 -279
  20. package/engine/monero/address.js +15 -33
  21. package/engine/monero/keys.js +124 -0
  22. package/engine/monero/mnemonic.js +104 -0
  23. package/engine/monero/scan.js +121 -28
  24. package/engine/monero/wallet.js +31 -68
  25. package/engine/monero/wordlist.en.js +210 -0
  26. package/engine/recovery/restore.js +9 -9
  27. package/engine/sdk/bridge.js +9 -187
  28. package/engine/ui/walletModal.js +7 -27
  29. package/index.d.ts +234 -262
  30. package/package.json +7 -6
  31. package/src/actions.mjs +8 -5
  32. package/src/codes.mjs +17 -0
  33. package/src/config.mjs +17 -54
  34. package/src/engine.mjs +9 -6
  35. package/src/feeEstimate.mjs +11 -4
  36. package/src/http.mjs +4 -1
  37. package/src/index.mjs +24 -45
  38. package/src/legs/kyber.mjs +23 -0
  39. package/src/lock.mjs +1 -0
  40. package/src/order.mjs +110 -22
  41. package/src/primitives.mjs +4 -5
  42. package/src/probes.mjs +9 -3
  43. package/src/public/networks.d.ts +45 -0
  44. package/src/public/networks.mjs +10 -1
  45. package/src/public/recovery.d.ts +17 -1
  46. package/src/public/recovery.mjs +1 -0
  47. package/src/public/xmr.mjs +1 -1
  48. package/src/quotePolicy.mjs +25 -0
  49. package/src/quotes.mjs +109 -765
  50. package/src/readyWindow.mjs +76 -0
  51. package/src/recovery-key.mjs +71 -16
  52. package/src/recovery.mjs +11 -28
  53. package/src/relayClaim.mjs +132 -0
  54. package/src/relayFeatures.mjs +25 -13
  55. package/src/relayFirmClient.mjs +36 -7
  56. package/src/relayQuote.mjs +92 -11
  57. package/src/relayView.mjs +3 -3
  58. package/src/swap-flow.mjs +146 -60
  59. package/src/swaps.mjs +521 -357
  60. package/src/sweep-action.mjs +73 -0
  61. package/src/sweep-restore.mjs +8 -4
  62. package/src/sweep.mjs +12 -2
  63. package/src/version.mjs +1 -1
  64. package/src/xmr-arrival.mjs +328 -29
  65. package/src/xmrAmountPolicy.mjs +35 -0
  66. package/assets/vendors/atomic/atomic-browser.js +0 -24
  67. package/assets/vendors/monero/monero-js-browser.js +0 -58
  68. package/assets/vendors/monero-js/LICENSE +0 -9
  69. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
  70. package/engine/atomic/order-client.js +0 -56
  71. package/engine/atomic/order-worker.js +0 -156
  72. package/engine/evm/asyncExec.js +0 -577
  73. package/engine/evm/asyncLegs.js +0 -308
@@ -0,0 +1,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
+ }
@@ -247,9 +247,13 @@ export async function restoreWallet(request = {}) {
247
247
  why: e && e.params && e.params.why ? e.params.why : null,
248
248
  };
249
249
  }
250
- // THE KEY IMAGES OF THE WALLET, CHECKED AT THE NODE. `scanTxs` finds an output; whether the chain already
251
- // spent it is a separate fact, and the caller must not sign on a guess. A failed scan has no images to ask for.
252
- if (windowReport.used && requestWindow.nodeUrl && typeof driver.getKeyImages === "function") {
250
+ // THE KEY IMAGES OF THE WALLET, CHECKED AT THE NODE - ONLY WHEN THE CALLER EXPLICITLY TRUSTS THAT NODE.
251
+ // Key images are linkable: a third-party daemon can tie them to the visitor's connection and recognise later
252
+ // spends. The window path must not leak them by default. A trusted-node caller opts in with
253
+ // `window.trustedNode: true`; otherwise the pass reports spent status as unavailable and the full-scan path
254
+ // (which uses the wallet's own spent check) remains available.
255
+ if (windowReport.used && requestWindow.nodeUrl && requestWindow.trustedNode === true
256
+ && typeof driver.getKeyImages === "function") {
253
257
  try {
254
258
  const exported = await driver.getKeyImages();
255
259
  const images = Array.isArray(exported) ? exported
@@ -273,7 +277,7 @@ export async function restoreWallet(request = {}) {
273
277
  } catch { windowReport.spent = null; windowReport.spentWhy = "check-failed"; }
274
278
  } else if (windowReport.used && requestWindow.nodeUrl) {
275
279
  windowReport.spent = null;
276
- windowReport.spentWhy = "no-key-images";
280
+ windowReport.spentWhy = requestWindow.trustedNode === true ? "no-key-images" : "untrusted-node";
277
281
  }
278
282
  // A WINDOW WITH COINS IS THE ANSWER. A window with none falls through to the full scan unless the caller
279
283
  // explicitly turned the fallback off.
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";
@@ -37,7 +38,11 @@ const STEPS = ["unlock", "sync", "sweep", "relay"];
37
38
  export const MAX_SWEEP_FEE_ATOMIC = 10_000_000_000n; // 0.01 XMR
38
39
 
39
40
  export function sweepFeeVerdict({ feeAtomic = null, amountAtomic = null, maxFeeAtomic = MAX_SWEEP_FEE_ATOMIC } = {}) {
40
- if (feeAtomic === null || feeAtomic === undefined) return { ok: true, checked: false, fee: null, limit: String(maxFeeAtomic) };
41
+ if (feeAtomic === null || feeAtomic === undefined) {
42
+ // A FEE THAT WAS NOT REPORTED IS NOT A FREE WITHDRAWAL. The ceiling cannot be applied to an unknown number;
43
+ // the page must show the refusal instead of a withdrawal whose cost is invisible.
44
+ return { ok: false, code: "sweep-fee-unknown", checked: false, fee: null, limit: String(maxFeeAtomic) };
45
+ }
41
46
  let fee;
42
47
  let amount;
43
48
  let limit;
@@ -125,10 +130,15 @@ const payloadFromOrder = async (request) => {
125
130
  receiveAddress: null,
126
131
  restoreHeight: Number(order.startHeight) > 0 ? Number(order.startHeight) : null,
127
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 });
128
137
  return {
129
138
  payload,
130
139
  contents: await engine.recoveryFile.createRecoveryFile(payload, passphrase),
131
140
  address: joint.address,
141
+ ...action,
132
142
  };
133
143
  };
134
144
 
@@ -165,7 +175,7 @@ const feeOf = async (wallet, signed) => {
165
175
  return /^\d+$/.test(text) ? text : null;
166
176
  };
167
177
 
168
- export function createSweep({ http, config, call = null }) {
178
+ export function createSweep({ call = null }) {
169
179
  // THE NAME IS NEEDED BY THE OBJECT ITSELF: `run` calls `api.plan(...)` - the step order is held by the plan and
170
180
  // the withdrawal living in one object, not in two copies. During a manual merge of branches the object was left
171
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.56.1";
9
+ export const SDK_VERSION = "0.58.0";
@@ -23,9 +23,9 @@
23
23
  // hashes), never for a single transaction: otherwise a node links the user's IP to the trade. Requests carry
24
24
  // `Content-Type: text/plain` (verified on every node in the default list - it avoids the CORS preflight).
25
25
  //
26
- // WHAT THE MAKER GIVES IS ONLY A HINT. The maker's node may name the payout txid; the backend may relay it. It
27
- // decides nothing - a fabricated txid simply fails the check. Without a txid the client scans blocks from the
28
- // swap's birth height (a few dozen blocks).
26
+ // WHAT THE MAKER GIVES IS ONLY A REPORTED HINT. The maker's node may name the payout txid; the backend may relay
27
+ // it, but it does not narrow the walk and cannot hide another transfer. Every matching transfer is judged; the
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
31
 
@@ -47,7 +47,7 @@ const failureOf = (error, node) => {
47
47
  const name = String(params.name || (error && error.name) || "");
48
48
  if (params.status !== undefined && params.status !== null) code = "http";
49
49
  else if (/^(TimeoutError|AbortError)$/.test(name) || /timeout|abort/i.test(why) || /timeout|abort/i.test(name)) code = "timeout";
50
- else if (why === "bad-json" || why === "no-height" || why === "no-block") code = "bad-answer";
50
+ else if (why === "bad-json" || why === "no-height" || why === "no-block" || why === "busy" || why === "partial-transactions") code = "bad-answer";
51
51
  const out = { url: node.url, operator: node.operator, code };
52
52
  if (params.status !== undefined && params.status !== null) out.status = params.status;
53
53
  if (why) out.why = why;
@@ -57,6 +57,9 @@ const failureOf = (error, node) => {
57
57
  // A NODE LIST IS A LIST OF {url, operator}. The operator is what makes two nodes two witnesses: two nodes of one
58
58
  // operator are one opinion. A plain string is accepted and its operator is the host - a user who adds their own
59
59
  // node is the operator of it.
60
+ //
61
+ // `protocol` is an OPTIONAL capability, not a role. It is kept here so a slice-only witness can be named on the
62
+ // same list without inferring an endpoint from a standard daemon URL.
60
63
  export function normalizeNodes(nodes) {
61
64
  if (!Array.isArray(nodes)) throw new SdkError("bad-input", { field: "nodes" });
62
65
  const out = [];
@@ -66,7 +69,12 @@ export function normalizeNodes(nodes) {
66
69
  out.push({ url, operator: hostOf(url) });
67
70
  } else if (raw && typeof raw === "object" && isStr(raw.url)) {
68
71
  const url = raw.url.replace(/\/+$/, "");
69
- out.push({ url, operator: isStr(raw.operator) ? raw.operator : hostOf(url) });
72
+ const node = { url, operator: isStr(raw.operator) ? raw.operator : hostOf(url) };
73
+ if (raw.protocol !== undefined && raw.protocol !== null) {
74
+ if (!isStr(raw.protocol)) throw new SdkError("bad-input", { field: "nodes.protocol" });
75
+ node.protocol = raw.protocol;
76
+ }
77
+ out.push(node);
70
78
  } else {
71
79
  throw new SdkError("bad-input", { field: "nodes", why: "each-node-is-url-or-url+operator" });
72
80
  }
@@ -106,6 +114,10 @@ async function getInfo(node, fetchImpl, timeoutMs) {
106
114
  const j = await call(node, "/json_rpc", { jsonrpc: "2.0", id: "info", method: "get_info" }, fetchImpl, timeoutMs);
107
115
  const r = j && j.result;
108
116
  if (!r || !Number.isFinite(Number(r.height))) throw new SdkError("xmr-no-nodes", { node: node.url, why: "no-height" });
117
+ // A BUSY NODE HAS NOT FINISHED ITS OWN VIEW. Its height is not evidence that the walk was complete.
118
+ if (r.busy === true || r.busy_syncing === true || (typeof r.status === "string" && r.status && r.status !== "OK")) {
119
+ throw new SdkError("xmr-no-nodes", { node: node.url, why: "busy" });
120
+ }
109
121
  return { height: Number(r.height), synced: r.synchronized !== false, nettype: r.nettype || null };
110
122
  }
111
123
 
@@ -127,15 +139,27 @@ async function getBlock(node, height, fetchImpl, timeoutMs) {
127
139
  async function getBlockTxs(node, hashes, fetchImpl, timeoutMs) {
128
140
  if (!hashes.length) return [];
129
141
  const j = await call(node, "/get_transactions", { txs_hashes: hashes, decode_as_json: true }, fetchImpl, timeoutMs);
130
- const wrappers = j.txs || [];
131
- return (j.txs_as_json || []).map((s, i) => {
132
- const body = typeof s === "string" ? JSON.parse(s) : s;
142
+ const wrappers = Array.isArray(j.txs) ? j.txs : [];
143
+ const bodies = Array.isArray(j.txs_as_json) ? j.txs_as_json : [];
144
+ // A PARTIAL ANSWER IS NOT AN EMPTY BLOCK. If the node returns fewer transactions than the block named, the walk
145
+ // cannot conclude "no payment": that answer is unknown and must stop the refund path.
146
+ if (bodies.length !== hashes.length || (wrappers.length && wrappers.length !== hashes.length)) {
147
+ throw new SdkError("xmr-no-nodes", { node: node.url, why: "partial-transactions", want: hashes.length, got: bodies.length });
148
+ }
149
+ const out = bodies.map((s, i) => {
150
+ let body;
151
+ try { body = typeof s === "string" ? JSON.parse(s) : s; }
152
+ catch { throw new SdkError("xmr-no-nodes", { node: node.url, why: "bad-json" }); }
133
153
  const w = wrappers[i] || {};
134
154
  body.tx_hash = String(w.tx_hash || body.tx_hash || "").replace(/^0x/, "").toLowerCase();
135
155
  body.block_height = w.block_height ?? null;
136
156
  body.confirmations = w.confirmations ?? null;
137
157
  return body;
138
- });
158
+ }).filter((body) => hashes.includes(String(body.tx_hash || "").toLowerCase()));
159
+ if (out.length !== hashes.length) {
160
+ throw new SdkError("xmr-no-nodes", { node: node.url, why: "partial-transactions", want: hashes.length, got: out.length });
161
+ }
162
+ return out;
139
163
  }
140
164
 
141
165
  // The amount of our own outputs in a matched transaction (a swap can be paid in several outputs). An output whose
@@ -143,29 +167,43 @@ async function getBlockTxs(node, hashes, fetchImpl, timeoutMs) {
143
167
  const sumOutputs = (hit) => hit.outputs.reduce((n, o) => n + (o.amountVerified ? (o.amountAtomic || 0n) : 0n), 0n);
144
168
 
145
169
  /**
146
- * FIND THE TRANSACTION, IF IT IS THERE. Blocks are walked from the swap's birth height upwards and the whole block
147
- * is asked for each height, so a public node never learns which transaction is ours. A txid hint only shortens the
148
- * work: a block without that hash is still fetched whole, but its transactions are not parsed.
170
+ * FIND THE BEST MATCHING TRANSFER. Blocks are walked from the swap's birth height upwards and the whole block is
171
+ * asked for each height, so a public node never learns which transaction is ours. Every matching transfer is
172
+ * judged: a full unlocked payout wins over dust or a locked one. The reported hint is not an input here.
149
173
  */
150
- async function locate(node, { txid, address, viewSecret, spendPub, fromHeight, toHeight, nowSec, fetchImpl, timeoutMs }) {
174
+ async function locate(node, { expectedAtomic, address, viewSecret, spendPub, fromHeight, toHeight, nowSec, fetchImpl, timeoutMs }) {
151
175
  const from = Math.max(0, intOf(fromHeight) ?? 0);
152
176
  const to = intOf(toHeight);
153
177
  if (!Number.isFinite(to) || to < from) throw new SdkError("bad-input", { field: "fromHeight", got: fromHeight });
178
+ let best = null;
154
179
  for (let h = from; h <= to; h++) {
155
180
  const { txHashes } = await getBlock(node, h, fetchImpl, timeoutMs);
156
181
  if (!txHashes.length) continue;
157
- if (txid && !txHashes.includes(txid)) continue; // the hint says it is not in this block
182
+ // EVERY BLOCK IS WALKED. The reported hint cannot hide a full payout in another block.
158
183
  const txs = await getBlockTxs(node, txHashes, fetchImpl, timeoutMs);
159
184
  for (const tx of txs) {
160
- if (txid && tx.tx_hash !== txid) continue;
161
- const hit = engine.xmrScan.matchTransaction(tx, [{ address, viewSecret, spendPub }], { height: h, nowSec });
185
+ const hit = engine.xmrScan.matchTransaction(tx, [{ address, viewSecret, spendPub }], {
186
+ height: h, tipHeight: Math.max(0, to), nowSec,
187
+ });
162
188
  // LOCATE FINDS AN OUTPUT, NOT AN AMOUNT. The amount can be forged or unbacked; the verification step below
163
189
  // refuses it. Requiring a positive verified sum here made two nodes that agreed on a forged amount look like
164
190
  // "no transaction at all".
165
- if (hit.length) return { txid: tx.tx_hash, height: h };
191
+ if (!hit.length) continue;
192
+ const amountAtomic = sumOutputs(hit[0]);
193
+ const amountVerified = hit[0].outputs.every((o) => o.amountVerified === true);
194
+ const locked = hit[0].unlock && hit[0].unlock.locked === true;
195
+ // JUDGE EVERY MATCHING TRANSFER. A dust transfer before the full payout is a real candidate but a worse
196
+ // one; a full unlocked payout wins over a full locked one. The verification step still compares the chosen
197
+ // transaction across operators.
198
+ const score = (amountAtomic >= expectedAtomic ? 4 : 0) + (amountVerified ? 2 : 0) + (locked ? 0 : 1);
199
+ const candidate = { txid: tx.tx_hash, height: h };
200
+ if (score === 7) return candidate;
201
+ if (!best || score > best.score || (score === best.score && amountAtomic > best.amountAtomic)) {
202
+ best = { ...candidate, score, amountAtomic };
203
+ }
166
204
  }
167
205
  }
168
- return null;
206
+ return best;
169
207
  }
170
208
 
171
209
  /**
@@ -192,7 +230,27 @@ export async function verifyArrival(request) {
192
230
  const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : Math.floor(Date.now() / 1000);
193
231
  const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : 20000;
194
232
  const txidHint = txidOf(request.txid);
195
- const watched = { address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub };
233
+ // THE KEY MUST BELONG TO THE ADDRESS, NOT MERELY BE PASSED BESIDE IT. The scanner used to try both byte orders
234
+ // of the view secret and accept the first match; a maker could pay to the address built from the other reading and
235
+ // still get `arrived` while the person's wallet saw nothing. Decode the address, keep the matching view form, and
236
+ // require its spend key to be the same key.
237
+ let addressKeys;
238
+ try { addressKeys = engine.xmrArrivalRead.decodeAddressKeys(request.address); }
239
+ catch { throw new SdkError("bad-input", { field: "address", why: "not-a-monero-address" }); }
240
+ // THE WATCHED ADDRESS IS A PRIMARY ADDRESS. A subaddress has a different payload layout and its view/spend points
241
+ // are not the ones the joint-address builder produces; refusing it by name is clearer than a spurious spend-pub
242
+ // mismatch. SDK-generated addresses are always primary.
243
+ if (!addressKeys.network) throw new SdkError("bad-input", { field: "address", why: "subaddress-not-supported" });
244
+ const spendPub = String(request.spendPub).replace(/^0x/, "").toLowerCase();
245
+ if (!addressKeys.spendPub || spendPub !== String(addressKeys.spendPub).toLowerCase()) {
246
+ throw new SdkError("xmr-address-mismatch", { field: "spendPub", address: request.address });
247
+ }
248
+ const viewForm = engine.xmrScan.viewKeyFormForAddress(request.viewSecret, addressKeys.viewPub);
249
+ if (!viewForm) {
250
+ throw new SdkError("xmr-address-mismatch", { field: "viewSecret", address: request.address });
251
+ }
252
+ const viewSecret = engine.xmrScan.viewSecretCandidates(request.viewSecret).find(([form]) => form === viewForm)?.[1] ?? request.viewSecret;
253
+ const watched = { address: request.address, viewSecret, spendPub: addressKeys.spendPub };
196
254
 
197
255
  // 1. THE TIP, and with it the first proof that ANY node answers. All nodes down is a named refusal, not silence.
198
256
  const live = [];
@@ -212,11 +270,18 @@ export async function verifyArrival(request) {
212
270
 
213
271
  // 2. LOCATE: from the birth height, by whole blocks. The first reachable node does the walk.
214
272
  let located = null;
215
- let completedWalk = false;
216
- for (const { node } of live) {
273
+ const completedOperators = new Set();
274
+ for (const { node, info } of live) {
275
+ // A WITNESS THAT IS NOT SYNCHRONIZED HAS NOT SEEN THE RANGE. Counting its empty walk as absence would let two
276
+ // nodes that restarted behind the payout height refund a paid swap; the same rule already guards the positive
277
+ // branch below.
278
+ if (!info.synced) {
279
+ failed.push({ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" });
280
+ continue;
281
+ }
217
282
  try {
218
- located = await locate(node, { txid: txidHint, address: request.address, viewSecret: request.viewSecret, spendPub: request.spendPub, fromHeight: request.fromHeight, toHeight: top, nowSec, fetchImpl, timeoutMs });
219
- completedWalk = true;
283
+ located = await locate(node, { expectedAtomic, address: request.address, viewSecret, spendPub, fromHeight: request.fromHeight, toHeight: top, nowSec, fetchImpl, timeoutMs });
284
+ if (!located) completedOperators.add(node.operator);
220
285
  } catch (error) {
221
286
  failed.push(failureOf(error, node));
222
287
  located = null;
@@ -224,10 +289,19 @@ export async function verifyArrival(request) {
224
289
  if (located) break;
225
290
  }
226
291
  if (!located) {
227
- // ONE NODE FINISHED THE WALK AND FOUND NOTHING: that is a complete answer, even when another node failed.
228
- // Only when NO node finished the walk is every node unreachable.
229
- if (!completedWalk) throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
230
- return { seen: false, state: "pending", txid: txidHint, tip, checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height })), failed };
292
+ // ABSENCE IS A CLAIM ABOUT MONEY, SO IT NEEDS TWO OPERATORS. One node can withhold a transaction and make
293
+ // this walk look empty; a refund signed on that answer would take the depositor's ETH from a maker who paid.
294
+ // Only when no node finished the walk is every node unreachable.
295
+ if (!completedOperators.size) {
296
+ // A LIVE BUT UNSYNCHRONIZED NODE IS UNKNOWN, NOT ABSENT. Returning pending keeps the refund closed while
297
+ // naming the stale witness in `failed`; xmr-no-nodes would say the nodes did not answer, which they did.
298
+ if (live.some((entry) => !entry.info.synced)) {
299
+ return { seen: false, state: "pending", absent: false, txid: txidHint, tip,
300
+ completedOperators: [], checked: live.map((l) => ({ url: l.node.url, operator: l.node.operator, height: l.info.height, synchronized: l.info.synced })), failed };
301
+ }
302
+ throw new SdkError("xmr-no-nodes", { tried: nodes.map((n) => n.url), nodes: failed });
303
+ }
304
+ 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 };
231
305
  }
232
306
 
233
307
  // 3. VERIFY ON EVERY NODE: the SAME block hash, the SAME transaction inside it, the confirmations and the money.
@@ -356,18 +430,243 @@ export async function verifyArrival(request) {
356
430
  operators: [...best.operators], agreedBy, checked: seen, failed };
357
431
  }
358
432
 
433
+ // ---------------------------------------------------------------------------
434
+ // WITNESS-V1: FIXED BLOCK SLICES FOR THE SHADOW CHECK
435
+ // ---------------------------------------------------------------------------
436
+ //
437
+ // This is the client side of the read-only slice endpoint. It is deliberately a SEPARATE call from
438
+ // `verifyArrival`: the production decision still uses the exact walk until an independent operator serves
439
+ // witness-v1. `verifyArrivalShadow` runs both and compares them without changing ready, refund or any swap state.
440
+
441
+ export const WITNESS_SLICE_BLOCKS = 20;
442
+
443
+ export function witnessSliceIndex(height) {
444
+ const value = Number(height);
445
+ if (!Number.isSafeInteger(value) || value < 0) throw new SdkError("bad-input", { field: "height" });
446
+ return Math.floor(value / WITNESS_SLICE_BLOCKS);
447
+ }
448
+
449
+ export function witnessSliceStart(index) {
450
+ const value = Number(index);
451
+ if (!Number.isSafeInteger(value) || value < 0) throw new SdkError("bad-input", { field: "slice" });
452
+ return value * WITNESS_SLICE_BLOCKS;
453
+ }
454
+
455
+ export function witnessSliceEnd(index) {
456
+ return witnessSliceStart(index) + WITNESS_SLICE_BLOCKS - 1;
457
+ }
458
+
459
+ const witnessHash = (value) => {
460
+ const text = String(value || "").replace(/^0x/, "").toLowerCase();
461
+ return /^[0-9a-f]{64}$/.test(text) ? text : null;
462
+ };
463
+
464
+ function assertWitnessSliceBody(body, { network, index }) {
465
+ if (!body || typeof body !== "object") throw new SdkError("xmr-no-nodes", { why: "bad-witness-slice" });
466
+ if (Number(body.version) !== 1) throw new SdkError("xmr-no-nodes", { why: "bad-witness-version" });
467
+ if (String(body.network) !== String(network)) throw new SdkError("xmr-no-nodes", { why: "witness-network" });
468
+ if (Number(body.grid) !== WITNESS_SLICE_BLOCKS) throw new SdkError("xmr-no-nodes", { why: "witness-grid" });
469
+ if (Number(body.slice) !== index) throw new SdkError("xmr-no-nodes", { why: "witness-slice" });
470
+ if (Number(body.from) !== witnessSliceStart(index) || Number(body.to) !== witnessSliceEnd(index)) {
471
+ throw new SdkError("xmr-no-nodes", { why: "witness-bounds" });
472
+ }
473
+ if (!Array.isArray(body.blocks) || body.blocks.length !== WITNESS_SLICE_BLOCKS) {
474
+ throw new SdkError("xmr-no-nodes", { why: "witness-block-count" });
475
+ }
476
+ const blocks = body.blocks.map((block, i) => {
477
+ if (!block || Number(block.height) !== witnessSliceStart(index) + i) {
478
+ throw new SdkError("xmr-no-nodes", { why: "witness-height" });
479
+ }
480
+ const hash = witnessHash(block.hash);
481
+ if (!hash) throw new SdkError("xmr-no-nodes", { why: "witness-hash" });
482
+ if (!Array.isArray(block.txids)) throw new SdkError("xmr-no-nodes", { why: "witness-txids" });
483
+ const txids = block.txids.map((txid) => {
484
+ const value = witnessHash(txid);
485
+ if (!value) throw new SdkError("xmr-no-nodes", { why: "witness-txid" });
486
+ return value;
487
+ });
488
+ return { height: Number(block.height), hash, txids };
489
+ });
490
+ return { version: 1, network: String(network), grid: WITNESS_SLICE_BLOCKS, slice: index,
491
+ from: body.from, to: body.to, blocks };
492
+ }
493
+
494
+ async function readWitnessSlice(node, index, { network, fetchImpl, timeoutMs }) {
495
+ if (node.protocol !== "witness-v1") throw new SdkError("xmr-no-nodes", { node: node.url, why: "no-slice-witness" });
496
+ const body = await call(node, "/v1/witness/slice",
497
+ { version: 1, network, grid: WITNESS_SLICE_BLOCKS, slice: index }, fetchImpl, timeoutMs);
498
+ return assertWitnessSliceBody(body, { network, index });
499
+ }
500
+
501
+ // ALL THE TRANSACTIONS OF A SLICE, IN ONE REQUEST. The request names the whole slice's txids, not the one
502
+ // transaction an order is looking for.
503
+ async function readSliceTransactions(node, slice, { fetchImpl, timeoutMs }) {
504
+ const txids = [...new Set(slice.blocks.flatMap((block) => block.txids))];
505
+ if (!txids.length) return new Map();
506
+ if (txids.length > 4096) throw new SdkError("xmr-no-nodes", { node: node.url, why: "slice-too-large", count: txids.length });
507
+ const txs = await getBlockTxs(node, txids, fetchImpl, timeoutMs);
508
+ return new Map(txs.map((tx) => [String(tx.tx_hash || "").toLowerCase(), tx]));
509
+ }
510
+
511
+ // FIND A PAYMENT THROUGH SLICES. The exact `fromHeight` is local: the witness sees only slice indexes.
512
+ async function locateInSlices(node, { expectedAtomic, address, viewSecret, spendPub, fromHeight, toHeight, nowSec, network, fetchImpl, timeoutMs }) {
513
+ const first = witnessSliceIndex(fromHeight);
514
+ const last = witnessSliceIndex(toHeight);
515
+ let best = null;
516
+ let completed = true;
517
+ for (let index = first; index <= last; index++) {
518
+ const slice = await readWitnessSlice(node, index, { network, fetchImpl, timeoutMs });
519
+ const txs = await readSliceTransactions(node, slice, { fetchImpl, timeoutMs });
520
+ for (const block of slice.blocks) {
521
+ for (const txid of block.txids) {
522
+ const tx = txs.get(txid);
523
+ if (!tx) continue;
524
+ const hit = engine.xmrScan.matchTransaction(tx, [{ address, viewSecret, spendPub }], {
525
+ height: block.height, tipHeight: Math.max(0, toHeight), nowSec,
526
+ });
527
+ if (!hit.length) continue;
528
+ const amountAtomic = sumOutputs(hit[0]);
529
+ const amountVerified = hit[0].outputs.every((o) => o.amountVerified === true);
530
+ const locked = hit[0].unlock && hit[0].unlock.locked === true;
531
+ const score = (amountAtomic >= expectedAtomic ? 4 : 0) + (amountVerified ? 2 : 0) + (locked ? 0 : 1);
532
+ const candidate = { txid, height: block.height, blockHash: block.hash, amountAtomic, score };
533
+ if (!best || score > best.score || (score === best.score && amountAtomic > best.amountAtomic)) best = candidate;
534
+ }
535
+ }
536
+ // THE WHOLE SLICE WAS READ. A perfect candidate lets the walk stop after this slice, not after a block:
537
+ // the last witness request is still a fixed slice, never the payout height. `completed` means the full
538
+ // requested slice range was walked, so it stays false on an early stop.
539
+ if (best && best.score === 7) {
540
+ completed = index === last;
541
+ break;
542
+ }
543
+ }
544
+ return { located: best, completed };
545
+ }
546
+
547
+ /**
548
+ * RUN THE PRODUCTION CHECK AND THE SLICE CHECK SIDE BY SIDE.
549
+ *
550
+ * This is a shadow: it returns the exact verdict, the slice reading and the differences. It never flips
551
+ * `ready`, signs anything or changes a swap. It is the first step before a slice-only default.
552
+ *
553
+ * `witnessNodes` must name at least one `{url, operator, protocol: "witness-v1"}` node. A URL without the
554
+ * protocol is not guessed into an endpoint.
555
+ */
556
+ export async function verifyArrivalShadow(request) {
557
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "request" });
558
+ if (request.witnessNodes === undefined || request.witnessNodes === null) {
559
+ throw new SdkError("bad-input", { field: "witnessNodes", why: "required" });
560
+ }
561
+ const witnessNodes = normalizeNodes(request.witnessNodes);
562
+ if (!witnessNodes.some((node) => node.protocol === "witness-v1")) {
563
+ throw new SdkError("bad-input", { field: "witnessNodes", why: "no-witness-v1" });
564
+ }
565
+ let addressKeys;
566
+ try { addressKeys = engine.xmrArrivalRead.decodeAddressKeys(request.address); }
567
+ catch { throw new SdkError("bad-input", { field: "address", why: "not-a-monero-address" }); }
568
+ if (!addressKeys.network) throw new SdkError("bad-input", { field: "address", why: "subaddress-not-supported" });
569
+ const network = request.network || addressKeys.network;
570
+ const fetchImpl = typeof request.fetch === "function" ? request.fetch : globalThis.fetch;
571
+ if (typeof fetchImpl !== "function") throw new SdkError("bad-input", { field: "fetch" });
572
+ const timeoutMs = Number.isFinite(Number(request.timeoutMs)) && Number(request.timeoutMs) > 0 ? Number(request.timeoutMs) : 20000;
573
+ const nowSec = Number.isFinite(Number(request.nowSec)) ? Number(request.nowSec) : Math.floor(Date.now() / 1000);
574
+ const fromHeight = Number(request.fromHeight);
575
+ if (!Number.isSafeInteger(fromHeight) || fromHeight <= 0) throw new SdkError("bad-input", { field: "fromHeight" });
576
+ let expectedAtomic;
577
+ try { expectedAtomic = BigInt(request.expectedAtomic); } catch { throw new SdkError("bad-input", { field: "expectedAtomic" }); }
578
+ if (expectedAtomic <= 0n) throw new SdkError("bad-input", { field: "expectedAtomic" });
579
+ if (!isStr(request.spendPub)) throw new SdkError("bad-input", { field: "spendPub" });
580
+ if (request.viewSecret === undefined || request.viewSecret === null) throw new SdkError("bad-input", { field: "viewSecret" });
581
+ const spendPub = String(request.spendPub).replace(/^0x/, "").toLowerCase();
582
+ if (spendPub !== String(addressKeys.spendPub).toLowerCase()) {
583
+ throw new SdkError("xmr-address-mismatch", { field: "spendPub", address: request.address });
584
+ }
585
+ const viewForm = engine.xmrScan.viewKeyFormForAddress(request.viewSecret, addressKeys.viewPub);
586
+ if (!viewForm) throw new SdkError("xmr-address-mismatch", { field: "viewSecret", address: request.address });
587
+ const viewSecret = engine.xmrScan.viewSecretCandidates(request.viewSecret).find(([form]) => form === viewForm)?.[1] ?? request.viewSecret;
588
+
589
+ let exact = null;
590
+ let exactError = null;
591
+ try { exact = await verifyArrival(request); }
592
+ catch (error) { exactError = { code: error && error.code ? error.code : "unknown", params: (error && error.params) || {} }; }
593
+
594
+ const checked = [];
595
+ const failed = [];
596
+ let located = null;
597
+ let completed = false;
598
+ for (const node of witnessNodes) {
599
+ if (node.protocol !== "witness-v1") { failed.push({ url: node.url, operator: node.operator, code: "no-slice-witness" }); continue; }
600
+ let info;
601
+ try { info = await getInfo(node, fetchImpl, timeoutMs); }
602
+ catch (error) { failed.push(failureOf(error, node)); checked.push({ url: node.url, operator: node.operator, state: "down" }); continue; }
603
+ if (!info.synced) {
604
+ failed.push({ url: node.url, operator: node.operator, code: "stale", why: "not-synchronized" });
605
+ checked.push({ url: node.url, operator: node.operator, state: "stale", height: info.height });
606
+ continue;
607
+ }
608
+ const top = Math.max(0, info.height - 1);
609
+ checked.push({ url: node.url, operator: node.operator, state: "ok", height: info.height });
610
+ try {
611
+ const found = await locateInSlices(node, {
612
+ expectedAtomic, address: request.address, viewSecret, spendPub, fromHeight, toHeight: top,
613
+ nowSec, network, fetchImpl, timeoutMs,
614
+ });
615
+ completed = completed || found.completed;
616
+ if (found.located && (!located || found.located.score > located.score)) {
617
+ located = found.located;
618
+ located.operator = node.operator;
619
+ located.url = node.url;
620
+ }
621
+ } catch (error) {
622
+ failed.push(failureOf(error, node));
623
+ }
624
+ }
625
+
626
+ const witness = located
627
+ ? { state: "seen", txid: located.txid, height: located.height, blockHash: located.blockHash,
628
+ amountAtomic: located.amountAtomic.toString(), operator: located.operator, url: located.url, completed, checked, failed }
629
+ : { state: "pending", txid: null, height: null, blockHash: null, amountAtomic: null, completed, checked, failed };
630
+
631
+ const problems = [];
632
+ let agrees = null;
633
+ if (exactError) problems.push("exact:" + exactError.code);
634
+ if (located && exact && exact.txid) {
635
+ if (String(exact.txid).toLowerCase() !== located.txid) problems.push("txid");
636
+ if (Number(exact.height) !== located.height) problems.push("height");
637
+ if (String(exact.blockHash || "").toLowerCase() !== located.blockHash) problems.push("blockHash");
638
+ if (String(exact.amountAtomic ?? "") !== located.amountAtomic.toString()) problems.push("amount");
639
+ agrees = problems.length === 0;
640
+ } else if (located) {
641
+ problems.push("exact:no-transaction");
642
+ agrees = false;
643
+ } else if (exact && exact.absent === true) {
644
+ // ABSENCE NEEDS THE WHOLE SLICE WALK, NOT A SILENT WITNESS. A server that is down, stale or answered a
645
+ // partial slice has not shown that the money is absent; its missing answer must not become agreement.
646
+ if (witness.completed && witness.failed.length === 0) agrees = true;
647
+ else {
648
+ agrees = false;
649
+ problems.push("witness:not-completed");
650
+ }
651
+ }
652
+ return { exact, exactError, witness, agrees, problems };
653
+ }
654
+
359
655
  /**
360
656
  * IS THERE STILL TIME FOR THE CONFIRMATIONS? Ten confirmations of Monero are about twenty minutes, and the ready
361
657
  * deadline does not move. If less than that is left, the client must NAME it and not start - waiting silently would
362
658
  * start a trade that cannot be finished in time. Returns seconds left; refuses with `xmr-too-late` otherwise.
363
659
  */
364
- export function assertTimeForConfirmations({ readyBySec, nowSec, minConfirmations, blockTimeSec } = {}) {
660
+ export function assertTimeForConfirmations({ readyBySec, nowSec, minConfirmations, blockTimeSec, minLeadSec = null } = {}) {
365
661
  const readyBy = Number(readyBySec);
366
662
  const now = Number.isFinite(Number(nowSec)) ? Number(nowSec) : Math.floor(Date.now() / 1000);
367
663
  const count = Math.max(1, intOf(minConfirmations) ?? 1);
368
664
  const block = Number.isFinite(Number(blockTimeSec)) && Number(blockTimeSec) > 0 ? Number(blockTimeSec) : 120;
369
665
  if (!Number.isFinite(readyBy) || readyBy <= 0) return null; // no deadline known - nothing to compare against
370
- const needSec = count * block;
666
+ // THE NODE'S LEAD WINS WHEN IT IS LONGER. A maker that advertises a 2400 s minimum cannot be paid in the old
667
+ // 1200 s; the client uses the longer of the two so its own confirmations and the maker's settlement both fit.
668
+ const nodeLead = Number.isFinite(Number(minLeadSec)) && Number(minLeadSec) > 0 ? Number(minLeadSec) : 0;
669
+ const needSec = Math.max(count * block, nodeLead);
371
670
  const leftSec = Math.floor(readyBy - now);
372
671
  if (leftSec < needSec) throw new SdkError("xmr-too-late", { needSec, leftSec, minConfirmations: count, readyBy: Math.floor(readyBy) });
373
672
  return leftSec;