@aztec/sequencer-client 0.0.1-commit.a072138 → 0.0.1-commit.a5db02d

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 (133) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +34 -11
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +77 -39
  5. package/dest/config.d.ts +32 -6
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +94 -46
  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 +138 -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 +80 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +13 -28
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +9 -66
  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/publisher/config.d.ts +51 -17
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +131 -42
  23. package/dest/publisher/index.d.ts +2 -1
  24. package/dest/publisher/index.d.ts.map +1 -1
  25. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  26. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  27. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  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 +107 -67
  47. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher.js +539 -378
  49. package/dest/publisher/write_json.d.ts +11 -0
  50. package/dest/publisher/write_json.d.ts.map +1 -0
  51. package/dest/publisher/write_json.js +57 -0
  52. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  53. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  54. package/dest/sequencer/automine/automine_factory.js +85 -0
  55. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  56. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  57. package/dest/sequencer/automine/automine_sequencer.js +690 -0
  58. package/dest/sequencer/automine/index.d.ts +3 -0
  59. package/dest/sequencer/automine/index.d.ts.map +1 -0
  60. package/dest/sequencer/automine/index.js +2 -0
  61. package/dest/sequencer/checkpoint_proposal_job.d.ts +81 -19
  62. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  63. package/dest/sequencer/checkpoint_proposal_job.js +891 -282
  64. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  65. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  66. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  67. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  68. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  69. package/dest/sequencer/checkpoint_voter.js +2 -5
  70. package/dest/sequencer/errors.d.ts +1 -8
  71. package/dest/sequencer/errors.d.ts.map +1 -1
  72. package/dest/sequencer/errors.js +0 -9
  73. package/dest/sequencer/events.d.ts +62 -5
  74. package/dest/sequencer/events.d.ts.map +1 -1
  75. package/dest/sequencer/metrics.d.ts +23 -8
  76. package/dest/sequencer/metrics.d.ts.map +1 -1
  77. package/dest/sequencer/metrics.js +117 -21
  78. package/dest/sequencer/requests_tracker.d.ts +22 -0
  79. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  80. package/dest/sequencer/requests_tracker.js +33 -0
  81. package/dest/sequencer/sequencer.d.ts +181 -44
  82. package/dest/sequencer/sequencer.d.ts.map +1 -1
  83. package/dest/sequencer/sequencer.js +614 -216
  84. package/dest/sequencer/types.d.ts +2 -2
  85. package/dest/sequencer/types.d.ts.map +1 -1
  86. package/dest/test/index.d.ts +5 -7
  87. package/dest/test/index.d.ts.map +1 -1
  88. package/dest/test/mock_checkpoint_builder.d.ts +11 -11
  89. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  90. package/dest/test/mock_checkpoint_builder.js +45 -34
  91. package/dest/test/utils.d.ts +17 -3
  92. package/dest/test/utils.d.ts.map +1 -1
  93. package/dest/test/utils.js +28 -9
  94. package/package.json +28 -28
  95. package/src/client/sequencer-client.ts +110 -47
  96. package/src/config.ts +120 -55
  97. package/src/global_variable_builder/README.md +44 -0
  98. package/src/global_variable_builder/fee_predictor.ts +182 -0
  99. package/src/global_variable_builder/fee_provider.ts +97 -0
  100. package/src/global_variable_builder/global_builder.ts +20 -89
  101. package/src/global_variable_builder/index.ts +3 -1
  102. package/src/publisher/config.ts +173 -40
  103. package/src/publisher/index.ts +3 -0
  104. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  105. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  106. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  107. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  108. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  109. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  110. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  111. package/src/publisher/sequencer-publisher.ts +628 -469
  112. package/src/publisher/write_json.ts +78 -0
  113. package/src/sequencer/automine/README.md +60 -0
  114. package/src/sequencer/automine/automine_factory.ts +152 -0
  115. package/src/sequencer/automine/automine_sequencer.ts +796 -0
  116. package/src/sequencer/automine/index.ts +6 -0
  117. package/src/sequencer/checkpoint_proposal_job.ts +1083 -305
  118. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  119. package/src/sequencer/checkpoint_voter.ts +1 -12
  120. package/src/sequencer/errors.ts +0 -15
  121. package/src/sequencer/events.ts +66 -5
  122. package/src/sequencer/metrics.ts +132 -25
  123. package/src/sequencer/requests_tracker.ts +43 -0
  124. package/src/sequencer/sequencer.ts +728 -241
  125. package/src/sequencer/types.ts +1 -1
  126. package/src/test/index.ts +4 -6
  127. package/src/test/mock_checkpoint_builder.ts +63 -49
  128. package/src/test/utils.ts +64 -10
  129. package/dest/sequencer/timetable.d.ts +0 -90
  130. package/dest/sequencer/timetable.d.ts.map +0 -1
  131. package/dest/sequencer/timetable.js +0 -226
  132. package/src/sequencer/README.md +0 -531
  133. package/src/sequencer/timetable.ts +0 -282
@@ -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,23 +110,23 @@ 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 = [
66
118
  'invalidate-by-invalid-attestation',
67
119
  'invalidate-by-insufficient-attestations',
120
+ 'prune',
68
121
  'propose',
69
122
  'governance-signal',
70
- 'empire-slashing-signal',
71
- 'create-empire-payload',
72
- 'execute-empire-payload',
73
123
  'vote-offenses',
74
124
  'execute-slash',
75
125
  ] as const;
76
126
 
77
127
  export type Action = (typeof Actions)[number];
78
128
 
79
- type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slashing-signal'>;
129
+ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
80
130
 
81
131
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
82
132
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
@@ -87,14 +137,22 @@ export type InvalidateCheckpointRequest = {
87
137
  gasUsed: bigint;
88
138
  checkpointNumber: CheckpointNumber;
89
139
  forcePendingCheckpointNumber: CheckpointNumber;
140
+ /** Archive at the rollback target checkpoint (checkpoint N-1). */
141
+ lastArchive: Fr;
90
142
  };
91
143
 
92
- interface RequestWithExpiry {
144
+ type EnqueueProposeCheckpointOpts = {
145
+ txTimeoutAt?: Date;
146
+ };
147
+
148
+ export interface RequestWithExpiry {
93
149
  action: Action;
94
150
  request: L1TxRequest;
95
151
  lastValidL2Slot: SlotNumber;
96
152
  gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
97
153
  blobConfig?: L1BlobInputs;
154
+ /** Gas consumed by validateBlobs; stashed for the bundle simulate at send time. */
155
+ blobEvaluationGas?: bigint;
98
156
  checkSuccess: (
99
157
  request: L1TxRequest,
100
158
  result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
@@ -104,69 +162,92 @@ interface RequestWithExpiry {
104
162
  export class SequencerPublisher {
105
163
  private interrupted = false;
106
164
  private metrics: SequencerPublisherMetrics;
165
+ private bundleSimulator: SequencerBundleSimulator;
107
166
  public epochCache: EpochCache;
167
+ private failedTxStore?: Promise<L1TxFailedStore | undefined>;
108
168
 
109
- protected governanceLog = createLogger('sequencer:publisher:governance');
110
- protected slashingLog = createLogger('sequencer:publisher:slashing');
169
+ /**
170
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
171
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
172
+ * publisher can route to so any of their custom errors decode against it.
173
+ */
174
+ private readonly revertDecoderAbi: Abi = mergeAbis([RollupAbi, SlashingProposerAbi, EmpireBaseAbi, ErrorsAbi]);
111
175
 
112
176
  protected lastActions: Partial<Record<Action, SlotNumber>> = {};
113
177
 
114
- private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
115
-
116
178
  protected log: Logger;
117
179
  protected ethereumSlotDuration: bigint;
180
+ protected aztecSlotDuration: bigint;
181
+ private readonly previousL1BlockWaitTimeoutMs: number;
182
+ private readonly previousL1BlockWaitPollIntervalMs: number;
183
+
184
+ /** Date provider for wall-clock time. */
185
+ private readonly dateProvider: DateProvider;
118
186
 
119
187
  private blobClient: BlobClientInterface;
120
188
 
121
- /** Address to use for simulations in fisherman mode (actual proposer's address) */
122
- private proposerAddressForSimulation?: EthAddress;
189
+ /** Optional callback to obtain a replacement publisher when the current one fails to send. */
190
+ private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
123
191
 
124
192
  /** L1 fee analyzer for fisherman mode */
125
193
  private l1FeeAnalyzer?: L1FeeAnalyzer;
126
- // A CALL to a cold address is 2700 gas
127
- public static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
128
194
 
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;
195
+ /** Fee asset price oracle for computing price modifiers from Uniswap V4 */
196
+ private feeAssetPriceOracle: FeeAssetPriceOracle;
197
+
198
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */
199
+ private readonly interruptibleSleep = new InterruptibleSleep();
131
200
 
132
- public l1TxUtils: L1TxUtilsWithBlobs;
201
+ public l1TxUtils: L1TxUtils;
133
202
  public rollupContract: RollupContract;
134
203
  public govProposerContract: GovernanceProposerContract;
135
- public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
136
- public slashFactoryContract: SlashFactoryContract;
204
+ public slashingProposerContract: SlashingProposerContract | undefined;
137
205
 
138
206
  public readonly tracer: Tracer;
139
207
 
140
208
  protected requests: RequestWithExpiry[] = [];
141
209
 
142
210
  constructor(
143
- private config: TxSenderConfig & PublisherConfig & Pick<L1ContractsConfig, 'ethereumSlotDuration'>,
211
+ private config: Pick<
212
+ SequencerPublisherConfig,
213
+ | 'fishermanMode'
214
+ | 'l1TxFailedStore'
215
+ | 'sequencerPublisherPreviousL1BlockWaitTimeoutMs'
216
+ | 'sequencerPublisherPreviousL1BlockWaitPollIntervalMs'
217
+ > &
218
+ Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'> & { l1ChainId: number },
144
219
  deps: {
145
220
  telemetry?: TelemetryClient;
146
221
  blobClient: BlobClientInterface;
147
- l1TxUtils: L1TxUtilsWithBlobs;
222
+ l1TxUtils: L1TxUtils;
148
223
  rollupContract: RollupContract;
149
- slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
224
+ slashingProposerContract: SlashingProposerContract | undefined;
150
225
  governanceProposerContract: GovernanceProposerContract;
151
- slashFactoryContract: SlashFactoryContract;
152
226
  epochCache: EpochCache;
153
227
  dateProvider: DateProvider;
154
228
  metrics: SequencerPublisherMetrics;
155
229
  lastActions: Partial<Record<Action, SlotNumber>>;
156
230
  log?: Logger;
231
+ getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
157
232
  },
158
233
  ) {
159
234
  this.log = deps.log ?? createLogger('sequencer:publisher');
160
235
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
236
+ this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
237
+ this.previousL1BlockWaitTimeoutMs = config.sequencerPublisherPreviousL1BlockWaitTimeoutMs;
238
+ this.previousL1BlockWaitPollIntervalMs = config.sequencerPublisherPreviousL1BlockWaitPollIntervalMs;
239
+ this.dateProvider = deps.dateProvider;
161
240
  this.epochCache = deps.epochCache;
162
241
  this.lastActions = deps.lastActions;
163
242
 
164
243
  this.blobClient = deps.blobClient;
244
+ this.dateProvider = deps.dateProvider;
165
245
 
166
246
  const telemetry = deps.telemetry ?? getTelemetryClient();
167
247
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
168
248
  this.tracer = telemetry.getTracer('SequencerPublisher');
169
249
  this.l1TxUtils = deps.l1TxUtils;
250
+ this.getNextPublisher = deps.getNextPublisher;
170
251
 
171
252
  this.rollupContract = deps.rollupContract;
172
253
 
@@ -178,22 +259,71 @@ export class SequencerPublisher {
178
259
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
179
260
  this.slashingProposerContract = newSlashingProposer;
180
261
  });
181
- this.slashFactoryContract = deps.slashFactoryContract;
182
-
183
262
  // Initialize L1 fee analyzer for fisherman mode
184
263
  if (config.fishermanMode) {
185
264
  this.l1FeeAnalyzer = new L1FeeAnalyzer(
186
265
  this.l1TxUtils.client,
187
266
  deps.dateProvider,
188
- createLogger('sequencer:publisher:fee-analyzer'),
267
+ this.log.createChild('fee-analyzer'),
189
268
  );
190
269
  }
270
+
271
+ // Initialize fee asset price oracle
272
+ this.feeAssetPriceOracle = new FeeAssetPriceOracle(
273
+ this.l1TxUtils.client,
274
+ this.rollupContract,
275
+ this.log.createChild('price-oracle'),
276
+ );
277
+
278
+ // Initialize failed L1 tx store (optional, for test networks)
279
+ this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
280
+
281
+ this.bundleSimulator = new SequencerBundleSimulator({
282
+ getL1TxUtils: () => this.l1TxUtils,
283
+ rollupContract: this.rollupContract,
284
+ epochCache: this.epochCache,
285
+ log: this.log.createChild('bundle-simulator'),
286
+ });
287
+ }
288
+
289
+ /**
290
+ * Backs up a failed L1 transaction to the configured store for debugging.
291
+ * Does nothing if no store is configured.
292
+ */
293
+ private backupFailedTx(failedTx: Omit<FailedL1Tx, 'timestamp'>): void {
294
+ if (!this.failedTxStore) {
295
+ return;
296
+ }
297
+
298
+ const tx: FailedL1Tx = {
299
+ ...failedTx,
300
+ timestamp: Date.now(),
301
+ };
302
+
303
+ // Fire and forget - don't block on backup
304
+ void this.failedTxStore
305
+ .then(store => store?.saveFailedTx(tx))
306
+ .catch(err => {
307
+ this.log.warn(`Failed to backup failed L1 tx to store`, err);
308
+ });
191
309
  }
192
310
 
193
311
  public getRollupContract(): RollupContract {
194
312
  return this.rollupContract;
195
313
  }
196
314
 
315
+ /**
316
+ * Gets the fee asset price modifier from the oracle.
317
+ *
318
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
319
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
320
+ * modifier matches the parent L1 will use when applying it.
321
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
322
+ */
323
+ public getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12?: bigint): Promise<bigint> {
324
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
325
+ }
326
+
197
327
  public getSenderAddress() {
198
328
  return this.l1TxUtils.getSenderAddress();
199
329
  }
@@ -205,20 +335,12 @@ export class SequencerPublisher {
205
335
  return this.l1FeeAnalyzer;
206
336
  }
207
337
 
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
338
  public addRequest(request: RequestWithExpiry) {
217
339
  this.requests.push(request);
218
340
  }
219
341
 
220
342
  public getCurrentL2Slot(): SlotNumber {
221
- return this.epochCache.getEpochAndSlotNow().slot;
343
+ return this.epochCache.getSlotNow();
222
344
  }
223
345
 
224
346
  /**
@@ -290,22 +412,26 @@ export class SequencerPublisher {
290
412
 
291
413
  /**
292
414
  * Sends all requests that are still valid.
415
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
416
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
417
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
418
+ * AutomineSequencer, which publishes synchronously within the current slot.
293
419
  * @returns one of:
294
420
  * - A receipt and stats if the tx succeeded
295
421
  * - a receipt and errorMsg if it failed on L1
296
422
  * - undefined if no valid requests are found OR the tx failed to send.
297
423
  */
298
424
  @trackSpan('SequencerPublisher.sendRequests')
299
- public async sendRequests() {
425
+ public async sendRequests(targetSlot?: SlotNumber): Promise<SendRequestsResult | undefined> {
300
426
  const requestsToProcess = [...this.requests];
301
427
  this.requests = [];
428
+
302
429
  if (this.interrupted || requestsToProcess.length === 0) {
303
430
  return undefined;
304
431
  }
305
- const currentL2Slot = this.getCurrentL2Slot();
432
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
306
433
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
307
434
  const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
308
- const validActions = validRequests.map(x => x.action);
309
435
  const expiredActions = requestsToProcess
310
436
  .filter(request => request.lastValidL2Slot < currentL2Slot)
311
437
  .map(x => x.action);
@@ -328,53 +454,60 @@ export class SequencerPublisher {
328
454
  return undefined;
329
455
  }
330
456
 
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
- }
457
+ // Collect earliest txTimeoutAt across all requests.
458
+ const gasConfigs = validRequests.filter(request => request.gasConfig).map(request => request.gasConfig);
355
459
  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 };
460
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined;
358
461
 
359
462
  // Sort the requests so that proposals always go first
360
463
  // This ensures the committee gets precomputed correctly
361
464
  validRequests.sort((a, b) => compareActions(a.action, b.action));
362
465
 
363
466
  try {
467
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
468
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
469
+
470
+ if (bundleResult.kind === 'aborted') {
471
+ this.logDroppedInSim(bundleResult.droppedRequests);
472
+ void this.backupDroppedInSim(bundleResult.droppedRequests).catch(err =>
473
+ this.log.error(`Failed to backup requests dropped in simulation`, err),
474
+ );
475
+ return undefined;
476
+ }
477
+
478
+ const { requests, droppedRequests, gasLimit } =
479
+ bundleResult.kind === 'fallback'
480
+ ? {
481
+ requests: bundleResult.requests,
482
+ droppedRequests: bundleResult.droppedRequests,
483
+ gasLimit: MAX_L1_TX_LIMIT,
484
+ }
485
+ : bundleResult;
486
+
487
+ this.logDroppedInSim(droppedRequests);
488
+
489
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
490
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
491
+ const [blobConfig] = requests.filter(r => r.blobConfig).map(r => r.blobConfig);
492
+ const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
493
+
364
494
  this.log.debug('Forwarding transactions', {
365
- validRequests: validRequests.map(request => request.action),
495
+ requests: requests.map(request => request.action),
366
496
  txConfig,
367
497
  });
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 };
498
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
499
+ if (result === undefined) {
500
+ return undefined;
501
+ }
502
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
503
+ const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action)];
504
+ return {
505
+ result,
506
+ expiredActions,
507
+ sentActions: requests.map(x => x.action),
508
+ successfulActions,
509
+ failedActions: allFailedActions,
510
+ };
378
511
  } catch (err) {
379
512
  const viemError = formatViemError(err);
380
513
  this.log.error(`Failed to publish bundled transactions`, viemError);
@@ -391,49 +524,230 @@ export class SequencerPublisher {
391
524
  }
392
525
  }
393
526
 
527
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */
528
+ private logDroppedInSim(dropped: DroppedRequest[]): void {
529
+ for (const drop of dropped) {
530
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
531
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
532
+ action: drop.request.action,
533
+ revertReason: revertReasonDecoded ?? drop.returnData,
534
+ revertReasonDecoded,
535
+ returnData: drop.returnData,
536
+ });
537
+ }
538
+ }
539
+
540
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */
541
+ private async backupDroppedInSim(dropped: DroppedRequest[]): Promise<void> {
542
+ if (dropped.length === 0) {
543
+ return;
544
+ }
545
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
546
+ for (const { request: req } of dropped) {
547
+ this.backupFailedTx({
548
+ id: keccak256(req.request.data!),
549
+ failureType: 'simulation',
550
+ request: { to: req.request.to! as Hex, data: req.request.data! },
551
+ l1BlockNumber: l1BlockNumber.toString(),
552
+ error: { message: 'Bundle entry dropped: action reverted in sim' },
553
+ context: {
554
+ actions: [req.action],
555
+ sender: this.getSenderAddress().toString(),
556
+ },
557
+ });
558
+ }
559
+ }
560
+
561
+ /**
562
+ * Forwards transactions via Multicall3, rotating to the next available publisher if a send
563
+ * failure occurs (i.e. the tx never reached the chain).
564
+ * On-chain reverts and simulation errors are returned as-is without rotation.
565
+ */
566
+ private async forwardWithPublisherRotation(
567
+ validRequests: RequestWithExpiry[],
568
+ txConfig: RequestWithExpiry['gasConfig'],
569
+ blobConfig: L1BlobInputs | undefined,
570
+ ) {
571
+ if (!txConfig?.gasLimit) {
572
+ throw new Error('gasLimit is required for bundled transactions');
573
+ }
574
+ const txConfigWithGasLimit = txConfig as L1TxConfig & { gasLimit: bigint };
575
+
576
+ const triedAddresses: EthAddress[] = [];
577
+ let currentPublisher = this.l1TxUtils;
578
+
579
+ while (true) {
580
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
581
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
582
+ triedAddresses: triedAddresses.map(a => a.toString()),
583
+ });
584
+ return undefined;
585
+ }
586
+ triedAddresses.push(currentPublisher.getSenderAddress());
587
+
588
+ try {
589
+ const result = await Multicall3.forward(
590
+ validRequests.map(r => r.request),
591
+ currentPublisher,
592
+ txConfigWithGasLimit,
593
+ blobConfig,
594
+ { gasLimitRequired: true },
595
+ );
596
+ this.l1TxUtils = currentPublisher;
597
+ return result;
598
+ } catch (err) {
599
+ if (err instanceof TimeoutError) {
600
+ throw err;
601
+ }
602
+ if (err instanceof MulticallForwarderRevertedError) {
603
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
604
+ transactionHash: err.receipt.transactionHash,
605
+ });
606
+ return undefined;
607
+ }
608
+ const viemError = formatViemError(err);
609
+ if (!this.getNextPublisher) {
610
+ this.log.error('Failed to publish bundled transactions', viemError);
611
+ return undefined;
612
+ }
613
+ this.log.warn(
614
+ `Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`,
615
+ viemError,
616
+ );
617
+ const nextPublisher = await this.getNextPublisher([...triedAddresses]);
618
+ if (!nextPublisher) {
619
+ this.log.error(
620
+ `All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`,
621
+ viemError,
622
+ { triedAddresses: triedAddresses.map(a => a.toString()) },
623
+ );
624
+ return undefined;
625
+ }
626
+ currentPublisher = nextPublisher;
627
+ }
628
+ }
629
+ }
630
+
631
+ /*
632
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
633
+ */
634
+ public async sendRequestsAt(targetSlot: SlotNumber): Promise<SendRequestsResult | undefined> {
635
+ await this.waitForTargetSlot(targetSlot);
636
+ if (this.interrupted) {
637
+ return undefined;
638
+ }
639
+
640
+ return this.sendRequests(targetSlot);
641
+ }
642
+
643
+ /**
644
+ * Sleeps until one L1 slot before the L2 slot boundary, and then waits for that L1 block
645
+ * to be mined, so we don't risk being included in it. If that block never gets mined after
646
+ * a timeout, we assume it got skipped on L1, so we send the tx anyway.
647
+ */
648
+ private async waitForTargetSlot(targetSlot: SlotNumber): Promise<void> {
649
+ const l1Constants = this.epochCache.getL1Constants();
650
+ const nowInSeconds = this.dateProvider.nowInSeconds();
651
+ const startOfTargetSlotTs = getTimestampForSlot(targetSlot, l1Constants);
652
+ const previousL1BlockTs = startOfTargetSlotTs - this.ethereumSlotDuration;
653
+ const waitDeadlineTs = previousL1BlockTs + BigInt(this.previousL1BlockWaitTimeoutMs / 1000);
654
+ const logCtx = { targetSlot, startOfTargetSlotTs, nowInSeconds, previousL1BlockTs, waitDeadlineTs };
655
+
656
+ // Check if we are already past time
657
+ if (nowInSeconds >= startOfTargetSlotTs) {
658
+ this.log.verbose(`Target slot ${targetSlot} already started, sending requests immediately`, logCtx);
659
+ return;
660
+ }
661
+
662
+ // Otherwise we wait
663
+ this.log.debug(`Waiting for slot ${targetSlot} before sending requests`, logCtx);
664
+
665
+ // Wait until previous L1 block timestamp first
666
+ const sleepMs = (Number(previousL1BlockTs) - nowInSeconds) * 1000;
667
+ if (sleepMs > 0 && !this.interrupted) {
668
+ this.log.trace(`Sleeping ${sleepMs}ms before waiting for previous L1 block`, logCtx);
669
+ await this.interruptibleSleep.sleep(sleepMs);
670
+ }
671
+
672
+ // Then loop until we see the previous L1 block, so we know that we cannot be included in it.
673
+ // We time out after a while, once we are sure that that block is skipped in L1.
674
+ while (!this.interrupted) {
675
+ try {
676
+ const nowInSeconds = this.dateProvider.nowInSeconds();
677
+ logCtx.nowInSeconds = nowInSeconds;
678
+
679
+ if (nowInSeconds >= waitDeadlineTs) {
680
+ this.log.warn(`Timed out waiting for previous L1 block before sending requests, proceeding`, logCtx);
681
+ return;
682
+ }
683
+
684
+ const latestBlockTs = await this.l1TxUtils.getBlock().then(b => b.timestamp);
685
+ if (latestBlockTs >= previousL1BlockTs) {
686
+ this.log.debug(`Previous L1 block mined, proceeding to send requests`, { ...logCtx, latestBlockTs });
687
+ return;
688
+ }
689
+ this.log.trace(`Previous L1 block not mined yet, continuing to wait`, { ...logCtx, latestBlockTs });
690
+ } catch (err) {
691
+ this.log.error(`Error while waiting for previous L1 block before sending requests; retrying`, err, logCtx);
692
+ } finally {
693
+ await this.interruptibleSleep.sleep(this.previousL1BlockWaitPollIntervalMs);
694
+ }
695
+ }
696
+ }
697
+
394
698
  private callbackBundledTransactions(
395
699
  requests: RequestWithExpiry[],
396
- result?: { receipt: TransactionReceipt } | FormattedViemError,
700
+ result: { receipt: TransactionReceipt; multicallData: Hex },
397
701
  ) {
398
702
  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
- }
703
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
704
+ result,
705
+ requests: requests.map(r => ({
706
+ ...r,
707
+ // Avoid logging large blob data
708
+ blobConfig: r.blobConfig
709
+ ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
710
+ : undefined,
711
+ })),
712
+ });
713
+ const successfulActions: Action[] = [];
714
+ const failedActions: Action[] = [];
715
+ for (const request of requests) {
716
+ if (request.checkSuccess(request.request, result)) {
717
+ successfulActions.push(request.action);
718
+ } else {
719
+ failedActions.push(request.action);
412
720
  }
413
- return { successfulActions, failedActions };
414
721
  }
722
+ return { successfulActions, failedActions };
415
723
  }
416
724
 
417
725
  /**
418
- * @notice Will call `canProposeAtNextEthBlock` to make sure that it is possible to propose
726
+ * @notice Will call `canProposeAt` to make sure that it is possible to propose
419
727
  * @param tipArchive - The archive to check
420
728
  * @returns The slot and block number if it is possible to propose, undefined otherwise
421
729
  */
422
- public canProposeAtNextEthBlock(
423
- tipArchive: Fr,
424
- msgSender: EthAddress,
425
- opts: { forcePendingCheckpointNumber?: CheckpointNumber } = {},
426
- ) {
730
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
427
731
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
428
- const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
732
+ // These errors are expected when we cannot actually propose right now — usually because our
733
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
734
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
735
+ // skip the proposal; we do NOT treat these as bugs.
736
+ const expectedErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
737
+
738
+ const slotOffset = this.aztecSlotDuration;
739
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
429
740
 
430
741
  return this.rollupContract
431
- .canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
432
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
433
- })
742
+ .canProposeAt(
743
+ tipArchive.toBuffer(),
744
+ msgSender.toString(),
745
+ nextL1SlotTs,
746
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
747
+ )
434
748
  .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))}`, {
749
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
750
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
437
751
  error: err.message,
438
752
  });
439
753
  } else {
@@ -442,6 +756,7 @@ export class SequencerPublisher {
442
756
  return undefined;
443
757
  });
444
758
  }
759
+
445
760
  /**
446
761
  * @notice Will simulate `validateHeader` to make sure that the block header is valid
447
762
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
@@ -451,13 +766,13 @@ export class SequencerPublisher {
451
766
  @trackSpan('SequencerPublisher.validateBlockHeader')
452
767
  public async validateBlockHeader(
453
768
  header: CheckpointHeader,
454
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
769
+ simulationOverridesPlan?: SimulationOverridesPlan,
455
770
  ): Promise<void> {
456
771
  const flags = { ignoreDA: true, ignoreSignatures: true };
457
772
 
458
773
  const args = [
459
774
  header.toViem(),
460
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
775
+ CommitteeAttestationsAndSigners.packAttestations([]),
461
776
  [], // no signers
462
777
  Signature.empty().toViemSignature(),
463
778
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -465,10 +780,9 @@ export class SequencerPublisher {
465
780
  flags,
466
781
  ] as const;
467
782
 
468
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
469
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
470
- opts?.forcePendingCheckpointNumber,
471
- );
783
+ const l1Constants = this.epochCache.getL1Constants();
784
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
785
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
472
786
  let balance = 0n;
473
787
  if (this.config.fishermanMode) {
474
788
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -488,7 +802,7 @@ export class SequencerPublisher {
488
802
  data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
489
803
  from: MULTI_CALL_3_ADDRESS,
490
804
  },
491
- { time: ts + 1n },
805
+ { time: ts },
492
806
  stateOverrides,
493
807
  );
494
808
  this.log.debug(`Simulated validateHeader`);
@@ -521,6 +835,8 @@ export class SequencerPublisher {
521
835
  const request = this.buildInvalidateCheckpointRequest(validationResult);
522
836
  this.log.debug(`Simulating invalidate checkpoint ${checkpointNumber}`, { ...logData, request });
523
837
 
838
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
839
+
524
840
  try {
525
841
  const { gasUsed } = await this.l1TxUtils.simulate(
526
842
  request,
@@ -539,6 +855,7 @@ export class SequencerPublisher {
539
855
  gasUsed,
540
856
  checkpointNumber,
541
857
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
858
+ lastArchive: validationResult.checkpoint.lastArchive,
542
859
  reason,
543
860
  };
544
861
  } catch (err) {
@@ -551,8 +868,8 @@ export class SequencerPublisher {
551
868
  `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
552
869
  { ...logData, request, error: viemError.message },
553
870
  );
554
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
555
- if (latestPendingCheckpointNumber < checkpointNumber) {
871
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
872
+ if (latestProposedCheckpointNumber < checkpointNumber) {
556
873
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
557
874
  return undefined;
558
875
  } else {
@@ -572,6 +889,18 @@ export class SequencerPublisher {
572
889
 
573
890
  // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
574
891
  this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
892
+ this.backupFailedTx({
893
+ id: keccak256(request.data!),
894
+ failureType: 'simulation',
895
+ request: { to: request.to!, data: request.data!, value: request.value?.toString() },
896
+ l1BlockNumber: l1BlockNumber.toString(),
897
+ error: { message: viemError.message, name: viemError.name },
898
+ context: {
899
+ actions: [`invalidate-${reason}`],
900
+ checkpointNumber,
901
+ sender: this.getSenderAddress().toString(),
902
+ },
903
+ });
575
904
  throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, { cause: viemError });
576
905
  }
577
906
  }
@@ -585,9 +914,11 @@ export class SequencerPublisher {
585
914
  const logData = { ...checkpoint, reason };
586
915
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
587
916
 
588
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
589
- validationResult.attestations,
590
- ).getPackedAttestations();
917
+ // Use the exact packed tuple posted to L1 verbatim. A repack via `packAttestations` is not a
918
+ // byte-faithful inverse of `fromPacked` (a canonicalized yParity byte or an all-zero signature slot
919
+ // round-trips differently), so it would diverge from the stored `attestationsHash` and revert the
920
+ // invalidation.
921
+ const attestationsAndSigners = validationResult.verbatimAttestations;
591
922
 
592
923
  if (reason === 'invalid-attestation') {
593
924
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -608,59 +939,11 @@ export class SequencerPublisher {
608
939
  }
609
940
  }
610
941
 
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
942
  private async enqueueCastSignalHelper(
659
943
  slotNumber: SlotNumber,
660
- timestamp: bigint,
661
944
  signalType: GovernanceSignalAction,
662
945
  payload: EthAddress,
663
- base: IEmpireBase,
946
+ base: GovernanceProposerContract,
664
947
  signerAddress: EthAddress,
665
948
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
666
949
  ): Promise<boolean> {
@@ -686,11 +969,31 @@ export class SequencerPublisher {
686
969
  return false;
687
970
  }
688
971
 
689
- if (await this.isPayloadEmpty(payload)) {
972
+ if (await base.isPayloadEmpty(payload)) {
690
973
  this.log.warn(`Skipping vote cast for payload with empty code`);
691
974
  return false;
692
975
  }
693
976
 
977
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
978
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
979
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
980
+ // the same payload in a future round.
981
+ let proposed = false;
982
+ try {
983
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
984
+ } catch (err) {
985
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
986
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
987
+ // participation entirely; failing open at worst produces a duplicate signal that the
988
+ // contract will simply count alongside others in the round.
989
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
990
+ }
991
+
992
+ if (proposed) {
993
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
994
+ return false;
995
+ }
996
+
694
997
  const cachedLastVote = this.lastActions[signalType];
695
998
  this.lastActions[signalType] = slotNumber;
696
999
  const action = signalType;
@@ -709,26 +1012,19 @@ export class SequencerPublisher {
709
1012
  lastValidL2Slot: slotNumber,
710
1013
  });
711
1014
 
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
1015
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
721
1016
  this.addRequest({
722
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
723
1017
  action,
724
1018
  request,
725
1019
  lastValidL2Slot: slotNumber,
726
1020
  checkSuccess: (_request, result) => {
727
1021
  const success =
728
1022
  result &&
729
- result.receipt &&
730
- result.receipt.status === 'success' &&
731
- tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
1023
+ extractEventSuccess(result.receipt, {
1024
+ address: base.address.toString(),
1025
+ abi: EmpireBaseAbi,
1026
+ eventName: 'SignalCast',
1027
+ });
732
1028
 
733
1029
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
734
1030
  if (!success) {
@@ -750,33 +1046,19 @@ export class SequencerPublisher {
750
1046
  return true;
751
1047
  }
752
1048
 
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
1049
  /**
765
1050
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
766
1051
  * @param slotNumber - The slot number to cast a signal for.
767
- * @param timestamp - The timestamp of the slot to cast a signal for.
768
1052
  * @returns True if the signal was successfully enqueued, false otherwise.
769
1053
  */
770
1054
  public enqueueGovernanceCastSignal(
771
1055
  governancePayload: EthAddress,
772
1056
  slotNumber: SlotNumber,
773
- timestamp: bigint,
774
1057
  signerAddress: EthAddress,
775
1058
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
776
1059
  ): Promise<boolean> {
777
1060
  return this.enqueueCastSignalHelper(
778
1061
  slotNumber,
779
- timestamp,
780
1062
  'governance-signal',
781
1063
  governancePayload,
782
1064
  this.govProposerContract,
@@ -785,11 +1067,51 @@ export class SequencerPublisher {
785
1067
  );
786
1068
  }
787
1069
 
1070
+ /**
1071
+ * Enqueues a `prune()` transaction if the rollup is prunable at the given slot's L1 timestamp.
1072
+ * `prune()` is permissionless and idempotent — if the chain is no longer prunable by send time the
1073
+ * bundle simulation usually drops the entry; on a node without `eth_simulateV1` the bundle is sent
1074
+ * as-is and the prune reverts `Rollup__NothingToPrune` inside `aggregate3(allowFailure: true)`
1075
+ * (a failed action, never a whole-tx revert). Used by the failed-sync fallback so a stuck pending
1076
+ * chain (e.g. bad data blocking sync) can be wound back to recover.
1077
+ * @returns true if a prune request was enqueued, false otherwise.
1078
+ */
1079
+ public async enqueuePruneIfPrunable(slotNumber: SlotNumber): Promise<boolean> {
1080
+ if (this.lastActions['prune'] === slotNumber) {
1081
+ this.log.debug(`Skipping duplicate prune for slot ${slotNumber}`, { slotNumber });
1082
+ return false;
1083
+ }
1084
+ // Use the SAME timestamp the bundle simulator overrides block.timestamp with at send time
1085
+ // (sequencer-bundle-simulator.ts) so this upfront check and the send-time sim agree. Slot-start
1086
+ // and last-L1-slot both fall within the same L2 slot (and epoch, which is what `canPruneAtTime`
1087
+ // derives), so they agree today; matching the simulator keeps it robust if the contract ever uses
1088
+ // the timestamp more granularly.
1089
+ const ts = getLastL1SlotTimestampForL2Slot(slotNumber, this.epochCache.getL1Constants());
1090
+ const canPrune = await this.rollupContract.canPruneAtTime(ts).catch(err => {
1091
+ this.log.error(`Failed to check canPruneAtTime for slot ${slotNumber}`, err, { slotNumber });
1092
+ return false;
1093
+ });
1094
+ if (!canPrune) {
1095
+ this.log.debug(`Rollup not prunable at slot ${slotNumber}`, { slotNumber });
1096
+ return false;
1097
+ }
1098
+ const request: L1TxRequest = {
1099
+ to: this.rollupContract.address,
1100
+ data: encodeFunctionData({ abi: RollupAbi, functionName: 'prune', args: [] }),
1101
+ };
1102
+ this.log.info(`Enqueuing rollup prune for slot ${slotNumber}`, { slotNumber });
1103
+ return this.enqueueRequest(
1104
+ 'prune',
1105
+ request,
1106
+ { address: this.rollupContract.address, abi: RollupAbi, eventName: 'PrunedPending' },
1107
+ slotNumber,
1108
+ );
1109
+ }
1110
+
788
1111
  /** Enqueues all slashing actions as returned by the slasher client. */
789
1112
  public async enqueueSlashingActions(
790
1113
  actions: ProposerSlashAction[],
791
1114
  slotNumber: SlotNumber,
792
- timestamp: bigint,
793
1115
  signerAddress: EthAddress,
794
1116
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
795
1117
  ): Promise<boolean> {
@@ -800,58 +1122,6 @@ export class SequencerPublisher {
800
1122
 
801
1123
  for (const action of actions) {
802
1124
  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
1125
  case 'vote-offenses': {
856
1126
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
857
1127
  slotNumber,
@@ -859,19 +1129,21 @@ export class SequencerPublisher {
859
1129
  votesCount: action.votes.length,
860
1130
  signerAddress,
861
1131
  });
862
- if (this.slashingProposerContract?.type !== 'tally') {
863
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1132
+ if (!this.slashingProposerContract) {
1133
+ this.log.error('No slashing proposer contract available');
864
1134
  return false;
865
1135
  }
866
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
867
1136
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
868
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
869
- await this.simulateAndEnqueueRequest(
1137
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1138
+ this.enqueueRequest(
870
1139
  'vote-offenses',
871
1140
  request,
872
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1141
+ {
1142
+ address: this.slashingProposerContract.address.toString(),
1143
+ abi: SlashingProposerAbi,
1144
+ eventName: 'VoteCast',
1145
+ },
873
1146
  slotNumber,
874
- timestamp,
875
1147
  );
876
1148
  break;
877
1149
  }
@@ -882,18 +1154,23 @@ export class SequencerPublisher {
882
1154
  round: action.round,
883
1155
  signerAddress,
884
1156
  });
885
- if (this.slashingProposerContract?.type !== 'tally') {
886
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1157
+ if (!this.slashingProposerContract) {
1158
+ this.log.error('No slashing proposer contract available');
887
1159
  return false;
888
1160
  }
889
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
890
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
891
- await this.simulateAndEnqueueRequest(
1161
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1162
+ action.round,
1163
+ action.committees,
1164
+ );
1165
+ this.enqueueRequest(
892
1166
  'execute-slash',
893
- request,
894
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1167
+ executeRequest,
1168
+ {
1169
+ address: this.slashingProposerContract.address.toString(),
1170
+ abi: SlashingProposerAbi,
1171
+ eventName: 'RoundExecuted',
1172
+ },
895
1173
  slotNumber,
896
- timestamp,
897
1174
  );
898
1175
  break;
899
1176
  }
@@ -908,51 +1185,32 @@ export class SequencerPublisher {
908
1185
  return true;
909
1186
  }
910
1187
 
911
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1188
+ /** Enqueues a proposal for a checkpoint on L1 */
912
1189
  public async enqueueProposeCheckpoint(
913
1190
  checkpoint: Checkpoint,
914
1191
  attestationsAndSigners: CommitteeAttestationsAndSigners,
915
1192
  attestationsAndSignersSignature: Signature,
916
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1193
+ opts: EnqueueProposeCheckpointOpts = {},
917
1194
  ): Promise<void> {
918
1195
  const checkpointHeader = checkpoint.header;
919
1196
 
920
1197
  const blobFields = checkpoint.toBlobFields();
921
- const blobs = getBlobsPerL1Block(blobFields);
1198
+ const blobs = await getBlobsPerL1Block(blobFields);
922
1199
 
923
- const proposeTxArgs = {
1200
+ const proposeTxArgs: L1ProcessArgs = {
924
1201
  header: checkpointHeader,
925
1202
  archive: checkpoint.archive.root.toBuffer(),
926
1203
  blobs,
927
1204
  attestationsAndSigners,
928
1205
  attestationsAndSignersSignature,
1206
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
929
1207
  };
930
1208
 
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);
1209
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1210
+ ...checkpoint.toCheckpointInfo(),
1211
+ txTimeoutAt: opts.txTimeoutAt,
1212
+ });
1213
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
956
1214
  }
957
1215
 
958
1216
  public enqueueInvalidateCheckpoint(
@@ -963,23 +1221,22 @@ export class SequencerPublisher {
963
1221
  return;
964
1222
  }
965
1223
 
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
1224
  const { gasUsed, checkpointNumber } = request;
970
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1225
+ const logData = { gasUsed, checkpointNumber, opts };
971
1226
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
972
1227
  this.addRequest({
973
1228
  action: `invalidate-by-${request.reason}`,
974
1229
  request: request.request,
975
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1230
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
976
1231
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
977
1232
  checkSuccess: (_req, result) => {
978
1233
  const success =
979
1234
  result &&
980
- result.receipt &&
981
- result.receipt.status === 'success' &&
982
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1235
+ extractEventSuccess(result.receipt, {
1236
+ address: this.rollupContract.address,
1237
+ abi: RollupAbi,
1238
+ eventName: 'CheckpointInvalidated',
1239
+ });
983
1240
  if (!success) {
984
1241
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
985
1242
  } else {
@@ -990,57 +1247,36 @@ export class SequencerPublisher {
990
1247
  });
991
1248
  }
992
1249
 
993
- private async simulateAndEnqueueRequest(
1250
+ /**
1251
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1252
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1253
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1254
+ */
1255
+ private enqueueRequest(
994
1256
  action: Action,
995
1257
  request: L1TxRequest,
996
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1258
+ eventOpts: { address: string; abi: Abi; eventName: string },
997
1259
  slotNumber: SlotNumber,
998
- timestamp: bigint,
999
- ) {
1000
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1260
+ ): boolean {
1001
1261
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1002
1262
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1003
1263
  return false;
1004
1264
  }
1005
-
1006
1265
  const cachedLastActionSlot = this.lastActions[action];
1007
1266
  this.lastActions[action] = slotNumber;
1008
1267
 
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);
1268
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1032
1269
  this.addRequest({
1033
1270
  action,
1034
- request: requestWithAbi,
1035
- gasConfig: { gasLimit },
1271
+ request,
1036
1272
  lastValidL2Slot: slotNumber,
1037
- checkSuccess: (_req, result) => {
1038
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1273
+ checkSuccess: (_request, result) => {
1274
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1039
1275
  if (!success) {
1040
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1276
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1041
1277
  this.lastActions[action] = cachedLastActionSlot;
1042
1278
  } else {
1043
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1279
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1044
1280
  }
1045
1281
  return !!success;
1046
1282
  },
@@ -1056,6 +1292,7 @@ export class SequencerPublisher {
1056
1292
  */
1057
1293
  public interrupt() {
1058
1294
  this.interrupted = true;
1295
+ this.interruptibleSleep.interrupt();
1059
1296
  this.l1TxUtils.interrupt();
1060
1297
  }
1061
1298
 
@@ -1065,11 +1302,7 @@ export class SequencerPublisher {
1065
1302
  this.l1TxUtils.restart();
1066
1303
  }
1067
1304
 
1068
- private async prepareProposeTx(
1069
- encodedData: L1ProcessArgs,
1070
- timestamp: bigint,
1071
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1072
- ) {
1305
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1073
1306
  const kzg = Blob.getViemKzgInstance();
1074
1307
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1075
1308
  this.log.debug('Validating blob input', { blobInput });
@@ -1082,7 +1315,11 @@ export class SequencerPublisher {
1082
1315
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1083
1316
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1084
1317
  } else {
1085
- // Normal mode - use estimateGas with blob inputs
1318
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1319
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1320
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1321
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1322
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1086
1323
  blobEvaluationGas = await this.l1TxUtils
1087
1324
  .estimateGas(
1088
1325
  this.getSenderAddress().toString(),
@@ -1100,9 +1337,27 @@ export class SequencerPublisher {
1100
1337
  kzg,
1101
1338
  },
1102
1339
  )
1103
- .catch(err => {
1104
- const { message, metaMessages } = formatViemError(err);
1105
- this.log.error(`Failed to validate blobs`, message, { metaMessages });
1340
+ .catch(async err => {
1341
+ const viemError = formatViemError(err);
1342
+ this.log.error(`Failed to validate blobs`, viemError.message, { metaMessages: viemError.metaMessages });
1343
+ const validateBlobsData = encodeFunctionData({
1344
+ abi: RollupAbi,
1345
+ functionName: 'validateBlobs',
1346
+ args: [blobInput],
1347
+ });
1348
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1349
+ this.backupFailedTx({
1350
+ id: keccak256(validateBlobsData),
1351
+ failureType: 'simulation',
1352
+ request: { to: this.rollupContract.address as Hex, data: validateBlobsData },
1353
+ blobData: encodedData.blobs.map(b => toHex(b.data)) as Hex[],
1354
+ l1BlockNumber: l1BlockNumber.toString(),
1355
+ error: { message: viemError.message, name: viemError.name },
1356
+ context: {
1357
+ actions: ['validate-blobs'],
1358
+ sender: this.getSenderAddress().toString(),
1359
+ },
1360
+ });
1106
1361
  throw new Error('Failed to validate blobs');
1107
1362
  });
1108
1363
  }
@@ -1113,8 +1368,7 @@ export class SequencerPublisher {
1113
1368
  header: encodedData.header.toViem(),
1114
1369
  archive: toHex(encodedData.archive),
1115
1370
  oracleInput: {
1116
- // We are currently not modifying these. See #9963
1117
- feeAssetPriceModifier: 0n,
1371
+ feeAssetPriceModifier: encodedData.feeAssetPriceModifier,
1118
1372
  },
1119
1373
  },
1120
1374
  encodedData.attestationsAndSigners.getPackedAttestations(),
@@ -1123,124 +1377,21 @@ export class SequencerPublisher {
1123
1377
  blobInput,
1124
1378
  ] as const;
1125
1379
 
1126
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1127
-
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
- });
1380
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1220
1381
 
1221
- return { rollupData, simulationResult };
1382
+ return { args, blobEvaluationGas, rollupData };
1222
1383
  }
1223
1384
 
1224
1385
  private async addProposeTx(
1225
1386
  checkpoint: Checkpoint,
1226
1387
  encodedData: L1ProcessArgs,
1227
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1228
- timestamp: bigint,
1388
+ opts: EnqueueProposeCheckpointOpts = {},
1229
1389
  ): Promise<void> {
1230
1390
  const slot = checkpoint.header.slotNumber;
1231
1391
  const timer = new Timer();
1232
1392
  const kzg = Blob.getViemKzgInstance();
1233
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
1234
- encodedData,
1235
- timestamp,
1236
- opts,
1237
- );
1393
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1238
1394
  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
1395
 
1245
1396
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1246
1397
  // 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 +1408,8 @@ export class SequencerPublisher {
1257
1408
  data: rollupData,
1258
1409
  },
1259
1410
  lastValidL2Slot: checkpoint.header.slotNumber,
1260
- gasConfig: { ...opts, gasLimit },
1411
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1412
+ blobEvaluationGas,
1261
1413
  blobConfig: {
1262
1414
  blobs: encodedData.blobs.map(b => b.data),
1263
1415
  kzg,
@@ -1267,10 +1419,11 @@ export class SequencerPublisher {
1267
1419
  return false;
1268
1420
  }
1269
1421
  const { receipt, stats, errorMsg } = result;
1270
- const success =
1271
- receipt &&
1272
- receipt.status === 'success' &&
1273
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1422
+ const success = extractEventSuccess(receipt, {
1423
+ address: this.rollupContract.address,
1424
+ abi: RollupAbi,
1425
+ eventName: 'CheckpointProposed',
1426
+ });
1274
1427
 
1275
1428
  if (success) {
1276
1429
  const endBlock = receipt.blockNumber;
@@ -1310,4 +1463,10 @@ export class SequencerPublisher {
1310
1463
  },
1311
1464
  });
1312
1465
  }
1466
+
1467
+ /** Returns the timestamp of the next L1 slot boundary after now. */
1468
+ private getNextL1SlotTimestamp(): bigint {
1469
+ const l1Constants = this.epochCache.getL1Constants();
1470
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1471
+ }
1313
1472
  }