@aztec/sequencer-client 5.0.0-private.20260319 → 5.0.0-rc.1

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/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +8 -3
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +17 -32
  5. package/dest/config.d.ts +10 -4
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +48 -24
  8. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  9. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  10. package/dest/global_variable_builder/fee_predictor.js +128 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_provider.js +67 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +14 -14
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +16 -51
  17. package/dest/global_variable_builder/index.d.ts +4 -2
  18. package/dest/global_variable_builder/index.d.ts.map +1 -1
  19. package/dest/global_variable_builder/index.js +2 -0
  20. package/dest/publisher/config.d.ts +15 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +19 -4
  23. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +3 -4
  24. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  25. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  26. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  27. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  28. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -5
  29. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  30. package/dest/publisher/sequencer-publisher-factory.js +2 -3
  31. package/dest/publisher/sequencer-publisher.d.ts +70 -64
  32. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher.js +312 -533
  34. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  35. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  36. package/dest/sequencer/automine/automine_factory.js +85 -0
  37. package/dest/sequencer/automine/automine_sequencer.d.ts +184 -0
  38. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  39. package/dest/sequencer/automine/automine_sequencer.js +677 -0
  40. package/dest/sequencer/automine/index.d.ts +3 -0
  41. package/dest/sequencer/automine/index.d.ts.map +1 -0
  42. package/dest/sequencer/automine/index.js +2 -0
  43. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  44. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  45. package/dest/sequencer/chain_state_overrides.js +98 -0
  46. package/dest/sequencer/checkpoint_proposal_job.d.ts +73 -21
  47. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  48. package/dest/sequencer/checkpoint_proposal_job.js +709 -199
  49. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  50. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  51. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  52. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  53. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  54. package/dest/sequencer/checkpoint_voter.js +2 -5
  55. package/dest/sequencer/errors.d.ts +1 -8
  56. package/dest/sequencer/errors.d.ts.map +1 -1
  57. package/dest/sequencer/errors.js +0 -9
  58. package/dest/sequencer/events.d.ts +61 -4
  59. package/dest/sequencer/events.d.ts.map +1 -1
  60. package/dest/sequencer/metrics.d.ts +9 -10
  61. package/dest/sequencer/metrics.d.ts.map +1 -1
  62. package/dest/sequencer/metrics.js +34 -20
  63. package/dest/sequencer/sequencer.d.ts +112 -27
  64. package/dest/sequencer/sequencer.d.ts.map +1 -1
  65. package/dest/sequencer/sequencer.js +467 -147
  66. package/dest/sequencer/types.d.ts +2 -2
  67. package/dest/sequencer/types.d.ts.map +1 -1
  68. package/dest/test/index.d.ts +3 -3
  69. package/dest/test/index.d.ts.map +1 -1
  70. package/dest/test/utils.d.ts +15 -1
  71. package/dest/test/utils.d.ts.map +1 -1
  72. package/dest/test/utils.js +23 -6
  73. package/package.json +28 -27
  74. package/src/client/sequencer-client.ts +29 -41
  75. package/src/config.ts +57 -24
  76. package/src/global_variable_builder/README.md +44 -0
  77. package/src/global_variable_builder/fee_predictor.ts +172 -0
  78. package/src/global_variable_builder/fee_provider.ts +80 -0
  79. package/src/global_variable_builder/global_builder.ts +25 -63
  80. package/src/global_variable_builder/index.ts +3 -1
  81. package/src/publisher/config.ts +40 -6
  82. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  83. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  84. package/src/publisher/sequencer-publisher-factory.ts +3 -6
  85. package/src/publisher/sequencer-publisher.ts +368 -577
  86. package/src/sequencer/automine/README.md +60 -0
  87. package/src/sequencer/automine/automine_factory.ts +152 -0
  88. package/src/sequencer/automine/automine_sequencer.ts +783 -0
  89. package/src/sequencer/automine/index.ts +6 -0
  90. package/src/sequencer/chain_state_overrides.ts +169 -0
  91. package/src/sequencer/checkpoint_proposal_job.ts +818 -224
  92. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  93. package/src/sequencer/checkpoint_voter.ts +1 -12
  94. package/src/sequencer/errors.ts +0 -15
  95. package/src/sequencer/events.ts +65 -4
  96. package/src/sequencer/metrics.ts +43 -24
  97. package/src/sequencer/sequencer.ts +542 -164
  98. package/src/sequencer/types.ts +1 -1
  99. package/src/test/index.ts +2 -2
  100. package/src/test/utils.ts +59 -10
  101. package/dest/sequencer/timetable.d.ts +0 -88
  102. package/dest/sequencer/timetable.d.ts.map +0 -1
  103. package/dest/sequencer/timetable.js +0 -222
  104. package/src/sequencer/README.md +0 -531
  105. package/src/sequencer/timetable.ts +0 -283
@@ -3,16 +3,15 @@ import { Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec/
3
3
  import type { EpochCache } from '@aztec/epoch-cache';
4
4
  import type { L1ContractsConfig } from '@aztec/ethereum/config';
5
5
  import {
6
- type EmpireSlashingProposerContract,
7
6
  FeeAssetPriceOracle,
8
7
  type GovernanceProposerContract,
9
- type IEmpireBase,
10
8
  MULTI_CALL_3_ADDRESS,
11
9
  Multicall3,
12
- RollupContract,
13
- type TallySlashingProposerContract,
14
- type ViemCommitteeAttestations,
15
- type ViemHeader,
10
+ MulticallForwarderRevertedError,
11
+ type RollupContract,
12
+ type SimulationOverridesPlan,
13
+ type SlashingProposerContract,
14
+ buildSimulationOverridesStateOverride,
16
15
  } from '@aztec/ethereum/contracts';
17
16
  import { type L1FeeAnalysisResult, L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
18
17
  import {
@@ -24,44 +23,81 @@ import {
24
23
  type TransactionStats,
25
24
  WEI_CONST,
26
25
  } from '@aztec/ethereum/l1-tx-utils';
27
- import { FormattedViemError, formatViemError, mergeAbis, tryExtractEvent } from '@aztec/ethereum/utils';
28
- import { sumBigint } from '@aztec/foundation/bigint';
29
- import { toHex as toPaddedHex } from '@aztec/foundation/bigint-buffer';
26
+ import {
27
+ FormattedViemError,
28
+ formatViemError,
29
+ mergeAbis,
30
+ tryDecodeRevertReason,
31
+ tryExtractEvent,
32
+ } from '@aztec/ethereum/utils';
30
33
  import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
31
34
  import { trimmedBytesLength } from '@aztec/foundation/buffer';
32
35
  import { pick } from '@aztec/foundation/collection';
33
36
  import type { Fr } from '@aztec/foundation/curves/bn254';
34
37
  import { TimeoutError } from '@aztec/foundation/error';
35
38
  import { EthAddress } from '@aztec/foundation/eth-address';
36
- import { Signature, type ViemSignature } from '@aztec/foundation/eth-signature';
39
+ import { Signature } from '@aztec/foundation/eth-signature';
37
40
  import { type Logger, createLogger } from '@aztec/foundation/log';
38
- import { makeBackoff, retry } from '@aztec/foundation/retry';
41
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
39
42
  import { bufferToHex } from '@aztec/foundation/string';
40
- import { DateProvider, Timer } from '@aztec/foundation/timer';
41
- import { EmpireBaseAbi, ErrorsAbi, RollupAbi } from '@aztec/l1-artifacts';
43
+ import { type DateProvider, Timer } from '@aztec/foundation/timer';
44
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi, SlashingProposerAbi } from '@aztec/l1-artifacts';
42
45
  import { type ProposerSlashAction, encodeSlashConsensusVotes } from '@aztec/slasher';
43
46
  import { CommitteeAttestationsAndSigners, type ValidateCheckpointResult } from '@aztec/stdlib/block';
44
47
  import type { Checkpoint } from '@aztec/stdlib/checkpoint';
45
- import { SlashFactoryContract } from '@aztec/stdlib/l1-contracts';
48
+ import {
49
+ getLastL1SlotTimestampForL2Slot,
50
+ getNextL1SlotTimestamp,
51
+ getTimestampForSlot,
52
+ } from '@aztec/stdlib/epoch-helpers';
46
53
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
47
54
  import type { L1PublishCheckpointStats } from '@aztec/stdlib/stats';
48
55
  import { type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
49
56
 
50
57
  import {
58
+ type Abi,
51
59
  type Hex,
52
- type StateOverride,
53
60
  type TransactionReceipt,
54
61
  type TypedDataDefinition,
55
62
  encodeFunctionData,
56
63
  keccak256,
57
- multicall3Abi,
58
64
  toHex,
59
65
  } from 'viem';
60
66
 
61
67
  import type { SequencerPublisherConfig } from './config.js';
62
68
  import { type FailedL1Tx, type L1TxFailedStore, createL1TxFailedStore } from './l1_tx_failed_store/index.js';
69
+ import { type DroppedRequest, SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
63
70
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
64
71
 
72
+ /**
73
+ * Returns true if the receipt indicates a successful send AND the expected event was emitted
74
+ * by the target contract. Both pieces are required: an aggregate3 entry that reverted will
75
+ * have receipt.status === 'success' but no event log.
76
+ */
77
+ function extractEventSuccess(
78
+ receipt: TransactionReceipt | undefined,
79
+ opts: { address: string; abi: Abi; eventName: string },
80
+ ): boolean {
81
+ if (!receipt || receipt.status !== 'success') {
82
+ return false;
83
+ }
84
+ return !!tryExtractEvent(receipt.logs, opts.address.toString() as Hex, opts.abi, opts.eventName);
85
+ }
86
+
87
+ /** Result of a sendRequests call, returned by both sendRequests() and sendRequestsAt(). */
88
+ export type SendRequestsResult = {
89
+ /** The L1 transaction receipt from the bundled multicall. */
90
+ result: { receipt: TransactionReceipt };
91
+ /** Actions that expired (past their deadline) before the request was sent. */
92
+ expiredActions: Action[];
93
+ /** Actions that were included in the sent L1 transaction. */
94
+ sentActions: Action[];
95
+ /** Actions whose L1 simulation succeeded (subset of sentActions). */
96
+ successfulActions: Action[];
97
+ /** Actions whose L1 simulation failed (subset of sentActions). */
98
+ failedActions: Action[];
99
+ };
100
+
65
101
  /** Arguments to the process method of the rollup contract */
66
102
  type L1ProcessArgs = {
67
103
  /** The L2 block header. */
@@ -83,16 +119,13 @@ export const Actions = [
83
119
  'invalidate-by-insufficient-attestations',
84
120
  'propose',
85
121
  'governance-signal',
86
- 'empire-slashing-signal',
87
- 'create-empire-payload',
88
- 'execute-empire-payload',
89
122
  'vote-offenses',
90
123
  'execute-slash',
91
124
  ] as const;
92
125
 
93
126
  export type Action = (typeof Actions)[number];
94
127
 
95
- type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slashing-signal'>;
128
+ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
96
129
 
97
130
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
98
131
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
@@ -103,14 +136,22 @@ export type InvalidateCheckpointRequest = {
103
136
  gasUsed: bigint;
104
137
  checkpointNumber: CheckpointNumber;
105
138
  forcePendingCheckpointNumber: CheckpointNumber;
139
+ /** Archive at the rollback target checkpoint (checkpoint N-1). */
140
+ lastArchive: Fr;
141
+ };
142
+
143
+ type EnqueueProposeCheckpointOpts = {
144
+ txTimeoutAt?: Date;
106
145
  };
107
146
 
108
- interface RequestWithExpiry {
147
+ export interface RequestWithExpiry {
109
148
  action: Action;
110
149
  request: L1TxRequest;
111
150
  lastValidL2Slot: SlotNumber;
112
151
  gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
113
152
  blobConfig?: L1BlobInputs;
153
+ /** Gas consumed by validateBlobs; stashed for the bundle simulate at send time. */
154
+ blobEvaluationGas?: bigint;
114
155
  checkSuccess: (
115
156
  request: L1TxRequest,
116
157
  result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
@@ -120,25 +161,27 @@ interface RequestWithExpiry {
120
161
  export class SequencerPublisher {
121
162
  private interrupted = false;
122
163
  private metrics: SequencerPublisherMetrics;
164
+ private bundleSimulator: SequencerBundleSimulator;
123
165
  public epochCache: EpochCache;
124
166
  private failedTxStore?: Promise<L1TxFailedStore | undefined>;
125
167
 
126
- protected governanceLog = createLogger('sequencer:publisher:governance');
127
- protected slashingLog = createLogger('sequencer:publisher:slashing');
168
+ /**
169
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
170
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
171
+ * publisher can route to so any of their custom errors decode against it.
172
+ */
173
+ private readonly revertDecoderAbi: Abi = mergeAbis([RollupAbi, SlashingProposerAbi, EmpireBaseAbi, ErrorsAbi]);
128
174
 
129
175
  protected lastActions: Partial<Record<Action, SlotNumber>> = {};
130
176
 
131
- private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
132
- private payloadProposedCache: Set<string> = new Set<string>();
133
-
134
177
  protected log: Logger;
135
178
  protected ethereumSlotDuration: bigint;
136
179
  protected aztecSlotDuration: bigint;
137
180
 
138
- private blobClient: BlobClientInterface;
181
+ /** Date provider for wall-clock time. */
182
+ private readonly dateProvider: DateProvider;
139
183
 
140
- /** Address to use for simulations in fisherman mode (actual proposer's address) */
141
- private proposerAddressForSimulation?: EthAddress;
184
+ private blobClient: BlobClientInterface;
142
185
 
143
186
  /** Optional callback to obtain a replacement publisher when the current one fails to send. */
144
187
  private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
@@ -149,17 +192,13 @@ export class SequencerPublisher {
149
192
  /** Fee asset price oracle for computing price modifiers from Uniswap V4 */
150
193
  private feeAssetPriceOracle: FeeAssetPriceOracle;
151
194
 
152
- // A CALL to a cold address is 2700 gas
153
- public static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
154
-
155
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
156
- public static VOTE_GAS_GUESS: bigint = 800_000n;
195
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */
196
+ private readonly interruptibleSleep = new InterruptibleSleep();
157
197
 
158
198
  public l1TxUtils: L1TxUtils;
159
199
  public rollupContract: RollupContract;
160
200
  public govProposerContract: GovernanceProposerContract;
161
- public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
162
- public slashFactoryContract: SlashFactoryContract;
201
+ public slashingProposerContract: SlashingProposerContract | undefined;
163
202
 
164
203
  public readonly tracer: Tracer;
165
204
 
@@ -173,9 +212,8 @@ export class SequencerPublisher {
173
212
  blobClient: BlobClientInterface;
174
213
  l1TxUtils: L1TxUtils;
175
214
  rollupContract: RollupContract;
176
- slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
215
+ slashingProposerContract: SlashingProposerContract | undefined;
177
216
  governanceProposerContract: GovernanceProposerContract;
178
- slashFactoryContract: SlashFactoryContract;
179
217
  epochCache: EpochCache;
180
218
  dateProvider: DateProvider;
181
219
  metrics: SequencerPublisherMetrics;
@@ -187,10 +225,12 @@ export class SequencerPublisher {
187
225
  this.log = deps.log ?? createLogger('sequencer:publisher');
188
226
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
189
227
  this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
228
+ this.dateProvider = deps.dateProvider;
190
229
  this.epochCache = deps.epochCache;
191
230
  this.lastActions = deps.lastActions;
192
231
 
193
232
  this.blobClient = deps.blobClient;
233
+ this.dateProvider = deps.dateProvider;
194
234
 
195
235
  const telemetry = deps.telemetry ?? getTelemetryClient();
196
236
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
@@ -208,14 +248,12 @@ export class SequencerPublisher {
208
248
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
209
249
  this.slashingProposerContract = newSlashingProposer;
210
250
  });
211
- this.slashFactoryContract = deps.slashFactoryContract;
212
-
213
251
  // Initialize L1 fee analyzer for fisherman mode
214
252
  if (config.fishermanMode) {
215
253
  this.l1FeeAnalyzer = new L1FeeAnalyzer(
216
254
  this.l1TxUtils.client,
217
255
  deps.dateProvider,
218
- createLogger('sequencer:publisher:fee-analyzer'),
256
+ this.log.createChild('fee-analyzer'),
219
257
  );
220
258
  }
221
259
 
@@ -223,11 +261,18 @@ export class SequencerPublisher {
223
261
  this.feeAssetPriceOracle = new FeeAssetPriceOracle(
224
262
  this.l1TxUtils.client,
225
263
  this.rollupContract,
226
- createLogger('sequencer:publisher:price-oracle'),
264
+ this.log.createChild('price-oracle'),
227
265
  );
228
266
 
229
267
  // Initialize failed L1 tx store (optional, for test networks)
230
268
  this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
269
+
270
+ this.bundleSimulator = new SequencerBundleSimulator({
271
+ getL1TxUtils: () => this.l1TxUtils,
272
+ rollupContract: this.rollupContract,
273
+ epochCache: this.epochCache,
274
+ log: this.log.createChild('bundle-simulator'),
275
+ });
231
276
  }
232
277
 
233
278
  /**
@@ -258,10 +303,14 @@ export class SequencerPublisher {
258
303
 
259
304
  /**
260
305
  * Gets the fee asset price modifier from the oracle.
261
- * Returns 0n if the oracle query fails.
306
+ *
307
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
308
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
309
+ * modifier matches the parent L1 will use when applying it.
310
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
262
311
  */
263
- public getFeeAssetPriceModifier(): Promise<bigint> {
264
- return this.feeAssetPriceOracle.computePriceModifier();
312
+ public getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12?: bigint): Promise<bigint> {
313
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
265
314
  }
266
315
 
267
316
  public getSenderAddress() {
@@ -275,14 +324,6 @@ export class SequencerPublisher {
275
324
  return this.l1FeeAnalyzer;
276
325
  }
277
326
 
278
- /**
279
- * Sets the proposer address to use for simulations in fisherman mode.
280
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
281
- */
282
- public setProposerAddressForSimulation(proposerAddress: EthAddress | undefined) {
283
- this.proposerAddressForSimulation = proposerAddress;
284
- }
285
-
286
327
  public addRequest(request: RequestWithExpiry) {
287
328
  this.requests.push(request);
288
329
  }
@@ -360,22 +401,26 @@ export class SequencerPublisher {
360
401
 
361
402
  /**
362
403
  * Sends all requests that are still valid.
404
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
405
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
406
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
407
+ * AutomineSequencer, which publishes synchronously within the current slot.
363
408
  * @returns one of:
364
409
  * - A receipt and stats if the tx succeeded
365
410
  * - a receipt and errorMsg if it failed on L1
366
411
  * - undefined if no valid requests are found OR the tx failed to send.
367
412
  */
368
413
  @trackSpan('SequencerPublisher.sendRequests')
369
- public async sendRequests() {
414
+ public async sendRequests(targetSlot?: SlotNumber): Promise<SendRequestsResult | undefined> {
370
415
  const requestsToProcess = [...this.requests];
371
416
  this.requests = [];
417
+
372
418
  if (this.interrupted || requestsToProcess.length === 0) {
373
419
  return undefined;
374
420
  }
375
- const currentL2Slot = this.getCurrentL2Slot();
421
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
376
422
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
377
423
  const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
378
- const validActions = validRequests.map(x => x.action);
379
424
  const expiredActions = requestsToProcess
380
425
  .filter(request => request.lastValidL2Slot < currentL2Slot)
381
426
  .map(x => x.action);
@@ -398,70 +443,58 @@ export class SequencerPublisher {
398
443
  return undefined;
399
444
  }
400
445
 
401
- // @note - we can only have one blob config per bundle
402
- // find requests with gas and blob configs
403
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
446
+ // Collect earliest txTimeoutAt across all requests.
404
447
  const gasConfigs = validRequests.filter(request => request.gasConfig).map(request => request.gasConfig);
405
- const blobConfigs = validRequests.filter(request => request.blobConfig).map(request => request.blobConfig);
406
-
407
- if (blobConfigs.length > 1) {
408
- throw new Error('Multiple blob configs found');
409
- }
410
-
411
- const blobConfig = blobConfigs[0];
412
-
413
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
414
- const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
415
- let gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
416
- // Cap at L1 block gas limit so the node accepts the tx ("gas limit too high" otherwise).
417
- const maxGas = MAX_L1_TX_LIMIT;
418
- if (gasLimit !== undefined && gasLimit > maxGas) {
419
- this.log.debug('Capping bundled tx gas limit to L1 max', {
420
- requested: gasLimit,
421
- capped: maxGas,
422
- });
423
- gasLimit = maxGas;
424
- }
425
448
  const txTimeoutAts = gasConfigs.map(g => g?.txTimeoutAt).filter((g): g is Date => g !== undefined);
426
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined; // earliest
427
- const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
449
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined;
428
450
 
429
451
  // Sort the requests so that proposals always go first
430
452
  // This ensures the committee gets precomputed correctly
431
453
  validRequests.sort((a, b) => compareActions(a.action, b.action));
432
454
 
433
455
  try {
434
- // Capture context for failed tx backup before sending
435
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
436
- const multicallData = encodeFunctionData({
437
- abi: multicall3Abi,
438
- functionName: 'aggregate3',
439
- args: [
440
- validRequests.map(r => ({
441
- target: r.request.to!,
442
- callData: r.request.data!,
443
- allowFailure: true,
444
- })),
445
- ],
446
- });
447
- const blobDataHex = blobConfig?.blobs?.map(b => toHex(b)) as Hex[] | undefined;
456
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
457
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
458
+
459
+ if (bundleResult.kind === 'aborted') {
460
+ this.logDroppedInSim(bundleResult.droppedRequests);
461
+ void this.backupDroppedInSim(bundleResult.droppedRequests);
462
+ return undefined;
463
+ }
448
464
 
449
- const txContext = { multicallData, blobData: blobDataHex, l1BlockNumber };
465
+ const { requests, droppedRequests, gasLimit } =
466
+ bundleResult.kind === 'fallback'
467
+ ? {
468
+ requests: bundleResult.requests,
469
+ droppedRequests: bundleResult.droppedRequests,
470
+ gasLimit: MAX_L1_TX_LIMIT,
471
+ }
472
+ : bundleResult;
473
+
474
+ this.logDroppedInSim(droppedRequests);
475
+
476
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
477
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
478
+ const [blobConfig] = requests.filter(r => r.blobConfig).map(r => r.blobConfig);
479
+ const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
450
480
 
451
481
  this.log.debug('Forwarding transactions', {
452
- validRequests: validRequests.map(request => request.action),
482
+ requests: requests.map(request => request.action),
453
483
  txConfig,
454
484
  });
455
- const result = await this.forwardWithPublisherRotation(validRequests, txConfig, blobConfig);
485
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
456
486
  if (result === undefined) {
457
487
  return undefined;
458
488
  }
459
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(
460
- validRequests,
489
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
490
+ const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action)];
491
+ return {
461
492
  result,
462
- txContext,
463
- );
464
- return { result, expiredActions, sentActions: validActions, successfulActions, failedActions };
493
+ expiredActions,
494
+ sentActions: requests.map(x => x.action),
495
+ successfulActions,
496
+ failedActions: allFailedActions,
497
+ };
465
498
  } catch (err) {
466
499
  const viemError = formatViemError(err);
467
500
  this.log.error(`Failed to publish bundled transactions`, viemError);
@@ -478,6 +511,40 @@ export class SequencerPublisher {
478
511
  }
479
512
  }
480
513
 
514
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */
515
+ private logDroppedInSim(dropped: DroppedRequest[]): void {
516
+ for (const drop of dropped) {
517
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
518
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
519
+ action: drop.request.action,
520
+ revertReason: revertReasonDecoded ?? drop.returnData,
521
+ revertReasonDecoded,
522
+ returnData: drop.returnData,
523
+ });
524
+ }
525
+ }
526
+
527
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */
528
+ private async backupDroppedInSim(dropped: DroppedRequest[]): Promise<void> {
529
+ if (dropped.length === 0) {
530
+ return;
531
+ }
532
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
533
+ for (const { request: req } of dropped) {
534
+ this.backupFailedTx({
535
+ id: keccak256(req.request.data!),
536
+ failureType: 'simulation',
537
+ request: { to: req.request.to! as Hex, data: req.request.data! },
538
+ l1BlockNumber: l1BlockNumber.toString(),
539
+ error: { message: 'Bundle entry dropped: action reverted in sim' },
540
+ context: {
541
+ actions: [req.action],
542
+ sender: this.getSenderAddress().toString(),
543
+ },
544
+ });
545
+ }
546
+ }
547
+
481
548
  /**
482
549
  * Forwards transactions via Multicall3, rotating to the next available publisher if a send
483
550
  * failure occurs (i.e. the tx never reached the chain).
@@ -488,19 +555,30 @@ export class SequencerPublisher {
488
555
  txConfig: RequestWithExpiry['gasConfig'],
489
556
  blobConfig: L1BlobInputs | undefined,
490
557
  ) {
558
+ if (!txConfig?.gasLimit) {
559
+ throw new Error('gasLimit is required for bundled transactions');
560
+ }
561
+ const txConfigWithGasLimit = txConfig as L1TxConfig & { gasLimit: bigint };
562
+
491
563
  const triedAddresses: EthAddress[] = [];
492
564
  let currentPublisher = this.l1TxUtils;
493
565
 
494
566
  while (true) {
567
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
568
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
569
+ triedAddresses: triedAddresses.map(a => a.toString()),
570
+ });
571
+ return undefined;
572
+ }
495
573
  triedAddresses.push(currentPublisher.getSenderAddress());
574
+
496
575
  try {
497
576
  const result = await Multicall3.forward(
498
577
  validRequests.map(r => r.request),
499
578
  currentPublisher,
500
- txConfig,
579
+ txConfigWithGasLimit,
501
580
  blobConfig,
502
- this.rollupContract.address,
503
- this.log,
581
+ { gasLimitRequired: true },
504
582
  );
505
583
  this.l1TxUtils = currentPublisher;
506
584
  return result;
@@ -508,6 +586,12 @@ export class SequencerPublisher {
508
586
  if (err instanceof TimeoutError) {
509
587
  throw err;
510
588
  }
589
+ if (err instanceof MulticallForwarderRevertedError) {
590
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
591
+ transactionHash: err.receipt.transactionHash,
592
+ });
593
+ return undefined;
594
+ }
511
595
  const viemError = formatViemError(err);
512
596
  if (!this.getNextPublisher) {
513
597
  this.log.error('Failed to publish bundled transactions', viemError);
@@ -519,7 +603,11 @@ export class SequencerPublisher {
519
603
  );
520
604
  const nextPublisher = await this.getNextPublisher([...triedAddresses]);
521
605
  if (!nextPublisher) {
522
- this.log.error('All available publishers exhausted, failed to publish bundled transactions');
606
+ this.log.error(
607
+ `All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`,
608
+ viemError,
609
+ { triedAddresses: triedAddresses.map(a => a.toString()) },
610
+ );
523
611
  return undefined;
524
612
  }
525
613
  currentPublisher = nextPublisher;
@@ -527,74 +615,63 @@ export class SequencerPublisher {
527
615
  }
528
616
  }
529
617
 
618
+ /*
619
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
620
+ * Sleeps until one L1 slot before the L2 slot boundary so the tx has a chance of being
621
+ * picked up by the first L1 block of the L2 slot.
622
+ * NB: there is a known correctness risk — being included in the L1 block right before the
623
+ * L2 slot starts would revert propose with HeaderLib__InvalidSlotNumber.
624
+ * Uses InterruptibleSleep so it can be cancelled via interrupt().
625
+ */
626
+ public async sendRequestsAt(targetSlot: SlotNumber): Promise<SendRequestsResult | undefined> {
627
+ const l1Constants = this.epochCache.getL1Constants();
628
+ // Start of the target L2 slot, in ms (getTimestampForSlot returns seconds).
629
+ const startOfTargetSlotMs = Number(getTimestampForSlot(targetSlot, l1Constants)) * 1000;
630
+ // Aim to be in the mempool one L1 slot before the L2 slot starts, so we have a chance of
631
+ // being picked up by the first L1 block of the L2 slot.
632
+ const submitAfterMs = startOfTargetSlotMs - Number(this.ethereumSlotDuration) * 1000;
633
+ if (this.interrupted) {
634
+ return undefined;
635
+ }
636
+ const sleepMs = submitAfterMs - this.dateProvider.now();
637
+ if (sleepMs > 0) {
638
+ this.log.debug(`Sleeping ${sleepMs}ms before sending requests`, {
639
+ targetSlot,
640
+ submitAfterMs,
641
+ });
642
+ await this.interruptibleSleep.sleep(sleepMs);
643
+ }
644
+ if (this.interrupted) {
645
+ return undefined;
646
+ }
647
+ return this.sendRequests(targetSlot);
648
+ }
649
+
530
650
  private callbackBundledTransactions(
531
651
  requests: RequestWithExpiry[],
532
- result: { receipt: TransactionReceipt; errorMsg?: string } | FormattedViemError | undefined,
533
- txContext: { multicallData: Hex; blobData?: Hex[]; l1BlockNumber: bigint },
652
+ result: { receipt: TransactionReceipt; multicallData: Hex },
534
653
  ) {
535
654
  const actionsListStr = requests.map(r => r.action).join(', ');
536
- if (result instanceof FormattedViemError) {
537
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
538
- this.backupFailedTx({
539
- id: keccak256(txContext.multicallData),
540
- failureType: 'send-error',
541
- request: { to: MULTI_CALL_3_ADDRESS, data: txContext.multicallData },
542
- blobData: txContext.blobData,
543
- l1BlockNumber: txContext.l1BlockNumber.toString(),
544
- error: { message: result.message, name: result.name },
545
- context: {
546
- actions: requests.map(r => r.action),
547
- requests: requests.map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
548
- sender: this.getSenderAddress().toString(),
549
- },
550
- });
551
- return { failedActions: requests.map(r => r.action) };
552
- } else {
553
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
554
- result,
555
- requests: requests.map(r => ({
556
- ...r,
557
- // Avoid logging large blob data
558
- blobConfig: r.blobConfig
559
- ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
560
- : undefined,
561
- })),
562
- });
563
- const successfulActions: Action[] = [];
564
- const failedActions: Action[] = [];
565
- for (const request of requests) {
566
- if (request.checkSuccess(request.request, result)) {
567
- successfulActions.push(request.action);
568
- } else {
569
- failedActions.push(request.action);
570
- }
571
- }
572
- // Single backup for the whole reverted tx
573
- if (failedActions.length > 0 && result?.receipt?.status === 'reverted') {
574
- this.backupFailedTx({
575
- id: result.receipt.transactionHash,
576
- failureType: 'revert',
577
- request: { to: MULTI_CALL_3_ADDRESS, data: txContext.multicallData },
578
- blobData: txContext.blobData,
579
- l1BlockNumber: result.receipt.blockNumber.toString(),
580
- receipt: {
581
- transactionHash: result.receipt.transactionHash,
582
- blockNumber: result.receipt.blockNumber.toString(),
583
- gasUsed: (result.receipt.gasUsed ?? 0n).toString(),
584
- status: 'reverted',
585
- },
586
- error: { message: result.errorMsg ?? 'Transaction reverted' },
587
- context: {
588
- actions: failedActions,
589
- requests: requests
590
- .filter(r => failedActions.includes(r.action))
591
- .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
592
- sender: this.getSenderAddress().toString(),
593
- },
594
- });
655
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
656
+ result,
657
+ requests: requests.map(r => ({
658
+ ...r,
659
+ // Avoid logging large blob data
660
+ blobConfig: r.blobConfig
661
+ ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
662
+ : undefined,
663
+ })),
664
+ });
665
+ const successfulActions: Action[] = [];
666
+ const failedActions: Action[] = [];
667
+ for (const request of requests) {
668
+ if (request.checkSuccess(request.request, result)) {
669
+ successfulActions.push(request.action);
670
+ } else {
671
+ failedActions.push(request.action);
595
672
  }
596
- return { successfulActions, failedActions };
597
673
  }
674
+ return { successfulActions, failedActions };
598
675
  }
599
676
 
600
677
  /**
@@ -602,24 +679,27 @@ export class SequencerPublisher {
602
679
  * @param tipArchive - The archive to check
603
680
  * @returns The slot and block number if it is possible to propose, undefined otherwise
604
681
  */
605
- public canProposeAt(
606
- tipArchive: Fr,
607
- msgSender: EthAddress,
608
- opts: { forcePendingCheckpointNumber?: CheckpointNumber; pipelined?: boolean } = {},
609
- ) {
682
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
610
683
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
611
- const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
684
+ // These errors are expected when we cannot actually propose right now — usually because our
685
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
686
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
687
+ // skip the proposal; we do NOT treat these as bugs.
688
+ const expectedErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
612
689
 
613
- const pipelined = opts.pipelined ?? this.epochCache.isProposerPipeliningEnabled();
614
- const slotOffset = pipelined ? this.aztecSlotDuration : 0n;
690
+ const slotOffset = this.aztecSlotDuration;
691
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
615
692
 
616
693
  return this.rollupContract
617
- .canProposeAt(tipArchive.toBuffer(), msgSender.toString(), this.ethereumSlotDuration, slotOffset, {
618
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
619
- })
694
+ .canProposeAt(
695
+ tipArchive.toBuffer(),
696
+ msgSender.toString(),
697
+ nextL1SlotTs,
698
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
699
+ )
620
700
  .catch(err => {
621
- if (err instanceof FormattedViemError && ignoredErrors.find(e => err.message.includes(e))) {
622
- this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find(e => err.message.includes(e))}`, {
701
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
702
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
623
703
  error: err.message,
624
704
  });
625
705
  } else {
@@ -638,13 +718,13 @@ export class SequencerPublisher {
638
718
  @trackSpan('SequencerPublisher.validateBlockHeader')
639
719
  public async validateBlockHeader(
640
720
  header: CheckpointHeader,
641
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
721
+ simulationOverridesPlan?: SimulationOverridesPlan,
642
722
  ): Promise<void> {
643
723
  const flags = { ignoreDA: true, ignoreSignatures: true };
644
724
 
645
725
  const args = [
646
726
  header.toViem(),
647
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
727
+ CommitteeAttestationsAndSigners.packAttestations([]),
648
728
  [], // no signers
649
729
  Signature.empty().toViemSignature(),
650
730
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -652,10 +732,9 @@ export class SequencerPublisher {
652
732
  flags,
653
733
  ] as const;
654
734
 
655
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
656
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
657
- opts?.forcePendingCheckpointNumber,
658
- );
735
+ const l1Constants = this.epochCache.getL1Constants();
736
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
737
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
659
738
  let balance = 0n;
660
739
  if (this.config.fishermanMode) {
661
740
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -675,7 +754,7 @@ export class SequencerPublisher {
675
754
  data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
676
755
  from: MULTI_CALL_3_ADDRESS,
677
756
  },
678
- { time: ts + 1n },
757
+ { time: ts },
679
758
  stateOverrides,
680
759
  );
681
760
  this.log.debug(`Simulated validateHeader`);
@@ -728,6 +807,7 @@ export class SequencerPublisher {
728
807
  gasUsed,
729
808
  checkpointNumber,
730
809
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
810
+ lastArchive: validationResult.checkpoint.lastArchive,
731
811
  reason,
732
812
  };
733
813
  } catch (err) {
@@ -740,8 +820,8 @@ export class SequencerPublisher {
740
820
  `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
741
821
  { ...logData, request, error: viemError.message },
742
822
  );
743
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
744
- if (latestPendingCheckpointNumber < checkpointNumber) {
823
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
824
+ if (latestProposedCheckpointNumber < checkpointNumber) {
745
825
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
746
826
  return undefined;
747
827
  } else {
@@ -786,9 +866,7 @@ export class SequencerPublisher {
786
866
  const logData = { ...checkpoint, reason };
787
867
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
788
868
 
789
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
790
- validationResult.attestations,
791
- ).getPackedAttestations();
869
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
792
870
 
793
871
  if (reason === 'invalid-attestation') {
794
872
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -809,45 +887,11 @@ export class SequencerPublisher {
809
887
  }
810
888
  }
811
889
 
812
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */
813
- @trackSpan('SequencerPublisher.validateCheckpointForSubmission')
814
- public async validateCheckpointForSubmission(
815
- checkpoint: Checkpoint,
816
- attestationsAndSigners: CommitteeAttestationsAndSigners,
817
- attestationsAndSignersSignature: Signature,
818
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
819
- ): Promise<bigint> {
820
- // Anchor the simulation timestamp to the checkpoint's own slot start time
821
- // rather than the current L1 block timestamp, which may overshoot into the next slot if the build ran late.
822
- const ts = checkpoint.header.timestamp;
823
- const blobFields = checkpoint.toBlobFields();
824
- const blobs = await getBlobsPerL1Block(blobFields);
825
- const blobInput = getPrefixedEthBlobCommitments(blobs);
826
-
827
- const args = [
828
- {
829
- header: checkpoint.header.toViem(),
830
- archive: toHex(checkpoint.archive.root.toBuffer()),
831
- oracleInput: {
832
- feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
833
- },
834
- },
835
- attestationsAndSigners.getPackedAttestations(),
836
- attestationsAndSigners.getSigners().map(signer => signer.toString()),
837
- attestationsAndSignersSignature.toViemSignature(),
838
- blobInput,
839
- ] as const;
840
-
841
- await this.simulateProposeTx(args, ts, options);
842
- return ts;
843
- }
844
-
845
890
  private async enqueueCastSignalHelper(
846
891
  slotNumber: SlotNumber,
847
- timestamp: bigint,
848
892
  signalType: GovernanceSignalAction,
849
893
  payload: EthAddress,
850
- base: IEmpireBase,
894
+ base: GovernanceProposerContract,
851
895
  signerAddress: EthAddress,
852
896
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
853
897
  ): Promise<boolean> {
@@ -873,34 +917,28 @@ export class SequencerPublisher {
873
917
  return false;
874
918
  }
875
919
 
876
- if (await this.isPayloadEmpty(payload)) {
920
+ if (await base.isPayloadEmpty(payload)) {
877
921
  this.log.warn(`Skipping vote cast for payload with empty code`);
878
922
  return false;
879
923
  }
880
924
 
881
- // Check if payload was already submitted to governance
882
- const cacheKey = payload.toString();
883
- if (!this.payloadProposedCache.has(cacheKey)) {
884
- try {
885
- const l1StartBlock = await this.rollupContract.getL1StartBlock();
886
- const proposed = await retry(
887
- () => base.hasPayloadBeenProposed(payload.toString(), l1StartBlock),
888
- 'Check if payload was proposed',
889
- makeBackoff([0, 1, 2]),
890
- this.log,
891
- true,
892
- );
893
- if (proposed) {
894
- this.payloadProposedCache.add(cacheKey);
895
- }
896
- } catch (err) {
897
- this.log.warn(`Failed to check if payload ${payload} was proposed after retries, skipping signal`, err);
898
- return false;
899
- }
925
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
926
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
927
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
928
+ // the same payload in a future round.
929
+ let proposed = false;
930
+ try {
931
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
932
+ } catch (err) {
933
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
934
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
935
+ // participation entirely; failing open at worst produces a duplicate signal that the
936
+ // contract will simply count alongside others in the round.
937
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
900
938
  }
901
939
 
902
- if (this.payloadProposedCache.has(cacheKey)) {
903
- this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
940
+ if (proposed) {
941
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
904
942
  return false;
905
943
  }
906
944
 
@@ -922,41 +960,19 @@ export class SequencerPublisher {
922
960
  lastValidL2Slot: slotNumber,
923
961
  });
924
962
 
925
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
926
-
927
- try {
928
- await this.l1TxUtils.simulate(request, { time: timestamp }, [], mergeAbis([request.abi ?? [], ErrorsAbi]));
929
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, { request });
930
- } catch (err) {
931
- const viemError = formatViemError(err);
932
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, viemError);
933
- this.backupFailedTx({
934
- id: keccak256(request.data!),
935
- failureType: 'simulation',
936
- request: { to: request.to!, data: request.data!, value: request.value?.toString() },
937
- l1BlockNumber: l1BlockNumber.toString(),
938
- error: { message: viemError.message, name: viemError.name },
939
- context: {
940
- actions: [action],
941
- slot: slotNumber,
942
- sender: this.getSenderAddress().toString(),
943
- },
944
- });
945
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
946
- }
947
-
948
963
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
949
964
  this.addRequest({
950
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
951
965
  action,
952
966
  request,
953
967
  lastValidL2Slot: slotNumber,
954
968
  checkSuccess: (_request, result) => {
955
969
  const success =
956
970
  result &&
957
- result.receipt &&
958
- result.receipt.status === 'success' &&
959
- tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
971
+ extractEventSuccess(result.receipt, {
972
+ address: base.address.toString(),
973
+ abi: EmpireBaseAbi,
974
+ eventName: 'SignalCast',
975
+ });
960
976
 
961
977
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
962
978
  if (!success) {
@@ -978,33 +994,19 @@ export class SequencerPublisher {
978
994
  return true;
979
995
  }
980
996
 
981
- private async isPayloadEmpty(payload: EthAddress): Promise<boolean> {
982
- const key = payload.toString();
983
- const cached = this.isPayloadEmptyCache.get(key);
984
- if (cached) {
985
- return cached;
986
- }
987
- const isEmpty = !(await this.l1TxUtils.getCode(payload));
988
- this.isPayloadEmptyCache.set(key, isEmpty);
989
- return isEmpty;
990
- }
991
-
992
997
  /**
993
998
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
994
999
  * @param slotNumber - The slot number to cast a signal for.
995
- * @param timestamp - The timestamp of the slot to cast a signal for.
996
1000
  * @returns True if the signal was successfully enqueued, false otherwise.
997
1001
  */
998
1002
  public enqueueGovernanceCastSignal(
999
1003
  governancePayload: EthAddress,
1000
1004
  slotNumber: SlotNumber,
1001
- timestamp: bigint,
1002
1005
  signerAddress: EthAddress,
1003
1006
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
1004
1007
  ): Promise<boolean> {
1005
1008
  return this.enqueueCastSignalHelper(
1006
1009
  slotNumber,
1007
- timestamp,
1008
1010
  'governance-signal',
1009
1011
  governancePayload,
1010
1012
  this.govProposerContract,
@@ -1017,7 +1019,6 @@ export class SequencerPublisher {
1017
1019
  public async enqueueSlashingActions(
1018
1020
  actions: ProposerSlashAction[],
1019
1021
  slotNumber: SlotNumber,
1020
- timestamp: bigint,
1021
1022
  signerAddress: EthAddress,
1022
1023
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
1023
1024
  ): Promise<boolean> {
@@ -1028,58 +1029,6 @@ export class SequencerPublisher {
1028
1029
 
1029
1030
  for (const action of actions) {
1030
1031
  switch (action.type) {
1031
- case 'vote-empire-payload': {
1032
- if (this.slashingProposerContract?.type !== 'empire') {
1033
- this.log.error('Cannot vote for empire payload on non-empire slashing contract');
1034
- break;
1035
- }
1036
- this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
1037
- signerAddress,
1038
- });
1039
- await this.enqueueCastSignalHelper(
1040
- slotNumber,
1041
- timestamp,
1042
- 'empire-slashing-signal',
1043
- action.payload,
1044
- this.slashingProposerContract,
1045
- signerAddress,
1046
- signer,
1047
- );
1048
- break;
1049
- }
1050
-
1051
- case 'create-empire-payload': {
1052
- this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, { slotNumber, signerAddress });
1053
- const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
1054
- await this.simulateAndEnqueueRequest(
1055
- 'create-empire-payload',
1056
- request,
1057
- (receipt: TransactionReceipt) =>
1058
- !!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs),
1059
- slotNumber,
1060
- timestamp,
1061
- );
1062
- break;
1063
- }
1064
-
1065
- case 'execute-empire-payload': {
1066
- this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, { slotNumber, signerAddress });
1067
- if (this.slashingProposerContract?.type !== 'empire') {
1068
- this.log.error('Cannot execute slashing payload on non-empire slashing contract');
1069
- return false;
1070
- }
1071
- const empireSlashingProposer = this.slashingProposerContract as EmpireSlashingProposerContract;
1072
- const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
1073
- await this.simulateAndEnqueueRequest(
1074
- 'execute-empire-payload',
1075
- request,
1076
- (receipt: TransactionReceipt) => !!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs),
1077
- slotNumber,
1078
- timestamp,
1079
- );
1080
- break;
1081
- }
1082
-
1083
1032
  case 'vote-offenses': {
1084
1033
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
1085
1034
  slotNumber,
@@ -1087,19 +1036,21 @@ export class SequencerPublisher {
1087
1036
  votesCount: action.votes.length,
1088
1037
  signerAddress,
1089
1038
  });
1090
- if (this.slashingProposerContract?.type !== 'tally') {
1091
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1039
+ if (!this.slashingProposerContract) {
1040
+ this.log.error('No slashing proposer contract available');
1092
1041
  return false;
1093
1042
  }
1094
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
1095
1043
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1096
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
1097
- await this.simulateAndEnqueueRequest(
1044
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1045
+ this.enqueueRequest(
1098
1046
  'vote-offenses',
1099
1047
  request,
1100
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1048
+ {
1049
+ address: this.slashingProposerContract.address.toString(),
1050
+ abi: SlashingProposerAbi,
1051
+ eventName: 'VoteCast',
1052
+ },
1101
1053
  slotNumber,
1102
- timestamp,
1103
1054
  );
1104
1055
  break;
1105
1056
  }
@@ -1110,18 +1061,23 @@ export class SequencerPublisher {
1110
1061
  round: action.round,
1111
1062
  signerAddress,
1112
1063
  });
1113
- if (this.slashingProposerContract?.type !== 'tally') {
1114
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1064
+ if (!this.slashingProposerContract) {
1065
+ this.log.error('No slashing proposer contract available');
1115
1066
  return false;
1116
1067
  }
1117
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
1118
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
1119
- await this.simulateAndEnqueueRequest(
1068
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1069
+ action.round,
1070
+ action.committees,
1071
+ );
1072
+ this.enqueueRequest(
1120
1073
  'execute-slash',
1121
- request,
1122
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1074
+ executeRequest,
1075
+ {
1076
+ address: this.slashingProposerContract.address.toString(),
1077
+ abi: SlashingProposerAbi,
1078
+ eventName: 'RoundExecuted',
1079
+ },
1123
1080
  slotNumber,
1124
- timestamp,
1125
1081
  );
1126
1082
  break;
1127
1083
  }
@@ -1136,12 +1092,12 @@ export class SequencerPublisher {
1136
1092
  return true;
1137
1093
  }
1138
1094
 
1139
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1095
+ /** Enqueues a proposal for a checkpoint on L1 */
1140
1096
  public async enqueueProposeCheckpoint(
1141
1097
  checkpoint: Checkpoint,
1142
1098
  attestationsAndSigners: CommitteeAttestationsAndSigners,
1143
1099
  attestationsAndSignersSignature: Signature,
1144
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1100
+ opts: EnqueueProposeCheckpointOpts = {},
1145
1101
  ): Promise<void> {
1146
1102
  const checkpointHeader = checkpoint.header;
1147
1103
 
@@ -1157,31 +1113,11 @@ export class SequencerPublisher {
1157
1113
  feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
1158
1114
  };
1159
1115
 
1160
- let ts: bigint;
1161
-
1162
- try {
1163
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
1164
- // This means that we can avoid the simulation issues in later checks.
1165
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
1166
- // make time consistency checks break.
1167
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
1168
- ts = await this.validateCheckpointForSubmission(
1169
- checkpoint,
1170
- attestationsAndSigners,
1171
- attestationsAndSignersSignature,
1172
- opts,
1173
- );
1174
- } catch (err: any) {
1175
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
1176
- ...checkpoint.getStats(),
1177
- slotNumber: checkpoint.header.slotNumber,
1178
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
1179
- });
1180
- throw err;
1181
- }
1182
-
1183
- this.log.verbose(`Enqueuing checkpoint propose transaction`, { ...checkpoint.toCheckpointInfo(), ...opts });
1184
- await this.addProposeTx(checkpoint, proposeTxArgs, opts, ts);
1116
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1117
+ ...checkpoint.toCheckpointInfo(),
1118
+ txTimeoutAt: opts.txTimeoutAt,
1119
+ });
1120
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
1185
1121
  }
1186
1122
 
1187
1123
  public enqueueInvalidateCheckpoint(
@@ -1192,23 +1128,22 @@ export class SequencerPublisher {
1192
1128
  return;
1193
1129
  }
1194
1130
 
1195
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1196
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(request.gasUsed) * 64) / 63)));
1197
-
1198
1131
  const { gasUsed, checkpointNumber } = request;
1199
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1132
+ const logData = { gasUsed, checkpointNumber, opts };
1200
1133
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1201
1134
  this.addRequest({
1202
1135
  action: `invalidate-by-${request.reason}`,
1203
1136
  request: request.request,
1204
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1137
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
1205
1138
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1206
1139
  checkSuccess: (_req, result) => {
1207
1140
  const success =
1208
1141
  result &&
1209
- result.receipt &&
1210
- result.receipt.status === 'success' &&
1211
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1142
+ extractEventSuccess(result.receipt, {
1143
+ address: this.rollupContract.address,
1144
+ abi: RollupAbi,
1145
+ eventName: 'CheckpointInvalidated',
1146
+ });
1212
1147
  if (!success) {
1213
1148
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
1214
1149
  } else {
@@ -1219,72 +1154,36 @@ export class SequencerPublisher {
1219
1154
  });
1220
1155
  }
1221
1156
 
1222
- private async simulateAndEnqueueRequest(
1157
+ /**
1158
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1159
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1160
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1161
+ */
1162
+ private enqueueRequest(
1223
1163
  action: Action,
1224
1164
  request: L1TxRequest,
1225
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1165
+ eventOpts: { address: string; abi: Abi; eventName: string },
1226
1166
  slotNumber: SlotNumber,
1227
- timestamp: bigint,
1228
- ) {
1229
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1167
+ ): boolean {
1230
1168
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1231
1169
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1232
1170
  return false;
1233
1171
  }
1234
-
1235
1172
  const cachedLastActionSlot = this.lastActions[action];
1236
1173
  this.lastActions[action] = slotNumber;
1237
1174
 
1238
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1239
-
1240
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1241
-
1242
- let gasUsed: bigint;
1243
- const simulateAbi = mergeAbis([request.abi ?? [], ErrorsAbi]);
1244
- try {
1245
- ({ gasUsed } = await this.l1TxUtils.simulate(request, { time: timestamp }, [], simulateAbi)); // TODO(palla/slash): Check the timestamp logic
1246
- this.log.verbose(`Simulation for ${action} succeeded`, { ...logData, request, gasUsed });
1247
- } catch (err) {
1248
- const viemError = formatViemError(err, simulateAbi);
1249
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1250
-
1251
- this.backupFailedTx({
1252
- id: keccak256(request.data!),
1253
- failureType: 'simulation',
1254
- request: { to: request.to!, data: request.data!, value: request.value?.toString() },
1255
- l1BlockNumber: l1BlockNumber.toString(),
1256
- error: { message: viemError.message, name: viemError.name },
1257
- context: {
1258
- actions: [action],
1259
- slot: slotNumber,
1260
- sender: this.getSenderAddress().toString(),
1261
- },
1262
- });
1263
-
1264
- return false;
1265
- }
1266
-
1267
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1268
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(gasUsed) * 64) / 63)));
1269
- logData.gasLimit = gasLimit;
1270
-
1271
- // Store the ABI used for simulation on the request so Multicall3.forward can decode errors
1272
- // when the tx is sent and a revert is diagnosed via simulation.
1273
- const requestWithAbi = { ...request, abi: simulateAbi };
1274
-
1275
- this.log.debug(`Enqueuing ${action}`, logData);
1175
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1276
1176
  this.addRequest({
1277
1177
  action,
1278
- request: requestWithAbi,
1279
- gasConfig: { gasLimit },
1178
+ request,
1280
1179
  lastValidL2Slot: slotNumber,
1281
- checkSuccess: (_req, result) => {
1282
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1180
+ checkSuccess: (_request, result) => {
1181
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1283
1182
  if (!success) {
1284
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1183
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1285
1184
  this.lastActions[action] = cachedLastActionSlot;
1286
1185
  } else {
1287
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1186
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1288
1187
  }
1289
1188
  return !!success;
1290
1189
  },
@@ -1300,6 +1199,7 @@ export class SequencerPublisher {
1300
1199
  */
1301
1200
  public interrupt() {
1302
1201
  this.interrupted = true;
1202
+ this.interruptibleSleep.interrupt();
1303
1203
  this.l1TxUtils.interrupt();
1304
1204
  }
1305
1205
 
@@ -1309,11 +1209,7 @@ export class SequencerPublisher {
1309
1209
  this.l1TxUtils.restart();
1310
1210
  }
1311
1211
 
1312
- private async prepareProposeTx(
1313
- encodedData: L1ProcessArgs,
1314
- timestamp: bigint,
1315
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1316
- ) {
1212
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1317
1213
  const kzg = Blob.getViemKzgInstance();
1318
1214
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1319
1215
  this.log.debug('Validating blob input', { blobInput });
@@ -1326,7 +1222,11 @@ export class SequencerPublisher {
1326
1222
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1327
1223
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1328
1224
  } else {
1329
- // Normal mode - use estimateGas with blob inputs
1225
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1226
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1227
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1228
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1229
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1330
1230
  blobEvaluationGas = await this.l1TxUtils
1331
1231
  .estimateGas(
1332
1232
  this.getSenderAddress().toString(),
@@ -1384,138 +1284,21 @@ export class SequencerPublisher {
1384
1284
  blobInput,
1385
1285
  ] as const;
1386
1286
 
1387
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1287
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1388
1288
 
1389
- return { args, blobEvaluationGas, rollupData, simulationResult };
1390
- }
1391
-
1392
- /**
1393
- * Simulates the propose tx with eth_simulateV1
1394
- * @param args - The propose tx args
1395
- * @param timestamp - The timestamp to simulate proposal at
1396
- * @returns The simulation result
1397
- */
1398
- private async simulateProposeTx(
1399
- args: readonly [
1400
- {
1401
- readonly header: ViemHeader;
1402
- readonly archive: `0x${string}`;
1403
- readonly oracleInput: {
1404
- readonly feeAssetPriceModifier: bigint;
1405
- };
1406
- },
1407
- ViemCommitteeAttestations,
1408
- `0x${string}`[], // Signers
1409
- ViemSignature,
1410
- `0x${string}`,
1411
- ],
1412
- timestamp: bigint,
1413
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1414
- ) {
1415
- const rollupData = encodeFunctionData({
1416
- abi: RollupAbi,
1417
- functionName: 'propose',
1418
- args,
1419
- });
1420
-
1421
- // override the pending checkpoint number if requested
1422
- const forcePendingCheckpointNumberStateDiff = (
1423
- options.forcePendingCheckpointNumber !== undefined
1424
- ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber)
1425
- : []
1426
- ).flatMap(override => override.stateDiff ?? []);
1427
-
1428
- const stateOverrides: StateOverride = [
1429
- {
1430
- address: this.rollupContract.address,
1431
- // @note we override checkBlob to false since blobs are not part simulate()
1432
- stateDiff: [
1433
- { slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true), value: toPaddedHex(0n, true) },
1434
- ...forcePendingCheckpointNumberStateDiff,
1435
- ],
1436
- },
1437
- ];
1438
- // In fisherman mode, simulate as the proposer but with sufficient balance
1439
- if (this.proposerAddressForSimulation) {
1440
- stateOverrides.push({
1441
- address: this.proposerAddressForSimulation.toString(),
1442
- balance: 10n * WEI_CONST * WEI_CONST, // 10 ETH
1443
- });
1444
- }
1445
-
1446
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1447
-
1448
- const simulationResult = await this.l1TxUtils
1449
- .simulate(
1450
- {
1451
- to: this.rollupContract.address,
1452
- data: rollupData,
1453
- gas: MAX_L1_TX_LIMIT,
1454
- ...(this.proposerAddressForSimulation && { from: this.proposerAddressForSimulation.toString() }),
1455
- },
1456
- {
1457
- // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
1458
- time: timestamp + 1n,
1459
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1460
- gasLimit: MAX_L1_TX_LIMIT * 2n,
1461
- },
1462
- stateOverrides,
1463
- RollupAbi,
1464
- {
1465
- // @note fallback gas estimate to use if the node doesn't support simulation API
1466
- fallbackGasEstimate: MAX_L1_TX_LIMIT,
1467
- },
1468
- )
1469
- .catch(err => {
1470
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1471
- const viemError = formatViemError(err);
1472
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1473
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1474
- // Return a minimal simulation result with the fallback gas estimate
1475
- return {
1476
- gasUsed: MAX_L1_TX_LIMIT,
1477
- logs: [],
1478
- };
1479
- }
1480
- this.log.error(`Failed to simulate propose tx`, viemError);
1481
- this.backupFailedTx({
1482
- id: keccak256(rollupData),
1483
- failureType: 'simulation',
1484
- request: { to: this.rollupContract.address, data: rollupData },
1485
- l1BlockNumber: l1BlockNumber.toString(),
1486
- error: { message: viemError.message, name: viemError.name },
1487
- context: {
1488
- actions: ['propose'],
1489
- slot: Number(args[0].header.slotNumber),
1490
- sender: this.getSenderAddress().toString(),
1491
- },
1492
- });
1493
- throw err;
1494
- });
1495
-
1496
- return { rollupData, simulationResult };
1289
+ return { args, blobEvaluationGas, rollupData };
1497
1290
  }
1498
1291
 
1499
1292
  private async addProposeTx(
1500
1293
  checkpoint: Checkpoint,
1501
1294
  encodedData: L1ProcessArgs,
1502
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1503
- timestamp: bigint,
1295
+ opts: EnqueueProposeCheckpointOpts = {},
1504
1296
  ): Promise<void> {
1505
1297
  const slot = checkpoint.header.slotNumber;
1506
1298
  const timer = new Timer();
1507
1299
  const kzg = Blob.getViemKzgInstance();
1508
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
1509
- encodedData,
1510
- timestamp,
1511
- opts,
1512
- );
1300
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1513
1301
  const startBlock = await this.l1TxUtils.getBlockNumber();
1514
- const gasLimit = this.l1TxUtils.bumpGasLimit(
1515
- BigInt(Math.ceil((Number(simulationResult.gasUsed) * 64) / 63)) +
1516
- blobEvaluationGas +
1517
- SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS, // We issue the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1518
- );
1519
1302
 
1520
1303
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1521
1304
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
@@ -1532,7 +1315,8 @@ export class SequencerPublisher {
1532
1315
  data: rollupData,
1533
1316
  },
1534
1317
  lastValidL2Slot: checkpoint.header.slotNumber,
1535
- gasConfig: { ...opts, gasLimit },
1318
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1319
+ blobEvaluationGas,
1536
1320
  blobConfig: {
1537
1321
  blobs: encodedData.blobs.map(b => b.data),
1538
1322
  kzg,
@@ -1542,10 +1326,11 @@ export class SequencerPublisher {
1542
1326
  return false;
1543
1327
  }
1544
1328
  const { receipt, stats, errorMsg } = result;
1545
- const success =
1546
- receipt &&
1547
- receipt.status === 'success' &&
1548
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1329
+ const success = extractEventSuccess(receipt, {
1330
+ address: this.rollupContract.address,
1331
+ abi: RollupAbi,
1332
+ eventName: 'CheckpointProposed',
1333
+ });
1549
1334
 
1550
1335
  if (success) {
1551
1336
  const endBlock = receipt.blockNumber;
@@ -1585,4 +1370,10 @@ export class SequencerPublisher {
1585
1370
  },
1586
1371
  });
1587
1372
  }
1373
+
1374
+ /** Returns the timestamp of the next L1 slot boundary after now. */
1375
+ private getNextL1SlotTimestamp(): bigint {
1376
+ const l1Constants = this.epochCache.getL1Constants();
1377
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1378
+ }
1588
1379
  }