@ninsei-labs/sdk 0.55.4 → 0.57.2

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 (68) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +51 -24
  4. package/THIRD_PARTY_NOTICES.md +174 -0
  5. package/assets/vendors/MANIFEST.json +18 -0
  6. package/assets/vendors/sdk/sdk-browser.js +2059 -2
  7. package/engine/atomic/dleq2.js +187 -22
  8. package/engine/atomic/order.js +21 -3
  9. package/engine/core/config.js +17 -24
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/store.js +25 -4
  12. package/engine/core/swap.js +54 -52
  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 +24 -26
  17. package/engine/evm/funding.js +8 -3
  18. package/engine/evm/index.js +2 -4
  19. package/engine/evm/session.js +3 -3
  20. package/engine/monero/scan.js +101 -22
  21. package/engine/recovery/restore.js +8 -8
  22. package/engine/sdk/bridge.js +3 -6
  23. package/index.d.ts +57 -27
  24. package/package.json +25 -8
  25. package/src/actions.mjs +52 -9
  26. package/src/adapters/evm-wallet.mjs +24 -5
  27. package/src/adapters/index.d.ts +66 -0
  28. package/src/adapters/index.mjs +0 -6
  29. package/src/codes.mjs +14 -0
  30. package/src/config.mjs +1 -0
  31. package/src/engine.mjs +6 -6
  32. package/src/feeEstimate.mjs +11 -4
  33. package/src/http.mjs +4 -1
  34. package/src/index.mjs +4 -3
  35. package/src/legs/kyber.mjs +23 -0
  36. package/src/lock.mjs +2 -1
  37. package/src/order.mjs +108 -20
  38. package/src/primitives.mjs +4 -5
  39. package/src/probes.mjs +9 -3
  40. package/src/provider/envFile.mjs +11 -1
  41. package/src/public/networks.d.ts +45 -0
  42. package/src/public/networks.mjs +10 -1
  43. package/src/public/order.d.ts +4 -0
  44. package/src/public/recovery.d.ts +40 -54
  45. package/src/public/recovery.mjs +2 -8
  46. package/src/public/xmr.d.ts +14 -3
  47. package/src/public/xmr.mjs +1 -1
  48. package/src/quoteEip712Spec.mjs +9 -1
  49. package/src/quotes.mjs +118 -49
  50. package/src/record.mjs +3 -3
  51. package/src/recovery-key.mjs +161 -237
  52. package/src/relayFeatures.mjs +25 -13
  53. package/src/relayFirmClient.mjs +69 -6
  54. package/src/relayQuote.mjs +87 -10
  55. package/src/relayRequest.mjs +12 -3
  56. package/src/relayView.mjs +3 -3
  57. package/src/swap-flow.mjs +153 -67
  58. package/src/swaps.mjs +346 -174
  59. package/src/sweep-restore.mjs +14 -6
  60. package/src/sweep.mjs +34 -11
  61. package/src/version.mjs +1 -1
  62. package/src/xmr-arrival.mjs +55 -24
  63. package/assets/vendors/atomic/atomic-browser.js +0 -24
  64. package/engine/atomic/order-client.js +0 -56
  65. package/engine/atomic/order-worker.js +0 -156
  66. package/engine/evm/asyncExec.js +0 -577
  67. package/engine/evm/asyncLegs.js +0 -308
  68. package/src/adapters/node-test-evm-wallet.mjs +0 -357
@@ -3,14 +3,31 @@
3
3
  // Everything below this header is identical to the source.
4
4
 
5
5
  // DLEQ ACROSS CURVES: a proof that one scalar stands behind points on secp256k1 and ed25519.
6
- // Ported from go-dleq (prove.go, verify.go) to @noble/curves.
6
+ // Ported from go-dleq (prove.go, verify.go) to @noble/curves. The upstream project is
7
+ // github.com/athanorlabs/go-dleq at d6fd7c03e213683cbb286d4d5bbba1c7e7e1cfe1 and is licensed LGPL-3.0-only; see
8
+ // THIRD_PARTY_NOTICES.md. This file is distributed under LGPL-3.0-only; the rest of the package remains MIT.
7
9
  // THE CHALLENGE IS COMPUTED AS IN THE ORIGINAL: SHA3-512 and WIDE REDUCTION. The old edition used keccak256
8
10
  // (32 bytes) reduced mod the order, which was BIASED (~2^-128) and differed from the reference; named by the
9
11
  // audit and closed here. Now: a 64-byte hash, read LEAST-SIGNIFICANT first and reduced mod the order, exactly
10
12
  // what ed25519 HashToScalar does. CONSEQUENCE: old proofs do not verify, so the context version was raised
11
13
  // (ninsei-order-v3), else a live quote with an old proof would break silently.
12
- // STRICT SUBGROUP CHECK. ed25519 has cofactor 8, so a point may carry a small-order component; the check
13
- // "multiply by 8 is non-zero" lets it through and makes the equalities degenerate. We check strictly: [l]*P = 0.
14
+ // BOTH CURVES READ LITTLE-ENDIAN BY DECISION. That matches ed25519 in the reference; go-dleq's secp256k1 side
15
+ // reads big-endian. Security is neutral (either endianness gives a uniform challenge), but the wire forms differ.
16
+ // THE BIT COUNT IS 253, NOT THE REFERENCE'S 252. 253 is bitlen(l), the smaller of the two orders. The reference
17
+ // uses a conservative 252 for ed25519; it rejects witnesses in [2^252, 2^253), which Ninsei accepts. Honest halves
18
+ // are below l < 2^253, so the ranges agree; vector kat-05 pins the boundary.
19
+ // KNOWLEDGE PROOFS CLOSE THE PURE-MULTIPLE GAP. The bit proof only proves that the G-components share x. Without
20
+ // a Schnorr proof of knowledge per curve, a counterparty could quote X = x*G + rho*H: the bit proof still
21
+ // verifies, but the on-chain reveal needs rho*log(H), so the order locks up. `pokA`/`pokB` prove X = x*G for each
22
+ // curve and are checked before the 253 bit parts. This is the guard MRL-0010 derivatives add.
23
+ // STRICT SUBGROUP CHECK. ed25519 has cofactor 8, so a point may carry a small-order component. [8]*P != 0 was the
24
+ // old test; it rejected a purely small-order point but not a point with a small component. [l]*P = 0 pins every
25
+ // intermediate equation to the prime-order subgroup. This is canonical-form enforcement and defense-in-depth,
26
+ // not the soundness fix: the review could not construct an accepting torsion proof even without it.
27
+ // N3: UNCOMPRESSED secp256k1 POINTS (65-byte 04||x||y) ARE ACCEPTED. The point parser canonicalises them to the
28
+ // compressed form before the challenge, so the transcript is the same; this is leniency, not a second encoding.
29
+ // N4: SCALARS AT OR ABOVE THE ORDER ARE REDUCED HERE, NOT REFUSED, matching the reference. The relay spec 12.10
30
+ // is stricter and refuses them on the wire; this verifier still accepts a reduced residue from an older vector.
14
31
  // IMPORTANT: the primitives are audited (@noble/curves), THIS implementation is not.
15
32
  //
16
33
  //
@@ -63,15 +80,16 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
63
80
  };
64
81
  const enc = (x) => (typeof x === "string" ? x : x.toHex ? x.toHex() : String(x));
65
82
  function hexBytes(h) {
66
- const s = h.replace(/^0x/, "");
83
+ const s = h.replace(/^0x/i, "");
67
84
  const out = new Uint8Array(s.length / 2);
68
85
  for (let i = 0; i < out.length; i++) out[i] = parseInt(s.substr(i * 2, 2), 16);
69
86
  return out;
70
87
  }
71
88
  const bigToHex = (v) => v.toString(16).padStart(64, "0");
72
89
  function bytesToBig(b) { let v = 0n; for (const x of b) v = (v << 8n) | BigInt(x); return v; }
73
- // READ LEAST-SIGNIFICANT FIRST, as ed25519 in the reference. Not style: the reverse order gives a different
74
- // challenge and the proof would not match the other side.
90
+ // READ LEAST-SIGNIFICANT FIRST FOR BOTH CURVES BY DECISION. This is ed25519's order in the reference; go-dleq
91
+ // reduces secp256k1 big-endian. Either choice is uniform and secure; the difference is wire compatibility, not
92
+ // soundness. The prover and verifier here use the same rule, so a Ninsei proof is self-consistent.
75
93
  function bytesToBigLE(b) { let v = 0n; for (let i = b.length - 1; i >= 0; i--) v = (v << 8n) | BigInt(b[i]); return v; }
76
94
  function concat(parts) {
77
95
  const t = parts.reduce((s, p) => s + p.length, 0), out = new Uint8Array(t);
@@ -122,8 +140,23 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
122
140
  const encP = (p) => hexBytes(p.toHex());
123
141
  const encS = (s) => hexBytes(bigToHex(s));
124
142
 
143
+ // THE SAME WORK, TWO WAYS TO DRAIN IT. The synchronous entry points drain the iterator immediately; the
144
+ // chunked entry points await between steps so a browser can paint. There is one implementation of the
145
+ // arithmetic, not a second "async" copy of it.
146
+ function drain(iterator) {
147
+ let step = iterator.next();
148
+ while (!step.done) step = iterator.next();
149
+ return step.value;
150
+ }
151
+ const nextTurn = async (yieldTo) => {
152
+ if (typeof yieldTo === "function") return await yieldTo();
153
+ if (globalThis.scheduler && typeof globalThis.scheduler.yield === "function") return await globalThis.scheduler.yield();
154
+ return await new Promise((resolve) => setTimeout(resolve, 0));
155
+ };
156
+
125
157
  // Per-bit commitments: C_i = b_i*G + r_i*G', with sum(r_i*2^i) = 0, so sum(C_i*2^i) = x*G.
126
- function commitments(curve, x) {
158
+ // The iterator yields after every bit; the chunked caller decides how many yields make one turn.
159
+ function* commitmentsSteps(curve, x) {
127
160
  const rs = [], cs = [];
128
161
  let sum = 0n, pow = 1n;
129
162
  for (let i = 0; i < BITS; i++) {
@@ -137,20 +170,26 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
137
170
  }
138
171
  const b = bit(x, i);
139
172
  cs.push(addP(mul(curve, b), mul(curve, rs[i], curve.Galt)));
173
+ yield i + 1;
140
174
  }
141
175
  return { rs, cs };
142
176
  }
177
+ function commitments(curve, x) { return drain(commitmentsSteps(curve, x)); }
143
178
  function modInv(a, m) {
144
179
  let [old_r, r] = [a % m, m], [old_s, s] = [1n, 0n];
145
180
  while (r !== 0n) { const q = old_r / r; [old_r, r] = [r, old_r - q * r]; [old_s, s] = [s, old_s - q * s]; }
146
181
  if (old_r !== 1n) throw new Error("modInv: not invertible");
147
182
  return ((old_s % m) + m) % m;
148
183
  }
149
- function sumCommitments(curve, cs) {
184
+ function* sumCommitmentsSteps(curve, cs) {
150
185
  let sum = cs[0];
151
- for (let i = 1; i < cs.length; i++) sum = addP(sum, mul(curve, 2n ** BigInt(i) % curve.order, cs[i]));
186
+ for (let i = 1; i < cs.length; i++) {
187
+ sum = addP(sum, mul(curve, 2n ** BigInt(i) % curve.order, cs[i]));
188
+ yield { phase: "sum", done: i, total: cs.length };
189
+ }
152
190
  return sum;
153
191
  }
192
+ function sumCommitments(curve, cs) { return drain(sumCommitmentsSteps(curve, cs)); }
154
193
 
155
194
  // OR proof "commitment to 0 or to 1" for one bit, on both curves at once.
156
195
  //
@@ -182,12 +221,44 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
182
221
  // Scalars go to hex: the proof must survive JSON and the thread boundary.
183
222
  const sigOut = (s) => ({ eA: bigToHex(s.eA), eB: bigToHex(s.eB), a0: bigToHex(s.a0), a1: bigToHex(s.a1), b0: bigToHex(s.b0), b1: bigToHex(s.b1) });
184
223
 
185
- // STEP 1. PREPARATION. Computed SEQUENTIALLY and whole: commitments depend on the running sum, so this step is
186
- // not split. Per-bit data is prepared here - exactly what step 2 needs: the bit, its commitments and its
187
- // randomness. THE HALF IS NO LONGER HERE, and that is the key property.
188
- function prepareProof(x, context) {
224
+ // SCHNORR PROOF OF KNOWLEDGE, ONE PER CURVE. The bit proof proves only that the G-components of XA and XB
225
+ // share x; it does not prove that either point is a pure multiple of G. A prover can put rho*H into X, adjust
226
+ // the last blinder, and still satisfy every bit equation. This proof closes that gap: it shows X = x*G, so a
227
+ // H-component cannot hide in the claimed point. The challenge binds the context, the point and the nonce point;
228
+ // a proof made for another order or another curve does not verify.
229
+ function knowledgeProof(curve, x, X, context, label) {
230
+ const k = randScalar(curve);
231
+ const R = mul(curve, k);
232
+ const e = challenge(curve, [ctxUtf8(context), ctxUtf8("ninsei-dleq-pok|" + label), encP(X), encP(R)]);
233
+ return { R: enc(R), s: bigToHex((k + e * x) % curve.order) };
234
+ }
235
+ function verifyKnowledge(curve, X, pok, context, label) {
236
+ if (!pok || typeof pok !== "object") return false;
237
+ if (typeof pok.R !== "string" || typeof pok.s !== "string") return false;
238
+ let R, s;
239
+ try {
240
+ R = curve.P.fromHex(pok.R.replace(/^0x/i, ""));
241
+ s = BigInt(String(pok.s).startsWith("0X") ? "0x" + String(pok.s).slice(2) : String(pok.s).startsWith("0x") ? pok.s : "0x" + pok.s);
242
+ } catch { return false; }
243
+ const e = challenge(curve, [ctxUtf8(context), ctxUtf8("ninsei-dleq-pok|" + label), encP(X), encP(R)]);
244
+ return mul(curve, s).equals(addP(R, mPublic(curve, X, e)));
245
+ }
246
+
247
+ // STEP 1. PREPARATION. The commitments depend on the running sum, so the order of the arithmetic is fixed;
248
+ // the iterator yields between bits, which is enough for the chunked caller to keep the page alive. Per-bit
249
+ // data is prepared here - exactly what step 2 needs: the bit, its commitments and its randomness. THE HALF IS
250
+ // NO LONGER HERE, and that is the key property.
251
+ function* prepareProofSteps(x, context) {
252
+ x = typeof x === "bigint" ? x : BigInt(x);
189
253
  const XA = mul(curves.A, x), XB = mul(curves.B, x);
190
- const cA = commitments(curves.A, x), cB = commitments(curves.B, x);
254
+ yield { phase: "prepare", done: 0, total: BITS };
255
+ const itA = commitmentsSteps(curves.A, x), itB = commitmentsSteps(curves.B, x);
256
+ for (let i = 0; i < BITS; i++) {
257
+ const a = itA.next(), b = itB.next();
258
+ if (a.done || b.done) throw new Error("prepareProof: commitments ended early");
259
+ yield { phase: "prepare", done: i + 1, total: BITS };
260
+ }
261
+ const cA = itA.next().value, cB = itB.next().value;
191
262
  const bits = [];
192
263
  for (let i = 0; i < BITS; i++) {
193
264
  bits.push({
@@ -197,7 +268,27 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
197
268
  rA: bigToHex(cA.rs[i]), rB: bigToHex(cB.rs[i]),
198
269
  });
199
270
  }
200
- return { XA: enc(XA), XB: enc(XB), context: String(context == null ? "" : context), bits };
271
+ yield { phase: "know", done: BITS, total: BITS };
272
+ return {
273
+ XA: enc(XA), XB: enc(XB), context: String(context == null ? "" : context),
274
+ pokA: knowledgeProof(curves.A, x, XA, context, "A"),
275
+ pokB: knowledgeProof(curves.B, x, XB, context, "B"),
276
+ bits,
277
+ };
278
+ }
279
+ function prepareProof(x, context) { return drain(prepareProofSteps(x, context)); }
280
+ async function prepareProofChunked(x, context, options = {}) {
281
+ const chunkBits = Number.isSafeInteger(options.chunkBits) && options.chunkBits > 0
282
+ ? Math.min(options.chunkBits, BITS) : 8;
283
+ const it = prepareProofSteps(x, context);
284
+ let seen = 0;
285
+ for (;;) {
286
+ const step = it.next();
287
+ if (step.done) return step.value;
288
+ seen += 1;
289
+ if (typeof options.onPrepare === "function") options.onPrepare(step.value);
290
+ if (seen % chunkBits === 0) await nextTurn(options.yieldTo);
291
+ }
201
292
  }
202
293
 
203
294
  // STEP 2. PROVE ONE BIT. Called on the prepared data, self-contained, knowing neither the half nor other bits.
@@ -221,7 +312,7 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
221
312
  if (!item) throw new Error("assembleProof: no part for bit " + i);
222
313
  proofs.push({ cA: item.cA, cB: item.cB, sig: item.sig });
223
314
  }
224
- return { XA: prepared.XA, XB: prepared.XB, proofs };
315
+ return { XA: prepared.XA, XB: prepared.XB, pokA: prepared.pokA, pokB: prepared.pokB, proofs };
225
316
  }
226
317
 
227
318
  // prove REMAINS THE SAME FUNCTION, assembled from the same three steps: no second implementation appeared.
@@ -237,6 +328,29 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
237
328
  return assembleProof(prepared, parts);
238
329
  }
239
330
 
331
+ // THE CHUNKED PROOF IS THE SAME PROOF, WITH TURNS. Preparation and every bit come from the iterators above;
332
+ // this function only decides when to give the event loop a chance to paint. The page stays responsive while
333
+ // the arithmetic is still the one implementation.
334
+ async function proveChunked(x, context, options = {}) {
335
+ const chunkBits = Number.isSafeInteger(options.chunkBits) && options.chunkBits > 0
336
+ ? Math.min(options.chunkBits, BITS) : 4;
337
+ const prepared = await prepareProofChunked(x, context, {
338
+ chunkBits: Number.isSafeInteger(options.prepareChunkBits) && options.prepareChunkBits > 0
339
+ ? options.prepareChunkBits : 8,
340
+ yieldTo: options.yieldTo,
341
+ onPrepare: options.onPrepare,
342
+ });
343
+ const parts = [];
344
+ for (let i = 0; i < BITS; i++) {
345
+ parts.push(proveBit(prepared.bits[i], prepared.context));
346
+ if ((i + 1) % chunkBits === 0 || i === BITS - 1) {
347
+ if (typeof options.onBit === "function") options.onBit(i + 1, BITS);
348
+ await nextTurn(options.yieldTo);
349
+ }
350
+ }
351
+ return assembleProof(prepared, parts);
352
+ }
353
+
240
354
  // STRICT SUBGROUP CHECK, NOT JUST SMALL ORDER. The old edition checked [8]*P != 0: it rejected a purely
241
355
  // small-order point but let a point with a small COMPONENT through, so a degenerate equality passed. Strict:
242
356
  // [l]*P = 0. secp256k1 is not checked: cofactor 1, the whole group is prime order.
@@ -250,19 +364,38 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
250
364
  // FORM IS CHECKED BEFORE COUNTING. The old loop ran over the received list length: a short proof proved
251
365
  // ANOTHER representation, a long one burned check time. An honest path always sends exactly BITS parts. An
252
366
  // unparsable field returns a refusal, not an exception: the caller must get {ok:false}, not crash.
253
- function verify(proof, context) {
367
+ function* verifySteps(proof, context, options = {}) {
254
368
  if (!proof || typeof proof !== "object") return { ok: false, reason: "proof: an object is expected" };
255
369
  if (typeof proof.XA !== "string" || typeof proof.XB !== "string") return { ok: false, reason: "proof: no XA or XB" };
256
370
  if (!Array.isArray(proof.proofs)) return { ok: false, reason: "proof: no parts list" };
257
371
  if (proof.proofs.length !== BITS) return { ok: false, reason: "proof: " + proof.proofs.length + " parts, expected " + BITS };
258
- const P = (curve, h) => curve.P.fromHex(String(h).replace(/^0x/, ""));
372
+ const requireKnowledge = options.requireKnowledge !== false;
373
+ const P = (curve, h) => curve.P.fromHex(String(h).replace(/^0x/i, ""));
259
374
  let XA, XB, csA, csB;
260
375
  try {
261
376
  XA = P(curves.A, proof.XA); XB = P(curves.B, proof.XB);
377
+ // THE SUBJECT MUST NOT BE THE EDWARDS IDENTITY. A proof of the identity can be manufactured without
378
+ // contributing a half, and the joint spend point would silently lose this side; Monero/relay spec 12.10
379
+ // forbids it. The secp256k1 side needs no separate branch: @noble refuses the point-at-infinity encoding, so
380
+ // an XA identity is refused as unparsable before this check.
381
+ if (XB.equals(curves.B.P.ZERO)) {
382
+ return { ok: false, reason: "proof: the subject point is the identity" };
383
+ }
262
384
  if (!torsionFree(curves.B, XB)) return { ok: false, reason: "proof: XB is not in the prime-order subgroup" };
263
385
  } catch (e) {
264
386
  return { ok: false, reason: "proof: XA or XB is unparsable (" + String((e && e.message) || e) + ")" };
265
387
  }
388
+ // THE PURE-MULTIPLE GUARD COMES BEFORE THE BIT LOOP. It is optional only so old vectors can still be checked
389
+ // as historical artifacts; every proof produced by this module carries both fields and SDK callers require
390
+ // them. A missing or tampered `pokA`/`pokB` is a refusal, never a skipped check.
391
+ if (requireKnowledge) {
392
+ try {
393
+ if (!verifyKnowledge(curves.A, XA, proof.pokA, context, "A")) return { ok: false, reason: "proof: the secp256k1 knowledge proof did not verify" };
394
+ if (!verifyKnowledge(curves.B, XB, proof.pokB, context, "B")) return { ok: false, reason: "proof: the ed25519 knowledge proof did not verify" };
395
+ } catch (e) {
396
+ return { ok: false, reason: "proof: the knowledge proof is unparsable (" + String((e && e.message) || e) + ")" };
397
+ }
398
+ }
266
399
  // THE BIT NUMBER IS NAMED HERE TOO: without it, "somewhere in the proof" is indistinguishable from any of
267
400
  // the 253 commitments being corrupt.
268
401
  try {
@@ -275,14 +408,23 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
275
408
  } catch (e) {
276
409
  return { ok: false, reason: "proof: " + String((e && e.message) || e) };
277
410
  }
278
- if (!sumCommitments(curves.A, csA).equals(XA)) return { ok: false, reason: "the commitment sum does not give X on secp256k1" };
279
- if (!sumCommitments(curves.B, csB).equals(XB)) return { ok: false, reason: "the commitment sum does not give X on ed25519" };
411
+ const sumA = yield* sumCommitmentsSteps(curves.A, csA);
412
+ if (!sumA.equals(XA)) return { ok: false, reason: "the commitment sum does not give X on secp256k1" };
413
+ const sumB = yield* sumCommitmentsSteps(curves.B, csB);
414
+ if (!sumB.equals(XB)) return { ok: false, reason: "the commitment sum does not give X on ed25519" };
280
415
  for (let i = 0; i < proof.proofs.length; i++) {
281
416
  const item = proof.proofs[i];
282
417
  try {
283
418
  if (!torsionFree(curves.B, csB[i])) return { ok: false, reason: "bit " + i + ": the commitment is not in the prime-order subgroup" };
284
419
  const cA = item.cA, cB = item.cB;
285
- const sig = Object.fromEntries(Object.entries(item.sig).map(([k, v]) => [k, BigInt(String(v).startsWith("0x") ? v : "0x" + v)]));
420
+ // ONLY THE SIX PROTOCOL SCALARS ARE READ. Unknown fields in `sig` are ignored (N2), and a missing one
421
+ // still refuses: Object.entries would try to parse an unknown key as a scalar and throw.
422
+ const sig = {};
423
+ for (const k of ["eA", "eB", "a0", "a1", "b0", "b1"]) {
424
+ const v = item.sig[k];
425
+ const text = String(v);
426
+ sig[k] = BigInt(/^0x/i.test(text) ? text : "0x" + text);
427
+ }
286
428
  const pA = P(curves.A, cA), pB = P(curves.B, cB);
287
429
  const pre = (q1, q2) => [ctxUtf8(context), encP(pA), encP(pB), encP(q1), encP(q2)];
288
430
  const aG = mul(curves.A, sig.a1, curves.A.Galt), eCA = mPublic(curves.A, pA, sig.eA);
@@ -297,9 +439,32 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
297
439
  } catch (e) {
298
440
  return { ok: false, reason: "bit " + i + ": fields are unparsable (" + String((e && e.message) || e) + ")" };
299
441
  }
442
+ yield { phase: "verify", done: i + 1, total: proof.proofs.length };
300
443
  }
301
444
  return { ok: true };
302
445
  }
446
+ function verify(proof, context, options = {}) { return drain(verifySteps(proof, context, options)); }
303
447
 
304
- return { BITS, curves, prove, verify, prepareProof, proveBit, assembleProof, torsionFree };
448
+ // THE CHUNKED VERIFIER IS THE SAME VERIFIER, WITH TURNS. The sum and the bit loop are the expensive parts;
449
+ // the phase-aware chunk keeps the browser paint budget without adding a second verification path.
450
+ async function verifyChunked(proof, context, options = {}) {
451
+ const it = verifySteps(proof, context, options);
452
+ let phase = null, count = 0;
453
+ for (;;) {
454
+ const step = it.next();
455
+ if (step.done) return step.value;
456
+ const nextPhase = step.value && step.value.phase ? step.value.phase : null;
457
+ if (nextPhase !== phase) { phase = nextPhase; count = 0; }
458
+ count += 1;
459
+ if (typeof options.onProgress === "function") options.onProgress(step.value);
460
+ // VERIFY CHUNKS ARE SHORTER THAN PROOF CHUNKS: one verification step is more expensive than one
461
+ // proof bit, and a 50 ms turn is already visible as a stutter. The caller can raise it when it has a
462
+ // larger budget; the default keeps the page within a frame or two.
463
+ const every = phase === "sum" ? 16
464
+ : (Number.isSafeInteger(options.verifyChunkBits) && options.verifyChunkBits > 0
465
+ ? Math.min(options.verifyChunkBits, BITS) : 2);
466
+ if (count % every === 0) await nextTurn(options.yieldTo);
467
+ }
468
+ }
469
+ return { BITS, curves, prove, proveChunked, verify, verifyChunked, prepareProof, prepareProofChunked, proveBit, assembleProof, torsionFree };
305
470
  }
@@ -42,13 +42,24 @@ export function createOrderBuilder({ ed25519, secp256k1, keccak256, sha3_512, ra
42
42
  return { half, pub, viewHalf, viewPub, enc: encPair, proof, standIn };
43
43
  }
44
44
 
45
+ // THE CHUNKED SIDE IS THE SAME SIDE, WITH TURNS. The halves and the encryption key are cheap; only the DLEQ
46
+ // proof is chunked, through the same generator the synchronous path drains.
47
+ async function newSideChunked(orderContext, standIn = false, options = {}) {
48
+ const half = halves.newHalf();
49
+ const pub = halves.publicHalves(half);
50
+ const viewHalf = halves.newHalf();
51
+ const viewPub = halves.publicHalves(viewHalf).ed;
52
+ const encPair = enc.recipientKeyPair();
53
+ const proof = await dleq.proveChunked(half, orderContext, options);
54
+ return { half, pub, viewHalf, viewPub, enc: encPair, proof, standIn };
55
+ }
56
+
45
57
  // Checking the counterparty side IS conditions (1) and (2): its proof, and - if an envelope is given - opening
46
58
  // ITS envelope with OUR private key and verifying against ITS public point.
47
59
  //
48
60
  // KEY ROLES ARE FUNDAMENTAL HERE, and the first version mixed them up: it opened the envelope with the
49
61
  // counterparty's own key (which we do not have - the envelope is addressed to them). That check could never pass.
50
- function verifySide(side, orderContext, sealedPayloadBytes, ownEncPriv) {
51
- const proofOk = dleq.verify(side.proof, orderContext);
62
+ function verifySideAfterProof(side, orderContext, sealedPayloadBytes, ownEncPriv, proofOk) {
52
63
  if (!proofOk.ok) return { ok: false, reason: "counterparty DLEQ failed: " + proofOk.reason };
53
64
  // THE PROVEN POINT MUST BE THE ONE THAT GOES INTO THE ORDER, and this check was missing. A proof confirms that
54
65
  // ONE scalar stands behind a pair of points, but not that the proven ed25519 point is the one the joint address
@@ -90,6 +101,13 @@ export function createOrderBuilder({ ed25519, secp256k1, keccak256, sha3_512, ra
90
101
  }
91
102
  return { ok: true };
92
103
  }
104
+ function verifySide(side, orderContext, sealedPayloadBytes, ownEncPriv) {
105
+ return verifySideAfterProof(side, orderContext, sealedPayloadBytes, ownEncPriv, dleq.verify(side.proof, orderContext));
106
+ }
107
+ async function verifySideChunked(side, orderContext, sealedPayloadBytes, ownEncPriv, options = {}) {
108
+ const proofOk = await dleq.verifyChunked(side.proof, orderContext, options);
109
+ return verifySideAfterProof(side, orderContext, sealedPayloadBytes, ownEncPriv, proofOk);
110
+ }
93
111
 
94
112
  // The envelope with our half, encrypted to the counterparty key: what goes to them and to the contract.
95
113
  function sealFor(counterparty, ownHalf, orderContext) {
@@ -134,5 +152,5 @@ export function createOrderBuilder({ ed25519, secp256k1, keccak256, sha3_512, ra
134
152
  });
135
153
  }
136
154
 
137
- return { halves, dleq, enc, newSide, verifySide, sealFor, openFrom, jointAddressPoint, pointOf, jointAddress, halfCommitment };
155
+ return { halves, dleq, enc, newSide, newSideChunked, verifySide, verifySideChunked, sealFor, openFrom, jointAddressPoint, pointOf, jointAddress, halfCommitment };
138
156
  }
@@ -2,6 +2,9 @@
2
2
  // Edit the source under www/js and regenerate the mirror; a drift guard reddens on any difference.
3
3
  // Everything below this header is identical to the source.
4
4
 
5
+ // VM-neutral deployment pins generated from deployments/<vm>/<network>.json. No address table is copied below.
6
+ import { DEPLOYMENTS, DEPLOYMENT_CHAINS, DEPLOYMENT_VMS, deploymentFor } from "./deployments.generated.js";
7
+
5
8
  // Demo configuration. Every number a user sees lives here. Values come from the litepaper and are marked as demo data in the UI.
6
9
  //
7
10
  // Networks and tokens are one CHAINS structure: each network has its own native token, its own accepted tokens and
@@ -363,22 +366,10 @@ export const CHAINS = [
363
366
  explorerName: "arbiscan (sepolia)",
364
367
  gasUsd: 0.01,
365
368
  routeType: "atomic",
366
- // THE DEMO'S MAIN NETWORK: the Ninsei escrow factory and the interface's fee cashier live here. The next
367
- // contract version (contracts-testnet-2026.10.26) is a FACT, not an intention:
368
- // factory 0x69b5a6878b542960af4d239ecc60ad1c9e3e6932 (height 323014007,
369
- // transaction 0xbe8244da0cb1429edc92d18c7c8b5ba1c6b17c42a5806609d930a6496e918408);
370
- // cashier 0x05b7433f66f2b75cc7ece9ec00af0fb810f9c9e0;
371
- // registry 0x4707a6684b654fbd74372ec624efc0f825af0537 (this release deploys it);
372
- // implementation 0x2E0214c6242fB794a4cC861D609Ecee544735170, codehash
373
- // 0xc6cde36301b6551a6ca8bd2c47fbd5ffd01ffcdf22d2f6909be2b3b2dcf360b4.
374
- // `OrderCreated` now carries xmrAmount; the SDK reads it from the event and keeps the clone fallback for the
375
- // previous event. PREVIOUS factory before this version: 0x3eE25f12758ec28e5b3045d16132D89Cd0bf341F
376
- // (height 321430239, cashier 0x1123A3875775Da25FA181Af0d91EB278E94a5dfb).
377
- // mode: "live" - order creation TOGETHER WITH THE MONEY in one transaction (createOrderAndFund). cashier: the
378
- // INTERFACE's fee cashier, named in quotes. implementationCodeHash: the escrow implementation the factory
379
- // carries, checked against the chain. deploymentBlock: the height the factory was created at; a log search for
380
- // its orders starts here, not at zero, because public RPCs cap a log query at about 10M blocks.
381
- escrow: { address: "0x69b5a6878b542960af4d239ecc60ad1c9e3e6932", mode: "live", deploymentBlock: 323014007, cashier: "0x05b7433f66f2b75cc7ece9ec00af0fb810f9c9e0", implementationCodeHash: "0xc6cde36301b6551a6ca8bd2c47fbd5ffd01ffcdf22d2f6909be2b3b2dcf360b4" },
369
+ // THE DEPLOYMENT PIN COMES FROM deployments/evm/<network>.json, generated into deployments.generated.js.
370
+ // A redeploy changes that manifest, not this file: address, cashier, registry, implementation code hash
371
+ // and the factory's birth block all move together.
372
+ escrow: deploymentFor("arbitrum-sepolia").escrow,
382
373
  tokens: [
383
374
  // Test USDC (Circle): decimals 6 and symbol "USDC" verified on chain by the same node.
384
375
  { symbol: "USDC", address: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d", decimals: 6, usd: 1, cls: "ar-token-usdc" },
@@ -795,13 +786,15 @@ export function allowedProvidersFor(chainOrId) {
795
786
  // THE LIST OF KNOWN FACTORY BUILDS - INTERFACE POLICY, next to allowedProviders. The value is the extcodehash
796
787
  // (keccak256 of the code) of a factory the interface will accept: the factory comes from the PROVIDER REGISTRY
797
788
  // record, and its code is compared against this list. Empty for a network = no policy (the factory must still be
798
- // named by the record and match the signed quote). Filled at deploy: the factory has no immutables, so one build
799
- // gives the same hash to anyone who deployed it - a provider's own factory lands in the same list.
800
- export const KNOWN_FACTORY_CODES = {
801
- // contracts-testnet-2026.10.26, factory deployed at 0x69b5a6878b542960af4d239ecc60ad1c9e3e6932.
802
- // The factory has no immutables; this hash is reproducible from that release's source.
803
- "arbitrum-sepolia": ["0x4d51e943b7786be7d3f9e2c44ad0b54f82932dba12ac6fa34be5088500d6615c"],
804
- };
789
+ // named by the record and match the signed quote). Filled from the generated deployment pins, per network; a
790
+ // provider's own factory on the same build lands in the same list because the factory has no immutables.
791
+ export const KNOWN_FACTORY_CODES = Object.freeze(Object.fromEntries(
792
+ Object.values(DEPLOYMENTS)
793
+ .filter((deployment) => deployment.status === "live" && deployment.knownFactoryCodes.length > 0)
794
+ .map((deployment) => [deployment.network, [...deployment.knownFactoryCodes]]),
795
+ ));
796
+
797
+ export { DEPLOYMENTS, DEPLOYMENT_CHAINS, DEPLOYMENT_VMS, deploymentFor };
805
798
 
806
799
  export function knownFactoryCodesFor(chainOrId) {
807
800
  const id = typeof chainOrId === "string" ? chainOrId : chainOrId && chainOrId.id;
@@ -851,7 +844,7 @@ export function nativeOf(chainId) {
851
844
 
852
845
  // A network's WRAPPED native token (WETH/WBNB...), or null. It is what the liquidity leg settles (KyberSwap Limit
853
846
  // Order trades ERC20 against ERC20 and cannot deliver native) and what the native leg sells to buy native coin: the
854
- // engine's composed route (www/js/evm/asyncExec.js) turns the token into this wrapped token first, then into native.
847
+ // engine's composed route (the package provider layer) turns the token into this wrapped token first, then into native.
855
848
  export function wrappedNativeOf(chainId) {
856
849
  const c = chainById(chainId);
857
850
  return (c.tokens || []).find((t) => t && t.peg === "native") || null;
@@ -0,0 +1,103 @@
1
+ // GENERATED FILE - do not edit. Run: node tools/gen-deployment-pins.mjs --write
2
+ // Source: deployments/<vm>/<network>.json, copied from the reviewed contract release manifest.
3
+ const freeze = (value) => {
4
+ if (value && typeof value === "object") {
5
+ Object.freeze(value);
6
+ for (const child of Object.values(value)) freeze(child);
7
+ }
8
+ return value;
9
+ };
10
+
11
+ const DATA = {
12
+ "arbitrum-sepolia": {
13
+ "vm": "evm",
14
+ "network": "arbitrum-sepolia",
15
+ "caip2": "eip155:421614",
16
+ "chainRef": "421614",
17
+ "status": "live",
18
+ "release": {
19
+ "tag": "contracts-testnet-2026.11.04",
20
+ "commit": "930366a387c0c696bda6f5c038f23617447ebb78",
21
+ "toolchain": "0.8.38",
22
+ "deployedAt": "2026-11-04T15:00:55.822Z"
23
+ },
24
+ "anchor": {
25
+ "kind": "block",
26
+ "value": "326005419"
27
+ },
28
+ "artifacts": {
29
+ "factory": {
30
+ "role": "factory",
31
+ "kind": "contract",
32
+ "address": "0x245d3a4ac4b98d713f6c5130b56cd5d550f8cefe",
33
+ "addressFormat": "hex-20",
34
+ "codeHash": "0x1fdfa1c922f660506243cab4c889aa83e22ce27d818bac9c5e4ecbccbdd04906",
35
+ "hashKind": "keccak256",
36
+ "tx": {
37
+ "kind": "hash",
38
+ "value": "0xf62f54cbb0c236edc467652fce8c746c903a5d0ab4ecdd492649d57a92862296"
39
+ }
40
+ },
41
+ "cashier": {
42
+ "role": "cashier",
43
+ "kind": "contract",
44
+ "address": "0x40515449159EfbCb5eF5eB9e2E08ba432E150a1C",
45
+ "addressFormat": "hex-20",
46
+ "tx": {
47
+ "kind": "hash",
48
+ "value": "0xf62f54cbb0c236edc467652fce8c746c903a5d0ab4ecdd492649d57a92862296"
49
+ }
50
+ },
51
+ "registry": {
52
+ "role": "registry",
53
+ "kind": "contract",
54
+ "address": "0x92191dc3517e15db6468628b1a493576728a9798",
55
+ "addressFormat": "hex-20",
56
+ "tx": {
57
+ "kind": "hash",
58
+ "value": "0x8f60792dac889008ec5678c6f30790730d278518d512a3b19657829896391adf"
59
+ }
60
+ },
61
+ "implementation": {
62
+ "role": "implementation",
63
+ "kind": "contract",
64
+ "address": "0xF88658b53FcB965E580638bbFe048E8f587d6D11",
65
+ "addressFormat": "hex-20",
66
+ "codeHash": "0x7020a1017adbb4d4ce4710f7c632d48a5469a6f3076608e77d5675dee125653c",
67
+ "hashKind": "keccak256",
68
+ "tx": {
69
+ "kind": "hash",
70
+ "value": "0xf62f54cbb0c236edc467652fce8c746c903a5d0ab4ecdd492649d57a92862296"
71
+ }
72
+ }
73
+ },
74
+ "escrow": {
75
+ "address": "0x245d3a4ac4b98d713f6c5130b56cd5d550f8cefe",
76
+ "mode": "live",
77
+ "deploymentBlock": 326005419,
78
+ "cashier": "0x40515449159EfbCb5eF5eB9e2E08ba432E150a1C",
79
+ "registry": "0x92191dc3517e15db6468628b1a493576728a9798",
80
+ "implementationCodeHash": "0x7020a1017adbb4d4ce4710f7c632d48a5469a6f3076608e77d5675dee125653c"
81
+ },
82
+ "knownFactoryCodes": [
83
+ "0x1fdfa1c922f660506243cab4c889aa83e22ce27d818bac9c5e4ecbccbdd04906"
84
+ ]
85
+ }
86
+ };
87
+
88
+ export const DEPLOYMENTS = freeze(DATA);
89
+ export const DEPLOYMENT_CHAINS = freeze(Object.keys(DATA).sort());
90
+ export const DEPLOYMENT_VMS = freeze([...new Set(Object.values(DATA).map((d) => d.vm))].sort());
91
+
92
+ // Accept a network id, a CAIP-2, or an EVM chain id. No fallback to another network: an unknown deployment is null.
93
+ export function deploymentFor(chainOrId) {
94
+ if (chainOrId === null || chainOrId === undefined) return null;
95
+ const value = typeof chainOrId === "object"
96
+ ? chainOrId.id ?? chainOrId.network ?? chainOrId.caip2
97
+ : chainOrId;
98
+ if (value === null || value === undefined) return null;
99
+ if (typeof value === "number" || /^[0-9]+$/.test(String(value))) {
100
+ return Object.values(DEPLOYMENTS).find((d) => Number(d.chainRef) === Number(value)) ?? null;
101
+ }
102
+ return DEPLOYMENTS[value] ?? Object.values(DEPLOYMENTS).find((d) => d.caip2 === value) ?? null;
103
+ }
@@ -87,10 +87,10 @@ export function bindStorage(next) {
87
87
  /** What is used right now: this is visible from outside, and by this the checks tell memory from a browser. */
88
88
  export const storage = () => adapter;
89
89
 
90
- export function loadState() {
90
+ function loadStateFrom(source) {
91
91
  let raw;
92
92
  try {
93
- raw = adapter.get(APP.storageKey);
93
+ raw = source.get(APP.storageKey);
94
94
  } catch (error) {
95
95
  throw storageFailure("read", error);
96
96
  }
@@ -107,12 +107,16 @@ export function loadState() {
107
107
  return { ...structuredClone(EMPTY), ...parsed, settings: { ...EMPTY.settings, ...(parsed.settings || {}) } };
108
108
  }
109
109
 
110
+ export function loadState() {
111
+ return loadStateFrom(adapter);
112
+ }
113
+
110
114
  // BigInt IS NOT SERIALISED IN JSON - and the key halves are BigInt. JSON.stringify FAILS on them
111
115
  // ("Do not know how to serialize a BigInt", bigintSafe), and the failure looks silent: the swap record is
112
116
  // simply not saved, the recovery file is not issued, and the screen shows an address that is not on chain.
113
117
  // We turn BigInt into a hex string: the same meaning, but serialisable, and the secret is not lost.
114
118
  const bigintSafe = (key, value) => (typeof value === "bigint" ? "0x" + value.toString(16) : value);
115
- export function saveState(state) {
119
+ function saveStateTo(source, state) {
116
120
  let text;
117
121
  try {
118
122
  text = JSON.stringify(state, bigintSafe);
@@ -120,13 +124,30 @@ export function saveState(state) {
120
124
  throw storageFailure("serialize", error);
121
125
  }
122
126
  try {
123
- adapter.set(APP.storageKey, text);
127
+ source.set(APP.storageKey, text);
124
128
  } catch (error) {
125
129
  throw storageFailure("write", error);
126
130
  }
127
131
  return state;
128
132
  }
129
133
 
134
+ export function saveState(state) {
135
+ return saveStateTo(adapter, state);
136
+ }
137
+
138
+ /**
139
+ * A store bound to one adapter, without changing the module-wide one. The SDK facade uses this for each client:
140
+ * two clients with different storages must not share records, and one client must not refuse the other.
141
+ */
142
+ export function createStore(next) {
143
+ checkAdapter(next);
144
+ return {
145
+ loadState: () => loadStateFrom(next),
146
+ saveState: (state) => saveStateTo(next, state),
147
+ storage: () => next,
148
+ };
149
+ }
150
+
130
151
  export function update(mutator) {
131
152
  const s = loadState();
132
153
  const out = mutator(s) || s;