@aztec/ethereum 0.0.1-commit.ff7989d6c → 0.0.1-commit.ffe5b04ea

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.
@@ -2,9 +2,17 @@ import { createLogger } from '@aztec/foundation/log';
2
2
  import { makeBackoff, retry } from '@aztec/foundation/retry';
3
3
  import { fileURLToPath } from '@aztec/foundation/url';
4
4
 
5
- import { type Anvil, createAnvil } from '@viem/anvil';
5
+ import { type ChildProcess, spawn } from 'child_process';
6
6
  import { dirname, resolve } from 'path';
7
7
 
8
+ /** Minimal interface matching the @viem/anvil Anvil shape used by callers. */
9
+ export interface Anvil {
10
+ readonly port: number;
11
+ readonly host: string;
12
+ readonly status: 'listening' | 'idle';
13
+ stop(): Promise<void>;
14
+ }
15
+
8
16
  /**
9
17
  * Ensures there's a running Anvil instance and returns the RPC URL.
10
18
  */
@@ -16,7 +24,7 @@ export async function startAnvil(
16
24
  captureMethodCalls?: boolean;
17
25
  accounts?: number;
18
26
  chainId?: number;
19
- /** The hardfork to use - note: @viem/anvil types are out of date but 'cancun' and 'latest' work */
27
+ /** The hardfork to use (e.g. 'cancun', 'latest'). */
20
28
  hardfork?: string;
21
29
  } = {},
22
30
  ): Promise<{ anvil: Anvil; methodCalls?: string[]; rpcUrl: string; stop: () => Promise<void> }> {
@@ -24,48 +32,157 @@ export async function startAnvil(
24
32
  const logger = opts.log ? createLogger('ethereum:anvil') : undefined;
25
33
  const methodCalls = opts.captureMethodCalls ? ([] as string[]) : undefined;
26
34
 
27
- let port: number | undefined;
35
+ let detectedPort: number | undefined;
28
36
 
29
- // Start anvil.
30
- // We go via a wrapper script to ensure if the parent dies, anvil dies.
31
37
  const anvil = await retry(
32
38
  async () => {
33
- const anvil = createAnvil({
34
- anvilBinary,
35
- host: '127.0.0.1',
36
- port: opts.port ?? (process.env.ANVIL_PORT ? parseInt(process.env.ANVIL_PORT) : 8545),
37
- blockTime: opts.l1BlockTime,
38
- stopTimeout: 1000,
39
- accounts: opts.accounts ?? 20,
40
- gasLimit: 45_000_000n,
41
- chainId: opts.chainId ?? 31337,
39
+ const port = opts.port ?? (process.env.ANVIL_PORT ? parseInt(process.env.ANVIL_PORT) : 8545);
40
+ const args: string[] = [
41
+ '--host',
42
+ '127.0.0.1',
43
+ '--port',
44
+ String(port),
45
+ '--accounts',
46
+ String(opts.accounts ?? 20),
47
+ '--gas-limit',
48
+ String(45_000_000),
49
+ '--chain-id',
50
+ String(opts.chainId ?? 31337),
51
+ ];
52
+ if (opts.l1BlockTime !== undefined) {
53
+ args.push('--block-time', String(opts.l1BlockTime));
54
+ }
55
+ if (opts.hardfork !== undefined) {
56
+ args.push('--hardfork', opts.hardfork);
57
+ }
58
+
59
+ const child = spawn(anvilBinary, args, {
60
+ stdio: ['ignore', 'pipe', 'pipe'],
61
+ env: { ...process.env, RAYON_NUM_THREADS: '1' },
42
62
  });
43
63
 
44
- // Listen to the anvil output to get the port.
45
- const removeHandler = anvil.on('message', (message: string) => {
46
- logger?.debug(message.trim());
64
+ // Wait for "Listening on" or an early exit.
65
+ await new Promise<void>((resolve, reject) => {
66
+ let stderr = '';
67
+
68
+ const onStdout = (data: Buffer) => {
69
+ const text = data.toString();
70
+ logger?.debug(text.trim());
71
+ methodCalls?.push(...(text.match(/eth_[^\s]+/g) || []));
47
72
 
48
- methodCalls?.push(...(message.match(/eth_[^\s]+/g) || []));
49
- if (port === undefined && message.includes('Listening on')) {
50
- port = parseInt(message.match(/Listening on ([^:]+):(\d+)/)![2]);
51
- }
73
+ if (detectedPort === undefined && text.includes('Listening on')) {
74
+ const match = text.match(/Listening on ([^:]+):(\d+)/);
75
+ if (match) {
76
+ detectedPort = parseInt(match[2]);
77
+ }
78
+ }
79
+ if (detectedPort !== undefined) {
80
+ child.stdout?.removeListener('data', onStdout);
81
+ child.stderr?.removeListener('data', onStderr);
82
+ child.removeListener('close', onClose);
83
+ resolve();
84
+ }
85
+ };
86
+
87
+ const onStderr = (data: Buffer) => {
88
+ stderr += data.toString();
89
+ logger?.debug(data.toString().trim());
90
+ };
91
+
92
+ const onClose = (code: number | null) => {
93
+ child.stdout?.removeListener('data', onStdout);
94
+ child.stderr?.removeListener('data', onStderr);
95
+ reject(new Error(`Anvil exited with code ${code} before listening. stderr: ${stderr}`));
96
+ };
97
+
98
+ child.stdout?.on('data', onStdout);
99
+ child.stderr?.on('data', onStderr);
100
+ child.once('close', onClose);
52
101
  });
53
- await anvil.start();
54
- if (!logger && !opts.captureMethodCalls) {
55
- removeHandler();
102
+
103
+ // Continue piping for logging / method-call capture after startup.
104
+ if (logger || opts.captureMethodCalls) {
105
+ child.stdout?.on('data', (data: Buffer) => {
106
+ const text = data.toString();
107
+ logger?.debug(text.trim());
108
+ methodCalls?.push(...(text.match(/eth_[^\s]+/g) || []));
109
+ });
110
+ child.stderr?.on('data', (data: Buffer) => {
111
+ logger?.debug(data.toString().trim());
112
+ });
113
+ } else {
114
+ // Consume streams so the child process doesn't block on full pipe buffers.
115
+ child.stdout?.resume();
116
+ child.stderr?.resume();
56
117
  }
57
118
 
58
- return anvil;
119
+ return child;
59
120
  },
60
121
  'Start anvil',
61
122
  makeBackoff([5, 5, 5]),
62
123
  );
63
124
 
64
- if (!port) {
125
+ if (!detectedPort) {
65
126
  throw new Error('Failed to start anvil');
66
127
  }
67
128
 
68
- // Monkeypatch the anvil instance to include the actually assigned port
69
- // Object.defineProperty(anvil, 'port', { value: port, writable: false });
70
- return { anvil, methodCalls, stop: () => anvil.stop(), rpcUrl: `http://127.0.0.1:${port}` };
129
+ const port = detectedPort;
130
+ let status: 'listening' | 'idle' = 'listening';
131
+
132
+ anvil.once('close', () => {
133
+ status = 'idle';
134
+ });
135
+
136
+ const stop = async () => {
137
+ if (status === 'idle') {
138
+ return;
139
+ }
140
+ await killChild(anvil);
141
+ };
142
+
143
+ const anvilObj: Anvil = {
144
+ port,
145
+ host: '127.0.0.1',
146
+ get status() {
147
+ return status;
148
+ },
149
+ stop,
150
+ };
151
+
152
+ return { anvil: anvilObj, methodCalls, stop, rpcUrl: `http://127.0.0.1:${port}` };
153
+ }
154
+
155
+ /** Send SIGTERM, wait up to 5 s, then SIGKILL. All timers are always cleared. */
156
+ function killChild(child: ChildProcess): Promise<void> {
157
+ return new Promise<void>(resolve => {
158
+ if (child.exitCode !== null || child.killed) {
159
+ child.stdout?.destroy();
160
+ child.stderr?.destroy();
161
+ resolve();
162
+ return;
163
+ }
164
+
165
+ let killTimer: NodeJS.Timeout | undefined;
166
+
167
+ const onClose = () => {
168
+ if (killTimer !== undefined) {
169
+ clearTimeout(killTimer);
170
+ }
171
+ // Destroy stdio streams so their PipeWrap handles don't keep the event loop alive.
172
+ child.stdout?.destroy();
173
+ child.stderr?.destroy();
174
+ resolve();
175
+ };
176
+
177
+ child.once('close', onClose);
178
+ child.kill('SIGTERM');
179
+
180
+ killTimer = setTimeout(() => {
181
+ killTimer = undefined;
182
+ child.kill('SIGKILL');
183
+ }, 5000);
184
+
185
+ // Ensure the timer does not prevent Node from exiting.
186
+ killTimer.unref();
187
+ });
71
188
  }
package/src/utils.ts CHANGED
@@ -170,6 +170,21 @@ function getNestedErrorData(error: unknown): string | undefined {
170
170
  return undefined;
171
171
  }
172
172
 
173
+ /**
174
+ * Truncates an error message to a safe length for log renderers.
175
+ * LogExplorer can only render up to 2500 characters in its summary view.
176
+ * We cap at 2000 to leave room for decorating context added by callers.
177
+ */
178
+ function truncateErrorMessage(message: string): string {
179
+ const MAX = 2000;
180
+ const CHUNK = 950;
181
+ if (message.length <= MAX) {
182
+ return message;
183
+ }
184
+ const truncated = message.length - 2 * CHUNK;
185
+ return message.slice(0, CHUNK) + `...${truncated} characters truncated...` + message.slice(-CHUNK);
186
+ }
187
+
173
188
  /**
174
189
  * Formats a Viem error into a FormattedViemError instance.
175
190
  * @param error - The error to format.
@@ -232,22 +247,10 @@ export function formatViemError(error: any, abi: Abi = ErrorsAbi): FormattedViem
232
247
 
233
248
  // If it's a regular Error instance, return it with its message
234
249
  if (error instanceof Error) {
235
- return new FormattedViemError(error.message, (error as any)?.metaMessages);
236
- }
237
-
238
- const body = String(error);
239
- const length = body.length;
240
- // LogExplorer can only render up to 2500 characters in it's summary view. Try to keep the whole message below this number
241
- // Limit the error to 2000 chacaters in order to allow code higher up to decorate this error with extra details (up to 500 characters)
242
- if (length > 2000) {
243
- const chunk = 950;
244
- const truncated = length - 2 * chunk;
245
- return new FormattedViemError(
246
- body.slice(0, chunk) + `...${truncated} characters truncated...` + body.slice(-1 * chunk),
247
- );
250
+ return new FormattedViemError(truncateErrorMessage(error.message), (error as any)?.metaMessages);
248
251
  }
249
252
 
250
- return new FormattedViemError(body);
253
+ return new FormattedViemError(truncateErrorMessage(String(error)));
251
254
  }
252
255
 
253
256
  function stripAbis(obj: any) {