@aztec-labs/sequencer-client 6.0.0-nightly.20260829

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 (165) hide show
  1. package/README.md +307 -0
  2. package/dest/client/index.d.ts +2 -0
  3. package/dest/client/index.d.ts.map +1 -0
  4. package/dest/client/index.js +1 -0
  5. package/dest/client/sequencer-client.d.ts +94 -0
  6. package/dest/client/sequencer-client.d.ts.map +1 -0
  7. package/dest/client/sequencer-client.js +177 -0
  8. package/dest/config.d.ts +56 -0
  9. package/dest/config.d.ts.map +1 -0
  10. package/dest/config.js +251 -0
  11. package/dest/global_variable_builder/fee_predictor.d.ts +49 -0
  12. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_predictor.js +127 -0
  14. package/dest/global_variable_builder/fee_provider.d.ts +28 -0
  15. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  16. package/dest/global_variable_builder/fee_provider.js +87 -0
  17. package/dest/global_variable_builder/global_builder.d.ts +28 -0
  18. package/dest/global_variable_builder/global_builder.d.ts.map +1 -0
  19. package/dest/global_variable_builder/global_builder.js +40 -0
  20. package/dest/global_variable_builder/index.d.ts +4 -0
  21. package/dest/global_variable_builder/index.d.ts.map +1 -0
  22. package/dest/global_variable_builder/index.js +3 -0
  23. package/dest/index.d.ts +7 -0
  24. package/dest/index.d.ts.map +1 -0
  25. package/dest/index.js +8 -0
  26. package/dest/publisher/config.d.ts +68 -0
  27. package/dest/publisher/config.d.ts.map +1 -0
  28. package/dest/publisher/config.js +137 -0
  29. package/dest/publisher/index.d.ts +5 -0
  30. package/dest/publisher/index.d.ts.map +1 -0
  31. package/dest/publisher/index.js +4 -0
  32. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  33. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  34. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  35. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  36. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  37. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  38. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +101 -0
  39. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  40. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
  41. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  42. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  43. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
  44. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  45. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  46. package/dest/publisher/l1_tx_failed_store/index.js +3 -0
  47. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  48. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  49. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  50. package/dest/publisher/sequencer-publisher-factory.d.ts +50 -0
  51. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  52. package/dest/publisher/sequencer-publisher-factory.js +75 -0
  53. package/dest/publisher/sequencer-publisher-metrics.d.ts +26 -0
  54. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -0
  55. package/dest/publisher/sequencer-publisher-metrics.js +101 -0
  56. package/dest/publisher/sequencer-publisher.d.ts +254 -0
  57. package/dest/publisher/sequencer-publisher.d.ts.map +1 -0
  58. package/dest/publisher/sequencer-publisher.js +1784 -0
  59. package/dest/publisher/write_json.d.ts +11 -0
  60. package/dest/publisher/write_json.d.ts.map +1 -0
  61. package/dest/publisher/write_json.js +57 -0
  62. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  63. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  64. package/dest/sequencer/automine/automine_factory.js +85 -0
  65. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  66. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  67. package/dest/sequencer/automine/automine_sequencer.js +732 -0
  68. package/dest/sequencer/automine/index.d.ts +3 -0
  69. package/dest/sequencer/automine/index.d.ts.map +1 -0
  70. package/dest/sequencer/automine/index.js +2 -0
  71. package/dest/sequencer/checkpoint_proposal_job.d.ts +169 -0
  72. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  73. package/dest/sequencer/checkpoint_proposal_job.js +1961 -0
  74. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  75. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  76. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  77. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  78. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  79. package/dest/sequencer/checkpoint_voter.js +106 -0
  80. package/dest/sequencer/config.d.ts +8 -0
  81. package/dest/sequencer/config.d.ts.map +1 -0
  82. package/dest/sequencer/config.js +1 -0
  83. package/dest/sequencer/errors.d.ts +11 -0
  84. package/dest/sequencer/errors.d.ts.map +1 -0
  85. package/dest/sequencer/errors.js +15 -0
  86. package/dest/sequencer/events.d.ts +103 -0
  87. package/dest/sequencer/events.d.ts.map +1 -0
  88. package/dest/sequencer/events.js +1 -0
  89. package/dest/sequencer/inbox_bucket_selector.d.ts +88 -0
  90. package/dest/sequencer/inbox_bucket_selector.d.ts.map +1 -0
  91. package/dest/sequencer/inbox_bucket_selector.js +80 -0
  92. package/dest/sequencer/index.d.ts +6 -0
  93. package/dest/sequencer/index.d.ts.map +1 -0
  94. package/dest/sequencer/index.js +5 -0
  95. package/dest/sequencer/metrics.d.ts +75 -0
  96. package/dest/sequencer/metrics.d.ts.map +1 -0
  97. package/dest/sequencer/metrics.js +343 -0
  98. package/dest/sequencer/missing_committee.d.ts +72 -0
  99. package/dest/sequencer/missing_committee.d.ts.map +1 -0
  100. package/dest/sequencer/missing_committee.js +139 -0
  101. package/dest/sequencer/requests_tracker.d.ts +22 -0
  102. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  103. package/dest/sequencer/requests_tracker.js +33 -0
  104. package/dest/sequencer/sequencer.d.ts +326 -0
  105. package/dest/sequencer/sequencer.d.ts.map +1 -0
  106. package/dest/sequencer/sequencer.js +1495 -0
  107. package/dest/sequencer/types.d.ts +3 -0
  108. package/dest/sequencer/types.d.ts.map +1 -0
  109. package/dest/sequencer/types.js +1 -0
  110. package/dest/sequencer/utils.d.ts +30 -0
  111. package/dest/sequencer/utils.d.ts.map +1 -0
  112. package/dest/sequencer/utils.js +18 -0
  113. package/dest/test/index.d.ts +23 -0
  114. package/dest/test/index.d.ts.map +1 -0
  115. package/dest/test/index.js +6 -0
  116. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  117. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  118. package/dest/test/mock_checkpoint_builder.js +230 -0
  119. package/dest/test/utils.d.ts +67 -0
  120. package/dest/test/utils.d.ts.map +1 -0
  121. package/dest/test/utils.js +121 -0
  122. package/package.json +118 -0
  123. package/src/client/index.ts +1 -0
  124. package/src/client/sequencer-client.ts +281 -0
  125. package/src/config.ts +309 -0
  126. package/src/global_variable_builder/README.md +44 -0
  127. package/src/global_variable_builder/fee_predictor.ts +176 -0
  128. package/src/global_variable_builder/fee_provider.ts +104 -0
  129. package/src/global_variable_builder/global_builder.ts +68 -0
  130. package/src/global_variable_builder/index.ts +3 -0
  131. package/src/index.ts +15 -0
  132. package/src/publisher/config.ts +220 -0
  133. package/src/publisher/index.ts +8 -0
  134. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  135. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  136. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +166 -0
  137. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
  138. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  139. package/src/publisher/sequencer-bundle-simulator.ts +253 -0
  140. package/src/publisher/sequencer-publisher-factory.ts +121 -0
  141. package/src/publisher/sequencer-publisher-metrics.ts +145 -0
  142. package/src/publisher/sequencer-publisher.ts +1719 -0
  143. package/src/publisher/write_json.ts +77 -0
  144. package/src/sequencer/README.md +243 -0
  145. package/src/sequencer/automine/README.md +60 -0
  146. package/src/sequencer/automine/automine_factory.ts +156 -0
  147. package/src/sequencer/automine/automine_sequencer.ts +841 -0
  148. package/src/sequencer/automine/index.ts +6 -0
  149. package/src/sequencer/checkpoint_proposal_job.ts +1889 -0
  150. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  151. package/src/sequencer/checkpoint_voter.ts +118 -0
  152. package/src/sequencer/config.ts +9 -0
  153. package/src/sequencer/errors.ts +21 -0
  154. package/src/sequencer/events.ts +93 -0
  155. package/src/sequencer/inbox_bucket_selector.ts +160 -0
  156. package/src/sequencer/index.ts +5 -0
  157. package/src/sequencer/metrics.ts +463 -0
  158. package/src/sequencer/missing_committee.ts +192 -0
  159. package/src/sequencer/requests_tracker.ts +43 -0
  160. package/src/sequencer/sequencer.ts +1401 -0
  161. package/src/sequencer/types.ts +6 -0
  162. package/src/sequencer/utils.ts +42 -0
  163. package/src/test/index.ts +26 -0
  164. package/src/test/mock_checkpoint_builder.ts +324 -0
  165. package/src/test/utils.ts +215 -0
@@ -0,0 +1,1719 @@
1
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi, SlashingProposerAbi } from '@aztec/l1-artifacts';
2
+
3
+ import type { BlobClientInterface } from '@aztec-labs/blob-client/client';
4
+ import { Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec-labs/blob-lib';
5
+ import type { EpochCache } from '@aztec-labs/epoch-cache';
6
+ import type { L1ContractsConfig } from '@aztec-labs/ethereum/config';
7
+ import {
8
+ FeeAssetPriceOracle,
9
+ type GovernanceProposerContract,
10
+ MULTI_CALL_3_ADDRESS,
11
+ Multicall3,
12
+ MulticallForwarderRevertedError,
13
+ type PayloadProposalStatus,
14
+ type RollupContract,
15
+ type SimulationOverridesPlan,
16
+ type SlashingProposerContract,
17
+ buildSimulationOverridesStateOverride,
18
+ } from '@aztec-labs/ethereum/contracts';
19
+ import { type L1FeeAnalysisResult, L1FeeAnalyzer, captureWindowBlockFees } from '@aztec-labs/ethereum/l1-fee-analysis';
20
+ import {
21
+ type L1BlobInputs,
22
+ type L1TxConfig,
23
+ type L1TxRequest,
24
+ L1TxTimeoutError,
25
+ type L1TxUtils,
26
+ MAX_L1_TX_LIMIT,
27
+ type TransactionStats,
28
+ WEI_CONST,
29
+ } from '@aztec-labs/ethereum/l1-tx-utils';
30
+ import {
31
+ FormattedViemError,
32
+ formatViemError,
33
+ mergeAbis,
34
+ tryDecodeRevertReason,
35
+ tryExtractEvent,
36
+ } from '@aztec-labs/ethereum/utils';
37
+ import { CheckpointNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
38
+ import { trimmedBytesLength } from '@aztec-labs/foundation/buffer';
39
+ import { pick } from '@aztec-labs/foundation/collection';
40
+ import type { Fr } from '@aztec-labs/foundation/curves/bn254';
41
+ import { TimeoutError } from '@aztec-labs/foundation/error';
42
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
43
+ import { Signature } from '@aztec-labs/foundation/eth-signature';
44
+ import { type Logger, createLogger } from '@aztec-labs/foundation/log';
45
+ import { InterruptibleSleep } from '@aztec-labs/foundation/sleep';
46
+ import { bufferToHex } from '@aztec-labs/foundation/string';
47
+ import { type DateProvider, Timer } from '@aztec-labs/foundation/timer';
48
+ import { type ProposerSlashAction, encodeSlashConsensusVotes } from '@aztec-labs/slasher';
49
+ import { CommitteeAttestationsAndSigners, type ValidateCheckpointResult } from '@aztec-labs/stdlib/block';
50
+ import type { Checkpoint } from '@aztec-labs/stdlib/checkpoint';
51
+ import type { SequencerConfig } from '@aztec-labs/stdlib/config';
52
+ import {
53
+ getLastL1SlotTimestampForL2Slot,
54
+ getNextL1SlotTimestamp,
55
+ getTimestampForSlot,
56
+ } from '@aztec-labs/stdlib/epoch-helpers';
57
+ import type { CheckpointHeader } from '@aztec-labs/stdlib/rollup';
58
+ import type { L1PublishCheckpointStats } from '@aztec-labs/stdlib/stats';
59
+ import { type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec-labs/telemetry-client';
60
+ import {
61
+ type Abi,
62
+ type Hex,
63
+ type TransactionReceipt,
64
+ type TypedDataDefinition,
65
+ encodeFunctionData,
66
+ keccak256,
67
+ toHex,
68
+ } from 'viem';
69
+
70
+ import type { SequencerPublisherConfig } from './config.js';
71
+ import { type FailedL1Tx, type L1TxFailedStore, createL1TxFailedStore } from './l1_tx_failed_store/index.js';
72
+ import { type DroppedRequest, SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
73
+ import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
74
+
75
+ /**
76
+ * Returns true if the receipt indicates a successful send AND the expected event was emitted
77
+ * by the target contract. Both pieces are required: an aggregate3 entry that reverted will
78
+ * have receipt.status === 'success' but no event log.
79
+ */
80
+ function extractEventSuccess(
81
+ receipt: TransactionReceipt | undefined,
82
+ opts: { address: string; abi: Abi; eventName: string },
83
+ ): boolean {
84
+ if (!receipt || receipt.status !== 'success') {
85
+ return false;
86
+ }
87
+ return !!tryExtractEvent(receipt.logs, opts.address.toString() as Hex, opts.abi, opts.eventName);
88
+ }
89
+
90
+ /** Result of a sendRequests call, returned by both sendRequests() and sendRequestsAt(). */
91
+ export type SendRequestsResult = {
92
+ /** The L1 transaction receipt from the bundled multicall. */
93
+ result: { receipt: TransactionReceipt };
94
+ /** Actions that expired (past their deadline) before the request was sent. */
95
+ expiredActions: Action[];
96
+ /** Actions that were included in the sent L1 transaction. */
97
+ sentActions: Action[];
98
+ /** Actions whose L1 simulation succeeded (subset of sentActions). */
99
+ successfulActions: Action[];
100
+ /** Actions whose L1 simulation failed (subset of sentActions). */
101
+ failedActions: Action[];
102
+ };
103
+
104
+ /** Arguments to the process method of the rollup contract */
105
+ type L1ProcessArgs = {
106
+ /** The L2 block header. */
107
+ header: CheckpointHeader;
108
+ /** A root of the archive tree after the L2 block is applied. */
109
+ archive: Buffer;
110
+ /** L2 block blobs containing all tx effects. */
111
+ blobs: Blob[];
112
+ /** Attestations */
113
+ attestationsAndSigners: CommitteeAttestationsAndSigners;
114
+ /** Attestations and signers signature */
115
+ attestationsAndSignersSignature: Signature;
116
+ /** The fee asset price modifier in basis points (from oracle) */
117
+ feeAssetPriceModifier: bigint;
118
+ /** Sequence number of the Inbox bucket the header's rolling hash corresponds to. */
119
+ bucketHint: bigint;
120
+ };
121
+
122
+ export const Actions = [
123
+ 'invalidate-by-invalid-attestation',
124
+ 'invalidate-by-insufficient-attestations',
125
+ 'prune',
126
+ 'propose',
127
+ 'governance-signal',
128
+ 'vote-offenses',
129
+ 'execute-slash',
130
+ ] as const;
131
+
132
+ export type Action = (typeof Actions)[number];
133
+
134
+ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
135
+
136
+ // Sorting for actions such that invalidations go before proposals, and proposals go before votes
137
+ export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
138
+
139
+ export type InvalidateCheckpointRequest = {
140
+ request: L1TxRequest;
141
+ reason: 'invalid-attestation' | 'insufficient-attestations';
142
+ gasUsed: bigint;
143
+ checkpointNumber: CheckpointNumber;
144
+ forcePendingCheckpointNumber: CheckpointNumber;
145
+ /** Archive at the rollback target checkpoint (checkpoint N-1). */
146
+ lastArchive: Fr;
147
+ };
148
+
149
+ type EnqueueProposeCheckpointOpts = {
150
+ txTimeoutAt?: Date;
151
+ };
152
+
153
+ export interface RequestWithExpiry {
154
+ action: Action;
155
+ request: L1TxRequest;
156
+ lastValidL2Slot: SlotNumber;
157
+ gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
158
+ blobConfig?: L1BlobInputs;
159
+ /** Gas consumed by validateBlobs; stashed for the bundle simulate at send time. */
160
+ blobEvaluationGas?: bigint;
161
+ checkSuccess: (
162
+ request: L1TxRequest,
163
+ result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
164
+ ) => boolean;
165
+ }
166
+
167
+ export class SequencerPublisher {
168
+ private interrupted = false;
169
+ private metrics: SequencerPublisherMetrics;
170
+ private bundleSimulator: SequencerBundleSimulator;
171
+ public epochCache: EpochCache;
172
+ private failedTxStore?: Promise<L1TxFailedStore | undefined>;
173
+
174
+ /**
175
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
176
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
177
+ * publisher can route to so any of their custom errors decode against it.
178
+ */
179
+ private readonly revertDecoderAbi: Abi = mergeAbis([RollupAbi, SlashingProposerAbi, EmpireBaseAbi, ErrorsAbi]);
180
+
181
+ protected lastActions: Partial<Record<Action, SlotNumber>> = {};
182
+
183
+ protected log: Logger;
184
+ protected ethereumSlotDuration: bigint;
185
+ protected aztecSlotDuration: bigint;
186
+ private readonly previousL1BlockWaitTimeoutMs: number;
187
+ private readonly previousL1BlockWaitPollIntervalMs: number;
188
+
189
+ /** Date provider for wall-clock time. */
190
+ private readonly dateProvider: DateProvider;
191
+
192
+ private blobClient: BlobClientInterface;
193
+
194
+ /** Optional callback to obtain a replacement publisher when the current one fails to send. */
195
+ private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
196
+
197
+ /** L1 fee analyzer for fisherman mode */
198
+ private l1FeeAnalyzer?: L1FeeAnalyzer;
199
+
200
+ /** Fee asset price oracle for computing price modifiers from Uniswap V4 */
201
+ private feeAssetPriceOracle: FeeAssetPriceOracle;
202
+
203
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */
204
+ private readonly interruptibleSleep = new InterruptibleSleep();
205
+
206
+ public l1TxUtils: L1TxUtils;
207
+ public rollupContract: RollupContract;
208
+ public govProposerContract: GovernanceProposerContract;
209
+ public slashingProposerContract: SlashingProposerContract | undefined;
210
+
211
+ public readonly tracer: Tracer;
212
+
213
+ protected requests: RequestWithExpiry[] = [];
214
+
215
+ constructor(
216
+ private config: Pick<
217
+ SequencerPublisherConfig,
218
+ | 'fishermanMode'
219
+ | 'l1TxFailedStore'
220
+ | 'sequencerPublisherPreviousL1BlockWaitTimeoutMs'
221
+ | 'sequencerPublisherPreviousL1BlockWaitPollIntervalMs'
222
+ > &
223
+ Pick<SequencerConfig, 'governanceProposerForcePayloadVote'> &
224
+ Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'> & { l1ChainId: number },
225
+ deps: {
226
+ telemetry?: TelemetryClient;
227
+ blobClient: BlobClientInterface;
228
+ l1TxUtils: L1TxUtils;
229
+ rollupContract: RollupContract;
230
+ slashingProposerContract: SlashingProposerContract | undefined;
231
+ governanceProposerContract: GovernanceProposerContract;
232
+ epochCache: EpochCache;
233
+ dateProvider: DateProvider;
234
+ metrics: SequencerPublisherMetrics;
235
+ lastActions: Partial<Record<Action, SlotNumber>>;
236
+ log?: Logger;
237
+ getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
238
+ },
239
+ ) {
240
+ this.log = deps.log ?? createLogger('sequencer:publisher');
241
+ this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
242
+ this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
243
+ this.previousL1BlockWaitTimeoutMs = config.sequencerPublisherPreviousL1BlockWaitTimeoutMs;
244
+ this.previousL1BlockWaitPollIntervalMs = config.sequencerPublisherPreviousL1BlockWaitPollIntervalMs;
245
+ this.dateProvider = deps.dateProvider;
246
+ this.epochCache = deps.epochCache;
247
+ this.lastActions = deps.lastActions;
248
+
249
+ this.blobClient = deps.blobClient;
250
+ this.dateProvider = deps.dateProvider;
251
+
252
+ const telemetry = deps.telemetry ?? getTelemetryClient();
253
+ this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
254
+ this.tracer = telemetry.getTracer('SequencerPublisher');
255
+ this.l1TxUtils = deps.l1TxUtils;
256
+ this.getNextPublisher = deps.getNextPublisher;
257
+
258
+ this.rollupContract = deps.rollupContract;
259
+
260
+ this.govProposerContract = deps.governanceProposerContract;
261
+ this.slashingProposerContract = deps.slashingProposerContract;
262
+
263
+ this.rollupContract.listenToSlasherChanged(async () => {
264
+ this.log.info('Slashing proposer changed');
265
+ const newSlashingProposer = await this.rollupContract.getSlashingProposer();
266
+ this.slashingProposerContract = newSlashingProposer;
267
+ });
268
+ // Initialize L1 fee analyzer for fisherman mode
269
+ if (config.fishermanMode) {
270
+ this.l1FeeAnalyzer = new L1FeeAnalyzer(
271
+ this.l1TxUtils.client,
272
+ deps.dateProvider,
273
+ this.log.createChild('fee-analyzer'),
274
+ );
275
+ }
276
+
277
+ // Initialize fee asset price oracle
278
+ this.feeAssetPriceOracle = new FeeAssetPriceOracle(
279
+ this.l1TxUtils.client,
280
+ this.rollupContract,
281
+ this.log.createChild('price-oracle'),
282
+ );
283
+
284
+ // Initialize failed L1 tx store (optional, for test networks)
285
+ this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
286
+
287
+ this.bundleSimulator = new SequencerBundleSimulator({
288
+ getL1TxUtils: () => this.l1TxUtils,
289
+ rollupContract: this.rollupContract,
290
+ epochCache: this.epochCache,
291
+ log: this.log.createChild('bundle-simulator'),
292
+ });
293
+ }
294
+
295
+ /**
296
+ * Logs the gas-pricing data of a failed L1 transaction at warn — so underpricing is diagnosable
297
+ * from logs even with no failed-tx store configured — and backs the record up to the store when
298
+ * one is. When captureFeeSummary is true, also records the fee data of the already-mined L1
299
+ * blocks in the target slot's inclusion window.
300
+ */
301
+ private backupFailedTx(
302
+ failedTx: Omit<FailedL1Tx, 'timestamp'>,
303
+ opts?: { captureFeeSummary?: boolean; targetSlot?: SlotNumber; sharedFeeSummary?: FailedL1Tx['gasInfo'] },
304
+ ): void {
305
+ const tx: FailedL1Tx = {
306
+ ...failedTx,
307
+ timestamp: Date.now(),
308
+ };
309
+
310
+ // Fire and forget - don't block on backup
311
+ void (async () => {
312
+ try {
313
+ // Prefer a pre-captured summary (shared across a batch of failures in the same slot) so we
314
+ // don't re-read the fee window per record. A capture error must not lose the record itself.
315
+ const feeSummary =
316
+ opts?.sharedFeeSummary ??
317
+ (opts?.captureFeeSummary
318
+ ? await this.captureFeeEnvironment(opts.targetSlot).catch(() => undefined)
319
+ : undefined);
320
+ if (feeSummary) {
321
+ tx.gasInfo = { ...tx.gasInfo, ...feeSummary };
322
+ }
323
+ if (tx.gasInfo) {
324
+ this.log.warn(`Gas pricing data for failed L1 tx (${tx.failureType})`, {
325
+ failureType: tx.failureType,
326
+ actions: tx.context.actions,
327
+ slot: tx.context.slot,
328
+ ...tx.gasInfo,
329
+ ...tx.timing,
330
+ });
331
+ }
332
+ const store = await this.failedTxStore;
333
+ if (store) {
334
+ await store.saveFailedTx(tx);
335
+ }
336
+ } catch (err) {
337
+ this.log.warn(`Failed to backup failed L1 tx to store`, err);
338
+ }
339
+ })();
340
+ }
341
+
342
+ /**
343
+ * Captures per-block fee data for the L1 blocks in the target slot's inclusion window (the blocks the
344
+ * tx could have landed in) for underpricing diagnostics. Reads only already-mined blocks, so it never
345
+ * waits on the chain. Safe to call off the critical path: the underlying capture never throws, and this
346
+ * returns undefined when there is no target slot or the window is not yet mined (e.g. an early send
347
+ * failure), in which case the record simply carries no window data.
348
+ */
349
+ private async captureFeeEnvironment(targetL2Slot: SlotNumber | undefined): Promise<FailedL1Tx['gasInfo']> {
350
+ if (targetL2Slot === undefined) {
351
+ return undefined;
352
+ }
353
+ const l1Constants = this.epochCache.getL1Constants();
354
+ // The inclusion window is [start of slot N, start of slot N+1): all L1 blocks that can include a tx
355
+ // for this L2 slot. getTimestampForSlot returns seconds, matching block.timestamp.
356
+ const windowStartS = getTimestampForSlot(targetL2Slot, l1Constants);
357
+ const windowEndS = getTimestampForSlot(SlotNumber(Number(targetL2Slot) + 1), l1Constants);
358
+ const windowBlocks = await captureWindowBlockFees(this.l1TxUtils.client, windowStartS, windowEndS);
359
+ if (windowBlocks.length === 0) {
360
+ return undefined;
361
+ }
362
+ return { windowBlocks };
363
+ }
364
+
365
+ /** Computes timing info relative to the L2 slot deadline. */
366
+ private computeTimingInfo(targetL2Slot: SlotNumber | undefined): FailedL1Tx['timing'] {
367
+ if (targetL2Slot === undefined) {
368
+ return undefined;
369
+ }
370
+ const l1Constants = this.epochCache.getL1Constants();
371
+ const slotDeadlineS = getTimestampForSlot(SlotNumber(Number(targetL2Slot) + 1), l1Constants);
372
+ const slotDeadlineMs = Number(slotDeadlineS) * 1000;
373
+ return {
374
+ targetL2Slot: Number(targetL2Slot),
375
+ slotDeadlineTimestampS: slotDeadlineS,
376
+ msUntilSlotDeadline: slotDeadlineMs - this.dateProvider.now(),
377
+ };
378
+ }
379
+
380
+ /**
381
+ * Builds an id for a synthetic failure record (send-error/timeout) that has no on-chain tx hash.
382
+ * Includes the failure time so each attempt — including retries of the same slot — is stored as its
383
+ * own record rather than overwriting the previous one.
384
+ */
385
+ private failureRecordId(actions: string[], targetSlot: SlotNumber | undefined): Hex {
386
+ return keccak256(toHex(`${actions.join(',')}:${targetSlot ?? ''}:${Date.now()}`));
387
+ }
388
+
389
+ public getRollupContract(): RollupContract {
390
+ return this.rollupContract;
391
+ }
392
+
393
+ /**
394
+ * Gets the fee asset price modifier from the oracle.
395
+ *
396
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
397
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
398
+ * modifier matches the parent L1 will use when applying it.
399
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
400
+ */
401
+ public getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12?: bigint): Promise<bigint> {
402
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
403
+ }
404
+
405
+ public getSenderAddress() {
406
+ return this.l1TxUtils.getSenderAddress();
407
+ }
408
+
409
+ /**
410
+ * Gets the L1 fee analyzer instance (only available in fisherman mode)
411
+ */
412
+ public getL1FeeAnalyzer(): L1FeeAnalyzer | undefined {
413
+ return this.l1FeeAnalyzer;
414
+ }
415
+
416
+ public addRequest(request: RequestWithExpiry) {
417
+ this.requests.push(request);
418
+ }
419
+
420
+ public getCurrentL2Slot(): SlotNumber {
421
+ return this.epochCache.getSlotNow();
422
+ }
423
+
424
+ /**
425
+ * Clears all pending requests without sending them.
426
+ */
427
+ public clearPendingRequests(): void {
428
+ const count = this.requests.length;
429
+ this.requests = [];
430
+ if (count > 0) {
431
+ this.log.debug(`Cleared ${count} pending request(s)`);
432
+ }
433
+ }
434
+
435
+ /**
436
+ * Analyzes L1 fees for the pending requests without sending them.
437
+ * This is used in fisherman mode to validate fee calculations.
438
+ * @param l2SlotNumber - The L2 slot number for this analysis
439
+ * @param onComplete - Optional callback to invoke when analysis completes (after block is mined)
440
+ * @returns The analysis result (incomplete until block mines), or undefined if no requests
441
+ */
442
+ public async analyzeL1Fees(
443
+ l2SlotNumber: SlotNumber,
444
+ onComplete?: (analysis: L1FeeAnalysisResult) => void,
445
+ ): Promise<L1FeeAnalysisResult | undefined> {
446
+ if (!this.l1FeeAnalyzer) {
447
+ this.log.warn('L1 fee analyzer not available (not in fisherman mode)');
448
+ return undefined;
449
+ }
450
+
451
+ const requestsToAnalyze = [...this.requests];
452
+ if (requestsToAnalyze.length === 0) {
453
+ this.log.debug('No requests to analyze for L1 fees');
454
+ return undefined;
455
+ }
456
+
457
+ // Extract blob config from requests (if any)
458
+ const blobConfigs = requestsToAnalyze.filter(request => request.blobConfig).map(request => request.blobConfig);
459
+ const blobConfig = blobConfigs[0];
460
+
461
+ // Get gas configs
462
+ const gasConfigs = requestsToAnalyze.filter(request => request.gasConfig).map(request => request.gasConfig);
463
+ const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
464
+ const gasLimit = gasLimits.length > 0 ? gasLimits.reduce((sum, g) => sum + g, 0n) : 0n;
465
+
466
+ // Get the transaction requests
467
+ const l1Requests = requestsToAnalyze.map(r => r.request);
468
+
469
+ // Start the analysis
470
+ const analysisId = await this.l1FeeAnalyzer.startAnalysis(
471
+ l2SlotNumber,
472
+ gasLimit > 0n ? gasLimit : MAX_L1_TX_LIMIT,
473
+ l1Requests,
474
+ blobConfig,
475
+ onComplete,
476
+ );
477
+
478
+ this.log.info('Started L1 fee analysis', {
479
+ analysisId,
480
+ l2SlotNumber: l2SlotNumber.toString(),
481
+ requestCount: requestsToAnalyze.length,
482
+ hasBlobConfig: !!blobConfig,
483
+ gasLimit: gasLimit.toString(),
484
+ actions: requestsToAnalyze.map(r => r.action),
485
+ });
486
+
487
+ // Return the analysis result (will be incomplete until block mines)
488
+ return this.l1FeeAnalyzer.getAnalysis(analysisId);
489
+ }
490
+
491
+ /**
492
+ * Sends all requests that are still valid.
493
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
494
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
495
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
496
+ * AutomineSequencer, which publishes synchronously within the current slot.
497
+ * @returns one of:
498
+ * - A receipt and stats if the tx succeeded
499
+ * - a receipt and errorMsg if it failed on L1
500
+ * - undefined if no valid requests are found OR the tx failed to send.
501
+ */
502
+ @trackSpan('SequencerPublisher.sendRequests')
503
+ public async sendRequests(targetSlot?: SlotNumber): Promise<SendRequestsResult | undefined> {
504
+ const requestsToProcess = [...this.requests];
505
+ this.requests = [];
506
+
507
+ if (this.interrupted || requestsToProcess.length === 0) {
508
+ return undefined;
509
+ }
510
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
511
+ this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
512
+ const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
513
+ const expiredActions = requestsToProcess
514
+ .filter(request => request.lastValidL2Slot < currentL2Slot)
515
+ .map(x => x.action);
516
+
517
+ if (validRequests.length !== requestsToProcess.length) {
518
+ this.log.warn(`Some requests were expired for slot ${currentL2Slot}`, {
519
+ validRequests: validRequests.map(request => ({
520
+ action: request.action,
521
+ lastValidL2Slot: request.lastValidL2Slot,
522
+ })),
523
+ requests: requestsToProcess.map(request => ({
524
+ action: request.action,
525
+ lastValidL2Slot: request.lastValidL2Slot,
526
+ })),
527
+ });
528
+ }
529
+
530
+ if (validRequests.length === 0) {
531
+ this.log.debug(`No valid requests to send`);
532
+ return undefined;
533
+ }
534
+
535
+ // Collect earliest txTimeoutAt across all requests.
536
+ const gasConfigs = validRequests.filter(request => request.gasConfig).map(request => request.gasConfig);
537
+ const txTimeoutAts = gasConfigs.map(g => g?.txTimeoutAt).filter((g): g is Date => g !== undefined);
538
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined;
539
+
540
+ // Sort the requests so that proposals always go first
541
+ // This ensures the committee gets precomputed correctly
542
+ validRequests.sort((a, b) => compareActions(a.action, b.action));
543
+
544
+ try {
545
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
546
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
547
+
548
+ if (bundleResult.kind === 'aborted') {
549
+ this.logDroppedInSim(bundleResult.droppedRequests);
550
+ void this.backupDroppedInSim(bundleResult.droppedRequests, currentL2Slot).catch(err =>
551
+ this.log.error(`Failed to backup requests dropped in simulation`, err),
552
+ );
553
+ return undefined;
554
+ }
555
+
556
+ const { requests, droppedRequests, gasLimit } =
557
+ bundleResult.kind === 'fallback'
558
+ ? {
559
+ requests: bundleResult.requests,
560
+ droppedRequests: bundleResult.droppedRequests,
561
+ gasLimit: MAX_L1_TX_LIMIT,
562
+ }
563
+ : bundleResult;
564
+
565
+ this.logDroppedInSim(droppedRequests);
566
+
567
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
568
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
569
+ const [blobConfig] = requests.filter(r => r.blobConfig).map(r => r.blobConfig);
570
+ const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
571
+
572
+ this.log.debug('Forwarding transactions', {
573
+ requests: requests.map(request => request.action),
574
+ txConfig,
575
+ });
576
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig, currentL2Slot);
577
+ if (result === undefined) {
578
+ return undefined;
579
+ }
580
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
581
+ const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action)];
582
+ return {
583
+ result,
584
+ expiredActions,
585
+ sentActions: requests.map(x => x.action),
586
+ successfulActions,
587
+ failedActions: allFailedActions,
588
+ };
589
+ } catch (err) {
590
+ const viemError = formatViemError(err);
591
+ this.log.error(`Failed to publish bundled transactions`, viemError);
592
+ if (err instanceof TimeoutError) {
593
+ const timeoutState = err instanceof L1TxTimeoutError ? err.txState : undefined;
594
+ void (async () => {
595
+ // The RPC is likely degraded right after a timeout, so back up without the block number
596
+ // rather than leaking an unhandled rejection.
597
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber().catch(() => 0n);
598
+ this.backupFailedTx(
599
+ {
600
+ id: this.failureRecordId(
601
+ validRequests.map(r => r.action),
602
+ currentL2Slot,
603
+ ),
604
+ failureType: 'timeout',
605
+ request: { to: MULTI_CALL_3_ADDRESS as Hex, data: '0x' as Hex },
606
+ l1BlockNumber,
607
+ error: { message: viemError.message, name: 'TimeoutError' },
608
+ context: {
609
+ actions: validRequests.map(r => r.action),
610
+ requests: validRequests
611
+ .filter(r => r.request.to !== null)
612
+ .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
613
+ sender: this.getSenderAddress().toString(),
614
+ slot: Number(currentL2Slot),
615
+ },
616
+ timing: this.computeTimingInfo(currentL2Slot),
617
+ gasInfo: timeoutState
618
+ ? {
619
+ sentFeesPerGasLadder: timeoutState.feesPerGasHistory,
620
+ attempts: timeoutState.attempts,
621
+ gasLimit: timeoutState.gasLimit,
622
+ nonce: timeoutState.nonce,
623
+ }
624
+ : undefined,
625
+ },
626
+ { captureFeeSummary: true, targetSlot: currentL2Slot },
627
+ );
628
+ })();
629
+ }
630
+ return undefined;
631
+ } finally {
632
+ try {
633
+ this.metrics.recordSenderBalance(
634
+ await this.l1TxUtils.getSenderBalance(),
635
+ this.l1TxUtils.getSenderAddress().toString(),
636
+ );
637
+ } catch (err) {
638
+ this.log.warn(`Failed to record balance after sending tx: ${err}`);
639
+ }
640
+ }
641
+ }
642
+
643
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */
644
+ private logDroppedInSim(dropped: DroppedRequest[]): void {
645
+ for (const drop of dropped) {
646
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
647
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
648
+ action: drop.request.action,
649
+ revertReason: revertReasonDecoded ?? drop.returnData,
650
+ revertReasonDecoded,
651
+ returnData: drop.returnData,
652
+ });
653
+ }
654
+ }
655
+
656
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */
657
+ private async backupDroppedInSim(dropped: DroppedRequest[], targetSlot?: SlotNumber): Promise<void> {
658
+ if (dropped.length === 0) {
659
+ return;
660
+ }
661
+ // Invoked as `void backupDroppedInSim(...)` on the publish path, so it must not throw.
662
+ try {
663
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
664
+ // Every dropped entry failed in the same slot against the same L1 fee conditions, so capture
665
+ // the fee environment once and share it rather than re-reading the window per entry.
666
+ const sharedFeeSummary = await this.captureFeeEnvironment(targetSlot).catch(() => undefined);
667
+ const timing = this.computeTimingInfo(targetSlot);
668
+ for (const { request: req } of dropped) {
669
+ this.backupFailedTx(
670
+ {
671
+ id: keccak256(req.request.data!),
672
+ failureType: 'simulation',
673
+ request: { to: req.request.to! as Hex, data: req.request.data! },
674
+ l1BlockNumber,
675
+ error: { message: 'Bundle entry dropped: action reverted in sim' },
676
+ context: {
677
+ actions: [req.action],
678
+ sender: this.getSenderAddress().toString(),
679
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined,
680
+ },
681
+ timing,
682
+ },
683
+ { sharedFeeSummary },
684
+ );
685
+ }
686
+ } catch (err) {
687
+ this.log.warn(`Failed to back up dropped-in-sim entries`, err);
688
+ }
689
+ }
690
+
691
+ /**
692
+ * Forwards transactions via Multicall3, rotating to the next available publisher if a send
693
+ * failure occurs (i.e. the tx never reached the chain).
694
+ * On-chain reverts and simulation errors are returned as-is without rotation.
695
+ */
696
+ private async forwardWithPublisherRotation(
697
+ validRequests: RequestWithExpiry[],
698
+ txConfig: RequestWithExpiry['gasConfig'],
699
+ blobConfig: L1BlobInputs | undefined,
700
+ targetSlot?: SlotNumber,
701
+ ) {
702
+ if (!txConfig?.gasLimit) {
703
+ throw new Error('gasLimit is required for bundled transactions');
704
+ }
705
+ const txConfigWithGasLimit = txConfig as L1TxConfig & { gasLimit: bigint };
706
+
707
+ const triedAddresses: EthAddress[] = [];
708
+ let currentPublisher = this.l1TxUtils;
709
+
710
+ while (true) {
711
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
712
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
713
+ triedAddresses: triedAddresses.map(a => a.toString()),
714
+ });
715
+ return undefined;
716
+ }
717
+ triedAddresses.push(currentPublisher.getSenderAddress());
718
+
719
+ try {
720
+ const result = await Multicall3.forward(
721
+ validRequests.map(r => r.request),
722
+ currentPublisher,
723
+ txConfigWithGasLimit,
724
+ blobConfig,
725
+ { gasLimitRequired: true },
726
+ );
727
+ this.l1TxUtils = currentPublisher;
728
+ return result;
729
+ } catch (err) {
730
+ if (err instanceof TimeoutError) {
731
+ throw err;
732
+ }
733
+ if (err instanceof MulticallForwarderRevertedError) {
734
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
735
+ transactionHash: err.receipt.transactionHash,
736
+ });
737
+ this.backupRevertFailure(validRequests, err, currentPublisher, targetSlot);
738
+ return undefined;
739
+ }
740
+ const viemError = formatViemError(err);
741
+ if (!this.getNextPublisher) {
742
+ this.log.error('Failed to publish bundled transactions', viemError);
743
+ this.backupSendFailure(validRequests, viemError, currentPublisher, targetSlot);
744
+ return undefined;
745
+ }
746
+ this.log.warn(
747
+ `Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`,
748
+ viemError,
749
+ );
750
+ const nextPublisher = await this.getNextPublisher([...triedAddresses]);
751
+ if (!nextPublisher) {
752
+ this.log.error(
753
+ `All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`,
754
+ viemError,
755
+ { triedAddresses: triedAddresses.map(a => a.toString()) },
756
+ );
757
+ this.backupSendFailure(validRequests, viemError, currentPublisher, targetSlot);
758
+ return undefined;
759
+ }
760
+ currentPublisher = nextPublisher;
761
+ }
762
+ }
763
+ }
764
+
765
+ /** Backs up an on-chain revert failure to the failed tx store. */
766
+ private backupRevertFailure(
767
+ requests: RequestWithExpiry[],
768
+ err: MulticallForwarderRevertedError,
769
+ publisher: L1TxUtils,
770
+ targetSlot?: SlotNumber,
771
+ ): void {
772
+ this.backupFailedTx(
773
+ {
774
+ id: err.receipt.transactionHash,
775
+ failureType: 'revert',
776
+ request: { to: MULTI_CALL_3_ADDRESS as Hex, data: '0x' as Hex },
777
+ l1BlockNumber: err.receipt.blockNumber,
778
+ receipt: {
779
+ transactionHash: err.receipt.transactionHash,
780
+ blockNumber: err.receipt.blockNumber,
781
+ gasUsed: err.receipt.gasUsed,
782
+ status: 'reverted',
783
+ },
784
+ error: { message: err.message, name: err.name },
785
+ context: {
786
+ actions: requests.map(r => r.action),
787
+ requests: requests
788
+ .filter(r => r.request.to !== null)
789
+ .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
790
+ sender: publisher.getSenderAddress().toString(),
791
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined,
792
+ },
793
+ gasInfo: err.txState
794
+ ? {
795
+ sentFeesPerGas: err.txState.feesPerGas,
796
+ gasLimit: err.txState.gasLimit,
797
+ nonce: err.txState.nonce,
798
+ }
799
+ : undefined,
800
+ timing: this.computeTimingInfo(targetSlot),
801
+ },
802
+ { captureFeeSummary: true, targetSlot },
803
+ );
804
+ }
805
+
806
+ /** Backs up a send failure (tx never reached chain) to the failed tx store. */
807
+ private backupSendFailure(
808
+ requests: RequestWithExpiry[],
809
+ error: FormattedViemError | Error,
810
+ publisher: L1TxUtils,
811
+ targetSlot?: SlotNumber,
812
+ ): void {
813
+ // If we can't get the block number, still back up without it.
814
+ void this.l1TxUtils
815
+ .getBlockNumber()
816
+ .catch(() => 0n)
817
+ .then(l1BlockNumber => {
818
+ this.backupFailedTx(
819
+ {
820
+ id: this.failureRecordId(
821
+ requests.map(r => r.action),
822
+ targetSlot,
823
+ ),
824
+ failureType: 'send-error',
825
+ request: { to: MULTI_CALL_3_ADDRESS as Hex, data: '0x' as Hex },
826
+ l1BlockNumber,
827
+ error: {
828
+ message: error.message,
829
+ name: 'name' in error ? error.name : undefined,
830
+ },
831
+ context: {
832
+ actions: requests.map(r => r.action),
833
+ requests: requests
834
+ .filter(r => r.request.to !== null)
835
+ .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
836
+ sender: publisher.getSenderAddress().toString(),
837
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined,
838
+ },
839
+ timing: this.computeTimingInfo(targetSlot),
840
+ },
841
+ { captureFeeSummary: true, targetSlot },
842
+ );
843
+ });
844
+ }
845
+
846
+ /*
847
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
848
+ */
849
+ public async sendRequestsAt(targetSlot: SlotNumber): Promise<SendRequestsResult | undefined> {
850
+ await this.waitForTargetSlot(targetSlot);
851
+ if (this.interrupted) {
852
+ return undefined;
853
+ }
854
+
855
+ return this.sendRequests(targetSlot);
856
+ }
857
+
858
+ /**
859
+ * Sleeps until one L1 slot before the L2 slot boundary, and then waits for that L1 block
860
+ * to be mined, so we don't risk being included in it. If that block never gets mined after
861
+ * a timeout, we assume it got skipped on L1, so we send the tx anyway.
862
+ */
863
+ private async waitForTargetSlot(targetSlot: SlotNumber): Promise<void> {
864
+ const l1Constants = this.epochCache.getL1Constants();
865
+ const nowInSeconds = this.dateProvider.nowInSeconds();
866
+ const startOfTargetSlotTs = getTimestampForSlot(targetSlot, l1Constants);
867
+ const previousL1BlockTs = startOfTargetSlotTs - this.ethereumSlotDuration;
868
+ const waitDeadlineTs = previousL1BlockTs + BigInt(this.previousL1BlockWaitTimeoutMs / 1000);
869
+ const logCtx = { targetSlot, startOfTargetSlotTs, nowInSeconds, previousL1BlockTs, waitDeadlineTs };
870
+
871
+ // Check if we are already past time
872
+ if (nowInSeconds >= startOfTargetSlotTs) {
873
+ this.log.verbose(`Target slot ${targetSlot} already started, sending requests immediately`, logCtx);
874
+ return;
875
+ }
876
+
877
+ // Otherwise we wait
878
+ this.log.debug(`Waiting for slot ${targetSlot} before sending requests`, logCtx);
879
+
880
+ // Wait until previous L1 block timestamp first
881
+ const sleepMs = (Number(previousL1BlockTs) - nowInSeconds) * 1000;
882
+ if (sleepMs > 0 && !this.interrupted) {
883
+ this.log.trace(`Sleeping ${sleepMs}ms before waiting for previous L1 block`, logCtx);
884
+ await this.interruptibleSleep.sleep(sleepMs);
885
+ }
886
+
887
+ // Then loop until we see the previous L1 block, so we know that we cannot be included in it.
888
+ // We time out after a while, once we are sure that that block is skipped in L1.
889
+ while (!this.interrupted) {
890
+ try {
891
+ const nowInSeconds = this.dateProvider.nowInSeconds();
892
+ logCtx.nowInSeconds = nowInSeconds;
893
+
894
+ if (nowInSeconds >= waitDeadlineTs) {
895
+ this.log.warn(`Timed out waiting for previous L1 block before sending requests, proceeding`, logCtx);
896
+ return;
897
+ }
898
+
899
+ const latestBlockTs = await this.l1TxUtils.getBlock().then(b => b.timestamp);
900
+ if (latestBlockTs >= previousL1BlockTs) {
901
+ this.log.debug(`Previous L1 block mined, proceeding to send requests`, { ...logCtx, latestBlockTs });
902
+ return;
903
+ }
904
+ this.log.trace(`Previous L1 block not mined yet, continuing to wait`, { ...logCtx, latestBlockTs });
905
+ } catch (err) {
906
+ this.log.error(`Error while waiting for previous L1 block before sending requests; retrying`, err, logCtx);
907
+ } finally {
908
+ await this.interruptibleSleep.sleep(this.previousL1BlockWaitPollIntervalMs);
909
+ }
910
+ }
911
+ }
912
+
913
+ private callbackBundledTransactions(
914
+ requests: RequestWithExpiry[],
915
+ result: { receipt: TransactionReceipt; multicallData: Hex },
916
+ ) {
917
+ const actionsListStr = requests.map(r => r.action).join(', ');
918
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
919
+ result,
920
+ requests: requests.map(r => ({
921
+ ...r,
922
+ // Avoid logging large blob data
923
+ blobConfig: r.blobConfig
924
+ ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
925
+ : undefined,
926
+ })),
927
+ });
928
+ const successfulActions: Action[] = [];
929
+ const failedActions: Action[] = [];
930
+ for (const request of requests) {
931
+ if (request.checkSuccess(request.request, result)) {
932
+ successfulActions.push(request.action);
933
+ } else {
934
+ failedActions.push(request.action);
935
+ }
936
+ }
937
+ return { successfulActions, failedActions };
938
+ }
939
+
940
+ /**
941
+ * @notice Will call `canProposeAt` to make sure that it is possible to propose
942
+ * @param tipArchive - The archive to check
943
+ * @returns The slot and block number if it is possible to propose, undefined otherwise
944
+ */
945
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
946
+ // TODO: #14291 - should loop through multiple keys to check if any of them can propose
947
+ // These errors are expected when we cannot actually propose right now — usually because our
948
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
949
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
950
+ // skip the proposal; we do NOT treat these as bugs.
951
+ const expectedErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
952
+
953
+ const slotOffset = this.aztecSlotDuration;
954
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
955
+
956
+ return this.rollupContract
957
+ .canProposeAt(
958
+ tipArchive.toBuffer(),
959
+ msgSender.toString(),
960
+ nextL1SlotTs,
961
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
962
+ )
963
+ .catch(err => {
964
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
965
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
966
+ error: err.message,
967
+ });
968
+ } else {
969
+ this.log.error(err.name, err);
970
+ }
971
+ return undefined;
972
+ });
973
+ }
974
+
975
+ /**
976
+ * @notice Will simulate the rollup's `validateHeaderWithAttestations` to make sure the checkpoint header is valid
977
+ * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header,
978
+ * skipping the DA and signature checks. It will throw if the checkpoint header is invalid.
979
+ * @param header - The checkpoint header to validate
980
+ */
981
+ @trackSpan('SequencerPublisher.validateCheckpointHeader')
982
+ public async validateCheckpointHeader(
983
+ header: CheckpointHeader,
984
+ simulationOverridesPlan?: SimulationOverridesPlan,
985
+ ): Promise<void> {
986
+ const flags = { ignoreDA: true, ignoreSignatures: true };
987
+
988
+ const args = [
989
+ header.toViem(),
990
+ CommitteeAttestationsAndSigners.packAttestations([]),
991
+ [], // no signers
992
+ Signature.empty().toViemSignature(),
993
+ `0x${'0'.repeat(64)}`, // 32 empty bytes
994
+ header.blobsHash.toString(),
995
+ flags,
996
+ ] as const;
997
+
998
+ const l1Constants = this.epochCache.getL1Constants();
999
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
1000
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
1001
+ // Balance override for compatibility with providers that apply an upfront funds check to simulated calls.
1002
+ stateOverrides.push({
1003
+ address: MULTI_CALL_3_ADDRESS,
1004
+ balance: 10n * WEI_CONST * WEI_CONST, // 10 ETH
1005
+ });
1006
+
1007
+ await this.l1TxUtils.simulate(
1008
+ {
1009
+ to: this.rollupContract.address,
1010
+ data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
1011
+ from: MULTI_CALL_3_ADDRESS,
1012
+ },
1013
+ { time: ts },
1014
+ stateOverrides,
1015
+ );
1016
+ this.log.debug(`Simulated validateHeader`);
1017
+ }
1018
+
1019
+ /**
1020
+ * Simulate making a call to invalidate a checkpoint with invalid attestations. Returns undefined if no need to invalidate.
1021
+ * @param validationResult - The validation result indicating which checkpoint to invalidate (as returned by the archiver)
1022
+ */
1023
+ public async simulateInvalidateCheckpoint(
1024
+ validationResult: ValidateCheckpointResult,
1025
+ ): Promise<InvalidateCheckpointRequest | undefined> {
1026
+ if (validationResult.valid) {
1027
+ return undefined;
1028
+ }
1029
+
1030
+ const { reason, checkpoint } = validationResult;
1031
+ const checkpointNumber = checkpoint.checkpointNumber;
1032
+ const logData = { ...checkpoint, reason };
1033
+
1034
+ const currentCheckpointNumber = await this.rollupContract.getCheckpointNumber();
1035
+ if (currentCheckpointNumber < checkpointNumber) {
1036
+ this.log.verbose(
1037
+ `Skipping checkpoint ${checkpointNumber} invalidation since it has already been removed from the pending chain`,
1038
+ { currentCheckpointNumber, ...logData },
1039
+ );
1040
+ return undefined;
1041
+ }
1042
+
1043
+ const request = this.buildInvalidateCheckpointRequest(validationResult);
1044
+ this.log.debug(`Simulating invalidate checkpoint ${checkpointNumber}`, { ...logData, request });
1045
+
1046
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1047
+
1048
+ try {
1049
+ const { gasUsed } = await this.l1TxUtils.simulate(
1050
+ request,
1051
+ undefined,
1052
+ undefined,
1053
+ mergeAbis([request.abi ?? [], ErrorsAbi]),
1054
+ );
1055
+ this.log.verbose(`Simulation for invalidate checkpoint ${checkpointNumber} succeeded`, {
1056
+ ...logData,
1057
+ request,
1058
+ gasUsed,
1059
+ });
1060
+
1061
+ return {
1062
+ request,
1063
+ gasUsed,
1064
+ checkpointNumber,
1065
+ forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
1066
+ lastArchive: validationResult.checkpoint.lastArchive,
1067
+ reason,
1068
+ };
1069
+ } catch (err) {
1070
+ const viemError = formatViemError(err);
1071
+
1072
+ // If the error is due to the checkpoint not being in the pending chain, and it was indeed removed by someone else,
1073
+ // we can safely ignore it and return undefined so we go ahead with checkpoint building.
1074
+ if (viemError.message?.includes('Rollup__CheckpointNotInPendingChain')) {
1075
+ this.log.verbose(
1076
+ `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
1077
+ { ...logData, request, error: viemError.message },
1078
+ );
1079
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
1080
+ if (latestProposedCheckpointNumber < checkpointNumber) {
1081
+ this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
1082
+ return undefined;
1083
+ } else {
1084
+ this.log.error(
1085
+ `Simulation for invalidate checkpoint ${checkpointNumber} failed and it is still in pending chain`,
1086
+ viemError,
1087
+ logData,
1088
+ );
1089
+ throw new Error(
1090
+ `Failed to simulate invalidate checkpoint ${checkpointNumber} while it is still in pending chain`,
1091
+ {
1092
+ cause: viemError,
1093
+ },
1094
+ );
1095
+ }
1096
+ }
1097
+
1098
+ // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
1099
+ this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
1100
+ this.backupFailedTx(
1101
+ {
1102
+ id: keccak256(request.data!),
1103
+ failureType: 'simulation',
1104
+ request: { to: request.to!, data: request.data!, value: request.value },
1105
+ l1BlockNumber,
1106
+ error: { message: viemError.message, name: viemError.name },
1107
+ context: {
1108
+ actions: [`invalidate-${reason}`],
1109
+ checkpointNumber,
1110
+ sender: this.getSenderAddress().toString(),
1111
+ },
1112
+ timing: this.computeTimingInfo(this.getCurrentL2Slot()),
1113
+ },
1114
+ { captureFeeSummary: true, targetSlot: this.getCurrentL2Slot() },
1115
+ );
1116
+ throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, { cause: viemError });
1117
+ }
1118
+ }
1119
+
1120
+ private buildInvalidateCheckpointRequest(validationResult: ValidateCheckpointResult) {
1121
+ if (validationResult.valid) {
1122
+ throw new Error('Cannot invalidate a valid checkpoint');
1123
+ }
1124
+
1125
+ const { checkpoint, committee, reason } = validationResult;
1126
+ const logData = { ...checkpoint, reason };
1127
+ this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
1128
+
1129
+ // Use the exact packed tuple posted to L1 verbatim. A repack via `packAttestations` is not a
1130
+ // byte-faithful inverse of `fromPacked` (a canonicalized yParity byte or an all-zero signature slot
1131
+ // round-trips differently), so it would diverge from the stored `attestationsHash` and revert the
1132
+ // invalidation.
1133
+ const attestationsAndSigners = validationResult.verbatimAttestations;
1134
+
1135
+ if (reason === 'invalid-attestation') {
1136
+ return this.rollupContract.buildInvalidateBadAttestationRequest(
1137
+ checkpoint.checkpointNumber,
1138
+ attestationsAndSigners,
1139
+ committee,
1140
+ validationResult.invalidIndex,
1141
+ );
1142
+ } else if (reason === 'insufficient-attestations') {
1143
+ return this.rollupContract.buildInvalidateInsufficientAttestationsRequest(
1144
+ checkpoint.checkpointNumber,
1145
+ attestationsAndSigners,
1146
+ committee,
1147
+ );
1148
+ } else {
1149
+ const _: never = reason;
1150
+ throw new Error(`Unknown reason for invalidation`);
1151
+ }
1152
+ }
1153
+
1154
+ private async enqueueCastSignalHelper(
1155
+ slotNumber: SlotNumber,
1156
+ signalType: GovernanceSignalAction,
1157
+ payload: EthAddress,
1158
+ base: GovernanceProposerContract,
1159
+ signerAddress: EthAddress,
1160
+ signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
1161
+ ): Promise<boolean> {
1162
+ if (this.lastActions[signalType] && this.lastActions[signalType] === slotNumber) {
1163
+ this.log.debug(`Skipping duplicate vote cast signal ${signalType} for slot ${slotNumber}`);
1164
+ return false;
1165
+ }
1166
+ if (payload.equals(EthAddress.ZERO)) {
1167
+ return false;
1168
+ }
1169
+ if (signerAddress.equals(EthAddress.ZERO)) {
1170
+ this.log.warn(`Cannot enqueue vote cast signal ${signalType} for address zero at slot ${slotNumber}`);
1171
+ return false;
1172
+ }
1173
+
1174
+ const canonicalRollup = await base.getRollupAddress();
1175
+ if (!canonicalRollup.equals(EthAddress.fromString(this.rollupContract.address))) {
1176
+ this.log.warn(`Rollup ${this.rollupContract.address} is not canonical, skipping governance signal`, {
1177
+ slotNumber,
1178
+ signalType,
1179
+ canonicalRollup,
1180
+ targetRollup: this.rollupContract.address,
1181
+ payload: payload.toString(),
1182
+ });
1183
+ return false;
1184
+ }
1185
+
1186
+ const round = await base.computeRound(slotNumber);
1187
+ const roundInfo = await base.getRoundInfo(this.rollupContract.address, round);
1188
+
1189
+ if (roundInfo.quorumReached) {
1190
+ return false;
1191
+ }
1192
+
1193
+ if (roundInfo.lastSignalSlot >= slotNumber) {
1194
+ return false;
1195
+ }
1196
+
1197
+ if (await base.isPayloadEmpty(payload)) {
1198
+ this.log.warn(`Skipping vote cast for payload with empty code`);
1199
+ return false;
1200
+ }
1201
+
1202
+ // Classify the payload against the Governance proposal history so we stop signalling once its
1203
+ // proposal is live or was already executed, while still re-signalling one whose proposal was
1204
+ // merely rejected/dropped/expired.
1205
+ let status: PayloadProposalStatus = 'none';
1206
+ try {
1207
+ status = await base.getPayloadProposalStatus(payload.toString());
1208
+ } catch (err) {
1209
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
1210
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
1211
+ // participation entirely; failing open at worst produces a duplicate signal that the
1212
+ // contract will simply count alongside others in the round.
1213
+ this.log.error(`Failed to check governance proposal status for payload ${payload} (signalling anyway)`, err, {
1214
+ slotNumber,
1215
+ signalType,
1216
+ });
1217
+ }
1218
+
1219
+ if (status === 'live') {
1220
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`, {
1221
+ slotNumber,
1222
+ signalType,
1223
+ payload: payload.toString(),
1224
+ });
1225
+ return false;
1226
+ }
1227
+
1228
+ if (status === 'executed' && !this.config.governanceProposerForcePayloadVote) {
1229
+ this.log.info(
1230
+ `Payload ${payload} was executed by governance within lookback, stopping signals ` +
1231
+ `(set GOVERNANCE_PROPOSER_FORCE_PAYLOAD_VOTE to re-signal)`,
1232
+ { slotNumber, signalType, payload: payload.toString() },
1233
+ );
1234
+ return false;
1235
+ }
1236
+
1237
+ const cachedLastVote = this.lastActions[signalType];
1238
+ this.lastActions[signalType] = slotNumber;
1239
+ const action = signalType;
1240
+
1241
+ const request = await base.createSignalRequestWithSignature(
1242
+ payload.toString(),
1243
+ slotNumber,
1244
+ this.config.l1ChainId,
1245
+ signerAddress.toString(),
1246
+ signer,
1247
+ );
1248
+ this.log.debug(`Created ${action} request with signature`, {
1249
+ request,
1250
+ round,
1251
+ signer: this.l1TxUtils.client.account?.address,
1252
+ lastValidL2Slot: slotNumber,
1253
+ });
1254
+
1255
+ // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
1256
+ this.addRequest({
1257
+ action,
1258
+ request,
1259
+ lastValidL2Slot: slotNumber,
1260
+ checkSuccess: (_request, result) => {
1261
+ const success =
1262
+ result &&
1263
+ extractEventSuccess(result.receipt, {
1264
+ address: base.address.toString(),
1265
+ abi: EmpireBaseAbi,
1266
+ eventName: 'SignalCast',
1267
+ });
1268
+
1269
+ const logData = { ...result, slotNumber, round, payload: payload.toString() };
1270
+ if (!success) {
1271
+ this.log.error(
1272
+ `Signaling in ${action} for ${payload} at slot ${slotNumber} in round ${round} failed`,
1273
+ logData,
1274
+ );
1275
+ this.lastActions[signalType] = cachedLastVote;
1276
+ return false;
1277
+ } else {
1278
+ this.log.info(
1279
+ `Signaling in ${action} for ${payload} at slot ${slotNumber} in round ${round} succeeded`,
1280
+ logData,
1281
+ );
1282
+ return true;
1283
+ }
1284
+ },
1285
+ });
1286
+ return true;
1287
+ }
1288
+
1289
+ /**
1290
+ * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
1291
+ * @param slotNumber - The slot number to cast a signal for.
1292
+ * @returns True if the signal was successfully enqueued, false otherwise.
1293
+ */
1294
+ public enqueueGovernanceCastSignal(
1295
+ governancePayload: EthAddress,
1296
+ slotNumber: SlotNumber,
1297
+ signerAddress: EthAddress,
1298
+ signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
1299
+ ): Promise<boolean> {
1300
+ return this.enqueueCastSignalHelper(
1301
+ slotNumber,
1302
+ 'governance-signal',
1303
+ governancePayload,
1304
+ this.govProposerContract,
1305
+ signerAddress,
1306
+ signer,
1307
+ );
1308
+ }
1309
+
1310
+ /**
1311
+ * Enqueues a `prune()` transaction if the rollup is prunable at the given slot's L1 timestamp.
1312
+ * `prune()` is permissionless and idempotent — if the chain is no longer prunable by send time the
1313
+ * bundle simulation usually drops the entry; on a node without `eth_simulateV1` the bundle is sent
1314
+ * as-is and the prune reverts `Rollup__NothingToPrune` inside `aggregate3(allowFailure: true)`
1315
+ * (a failed action, never a whole-tx revert). Used by the failed-sync fallback so a stuck pending
1316
+ * chain (e.g. bad data blocking sync) can be wound back to recover.
1317
+ * @returns true if a prune request was enqueued, false otherwise.
1318
+ */
1319
+ public async enqueuePruneIfPrunable(slotNumber: SlotNumber): Promise<boolean> {
1320
+ if (this.lastActions['prune'] === slotNumber) {
1321
+ this.log.debug(`Skipping duplicate prune for slot ${slotNumber}`, { slotNumber });
1322
+ return false;
1323
+ }
1324
+ // Use the SAME timestamp the bundle simulator overrides block.timestamp with at send time
1325
+ // (sequencer-bundle-simulator.ts) so this upfront check and the send-time sim agree. Slot-start
1326
+ // and last-L1-slot both fall within the same L2 slot (and epoch, which is what `canPruneAtTime`
1327
+ // derives), so they agree today; matching the simulator keeps it robust if the contract ever uses
1328
+ // the timestamp more granularly.
1329
+ const ts = getLastL1SlotTimestampForL2Slot(slotNumber, this.epochCache.getL1Constants());
1330
+ const canPrune = await this.rollupContract.canPruneAtTime(ts).catch(err => {
1331
+ this.log.error(`Failed to check canPruneAtTime for slot ${slotNumber}`, err, { slotNumber });
1332
+ return false;
1333
+ });
1334
+ if (!canPrune) {
1335
+ this.log.debug(`Rollup not prunable at slot ${slotNumber}`, { slotNumber });
1336
+ return false;
1337
+ }
1338
+ const request: L1TxRequest = {
1339
+ to: this.rollupContract.address,
1340
+ data: encodeFunctionData({ abi: RollupAbi, functionName: 'prune', args: [] }),
1341
+ };
1342
+ this.log.info(`Enqueuing rollup prune for slot ${slotNumber}`, { slotNumber });
1343
+ return this.enqueueRequest(
1344
+ 'prune',
1345
+ request,
1346
+ { address: this.rollupContract.address, abi: RollupAbi, eventName: 'PrunedPending' },
1347
+ slotNumber,
1348
+ );
1349
+ }
1350
+
1351
+ /** Enqueues all slashing actions as returned by the slasher client. */
1352
+ public async enqueueSlashingActions(
1353
+ actions: ProposerSlashAction[],
1354
+ slotNumber: SlotNumber,
1355
+ signerAddress: EthAddress,
1356
+ signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
1357
+ ): Promise<boolean> {
1358
+ if (actions.length === 0) {
1359
+ this.log.debug(`No slashing actions to enqueue for slot ${slotNumber}`);
1360
+ return false;
1361
+ }
1362
+
1363
+ for (const action of actions) {
1364
+ switch (action.type) {
1365
+ case 'vote-offenses': {
1366
+ this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
1367
+ slotNumber,
1368
+ round: action.round,
1369
+ votesCount: action.votes.length,
1370
+ signerAddress,
1371
+ });
1372
+ if (!this.slashingProposerContract) {
1373
+ this.log.error('No slashing proposer contract available');
1374
+ return false;
1375
+ }
1376
+ const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1377
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1378
+ this.enqueueRequest(
1379
+ 'vote-offenses',
1380
+ request,
1381
+ {
1382
+ address: this.slashingProposerContract.address.toString(),
1383
+ abi: SlashingProposerAbi,
1384
+ eventName: 'VoteCast',
1385
+ },
1386
+ slotNumber,
1387
+ );
1388
+ break;
1389
+ }
1390
+
1391
+ case 'execute-slash': {
1392
+ this.log.debug(`Enqueuing slash execution for round ${action.round} at slot ${slotNumber}`, {
1393
+ slotNumber,
1394
+ round: action.round,
1395
+ signerAddress,
1396
+ });
1397
+ if (!this.slashingProposerContract) {
1398
+ this.log.error('No slashing proposer contract available');
1399
+ return false;
1400
+ }
1401
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1402
+ action.round,
1403
+ action.committees,
1404
+ );
1405
+ this.enqueueRequest(
1406
+ 'execute-slash',
1407
+ executeRequest,
1408
+ {
1409
+ address: this.slashingProposerContract.address.toString(),
1410
+ abi: SlashingProposerAbi,
1411
+ eventName: 'RoundExecuted',
1412
+ },
1413
+ slotNumber,
1414
+ );
1415
+ break;
1416
+ }
1417
+
1418
+ default: {
1419
+ const _: never = action;
1420
+ throw new Error(`Unknown slashing action type: ${(action as ProposerSlashAction).type}`);
1421
+ }
1422
+ }
1423
+ }
1424
+
1425
+ return true;
1426
+ }
1427
+
1428
+ /** Enqueues a proposal for a checkpoint on L1 */
1429
+ public async enqueueProposeCheckpoint(
1430
+ checkpoint: Checkpoint,
1431
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
1432
+ attestationsAndSignersSignature: Signature,
1433
+ bucketHint: bigint,
1434
+ opts: EnqueueProposeCheckpointOpts = {},
1435
+ ): Promise<void> {
1436
+ const checkpointHeader = checkpoint.header;
1437
+
1438
+ const blobFields = checkpoint.toBlobFields();
1439
+ const blobs = await getBlobsPerL1Block(blobFields);
1440
+
1441
+ const proposeTxArgs: L1ProcessArgs = {
1442
+ header: checkpointHeader,
1443
+ archive: checkpoint.archive.root.toBuffer(),
1444
+ blobs,
1445
+ attestationsAndSigners,
1446
+ attestationsAndSignersSignature,
1447
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
1448
+ bucketHint,
1449
+ };
1450
+
1451
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1452
+ ...checkpoint.toCheckpointInfo(),
1453
+ txTimeoutAt: opts.txTimeoutAt,
1454
+ });
1455
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
1456
+ }
1457
+
1458
+ public enqueueInvalidateCheckpoint(
1459
+ request: InvalidateCheckpointRequest | undefined,
1460
+ opts: { txTimeoutAt?: Date } = {},
1461
+ ) {
1462
+ if (!request) {
1463
+ return;
1464
+ }
1465
+
1466
+ const { gasUsed, checkpointNumber } = request;
1467
+ const logData = { gasUsed, checkpointNumber, opts };
1468
+ this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1469
+ this.addRequest({
1470
+ action: `invalidate-by-${request.reason}`,
1471
+ request: request.request,
1472
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
1473
+ lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1474
+ checkSuccess: (_req, result) => {
1475
+ const success =
1476
+ result &&
1477
+ extractEventSuccess(result.receipt, {
1478
+ address: this.rollupContract.address,
1479
+ abi: RollupAbi,
1480
+ eventName: 'CheckpointInvalidated',
1481
+ });
1482
+ if (!success) {
1483
+ this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
1484
+ } else {
1485
+ this.log.info(`Invalidate checkpoint ${request.checkpointNumber} succeeded`, { ...result, ...logData });
1486
+ }
1487
+ return !!success;
1488
+ },
1489
+ });
1490
+ }
1491
+
1492
+ /**
1493
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1494
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1495
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1496
+ */
1497
+ private enqueueRequest(
1498
+ action: Action,
1499
+ request: L1TxRequest,
1500
+ eventOpts: { address: string; abi: Abi; eventName: string },
1501
+ slotNumber: SlotNumber,
1502
+ ): boolean {
1503
+ if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1504
+ this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1505
+ return false;
1506
+ }
1507
+ const cachedLastActionSlot = this.lastActions[action];
1508
+ this.lastActions[action] = slotNumber;
1509
+
1510
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1511
+ this.addRequest({
1512
+ action,
1513
+ request,
1514
+ lastValidL2Slot: slotNumber,
1515
+ checkSuccess: (_request, result) => {
1516
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1517
+ if (!success) {
1518
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1519
+ this.lastActions[action] = cachedLastActionSlot;
1520
+ } else {
1521
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1522
+ }
1523
+ return !!success;
1524
+ },
1525
+ });
1526
+ return true;
1527
+ }
1528
+
1529
+ /**
1530
+ * Calling `interrupt` will cause any in progress call to `publishRollup` to return `false` asap.
1531
+ * Be warned, the call may return false even if the tx subsequently gets successfully mined.
1532
+ * In practice this shouldn't matter, as we'll only ever be calling `interrupt` when we know it's going to fail.
1533
+ * A call to `restart` is required before you can continue publishing.
1534
+ */
1535
+ public interrupt() {
1536
+ this.interrupted = true;
1537
+ this.interruptibleSleep.interrupt();
1538
+ this.l1TxUtils.interrupt();
1539
+ }
1540
+
1541
+ /** Restarts the publisher after calling `interrupt`. */
1542
+ public restart() {
1543
+ this.interrupted = false;
1544
+ this.l1TxUtils.restart();
1545
+ }
1546
+
1547
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1548
+ const kzg = Blob.getViemKzgInstance();
1549
+ const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1550
+ this.log.debug('Validating blob input', { blobInput });
1551
+
1552
+ // Get blob evaluation gas
1553
+ let blobEvaluationGas: bigint;
1554
+ if (this.config.fishermanMode) {
1555
+ // In fisherman mode, we can't estimate blob gas because estimateGas doesn't support state overrides
1556
+ // Use a fixed estimate.
1557
+ blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1558
+ this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1559
+ } else {
1560
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1561
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1562
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1563
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1564
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1565
+ blobEvaluationGas = await this.l1TxUtils
1566
+ .estimateGas(
1567
+ this.getSenderAddress().toString(),
1568
+ {
1569
+ to: this.rollupContract.address,
1570
+ data: encodeFunctionData({
1571
+ abi: RollupAbi,
1572
+ functionName: 'validateBlobs',
1573
+ args: [blobInput],
1574
+ }),
1575
+ },
1576
+ {},
1577
+ {
1578
+ blobs: encodedData.blobs.map(b => b.data),
1579
+ kzg,
1580
+ },
1581
+ )
1582
+ .catch(async err => {
1583
+ const viemError = formatViemError(err);
1584
+ this.log.error(`Failed to validate blobs`, viemError.message, { metaMessages: viemError.metaMessages });
1585
+ const validateBlobsData = encodeFunctionData({
1586
+ abi: RollupAbi,
1587
+ functionName: 'validateBlobs',
1588
+ args: [blobInput],
1589
+ });
1590
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1591
+ this.backupFailedTx(
1592
+ {
1593
+ id: keccak256(validateBlobsData),
1594
+ failureType: 'simulation',
1595
+ request: { to: this.rollupContract.address as Hex, data: validateBlobsData },
1596
+ blobData: encodedData.blobs.map(b => toHex(b.data)) as Hex[],
1597
+ l1BlockNumber,
1598
+ error: { message: viemError.message, name: viemError.name },
1599
+ context: {
1600
+ actions: ['validate-blobs'],
1601
+ sender: this.getSenderAddress().toString(),
1602
+ },
1603
+ timing: this.computeTimingInfo(this.getCurrentL2Slot()),
1604
+ },
1605
+ { captureFeeSummary: true, targetSlot: this.getCurrentL2Slot() },
1606
+ );
1607
+ throw new Error('Failed to validate blobs');
1608
+ });
1609
+ }
1610
+ const signers = encodedData.attestationsAndSigners.getSigners().map(signer => signer.toString());
1611
+
1612
+ const args = [
1613
+ {
1614
+ header: encodedData.header.toViem(),
1615
+ archive: toHex(encodedData.archive),
1616
+ oracleInput: {
1617
+ feeAssetPriceModifier: encodedData.feeAssetPriceModifier,
1618
+ },
1619
+ bucketHint: encodedData.bucketHint,
1620
+ },
1621
+ encodedData.attestationsAndSigners.getPackedAttestations(),
1622
+ signers,
1623
+ encodedData.attestationsAndSignersSignature.toViemSignature(),
1624
+ blobInput,
1625
+ ] as const;
1626
+
1627
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1628
+
1629
+ return { args, blobEvaluationGas, rollupData };
1630
+ }
1631
+
1632
+ private async addProposeTx(
1633
+ checkpoint: Checkpoint,
1634
+ encodedData: L1ProcessArgs,
1635
+ opts: EnqueueProposeCheckpointOpts = {},
1636
+ ): Promise<void> {
1637
+ const slot = checkpoint.header.slotNumber;
1638
+ const timer = new Timer();
1639
+ const kzg = Blob.getViemKzgInstance();
1640
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1641
+ const startBlock = await this.l1TxUtils.getBlockNumber();
1642
+
1643
+ // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1644
+ // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
1645
+ void Promise.resolve().then(() =>
1646
+ this.blobClient.sendBlobsToFilestore(encodedData.blobs).catch(_err => {
1647
+ this.log.error('Failed to send blobs to blob client');
1648
+ }),
1649
+ );
1650
+
1651
+ return this.addRequest({
1652
+ action: 'propose',
1653
+ request: {
1654
+ to: this.rollupContract.address,
1655
+ data: rollupData,
1656
+ },
1657
+ lastValidL2Slot: checkpoint.header.slotNumber,
1658
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1659
+ blobEvaluationGas,
1660
+ blobConfig: {
1661
+ blobs: encodedData.blobs.map(b => b.data),
1662
+ kzg,
1663
+ },
1664
+ checkSuccess: (_request, result) => {
1665
+ if (!result) {
1666
+ return false;
1667
+ }
1668
+ const { receipt, stats, errorMsg } = result;
1669
+ const success = extractEventSuccess(receipt, {
1670
+ address: this.rollupContract.address,
1671
+ abi: RollupAbi,
1672
+ eventName: 'CheckpointProposed',
1673
+ });
1674
+
1675
+ if (success) {
1676
+ const endBlock = receipt.blockNumber;
1677
+ const inclusionBlocks = Number(endBlock - startBlock);
1678
+ const { calldataGas, calldataSize, sender } = stats!;
1679
+ const publishStats: L1PublishCheckpointStats = {
1680
+ gasPrice: receipt.effectiveGasPrice,
1681
+ gasUsed: receipt.gasUsed,
1682
+ blobGasUsed: receipt.blobGasUsed ?? 0n,
1683
+ blobDataGas: receipt.blobGasPrice ?? 0n,
1684
+ transactionHash: receipt.transactionHash,
1685
+ calldataGas,
1686
+ calldataSize,
1687
+ sender,
1688
+ ...checkpoint.getStats(),
1689
+ eventName: 'rollup-published-to-l1',
1690
+ blobCount: encodedData.blobs.length,
1691
+ inclusionBlocks,
1692
+ };
1693
+ this.log.info(`Published checkpoint ${checkpoint.number} at slot ${slot} to rollup contract`, {
1694
+ ...stats,
1695
+ ...checkpoint.getStats(),
1696
+ ...pick(receipt, 'transactionHash', 'blockHash'),
1697
+ });
1698
+ this.metrics.recordProcessBlockTx(timer.ms(), publishStats);
1699
+
1700
+ return true;
1701
+ } else {
1702
+ this.metrics.recordFailedTx('process');
1703
+ this.log.error(
1704
+ `Publishing checkpoint at slot ${slot} failed with ${errorMsg ?? 'no error message'}`,
1705
+ undefined,
1706
+ { ...checkpoint.getStats(), ...receipt },
1707
+ );
1708
+ return false;
1709
+ }
1710
+ },
1711
+ });
1712
+ }
1713
+
1714
+ /** Returns the timestamp of the next L1 slot boundary after now. */
1715
+ private getNextL1SlotTimestamp(): bigint {
1716
+ const l1Constants = this.epochCache.getL1Constants();
1717
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1718
+ }
1719
+ }