@aztec/sequencer-client 0.0.1-commit.4d3c002 → 0.0.1-commit.4d9804df

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +20 -5
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +26 -22
  5. package/dest/config.d.ts +11 -4
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +55 -26
  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 +138 -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 +80 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +7 -26
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +6 -67
  17. package/dest/global_variable_builder/index.d.ts +3 -1
  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 +7 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +13 -3
  23. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  24. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  25. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  26. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +50 -11
  27. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  28. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -1
  29. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +2 -2
  30. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -1
  31. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +4 -2
  32. package/dest/publisher/l1_tx_failed_store/index.d.ts +2 -2
  33. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -1
  34. package/dest/publisher/l1_tx_failed_store/index.js +1 -0
  35. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  36. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  37. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  38. package/dest/publisher/sequencer-publisher-factory.d.ts +1 -3
  39. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  40. package/dest/publisher/sequencer-publisher-factory.js +0 -1
  41. package/dest/publisher/sequencer-publisher.d.ts +77 -68
  42. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  43. package/dest/publisher/sequencer-publisher.js +593 -553
  44. package/dest/publisher/write_json.d.ts +11 -0
  45. package/dest/publisher/write_json.d.ts.map +1 -0
  46. package/dest/publisher/write_json.js +57 -0
  47. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  48. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  49. package/dest/sequencer/automine/automine_factory.js +85 -0
  50. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  51. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  52. package/dest/sequencer/automine/automine_sequencer.js +690 -0
  53. package/dest/sequencer/automine/index.d.ts +3 -0
  54. package/dest/sequencer/automine/index.d.ts.map +1 -0
  55. package/dest/sequencer/automine/index.js +2 -0
  56. package/dest/sequencer/checkpoint_proposal_job.d.ts +67 -36
  57. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  58. package/dest/sequencer/checkpoint_proposal_job.js +686 -253
  59. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  60. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  61. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  62. package/dest/sequencer/events.d.ts +61 -5
  63. package/dest/sequencer/events.d.ts.map +1 -1
  64. package/dest/sequencer/metrics.d.ts +9 -10
  65. package/dest/sequencer/metrics.d.ts.map +1 -1
  66. package/dest/sequencer/metrics.js +34 -20
  67. package/dest/sequencer/requests_tracker.d.ts +22 -0
  68. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  69. package/dest/sequencer/requests_tracker.js +33 -0
  70. package/dest/sequencer/sequencer.d.ts +145 -33
  71. package/dest/sequencer/sequencer.d.ts.map +1 -1
  72. package/dest/sequencer/sequencer.js +520 -180
  73. package/dest/sequencer/types.d.ts +2 -2
  74. package/dest/sequencer/types.d.ts.map +1 -1
  75. package/dest/test/index.d.ts +3 -3
  76. package/dest/test/index.d.ts.map +1 -1
  77. package/dest/test/utils.d.ts +15 -1
  78. package/dest/test/utils.d.ts.map +1 -1
  79. package/dest/test/utils.js +25 -7
  80. package/package.json +30 -28
  81. package/src/client/sequencer-client.ts +37 -27
  82. package/src/config.ts +64 -26
  83. package/src/global_variable_builder/README.md +44 -0
  84. package/src/global_variable_builder/fee_predictor.ts +182 -0
  85. package/src/global_variable_builder/fee_provider.ts +97 -0
  86. package/src/global_variable_builder/global_builder.ts +11 -91
  87. package/src/global_variable_builder/index.ts +2 -0
  88. package/src/publisher/config.ts +30 -7
  89. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  90. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +117 -8
  91. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +4 -3
  92. package/src/publisher/l1_tx_failed_store/index.ts +1 -1
  93. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  94. package/src/publisher/sequencer-publisher-factory.ts +0 -3
  95. package/src/publisher/sequencer-publisher.ts +671 -641
  96. package/src/publisher/write_json.ts +78 -0
  97. package/src/sequencer/README.md +162 -450
  98. package/src/sequencer/automine/README.md +60 -0
  99. package/src/sequencer/automine/automine_factory.ts +152 -0
  100. package/src/sequencer/automine/automine_sequencer.ts +796 -0
  101. package/src/sequencer/automine/index.ts +6 -0
  102. package/src/sequencer/checkpoint_proposal_job.ts +808 -313
  103. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  104. package/src/sequencer/events.ts +66 -5
  105. package/src/sequencer/metrics.ts +43 -24
  106. package/src/sequencer/requests_tracker.ts +43 -0
  107. package/src/sequencer/sequencer.ts +586 -206
  108. package/src/sequencer/types.ts +1 -1
  109. package/src/test/index.ts +2 -2
  110. package/src/test/utils.ts +61 -10
  111. package/dest/sequencer/timetable.d.ts +0 -88
  112. package/dest/sequencer/timetable.d.ts.map +0 -1
  113. package/dest/sequencer/timetable.js +0 -222
  114. package/src/sequencer/timetable.ts +0 -283
@@ -3,72 +3,92 @@ 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
- type FeeHeader,
9
7
  type GovernanceProposerContract,
10
- type IEmpireBase,
11
8
  MULTI_CALL_3_ADDRESS,
12
9
  Multicall3,
13
- RollupContract,
14
- type TallySlashingProposerContract,
15
- type ViemCommitteeAttestations,
16
- type ViemHeader,
10
+ MulticallForwarderRevertedError,
11
+ type RollupContract,
12
+ type SimulationOverridesPlan,
13
+ type SlashingProposerContract,
14
+ buildSimulationOverridesStateOverride,
17
15
  } from '@aztec/ethereum/contracts';
18
- import { type L1FeeAnalysisResult, L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
16
+ import { type L1FeeAnalysisResult, L1FeeAnalyzer, captureWindowBlockFees } from '@aztec/ethereum/l1-fee-analysis';
19
17
  import {
20
18
  type L1BlobInputs,
21
19
  type L1TxConfig,
22
20
  type L1TxRequest,
21
+ L1TxTimeoutError,
23
22
  type L1TxUtils,
24
23
  MAX_L1_TX_LIMIT,
25
24
  type TransactionStats,
26
25
  WEI_CONST,
27
26
  } from '@aztec/ethereum/l1-tx-utils';
28
- import { FormattedViemError, formatViemError, mergeAbis, tryExtractEvent } from '@aztec/ethereum/utils';
29
- import { sumBigint } from '@aztec/foundation/bigint';
30
- import { toHex as toPaddedHex } from '@aztec/foundation/bigint-buffer';
27
+ import {
28
+ FormattedViemError,
29
+ formatViemError,
30
+ mergeAbis,
31
+ tryDecodeRevertReason,
32
+ tryExtractEvent,
33
+ } from '@aztec/ethereum/utils';
31
34
  import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
32
35
  import { trimmedBytesLength } from '@aztec/foundation/buffer';
33
36
  import { pick } from '@aztec/foundation/collection';
34
37
  import type { Fr } from '@aztec/foundation/curves/bn254';
35
38
  import { TimeoutError } from '@aztec/foundation/error';
36
39
  import { EthAddress } from '@aztec/foundation/eth-address';
37
- import { Signature, type ViemSignature } from '@aztec/foundation/eth-signature';
40
+ import { Signature } from '@aztec/foundation/eth-signature';
38
41
  import { type Logger, createLogger } from '@aztec/foundation/log';
39
- import { makeBackoff, retry } from '@aztec/foundation/retry';
40
42
  import { InterruptibleSleep } from '@aztec/foundation/sleep';
41
43
  import { bufferToHex } from '@aztec/foundation/string';
42
44
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
43
- import { EmpireBaseAbi, ErrorsAbi, RollupAbi } from '@aztec/l1-artifacts';
45
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi, SlashingProposerAbi } from '@aztec/l1-artifacts';
44
46
  import { type ProposerSlashAction, encodeSlashConsensusVotes } from '@aztec/slasher';
45
47
  import { CommitteeAttestationsAndSigners, type ValidateCheckpointResult } from '@aztec/stdlib/block';
46
48
  import type { Checkpoint } from '@aztec/stdlib/checkpoint';
47
- import { getLastL1SlotTimestampForL2Slot, getNextL1SlotTimestamp } from '@aztec/stdlib/epoch-helpers';
48
- import { SlashFactoryContract } from '@aztec/stdlib/l1-contracts';
49
+ import {
50
+ getLastL1SlotTimestampForL2Slot,
51
+ getNextL1SlotTimestamp,
52
+ getTimestampForSlot,
53
+ } from '@aztec/stdlib/epoch-helpers';
49
54
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
50
55
  import type { L1PublishCheckpointStats } from '@aztec/stdlib/stats';
51
56
  import { type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
52
57
 
53
58
  import {
59
+ type Abi,
54
60
  type Hex,
55
- type StateOverride,
56
61
  type TransactionReceipt,
57
62
  type TypedDataDefinition,
58
63
  encodeFunctionData,
59
64
  keccak256,
60
- multicall3Abi,
61
65
  toHex,
62
66
  } from 'viem';
63
67
 
64
68
  import type { SequencerPublisherConfig } from './config.js';
65
69
  import { type FailedL1Tx, type L1TxFailedStore, createL1TxFailedStore } from './l1_tx_failed_store/index.js';
70
+ import { type DroppedRequest, SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
66
71
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
67
72
 
73
+ /**
74
+ * Returns true if the receipt indicates a successful send AND the expected event was emitted
75
+ * by the target contract. Both pieces are required: an aggregate3 entry that reverted will
76
+ * have receipt.status === 'success' but no event log.
77
+ */
78
+ function extractEventSuccess(
79
+ receipt: TransactionReceipt | undefined,
80
+ opts: { address: string; abi: Abi; eventName: string },
81
+ ): boolean {
82
+ if (!receipt || receipt.status !== 'success') {
83
+ return false;
84
+ }
85
+ return !!tryExtractEvent(receipt.logs, opts.address.toString() as Hex, opts.abi, opts.eventName);
86
+ }
87
+
68
88
  /** Result of a sendRequests call, returned by both sendRequests() and sendRequestsAt(). */
69
89
  export type SendRequestsResult = {
70
- /** The L1 transaction receipt or error from the bundled multicall. */
71
- result: { receipt: TransactionReceipt; errorMsg?: string } | FormattedViemError;
90
+ /** The L1 transaction receipt from the bundled multicall. */
91
+ result: { receipt: TransactionReceipt };
72
92
  /** Actions that expired (past their deadline) before the request was sent. */
73
93
  expiredActions: Action[];
74
94
  /** Actions that were included in the sent L1 transaction. */
@@ -98,18 +118,16 @@ type L1ProcessArgs = {
98
118
  export const Actions = [
99
119
  'invalidate-by-invalid-attestation',
100
120
  'invalidate-by-insufficient-attestations',
121
+ 'prune',
101
122
  'propose',
102
123
  'governance-signal',
103
- 'empire-slashing-signal',
104
- 'create-empire-payload',
105
- 'execute-empire-payload',
106
124
  'vote-offenses',
107
125
  'execute-slash',
108
126
  ] as const;
109
127
 
110
128
  export type Action = (typeof Actions)[number];
111
129
 
112
- type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slashing-signal'>;
130
+ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
113
131
 
114
132
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
115
133
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
@@ -124,12 +142,18 @@ export type InvalidateCheckpointRequest = {
124
142
  lastArchive: Fr;
125
143
  };
126
144
 
127
- interface RequestWithExpiry {
145
+ type EnqueueProposeCheckpointOpts = {
146
+ txTimeoutAt?: Date;
147
+ };
148
+
149
+ export interface RequestWithExpiry {
128
150
  action: Action;
129
151
  request: L1TxRequest;
130
152
  lastValidL2Slot: SlotNumber;
131
153
  gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
132
154
  blobConfig?: L1BlobInputs;
155
+ /** Gas consumed by validateBlobs; stashed for the bundle simulate at send time. */
156
+ blobEvaluationGas?: bigint;
133
157
  checkSuccess: (
134
158
  request: L1TxRequest,
135
159
  result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
@@ -139,29 +163,30 @@ interface RequestWithExpiry {
139
163
  export class SequencerPublisher {
140
164
  private interrupted = false;
141
165
  private metrics: SequencerPublisherMetrics;
166
+ private bundleSimulator: SequencerBundleSimulator;
142
167
  public epochCache: EpochCache;
143
168
  private failedTxStore?: Promise<L1TxFailedStore | undefined>;
144
169
 
145
- protected governanceLog = createLogger('sequencer:publisher:governance');
146
- protected slashingLog = createLogger('sequencer:publisher:slashing');
170
+ /**
171
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
172
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
173
+ * publisher can route to so any of their custom errors decode against it.
174
+ */
175
+ private readonly revertDecoderAbi: Abi = mergeAbis([RollupAbi, SlashingProposerAbi, EmpireBaseAbi, ErrorsAbi]);
147
176
 
148
177
  protected lastActions: Partial<Record<Action, SlotNumber>> = {};
149
178
 
150
- private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
151
- private payloadProposedCache: Set<string> = new Set<string>();
152
-
153
179
  protected log: Logger;
154
180
  protected ethereumSlotDuration: bigint;
155
181
  protected aztecSlotDuration: bigint;
182
+ private readonly previousL1BlockWaitTimeoutMs: number;
183
+ private readonly previousL1BlockWaitPollIntervalMs: number;
156
184
 
157
185
  /** Date provider for wall-clock time. */
158
186
  private readonly dateProvider: DateProvider;
159
187
 
160
188
  private blobClient: BlobClientInterface;
161
189
 
162
- /** Address to use for simulations in fisherman mode (actual proposer's address) */
163
- private proposerAddressForSimulation?: EthAddress;
164
-
165
190
  /** Optional callback to obtain a replacement publisher when the current one fails to send. */
166
191
  private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
167
192
 
@@ -174,33 +199,31 @@ export class SequencerPublisher {
174
199
  /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */
175
200
  private readonly interruptibleSleep = new InterruptibleSleep();
176
201
 
177
- // A CALL to a cold address is 2700 gas
178
- public static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
179
-
180
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
181
- public static VOTE_GAS_GUESS: bigint = 800_000n;
182
-
183
202
  public l1TxUtils: L1TxUtils;
184
203
  public rollupContract: RollupContract;
185
204
  public govProposerContract: GovernanceProposerContract;
186
- public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
187
- public slashFactoryContract: SlashFactoryContract;
205
+ public slashingProposerContract: SlashingProposerContract | undefined;
188
206
 
189
207
  public readonly tracer: Tracer;
190
208
 
191
209
  protected requests: RequestWithExpiry[] = [];
192
210
 
193
211
  constructor(
194
- private config: Pick<SequencerPublisherConfig, 'fishermanMode' | 'l1TxFailedStore'> &
212
+ private config: Pick<
213
+ SequencerPublisherConfig,
214
+ | 'fishermanMode'
215
+ | 'l1TxFailedStore'
216
+ | 'sequencerPublisherPreviousL1BlockWaitTimeoutMs'
217
+ | 'sequencerPublisherPreviousL1BlockWaitPollIntervalMs'
218
+ > &
195
219
  Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'> & { l1ChainId: number },
196
220
  deps: {
197
221
  telemetry?: TelemetryClient;
198
222
  blobClient: BlobClientInterface;
199
223
  l1TxUtils: L1TxUtils;
200
224
  rollupContract: RollupContract;
201
- slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
225
+ slashingProposerContract: SlashingProposerContract | undefined;
202
226
  governanceProposerContract: GovernanceProposerContract;
203
- slashFactoryContract: SlashFactoryContract;
204
227
  epochCache: EpochCache;
205
228
  dateProvider: DateProvider;
206
229
  metrics: SequencerPublisherMetrics;
@@ -212,6 +235,8 @@ export class SequencerPublisher {
212
235
  this.log = deps.log ?? createLogger('sequencer:publisher');
213
236
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
214
237
  this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
238
+ this.previousL1BlockWaitTimeoutMs = config.sequencerPublisherPreviousL1BlockWaitTimeoutMs;
239
+ this.previousL1BlockWaitPollIntervalMs = config.sequencerPublisherPreviousL1BlockWaitPollIntervalMs;
215
240
  this.dateProvider = deps.dateProvider;
216
241
  this.epochCache = deps.epochCache;
217
242
  this.lastActions = deps.lastActions;
@@ -235,14 +260,12 @@ export class SequencerPublisher {
235
260
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
236
261
  this.slashingProposerContract = newSlashingProposer;
237
262
  });
238
- this.slashFactoryContract = deps.slashFactoryContract;
239
-
240
263
  // Initialize L1 fee analyzer for fisherman mode
241
264
  if (config.fishermanMode) {
242
265
  this.l1FeeAnalyzer = new L1FeeAnalyzer(
243
266
  this.l1TxUtils.client,
244
267
  deps.dateProvider,
245
- createLogger('sequencer:publisher:fee-analyzer'),
268
+ this.log.createChild('fee-analyzer'),
246
269
  );
247
270
  }
248
271
 
@@ -250,33 +273,112 @@ export class SequencerPublisher {
250
273
  this.feeAssetPriceOracle = new FeeAssetPriceOracle(
251
274
  this.l1TxUtils.client,
252
275
  this.rollupContract,
253
- createLogger('sequencer:publisher:price-oracle'),
276
+ this.log.createChild('price-oracle'),
254
277
  );
255
278
 
256
279
  // Initialize failed L1 tx store (optional, for test networks)
257
280
  this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
281
+
282
+ this.bundleSimulator = new SequencerBundleSimulator({
283
+ getL1TxUtils: () => this.l1TxUtils,
284
+ rollupContract: this.rollupContract,
285
+ epochCache: this.epochCache,
286
+ log: this.log.createChild('bundle-simulator'),
287
+ });
258
288
  }
259
289
 
260
290
  /**
261
- * Backs up a failed L1 transaction to the configured store for debugging.
262
- * Does nothing if no store is configured.
291
+ * Logs the gas-pricing data of a failed L1 transaction at warn so underpricing is diagnosable
292
+ * from logs even with no failed-tx store configured — and backs the record up to the store when
293
+ * one is. When captureFeeSummary is true, also records the fee data of the already-mined L1
294
+ * blocks in the target slot's inclusion window.
263
295
  */
264
- private backupFailedTx(failedTx: Omit<FailedL1Tx, 'timestamp'>): void {
265
- if (!this.failedTxStore) {
266
- return;
267
- }
268
-
296
+ private backupFailedTx(
297
+ failedTx: Omit<FailedL1Tx, 'timestamp'>,
298
+ opts?: { captureFeeSummary?: boolean; targetSlot?: SlotNumber; sharedFeeSummary?: FailedL1Tx['gasInfo'] },
299
+ ): void {
269
300
  const tx: FailedL1Tx = {
270
301
  ...failedTx,
271
302
  timestamp: Date.now(),
272
303
  };
273
304
 
274
305
  // Fire and forget - don't block on backup
275
- void this.failedTxStore
276
- .then(store => store?.saveFailedTx(tx))
277
- .catch(err => {
306
+ void (async () => {
307
+ try {
308
+ // Prefer a pre-captured summary (shared across a batch of failures in the same slot) so we
309
+ // don't re-read the fee window per record. A capture error must not lose the record itself.
310
+ const feeSummary =
311
+ opts?.sharedFeeSummary ??
312
+ (opts?.captureFeeSummary
313
+ ? await this.captureFeeEnvironment(opts.targetSlot).catch(() => undefined)
314
+ : undefined);
315
+ if (feeSummary) {
316
+ tx.gasInfo = { ...tx.gasInfo, ...feeSummary };
317
+ }
318
+ if (tx.gasInfo) {
319
+ this.log.warn(`Gas pricing data for failed L1 tx (${tx.failureType})`, {
320
+ failureType: tx.failureType,
321
+ actions: tx.context.actions,
322
+ slot: tx.context.slot,
323
+ ...tx.gasInfo,
324
+ ...tx.timing,
325
+ });
326
+ }
327
+ const store = await this.failedTxStore;
328
+ if (store) {
329
+ await store.saveFailedTx(tx);
330
+ }
331
+ } catch (err) {
278
332
  this.log.warn(`Failed to backup failed L1 tx to store`, err);
279
- });
333
+ }
334
+ })();
335
+ }
336
+
337
+ /**
338
+ * Captures per-block fee data for the L1 blocks in the target slot's inclusion window (the blocks the
339
+ * tx could have landed in) for underpricing diagnostics. Reads only already-mined blocks, so it never
340
+ * waits on the chain. Safe to call off the critical path: the underlying capture never throws, and this
341
+ * returns undefined when there is no target slot or the window is not yet mined (e.g. an early send
342
+ * failure), in which case the record simply carries no window data.
343
+ */
344
+ private async captureFeeEnvironment(targetL2Slot: SlotNumber | undefined): Promise<FailedL1Tx['gasInfo']> {
345
+ if (targetL2Slot === undefined) {
346
+ return undefined;
347
+ }
348
+ const l1Constants = this.epochCache.getL1Constants();
349
+ // The inclusion window is [start of slot N, start of slot N+1): all L1 blocks that can include a tx
350
+ // for this L2 slot. getTimestampForSlot returns seconds, matching block.timestamp.
351
+ const windowStartS = getTimestampForSlot(targetL2Slot, l1Constants);
352
+ const windowEndS = getTimestampForSlot(SlotNumber(Number(targetL2Slot) + 1), l1Constants);
353
+ const windowBlocks = await captureWindowBlockFees(this.l1TxUtils.client, windowStartS, windowEndS);
354
+ if (windowBlocks.length === 0) {
355
+ return undefined;
356
+ }
357
+ return { windowBlocks };
358
+ }
359
+
360
+ /** Computes timing info relative to the L2 slot deadline. */
361
+ private computeTimingInfo(targetL2Slot: SlotNumber | undefined): FailedL1Tx['timing'] {
362
+ if (targetL2Slot === undefined) {
363
+ return undefined;
364
+ }
365
+ const l1Constants = this.epochCache.getL1Constants();
366
+ const slotDeadlineS = getTimestampForSlot(SlotNumber(Number(targetL2Slot) + 1), l1Constants);
367
+ const slotDeadlineMs = Number(slotDeadlineS) * 1000;
368
+ return {
369
+ targetL2Slot: Number(targetL2Slot),
370
+ slotDeadlineTimestampS: slotDeadlineS,
371
+ msUntilSlotDeadline: slotDeadlineMs - this.dateProvider.now(),
372
+ };
373
+ }
374
+
375
+ /**
376
+ * Builds an id for a synthetic failure record (send-error/timeout) that has no on-chain tx hash.
377
+ * Includes the failure time so each attempt — including retries of the same slot — is stored as its
378
+ * own record rather than overwriting the previous one.
379
+ */
380
+ private failureRecordId(actions: string[], targetSlot: SlotNumber | undefined): Hex {
381
+ return keccak256(toHex(`${actions.join(',')}:${targetSlot ?? ''}:${Date.now()}`));
280
382
  }
281
383
 
282
384
  public getRollupContract(): RollupContract {
@@ -285,10 +387,14 @@ export class SequencerPublisher {
285
387
 
286
388
  /**
287
389
  * Gets the fee asset price modifier from the oracle.
288
- * Returns 0n if the oracle query fails.
390
+ *
391
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
392
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
393
+ * modifier matches the parent L1 will use when applying it.
394
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
289
395
  */
290
- public getFeeAssetPriceModifier(): Promise<bigint> {
291
- return this.feeAssetPriceOracle.computePriceModifier();
396
+ public getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12?: bigint): Promise<bigint> {
397
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
292
398
  }
293
399
 
294
400
  public getSenderAddress() {
@@ -302,14 +408,6 @@ export class SequencerPublisher {
302
408
  return this.l1FeeAnalyzer;
303
409
  }
304
410
 
305
- /**
306
- * Sets the proposer address to use for simulations in fisherman mode.
307
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
308
- */
309
- public setProposerAddressForSimulation(proposerAddress: EthAddress | undefined) {
310
- this.proposerAddressForSimulation = proposerAddress;
311
- }
312
-
313
411
  public addRequest(request: RequestWithExpiry) {
314
412
  this.requests.push(request);
315
413
  }
@@ -387,23 +485,26 @@ export class SequencerPublisher {
387
485
 
388
486
  /**
389
487
  * Sends all requests that are still valid.
488
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
489
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
490
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
491
+ * AutomineSequencer, which publishes synchronously within the current slot.
390
492
  * @returns one of:
391
493
  * - A receipt and stats if the tx succeeded
392
494
  * - a receipt and errorMsg if it failed on L1
393
495
  * - undefined if no valid requests are found OR the tx failed to send.
394
496
  */
395
497
  @trackSpan('SequencerPublisher.sendRequests')
396
- public async sendRequests(): Promise<SendRequestsResult | undefined> {
498
+ public async sendRequests(targetSlot?: SlotNumber): Promise<SendRequestsResult | undefined> {
397
499
  const requestsToProcess = [...this.requests];
398
500
  this.requests = [];
399
501
 
400
502
  if (this.interrupted || requestsToProcess.length === 0) {
401
503
  return undefined;
402
504
  }
403
- const currentL2Slot = this.getCurrentL2Slot();
505
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
404
506
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
405
507
  const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
406
- const validActions = validRequests.map(x => x.action);
407
508
  const expiredActions = requestsToProcess
408
509
  .filter(request => request.lastValidL2Slot < currentL2Slot)
409
510
  .map(x => x.action);
@@ -426,73 +527,101 @@ export class SequencerPublisher {
426
527
  return undefined;
427
528
  }
428
529
 
429
- // @note - we can only have one blob config per bundle
430
- // find requests with gas and blob configs
431
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
530
+ // Collect earliest txTimeoutAt across all requests.
432
531
  const gasConfigs = validRequests.filter(request => request.gasConfig).map(request => request.gasConfig);
433
- const blobConfigs = validRequests.filter(request => request.blobConfig).map(request => request.blobConfig);
434
-
435
- if (blobConfigs.length > 1) {
436
- throw new Error('Multiple blob configs found');
437
- }
438
-
439
- const blobConfig = blobConfigs[0];
440
-
441
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
442
- const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
443
- let gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
444
- // Cap at L1 block gas limit so the node accepts the tx ("gas limit too high" otherwise).
445
- const maxGas = MAX_L1_TX_LIMIT;
446
- if (gasLimit !== undefined && gasLimit > maxGas) {
447
- this.log.debug('Capping bundled tx gas limit to L1 max', {
448
- requested: gasLimit,
449
- capped: maxGas,
450
- });
451
- gasLimit = maxGas;
452
- }
453
532
  const txTimeoutAts = gasConfigs.map(g => g?.txTimeoutAt).filter((g): g is Date => g !== undefined);
454
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined; // earliest
455
- const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
533
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined;
456
534
 
457
535
  // Sort the requests so that proposals always go first
458
536
  // This ensures the committee gets precomputed correctly
459
537
  validRequests.sort((a, b) => compareActions(a.action, b.action));
460
538
 
461
539
  try {
462
- // Capture context for failed tx backup before sending
463
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
464
- const multicallData = encodeFunctionData({
465
- abi: multicall3Abi,
466
- functionName: 'aggregate3',
467
- args: [
468
- validRequests.map(r => ({
469
- target: r.request.to!,
470
- callData: r.request.data!,
471
- allowFailure: true,
472
- })),
473
- ],
474
- });
475
- const blobDataHex = blobConfig?.blobs?.map(b => toHex(b)) as Hex[] | undefined;
540
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
541
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
542
+
543
+ if (bundleResult.kind === 'aborted') {
544
+ this.logDroppedInSim(bundleResult.droppedRequests);
545
+ void this.backupDroppedInSim(bundleResult.droppedRequests, currentL2Slot).catch(err =>
546
+ this.log.error(`Failed to backup requests dropped in simulation`, err),
547
+ );
548
+ return undefined;
549
+ }
476
550
 
477
- const txContext = { multicallData, blobData: blobDataHex, l1BlockNumber };
551
+ const { requests, droppedRequests, gasLimit } =
552
+ bundleResult.kind === 'fallback'
553
+ ? {
554
+ requests: bundleResult.requests,
555
+ droppedRequests: bundleResult.droppedRequests,
556
+ gasLimit: MAX_L1_TX_LIMIT,
557
+ }
558
+ : bundleResult;
559
+
560
+ this.logDroppedInSim(droppedRequests);
561
+
562
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
563
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
564
+ const [blobConfig] = requests.filter(r => r.blobConfig).map(r => r.blobConfig);
565
+ const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
478
566
 
479
567
  this.log.debug('Forwarding transactions', {
480
- validRequests: validRequests.map(request => request.action),
568
+ requests: requests.map(request => request.action),
481
569
  txConfig,
482
570
  });
483
- const result = await this.forwardWithPublisherRotation(validRequests, txConfig, blobConfig);
571
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig, currentL2Slot);
484
572
  if (result === undefined) {
485
573
  return undefined;
486
574
  }
487
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(
488
- validRequests,
575
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
576
+ const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action)];
577
+ return {
489
578
  result,
490
- txContext,
491
- );
492
- return { result, expiredActions, sentActions: validActions, successfulActions, failedActions };
579
+ expiredActions,
580
+ sentActions: requests.map(x => x.action),
581
+ successfulActions,
582
+ failedActions: allFailedActions,
583
+ };
493
584
  } catch (err) {
494
585
  const viemError = formatViemError(err);
495
586
  this.log.error(`Failed to publish bundled transactions`, viemError);
587
+ if (err instanceof TimeoutError) {
588
+ const timeoutState = err instanceof L1TxTimeoutError ? err.txState : undefined;
589
+ void (async () => {
590
+ // The RPC is likely degraded right after a timeout, so back up without the block number
591
+ // rather than leaking an unhandled rejection.
592
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber().catch(() => 0n);
593
+ this.backupFailedTx(
594
+ {
595
+ id: this.failureRecordId(
596
+ validRequests.map(r => r.action),
597
+ currentL2Slot,
598
+ ),
599
+ failureType: 'timeout',
600
+ request: { to: MULTI_CALL_3_ADDRESS as Hex, data: '0x' as Hex },
601
+ l1BlockNumber,
602
+ error: { message: viemError.message, name: 'TimeoutError' },
603
+ context: {
604
+ actions: validRequests.map(r => r.action),
605
+ requests: validRequests
606
+ .filter(r => r.request.to !== null)
607
+ .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
608
+ sender: this.getSenderAddress().toString(),
609
+ slot: Number(currentL2Slot),
610
+ },
611
+ timing: this.computeTimingInfo(currentL2Slot),
612
+ gasInfo: timeoutState
613
+ ? {
614
+ sentGasPriceLadder: timeoutState.gasPriceHistory,
615
+ attempts: timeoutState.attempts,
616
+ gasLimit: timeoutState.gasLimit,
617
+ nonce: timeoutState.nonce,
618
+ }
619
+ : undefined,
620
+ },
621
+ { captureFeeSummary: true, targetSlot: currentL2Slot },
622
+ );
623
+ })();
624
+ }
496
625
  return undefined;
497
626
  } finally {
498
627
  try {
@@ -506,6 +635,54 @@ export class SequencerPublisher {
506
635
  }
507
636
  }
508
637
 
638
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */
639
+ private logDroppedInSim(dropped: DroppedRequest[]): void {
640
+ for (const drop of dropped) {
641
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
642
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
643
+ action: drop.request.action,
644
+ revertReason: revertReasonDecoded ?? drop.returnData,
645
+ revertReasonDecoded,
646
+ returnData: drop.returnData,
647
+ });
648
+ }
649
+ }
650
+
651
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */
652
+ private async backupDroppedInSim(dropped: DroppedRequest[], targetSlot?: SlotNumber): Promise<void> {
653
+ if (dropped.length === 0) {
654
+ return;
655
+ }
656
+ // Invoked as `void backupDroppedInSim(...)` on the publish path, so it must not throw.
657
+ try {
658
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
659
+ // Every dropped entry failed in the same slot against the same L1 fee conditions, so capture
660
+ // the fee environment once and share it rather than re-reading the window per entry.
661
+ const sharedFeeSummary = await this.captureFeeEnvironment(targetSlot).catch(() => undefined);
662
+ const timing = this.computeTimingInfo(targetSlot);
663
+ for (const { request: req } of dropped) {
664
+ this.backupFailedTx(
665
+ {
666
+ id: keccak256(req.request.data!),
667
+ failureType: 'simulation',
668
+ request: { to: req.request.to! as Hex, data: req.request.data! },
669
+ l1BlockNumber,
670
+ error: { message: 'Bundle entry dropped: action reverted in sim' },
671
+ context: {
672
+ actions: [req.action],
673
+ sender: this.getSenderAddress().toString(),
674
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined,
675
+ },
676
+ timing,
677
+ },
678
+ { sharedFeeSummary },
679
+ );
680
+ }
681
+ } catch (err) {
682
+ this.log.warn(`Failed to back up dropped-in-sim entries`, err);
683
+ }
684
+ }
685
+
509
686
  /**
510
687
  * Forwards transactions via Multicall3, rotating to the next available publisher if a send
511
688
  * failure occurs (i.e. the tx never reached the chain).
@@ -515,20 +692,32 @@ export class SequencerPublisher {
515
692
  validRequests: RequestWithExpiry[],
516
693
  txConfig: RequestWithExpiry['gasConfig'],
517
694
  blobConfig: L1BlobInputs | undefined,
695
+ targetSlot?: SlotNumber,
518
696
  ) {
697
+ if (!txConfig?.gasLimit) {
698
+ throw new Error('gasLimit is required for bundled transactions');
699
+ }
700
+ const txConfigWithGasLimit = txConfig as L1TxConfig & { gasLimit: bigint };
701
+
519
702
  const triedAddresses: EthAddress[] = [];
520
703
  let currentPublisher = this.l1TxUtils;
521
704
 
522
705
  while (true) {
706
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
707
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
708
+ triedAddresses: triedAddresses.map(a => a.toString()),
709
+ });
710
+ return undefined;
711
+ }
523
712
  triedAddresses.push(currentPublisher.getSenderAddress());
713
+
524
714
  try {
525
715
  const result = await Multicall3.forward(
526
716
  validRequests.map(r => r.request),
527
717
  currentPublisher,
528
- txConfig,
718
+ txConfigWithGasLimit,
529
719
  blobConfig,
530
- this.rollupContract.address,
531
- this.log,
720
+ { gasLimitRequired: true },
532
721
  );
533
722
  this.l1TxUtils = currentPublisher;
534
723
  return result;
@@ -536,9 +725,17 @@ export class SequencerPublisher {
536
725
  if (err instanceof TimeoutError) {
537
726
  throw err;
538
727
  }
728
+ if (err instanceof MulticallForwarderRevertedError) {
729
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
730
+ transactionHash: err.receipt.transactionHash,
731
+ });
732
+ this.backupRevertFailure(validRequests, err, currentPublisher, targetSlot);
733
+ return undefined;
734
+ }
539
735
  const viemError = formatViemError(err);
540
736
  if (!this.getNextPublisher) {
541
737
  this.log.error('Failed to publish bundled transactions', viemError);
738
+ this.backupSendFailure(validRequests, viemError, currentPublisher, targetSlot);
542
739
  return undefined;
543
740
  }
544
741
  this.log.warn(
@@ -547,7 +744,12 @@ export class SequencerPublisher {
547
744
  );
548
745
  const nextPublisher = await this.getNextPublisher([...triedAddresses]);
549
746
  if (!nextPublisher) {
550
- this.log.error('All available publishers exhausted, failed to publish bundled transactions');
747
+ this.log.error(
748
+ `All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`,
749
+ viemError,
750
+ { triedAddresses: triedAddresses.map(a => a.toString()) },
751
+ );
752
+ this.backupSendFailure(validRequests, viemError, currentPublisher, targetSlot);
551
753
  return undefined;
552
754
  }
553
755
  currentPublisher = nextPublisher;
@@ -555,91 +757,179 @@ export class SequencerPublisher {
555
757
  }
556
758
  }
557
759
 
760
+ /** Backs up an on-chain revert failure to the failed tx store. */
761
+ private backupRevertFailure(
762
+ requests: RequestWithExpiry[],
763
+ err: MulticallForwarderRevertedError,
764
+ publisher: L1TxUtils,
765
+ targetSlot?: SlotNumber,
766
+ ): void {
767
+ this.backupFailedTx(
768
+ {
769
+ id: err.receipt.transactionHash,
770
+ failureType: 'revert',
771
+ request: { to: MULTI_CALL_3_ADDRESS as Hex, data: '0x' as Hex },
772
+ l1BlockNumber: err.receipt.blockNumber,
773
+ receipt: {
774
+ transactionHash: err.receipt.transactionHash,
775
+ blockNumber: err.receipt.blockNumber,
776
+ gasUsed: err.receipt.gasUsed,
777
+ status: 'reverted',
778
+ },
779
+ error: { message: err.message, name: err.name },
780
+ context: {
781
+ actions: requests.map(r => r.action),
782
+ requests: requests
783
+ .filter(r => r.request.to !== null)
784
+ .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
785
+ sender: publisher.getSenderAddress().toString(),
786
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined,
787
+ },
788
+ gasInfo: err.txState
789
+ ? {
790
+ sentGasPrice: err.txState.gasPrice,
791
+ gasLimit: err.txState.gasLimit,
792
+ nonce: err.txState.nonce,
793
+ }
794
+ : undefined,
795
+ timing: this.computeTimingInfo(targetSlot),
796
+ },
797
+ { captureFeeSummary: true, targetSlot },
798
+ );
799
+ }
800
+
801
+ /** Backs up a send failure (tx never reached chain) to the failed tx store. */
802
+ private backupSendFailure(
803
+ requests: RequestWithExpiry[],
804
+ error: FormattedViemError | Error,
805
+ publisher: L1TxUtils,
806
+ targetSlot?: SlotNumber,
807
+ ): void {
808
+ // If we can't get the block number, still back up without it.
809
+ void this.l1TxUtils
810
+ .getBlockNumber()
811
+ .catch(() => 0n)
812
+ .then(l1BlockNumber => {
813
+ this.backupFailedTx(
814
+ {
815
+ id: this.failureRecordId(
816
+ requests.map(r => r.action),
817
+ targetSlot,
818
+ ),
819
+ failureType: 'send-error',
820
+ request: { to: MULTI_CALL_3_ADDRESS as Hex, data: '0x' as Hex },
821
+ l1BlockNumber,
822
+ error: {
823
+ message: error.message,
824
+ name: 'name' in error ? error.name : undefined,
825
+ },
826
+ context: {
827
+ actions: requests.map(r => r.action),
828
+ requests: requests
829
+ .filter(r => r.request.to !== null)
830
+ .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
831
+ sender: publisher.getSenderAddress().toString(),
832
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined,
833
+ },
834
+ timing: this.computeTimingInfo(targetSlot),
835
+ },
836
+ { captureFeeSummary: true, targetSlot },
837
+ );
838
+ });
839
+ }
840
+
558
841
  /*
559
- * Schedules sending all enqueued requests at (or after) the given timestamp.
560
- * Uses InterruptibleSleep so it can be cancelled via interrupt().
561
- * Returns the promise for the L1 response (caller should NOT await this in the work loop).
842
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
562
843
  */
563
- public async sendRequestsAt(submitAfter: Date): Promise<SendRequestsResult | undefined> {
564
- const ms = submitAfter.getTime() - this.dateProvider.now();
565
- if (ms > 0) {
566
- this.log.debug(`Sleeping ${ms}ms before sending requests`, { submitAfter });
567
- await this.interruptibleSleep.sleep(ms);
568
- }
844
+ public async sendRequestsAt(targetSlot: SlotNumber): Promise<SendRequestsResult | undefined> {
845
+ await this.waitForTargetSlot(targetSlot);
569
846
  if (this.interrupted) {
570
847
  return undefined;
571
848
  }
572
- return this.sendRequests();
849
+
850
+ return this.sendRequests(targetSlot);
851
+ }
852
+
853
+ /**
854
+ * Sleeps until one L1 slot before the L2 slot boundary, and then waits for that L1 block
855
+ * to be mined, so we don't risk being included in it. If that block never gets mined after
856
+ * a timeout, we assume it got skipped on L1, so we send the tx anyway.
857
+ */
858
+ private async waitForTargetSlot(targetSlot: SlotNumber): Promise<void> {
859
+ const l1Constants = this.epochCache.getL1Constants();
860
+ const nowInSeconds = this.dateProvider.nowInSeconds();
861
+ const startOfTargetSlotTs = getTimestampForSlot(targetSlot, l1Constants);
862
+ const previousL1BlockTs = startOfTargetSlotTs - this.ethereumSlotDuration;
863
+ const waitDeadlineTs = previousL1BlockTs + BigInt(this.previousL1BlockWaitTimeoutMs / 1000);
864
+ const logCtx = { targetSlot, startOfTargetSlotTs, nowInSeconds, previousL1BlockTs, waitDeadlineTs };
865
+
866
+ // Check if we are already past time
867
+ if (nowInSeconds >= startOfTargetSlotTs) {
868
+ this.log.verbose(`Target slot ${targetSlot} already started, sending requests immediately`, logCtx);
869
+ return;
870
+ }
871
+
872
+ // Otherwise we wait
873
+ this.log.debug(`Waiting for slot ${targetSlot} before sending requests`, logCtx);
874
+
875
+ // Wait until previous L1 block timestamp first
876
+ const sleepMs = (Number(previousL1BlockTs) - nowInSeconds) * 1000;
877
+ if (sleepMs > 0 && !this.interrupted) {
878
+ this.log.trace(`Sleeping ${sleepMs}ms before waiting for previous L1 block`, logCtx);
879
+ await this.interruptibleSleep.sleep(sleepMs);
880
+ }
881
+
882
+ // Then loop until we see the previous L1 block, so we know that we cannot be included in it.
883
+ // We time out after a while, once we are sure that that block is skipped in L1.
884
+ while (!this.interrupted) {
885
+ try {
886
+ const nowInSeconds = this.dateProvider.nowInSeconds();
887
+ logCtx.nowInSeconds = nowInSeconds;
888
+
889
+ if (nowInSeconds >= waitDeadlineTs) {
890
+ this.log.warn(`Timed out waiting for previous L1 block before sending requests, proceeding`, logCtx);
891
+ return;
892
+ }
893
+
894
+ const latestBlockTs = await this.l1TxUtils.getBlock().then(b => b.timestamp);
895
+ if (latestBlockTs >= previousL1BlockTs) {
896
+ this.log.debug(`Previous L1 block mined, proceeding to send requests`, { ...logCtx, latestBlockTs });
897
+ return;
898
+ }
899
+ this.log.trace(`Previous L1 block not mined yet, continuing to wait`, { ...logCtx, latestBlockTs });
900
+ } catch (err) {
901
+ this.log.error(`Error while waiting for previous L1 block before sending requests; retrying`, err, logCtx);
902
+ } finally {
903
+ await this.interruptibleSleep.sleep(this.previousL1BlockWaitPollIntervalMs);
904
+ }
905
+ }
573
906
  }
574
907
 
575
908
  private callbackBundledTransactions(
576
909
  requests: RequestWithExpiry[],
577
- result: { receipt: TransactionReceipt; errorMsg?: string } | FormattedViemError | undefined,
578
- txContext: { multicallData: Hex; blobData?: Hex[]; l1BlockNumber: bigint },
910
+ result: { receipt: TransactionReceipt; multicallData: Hex },
579
911
  ) {
580
912
  const actionsListStr = requests.map(r => r.action).join(', ');
581
- if (result instanceof FormattedViemError) {
582
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
583
- this.backupFailedTx({
584
- id: keccak256(txContext.multicallData),
585
- failureType: 'send-error',
586
- request: { to: MULTI_CALL_3_ADDRESS, data: txContext.multicallData },
587
- blobData: txContext.blobData,
588
- l1BlockNumber: txContext.l1BlockNumber.toString(),
589
- error: { message: result.message, name: result.name },
590
- context: {
591
- actions: requests.map(r => r.action),
592
- requests: requests.map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
593
- sender: this.getSenderAddress().toString(),
594
- },
595
- });
596
- return { failedActions: requests.map(r => r.action) };
597
- } else {
598
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
599
- result,
600
- requests: requests.map(r => ({
601
- ...r,
602
- // Avoid logging large blob data
603
- blobConfig: r.blobConfig
604
- ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
605
- : undefined,
606
- })),
607
- });
608
- const successfulActions: Action[] = [];
609
- const failedActions: Action[] = [];
610
- for (const request of requests) {
611
- if (request.checkSuccess(request.request, result)) {
612
- successfulActions.push(request.action);
613
- } else {
614
- failedActions.push(request.action);
615
- }
616
- }
617
- // Single backup for the whole reverted tx
618
- if (failedActions.length > 0 && result?.receipt?.status === 'reverted') {
619
- this.backupFailedTx({
620
- id: result.receipt.transactionHash,
621
- failureType: 'revert',
622
- request: { to: MULTI_CALL_3_ADDRESS, data: txContext.multicallData },
623
- blobData: txContext.blobData,
624
- l1BlockNumber: result.receipt.blockNumber.toString(),
625
- receipt: {
626
- transactionHash: result.receipt.transactionHash,
627
- blockNumber: result.receipt.blockNumber.toString(),
628
- gasUsed: (result.receipt.gasUsed ?? 0n).toString(),
629
- status: 'reverted',
630
- },
631
- error: { message: result.errorMsg ?? 'Transaction reverted' },
632
- context: {
633
- actions: failedActions,
634
- requests: requests
635
- .filter(r => failedActions.includes(r.action))
636
- .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
637
- sender: this.getSenderAddress().toString(),
638
- },
639
- });
913
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
914
+ result,
915
+ requests: requests.map(r => ({
916
+ ...r,
917
+ // Avoid logging large blob data
918
+ blobConfig: r.blobConfig
919
+ ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
920
+ : undefined,
921
+ })),
922
+ });
923
+ const successfulActions: Action[] = [];
924
+ const failedActions: Action[] = [];
925
+ for (const request of requests) {
926
+ if (request.checkSuccess(request.request, result)) {
927
+ successfulActions.push(request.action);
928
+ } else {
929
+ failedActions.push(request.action);
640
930
  }
641
- return { successfulActions, failedActions };
642
931
  }
932
+ return { successfulActions, failedActions };
643
933
  }
644
934
 
645
935
  /**
@@ -647,30 +937,27 @@ export class SequencerPublisher {
647
937
  * @param tipArchive - The archive to check
648
938
  * @returns The slot and block number if it is possible to propose, undefined otherwise
649
939
  */
650
- public canProposeAt(
651
- tipArchive: Fr,
652
- msgSender: EthAddress,
653
- opts: {
654
- forcePendingCheckpointNumber?: CheckpointNumber;
655
- forceArchive?: { checkpointNumber: CheckpointNumber; archive: Fr };
656
- pipelined?: boolean;
657
- } = {},
658
- ) {
940
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
659
941
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
660
- const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
942
+ // These errors are expected when we cannot actually propose right now — usually because our
943
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
944
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
945
+ // skip the proposal; we do NOT treat these as bugs.
946
+ const expectedErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
661
947
 
662
- const pipelined = opts.pipelined ?? this.epochCache.isProposerPipeliningEnabled();
663
- const slotOffset = pipelined ? this.aztecSlotDuration : 0n;
948
+ const slotOffset = this.aztecSlotDuration;
664
949
  const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
665
950
 
666
951
  return this.rollupContract
667
- .canProposeAt(tipArchive.toBuffer(), msgSender.toString(), nextL1SlotTs, {
668
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
669
- forceArchive: opts.forceArchive,
670
- })
952
+ .canProposeAt(
953
+ tipArchive.toBuffer(),
954
+ msgSender.toString(),
955
+ nextL1SlotTs,
956
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
957
+ )
671
958
  .catch(err => {
672
- if (err instanceof FormattedViemError && ignoredErrors.find(e => err.message.includes(e))) {
673
- this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find(e => err.message.includes(e))}`, {
959
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
960
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
674
961
  error: err.message,
675
962
  });
676
963
  } else {
@@ -689,13 +976,13 @@ export class SequencerPublisher {
689
976
  @trackSpan('SequencerPublisher.validateBlockHeader')
690
977
  public async validateBlockHeader(
691
978
  header: CheckpointHeader,
692
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
979
+ simulationOverridesPlan?: SimulationOverridesPlan,
693
980
  ): Promise<void> {
694
981
  const flags = { ignoreDA: true, ignoreSignatures: true };
695
982
 
696
983
  const args = [
697
984
  header.toViem(),
698
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
985
+ CommitteeAttestationsAndSigners.packAttestations([]),
699
986
  [], // no signers
700
987
  Signature.empty().toViemSignature(),
701
988
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -703,10 +990,9 @@ export class SequencerPublisher {
703
990
  flags,
704
991
  ] as const;
705
992
 
706
- const ts = this.getSimulationTimestamp(header.slotNumber);
707
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
708
- opts?.forcePendingCheckpointNumber,
709
- );
993
+ const l1Constants = this.epochCache.getL1Constants();
994
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
995
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
710
996
  let balance = 0n;
711
997
  if (this.config.fishermanMode) {
712
998
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -813,18 +1099,22 @@ export class SequencerPublisher {
813
1099
 
814
1100
  // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
815
1101
  this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
816
- this.backupFailedTx({
817
- id: keccak256(request.data!),
818
- failureType: 'simulation',
819
- request: { to: request.to!, data: request.data!, value: request.value?.toString() },
820
- l1BlockNumber: l1BlockNumber.toString(),
821
- error: { message: viemError.message, name: viemError.name },
822
- context: {
823
- actions: [`invalidate-${reason}`],
824
- checkpointNumber,
825
- sender: this.getSenderAddress().toString(),
1102
+ this.backupFailedTx(
1103
+ {
1104
+ id: keccak256(request.data!),
1105
+ failureType: 'simulation',
1106
+ request: { to: request.to!, data: request.data!, value: request.value },
1107
+ l1BlockNumber,
1108
+ error: { message: viemError.message, name: viemError.name },
1109
+ context: {
1110
+ actions: [`invalidate-${reason}`],
1111
+ checkpointNumber,
1112
+ sender: this.getSenderAddress().toString(),
1113
+ },
1114
+ timing: this.computeTimingInfo(this.getCurrentL2Slot()),
826
1115
  },
827
- });
1116
+ { captureFeeSummary: true, targetSlot: this.getCurrentL2Slot() },
1117
+ );
828
1118
  throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, { cause: viemError });
829
1119
  }
830
1120
  }
@@ -838,9 +1128,11 @@ export class SequencerPublisher {
838
1128
  const logData = { ...checkpoint, reason };
839
1129
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
840
1130
 
841
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
842
- validationResult.attestations,
843
- ).getPackedAttestations();
1131
+ // Use the exact packed tuple posted to L1 verbatim. A repack via `packAttestations` is not a
1132
+ // byte-faithful inverse of `fromPacked` (a canonicalized yParity byte or an all-zero signature slot
1133
+ // round-trips differently), so it would diverge from the stored `attestationsHash` and revert the
1134
+ // invalidation.
1135
+ const attestationsAndSigners = validationResult.verbatimAttestations;
844
1136
 
845
1137
  if (reason === 'invalid-attestation') {
846
1138
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -861,43 +1153,11 @@ export class SequencerPublisher {
861
1153
  }
862
1154
  }
863
1155
 
864
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */
865
- @trackSpan('SequencerPublisher.validateCheckpointForSubmission')
866
- public async validateCheckpointForSubmission(
867
- checkpoint: Checkpoint,
868
- attestationsAndSigners: CommitteeAttestationsAndSigners,
869
- attestationsAndSignersSignature: Signature,
870
- options: {
871
- forcePendingCheckpointNumber?: CheckpointNumber;
872
- forceProposedFeeHeader?: { checkpointNumber: CheckpointNumber; feeHeader: FeeHeader };
873
- },
874
- ): Promise<void> {
875
- const blobFields = checkpoint.toBlobFields();
876
- const blobs = await getBlobsPerL1Block(blobFields);
877
- const blobInput = getPrefixedEthBlobCommitments(blobs);
878
-
879
- const args = [
880
- {
881
- header: checkpoint.header.toViem(),
882
- archive: toHex(checkpoint.archive.root.toBuffer()),
883
- oracleInput: {
884
- feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
885
- },
886
- },
887
- attestationsAndSigners.getPackedAttestations(),
888
- attestationsAndSigners.getSigners().map(signer => signer.toString()),
889
- attestationsAndSignersSignature.toViemSignature(),
890
- blobInput,
891
- ] as const;
892
-
893
- await this.simulateProposeTx(args, options);
894
- }
895
-
896
1156
  private async enqueueCastSignalHelper(
897
1157
  slotNumber: SlotNumber,
898
1158
  signalType: GovernanceSignalAction,
899
1159
  payload: EthAddress,
900
- base: IEmpireBase,
1160
+ base: GovernanceProposerContract,
901
1161
  signerAddress: EthAddress,
902
1162
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
903
1163
  ): Promise<boolean> {
@@ -923,34 +1183,28 @@ export class SequencerPublisher {
923
1183
  return false;
924
1184
  }
925
1185
 
926
- if (await this.isPayloadEmpty(payload)) {
1186
+ if (await base.isPayloadEmpty(payload)) {
927
1187
  this.log.warn(`Skipping vote cast for payload with empty code`);
928
1188
  return false;
929
1189
  }
930
1190
 
931
- // Check if payload was already submitted to governance
932
- const cacheKey = payload.toString();
933
- if (!this.payloadProposedCache.has(cacheKey)) {
934
- try {
935
- const l1StartBlock = await this.rollupContract.getL1StartBlock();
936
- const proposed = await retry(
937
- () => base.hasPayloadBeenProposed(payload.toString(), l1StartBlock),
938
- 'Check if payload was proposed',
939
- makeBackoff([0, 1, 2]),
940
- this.log,
941
- true,
942
- );
943
- if (proposed) {
944
- this.payloadProposedCache.add(cacheKey);
945
- }
946
- } catch (err) {
947
- this.log.warn(`Failed to check if payload ${payload} was proposed after retries, skipping signal`, err);
948
- return false;
949
- }
1191
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
1192
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
1193
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
1194
+ // the same payload in a future round.
1195
+ let proposed = false;
1196
+ try {
1197
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
1198
+ } catch (err) {
1199
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
1200
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
1201
+ // participation entirely; failing open at worst produces a duplicate signal that the
1202
+ // contract will simply count alongside others in the round.
1203
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
950
1204
  }
951
1205
 
952
- if (this.payloadProposedCache.has(cacheKey)) {
953
- this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
1206
+ if (proposed) {
1207
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
954
1208
  return false;
955
1209
  }
956
1210
 
@@ -972,45 +1226,19 @@ export class SequencerPublisher {
972
1226
  lastValidL2Slot: slotNumber,
973
1227
  });
974
1228
 
975
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
976
- const timestamp = this.getSimulationTimestamp(slotNumber);
977
-
978
- try {
979
- await this.l1TxUtils.simulate(request, { time: timestamp }, [], mergeAbis([request.abi ?? [], ErrorsAbi]));
980
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, { request });
981
- } catch (err) {
982
- const viemError = formatViemError(err);
983
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, viemError, {
984
- simulationTimestamp: timestamp,
985
- l1BlockNumber,
986
- });
987
- this.backupFailedTx({
988
- id: keccak256(request.data!),
989
- failureType: 'simulation',
990
- request: { to: request.to!, data: request.data!, value: request.value?.toString() },
991
- l1BlockNumber: l1BlockNumber.toString(),
992
- error: { message: viemError.message, name: viemError.name },
993
- context: {
994
- actions: [action],
995
- slot: slotNumber,
996
- sender: this.getSenderAddress().toString(),
997
- },
998
- });
999
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
1000
- }
1001
-
1002
1229
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
1003
1230
  this.addRequest({
1004
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
1005
1231
  action,
1006
1232
  request,
1007
1233
  lastValidL2Slot: slotNumber,
1008
1234
  checkSuccess: (_request, result) => {
1009
1235
  const success =
1010
1236
  result &&
1011
- result.receipt &&
1012
- result.receipt.status === 'success' &&
1013
- tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
1237
+ extractEventSuccess(result.receipt, {
1238
+ address: base.address.toString(),
1239
+ abi: EmpireBaseAbi,
1240
+ eventName: 'SignalCast',
1241
+ });
1014
1242
 
1015
1243
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
1016
1244
  if (!success) {
@@ -1032,17 +1260,6 @@ export class SequencerPublisher {
1032
1260
  return true;
1033
1261
  }
1034
1262
 
1035
- private async isPayloadEmpty(payload: EthAddress): Promise<boolean> {
1036
- const key = payload.toString();
1037
- const cached = this.isPayloadEmptyCache.get(key);
1038
- if (cached) {
1039
- return cached;
1040
- }
1041
- const isEmpty = !(await this.l1TxUtils.getCode(payload));
1042
- this.isPayloadEmptyCache.set(key, isEmpty);
1043
- return isEmpty;
1044
- }
1045
-
1046
1263
  /**
1047
1264
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
1048
1265
  * @param slotNumber - The slot number to cast a signal for.
@@ -1064,6 +1281,47 @@ export class SequencerPublisher {
1064
1281
  );
1065
1282
  }
1066
1283
 
1284
+ /**
1285
+ * Enqueues a `prune()` transaction if the rollup is prunable at the given slot's L1 timestamp.
1286
+ * `prune()` is permissionless and idempotent — if the chain is no longer prunable by send time the
1287
+ * bundle simulation usually drops the entry; on a node without `eth_simulateV1` the bundle is sent
1288
+ * as-is and the prune reverts `Rollup__NothingToPrune` inside `aggregate3(allowFailure: true)`
1289
+ * (a failed action, never a whole-tx revert). Used by the failed-sync fallback so a stuck pending
1290
+ * chain (e.g. bad data blocking sync) can be wound back to recover.
1291
+ * @returns true if a prune request was enqueued, false otherwise.
1292
+ */
1293
+ public async enqueuePruneIfPrunable(slotNumber: SlotNumber): Promise<boolean> {
1294
+ if (this.lastActions['prune'] === slotNumber) {
1295
+ this.log.debug(`Skipping duplicate prune for slot ${slotNumber}`, { slotNumber });
1296
+ return false;
1297
+ }
1298
+ // Use the SAME timestamp the bundle simulator overrides block.timestamp with at send time
1299
+ // (sequencer-bundle-simulator.ts) so this upfront check and the send-time sim agree. Slot-start
1300
+ // and last-L1-slot both fall within the same L2 slot (and epoch, which is what `canPruneAtTime`
1301
+ // derives), so they agree today; matching the simulator keeps it robust if the contract ever uses
1302
+ // the timestamp more granularly.
1303
+ const ts = getLastL1SlotTimestampForL2Slot(slotNumber, this.epochCache.getL1Constants());
1304
+ const canPrune = await this.rollupContract.canPruneAtTime(ts).catch(err => {
1305
+ this.log.error(`Failed to check canPruneAtTime for slot ${slotNumber}`, err, { slotNumber });
1306
+ return false;
1307
+ });
1308
+ if (!canPrune) {
1309
+ this.log.debug(`Rollup not prunable at slot ${slotNumber}`, { slotNumber });
1310
+ return false;
1311
+ }
1312
+ const request: L1TxRequest = {
1313
+ to: this.rollupContract.address,
1314
+ data: encodeFunctionData({ abi: RollupAbi, functionName: 'prune', args: [] }),
1315
+ };
1316
+ this.log.info(`Enqueuing rollup prune for slot ${slotNumber}`, { slotNumber });
1317
+ return this.enqueueRequest(
1318
+ 'prune',
1319
+ request,
1320
+ { address: this.rollupContract.address, abi: RollupAbi, eventName: 'PrunedPending' },
1321
+ slotNumber,
1322
+ );
1323
+ }
1324
+
1067
1325
  /** Enqueues all slashing actions as returned by the slasher client. */
1068
1326
  public async enqueueSlashingActions(
1069
1327
  actions: ProposerSlashAction[],
@@ -1078,55 +1336,6 @@ export class SequencerPublisher {
1078
1336
 
1079
1337
  for (const action of actions) {
1080
1338
  switch (action.type) {
1081
- case 'vote-empire-payload': {
1082
- if (this.slashingProposerContract?.type !== 'empire') {
1083
- this.log.error('Cannot vote for empire payload on non-empire slashing contract');
1084
- break;
1085
- }
1086
- this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
1087
- signerAddress,
1088
- });
1089
- await this.enqueueCastSignalHelper(
1090
- slotNumber,
1091
- 'empire-slashing-signal',
1092
- action.payload,
1093
- this.slashingProposerContract,
1094
- signerAddress,
1095
- signer,
1096
- );
1097
- break;
1098
- }
1099
-
1100
- case 'create-empire-payload': {
1101
- this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, { slotNumber, signerAddress });
1102
- const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
1103
- await this.simulateAndEnqueueRequest(
1104
- 'create-empire-payload',
1105
- request,
1106
- (receipt: TransactionReceipt) =>
1107
- !!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs),
1108
- slotNumber,
1109
- );
1110
- break;
1111
- }
1112
-
1113
- case 'execute-empire-payload': {
1114
- this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, { slotNumber, signerAddress });
1115
- if (this.slashingProposerContract?.type !== 'empire') {
1116
- this.log.error('Cannot execute slashing payload on non-empire slashing contract');
1117
- return false;
1118
- }
1119
- const empireSlashingProposer = this.slashingProposerContract as EmpireSlashingProposerContract;
1120
- const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
1121
- await this.simulateAndEnqueueRequest(
1122
- 'execute-empire-payload',
1123
- request,
1124
- (receipt: TransactionReceipt) => !!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs),
1125
- slotNumber,
1126
- );
1127
- break;
1128
- }
1129
-
1130
1339
  case 'vote-offenses': {
1131
1340
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
1132
1341
  slotNumber,
@@ -1134,17 +1343,20 @@ export class SequencerPublisher {
1134
1343
  votesCount: action.votes.length,
1135
1344
  signerAddress,
1136
1345
  });
1137
- if (this.slashingProposerContract?.type !== 'tally') {
1138
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1346
+ if (!this.slashingProposerContract) {
1347
+ this.log.error('No slashing proposer contract available');
1139
1348
  return false;
1140
1349
  }
1141
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
1142
1350
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1143
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
1144
- await this.simulateAndEnqueueRequest(
1351
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1352
+ this.enqueueRequest(
1145
1353
  'vote-offenses',
1146
1354
  request,
1147
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1355
+ {
1356
+ address: this.slashingProposerContract.address.toString(),
1357
+ abi: SlashingProposerAbi,
1358
+ eventName: 'VoteCast',
1359
+ },
1148
1360
  slotNumber,
1149
1361
  );
1150
1362
  break;
@@ -1156,16 +1368,22 @@ export class SequencerPublisher {
1156
1368
  round: action.round,
1157
1369
  signerAddress,
1158
1370
  });
1159
- if (this.slashingProposerContract?.type !== 'tally') {
1160
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1371
+ if (!this.slashingProposerContract) {
1372
+ this.log.error('No slashing proposer contract available');
1161
1373
  return false;
1162
1374
  }
1163
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
1164
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
1165
- await this.simulateAndEnqueueRequest(
1375
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1376
+ action.round,
1377
+ action.committees,
1378
+ );
1379
+ this.enqueueRequest(
1166
1380
  'execute-slash',
1167
- request,
1168
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1381
+ executeRequest,
1382
+ {
1383
+ address: this.slashingProposerContract.address.toString(),
1384
+ abi: SlashingProposerAbi,
1385
+ eventName: 'RoundExecuted',
1386
+ },
1169
1387
  slotNumber,
1170
1388
  );
1171
1389
  break;
@@ -1181,16 +1399,12 @@ export class SequencerPublisher {
1181
1399
  return true;
1182
1400
  }
1183
1401
 
1184
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1402
+ /** Enqueues a proposal for a checkpoint on L1 */
1185
1403
  public async enqueueProposeCheckpoint(
1186
1404
  checkpoint: Checkpoint,
1187
1405
  attestationsAndSigners: CommitteeAttestationsAndSigners,
1188
1406
  attestationsAndSignersSignature: Signature,
1189
- opts: {
1190
- txTimeoutAt?: Date;
1191
- forcePendingCheckpointNumber?: CheckpointNumber;
1192
- forceProposedFeeHeader?: { checkpointNumber: CheckpointNumber; feeHeader: FeeHeader };
1193
- } = {},
1407
+ opts: EnqueueProposeCheckpointOpts = {},
1194
1408
  ): Promise<void> {
1195
1409
  const checkpointHeader = checkpoint.header;
1196
1410
 
@@ -1206,29 +1420,11 @@ export class SequencerPublisher {
1206
1420
  feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
1207
1421
  };
1208
1422
 
1209
- try {
1210
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
1211
- // This means that we can avoid the simulation issues in later checks.
1212
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
1213
- // make time consistency checks break.
1214
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
1215
- await this.validateCheckpointForSubmission(
1216
- checkpoint,
1217
- attestationsAndSigners,
1218
- attestationsAndSignersSignature,
1219
- opts,
1220
- );
1221
- } catch (err: any) {
1222
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
1223
- ...checkpoint.getStats(),
1224
- slotNumber: checkpoint.header.slotNumber,
1225
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
1226
- });
1227
- throw err;
1228
- }
1229
-
1230
- this.log.verbose(`Enqueuing checkpoint propose transaction`, { ...checkpoint.toCheckpointInfo(), ...opts });
1231
- await this.addProposeTx(checkpoint, proposeTxArgs, opts);
1423
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1424
+ ...checkpoint.toCheckpointInfo(),
1425
+ txTimeoutAt: opts.txTimeoutAt,
1426
+ });
1427
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
1232
1428
  }
1233
1429
 
1234
1430
  public enqueueInvalidateCheckpoint(
@@ -1239,23 +1435,22 @@ export class SequencerPublisher {
1239
1435
  return;
1240
1436
  }
1241
1437
 
1242
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1243
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(request.gasUsed) * 64) / 63)));
1244
-
1245
1438
  const { gasUsed, checkpointNumber } = request;
1246
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1439
+ const logData = { gasUsed, checkpointNumber, opts };
1247
1440
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1248
1441
  this.addRequest({
1249
1442
  action: `invalidate-by-${request.reason}`,
1250
1443
  request: request.request,
1251
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1444
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
1252
1445
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1253
1446
  checkSuccess: (_req, result) => {
1254
1447
  const success =
1255
1448
  result &&
1256
- result.receipt &&
1257
- result.receipt.status === 'success' &&
1258
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1449
+ extractEventSuccess(result.receipt, {
1450
+ address: this.rollupContract.address,
1451
+ abi: RollupAbi,
1452
+ eventName: 'CheckpointInvalidated',
1453
+ });
1259
1454
  if (!success) {
1260
1455
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
1261
1456
  } else {
@@ -1266,73 +1461,36 @@ export class SequencerPublisher {
1266
1461
  });
1267
1462
  }
1268
1463
 
1269
- private async simulateAndEnqueueRequest(
1464
+ /**
1465
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1466
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1467
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1468
+ */
1469
+ private enqueueRequest(
1270
1470
  action: Action,
1271
1471
  request: L1TxRequest,
1272
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1472
+ eventOpts: { address: string; abi: Abi; eventName: string },
1273
1473
  slotNumber: SlotNumber,
1274
- ) {
1275
- const timestamp = this.getSimulationTimestamp(slotNumber);
1276
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1474
+ ): boolean {
1277
1475
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1278
1476
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1279
1477
  return false;
1280
1478
  }
1281
-
1282
1479
  const cachedLastActionSlot = this.lastActions[action];
1283
1480
  this.lastActions[action] = slotNumber;
1284
1481
 
1285
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1286
-
1287
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1288
-
1289
- let gasUsed: bigint;
1290
- const simulateAbi = mergeAbis([request.abi ?? [], ErrorsAbi]);
1291
-
1292
- try {
1293
- ({ gasUsed } = await this.l1TxUtils.simulate(request, { time: timestamp }, [], simulateAbi));
1294
- this.log.verbose(`Simulation for ${action} succeeded`, { ...logData, request, gasUsed });
1295
- } catch (err) {
1296
- const viemError = formatViemError(err, simulateAbi);
1297
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1298
-
1299
- this.backupFailedTx({
1300
- id: keccak256(request.data!),
1301
- failureType: 'simulation',
1302
- request: { to: request.to!, data: request.data!, value: request.value?.toString() },
1303
- l1BlockNumber: l1BlockNumber.toString(),
1304
- error: { message: viemError.message, name: viemError.name },
1305
- context: {
1306
- actions: [action],
1307
- slot: slotNumber,
1308
- sender: this.getSenderAddress().toString(),
1309
- },
1310
- });
1311
-
1312
- return false;
1313
- }
1314
-
1315
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1316
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(gasUsed) * 64) / 63)));
1317
- logData.gasLimit = gasLimit;
1318
-
1319
- // Store the ABI used for simulation on the request so Multicall3.forward can decode errors
1320
- // when the tx is sent and a revert is diagnosed via simulation.
1321
- const requestWithAbi = { ...request, abi: simulateAbi };
1322
-
1323
- this.log.debug(`Enqueuing ${action}`, logData);
1482
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1324
1483
  this.addRequest({
1325
1484
  action,
1326
- request: requestWithAbi,
1327
- gasConfig: { gasLimit },
1485
+ request,
1328
1486
  lastValidL2Slot: slotNumber,
1329
- checkSuccess: (_req, result) => {
1330
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1487
+ checkSuccess: (_request, result) => {
1488
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1331
1489
  if (!success) {
1332
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1490
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1333
1491
  this.lastActions[action] = cachedLastActionSlot;
1334
1492
  } else {
1335
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1493
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1336
1494
  }
1337
1495
  return !!success;
1338
1496
  },
@@ -1358,10 +1516,7 @@ export class SequencerPublisher {
1358
1516
  this.l1TxUtils.restart();
1359
1517
  }
1360
1518
 
1361
- private async prepareProposeTx(
1362
- encodedData: L1ProcessArgs,
1363
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1364
- ) {
1519
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1365
1520
  const kzg = Blob.getViemKzgInstance();
1366
1521
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1367
1522
  this.log.debug('Validating blob input', { blobInput });
@@ -1374,7 +1529,11 @@ export class SequencerPublisher {
1374
1529
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1375
1530
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1376
1531
  } else {
1377
- // Normal mode - use estimateGas with blob inputs
1532
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1533
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1534
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1535
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1536
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1378
1537
  blobEvaluationGas = await this.l1TxUtils
1379
1538
  .estimateGas(
1380
1539
  this.getSenderAddress().toString(),
@@ -1401,18 +1560,22 @@ export class SequencerPublisher {
1401
1560
  args: [blobInput],
1402
1561
  });
1403
1562
  const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1404
- this.backupFailedTx({
1405
- id: keccak256(validateBlobsData),
1406
- failureType: 'simulation',
1407
- request: { to: this.rollupContract.address as Hex, data: validateBlobsData },
1408
- blobData: encodedData.blobs.map(b => toHex(b.data)) as Hex[],
1409
- l1BlockNumber: l1BlockNumber.toString(),
1410
- error: { message: viemError.message, name: viemError.name },
1411
- context: {
1412
- actions: ['validate-blobs'],
1413
- sender: this.getSenderAddress().toString(),
1563
+ this.backupFailedTx(
1564
+ {
1565
+ id: keccak256(validateBlobsData),
1566
+ failureType: 'simulation',
1567
+ request: { to: this.rollupContract.address as Hex, data: validateBlobsData },
1568
+ blobData: encodedData.blobs.map(b => toHex(b.data)) as Hex[],
1569
+ l1BlockNumber,
1570
+ error: { message: viemError.message, name: viemError.name },
1571
+ context: {
1572
+ actions: ['validate-blobs'],
1573
+ sender: this.getSenderAddress().toString(),
1574
+ },
1575
+ timing: this.computeTimingInfo(this.getCurrentL2Slot()),
1414
1576
  },
1415
- });
1577
+ { captureFeeSummary: true, targetSlot: this.getCurrentL2Slot() },
1578
+ );
1416
1579
  throw new Error('Failed to validate blobs');
1417
1580
  });
1418
1581
  }
@@ -1432,149 +1595,21 @@ export class SequencerPublisher {
1432
1595
  blobInput,
1433
1596
  ] as const;
1434
1597
 
1435
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, options);
1598
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1436
1599
 
1437
- return { args, blobEvaluationGas, rollupData, simulationResult };
1438
- }
1439
-
1440
- /**
1441
- * Simulates the propose tx with eth_simulateV1
1442
- * @param args - The propose tx args
1443
- * @returns The simulation result
1444
- */
1445
- private async simulateProposeTx(
1446
- args: readonly [
1447
- {
1448
- readonly header: ViemHeader;
1449
- readonly archive: `0x${string}`;
1450
- readonly oracleInput: {
1451
- readonly feeAssetPriceModifier: bigint;
1452
- };
1453
- },
1454
- ViemCommitteeAttestations,
1455
- `0x${string}`[], // Signers
1456
- ViemSignature,
1457
- `0x${string}`,
1458
- ],
1459
- options: {
1460
- forcePendingCheckpointNumber?: CheckpointNumber;
1461
- forceProposedFeeHeader?: { checkpointNumber: CheckpointNumber; feeHeader: FeeHeader };
1462
- },
1463
- ) {
1464
- const rollupData = encodeFunctionData({
1465
- abi: RollupAbi,
1466
- functionName: 'propose',
1467
- args,
1468
- });
1469
-
1470
- // override the proposed checkpoint number if requested
1471
- const forcePendingCheckpointNumberStateDiff = (
1472
- options.forcePendingCheckpointNumber !== undefined
1473
- ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber)
1474
- : []
1475
- ).flatMap(override => override.stateDiff ?? []);
1476
-
1477
- // override the fee header for a specific checkpoint number if requested (used when pipelining)
1478
- const forceProposedFeeHeaderStateDiff = (
1479
- options.forceProposedFeeHeader !== undefined
1480
- ? await this.rollupContract.makeFeeHeaderOverride(
1481
- options.forceProposedFeeHeader.checkpointNumber,
1482
- options.forceProposedFeeHeader.feeHeader,
1483
- )
1484
- : []
1485
- ).flatMap(override => override.stateDiff ?? []);
1486
-
1487
- const stateOverrides: StateOverride = [
1488
- {
1489
- address: this.rollupContract.address,
1490
- // @note we override checkBlob to false since blobs are not part simulate()
1491
- stateDiff: [
1492
- { slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true), value: toPaddedHex(0n, true) },
1493
- ...forcePendingCheckpointNumberStateDiff,
1494
- ...forceProposedFeeHeaderStateDiff,
1495
- ],
1496
- },
1497
- ];
1498
- // In fisherman mode, simulate as the proposer but with sufficient balance
1499
- if (this.proposerAddressForSimulation) {
1500
- stateOverrides.push({
1501
- address: this.proposerAddressForSimulation.toString(),
1502
- balance: 10n * WEI_CONST * WEI_CONST, // 10 ETH
1503
- });
1504
- }
1505
-
1506
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1507
- const simTs = this.getSimulationTimestamp(SlotNumber.fromBigInt(args[0].header.slotNumber));
1508
-
1509
- const simulationResult = await this.l1TxUtils
1510
- .simulate(
1511
- {
1512
- to: this.rollupContract.address,
1513
- data: rollupData,
1514
- gas: MAX_L1_TX_LIMIT,
1515
- ...(this.proposerAddressForSimulation && { from: this.proposerAddressForSimulation.toString() }),
1516
- },
1517
- {
1518
- time: simTs,
1519
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1520
- gasLimit: MAX_L1_TX_LIMIT * 2n,
1521
- },
1522
- stateOverrides,
1523
- RollupAbi,
1524
- {
1525
- // @note fallback gas estimate to use if the node doesn't support simulation API
1526
- fallbackGasEstimate: MAX_L1_TX_LIMIT,
1527
- },
1528
- )
1529
- .catch(err => {
1530
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1531
- const viemError = formatViemError(err);
1532
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1533
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1534
- // Return a minimal simulation result with the fallback gas estimate
1535
- return {
1536
- gasUsed: MAX_L1_TX_LIMIT,
1537
- logs: [],
1538
- };
1539
- }
1540
- this.log.error(`Failed to simulate propose tx`, viemError, { simulationTimestamp: simTs });
1541
- this.backupFailedTx({
1542
- id: keccak256(rollupData),
1543
- failureType: 'simulation',
1544
- request: { to: this.rollupContract.address, data: rollupData },
1545
- l1BlockNumber: l1BlockNumber.toString(),
1546
- error: { message: viemError.message, name: viemError.name },
1547
- context: {
1548
- actions: ['propose'],
1549
- slot: Number(args[0].header.slotNumber),
1550
- sender: this.getSenderAddress().toString(),
1551
- },
1552
- });
1553
- throw err;
1554
- });
1555
-
1556
- return { rollupData, simulationResult };
1600
+ return { args, blobEvaluationGas, rollupData };
1557
1601
  }
1558
1602
 
1559
1603
  private async addProposeTx(
1560
1604
  checkpoint: Checkpoint,
1561
1605
  encodedData: L1ProcessArgs,
1562
- opts: {
1563
- txTimeoutAt?: Date;
1564
- forcePendingCheckpointNumber?: CheckpointNumber;
1565
- forceProposedFeeHeader?: { checkpointNumber: CheckpointNumber; feeHeader: FeeHeader };
1566
- } = {},
1606
+ opts: EnqueueProposeCheckpointOpts = {},
1567
1607
  ): Promise<void> {
1568
1608
  const slot = checkpoint.header.slotNumber;
1569
1609
  const timer = new Timer();
1570
1610
  const kzg = Blob.getViemKzgInstance();
1571
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, opts);
1611
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1572
1612
  const startBlock = await this.l1TxUtils.getBlockNumber();
1573
- const gasLimit = this.l1TxUtils.bumpGasLimit(
1574
- BigInt(Math.ceil((Number(simulationResult.gasUsed) * 64) / 63)) +
1575
- blobEvaluationGas +
1576
- SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS, // We issue the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1577
- );
1578
1613
 
1579
1614
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1580
1615
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
@@ -1591,7 +1626,8 @@ export class SequencerPublisher {
1591
1626
  data: rollupData,
1592
1627
  },
1593
1628
  lastValidL2Slot: checkpoint.header.slotNumber,
1594
- gasConfig: { ...opts, gasLimit },
1629
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1630
+ blobEvaluationGas,
1595
1631
  blobConfig: {
1596
1632
  blobs: encodedData.blobs.map(b => b.data),
1597
1633
  kzg,
@@ -1601,10 +1637,11 @@ export class SequencerPublisher {
1601
1637
  return false;
1602
1638
  }
1603
1639
  const { receipt, stats, errorMsg } = result;
1604
- const success =
1605
- receipt &&
1606
- receipt.status === 'success' &&
1607
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1640
+ const success = extractEventSuccess(receipt, {
1641
+ address: this.rollupContract.address,
1642
+ abi: RollupAbi,
1643
+ eventName: 'CheckpointProposed',
1644
+ });
1608
1645
 
1609
1646
  if (success) {
1610
1647
  const endBlock = receipt.blockNumber;
@@ -1645,13 +1682,6 @@ export class SequencerPublisher {
1645
1682
  });
1646
1683
  }
1647
1684
 
1648
- /** Returns the timestamp of the last L1 slot within a given L2 slot. Used as the simulation timestamp
1649
- * for eth_simulateV1 calls, since it's guaranteed to be greater than any L1 block produced during the slot. */
1650
- private getSimulationTimestamp(slot: SlotNumber): bigint {
1651
- const l1Constants = this.epochCache.getL1Constants();
1652
- return getLastL1SlotTimestampForL2Slot(slot, l1Constants);
1653
- }
1654
-
1655
1685
  /** Returns the timestamp of the next L1 slot boundary after now. */
1656
1686
  private getNextL1SlotTimestamp(): bigint {
1657
1687
  const l1Constants = this.epochCache.getL1Constants();