@aztec/sequencer-client 0.0.1-commit.b33fc05d0 → 0.0.1-commit.b3d3157a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +8 -14
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +33 -83
  5. package/dest/config.d.ts +5 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +42 -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 +318 -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 +509 -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 +60 -10
  47. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  48. package/dest/sequencer/checkpoint_proposal_job.js +748 -200
  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 +48 -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 +63 -13
  64. package/dest/sequencer/sequencer.d.ts.map +1 -1
  65. package/dest/sequencer/sequencer.js +349 -107
  66. package/dest/sequencer/timetable.d.ts +11 -1
  67. package/dest/sequencer/timetable.d.ts.map +1 -1
  68. package/dest/sequencer/timetable.js +41 -36
  69. package/dest/sequencer/types.d.ts +2 -2
  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 +53 -114
  78. package/src/config.ts +48 -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 +377 -568
  90. package/src/sequencer/README.md +162 -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 +595 -0
  94. package/src/sequencer/chain_state_overrides.ts +162 -0
  95. package/src/sequencer/checkpoint_proposal_job.ts +894 -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 +51 -2
  99. package/src/sequencer/index.ts +2 -0
  100. package/src/sequencer/metrics.ts +57 -24
  101. package/src/sequencer/sequencer.ts +429 -121
  102. package/src/sequencer/timetable.ts +49 -44
  103. package/src/sequencer/types.ts +1 -1
  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 (the production path, via
405
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
406
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
407
+ * AutomineSequencer, which publishes synchronously within the current slot.
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,91 @@ 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
+ if (this.interrupted) {
634
+ return undefined;
635
+ }
636
+ const sleepMs = submitAfterMs - this.dateProvider.now();
637
+ if (sleepMs > 0) {
638
+ this.log.debug(`Sleeping ${sleepMs}ms before sending requests`, {
639
+ targetSlot,
640
+ submitAfterMs,
641
+ });
642
+ await this.interruptibleSleep.sleep(sleepMs);
643
+ }
644
+ if (this.interrupted) {
645
+ return undefined;
646
+ }
647
+ return this.sendRequests(targetSlot);
648
+ }
649
+
527
650
  private callbackBundledTransactions(
528
651
  requests: RequestWithExpiry[],
529
- result: { receipt: TransactionReceipt; errorMsg?: string } | FormattedViemError | undefined,
530
- txContext: { multicallData: Hex; blobData?: Hex[]; l1BlockNumber: bigint },
652
+ result: { receipt: TransactionReceipt; multicallData: Hex },
531
653
  ) {
532
654
  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
- });
655
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
656
+ result,
657
+ requests: requests.map(r => ({
658
+ ...r,
659
+ // Avoid logging large blob data
660
+ blobConfig: r.blobConfig
661
+ ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
662
+ : undefined,
663
+ })),
664
+ });
665
+ const successfulActions: Action[] = [];
666
+ const failedActions: Action[] = [];
667
+ for (const request of requests) {
668
+ if (request.checkSuccess(request.request, result)) {
669
+ successfulActions.push(request.action);
670
+ } else {
671
+ failedActions.push(request.action);
583
672
  }
584
- return { successfulActions, failedActions };
585
673
  }
674
+ return { successfulActions, failedActions };
586
675
  }
587
676
 
588
677
  /**
589
- * @notice Will call `canProposeAtNextEthBlock` to make sure that it is possible to propose
678
+ * @notice Will call `canProposeAt` to make sure that it is possible to propose
590
679
  * @param tipArchive - The archive to check
591
680
  * @returns The slot and block number if it is possible to propose, undefined otherwise
592
681
  */
593
- public canProposeAtNextEthBlock(
594
- tipArchive: Fr,
595
- msgSender: EthAddress,
596
- opts: { forcePendingCheckpointNumber?: CheckpointNumber } = {},
597
- ) {
682
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
598
683
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
599
- const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
684
+ // These errors are expected when we cannot actually propose right now — usually because our
685
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
686
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
687
+ // skip the proposal; we do NOT treat these as bugs.
688
+ const expectedErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
689
+
690
+ const slotOffset = this.aztecSlotDuration;
691
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
600
692
 
601
693
  return this.rollupContract
602
- .canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
603
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
604
- })
694
+ .canProposeAt(
695
+ tipArchive.toBuffer(),
696
+ msgSender.toString(),
697
+ nextL1SlotTs,
698
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
699
+ )
605
700
  .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))}`, {
701
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
702
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
608
703
  error: err.message,
609
704
  });
610
705
  } else {
@@ -613,6 +708,7 @@ export class SequencerPublisher {
613
708
  return undefined;
614
709
  });
615
710
  }
711
+
616
712
  /**
617
713
  * @notice Will simulate `validateHeader` to make sure that the block header is valid
618
714
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
@@ -622,13 +718,13 @@ export class SequencerPublisher {
622
718
  @trackSpan('SequencerPublisher.validateBlockHeader')
623
719
  public async validateBlockHeader(
624
720
  header: CheckpointHeader,
625
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
721
+ simulationOverridesPlan?: SimulationOverridesPlan,
626
722
  ): Promise<void> {
627
723
  const flags = { ignoreDA: true, ignoreSignatures: true };
628
724
 
629
725
  const args = [
630
726
  header.toViem(),
631
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
727
+ CommitteeAttestationsAndSigners.packAttestations([]),
632
728
  [], // no signers
633
729
  Signature.empty().toViemSignature(),
634
730
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -636,10 +732,9 @@ export class SequencerPublisher {
636
732
  flags,
637
733
  ] as const;
638
734
 
639
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
640
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
641
- opts?.forcePendingCheckpointNumber,
642
- );
735
+ const l1Constants = this.epochCache.getL1Constants();
736
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
737
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
643
738
  let balance = 0n;
644
739
  if (this.config.fishermanMode) {
645
740
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -659,7 +754,7 @@ export class SequencerPublisher {
659
754
  data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
660
755
  from: MULTI_CALL_3_ADDRESS,
661
756
  },
662
- { time: ts + 1n },
757
+ { time: ts },
663
758
  stateOverrides,
664
759
  );
665
760
  this.log.debug(`Simulated validateHeader`);
@@ -712,6 +807,7 @@ export class SequencerPublisher {
712
807
  gasUsed,
713
808
  checkpointNumber,
714
809
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
810
+ lastArchive: validationResult.checkpoint.lastArchive,
715
811
  reason,
716
812
  };
717
813
  } catch (err) {
@@ -724,8 +820,8 @@ export class SequencerPublisher {
724
820
  `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
725
821
  { ...logData, request, error: viemError.message },
726
822
  );
727
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
728
- if (latestPendingCheckpointNumber < checkpointNumber) {
823
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
824
+ if (latestProposedCheckpointNumber < checkpointNumber) {
729
825
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
730
826
  return undefined;
731
827
  } else {
@@ -770,9 +866,7 @@ export class SequencerPublisher {
770
866
  const logData = { ...checkpoint, reason };
771
867
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
772
868
 
773
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
774
- validationResult.attestations,
775
- ).getPackedAttestations();
869
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
776
870
 
777
871
  if (reason === 'invalid-attestation') {
778
872
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -793,43 +887,11 @@ export class SequencerPublisher {
793
887
  }
794
888
  }
795
889
 
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
890
  private async enqueueCastSignalHelper(
828
891
  slotNumber: SlotNumber,
829
- timestamp: bigint,
830
892
  signalType: GovernanceSignalAction,
831
893
  payload: EthAddress,
832
- base: IEmpireBase,
894
+ base: GovernanceProposerContract,
833
895
  signerAddress: EthAddress,
834
896
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
835
897
  ): Promise<boolean> {
@@ -855,34 +917,28 @@ export class SequencerPublisher {
855
917
  return false;
856
918
  }
857
919
 
858
- if (await this.isPayloadEmpty(payload)) {
920
+ if (await base.isPayloadEmpty(payload)) {
859
921
  this.log.warn(`Skipping vote cast for payload with empty code`);
860
922
  return false;
861
923
  }
862
924
 
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
- }
925
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
926
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
927
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
928
+ // the same payload in a future round.
929
+ let proposed = false;
930
+ try {
931
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
932
+ } catch (err) {
933
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
934
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
935
+ // participation entirely; failing open at worst produces a duplicate signal that the
936
+ // contract will simply count alongside others in the round.
937
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
882
938
  }
883
939
 
884
- if (this.payloadProposedCache.has(cacheKey)) {
885
- this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
940
+ if (proposed) {
941
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
886
942
  return false;
887
943
  }
888
944
 
@@ -904,41 +960,19 @@ export class SequencerPublisher {
904
960
  lastValidL2Slot: slotNumber,
905
961
  });
906
962
 
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
963
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
931
964
  this.addRequest({
932
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
933
965
  action,
934
966
  request,
935
967
  lastValidL2Slot: slotNumber,
936
968
  checkSuccess: (_request, result) => {
937
969
  const success =
938
970
  result &&
939
- result.receipt &&
940
- result.receipt.status === 'success' &&
941
- tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
971
+ extractEventSuccess(result.receipt, {
972
+ address: base.address.toString(),
973
+ abi: EmpireBaseAbi,
974
+ eventName: 'SignalCast',
975
+ });
942
976
 
943
977
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
944
978
  if (!success) {
@@ -960,33 +994,19 @@ export class SequencerPublisher {
960
994
  return true;
961
995
  }
962
996
 
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
997
  /**
975
998
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
976
999
  * @param slotNumber - The slot number to cast a signal for.
977
- * @param timestamp - The timestamp of the slot to cast a signal for.
978
1000
  * @returns True if the signal was successfully enqueued, false otherwise.
979
1001
  */
980
1002
  public enqueueGovernanceCastSignal(
981
1003
  governancePayload: EthAddress,
982
1004
  slotNumber: SlotNumber,
983
- timestamp: bigint,
984
1005
  signerAddress: EthAddress,
985
1006
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
986
1007
  ): Promise<boolean> {
987
1008
  return this.enqueueCastSignalHelper(
988
1009
  slotNumber,
989
- timestamp,
990
1010
  'governance-signal',
991
1011
  governancePayload,
992
1012
  this.govProposerContract,
@@ -999,7 +1019,6 @@ export class SequencerPublisher {
999
1019
  public async enqueueSlashingActions(
1000
1020
  actions: ProposerSlashAction[],
1001
1021
  slotNumber: SlotNumber,
1002
- timestamp: bigint,
1003
1022
  signerAddress: EthAddress,
1004
1023
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
1005
1024
  ): Promise<boolean> {
@@ -1010,58 +1029,6 @@ export class SequencerPublisher {
1010
1029
 
1011
1030
  for (const action of actions) {
1012
1031
  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
1032
  case 'vote-offenses': {
1066
1033
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
1067
1034
  slotNumber,
@@ -1069,19 +1036,21 @@ export class SequencerPublisher {
1069
1036
  votesCount: action.votes.length,
1070
1037
  signerAddress,
1071
1038
  });
1072
- if (this.slashingProposerContract?.type !== 'tally') {
1073
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1039
+ if (!this.slashingProposerContract) {
1040
+ this.log.error('No slashing proposer contract available');
1074
1041
  return false;
1075
1042
  }
1076
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
1077
1043
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1078
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
1079
- await this.simulateAndEnqueueRequest(
1044
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1045
+ this.enqueueRequest(
1080
1046
  'vote-offenses',
1081
1047
  request,
1082
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1048
+ {
1049
+ address: this.slashingProposerContract.address.toString(),
1050
+ abi: SlashingProposerAbi,
1051
+ eventName: 'VoteCast',
1052
+ },
1083
1053
  slotNumber,
1084
- timestamp,
1085
1054
  );
1086
1055
  break;
1087
1056
  }
@@ -1092,18 +1061,23 @@ export class SequencerPublisher {
1092
1061
  round: action.round,
1093
1062
  signerAddress,
1094
1063
  });
1095
- if (this.slashingProposerContract?.type !== 'tally') {
1096
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1064
+ if (!this.slashingProposerContract) {
1065
+ this.log.error('No slashing proposer contract available');
1097
1066
  return false;
1098
1067
  }
1099
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
1100
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
1101
- await this.simulateAndEnqueueRequest(
1068
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1069
+ action.round,
1070
+ action.committees,
1071
+ );
1072
+ this.enqueueRequest(
1102
1073
  'execute-slash',
1103
- request,
1104
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1074
+ executeRequest,
1075
+ {
1076
+ address: this.slashingProposerContract.address.toString(),
1077
+ abi: SlashingProposerAbi,
1078
+ eventName: 'RoundExecuted',
1079
+ },
1105
1080
  slotNumber,
1106
- timestamp,
1107
1081
  );
1108
1082
  break;
1109
1083
  }
@@ -1118,12 +1092,12 @@ export class SequencerPublisher {
1118
1092
  return true;
1119
1093
  }
1120
1094
 
1121
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1095
+ /** Enqueues a proposal for a checkpoint on L1 */
1122
1096
  public async enqueueProposeCheckpoint(
1123
1097
  checkpoint: Checkpoint,
1124
1098
  attestationsAndSigners: CommitteeAttestationsAndSigners,
1125
1099
  attestationsAndSignersSignature: Signature,
1126
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1100
+ opts: EnqueueProposeCheckpointOpts = {},
1127
1101
  ): Promise<void> {
1128
1102
  const checkpointHeader = checkpoint.header;
1129
1103
 
@@ -1139,31 +1113,11 @@ export class SequencerPublisher {
1139
1113
  feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
1140
1114
  };
1141
1115
 
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);
1116
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1117
+ ...checkpoint.toCheckpointInfo(),
1118
+ txTimeoutAt: opts.txTimeoutAt,
1119
+ });
1120
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
1167
1121
  }
1168
1122
 
1169
1123
  public enqueueInvalidateCheckpoint(
@@ -1174,23 +1128,22 @@ export class SequencerPublisher {
1174
1128
  return;
1175
1129
  }
1176
1130
 
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
1131
  const { gasUsed, checkpointNumber } = request;
1181
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1132
+ const logData = { gasUsed, checkpointNumber, opts };
1182
1133
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1183
1134
  this.addRequest({
1184
1135
  action: `invalidate-by-${request.reason}`,
1185
1136
  request: request.request,
1186
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1137
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
1187
1138
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1188
1139
  checkSuccess: (_req, result) => {
1189
1140
  const success =
1190
1141
  result &&
1191
- result.receipt &&
1192
- result.receipt.status === 'success' &&
1193
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1142
+ extractEventSuccess(result.receipt, {
1143
+ address: this.rollupContract.address,
1144
+ abi: RollupAbi,
1145
+ eventName: 'CheckpointInvalidated',
1146
+ });
1194
1147
  if (!success) {
1195
1148
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
1196
1149
  } else {
@@ -1201,72 +1154,36 @@ export class SequencerPublisher {
1201
1154
  });
1202
1155
  }
1203
1156
 
1204
- private async simulateAndEnqueueRequest(
1157
+ /**
1158
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1159
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1160
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1161
+ */
1162
+ private enqueueRequest(
1205
1163
  action: Action,
1206
1164
  request: L1TxRequest,
1207
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1165
+ eventOpts: { address: string; abi: Abi; eventName: string },
1208
1166
  slotNumber: SlotNumber,
1209
- timestamp: bigint,
1210
- ) {
1211
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1167
+ ): boolean {
1212
1168
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1213
1169
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1214
1170
  return false;
1215
1171
  }
1216
-
1217
1172
  const cachedLastActionSlot = this.lastActions[action];
1218
1173
  this.lastActions[action] = slotNumber;
1219
1174
 
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);
1175
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1258
1176
  this.addRequest({
1259
1177
  action,
1260
- request: requestWithAbi,
1261
- gasConfig: { gasLimit },
1178
+ request,
1262
1179
  lastValidL2Slot: slotNumber,
1263
- checkSuccess: (_req, result) => {
1264
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1180
+ checkSuccess: (_request, result) => {
1181
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1265
1182
  if (!success) {
1266
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1183
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1267
1184
  this.lastActions[action] = cachedLastActionSlot;
1268
1185
  } else {
1269
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1186
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1270
1187
  }
1271
1188
  return !!success;
1272
1189
  },
@@ -1282,6 +1199,7 @@ export class SequencerPublisher {
1282
1199
  */
1283
1200
  public interrupt() {
1284
1201
  this.interrupted = true;
1202
+ this.interruptibleSleep.interrupt();
1285
1203
  this.l1TxUtils.interrupt();
1286
1204
  }
1287
1205
 
@@ -1291,11 +1209,7 @@ export class SequencerPublisher {
1291
1209
  this.l1TxUtils.restart();
1292
1210
  }
1293
1211
 
1294
- private async prepareProposeTx(
1295
- encodedData: L1ProcessArgs,
1296
- timestamp: bigint,
1297
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1298
- ) {
1212
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1299
1213
  const kzg = Blob.getViemKzgInstance();
1300
1214
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1301
1215
  this.log.debug('Validating blob input', { blobInput });
@@ -1308,7 +1222,11 @@ export class SequencerPublisher {
1308
1222
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1309
1223
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1310
1224
  } else {
1311
- // Normal mode - use estimateGas with blob inputs
1225
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1226
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1227
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1228
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1229
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1312
1230
  blobEvaluationGas = await this.l1TxUtils
1313
1231
  .estimateGas(
1314
1232
  this.getSenderAddress().toString(),
@@ -1366,138 +1284,21 @@ export class SequencerPublisher {
1366
1284
  blobInput,
1367
1285
  ] as const;
1368
1286
 
1369
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1287
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1370
1288
 
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 };
1289
+ return { args, blobEvaluationGas, rollupData };
1479
1290
  }
1480
1291
 
1481
1292
  private async addProposeTx(
1482
1293
  checkpoint: Checkpoint,
1483
1294
  encodedData: L1ProcessArgs,
1484
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1485
- timestamp: bigint,
1295
+ opts: EnqueueProposeCheckpointOpts = {},
1486
1296
  ): Promise<void> {
1487
1297
  const slot = checkpoint.header.slotNumber;
1488
1298
  const timer = new Timer();
1489
1299
  const kzg = Blob.getViemKzgInstance();
1490
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
1491
- encodedData,
1492
- timestamp,
1493
- opts,
1494
- );
1300
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1495
1301
  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
1302
 
1502
1303
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1503
1304
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
@@ -1514,7 +1315,8 @@ export class SequencerPublisher {
1514
1315
  data: rollupData,
1515
1316
  },
1516
1317
  lastValidL2Slot: checkpoint.header.slotNumber,
1517
- gasConfig: { ...opts, gasLimit },
1318
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1319
+ blobEvaluationGas,
1518
1320
  blobConfig: {
1519
1321
  blobs: encodedData.blobs.map(b => b.data),
1520
1322
  kzg,
@@ -1524,10 +1326,11 @@ export class SequencerPublisher {
1524
1326
  return false;
1525
1327
  }
1526
1328
  const { receipt, stats, errorMsg } = result;
1527
- const success =
1528
- receipt &&
1529
- receipt.status === 'success' &&
1530
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1329
+ const success = extractEventSuccess(receipt, {
1330
+ address: this.rollupContract.address,
1331
+ abi: RollupAbi,
1332
+ eventName: 'CheckpointProposed',
1333
+ });
1531
1334
 
1532
1335
  if (success) {
1533
1336
  const endBlock = receipt.blockNumber;
@@ -1567,4 +1370,10 @@ export class SequencerPublisher {
1567
1370
  },
1568
1371
  });
1569
1372
  }
1373
+
1374
+ /** Returns the timestamp of the next L1 slot boundary after now. */
1375
+ private getNextL1SlotTimestamp(): bigint {
1376
+ const l1Constants = this.epochCache.getL1Constants();
1377
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1378
+ }
1570
1379
  }