@aztec/ethereum 4.0.0-devnet.2-patch.3 → 4.0.0-devnet.3-patch.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 (44) hide show
  1. package/dest/client.d.ts +10 -2
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +13 -7
  4. package/dest/config.d.ts +3 -1
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +6 -0
  7. package/dest/contracts/registry.d.ts +3 -1
  8. package/dest/contracts/registry.d.ts.map +1 -1
  9. package/dest/contracts/registry.js +30 -1
  10. package/dest/contracts/rollup.d.ts +21 -8
  11. package/dest/contracts/rollup.d.ts.map +1 -1
  12. package/dest/contracts/rollup.js +62 -12
  13. package/dest/generated/l1-contracts-defaults.d.ts +2 -2
  14. package/dest/generated/l1-contracts-defaults.js +2 -2
  15. package/dest/l1_reader.d.ts +3 -1
  16. package/dest/l1_reader.d.ts.map +1 -1
  17. package/dest/l1_reader.js +6 -1
  18. package/dest/l1_tx_utils/l1_tx_utils.d.ts +4 -3
  19. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  20. package/dest/l1_tx_utils/l1_tx_utils.js +14 -32
  21. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +1 -1
  22. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  23. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +8 -4
  24. package/dest/test/chain_monitor.d.ts +22 -3
  25. package/dest/test/chain_monitor.d.ts.map +1 -1
  26. package/dest/test/chain_monitor.js +33 -2
  27. package/dest/test/eth_cheat_codes.d.ts +6 -4
  28. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  29. package/dest/test/eth_cheat_codes.js +6 -4
  30. package/dest/test/start_anvil.d.ts +23 -3
  31. package/dest/test/start_anvil.d.ts.map +1 -1
  32. package/dest/test/start_anvil.js +143 -29
  33. package/package.json +5 -5
  34. package/src/client.ts +10 -2
  35. package/src/config.ts +12 -0
  36. package/src/contracts/registry.ts +31 -1
  37. package/src/contracts/rollup.ts +79 -24
  38. package/src/generated/l1-contracts-defaults.ts +2 -2
  39. package/src/l1_reader.ts +13 -1
  40. package/src/l1_tx_utils/l1_tx_utils.ts +14 -21
  41. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +8 -4
  42. package/src/test/chain_monitor.ts +60 -3
  43. package/src/test/eth_cheat_codes.ts +6 -4
  44. package/src/test/start_anvil.ts +177 -29
@@ -14,16 +14,13 @@ import {
14
14
  type Abi,
15
15
  type BlockOverrides,
16
16
  type Hex,
17
- type NonceManager,
18
17
  type PrepareTransactionRequestRequest,
19
18
  type StateOverride,
20
19
  type TransactionReceipt,
21
20
  type TransactionSerializable,
22
- createNonceManager,
23
21
  formatGwei,
24
22
  serializeTransaction,
25
23
  } from 'viem';
26
- import { jsonRpc } from 'viem/nonce';
27
24
 
28
25
  import type { ViemClient } from '../types.js';
29
26
  import { formatViemError } from '../utils.js';
@@ -47,8 +44,9 @@ import {
47
44
  const MAX_L1_TX_STATES = 32;
48
45
 
49
46
  export class L1TxUtils extends ReadOnlyL1TxUtils {
50
- protected nonceManager: NonceManager;
51
47
  protected txs: L1TxState[] = [];
48
+ /** Last nonce successfully sent to the chain. Used as a lower bound when a fallback RPC node returns a stale count. */
49
+ private lastSentNonce: number | undefined;
52
50
  /** Tx delayer for testing. Only set when enableDelayer config is true. */
53
51
  public delayer?: Delayer;
54
52
  /** KZG instance for blob operations. */
@@ -68,7 +66,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
68
66
  delayer?: Delayer,
69
67
  ) {
70
68
  super(client, logger, dateProvider, config, debugMaxGasLimit);
71
- this.nonceManager = createNonceManager({ source: jsonRpc() });
72
69
  this.kzg = kzg;
73
70
 
74
71
  // Set up delayer: use provided one or create new
@@ -110,6 +107,11 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
110
107
  this.metrics?.recordMinedTx(l1TxState, new Date(l1Timestamp));
111
108
  } else if (newState === TxUtilsState.NOT_MINED) {
112
109
  this.metrics?.recordDroppedTx(l1TxState);
110
+ // The tx was dropped: the chain nonce reverted to l1TxState.nonce, so our lower bound is
111
+ // no longer valid. Clear it so the next send fetches the real nonce from the chain.
112
+ if (this.lastSentNonce === l1TxState.nonce) {
113
+ this.lastSentNonce = undefined;
114
+ }
113
115
  }
114
116
 
115
117
  // Update state in the store
@@ -244,9 +246,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
244
246
  throw new InterruptError(`Transaction sending is interrupted`);
245
247
  }
246
248
 
247
- // Check timeout before consuming nonce to avoid leaking a nonce that was never sent.
248
- // A leaked nonce creates a gap (e.g. nonce 107 consumed but unsent), so all subsequent
249
- // transactions (108, 109, ...) can never be mined since the chain expects 107 first.
250
249
  const now = new Date(await this.getL1Timestamp());
251
250
  if (gasConfig.txTimeoutAt && now > gasConfig.txTimeoutAt) {
252
251
  throw new TimeoutError(
@@ -254,11 +253,11 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
254
253
  );
255
254
  }
256
255
 
257
- const nonce = await this.nonceManager.consume({
258
- client: this.client,
259
- address: account,
260
- chainId: this.client.chain.id,
261
- });
256
+ const chainNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
257
+ // If a fallback RPC node returns a stale count (lower than what we last sent), use our
258
+ // local lower bound to avoid sending a duplicate of an already-pending transaction.
259
+ const nonce =
260
+ this.lastSentNonce !== undefined && chainNonce <= this.lastSentNonce ? this.lastSentNonce + 1 : chainNonce;
262
261
 
263
262
  const baseState = { request, gasLimit, blobInputs, gasPrice, nonce };
264
263
  const txData = this.makeTxData(baseState, { isCancelTx: false });
@@ -266,6 +265,8 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
266
265
  // Send the new tx
267
266
  const signedRequest = await this.prepareSignedTransaction(txData);
268
267
  const txHash = await this.client.sendRawTransaction({ serializedTransaction: signedRequest });
268
+ // Update after tx is sent successfully
269
+ this.lastSentNonce = nonce;
269
270
 
270
271
  // Create the new state for monitoring
271
272
  const l1TxState: L1TxState = {
@@ -449,7 +450,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
449
450
  { nonce, account, pendingNonce, timePassed },
450
451
  );
451
452
  await this.updateState(state, TxUtilsState.NOT_MINED);
452
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
453
453
  throw new DroppedTransactionError(nonce, account);
454
454
  }
455
455
 
@@ -541,12 +541,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
541
541
 
542
542
  // Oh no, the transaction has timed out!
543
543
  if (isCancelTx || !gasConfig.cancelTxOnTimeout) {
544
- // If this was already a cancellation tx, or we are configured to not cancel txs, we just mark it as NOT_MINED
545
- // and reset the nonce manager, so the next tx that comes along can reuse the nonce if/when this tx gets dropped.
546
- // This is the nastiest scenario for us, since the new tx could acquire the next nonce, but then this tx is dropped,
547
- // and the new tx would never get mined. Eventually, the new tx would also drop.
548
544
  await this.updateState(state, TxUtilsState.NOT_MINED);
549
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
550
545
  } else {
551
546
  // Otherwise we fire the cancellation without awaiting to avoid blocking the caller,
552
547
  // and monitor it in the background so we can speed it up as needed.
@@ -685,7 +680,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
685
680
  { nonce, account },
686
681
  );
687
682
  await this.updateState(state, TxUtilsState.NOT_MINED);
688
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
689
683
  return;
690
684
  }
691
685
 
@@ -697,7 +691,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
697
691
  { nonce, account, currentNonce },
698
692
  );
699
693
  await this.updateState(state, TxUtilsState.NOT_MINED);
700
- this.nonceManager.reset({ address: account, chainId: this.client.chain.id });
701
694
  return;
702
695
  }
703
696
 
@@ -130,9 +130,10 @@ export class ReadOnlyL1TxUtils {
130
130
  const numBlocks = Math.ceil(gasConfig.stallTimeMs! / BLOCK_TIME_MS);
131
131
  for (let i = 0; i < numBlocks; i++) {
132
132
  // each block can go up 12.5% from previous baseFee
133
- maxFeePerGas = (maxFeePerGas * (1_000n + 125n)) / 1_000n;
133
+ // ceil, (a+b-1)/b, to avoid truncation at small values (e.g. 1 wei blob base fee)
134
+ maxFeePerGas = (maxFeePerGas * (1_000n + 125n) + 999n) / 1_000n;
134
135
  // same for blob gas fee
135
- maxFeePerBlobGas = (maxFeePerBlobGas * (1_000n + 125n)) / 1_000n;
136
+ maxFeePerBlobGas = (maxFeePerBlobGas * (1_000n + 125n) + 999n) / 1_000n;
136
137
  }
137
138
 
138
139
  if (attempt > 0) {
@@ -242,13 +243,16 @@ export class ReadOnlyL1TxUtils {
242
243
  const gasConfig = { ...this.config, ..._gasConfig };
243
244
  let initialEstimate = 0n;
244
245
  if (_blobInputs) {
245
- // @note requests with blobs also require maxFeePerBlobGas to be set
246
+ // @note requests with blobs also require maxFeePerBlobGas to be set.
247
+ // Use 2x buffer for maxFeePerBlobGas to avoid stale fees and to pass EIP-4844 validation (even if it is a gas estimation call).
248
+ // 1. maxFeePerBlobGas >= blobBaseFee
249
+ // 2. account balance >= gas * maxFeePerGas + maxFeePerBlobGas * blobCount + value
246
250
  const gasPrice = await this.getGasPrice(gasConfig, true, 0);
247
251
  initialEstimate = await this.client.estimateGas({
248
252
  account,
249
253
  ...request,
250
254
  ..._blobInputs,
251
- maxFeePerBlobGas: gasPrice.maxFeePerBlobGas!,
255
+ maxFeePerBlobGas: gasPrice.maxFeePerBlobGas! * 2n,
252
256
  gas: MAX_L1_TX_LIMIT,
253
257
  blockTag: 'latest',
254
258
  });
@@ -1,4 +1,4 @@
1
- import type { RollupContract } from '@aztec/ethereum/contracts';
1
+ import type { ManaMinFeeComponents, RollupContract } from '@aztec/ethereum/contracts';
2
2
  import { InboxContract } from '@aztec/ethereum/contracts';
3
3
  import { CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
4
  import { EthAddress } from '@aztec/foundation/eth-address';
@@ -10,6 +10,20 @@ import { EventEmitter } from 'events';
10
10
 
11
11
  import type { ViemClient } from '../types.js';
12
12
 
13
+ /** L2 fee data reported by the chain monitor. */
14
+ export type L2FeeData = ManaMinFeeComponents & {
15
+ /** Total minimum fee per mana in Fee Juice (sum of sequencerCost + proverCost + congestionCost). */
16
+ minFeePerMana: bigint;
17
+ /** L1 base fee observed by the oracle. */
18
+ l1BaseFee: bigint;
19
+ /** L1 blob fee observed by the oracle. */
20
+ l1BlobFee: bigint;
21
+ /** ETH per fee asset exchange rate (1e12 precision). */
22
+ ethPerFeeAsset: bigint;
23
+ /** Mana target per checkpoint. */
24
+ manaTarget: bigint;
25
+ };
26
+
13
27
  export type ChainMonitorEventMap = {
14
28
  'l1-block': [{ l1BlockNumber: number; timestamp: bigint }];
15
29
  checkpoint: [
@@ -19,6 +33,7 @@ export type ChainMonitorEventMap = {
19
33
  'l2-messages': [{ totalL2Messages: number; l1BlockNumber: number }];
20
34
  'l2-epoch': [{ l2EpochNumber: EpochNumber; timestamp: bigint; committee: EthAddress[] | undefined }];
21
35
  'l2-slot': [{ l2SlotNumber: SlotNumber; timestamp: bigint }];
36
+ 'l2-fees': [L2FeeData];
22
37
  };
23
38
 
24
39
  /** Utility class that polls the chain on quick intervals and logs new L1 blocks, L2 blocks, and L2 proofs. */
@@ -45,6 +60,8 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
45
60
  public l2EpochNumber!: EpochNumber;
46
61
  /** Current L2 slot number */
47
62
  public l2SlotNumber!: SlotNumber;
63
+ /** Current L2 fee data (components of the minimum fee per mana). */
64
+ public l2FeeData!: L2FeeData;
48
65
 
49
66
  constructor(
50
67
  private readonly rollup: RollupContract,
@@ -77,7 +94,7 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
77
94
  }
78
95
  }
79
96
 
80
- private async getInbox() {
97
+ protected async getInbox() {
81
98
  if (!this.inbox) {
82
99
  const { inboxAddress } = await this.rollup.getRollupAddresses();
83
100
  this.inbox = new InboxContract(this.l1Client, inboxAddress);
@@ -158,7 +175,7 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
158
175
  this.l2EpochNumber = l2Epoch;
159
176
  committee = await this.rollup.getCurrentEpochCommittee();
160
177
  this.emit('l2-epoch', { l2EpochNumber: l2Epoch, timestamp, committee });
161
- msg += ` starting new epoch ${this.l2EpochNumber} `;
178
+ msg += ` starting new epoch ${this.l2EpochNumber}`;
162
179
  }
163
180
 
164
181
  if (l2SlotNumber !== this.l2SlotNumber) {
@@ -166,6 +183,13 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
166
183
  this.emit('l2-slot', { l2SlotNumber, timestamp });
167
184
  }
168
185
 
186
+ const feeData = await this.fetchFeeData(timestamp);
187
+ if (this.hasFeeDataChanged(feeData)) {
188
+ msg += ` with L2 min fee ${feeData.minFeePerMana}`;
189
+ this.l2FeeData = feeData;
190
+ this.emit('l2-fees', feeData);
191
+ }
192
+
169
193
  this.logger.info(msg, {
170
194
  currentTimestamp: this.dateProvider.nowInSeconds(),
171
195
  l1Timestamp: timestamp,
@@ -176,6 +200,7 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
176
200
  provenCheckpointNumber: this.provenCheckpointNumber,
177
201
  totalL2Messages: this.totalL2Messages,
178
202
  committee,
203
+ ...this.l2FeeData,
179
204
  });
180
205
 
181
206
  return this;
@@ -242,4 +267,36 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
242
267
  this.on('checkpoint', listener);
243
268
  });
244
269
  }
270
+
271
+ private async fetchFeeData(timestamp: bigint): Promise<L2FeeData> {
272
+ const [components, minFeePerMana, l1Fees, ethPerFeeAsset, manaTarget] = await Promise.all([
273
+ this.rollup.getManaMinFeeComponentsAt(timestamp, true),
274
+ this.rollup.getManaMinFeeAt(timestamp, true),
275
+ this.rollup.getL1FeesAt(timestamp),
276
+ this.rollup.getEthPerFeeAsset(),
277
+ this.rollup.getManaTarget(),
278
+ ]);
279
+ return {
280
+ ...components,
281
+ minFeePerMana,
282
+ l1BaseFee: l1Fees.baseFee,
283
+ l1BlobFee: l1Fees.blobFee,
284
+ ethPerFeeAsset,
285
+ manaTarget,
286
+ };
287
+ }
288
+
289
+ private hasFeeDataChanged(newData: L2FeeData): boolean {
290
+ if (!this.l2FeeData) {
291
+ return true;
292
+ }
293
+ return (
294
+ this.l2FeeData.sequencerCost !== newData.sequencerCost ||
295
+ this.l2FeeData.proverCost !== newData.proverCost ||
296
+ this.l2FeeData.congestionCost !== newData.congestionCost ||
297
+ this.l2FeeData.l1BaseFee !== newData.l1BaseFee ||
298
+ this.l2FeeData.l1BlobFee !== newData.l1BlobFee ||
299
+ this.l2FeeData.ethPerFeeAsset !== newData.ethPerFeeAsset
300
+ );
301
+ }
245
302
  }
@@ -85,10 +85,12 @@ export class EthCheatCodes {
85
85
  }
86
86
 
87
87
  /**
88
- * Get the current timestamp
89
- * @returns The current timestamp
88
+ * Get the timestamp of the latest mined L1 block.
89
+ * Note: this is NOT the current time — it's the discrete timestamp of the last block.
90
+ * Between blocks, the actual chain time advances but no new block reflects it.
91
+ * @returns The latest block timestamp in seconds
90
92
  */
91
- public async timestamp(): Promise<number> {
93
+ public async lastBlockTimestamp(): Promise<number> {
92
94
  const res = await this.doRpcCall('eth_getBlockByNumber', ['latest', true]);
93
95
  return parseInt(res.timestamp, 16);
94
96
  }
@@ -552,7 +554,7 @@ export class EthCheatCodes {
552
554
  }
553
555
 
554
556
  public async syncDateProvider() {
555
- const timestamp = await this.timestamp();
557
+ const timestamp = await this.lastBlockTimestamp();
556
558
  if ('setTime' in this.dateProvider) {
557
559
  this.dateProvider.setTime(timestamp * 1000);
558
560
  }
@@ -1,10 +1,19 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
2
  import { makeBackoff, retry } from '@aztec/foundation/retry';
3
+ import type { TestDateProvider } from '@aztec/foundation/timer';
3
4
  import { fileURLToPath } from '@aztec/foundation/url';
4
5
 
5
- import { type Anvil, createAnvil } from '@viem/anvil';
6
+ import { type ChildProcess, spawn } from 'child_process';
6
7
  import { dirname, resolve } from 'path';
7
8
 
9
+ /** Minimal interface matching the @viem/anvil Anvil shape used by callers. */
10
+ export interface Anvil {
11
+ readonly port: number;
12
+ readonly host: string;
13
+ readonly status: 'listening' | 'idle';
14
+ stop(): Promise<void>;
15
+ }
16
+
8
17
  /**
9
18
  * Ensures there's a running Anvil instance and returns the RPC URL.
10
19
  */
@@ -16,56 +25,195 @@ export async function startAnvil(
16
25
  captureMethodCalls?: boolean;
17
26
  accounts?: number;
18
27
  chainId?: number;
19
- /** The hardfork to use - note: @viem/anvil types are out of date but 'cancun' and 'latest' work */
28
+ /** The hardfork to use (e.g. 'cancun', 'latest'). */
20
29
  hardfork?: string;
30
+ /**
31
+ * Number of slots per epoch used by anvil to compute the 'finalized' and 'safe' block tags.
32
+ * Anvil reports `finalized = latest - slotsInAnEpoch * 2`.
33
+ * Defaults to 1 so the finalized block advances immediately, making tests that check
34
+ * L1-finality-based logic work without needing hundreds of mined blocks.
35
+ */
36
+ slotsInAnEpoch?: number;
37
+ /**
38
+ * If provided, the date provider will be synced to anvil's block time on every mined block.
39
+ * This keeps the dateProvider in lockstep with anvil's chain time, avoiding drift between
40
+ * the wall clock and the L1 chain when computing L1 slot timestamps.
41
+ */
42
+ dateProvider?: TestDateProvider;
21
43
  } = {},
22
44
  ): Promise<{ anvil: Anvil; methodCalls?: string[]; rpcUrl: string; stop: () => Promise<void> }> {
23
45
  const anvilBinary = resolve(dirname(fileURLToPath(import.meta.url)), '../../', 'scripts/anvil_kill_wrapper.sh');
24
46
  const logger = opts.log ? createLogger('ethereum:anvil') : undefined;
25
47
  const methodCalls = opts.captureMethodCalls ? ([] as string[]) : undefined;
26
48
 
27
- let port: number | undefined;
49
+ let detectedPort: number | undefined;
28
50
 
29
- // Start anvil.
30
- // We go via a wrapper script to ensure if the parent dies, anvil dies.
31
51
  const anvil = await retry(
32
52
  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,
53
+ const port = opts.port ?? (process.env.ANVIL_PORT ? parseInt(process.env.ANVIL_PORT) : 8545);
54
+ const args: string[] = [
55
+ '--host',
56
+ '127.0.0.1',
57
+ '--port',
58
+ String(port),
59
+ '--accounts',
60
+ String(opts.accounts ?? 20),
61
+ '--gas-limit',
62
+ String(45_000_000),
63
+ '--chain-id',
64
+ String(opts.chainId ?? 31337),
65
+ ];
66
+ if (opts.l1BlockTime !== undefined) {
67
+ args.push('--block-time', String(opts.l1BlockTime));
68
+ }
69
+ if (opts.hardfork !== undefined) {
70
+ args.push('--hardfork', opts.hardfork);
71
+ }
72
+ args.push('--slots-in-an-epoch', String(opts.slotsInAnEpoch ?? 1));
73
+
74
+ const child = spawn(anvilBinary, args, {
75
+ stdio: ['ignore', 'pipe', 'pipe'],
76
+ env: { ...process.env, RAYON_NUM_THREADS: '1' },
42
77
  });
43
78
 
44
- // Listen to the anvil output to get the port.
45
- const removeHandler = anvil.on('message', (message: string) => {
46
- logger?.debug(message.trim());
79
+ // Wait for "Listening on" or an early exit.
80
+ await new Promise<void>((resolve, reject) => {
81
+ let stderr = '';
82
+
83
+ const onStdout = (data: Buffer) => {
84
+ const text = data.toString();
85
+ logger?.debug(text.trim());
86
+ methodCalls?.push(...(text.match(/eth_[^\s]+/g) || []));
87
+
88
+ if (detectedPort === undefined && text.includes('Listening on')) {
89
+ const match = text.match(/Listening on ([^:]+):(\d+)/);
90
+ if (match) {
91
+ detectedPort = parseInt(match[2]);
92
+ }
93
+ }
94
+ if (detectedPort !== undefined) {
95
+ child.stdout?.removeListener('data', onStdout);
96
+ child.stderr?.removeListener('data', onStderr);
97
+ child.removeListener('close', onClose);
98
+ resolve();
99
+ }
100
+ };
47
101
 
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
- }
102
+ const onStderr = (data: Buffer) => {
103
+ stderr += data.toString();
104
+ logger?.debug(data.toString().trim());
105
+ };
106
+
107
+ const onClose = (code: number | null) => {
108
+ child.stdout?.removeListener('data', onStdout);
109
+ child.stderr?.removeListener('data', onStderr);
110
+ reject(new Error(`Anvil exited with code ${code} before listening. stderr: ${stderr}`));
111
+ };
112
+
113
+ child.stdout?.on('data', onStdout);
114
+ child.stderr?.on('data', onStderr);
115
+ child.once('close', onClose);
52
116
  });
53
- await anvil.start();
54
- if (!logger && !opts.captureMethodCalls) {
55
- removeHandler();
117
+
118
+ // Continue piping for logging, method-call capture, and/or dateProvider sync after startup.
119
+ if (logger || opts.captureMethodCalls || opts.dateProvider) {
120
+ child.stdout?.on('data', (data: Buffer) => {
121
+ const text = data.toString();
122
+ logger?.debug(text.trim());
123
+ methodCalls?.push(...(text.match(/eth_[^\s]+/g) || []));
124
+ if (opts.dateProvider) {
125
+ syncDateProviderFromAnvilOutput(text, opts.dateProvider);
126
+ }
127
+ });
128
+ child.stderr?.on('data', (data: Buffer) => {
129
+ logger?.debug(data.toString().trim());
130
+ });
131
+ } else {
132
+ // Consume streams so the child process doesn't block on full pipe buffers.
133
+ child.stdout?.resume();
134
+ child.stderr?.resume();
56
135
  }
57
136
 
58
- return anvil;
137
+ return child;
59
138
  },
60
139
  'Start anvil',
61
140
  makeBackoff([5, 5, 5]),
62
141
  );
63
142
 
64
- if (!port) {
143
+ if (!detectedPort) {
65
144
  throw new Error('Failed to start anvil');
66
145
  }
67
146
 
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}` };
147
+ const port = detectedPort;
148
+ let status: 'listening' | 'idle' = 'listening';
149
+
150
+ anvil.once('close', () => {
151
+ status = 'idle';
152
+ });
153
+
154
+ const stop = async () => {
155
+ if (status === 'idle') {
156
+ return;
157
+ }
158
+ await killChild(anvil);
159
+ };
160
+
161
+ const anvilObj: Anvil = {
162
+ port,
163
+ host: '127.0.0.1',
164
+ get status() {
165
+ return status;
166
+ },
167
+ stop,
168
+ };
169
+
170
+ return { anvil: anvilObj, methodCalls, stop, rpcUrl: `http://127.0.0.1:${port}` };
171
+ }
172
+
173
+ /** Extracts block time from anvil stdout and syncs the dateProvider. */
174
+ function syncDateProviderFromAnvilOutput(text: string, dateProvider: TestDateProvider): void {
175
+ // Anvil logs mined blocks as:
176
+ // Block Time: "Fri, 20 Mar 2026 02:10:46 +0000"
177
+ const match = text.match(/Block Time:\s*"([^"]+)"/);
178
+ if (match) {
179
+ const blockTimeMs = new Date(match[1]).getTime();
180
+ if (!isNaN(blockTimeMs)) {
181
+ dateProvider.setTime(blockTimeMs);
182
+ }
183
+ }
184
+ }
185
+
186
+ /** Send SIGTERM, wait up to 5 s, then SIGKILL. All timers are always cleared. */
187
+ function killChild(child: ChildProcess): Promise<void> {
188
+ return new Promise<void>(resolve => {
189
+ if (child.exitCode !== null || child.killed) {
190
+ child.stdout?.destroy();
191
+ child.stderr?.destroy();
192
+ resolve();
193
+ return;
194
+ }
195
+
196
+ let killTimer: NodeJS.Timeout | undefined;
197
+
198
+ const onClose = () => {
199
+ if (killTimer !== undefined) {
200
+ clearTimeout(killTimer);
201
+ }
202
+ // Destroy stdio streams so their PipeWrap handles don't keep the event loop alive.
203
+ child.stdout?.destroy();
204
+ child.stderr?.destroy();
205
+ resolve();
206
+ };
207
+
208
+ child.once('close', onClose);
209
+ child.kill('SIGTERM');
210
+
211
+ killTimer = setTimeout(() => {
212
+ killTimer = undefined;
213
+ child.kill('SIGKILL');
214
+ }, 5000);
215
+
216
+ // Ensure the timer does not prevent Node from exiting.
217
+ killTimer.unref();
218
+ });
71
219
  }