@aztec/ethereum 0.0.1-commit.358457c → 0.0.1-commit.381b1a9

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,56 +24,173 @@ 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;
29
+ /**
30
+ * Number of slots per epoch used by anvil to compute the 'finalized' and 'safe' block tags.
31
+ * Anvil reports `finalized = latest - slotsInAnEpoch * 2`.
32
+ * Defaults to 1 so the finalized block advances immediately, making tests that check
33
+ * L1-finality-based logic work without needing hundreds of mined blocks.
34
+ */
35
+ slotsInAnEpoch?: number;
21
36
  } = {},
22
37
  ): Promise<{ anvil: Anvil; methodCalls?: string[]; rpcUrl: string; stop: () => Promise<void> }> {
23
38
  const anvilBinary = resolve(dirname(fileURLToPath(import.meta.url)), '../../', 'scripts/anvil_kill_wrapper.sh');
24
39
  const logger = opts.log ? createLogger('ethereum:anvil') : undefined;
25
40
  const methodCalls = opts.captureMethodCalls ? ([] as string[]) : undefined;
26
41
 
27
- let port: number | undefined;
42
+ let detectedPort: number | undefined;
28
43
 
29
- // Start anvil.
30
- // We go via a wrapper script to ensure if the parent dies, anvil dies.
31
44
  const anvil = await retry(
32
45
  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,
46
+ const port = opts.port ?? (process.env.ANVIL_PORT ? parseInt(process.env.ANVIL_PORT) : 8545);
47
+ const args: string[] = [
48
+ '--host',
49
+ '127.0.0.1',
50
+ '--port',
51
+ String(port),
52
+ '--accounts',
53
+ String(opts.accounts ?? 20),
54
+ '--gas-limit',
55
+ String(45_000_000),
56
+ '--chain-id',
57
+ String(opts.chainId ?? 31337),
58
+ ];
59
+ if (opts.l1BlockTime !== undefined) {
60
+ args.push('--block-time', String(opts.l1BlockTime));
61
+ }
62
+ if (opts.hardfork !== undefined) {
63
+ args.push('--hardfork', opts.hardfork);
64
+ }
65
+ args.push('--slots-in-an-epoch', String(opts.slotsInAnEpoch ?? 1));
66
+
67
+ const child = spawn(anvilBinary, args, {
68
+ stdio: ['ignore', 'pipe', 'pipe'],
69
+ env: { ...process.env, RAYON_NUM_THREADS: '1' },
42
70
  });
43
71
 
44
- // Listen to the anvil output to get the port.
45
- const removeHandler = anvil.on('message', (message: string) => {
46
- logger?.debug(message.trim());
72
+ // Wait for "Listening on" or an early exit.
73
+ await new Promise<void>((resolve, reject) => {
74
+ let stderr = '';
75
+
76
+ const onStdout = (data: Buffer) => {
77
+ const text = data.toString();
78
+ logger?.debug(text.trim());
79
+ methodCalls?.push(...(text.match(/eth_[^\s]+/g) || []));
47
80
 
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
- }
81
+ if (detectedPort === undefined && text.includes('Listening on')) {
82
+ const match = text.match(/Listening on ([^:]+):(\d+)/);
83
+ if (match) {
84
+ detectedPort = parseInt(match[2]);
85
+ }
86
+ }
87
+ if (detectedPort !== undefined) {
88
+ child.stdout?.removeListener('data', onStdout);
89
+ child.stderr?.removeListener('data', onStderr);
90
+ child.removeListener('close', onClose);
91
+ resolve();
92
+ }
93
+ };
94
+
95
+ const onStderr = (data: Buffer) => {
96
+ stderr += data.toString();
97
+ logger?.debug(data.toString().trim());
98
+ };
99
+
100
+ const onClose = (code: number | null) => {
101
+ child.stdout?.removeListener('data', onStdout);
102
+ child.stderr?.removeListener('data', onStderr);
103
+ reject(new Error(`Anvil exited with code ${code} before listening. stderr: ${stderr}`));
104
+ };
105
+
106
+ child.stdout?.on('data', onStdout);
107
+ child.stderr?.on('data', onStderr);
108
+ child.once('close', onClose);
52
109
  });
53
- await anvil.start();
54
- if (!logger && !opts.captureMethodCalls) {
55
- removeHandler();
110
+
111
+ // Continue piping for logging / method-call capture after startup.
112
+ if (logger || opts.captureMethodCalls) {
113
+ child.stdout?.on('data', (data: Buffer) => {
114
+ const text = data.toString();
115
+ logger?.debug(text.trim());
116
+ methodCalls?.push(...(text.match(/eth_[^\s]+/g) || []));
117
+ });
118
+ child.stderr?.on('data', (data: Buffer) => {
119
+ logger?.debug(data.toString().trim());
120
+ });
121
+ } else {
122
+ // Consume streams so the child process doesn't block on full pipe buffers.
123
+ child.stdout?.resume();
124
+ child.stderr?.resume();
56
125
  }
57
126
 
58
- return anvil;
127
+ return child;
59
128
  },
60
129
  'Start anvil',
61
130
  makeBackoff([5, 5, 5]),
62
131
  );
63
132
 
64
- if (!port) {
133
+ if (!detectedPort) {
65
134
  throw new Error('Failed to start anvil');
66
135
  }
67
136
 
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}` };
137
+ const port = detectedPort;
138
+ let status: 'listening' | 'idle' = 'listening';
139
+
140
+ anvil.once('close', () => {
141
+ status = 'idle';
142
+ });
143
+
144
+ const stop = async () => {
145
+ if (status === 'idle') {
146
+ return;
147
+ }
148
+ await killChild(anvil);
149
+ };
150
+
151
+ const anvilObj: Anvil = {
152
+ port,
153
+ host: '127.0.0.1',
154
+ get status() {
155
+ return status;
156
+ },
157
+ stop,
158
+ };
159
+
160
+ return { anvil: anvilObj, methodCalls, stop, rpcUrl: `http://127.0.0.1:${port}` };
161
+ }
162
+
163
+ /** Send SIGTERM, wait up to 5 s, then SIGKILL. All timers are always cleared. */
164
+ function killChild(child: ChildProcess): Promise<void> {
165
+ return new Promise<void>(resolve => {
166
+ if (child.exitCode !== null || child.killed) {
167
+ child.stdout?.destroy();
168
+ child.stderr?.destroy();
169
+ resolve();
170
+ return;
171
+ }
172
+
173
+ let killTimer: NodeJS.Timeout | undefined;
174
+
175
+ const onClose = () => {
176
+ if (killTimer !== undefined) {
177
+ clearTimeout(killTimer);
178
+ }
179
+ // Destroy stdio streams so their PipeWrap handles don't keep the event loop alive.
180
+ child.stdout?.destroy();
181
+ child.stderr?.destroy();
182
+ resolve();
183
+ };
184
+
185
+ child.once('close', onClose);
186
+ child.kill('SIGTERM');
187
+
188
+ killTimer = setTimeout(() => {
189
+ killTimer = undefined;
190
+ child.kill('SIGKILL');
191
+ }, 5000);
192
+
193
+ // Ensure the timer does not prevent Node from exiting.
194
+ killTimer.unref();
195
+ });
71
196
  }