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

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 (101) 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 +49 -25
  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 +13 -26
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +9 -67
  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 +19 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +30 -5
  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 +84 -65
  32. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher.js +403 -531
  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 +189 -0
  38. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  39. package/dest/sequencer/automine/automine_sequencer.js +689 -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/checkpoint_proposal_job.d.ts +73 -21
  44. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  45. package/dest/sequencer/checkpoint_proposal_job.js +709 -200
  46. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  47. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  48. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  49. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  50. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  51. package/dest/sequencer/checkpoint_voter.js +2 -5
  52. package/dest/sequencer/errors.d.ts +1 -8
  53. package/dest/sequencer/errors.d.ts.map +1 -1
  54. package/dest/sequencer/errors.js +0 -9
  55. package/dest/sequencer/events.d.ts +61 -4
  56. package/dest/sequencer/events.d.ts.map +1 -1
  57. package/dest/sequencer/metrics.d.ts +9 -10
  58. package/dest/sequencer/metrics.d.ts.map +1 -1
  59. package/dest/sequencer/metrics.js +34 -20
  60. package/dest/sequencer/sequencer.d.ts +117 -30
  61. package/dest/sequencer/sequencer.d.ts.map +1 -1
  62. package/dest/sequencer/sequencer.js +483 -158
  63. package/dest/sequencer/types.d.ts +2 -2
  64. package/dest/sequencer/types.d.ts.map +1 -1
  65. package/dest/test/index.d.ts +3 -3
  66. package/dest/test/index.d.ts.map +1 -1
  67. package/dest/test/utils.d.ts +15 -1
  68. package/dest/test/utils.d.ts.map +1 -1
  69. package/dest/test/utils.js +24 -7
  70. package/package.json +28 -27
  71. package/src/client/sequencer-client.ts +29 -41
  72. package/src/config.ts +58 -25
  73. package/src/global_variable_builder/README.md +44 -0
  74. package/src/global_variable_builder/fee_predictor.ts +172 -0
  75. package/src/global_variable_builder/fee_provider.ts +80 -0
  76. package/src/global_variable_builder/global_builder.ts +19 -89
  77. package/src/global_variable_builder/index.ts +3 -1
  78. package/src/publisher/config.ts +62 -7
  79. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  80. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  81. package/src/publisher/sequencer-publisher-factory.ts +3 -6
  82. package/src/publisher/sequencer-publisher.ts +456 -578
  83. package/src/sequencer/automine/README.md +60 -0
  84. package/src/sequencer/automine/automine_factory.ts +152 -0
  85. package/src/sequencer/automine/automine_sequencer.ts +795 -0
  86. package/src/sequencer/automine/index.ts +6 -0
  87. package/src/sequencer/checkpoint_proposal_job.ts +817 -225
  88. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  89. package/src/sequencer/checkpoint_voter.ts +1 -12
  90. package/src/sequencer/errors.ts +0 -15
  91. package/src/sequencer/events.ts +65 -4
  92. package/src/sequencer/metrics.ts +43 -24
  93. package/src/sequencer/sequencer.ts +557 -175
  94. package/src/sequencer/types.ts +1 -1
  95. package/src/test/index.ts +2 -2
  96. package/src/test/utils.ts +60 -10
  97. package/dest/sequencer/timetable.d.ts +0 -88
  98. package/dest/sequencer/timetable.d.ts.map +0 -1
  99. package/dest/sequencer/timetable.js +0 -222
  100. package/src/sequencer/README.md +0 -531
  101. 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. */
@@ -81,18 +117,16 @@ type L1ProcessArgs = {
81
117
  export const Actions = [
82
118
  'invalidate-by-invalid-attestation',
83
119
  'invalidate-by-insufficient-attestations',
120
+ 'prune',
84
121
  'propose',
85
122
  'governance-signal',
86
- 'empire-slashing-signal',
87
- 'create-empire-payload',
88
- 'execute-empire-payload',
89
123
  'vote-offenses',
90
124
  'execute-slash',
91
125
  ] as const;
92
126
 
93
127
  export type Action = (typeof Actions)[number];
94
128
 
95
- type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slashing-signal'>;
129
+ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
96
130
 
97
131
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
98
132
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
@@ -103,14 +137,22 @@ export type InvalidateCheckpointRequest = {
103
137
  gasUsed: bigint;
104
138
  checkpointNumber: CheckpointNumber;
105
139
  forcePendingCheckpointNumber: CheckpointNumber;
140
+ /** Archive at the rollback target checkpoint (checkpoint N-1). */
141
+ lastArchive: Fr;
142
+ };
143
+
144
+ type EnqueueProposeCheckpointOpts = {
145
+ txTimeoutAt?: Date;
106
146
  };
107
147
 
108
- interface RequestWithExpiry {
148
+ export interface RequestWithExpiry {
109
149
  action: Action;
110
150
  request: L1TxRequest;
111
151
  lastValidL2Slot: SlotNumber;
112
152
  gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
113
153
  blobConfig?: L1BlobInputs;
154
+ /** Gas consumed by validateBlobs; stashed for the bundle simulate at send time. */
155
+ blobEvaluationGas?: bigint;
114
156
  checkSuccess: (
115
157
  request: L1TxRequest,
116
158
  result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
@@ -120,25 +162,29 @@ interface RequestWithExpiry {
120
162
  export class SequencerPublisher {
121
163
  private interrupted = false;
122
164
  private metrics: SequencerPublisherMetrics;
165
+ private bundleSimulator: SequencerBundleSimulator;
123
166
  public epochCache: EpochCache;
124
167
  private failedTxStore?: Promise<L1TxFailedStore | undefined>;
125
168
 
126
- protected governanceLog = createLogger('sequencer:publisher:governance');
127
- protected slashingLog = createLogger('sequencer:publisher:slashing');
169
+ /**
170
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
171
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
172
+ * publisher can route to so any of their custom errors decode against it.
173
+ */
174
+ private readonly revertDecoderAbi: Abi = mergeAbis([RollupAbi, SlashingProposerAbi, EmpireBaseAbi, ErrorsAbi]);
128
175
 
129
176
  protected lastActions: Partial<Record<Action, SlotNumber>> = {};
130
177
 
131
- private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
132
- private payloadProposedCache: Set<string> = new Set<string>();
133
-
134
178
  protected log: Logger;
135
179
  protected ethereumSlotDuration: bigint;
136
180
  protected aztecSlotDuration: bigint;
181
+ private readonly previousL1BlockWaitTimeoutMs: number;
182
+ private readonly previousL1BlockWaitPollIntervalMs: number;
137
183
 
138
- private blobClient: BlobClientInterface;
184
+ /** Date provider for wall-clock time. */
185
+ private readonly dateProvider: DateProvider;
139
186
 
140
- /** Address to use for simulations in fisherman mode (actual proposer's address) */
141
- private proposerAddressForSimulation?: EthAddress;
187
+ private blobClient: BlobClientInterface;
142
188
 
143
189
  /** Optional callback to obtain a replacement publisher when the current one fails to send. */
144
190
  private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
@@ -149,33 +195,34 @@ export class SequencerPublisher {
149
195
  /** Fee asset price oracle for computing price modifiers from Uniswap V4 */
150
196
  private feeAssetPriceOracle: FeeAssetPriceOracle;
151
197
 
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;
198
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */
199
+ private readonly interruptibleSleep = new InterruptibleSleep();
157
200
 
158
201
  public l1TxUtils: L1TxUtils;
159
202
  public rollupContract: RollupContract;
160
203
  public govProposerContract: GovernanceProposerContract;
161
- public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
162
- public slashFactoryContract: SlashFactoryContract;
204
+ public slashingProposerContract: SlashingProposerContract | undefined;
163
205
 
164
206
  public readonly tracer: Tracer;
165
207
 
166
208
  protected requests: RequestWithExpiry[] = [];
167
209
 
168
210
  constructor(
169
- private config: Pick<SequencerPublisherConfig, 'fishermanMode' | 'l1TxFailedStore'> &
211
+ private config: Pick<
212
+ SequencerPublisherConfig,
213
+ | 'fishermanMode'
214
+ | 'l1TxFailedStore'
215
+ | 'sequencerPublisherPreviousL1BlockWaitTimeoutMs'
216
+ | 'sequencerPublisherPreviousL1BlockWaitPollIntervalMs'
217
+ > &
170
218
  Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'> & { l1ChainId: number },
171
219
  deps: {
172
220
  telemetry?: TelemetryClient;
173
221
  blobClient: BlobClientInterface;
174
222
  l1TxUtils: L1TxUtils;
175
223
  rollupContract: RollupContract;
176
- slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
224
+ slashingProposerContract: SlashingProposerContract | undefined;
177
225
  governanceProposerContract: GovernanceProposerContract;
178
- slashFactoryContract: SlashFactoryContract;
179
226
  epochCache: EpochCache;
180
227
  dateProvider: DateProvider;
181
228
  metrics: SequencerPublisherMetrics;
@@ -187,10 +234,14 @@ export class SequencerPublisher {
187
234
  this.log = deps.log ?? createLogger('sequencer:publisher');
188
235
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
189
236
  this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
237
+ this.previousL1BlockWaitTimeoutMs = config.sequencerPublisherPreviousL1BlockWaitTimeoutMs;
238
+ this.previousL1BlockWaitPollIntervalMs = config.sequencerPublisherPreviousL1BlockWaitPollIntervalMs;
239
+ this.dateProvider = deps.dateProvider;
190
240
  this.epochCache = deps.epochCache;
191
241
  this.lastActions = deps.lastActions;
192
242
 
193
243
  this.blobClient = deps.blobClient;
244
+ this.dateProvider = deps.dateProvider;
194
245
 
195
246
  const telemetry = deps.telemetry ?? getTelemetryClient();
196
247
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
@@ -208,14 +259,12 @@ export class SequencerPublisher {
208
259
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
209
260
  this.slashingProposerContract = newSlashingProposer;
210
261
  });
211
- this.slashFactoryContract = deps.slashFactoryContract;
212
-
213
262
  // Initialize L1 fee analyzer for fisherman mode
214
263
  if (config.fishermanMode) {
215
264
  this.l1FeeAnalyzer = new L1FeeAnalyzer(
216
265
  this.l1TxUtils.client,
217
266
  deps.dateProvider,
218
- createLogger('sequencer:publisher:fee-analyzer'),
267
+ this.log.createChild('fee-analyzer'),
219
268
  );
220
269
  }
221
270
 
@@ -223,11 +272,18 @@ export class SequencerPublisher {
223
272
  this.feeAssetPriceOracle = new FeeAssetPriceOracle(
224
273
  this.l1TxUtils.client,
225
274
  this.rollupContract,
226
- createLogger('sequencer:publisher:price-oracle'),
275
+ this.log.createChild('price-oracle'),
227
276
  );
228
277
 
229
278
  // Initialize failed L1 tx store (optional, for test networks)
230
279
  this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
280
+
281
+ this.bundleSimulator = new SequencerBundleSimulator({
282
+ getL1TxUtils: () => this.l1TxUtils,
283
+ rollupContract: this.rollupContract,
284
+ epochCache: this.epochCache,
285
+ log: this.log.createChild('bundle-simulator'),
286
+ });
231
287
  }
232
288
 
233
289
  /**
@@ -258,10 +314,14 @@ export class SequencerPublisher {
258
314
 
259
315
  /**
260
316
  * Gets the fee asset price modifier from the oracle.
261
- * Returns 0n if the oracle query fails.
317
+ *
318
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
319
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
320
+ * modifier matches the parent L1 will use when applying it.
321
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
262
322
  */
263
- public getFeeAssetPriceModifier(): Promise<bigint> {
264
- return this.feeAssetPriceOracle.computePriceModifier();
323
+ public getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12?: bigint): Promise<bigint> {
324
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
265
325
  }
266
326
 
267
327
  public getSenderAddress() {
@@ -275,14 +335,6 @@ export class SequencerPublisher {
275
335
  return this.l1FeeAnalyzer;
276
336
  }
277
337
 
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
338
  public addRequest(request: RequestWithExpiry) {
287
339
  this.requests.push(request);
288
340
  }
@@ -360,22 +412,26 @@ export class SequencerPublisher {
360
412
 
361
413
  /**
362
414
  * Sends all requests that are still valid.
415
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
416
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
417
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
418
+ * AutomineSequencer, which publishes synchronously within the current slot.
363
419
  * @returns one of:
364
420
  * - A receipt and stats if the tx succeeded
365
421
  * - a receipt and errorMsg if it failed on L1
366
422
  * - undefined if no valid requests are found OR the tx failed to send.
367
423
  */
368
424
  @trackSpan('SequencerPublisher.sendRequests')
369
- public async sendRequests() {
425
+ public async sendRequests(targetSlot?: SlotNumber): Promise<SendRequestsResult | undefined> {
370
426
  const requestsToProcess = [...this.requests];
371
427
  this.requests = [];
428
+
372
429
  if (this.interrupted || requestsToProcess.length === 0) {
373
430
  return undefined;
374
431
  }
375
- const currentL2Slot = this.getCurrentL2Slot();
432
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
376
433
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
377
434
  const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
378
- const validActions = validRequests.map(x => x.action);
379
435
  const expiredActions = requestsToProcess
380
436
  .filter(request => request.lastValidL2Slot < currentL2Slot)
381
437
  .map(x => x.action);
@@ -398,70 +454,58 @@ export class SequencerPublisher {
398
454
  return undefined;
399
455
  }
400
456
 
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
457
+ // Collect earliest txTimeoutAt across all requests.
404
458
  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
459
  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 };
460
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined;
428
461
 
429
462
  // Sort the requests so that proposals always go first
430
463
  // This ensures the committee gets precomputed correctly
431
464
  validRequests.sort((a, b) => compareActions(a.action, b.action));
432
465
 
433
466
  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;
467
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
468
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
469
+
470
+ if (bundleResult.kind === 'aborted') {
471
+ this.logDroppedInSim(bundleResult.droppedRequests);
472
+ void this.backupDroppedInSim(bundleResult.droppedRequests);
473
+ return undefined;
474
+ }
448
475
 
449
- const txContext = { multicallData, blobData: blobDataHex, l1BlockNumber };
476
+ const { requests, droppedRequests, gasLimit } =
477
+ bundleResult.kind === 'fallback'
478
+ ? {
479
+ requests: bundleResult.requests,
480
+ droppedRequests: bundleResult.droppedRequests,
481
+ gasLimit: MAX_L1_TX_LIMIT,
482
+ }
483
+ : bundleResult;
484
+
485
+ this.logDroppedInSim(droppedRequests);
486
+
487
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
488
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
489
+ const [blobConfig] = requests.filter(r => r.blobConfig).map(r => r.blobConfig);
490
+ const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
450
491
 
451
492
  this.log.debug('Forwarding transactions', {
452
- validRequests: validRequests.map(request => request.action),
493
+ requests: requests.map(request => request.action),
453
494
  txConfig,
454
495
  });
455
- const result = await this.forwardWithPublisherRotation(validRequests, txConfig, blobConfig);
496
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
456
497
  if (result === undefined) {
457
498
  return undefined;
458
499
  }
459
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(
460
- validRequests,
500
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
501
+ const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action)];
502
+ return {
461
503
  result,
462
- txContext,
463
- );
464
- return { result, expiredActions, sentActions: validActions, successfulActions, failedActions };
504
+ expiredActions,
505
+ sentActions: requests.map(x => x.action),
506
+ successfulActions,
507
+ failedActions: allFailedActions,
508
+ };
465
509
  } catch (err) {
466
510
  const viemError = formatViemError(err);
467
511
  this.log.error(`Failed to publish bundled transactions`, viemError);
@@ -478,6 +522,40 @@ export class SequencerPublisher {
478
522
  }
479
523
  }
480
524
 
525
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */
526
+ private logDroppedInSim(dropped: DroppedRequest[]): void {
527
+ for (const drop of dropped) {
528
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
529
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
530
+ action: drop.request.action,
531
+ revertReason: revertReasonDecoded ?? drop.returnData,
532
+ revertReasonDecoded,
533
+ returnData: drop.returnData,
534
+ });
535
+ }
536
+ }
537
+
538
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */
539
+ private async backupDroppedInSim(dropped: DroppedRequest[]): Promise<void> {
540
+ if (dropped.length === 0) {
541
+ return;
542
+ }
543
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
544
+ for (const { request: req } of dropped) {
545
+ this.backupFailedTx({
546
+ id: keccak256(req.request.data!),
547
+ failureType: 'simulation',
548
+ request: { to: req.request.to! as Hex, data: req.request.data! },
549
+ l1BlockNumber: l1BlockNumber.toString(),
550
+ error: { message: 'Bundle entry dropped: action reverted in sim' },
551
+ context: {
552
+ actions: [req.action],
553
+ sender: this.getSenderAddress().toString(),
554
+ },
555
+ });
556
+ }
557
+ }
558
+
481
559
  /**
482
560
  * Forwards transactions via Multicall3, rotating to the next available publisher if a send
483
561
  * failure occurs (i.e. the tx never reached the chain).
@@ -488,19 +566,30 @@ export class SequencerPublisher {
488
566
  txConfig: RequestWithExpiry['gasConfig'],
489
567
  blobConfig: L1BlobInputs | undefined,
490
568
  ) {
569
+ if (!txConfig?.gasLimit) {
570
+ throw new Error('gasLimit is required for bundled transactions');
571
+ }
572
+ const txConfigWithGasLimit = txConfig as L1TxConfig & { gasLimit: bigint };
573
+
491
574
  const triedAddresses: EthAddress[] = [];
492
575
  let currentPublisher = this.l1TxUtils;
493
576
 
494
577
  while (true) {
578
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
579
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
580
+ triedAddresses: triedAddresses.map(a => a.toString()),
581
+ });
582
+ return undefined;
583
+ }
495
584
  triedAddresses.push(currentPublisher.getSenderAddress());
585
+
496
586
  try {
497
587
  const result = await Multicall3.forward(
498
588
  validRequests.map(r => r.request),
499
589
  currentPublisher,
500
- txConfig,
590
+ txConfigWithGasLimit,
501
591
  blobConfig,
502
- this.rollupContract.address,
503
- this.log,
592
+ { gasLimitRequired: true },
504
593
  );
505
594
  this.l1TxUtils = currentPublisher;
506
595
  return result;
@@ -508,6 +597,12 @@ export class SequencerPublisher {
508
597
  if (err instanceof TimeoutError) {
509
598
  throw err;
510
599
  }
600
+ if (err instanceof MulticallForwarderRevertedError) {
601
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
602
+ transactionHash: err.receipt.transactionHash,
603
+ });
604
+ return undefined;
605
+ }
511
606
  const viemError = formatViemError(err);
512
607
  if (!this.getNextPublisher) {
513
608
  this.log.error('Failed to publish bundled transactions', viemError);
@@ -519,7 +614,11 @@ export class SequencerPublisher {
519
614
  );
520
615
  const nextPublisher = await this.getNextPublisher([...triedAddresses]);
521
616
  if (!nextPublisher) {
522
- this.log.error('All available publishers exhausted, failed to publish bundled transactions');
617
+ this.log.error(
618
+ `All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`,
619
+ viemError,
620
+ { triedAddresses: triedAddresses.map(a => a.toString()) },
621
+ );
523
622
  return undefined;
524
623
  }
525
624
  currentPublisher = nextPublisher;
@@ -527,74 +626,98 @@ export class SequencerPublisher {
527
626
  }
528
627
  }
529
628
 
629
+ /*
630
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
631
+ */
632
+ public async sendRequestsAt(targetSlot: SlotNumber): Promise<SendRequestsResult | undefined> {
633
+ await this.waitForTargetSlot(targetSlot);
634
+ if (this.interrupted) {
635
+ return undefined;
636
+ }
637
+
638
+ return this.sendRequests(targetSlot);
639
+ }
640
+
641
+ /**
642
+ * Sleeps until one L1 slot before the L2 slot boundary, and then waits for that L1 block
643
+ * to be mined, so we don't risk being included in it. If that block never gets mined after
644
+ * a timeout, we assume it got skipped on L1, so we send the tx anyway.
645
+ */
646
+ private async waitForTargetSlot(targetSlot: SlotNumber): Promise<void> {
647
+ const l1Constants = this.epochCache.getL1Constants();
648
+ const nowInSeconds = this.dateProvider.nowInSeconds();
649
+ const startOfTargetSlotTs = getTimestampForSlot(targetSlot, l1Constants);
650
+ const previousL1BlockTs = startOfTargetSlotTs - this.ethereumSlotDuration;
651
+ const waitDeadlineTs = previousL1BlockTs + BigInt(this.previousL1BlockWaitTimeoutMs / 1000);
652
+ const logCtx = { targetSlot, startOfTargetSlotTs, nowInSeconds, previousL1BlockTs, waitDeadlineTs };
653
+
654
+ // Check if we are already past time
655
+ if (nowInSeconds >= startOfTargetSlotTs) {
656
+ this.log.verbose(`Target slot ${targetSlot} already started, sending requests immediately`, logCtx);
657
+ return;
658
+ }
659
+
660
+ // Otherwise we wait
661
+ this.log.debug(`Waiting for slot ${targetSlot} before sending requests`, logCtx);
662
+
663
+ // Wait until previous L1 block timestamp first
664
+ const sleepMs = (Number(previousL1BlockTs) - nowInSeconds) * 1000;
665
+ if (sleepMs > 0 && !this.interrupted) {
666
+ this.log.trace(`Sleeping ${sleepMs}ms before waiting for previous L1 block`, logCtx);
667
+ await this.interruptibleSleep.sleep(sleepMs);
668
+ }
669
+
670
+ // Then loop until we see the previous L1 block, so we know that we cannot be included in it.
671
+ // We time out after a while, once we are sure that that block is skipped in L1.
672
+ while (!this.interrupted) {
673
+ try {
674
+ const nowInSeconds = this.dateProvider.nowInSeconds();
675
+ logCtx.nowInSeconds = nowInSeconds;
676
+
677
+ if (nowInSeconds >= waitDeadlineTs) {
678
+ this.log.warn(`Timed out waiting for previous L1 block before sending requests, proceeding`, logCtx);
679
+ return;
680
+ }
681
+
682
+ const latestBlockTs = await this.l1TxUtils.getBlock().then(b => b.timestamp);
683
+ if (latestBlockTs >= previousL1BlockTs) {
684
+ this.log.debug(`Previous L1 block mined, proceeding to send requests`, { ...logCtx, latestBlockTs });
685
+ return;
686
+ }
687
+ this.log.trace(`Previous L1 block not mined yet, continuing to wait`, { ...logCtx, latestBlockTs });
688
+ } catch (err) {
689
+ this.log.error(`Error while waiting for previous L1 block before sending requests; retrying`, err, logCtx);
690
+ } finally {
691
+ await this.interruptibleSleep.sleep(this.previousL1BlockWaitPollIntervalMs);
692
+ }
693
+ }
694
+ }
695
+
530
696
  private callbackBundledTransactions(
531
697
  requests: RequestWithExpiry[],
532
- result: { receipt: TransactionReceipt; errorMsg?: string } | FormattedViemError | undefined,
533
- txContext: { multicallData: Hex; blobData?: Hex[]; l1BlockNumber: bigint },
698
+ result: { receipt: TransactionReceipt; multicallData: Hex },
534
699
  ) {
535
700
  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
- });
701
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
702
+ result,
703
+ requests: requests.map(r => ({
704
+ ...r,
705
+ // Avoid logging large blob data
706
+ blobConfig: r.blobConfig
707
+ ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
708
+ : undefined,
709
+ })),
710
+ });
711
+ const successfulActions: Action[] = [];
712
+ const failedActions: Action[] = [];
713
+ for (const request of requests) {
714
+ if (request.checkSuccess(request.request, result)) {
715
+ successfulActions.push(request.action);
716
+ } else {
717
+ failedActions.push(request.action);
595
718
  }
596
- return { successfulActions, failedActions };
597
719
  }
720
+ return { successfulActions, failedActions };
598
721
  }
599
722
 
600
723
  /**
@@ -602,24 +725,27 @@ export class SequencerPublisher {
602
725
  * @param tipArchive - The archive to check
603
726
  * @returns The slot and block number if it is possible to propose, undefined otherwise
604
727
  */
605
- public canProposeAt(
606
- tipArchive: Fr,
607
- msgSender: EthAddress,
608
- opts: { forcePendingCheckpointNumber?: CheckpointNumber; pipelined?: boolean } = {},
609
- ) {
728
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
610
729
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
611
- const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
730
+ // These errors are expected when we cannot actually propose right now — usually because our
731
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
732
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
733
+ // skip the proposal; we do NOT treat these as bugs.
734
+ const expectedErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
612
735
 
613
- const pipelined = opts.pipelined ?? this.epochCache.isProposerPipeliningEnabled();
614
- const slotOffset = pipelined ? this.aztecSlotDuration : 0n;
736
+ const slotOffset = this.aztecSlotDuration;
737
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
615
738
 
616
739
  return this.rollupContract
617
- .canProposeAt(tipArchive.toBuffer(), msgSender.toString(), this.ethereumSlotDuration, slotOffset, {
618
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
619
- })
740
+ .canProposeAt(
741
+ tipArchive.toBuffer(),
742
+ msgSender.toString(),
743
+ nextL1SlotTs,
744
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
745
+ )
620
746
  .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))}`, {
747
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
748
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
623
749
  error: err.message,
624
750
  });
625
751
  } else {
@@ -638,13 +764,13 @@ export class SequencerPublisher {
638
764
  @trackSpan('SequencerPublisher.validateBlockHeader')
639
765
  public async validateBlockHeader(
640
766
  header: CheckpointHeader,
641
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
767
+ simulationOverridesPlan?: SimulationOverridesPlan,
642
768
  ): Promise<void> {
643
769
  const flags = { ignoreDA: true, ignoreSignatures: true };
644
770
 
645
771
  const args = [
646
772
  header.toViem(),
647
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
773
+ CommitteeAttestationsAndSigners.packAttestations([]),
648
774
  [], // no signers
649
775
  Signature.empty().toViemSignature(),
650
776
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -652,10 +778,9 @@ export class SequencerPublisher {
652
778
  flags,
653
779
  ] as const;
654
780
 
655
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
656
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
657
- opts?.forcePendingCheckpointNumber,
658
- );
781
+ const l1Constants = this.epochCache.getL1Constants();
782
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
783
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
659
784
  let balance = 0n;
660
785
  if (this.config.fishermanMode) {
661
786
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -675,7 +800,7 @@ export class SequencerPublisher {
675
800
  data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
676
801
  from: MULTI_CALL_3_ADDRESS,
677
802
  },
678
- { time: ts + 1n },
803
+ { time: ts },
679
804
  stateOverrides,
680
805
  );
681
806
  this.log.debug(`Simulated validateHeader`);
@@ -728,6 +853,7 @@ export class SequencerPublisher {
728
853
  gasUsed,
729
854
  checkpointNumber,
730
855
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
856
+ lastArchive: validationResult.checkpoint.lastArchive,
731
857
  reason,
732
858
  };
733
859
  } catch (err) {
@@ -740,8 +866,8 @@ export class SequencerPublisher {
740
866
  `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
741
867
  { ...logData, request, error: viemError.message },
742
868
  );
743
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
744
- if (latestPendingCheckpointNumber < checkpointNumber) {
869
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
870
+ if (latestProposedCheckpointNumber < checkpointNumber) {
745
871
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
746
872
  return undefined;
747
873
  } else {
@@ -786,9 +912,7 @@ export class SequencerPublisher {
786
912
  const logData = { ...checkpoint, reason };
787
913
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
788
914
 
789
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
790
- validationResult.attestations,
791
- ).getPackedAttestations();
915
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
792
916
 
793
917
  if (reason === 'invalid-attestation') {
794
918
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -809,45 +933,11 @@ export class SequencerPublisher {
809
933
  }
810
934
  }
811
935
 
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
936
  private async enqueueCastSignalHelper(
846
937
  slotNumber: SlotNumber,
847
- timestamp: bigint,
848
938
  signalType: GovernanceSignalAction,
849
939
  payload: EthAddress,
850
- base: IEmpireBase,
940
+ base: GovernanceProposerContract,
851
941
  signerAddress: EthAddress,
852
942
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
853
943
  ): Promise<boolean> {
@@ -873,34 +963,28 @@ export class SequencerPublisher {
873
963
  return false;
874
964
  }
875
965
 
876
- if (await this.isPayloadEmpty(payload)) {
966
+ if (await base.isPayloadEmpty(payload)) {
877
967
  this.log.warn(`Skipping vote cast for payload with empty code`);
878
968
  return false;
879
969
  }
880
970
 
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
- }
971
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
972
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
973
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
974
+ // the same payload in a future round.
975
+ let proposed = false;
976
+ try {
977
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
978
+ } catch (err) {
979
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
980
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
981
+ // participation entirely; failing open at worst produces a duplicate signal that the
982
+ // contract will simply count alongside others in the round.
983
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
900
984
  }
901
985
 
902
- if (this.payloadProposedCache.has(cacheKey)) {
903
- this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
986
+ if (proposed) {
987
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
904
988
  return false;
905
989
  }
906
990
 
@@ -922,41 +1006,19 @@ export class SequencerPublisher {
922
1006
  lastValidL2Slot: slotNumber,
923
1007
  });
924
1008
 
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
1009
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
949
1010
  this.addRequest({
950
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
951
1011
  action,
952
1012
  request,
953
1013
  lastValidL2Slot: slotNumber,
954
1014
  checkSuccess: (_request, result) => {
955
1015
  const success =
956
1016
  result &&
957
- result.receipt &&
958
- result.receipt.status === 'success' &&
959
- tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
1017
+ extractEventSuccess(result.receipt, {
1018
+ address: base.address.toString(),
1019
+ abi: EmpireBaseAbi,
1020
+ eventName: 'SignalCast',
1021
+ });
960
1022
 
961
1023
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
962
1024
  if (!success) {
@@ -978,33 +1040,19 @@ export class SequencerPublisher {
978
1040
  return true;
979
1041
  }
980
1042
 
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
1043
  /**
993
1044
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
994
1045
  * @param slotNumber - The slot number to cast a signal for.
995
- * @param timestamp - The timestamp of the slot to cast a signal for.
996
1046
  * @returns True if the signal was successfully enqueued, false otherwise.
997
1047
  */
998
1048
  public enqueueGovernanceCastSignal(
999
1049
  governancePayload: EthAddress,
1000
1050
  slotNumber: SlotNumber,
1001
- timestamp: bigint,
1002
1051
  signerAddress: EthAddress,
1003
1052
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
1004
1053
  ): Promise<boolean> {
1005
1054
  return this.enqueueCastSignalHelper(
1006
1055
  slotNumber,
1007
- timestamp,
1008
1056
  'governance-signal',
1009
1057
  governancePayload,
1010
1058
  this.govProposerContract,
@@ -1013,11 +1061,51 @@ export class SequencerPublisher {
1013
1061
  );
1014
1062
  }
1015
1063
 
1064
+ /**
1065
+ * Enqueues a `prune()` transaction if the rollup is prunable at the given slot's L1 timestamp.
1066
+ * `prune()` is permissionless and idempotent — if the chain is no longer prunable by send time the
1067
+ * bundle simulation usually drops the entry; on a node without `eth_simulateV1` the bundle is sent
1068
+ * as-is and the prune reverts `Rollup__NothingToPrune` inside `aggregate3(allowFailure: true)`
1069
+ * (a failed action, never a whole-tx revert). Used by the failed-sync fallback so a stuck pending
1070
+ * chain (e.g. bad data blocking sync) can be wound back to recover.
1071
+ * @returns true if a prune request was enqueued, false otherwise.
1072
+ */
1073
+ public async enqueuePruneIfPrunable(slotNumber: SlotNumber): Promise<boolean> {
1074
+ if (this.lastActions['prune'] === slotNumber) {
1075
+ this.log.debug(`Skipping duplicate prune for slot ${slotNumber}`, { slotNumber });
1076
+ return false;
1077
+ }
1078
+ // Use the SAME timestamp the bundle simulator overrides block.timestamp with at send time
1079
+ // (sequencer-bundle-simulator.ts) so this upfront check and the send-time sim agree. Slot-start
1080
+ // and last-L1-slot both fall within the same L2 slot (and epoch, which is what `canPruneAtTime`
1081
+ // derives), so they agree today; matching the simulator keeps it robust if the contract ever uses
1082
+ // the timestamp more granularly.
1083
+ const ts = getLastL1SlotTimestampForL2Slot(slotNumber, this.epochCache.getL1Constants());
1084
+ const canPrune = await this.rollupContract.canPruneAtTime(ts).catch(err => {
1085
+ this.log.error(`Failed to check canPruneAtTime for slot ${slotNumber}`, err, { slotNumber });
1086
+ return false;
1087
+ });
1088
+ if (!canPrune) {
1089
+ this.log.debug(`Rollup not prunable at slot ${slotNumber}`, { slotNumber });
1090
+ return false;
1091
+ }
1092
+ const request: L1TxRequest = {
1093
+ to: this.rollupContract.address,
1094
+ data: encodeFunctionData({ abi: RollupAbi, functionName: 'prune', args: [] }),
1095
+ };
1096
+ this.log.info(`Enqueuing rollup prune for slot ${slotNumber}`, { slotNumber });
1097
+ return this.enqueueRequest(
1098
+ 'prune',
1099
+ request,
1100
+ { address: this.rollupContract.address, abi: RollupAbi, eventName: 'PrunedPending' },
1101
+ slotNumber,
1102
+ );
1103
+ }
1104
+
1016
1105
  /** Enqueues all slashing actions as returned by the slasher client. */
1017
1106
  public async enqueueSlashingActions(
1018
1107
  actions: ProposerSlashAction[],
1019
1108
  slotNumber: SlotNumber,
1020
- timestamp: bigint,
1021
1109
  signerAddress: EthAddress,
1022
1110
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
1023
1111
  ): Promise<boolean> {
@@ -1028,58 +1116,6 @@ export class SequencerPublisher {
1028
1116
 
1029
1117
  for (const action of actions) {
1030
1118
  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
1119
  case 'vote-offenses': {
1084
1120
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
1085
1121
  slotNumber,
@@ -1087,19 +1123,21 @@ export class SequencerPublisher {
1087
1123
  votesCount: action.votes.length,
1088
1124
  signerAddress,
1089
1125
  });
1090
- if (this.slashingProposerContract?.type !== 'tally') {
1091
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1126
+ if (!this.slashingProposerContract) {
1127
+ this.log.error('No slashing proposer contract available');
1092
1128
  return false;
1093
1129
  }
1094
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
1095
1130
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1096
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
1097
- await this.simulateAndEnqueueRequest(
1131
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1132
+ this.enqueueRequest(
1098
1133
  'vote-offenses',
1099
1134
  request,
1100
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1135
+ {
1136
+ address: this.slashingProposerContract.address.toString(),
1137
+ abi: SlashingProposerAbi,
1138
+ eventName: 'VoteCast',
1139
+ },
1101
1140
  slotNumber,
1102
- timestamp,
1103
1141
  );
1104
1142
  break;
1105
1143
  }
@@ -1110,18 +1148,23 @@ export class SequencerPublisher {
1110
1148
  round: action.round,
1111
1149
  signerAddress,
1112
1150
  });
1113
- if (this.slashingProposerContract?.type !== 'tally') {
1114
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1151
+ if (!this.slashingProposerContract) {
1152
+ this.log.error('No slashing proposer contract available');
1115
1153
  return false;
1116
1154
  }
1117
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
1118
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
1119
- await this.simulateAndEnqueueRequest(
1155
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1156
+ action.round,
1157
+ action.committees,
1158
+ );
1159
+ this.enqueueRequest(
1120
1160
  'execute-slash',
1121
- request,
1122
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1161
+ executeRequest,
1162
+ {
1163
+ address: this.slashingProposerContract.address.toString(),
1164
+ abi: SlashingProposerAbi,
1165
+ eventName: 'RoundExecuted',
1166
+ },
1123
1167
  slotNumber,
1124
- timestamp,
1125
1168
  );
1126
1169
  break;
1127
1170
  }
@@ -1136,12 +1179,12 @@ export class SequencerPublisher {
1136
1179
  return true;
1137
1180
  }
1138
1181
 
1139
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1182
+ /** Enqueues a proposal for a checkpoint on L1 */
1140
1183
  public async enqueueProposeCheckpoint(
1141
1184
  checkpoint: Checkpoint,
1142
1185
  attestationsAndSigners: CommitteeAttestationsAndSigners,
1143
1186
  attestationsAndSignersSignature: Signature,
1144
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1187
+ opts: EnqueueProposeCheckpointOpts = {},
1145
1188
  ): Promise<void> {
1146
1189
  const checkpointHeader = checkpoint.header;
1147
1190
 
@@ -1157,31 +1200,11 @@ export class SequencerPublisher {
1157
1200
  feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
1158
1201
  };
1159
1202
 
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);
1203
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1204
+ ...checkpoint.toCheckpointInfo(),
1205
+ txTimeoutAt: opts.txTimeoutAt,
1206
+ });
1207
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
1185
1208
  }
1186
1209
 
1187
1210
  public enqueueInvalidateCheckpoint(
@@ -1192,23 +1215,22 @@ export class SequencerPublisher {
1192
1215
  return;
1193
1216
  }
1194
1217
 
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
1218
  const { gasUsed, checkpointNumber } = request;
1199
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1219
+ const logData = { gasUsed, checkpointNumber, opts };
1200
1220
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1201
1221
  this.addRequest({
1202
1222
  action: `invalidate-by-${request.reason}`,
1203
1223
  request: request.request,
1204
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1224
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
1205
1225
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1206
1226
  checkSuccess: (_req, result) => {
1207
1227
  const success =
1208
1228
  result &&
1209
- result.receipt &&
1210
- result.receipt.status === 'success' &&
1211
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1229
+ extractEventSuccess(result.receipt, {
1230
+ address: this.rollupContract.address,
1231
+ abi: RollupAbi,
1232
+ eventName: 'CheckpointInvalidated',
1233
+ });
1212
1234
  if (!success) {
1213
1235
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
1214
1236
  } else {
@@ -1219,72 +1241,36 @@ export class SequencerPublisher {
1219
1241
  });
1220
1242
  }
1221
1243
 
1222
- private async simulateAndEnqueueRequest(
1244
+ /**
1245
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1246
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1247
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1248
+ */
1249
+ private enqueueRequest(
1223
1250
  action: Action,
1224
1251
  request: L1TxRequest,
1225
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1252
+ eventOpts: { address: string; abi: Abi; eventName: string },
1226
1253
  slotNumber: SlotNumber,
1227
- timestamp: bigint,
1228
- ) {
1229
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1254
+ ): boolean {
1230
1255
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1231
1256
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1232
1257
  return false;
1233
1258
  }
1234
-
1235
1259
  const cachedLastActionSlot = this.lastActions[action];
1236
1260
  this.lastActions[action] = slotNumber;
1237
1261
 
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);
1262
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1276
1263
  this.addRequest({
1277
1264
  action,
1278
- request: requestWithAbi,
1279
- gasConfig: { gasLimit },
1265
+ request,
1280
1266
  lastValidL2Slot: slotNumber,
1281
- checkSuccess: (_req, result) => {
1282
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1267
+ checkSuccess: (_request, result) => {
1268
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1283
1269
  if (!success) {
1284
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1270
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1285
1271
  this.lastActions[action] = cachedLastActionSlot;
1286
1272
  } else {
1287
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1273
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1288
1274
  }
1289
1275
  return !!success;
1290
1276
  },
@@ -1300,6 +1286,7 @@ export class SequencerPublisher {
1300
1286
  */
1301
1287
  public interrupt() {
1302
1288
  this.interrupted = true;
1289
+ this.interruptibleSleep.interrupt();
1303
1290
  this.l1TxUtils.interrupt();
1304
1291
  }
1305
1292
 
@@ -1309,11 +1296,7 @@ export class SequencerPublisher {
1309
1296
  this.l1TxUtils.restart();
1310
1297
  }
1311
1298
 
1312
- private async prepareProposeTx(
1313
- encodedData: L1ProcessArgs,
1314
- timestamp: bigint,
1315
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1316
- ) {
1299
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1317
1300
  const kzg = Blob.getViemKzgInstance();
1318
1301
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1319
1302
  this.log.debug('Validating blob input', { blobInput });
@@ -1326,7 +1309,11 @@ export class SequencerPublisher {
1326
1309
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1327
1310
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1328
1311
  } else {
1329
- // Normal mode - use estimateGas with blob inputs
1312
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1313
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1314
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1315
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1316
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1330
1317
  blobEvaluationGas = await this.l1TxUtils
1331
1318
  .estimateGas(
1332
1319
  this.getSenderAddress().toString(),
@@ -1384,138 +1371,21 @@ export class SequencerPublisher {
1384
1371
  blobInput,
1385
1372
  ] as const;
1386
1373
 
1387
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1374
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1388
1375
 
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 };
1376
+ return { args, blobEvaluationGas, rollupData };
1497
1377
  }
1498
1378
 
1499
1379
  private async addProposeTx(
1500
1380
  checkpoint: Checkpoint,
1501
1381
  encodedData: L1ProcessArgs,
1502
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1503
- timestamp: bigint,
1382
+ opts: EnqueueProposeCheckpointOpts = {},
1504
1383
  ): Promise<void> {
1505
1384
  const slot = checkpoint.header.slotNumber;
1506
1385
  const timer = new Timer();
1507
1386
  const kzg = Blob.getViemKzgInstance();
1508
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
1509
- encodedData,
1510
- timestamp,
1511
- opts,
1512
- );
1387
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1513
1388
  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
1389
 
1520
1390
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1521
1391
  // 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 +1402,8 @@ export class SequencerPublisher {
1532
1402
  data: rollupData,
1533
1403
  },
1534
1404
  lastValidL2Slot: checkpoint.header.slotNumber,
1535
- gasConfig: { ...opts, gasLimit },
1405
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1406
+ blobEvaluationGas,
1536
1407
  blobConfig: {
1537
1408
  blobs: encodedData.blobs.map(b => b.data),
1538
1409
  kzg,
@@ -1542,10 +1413,11 @@ export class SequencerPublisher {
1542
1413
  return false;
1543
1414
  }
1544
1415
  const { receipt, stats, errorMsg } = result;
1545
- const success =
1546
- receipt &&
1547
- receipt.status === 'success' &&
1548
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1416
+ const success = extractEventSuccess(receipt, {
1417
+ address: this.rollupContract.address,
1418
+ abi: RollupAbi,
1419
+ eventName: 'CheckpointProposed',
1420
+ });
1549
1421
 
1550
1422
  if (success) {
1551
1423
  const endBlock = receipt.blockNumber;
@@ -1585,4 +1457,10 @@ export class SequencerPublisher {
1585
1457
  },
1586
1458
  });
1587
1459
  }
1460
+
1461
+ /** Returns the timestamp of the next L1 slot boundary after now. */
1462
+ private getNextL1SlotTimestamp(): bigint {
1463
+ const l1Constants = this.epochCache.getL1Constants();
1464
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1465
+ }
1588
1466
  }