@ninsei-labs/sdk 0.56.1 → 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 (55) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE-POLICY.md +9 -2
  3. package/README.md +17 -4
  4. package/THIRD_PARTY_NOTICES.md +174 -0
  5. package/assets/vendors/MANIFEST.json +1 -5
  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 +17 -24
  10. package/engine/core/deployments.generated.js +103 -0
  11. package/engine/core/swap.js +7 -7
  12. package/engine/evm/asyncRoute.js +1 -1
  13. package/engine/evm/claimGas.js +2 -1
  14. package/engine/evm/escrow.js +13 -8
  15. package/engine/evm/factory.js +11 -6
  16. package/engine/evm/funding.js +8 -3
  17. package/engine/evm/index.js +2 -4
  18. package/engine/evm/session.js +3 -3
  19. package/engine/monero/scan.js +101 -22
  20. package/engine/recovery/restore.js +8 -8
  21. package/engine/sdk/bridge.js +2 -5
  22. package/index.d.ts +48 -11
  23. package/package.json +4 -2
  24. package/src/actions.mjs +8 -5
  25. package/src/codes.mjs +5 -0
  26. package/src/config.mjs +1 -0
  27. package/src/engine.mjs +6 -6
  28. package/src/feeEstimate.mjs +11 -4
  29. package/src/http.mjs +4 -1
  30. package/src/index.mjs +1 -1
  31. package/src/legs/kyber.mjs +23 -0
  32. package/src/lock.mjs +1 -0
  33. package/src/order.mjs +108 -20
  34. package/src/primitives.mjs +4 -5
  35. package/src/probes.mjs +9 -3
  36. package/src/public/networks.d.ts +45 -0
  37. package/src/public/networks.mjs +10 -1
  38. package/src/public/xmr.mjs +1 -1
  39. package/src/quotes.mjs +97 -23
  40. package/src/recovery-key.mjs +32 -14
  41. package/src/relayFeatures.mjs +25 -13
  42. package/src/relayFirmClient.mjs +33 -7
  43. package/src/relayQuote.mjs +87 -10
  44. package/src/relayView.mjs +3 -3
  45. package/src/swap-flow.mjs +100 -58
  46. package/src/swaps.mjs +234 -64
  47. package/src/sweep-restore.mjs +8 -4
  48. package/src/sweep.mjs +5 -1
  49. package/src/version.mjs +1 -1
  50. package/src/xmr-arrival.mjs +55 -24
  51. package/assets/vendors/atomic/atomic-browser.js +0 -24
  52. package/engine/atomic/order-client.js +0 -56
  53. package/engine/atomic/order-worker.js +0 -156
  54. package/engine/evm/asyncExec.js +0 -577
  55. package/engine/evm/asyncLegs.js +0 -308
package/src/http.mjs CHANGED
@@ -60,7 +60,10 @@ export function createHttp({ apiBase, fetchImpl = null, timeoutMs = 20_000 }) {
60
60
  const res = await impl(apiBase + path, init);
61
61
  if (!res || typeof res.ok !== "boolean") throw new SdkError("server-unavailable", { why: "bad-response" });
62
62
  let parsed = null;
63
- try { parsed = await res.json(); } catch { parsed = null; }
63
+ // A BODY CUT BY THE TIMEOUT IS NOT AN EMPTY ANSWER. Returning null made a broken response look like a
64
+ // service that answered with no data; the caller then reported the wrong refusal.
65
+ try { parsed = await res.json(); }
66
+ catch { throw new SdkError("server-unavailable", { why: "body" }); }
64
67
  return { ok: res.ok, status: res.status, body: parsed };
65
68
  } catch (error) {
66
69
  if (error instanceof SdkError) throw error;
package/src/index.mjs CHANGED
@@ -295,7 +295,7 @@ export function createNinsei(options) {
295
295
  // THE PATHS, THE POLL TIMINGS AND THE PASS GO INTO THE START: without the configuration the "server" step
296
296
  // would not know where to knock, and without the pass there is nothing to present to the service (and that
297
297
  // is a refusal with a CODE, not an invented path).
298
- swaps: createSwaps({ preflight, http, mode: o.mode, xmrNetwork: o.xmrNetwork, call: o.evmCall, store,
298
+ swaps: createSwaps({ preflight, http, mode: o.mode, xmrNetwork: o.xmrNetwork, call: o.evmCall, now: o.now || null, evmBlock: o.evmBlock || null, store,
299
299
  // THE LOG SEAM FOR THE DECLINE CHECK: the watch asks the escrow for its `Declined` event on every tick, so
300
300
  // a declined order stops the wait at once instead of running to `xmr-timeout`.
301
301
  logs: o.evmLogs || null,
@@ -229,6 +229,29 @@ export async function kyberUnsignedOrder({ params, chainId = null, fetchImpl = n
229
229
  if (typeNames !== expectedNames) return refusal("kyber-bad-response", { where: "sign-message", field: "types" });
230
230
  const missing = kyberOrderMissingFields(message);
231
231
  if (missing.length) return refusal("kyber-bad-response", { where: "sign-message", missing });
232
+ // THE SERVICE MUST SIGN THE ORDER WE ASKED FOR. A receiver, maker or asset it chooses for us is a valid order
233
+ // for someone else; compare every field the request fixed before the typed data reaches the wallet.
234
+ const addresses = ["maker", "makerAsset", "takerAsset", "receiver"];
235
+ for (const field of addresses) {
236
+ if (String(message[field] || "").toLowerCase() !== String(params[field] || "").toLowerCase()) {
237
+ return refusal("kyber-bad-response", { where: "sign-message", field });
238
+ }
239
+ }
240
+ for (const field of ["makingAmount", "takingAmount"]) {
241
+ if (String(message[field]) !== String(params[field])) {
242
+ return refusal("kyber-bad-response", { where: "sign-message", field });
243
+ }
244
+ }
245
+ // A REQUEST THAT LIMITS WHO MAY FILL THE ORDER MUST NOT BE WIDENED. The signed field is one address; zero means
246
+ // anyone. When the request fixed a list, the service must name one of its members (a narrower choice is fine,
247
+ // "anyone" is not).
248
+ const allowed = params.allowedSenders === undefined || params.allowedSenders === null
249
+ ? null
250
+ : (Array.isArray(params.allowedSenders) ? params.allowedSenders : [params.allowedSenders])
251
+ .map((value) => String(value || "").toLowerCase());
252
+ if (allowed && allowed.length && !allowed.includes(String(message.allowedSender || "").toLowerCase())) {
253
+ return refusal("kyber-bad-response", { where: "sign-message", field: "allowedSender" });
254
+ }
232
255
  let digest;
233
256
  try {
234
257
  digest = kyberOrderDigestHex({ order: message, chainId: id, contract });
package/src/lock.mjs CHANGED
@@ -98,6 +98,7 @@ export async function send(request, wallet, deps = {}) {
98
98
  return await evm.fundOrder({
99
99
  ...canonical,
100
100
  call: reader,
101
+ onPredicted: deps.onPredicted,
101
102
  send: (tx) => wallet.send({ ...tx, chainId: canonical.chainId, from: canonical.locker }),
102
103
  // NORMALISING THE RECEIPT ARGUMENT'S SHAPE - HERE, AT THE CORE'S BOUNDARY, NOT AT EVERY CALLER.
103
104
  //
package/src/order.mjs CHANGED
@@ -137,27 +137,73 @@ export function buildOwnSide(order, onBit) {
137
137
  return { context, side, spendPoint: norm(side.pub.ed), viewPoint: norm(side.viewPub), encPub: norm(side.enc.pub) };
138
138
  }
139
139
 
140
+ /**
141
+ * The same side, with the proof yielding between chunks. The synchronous `buildOwnSide` remains the entry for
142
+ * callers that cannot await; both drain the same engine builder.
143
+ */
144
+ export async function buildOwnSideChunked(order, options = {}) {
145
+ const context = contextOf(order);
146
+ const side = await builder().newSideChunked(context, false, options);
147
+ return { context, side, spendPoint: norm(side.pub.ed), viewPoint: norm(side.viewPub), encPub: norm(side.enc.pub) };
148
+ }
149
+
140
150
  /**
141
151
  * OUR SIDE FROM HALVES WE ALREADY HAVE - the one recovery key case. A random side would be a second secret,
142
152
  * which is exactly what one key removes. The proof is still bound to this order and built by the same engine
143
153
  * builder; only the source of the two numbers changes.
144
154
  */
145
- export function buildOwnSideFromHalves(order, { spendHalf, viewHalf } = {}) {
146
- const context = contextOf(order);
147
- const b = builder();
155
+ function knownHalves(builderInstance, { spendHalf, viewHalf } = {}) {
148
156
  const scalar = (value, name) => {
149
157
  const n = BigInt(value);
150
- if (n <= 0n || n >= BigInt(b.halves.LIMIT)) throw new SdkError("bad-input", { field: name });
158
+ if (n <= 0n || n >= BigInt(builderInstance.halves.LIMIT)) throw new SdkError("bad-input", { field: name });
151
159
  return n;
152
160
  };
153
161
  const half = scalar(spendHalf, "spendHalf");
154
162
  const view = scalar(viewHalf, "viewHalf");
155
- const pub = b.halves.publicHalves(half);
156
- const viewPub = b.halves.publicHalves(view).ed;
157
- const encPair = b.enc.recipientKeyPair();
158
- const proof = b.dleq.prove(half, context);
163
+ return {
164
+ half, view,
165
+ pub: builderInstance.halves.publicHalves(half),
166
+ viewPub: builderInstance.halves.publicHalves(view).ed,
167
+ encPair: builderInstance.enc.recipientKeyPair(),
168
+ };
169
+ }
170
+
171
+ function sideFromKnown({ half, view, pub, viewPub, encPair }, proof) {
159
172
  const side = { half, pub, viewHalf: view, viewPub, enc: encPair, proof, standIn: false };
160
- return { context, side, spendPoint: norm(pub.ed), viewPoint: norm(viewPub), encPub: norm(encPair.pub) };
173
+ return { side, spendPoint: norm(pub.ed), viewPoint: norm(viewPub), encPub: norm(encPair.pub) };
174
+ }
175
+
176
+ export function buildOwnSideFromHalves(order, { spendHalf, viewHalf } = {}) {
177
+ const context = contextOf(order);
178
+ const b = builder();
179
+ const inputs = knownHalves(b, { spendHalf, viewHalf });
180
+ const proof = b.dleq.prove(inputs.half, context);
181
+ const { side, spendPoint, viewPoint, encPub } = sideFromKnown(inputs, proof);
182
+ return { context, side, spendPoint, viewPoint, encPub };
183
+ }
184
+
185
+ /** The same known-halves side, with the DLEQ proof yielding between chunks. */
186
+ export async function buildOwnSideFromHalvesChunked(order, { spendHalf, viewHalf } = {}, options = {}) {
187
+ const context = contextOf(order);
188
+ const b = builder();
189
+ const inputs = knownHalves(b, { spendHalf, viewHalf });
190
+ const proof = await b.dleq.proveChunked(inputs.half, context, options);
191
+ const { side, spendPoint, viewPoint, encPub } = sideFromKnown(inputs, proof);
192
+ return { context, side, spendPoint, viewPoint, encPub, commitHalf: norm(b.halfCommitment(inputs.half)) };
193
+ }
194
+
195
+ /**
196
+ * THE SAME LOCAL SIDE WITHOUT A SECOND PROOF. A path that already received a verified proof in the firm request
197
+ * (or in the quote) only needs this side's points, view point, encryption key and half for the record and the
198
+ * commitment. Running `prove` again costs ~3 s and its result is never sent. The returned side deliberately has
199
+ * `proof: null`: callers that need a proof must build it, not receive a plausible-looking empty object.
200
+ */
201
+ export function buildOwnSideFromHalvesKnown(order, { spendHalf, viewHalf } = {}) {
202
+ const context = contextOf(order);
203
+ const b = builder();
204
+ const inputs = knownHalves(b, { spendHalf, viewHalf });
205
+ const { side, spendPoint, viewPoint, encPub } = sideFromKnown(inputs, null);
206
+ return { context, side, spendPoint, viewPoint, encPub, commitHalf: norm(b.halfCommitment(inputs.half)) };
161
207
  }
162
208
 
163
209
  /**
@@ -167,7 +213,7 @@ export function buildOwnSideFromHalves(order, { spendHalf, viewHalf } = {}) {
167
213
  * against its point. The sandbox stand-in is built here too and marked: it must not be passed off as a real
168
214
  * provider.
169
215
  */
170
- export function acceptCounterparty({ context, side = null, counterparty = null, standIn = false }) {
216
+ function acceptedCounterparty({ context, side = null, counterparty = null, standIn = false, mock = null }) {
171
217
  let accepted = null;
172
218
  if (counterparty && typeof counterparty === "object") {
173
219
  const pub = counterparty.pub && typeof counterparty.pub === "object" ? counterparty.pub : {};
@@ -192,14 +238,14 @@ export function acceptCounterparty({ context, side = null, counterparty = null,
192
238
  };
193
239
  } else if (standIn === true) {
194
240
  // THE STAND-IN IS COMPUTED IN THE SAME CONTEXT AS THE ORDER: the string gets nothing appended. The same path
195
- // as the page (sdk/src/swap-flow.mjs: worker.buildSide) and the flow check - otherwise what would be checked is
196
- // not what the page runs on.
197
- const mock = builder().newSide(context, true);
198
- accepted = { proof: sameFormAsPoint(mock.proof), edPub: norm(mock.pub.ed), viewPoint: norm(mock.viewPub),
199
- viewHalf: mock.viewHalf, half: mock.half,
241
+ // as the flow (sdk/src/swap-flow.mjs, buildOwnSide) and the check - otherwise what would be checked is
242
+ // not what the page runs on. A chunked caller passes the mock it already built.
243
+ const built = mock || builder().newSide(context, true);
244
+ accepted = { proof: sameFormAsPoint(built.proof), edPub: norm(built.pub.ed), viewPoint: norm(built.viewPub),
245
+ viewHalf: built.viewHalf, half: built.half,
200
246
  // THE STAND-IN DOES CARRY A COMMITMENT: it is derived from the half it just built, by the same formula
201
247
  // the contract uses. The proof check below is therefore the real one, not a path that skips it.
202
- commitHalfClaimer: norm(builder().halfCommitment(mock.half)), sealed: null, providerId: null, standIn: true, mock };
248
+ commitHalfClaimer: norm(builder().halfCommitment(built.half)), sealed: null, providerId: null, standIn: true, mock: built };
203
249
  } else {
204
250
  throw new SdkError("bad-input", { field: "counterparty" });
205
251
  }
@@ -214,6 +260,11 @@ export function acceptCounterparty({ context, side = null, counterparty = null,
214
260
  // flow the half arrives from the chain via the commit/reveal mechanism, so a locked package honestly answers
215
261
  // with a refusal rather than passing itself off as a working key handover.
216
262
  const ownEncPriv = accepted.sealed && side && side.enc ? side.enc.priv : null;
263
+ return { accepted, ownEncPriv };
264
+ }
265
+
266
+ export function acceptCounterparty({ context, side = null, counterparty = null, standIn = false }) {
267
+ const { accepted, ownEncPriv } = acceptedCounterparty({ context, side, counterparty, standIn });
217
268
  let verdict = null;
218
269
  try { verdict = builder().verifySide({ proof: accepted.proof, pub: { ed: accepted.edPub }, commitHalfClaimer: accepted.commitHalfClaimer }, context, accepted.sealed, ownEncPriv); }
219
270
  catch { throw new SdkError("bad-input", { field: "counterparty" }); }
@@ -223,25 +274,40 @@ export function acceptCounterparty({ context, side = null, counterparty = null,
223
274
  return accepted;
224
275
  }
225
276
 
277
+ export async function acceptCounterpartyChunked({ context, side = null, counterparty = null, standIn = false, options = {} }) {
278
+ const mock = (counterparty || standIn !== true) ? null : await builder().newSideChunked(context, true, options);
279
+ const { accepted, ownEncPriv } = acceptedCounterparty({ context, side, counterparty, standIn, mock });
280
+ let verdict = null;
281
+ try { verdict = await builder().verifySideChunked({ proof: accepted.proof, pub: { ed: accepted.edPub }, commitHalfClaimer: accepted.commitHalfClaimer }, context, accepted.sealed, ownEncPriv, options); }
282
+ catch { throw new SdkError("bad-input", { field: "counterparty" }); }
283
+ if (!verdict || verdict.ok !== true) {
284
+ throw new SdkError("quote-refused", { step: "proof", why: verdict && verdict.reason ? "rejected" : "unknown" });
285
+ }
286
+ return accepted;
287
+ }
288
+
226
289
  /**
227
290
  * THE ORDER STEP AS A WHOLE: your own side (or one already built by the record), the counterparty's side and the
228
291
  * joint address. It hands out the fields the record and the recovery file are assembled from; NOT A SINGLE empty
229
292
  * value: an address is not assembled without the other's point, and that is a refusal, not an empty string.
230
293
  */
231
- export function orderStep({ order, side = null, counterparty = null, standIn = false, network = null }) {
232
- const context = contextOf(order);
233
- const own = side
294
+ function ownSideOf({ order, side, context }) {
295
+ return side
234
296
  ? { context, side, spendPoint: norm(side.pub && side.pub.ed), viewPoint: norm(side.viewPub),
235
297
  encPub: norm(side.enc && side.enc.pub ? side.enc.pub : null) }
236
298
  : buildOwnSide(order);
299
+ }
300
+
301
+ function checkOwnSide(own) {
237
302
  const lack = [];
238
303
  if (own.side.half === undefined || own.side.half === null) lack.push("half");
239
304
  if (own.side.viewHalf === undefined || own.side.viewHalf === null) lack.push("viewHalf");
240
305
  if (!isPoint(own.spendPoint)) lack.push("spendPoint");
241
306
  if (!isPoint(own.viewPoint)) lack.push("viewPoint");
242
307
  if (lack.length) throw new SdkError("bad-input", { field: "side", missing: lack });
308
+ }
243
309
 
244
- const other = acceptCounterparty({ context: own.context, side: own.side, counterparty, standIn });
310
+ function orderStepResult({ own, other, network }) {
245
311
  const otherViewPoint = other.viewPoint || (other.viewHalf ? norm(builder().pointOf(other.viewHalf)) : null);
246
312
  if (!otherViewPoint) throw new SdkError("bad-input", { field: "counterparty", missing: ["viewPoint"] });
247
313
 
@@ -279,3 +345,25 @@ export function orderStep({ order, side = null, counterparty = null, standIn = f
279
345
  },
280
346
  };
281
347
  }
348
+
349
+ export function orderStep({ order, side = null, counterparty = null, standIn = false, network = null }) {
350
+ const context = contextOf(order);
351
+ const own = ownSideOf({ order, side, context });
352
+ checkOwnSide(own);
353
+ const other = acceptCounterparty({ context: own.context, side: own.side, counterparty, standIn });
354
+ return orderStepResult({ own, other, network });
355
+ }
356
+
357
+ /**
358
+ * THE CHUNKED ORDER STEP. Same steps and same result object as `orderStep`, but the proof and the verification
359
+ * yield to the event loop. It exists for a browser that must keep painting; it is not a second rule set.
360
+ */
361
+ export async function orderStepChunked({ order, side = null, counterparty = null, standIn = false, network = null, options = {} }) {
362
+ const context = contextOf(order);
363
+ const own = side
364
+ ? ownSideOf({ order, side, context })
365
+ : await buildOwnSideChunked(order, options);
366
+ checkOwnSide(own);
367
+ const other = await acceptCounterpartyChunked({ context: own.context, side: own.side, counterparty, standIn, options });
368
+ return orderStepResult({ own, other, network });
369
+ }
@@ -1,10 +1,9 @@
1
1
  // ATOMIC SWAP PRIMITIVES - FROM THE SAME npm PACKAGES AS THE PAGE BUNDLE.
2
2
  //
3
- // The bundle entry point (tools/atomic-browser-entry.mjs) hands the page exactly five names: ed25519, secp256k1,
4
- // keccak256, sha3_512, randomBytes. The order-side build modules (www/js/atomic/order.js) do NOT import them
5
- // themselves - they arrive as parameters. That is what lets the SDK expose the same primitives from the same
6
- // packages instead of dragging a hashed build artefact into the core: a package never has a "version with a
7
- // different cache".
3
+ // The order builder takes exactly five names: ed25519, secp256k1, keccak256, sha3_512, randomBytes. The
4
+ // order-side build modules (www/js/atomic/order.js) do NOT import them themselves - they arrive as parameters.
5
+ // That is what lets the SDK use the same primitives from the same packages instead of dragging a hashed build
6
+ // artefact into the core: a package never has a "version with a different cache".
8
7
  //
9
8
  // WHY EXACTLY THESE PACKAGES, AND NOT JUST ANY. keccak256 and sha3_512 are DIFFERENT functions, and they must
10
9
  // not be confused: the commitment for a half is computed with keccak256 (exactly as Solidity does it), while the
package/src/probes.mjs CHANGED
@@ -40,16 +40,22 @@ export async function probeMoneroNode({ url, fetchImpl = globalThis.fetch, timeo
40
40
  signal: controller ? controller.signal : undefined,
41
41
  });
42
42
  } catch (error) {
43
+ if (timer) clearTimeout(timer);
43
44
  const aborted = error && (error.name === "AbortError" || error.code === "ABORT_ERR");
44
45
  return { ok: false, why: aborted ? "timeout" : "unreachable", ms: Date.now() - started };
45
- } finally {
46
- if (timer) clearTimeout(timer);
47
46
  }
48
47
  if (!response || !response.ok) {
48
+ if (timer) clearTimeout(timer);
49
49
  return { ok: false, why: "http", status: response ? response.status : null, ms: Date.now() - started };
50
50
  }
51
51
  let body = null;
52
- try { body = await response.json(); } catch { return { ok: false, why: "not-json", ms: Date.now() - started }; }
52
+ // THE TIMER COVERS THE BODY TOO. Clearing it when the headers arrived left a node that sent `{` and stopped
53
+ // holding the whole call forever.
54
+ try { body = await response.json(); } catch {
55
+ if (timer) clearTimeout(timer);
56
+ return { ok: false, why: "not-json", ms: Date.now() - started };
57
+ }
58
+ if (timer) clearTimeout(timer);
53
59
  if (!body || body.error) {
54
60
  return { ok: false, why: "rpc", rpc: body && body.error ? body.error.code ?? null : null, ms: Date.now() - started };
55
61
  }
@@ -63,3 +63,48 @@ export declare const CHAINS: readonly Chain[];
63
63
  export declare const DEX_CHAINS: readonly string[];
64
64
  export declare const DEFAULT_CHAIN: string;
65
65
  export declare const ASYNC_ROUTE_PROVIDERS: Readonly<Record<string, AsyncRouteProvider>>;
66
+
67
+ /** One contract/program artifact in a deployment manifest. */
68
+ export interface DeploymentArtifact {
69
+ readonly role: string;
70
+ readonly kind: string;
71
+ readonly address: string;
72
+ readonly addressFormat: string;
73
+ readonly codeHash?: string;
74
+ readonly hashKind?: string;
75
+ readonly tx: { readonly kind: string; readonly value: string };
76
+ }
77
+
78
+ /** A VM-neutral deployment pin. Only the EVM artifacts are generated today. */
79
+ export interface DeploymentPin {
80
+ readonly vm: string;
81
+ readonly network: string;
82
+ readonly caip2: string;
83
+ readonly chainRef: string;
84
+ readonly status: "live" | "simulated" | "retired";
85
+ readonly release: {
86
+ readonly tag: string | null;
87
+ readonly commit: string | null;
88
+ readonly toolchain: string | null;
89
+ readonly deployedAt: string | null;
90
+ };
91
+ readonly anchor: { readonly kind: string; readonly value: string };
92
+ readonly artifacts: Readonly<Record<string, DeploymentArtifact>>;
93
+ /** EVM compatibility view used by `ChainConfig.escrow`. */
94
+ readonly escrow: {
95
+ readonly address: string;
96
+ readonly mode: string | null;
97
+ readonly deploymentBlock: number;
98
+ readonly cashier: string;
99
+ readonly registry: string;
100
+ readonly implementationCodeHash: string;
101
+ };
102
+ readonly knownFactoryCodes: readonly string[];
103
+ }
104
+
105
+ export declare const DEPLOYMENTS: Readonly<Record<string, DeploymentPin>>;
106
+ export declare const DEPLOYMENT_CHAINS: readonly string[];
107
+ export declare const DEPLOYMENT_VMS: readonly string[];
108
+ export declare function deploymentFor(
109
+ chainOrId: string | number | { readonly id?: string; readonly network?: string; readonly caip2?: string } | null,
110
+ ): DeploymentPin | null;
@@ -6,4 +6,13 @@
6
6
  //
7
7
  // Names only: the engine owns the values. Nothing here is re-implemented.
8
8
 
9
- export { ASYNC_ROUTE_PROVIDERS, CHAINS, DEFAULT_CHAIN, DEX_CHAINS } from "../../engine/core/config.js";
9
+ export {
10
+ ASYNC_ROUTE_PROVIDERS,
11
+ CHAINS,
12
+ DEFAULT_CHAIN,
13
+ DEX_CHAINS,
14
+ DEPLOYMENTS,
15
+ DEPLOYMENT_CHAINS,
16
+ DEPLOYMENT_VMS,
17
+ deploymentFor,
18
+ } from "../../engine/core/config.js";
@@ -58,7 +58,7 @@ export {
58
58
  plainLoopbackAllowed,
59
59
  } from "../../engine/monero/daemonAddress.js";
60
60
 
61
- // WHAT A TRANSACTION WILL COST: the daemon's price per kilobyte, by priority, and the arithmetic that turns it into
61
+ // WHAT A TRANSACTION WILL COST: the daemon's price per byte, by priority, and the arithmetic that turns it into
62
62
  // a fee. The page learned the fee only after signing.
63
63
  export { moneroFeeEstimate, feeForBytes } from "../feeEstimate.mjs";
64
64
 
package/src/quotes.mjs CHANGED
@@ -22,7 +22,7 @@ import { orderQuoteMissingFields, recoverOrderQuoteKey } from "./quoteEip712.mjs
22
22
  import { claimGasGiftWei } from "../engine/evm/claimGas.js";
23
23
  import { parseXmr } from "../engine/core/xmrAmount.js";
24
24
  import { takerHalvesV2, recoverySaltOf } from "./recovery-key.mjs";
25
- import { acceptCounterparty, buildOwnSideFromHalves, jointAddress } from "./order.mjs";
25
+ import { acceptCounterpartyChunked, buildOwnSideFromHalvesChunked, jointAddress } from "./order.mjs";
26
26
  import { requestFirmQuote } from "./relayFirmClient.mjs";
27
27
  // THE CHAIN READ NEEDED TO ASK THE REGISTRY WHO OWNS THE KEY. The selector is COMPUTED from the signature, not
28
28
  // remembered: a single wrong hex digit would call another function and return a zero address - and a zero
@@ -52,6 +52,25 @@ const addressFromWord = (raw) => {
52
52
  return h.length >= 40 ? "0x" + h.slice(-40).toLowerCase() : null;
53
53
  };
54
54
 
55
+ // THE CASHIER IS THE NETWORK'S VAULT, NOT A FIELD THE MAKER MAY CHOOSE. The escrow binds it at birth, but the
56
+ // client must refuse an answer before it funds or sends XMR: a look-alike vault with the canonical runtime and
57
+ // crafted storage would pass the escrow's code check and make every claim revert after the payout.
58
+ const pinnedCashier = (config) => {
59
+ const chain = config && config.settlement && config.settlement.chain;
60
+ const value = chain && chain.escrow && chain.escrow.cashier;
61
+ return typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value) ? value.toLowerCase() : null;
62
+ };
63
+ const requirePinnedCashier = (quote, step, config) => {
64
+ const chain = config && config.settlement && config.settlement.chain;
65
+ const pin = pinnedCashier(config);
66
+ // A caller without a network profile has nothing to compare against. A profile that names a chain but no vault
67
+ // is a broken profile, not a free pass: refuse it before a quote can be funded.
68
+ if (!pin && !chain) return;
69
+ const got = String(quote && quote.cashier || "").toLowerCase();
70
+ if (!pin) fail("quote-cashier-mismatch", { step, why: "no-pinned-cashier", got: got || null });
71
+ if (got !== pin) fail("quote-cashier-mismatch", { step, got: got || null, want: pin });
72
+ };
73
+
55
74
  const num = (v) => (v === undefined || v === null || v === "" ? null : (Number.isFinite(Number(v)) ? Number(v) : null));
56
75
  const pairAsset = (pair) => String(pair || "").split("/")[0].toUpperCase();
57
76
  const pairCurrency = (pair) => String(pair || "").split("/")[1] ? String(pair).split("/")[1].toUpperCase() : "";
@@ -249,6 +268,29 @@ const compactRefusal = (r) => ({ ...compactOffer(r), code: r.code, why: r.why })
249
268
  * base fee and the same formula; a quote may carry up to twice that estimate (gas moves between the sizing and
250
269
  * the check). Zero is the buy side and is always allowed. An unmeasured base fee is a refusal, not a free pass.
251
270
  */
271
+ /**
272
+ * THE PRIORITY FEE OF A BLOCK, FROM ONE RULE. An explicit priority field wins; a plain RPC block may carry only
273
+ * `gasPrice`, so the priority is the part above the base fee. No block or no readable pair means zero - the
274
+ * caller then uses the base fee alone, which is the old, stricter behaviour.
275
+ */
276
+ const priorityFeeOfBlock = (block) => {
277
+ if (!block || typeof block !== "object") return 0n;
278
+ const explicit = block.priorityFeePerGas !== undefined && block.priorityFeePerGas !== null
279
+ ? block.priorityFeePerGas
280
+ : (block.maxPriorityFeePerGas !== undefined && block.maxPriorityFeePerGas !== null
281
+ ? block.maxPriorityFeePerGas : null);
282
+ if (explicit !== null) return explicit;
283
+ const base = block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei;
284
+ if (block.gasPrice === undefined || block.gasPrice === null || base === undefined || base === null) return 0n;
285
+ try {
286
+ const gas = BigInt(block.gasPrice);
287
+ const baseValue = BigInt(base);
288
+ return gas > baseValue ? gas - baseValue : 0n;
289
+ } catch { return 0n; }
290
+ };
291
+
292
+ export const claimPriorityFeeOfBlock = priorityFeeOfBlock;
293
+
252
294
  export function claimTipVerdict({ claimTipWei = 0, baseFeeWei = null, priorityFeeWei = 0, factor = 2 } = {}) {
253
295
  let tip = 0n;
254
296
  try { tip = BigInt(claimTipWei === undefined || claimTipWei === null || claimTipWei === "" ? 0 : claimTipWei); }
@@ -424,6 +466,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
424
466
  const ticket = res.body;
425
467
  const quote = (ticket.handoff && ticket.handoff.quote) || ticket.quote || null;
426
468
  if (!quote || typeof quote !== "object") fail("quote-field-unbound", { step: "order-sell", field: "quote" });
469
+ requirePinnedCashier(quote, "order-sell", config);
427
470
  // THE SALE TICKET IS A SIGNED QUOTE, AND IT GETS THE SAME GATES AS `firm`: every field of the signed set,
428
471
  // its expiry, the EIP-712 signature and the named key, the registry's provider mapping, the interface's
429
472
  // allow-list, and the factory/implementation policy. The one difference is the binding below: a sale has no
@@ -604,14 +647,8 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
604
647
  const baseFeeWei = block && (block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei);
605
648
  // THE NODE SIZES THE TIP FROM THE GAS PRICE, PRIORITY INCLUDED. The SDK used to pass only the base fee, so an
606
649
  // honest L1 tip (or a base fee that dropped between sizing and checking) was refused.
607
- let priorityFeeWei = block && block.priorityFeePerGas !== undefined ? block.priorityFeePerGas : null;
608
- if (priorityFeeWei === null && block && block.gasPrice !== undefined && baseFeeWei !== undefined && baseFeeWei !== null) {
609
- try {
610
- const gas = BigInt(block.gasPrice); const base = BigInt(baseFeeWei);
611
- priorityFeeWei = gas > base ? gas - base : 0n;
612
- } catch { priorityFeeWei = 0n; }
613
- }
614
- const verdict = claimTipVerdict({ claimTipWei: shownBig, baseFeeWei, priorityFeeWei: priorityFeeWei === null ? 0n : priorityFeeWei });
650
+ const priorityFeeWei = priorityFeeOfBlock(block);
651
+ const verdict = claimTipVerdict({ claimTipWei: shownBig, baseFeeWei, priorityFeeWei });
615
652
  if (!verdict.ok) fail(verdict.code, { step: "claimTip", ...verdict });
616
653
  }
617
654
  return ticket;
@@ -654,6 +691,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
654
691
  }
655
692
  const body = res.body;
656
693
  const quote = body.quote;
694
+ requirePinnedCashier(quote, "order-quote", config);
657
695
  // THE MAKER'S VIEW HALF IS OURS, NOT THE NODE'S CHOICE. When the caller supplies it, the quote must carry the
658
696
  // same scalar back; otherwise the maker used another half and the joint view key cannot be rebuilt from the key.
659
697
  if (viewHalfClaimer !== null) {
@@ -819,7 +857,8 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
819
857
  let block = null;
820
858
  try { block = await evmBlock("latest"); } catch { fail("quote-tip-unchecked", { step: "claimTip", why: "block-read-failed" }); }
821
859
  const baseFeeWei = block && (block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei);
822
- const verdict = claimTipVerdict({ claimTipWei: quote.claimTip, baseFeeWei });
860
+ const priorityFeeWei = priorityFeeOfBlock(block);
861
+ const verdict = claimTipVerdict({ claimTipWei: quote.claimTip, baseFeeWei, priorityFeeWei });
823
862
  if (!verdict.ok) fail(verdict.code, { step: "claimTip", ...verdict });
824
863
  }
825
864
  return quote;
@@ -845,6 +884,14 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
845
884
  const registry = String(features.registry || "").toLowerCase();
846
885
  if (!/^0x[0-9a-f]{40}$/.test(maker) || maker === ZERO_ADDRESS) fail("bad-input", { field: "features.provider" });
847
886
  if (!/^0x[0-9a-f]{40}$/.test(registry) || registry === ZERO_ADDRESS) fail("bad-input", { field: "features.registry" });
887
+ // THE REGISTRY IS A PROPERTY OF THE NETWORK, NOT OF THE FEATURES THAT ARRIVED WITH THE QUOTE. A relay that
888
+ // names its own registry can authorise its own maker. The pinned value comes from the network config; a
889
+ // network without a pinned registry keeps the old path until it is deployed.
890
+ const pinnedRegistry = config && config.settlement && config.settlement.chain &&
891
+ config.settlement.chain.escrow && config.settlement.chain.escrow.registry;
892
+ if (pinnedRegistry && !sameText(registry, pinnedRegistry)) {
893
+ fail("bad-input", { field: "features.registry", why: "not-the-network-registry" });
894
+ }
848
895
  // THE FEATURES' HPKE KEY AND FRAME KEY BELONG TO THE REGISTERED MAKER. Check the registry mapping BEFORE
849
896
  // sealing any view material to the HPKE key: a dishonest relay could otherwise hand us its own key, read both
850
897
  // view halves and swap in its own node half. The answer's registry check later is not a substitute for this
@@ -862,7 +909,10 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
862
909
  if (!sameText(featureProvider, features.provider)) {
863
910
  fail("quote-provider-mismatch", { step: "registry", got: featureProvider, want: features.provider });
864
911
  }
865
- if (denylist && typeof order.locker === "string" && denylist.has(order.locker.toLowerCase())) {
912
+ // THE CLIENT'S OWN ADDRESS IS WHAT THE DENYLIST COVERS. On an ask that is the locker; on a bid the client
913
+ // is the claimer, and testing the maker's locker there checks the wrong party.
914
+ const deniedAddress = side === "bid" ? order.claimer : order.locker;
915
+ if (denylist && typeof deniedAddress === "string" && denylist.has(deniedAddress.toLowerCase())) {
866
916
  fail("address-denied", { step: "order-quote" });
867
917
  }
868
918
  // THE PROVIDER'S ROLE IS PART OF THE SIDE. A caller that names another claimer/locker is not asking
@@ -906,7 +956,7 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
906
956
  }
907
957
  const derived = takerHalvesV2({ mnemonic, chainId, factory: order.factory, salt });
908
958
  const derivation = { kind: "salt-v2", salt };
909
- const own = buildOwnSideFromHalves(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
959
+ const own = await buildOwnSideFromHalvesChunked(order, { spendHalf: derived.spendHalf, viewHalf: derived.viewHalf });
910
960
  const xa = secp256k1.Point.fromHex(own.side.proof.XA);
911
961
  const clientHalf = {
912
962
  commitHalf: bytesToHexQ(keccak256(xa.toBytes(false).slice(1))),
@@ -937,11 +987,12 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
937
987
  side,
938
988
  });
939
989
  const quote = result.quote;
990
+ requirePinnedCashier(quote, "relay", config);
940
991
  // THE NODE HALF IS NOT A DECORATION. The answer's proof must stand in THIS order's context and the proven
941
992
  // point must be the one the quote commits to. For ask that is the claimer's commitment; for bid the node
942
993
  // half is the locker's and carries its own commitment. This is the same engine check the swap path uses.
943
994
  const nodeHalf = result.nodeHalf;
944
- acceptCounterparty({
995
+ await acceptCounterpartyChunked({
945
996
  context: own.context,
946
997
  side: own.side,
947
998
  counterparty: side === "ask"
@@ -1046,7 +1097,8 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
1046
1097
  let block = null;
1047
1098
  try { block = await evmBlock("latest"); } catch { fail("quote-tip-unchecked", { step: "claimTip", why: "block-read-failed" }); }
1048
1099
  const baseFeeWei = block && (block.baseFeePerGas !== undefined ? block.baseFeePerGas : block.baseFeeWei);
1049
- const verdict = claimTipVerdict({ claimTipWei: quote.claimTip, baseFeeWei });
1100
+ const priorityFeeWei = priorityFeeOfBlock(block);
1101
+ const verdict = claimTipVerdict({ claimTipWei: quote.claimTip, baseFeeWei, priorityFeeWei });
1050
1102
  if (!verdict.ok) fail(verdict.code, { step: "claimTip", ...verdict });
1051
1103
  }
1052
1104
  // THE SIGNED XMR AMOUNT TRAVELS WITH THE ORDER TERMS. `swaps.start` records its order as given, and the
@@ -1055,19 +1107,41 @@ export function createQuotes({ config, http, now = () => Date.now(), evmCall = n
1055
1107
  const signedAtomic = result.orderQuote && result.orderQuote.xmrAmount !== undefined && result.orderQuote.xmrAmount !== null
1056
1108
  ? String(result.orderQuote.xmrAmount) : null;
1057
1109
  if (!signedAtomic) fail("quote-field-unbound", { step: "xmrAmount", field: "orderQuote.xmrAmount" });
1110
+ // THE ANSWER IS ALSO A START REQUEST. `swaps.start` reads the paying asset from the quote; the relay answer
1111
+ // carried only the signed order terms, so a caller that followed the guide reached `balance-unchecked`.
1112
+ // The asset is display metadata here; the signed `orderQuote` is unchanged.
1113
+ const marketAsset = request.market && String(request.market).includes(":")
1114
+ ? String(request.market).split(":").slice(1).join(":") : null;
1115
+ const asset = String(order.asset || marketAsset || "").trim();
1116
+ const startQuote = { ...quote, viewHalfClaimer: derived.makerViewHalf, xmrAmount: signedAtomic,
1117
+ ...(asset ? { asset, token: asset.toLowerCase() } : {}),
1118
+ // A STABLE ID FOR THE PENDING-FUNDING RECORD. The signed nonce is the one value every relay answer carries.
1119
+ ...(quote.nonce !== undefined && quote.nonce !== null ? { id: String(quote.nonce) } : {}) };
1120
+ const startCounterparty = {
1121
+ proof: nodeHalf.proof,
1122
+ edPointClaimer: side === "ask" ? quote.edPointClaimer : nodeHalf.edPoint,
1123
+ commitHalfClaimer: side === "ask" ? quote.commitHalfClaimer : nodeHalf.commitHalf,
1124
+ viewHalfClaimer: derived.makerViewHalf,
1125
+ viewPoint: side === "ask" ? result.edViewPointClaimer : result.edViewPointLocker,
1126
+ };
1127
+ // ONE ORDER OBJECT, TWO REFERENCES. `order` and `startRequest.order` must not drift apart.
1128
+ const startOrder = { ...order, xmrAmount: signedAtomic };
1058
1129
  return {
1059
1130
  ...result,
1060
- quote: { ...quote, viewHalfClaimer: derived.makerViewHalf, xmrAmount: signedAtomic },
1061
- order: { ...order, xmrAmount: signedAtomic },
1131
+ quote: startQuote,
1132
+ order: startOrder,
1133
+ // THE CALLER ADDS ITS WALLET, `receiveTo` AND THE HEIGHT; everything the relay can know is here.
1134
+ startRequest: {
1135
+ quote: startQuote,
1136
+ order: startOrder,
1137
+ orderQuote: result.orderQuote,
1138
+ counterparty: startCounterparty,
1139
+ recoveryKey: request.recoveryKey,
1140
+ recoverySalt: order.salt,
1141
+ },
1062
1142
  // THE SHAPE `swaps.start` TAKES: the proof and the claimer commitment travel with the view half, so a
1063
1143
  // caller can pass this object as `counterparty` without rebuilding the relay fields.
1064
- counterparty: {
1065
- proof: nodeHalf.proof,
1066
- edPointClaimer: side === "ask" ? quote.edPointClaimer : nodeHalf.edPoint,
1067
- commitHalfClaimer: side === "ask" ? quote.commitHalfClaimer : nodeHalf.commitHalf,
1068
- viewHalfClaimer: derived.makerViewHalf,
1069
- viewPoint: side === "ask" ? result.edViewPointClaimer : result.edViewPointLocker,
1070
- },
1144
+ counterparty: startCounterparty,
1071
1145
  viewHalfClaimer: derived.makerViewHalf,
1072
1146
  viewHalfPoint: derived.makerViewPoint,
1073
1147
  jointAddress: oneTimeAddress.address,