@aztec/ethereum 0.0.1-commit.4d3c002 → 0.0.1-commit.4d9804df

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 (143) hide show
  1. package/dest/client.d.ts +17 -3
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +49 -3
  4. package/dest/config.d.ts +27 -8
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +59 -12
  7. package/dest/contracts/chain_state_override.d.ts +78 -0
  8. package/dest/contracts/chain_state_override.d.ts.map +1 -0
  9. package/dest/contracts/chain_state_override.js +137 -0
  10. package/dest/contracts/empire_base.d.ts +1 -3
  11. package/dest/contracts/empire_base.d.ts.map +1 -1
  12. package/dest/contracts/fee_asset_price_oracle.d.ts +6 -2
  13. package/dest/contracts/fee_asset_price_oracle.d.ts.map +1 -1
  14. package/dest/contracts/fee_asset_price_oracle.js +11 -6
  15. package/dest/contracts/governance.d.ts +108 -33
  16. package/dest/contracts/governance.d.ts.map +1 -1
  17. package/dest/contracts/governance.js +193 -12
  18. package/dest/contracts/governance_proposer.d.ts +33 -3
  19. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  20. package/dest/contracts/governance_proposer.js +51 -9
  21. package/dest/contracts/gse.d.ts +4 -2
  22. package/dest/contracts/gse.d.ts.map +1 -1
  23. package/dest/contracts/gse.js +2 -2
  24. package/dest/contracts/inbox.d.ts +3 -3
  25. package/dest/contracts/inbox.d.ts.map +1 -1
  26. package/dest/contracts/inbox.js +9 -3
  27. package/dest/contracts/index.d.ts +3 -3
  28. package/dest/contracts/index.d.ts.map +1 -1
  29. package/dest/contracts/index.js +2 -2
  30. package/dest/contracts/multicall.d.ts +82 -14
  31. package/dest/contracts/multicall.d.ts.map +1 -1
  32. package/dest/contracts/multicall.js +119 -95
  33. package/dest/contracts/outbox.d.ts +27 -4
  34. package/dest/contracts/outbox.d.ts.map +1 -1
  35. package/dest/contracts/outbox.js +34 -7
  36. package/dest/contracts/rollup.d.ts +5383 -31
  37. package/dest/contracts/rollup.d.ts.map +1 -1
  38. package/dest/contracts/rollup.js +223 -90
  39. package/dest/contracts/{tally_slashing_proposer.d.ts → slashing_proposer.d.ts} +3 -4
  40. package/dest/contracts/slashing_proposer.d.ts.map +1 -0
  41. package/dest/contracts/{tally_slashing_proposer.js → slashing_proposer.js} +13 -15
  42. package/dest/deploy_aztec_l1_contracts.d.ts +18 -10
  43. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  44. package/dest/deploy_aztec_l1_contracts.js +28 -17
  45. package/dest/foundry_binary.d.ts +13 -0
  46. package/dest/foundry_binary.d.ts.map +1 -0
  47. package/dest/foundry_binary.js +52 -0
  48. package/dest/l1_artifacts.d.ts +14941 -16273
  49. package/dest/l1_artifacts.d.ts.map +1 -1
  50. package/dest/l1_artifacts.js +9 -24
  51. package/dest/l1_contract_addresses.d.ts +61 -65
  52. package/dest/l1_contract_addresses.d.ts.map +1 -1
  53. package/dest/l1_contract_addresses.js +101 -82
  54. package/dest/l1_reader.d.ts +3 -5
  55. package/dest/l1_reader.d.ts.map +1 -1
  56. package/dest/l1_reader.js +3 -6
  57. package/dest/l1_tx_utils/config.js +3 -3
  58. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +23 -4
  59. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -1
  60. package/dest/l1_tx_utils/l1_fee_analyzer.js +65 -3
  61. package/dest/l1_tx_utils/l1_tx_utils.d.ts +7 -1
  62. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  63. package/dest/l1_tx_utils/l1_tx_utils.js +105 -32
  64. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +1 -1
  65. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  66. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +2 -1
  67. package/dest/l1_tx_utils/tx_delayer.d.ts +5 -3
  68. package/dest/l1_tx_utils/tx_delayer.d.ts.map +1 -1
  69. package/dest/l1_tx_utils/tx_delayer.js +7 -5
  70. package/dest/l1_tx_utils/types.d.ts +27 -1
  71. package/dest/l1_tx_utils/types.d.ts.map +1 -1
  72. package/dest/l1_tx_utils/types.js +10 -0
  73. package/dest/publisher_manager.d.ts +18 -6
  74. package/dest/publisher_manager.d.ts.map +1 -1
  75. package/dest/publisher_manager.js +44 -7
  76. package/dest/queries.d.ts +13 -2
  77. package/dest/queries.d.ts.map +1 -1
  78. package/dest/queries.js +69 -4
  79. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  80. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  81. package/dest/test/blob_kzg_warmup.js +64 -0
  82. package/dest/test/chain_monitor.d.ts +34 -2
  83. package/dest/test/chain_monitor.d.ts.map +1 -1
  84. package/dest/test/chain_monitor.js +76 -6
  85. package/dest/test/eth_cheat_codes.d.ts +32 -3
  86. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  87. package/dest/test/eth_cheat_codes.js +83 -37
  88. package/dest/test/index.d.ts +2 -1
  89. package/dest/test/index.d.ts.map +1 -1
  90. package/dest/test/index.js +1 -0
  91. package/dest/test/rollup_cheat_codes.d.ts +60 -3
  92. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  93. package/dest/test/rollup_cheat_codes.js +86 -7
  94. package/dest/test/start_anvil.d.ts +1 -1
  95. package/dest/test/start_anvil.d.ts.map +1 -1
  96. package/dest/test/start_anvil.js +41 -5
  97. package/dest/utils.d.ts +9 -2
  98. package/dest/utils.d.ts.map +1 -1
  99. package/dest/utils.js +34 -6
  100. package/package.json +6 -7
  101. package/src/client.ts +57 -1
  102. package/src/config.ts +82 -16
  103. package/src/contracts/chain_state_override.ts +200 -0
  104. package/src/contracts/empire_base.ts +0 -2
  105. package/src/contracts/fee_asset_price_oracle.ts +10 -5
  106. package/src/contracts/governance.ts +266 -9
  107. package/src/contracts/governance_proposer.ts +52 -5
  108. package/src/contracts/gse.ts +7 -2
  109. package/src/contracts/inbox.ts +12 -4
  110. package/src/contracts/index.ts +2 -2
  111. package/src/contracts/multicall.ts +183 -106
  112. package/src/contracts/outbox.ts +42 -8
  113. package/src/contracts/rollup.ts +252 -96
  114. package/src/contracts/{tally_slashing_proposer.ts → slashing_proposer.ts} +14 -16
  115. package/src/deploy_aztec_l1_contracts.ts +32 -18
  116. package/src/foundry_binary.ts +57 -0
  117. package/src/l1_artifacts.ts +12 -35
  118. package/src/l1_contract_addresses.ts +120 -94
  119. package/src/l1_reader.ts +4 -9
  120. package/src/l1_tx_utils/config.ts +3 -3
  121. package/src/l1_tx_utils/l1_fee_analyzer.ts +75 -3
  122. package/src/l1_tx_utils/l1_tx_utils.ts +98 -34
  123. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +2 -1
  124. package/src/l1_tx_utils/tx_delayer.ts +16 -7
  125. package/src/l1_tx_utils/types.ts +32 -0
  126. package/src/publisher_manager.ts +54 -18
  127. package/src/queries.ts +76 -4
  128. package/src/test/blob_kzg_warmup.ts +65 -0
  129. package/src/test/chain_monitor.ts +93 -5
  130. package/src/test/eth_cheat_codes.ts +76 -41
  131. package/src/test/index.ts +1 -0
  132. package/src/test/rollup_cheat_codes.ts +115 -6
  133. package/src/test/start_anvil.ts +38 -6
  134. package/src/utils.ts +30 -6
  135. package/dest/contracts/empire_slashing_proposer.d.ts +0 -69
  136. package/dest/contracts/empire_slashing_proposer.d.ts.map +0 -1
  137. package/dest/contracts/empire_slashing_proposer.js +0 -216
  138. package/dest/contracts/tally_slashing_proposer.d.ts.map +0 -1
  139. package/dest/generated/l1-contracts-defaults.d.ts +0 -30
  140. package/dest/generated/l1-contracts-defaults.d.ts.map +0 -1
  141. package/dest/generated/l1-contracts-defaults.js +0 -30
  142. package/src/contracts/empire_slashing_proposer.ts +0 -265
  143. package/src/generated/l1-contracts-defaults.ts +0 -32
@@ -0,0 +1,65 @@
1
+ import { getBytesPerBlob, getBytesPerCommitment, getKzg } from '@aztec/blob-lib';
2
+ import type { Logger } from '@aztec/foundation/log';
3
+
4
+ import type { ExtendedViemWalletClient } from '../types.js';
5
+
6
+ /**
7
+ * Warms both KZG trusted setups in parallel for tests against a local anvil:
8
+ * - anvil's own setup, loaded lazily when it first validates a blob sidecar in `eth_sendRawTransaction`
9
+ * - our `@crate-crypto/node-eth-kzg` singleton (`getKzg()`, a ~2.2s synchronous precomp build)
10
+ *
11
+ * Without this, the first checkpoint publish pays both serially (~4.4s). The recipe does all RPC round
12
+ * trips up front, fires a single bare raw send carrying a fake (garbage) blob sidecar that anvil rejects
13
+ * after loading its trusted setup, yields once to flush the socket write, then synchronously builds our
14
+ * own precomp tables while anvil warms in parallel. The fake tx is rejected at admission, so it never
15
+ * enters the pool, mines no block, and burns no nonce — sending it from the passed client is harmless.
16
+ *
17
+ * Best-effort: any failure is debug-logged and swallowed, leaving lazy init as the fallback. Never throws.
18
+ *
19
+ * @param l1Client - The L1 client whose account sends the (rejected) warm-up blob tx.
20
+ */
21
+ export async function warmBlobKzg(l1Client: ExtendedViemWalletClient, logger?: Logger): Promise<void> {
22
+ try {
23
+ // A pure-JS fake kzg: returns deterministic garbage of the correct lengths (commitment and proof are
24
+ // both 48 bytes). It makes viem build a syntactically valid sidecar without initializing any native
25
+ // module, so anvil loads its trusted setup to validate the (invalid) proof and then rejects the tx.
26
+ const fakeKzg = {
27
+ blobToKzgCommitment: () => {
28
+ const commitment = new Uint8Array(getBytesPerCommitment());
29
+ commitment.fill(0xab);
30
+ commitment[0] = 0xc0;
31
+ return commitment;
32
+ },
33
+ computeBlobKzgProof: () => {
34
+ const proof = new Uint8Array(getBytesPerCommitment());
35
+ proof.fill(0xcd);
36
+ proof[0] = 0xc0;
37
+ return proof;
38
+ },
39
+ };
40
+
41
+ // All RPC round trips (nonce, fees, gas) happen here, so only a single socket write remains to flush.
42
+ const prepared = await l1Client.prepareTransactionRequest({
43
+ blobs: [new Uint8Array(getBytesPerBlob())],
44
+ kzg: fakeKzg,
45
+ to: '0x0000000000000000000000000000000000000000',
46
+ value: 0n,
47
+ maxFeePerBlobGas: 1_000_000_000_000n,
48
+ });
49
+ const serialized = await l1Client.signTransaction(prepared);
50
+
51
+ // Fire the raw send without awaiting and swallow the expected rejection.
52
+ const sent = l1Client.request({ method: 'eth_sendRawTransaction', params: [serialized] }).catch(() => {});
53
+
54
+ // Flush the single socket write so anvil receives the tx and starts loading its trusted setup in its
55
+ // own process before we block the event loop below.
56
+ await new Promise(resolve => setImmediate(resolve));
57
+
58
+ // Synchronously build our precomp tables (~2.2s, event-loop-blocking); anvil warms in parallel.
59
+ getKzg();
60
+
61
+ await sent;
62
+ } catch (err) {
63
+ logger?.debug('Failed to warm blob KZG; falling back to lazy init', { err });
64
+ }
65
+ }
@@ -36,9 +36,20 @@ export type ChainMonitorEventMap = {
36
36
  'l2-fees': [L2FeeData];
37
37
  };
38
38
 
39
+ /** Options for tuning what the {@link ChainMonitor} polls on each new L1 block. */
40
+ export type ChainMonitorOptions = {
41
+ /**
42
+ * Whether to fetch L2 fee/oracle data (5 extra rollup reads per new L1 block) and emit `l2-fees`.
43
+ * Defaults to `true`. Set to `false` for tests that only care about slot/checkpoint/proven state to
44
+ * avoid the extra round-trips.
45
+ */
46
+ includeFeeData?: boolean;
47
+ };
48
+
39
49
  /** Utility class that polls the chain on quick intervals and logs new L1 blocks, L2 blocks, and L2 proofs. */
40
50
  export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
41
51
  private readonly l1Client: ViemClient;
52
+ private readonly includeFeeData: boolean;
42
53
  private inbox: InboxContract | undefined;
43
54
  private handle: NodeJS.Timeout | undefined;
44
55
  // eslint-disable-next-line aztec-custom/no-non-primitive-in-collections
@@ -68,9 +79,11 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
68
79
  private readonly dateProvider: DateProvider = new DateProvider(),
69
80
  private readonly logger = createLogger('aztecjs:utils:chain_monitor'),
70
81
  private readonly intervalMs = 200,
82
+ options: ChainMonitorOptions = {},
71
83
  ) {
72
84
  super();
73
85
  this.l1Client = rollup.client;
86
+ this.includeFeeData = options.includeFeeData ?? true;
74
87
  }
75
88
 
76
89
  start() {
@@ -183,11 +196,13 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
183
196
  this.emit('l2-slot', { l2SlotNumber, timestamp });
184
197
  }
185
198
 
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);
199
+ if (this.includeFeeData) {
200
+ const feeData = await this.fetchFeeData(timestamp);
201
+ if (this.hasFeeDataChanged(feeData)) {
202
+ msg += ` with L2 min fee ${feeData.minFeePerMana}`;
203
+ this.l2FeeData = feeData;
204
+ this.emit('l2-fees', feeData);
205
+ }
191
206
  }
192
207
 
193
208
  this.logger.info(msg, {
@@ -221,6 +236,11 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
221
236
  });
222
237
  }
223
238
 
239
+ public async waitUntilNextL2Slot(): Promise<void> {
240
+ const targetSlot = SlotNumber.add((await this.run()).l2SlotNumber, 1);
241
+ return this.waitUntilL2Slot(targetSlot);
242
+ }
243
+
224
244
  public waitUntilL1Block(block: number | bigint): Promise<void> {
225
245
  const targetBlock = typeof block === 'bigint' ? block.valueOf() : block;
226
246
  if (this.l1BlockNumber >= targetBlock) {
@@ -268,6 +288,74 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
268
288
  });
269
289
  }
270
290
 
291
+ /**
292
+ * Resolves with the first `checkpoint` event whose payload satisfies `match`. Unlike
293
+ * {@link waitUntilCheckpoint} (which waits for a target number), this lets callers wait for an
294
+ * arbitrary checkpoint property (e.g. one published in the first half of its slot). Rejects after
295
+ * `opts.timeout` ms if provided; otherwise waits indefinitely.
296
+ *
297
+ * By default this is purely event-driven and only resolves on the *next* matching checkpoint that
298
+ * arrives after the call. Set `checkCurrentCheckpoint` to also test the current checkpoint first (via
299
+ * a fresh {@link run} snapshot) and short-circuit if it already satisfies `match`. Use it only for
300
+ * latching state predicates (e.g. "checkpoint number has passed N"), where an already-satisfied
301
+ * result is valid and you want to avoid missing an advance that landed before the listener attached.
302
+ * Do NOT set it when the predicate depends on observing the checkpoint live (e.g. one published
303
+ * mid-slot that the caller then times against wall-clock), since it may return a checkpoint whose
304
+ * slot has already elapsed.
305
+ */
306
+ public async waitForCheckpoint(
307
+ match: (event: ChainMonitorEventMap['checkpoint'][0]) => boolean,
308
+ opts: { timeout?: number; checkCurrentCheckpoint?: boolean } = {},
309
+ ): Promise<ChainMonitorEventMap['checkpoint'][0]> {
310
+ if (opts.checkCurrentCheckpoint) {
311
+ await this.run();
312
+ const current: ChainMonitorEventMap['checkpoint'][0] = {
313
+ checkpointNumber: this.checkpointNumber,
314
+ l1BlockNumber: this.l1BlockNumber,
315
+ l2SlotNumber: this.l2SlotNumber,
316
+ timestamp: this.checkpointTimestamp,
317
+ };
318
+ if (match(current)) {
319
+ return current;
320
+ }
321
+ }
322
+ return new Promise((resolve, reject) => {
323
+ let timer: NodeJS.Timeout | undefined;
324
+ const listener = (event: ChainMonitorEventMap['checkpoint'][0]) => {
325
+ if (match(event)) {
326
+ if (timer) {
327
+ clearTimeout(timer);
328
+ }
329
+ this.off('checkpoint', listener);
330
+ resolve(event);
331
+ }
332
+ };
333
+ if (opts.timeout !== undefined) {
334
+ timer = setTimeout(() => {
335
+ this.off('checkpoint', listener);
336
+ reject(new Error(`Timed out after ${opts.timeout}ms waiting for a matching checkpoint`));
337
+ }, opts.timeout);
338
+ }
339
+ this.on('checkpoint', listener);
340
+ });
341
+ }
342
+
343
+ /** Resolves once the proven checkpoint number reaches `checkpointNumber`. */
344
+ public waitUntilCheckpointProven(checkpointNumber: CheckpointNumber): Promise<void> {
345
+ if (this.provenCheckpointNumber >= checkpointNumber) {
346
+ return Promise.resolve();
347
+ }
348
+ return new Promise(resolve => {
349
+ const listener = (data: { provenCheckpointNumber: CheckpointNumber; timestamp: bigint }) => {
350
+ if (data.provenCheckpointNumber >= checkpointNumber) {
351
+ this.off('checkpoint-proven', listener);
352
+ resolve();
353
+ }
354
+ };
355
+ this.on('checkpoint-proven', listener);
356
+ });
357
+ }
358
+
271
359
  private async fetchFeeData(timestamp: bigint): Promise<L2FeeData> {
272
360
  const [components, minFeePerMana, l1Fees, ethPerFeeAsset, manaTarget] = await Promise.all([
273
361
  this.rollup.getManaMinFeeComponentsAt(timestamp, true),
@@ -95,6 +95,16 @@ export class EthCheatCodes {
95
95
  return parseInt(res.timestamp, 16);
96
96
  }
97
97
 
98
+ /**
99
+ * Get the timestamp of the pending L1 block — the block that anvil will mine next.
100
+ * Reflects any prior `setNextBlockTimestamp` call or the configured block interval.
101
+ * @returns The pending block timestamp in seconds.
102
+ */
103
+ public async nextBlockTimestamp(): Promise<number> {
104
+ const res = await this.doRpcCall('eth_getBlockByNumber', ['pending', false]);
105
+ return parseInt(res.timestamp, 16);
106
+ }
107
+
98
108
  /**
99
109
  * Advance the chain by a number of blocks
100
110
  * @param numberOfBlocks - The number of blocks to mine
@@ -196,6 +206,22 @@ export class EthCheatCodes {
196
206
  }
197
207
  }
198
208
 
209
+ /**
210
+ * Starts interval mining from a freshly mined block and syncs the date provider to the block timestamp.
211
+ */
212
+ public async startIntervalMiningWithFreshBlock(seconds: number): Promise<void> {
213
+ if (seconds <= 0) {
214
+ throw new Error(`Interval mining requires a positive interval, got ${seconds}`);
215
+ }
216
+
217
+ await this.setAutomine(false);
218
+ await this.setIntervalMining(0, { silent: true });
219
+ await this.evmMine();
220
+ await this.syncDateProvider();
221
+ await this.setIntervalMining(seconds);
222
+ this.logger.warn(`Started L1 interval mining at ${seconds} seconds from a fresh block`);
223
+ }
224
+
199
225
  /**
200
226
  * Set the automine status of the underlying anvil chain
201
227
  * @param automine - The automine status to set
@@ -468,58 +494,67 @@ export class EthCheatCodes {
468
494
  }
469
495
 
470
496
  /**
471
- * Mines an empty block by temporarily removing all pending transactions from the mempool,
472
- * mining a block, and then re-adding the transactions back to the pool.
497
+ * Mines empty blocks while leaving any pending transactions untouched in the mempool.
498
+ *
499
+ * Never manipulates the mempool, so it is immune to the race that dropping and re-adding txs has against a
500
+ * concurrent publisher that is monitoring and re-broadcasting the same in-flight tx (with that approach the
501
+ * in-flight tx could reappear in the pool and be swept into the "empty" block, mining a proposal the caller
502
+ * expected to stay pending). Works in two steps: first the block gas limit is temporarily lowered below the
503
+ * intrinsic cost of any transaction (21000 gas) and the blocks are mined, so no pending tx is includable;
504
+ * then those blocks are reorged out and replaced with empty blocks mined at the restored gas limit. The
505
+ * reorg is needed because anvil applies a new gas limit only to future blocks: without it the just-mined
506
+ * blocks would keep the tiny gas limit, and an `eth_call` against `latest` (whose gas is capped by the
507
+ * block gas limit) would revert with "intrinsic gas too high".
508
+ *
509
+ * The replacement blocks advance L1 time. `anvil_reorg` stamps each replacement as `parent + N*interval`,
510
+ * so on its own it would freeze L1 time at the parent timestamp; callers that measure elapsed L1 time
511
+ * (L1TxUtils stall/timeout detection, `syncDateProvider`-driven slot advancement) rely on it moving
512
+ * forward. We reproduce the wall-clock advance the mine step just made (at least 1s per block) via a
513
+ * temporary block-timestamp interval, then restore any pre-existing interval.
473
514
  */
474
515
  public async mineEmptyBlock(blockCount: number = 1): Promise<void> {
475
516
  await this.execWithPausedAnvil(async () => {
476
- // Get all pending and queued transactions from the pool
477
- const txs = await this.getTxPoolContents();
478
-
479
- this.logger.debug(`Found ${txs.length} transactions in pool`);
480
-
481
- // Get raw transactions before dropping them
482
- const rawTxs: Hex[] = [];
483
- for (const tx of txs) {
484
- try {
485
- const rawTx = await this.doRpcCall('debug_getRawTransaction', [tx.hash]);
486
- if (rawTx) {
487
- rawTxs.push(rawTx);
488
- this.logger.debug(`Got raw tx for ${tx.hash}`);
489
- } else {
490
- this.logger.warn(`No raw tx found for ${tx.hash}`);
491
- }
492
- } catch {
493
- this.logger.warn(`Failed to get raw transaction for ${tx.hash}`);
494
- }
517
+ const originalGasLimit = await this.getBlockGasLimit();
518
+ const parentTimestamp = await this.lastBlockTimestamp();
519
+ // anvil has no getter for the block-timestamp interval, but the pending block is stamped
520
+ // `latest + interval`, so this delta is the standing interval (0 when none is set).
521
+ const priorInterval = (await this.nextBlockTimestamp()) - parentTimestamp;
522
+ try {
523
+ await this.setBlockGasLimit(1n);
524
+ await this.doMine(blockCount);
525
+ } finally {
526
+ await this.setBlockGasLimit(originalGasLimit);
495
527
  }
496
-
497
- this.logger.debug(`Retrieved ${rawTxs.length} raw transactions`);
498
-
499
- // Drop all transactions from the mempool
500
- await this.doRpcCall('anvil_dropAllTransactions', []);
501
-
502
- // Mine an empty block
503
- await this.doMine(blockCount);
504
-
505
- // Re-add the transactions to the pool
506
- for (const rawTx of rawTxs) {
507
- try {
508
- const txHash = await this.doRpcCall('eth_sendRawTransaction', [rawTx]);
509
- this.logger.debug(`Re-added transaction ${txHash}`);
510
- } catch (err) {
511
- this.logger.warn(`Failed to re-add transaction: ${err}`);
528
+ const advance = (await this.lastBlockTimestamp()) - parentTimestamp;
529
+ const perBlockInterval = Math.max(1, Math.floor(advance / blockCount));
530
+ // Replace the tiny-gas-limit blocks with empty blocks at the restored gas limit, keeping the same
531
+ // height. The reorged-out blocks held no transactions, so nothing returns to the pool.
532
+ await this.doRpcCall('anvil_setBlockTimestampInterval', [perBlockInterval]);
533
+ try {
534
+ await this.doRpcCall('anvil_reorg', [blockCount, []]);
535
+ } finally {
536
+ if (priorInterval > 0) {
537
+ await this.doRpcCall('anvil_setBlockTimestampInterval', [priorInterval]);
538
+ } else {
539
+ await this.doRpcCall('anvil_removeBlockTimestampInterval', []);
512
540
  }
513
541
  }
514
-
515
- if (rawTxs.length !== txs.length) {
516
- this.logger.warn(`Failed to add all txs back: had ${txs.length} but re-added ${rawTxs.length}`);
517
- }
518
542
  });
519
543
 
520
544
  this.logger.warn(`Mined ${blockCount} empty L1 ${pluralize('block', blockCount)}`);
521
545
  }
522
546
 
547
+ /** Returns the gas limit of the latest mined L1 block. */
548
+ public async getBlockGasLimit(): Promise<bigint> {
549
+ const block = await this.doRpcCall('eth_getBlockByNumber', ['latest', false]);
550
+ return BigInt(block.gasLimit);
551
+ }
552
+
553
+ /** Sets the block gas limit applied to subsequently mined L1 blocks. */
554
+ public async setBlockGasLimit(gasLimit: bigint): Promise<void> {
555
+ await this.doRpcCall('anvil_setBlockGasLimit', [toHex(gasLimit)]);
556
+ }
557
+
523
558
  public async execWithPausedAnvil<T>(fn: () => Promise<T>): Promise<T> {
524
559
  const [blockInterval, wasAutoMining] = await Promise.all([this.getIntervalMining(), this.isAutoMining()]);
525
560
  try {
package/src/test/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './blob_kzg_warmup.js';
1
2
  export * from './eth_cheat_codes.js';
2
3
  export * from './eth_cheat_codes_with_state.js';
3
4
  export * from './start_anvil.js';
@@ -4,6 +4,7 @@ import type { ViemPublicClient } from '@aztec/ethereum/types';
4
4
  import { CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
5
5
  import { EthAddress } from '@aztec/foundation/eth-address';
6
6
  import { createLogger } from '@aztec/foundation/log';
7
+ import { retryUntil } from '@aztec/foundation/retry';
7
8
  import type { DateProvider } from '@aztec/foundation/timer';
8
9
  import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
9
10
 
@@ -15,6 +16,7 @@ import {
15
16
  getContract,
16
17
  hexToBigInt,
17
18
  http,
19
+ keccak256,
18
20
  } from 'viem';
19
21
 
20
22
  import { EthCheatCodes } from './eth_cheat_codes.js';
@@ -53,7 +55,17 @@ export class RollupCheatCodes {
53
55
  /** Returns the current slot */
54
56
  public async getSlot(): Promise<SlotNumber> {
55
57
  const ts = BigInt((await this.client.getBlock()).timestamp);
56
- return SlotNumber.fromBigInt(await this.rollup.read.getSlotAt([ts]));
58
+ return this.getSlotAt(ts);
59
+ }
60
+
61
+ /** Returns the slot number at a given timestamp. */
62
+ public async getSlotAt(timestamp: bigint): Promise<SlotNumber> {
63
+ return SlotNumber.fromBigInt(await this.rollup.read.getSlotAt([timestamp]));
64
+ }
65
+
66
+ /** Returns the timestamp for the start of a given slot. */
67
+ public async getTimestampForSlot(slot: SlotNumber): Promise<bigint> {
68
+ return await this.rollup.read.getTimestampForSlot([BigInt(slot)]);
57
69
  }
58
70
 
59
71
  /** Returns the number of seconds until the start of the given slot based on L1 block timestamp. */
@@ -168,6 +180,21 @@ export class RollupCheatCodes {
168
180
  return [timestamp, nextSlot];
169
181
  }
170
182
 
183
+ /**
184
+ * Warps L1 time to the start of an explicit absolute slot. Unlike `advanceSlots(N)` which is
185
+ * relative to the current L1 timestamp at call time and therefore races with real-time
186
+ * progression between query and warp, this lands at the slot regardless of latency.
187
+ *
188
+ * Throws if the requested slot is in the past relative to current L1 time (anvil cannot
189
+ * rewind).
190
+ */
191
+ public async advanceToSlot(slot: SlotNumber) {
192
+ const timestamp = await this.rollup.read.getTimestampForSlot([BigInt(slot)]);
193
+ await this.ethCheatCodes.warp(Number(timestamp), { silent: true, resetBlockInterval: true });
194
+ this.logger.warn(`Advanced to slot ${slot}`, { timestamp });
195
+ return timestamp;
196
+ }
197
+
171
198
  /**
172
199
  * Warps time in L1 equivalent to however many slots.
173
200
  * @param howMany - The number of slots to advance.
@@ -218,6 +245,56 @@ export class RollupCheatCodes {
218
245
  });
219
246
  }
220
247
 
248
+ /**
249
+ * Polls the rollup until its current epoch reaches `epoch`. Unlike {@link advanceToEpoch} this does
250
+ * not warp the L1 clock; it only waits for the chain to reach `epoch` through external activity.
251
+ */
252
+ public async waitForEpoch(epoch: EpochNumber, opts: { timeout?: number; interval?: number } = {}): Promise<void> {
253
+ await retryUntil(
254
+ async () => (await this.getEpoch()) >= epoch || undefined,
255
+ `rollup epoch >= ${epoch}`,
256
+ opts.timeout ?? 60,
257
+ opts.interval ?? 1,
258
+ );
259
+ }
260
+
261
+ /**
262
+ * Polls the rollup until its current slot reaches `slot`. Unlike {@link advanceToSlot} this does not
263
+ * warp the L1 clock; it only waits for the chain to reach `slot` through external activity.
264
+ */
265
+ public async waitForSlot(slot: SlotNumber, opts: { timeout?: number; interval?: number } = {}): Promise<void> {
266
+ await retryUntil(
267
+ async () => (await this.getSlot()) >= slot || undefined,
268
+ `rollup slot >= ${slot}`,
269
+ opts.timeout ?? 60,
270
+ opts.interval ?? 1,
271
+ );
272
+ }
273
+
274
+ /**
275
+ * Polls the rollup until its pending checkpoint settles below `checkpoint` on a freshly mined, non-zero
276
+ * checkpoint, and returns that new pending checkpoint number. Reads the L1 rollup contract directly
277
+ * rather than a node, since a rollback lands on L1 first.
278
+ *
279
+ * A prune can momentarily drop the pending checkpoint to 0 before the post-deadline propose mines its
280
+ * replacement, so a caller detecting a rollback wants the new lower checkpoint, not that transient
281
+ * empty state — hence the non-zero guard.
282
+ */
283
+ public async waitForCheckpointBelow(
284
+ checkpoint: CheckpointNumber,
285
+ opts: { timeout?: number; interval?: number } = {},
286
+ ): Promise<CheckpointNumber> {
287
+ return await retryUntil(
288
+ async () => {
289
+ const { pending } = await this.getTips();
290
+ return pending > 0 && pending < checkpoint ? pending : undefined;
291
+ },
292
+ `rollup checkpoint in (0, ${checkpoint})`,
293
+ opts.timeout ?? 60,
294
+ opts.interval ?? 1,
295
+ );
296
+ }
297
+
221
298
  /**
222
299
  * Overrides the inProgress field of the Inbox contract state
223
300
  * @param howMuch - How many checkpoints to move it forward
@@ -259,12 +336,14 @@ export class RollupCheatCodes {
259
336
  });
260
337
  }
261
338
 
262
- public insertOutbox(epoch: EpochNumber, outHash: bigint) {
339
+ public insertOutbox(epoch: EpochNumber, numCheckpointsInEpoch: number, outHash: bigint) {
263
340
  return this.ethCheatCodes.execWithPausedAnvil(async () => {
264
341
  const outboxAddress = await this.rollup.read.getOutbox();
265
- const epochRootSlot = OutboxContract.getEpochRootStorageSlot(epoch);
342
+ const epochRootSlot = OutboxContract.getEpochRootStorageSlot(epoch, numCheckpointsInEpoch);
266
343
  await this.ethCheatCodes.store(EthAddress.fromString(outboxAddress), epochRootSlot, outHash);
267
- this.logger.warn(`Advanced outbox to epoch ${epoch} with out hash ${outHash}`);
344
+ this.logger.warn(
345
+ `Advanced outbox to epoch ${epoch} numCheckpointsInEpoch ${numCheckpointsInEpoch} with out hash ${outHash}`,
346
+ );
268
347
  });
269
348
  }
270
349
 
@@ -313,7 +392,8 @@ export class RollupCheatCodes {
313
392
  }
314
393
 
315
394
  /**
316
- * Directly updates proving cost per mana.
395
+ * Directly updates proving cost per mana. Throws if the on-chain tx reverts
396
+ * (e.g. rate-limit cooldown, step cap, or floor) instead of silently succeeding.
317
397
  * @param ethValue - The new proving cost per mana in ETH
318
398
  */
319
399
  public async setProvingCostPerMana(ethValue: bigint) {
@@ -323,8 +403,37 @@ export class RollupCheatCodes {
323
403
  chain: this.client.chain,
324
404
  gasLimit: 1000000n,
325
405
  });
326
- await this.client.waitForTransactionReceipt({ hash });
406
+ const receipt = await this.client.waitForTransactionReceipt({ hash });
407
+ if (receipt.status !== 'success') {
408
+ throw new Error(
409
+ `setProvingCostPerMana(${ethValue}) reverted on L1 (tx ${hash}). ` +
410
+ `Likely FeeLib rate-limit (30-day cooldown or 1.5x step cap); ` +
411
+ `use clearProvingCostCooldown() between successive updates.`,
412
+ );
413
+ }
327
414
  this.logger.warn(`Updated proving cost per mana to ${ethValue}`);
328
415
  });
329
416
  }
417
+
418
+ /**
419
+ * Resets the 30-day proving-cost update cooldown enforced by FeeLib.updateProvingCostPerMana
420
+ * by zeroing `FeeStore.provingCostLastUpdate` directly in contract storage. Use between
421
+ * successive setProvingCostPerMana / bumpProvingCostPerMana calls so the later update can
422
+ * land instead of reverting. Does not touch L1 time, so PXE/tx-expiration state stays intact.
423
+ *
424
+ * @note This is tightly coupled to the `FeeStore` layout in
425
+ * l1-contracts/src/core/libraries/rollup/FeeLib.sol:
426
+ * slot + 0: CompressedFeeConfig config (uint256)
427
+ * slot + 1: L1GasOracleValues l1GasOracleValues (14+14+4 bytes, packed)
428
+ * slot + 2: uint64 provingCostLastUpdate (only member — zeroing the slot is safe)
429
+ * If the struct layout changes, update the offset below.
430
+ */
431
+ public async clearProvingCostCooldown() {
432
+ const feeStoreBaseSlot = hexToBigInt(keccak256(Buffer.from('aztec.fee.storage', 'utf-8')));
433
+ const provingCostLastUpdateSlot = feeStoreBaseSlot + 2n;
434
+ await this.ethCheatCodes.store(EthAddress.fromString(this.rollup.address), provingCostLastUpdateSlot, 0n, {
435
+ silent: true,
436
+ });
437
+ this.logger.warn(`Cleared proving-cost update cooldown`);
438
+ }
330
439
  }
@@ -1,10 +1,10 @@
1
1
  import { createLogger } from '@aztec/foundation/log';
2
2
  import { makeBackoff, retry } from '@aztec/foundation/retry';
3
3
  import type { TestDateProvider } from '@aztec/foundation/timer';
4
- import { fileURLToPath } from '@aztec/foundation/url';
5
4
 
6
5
  import { type ChildProcess, spawn } from 'child_process';
7
- import { dirname, resolve } from 'path';
6
+
7
+ import { resolveFoundryBinary } from '../foundry_binary.js';
8
8
 
9
9
  /** Minimal interface matching the @viem/anvil Anvil shape used by callers. */
10
10
  export interface Anvil {
@@ -14,6 +14,30 @@ export interface Anvil {
14
14
  stop(): Promise<void>;
15
15
  }
16
16
 
17
+ // Watchdog wrapper: instead of spawning anvil directly, we spawn a small bash supervisor that runs
18
+ // anvil as a background child and polls its own parent (this node process). If the parent dies for
19
+ // ANY reason — including SIGKILL / crash / OOM, where node's own exit handlers never run — the poll
20
+ // loop ends and the EXIT trap reaps anvil. The script is inlined (rather than shipped as a `.sh`) so
21
+ // it works from the published npm tarball too, and the resolved anvil binary is passed via
22
+ // `$ANVIL_BIN` so it works without `anvil` on PATH.
23
+ //
24
+ // `$@` is the anvil argv; `bash -c <script> bash <...args>` puts the args in `$@` and `$0` = 'bash'.
25
+ //
26
+ // The EXIT trap reaps anvil; INT/TERM just `exit` (which fires the EXIT trap) so a signal terminates
27
+ // the supervisor promptly instead of being swallowed — a trapped TERM does NOT terminate the shell,
28
+ // so trapping the kill directly on TERM would leave the poll loop running and the caller's teardown
29
+ // hanging until its SIGKILL escalation. `sleep & wait` makes the poll interruptible, so INT/TERM are
30
+ // handled immediately rather than after the current `sleep` returns.
31
+ const ANVIL_WATCHDOG = `
32
+ set -u
33
+ parent=$PPID
34
+ "$ANVIL_BIN" "$@" &
35
+ anvil_pid=$!
36
+ trap 'kill "$anvil_pid" 2>/dev/null' EXIT
37
+ trap 'exit 0' INT TERM
38
+ while kill -0 "$parent" 2>/dev/null; do sleep 1 & wait $!; done
39
+ `;
40
+
17
41
  /**
18
42
  * Ensures there's a running Anvil instance and returns the RPC URL.
19
43
  */
@@ -42,7 +66,7 @@ export async function startAnvil(
42
66
  dateProvider?: TestDateProvider;
43
67
  } = {},
44
68
  ): Promise<{ anvil: Anvil; methodCalls?: string[]; rpcUrl: string; stop: () => Promise<void> }> {
45
- const anvilBinary = resolve(dirname(fileURLToPath(import.meta.url)), '../../', 'scripts/anvil_kill_wrapper.sh');
69
+ const anvilBinary = resolveFoundryBinary('anvil');
46
70
  const logger = opts.log ? createLogger('ethereum:anvil') : undefined;
47
71
  const methodCalls = opts.captureMethodCalls ? ([] as string[]) : undefined;
48
72
 
@@ -50,6 +74,9 @@ export async function startAnvil(
50
74
 
51
75
  const anvil = await retry(
52
76
  async () => {
77
+ // `--port 0` lets anvil bind an OS-assigned ephemeral port; the actual port is read back from
78
+ // its "Listening on host:port" stdout below, so independent suites can spawn their own anvil
79
+ // in parallel without fighting over a fixed port.
53
80
  const port = opts.port ?? (process.env.ANVIL_PORT ? parseInt(process.env.ANVIL_PORT) : 8545);
54
81
  const args: string[] = [
55
82
  '--host',
@@ -71,9 +98,11 @@ export async function startAnvil(
71
98
  }
72
99
  args.push('--slots-in-an-epoch', String(opts.slotsInAnEpoch ?? 1));
73
100
 
74
- const child = spawn(anvilBinary, args, {
101
+ // Spawn the watchdog (see ANVIL_WATCHDOG). It launches anvil with these args and reaps it if we
102
+ // die; `$0` is 'bash' and `$@` is the anvil argv.
103
+ const child = spawn('bash', ['-c', ANVIL_WATCHDOG, 'bash', ...args], {
75
104
  stdio: ['ignore', 'pipe', 'pipe'],
76
- env: { ...process.env, RAYON_NUM_THREADS: '1' },
105
+ env: { ...process.env, ANVIL_BIN: anvilBinary, RAYON_NUM_THREADS: '1' },
77
106
  });
78
107
 
79
108
  // Wait for "Listening on" or an early exit.
@@ -183,7 +212,10 @@ function syncDateProviderFromAnvilOutput(text: string, dateProvider: TestDatePro
183
212
  }
184
213
  }
185
214
 
186
- /** Send SIGTERM, wait up to 5 s, then SIGKILL. All timers are always cleared. */
215
+ /**
216
+ * Send SIGTERM to the watchdog, wait up to 5 s, then SIGKILL. The watchdog's trap forwards the
217
+ * signal to anvil, so terminating it tears down anvil too. All timers are always cleared.
218
+ */
187
219
  function killChild(child: ChildProcess): Promise<void> {
188
220
  return new Promise<void>(resolve => {
189
221
  if (child.exitCode !== null || child.killed) {