@ninsei-labs/sdk 0.55.3 → 0.56.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/sweep.mjs CHANGED
@@ -11,7 +11,7 @@ import { restoreWallet } from "./sweep-restore.mjs";
11
11
  import { moneroWalletAdapter } from "./adapters/monero-wallet.mjs";
12
12
  import { checkDestination } from "./destination.mjs";
13
13
  import { revealedHalfWord } from "./sweep-half.mjs";
14
- import { takerHalves, takerHalvesV2 } from "./recovery-key.mjs";
14
+ import { takerHalvesV2 } from "./recovery-key.mjs";
15
15
  import { jointAddress } from "./order.mjs";
16
16
  import { formatXmr } from "../engine/core/xmrAmount.js";
17
17
 
@@ -29,6 +29,24 @@ const xmrAmountOf = (value) => {
29
29
  // The same boundary as when the file was issued: a passphrase shorter than twelve characters will not open the file.
30
30
  const MIN_PASSPHRASE = 12;
31
31
  const STEPS = ["unlock", "sync", "sweep", "relay"];
32
+
33
+ // A NODE MUST NOT BE ABLE TO SET THE WITHDRAWAL FEE. The node's estimate reaches the SDK through the wallet,
34
+ // and an untrusted node can answer with most of the balance. The absolute ceiling is deliberately far above a
35
+ // normal priority fee (0.01 XMR) while still rejecting a percentage-sized charge. A caller that needs another
36
+ // ceiling can pass `maxFeeAtomic` explicitly.
37
+ export const MAX_SWEEP_FEE_ATOMIC = 10_000_000_000n; // 0.01 XMR
38
+
39
+ export function sweepFeeVerdict({ feeAtomic = null, amountAtomic = null, maxFeeAtomic = MAX_SWEEP_FEE_ATOMIC } = {}) {
40
+ if (feeAtomic === null || feeAtomic === undefined) return { ok: true, checked: false, fee: null, limit: String(maxFeeAtomic) };
41
+ let fee;
42
+ let amount;
43
+ let limit;
44
+ try { fee = BigInt(feeAtomic); amount = amountAtomic === null || amountAtomic === undefined ? null : BigInt(amountAtomic); limit = BigInt(maxFeeAtomic); }
45
+ catch { return { ok: false, code: "sweep-fee-too-high", why: "unreadable", fee: String(feeAtomic), limit: String(maxFeeAtomic) }; }
46
+ if (fee < 0n || limit < 0n) return { ok: false, code: "sweep-fee-too-high", why: "negative", fee: fee.toString(), limit: limit.toString() };
47
+ if (fee > limit) return { ok: false, code: "sweep-fee-too-high", why: "ceiling", fee: fee.toString(), limit: limit.toString(), amount: amount === null ? null : amount.toString() };
48
+ return { ok: true, checked: true, fee: fee.toString(), limit: limit.toString(), amount: amount === null ? null : amount.toString() };
49
+ }
32
50
  // `revealedHalf()` on the escrow. Public data: the function returns the half the settlement published.
33
51
  const REVEALED_HALF_SELECTOR = "0x3f267bb6";
34
52
 
@@ -60,17 +78,12 @@ const payloadFromOrder = async (request) => {
60
78
  // TWO DERIVATIONS, BOTH LIVE. A v1 order has an index; a v2 order has the public salt from OrderCreated and
61
79
  // the factory in its binding. The page may hand either shape back; reading `index` from a v2 order would invent
62
80
  // a number and rebuild the wrong address.
63
- let halves;
64
- if (order.derivation === "salt-v2") {
65
- if (typeof order.factory !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(order.factory)) {
66
- throw new SdkError("bad-input", { field: "order.factory" });
67
- }
68
- halves = takerHalvesV2({ mnemonic: request.mnemonic, chainId, factory: order.factory, salt: order.salt });
69
- } else {
70
- const index = Number(order.index);
71
- if (!Number.isSafeInteger(index) || index < 0) throw new SdkError("bad-input", { field: "order.index" });
72
- halves = takerHalves({ mnemonic: request.mnemonic, chainId, index });
81
+ // ONE DERIVATION. An order without the factory and salt of its OrderCreated event is not an order this key can
82
+ // rebuild; there is no index branch left to guess from.
83
+ if (typeof order.factory !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(order.factory)) {
84
+ throw new SdkError("bad-input", { field: "order.factory" });
73
85
  }
86
+ const halves = takerHalvesV2({ mnemonic: request.mnemonic, chainId, factory: order.factory, salt: order.salt });
74
87
  const buy = side === "buy";
75
88
  if (bare(buy ? order.edPointLocker : order.edPointClaimer) !== bare(halves.spendPoint)) {
76
89
  throw new SdkError("bad-input", { field: "order", why: "spend-point" });
@@ -366,6 +379,12 @@ export function createSweep({ http, config, call = null }) {
366
379
  // support, and the interface would show a free transfer.
367
380
  const fee = await feeOf(wallet, signed);
368
381
  const feeValue = fee === null ? null : BigInt(fee);
382
+ const feeVerdict = sweepFeeVerdict({
383
+ feeAtomic: fee,
384
+ amountAtomic: unlocked,
385
+ ...(request.maxFeeAtomic === undefined || request.maxFeeAtomic === null ? {} : { maxFeeAtomic: request.maxFeeAtomic }),
386
+ });
387
+ if (!feeVerdict.ok) throw new SdkError(feeVerdict.code, { fee: feeVerdict.fee, limit: feeVerdict.limit, amount: feeVerdict.amount, why: feeVerdict.why });
369
388
  const token = "sweep-" + (++sessionSeq);
370
389
  sessions.set(token, { wallet, plan, signed });
371
390
  return {
package/src/version.mjs CHANGED
@@ -6,4 +6,4 @@
6
6
  // tools/sync-version.mjs. Do not edit it by hand - set the version in package.json and run `npm run sync:version`.
7
7
  // The `version` check in tools/check.mjs refuses a mismatch, and refuses a runtime read of package.json here.
8
8
 
9
- export const SDK_VERSION = "0.55.3";
9
+ export const SDK_VERSION = "0.56.1";
@@ -41,9 +41,13 @@ const failureOf = (error, node) => {
41
41
  const params = (error && error.params) || {};
42
42
  let code = "network";
43
43
  const why = params.why === undefined || params.why === null ? "" : String(params.why);
44
+ // A BROWSER NAMES A TIMEOUT BY THE ERROR'S NAME, NOT ITS MESSAGE. Chromium says "signal timed out" where Node
45
+ // says "The operation was aborted due to timeout"; the name is the one stable word. Check it before rewrapping
46
+ // the answer as a bad one.
47
+ const name = String(params.name || (error && error.name) || "");
44
48
  if (params.status !== undefined && params.status !== null) code = "http";
49
+ else if (/^(TimeoutError|AbortError)$/.test(name) || /timeout|abort/i.test(why) || /timeout|abort/i.test(name)) code = "timeout";
45
50
  else if (why === "bad-json" || why === "no-height" || why === "no-block") code = "bad-answer";
46
- else if (/timeout|abort/i.test(why) || /timeout|abort/i.test(String((error && error.name) || ""))) code = "timeout";
47
51
  const out = { url: node.url, operator: node.operator, code };
48
52
  if (params.status !== undefined && params.status !== null) out.status = params.status;
49
53
  if (why) out.why = why;
@@ -83,10 +87,19 @@ async function call(node, path, body, fetchImpl, timeoutMs) {
83
87
  signal: typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(timeoutMs) : undefined,
84
88
  });
85
89
  } catch (error) {
86
- throw new SdkError("xmr-no-nodes", { node: node.url, why: String((error && error.message) || error).slice(0, 120) });
90
+ // KEEP THE NAME: `AbortSignal.timeout` is "TimeoutError" in a browser and "AbortError" in Node; the message
91
+ // alone is not portable, and the arrival report has to say timeout rather than network.
92
+ throw new SdkError("xmr-no-nodes", { node: node.url, name: String((error && error.name) || ""),
93
+ why: String((error && error.message) || error).slice(0, 120) });
87
94
  }
88
95
  if (!res || res.ok !== true) throw new SdkError("xmr-no-nodes", { node: node.url, status: res ? res.status : null });
89
- try { return await res.json(); } catch { throw new SdkError("xmr-no-nodes", { node: node.url, why: "bad-json" }); }
96
+ try { return await res.json(); } catch (error) {
97
+ // A BODY CUT BY THE TIMEOUT IS STILL A TIMEOUT. `res.json()` rejects after the signal fired; in Node and in
98
+ // browsers that is a TimeoutError/AbortError, not a malformed answer.
99
+ const name = String((error && error.name) || "");
100
+ const timedOut = /^(TimeoutError|AbortError)$/.test(name) || /timeout|abort/i.test(name);
101
+ throw new SdkError("xmr-no-nodes", { node: node.url, name, why: timedOut ? "timeout" : "bad-json" });
102
+ }
90
103
  }
91
104
 
92
105
  async function getInfo(node, fetchImpl, timeoutMs) {
@@ -226,6 +239,9 @@ export async function verifyArrival(request) {
226
239
  catch (error) { record.state = "down"; record.failure = failureOf(error, node); failed.push(record.failure); seen.push(record); continue; }
227
240
  // A LAGGING NODE IS NOT A WITNESS and is not a disagreement: it simply cannot see the block yet.
228
241
  if (!info.synced || info.height < located.height) { record.state = "stale"; record.height = info.height; seen.push(record); continue; }
242
+ // A WITNESS THAT ANSWERED HAS A HEIGHT, whether it is still confirming or already arrived; the caller can say
243
+ // "answered, height N" without inferring it from the block only when the state is stale.
244
+ record.height = info.height;
229
245
  let block;
230
246
  try { block = await getBlock(node, located.height, fetchImpl, timeoutMs); }
231
247
  catch (error) { record.state = "down"; record.failure = failureOf(error, node); failed.push(record.failure); seen.push(record); continue; }
@@ -303,7 +319,7 @@ export async function verifyArrival(request) {
303
319
  throw new SdkError("xmr-nodes-disagree", {
304
320
  txid: located.txid, height: located.height,
305
321
  nodes: okay.map((r) => ({ url: r.url, operator: r.operator, blockHash: r.blockHash || null, outputs: r.outputs, why: "observation" })),
306
- agreed: [],
322
+ agreed: [], failed,
307
323
  });
308
324
  }
309
325
  const best = [...byObservation.values()][0];
@@ -318,13 +334,13 @@ export async function verifyArrival(request) {
318
334
  if (locked) {
319
335
  const until = locked.unlock;
320
336
  throw new SdkError("xmr-locked", { txid: located.txid, height: located.height, address: request.address,
321
- untilHeight: until.untilHeight ?? null, untilTime: until.untilTime ?? null });
337
+ untilHeight: until.untilHeight ?? null, untilTime: until.untilTime ?? null, failed });
322
338
  }
323
339
 
324
340
  // THE AMOUNT IS NOT LESS THAN EXPECTED. A shortfall is named rather than shown as a completed swap. The figure
325
341
  // comes from the agreed observation, never from the largest answer of one node: that maximum was the defect.
326
342
  if (amountAtomic < expectedAtomic) {
327
- throw new SdkError("xmr-underpaid", { txid: located.txid, height: located.height, got: amountAtomic.toString(), want: expectedAtomic.toString() });
343
+ throw new SdkError("xmr-underpaid", { txid: located.txid, height: located.height, got: amountAtomic.toString(), want: expectedAtomic.toString(), failed });
328
344
  }
329
345
 
330
346
  if (best.operators.size < 2) {
@@ -1,357 +0,0 @@
1
- // A TEST EVM WALLET FOR NODE: KEY FROM THE ENVIRONMENT, REFUSAL ON A PRODUCTION NETWORK.
2
- //
3
- // WHY A SEPARATE ADAPTER. The SDK had only the browser wallet (evm-wallet.mjs): it receives the page's ready-made
4
- // EIP-1193 provider and signs via eth_sendTransaction - that is, the person's wallet does the signing. From Node
5
- // there is nothing to sign with, and a live run on a local chain was impossible: the SDK refused at the very first
6
- // step that needed a signature. This file closes exactly that hole - and only it.
7
- //
8
- // THIS IS A TOOL OF THE TEST CONTOUR, NOT A USER WALLET. The name shows it (node-test-*), and from that come two
9
- // rules that are not up for discussion here:
10
- //
11
- // 1) THE KEY COMES ONLY FROM THE ENVIRONMENT OR FROM A FILE, the path to which also lives in the environment.
12
- // This module does NOT read command-line arguments AT ALL: a key in argv is visible in the shell history and
13
- // in the process list, that is, it leaks before anything is signed. The key's value is never printed: only the
14
- // address, transaction hashes and amounts go out.
15
- //
16
- // 2) ON A PRODUCTION NETWORK THE ADAPTER DOES NOT SIGN. The rule is not its own: it is already declared by the
17
- // engine (sdk/src/swap-flow.mjs: production = chain.escrow.mode === "live" && !chain.testnet) and the page
18
- // itself uses the same marker. A private "production network" marker would silently drift from the engine, and
19
- // then the test key would sign real money. So the rule is taken from the network registry, not written here.
20
- //
21
- // DEPENDENCIES. The signature is assembled the same way as the provider node's (rfq/evmSend.mjs): @noble/curves
22
- // (secp256k1) and keccak256 - they are in the repository's devDependencies and already used in the project. There
23
- // is neither DOM nor node:fs at the top level here: the adapters directory is the only place where the environment
24
- // is allowed, but a static node:fs import would break the package's browser build, so the file is read via a
25
- // dynamic import and only inside the key-loading function.
26
- import { secp256k1 } from "@noble/curves/secp256k1.js";
27
- import keccakPkg from "keccak256";
28
- import { SdkError } from "../errors.mjs";
29
- import { config as engineConfig } from "../engine.mjs";
30
-
31
- const keccak256 = (bytes) => new Uint8Array(keccakPkg(Buffer.from(bytes)));
32
-
33
- // THE ENVIRONMENT VARIABLE NAMES - HERE, IN ONE PLACE: the run and the adapter must look at the same name,
34
- // otherwise the key "is there" but the adapter does not see it.
35
- export const KEY_ENV = "NINSEI_TEST_EVM_KEY";
36
- export const KEY_FILE_ENV = "NINSEI_TEST_EVM_KEY_FILE";
37
- export const RPC_ENV = "NINSEI_TEST_EVM_RPC";
38
- export const CHAIN_ENV = "NINSEI_TEST_EVM_CHAIN";
39
- export const CLAIMER_ENV = "NINSEI_TEST_EVM_CLAIMER";
40
-
41
- // AN EXPLICIT WHITELIST OF TEST NETWORKS - HERE, NOT IN THE ENGINE, and WHY. The engine's "production network" rule
42
- // (sdk/src/swap-flow.mjs: escrow.mode === "live" && !testnet) today does not trigger ON ANY recorded network: for
43
- // the registry's production networks the escrow is marked "simulated", that is, by the letter of the rule they are
44
- // not production. So the test key would also sign on mainnet - the engine would not notice, and the engine's rule
45
- // must not be changed (it is shared by the page and all legs). So the "signing is ALLOWED here" marker is set
46
- // separately and EXPLICITLY: only what is listed, and nothing more. The local anvil by chainId 31337, and the
47
- // demo testnet arbitrum-sepolia by chainId 421614 - the network the demo escrow lives on (the registry entry
48
- // marks it testnet: true with a live escrow, so the second line below already passes; without it in THIS list
49
- // the first line refuses the whole demo contour, and no headless run can sign).
50
- export const TEST_CHAIN_IDS = Object.freeze([31337, 421614]);
51
-
52
- const envOf = (name) => {
53
- const box = typeof process !== "undefined" && process ? process.env : null;
54
- const value = box ? box[name] : undefined;
55
- return typeof value === "string" && value.trim() ? value.trim() : null;
56
- };
57
- export const envValue = envOf;
58
-
59
- // --- ENCODINGS -----------------------------------------------------------------------------------------
60
- const hexToBytes = (hex) => {
61
- const h = String(hex || "").replace(/^0x/, "");
62
- if (h.length === 0) return new Uint8Array(0);
63
- if (h.length % 2) throw new SdkError("bad-input", { field: "hex", why: "odd" });
64
- if (!/^[0-9a-fA-F]+$/.test(h)) throw new SdkError("bad-input", { field: "hex", why: "not-hex" });
65
- return Uint8Array.from(Buffer.from(h, "hex"));
66
- };
67
- const bytesToHex = (bytes) => "0x" + Buffer.from(bytes).toString("hex");
68
- // Integers in RLP are encoded MINIMALLY, and zero is the empty string. A non-canonical encoding (an extra leading
69
- // zero) makes the node reject the WHOLE transaction, even though the signature is valid.
70
- const numToBytes = (value) => {
71
- const v = BigInt(value);
72
- if (v < 0n) throw new SdkError("bad-input", { field: "value", why: "negative" });
73
- if (v === 0n) return new Uint8Array(0);
74
- let hex = v.toString(16);
75
- if (hex.length % 2) hex = "0" + hex;
76
- return hexToBytes(hex);
77
- };
78
- const intFromBytes = (bytes) => numToBytes(BigInt(bytesToHex(bytes)));
79
- const encodeLength = (len, offset) => {
80
- if (len < 56) return Uint8Array.from([offset + len]);
81
- const lenBytes = numToBytes(len);
82
- return Uint8Array.from([offset + 55 + lenBytes.length, ...lenBytes]);
83
- };
84
- const rlpItem = (item) => {
85
- if (item instanceof Uint8Array) {
86
- if (item.length === 1 && item[0] < 0x80) return item;
87
- return Uint8Array.from([...encodeLength(item.length, 0x80), ...item]);
88
- }
89
- if (Array.isArray(item)) {
90
- const body = item.flatMap((x) => [...rlpItem(x)]);
91
- return Uint8Array.from([...encodeLength(body.length, 0xc0), ...body]);
92
- }
93
- throw new SdkError("bad-input", { field: "rlp" });
94
- };
95
-
96
- /** The account address for a private key: the last 20 bytes of the keccak256 of the UNcompressed point. */
97
- export function addressOfPrivateKey(privateKeyHex) {
98
- const pub = secp256k1.getPublicKey(hexToBytes(privateKeyHex), false);
99
- return "0x" + Buffer.from(keccak256(pub.slice(1))).toString("hex").slice(-40);
100
- }
101
-
102
- /**
103
- * SIGNING A LEGACY TRANSACTION (type 0, EIP-155). Legacy specifically, not 1559: it has no dependency on fee
104
- * history, and a local chain accepts it everywhere. Three things that are easy to get silently wrong (all three
105
- * were already caught in rfq/evmSend.mjs by checking against the Foundry reference, and all three are repeated
106
- * here deliberately):
107
- * prehash: false - Ethereum signs the ALREADY computed keccak hash; the library by default hashes the passed
108
- * data once more, and the signature becomes valid in form and completely foreign;
109
- * recovery is the FIRST byte of the 65-byte signature (not the last);
110
- * r and s go into RLP with minimal encoding, not full 32 bytes.
111
- */
112
- export function signLegacyTx({ privateKey, nonce, gasPrice, gasLimit, to, data = "0x", value = 0, chainId }) {
113
- const signing = rlpItem([
114
- numToBytes(nonce), numToBytes(gasPrice), numToBytes(gasLimit), hexToBytes(to),
115
- numToBytes(value), hexToBytes(data), numToBytes(chainId), new Uint8Array(0), new Uint8Array(0),
116
- ]);
117
- const digest = keccak256(signing);
118
- const sig = secp256k1.sign(digest, hexToBytes(privateKey), { format: "recovered", prehash: false });
119
- if (sig.length !== 65) throw new SdkError("bad-input", { field: "signature", got: sig.length });
120
- const recovery = Number(sig[0]);
121
- if (recovery !== 0 && recovery !== 1) throw new SdkError("bad-input", { field: "signature", why: "recovery" });
122
- const r = intFromBytes(sig.slice(1, 33));
123
- const s = intFromBytes(sig.slice(33, 65));
124
- const v = BigInt(recovery) + 35n + BigInt(chainId) * 2n;
125
- const raw = rlpItem([
126
- numToBytes(nonce), numToBytes(gasPrice), numToBytes(gasLimit), hexToBytes(to),
127
- numToBytes(value), hexToBytes(data), numToBytes(v), r, s,
128
- ]);
129
- return { raw: bytesToHex(raw), hash: bytesToHex(keccak256(raw)) };
130
- }
131
-
132
- // --- LOADING THE KEY ------------------------------------------------------------------------------------
133
- /**
134
- * The key from the environment or from a file. THE LOADER LIVES NEXT TO THE ADAPTER ON PURPOSE: it is the only
135
- * entry point for the key, and if the caller could pass the key as an argument, the rule "never from argv" would
136
- * rest on an honest word.
137
- * Returns { privateKey, address, from } - from names the source ("env" or "file"), the key itself goes out only in
138
- * this field and is never printed anywhere.
139
- */
140
- export async function testPrivateKeyFromEnv() {
141
- let raw = envOf(KEY_ENV);
142
- let from = "env";
143
- if (!raw) {
144
- const file = envOf(KEY_FILE_ENV);
145
- if (!file) throw new SdkError("bad-input", { field: "privateKey", missing: [KEY_ENV, KEY_FILE_ENV] });
146
- // DYNAMIC IMPORT: a static node:fs would end up in the package's browser build, though it is needed only here.
147
- const fs = await import("node:fs");
148
- raw = String(fs.readFileSync(file, "utf8")).trim().split(/\r?\n/)[0].trim();
149
- from = "file";
150
- }
151
- const hex = raw.replace(/^0x/, "");
152
- if (!/^[0-9a-fA-F]{64}$/.test(hex)) throw new SdkError("bad-input", { field: "privateKey", why: "shape" });
153
- return { privateKey: "0x" + hex.toLowerCase(), address: addressOfPrivateKey(hex), from };
154
- }
155
-
156
- // --- A READ PROVIDER ------------------------------------------------------------------------------------
157
- /**
158
- * An EIP-1193-compatible provider over HTTP JSON-RPC. Needed where the SDK reads the chain with the leg driver
159
- * (leg.balances -> eth_getBalance/eth_call) and as the reader for the lock step. THERE IS DELIBERATELY NO SIGNING
160
- * HERE: eth_sendTransaction answers with a refusal, because this adapter must sign with its own key, not the node -
161
- * otherwise the key would end up with the node, and the rule "key only from the environment" would stop meaning
162
- * anything.
163
- */
164
- export function evmRpcProvider(url) {
165
- if (typeof url !== "string" || !/^https?:\/\//.test(url)) throw new SdkError("bad-input", { field: "rpcUrl" });
166
- const call = async (method, params = []) => {
167
- const res = await fetch(url, {
168
- method: "POST",
169
- headers: { "content-type": "application/json" },
170
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
171
- });
172
- if (!res.ok) throw new SdkError("server-unavailable", { rpc: method, status: res.status });
173
- const body = await res.json();
174
- if (body && body.error) throw new SdkError("server-unavailable", { rpc: method, why: String(body.error.message || "").slice(0, 80) });
175
- return body ? body.result : null;
176
- };
177
- const provider = {
178
- url,
179
- request({ method, params = [] }) {
180
- if (method === "eth_sendTransaction") {
181
- throw new SdkError("not-implemented", { surface: "provider.eth_sendTransaction" });
182
- }
183
- if (method === "eth_requestAccounts") return Promise.resolve([]);
184
- return call(method, params);
185
- },
186
- };
187
- return provider;
188
- }
189
-
190
- /**
191
- * CONTRACT READ FOR THE LOCK SEAM: { to, data } -> hex. Exactly the shape the engine expects (www/js/evm/
192
- * session.js, readContract), so it is dropped into the SDK WITHOUT an adapter. This is a CHAIN READ, not a node
193
- * substitution: the calls go to the real node at the rpcUrl address.
194
- */
195
- export function evmRpcReader({ url }) {
196
- const provider = evmRpcProvider(url);
197
- return ({ to, data } = {}) => {
198
- if (!to || !data) throw new SdkError("bad-input", { field: "eth_call" });
199
- return provider.request({ method: "eth_call", params: [{ to, data }, "latest"] });
200
- };
201
- }
202
-
203
- // --- THE PRODUCTION-NETWORK MARKER ----------------------------------------------------------------------
204
- /**
205
- * A PRODUCTION NETWORK - BY THE ENGINE'S RULE, NOT ITS OWN. The marker is taken from www/js/core/config.js (the
206
- * testnet field) and sdk/src/swap-flow.mjs (escrow.mode === "live"): on a production network there is a live
207
- * escrow and NO testnet marker. An unknown network is also considered production: there is nothing to prove it is a
208
- * test one, and an error in that direction costs a test key signing over real money.
209
- */
210
- export function isProductionChain(chainId) {
211
- const chain = typeof engineConfig.chainByChainId === "function" ? engineConfig.chainByChainId(Number(chainId)) : null;
212
- if (!chain) return { production: true, reason: "unknown-chain", chain: null };
213
- const escrow = chain.escrow && typeof chain.escrow === "object" ? chain.escrow : null;
214
- const production = Boolean(escrow && escrow.mode === "live" && !chain.testnet);
215
- return { production, reason: production ? "production" : "testnet", chain };
216
- }
217
-
218
- // --- THE ADAPTER ----------------------------------------------------------------------------------------
219
- /**
220
- * A test EVM wallet: the same interface as the page's wallet (vm, connect, disconnect, address, chainId, subscribe,
221
- * driver + send/receipt), but the signature is its own and the chain is read directly.
222
- *
223
- * IT ACCEPTS ONLY AN ALREADY-LOADED KEY: the loader is testPrivateKeyFromEnv above, and there is no other entry.
224
- * rpcUrl and chainId come from outside, but as VALUES (not the key), and the adapter keeps no factory address at
225
- * all: the addresses come from the SDK/engine's network registry, and a second source of truth about addresses must
226
- * not be introduced.
227
- */
228
- export function nodeTestEvmWallet({ privateKey, rpcUrl, chainId = null, id = "node-test" } = {}) {
229
- const hex = String(privateKey || "").replace(/^0x/, "");
230
- if (!/^[0-9a-fA-F]{64}$/.test(hex)) throw new SdkError("bad-input", { field: "privateKey" });
231
- const key = "0x" + hex.toLowerCase();
232
- const owner = addressOfPrivateKey(key);
233
- const provider = evmRpcProvider(rpcUrl);
234
- let connected = false;
235
-
236
- const remoteChainId = async () => Number(BigInt(await provider.request({ method: "eth_chainId" })));
237
-
238
- // REFUSAL ON A PRODUCTION NETWORK - ONE POINT THROUGH WHICH EVERY SIGNATURE PASSES. The check stands here, not in
239
- // connect(), deliberately: connect may happen once and early, while the node's network may change later (or turn
240
- // out to be the wrong one at the moment of signing). We ask the network OF THE NODE right before signing.
241
- const assertTestContour = async () => {
242
- const remote = await remoteChainId();
243
- // A NETWORK OUTSIDE THE WHITELIST IS A REFUSAL NAMING THE NETWORK, BEFORE ANY SIGNATURE. This is the FIRST line
244
- // of defense and it does not depend on how the network is marked in the registry (the production marker is the
245
- // second line below, and today it may not trigger).
246
- if (!TEST_CHAIN_IDS.includes(Number(remote))) {
247
- throw new SdkError("wrong-chain", {
248
- why: "test-contour-network-not-allowed", chainId: remote, allowed: [...TEST_CHAIN_IDS],
249
- });
250
- }
251
- // THE SECOND LINE - THE ENGINE'S PRODUCTION-NETWORK RULE (not rewritten here, taken from the registry). It stays
252
- // for the case where a network from the list is later marked production: then the signature still stops.
253
- const view = isProductionChain(remote);
254
- if (view.production) {
255
- throw new SdkError("wrong-chain", {
256
- why: "test-contour-refuses-live-network", chainId: remote, reason: view.reason,
257
- escrowMode: view.chain && view.chain.escrow ? view.chain.escrow.mode : null,
258
- testnet: view.chain ? Boolean(view.chain.testnet) : null,
259
- });
260
- }
261
- if (chainId !== null && Number(chainId) !== remote) {
262
- throw new SdkError("wrong-chain", { got: remote, want: Number(chainId) });
263
- }
264
- return remote;
265
- };
266
-
267
- return {
268
- vm: "evm",
269
- id,
270
- // The address going out is what is anyway visible in every transaction. The key is not handed out by any method.
271
- async connect(options = {}) {
272
- const want = options && options.chainId !== undefined && options.chainId !== null ? Number(options.chainId) : chainId;
273
- const remote = await remoteChainId();
274
- if (want !== null && want !== undefined && Number(want) !== remote) {
275
- throw new SdkError("wrong-chain", { got: remote, want: Number(want) });
276
- }
277
- connected = true;
278
- },
279
- async disconnect() {
280
- connected = false;
281
- },
282
- address() {
283
- return owner;
284
- },
285
- async chainId() {
286
- return remoteChainId();
287
- },
288
- // NO SUBSCRIPTION: a local run has no "wallet changed network" event, while a poll timer would keep the process
289
- // alive after the last transaction. We return an unsubscribe function, as the adapter interface requires.
290
- subscribe() {
291
- return () => {};
292
- },
293
- driver() {
294
- return provider;
295
- },
296
- /**
297
- * SENDING: sign with its own key and eth_sendRawTransaction. The nonce is taken by pending, the gas price - from
298
- * the node, the gas limit - from the caller (the lock passes its own; if it did not, we estimate with a margin).
299
- * None of these numbers is invented: a guessed gas limit costs a signature, and a guessed nonce costs a lost
300
- * transaction.
301
- */
302
- async send({ to, data = "0x", value = 0n, gas = null }) {
303
- if (!connected) throw new SdkError("wallet-not-connected");
304
- if (typeof to !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(to)) throw new SdkError("bad-input", { field: "send.to" });
305
- const remote = await assertTestContour();
306
- const valueWei = BigInt(value === undefined || value === null ? 0 : value);
307
- const nonce = Number(BigInt(await provider.request({ method: "eth_getTransactionCount", params: [owner, "pending"] })));
308
- // NEVER SIGN BELOW THE BLOCK BASE FEE. On a live node eth_gasPrice answers a tick behind and comes out
309
- // slightly BELOW the next block's base - the signature is then rejected with "max fee per gas less than
310
- // block base fee". The node's own sender already carries this rule (rfq/evm.mjs: base + base/8); the test
311
- // adapter must not diverge from it, or a headless run cannot send anything on such a network.
312
- let gasPrice = BigInt(await provider.request({ method: "eth_gasPrice" }));
313
- try {
314
- const block = await provider.request({ method: "eth_getBlockByNumber", params: ["latest", false] });
315
- const baseFee = block && block.baseFeePerGas ? BigInt(block.baseFeePerGas) : 0n;
316
- if (baseFee > 0n && gasPrice <= baseFee) gasPrice = baseFee + baseFee / 8n;
317
- } catch { /* the base fee was not read - the node's own price stays */ }
318
- let gasLimit = gas === null || gas === undefined ? null : BigInt(gas);
319
- if (gasLimit === null) {
320
- const est = BigInt(await provider.request({
321
- method: "eth_estimateGas",
322
- params: [{ from: owner, to, value: "0x" + valueWei.toString(16), data }],
323
- }));
324
- gasLimit = (est * 12n) / 10n;
325
- }
326
- const signed = signLegacyTx({
327
- privateKey: key, nonce, gasPrice, gasLimit, to, data,
328
- value: valueWei, chainId: remote,
329
- });
330
- const hash = await provider.request({ method: "eth_sendRawTransaction", params: [signed.raw] });
331
- if (typeof hash !== "string" || !/^0x[0-9a-fA-F]{64}$/.test(hash)) {
332
- throw new SdkError("server-unavailable", { step: "send-raw" });
333
- }
334
- // THE HASH IS CHECKED AGAINST THE LOCALLY COMPUTED ONE. A discrepancy means the node accepted a transaction
335
- // different from the one we signed - and that must be found out here, not from missing money.
336
- if (hash.toLowerCase() !== signed.hash.toLowerCase()) {
337
- throw new SdkError("contract-reverted", { step: "hash-mismatch", node: hash, local: signed.hash });
338
- }
339
- return hash;
340
- },
341
- /**
342
- * THE RECEIPT: asked once and returned as is (null - not in a block yet). THE ARGUMENT SHAPE IS ACCEPTED BOTH
343
- * WAYS: a hash string and an object { hash }. This is not "just in case": the adapter contract declares
344
- * receipt(txHash: string), while the lock path in the SDK calls the receipt as receipt({ hash }) - the engine's
345
- * waitReceipt passes an object (www/js/evm/funding.js), and lock.mjs passes it into the adapter without
346
- * normalisation. A strict adapter answers bad-input to this, the refusal is swallowed by the wait, and the
347
- * escrow address is silently replaced with the PREDICTED one - that is, the "address from the receipt" check
348
- * stops working without saying so.
349
- */
350
- async receipt(txHash) {
351
- const hash = typeof txHash === "string" ? txHash : (txHash && typeof txHash.hash === "string" ? txHash.hash : null);
352
- if (!hash) throw new SdkError("bad-input", { field: "receipt.txHash" });
353
- const r = await provider.request({ method: "eth_getTransactionReceipt", params: [hash] });
354
- return r || null;
355
- },
356
- };
357
- }