@aztec/sequencer-client 0.0.1-commit.023c3e5 → 0.0.1-commit.031e54b

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 +281 -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 +65 -32
  5. package/dest/config.d.ts +28 -6
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +76 -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 +439 -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 +509 -0
  55. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  56. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  57. package/dest/sequencer/chain_state_overrides.js +98 -0
  58. package/dest/sequencer/checkpoint_proposal_job.d.ts +65 -11
  59. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  60. package/dest/sequencer/checkpoint_proposal_job.js +849 -249
  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 +48 -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 +85 -22
  76. package/dest/sequencer/sequencer.d.ts.map +1 -1
  77. package/dest/sequencer/sequencer.js +380 -137
  78. package/dest/sequencer/timetable.d.ts +14 -6
  79. package/dest/sequencer/timetable.d.ts.map +1 -1
  80. package/dest/sequencer/timetable.js +47 -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 +91 -35
  93. package/src/config.ts +98 -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 +532 -469
  109. package/src/sequencer/README.md +162 -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 +595 -0
  113. package/src/sequencer/chain_state_overrides.ts +162 -0
  114. package/src/sequencer/checkpoint_proposal_job.ts +1026 -268
  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 +51 -2
  118. package/src/sequencer/index.ts +2 -0
  119. package/src/sequencer/metrics.ts +132 -25
  120. package/src/sequencer/sequencer.ts +470 -156
  121. package/src/sequencer/timetable.ts +62 -56
  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 (the production path, via
405
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
406
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
407
+ * AutomineSequencer, which publishes synchronously within the current slot.
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,192 @@ 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 slotOffset = this.aztecSlotDuration;
688
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
429
689
 
430
690
  return this.rollupContract
431
- .canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
432
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
433
- })
691
+ .canProposeAt(
692
+ tipArchive.toBuffer(),
693
+ msgSender.toString(),
694
+ nextL1SlotTs,
695
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
696
+ )
434
697
  .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))}`, {
698
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
699
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
437
700
  error: err.message,
438
701
  });
439
702
  } else {
@@ -442,6 +705,7 @@ export class SequencerPublisher {
442
705
  return undefined;
443
706
  });
444
707
  }
708
+
445
709
  /**
446
710
  * @notice Will simulate `validateHeader` to make sure that the block header is valid
447
711
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
@@ -451,13 +715,13 @@ export class SequencerPublisher {
451
715
  @trackSpan('SequencerPublisher.validateBlockHeader')
452
716
  public async validateBlockHeader(
453
717
  header: CheckpointHeader,
454
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
718
+ simulationOverridesPlan?: SimulationOverridesPlan,
455
719
  ): Promise<void> {
456
720
  const flags = { ignoreDA: true, ignoreSignatures: true };
457
721
 
458
722
  const args = [
459
723
  header.toViem(),
460
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
724
+ CommitteeAttestationsAndSigners.packAttestations([]),
461
725
  [], // no signers
462
726
  Signature.empty().toViemSignature(),
463
727
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -465,10 +729,9 @@ export class SequencerPublisher {
465
729
  flags,
466
730
  ] as const;
467
731
 
468
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
469
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
470
- opts?.forcePendingCheckpointNumber,
471
- );
732
+ const l1Constants = this.epochCache.getL1Constants();
733
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
734
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
472
735
  let balance = 0n;
473
736
  if (this.config.fishermanMode) {
474
737
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -488,7 +751,7 @@ export class SequencerPublisher {
488
751
  data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
489
752
  from: MULTI_CALL_3_ADDRESS,
490
753
  },
491
- { time: ts + 1n },
754
+ { time: ts },
492
755
  stateOverrides,
493
756
  );
494
757
  this.log.debug(`Simulated validateHeader`);
@@ -521,6 +784,8 @@ export class SequencerPublisher {
521
784
  const request = this.buildInvalidateCheckpointRequest(validationResult);
522
785
  this.log.debug(`Simulating invalidate checkpoint ${checkpointNumber}`, { ...logData, request });
523
786
 
787
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
788
+
524
789
  try {
525
790
  const { gasUsed } = await this.l1TxUtils.simulate(
526
791
  request,
@@ -539,6 +804,7 @@ export class SequencerPublisher {
539
804
  gasUsed,
540
805
  checkpointNumber,
541
806
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
807
+ lastArchive: validationResult.checkpoint.lastArchive,
542
808
  reason,
543
809
  };
544
810
  } catch (err) {
@@ -551,8 +817,8 @@ export class SequencerPublisher {
551
817
  `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
552
818
  { ...logData, request, error: viemError.message },
553
819
  );
554
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
555
- if (latestPendingCheckpointNumber < checkpointNumber) {
820
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
821
+ if (latestProposedCheckpointNumber < checkpointNumber) {
556
822
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
557
823
  return undefined;
558
824
  } else {
@@ -572,6 +838,18 @@ export class SequencerPublisher {
572
838
 
573
839
  // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
574
840
  this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
841
+ this.backupFailedTx({
842
+ id: keccak256(request.data!),
843
+ failureType: 'simulation',
844
+ request: { to: request.to!, data: request.data!, value: request.value?.toString() },
845
+ l1BlockNumber: l1BlockNumber.toString(),
846
+ error: { message: viemError.message, name: viemError.name },
847
+ context: {
848
+ actions: [`invalidate-${reason}`],
849
+ checkpointNumber,
850
+ sender: this.getSenderAddress().toString(),
851
+ },
852
+ });
575
853
  throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, { cause: viemError });
576
854
  }
577
855
  }
@@ -585,9 +863,7 @@ export class SequencerPublisher {
585
863
  const logData = { ...checkpoint, reason };
586
864
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
587
865
 
588
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
589
- validationResult.attestations,
590
- ).getPackedAttestations();
866
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
591
867
 
592
868
  if (reason === 'invalid-attestation') {
593
869
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -608,59 +884,11 @@ export class SequencerPublisher {
608
884
  }
609
885
  }
610
886
 
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
887
  private async enqueueCastSignalHelper(
659
888
  slotNumber: SlotNumber,
660
- timestamp: bigint,
661
889
  signalType: GovernanceSignalAction,
662
890
  payload: EthAddress,
663
- base: IEmpireBase,
891
+ base: GovernanceProposerContract,
664
892
  signerAddress: EthAddress,
665
893
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
666
894
  ): Promise<boolean> {
@@ -686,11 +914,31 @@ export class SequencerPublisher {
686
914
  return false;
687
915
  }
688
916
 
689
- if (await this.isPayloadEmpty(payload)) {
917
+ if (await base.isPayloadEmpty(payload)) {
690
918
  this.log.warn(`Skipping vote cast for payload with empty code`);
691
919
  return false;
692
920
  }
693
921
 
922
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
923
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
924
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
925
+ // the same payload in a future round.
926
+ let proposed = false;
927
+ try {
928
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
929
+ } catch (err) {
930
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
931
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
932
+ // participation entirely; failing open at worst produces a duplicate signal that the
933
+ // contract will simply count alongside others in the round.
934
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
935
+ }
936
+
937
+ if (proposed) {
938
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
939
+ return false;
940
+ }
941
+
694
942
  const cachedLastVote = this.lastActions[signalType];
695
943
  this.lastActions[signalType] = slotNumber;
696
944
  const action = signalType;
@@ -709,26 +957,19 @@ export class SequencerPublisher {
709
957
  lastValidL2Slot: slotNumber,
710
958
  });
711
959
 
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
960
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
721
961
  this.addRequest({
722
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
723
962
  action,
724
963
  request,
725
964
  lastValidL2Slot: slotNumber,
726
965
  checkSuccess: (_request, result) => {
727
966
  const success =
728
967
  result &&
729
- result.receipt &&
730
- result.receipt.status === 'success' &&
731
- tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
968
+ extractEventSuccess(result.receipt, {
969
+ address: base.address.toString(),
970
+ abi: EmpireBaseAbi,
971
+ eventName: 'SignalCast',
972
+ });
732
973
 
733
974
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
734
975
  if (!success) {
@@ -750,33 +991,19 @@ export class SequencerPublisher {
750
991
  return true;
751
992
  }
752
993
 
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
994
  /**
765
995
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
766
996
  * @param slotNumber - The slot number to cast a signal for.
767
- * @param timestamp - The timestamp of the slot to cast a signal for.
768
997
  * @returns True if the signal was successfully enqueued, false otherwise.
769
998
  */
770
999
  public enqueueGovernanceCastSignal(
771
1000
  governancePayload: EthAddress,
772
1001
  slotNumber: SlotNumber,
773
- timestamp: bigint,
774
1002
  signerAddress: EthAddress,
775
1003
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
776
1004
  ): Promise<boolean> {
777
1005
  return this.enqueueCastSignalHelper(
778
1006
  slotNumber,
779
- timestamp,
780
1007
  'governance-signal',
781
1008
  governancePayload,
782
1009
  this.govProposerContract,
@@ -789,7 +1016,6 @@ export class SequencerPublisher {
789
1016
  public async enqueueSlashingActions(
790
1017
  actions: ProposerSlashAction[],
791
1018
  slotNumber: SlotNumber,
792
- timestamp: bigint,
793
1019
  signerAddress: EthAddress,
794
1020
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
795
1021
  ): Promise<boolean> {
@@ -800,58 +1026,6 @@ export class SequencerPublisher {
800
1026
 
801
1027
  for (const action of actions) {
802
1028
  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
1029
  case 'vote-offenses': {
856
1030
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
857
1031
  slotNumber,
@@ -859,19 +1033,21 @@ export class SequencerPublisher {
859
1033
  votesCount: action.votes.length,
860
1034
  signerAddress,
861
1035
  });
862
- if (this.slashingProposerContract?.type !== 'tally') {
863
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1036
+ if (!this.slashingProposerContract) {
1037
+ this.log.error('No slashing proposer contract available');
864
1038
  return false;
865
1039
  }
866
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
867
1040
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
868
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
869
- await this.simulateAndEnqueueRequest(
1041
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1042
+ this.enqueueRequest(
870
1043
  'vote-offenses',
871
1044
  request,
872
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1045
+ {
1046
+ address: this.slashingProposerContract.address.toString(),
1047
+ abi: SlashingProposerAbi,
1048
+ eventName: 'VoteCast',
1049
+ },
873
1050
  slotNumber,
874
- timestamp,
875
1051
  );
876
1052
  break;
877
1053
  }
@@ -882,18 +1058,23 @@ export class SequencerPublisher {
882
1058
  round: action.round,
883
1059
  signerAddress,
884
1060
  });
885
- if (this.slashingProposerContract?.type !== 'tally') {
886
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1061
+ if (!this.slashingProposerContract) {
1062
+ this.log.error('No slashing proposer contract available');
887
1063
  return false;
888
1064
  }
889
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
890
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
891
- await this.simulateAndEnqueueRequest(
1065
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1066
+ action.round,
1067
+ action.committees,
1068
+ );
1069
+ this.enqueueRequest(
892
1070
  'execute-slash',
893
- request,
894
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1071
+ executeRequest,
1072
+ {
1073
+ address: this.slashingProposerContract.address.toString(),
1074
+ abi: SlashingProposerAbi,
1075
+ eventName: 'RoundExecuted',
1076
+ },
895
1077
  slotNumber,
896
- timestamp,
897
1078
  );
898
1079
  break;
899
1080
  }
@@ -908,51 +1089,32 @@ export class SequencerPublisher {
908
1089
  return true;
909
1090
  }
910
1091
 
911
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1092
+ /** Enqueues a proposal for a checkpoint on L1 */
912
1093
  public async enqueueProposeCheckpoint(
913
1094
  checkpoint: Checkpoint,
914
1095
  attestationsAndSigners: CommitteeAttestationsAndSigners,
915
1096
  attestationsAndSignersSignature: Signature,
916
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1097
+ opts: EnqueueProposeCheckpointOpts = {},
917
1098
  ): Promise<void> {
918
1099
  const checkpointHeader = checkpoint.header;
919
1100
 
920
1101
  const blobFields = checkpoint.toBlobFields();
921
- const blobs = getBlobsPerL1Block(blobFields);
1102
+ const blobs = await getBlobsPerL1Block(blobFields);
922
1103
 
923
- const proposeTxArgs = {
1104
+ const proposeTxArgs: L1ProcessArgs = {
924
1105
  header: checkpointHeader,
925
1106
  archive: checkpoint.archive.root.toBuffer(),
926
1107
  blobs,
927
1108
  attestationsAndSigners,
928
1109
  attestationsAndSignersSignature,
1110
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
929
1111
  };
930
1112
 
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);
1113
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1114
+ ...checkpoint.toCheckpointInfo(),
1115
+ txTimeoutAt: opts.txTimeoutAt,
1116
+ });
1117
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
956
1118
  }
957
1119
 
958
1120
  public enqueueInvalidateCheckpoint(
@@ -963,23 +1125,22 @@ export class SequencerPublisher {
963
1125
  return;
964
1126
  }
965
1127
 
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
1128
  const { gasUsed, checkpointNumber } = request;
970
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1129
+ const logData = { gasUsed, checkpointNumber, opts };
971
1130
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
972
1131
  this.addRequest({
973
1132
  action: `invalidate-by-${request.reason}`,
974
1133
  request: request.request,
975
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1134
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
976
1135
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
977
1136
  checkSuccess: (_req, result) => {
978
1137
  const success =
979
1138
  result &&
980
- result.receipt &&
981
- result.receipt.status === 'success' &&
982
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1139
+ extractEventSuccess(result.receipt, {
1140
+ address: this.rollupContract.address,
1141
+ abi: RollupAbi,
1142
+ eventName: 'CheckpointInvalidated',
1143
+ });
983
1144
  if (!success) {
984
1145
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
985
1146
  } else {
@@ -990,57 +1151,36 @@ export class SequencerPublisher {
990
1151
  });
991
1152
  }
992
1153
 
993
- private async simulateAndEnqueueRequest(
1154
+ /**
1155
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1156
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1157
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1158
+ */
1159
+ private enqueueRequest(
994
1160
  action: Action,
995
1161
  request: L1TxRequest,
996
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1162
+ eventOpts: { address: string; abi: Abi; eventName: string },
997
1163
  slotNumber: SlotNumber,
998
- timestamp: bigint,
999
- ) {
1000
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1164
+ ): boolean {
1001
1165
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1002
1166
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1003
1167
  return false;
1004
1168
  }
1005
-
1006
1169
  const cachedLastActionSlot = this.lastActions[action];
1007
1170
  this.lastActions[action] = slotNumber;
1008
1171
 
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);
1172
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1032
1173
  this.addRequest({
1033
1174
  action,
1034
- request: requestWithAbi,
1035
- gasConfig: { gasLimit },
1175
+ request,
1036
1176
  lastValidL2Slot: slotNumber,
1037
- checkSuccess: (_req, result) => {
1038
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1177
+ checkSuccess: (_request, result) => {
1178
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1039
1179
  if (!success) {
1040
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1180
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1041
1181
  this.lastActions[action] = cachedLastActionSlot;
1042
1182
  } else {
1043
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1183
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1044
1184
  }
1045
1185
  return !!success;
1046
1186
  },
@@ -1056,6 +1196,7 @@ export class SequencerPublisher {
1056
1196
  */
1057
1197
  public interrupt() {
1058
1198
  this.interrupted = true;
1199
+ this.interruptibleSleep.interrupt();
1059
1200
  this.l1TxUtils.interrupt();
1060
1201
  }
1061
1202
 
@@ -1065,11 +1206,7 @@ export class SequencerPublisher {
1065
1206
  this.l1TxUtils.restart();
1066
1207
  }
1067
1208
 
1068
- private async prepareProposeTx(
1069
- encodedData: L1ProcessArgs,
1070
- timestamp: bigint,
1071
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1072
- ) {
1209
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1073
1210
  const kzg = Blob.getViemKzgInstance();
1074
1211
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1075
1212
  this.log.debug('Validating blob input', { blobInput });
@@ -1082,7 +1219,11 @@ export class SequencerPublisher {
1082
1219
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1083
1220
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1084
1221
  } else {
1085
- // Normal mode - use estimateGas with blob inputs
1222
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1223
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1224
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1225
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1226
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1086
1227
  blobEvaluationGas = await this.l1TxUtils
1087
1228
  .estimateGas(
1088
1229
  this.getSenderAddress().toString(),
@@ -1100,9 +1241,27 @@ export class SequencerPublisher {
1100
1241
  kzg,
1101
1242
  },
1102
1243
  )
1103
- .catch(err => {
1104
- const { message, metaMessages } = formatViemError(err);
1105
- this.log.error(`Failed to validate blobs`, message, { metaMessages });
1244
+ .catch(async err => {
1245
+ const viemError = formatViemError(err);
1246
+ this.log.error(`Failed to validate blobs`, viemError.message, { metaMessages: viemError.metaMessages });
1247
+ const validateBlobsData = encodeFunctionData({
1248
+ abi: RollupAbi,
1249
+ functionName: 'validateBlobs',
1250
+ args: [blobInput],
1251
+ });
1252
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1253
+ this.backupFailedTx({
1254
+ id: keccak256(validateBlobsData),
1255
+ failureType: 'simulation',
1256
+ request: { to: this.rollupContract.address as Hex, data: validateBlobsData },
1257
+ blobData: encodedData.blobs.map(b => toHex(b.data)) as Hex[],
1258
+ l1BlockNumber: l1BlockNumber.toString(),
1259
+ error: { message: viemError.message, name: viemError.name },
1260
+ context: {
1261
+ actions: ['validate-blobs'],
1262
+ sender: this.getSenderAddress().toString(),
1263
+ },
1264
+ });
1106
1265
  throw new Error('Failed to validate blobs');
1107
1266
  });
1108
1267
  }
@@ -1113,8 +1272,7 @@ export class SequencerPublisher {
1113
1272
  header: encodedData.header.toViem(),
1114
1273
  archive: toHex(encodedData.archive),
1115
1274
  oracleInput: {
1116
- // We are currently not modifying these. See #9963
1117
- feeAssetPriceModifier: 0n,
1275
+ feeAssetPriceModifier: encodedData.feeAssetPriceModifier,
1118
1276
  },
1119
1277
  },
1120
1278
  encodedData.attestationsAndSigners.getPackedAttestations(),
@@ -1123,124 +1281,21 @@ export class SequencerPublisher {
1123
1281
  blobInput,
1124
1282
  ] as const;
1125
1283
 
1126
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1284
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1127
1285
 
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 };
1286
+ return { args, blobEvaluationGas, rollupData };
1222
1287
  }
1223
1288
 
1224
1289
  private async addProposeTx(
1225
1290
  checkpoint: Checkpoint,
1226
1291
  encodedData: L1ProcessArgs,
1227
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1228
- timestamp: bigint,
1292
+ opts: EnqueueProposeCheckpointOpts = {},
1229
1293
  ): Promise<void> {
1230
1294
  const slot = checkpoint.header.slotNumber;
1231
1295
  const timer = new Timer();
1232
1296
  const kzg = Blob.getViemKzgInstance();
1233
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
1234
- encodedData,
1235
- timestamp,
1236
- opts,
1237
- );
1297
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1238
1298
  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
1299
 
1245
1300
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1246
1301
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
@@ -1257,7 +1312,8 @@ export class SequencerPublisher {
1257
1312
  data: rollupData,
1258
1313
  },
1259
1314
  lastValidL2Slot: checkpoint.header.slotNumber,
1260
- gasConfig: { ...opts, gasLimit },
1315
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1316
+ blobEvaluationGas,
1261
1317
  blobConfig: {
1262
1318
  blobs: encodedData.blobs.map(b => b.data),
1263
1319
  kzg,
@@ -1267,10 +1323,11 @@ export class SequencerPublisher {
1267
1323
  return false;
1268
1324
  }
1269
1325
  const { receipt, stats, errorMsg } = result;
1270
- const success =
1271
- receipt &&
1272
- receipt.status === 'success' &&
1273
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1326
+ const success = extractEventSuccess(receipt, {
1327
+ address: this.rollupContract.address,
1328
+ abi: RollupAbi,
1329
+ eventName: 'CheckpointProposed',
1330
+ });
1274
1331
 
1275
1332
  if (success) {
1276
1333
  const endBlock = receipt.blockNumber;
@@ -1310,4 +1367,10 @@ export class SequencerPublisher {
1310
1367
  },
1311
1368
  });
1312
1369
  }
1370
+
1371
+ /** Returns the timestamp of the next L1 slot boundary after now. */
1372
+ private getNextL1SlotTimestamp(): bigint {
1373
+ const l1Constants = this.epochCache.getL1Constants();
1374
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1375
+ }
1313
1376
  }