@ninsei-labs/sdk 0.55.3 → 0.56.1

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.
@@ -9,8 +9,23 @@
9
9
  // audit and closed here. Now: a 64-byte hash, read LEAST-SIGNIFICANT first and reduced mod the order, exactly
10
10
  // what ed25519 HashToScalar does. CONSEQUENCE: old proofs do not verify, so the context version was raised
11
11
  // (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.
12
+ // BOTH CURVES READ LITTLE-ENDIAN BY DECISION. That matches ed25519 in the reference; go-dleq's secp256k1 side
13
+ // reads big-endian. Security is neutral (either endianness gives a uniform challenge), but the wire forms differ.
14
+ // THE BIT COUNT IS 253, NOT THE REFERENCE'S 252. 253 is bitlen(l), the smaller of the two orders. The reference
15
+ // uses a conservative 252 for ed25519; it rejects witnesses in [2^252, 2^253), which Ninsei accepts. Honest halves
16
+ // are below l < 2^253, so the ranges agree; vector kat-05 pins the boundary.
17
+ // KNOWLEDGE PROOFS CLOSE THE PURE-MULTIPLE GAP. The bit proof only proves that the G-components share x. Without
18
+ // a Schnorr proof of knowledge per curve, a counterparty could quote X = x*G + rho*H: the bit proof still
19
+ // verifies, but the on-chain reveal needs rho*log(H), so the order locks up. `pokA`/`pokB` prove X = x*G for each
20
+ // curve and are checked before the 253 bit parts. This is the guard MRL-0010 derivatives add.
21
+ // STRICT SUBGROUP CHECK. ed25519 has cofactor 8, so a point may carry a small-order component. [8]*P != 0 was the
22
+ // old test; it rejected a purely small-order point but not a point with a small component. [l]*P = 0 pins every
23
+ // intermediate equation to the prime-order subgroup. This is canonical-form enforcement and defense-in-depth,
24
+ // not the soundness fix: the review could not construct an accepting torsion proof even without it.
25
+ // N3: UNCOMPRESSED secp256k1 POINTS (65-byte 04||x||y) ARE ACCEPTED. The point parser canonicalises them to the
26
+ // compressed form before the challenge, so the transcript is the same; this is leniency, not a second encoding.
27
+ // N4: SCALARS AT OR ABOVE THE ORDER ARE REDUCED, NOT REFUSED, matching the reference. A non-canonical sig scalar
28
+ // therefore verifies as its residue; requiring < ord would add strictness without rejecting an honest proof.
14
29
  // IMPORTANT: the primitives are audited (@noble/curves), THIS implementation is not.
15
30
  //
16
31
  //
@@ -63,15 +78,16 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
63
78
  };
64
79
  const enc = (x) => (typeof x === "string" ? x : x.toHex ? x.toHex() : String(x));
65
80
  function hexBytes(h) {
66
- const s = h.replace(/^0x/, "");
81
+ const s = h.replace(/^0x/i, "");
67
82
  const out = new Uint8Array(s.length / 2);
68
83
  for (let i = 0; i < out.length; i++) out[i] = parseInt(s.substr(i * 2, 2), 16);
69
84
  return out;
70
85
  }
71
86
  const bigToHex = (v) => v.toString(16).padStart(64, "0");
72
87
  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.
88
+ // READ LEAST-SIGNIFICANT FIRST FOR BOTH CURVES BY DECISION. This is ed25519's order in the reference; go-dleq
89
+ // reduces secp256k1 big-endian. Either choice is uniform and secure; the difference is wire compatibility, not
90
+ // soundness. The prover and verifier here use the same rule, so a Ninsei proof is self-consistent.
75
91
  function bytesToBigLE(b) { let v = 0n; for (let i = b.length - 1; i >= 0; i--) v = (v << 8n) | BigInt(b[i]); return v; }
76
92
  function concat(parts) {
77
93
  const t = parts.reduce((s, p) => s + p.length, 0), out = new Uint8Array(t);
@@ -182,10 +198,34 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
182
198
  // Scalars go to hex: the proof must survive JSON and the thread boundary.
183
199
  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
200
 
201
+ // SCHNORR PROOF OF KNOWLEDGE, ONE PER CURVE. The bit proof proves only that the G-components of XA and XB
202
+ // share x; it does not prove that either point is a pure multiple of G. A prover can put rho*H into X, adjust
203
+ // the last blinder, and still satisfy every bit equation. This proof closes that gap: it shows X = x*G, so a
204
+ // H-component cannot hide in the claimed point. The challenge binds the context, the point and the nonce point;
205
+ // a proof made for another order or another curve does not verify.
206
+ function knowledgeProof(curve, x, X, context, label) {
207
+ const k = randScalar(curve);
208
+ const R = mul(curve, k);
209
+ const e = challenge(curve, [ctxUtf8(context), ctxUtf8("ninsei-dleq-pok|" + label), encP(X), encP(R)]);
210
+ return { R: enc(R), s: bigToHex((k + e * x) % curve.order) };
211
+ }
212
+ function verifyKnowledge(curve, X, pok, context, label) {
213
+ if (!pok || typeof pok !== "object") return false;
214
+ if (typeof pok.R !== "string" || typeof pok.s !== "string") return false;
215
+ let R, s;
216
+ try {
217
+ R = curve.P.fromHex(pok.R.replace(/^0x/i, ""));
218
+ s = BigInt(String(pok.s).startsWith("0X") ? "0x" + String(pok.s).slice(2) : String(pok.s).startsWith("0x") ? pok.s : "0x" + pok.s);
219
+ } catch { return false; }
220
+ const e = challenge(curve, [ctxUtf8(context), ctxUtf8("ninsei-dleq-pok|" + label), encP(X), encP(R)]);
221
+ return mul(curve, s).equals(addP(R, mPublic(curve, X, e)));
222
+ }
223
+
185
224
  // STEP 1. PREPARATION. Computed SEQUENTIALLY and whole: commitments depend on the running sum, so this step is
186
225
  // not split. Per-bit data is prepared here - exactly what step 2 needs: the bit, its commitments and its
187
226
  // randomness. THE HALF IS NO LONGER HERE, and that is the key property.
188
227
  function prepareProof(x, context) {
228
+ x = typeof x === "bigint" ? x : BigInt(x);
189
229
  const XA = mul(curves.A, x), XB = mul(curves.B, x);
190
230
  const cA = commitments(curves.A, x), cB = commitments(curves.B, x);
191
231
  const bits = [];
@@ -197,7 +237,12 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
197
237
  rA: bigToHex(cA.rs[i]), rB: bigToHex(cB.rs[i]),
198
238
  });
199
239
  }
200
- return { XA: enc(XA), XB: enc(XB), context: String(context == null ? "" : context), bits };
240
+ return {
241
+ XA: enc(XA), XB: enc(XB), context: String(context == null ? "" : context),
242
+ pokA: knowledgeProof(curves.A, x, XA, context, "A"),
243
+ pokB: knowledgeProof(curves.B, x, XB, context, "B"),
244
+ bits,
245
+ };
201
246
  }
202
247
 
203
248
  // STEP 2. PROVE ONE BIT. Called on the prepared data, self-contained, knowing neither the half nor other bits.
@@ -221,7 +266,7 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
221
266
  if (!item) throw new Error("assembleProof: no part for bit " + i);
222
267
  proofs.push({ cA: item.cA, cB: item.cB, sig: item.sig });
223
268
  }
224
- return { XA: prepared.XA, XB: prepared.XB, proofs };
269
+ return { XA: prepared.XA, XB: prepared.XB, pokA: prepared.pokA, pokB: prepared.pokB, proofs };
225
270
  }
226
271
 
227
272
  // prove REMAINS THE SAME FUNCTION, assembled from the same three steps: no second implementation appeared.
@@ -250,12 +295,13 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
250
295
  // FORM IS CHECKED BEFORE COUNTING. The old loop ran over the received list length: a short proof proved
251
296
  // ANOTHER representation, a long one burned check time. An honest path always sends exactly BITS parts. An
252
297
  // unparsable field returns a refusal, not an exception: the caller must get {ok:false}, not crash.
253
- function verify(proof, context) {
298
+ function verify(proof, context, options = {}) {
254
299
  if (!proof || typeof proof !== "object") return { ok: false, reason: "proof: an object is expected" };
255
300
  if (typeof proof.XA !== "string" || typeof proof.XB !== "string") return { ok: false, reason: "proof: no XA or XB" };
256
301
  if (!Array.isArray(proof.proofs)) return { ok: false, reason: "proof: no parts list" };
257
302
  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/, ""));
303
+ const requireKnowledge = options.requireKnowledge !== false;
304
+ const P = (curve, h) => curve.P.fromHex(String(h).replace(/^0x/i, ""));
259
305
  let XA, XB, csA, csB;
260
306
  try {
261
307
  XA = P(curves.A, proof.XA); XB = P(curves.B, proof.XB);
@@ -263,6 +309,17 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
263
309
  } catch (e) {
264
310
  return { ok: false, reason: "proof: XA or XB is unparsable (" + String((e && e.message) || e) + ")" };
265
311
  }
312
+ // THE PURE-MULTIPLE GUARD COMES BEFORE THE BIT LOOP. It is optional only so old vectors can still be checked
313
+ // as historical artifacts; every proof produced by this module carries both fields and SDK callers require
314
+ // them. A missing or tampered `pokA`/`pokB` is a refusal, never a skipped check.
315
+ if (requireKnowledge) {
316
+ try {
317
+ if (!verifyKnowledge(curves.A, XA, proof.pokA, context, "A")) return { ok: false, reason: "proof: the secp256k1 knowledge proof did not verify" };
318
+ if (!verifyKnowledge(curves.B, XB, proof.pokB, context, "B")) return { ok: false, reason: "proof: the ed25519 knowledge proof did not verify" };
319
+ } catch (e) {
320
+ return { ok: false, reason: "proof: the knowledge proof is unparsable (" + String((e && e.message) || e) + ")" };
321
+ }
322
+ }
266
323
  // THE BIT NUMBER IS NAMED HERE TOO: without it, "somewhere in the proof" is indistinguishable from any of
267
324
  // the 253 commitments being corrupt.
268
325
  try {
@@ -282,7 +339,14 @@ export function createDleq2({ ed25519, secp256k1, keccak256, sha3_512, randomByt
282
339
  try {
283
340
  if (!torsionFree(curves.B, csB[i])) return { ok: false, reason: "bit " + i + ": the commitment is not in the prime-order subgroup" };
284
341
  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)]));
342
+ // ONLY THE SIX PROTOCOL SCALARS ARE READ. Unknown fields in `sig` are ignored (N2), and a missing one
343
+ // still refuses: Object.entries would try to parse an unknown key as a scalar and throw.
344
+ const sig = {};
345
+ for (const k of ["eA", "eB", "a0", "a1", "b0", "b1"]) {
346
+ const v = item.sig[k];
347
+ const text = String(v);
348
+ sig[k] = BigInt(/^0x/i.test(text) ? text : "0x" + text);
349
+ }
286
350
  const pA = P(curves.A, cA), pB = P(curves.B, cB);
287
351
  const pre = (q1, q2) => [ctxUtf8(context), encP(pA), encP(pB), encP(q1), encP(q2)];
288
352
  const aG = mul(curves.A, sig.a1, curves.A.Galt), eCA = mPublic(curves.A, pA, sig.eA);
@@ -363,22 +363,22 @@ export const CHAINS = [
363
363
  explorerName: "arbiscan (sepolia)",
364
364
  gasUsd: 0.01,
365
365
  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).
366
+ // THE DEMO'S MAIN NETWORK: the Ninsei escrow factory and the interface's fee cashier live here. The current
367
+ // contract version (contracts-testnet-2026.11.03-fix) is a FACT, not an intention:
368
+ // factory 0x6ab0ef3aa67b022d4007550e7556108537debb55 (height 325677796,
369
+ // transaction 0xe5f2244c2aa07bb372352b5cb47fa6fdd531a1f8a763d4246b0d31efa0723d2d);
370
+ // cashier 0x6c6c6da6392a92b8b9c69b3ec234d524cdcfcb57;
371
+ // registry 0xf06ec2b1de69ff5b528ed917edffbee7be6dccc9 (this release deploys it);
372
+ // implementation 0x584b8438204A7CDb207957F5572a7f34E5D526c8, codehash
373
+ // 0x334d6802099fccaef87b9569618ab3c46f6a2f075c2934c0cdbc8d4e4042944b.
374
+ // `OrderCreated` carries xmrAmount; the SDK reads it from the event. PREVIOUS factory before this version:
375
+ // 0x69b5a6878b542960af4d239ecc60ad1c9e3e6932 (height 323014007, cashier
376
+ // 0x05b7433f66f2b75cc7ece9ec00af0fb810f9c9e0).
377
377
  // mode: "live" - order creation TOGETHER WITH THE MONEY in one transaction (createOrderAndFund). cashier: the
378
378
  // INTERFACE's fee cashier, named in quotes. implementationCodeHash: the escrow implementation the factory
379
379
  // carries, checked against the chain. deploymentBlock: the height the factory was created at; a log search for
380
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" },
381
+ escrow: { address: "0x6ab0ef3aa67b022d4007550e7556108537debb55", mode: "live", deploymentBlock: 325677796, cashier: "0x6c6c6da6392a92b8b9c69b3ec234d524cdcfcb57", implementationCodeHash: "0x334d6802099fccaef87b9569618ab3c46f6a2f075c2934c0cdbc8d4e4042944b" },
382
382
  tokens: [
383
383
  // Test USDC (Circle): decimals 6 and symbol "USDC" verified on chain by the same node.
384
384
  { symbol: "USDC", address: "0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d", decimals: 6, usd: 1, cls: "ar-token-usdc" },
@@ -798,9 +798,9 @@ export function allowedProvidersFor(chainOrId) {
798
798
  // named by the record and match the signed quote). Filled at deploy: the factory has no immutables, so one build
799
799
  // gives the same hash to anyone who deployed it - a provider's own factory lands in the same list.
800
800
  export const KNOWN_FACTORY_CODES = {
801
- // contracts-testnet-2026.10.26, factory deployed at 0x69b5a6878b542960af4d239ecc60ad1c9e3e6932.
801
+ // contracts-testnet-2026.11.03-fix, factory deployed at 0x6ab0ef3aa67b022d4007550e7556108537debb55.
802
802
  // The factory has no immutables; this hash is reproducible from that release's source.
803
- "arbitrum-sepolia": ["0x4d51e943b7786be7d3f9e2c44ad0b54f82932dba12ac6fa34be5088500d6615c"],
803
+ "arbitrum-sepolia": ["0x9246f3b981311c4ed988d77bb2177ef45d78182e47d77a2077d0afe3f3377cb8"],
804
804
  };
805
805
 
806
806
  export function knownFactoryCodesFor(chainOrId) {
@@ -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;
@@ -50,8 +50,8 @@ export const TERMINAL = {
50
50
  refunded_eth: { phase: "refunded_eth", label: "ETH refunded" },
51
51
  };
52
52
 
53
- export function createSwap(input) {
54
- const s = loadState();
53
+ export function createSwap(input, store = null) {
54
+ const s = store ? store.loadState() : loadState();
55
55
  const now = Date.now();
56
56
  const swap = {
57
57
  id: shortId(),
@@ -61,7 +61,7 @@ export function createSwap(input) {
61
61
  // THERE IS NO QUOTE KIND IN THE RECORD. The former field mode ("floating"/"fixed") was a choice of price
62
62
  // kind, and in version 4 there is no second kind: a firm quote is exactly one - the order quote.
63
63
  network: input.network || DEFAULT_CHAIN,
64
- moneroNetwork: MONERO.networkType,
64
+ moneroNetwork: input.moneroNetwork || MONERO.networkType,
65
65
  realStart: now,
66
66
  simStartWall: now,
67
67
  createdAt: new Date(now).toISOString(),
@@ -121,7 +121,7 @@ export function createSwap(input) {
121
121
 
122
122
  s.swaps[swap.id] = swap;
123
123
  s.activeSwapId = swap.id;
124
- saveState(s);
124
+ if (store) store.saveState(s); else saveState(s);
125
125
  return swap;
126
126
  }
127
127
 
@@ -146,7 +146,7 @@ export function createReverseSwap(input = {}) {
146
146
  scenario: "happy",
147
147
  speed: Number(input.speed) || 60,
148
148
  network: input.network || DEFAULT_CHAIN,
149
- moneroNetwork: MONERO.networkType,
149
+ moneroNetwork: input.moneroNetwork || MONERO.networkType,
150
150
  realStart: now,
151
151
  simStartWall: now,
152
152
  createdAt: new Date(now).toISOString(),
@@ -179,7 +179,7 @@ export function createReverseSwap(input = {}) {
179
179
  counterViewHalf: input.counterViewHalf || null,
180
180
  counterViewPoint: input.counterViewPoint || null,
181
181
  counterSpendPoint: input.counterSpendPoint || null,
182
- moneroNetwork: MONERO.networkType,
182
+ moneroNetwork: input.moneroNetwork || MONERO.networkType,
183
183
  birthHeight: input.escrowBirthHeight || null,
184
184
  readyBy: input.readyBy || null,
185
185
  t1: input.t1 || null,
@@ -235,16 +235,16 @@ export function halvesWalletOf(swap) {
235
235
  };
236
236
  }
237
237
 
238
- export function forgetSwap(id) {
239
- const s = loadState();
238
+ export function forgetSwap(id, store = null) {
239
+ const s = store ? store.loadState() : loadState();
240
240
  if (!s.swaps[id]) return false;
241
241
  delete s.swaps[id];
242
- saveState(s);
242
+ if (store) store.saveState(s); else saveState(s);
243
243
  return true;
244
244
  }
245
245
 
246
- export function getSwap(id) {
247
- return loadState().swaps[id] || null;
246
+ export function getSwap(id, store = null) {
247
+ return (store ? store.loadState() : loadState()).swaps[id] || null;
248
248
  }
249
249
 
250
250
  export function allSwaps() {
@@ -289,9 +289,9 @@ export function serverRowToSwap(row) {
289
289
 
290
290
  // Add server records the browser lacks. Returns the number added: the caller decides from it whether to redraw
291
291
  // the list, rather than guessing.
292
- export function addServerSwaps(rows) {
292
+ export function addServerSwaps(rows, store = null) {
293
293
  if (!Array.isArray(rows) || rows.length === 0) return 0;
294
- const s = loadState();
294
+ const s = store ? store.loadState() : loadState();
295
295
  let added = 0;
296
296
  for (const row of rows) {
297
297
  if (!row || !row.id || !row.escrow) continue;
@@ -299,7 +299,7 @@ export function addServerSwaps(rows) {
299
299
  s.swaps[row.id] = serverRowToSwap(row);
300
300
  added += 1;
301
301
  }
302
- if (added) saveState(s);
302
+ if (added) { if (store) store.saveState(s); else saveState(s); }
303
303
  return added;
304
304
  }
305
305
 
@@ -313,14 +313,14 @@ export function activeSwaps() {
313
313
  // fields - escrow address, salt, deadlines, secret - and did NOT save it: the edits lived in memory and vanished
314
314
  // with the tab, while the progress screen read the OLD record from storage. That is exactly why the interface
315
315
  // showed an address not on chain even when funding had succeeded.
316
- export function saveSwap(swap) {
317
- return persist(swap);
316
+ export function saveSwap(swap, store = null) {
317
+ return persist(swap, store);
318
318
  }
319
319
 
320
- function persist(swap) {
321
- const s = loadState();
320
+ function persist(swap, store = null) {
321
+ const s = store ? store.loadState() : loadState();
322
322
  s.swaps[swap.id] = swap;
323
- saveState(s);
323
+ if (store) store.saveState(s); else saveState(s);
324
324
  return swap;
325
325
  }
326
326
 
@@ -337,8 +337,8 @@ function findEvent(swap, type) {
337
337
  // User actions
338
338
  // ---------------------------------------------------------------------------
339
339
 
340
- export function confirmReady(id) {
341
- const swap = getSwap(id);
340
+ export function confirmReady(id, store = null) {
341
+ const swap = getSwap(id, store);
342
342
  if (!swap || swap.settlement) return swap;
343
343
  const view = derive(swap);
344
344
  if (!view.can.ready) throw new Error("ready() is not available in this phase");
@@ -346,7 +346,7 @@ export function confirmReady(id) {
346
346
  event(swap, "ready", atSim);
347
347
  pushLog(swap, atSim, "ready() called by you", "maker may now claim the ETH escrow");
348
348
  if (!findEvent(swap, "funded_note")) event(swap, "funded_note", 0);
349
- return persist(swap);
349
+ return persist(swap, store);
350
350
  }
351
351
 
352
352
  // THE COUNTERPARTY'S SPEND HALF - THE ONE PLACE THAT SHOWS WHETHER THERE IS ANYTHING TO ASSEMBLE. The Monero
@@ -363,8 +363,8 @@ export function refundHalfRevealed(swap) {
363
363
  // stayed on the swap's one-time address, and the contract revealed the DEPOSITOR's half on refund. Then the same
364
364
  // sweep takes our coins back, and the settlement is marked recovered: the money returned to the user rather
365
365
  // than leaving through the swap.
366
- export function sweepNow(id) {
367
- const swap = getSwap(id);
366
+ export function sweepNow(id, store = null) {
367
+ const swap = getSwap(id, store);
368
368
  if (!swap) return swap;
369
369
  // The deal already settled: no second sweep - EXCEPT a reverse-flow refund, which is how our own XMR are taken
370
370
  // back.
@@ -379,11 +379,11 @@ export function sweepNow(id) {
379
379
  swap.settlement = { kind: "success", phase: TERMINAL.success.phase, atSim, txid: tx.txid, by: "you",
380
380
  ...(fromRefund ? { recovered: true } : {}) };
381
381
  pushLog(swap, atSim, "XMR swept to your address", tx.txid);
382
- return persist(swap);
382
+ return persist(swap, store);
383
383
  }
384
384
 
385
- export function refundEth(id, by = "you") {
386
- const swap = getSwap(id);
385
+ export function refundEth(id, by = "you", store = null) {
386
+ const swap = getSwap(id, store);
387
387
  if (!swap || swap.settlement) return swap;
388
388
  const view = derive(swap);
389
389
  if (!view.can.refund) throw new Error("refund is not available in this phase");
@@ -391,7 +391,7 @@ export function refundEth(id, by = "you") {
391
391
  const tx = chain.refundEscrow({ swapId: swap.id, by });
392
392
  swap.settlement = { kind: "refund_eth", phase: TERMINAL.refunded_eth.phase, atSim, txHash: tx.txHash, by };
393
393
  pushLog(swap, atSim, `ETH refunded to your wallet (${by})`, tx.txHash);
394
- return persist(swap);
394
+ return persist(swap, store);
395
395
  }
396
396
 
397
397
  // ---------------------------------------------------------------------------
@@ -519,25 +519,33 @@ export function derive(swap, now = nowReal()) {
519
519
  }
520
520
  } else if (live && readyAt === null && chainReadyByMs !== null && nowReal() >= chainReadyByMs
521
521
  && (chainT1Ms === null || nowReal() < chainT1Ms)) {
522
- // THERE WAS A DEAD ZONE - NOW AN OPEN DOOR. The depositor will not mark anymore, and the contract forbids a
523
- // claim without it, so the claim window NEVER OPENED - and a refund is allowed right after readyBy (the
524
- // contract condition: block.timestamp < readyBy || (block.timestamp < t1 && ready)). It also publishes the
525
- // depositor's half, so the maker takes his XMR back without waiting for t1. That is the answer to the dead
526
- // zone: before, the money and the half waited for t1, and the Monero leg was unavailable to both sides.
522
+ // THE DEAD ZONE IS REAL, AND THE CONTRACT DOES NOT OPEN THE REFUND IN IT. `refund()` rejects a call before
523
+ // `t1` when `block.timestamp >= readyBy` and `ready` is false; the same rule keeps the claim closed without the
524
+ // mark. Nothing can be signed between `readyBy` and `t1`, so the screen must not offer a refund that reverts.
527
525
  phase = "dead_zone";
528
- phaseLabel = "Ready deadline passed - the refund is open";
526
+ phaseLabel = "Ready deadline passed - the refund opens at T1";
529
527
  can.ready = false;
530
- can.refund = true;
531
- can.refundByAnyone = true;
528
+ can.refund = false;
529
+ can.refundByAnyone = false;
532
530
  note = "The ready() deadline has passed without your confirmation, so the maker cannot claim - and the " +
533
- "refund is open NOW, not at T1. It returns your ETH and publishes your half, so the maker can reclaim " +
534
- "the XMR from Monero right away. " +
535
- (chainT1Ms !== null ? "T1 closes the order for good: " + new Date(chainT1Ms).toISOString() + "." : "");
531
+ "escrow refuses a refund before T1 while the mark is absent. Nothing can be signed now; the refund opens " +
532
+ "at T1 and returns your ETH and publishes your half. " +
533
+ (chainT1Ms !== null ? "T1: " + new Date(chainT1Ms).toISOString() + "." : "");
536
534
  } else if (live && readyAt === null) {
537
535
  // Live mode: Monero-leg states come from the backend. The simulated EVM-leg timeouts (T0/T1, watchtower)
538
536
  // are deliberately NOT shown here: the contract does not exist yet, and a "refund ETH" button would be a
539
537
  // lie. The "EVM leg - simulation" mark hangs in the UI separately (derive().simulated).
540
- if (xmr.status === XMR_STATUS.LOCKED) {
538
+ if (chainT1Ms !== null && nowReal() >= chainT1Ms) {
539
+ // THE OTHER SIDE OF THE DEAD ZONE. From T1 the refund is open even without the ready mark; before this
540
+ // branch existed, a live order without the mark stayed "received, waiting" forever after T1.
541
+ phase = "refund_available";
542
+ phaseLabel = "Claim deadline passed - the refund is open";
543
+ can.ready = false;
544
+ can.refund = true;
545
+ can.refundByAnyone = true;
546
+ note = "The claim deadline passed without the ready mark. The refund is open to anyone who can present " +
547
+ "the depositor's half - that half is yours in the recovery file. It returns your ETH and publishes your half.";
548
+ } else if (xmr.status === XMR_STATUS.LOCKED) {
541
549
  // THE MONEY IS AT THE ADDRESS BUT LOCKED BY unlock_time. This is a NAMED state, not "waiting for arrival":
542
550
  // otherwise the screen would be silent and the amount would look zero. A readiness mark is impossible here
543
551
  // - claiming ETH against locked XMR would give the maker ETH for money that cannot be paid with.
@@ -644,16 +652,10 @@ export function derive(swap, now = nowReal()) {
644
652
  can.refund = realNow >= escrowT0; // an old order: from t0, and only the locker
645
653
  can.refundByAnyone = realNow >= chainT1; // from t1 - anyone
646
654
  } else {
647
- // A NEW ORDER: TWO BOUNDARIES. From t1 - as before, a refund is open to all. But if the ready mark is
648
- // absent, the claim window never opened, and a refund is open right after readyBy: otherwise the dead
649
- // zone would hold the money and the half until t1. The mark is taken from the RECORD (readyAt) - the
650
- // user sets it himself, and in this branch it is empty. If the record is lost while the chain has the
651
- // mark, the contract refuses: an honest refusal instead of a promise we would not keep.
652
- const chainReadyBy = swap.escrow && swap.escrow.readyBy ? Number(swap.escrow.readyBy) * 1000 : null;
653
- const earlyRefund = chainReadyBy !== null && realNow >= chainReadyBy && readyAt === null;
654
- can.refund = realNow >= chainT1 || earlyRefund;
655
- can.refundByAnyone = can.refund; // and from t1 a refund is open to all at once
656
- if (earlyRefund && realNow < chainT1) refundAfterSim = null; // the refund is already open: no countdown
655
+ // A NEW ORDER HAS ONE BOUNDARY. The escrow's `refund()` rejects every call before T1, including the
656
+ // window after readyBy without the mark; from T1 it is open to anyone. There is no early refund to offer.
657
+ can.refund = realNow >= chainT1;
658
+ can.refundByAnyone = can.refund; // from t1 a refund is open to all at once
657
659
  }
658
660
  } else if (!isLiveNetwork(swap)) {
659
661
  can.refund = sim >= t1At; // a demo deal: as before, from the simulator
@@ -5,21 +5,20 @@
5
5
  // Calls to the NinseiSwap escrow factory contract.
6
6
  //
7
7
  // There are no EVM libraries in the project and we are not adding any. BOTH FACTORY FUNCTIONS NOW TAKE THE
8
- // SIGNED QUOTE (OrderQuote.Quote), the signature as three words (r, s, v) and three depositor fields. The fee
9
- // and the registry address are PART of the quote, not a contract setting: the factory no longer has feeBps()/
8
+ // SIGNED QUOTE (OrderQuote.Quote) and the signature as three words (r, s, v). The depositor fields are inside
9
+ // the quote now, so they are not separate arguments. The fee and the registry address are PART of the quote, not a contract setting: the factory no longer has feeBps()/
10
10
  // feeFor() (the router was removed), so there is nothing to ask. All arguments are static, so calldata is a
11
11
  // selector plus 32-byte words, built here in one place and checked mechanically.
12
12
  //
13
- // cast sig "predict((address,address,address,address,address,address,uint256,uint64,uint64,bytes32,bytes32,bytes32,uint256,uint256,uint256,address,uint64,uint256,uint256,uint256),bytes32,bytes32,uint8,bytes32,bytes32,bytes32)" -> 0x3e949279
14
- // cast sig "createOrderAndFund(<same tuple>,...)" -> 0x3a504547
13
+ // cast sig "predict((address,address,address,address,address,address,uint256,uint64,uint64,bytes32,bytes32,bytes32,uint256,uint256,uint256,address,uint64,uint256,uint256,uint256,bytes32,bytes32,bytes32),bytes32,bytes32,uint8)" -> 0x76e3fdc8
14
+ // cast sig "createOrderAndFund(<same tuple>,...)" -> 0x50db6721
15
15
 
16
16
  export const FACTORY_METHODS = {
17
- // THE SELECTORS FOLLOW THE 20-FIELD QUOTE. claimTip is the last field of the tuple, so both selectors changed when
18
- // it joined the signed set; the old 19-field values (0x0824d205 / 0x4703a9d3) address a function this factory no
19
- // longer has.
20
- predict: "0x3e949279",
17
+ // THE SELECTORS FOLLOW THE 23-FIELD QUOTE. The depositor fields joined the signed tuple, so both selectors
18
+ // changed again; the old 20-field values (0x3e949279 / 0x3a504547) address a function this factory no longer has.
19
+ predict: "0x76e3fdc8",
21
20
  // create the escrow AND deposit funds in ONE transaction (a value transfer with the call).
22
- createOrderAndFund: "0x3a504547",
21
+ createOrderAndFund: "0x50db6721",
23
22
  };
24
23
 
25
24
  // The OrderCreated event topic. It grew the registry address, the provider and the signing key, and now carries
@@ -40,10 +39,8 @@ export const ORDER_CREATED_TOPICS = Object.freeze([ORDER_CREATED_TOPIC, ORDER_CR
40
39
  export const QUOTE_FIELDS = [
41
40
  "provider", "quoteKey", "registry", "cashier", "locker", "claimer", "amount", "readyBy", "t1", "salt",
42
41
  "commitHalfClaimer", "edPointClaimer", "chainId", "feeBps", "fee", "feeRecipient", "validUntil", "nonce", "xmrAmount",
43
- "claimTip",
42
+ "claimTip", "commitHalfLocker", "edPointLocker", "edViewPointLocker",
44
43
  ];
45
- // The depositor fields are NOT in the quote: they go as separate arguments (into the escrow init code).
46
- const LOCKER_HALF_FIELDS = ["commitHalfLocker", "edPointLocker", "edViewPointLocker"];
47
44
  const ADDR_FIELDS = ["provider", "quoteKey", "registry", "cashier", "locker", "claimer", "feeRecipient"];
48
45
  const B32_FIELDS = ["salt", "commitHalfClaimer", "edPointClaimer", "commitHalfLocker", "edPointLocker", "edViewPointLocker"];
49
46
 
@@ -99,6 +96,9 @@ function quoteWords(quote) {
99
96
  feeRecipient: word(quote.feeRecipient, 32), validUntil: word(quote.validUntil, 32), nonce: word(quote.nonce, 32),
100
97
  xmrAmount: word(quote.xmrAmount, 32),
101
98
  claimTip: word(quote.claimTip, 32),
99
+ commitHalfLocker: word(asHex32(quote.commitHalfLocker), 32),
100
+ edPointLocker: word(asHex32(quote.edPointLocker), 32),
101
+ edViewPointLocker: word(asHex32(quote.edViewPointLocker), 32),
102
102
  };
103
103
  return QUOTE_FIELDS.map((n) => map[n]).join("");
104
104
  }
@@ -113,15 +113,8 @@ function signatureWords(signature) {
113
113
  }
114
114
 
115
115
  // The common part of predict and createOrderAndFund.
116
- function lockerHalfWords(quote) {
117
- return LOCKER_HALF_FIELDS.map((name) => {
118
- if (quote[name] === undefined || quote[name] === null || quote[name] === "") throw new Error("the quote has no depositor field: " + name);
119
- return word(asHex32(quote[name]), 32);
120
- }).join("");
121
- }
122
-
123
116
  function quoteCallArgs(quote) {
124
- return quoteWords(quote) + signatureWords(quote.signature) + lockerHalfWords(quote);
117
+ return quoteWords(quote) + signatureWords(quote.signature);
125
118
  }
126
119
 
127
120
  // PREDICT THE ADDRESS. The argument set matches createOrderAndFund BYTE FOR BYTE (the address is the code hash of
@@ -121,7 +121,7 @@ function modeOf(chain) {
121
121
  function optionsFor(chain) {
122
122
  return {
123
123
  settlement: { chain: chain.id },
124
- xmrNetwork: MONERO.networkType,
124
+ xmrNetwork: (chain.monero && chain.monero.networkType) || MONERO.networkType,
125
125
  // NO BACKEND BY DEFAULT: a page that needs one passes its base explicitly.
126
126
  assetsBase: "/",
127
127
  mode: modeOf(chain),