@ninsei-labs/sdk 0.56.1 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +78 -28
  4. package/THIRD_PARTY_NOTICES.md +176 -2
  5. package/assets/vendors/MANIFEST.json +1 -13
  6. package/assets/vendors/sdk/sdk-browser.js +5 -4
  7. package/engine/atomic/dleq2.js +116 -15
  8. package/engine/atomic/order.js +21 -3
  9. package/engine/core/config.js +20 -46
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/rfqSource.js +6 -133
  12. package/engine/core/swap.js +8 -8
  13. package/engine/evm/asyncRoute.js +1 -1
  14. package/engine/evm/claimGas.js +2 -1
  15. package/engine/evm/escrow.js +13 -8
  16. package/engine/evm/factory.js +11 -6
  17. package/engine/evm/funding.js +8 -3
  18. package/engine/evm/index.js +5 -6
  19. package/engine/evm/session.js +48 -279
  20. package/engine/monero/address.js +15 -33
  21. package/engine/monero/keys.js +124 -0
  22. package/engine/monero/mnemonic.js +104 -0
  23. package/engine/monero/scan.js +121 -28
  24. package/engine/monero/wallet.js +31 -68
  25. package/engine/monero/wordlist.en.js +210 -0
  26. package/engine/recovery/restore.js +9 -9
  27. package/engine/sdk/bridge.js +9 -187
  28. package/engine/ui/walletModal.js +7 -27
  29. package/index.d.ts +234 -262
  30. package/package.json +7 -6
  31. package/src/actions.mjs +8 -5
  32. package/src/codes.mjs +17 -0
  33. package/src/config.mjs +17 -54
  34. package/src/engine.mjs +9 -6
  35. package/src/feeEstimate.mjs +11 -4
  36. package/src/http.mjs +4 -1
  37. package/src/index.mjs +24 -45
  38. package/src/legs/kyber.mjs +23 -0
  39. package/src/lock.mjs +1 -0
  40. package/src/order.mjs +110 -22
  41. package/src/primitives.mjs +4 -5
  42. package/src/probes.mjs +9 -3
  43. package/src/public/networks.d.ts +45 -0
  44. package/src/public/networks.mjs +10 -1
  45. package/src/public/recovery.d.ts +17 -1
  46. package/src/public/recovery.mjs +1 -0
  47. package/src/public/xmr.mjs +1 -1
  48. package/src/quotePolicy.mjs +25 -0
  49. package/src/quotes.mjs +109 -765
  50. package/src/readyWindow.mjs +76 -0
  51. package/src/recovery-key.mjs +71 -16
  52. package/src/recovery.mjs +11 -28
  53. package/src/relayClaim.mjs +132 -0
  54. package/src/relayFeatures.mjs +25 -13
  55. package/src/relayFirmClient.mjs +36 -7
  56. package/src/relayQuote.mjs +92 -11
  57. package/src/relayView.mjs +3 -3
  58. package/src/swap-flow.mjs +146 -60
  59. package/src/swaps.mjs +521 -357
  60. package/src/sweep-action.mjs +73 -0
  61. package/src/sweep-restore.mjs +8 -4
  62. package/src/sweep.mjs +12 -2
  63. package/src/version.mjs +1 -1
  64. package/src/xmr-arrival.mjs +328 -29
  65. package/src/xmrAmountPolicy.mjs +35 -0
  66. package/assets/vendors/atomic/atomic-browser.js +0 -24
  67. package/assets/vendors/monero/monero-js-browser.js +0 -58
  68. package/assets/vendors/monero-js/LICENSE +0 -9
  69. package/assets/vendors/walletconnect/wc-browser.js +0 -6202
  70. package/engine/atomic/order-client.js +0 -56
  71. package/engine/atomic/order-worker.js +0 -156
  72. package/engine/evm/asyncExec.js +0 -577
  73. package/engine/evm/asyncLegs.js +0 -308
@@ -6,6 +6,7 @@
6
6
  import { SdkError } from "./errors.mjs";
7
7
  import { keccak256, secp256k1 } from "./primitives.mjs";
8
8
  import { recoverOrderQuoteKey } from "./quoteEip712.mjs";
9
+ import { xmrAmountVerdict } from "./xmrAmountPolicy.mjs";
9
10
  import * as engine from "./engine.mjs";
10
11
 
11
12
  export const RELAY_QUOTE_TYPE =
@@ -15,7 +16,19 @@ const DOMAIN_TYPE = "EIP712Domain(string name,string version)";
15
16
  const DOMAIN_NAME = "Ninsei Relay";
16
17
  const DOMAIN_VERSION = "1";
17
18
 
18
- const utf8 = (value) => new TextEncoder().encode(String(value));
19
+ const wireText = (value, field) => {
20
+ if (typeof value === "string") return value;
21
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
22
+ if (typeof value === "bigint") return String(value);
23
+ throw new SdkError("bad-input", { field });
24
+ };
25
+ const wireNumber = (value, field) => {
26
+ let n = null;
27
+ try { n = Number(value); } catch { n = null; }
28
+ if (!Number.isFinite(n)) throw new SdkError("bad-input", { field });
29
+ return n;
30
+ };
31
+ const utf8 = (value, field = "text") => new TextEncoder().encode(wireText(value, field));
19
32
  const concat = (...arrays) => {
20
33
  const total = arrays.reduce((n, a) => n + a.length, 0);
21
34
  const out = new Uint8Array(total);
@@ -24,7 +37,7 @@ const concat = (...arrays) => {
24
37
  return out;
25
38
  };
26
39
  const hexBytes = (value, field, width) => {
27
- const text = String(value === undefined || value === null ? "" : value).replace(/^0x/, "");
40
+ const text = wireText(value === undefined || value === null ? "" : value, field).replace(/^0x/, "");
28
41
  if (!new RegExp("^[0-9a-fA-F]{" + width * 2 + "}$").test(text)) throw new SdkError("bad-input", { field });
29
42
  const out = new Uint8Array(width);
30
43
  for (let i = 0; i < width; i += 1) out[i] = parseInt(text.slice(i * 2, i * 2 + 2), 16);
@@ -44,19 +57,19 @@ const wordUint = (value, field) => {
44
57
  for (let i = 31; i >= 0 && n > 0n; i -= 1) { out[i] = Number(n & 0xffn); n >>= 8n; }
45
58
  return out;
46
59
  };
47
- const wordString = (value) => keccak256(utf8(value === undefined || value === null ? "" : value));
60
+ const wordString = (value, field) => keccak256(utf8(value === undefined || value === null ? "" : value, field));
48
61
 
49
62
  export function relayQuoteStructHash(answer) {
50
63
  if (!answer || typeof answer !== "object") throw new SdkError("bad-input", { field: "answer" });
51
64
  return keccak256(concat(
52
65
  keccak256(utf8(RELAY_QUOTE_TYPE)),
53
- wordString(answer.relayId),
66
+ wordString(answer.relayId, "answer.relayId"),
54
67
  wordAddress(answer.provider, "answer.provider"),
55
68
  wordBytes32(answer.session, "answer.session"),
56
69
  wordBytes32(answer.requestId, "answer.requestId"),
57
70
  wordUint(answer.counter, "answer.counter"),
58
71
  wordBytes32(answer.requestHash, "answer.requestHash"),
59
- wordString(answer.payload),
72
+ wordString(answer.payload, "answer.payload"),
60
73
  wordUint(answer.time, "answer.time"),
61
74
  ));
62
75
  }
@@ -73,13 +86,73 @@ export function relayQuoteDigest(answer) {
73
86
  return keccak256(concat(Uint8Array.from([0x19, 0x01]), relayQuoteDomainSeparator(), relayQuoteStructHash(answer)));
74
87
  }
75
88
 
89
+ export const RELAY_REQUEST_TYPE =
90
+ "QuoteRequest(string relayId,address provider,bytes32 session,bytes32 requestId,uint64 counter,uint64 expiry,string payload,uint256 feeBps,address feeRecipient)";
91
+
92
+ export function relayRequestStructHash(request) {
93
+ if (!request || typeof request !== "object") throw new SdkError("bad-input", { field: "forwarded" });
94
+ return keccak256(concat(
95
+ keccak256(utf8(RELAY_REQUEST_TYPE)),
96
+ wordString(request.relayId, "forwarded.relayId"),
97
+ wordAddress(request.provider, "forwarded.provider"),
98
+ wordBytes32(request.session, "forwarded.session"),
99
+ wordBytes32(request.requestId, "forwarded.requestId"),
100
+ wordUint(request.counter, "forwarded.counter"),
101
+ wordUint(request.expiry, "forwarded.expiry"),
102
+ wordString(request.payload, "forwarded.payload"),
103
+ wordUint(request.feeBps, "forwarded.feeBps"),
104
+ wordAddress(request.feeRecipient, "forwarded.feeRecipient"),
105
+ ));
106
+ }
107
+
108
+ export function relayRequestDigest(request) {
109
+ return keccak256(concat(Uint8Array.from([0x19, 0x01]), relayQuoteDomainSeparator(), relayRequestStructHash(request)));
110
+ }
111
+
112
+ /**
113
+ * THE FORWARDED REQUEST IS THE RELAY'S OWN SIGNED FRAME. The answer's `requestHash` is the digest of this
114
+ * object; without recomputing it, a relay could forward a different payload or maker while returning a
115
+ * correctly signed answer. The client always passes the answer's hash; a missing value becomes an empty
116
+ * string and fails the comparison.
117
+ *
118
+ * The frame's expiry and counter are not checked here. A fresh salt per request binds the payload, so a
119
+ * replayed old frame fails the payload comparison; the hash comparison then rejects a substituted one.
120
+ */
121
+ export function verifyRelayForwarded({ forwarded, relayKey, payload, provider, requestHash = null } = {}) {
122
+ if (!forwarded || typeof forwarded !== "object" || forwarded.type !== "quote_request" ||
123
+ wireNumber(forwarded.version, "forwarded.version") !== 1) {
124
+ throw new SdkError("quote-refused", { step: "answer", why: "forwarded" });
125
+ }
126
+ if (!/^0x[0-9a-fA-F]{40}$/.test(String(relayKey || ""))) {
127
+ throw new SdkError("quote-refused", { step: "relay-info", why: "key" });
128
+ }
129
+ if (wireText(forwarded.payload === undefined || forwarded.payload === null ? "" : forwarded.payload,
130
+ "forwarded.payload") !== payload) {
131
+ throw new SdkError("quote-refused", { step: "answer", why: "forwarded-payload" });
132
+ }
133
+ if (!same(forwarded.provider, provider)) {
134
+ throw new SdkError("quote-refused", { step: "answer", why: "forwarded-provider" });
135
+ }
136
+ const recovered = recoverAddress(relayRequestDigest(forwarded), forwarded.signature);
137
+ if (recovered === null || recovered !== String(relayKey).toLowerCase()) {
138
+ throw new SdkError("quote-refused", { step: "answer", why: "forwarded-signature" });
139
+ }
140
+ if (requestHash !== null && requestHash !== undefined) {
141
+ const digest = hex(relayRequestDigest(forwarded));
142
+ if (!same(digest, requestHash)) {
143
+ throw new SdkError("quote-refused", { step: "answer", why: "forwarded-hash" });
144
+ }
145
+ }
146
+ return forwarded;
147
+ }
148
+
76
149
  const hex = (bytes) => {
77
150
  let out = "0x";
78
151
  for (const byte of bytes) out += byte.toString(16).padStart(2, "0");
79
152
  return out;
80
153
  };
81
154
  function recoverAddress(digest, signature) {
82
- const sig = String(signature || "").replace(/^0x/, "");
155
+ const sig = wireText(signature === undefined || signature === null ? "" : signature, "signature").replace(/^0x/, "");
83
156
  if (!/^[0-9a-fA-F]{130}$/.test(sig)) return null;
84
157
  let v = parseInt(sig.slice(128, 130), 16);
85
158
  if (v >= 27) v -= 27;
@@ -97,7 +170,7 @@ function recoverAddress(digest, signature) {
97
170
 
98
171
  // The outer frame: signed by the quote key in the relay domain.
99
172
  export function verifyRelayQuoteFrame(answer, quoteKey) {
100
- if (!answer || typeof answer !== "object" || answer.type !== "quote" || Number(answer.version) !== 1) {
173
+ if (!answer || typeof answer !== "object" || answer.type !== "quote" || wireNumber(answer.version, "answer.version") !== 1) {
101
174
  throw new SdkError("quote-refused", { step: "answer", why: "frame" });
102
175
  }
103
176
  const recovered = recoverAddress(relayQuoteDigest(answer), answer.signature);
@@ -108,7 +181,7 @@ export function verifyRelayQuoteFrame(answer, quoteKey) {
108
181
  }
109
182
 
110
183
  const ZERO = "0x" + "00".repeat(20);
111
- const lower = (value) => String(value === undefined || value === null ? "" : value).toLowerCase();
184
+ const lower = (value) => wireText(value === undefined || value === null ? "" : value, "field").toLowerCase();
112
185
  const same = (a, b) => lower(a) === lower(b);
113
186
 
114
187
  function checkOrderQuote(quote, terms, nowSec) {
@@ -123,7 +196,6 @@ function checkOrderQuote(quote, terms, nowSec) {
123
196
  ["readyBy", String(order.readyBy)],
124
197
  ["t1", String(order.t1)],
125
198
  ["salt", order.salt],
126
- ["xmrAmount", String(terms.xmrAmount)],
127
199
  ["claimTip", String(terms.claimTip)],
128
200
  ["provider", terms.maker],
129
201
  ["registry", terms.registry],
@@ -131,6 +203,10 @@ function checkOrderQuote(quote, terms, nowSec) {
131
203
  for (const [field, want] of pairs) {
132
204
  if (!same(quote[field], want)) throw new SdkError("quote-refused", { step: "answer", why: "field", field });
133
205
  }
206
+ // THE XMR SIDE IS ALLOWED TO BE BETTER, NOT WORSE. `ask` may sign at least the requested amount; `bid` may sign
207
+ // at most it. The ETH `amount` above stays exact because it is part of the proof context.
208
+ const xmr = xmrAmountVerdict({ side: terms.side, requested: terms.xmrAmount, signed: quote.xmrAmount });
209
+ if (!xmr.ok) throw new SdkError("quote-refused", { step: "answer", why: "field", field: "xmrAmount" });
134
210
  if (same(quote.feeRecipient, ZERO)) {
135
211
  throw new SdkError("quote-refused", { step: "answer", why: "fee-recipient" });
136
212
  }
@@ -143,10 +219,15 @@ function checkOrderQuote(quote, terms, nowSec) {
143
219
  throw new SdkError("quote-refused", { step: "answer", why: "fee" });
144
220
  }
145
221
  if (fee !== (amount * BigInt(bps)) / 10000n) throw new SdkError("quote-refused", { step: "answer", why: "fee" });
146
- const validUntil = Number(quote.validUntil);
222
+ const validUntil = wireNumber(quote.validUntil, "quote.validUntil");
147
223
  if (!Number.isSafeInteger(validUntil) || validUntil <= nowSec) {
148
224
  throw new SdkError("quote-expired", { step: "answer", validUntil: quote.validUntil });
149
225
  }
226
+ const readyBy = wireNumber(order.readyBy, "order.readyBy");
227
+ const t1 = wireNumber(order.t1, "order.t1");
228
+ if (!Number.isSafeInteger(readyBy) || !Number.isSafeInteger(t1) || readyBy >= t1 || validUntil >= readyBy) {
229
+ throw new SdkError("quote-refused", { step: "answer", why: "validity", field: "validUntil" });
230
+ }
150
231
  }
151
232
 
152
233
  /**
@@ -164,7 +245,7 @@ export function verifyFirmAnswer({ answer, features, request, now = null } = {})
164
245
  if (!payload || typeof payload !== "object" || !payload.quote) {
165
246
  throw new SdkError("quote-refused", { step: "answer", why: "payload" });
166
247
  }
167
- if (payload.contextVersion !== "ninsei-order-v3" || Number(payload.quoteVersion) !== 10) {
248
+ if (payload.contextVersion !== "ninsei-order-v3" || wireNumber(payload.quoteVersion, "payload.quoteVersion") !== 10) {
168
249
  throw new SdkError("quote-refused", { step: "answer", why: "version" });
169
250
  }
170
251
  if (!same(payload.factory, request.terms.order.factory)) {
package/src/relayView.mjs CHANGED
@@ -66,9 +66,9 @@ export function relayViewInfo({ termsDigest, commitHalf, edPoint, edViewPointCli
66
66
  // One sender context, one Seal. The relay spec forbids reusing an ephemeral key for another encryption, so
67
67
  // the context is created here and never exposed.
68
68
  export async function sealViewEnvelope({ hpkeKey, info, plaintext } = {}) {
69
- // The two plaintext lengths are part of the wire contract: ask carries the node's view scalar, bid carries
70
- // the node's scalar followed by the client's. A caller that passes another length is refused before any
71
- // network or cryptographic work.
69
+ // Both current request paths seal 64 bytes: the node's view scalar followed by the client's. A 32-byte body is
70
+ // still accepted for older vectors, but no current request produces one; a caller that passes another length is
71
+ // refused before any network or cryptographic work.
72
72
  const publicKey = hexToBytes(hpkeKey, 32, "hpkeKey");
73
73
  const body = bytesOf(plaintext);
74
74
  if (body.length !== 32 && body.length !== 64) {
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
@@ -28,10 +28,20 @@
28
28
  // is the RULES, not the crypto.
29
29
  import { SdkError } from "./errors.mjs";
30
30
  import * as engine from "./engine.mjs";
31
+ // THE HALF'S COMMITMENT, COMPUTED LOCALLY. The escrow checks the low 160 bits of `keccak256(x||y)` of `half*G`
32
+ // (NinseiEscrow.halfMatchesCommit); the same formula runs here, so an action is compared with the order without
33
+ // the half ever leaving this process.
34
+ import { halfCommitmentHex } from "../engine/atomic/orderHalfCommit.js";
35
+ import { keccak256, secp256k1 } from "./primitives.mjs";
31
36
  // THE MAKER'S DECLINE (issue #40) - the escrow's `Declined` event and the neutral vocabulary the state is
32
37
  // reported in. It is its own module because TWO surfaces ask the same question (this flow and the swaps watch)
33
38
  // and a second implementation of the same event would be a second truth about it.
34
39
  import { declinedFromLogs, logReaderOf, blockBoundaryOf, DECLINED_TOPIC0 } from "./decline.mjs";
40
+ // THE ORDER SIDE IS BUILT IN-PROCESS, by the same engine builder the record and the facade use. The old
41
+ // browser worker shipped its own copy of the crypto bundle. Its verifySide checked the DLEQ equation but not
42
+ // that the proven point matched the quote's commitment; the package no longer needs a second build of the same
43
+ // primitives.
44
+ import { buildOwnSideChunked, orderStepChunked } from "./order.mjs";
35
45
 
36
46
  // THE ENGINE SURFACES, TAKEN THROUGH THE ONE SEAM (./engine.mjs) - exactly as the rest of the core does.
37
47
  const { chainById, DEFAULT_CHAIN, MONERO } = engine.config;
@@ -42,9 +52,8 @@ const {
42
52
  } = engine.escrow;
43
53
  // THE COUNTERPARTY GUARDS: whether a stand-in may be signed on this chain.
44
54
  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;
55
+ // THE ORDER CONTEXT, THE ORDER QUOTE AND THE SHARED CLAIM GAS LIMIT - all through the mirror, so the page and
56
+ // the package never keep a second copy of these rules.
48
57
  const { orderContextString } = engine.orderContext;
49
58
  const { requestOrderQuote, checkOrderQuoteShape } = engine.rfqSource;
50
59
  const { CLAIM_GAS_LIMIT } = engine.claimGas;
@@ -72,15 +81,13 @@ export async function runAtomicOrder({
72
81
  chainSlug, locker, claimer, amountWei, amountLabel, providerId = null,
73
82
  xmrNetwork = null,
74
83
  claimWindowSeconds = 3600, readyWindowSeconds = 14400, salt: providedSalt, onStage,
75
- // THE SUBSTITUTION POINTS FOR THE SAKE OF THE CHECK, and they are not decoration. The live flow could be
76
- // neither run in a check nor covered otherwise: it requires a browser Worker and a signature in the wallet.
77
- // Because of that two defects in a row appeared in it that neither the syntax nor the suite could see: the
78
- // signature did not accept the mandatory fields, and after the fix a reference to a variable outside its scope
79
- // remained - such things are visible only in operation. The defaults here are real: substitution is only in
80
- // checks.
84
+ // THE SUBSTITUTION POINTS FOR THE SAKE OF THE CHECK, and they are not decoration. The live flow reaches a
85
+ // wallet and a chain; the check drives the same sequence with synthetic sides. The defaults here are real:
86
+ // substitution is only in checks.
81
87
  deps = {},
82
88
  }) {
83
- const makeWorker = deps.createOrderWorker || createOrderWorker;
89
+ const buildSide = deps.buildOwnSide || buildOwnSideChunked;
90
+ const stepOrder = deps.orderStep || orderStepChunked;
84
91
  const fundLive = deps.fundOrderLive || fundOrderLive;
85
92
  const askQuote = deps.requestOrderQuote || requestOrderQuote;
86
93
  const factory = escrowFactoryAddress(chainSlug);
@@ -124,9 +131,8 @@ export async function runAtomicOrder({
124
131
  // commitments and BOTH public ed25519 points, and the half is published by the settlement itself
125
132
  // (claim/refund). The secret that used to be placed in the recovery file is now MY HALF: it is exactly what is
126
133
  // needed to claim the XMR.
127
- const worker = makeWorker();
128
134
  const say = (stage, detail) => onStage?.(stage, detail);
129
- try {
135
+ {
130
136
  // THE QUOTE FIRST, THEN YOUR OWN SIDE. The order of steps is set by the fact that the claimer is named by the
131
137
  // provider: the half binding includes the claimer's address, so our own half must be computed over the
132
138
  // context that is already fully known. It used to be the other way round, and the provider got an order with
@@ -157,7 +163,15 @@ export async function runAtomicOrder({
157
163
  const orderContext = orderContextString(order);
158
164
 
159
165
  say("half", "side");
160
- const mine = await worker.buildSide(orderContext, say);
166
+ // THE PROOF AND THE VERIFICATION YIELD BETWEEN CHUNKS. `runAtomicOrder` is already async, so the browser can
167
+ // paint while the same engine builder does the arithmetic.
168
+ const chunkOptions = {
169
+ onBit: (bit, total) => say("proof", `proving DLEQ proof: ${bit} of ${total} bits`),
170
+ onProgress: (step) => say("verify", step.phase === "sum"
171
+ ? `summing commitments: ${step.done} of ${step.total}`
172
+ : `verifying DLEQ proof: ${step.done} of ${step.total}`),
173
+ };
174
+ const mine = await buildSide(order, chunkOptions);
161
175
  say("half", "side-ready");
162
176
 
163
177
  // The counterparty stand-in. Honestly: only a real counterparty with its own key gives a guarantee; a
@@ -193,9 +207,7 @@ export async function runAtomicOrder({
193
207
  // THE STAND-IN IS COMPUTED OVER THE SAME CONTEXT AS THE ORDER. It used to append ":counterparty" to the
194
208
  // string, and that turned the check into a ritual: the stand-in's proof was bound to a different string,
195
209
  // that is, to nothing. Now exactly the path a real provider would take is checked.
196
- const mock = await worker.buildSide(orderContext);
197
- counter = { proof: mock.proof, edPub: mock.pub.ed, mock, viewHalf: mock.viewHalf, viewPoint: mock.viewPub,
198
- commitHalfClaimer: (await worker.halfCommitment(mock.half)).commitment };
210
+ counter = null;
199
211
  }
200
212
  // THE COUNTERPARTY CHECK REMAINS ONE AND IT IS THE MAIN ONE: the DLEQ proof in the context of this order.
201
213
  // It confirms that both public points stand for ONE scalar - that is, that the half declared for the Monero
@@ -204,16 +216,18 @@ export async function runAtomicOrder({
204
216
  // TOGETHER WITH IT, the fact is checked that the proven ed25519 point IS THE VERY ONE the contract will
205
217
  // receive: without that check a correct proof would guarantee nothing about the chain.
206
218
  say("verify", "dleq");
207
- const verdict = await worker.verifyCounterparty(orderContext, {
208
- proof: counter.proof, edPub: counter.edPub, commitHalfClaimer: counter.commitHalfClaimer,
209
- }, null);
210
- if (!verdict.ok) throw new SdkError("quote-refused", { step: "proof", why: "rejected" });
219
+ const step = await stepOrder({
220
+ order, side: mine.side, counterparty: counter, standIn: !quote,
221
+ network: xmrNetwork || (chain.monero && chain.monero.networkType) || MONERO.networkType,
222
+ options: chunkOptions,
223
+ });
224
+ const accepted = step.counterparty;
211
225
 
212
- // COMMITMENTS ON BOTH HALVES: our own is computed in the worker (only the hash goes out), the counterparty's
213
- // either arrived in the quote or is computed over the stand-in's half. Exactly these values are checked by
214
- // the contract in claim and refund and are included in termsHash.
215
- const commitHalfLocker = (await worker.halfCommitment(mine.half)).commitment;
216
- const commitHalfClaimer = counter.commitHalfClaimer || (await worker.halfCommitment(counter.mock.half)).commitment;
226
+ // COMMITMENTS ON BOTH HALVES: our own and the counterparty's are the ones the proof was verified against,
227
+ // by the same builder the contract and the recovery file use. Exactly these values are checked by the
228
+ // contract in claim and refund and are included in termsHash.
229
+ const commitHalfLocker = step.wallet.commitHalfLocker;
230
+ const commitHalfClaimer = step.wallet.commitHalfClaimer;
217
231
 
218
232
  // THE SHARED MONERO ADDRESS - FROM THE HALVES, AND IT IS COMPUTED BEFORE THE MONEY IS LOCKED. The address used
219
233
  // to be assembled from the maker's seed, that is, from the FULL key on its side: that is a custodial scheme,
@@ -223,16 +237,12 @@ export async function runAtomicOrder({
223
237
  // We compute it BEFORE funding on purpose: the address is derived from the same points that will go into the
224
238
  // contract, and if it cannot be assembled (the counterparty has neither a point nor a view half), we must
225
239
  // learn about it before the user signs the deposit.
226
- const otherViewPoint = counter.viewPoint || (counter.viewHalf ? (await worker.pointOf(counter.viewHalf)).ed : null);
240
+ const otherViewPoint = step.wallet.otherViewPoint;
227
241
  if (!otherViewPoint) {
228
242
  throw new SdkError("quote-refused", { step: "view-half" });
229
243
  }
230
244
  say("address", "joint-address");
231
- const joint = await worker.jointAddress({
232
- ownSpendHalf: mine.half, ownViewHalf: mine.viewHalf,
233
- otherSpendPoint: counter.edPub, otherViewPoint,
234
- network: xmrNetwork || (chain.monero && chain.monero.networkType) || MONERO.networkType,
235
- });
245
+ const joint = { address: step.wallet.address, spendPub: step.wallet.spendPub, viewPub: step.wallet.viewPub };
236
246
 
237
247
  // THE COUNTERPARTY STAND-IN ON A LIVE NETWORK IS A REFUSAL, NOT A SIGNATURE (the auditor's finding, review_02
238
248
  // section 6.3 and block D1, item 5). Without a provider the counterparty side is assembled locally, the proof
@@ -271,10 +281,10 @@ export async function runAtomicOrder({
271
281
  // The ed25519 points go into the order explicitly: the other side assembles the shared address from them
272
282
  // and checks the proof EXACTLY against the on-chain fields, not against what arrived in the quote (doc 27
273
283
  // section 11).
274
- edPointLocker: mine.pub.ed, edPointClaimer: counter.edPub,
284
+ edPointLocker: step.own.spendPoint, edPointClaimer: accepted.edPub,
275
285
  // THE DEPOSITOR'S VIEW POINT: from it the claimer assembles the address FROM THE ORDER FIELDS. Without it
276
286
  // it does not know where to send the XMR - and learns about it only after the money is deposited.
277
- edViewPointLocker: mine.viewPub,
287
+ edViewPointLocker: step.own.viewPoint,
278
288
  salt, // our swap salt: see funding.js
279
289
  amountLabel, // the ready amount string for the label: formatting lives in the UI
280
290
  amountWei,
@@ -296,19 +306,19 @@ export async function runAtomicOrder({
296
306
  feeWei: (funded && funded.feeWei) || 0n,
297
307
  feeTotalWei: (funded && funded.feeTotalWei) || null,
298
308
  feeBps: (funded && funded.feeBps) || 0,
299
- half: mine.half,
300
- counterHalf: standIn ? counter.mock.half : null,
309
+ half: step.side.half,
310
+ counterHalf: standIn ? accepted.half : null,
301
311
  // THE VIEW HALVES: our own and the counterparty's. Without them the address cannot be assembled and the
302
312
  // version 3 recovery file cannot be filled in, and without the file the user will not claim the XMR after
303
313
  // losing the tab.
304
- viewHalf: mine.viewHalf,
314
+ viewHalf: step.side.viewHalf,
305
315
  commitHalfLocker,
306
316
  commitHalfClaimer,
307
- edPointLocker: mine.pub.ed,
308
- edPointClaimer: counter.edPub,
317
+ edPointLocker: step.own.spendPoint,
318
+ edPointClaimer: accepted.edPub,
309
319
  // THE DEPOSITOR'S VIEW POINT goes into the record: without it there is nothing to compare the chain slot
310
320
  // edViewPointLocker against before signing - and it is part of the address the claimer will see.
311
- edViewPointLocker: mine.viewPub,
321
+ edViewPointLocker: step.own.viewPoint,
312
322
  // THE COUNTERPARTY'S VIEW HALF: the stand-in has it, a real provider does NOT, and this is a known gap of
313
323
  // the protocol, not a trifle: without its view half the shared Monero address cannot be assembled. While
314
324
  // the address in the application is built the previous way, the path does not break, but a quote under the
@@ -316,7 +326,7 @@ export async function runAtomicOrder({
316
326
  // ONE KIND OF HALF ON THE OUTPUT, and this is not pedantry: the stand-in's half is a number, the provider's
317
327
  // arrives as a string, and the consumer (the recovery file and the sweep) must not guess which it was
318
328
  // given. Next to the spend half, which is also a number.
319
- counterViewHalf: standIn ? counter.mock.viewHalf : BigInt(counter.viewHalf),
329
+ counterViewHalf: accepted.viewHalf === null || accepted.viewHalf === undefined ? null : BigInt(accepted.viewHalf),
320
330
  counterViewPoint: otherViewPoint,
321
331
  // THE SHARED ADDRESS: where the maker sends the XMR. Nobody can spend from it before the half is revealed.
322
332
  moneroAddress: joint.address,
@@ -329,8 +339,6 @@ export async function runAtomicOrder({
329
339
  // order_ref is empty (the regular payout does not reach the order).
330
340
  quoteId: (quote && quote.id) || null,
331
341
  };
332
- } finally {
333
- worker.stop();
334
342
  }
335
343
  }
336
344
 
@@ -356,7 +364,7 @@ export async function orderStatus(escrow, deps = {}) {
356
364
  // the engine read. The page goes through the bridge, which hands in the wallet's own reader, so the state is
357
365
  // read by the same wallet that will sign.
358
366
  const call = deps.call || readContract;
359
- const raw = await call({ to: escrow, data: encodeStatus() });
367
+ const raw = await call({ to: escrow, data: encodeStatus(), block: deps.blockTag || "latest" });
360
368
  return decodeStatus(raw);
361
369
  }
362
370
 
@@ -395,13 +403,14 @@ export async function orderDeadlines(escrow, deps = {}) {
395
403
  // THE SAME READER SEAM AS orderStatus: the deadline must be read by the wallet that will sign, not by a second
396
404
  // provider.
397
405
  const call = deps.call || readContract;
406
+ const block = deps.blockTag || "latest";
398
407
  const [raw1, rawH, rawReadyBy] = await Promise.all([
399
- call({ to: escrow, data: encodeT1() }),
400
- call({ to: escrow, data: encodeTermsHash() }),
408
+ call({ to: escrow, data: encodeT1(), block }),
409
+ call({ to: escrow, data: encodeTermsHash(), block }),
401
410
  // THE READY-MARK DEADLINE IS READ HERE TOO: without it the screen cannot say that the person is already in
402
- // the dead zone (the mark is closed, claiming is closed, refunding is not open yet) - and that is exactly
411
+ // the dead zone (the mark is closed, the claim is open, refunding is not open yet) - and that is exactly
403
412
  // where the deal hangs silently.
404
- call({ to: escrow, data: encodeRead("readyBy") }),
413
+ call({ to: escrow, data: encodeRead("readyBy"), block }),
405
414
  ]);
406
415
  // An empty eth_call response means there is NO CODE at the address: the contract is not deployed. This happens
407
416
  // when the createOrder transaction did not go through (for example the wallet rejected it over the fee) while
@@ -433,7 +442,8 @@ export async function orderLiveSlots(escrow, deps = {}) {
433
442
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
434
443
  const keys = ["edPointLocker", "edPointClaimer", "edViewPointLocker", "commitHalfLocker", "commitHalfClaimer"];
435
444
  try {
436
- const raws = await Promise.all(keys.map((k) => call({ to: escrow, data: encodeRead(k) })));
445
+ const block = deps.blockTag || "latest";
446
+ const raws = await Promise.all(keys.map((k) => call({ to: escrow, data: encodeRead(k), block })));
437
447
  const slots = {};
438
448
  keys.forEach((k, i) => { slots[k] = decodeBytes32(raws[i], k + "()"); });
439
449
  return { slots };
@@ -471,24 +481,93 @@ async function assertOrderOpen(escrow, what, deps) {
471
481
  async function assertActionWindow(escrow, what, deps, now = null) {
472
482
  if (typeof deps.blockTime !== "function") return;
473
483
  const call = deps.call || readContract;
484
+ const block = deps.blockTag || "latest";
474
485
  const [readyRaw, deadlines] = await Promise.all([
475
- call({ to: escrow, data: encodeRead("ready") }),
486
+ call({ to: escrow, data: encodeRead("ready"), block }),
476
487
  orderDeadlines(escrow, deps),
477
488
  ]);
478
489
  const marked = BigInt(readyRaw) !== 0n;
479
490
  const at = now === null ? Number(await deps.blockTime()) : Number(now);
480
- if (!Number.isSafeInteger(at) || at <= 0) return; // no chain time: do not sign a time verdict
491
+ // A HALF-REVEALING SEND NEEDS A READABLE CLOCK. Without it the deadline rule would be skipped, and a claim or
492
+ // refund that lands after its window still publishes the half. The actions facade always brings this seam.
493
+ if (!Number.isSafeInteger(at) || at <= 0) {
494
+ throw new SdkError("contract-reverted", { step: what, why: "clock-unreadable" });
495
+ }
496
+ // A TRANSACTION LANDS IN A LATER BLOCK. Keep a margin before every deadline so a send that is valid when signed
497
+ // does not become a revert that publishes the half.
498
+ const margin = 60;
481
499
  if (what === "claim") {
482
- if (at >= Number(deadlines.t1)) throw new SdkError("contract-reverted", { step: what, why: "window-closed" });
500
+ if (at + margin >= Number(deadlines.t1)) throw new SdkError("contract-reverted", { step: what, why: "window-closed" });
483
501
  if (!marked && at < Number(deadlines.readyBy)) throw new SdkError("contract-reverted", { step: what, why: "not-ready" });
484
502
  } else if (what === "refund") {
485
503
  // refund(): before t1 it is allowed only while the mark is absent and readyBy has not passed.
486
- if (at < Number(deadlines.t1) && (at >= Number(deadlines.readyBy) || marked)) {
504
+ if (at < Number(deadlines.t1) && (at + margin >= Number(deadlines.readyBy) || marked)) {
487
505
  throw new SdkError("contract-reverted", { step: what, why: "too-early" });
488
506
  }
489
507
  } else if (what === "mark-ready") {
490
508
  if (marked) throw new SdkError("contract-reverted", { step: what, why: "already-ready" });
491
- if (at >= Number(deadlines.readyBy)) throw new SdkError("contract-reverted", { step: what, why: "ready-window-closed" });
509
+ if (at + margin >= Number(deadlines.readyBy)) throw new SdkError("contract-reverted", { step: what, why: "ready-window-closed" });
510
+ }
511
+ }
512
+
513
+ // THE ACTION IS EXECUTED ON PAPER BEFORE IT IS SIGNED. `eth_call` runs the same call against the latest state
514
+ // from the same sender, so a revert becomes a named refusal instead of a mined transaction that changed nothing.
515
+ // The guards above answer the questions we know how to ask; this answers the contract itself, including its own
516
+ // deadlines. A caller without a call seam keeps the old behaviour.
517
+ //
518
+ // IT IS NOT USED FOR AN ACTION THAT CARRIES A HALF. A claim or a refund puts the half in the calldata, and the
519
+ // dry run would hand it to the RPC operator before any money moves; see assertHalfMatchesCommit below.
520
+ async function simulateAction(escrow, data, what, deps) {
521
+ const call = deps.call;
522
+ if (typeof call !== "function") return;
523
+ try {
524
+ await call({ to: escrow, data, from: deps.from });
525
+ } catch (error) {
526
+ const detail = error && (error.data || error.message);
527
+ const message = String((error && error.message) || "");
528
+ // A transport or wallet failure is not a revert. Keep it as it came: only a contract answer is turned into
529
+ // this action's refusal.
530
+ const reverted = (error && error.code === "contract-reverted")
531
+ || (error && typeof error.data === "string" && error.data.startsWith("0x"))
532
+ || /execution reverted|revert/i.test(message);
533
+ if (!reverted) throw error;
534
+ throw new SdkError("contract-reverted", {
535
+ step: what,
536
+ why: "simulation",
537
+ detail: typeof detail === "string" ? detail.slice(0, 200) : null,
538
+ });
539
+ }
540
+ }
541
+
542
+ // A DRY RUN MUST NOT HAND THE HALF TO THE RPC. `eth_call` goes to a public endpoint by default, so simulating
543
+ // `claim(half)` or `refund(half)` publishes the half to a third party while the escrow is still open and the ETH
544
+ // has not moved. Whoever keeps that call holds both halves of the Monero key when the person declines the
545
+ // transaction in the wallet or the send never lands (sdk#291).
546
+ //
547
+ // The simulation added exactly one check, and it is arithmetic: the half's point commitment must equal the
548
+ // order's. The contract compares the LOW 160 BITS of `keccak256(x||y)` of `half*G`
549
+ // (NinseiEscrow.halfMatchesCommit); the same formula runs here over the half we hold, against the slot READ FROM
550
+ // THE ESCROW. Every other refusal the contract can give (closed, unfunded, not ready, window closed) is answered
551
+ // by the state and clock guards above, before this line.
552
+ const low160Hex = (value) => String(value == null ? "" : value).replace(/^0x/i, "").toLowerCase().slice(-40);
553
+ async function assertHalfMatchesCommit(escrow, half, slot, what, deps) {
554
+ const field = what === "claim" ? "halfClaimer" : "halfLocker";
555
+ let got;
556
+ try {
557
+ got = low160Hex(halfCommitmentHex(BigInt(half), secp256k1, keccak256));
558
+ } catch {
559
+ throw new SdkError("bad-input", { field });
560
+ }
561
+ const call = deps.call || readContract;
562
+ let commit;
563
+ try {
564
+ commit = decodeBytes32(await call({ to: escrow, data: encodeRead(slot), block: deps.blockTag || "latest" }), slot + "()");
565
+ } catch {
566
+ // AN UNREAD ORDER IS NOT A MATCHING ONE.
567
+ throw new SdkError("contract-reverted", { step: what, why: "slots-unreadable" });
568
+ }
569
+ if (got !== low160Hex(commit)) {
570
+ throw new SdkError("contract-reverted", { step: what, why: "half-mismatch" });
492
571
  }
493
572
  }
494
573
 
@@ -501,13 +580,16 @@ async function assertActionWindow(escrow, what, deps, now = null) {
501
580
  export async function claimOrder({ escrow, halfClaimer, expect, onStep, deps = {} }) {
502
581
  if (!escrow) throw new SdkError("bad-input", { field: "escrow" });
503
582
  if (!halfClaimer) throw new SdkError("bad-input", { field: "halfClaimer" });
504
- // STATE, TIME AND SLOTS BEFORE SIGNING: a claim reveals the half, and it must be revealed in the VERY order
505
- // whose commitments we know, while that order is open. The contract's ready rule is TIME-DEPENDENT: before
583
+ // STATE, TIME, SLOTS AND THE HALF BEFORE SIGNING: a claim reveals the half, and it must be revealed in the VERY
584
+ // order whose commitments we know, while that order is open. The contract's ready rule is TIME-DEPENDENT: before
506
585
  // `readyBy` it requires the mark, after `readyBy` it allows a claim without it. Both are checked from the
507
586
  // chain's own timestamp when the actions facade brings one.
508
587
  await assertOrderOpen(escrow, "claim", deps);
509
588
  await assertActionWindow(escrow, "claim", deps);
510
589
  await assertOrderSlots(escrow, expect, "claim", deps);
590
+ // THE HALF IS CHECKED HERE, NOT BY A DRY RUN: the escrow's own comparison, computed locally and read against
591
+ // the order. No call carries the half until the send.
592
+ await assertHalfMatchesCommit(escrow, halfClaimer, "commitHalfClaimer", "claim", deps);
511
593
  onStep?.("confirm-claim");
512
594
  // THE CLAIM GAS LIMIT COMES FROM THE SHARED MODULE, NOT A LITERAL HERE (issue #127): the node lays exactly
513
595
  // this limit into the gas gift. It is set explicitly and with a margin: claim has the same trap as order
@@ -535,6 +617,9 @@ export async function refundOrder({ escrow, halfLocker, onStep, expect = null, d
535
617
  // for the same reason. Expectations are optional for compatibility with previous calls (the page calls without
536
618
  // them); the core always passes them.
537
619
  if (expect) await assertOrderSlots(escrow, expect, "refund", deps);
620
+ // THE SAME LOCAL CHECK ON THE DEPOSITOR'S HALF. A refund reveals it exactly as a claim reveals the claimer's,
621
+ // so it is compared with the escrow's `commitHalfLocker` before the signature and never sent to a dry run.
622
+ await assertHalfMatchesCommit(escrow, halfLocker, "commitHalfLocker", "refund", deps);
538
623
  onStep?.("confirm-refund");
539
624
  const hash = await (deps.send || sendTransaction)({ to: escrow, data: encodeRefund(halfLocker), gas: 250_000n });
540
625
  return { hash };
@@ -552,6 +637,7 @@ export async function markReadyOrder({ escrow, expect, onStep, deps = {} }) {
552
637
  await assertOrderOpen(escrow, "mark-ready", deps);
553
638
  await assertActionWindow(escrow, "mark-ready", deps);
554
639
  await assertOrderSlots(escrow, expect, "mark-ready", deps);
640
+ await simulateAction(escrow, encodeMarkReady(), "mark-ready", deps);
555
641
  onStep?.("confirm-mark-ready");
556
642
  const hash = await (deps.send || sendTransaction)({ to: escrow, data: encodeMarkReady(), gas: 120_000n });
557
643
  return { hash };