@aztec/sequencer-client 0.0.1-commit.04852196a → 0.0.1-commit.04d373f

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