@aztec/sequencer-client 0.0.1-commit.2448fdb → 0.0.1-commit.2606882

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 (118) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +4 -3
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +11 -11
  5. package/dest/config.d.ts +4 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +35 -14
  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 +4 -10
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +5 -40
  17. package/dest/global_variable_builder/index.d.ts +3 -1
  18. package/dest/global_variable_builder/index.d.ts.map +1 -1
  19. package/dest/global_variable_builder/index.js +2 -0
  20. package/dest/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 +19 -3
  24. package/dest/publisher/config.d.ts.map +1 -1
  25. package/dest/publisher/config.js +25 -5
  26. package/dest/publisher/index.d.ts +2 -1
  27. package/dest/publisher/index.d.ts.map +1 -1
  28. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  29. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  31. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  32. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  33. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  34. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  35. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  36. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  37. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  38. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  39. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  40. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  41. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  42. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  43. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -5
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +16 -3
  46. package/dest/publisher/sequencer-publisher.d.ts +77 -66
  47. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher.js +410 -398
  49. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  50. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  51. package/dest/sequencer/automine/automine_factory.js +84 -0
  52. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  53. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  54. package/dest/sequencer/automine/automine_sequencer.js +509 -0
  55. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  56. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  57. package/dest/sequencer/chain_state_overrides.js +98 -0
  58. package/dest/sequencer/checkpoint_proposal_job.d.ts +58 -10
  59. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  60. package/dest/sequencer/checkpoint_proposal_job.js +736 -191
  61. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  62. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  63. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  64. package/dest/sequencer/events.d.ts +48 -2
  65. package/dest/sequencer/events.d.ts.map +1 -1
  66. package/dest/sequencer/index.d.ts +3 -1
  67. package/dest/sequencer/index.d.ts.map +1 -1
  68. package/dest/sequencer/index.js +2 -0
  69. package/dest/sequencer/metrics.d.ts +13 -10
  70. package/dest/sequencer/metrics.d.ts.map +1 -1
  71. package/dest/sequencer/metrics.js +45 -20
  72. package/dest/sequencer/sequencer.d.ts +59 -12
  73. package/dest/sequencer/sequencer.d.ts.map +1 -1
  74. package/dest/sequencer/sequencer.js +344 -105
  75. package/dest/sequencer/timetable.d.ts +11 -1
  76. package/dest/sequencer/timetable.d.ts.map +1 -1
  77. package/dest/sequencer/timetable.js +41 -36
  78. package/dest/sequencer/types.d.ts +2 -2
  79. package/dest/sequencer/types.d.ts.map +1 -1
  80. package/dest/test/mock_checkpoint_builder.d.ts +1 -1
  81. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  82. package/dest/test/mock_checkpoint_builder.js +0 -2
  83. package/dest/test/utils.d.ts +1 -1
  84. package/dest/test/utils.d.ts.map +1 -1
  85. package/dest/test/utils.js +7 -6
  86. package/package.json +27 -28
  87. package/src/client/sequencer-client.ts +19 -20
  88. package/src/config.ts +40 -11
  89. package/src/global_variable_builder/README.md +44 -0
  90. package/src/global_variable_builder/fee_predictor.ts +172 -0
  91. package/src/global_variable_builder/fee_provider.ts +75 -0
  92. package/src/global_variable_builder/global_builder.ts +10 -46
  93. package/src/global_variable_builder/index.ts +2 -0
  94. package/src/index.ts +10 -1
  95. package/src/publisher/config.ts +49 -6
  96. package/src/publisher/index.ts +3 -0
  97. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  98. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  99. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  100. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  101. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  102. package/src/publisher/sequencer-publisher-factory.ts +18 -6
  103. package/src/publisher/sequencer-publisher.ts +485 -474
  104. package/src/sequencer/README.md +162 -450
  105. package/src/sequencer/automine/README.md +46 -0
  106. package/src/sequencer/automine/automine_factory.ts +145 -0
  107. package/src/sequencer/automine/automine_sequencer.ts +595 -0
  108. package/src/sequencer/chain_state_overrides.ts +162 -0
  109. package/src/sequencer/checkpoint_proposal_job.ts +857 -201
  110. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  111. package/src/sequencer/events.ts +51 -2
  112. package/src/sequencer/index.ts +2 -0
  113. package/src/sequencer/metrics.ts +57 -24
  114. package/src/sequencer/sequencer.ts +421 -118
  115. package/src/sequencer/timetable.ts +49 -44
  116. package/src/sequencer/types.ts +1 -1
  117. package/src/test/mock_checkpoint_builder.ts +0 -2
  118. 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,34 +23,81 @@ import {
24
23
  type TransactionStats,
25
24
  WEI_CONST,
26
25
  } from '@aztec/ethereum/l1-tx-utils';
27
- import { FormattedViemError, formatViemError, mergeAbis, tryExtractEvent } from '@aztec/ethereum/utils';
28
- import { sumBigint } from '@aztec/foundation/bigint';
29
- import { toHex as toPaddedHex } from '@aztec/foundation/bigint-buffer';
26
+ import {
27
+ FormattedViemError,
28
+ formatViemError,
29
+ mergeAbis,
30
+ tryDecodeRevertReason,
31
+ tryExtractEvent,
32
+ } from '@aztec/ethereum/utils';
30
33
  import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
31
34
  import { trimmedBytesLength } from '@aztec/foundation/buffer';
32
35
  import { pick } from '@aztec/foundation/collection';
33
36
  import type { Fr } from '@aztec/foundation/curves/bn254';
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 { getLastL1SlotTimestampForL2Slot, getNextL1SlotTimestamp } from '@aztec/stdlib/epoch-helpers';
45
- import { SlashFactoryContract } from '@aztec/stdlib/l1-contracts';
48
+ import {
49
+ getLastL1SlotTimestampForL2Slot,
50
+ getNextL1SlotTimestamp,
51
+ getTimestampForSlot,
52
+ } from '@aztec/stdlib/epoch-helpers';
46
53
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
47
54
  import type { L1PublishCheckpointStats } from '@aztec/stdlib/stats';
48
55
  import { type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
49
56
 
50
- import { type StateOverride, type TransactionReceipt, type TypedDataDefinition, encodeFunctionData, toHex } from 'viem';
57
+ import {
58
+ type Abi,
59
+ type Hex,
60
+ type TransactionReceipt,
61
+ type TypedDataDefinition,
62
+ encodeFunctionData,
63
+ keccak256,
64
+ toHex,
65
+ } from 'viem';
51
66
 
52
67
  import type { SequencerPublisherConfig } from './config.js';
68
+ import { type FailedL1Tx, type L1TxFailedStore, createL1TxFailedStore } from './l1_tx_failed_store/index.js';
69
+ import { type DroppedRequest, SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
53
70
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
54
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
+
55
101
  /** Arguments to the process method of the rollup contract */
56
102
  type L1ProcessArgs = {
57
103
  /** The L2 block header. */
@@ -73,16 +119,13 @@ export const Actions = [
73
119
  'invalidate-by-insufficient-attestations',
74
120
  'propose',
75
121
  'governance-signal',
76
- 'empire-slashing-signal',
77
- 'create-empire-payload',
78
- 'execute-empire-payload',
79
122
  'vote-offenses',
80
123
  'execute-slash',
81
124
  ] as const;
82
125
 
83
126
  export type Action = (typeof Actions)[number];
84
127
 
85
- type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slashing-signal'>;
128
+ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
86
129
 
87
130
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
88
131
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
@@ -93,14 +136,22 @@ export type InvalidateCheckpointRequest = {
93
136
  gasUsed: bigint;
94
137
  checkpointNumber: CheckpointNumber;
95
138
  forcePendingCheckpointNumber: CheckpointNumber;
139
+ /** Archive at the rollback target checkpoint (checkpoint N-1). */
140
+ lastArchive: Fr;
96
141
  };
97
142
 
98
- interface RequestWithExpiry {
143
+ type EnqueueProposeCheckpointOpts = {
144
+ txTimeoutAt?: Date;
145
+ };
146
+
147
+ export interface RequestWithExpiry {
99
148
  action: Action;
100
149
  request: L1TxRequest;
101
150
  lastValidL2Slot: SlotNumber;
102
151
  gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
103
152
  blobConfig?: L1BlobInputs;
153
+ /** Gas consumed by validateBlobs; stashed for the bundle simulate at send time. */
154
+ blobEvaluationGas?: bigint;
104
155
  checkSuccess: (
105
156
  request: L1TxRequest,
106
157
  result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
@@ -110,25 +161,30 @@ interface RequestWithExpiry {
110
161
  export class SequencerPublisher {
111
162
  private interrupted = false;
112
163
  private metrics: SequencerPublisherMetrics;
164
+ private bundleSimulator: SequencerBundleSimulator;
113
165
  public epochCache: EpochCache;
166
+ private failedTxStore?: Promise<L1TxFailedStore | undefined>;
114
167
 
115
- protected governanceLog = createLogger('sequencer:publisher:governance');
116
- 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]);
117
174
 
118
175
  protected lastActions: Partial<Record<Action, SlotNumber>> = {};
119
176
 
120
- private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
121
- private payloadProposedCache: Set<string> = new Set<string>();
122
-
123
177
  protected log: Logger;
124
178
  protected ethereumSlotDuration: bigint;
125
179
  protected aztecSlotDuration: bigint;
126
- private dateProvider: DateProvider;
180
+
181
+ /** Date provider for wall-clock time. */
182
+ private readonly dateProvider: DateProvider;
127
183
 
128
184
  private blobClient: BlobClientInterface;
129
185
 
130
- /** Address to use for simulations in fisherman mode (actual proposer's address) */
131
- private proposerAddressForSimulation?: EthAddress;
186
+ /** Optional callback to obtain a replacement publisher when the current one fails to send. */
187
+ private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
132
188
 
133
189
  /** L1 fee analyzer for fisherman mode */
134
190
  private l1FeeAnalyzer?: L1FeeAnalyzer;
@@ -136,38 +192,34 @@ export class SequencerPublisher {
136
192
  /** Fee asset price oracle for computing price modifiers from Uniswap V4 */
137
193
  private feeAssetPriceOracle: FeeAssetPriceOracle;
138
194
 
139
- // A CALL to a cold address is 2700 gas
140
- public static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
141
-
142
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
143
- 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();
144
197
 
145
198
  public l1TxUtils: L1TxUtils;
146
199
  public rollupContract: RollupContract;
147
200
  public govProposerContract: GovernanceProposerContract;
148
- public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
149
- public slashFactoryContract: SlashFactoryContract;
201
+ public slashingProposerContract: SlashingProposerContract | undefined;
150
202
 
151
203
  public readonly tracer: Tracer;
152
204
 
153
205
  protected requests: RequestWithExpiry[] = [];
154
206
 
155
207
  constructor(
156
- private config: Pick<SequencerPublisherConfig, 'fishermanMode'> &
208
+ private config: Pick<SequencerPublisherConfig, 'fishermanMode' | 'l1TxFailedStore'> &
157
209
  Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'> & { l1ChainId: number },
158
210
  deps: {
159
211
  telemetry?: TelemetryClient;
160
212
  blobClient: BlobClientInterface;
161
213
  l1TxUtils: L1TxUtils;
162
214
  rollupContract: RollupContract;
163
- slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
215
+ slashingProposerContract: SlashingProposerContract | undefined;
164
216
  governanceProposerContract: GovernanceProposerContract;
165
- slashFactoryContract: SlashFactoryContract;
166
217
  epochCache: EpochCache;
167
218
  dateProvider: DateProvider;
168
219
  metrics: SequencerPublisherMetrics;
169
220
  lastActions: Partial<Record<Action, SlotNumber>>;
170
221
  log?: Logger;
222
+ getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
171
223
  },
172
224
  ) {
173
225
  this.log = deps.log ?? createLogger('sequencer:publisher');
@@ -178,11 +230,13 @@ export class SequencerPublisher {
178
230
  this.lastActions = deps.lastActions;
179
231
 
180
232
  this.blobClient = deps.blobClient;
233
+ this.dateProvider = deps.dateProvider;
181
234
 
182
235
  const telemetry = deps.telemetry ?? getTelemetryClient();
183
236
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
184
237
  this.tracer = telemetry.getTracer('SequencerPublisher');
185
238
  this.l1TxUtils = deps.l1TxUtils;
239
+ this.getNextPublisher = deps.getNextPublisher;
186
240
 
187
241
  this.rollupContract = deps.rollupContract;
188
242
 
@@ -194,14 +248,12 @@ export class SequencerPublisher {
194
248
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
195
249
  this.slashingProposerContract = newSlashingProposer;
196
250
  });
197
- this.slashFactoryContract = deps.slashFactoryContract;
198
-
199
251
  // Initialize L1 fee analyzer for fisherman mode
200
252
  if (config.fishermanMode) {
201
253
  this.l1FeeAnalyzer = new L1FeeAnalyzer(
202
254
  this.l1TxUtils.client,
203
255
  deps.dateProvider,
204
- createLogger('sequencer:publisher:fee-analyzer'),
256
+ this.log.createChild('fee-analyzer'),
205
257
  );
206
258
  }
207
259
 
@@ -209,8 +261,40 @@ export class SequencerPublisher {
209
261
  this.feeAssetPriceOracle = new FeeAssetPriceOracle(
210
262
  this.l1TxUtils.client,
211
263
  this.rollupContract,
212
- createLogger('sequencer:publisher:price-oracle'),
264
+ this.log.createChild('price-oracle'),
213
265
  );
266
+
267
+ // Initialize failed L1 tx store (optional, for test networks)
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
+ });
276
+ }
277
+
278
+ /**
279
+ * Backs up a failed L1 transaction to the configured store for debugging.
280
+ * Does nothing if no store is configured.
281
+ */
282
+ private backupFailedTx(failedTx: Omit<FailedL1Tx, 'timestamp'>): void {
283
+ if (!this.failedTxStore) {
284
+ return;
285
+ }
286
+
287
+ const tx: FailedL1Tx = {
288
+ ...failedTx,
289
+ timestamp: Date.now(),
290
+ };
291
+
292
+ // Fire and forget - don't block on backup
293
+ void this.failedTxStore
294
+ .then(store => store?.saveFailedTx(tx))
295
+ .catch(err => {
296
+ this.log.warn(`Failed to backup failed L1 tx to store`, err);
297
+ });
214
298
  }
215
299
 
216
300
  public getRollupContract(): RollupContract {
@@ -219,10 +303,14 @@ export class SequencerPublisher {
219
303
 
220
304
  /**
221
305
  * Gets the fee asset price modifier from the oracle.
222
- * 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.
223
311
  */
224
- public getFeeAssetPriceModifier(): Promise<bigint> {
225
- return this.feeAssetPriceOracle.computePriceModifier();
312
+ public getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12?: bigint): Promise<bigint> {
313
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
226
314
  }
227
315
 
228
316
  public getSenderAddress() {
@@ -236,20 +324,12 @@ export class SequencerPublisher {
236
324
  return this.l1FeeAnalyzer;
237
325
  }
238
326
 
239
- /**
240
- * Sets the proposer address to use for simulations in fisherman mode.
241
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
242
- */
243
- public setProposerAddressForSimulation(proposerAddress: EthAddress | undefined) {
244
- this.proposerAddressForSimulation = proposerAddress;
245
- }
246
-
247
327
  public addRequest(request: RequestWithExpiry) {
248
328
  this.requests.push(request);
249
329
  }
250
330
 
251
331
  public getCurrentL2Slot(): SlotNumber {
252
- return this.epochCache.getEpochAndSlotNow().slot;
332
+ return this.epochCache.getSlotNow();
253
333
  }
254
334
 
255
335
  /**
@@ -321,22 +401,26 @@ export class SequencerPublisher {
321
401
 
322
402
  /**
323
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.
324
408
  * @returns one of:
325
409
  * - A receipt and stats if the tx succeeded
326
410
  * - a receipt and errorMsg if it failed on L1
327
411
  * - undefined if no valid requests are found OR the tx failed to send.
328
412
  */
329
413
  @trackSpan('SequencerPublisher.sendRequests')
330
- public async sendRequests() {
414
+ public async sendRequests(targetSlot?: SlotNumber): Promise<SendRequestsResult | undefined> {
331
415
  const requestsToProcess = [...this.requests];
332
416
  this.requests = [];
417
+
333
418
  if (this.interrupted || requestsToProcess.length === 0) {
334
419
  return undefined;
335
420
  }
336
- const currentL2Slot = this.getCurrentL2Slot();
421
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
337
422
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
338
423
  const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
339
- const validActions = validRequests.map(x => x.action);
340
424
  const expiredActions = requestsToProcess
341
425
  .filter(request => request.lastValidL2Slot < currentL2Slot)
342
426
  .map(x => x.action);
@@ -359,53 +443,58 @@ export class SequencerPublisher {
359
443
  return undefined;
360
444
  }
361
445
 
362
- // @note - we can only have one blob config per bundle
363
- // find requests with gas and blob configs
364
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
446
+ // Collect earliest txTimeoutAt across all requests.
365
447
  const gasConfigs = validRequests.filter(request => request.gasConfig).map(request => request.gasConfig);
366
- const blobConfigs = validRequests.filter(request => request.blobConfig).map(request => request.blobConfig);
367
-
368
- if (blobConfigs.length > 1) {
369
- throw new Error('Multiple blob configs found');
370
- }
371
-
372
- const blobConfig = blobConfigs[0];
373
-
374
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
375
- const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
376
- let gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
377
- // Cap at L1 block gas limit so the node accepts the tx ("gas limit too high" otherwise).
378
- const maxGas = MAX_L1_TX_LIMIT;
379
- if (gasLimit !== undefined && gasLimit > maxGas) {
380
- this.log.debug('Capping bundled tx gas limit to L1 max', {
381
- requested: gasLimit,
382
- capped: maxGas,
383
- });
384
- gasLimit = maxGas;
385
- }
386
448
  const txTimeoutAts = gasConfigs.map(g => g?.txTimeoutAt).filter((g): g is Date => g !== undefined);
387
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined; // earliest
388
- const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
449
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined;
389
450
 
390
451
  // Sort the requests so that proposals always go first
391
452
  // This ensures the committee gets precomputed correctly
392
453
  validRequests.sort((a, b) => compareActions(a.action, b.action));
393
454
 
394
455
  try {
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
+ }
464
+
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 };
480
+
395
481
  this.log.debug('Forwarding transactions', {
396
- validRequests: validRequests.map(request => request.action),
482
+ requests: requests.map(request => request.action),
397
483
  txConfig,
398
484
  });
399
- const result = await Multicall3.forward(
400
- validRequests.map(request => request.request),
401
- this.l1TxUtils,
402
- txConfig,
403
- blobConfig,
404
- this.rollupContract.address,
405
- this.log,
406
- );
407
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(validRequests, result);
408
- return { result, expiredActions, sentActions: validActions, successfulActions, failedActions };
485
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
486
+ if (result === undefined) {
487
+ return undefined;
488
+ }
489
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
490
+ const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action)];
491
+ return {
492
+ result,
493
+ expiredActions,
494
+ sentActions: requests.map(x => x.action),
495
+ successfulActions,
496
+ failedActions: allFailedActions,
497
+ };
409
498
  } catch (err) {
410
499
  const viemError = formatViemError(err);
411
500
  this.log.error(`Failed to publish bundled transactions`, viemError);
@@ -422,36 +511,164 @@ export class SequencerPublisher {
422
511
  }
423
512
  }
424
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
+
548
+ /**
549
+ * Forwards transactions via Multicall3, rotating to the next available publisher if a send
550
+ * failure occurs (i.e. the tx never reached the chain).
551
+ * On-chain reverts and simulation errors are returned as-is without rotation.
552
+ */
553
+ private async forwardWithPublisherRotation(
554
+ validRequests: RequestWithExpiry[],
555
+ txConfig: RequestWithExpiry['gasConfig'],
556
+ blobConfig: L1BlobInputs | undefined,
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
+
563
+ const triedAddresses: EthAddress[] = [];
564
+ let currentPublisher = this.l1TxUtils;
565
+
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
+ }
573
+ triedAddresses.push(currentPublisher.getSenderAddress());
574
+
575
+ try {
576
+ const result = await Multicall3.forward(
577
+ validRequests.map(r => r.request),
578
+ currentPublisher,
579
+ txConfigWithGasLimit,
580
+ blobConfig,
581
+ { gasLimitRequired: true },
582
+ );
583
+ this.l1TxUtils = currentPublisher;
584
+ return result;
585
+ } catch (err) {
586
+ if (err instanceof TimeoutError) {
587
+ throw err;
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
+ }
595
+ const viemError = formatViemError(err);
596
+ if (!this.getNextPublisher) {
597
+ this.log.error('Failed to publish bundled transactions', viemError);
598
+ return undefined;
599
+ }
600
+ this.log.warn(
601
+ `Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`,
602
+ viemError,
603
+ );
604
+ const nextPublisher = await this.getNextPublisher([...triedAddresses]);
605
+ if (!nextPublisher) {
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
+ );
611
+ return undefined;
612
+ }
613
+ currentPublisher = nextPublisher;
614
+ }
615
+ }
616
+ }
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
+
425
647
  private callbackBundledTransactions(
426
648
  requests: RequestWithExpiry[],
427
- result?: { receipt: TransactionReceipt } | FormattedViemError,
649
+ result: { receipt: TransactionReceipt; multicallData: Hex },
428
650
  ) {
429
651
  const actionsListStr = requests.map(r => r.action).join(', ');
430
- if (result instanceof FormattedViemError) {
431
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
432
- return { failedActions: requests.map(r => r.action) };
433
- } else {
434
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
435
- result,
436
- requests: requests.map(r => ({
437
- ...r,
438
- // Avoid logging large blob data
439
- blobConfig: r.blobConfig
440
- ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
441
- : undefined,
442
- })),
443
- });
444
- const successfulActions: Action[] = [];
445
- const failedActions: Action[] = [];
446
- for (const request of requests) {
447
- if (request.checkSuccess(request.request, result)) {
448
- successfulActions.push(request.action);
449
- } else {
450
- failedActions.push(request.action);
451
- }
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);
452
669
  }
453
- return { successfulActions, failedActions };
454
670
  }
671
+ return { successfulActions, failedActions };
455
672
  }
456
673
 
457
674
  /**
@@ -459,25 +676,27 @@ export class SequencerPublisher {
459
676
  * @param tipArchive - The archive to check
460
677
  * @returns The slot and block number if it is possible to propose, undefined otherwise
461
678
  */
462
- public canProposeAt(
463
- tipArchive: Fr,
464
- msgSender: EthAddress,
465
- opts: { forcePendingCheckpointNumber?: CheckpointNumber; pipelined?: boolean } = {},
466
- ) {
679
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
467
680
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
468
- 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'];
469
686
 
470
- const pipelined = opts.pipelined ?? false;
471
- const slotOffset = pipelined ? this.aztecSlotDuration : 0n;
687
+ const slotOffset = this.aztecSlotDuration;
472
688
  const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
473
689
 
474
690
  return this.rollupContract
475
- .canProposeAt(tipArchive.toBuffer(), msgSender.toString(), nextL1SlotTs, {
476
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
477
- })
691
+ .canProposeAt(
692
+ tipArchive.toBuffer(),
693
+ msgSender.toString(),
694
+ nextL1SlotTs,
695
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
696
+ )
478
697
  .catch(err => {
479
- if (err instanceof FormattedViemError && ignoredErrors.find(e => err.message.includes(e))) {
480
- this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find(e => err.message.includes(e))}`, {
698
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
699
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
481
700
  error: err.message,
482
701
  });
483
702
  } else {
@@ -486,6 +705,7 @@ export class SequencerPublisher {
486
705
  return undefined;
487
706
  });
488
707
  }
708
+
489
709
  /**
490
710
  * @notice Will simulate `validateHeader` to make sure that the block header is valid
491
711
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
@@ -495,13 +715,13 @@ export class SequencerPublisher {
495
715
  @trackSpan('SequencerPublisher.validateBlockHeader')
496
716
  public async validateBlockHeader(
497
717
  header: CheckpointHeader,
498
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
718
+ simulationOverridesPlan?: SimulationOverridesPlan,
499
719
  ): Promise<void> {
500
720
  const flags = { ignoreDA: true, ignoreSignatures: true };
501
721
 
502
722
  const args = [
503
723
  header.toViem(),
504
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
724
+ CommitteeAttestationsAndSigners.packAttestations([]),
505
725
  [], // no signers
506
726
  Signature.empty().toViemSignature(),
507
727
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -509,10 +729,9 @@ export class SequencerPublisher {
509
729
  flags,
510
730
  ] as const;
511
731
 
512
- const ts = this.getSimulationTimestamp(header.slotNumber);
513
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
514
- opts?.forcePendingCheckpointNumber,
515
- );
732
+ const l1Constants = this.epochCache.getL1Constants();
733
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
734
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
516
735
  let balance = 0n;
517
736
  if (this.config.fishermanMode) {
518
737
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -565,6 +784,8 @@ export class SequencerPublisher {
565
784
  const request = this.buildInvalidateCheckpointRequest(validationResult);
566
785
  this.log.debug(`Simulating invalidate checkpoint ${checkpointNumber}`, { ...logData, request });
567
786
 
787
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
788
+
568
789
  try {
569
790
  const { gasUsed } = await this.l1TxUtils.simulate(
570
791
  request,
@@ -583,6 +804,7 @@ export class SequencerPublisher {
583
804
  gasUsed,
584
805
  checkpointNumber,
585
806
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
807
+ lastArchive: validationResult.checkpoint.lastArchive,
586
808
  reason,
587
809
  };
588
810
  } catch (err) {
@@ -595,8 +817,8 @@ export class SequencerPublisher {
595
817
  `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
596
818
  { ...logData, request, error: viemError.message },
597
819
  );
598
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
599
- if (latestPendingCheckpointNumber < checkpointNumber) {
820
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
821
+ if (latestProposedCheckpointNumber < checkpointNumber) {
600
822
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
601
823
  return undefined;
602
824
  } else {
@@ -616,6 +838,18 @@ export class SequencerPublisher {
616
838
 
617
839
  // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
618
840
  this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
841
+ this.backupFailedTx({
842
+ id: keccak256(request.data!),
843
+ failureType: 'simulation',
844
+ request: { to: request.to!, data: request.data!, value: request.value?.toString() },
845
+ l1BlockNumber: l1BlockNumber.toString(),
846
+ error: { message: viemError.message, name: viemError.name },
847
+ context: {
848
+ actions: [`invalidate-${reason}`],
849
+ checkpointNumber,
850
+ sender: this.getSenderAddress().toString(),
851
+ },
852
+ });
619
853
  throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, { cause: viemError });
620
854
  }
621
855
  }
@@ -629,9 +863,7 @@ export class SequencerPublisher {
629
863
  const logData = { ...checkpoint, reason };
630
864
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
631
865
 
632
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
633
- validationResult.attestations,
634
- ).getPackedAttestations();
866
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
635
867
 
636
868
  if (reason === 'invalid-attestation') {
637
869
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -652,40 +884,11 @@ export class SequencerPublisher {
652
884
  }
653
885
  }
654
886
 
655
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */
656
- @trackSpan('SequencerPublisher.validateCheckpointForSubmission')
657
- public async validateCheckpointForSubmission(
658
- checkpoint: Checkpoint,
659
- attestationsAndSigners: CommitteeAttestationsAndSigners,
660
- attestationsAndSignersSignature: Signature,
661
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
662
- ): Promise<void> {
663
- const blobFields = checkpoint.toBlobFields();
664
- const blobs = await getBlobsPerL1Block(blobFields);
665
- const blobInput = getPrefixedEthBlobCommitments(blobs);
666
-
667
- const args = [
668
- {
669
- header: checkpoint.header.toViem(),
670
- archive: toHex(checkpoint.archive.root.toBuffer()),
671
- oracleInput: {
672
- feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
673
- },
674
- },
675
- attestationsAndSigners.getPackedAttestations(),
676
- attestationsAndSigners.getSigners().map(signer => signer.toString()),
677
- attestationsAndSignersSignature.toViemSignature(),
678
- blobInput,
679
- ] as const;
680
-
681
- await this.simulateProposeTx(args, options);
682
- }
683
-
684
887
  private async enqueueCastSignalHelper(
685
888
  slotNumber: SlotNumber,
686
889
  signalType: GovernanceSignalAction,
687
890
  payload: EthAddress,
688
- base: IEmpireBase,
891
+ base: GovernanceProposerContract,
689
892
  signerAddress: EthAddress,
690
893
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
691
894
  ): Promise<boolean> {
@@ -711,34 +914,28 @@ export class SequencerPublisher {
711
914
  return false;
712
915
  }
713
916
 
714
- if (await this.isPayloadEmpty(payload)) {
917
+ if (await base.isPayloadEmpty(payload)) {
715
918
  this.log.warn(`Skipping vote cast for payload with empty code`);
716
919
  return false;
717
920
  }
718
921
 
719
- // Check if payload was already submitted to governance
720
- const cacheKey = payload.toString();
721
- if (!this.payloadProposedCache.has(cacheKey)) {
722
- try {
723
- const l1StartBlock = await this.rollupContract.getL1StartBlock();
724
- const proposed = await retry(
725
- () => base.hasPayloadBeenProposed(payload.toString(), l1StartBlock),
726
- 'Check if payload was proposed',
727
- makeBackoff([0, 1, 2]),
728
- this.log,
729
- true,
730
- );
731
- if (proposed) {
732
- this.payloadProposedCache.add(cacheKey);
733
- }
734
- } catch (err) {
735
- this.log.warn(`Failed to check if payload ${payload} was proposed after retries, skipping signal`, err);
736
- return false;
737
- }
922
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
923
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
924
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
925
+ // the same payload in a future round.
926
+ let proposed = false;
927
+ try {
928
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
929
+ } catch (err) {
930
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
931
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
932
+ // participation entirely; failing open at worst produces a duplicate signal that the
933
+ // contract will simply count alongside others in the round.
934
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
738
935
  }
739
936
 
740
- if (this.payloadProposedCache.has(cacheKey)) {
741
- this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
937
+ if (proposed) {
938
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
742
939
  return false;
743
940
  }
744
941
 
@@ -760,31 +957,19 @@ export class SequencerPublisher {
760
957
  lastValidL2Slot: slotNumber,
761
958
  });
762
959
 
763
- const timestamp = this.getSimulationTimestamp(slotNumber);
764
-
765
- try {
766
- await this.l1TxUtils.simulate(request, { time: timestamp }, [], mergeAbis([request.abi ?? [], ErrorsAbi]));
767
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, { request });
768
- } catch (err) {
769
- const viemError = formatViemError(err);
770
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, viemError, {
771
- simulationTimestamp: timestamp,
772
- });
773
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
774
- }
775
-
776
960
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
777
961
  this.addRequest({
778
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
779
962
  action,
780
963
  request,
781
964
  lastValidL2Slot: slotNumber,
782
965
  checkSuccess: (_request, result) => {
783
966
  const success =
784
967
  result &&
785
- result.receipt &&
786
- result.receipt.status === 'success' &&
787
- tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
968
+ extractEventSuccess(result.receipt, {
969
+ address: base.address.toString(),
970
+ abi: EmpireBaseAbi,
971
+ eventName: 'SignalCast',
972
+ });
788
973
 
789
974
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
790
975
  if (!success) {
@@ -806,17 +991,6 @@ export class SequencerPublisher {
806
991
  return true;
807
992
  }
808
993
 
809
- private async isPayloadEmpty(payload: EthAddress): Promise<boolean> {
810
- const key = payload.toString();
811
- const cached = this.isPayloadEmptyCache.get(key);
812
- if (cached) {
813
- return cached;
814
- }
815
- const isEmpty = !(await this.l1TxUtils.getCode(payload));
816
- this.isPayloadEmptyCache.set(key, isEmpty);
817
- return isEmpty;
818
- }
819
-
820
994
  /**
821
995
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
822
996
  * @param slotNumber - The slot number to cast a signal for.
@@ -852,55 +1026,6 @@ export class SequencerPublisher {
852
1026
 
853
1027
  for (const action of actions) {
854
1028
  switch (action.type) {
855
- case 'vote-empire-payload': {
856
- if (this.slashingProposerContract?.type !== 'empire') {
857
- this.log.error('Cannot vote for empire payload on non-empire slashing contract');
858
- break;
859
- }
860
- this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
861
- signerAddress,
862
- });
863
- await this.enqueueCastSignalHelper(
864
- slotNumber,
865
- 'empire-slashing-signal',
866
- action.payload,
867
- this.slashingProposerContract,
868
- signerAddress,
869
- signer,
870
- );
871
- break;
872
- }
873
-
874
- case 'create-empire-payload': {
875
- this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, { slotNumber, signerAddress });
876
- const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
877
- await this.simulateAndEnqueueRequest(
878
- 'create-empire-payload',
879
- request,
880
- (receipt: TransactionReceipt) =>
881
- !!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs),
882
- slotNumber,
883
- );
884
- break;
885
- }
886
-
887
- case 'execute-empire-payload': {
888
- this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, { slotNumber, signerAddress });
889
- if (this.slashingProposerContract?.type !== 'empire') {
890
- this.log.error('Cannot execute slashing payload on non-empire slashing contract');
891
- return false;
892
- }
893
- const empireSlashingProposer = this.slashingProposerContract as EmpireSlashingProposerContract;
894
- const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
895
- await this.simulateAndEnqueueRequest(
896
- 'execute-empire-payload',
897
- request,
898
- (receipt: TransactionReceipt) => !!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs),
899
- slotNumber,
900
- );
901
- break;
902
- }
903
-
904
1029
  case 'vote-offenses': {
905
1030
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
906
1031
  slotNumber,
@@ -908,17 +1033,20 @@ export class SequencerPublisher {
908
1033
  votesCount: action.votes.length,
909
1034
  signerAddress,
910
1035
  });
911
- if (this.slashingProposerContract?.type !== 'tally') {
912
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1036
+ if (!this.slashingProposerContract) {
1037
+ this.log.error('No slashing proposer contract available');
913
1038
  return false;
914
1039
  }
915
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
916
1040
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
917
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
918
- await this.simulateAndEnqueueRequest(
1041
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1042
+ this.enqueueRequest(
919
1043
  'vote-offenses',
920
1044
  request,
921
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1045
+ {
1046
+ address: this.slashingProposerContract.address.toString(),
1047
+ abi: SlashingProposerAbi,
1048
+ eventName: 'VoteCast',
1049
+ },
922
1050
  slotNumber,
923
1051
  );
924
1052
  break;
@@ -930,16 +1058,22 @@ export class SequencerPublisher {
930
1058
  round: action.round,
931
1059
  signerAddress,
932
1060
  });
933
- if (this.slashingProposerContract?.type !== 'tally') {
934
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1061
+ if (!this.slashingProposerContract) {
1062
+ this.log.error('No slashing proposer contract available');
935
1063
  return false;
936
1064
  }
937
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
938
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
939
- await this.simulateAndEnqueueRequest(
1065
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1066
+ action.round,
1067
+ action.committees,
1068
+ );
1069
+ this.enqueueRequest(
940
1070
  'execute-slash',
941
- request,
942
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1071
+ executeRequest,
1072
+ {
1073
+ address: this.slashingProposerContract.address.toString(),
1074
+ abi: SlashingProposerAbi,
1075
+ eventName: 'RoundExecuted',
1076
+ },
943
1077
  slotNumber,
944
1078
  );
945
1079
  break;
@@ -955,12 +1089,12 @@ export class SequencerPublisher {
955
1089
  return true;
956
1090
  }
957
1091
 
958
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1092
+ /** Enqueues a proposal for a checkpoint on L1 */
959
1093
  public async enqueueProposeCheckpoint(
960
1094
  checkpoint: Checkpoint,
961
1095
  attestationsAndSigners: CommitteeAttestationsAndSigners,
962
1096
  attestationsAndSignersSignature: Signature,
963
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1097
+ opts: EnqueueProposeCheckpointOpts = {},
964
1098
  ): Promise<void> {
965
1099
  const checkpointHeader = checkpoint.header;
966
1100
 
@@ -976,29 +1110,11 @@ export class SequencerPublisher {
976
1110
  feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
977
1111
  };
978
1112
 
979
- try {
980
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
981
- // This means that we can avoid the simulation issues in later checks.
982
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
983
- // make time consistency checks break.
984
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
985
- await this.validateCheckpointForSubmission(
986
- checkpoint,
987
- attestationsAndSigners,
988
- attestationsAndSignersSignature,
989
- opts,
990
- );
991
- } catch (err: any) {
992
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
993
- ...checkpoint.getStats(),
994
- slotNumber: checkpoint.header.slotNumber,
995
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
996
- });
997
- throw err;
998
- }
999
-
1000
- this.log.verbose(`Enqueuing checkpoint propose transaction`, { ...checkpoint.toCheckpointInfo(), ...opts });
1001
- await this.addProposeTx(checkpoint, proposeTxArgs, opts);
1113
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1114
+ ...checkpoint.toCheckpointInfo(),
1115
+ txTimeoutAt: opts.txTimeoutAt,
1116
+ });
1117
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
1002
1118
  }
1003
1119
 
1004
1120
  public enqueueInvalidateCheckpoint(
@@ -1009,23 +1125,22 @@ export class SequencerPublisher {
1009
1125
  return;
1010
1126
  }
1011
1127
 
1012
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1013
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(request.gasUsed) * 64) / 63)));
1014
-
1015
1128
  const { gasUsed, checkpointNumber } = request;
1016
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1129
+ const logData = { gasUsed, checkpointNumber, opts };
1017
1130
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1018
1131
  this.addRequest({
1019
1132
  action: `invalidate-by-${request.reason}`,
1020
1133
  request: request.request,
1021
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1134
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
1022
1135
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1023
1136
  checkSuccess: (_req, result) => {
1024
1137
  const success =
1025
1138
  result &&
1026
- result.receipt &&
1027
- result.receipt.status === 'success' &&
1028
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1139
+ extractEventSuccess(result.receipt, {
1140
+ address: this.rollupContract.address,
1141
+ abi: RollupAbi,
1142
+ eventName: 'CheckpointInvalidated',
1143
+ });
1029
1144
  if (!success) {
1030
1145
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
1031
1146
  } else {
@@ -1036,58 +1151,36 @@ export class SequencerPublisher {
1036
1151
  });
1037
1152
  }
1038
1153
 
1039
- private async simulateAndEnqueueRequest(
1154
+ /**
1155
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1156
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1157
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1158
+ */
1159
+ private enqueueRequest(
1040
1160
  action: Action,
1041
1161
  request: L1TxRequest,
1042
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1162
+ eventOpts: { address: string; abi: Abi; eventName: string },
1043
1163
  slotNumber: SlotNumber,
1044
- ) {
1045
- const timestamp = this.getSimulationTimestamp(slotNumber);
1046
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1164
+ ): boolean {
1047
1165
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1048
1166
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1049
1167
  return false;
1050
1168
  }
1051
-
1052
1169
  const cachedLastActionSlot = this.lastActions[action];
1053
1170
  this.lastActions[action] = slotNumber;
1054
1171
 
1055
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1056
-
1057
- let gasUsed: bigint;
1058
- const simulateAbi = mergeAbis([request.abi ?? [], ErrorsAbi]);
1059
-
1060
- try {
1061
- ({ gasUsed } = await this.l1TxUtils.simulate(request, { time: timestamp }, [], simulateAbi));
1062
- this.log.verbose(`Simulation for ${action} succeeded`, { ...logData, request, gasUsed });
1063
- } catch (err) {
1064
- const viemError = formatViemError(err, simulateAbi);
1065
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1066
-
1067
- return false;
1068
- }
1069
-
1070
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1071
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(gasUsed) * 64) / 63)));
1072
- logData.gasLimit = gasLimit;
1073
-
1074
- // Store the ABI used for simulation on the request so Multicall3.forward can decode errors
1075
- // when the tx is sent and a revert is diagnosed via simulation.
1076
- const requestWithAbi = { ...request, abi: simulateAbi };
1077
-
1078
- this.log.debug(`Enqueuing ${action}`, logData);
1172
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1079
1173
  this.addRequest({
1080
1174
  action,
1081
- request: requestWithAbi,
1082
- gasConfig: { gasLimit },
1175
+ request,
1083
1176
  lastValidL2Slot: slotNumber,
1084
- checkSuccess: (_req, result) => {
1085
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1177
+ checkSuccess: (_request, result) => {
1178
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1086
1179
  if (!success) {
1087
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1180
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1088
1181
  this.lastActions[action] = cachedLastActionSlot;
1089
1182
  } else {
1090
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1183
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1091
1184
  }
1092
1185
  return !!success;
1093
1186
  },
@@ -1103,6 +1196,7 @@ export class SequencerPublisher {
1103
1196
  */
1104
1197
  public interrupt() {
1105
1198
  this.interrupted = true;
1199
+ this.interruptibleSleep.interrupt();
1106
1200
  this.l1TxUtils.interrupt();
1107
1201
  }
1108
1202
 
@@ -1112,10 +1206,7 @@ export class SequencerPublisher {
1112
1206
  this.l1TxUtils.restart();
1113
1207
  }
1114
1208
 
1115
- private async prepareProposeTx(
1116
- encodedData: L1ProcessArgs,
1117
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1118
- ) {
1209
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1119
1210
  const kzg = Blob.getViemKzgInstance();
1120
1211
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1121
1212
  this.log.debug('Validating blob input', { blobInput });
@@ -1128,7 +1219,11 @@ export class SequencerPublisher {
1128
1219
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1129
1220
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1130
1221
  } else {
1131
- // Normal mode - use estimateGas with blob inputs
1222
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1223
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1224
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1225
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1226
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1132
1227
  blobEvaluationGas = await this.l1TxUtils
1133
1228
  .estimateGas(
1134
1229
  this.getSenderAddress().toString(),
@@ -1146,9 +1241,27 @@ export class SequencerPublisher {
1146
1241
  kzg,
1147
1242
  },
1148
1243
  )
1149
- .catch(err => {
1150
- const { message, metaMessages } = formatViemError(err);
1151
- this.log.error(`Failed to validate blobs`, message, { metaMessages });
1244
+ .catch(async err => {
1245
+ const viemError = formatViemError(err);
1246
+ this.log.error(`Failed to validate blobs`, viemError.message, { metaMessages: viemError.metaMessages });
1247
+ const validateBlobsData = encodeFunctionData({
1248
+ abi: RollupAbi,
1249
+ functionName: 'validateBlobs',
1250
+ args: [blobInput],
1251
+ });
1252
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1253
+ this.backupFailedTx({
1254
+ id: keccak256(validateBlobsData),
1255
+ failureType: 'simulation',
1256
+ request: { to: this.rollupContract.address as Hex, data: validateBlobsData },
1257
+ blobData: encodedData.blobs.map(b => toHex(b.data)) as Hex[],
1258
+ l1BlockNumber: l1BlockNumber.toString(),
1259
+ error: { message: viemError.message, name: viemError.name },
1260
+ context: {
1261
+ actions: ['validate-blobs'],
1262
+ sender: this.getSenderAddress().toString(),
1263
+ },
1264
+ });
1152
1265
  throw new Error('Failed to validate blobs');
1153
1266
  });
1154
1267
  }
@@ -1168,118 +1281,21 @@ export class SequencerPublisher {
1168
1281
  blobInput,
1169
1282
  ] as const;
1170
1283
 
1171
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, options);
1172
-
1173
- return { args, blobEvaluationGas, rollupData, simulationResult };
1174
- }
1175
-
1176
- /**
1177
- * Simulates the propose tx with eth_simulateV1
1178
- * @param args - The propose tx args
1179
- * @returns The simulation result
1180
- */
1181
- private async simulateProposeTx(
1182
- args: readonly [
1183
- {
1184
- readonly header: ViemHeader;
1185
- readonly archive: `0x${string}`;
1186
- readonly oracleInput: {
1187
- readonly feeAssetPriceModifier: bigint;
1188
- };
1189
- },
1190
- ViemCommitteeAttestations,
1191
- `0x${string}`[], // Signers
1192
- ViemSignature,
1193
- `0x${string}`,
1194
- ],
1195
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1196
- ) {
1197
- const rollupData = encodeFunctionData({
1198
- abi: RollupAbi,
1199
- functionName: 'propose',
1200
- args,
1201
- });
1284
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1202
1285
 
1203
- // override the pending checkpoint number if requested
1204
- const forcePendingCheckpointNumberStateDiff = (
1205
- options.forcePendingCheckpointNumber !== undefined
1206
- ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber)
1207
- : []
1208
- ).flatMap(override => override.stateDiff ?? []);
1209
-
1210
- const stateOverrides: StateOverride = [
1211
- {
1212
- address: this.rollupContract.address,
1213
- // @note we override checkBlob to false since blobs are not part simulate()
1214
- stateDiff: [
1215
- { slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true), value: toPaddedHex(0n, true) },
1216
- ...forcePendingCheckpointNumberStateDiff,
1217
- ],
1218
- },
1219
- ];
1220
- // In fisherman mode, simulate as the proposer but with sufficient balance
1221
- if (this.proposerAddressForSimulation) {
1222
- stateOverrides.push({
1223
- address: this.proposerAddressForSimulation.toString(),
1224
- balance: 10n * WEI_CONST * WEI_CONST, // 10 ETH
1225
- });
1226
- }
1227
-
1228
- const simTs = this.getSimulationTimestamp(SlotNumber.fromBigInt(args[0].header.slotNumber));
1229
-
1230
- const simulationResult = await this.l1TxUtils
1231
- .simulate(
1232
- {
1233
- to: this.rollupContract.address,
1234
- data: rollupData,
1235
- gas: MAX_L1_TX_LIMIT,
1236
- ...(this.proposerAddressForSimulation && { from: this.proposerAddressForSimulation.toString() }),
1237
- },
1238
- {
1239
- time: simTs,
1240
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1241
- gasLimit: MAX_L1_TX_LIMIT * 2n,
1242
- },
1243
- stateOverrides,
1244
- RollupAbi,
1245
- {
1246
- // @note fallback gas estimate to use if the node doesn't support simulation API
1247
- fallbackGasEstimate: MAX_L1_TX_LIMIT,
1248
- },
1249
- )
1250
- .catch(err => {
1251
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1252
- const viemError = formatViemError(err);
1253
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1254
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1255
- // Return a minimal simulation result with the fallback gas estimate
1256
- return {
1257
- gasUsed: MAX_L1_TX_LIMIT,
1258
- logs: [],
1259
- };
1260
- }
1261
- this.log.error(`Failed to simulate propose tx`, viemError, { simulationTimestamp: simTs });
1262
- throw err;
1263
- });
1264
-
1265
- return { rollupData, simulationResult };
1286
+ return { args, blobEvaluationGas, rollupData };
1266
1287
  }
1267
1288
 
1268
1289
  private async addProposeTx(
1269
1290
  checkpoint: Checkpoint,
1270
1291
  encodedData: L1ProcessArgs,
1271
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1292
+ opts: EnqueueProposeCheckpointOpts = {},
1272
1293
  ): Promise<void> {
1273
1294
  const slot = checkpoint.header.slotNumber;
1274
1295
  const timer = new Timer();
1275
1296
  const kzg = Blob.getViemKzgInstance();
1276
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, opts);
1297
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1277
1298
  const startBlock = await this.l1TxUtils.getBlockNumber();
1278
- const gasLimit = this.l1TxUtils.bumpGasLimit(
1279
- BigInt(Math.ceil((Number(simulationResult.gasUsed) * 64) / 63)) +
1280
- blobEvaluationGas +
1281
- SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS, // We issue the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1282
- );
1283
1299
 
1284
1300
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1285
1301
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
@@ -1296,7 +1312,8 @@ export class SequencerPublisher {
1296
1312
  data: rollupData,
1297
1313
  },
1298
1314
  lastValidL2Slot: checkpoint.header.slotNumber,
1299
- gasConfig: { ...opts, gasLimit },
1315
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1316
+ blobEvaluationGas,
1300
1317
  blobConfig: {
1301
1318
  blobs: encodedData.blobs.map(b => b.data),
1302
1319
  kzg,
@@ -1306,10 +1323,11 @@ export class SequencerPublisher {
1306
1323
  return false;
1307
1324
  }
1308
1325
  const { receipt, stats, errorMsg } = result;
1309
- const success =
1310
- receipt &&
1311
- receipt.status === 'success' &&
1312
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1326
+ const success = extractEventSuccess(receipt, {
1327
+ address: this.rollupContract.address,
1328
+ abi: RollupAbi,
1329
+ eventName: 'CheckpointProposed',
1330
+ });
1313
1331
 
1314
1332
  if (success) {
1315
1333
  const endBlock = receipt.blockNumber;
@@ -1350,13 +1368,6 @@ export class SequencerPublisher {
1350
1368
  });
1351
1369
  }
1352
1370
 
1353
- /** Returns the timestamp of the last L1 slot within a given L2 slot. Used as the simulation timestamp
1354
- * for eth_simulateV1 calls, since it's guaranteed to be greater than any L1 block produced during the slot. */
1355
- private getSimulationTimestamp(slot: SlotNumber): bigint {
1356
- const l1Constants = this.epochCache.getL1Constants();
1357
- return getLastL1SlotTimestampForL2Slot(slot, l1Constants);
1358
- }
1359
-
1360
1371
  /** Returns the timestamp of the next L1 slot boundary after now. */
1361
1372
  private getNextL1SlotTimestamp(): bigint {
1362
1373
  const l1Constants = this.epochCache.getL1Constants();