@aztec/sequencer-client 0.0.1-commit.86469d5 → 0.0.1-commit.8655d4a

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 (125) hide show
  1. package/README.md +282 -21
  2. package/dest/client/sequencer-client.d.ts +19 -9
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +67 -33
  5. package/dest/config.d.ts +29 -7
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +77 -37
  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 -16
  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 +47 -17
  24. package/dest/publisher/config.d.ts.map +1 -1
  25. package/dest/publisher/config.js +121 -42
  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 +11 -5
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +27 -3
  46. package/dest/publisher/sequencer-publisher.d.ts +94 -67
  47. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher.js +440 -378
  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 +56 -11
  59. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  60. package/dest/sequencer/checkpoint_proposal_job.js +805 -225
  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 +23 -8
  73. package/dest/sequencer/metrics.d.ts.map +1 -1
  74. package/dest/sequencer/metrics.js +117 -21
  75. package/dest/sequencer/sequencer.d.ts +74 -21
  76. package/dest/sequencer/sequencer.d.ts.map +1 -1
  77. package/dest/sequencer/sequencer.js +353 -136
  78. package/dest/sequencer/timetable.d.ts +17 -6
  79. package/dest/sequencer/timetable.d.ts.map +1 -1
  80. package/dest/sequencer/timetable.js +51 -46
  81. package/dest/sequencer/types.d.ts +2 -2
  82. package/dest/sequencer/types.d.ts.map +1 -1
  83. package/dest/test/index.d.ts +3 -5
  84. package/dest/test/index.d.ts.map +1 -1
  85. package/dest/test/mock_checkpoint_builder.d.ts +11 -11
  86. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  87. package/dest/test/mock_checkpoint_builder.js +45 -34
  88. package/dest/test/utils.d.ts +3 -3
  89. package/dest/test/utils.d.ts.map +1 -1
  90. package/dest/test/utils.js +10 -8
  91. package/package.json +27 -28
  92. package/src/client/sequencer-client.ts +92 -35
  93. package/src/config.ts +102 -46
  94. package/src/global_variable_builder/README.md +44 -0
  95. package/src/global_variable_builder/fee_predictor.ts +172 -0
  96. package/src/global_variable_builder/fee_provider.ts +75 -0
  97. package/src/global_variable_builder/global_builder.ts +26 -63
  98. package/src/global_variable_builder/index.ts +3 -1
  99. package/src/index.ts +10 -1
  100. package/src/publisher/config.ts +157 -45
  101. package/src/publisher/index.ts +3 -0
  102. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  103. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  104. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  105. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  106. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  107. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  108. package/src/publisher/sequencer-publisher.ts +533 -469
  109. package/src/sequencer/README.md +152 -450
  110. package/src/sequencer/automine/README.md +46 -0
  111. package/src/sequencer/automine/automine_factory.ts +145 -0
  112. package/src/sequencer/automine/automine_sequencer.ts +592 -0
  113. package/src/sequencer/chain_state_overrides.ts +162 -0
  114. package/src/sequencer/checkpoint_proposal_job.ts +984 -245
  115. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  116. package/src/sequencer/checkpoint_voter.ts +1 -12
  117. package/src/sequencer/events.ts +50 -2
  118. package/src/sequencer/index.ts +2 -0
  119. package/src/sequencer/metrics.ts +132 -25
  120. package/src/sequencer/sequencer.ts +444 -154
  121. package/src/sequencer/timetable.ts +70 -57
  122. package/src/sequencer/types.ts +1 -1
  123. package/src/test/index.ts +2 -4
  124. package/src/test/mock_checkpoint_builder.ts +63 -49
  125. package/src/test/utils.ts +31 -10
@@ -3,51 +3,101 @@ 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,
6
+ FeeAssetPriceOracle,
7
7
  type GovernanceProposerContract,
8
- type IEmpireBase,
9
8
  MULTI_CALL_3_ADDRESS,
10
9
  Multicall3,
11
- RollupContract,
12
- type TallySlashingProposerContract,
13
- type ViemCommitteeAttestations,
14
- type ViemHeader,
10
+ MulticallForwarderRevertedError,
11
+ type RollupContract,
12
+ type SimulationOverridesPlan,
13
+ type SlashingProposerContract,
14
+ buildSimulationOverridesStateOverride,
15
15
  } from '@aztec/ethereum/contracts';
16
16
  import { type L1FeeAnalysisResult, L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
17
17
  import {
18
18
  type L1BlobInputs,
19
19
  type L1TxConfig,
20
20
  type L1TxRequest,
21
+ type L1TxUtils,
21
22
  MAX_L1_TX_LIMIT,
22
23
  type TransactionStats,
23
24
  WEI_CONST,
24
25
  } from '@aztec/ethereum/l1-tx-utils';
25
- import type { L1TxUtilsWithBlobs } from '@aztec/ethereum/l1-tx-utils-with-blobs';
26
- import { FormattedViemError, formatViemError, mergeAbis, tryExtractEvent } from '@aztec/ethereum/utils';
27
- import { sumBigint } from '@aztec/foundation/bigint';
28
- 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';
29
33
  import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
34
+ import { trimmedBytesLength } from '@aztec/foundation/buffer';
30
35
  import { pick } from '@aztec/foundation/collection';
31
36
  import type { Fr } from '@aztec/foundation/curves/bn254';
37
+ import { TimeoutError } from '@aztec/foundation/error';
32
38
  import { EthAddress } from '@aztec/foundation/eth-address';
33
- import { Signature, type ViemSignature } from '@aztec/foundation/eth-signature';
39
+ import { Signature } from '@aztec/foundation/eth-signature';
34
40
  import { type Logger, createLogger } from '@aztec/foundation/log';
41
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
35
42
  import { bufferToHex } from '@aztec/foundation/string';
36
- import { DateProvider, Timer } from '@aztec/foundation/timer';
37
- 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';
38
45
  import { type ProposerSlashAction, encodeSlashConsensusVotes } from '@aztec/slasher';
39
46
  import { CommitteeAttestationsAndSigners, type ValidateCheckpointResult } from '@aztec/stdlib/block';
40
47
  import type { Checkpoint } from '@aztec/stdlib/checkpoint';
41
- import { SlashFactoryContract } from '@aztec/stdlib/l1-contracts';
48
+ import {
49
+ getLastL1SlotTimestampForL2Slot,
50
+ getNextL1SlotTimestamp,
51
+ getTimestampForSlot,
52
+ } from '@aztec/stdlib/epoch-helpers';
42
53
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
43
54
  import type { L1PublishCheckpointStats } from '@aztec/stdlib/stats';
44
55
  import { type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
45
56
 
46
- import { type StateOverride, type TransactionReceipt, type TypedDataDefinition, encodeFunctionData, toHex } from 'viem';
47
-
48
- import type { PublisherConfig, TxSenderConfig } from './config.js';
57
+ import {
58
+ type Abi,
59
+ type Hex,
60
+ type TransactionReceipt,
61
+ type TypedDataDefinition,
62
+ encodeFunctionData,
63
+ keccak256,
64
+ toHex,
65
+ } from 'viem';
66
+
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';
49
70
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
50
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
+
51
101
  /** Arguments to the process method of the rollup contract */
52
102
  type L1ProcessArgs = {
53
103
  /** The L2 block header. */
@@ -60,6 +110,8 @@ type L1ProcessArgs = {
60
110
  attestationsAndSigners: CommitteeAttestationsAndSigners;
61
111
  /** Attestations and signers signature */
62
112
  attestationsAndSignersSignature: Signature;
113
+ /** The fee asset price modifier in basis points (from oracle) */
114
+ feeAssetPriceModifier: bigint;
63
115
  };
64
116
 
65
117
  export const Actions = [
@@ -67,16 +119,13 @@ export const Actions = [
67
119
  'invalidate-by-insufficient-attestations',
68
120
  'propose',
69
121
  'governance-signal',
70
- 'empire-slashing-signal',
71
- 'create-empire-payload',
72
- 'execute-empire-payload',
73
122
  'vote-offenses',
74
123
  'execute-slash',
75
124
  ] as const;
76
125
 
77
126
  export type Action = (typeof Actions)[number];
78
127
 
79
- type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slashing-signal'>;
128
+ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
80
129
 
81
130
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
82
131
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
@@ -87,14 +136,22 @@ export type InvalidateCheckpointRequest = {
87
136
  gasUsed: bigint;
88
137
  checkpointNumber: CheckpointNumber;
89
138
  forcePendingCheckpointNumber: CheckpointNumber;
139
+ /** Archive at the rollback target checkpoint (checkpoint N-1). */
140
+ lastArchive: Fr;
141
+ };
142
+
143
+ type EnqueueProposeCheckpointOpts = {
144
+ txTimeoutAt?: Date;
90
145
  };
91
146
 
92
- interface RequestWithExpiry {
147
+ export interface RequestWithExpiry {
93
148
  action: Action;
94
149
  request: L1TxRequest;
95
150
  lastValidL2Slot: SlotNumber;
96
151
  gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
97
152
  blobConfig?: L1BlobInputs;
153
+ /** Gas consumed by validateBlobs; stashed for the bundle simulate at send time. */
154
+ blobEvaluationGas?: bigint;
98
155
  checkSuccess: (
99
156
  request: L1TxRequest,
100
157
  result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
@@ -104,69 +161,82 @@ interface RequestWithExpiry {
104
161
  export class SequencerPublisher {
105
162
  private interrupted = false;
106
163
  private metrics: SequencerPublisherMetrics;
164
+ private bundleSimulator: SequencerBundleSimulator;
107
165
  public epochCache: EpochCache;
166
+ private failedTxStore?: Promise<L1TxFailedStore | undefined>;
108
167
 
109
- protected governanceLog = createLogger('sequencer:publisher:governance');
110
- 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]);
111
174
 
112
175
  protected lastActions: Partial<Record<Action, SlotNumber>> = {};
113
176
 
114
- private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
115
-
116
177
  protected log: Logger;
117
178
  protected ethereumSlotDuration: bigint;
179
+ protected aztecSlotDuration: bigint;
180
+
181
+ /** Date provider for wall-clock time. */
182
+ private readonly dateProvider: DateProvider;
118
183
 
119
184
  private blobClient: BlobClientInterface;
120
185
 
121
- /** Address to use for simulations in fisherman mode (actual proposer's address) */
122
- 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>;
123
188
 
124
189
  /** L1 fee analyzer for fisherman mode */
125
190
  private l1FeeAnalyzer?: L1FeeAnalyzer;
126
- // A CALL to a cold address is 2700 gas
127
- public static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
128
191
 
129
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
130
- public static VOTE_GAS_GUESS: bigint = 800_000n;
192
+ /** Fee asset price oracle for computing price modifiers from Uniswap V4 */
193
+ private feeAssetPriceOracle: FeeAssetPriceOracle;
194
+
195
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */
196
+ private readonly interruptibleSleep = new InterruptibleSleep();
131
197
 
132
- public l1TxUtils: L1TxUtilsWithBlobs;
198
+ public l1TxUtils: L1TxUtils;
133
199
  public rollupContract: RollupContract;
134
200
  public govProposerContract: GovernanceProposerContract;
135
- public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
136
- public slashFactoryContract: SlashFactoryContract;
201
+ public slashingProposerContract: SlashingProposerContract | undefined;
137
202
 
138
203
  public readonly tracer: Tracer;
139
204
 
140
205
  protected requests: RequestWithExpiry[] = [];
141
206
 
142
207
  constructor(
143
- private config: TxSenderConfig & PublisherConfig & Pick<L1ContractsConfig, 'ethereumSlotDuration'>,
208
+ private config: Pick<SequencerPublisherConfig, 'fishermanMode' | 'l1TxFailedStore'> &
209
+ Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'> & { l1ChainId: number },
144
210
  deps: {
145
211
  telemetry?: TelemetryClient;
146
212
  blobClient: BlobClientInterface;
147
- l1TxUtils: L1TxUtilsWithBlobs;
213
+ l1TxUtils: L1TxUtils;
148
214
  rollupContract: RollupContract;
149
- slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
215
+ slashingProposerContract: SlashingProposerContract | undefined;
150
216
  governanceProposerContract: GovernanceProposerContract;
151
- slashFactoryContract: SlashFactoryContract;
152
217
  epochCache: EpochCache;
153
218
  dateProvider: DateProvider;
154
219
  metrics: SequencerPublisherMetrics;
155
220
  lastActions: Partial<Record<Action, SlotNumber>>;
156
221
  log?: Logger;
222
+ getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
157
223
  },
158
224
  ) {
159
225
  this.log = deps.log ?? createLogger('sequencer:publisher');
160
226
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
227
+ this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
228
+ this.dateProvider = deps.dateProvider;
161
229
  this.epochCache = deps.epochCache;
162
230
  this.lastActions = deps.lastActions;
163
231
 
164
232
  this.blobClient = deps.blobClient;
233
+ this.dateProvider = deps.dateProvider;
165
234
 
166
235
  const telemetry = deps.telemetry ?? getTelemetryClient();
167
236
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
168
237
  this.tracer = telemetry.getTracer('SequencerPublisher');
169
238
  this.l1TxUtils = deps.l1TxUtils;
239
+ this.getNextPublisher = deps.getNextPublisher;
170
240
 
171
241
  this.rollupContract = deps.rollupContract;
172
242
 
@@ -178,22 +248,71 @@ export class SequencerPublisher {
178
248
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
179
249
  this.slashingProposerContract = newSlashingProposer;
180
250
  });
181
- this.slashFactoryContract = deps.slashFactoryContract;
182
-
183
251
  // Initialize L1 fee analyzer for fisherman mode
184
252
  if (config.fishermanMode) {
185
253
  this.l1FeeAnalyzer = new L1FeeAnalyzer(
186
254
  this.l1TxUtils.client,
187
255
  deps.dateProvider,
188
- createLogger('sequencer:publisher:fee-analyzer'),
256
+ this.log.createChild('fee-analyzer'),
189
257
  );
190
258
  }
259
+
260
+ // Initialize fee asset price oracle
261
+ this.feeAssetPriceOracle = new FeeAssetPriceOracle(
262
+ this.l1TxUtils.client,
263
+ this.rollupContract,
264
+ this.log.createChild('price-oracle'),
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
+ });
191
298
  }
192
299
 
193
300
  public getRollupContract(): RollupContract {
194
301
  return this.rollupContract;
195
302
  }
196
303
 
304
+ /**
305
+ * Gets the fee asset price modifier from the oracle.
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.
311
+ */
312
+ public getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12?: bigint): Promise<bigint> {
313
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
314
+ }
315
+
197
316
  public getSenderAddress() {
198
317
  return this.l1TxUtils.getSenderAddress();
199
318
  }
@@ -205,20 +324,12 @@ export class SequencerPublisher {
205
324
  return this.l1FeeAnalyzer;
206
325
  }
207
326
 
208
- /**
209
- * Sets the proposer address to use for simulations in fisherman mode.
210
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
211
- */
212
- public setProposerAddressForSimulation(proposerAddress: EthAddress | undefined) {
213
- this.proposerAddressForSimulation = proposerAddress;
214
- }
215
-
216
327
  public addRequest(request: RequestWithExpiry) {
217
328
  this.requests.push(request);
218
329
  }
219
330
 
220
331
  public getCurrentL2Slot(): SlotNumber {
221
- return this.epochCache.getEpochAndSlotNow().slot;
332
+ return this.epochCache.getSlotNow();
222
333
  }
223
334
 
224
335
  /**
@@ -290,22 +401,26 @@ export class SequencerPublisher {
290
401
 
291
402
  /**
292
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.
293
408
  * @returns one of:
294
409
  * - A receipt and stats if the tx succeeded
295
410
  * - a receipt and errorMsg if it failed on L1
296
411
  * - undefined if no valid requests are found OR the tx failed to send.
297
412
  */
298
413
  @trackSpan('SequencerPublisher.sendRequests')
299
- public async sendRequests() {
414
+ public async sendRequests(targetSlot?: SlotNumber): Promise<SendRequestsResult | undefined> {
300
415
  const requestsToProcess = [...this.requests];
301
416
  this.requests = [];
417
+
302
418
  if (this.interrupted || requestsToProcess.length === 0) {
303
419
  return undefined;
304
420
  }
305
- const currentL2Slot = this.getCurrentL2Slot();
421
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
306
422
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
307
423
  const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
308
- const validActions = validRequests.map(x => x.action);
309
424
  const expiredActions = requestsToProcess
310
425
  .filter(request => request.lastValidL2Slot < currentL2Slot)
311
426
  .map(x => x.action);
@@ -328,53 +443,58 @@ export class SequencerPublisher {
328
443
  return undefined;
329
444
  }
330
445
 
331
- // @note - we can only have one blob config per bundle
332
- // find requests with gas and blob configs
333
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
334
- const gasConfigs = requestsToProcess.filter(request => request.gasConfig).map(request => request.gasConfig);
335
- const blobConfigs = requestsToProcess.filter(request => request.blobConfig).map(request => request.blobConfig);
336
-
337
- if (blobConfigs.length > 1) {
338
- throw new Error('Multiple blob configs found');
339
- }
340
-
341
- const blobConfig = blobConfigs[0];
342
-
343
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
344
- const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
345
- let gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
346
- // Cap at L1 block gas limit so the node accepts the tx ("gas limit too high" otherwise).
347
- const maxGas = MAX_L1_TX_LIMIT;
348
- if (gasLimit !== undefined && gasLimit > maxGas) {
349
- this.log.debug('Capping bundled tx gas limit to L1 max', {
350
- requested: gasLimit,
351
- capped: maxGas,
352
- });
353
- gasLimit = maxGas;
354
- }
446
+ // Collect earliest txTimeoutAt across all requests.
447
+ const gasConfigs = validRequests.filter(request => request.gasConfig).map(request => request.gasConfig);
355
448
  const txTimeoutAts = gasConfigs.map(g => g?.txTimeoutAt).filter((g): g is Date => g !== undefined);
356
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined; // earliest
357
- const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
449
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined;
358
450
 
359
451
  // Sort the requests so that proposals always go first
360
452
  // This ensures the committee gets precomputed correctly
361
453
  validRequests.sort((a, b) => compareActions(a.action, b.action));
362
454
 
363
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
+
364
481
  this.log.debug('Forwarding transactions', {
365
- validRequests: validRequests.map(request => request.action),
482
+ requests: requests.map(request => request.action),
366
483
  txConfig,
367
484
  });
368
- const result = await Multicall3.forward(
369
- validRequests.map(request => request.request),
370
- this.l1TxUtils,
371
- txConfig,
372
- blobConfig,
373
- this.rollupContract.address,
374
- this.log,
375
- );
376
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(validRequests, result);
377
- 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
+ };
378
498
  } catch (err) {
379
499
  const viemError = formatViemError(err);
380
500
  this.log.error(`Failed to publish bundled transactions`, viemError);
@@ -391,49 +511,193 @@ export class SequencerPublisher {
391
511
  }
392
512
  }
393
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
+
394
647
  private callbackBundledTransactions(
395
648
  requests: RequestWithExpiry[],
396
- result?: { receipt: TransactionReceipt } | FormattedViemError,
649
+ result: { receipt: TransactionReceipt; multicallData: Hex },
397
650
  ) {
398
651
  const actionsListStr = requests.map(r => r.action).join(', ');
399
- if (result instanceof FormattedViemError) {
400
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
401
- return { failedActions: requests.map(r => r.action) };
402
- } else {
403
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, { result, requests });
404
- const successfulActions: Action[] = [];
405
- const failedActions: Action[] = [];
406
- for (const request of requests) {
407
- if (request.checkSuccess(request.request, result)) {
408
- successfulActions.push(request.action);
409
- } else {
410
- failedActions.push(request.action);
411
- }
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);
412
669
  }
413
- return { successfulActions, failedActions };
414
670
  }
671
+ return { successfulActions, failedActions };
415
672
  }
416
673
 
417
674
  /**
418
- * @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
419
676
  * @param tipArchive - The archive to check
420
677
  * @returns The slot and block number if it is possible to propose, undefined otherwise
421
678
  */
422
- public canProposeAtNextEthBlock(
423
- tipArchive: Fr,
424
- msgSender: EthAddress,
425
- opts: { forcePendingCheckpointNumber?: CheckpointNumber } = {},
426
- ) {
679
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
427
680
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
428
- 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;
429
690
 
430
691
  return this.rollupContract
431
- .canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
432
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
433
- })
692
+ .canProposeAt(
693
+ tipArchive.toBuffer(),
694
+ msgSender.toString(),
695
+ nextL1SlotTs,
696
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
697
+ )
434
698
  .catch(err => {
435
- if (err instanceof FormattedViemError && ignoredErrors.find(e => err.message.includes(e))) {
436
- 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))}`, {
437
701
  error: err.message,
438
702
  });
439
703
  } else {
@@ -442,6 +706,7 @@ export class SequencerPublisher {
442
706
  return undefined;
443
707
  });
444
708
  }
709
+
445
710
  /**
446
711
  * @notice Will simulate `validateHeader` to make sure that the block header is valid
447
712
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
@@ -451,13 +716,13 @@ export class SequencerPublisher {
451
716
  @trackSpan('SequencerPublisher.validateBlockHeader')
452
717
  public async validateBlockHeader(
453
718
  header: CheckpointHeader,
454
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
719
+ simulationOverridesPlan?: SimulationOverridesPlan,
455
720
  ): Promise<void> {
456
721
  const flags = { ignoreDA: true, ignoreSignatures: true };
457
722
 
458
723
  const args = [
459
724
  header.toViem(),
460
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
725
+ CommitteeAttestationsAndSigners.packAttestations([]),
461
726
  [], // no signers
462
727
  Signature.empty().toViemSignature(),
463
728
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -465,10 +730,9 @@ export class SequencerPublisher {
465
730
  flags,
466
731
  ] as const;
467
732
 
468
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
469
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
470
- opts?.forcePendingCheckpointNumber,
471
- );
733
+ const l1Constants = this.epochCache.getL1Constants();
734
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
735
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
472
736
  let balance = 0n;
473
737
  if (this.config.fishermanMode) {
474
738
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -488,7 +752,7 @@ export class SequencerPublisher {
488
752
  data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
489
753
  from: MULTI_CALL_3_ADDRESS,
490
754
  },
491
- { time: ts + 1n },
755
+ { time: ts },
492
756
  stateOverrides,
493
757
  );
494
758
  this.log.debug(`Simulated validateHeader`);
@@ -521,6 +785,8 @@ export class SequencerPublisher {
521
785
  const request = this.buildInvalidateCheckpointRequest(validationResult);
522
786
  this.log.debug(`Simulating invalidate checkpoint ${checkpointNumber}`, { ...logData, request });
523
787
 
788
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
789
+
524
790
  try {
525
791
  const { gasUsed } = await this.l1TxUtils.simulate(
526
792
  request,
@@ -539,6 +805,7 @@ export class SequencerPublisher {
539
805
  gasUsed,
540
806
  checkpointNumber,
541
807
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
808
+ lastArchive: validationResult.checkpoint.lastArchive,
542
809
  reason,
543
810
  };
544
811
  } catch (err) {
@@ -551,8 +818,8 @@ export class SequencerPublisher {
551
818
  `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
552
819
  { ...logData, request, error: viemError.message },
553
820
  );
554
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
555
- if (latestPendingCheckpointNumber < checkpointNumber) {
821
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
822
+ if (latestProposedCheckpointNumber < checkpointNumber) {
556
823
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
557
824
  return undefined;
558
825
  } else {
@@ -572,6 +839,18 @@ export class SequencerPublisher {
572
839
 
573
840
  // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
574
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
+ });
575
854
  throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, { cause: viemError });
576
855
  }
577
856
  }
@@ -585,9 +864,7 @@ export class SequencerPublisher {
585
864
  const logData = { ...checkpoint, reason };
586
865
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
587
866
 
588
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
589
- validationResult.attestations,
590
- ).getPackedAttestations();
867
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
591
868
 
592
869
  if (reason === 'invalid-attestation') {
593
870
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -608,59 +885,11 @@ export class SequencerPublisher {
608
885
  }
609
886
  }
610
887
 
611
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */
612
- @trackSpan('SequencerPublisher.validateCheckpointForSubmission')
613
- public async validateCheckpointForSubmission(
614
- checkpoint: Checkpoint,
615
- attestationsAndSigners: CommitteeAttestationsAndSigners,
616
- attestationsAndSignersSignature: Signature,
617
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
618
- ): Promise<bigint> {
619
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
620
-
621
- // TODO(palla/mbps): This should not be needed, there's no flow where we propose with zero attestations. Or is there?
622
- // If we have no attestations, we still need to provide the empty attestations
623
- // so that the committee is recalculated correctly
624
- // const ignoreSignatures = attestationsAndSigners.attestations.length === 0;
625
- // if (ignoreSignatures) {
626
- // const { committee } = await this.epochCache.getCommittee(block.header.globalVariables.slotNumber);
627
- // if (!committee) {
628
- // this.log.warn(`No committee found for slot ${block.header.globalVariables.slotNumber}`);
629
- // throw new Error(`No committee found for slot ${block.header.globalVariables.slotNumber}`);
630
- // }
631
- // attestationsAndSigners.attestations = committee.map(committeeMember =>
632
- // CommitteeAttestation.fromAddress(committeeMember),
633
- // );
634
- // }
635
-
636
- const blobFields = checkpoint.toBlobFields();
637
- const blobs = getBlobsPerL1Block(blobFields);
638
- const blobInput = getPrefixedEthBlobCommitments(blobs);
639
-
640
- const args = [
641
- {
642
- header: checkpoint.header.toViem(),
643
- archive: toHex(checkpoint.archive.root.toBuffer()),
644
- oracleInput: {
645
- feeAssetPriceModifier: 0n,
646
- },
647
- },
648
- attestationsAndSigners.getPackedAttestations(),
649
- attestationsAndSigners.getSigners().map(signer => signer.toString()),
650
- attestationsAndSignersSignature.toViemSignature(),
651
- blobInput,
652
- ] as const;
653
-
654
- await this.simulateProposeTx(args, ts, options);
655
- return ts;
656
- }
657
-
658
888
  private async enqueueCastSignalHelper(
659
889
  slotNumber: SlotNumber,
660
- timestamp: bigint,
661
890
  signalType: GovernanceSignalAction,
662
891
  payload: EthAddress,
663
- base: IEmpireBase,
892
+ base: GovernanceProposerContract,
664
893
  signerAddress: EthAddress,
665
894
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
666
895
  ): Promise<boolean> {
@@ -686,11 +915,31 @@ export class SequencerPublisher {
686
915
  return false;
687
916
  }
688
917
 
689
- if (await this.isPayloadEmpty(payload)) {
918
+ if (await base.isPayloadEmpty(payload)) {
690
919
  this.log.warn(`Skipping vote cast for payload with empty code`);
691
920
  return false;
692
921
  }
693
922
 
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);
936
+ }
937
+
938
+ if (proposed) {
939
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
940
+ return false;
941
+ }
942
+
694
943
  const cachedLastVote = this.lastActions[signalType];
695
944
  this.lastActions[signalType] = slotNumber;
696
945
  const action = signalType;
@@ -709,26 +958,19 @@ export class SequencerPublisher {
709
958
  lastValidL2Slot: slotNumber,
710
959
  });
711
960
 
712
- try {
713
- await this.l1TxUtils.simulate(request, { time: timestamp }, [], mergeAbis([request.abi ?? [], ErrorsAbi]));
714
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, { request });
715
- } catch (err) {
716
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, err);
717
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
718
- }
719
-
720
961
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
721
962
  this.addRequest({
722
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
723
963
  action,
724
964
  request,
725
965
  lastValidL2Slot: slotNumber,
726
966
  checkSuccess: (_request, result) => {
727
967
  const success =
728
968
  result &&
729
- result.receipt &&
730
- result.receipt.status === 'success' &&
731
- 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
+ });
732
974
 
733
975
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
734
976
  if (!success) {
@@ -750,33 +992,19 @@ export class SequencerPublisher {
750
992
  return true;
751
993
  }
752
994
 
753
- private async isPayloadEmpty(payload: EthAddress): Promise<boolean> {
754
- const key = payload.toString();
755
- const cached = this.isPayloadEmptyCache.get(key);
756
- if (cached) {
757
- return cached;
758
- }
759
- const isEmpty = !(await this.l1TxUtils.getCode(payload));
760
- this.isPayloadEmptyCache.set(key, isEmpty);
761
- return isEmpty;
762
- }
763
-
764
995
  /**
765
996
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
766
997
  * @param slotNumber - The slot number to cast a signal for.
767
- * @param timestamp - The timestamp of the slot to cast a signal for.
768
998
  * @returns True if the signal was successfully enqueued, false otherwise.
769
999
  */
770
1000
  public enqueueGovernanceCastSignal(
771
1001
  governancePayload: EthAddress,
772
1002
  slotNumber: SlotNumber,
773
- timestamp: bigint,
774
1003
  signerAddress: EthAddress,
775
1004
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
776
1005
  ): Promise<boolean> {
777
1006
  return this.enqueueCastSignalHelper(
778
1007
  slotNumber,
779
- timestamp,
780
1008
  'governance-signal',
781
1009
  governancePayload,
782
1010
  this.govProposerContract,
@@ -789,7 +1017,6 @@ export class SequencerPublisher {
789
1017
  public async enqueueSlashingActions(
790
1018
  actions: ProposerSlashAction[],
791
1019
  slotNumber: SlotNumber,
792
- timestamp: bigint,
793
1020
  signerAddress: EthAddress,
794
1021
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
795
1022
  ): Promise<boolean> {
@@ -800,58 +1027,6 @@ export class SequencerPublisher {
800
1027
 
801
1028
  for (const action of actions) {
802
1029
  switch (action.type) {
803
- case 'vote-empire-payload': {
804
- if (this.slashingProposerContract?.type !== 'empire') {
805
- this.log.error('Cannot vote for empire payload on non-empire slashing contract');
806
- break;
807
- }
808
- this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
809
- signerAddress,
810
- });
811
- await this.enqueueCastSignalHelper(
812
- slotNumber,
813
- timestamp,
814
- 'empire-slashing-signal',
815
- action.payload,
816
- this.slashingProposerContract,
817
- signerAddress,
818
- signer,
819
- );
820
- break;
821
- }
822
-
823
- case 'create-empire-payload': {
824
- this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, { slotNumber, signerAddress });
825
- const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
826
- await this.simulateAndEnqueueRequest(
827
- 'create-empire-payload',
828
- request,
829
- (receipt: TransactionReceipt) =>
830
- !!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs),
831
- slotNumber,
832
- timestamp,
833
- );
834
- break;
835
- }
836
-
837
- case 'execute-empire-payload': {
838
- this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, { slotNumber, signerAddress });
839
- if (this.slashingProposerContract?.type !== 'empire') {
840
- this.log.error('Cannot execute slashing payload on non-empire slashing contract');
841
- return false;
842
- }
843
- const empireSlashingProposer = this.slashingProposerContract as EmpireSlashingProposerContract;
844
- const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
845
- await this.simulateAndEnqueueRequest(
846
- 'execute-empire-payload',
847
- request,
848
- (receipt: TransactionReceipt) => !!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs),
849
- slotNumber,
850
- timestamp,
851
- );
852
- break;
853
- }
854
-
855
1030
  case 'vote-offenses': {
856
1031
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
857
1032
  slotNumber,
@@ -859,19 +1034,21 @@ export class SequencerPublisher {
859
1034
  votesCount: action.votes.length,
860
1035
  signerAddress,
861
1036
  });
862
- if (this.slashingProposerContract?.type !== 'tally') {
863
- 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');
864
1039
  return false;
865
1040
  }
866
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
867
1041
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
868
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
869
- await this.simulateAndEnqueueRequest(
1042
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1043
+ this.enqueueRequest(
870
1044
  'vote-offenses',
871
1045
  request,
872
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1046
+ {
1047
+ address: this.slashingProposerContract.address.toString(),
1048
+ abi: SlashingProposerAbi,
1049
+ eventName: 'VoteCast',
1050
+ },
873
1051
  slotNumber,
874
- timestamp,
875
1052
  );
876
1053
  break;
877
1054
  }
@@ -882,18 +1059,23 @@ export class SequencerPublisher {
882
1059
  round: action.round,
883
1060
  signerAddress,
884
1061
  });
885
- if (this.slashingProposerContract?.type !== 'tally') {
886
- 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');
887
1064
  return false;
888
1065
  }
889
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
890
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
891
- await this.simulateAndEnqueueRequest(
1066
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1067
+ action.round,
1068
+ action.committees,
1069
+ );
1070
+ this.enqueueRequest(
892
1071
  'execute-slash',
893
- request,
894
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1072
+ executeRequest,
1073
+ {
1074
+ address: this.slashingProposerContract.address.toString(),
1075
+ abi: SlashingProposerAbi,
1076
+ eventName: 'RoundExecuted',
1077
+ },
895
1078
  slotNumber,
896
- timestamp,
897
1079
  );
898
1080
  break;
899
1081
  }
@@ -908,51 +1090,32 @@ export class SequencerPublisher {
908
1090
  return true;
909
1091
  }
910
1092
 
911
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1093
+ /** Enqueues a proposal for a checkpoint on L1 */
912
1094
  public async enqueueProposeCheckpoint(
913
1095
  checkpoint: Checkpoint,
914
1096
  attestationsAndSigners: CommitteeAttestationsAndSigners,
915
1097
  attestationsAndSignersSignature: Signature,
916
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1098
+ opts: EnqueueProposeCheckpointOpts = {},
917
1099
  ): Promise<void> {
918
1100
  const checkpointHeader = checkpoint.header;
919
1101
 
920
1102
  const blobFields = checkpoint.toBlobFields();
921
- const blobs = getBlobsPerL1Block(blobFields);
1103
+ const blobs = await getBlobsPerL1Block(blobFields);
922
1104
 
923
- const proposeTxArgs = {
1105
+ const proposeTxArgs: L1ProcessArgs = {
924
1106
  header: checkpointHeader,
925
1107
  archive: checkpoint.archive.root.toBuffer(),
926
1108
  blobs,
927
1109
  attestationsAndSigners,
928
1110
  attestationsAndSignersSignature,
1111
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
929
1112
  };
930
1113
 
931
- let ts: bigint;
932
-
933
- try {
934
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
935
- // This means that we can avoid the simulation issues in later checks.
936
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
937
- // make time consistency checks break.
938
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
939
- ts = await this.validateCheckpointForSubmission(
940
- checkpoint,
941
- attestationsAndSigners,
942
- attestationsAndSignersSignature,
943
- opts,
944
- );
945
- } catch (err: any) {
946
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
947
- ...checkpoint.getStats(),
948
- slotNumber: checkpoint.header.slotNumber,
949
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
950
- });
951
- throw err;
952
- }
953
-
954
- this.log.verbose(`Enqueuing checkpoint propose transaction`, { ...checkpoint.toCheckpointInfo(), ...opts });
955
- 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 });
956
1119
  }
957
1120
 
958
1121
  public enqueueInvalidateCheckpoint(
@@ -963,23 +1126,22 @@ export class SequencerPublisher {
963
1126
  return;
964
1127
  }
965
1128
 
966
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
967
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(request.gasUsed) * 64) / 63)));
968
-
969
1129
  const { gasUsed, checkpointNumber } = request;
970
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1130
+ const logData = { gasUsed, checkpointNumber, opts };
971
1131
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
972
1132
  this.addRequest({
973
1133
  action: `invalidate-by-${request.reason}`,
974
1134
  request: request.request,
975
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1135
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
976
1136
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
977
1137
  checkSuccess: (_req, result) => {
978
1138
  const success =
979
1139
  result &&
980
- result.receipt &&
981
- result.receipt.status === 'success' &&
982
- 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
+ });
983
1145
  if (!success) {
984
1146
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
985
1147
  } else {
@@ -990,57 +1152,36 @@ export class SequencerPublisher {
990
1152
  });
991
1153
  }
992
1154
 
993
- 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(
994
1161
  action: Action,
995
1162
  request: L1TxRequest,
996
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1163
+ eventOpts: { address: string; abi: Abi; eventName: string },
997
1164
  slotNumber: SlotNumber,
998
- timestamp: bigint,
999
- ) {
1000
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1165
+ ): boolean {
1001
1166
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1002
1167
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1003
1168
  return false;
1004
1169
  }
1005
-
1006
1170
  const cachedLastActionSlot = this.lastActions[action];
1007
1171
  this.lastActions[action] = slotNumber;
1008
1172
 
1009
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1010
-
1011
- let gasUsed: bigint;
1012
- const simulateAbi = mergeAbis([request.abi ?? [], ErrorsAbi]);
1013
- try {
1014
- ({ gasUsed } = await this.l1TxUtils.simulate(request, { time: timestamp }, [], simulateAbi)); // TODO(palla/slash): Check the timestamp logic
1015
- this.log.verbose(`Simulation for ${action} succeeded`, { ...logData, request, gasUsed });
1016
- } catch (err) {
1017
- const viemError = formatViemError(err, simulateAbi);
1018
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1019
-
1020
- return false;
1021
- }
1022
-
1023
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1024
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(gasUsed) * 64) / 63)));
1025
- logData.gasLimit = gasLimit;
1026
-
1027
- // Store the ABI used for simulation on the request so Multicall3.forward can decode errors
1028
- // when the tx is sent and a revert is diagnosed via simulation.
1029
- const requestWithAbi = { ...request, abi: simulateAbi };
1030
-
1031
- this.log.debug(`Enqueuing ${action}`, logData);
1173
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1032
1174
  this.addRequest({
1033
1175
  action,
1034
- request: requestWithAbi,
1035
- gasConfig: { gasLimit },
1176
+ request,
1036
1177
  lastValidL2Slot: slotNumber,
1037
- checkSuccess: (_req, result) => {
1038
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1178
+ checkSuccess: (_request, result) => {
1179
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1039
1180
  if (!success) {
1040
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1181
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1041
1182
  this.lastActions[action] = cachedLastActionSlot;
1042
1183
  } else {
1043
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1184
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1044
1185
  }
1045
1186
  return !!success;
1046
1187
  },
@@ -1056,6 +1197,7 @@ export class SequencerPublisher {
1056
1197
  */
1057
1198
  public interrupt() {
1058
1199
  this.interrupted = true;
1200
+ this.interruptibleSleep.interrupt();
1059
1201
  this.l1TxUtils.interrupt();
1060
1202
  }
1061
1203
 
@@ -1065,11 +1207,7 @@ export class SequencerPublisher {
1065
1207
  this.l1TxUtils.restart();
1066
1208
  }
1067
1209
 
1068
- private async prepareProposeTx(
1069
- encodedData: L1ProcessArgs,
1070
- timestamp: bigint,
1071
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1072
- ) {
1210
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1073
1211
  const kzg = Blob.getViemKzgInstance();
1074
1212
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1075
1213
  this.log.debug('Validating blob input', { blobInput });
@@ -1082,7 +1220,11 @@ export class SequencerPublisher {
1082
1220
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1083
1221
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1084
1222
  } else {
1085
- // 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.
1086
1228
  blobEvaluationGas = await this.l1TxUtils
1087
1229
  .estimateGas(
1088
1230
  this.getSenderAddress().toString(),
@@ -1100,9 +1242,27 @@ export class SequencerPublisher {
1100
1242
  kzg,
1101
1243
  },
1102
1244
  )
1103
- .catch(err => {
1104
- const { message, metaMessages } = formatViemError(err);
1105
- 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
+ });
1106
1266
  throw new Error('Failed to validate blobs');
1107
1267
  });
1108
1268
  }
@@ -1113,8 +1273,7 @@ export class SequencerPublisher {
1113
1273
  header: encodedData.header.toViem(),
1114
1274
  archive: toHex(encodedData.archive),
1115
1275
  oracleInput: {
1116
- // We are currently not modifying these. See #9963
1117
- feeAssetPriceModifier: 0n,
1276
+ feeAssetPriceModifier: encodedData.feeAssetPriceModifier,
1118
1277
  },
1119
1278
  },
1120
1279
  encodedData.attestationsAndSigners.getPackedAttestations(),
@@ -1123,124 +1282,21 @@ export class SequencerPublisher {
1123
1282
  blobInput,
1124
1283
  ] as const;
1125
1284
 
1126
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1285
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1127
1286
 
1128
- return { args, blobEvaluationGas, rollupData, simulationResult };
1129
- }
1130
-
1131
- /**
1132
- * Simulates the propose tx with eth_simulateV1
1133
- * @param args - The propose tx args
1134
- * @param timestamp - The timestamp to simulate proposal at
1135
- * @returns The simulation result
1136
- */
1137
- private async simulateProposeTx(
1138
- args: readonly [
1139
- {
1140
- readonly header: ViemHeader;
1141
- readonly archive: `0x${string}`;
1142
- readonly oracleInput: {
1143
- readonly feeAssetPriceModifier: 0n;
1144
- };
1145
- },
1146
- ViemCommitteeAttestations,
1147
- `0x${string}`[], // Signers
1148
- ViemSignature,
1149
- `0x${string}`,
1150
- ],
1151
- timestamp: bigint,
1152
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1153
- ) {
1154
- const rollupData = encodeFunctionData({
1155
- abi: RollupAbi,
1156
- functionName: 'propose',
1157
- args,
1158
- });
1159
-
1160
- // override the pending checkpoint number if requested
1161
- const forcePendingCheckpointNumberStateDiff = (
1162
- options.forcePendingCheckpointNumber !== undefined
1163
- ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber)
1164
- : []
1165
- ).flatMap(override => override.stateDiff ?? []);
1166
-
1167
- const stateOverrides: StateOverride = [
1168
- {
1169
- address: this.rollupContract.address,
1170
- // @note we override checkBlob to false since blobs are not part simulate()
1171
- stateDiff: [
1172
- { slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true), value: toPaddedHex(0n, true) },
1173
- ...forcePendingCheckpointNumberStateDiff,
1174
- ],
1175
- },
1176
- ];
1177
- // In fisherman mode, simulate as the proposer but with sufficient balance
1178
- if (this.proposerAddressForSimulation) {
1179
- stateOverrides.push({
1180
- address: this.proposerAddressForSimulation.toString(),
1181
- balance: 10n * WEI_CONST * WEI_CONST, // 10 ETH
1182
- });
1183
- }
1184
-
1185
- const simulationResult = await this.l1TxUtils
1186
- .simulate(
1187
- {
1188
- to: this.rollupContract.address,
1189
- data: rollupData,
1190
- gas: MAX_L1_TX_LIMIT,
1191
- ...(this.proposerAddressForSimulation && { from: this.proposerAddressForSimulation.toString() }),
1192
- },
1193
- {
1194
- // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
1195
- time: timestamp + 1n,
1196
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1197
- gasLimit: MAX_L1_TX_LIMIT * 2n,
1198
- },
1199
- stateOverrides,
1200
- RollupAbi,
1201
- {
1202
- // @note fallback gas estimate to use if the node doesn't support simulation API
1203
- fallbackGasEstimate: MAX_L1_TX_LIMIT,
1204
- },
1205
- )
1206
- .catch(err => {
1207
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1208
- const viemError = formatViemError(err);
1209
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1210
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1211
- // Return a minimal simulation result with the fallback gas estimate
1212
- return {
1213
- gasUsed: MAX_L1_TX_LIMIT,
1214
- logs: [],
1215
- };
1216
- }
1217
- this.log.error(`Failed to simulate propose tx`, viemError);
1218
- throw err;
1219
- });
1220
-
1221
- return { rollupData, simulationResult };
1287
+ return { args, blobEvaluationGas, rollupData };
1222
1288
  }
1223
1289
 
1224
1290
  private async addProposeTx(
1225
1291
  checkpoint: Checkpoint,
1226
1292
  encodedData: L1ProcessArgs,
1227
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1228
- timestamp: bigint,
1293
+ opts: EnqueueProposeCheckpointOpts = {},
1229
1294
  ): Promise<void> {
1230
1295
  const slot = checkpoint.header.slotNumber;
1231
1296
  const timer = new Timer();
1232
1297
  const kzg = Blob.getViemKzgInstance();
1233
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
1234
- encodedData,
1235
- timestamp,
1236
- opts,
1237
- );
1298
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1238
1299
  const startBlock = await this.l1TxUtils.getBlockNumber();
1239
- const gasLimit = this.l1TxUtils.bumpGasLimit(
1240
- BigInt(Math.ceil((Number(simulationResult.gasUsed) * 64) / 63)) +
1241
- blobEvaluationGas +
1242
- SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS, // We issue the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1243
- );
1244
1300
 
1245
1301
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1246
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.
@@ -1257,7 +1313,8 @@ export class SequencerPublisher {
1257
1313
  data: rollupData,
1258
1314
  },
1259
1315
  lastValidL2Slot: checkpoint.header.slotNumber,
1260
- gasConfig: { ...opts, gasLimit },
1316
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1317
+ blobEvaluationGas,
1261
1318
  blobConfig: {
1262
1319
  blobs: encodedData.blobs.map(b => b.data),
1263
1320
  kzg,
@@ -1267,10 +1324,11 @@ export class SequencerPublisher {
1267
1324
  return false;
1268
1325
  }
1269
1326
  const { receipt, stats, errorMsg } = result;
1270
- const success =
1271
- receipt &&
1272
- receipt.status === 'success' &&
1273
- 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
+ });
1274
1332
 
1275
1333
  if (success) {
1276
1334
  const endBlock = receipt.blockNumber;
@@ -1310,4 +1368,10 @@ export class SequencerPublisher {
1310
1368
  },
1311
1369
  });
1312
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
+ }
1313
1377
  }