@aztec/ethereum 0.0.1-commit.2f68f620 → 0.0.1-commit.3100065

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 (54) hide show
  1. package/dest/config.d.ts +10 -1
  2. package/dest/config.d.ts.map +1 -1
  3. package/dest/config.js +24 -0
  4. package/dest/contracts/gse.d.ts +4 -2
  5. package/dest/contracts/gse.d.ts.map +1 -1
  6. package/dest/contracts/gse.js +2 -2
  7. package/dest/contracts/rollup.d.ts +168 -9
  8. package/dest/contracts/rollup.d.ts.map +1 -1
  9. package/dest/contracts/rollup.js +15 -5
  10. package/dest/deploy_aztec_l1_contracts.d.ts +5 -6
  11. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  12. package/dest/deploy_aztec_l1_contracts.js +10 -7
  13. package/dest/generated/l1-contracts-defaults.d.ts +1 -1
  14. package/dest/generated/l1-contracts-defaults.js +1 -1
  15. package/dest/l1_artifacts.d.ts +1219 -77
  16. package/dest/l1_artifacts.d.ts.map +1 -1
  17. package/dest/l1_tx_utils/config.js +3 -3
  18. package/dest/l1_tx_utils/l1_tx_utils.d.ts +1 -1
  19. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  20. package/dest/l1_tx_utils/l1_tx_utils.js +57 -15
  21. package/dest/publisher_manager.d.ts +18 -6
  22. package/dest/publisher_manager.d.ts.map +1 -1
  23. package/dest/publisher_manager.js +44 -7
  24. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  25. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  26. package/dest/test/blob_kzg_warmup.js +64 -0
  27. package/dest/test/chain_monitor.d.ts +33 -2
  28. package/dest/test/chain_monitor.d.ts.map +1 -1
  29. package/dest/test/chain_monitor.js +71 -6
  30. package/dest/test/eth_cheat_codes.d.ts +20 -3
  31. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  32. package/dest/test/eth_cheat_codes.js +50 -40
  33. package/dest/test/index.d.ts +2 -1
  34. package/dest/test/index.d.ts.map +1 -1
  35. package/dest/test/index.js +1 -0
  36. package/dest/test/rollup_cheat_codes.d.ts +30 -1
  37. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  38. package/dest/test/rollup_cheat_codes.js +27 -0
  39. package/dest/utils.js +11 -8
  40. package/package.json +5 -5
  41. package/src/config.ts +35 -0
  42. package/src/contracts/gse.ts +7 -2
  43. package/src/contracts/rollup.ts +15 -6
  44. package/src/deploy_aztec_l1_contracts.ts +10 -9
  45. package/src/generated/l1-contracts-defaults.ts +1 -1
  46. package/src/l1_tx_utils/config.ts +3 -3
  47. package/src/l1_tx_utils/l1_tx_utils.ts +52 -18
  48. package/src/publisher_manager.ts +54 -18
  49. package/src/test/blob_kzg_warmup.ts +65 -0
  50. package/src/test/chain_monitor.ts +88 -5
  51. package/src/test/eth_cheat_codes.ts +47 -43
  52. package/src/test/index.ts +1 -0
  53. package/src/test/rollup_cheat_codes.ts +51 -0
  54. package/src/utils.ts +11 -11
@@ -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, {
@@ -273,6 +288,74 @@ export class ChainMonitor extends EventEmitter<ChainMonitorEventMap> {
273
288
  });
274
289
  }
275
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
+
276
359
  private async fetchFeeData(timestamp: bigint): Promise<L2FeeData> {
277
360
  const [components, minFeePerMana, l1Fees, ethPerFeeAsset, manaTarget] = await Promise.all([
278
361
  this.rollup.getManaMinFeeComponentsAt(timestamp, true),
@@ -206,6 +206,22 @@ export class EthCheatCodes {
206
206
  }
207
207
  }
208
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
+
209
225
  /**
210
226
  * Set the automine status of the underlying anvil chain
211
227
  * @param automine - The automine status to set
@@ -478,58 +494,46 @@ export class EthCheatCodes {
478
494
  }
479
495
 
480
496
  /**
481
- * Mines an empty block by temporarily removing all pending transactions from the mempool,
482
- * 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".
483
508
  */
484
509
  public async mineEmptyBlock(blockCount: number = 1): Promise<void> {
485
510
  await this.execWithPausedAnvil(async () => {
486
- // Get all pending and queued transactions from the pool
487
- const txs = await this.getTxPoolContents();
488
-
489
- this.logger.debug(`Found ${txs.length} transactions in pool`);
490
-
491
- // Get raw transactions before dropping them
492
- const rawTxs: Hex[] = [];
493
- for (const tx of txs) {
494
- try {
495
- const rawTx = await this.doRpcCall('debug_getRawTransaction', [tx.hash]);
496
- if (rawTx) {
497
- rawTxs.push(rawTx);
498
- this.logger.debug(`Got raw tx for ${tx.hash}`);
499
- } else {
500
- this.logger.warn(`No raw tx found for ${tx.hash}`);
501
- }
502
- } catch {
503
- this.logger.warn(`Failed to get raw transaction for ${tx.hash}`);
504
- }
505
- }
506
-
507
- this.logger.debug(`Retrieved ${rawTxs.length} raw transactions`);
508
-
509
- // Drop all transactions from the mempool
510
- await this.doRpcCall('anvil_dropAllTransactions', []);
511
-
512
- // Mine an empty block
513
- await this.doMine(blockCount);
514
-
515
- // Re-add the transactions to the pool
516
- for (const rawTx of rawTxs) {
517
- try {
518
- const txHash = await this.doRpcCall('eth_sendRawTransaction', [rawTx]);
519
- this.logger.debug(`Re-added transaction ${txHash}`);
520
- } catch (err) {
521
- this.logger.warn(`Failed to re-add transaction: ${err}`);
522
- }
523
- }
524
-
525
- if (rawTxs.length !== txs.length) {
526
- this.logger.warn(`Failed to add all txs back: had ${txs.length} but re-added ${rawTxs.length}`);
511
+ const originalGasLimit = await this.getBlockGasLimit();
512
+ try {
513
+ await this.setBlockGasLimit(1n);
514
+ await this.doMine(blockCount);
515
+ } finally {
516
+ await this.setBlockGasLimit(originalGasLimit);
527
517
  }
518
+ // Replace the tiny-gas-limit blocks with empty blocks at the restored gas limit, keeping the same
519
+ // height and timestamps. The reorged-out blocks held no transactions, so nothing returns to the pool.
520
+ await this.doRpcCall('anvil_reorg', [blockCount, []]);
528
521
  });
529
522
 
530
523
  this.logger.warn(`Mined ${blockCount} empty L1 ${pluralize('block', blockCount)}`);
531
524
  }
532
525
 
526
+ /** Returns the gas limit of the latest mined L1 block. */
527
+ public async getBlockGasLimit(): Promise<bigint> {
528
+ const block = await this.doRpcCall('eth_getBlockByNumber', ['latest', false]);
529
+ return BigInt(block.gasLimit);
530
+ }
531
+
532
+ /** Sets the block gas limit applied to subsequently mined L1 blocks. */
533
+ public async setBlockGasLimit(gasLimit: bigint): Promise<void> {
534
+ await this.doRpcCall('anvil_setBlockGasLimit', [toHex(gasLimit)]);
535
+ }
536
+
533
537
  public async execWithPausedAnvil<T>(fn: () => Promise<T>): Promise<T> {
534
538
  const [blockInterval, wasAutoMining] = await Promise.all([this.getIntervalMining(), this.isAutoMining()]);
535
539
  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
 
@@ -244,6 +245,56 @@ export class RollupCheatCodes {
244
245
  });
245
246
  }
246
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
+
247
298
  /**
248
299
  * Overrides the inProgress field of the Inbox contract state
249
300
  * @param howMuch - How many checkpoints to move it forward
package/src/utils.ts CHANGED
@@ -235,18 +235,18 @@ export function formatViemError(error: any, abi: Abi = ErrorsAbi): FormattedViem
235
235
  // If decoding fails, we fall back to the original formatting
236
236
  }
237
237
 
238
- // Strip ABI from the error object before formatting
238
+ // Strip ABI from the error object before formatting. We clone first to avoid mutating the
239
+ // caller's error, but structuredClone throws DataCloneError on values it cannot clone (e.g.
240
+ // viem RPC errors carrying function-valued request context). If cloning fails, fall back to
241
+ // formatting the original error untouched rather than letting the clone failure mask it.
239
242
  if (error && typeof error === 'object') {
240
- // Create a clone to avoid modifying the original
241
- const errorClone = structuredClone(error);
242
-
243
- // Helper function to recursively remove ABI properties
244
-
245
- // Strip ABIs from the clone
246
- stripAbis(errorClone);
247
-
248
- // Use the cleaned clone for further processing
249
- error = errorClone;
243
+ try {
244
+ const errorClone = structuredClone(error);
245
+ stripAbis(errorClone);
246
+ error = errorClone;
247
+ } catch {
248
+ // Leave `error` as the original; we skip stripAbis to avoid mutating the caller's object.
249
+ }
250
250
  }
251
251
 
252
252
  // If it's a regular Error instance, return it with its message