@aztec/ethereum 0.0.1-commit.993d240 → 0.0.1-commit.9a89641

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 (105) hide show
  1. package/dest/client.d.ts +11 -3
  2. package/dest/client.d.ts.map +1 -1
  3. package/dest/client.js +35 -3
  4. package/dest/config.d.ts +22 -3
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +54 -3
  7. package/dest/contracts/governance.d.ts +36 -11
  8. package/dest/contracts/governance.d.ts.map +1 -1
  9. package/dest/contracts/governance.js +54 -24
  10. package/dest/contracts/governance_proposer.d.ts +7 -8
  11. package/dest/contracts/governance_proposer.d.ts.map +1 -1
  12. package/dest/contracts/governance_proposer.js +7 -10
  13. package/dest/contracts/gse.d.ts +8 -2
  14. package/dest/contracts/gse.d.ts.map +1 -1
  15. package/dest/contracts/gse.js +11 -2
  16. package/dest/contracts/multicall.d.ts +5 -3
  17. package/dest/contracts/multicall.d.ts.map +1 -1
  18. package/dest/contracts/multicall.js +7 -5
  19. package/dest/contracts/outbox.d.ts +8 -2
  20. package/dest/contracts/outbox.d.ts.map +1 -1
  21. package/dest/contracts/outbox.js +6 -2
  22. package/dest/contracts/rollup.d.ts +176 -9
  23. package/dest/contracts/rollup.d.ts.map +1 -1
  24. package/dest/contracts/rollup.js +48 -8
  25. package/dest/contracts/slashing_proposer.d.ts +37 -6
  26. package/dest/contracts/slashing_proposer.d.ts.map +1 -1
  27. package/dest/contracts/slashing_proposer.js +447 -17
  28. package/dest/deploy_aztec_l1_contracts.d.ts +16 -5
  29. package/dest/deploy_aztec_l1_contracts.d.ts.map +1 -1
  30. package/dest/deploy_aztec_l1_contracts.js +26 -13
  31. package/dest/foundry_binary.d.ts +13 -0
  32. package/dest/foundry_binary.d.ts.map +1 -0
  33. package/dest/foundry_binary.js +52 -0
  34. package/dest/l1_artifacts.d.ts +1242 -95
  35. package/dest/l1_artifacts.d.ts.map +1 -1
  36. package/dest/l1_tx_utils/config.js +3 -3
  37. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts +23 -4
  38. package/dest/l1_tx_utils/l1_fee_analyzer.d.ts.map +1 -1
  39. package/dest/l1_tx_utils/l1_fee_analyzer.js +65 -3
  40. package/dest/l1_tx_utils/l1_tx_utils.d.ts +1 -1
  41. package/dest/l1_tx_utils/l1_tx_utils.d.ts.map +1 -1
  42. package/dest/l1_tx_utils/l1_tx_utils.js +84 -22
  43. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts +1 -1
  44. package/dest/l1_tx_utils/readonly_l1_tx_utils.d.ts.map +1 -1
  45. package/dest/l1_tx_utils/readonly_l1_tx_utils.js +2 -1
  46. package/dest/l1_tx_utils/types.d.ts +27 -1
  47. package/dest/l1_tx_utils/types.d.ts.map +1 -1
  48. package/dest/l1_tx_utils/types.js +10 -0
  49. package/dest/publisher_manager.d.ts +18 -6
  50. package/dest/publisher_manager.d.ts.map +1 -1
  51. package/dest/publisher_manager.js +44 -7
  52. package/dest/queries.d.ts +1 -1
  53. package/dest/queries.d.ts.map +1 -1
  54. package/dest/queries.js +7 -1
  55. package/dest/test/blob_kzg_warmup.d.ts +19 -0
  56. package/dest/test/blob_kzg_warmup.d.ts.map +1 -0
  57. package/dest/test/blob_kzg_warmup.js +64 -0
  58. package/dest/test/chain_monitor.d.ts +33 -2
  59. package/dest/test/chain_monitor.d.ts.map +1 -1
  60. package/dest/test/chain_monitor.js +71 -6
  61. package/dest/test/eth_cheat_codes.d.ts +26 -3
  62. package/dest/test/eth_cheat_codes.d.ts.map +1 -1
  63. package/dest/test/eth_cheat_codes.js +72 -37
  64. package/dest/test/index.d.ts +2 -1
  65. package/dest/test/index.d.ts.map +1 -1
  66. package/dest/test/index.js +1 -0
  67. package/dest/test/rollup_cheat_codes.d.ts +30 -1
  68. package/dest/test/rollup_cheat_codes.d.ts.map +1 -1
  69. package/dest/test/rollup_cheat_codes.js +27 -0
  70. package/dest/test/start_anvil.d.ts +1 -1
  71. package/dest/test/start_anvil.d.ts.map +1 -1
  72. package/dest/test/start_anvil.js +41 -5
  73. package/dest/utils.d.ts +2 -2
  74. package/dest/utils.d.ts.map +1 -1
  75. package/dest/utils.js +15 -6
  76. package/package.json +5 -6
  77. package/src/client.ts +39 -1
  78. package/src/config.ts +73 -3
  79. package/src/contracts/governance.ts +63 -20
  80. package/src/contracts/governance_proposer.ts +11 -15
  81. package/src/contracts/gse.ts +19 -2
  82. package/src/contracts/multicall.ts +8 -5
  83. package/src/contracts/outbox.ts +6 -2
  84. package/src/contracts/rollup.ts +57 -8
  85. package/src/contracts/slashing_proposer.ts +78 -15
  86. package/src/deploy_aztec_l1_contracts.ts +31 -13
  87. package/src/foundry_binary.ts +57 -0
  88. package/src/l1_tx_utils/config.ts +3 -3
  89. package/src/l1_tx_utils/l1_fee_analyzer.ts +75 -3
  90. package/src/l1_tx_utils/l1_tx_utils.ts +71 -20
  91. package/src/l1_tx_utils/readonly_l1_tx_utils.ts +2 -1
  92. package/src/l1_tx_utils/types.ts +32 -0
  93. package/src/publisher_manager.ts +54 -18
  94. package/src/queries.ts +6 -0
  95. package/src/test/blob_kzg_warmup.ts +65 -0
  96. package/src/test/chain_monitor.ts +88 -5
  97. package/src/test/eth_cheat_codes.ts +66 -41
  98. package/src/test/index.ts +1 -0
  99. package/src/test/rollup_cheat_codes.ts +51 -0
  100. package/src/test/start_anvil.ts +38 -6
  101. package/src/utils.ts +12 -6
  102. package/dest/generated/l1-contracts-defaults.d.ts +0 -30
  103. package/dest/generated/l1-contracts-defaults.d.ts.map +0 -1
  104. package/dest/generated/l1-contracts-defaults.js +0 -30
  105. package/src/generated/l1-contracts-defaults.ts +0 -32
@@ -5,7 +5,7 @@ import { InterruptError, TimeoutError } from '@aztec/foundation/error';
5
5
  import { EthAddress } from '@aztec/foundation/eth-address';
6
6
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
7
7
  import { Semaphore } from '@aztec/foundation/queue';
8
- import { retryUntil } from '@aztec/foundation/retry';
8
+ import { makeBackoff, retry, retryUntil } from '@aztec/foundation/retry';
9
9
  import { sleep } from '@aztec/foundation/sleep';
10
10
  import { DateProvider } from '@aztec/foundation/timer';
11
11
  import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
@@ -36,6 +36,7 @@ import {
36
36
  type L1TxConfig,
37
37
  type L1TxRequest,
38
38
  type L1TxState,
39
+ L1TxTimeoutError,
39
40
  type SigningCallback,
40
41
  TerminalTxUtilsState,
41
42
  TxUtilsState,
@@ -44,6 +45,11 @@ import {
44
45
 
45
46
  const MAX_L1_TX_STATES = 32;
46
47
 
48
+ // Backoff (in seconds) for retrying the read-only RPC calls that prepare a tx cancellation. A
49
+ // cancellation is fired in the background after a tx times out and is important (it frees the stuck
50
+ // nonce), so a transient RPC failure while reading the pending nonce or gas price must not abandon it.
51
+ const CANCELLATION_PREP_RETRY_BACKOFF_S = [1, 2, 4, 8];
52
+
47
53
  export class L1TxUtils extends ReadOnlyL1TxUtils {
48
54
  protected txs: L1TxState[] = [];
49
55
  /** Last nonce successfully sent to the chain. Used as a lower bound when a fallback RPC node returns a stale count. */
@@ -301,6 +307,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
301
307
  txConfigOverrides: gasConfigOverrides ?? {},
302
308
  sentAtL1Ts: now,
303
309
  lastSentAtL1Ts: now,
310
+ gasPriceHistory: [baseState.gasPrice],
304
311
  };
305
312
 
306
313
  // And persist it
@@ -431,10 +438,23 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
431
438
 
432
439
  const initialTxHash = txHashes[0];
433
440
  let currentTxHash = txHashes.at(-1)!;
434
- let l1Timestamp: number;
441
+ let l1Timestamp = 0;
435
442
 
436
443
  while (true) {
437
- l1Timestamp = await this.getL1Timestamp();
444
+ try {
445
+ l1Timestamp = await this.getL1Timestamp();
446
+ } catch (err) {
447
+ // A transient RPC failure here must not abort monitoring with a rejection: callers that
448
+ // fire this loop in the background would surface it as an unhandled rejection (e.g. when a
449
+ // test tears down its L1 node while a monitor iteration is in flight). Exit quietly if we
450
+ // are shutting down, otherwise retry on the next interval.
451
+ if (this.interrupted) {
452
+ break;
453
+ }
454
+ this.logger.error(`Error fetching L1 timestamp while monitoring tx ${currentTxHash}`, err, { nonce, account });
455
+ await sleep(gasConfig.checkIntervalMs!);
456
+ continue;
457
+ }
438
458
 
439
459
  try {
440
460
  const timePassed = l1Timestamp - state.lastSentAtL1Ts.getTime();
@@ -486,6 +506,7 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
486
506
  if (timePassed >= stallTimeMs && attempts <= maxSpeedUpAttempts) {
487
507
  const newGasPrice = await this.getGasPrice(gasConfig, isBlobTx, attempts, state.gasPrice);
488
508
  state.gasPrice = newGasPrice;
509
+ state.gasPriceHistory?.push(newGasPrice);
489
510
 
490
511
  this.logger.debug(
491
512
  `Tx ${currentTxHash} with nonce ${nonce} from ${account} appears stuck. ` +
@@ -654,8 +675,22 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
654
675
  blobInputs?: L1BlobInputs,
655
676
  ): Promise<{ receipt: TransactionReceipt; state: L1TxState }> {
656
677
  const { state } = await this.sendTransaction(request, gasConfig, blobInputs);
657
- const receipt = await this.monitorTransaction(state);
658
- return { receipt, state };
678
+ try {
679
+ const receipt = await this.monitorTransaction(state);
680
+ return { receipt, state };
681
+ } catch (err) {
682
+ if (err instanceof TimeoutError) {
683
+ // Snapshot the ladder now: the fire-and-forget cancellation mutates state.gasPrice moments later.
684
+ throw new L1TxTimeoutError(err.message, {
685
+ gasPriceHistory: state.gasPriceHistory ? [...state.gasPriceHistory] : undefined,
686
+ finalGasPrice: state.gasPrice,
687
+ attempts: state.txHashes.length,
688
+ nonce: state.nonce,
689
+ gasLimit: state.gasLimit,
690
+ });
691
+ }
692
+ throw err;
693
+ }
659
694
  }
660
695
 
661
696
  public override async simulate(
@@ -706,9 +741,37 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
706
741
  return;
707
742
  }
708
743
 
709
- // Check if the original tx is still pending
710
- const currentNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
711
- if (currentNonce < nonce) {
744
+ // Resolve the pending nonce and cancellation gas price up front. These are read-only RPC calls, so
745
+ // they are safe to retry; a transient RPC failure here must not permanently abandon the cancellation
746
+ // (which would leave the nonce stuck and the tx state stranded short of CANCELLED). We retry with a
747
+ // real backoff before giving up, unlike getGasPrice's tight internal retry which can be exhausted by
748
+ // a brief node hiccup. The retried block performs no state-changing send, so retrying cannot
749
+ // double-send the cancellation tx.
750
+ const { currentNonce, cancelGasPrice } = await retry(
751
+ async () => {
752
+ const currentNonce = await this.client.getTransactionCount({ address: account, blockTag: 'pending' });
753
+ if (currentNonce >= nonce) {
754
+ // Get gas price with higher priority fee for cancellation
755
+ const cancelGasPrice = await this.getGasPrice(
756
+ {
757
+ ...this.config,
758
+ // Use high bump for cancellation to ensure it replaces the original tx
759
+ priorityFeeRetryBumpPercentage: 150, // 150% bump should be enough to replace any tx
760
+ },
761
+ isBlobTx,
762
+ state.txHashes.length,
763
+ previousGasPrice,
764
+ );
765
+ return { currentNonce, cancelGasPrice };
766
+ }
767
+ return { currentNonce, cancelGasPrice: undefined };
768
+ },
769
+ `Preparing cancellation for L1 tx from account ${account} with nonce ${nonce}`,
770
+ makeBackoff(CANCELLATION_PREP_RETRY_BACKOFF_S),
771
+ this.logger,
772
+ );
773
+
774
+ if (cancelGasPrice === undefined) {
712
775
  this.logger.verbose(
713
776
  `Not sending cancellation for L1 tx from account ${account} with nonce ${nonce} as it is dropped`,
714
777
  { nonce, account, currentNonce },
@@ -717,18 +780,6 @@ export class L1TxUtils extends ReadOnlyL1TxUtils {
717
780
  return;
718
781
  }
719
782
 
720
- // Get gas price with higher priority fee for cancellation
721
- const cancelGasPrice = await this.getGasPrice(
722
- {
723
- ...this.config,
724
- // Use high bump for cancellation to ensure it replaces the original tx
725
- priorityFeeRetryBumpPercentage: 150, // 150% bump should be enough to replace any tx
726
- },
727
- isBlobTx,
728
- state.txHashes.length,
729
- previousGasPrice,
730
- );
731
-
732
783
  const { maxFeePerGas, maxPriorityFeePerGas, maxFeePerBlobGas } = cancelGasPrice;
733
784
  this.logger.verbose(
734
785
  `Attempting to cancel L1 ${isBlobTx ? 'blob' : 'vanilla'} transaction from account ${account} with nonce ${nonce} after time out`,
@@ -3,6 +3,7 @@ import type { EthAddress } from '@aztec/foundation/eth-address';
3
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
4
4
  import { makeBackoff, retry } from '@aztec/foundation/retry';
5
5
  import { DateProvider } from '@aztec/foundation/timer';
6
+ import { getErrorCause } from '@aztec/foundation/types';
6
7
  import { RollupAbi } from '@aztec/l1-artifacts/RollupAbi';
7
8
 
8
9
  import pickBy from 'lodash.pickby';
@@ -395,7 +396,7 @@ export class ReadOnlyL1TxUtils {
395
396
  this.logger?.debug(`L1 transaction simulation succeeded`, { ...result[0].calls[0] });
396
397
  return { gasUsed: result[0].gasUsed, result: result[0].calls[0].data as `0x${string}` };
397
398
  } catch (err) {
398
- if (err instanceof MethodNotFoundRpcError || err instanceof MethodNotSupportedRpcError) {
399
+ if (getErrorCause(err, MethodNotFoundRpcError) || getErrorCause(err, MethodNotSupportedRpcError)) {
399
400
  if (gasConfig.fallbackGasEstimate) {
400
401
  this.logger?.warn(
401
402
  `Node does not support eth_simulateV1 API. Using fallback gas estimate: ${gasConfig.fallbackGasEstimate}`,
@@ -1,4 +1,5 @@
1
1
  import type { BlobKzgInstance } from '@aztec/blob-lib/types';
2
+ import { TimeoutError } from '@aztec/foundation/error';
2
3
  import { EthAddress } from '@aztec/foundation/eth-address';
3
4
  import type { ViemTransactionSignature } from '@aztec/foundation/eth-signature';
4
5
 
@@ -55,6 +56,12 @@ export type L1TxState = {
55
56
  cancelTxHashes: Hex[];
56
57
  gasLimit: bigint;
57
58
  gasPrice: GasPrice;
59
+ /**
60
+ * Prices used for each attempt (initial send followed by each speed-up), in order. Always set on
61
+ * newly sent txs; optional because states restored from the state store predate the field.
62
+ * In-memory only — not persisted by the state store.
63
+ */
64
+ gasPriceHistory?: GasPrice[];
58
65
  txConfigOverrides: L1TxConfig;
59
66
  request: L1TxRequest;
60
67
  status: TxUtilsState;
@@ -83,3 +90,28 @@ export class DroppedTransactionError extends Error {
83
90
  this.name = 'DroppedTransactionError';
84
91
  }
85
92
  }
93
+
94
+ /** Snapshot of what a timed-out L1 tx tried to pay, taken when the timeout is raised. */
95
+ export type TimedOutTxState = {
96
+ /** Prices used across the initial send and each speed-up, in order (undefined only for restored states). */
97
+ gasPriceHistory?: GasPrice[];
98
+ /** The last price the tx was sent at before timing out. */
99
+ finalGasPrice: GasPrice;
100
+ /** Number of send attempts (initial + speed-ups). */
101
+ attempts: number;
102
+ nonce: number;
103
+ gasLimit: bigint;
104
+ };
105
+
106
+ /**
107
+ * Thrown by sendAndMonitorTransaction when a tx times out. Subclasses TimeoutError so existing
108
+ * `instanceof TimeoutError` checks keep working, while carrying the gas-price ladder for diagnostics.
109
+ */
110
+ export class L1TxTimeoutError extends TimeoutError {
111
+ constructor(
112
+ message: string,
113
+ public readonly txState: TimedOutTxState,
114
+ ) {
115
+ super(message);
116
+ }
117
+ }
@@ -40,11 +40,12 @@ export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
40
40
  private log: Logger;
41
41
  private config: PublisherManagerConfig;
42
42
  private static readonly FUNDING_CHECK_INTERVAL_MS = 2 * 60 * 1000;
43
- private funder?: UtilsType;
44
- private fundingPromise?: RunningPromise;
43
+ protected funder?: UtilsType;
44
+ protected readonly fundingPromise?: RunningPromise;
45
+ private started = false;
45
46
 
46
47
  constructor(
47
- private publishers: UtilsType[],
48
+ protected publishers: UtilsType[],
48
49
  config: PublisherManagerConfig,
49
50
  opts?: { bindings?: LoggerBindings; funder?: UtilsType },
50
51
  ) {
@@ -67,34 +68,60 @@ export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
67
68
  this.funder = undefined;
68
69
  }
69
70
  }
71
+
72
+ if (this.funder && hasThreshold && hasAmount) {
73
+ this.fundingPromise = new RunningPromise(
74
+ () => this.triggerFundingIfNeeded(),
75
+ this.log,
76
+ PublisherManager.FUNDING_CHECK_INTERVAL_MS,
77
+ );
78
+ }
70
79
  }
71
80
 
72
- /** Loads the state of all publishers and the funder, and starts periodic funding checks. */
81
+ /**
82
+ * Clears any interrupted flag left by a previous {@link stop} so publishing works again after a restart,
83
+ * loads the state of all publishers and the funder, and starts periodic funding checks. Idempotent: a
84
+ * start while already started is a no-op, so it never re-runs `loadStateAndResumeMonitoring` (which
85
+ * would spawn a duplicate background monitor per pending nonce). Lifecycle calls are expected to be
86
+ * serialized by the caller.
87
+ */
73
88
  public async start(): Promise<void> {
89
+ if (this.started) {
90
+ this.log.debug('PublisherManager already started, ignoring start');
91
+ return;
92
+ }
93
+
94
+ // Clear the interrupted flag set by a previous stop() so a restarted manager can publish again.
95
+ // On a first start this is a no-op (the flag is already clear).
96
+ this.publishers.forEach(pub => pub.restart());
97
+ this.funder?.restart();
98
+
74
99
  await Promise.all([
75
100
  ...this.publishers.map(pub => pub.loadStateAndResumeMonitoring()),
76
101
  this.funder?.loadStateAndResumeMonitoring(),
77
102
  ]);
78
103
 
79
- if (
80
- this.funder &&
81
- this.config.publisherFundingThreshold !== undefined &&
82
- this.config.publisherFundingAmount !== undefined
83
- ) {
84
- this.fundingPromise = new RunningPromise(
85
- () => this.triggerFundingIfNeeded(),
86
- this.log,
87
- PublisherManager.FUNDING_CHECK_INTERVAL_MS,
88
- );
89
- this.fundingPromise.start();
90
- }
104
+ this.fundingPromise?.start();
105
+ // Marked started only once fully up, so a start that failed to load state can be retried.
106
+ this.started = true;
91
107
  }
92
108
 
93
- /** Stops the funding loop and interrupts all publishers. */
109
+ /**
110
+ * Stops the funding loop, interrupts all publishers so no further L1 txs are sent, and waits (bounded)
111
+ * for their in-flight tx monitor loops to wind down. Idempotent, and the manager may be restarted
112
+ * afterwards via {@link start}, which clears the interrupted flag.
113
+ */
94
114
  public async stop(): Promise<void> {
115
+ this.started = false;
95
116
  await this.fundingPromise?.stop();
96
117
  this.publishers.forEach(pub => pub.interrupt());
97
118
  this.funder?.interrupt();
119
+ // Wait for in-flight tx monitor loops to observe the interrupt, so no L1 requests are still
120
+ // being issued after shutdown (e.g. against an anvil instance a test is about to tear down).
121
+ await Promise.all([
122
+ ...this.publishers.map(pub => pub.waitMonitoringStopped()),
123
+ this.funder?.waitMonitoringStopped(),
124
+ ]);
98
125
  }
99
126
 
100
127
  // Finds and prioritises available publishers based on
@@ -133,8 +160,17 @@ export class PublisherManager<UtilsType extends L1TxUtils = L1TxUtils> {
133
160
  }),
134
161
  );
135
162
 
163
+ // Discount unfunded publishers: a publisher with no ETH cannot send a tx, so it must never win
164
+ // selection regardless of how favourable its state or last-used time is. Fall back to the full
165
+ // set only if every candidate is unfunded, so behaviour is no worse than before.
166
+ let fundedPublishers = publishersWithBalance.filter(p => p.balance > 0n);
167
+ if (fundedPublishers.length === 0) {
168
+ this.log.warn(`All candidate publishers have zero balance; selecting from unfunded publishers.`);
169
+ fundedPublishers = publishersWithBalance;
170
+ }
171
+
136
172
  // Sort based on state, then balance, then time since last use
137
- const sortedPublishers = publishersWithBalance.sort((a, b) => {
173
+ const sortedPublishers = fundedPublishers.sort((a, b) => {
138
174
  const stateComparison = sortOrder.indexOf(a.publisher.state) - sortOrder.indexOf(b.publisher.state);
139
175
  if (stateComparison !== 0) {
140
176
  return stateComparison;
package/src/queries.ts CHANGED
@@ -186,5 +186,11 @@ export async function getL1ContractsConfig(
186
186
  slashAmountMedium: slashingAmounts[1],
187
187
  slashAmountLarge: slashingAmounts[2],
188
188
  initialEthPerFeeAsset: DefaultL1ContractsConfig.initialEthPerFeeAsset,
189
+ // Not exposed by the rollup contract; fall back to defaults like the other non-on-chain fields above.
190
+ entryQueueBootstrapValidatorSetSize: DefaultL1ContractsConfig.entryQueueBootstrapValidatorSetSize,
191
+ entryQueueBootstrapFlushSize: DefaultL1ContractsConfig.entryQueueBootstrapFlushSize,
192
+ entryQueueFlushSizeMin: DefaultL1ContractsConfig.entryQueueFlushSizeMin,
193
+ entryQueueFlushSizeQuotient: DefaultL1ContractsConfig.entryQueueFlushSizeQuotient,
194
+ entryQueueMaxFlushSize: DefaultL1ContractsConfig.entryQueueMaxFlushSize,
189
195
  };
190
196
  }
@@ -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,67 @@ 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".
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.
483
514
  */
484
515
  public async mineEmptyBlock(blockCount: number = 1): Promise<void> {
485
516
  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
- }
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);
505
527
  }
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}`);
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', []);
522
540
  }
523
541
  }
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}`);
527
- }
528
542
  });
529
543
 
530
544
  this.logger.warn(`Mined ${blockCount} empty L1 ${pluralize('block', blockCount)}`);
531
545
  }
532
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
+
533
558
  public async execWithPausedAnvil<T>(fn: () => Promise<T>): Promise<T> {
534
559
  const [blockInterval, wasAutoMining] = await Promise.all([this.getIntervalMining(), this.isAutoMining()]);
535
560
  try {