@aztec/sequencer-client 0.0.1-commit.7b97ef96e → 0.0.1-commit.7cbc774

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