@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
package/src/swap-flow.mjs CHANGED
@@ -4,21 +4,21 @@
4
4
  // the UI called a simulation while the funding module waited for ready-made sealedCommitment and sealedHalf. Now
5
5
  // the order is fixed here, and there is no step that can be skipped by accident:
6
6
  //
7
- // 1) build your own side (the half + the proof) - in the WORKER, so the page does not freeze;
7
+ // 1) build your own side (the half + the proof) with the engine's order builder;
8
8
  // 2) assemble the counterparty's side (in the demo - a local stand-in, marked standIn);
9
9
  // 3) CHECK the counterparty against the single mandatory condition - the DLEQ proof in the context of THIS
10
10
  // order (there is no envelope in the scheme any more, doc 27) - before any locking: after it, that would no
11
11
  // longer help. The item "the envelope that confirms the half" left together with the envelope itself;
12
- // 4) obtain commitments on BOTH halves: our own is computed by the worker over our half (only the hash goes
13
- // out), the counterparty's commitment arrives in the quote. There is no longer any need to encrypt the half
12
+ // 4) obtain commitments on BOTH halves: our own is computed from our half, the counterparty's commitment
13
+ // arrives in the quote. There is no longer any need to encrypt the half
14
14
  // and hand it to the counterparty: it is revealed on-chain at settlement (claim/refund);
15
15
  // 5) and only now put the money in: with ONE createOrderAndFund transaction that creates the escrow together
16
16
  // with the money (the "lock" step below). The former name lock(sealedHalf) lied twice here: the contract has
17
17
  // no such function - the payable constructor moves the money - and there is no envelope in the order. Nor
18
18
  // does the escrow have a separate funding function: an order is either born with money or not born at all.
19
19
  //
20
- // THE CRYPTOGRAPHY LIVES UNDER www/js/atomic/* (mirrored as ../engine/atomic/*) AND IS CALLED ONLY THROUGH THE
21
- // WORKER. There is no crypto here - here is the order.
20
+ // THE CRYPTOGRAPHY LIVES UNDER www/js/atomic/* (mirrored as ../engine/atomic/*) AND IS CALLED ONLY THROUGH
21
+ // THE IN-PROCESS ORDER BUILDER. There is no crypto here - here is the order.
22
22
  //
23
23
  // WHY IT IS IN THE PACKAGE NOW. The page used to import this module straight from www/js/core/swap-flow.js; the
24
24
  // core (www/js, mirrored under ../engine/) was the second home of the deal flow. That is exactly the debt
@@ -32,6 +32,11 @@ import * as engine from "./engine.mjs";
32
32
  // reported in. It is its own module because TWO surfaces ask the same question (this flow and the swaps watch)
33
33
  // and a second implementation of the same event would be a second truth about it.
34
34
  import { declinedFromLogs, logReaderOf, blockBoundaryOf, DECLINED_TOPIC0 } from "./decline.mjs";
35
+ // THE ORDER SIDE IS BUILT IN-PROCESS, by the same engine builder the record and the facade use. The old
36
+ // browser worker shipped its own copy of the crypto bundle. Its verifySide checked the DLEQ equation but not
37
+ // that the proven point matched the quote's commitment; the package no longer needs a second build of the same
38
+ // primitives.
39
+ import { buildOwnSideChunked, orderStepChunked } from "./order.mjs";
35
40
 
36
41
  // THE ENGINE SURFACES, TAKEN THROUGH THE ONE SEAM (./engine.mjs) - exactly as the rest of the core does.
37
42
  const { chainById, DEFAULT_CHAIN, MONERO } = engine.config;
@@ -42,9 +47,8 @@ const {
42
47
  } = engine.escrow;
43
48
  // THE COUNTERPARTY GUARDS: whether a stand-in may be signed on this chain.
44
49
  const { liveOrderSlotsVerdict, counterpartyVerdict } = engine.guards;
45
- // THE HALF WORKER, THE ORDER CONTEXT, THE ORDER QUOTE AND THE SHARED CLAIM GAS LIMIT - all through the mirror,
46
- // so the page and the package never keep a second copy of these rules.
47
- const { createOrderWorker } = engine.orderClient;
50
+ // THE ORDER CONTEXT, THE ORDER QUOTE AND THE SHARED CLAIM GAS LIMIT - all through the mirror, so the page and
51
+ // the package never keep a second copy of these rules.
48
52
  const { orderContextString } = engine.orderContext;
49
53
  const { requestOrderQuote, checkOrderQuoteShape } = engine.rfqSource;
50
54
  const { CLAIM_GAS_LIMIT } = engine.claimGas;
@@ -70,16 +74,15 @@ export function escrowCashierAddress(chainSlug) {
70
74
  // The full flow. onStage(stage, detail) is called on every step - the interface must show what is going on.
71
75
  export async function runAtomicOrder({
72
76
  chainSlug, locker, claimer, amountWei, amountLabel, providerId = null,
77
+ xmrNetwork = null,
73
78
  claimWindowSeconds = 3600, readyWindowSeconds = 14400, salt: providedSalt, onStage,
74
- // THE SUBSTITUTION POINTS FOR THE SAKE OF THE CHECK, and they are not decoration. The live flow could be
75
- // neither run in a check nor covered otherwise: it requires a browser Worker and a signature in the wallet.
76
- // Because of that two defects in a row appeared in it that neither the syntax nor the suite could see: the
77
- // signature did not accept the mandatory fields, and after the fix a reference to a variable outside its scope
78
- // remained - such things are visible only in operation. The defaults here are real: substitution is only in
79
- // checks.
79
+ // THE SUBSTITUTION POINTS FOR THE SAKE OF THE CHECK, and they are not decoration. The live flow reaches a
80
+ // wallet and a chain; the check drives the same sequence with synthetic sides. The defaults here are real:
81
+ // substitution is only in checks.
80
82
  deps = {},
81
83
  }) {
82
- const makeWorker = deps.createOrderWorker || createOrderWorker;
84
+ const buildSide = deps.buildOwnSide || buildOwnSideChunked;
85
+ const stepOrder = deps.orderStep || orderStepChunked;
83
86
  const fundLive = deps.fundOrderLive || fundOrderLive;
84
87
  const askQuote = deps.requestOrderQuote || requestOrderQuote;
85
88
  const factory = escrowFactoryAddress(chainSlug);
@@ -123,9 +126,8 @@ export async function runAtomicOrder({
123
126
  // commitments and BOTH public ed25519 points, and the half is published by the settlement itself
124
127
  // (claim/refund). The secret that used to be placed in the recovery file is now MY HALF: it is exactly what is
125
128
  // needed to claim the XMR.
126
- const worker = makeWorker();
127
129
  const say = (stage, detail) => onStage?.(stage, detail);
128
- try {
130
+ {
129
131
  // THE QUOTE FIRST, THEN YOUR OWN SIDE. The order of steps is set by the fact that the claimer is named by the
130
132
  // provider: the half binding includes the claimer's address, so our own half must be computed over the
131
133
  // context that is already fully known. It used to be the other way round, and the provider got an order with
@@ -156,7 +158,15 @@ export async function runAtomicOrder({
156
158
  const orderContext = orderContextString(order);
157
159
 
158
160
  say("half", "side");
159
- const mine = await worker.buildSide(orderContext, say);
161
+ // THE PROOF AND THE VERIFICATION YIELD BETWEEN CHUNKS. `runAtomicOrder` is already async, so the browser can
162
+ // paint while the same engine builder does the arithmetic.
163
+ const chunkOptions = {
164
+ onBit: (bit, total) => say("proof", `proving DLEQ proof: ${bit} of ${total} bits`),
165
+ onProgress: (step) => say("verify", step.phase === "sum"
166
+ ? `summing commitments: ${step.done} of ${step.total}`
167
+ : `verifying DLEQ proof: ${step.done} of ${step.total}`),
168
+ };
169
+ const mine = await buildSide(order, chunkOptions);
160
170
  say("half", "side-ready");
161
171
 
162
172
  // The counterparty stand-in. Honestly: only a real counterparty with its own key gives a guarantee; a
@@ -192,9 +202,7 @@ export async function runAtomicOrder({
192
202
  // THE STAND-IN IS COMPUTED OVER THE SAME CONTEXT AS THE ORDER. It used to append ":counterparty" to the
193
203
  // string, and that turned the check into a ritual: the stand-in's proof was bound to a different string,
194
204
  // that is, to nothing. Now exactly the path a real provider would take is checked.
195
- const mock = await worker.buildSide(orderContext);
196
- counter = { proof: mock.proof, edPub: mock.pub.ed, mock, viewHalf: mock.viewHalf, viewPoint: mock.viewPub,
197
- commitHalfClaimer: (await worker.halfCommitment(mock.half)).commitment };
205
+ counter = null;
198
206
  }
199
207
  // THE COUNTERPARTY CHECK REMAINS ONE AND IT IS THE MAIN ONE: the DLEQ proof in the context of this order.
200
208
  // It confirms that both public points stand for ONE scalar - that is, that the half declared for the Monero
@@ -203,16 +211,18 @@ export async function runAtomicOrder({
203
211
  // TOGETHER WITH IT, the fact is checked that the proven ed25519 point IS THE VERY ONE the contract will
204
212
  // receive: without that check a correct proof would guarantee nothing about the chain.
205
213
  say("verify", "dleq");
206
- const verdict = await worker.verifyCounterparty(orderContext, {
207
- proof: counter.proof, edPub: counter.edPub, commitHalfClaimer: counter.commitHalfClaimer,
208
- }, null);
209
- if (!verdict.ok) throw new SdkError("quote-refused", { step: "proof", why: "rejected" });
214
+ const step = await stepOrder({
215
+ order, side: mine.side, counterparty: counter, standIn: !quote,
216
+ network: xmrNetwork || (chain.monero && chain.monero.networkType) || MONERO.networkType,
217
+ options: chunkOptions,
218
+ });
219
+ const accepted = step.counterparty;
210
220
 
211
- // COMMITMENTS ON BOTH HALVES: our own is computed in the worker (only the hash goes out), the counterparty's
212
- // either arrived in the quote or is computed over the stand-in's half. Exactly these values are checked by
213
- // the contract in claim and refund and are included in termsHash.
214
- const commitHalfLocker = (await worker.halfCommitment(mine.half)).commitment;
215
- const commitHalfClaimer = counter.commitHalfClaimer || (await worker.halfCommitment(counter.mock.half)).commitment;
221
+ // COMMITMENTS ON BOTH HALVES: our own and the counterparty's are the ones the proof was verified against,
222
+ // by the same builder the contract and the recovery file use. Exactly these values are checked by the
223
+ // contract in claim and refund and are included in termsHash.
224
+ const commitHalfLocker = step.wallet.commitHalfLocker;
225
+ const commitHalfClaimer = step.wallet.commitHalfClaimer;
216
226
 
217
227
  // THE SHARED MONERO ADDRESS - FROM THE HALVES, AND IT IS COMPUTED BEFORE THE MONEY IS LOCKED. The address used
218
228
  // to be assembled from the maker's seed, that is, from the FULL key on its side: that is a custodial scheme,
@@ -222,16 +232,12 @@ export async function runAtomicOrder({
222
232
  // We compute it BEFORE funding on purpose: the address is derived from the same points that will go into the
223
233
  // contract, and if it cannot be assembled (the counterparty has neither a point nor a view half), we must
224
234
  // learn about it before the user signs the deposit.
225
- const otherViewPoint = counter.viewPoint || (counter.viewHalf ? (await worker.pointOf(counter.viewHalf)).ed : null);
235
+ const otherViewPoint = step.wallet.otherViewPoint;
226
236
  if (!otherViewPoint) {
227
237
  throw new SdkError("quote-refused", { step: "view-half" });
228
238
  }
229
239
  say("address", "joint-address");
230
- const joint = await worker.jointAddress({
231
- ownSpendHalf: mine.half, ownViewHalf: mine.viewHalf,
232
- otherSpendPoint: counter.edPub, otherViewPoint,
233
- network: (chain.monero && chain.monero.networkType) || MONERO.networkType,
234
- });
240
+ const joint = { address: step.wallet.address, spendPub: step.wallet.spendPub, viewPub: step.wallet.viewPub };
235
241
 
236
242
  // THE COUNTERPARTY STAND-IN ON A LIVE NETWORK IS A REFUSAL, NOT A SIGNATURE (the auditor's finding, review_02
237
243
  // section 6.3 and block D1, item 5). Without a provider the counterparty side is assembled locally, the proof
@@ -270,10 +276,10 @@ export async function runAtomicOrder({
270
276
  // The ed25519 points go into the order explicitly: the other side assembles the shared address from them
271
277
  // and checks the proof EXACTLY against the on-chain fields, not against what arrived in the quote (doc 27
272
278
  // section 11).
273
- edPointLocker: mine.pub.ed, edPointClaimer: counter.edPub,
279
+ edPointLocker: step.own.spendPoint, edPointClaimer: accepted.edPub,
274
280
  // THE DEPOSITOR'S VIEW POINT: from it the claimer assembles the address FROM THE ORDER FIELDS. Without it
275
281
  // it does not know where to send the XMR - and learns about it only after the money is deposited.
276
- edViewPointLocker: mine.viewPub,
282
+ edViewPointLocker: step.own.viewPoint,
277
283
  salt, // our swap salt: see funding.js
278
284
  amountLabel, // the ready amount string for the label: formatting lives in the UI
279
285
  amountWei,
@@ -295,19 +301,19 @@ export async function runAtomicOrder({
295
301
  feeWei: (funded && funded.feeWei) || 0n,
296
302
  feeTotalWei: (funded && funded.feeTotalWei) || null,
297
303
  feeBps: (funded && funded.feeBps) || 0,
298
- half: mine.half,
299
- counterHalf: standIn ? counter.mock.half : null,
304
+ half: step.side.half,
305
+ counterHalf: standIn ? accepted.half : null,
300
306
  // THE VIEW HALVES: our own and the counterparty's. Without them the address cannot be assembled and the
301
307
  // version 3 recovery file cannot be filled in, and without the file the user will not claim the XMR after
302
308
  // losing the tab.
303
- viewHalf: mine.viewHalf,
309
+ viewHalf: step.side.viewHalf,
304
310
  commitHalfLocker,
305
311
  commitHalfClaimer,
306
- edPointLocker: mine.pub.ed,
307
- edPointClaimer: counter.edPub,
312
+ edPointLocker: step.own.spendPoint,
313
+ edPointClaimer: accepted.edPub,
308
314
  // THE DEPOSITOR'S VIEW POINT goes into the record: without it there is nothing to compare the chain slot
309
315
  // edViewPointLocker against before signing - and it is part of the address the claimer will see.
310
- edViewPointLocker: mine.viewPub,
316
+ edViewPointLocker: step.own.viewPoint,
311
317
  // THE COUNTERPARTY'S VIEW HALF: the stand-in has it, a real provider does NOT, and this is a known gap of
312
318
  // the protocol, not a trifle: without its view half the shared Monero address cannot be assembled. While
313
319
  // the address in the application is built the previous way, the path does not break, but a quote under the
@@ -315,7 +321,7 @@ export async function runAtomicOrder({
315
321
  // ONE KIND OF HALF ON THE OUTPUT, and this is not pedantry: the stand-in's half is a number, the provider's
316
322
  // arrives as a string, and the consumer (the recovery file and the sweep) must not guess which it was
317
323
  // given. Next to the spend half, which is also a number.
318
- counterViewHalf: standIn ? counter.mock.viewHalf : BigInt(counter.viewHalf),
324
+ counterViewHalf: accepted.viewHalf === null || accepted.viewHalf === undefined ? null : BigInt(accepted.viewHalf),
319
325
  counterViewPoint: otherViewPoint,
320
326
  // THE SHARED ADDRESS: where the maker sends the XMR. Nobody can spend from it before the half is revealed.
321
327
  moneroAddress: joint.address,
@@ -328,8 +334,6 @@ export async function runAtomicOrder({
328
334
  // order_ref is empty (the regular payout does not reach the order).
329
335
  quoteId: (quote && quote.id) || null,
330
336
  };
331
- } finally {
332
- worker.stop();
333
337
  }
334
338
  }
335
339
 
@@ -355,7 +359,7 @@ export async function orderStatus(escrow, deps = {}) {
355
359
  // the engine read. The page goes through the bridge, which hands in the wallet's own reader, so the state is
356
360
  // read by the same wallet that will sign.
357
361
  const call = deps.call || readContract;
358
- const raw = await call({ to: escrow, data: encodeStatus() });
362
+ const raw = await call({ to: escrow, data: encodeStatus(), block: deps.blockTag || "latest" });
359
363
  return decodeStatus(raw);
360
364
  }
361
365
 
@@ -394,13 +398,14 @@ export async function orderDeadlines(escrow, deps = {}) {
394
398
  // THE SAME READER SEAM AS orderStatus: the deadline must be read by the wallet that will sign, not by a second
395
399
  // provider.
396
400
  const call = deps.call || readContract;
401
+ const block = deps.blockTag || "latest";
397
402
  const [raw1, rawH, rawReadyBy] = await Promise.all([
398
- call({ to: escrow, data: encodeT1() }),
399
- call({ to: escrow, data: encodeTermsHash() }),
403
+ call({ to: escrow, data: encodeT1(), block }),
404
+ call({ to: escrow, data: encodeTermsHash(), block }),
400
405
  // THE READY-MARK DEADLINE IS READ HERE TOO: without it the screen cannot say that the person is already in
401
- // the dead zone (the mark is closed, claiming is closed, refunding is not open yet) - and that is exactly
406
+ // the dead zone (the mark is closed, the claim is open, refunding is not open yet) - and that is exactly
402
407
  // where the deal hangs silently.
403
- call({ to: escrow, data: encodeRead("readyBy") }),
408
+ call({ to: escrow, data: encodeRead("readyBy"), block }),
404
409
  ]);
405
410
  // An empty eth_call response means there is NO CODE at the address: the contract is not deployed. This happens
406
411
  // when the createOrder transaction did not go through (for example the wallet rejected it over the fee) while
@@ -432,7 +437,8 @@ export async function orderLiveSlots(escrow, deps = {}) {
432
437
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
433
438
  const keys = ["edPointLocker", "edPointClaimer", "edViewPointLocker", "commitHalfLocker", "commitHalfClaimer"];
434
439
  try {
435
- const raws = await Promise.all(keys.map((k) => call({ to: escrow, data: encodeRead(k) })));
440
+ const block = deps.blockTag || "latest";
441
+ const raws = await Promise.all(keys.map((k) => call({ to: escrow, data: encodeRead(k), block })));
436
442
  const slots = {};
437
443
  keys.forEach((k, i) => { slots[k] = decodeBytes32(raws[i], k + "()"); });
438
444
  return { slots };
@@ -454,6 +460,77 @@ export async function assertOrderSlots(escrow, expect, what = "signature", deps
454
460
  return verdict;
455
461
  }
456
462
 
463
+ // THE ORDER MUST STILL BE OPEN BEFORE A HALF IS REVEALED. A closed order (claimed or refunded) and an
464
+ // unfunded address have no action to take; the slot check alone cannot see that. The deadline rule is separate:
465
+ // this guard answers the state question, not the clock.
466
+ async function assertOrderOpen(escrow, what, deps) {
467
+ const state = await orderStatus(escrow, deps);
468
+ if (!state.isFunded || state.isClaimed || state.isRefunded) {
469
+ throw new SdkError("contract-reverted", { step: what, why: "closed" });
470
+ }
471
+ }
472
+
473
+ // THE CONTRACT'S CLOCK RULE, READ FROM THE SAME CHAIN. Without a block-time seam the time checks are skipped (a
474
+ // direct caller that has no block reader is not given a promise the core cannot keep); the actions facade always
475
+ // brings one. The ready mark is read once, so claim/refund/mark-ready cannot disagree about it.
476
+ async function assertActionWindow(escrow, what, deps, now = null) {
477
+ if (typeof deps.blockTime !== "function") return;
478
+ const call = deps.call || readContract;
479
+ const block = deps.blockTag || "latest";
480
+ const [readyRaw, deadlines] = await Promise.all([
481
+ call({ to: escrow, data: encodeRead("ready"), block }),
482
+ orderDeadlines(escrow, deps),
483
+ ]);
484
+ const marked = BigInt(readyRaw) !== 0n;
485
+ const at = now === null ? Number(await deps.blockTime()) : Number(now);
486
+ // A HALF-REVEALING SEND NEEDS A READABLE CLOCK. Without it the deadline rule would be skipped, and a claim or
487
+ // refund that lands after its window still publishes the half. The actions facade always brings this seam.
488
+ if (!Number.isSafeInteger(at) || at <= 0) {
489
+ throw new SdkError("contract-reverted", { step: what, why: "clock-unreadable" });
490
+ }
491
+ // A TRANSACTION LANDS IN A LATER BLOCK. Keep a margin before every deadline so a send that is valid when signed
492
+ // does not become a revert that publishes the half.
493
+ const margin = 60;
494
+ if (what === "claim") {
495
+ if (at + margin >= Number(deadlines.t1)) throw new SdkError("contract-reverted", { step: what, why: "window-closed" });
496
+ if (!marked && at < Number(deadlines.readyBy)) throw new SdkError("contract-reverted", { step: what, why: "not-ready" });
497
+ } else if (what === "refund") {
498
+ // refund(): before t1 it is allowed only while the mark is absent and readyBy has not passed.
499
+ if (at < Number(deadlines.t1) && (at + margin >= Number(deadlines.readyBy) || marked)) {
500
+ throw new SdkError("contract-reverted", { step: what, why: "too-early" });
501
+ }
502
+ } else if (what === "mark-ready") {
503
+ if (marked) throw new SdkError("contract-reverted", { step: what, why: "already-ready" });
504
+ if (at + margin >= Number(deadlines.readyBy)) throw new SdkError("contract-reverted", { step: what, why: "ready-window-closed" });
505
+ }
506
+ }
507
+
508
+ // THE ACTION IS EXECUTED ON PAPER BEFORE IT IS SIGNED. `eth_call` runs the same call against the latest state
509
+ // from the same sender, so a revert becomes a named refusal instead of a mined transaction that changed nothing.
510
+ // The guards above answer the questions we know how to ask; this answers the contract itself, including its own
511
+ // deadlines and the half checks. A caller without a call seam keeps the old behaviour.
512
+ async function simulateAction(escrow, data, what, deps) {
513
+ const call = deps.call;
514
+ if (typeof call !== "function") return;
515
+ try {
516
+ await call({ to: escrow, data, from: deps.from });
517
+ } catch (error) {
518
+ const detail = error && (error.data || error.message);
519
+ const message = String((error && error.message) || "");
520
+ // A transport or wallet failure is not a revert. Keep it as it came: only a contract answer is turned into
521
+ // this action's refusal.
522
+ const reverted = (error && error.code === "contract-reverted")
523
+ || (error && typeof error.data === "string" && error.data.startsWith("0x"))
524
+ || /execution reverted|revert/i.test(message);
525
+ if (!reverted) throw error;
526
+ throw new SdkError("contract-reverted", {
527
+ step: what,
528
+ why: "simulation",
529
+ detail: typeof detail === "string" ? detail.slice(0, 200) : null,
530
+ });
531
+ }
532
+ }
533
+
457
534
  // Claim the ETH by the CLAIMER'S half. The field name in the contract is halfClaimer (:213); the former word
458
535
  // "secret" is a synonym of the same value (the half serves as the preimage of the commitment), while "hashlock"
459
536
  // lied here: the current contract has NO hashlock field. Instead it has two half commitments -
@@ -463,9 +540,14 @@ export async function assertOrderSlots(escrow, expect, what = "signature", deps
463
540
  export async function claimOrder({ escrow, halfClaimer, expect, onStep, deps = {} }) {
464
541
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
465
542
  if (!halfClaimer) throw new SdkError("bad-input", { field: "halfClaimer" });
466
- // SLOT CHECK BEFORE SIGNING: a claim reveals the half, and it must be revealed in the VERY order whose
467
- // commitments we know. Beyond this point the decision cannot be undone.
543
+ // STATE, TIME AND SLOTS BEFORE SIGNING: a claim reveals the half, and it must be revealed in the VERY order
544
+ // whose commitments we know, while that order is open. The contract's ready rule is TIME-DEPENDENT: before
545
+ // `readyBy` it requires the mark, after `readyBy` it allows a claim without it. Both are checked from the
546
+ // chain's own timestamp when the actions facade brings one.
547
+ await assertOrderOpen(escrow, "claim", deps);
548
+ await assertActionWindow(escrow, "claim", deps);
468
549
  await assertOrderSlots(escrow, expect, "claim", deps);
550
+ await simulateAction(escrow, encodeClaim(halfClaimer), "claim", deps);
469
551
  onStep?.("confirm-claim");
470
552
  // THE CLAIM GAS LIMIT COMES FROM THE SHARED MODULE, NOT A LITERAL HERE (issue #127): the node lays exactly
471
553
  // this limit into the gas gift. It is set explicitly and with a margin: claim has the same trap as order
@@ -484,30 +566,34 @@ export async function claimOrder({ escrow, halfClaimer, expect, onStep, deps = {
484
566
  export async function refundOrder({ escrow, halfLocker, onStep, expect = null, deps = {} }) {
485
567
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
486
568
  if (!halfLocker) throw new SdkError("bad-input", { field: "halfLocker" });
487
- onStep?.("confirm-refund");
569
+ // A CLOSED ORDER IS NOT A REFUND. The state is read before the half is signed; the deadline itself stays with
570
+ // the caller and the contract (there is one boundary, t1).
571
+ await assertOrderOpen(escrow, "refund", deps);
572
+ await assertActionWindow(escrow, "refund", deps);
488
573
  // THE SLOT CHECK HERE TOO, WHEN EXPECTATIONS ARE GIVEN. A refund REVEALS the half - that is, it is as
489
574
  // irreversible as a claim, and signing it under an order whose commitments we have not checked is forbidden
490
575
  // for the same reason. Expectations are optional for compatibility with previous calls (the page calls without
491
576
  // them); the core always passes them.
492
577
  if (expect) await assertOrderSlots(escrow, expect, "refund", deps);
578
+ await simulateAction(escrow, encodeRefund(halfLocker), "refund", deps);
579
+ onStep?.("confirm-refund");
493
580
  const hash = await (deps.send || sendTransaction)({ to: escrow, data: encodeRefund(halfLocker), gas: 250_000n });
494
581
  return { hash };
495
582
  }
496
583
 
497
- // Readiness: "I saw the XMR on the shared address, claiming is allowed". Without it the contract FORBIDS
498
- // claiming (:215) - and this is protection, not a formality: the contract does not see Monero and would pay on
499
- // the deadline alone to someone who sent nothing. The party that deposited the ETH sets it, and only after it
500
- // has itself seen the XMR lock. THE MARK WINDOW IS LIMITED, and this matters for the moment of the call: only on
501
- // a funded order, only before readyBy and only once (:200-204). After readyBy without the mark the order closes
502
- // by a refund (decision 30.09.2026): the claim window did not open, so claim is forbidden while refund opens
503
- // immediately. There used to be a dead zone here: neither claim (needs ready) nor refund (needs the deadline)
504
- // would go through.
584
+ // Readiness: "I saw the XMR on the shared address". Before `readyBy` the contract requires it for a claim and
585
+ // refuses a refund; after `readyBy` a claim is allowed even without it, while a refund opens only at `t1`
586
+ // (the mark itself can no longer be set). The party that deposited the ETH sets it, and only after it has itself
587
+ // seen the XMR lock. THE MARK WINDOW IS LIMITED: only on a funded order, only before readyBy and only once.
505
588
  export async function markReadyOrder({ escrow, expect, onStep, deps = {} }) {
506
589
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
507
- // SLOT CHECK BEFORE SIGNING: ready() grants the claimer settlement at its own address, and the grant is given
508
- // to the VERY order whose points and commitments we have checked. A mark on a foreign order is a signature
509
- // under what we did not assemble.
590
+ // A MARK ON A CLOSED OR ALREADY MARKED ORDER IS REFUSED. Then the slot check: ready() grants the claimer
591
+ // settlement at its own address, and the grant is given to the VERY order whose points and commitments we have
592
+ // checked. A mark on a foreign order is a signature under what we did not assemble.
593
+ await assertOrderOpen(escrow, "mark-ready", deps);
594
+ await assertActionWindow(escrow, "mark-ready", deps);
510
595
  await assertOrderSlots(escrow, expect, "mark-ready", deps);
596
+ await simulateAction(escrow, encodeMarkReady(), "mark-ready", deps);
511
597
  onStep?.("confirm-mark-ready");
512
598
  const hash = await (deps.send || sendTransaction)({ to: escrow, data: encodeMarkReady(), gas: 120_000n });
513
599
  return { hash };