@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,1401 @@
1
+ import { getKzg } from '@aztec-labs/blob-lib';
2
+ import { type EpochCache, PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec-labs/epoch-cache';
3
+ import { NoCommitteeError, type RollupContract } from '@aztec-labs/ethereum/contracts';
4
+ import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
5
+ import { merge, omit, pick } from '@aztec-labs/foundation/collection';
6
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
7
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
8
+ import { type Logger, createLogger } from '@aztec-labs/foundation/log';
9
+ import { RunningPromise } from '@aztec-labs/foundation/running-promise';
10
+ import type { DateProvider } from '@aztec-labs/foundation/timer';
11
+ import type { TypedEventEmitter } from '@aztec-labs/foundation/types';
12
+ import type { P2P } from '@aztec-labs/p2p';
13
+ import type { SlasherClientInterface } from '@aztec-labs/slasher';
14
+ import type {
15
+ BlockData,
16
+ L2BlockSink,
17
+ L2BlockSource,
18
+ ProposedCheckpointSink,
19
+ ValidateCheckpointResult,
20
+ } from '@aztec-labs/stdlib/block';
21
+ import {
22
+ type Checkpoint,
23
+ type ProposedCheckpointData,
24
+ buildCheckpointSimulationOverridesPlan,
25
+ } from '@aztec-labs/stdlib/checkpoint';
26
+ import type { ChainConfig } from '@aztec-labs/stdlib/config';
27
+ import { getEpochAtSlot } from '@aztec-labs/stdlib/epoch-helpers';
28
+ import {
29
+ MIN_PER_BLOCK_ALLOCATION_MULTIPLIER,
30
+ MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER,
31
+ computeNetworkTxGasLimits,
32
+ } from '@aztec-labs/stdlib/gas';
33
+ import {
34
+ type ResolvedSequencerConfig,
35
+ type SequencerConfig,
36
+ SequencerConfigSchema,
37
+ type WorldStateSynchronizer,
38
+ } from '@aztec-labs/stdlib/interfaces/server';
39
+ import type { L1ToL2MessageSource } from '@aztec-labs/stdlib/messaging';
40
+ import type { CoordinationSignatureContext } from '@aztec-labs/stdlib/p2p';
41
+ import { pickFromSchema } from '@aztec-labs/stdlib/schemas';
42
+ import { ProposerTimetable, buildProposerTimetable } from '@aztec-labs/stdlib/timetable';
43
+ import {
44
+ Attributes,
45
+ type TelemetryClient,
46
+ type Tracer,
47
+ getTelemetryClient,
48
+ trackSpan,
49
+ } from '@aztec-labs/telemetry-client';
50
+ import { FullNodeCheckpointsBuilder, NodeKeystoreAdapter, type ValidatorClient } from '@aztec-labs/validator-client';
51
+ import EventEmitter from 'node:events';
52
+
53
+ import { DefaultSequencerConfig } from '../config.js';
54
+ import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
55
+ import type { SequencerPublisherFactory } from '../publisher/sequencer-publisher-factory.js';
56
+ import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
57
+ import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
58
+ import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
59
+ import { CheckpointVoter } from './checkpoint_voter.js';
60
+ import { SequencerInterruptedError } from './errors.js';
61
+ import type { SequencerEvents } from './events.js';
62
+ import { SequencerMetrics } from './metrics.js';
63
+ import { logMissingCommittee } from './missing_committee.js';
64
+ import { RequestsTracker } from './requests_tracker.js';
65
+ import type { SequencerRollupConstants } from './types.js';
66
+ import { SequencerState } from './utils.js';
67
+
68
+ export { SequencerState };
69
+
70
+ /** Slot snapshot used to prepare a checkpoint proposal. */
71
+ type SequencerSlotContext = {
72
+ slot: SlotNumber;
73
+ targetSlot: SlotNumber;
74
+ epoch: EpochNumber;
75
+ targetEpoch: EpochNumber;
76
+ ts: bigint;
77
+ nowSeconds: bigint;
78
+ };
79
+
80
+ /**
81
+ * Sequencer client
82
+ * - Checks whether it is elected as proposer for the next slot
83
+ * - Builds multiple blocks and broadcasts them
84
+ * - Collects attestations for the checkpoint
85
+ * - Publishes the checkpoint to L1
86
+ * - Votes for proposals and slashes on L1
87
+ */
88
+ export class Sequencer extends (EventEmitter as new () => TypedEventEmitter<SequencerEvents>) {
89
+ protected runningPromise?: RunningPromise;
90
+ private state = SequencerState.STOPPED;
91
+ private stateSlotNumber: SlotNumber | undefined;
92
+ /** Wall-clock time (ms, via the date provider) at which the current state was entered. */
93
+ private stateEnteredAtMs: number;
94
+ private metrics: SequencerMetrics;
95
+ private checkpointProposalJobMetrics: CheckpointProposalJobMetrics;
96
+ private readonly stateLog: Logger;
97
+
98
+ /** The last slot for which we attempted to perform our fallback duties (votes and/or prune) with degraded block production */
99
+ private lastSlotForFallbackAction: SlotNumber | undefined;
100
+
101
+ /** The (checkpoint, slot) of the last invalidation request we successfully simulated, to prevent
102
+ * re-simulating and re-submitting the same invalidation across the many ticks within a single slot. */
103
+ private lastInvalidationAttempt: { slot: SlotNumber; checkpointNumber: CheckpointNumber } | undefined;
104
+
105
+ /** The last epoch for which we logged a "no committee" diagnostic, to avoid per-slot log spam. */
106
+ private lastEpochForNoCommitteeLog: EpochNumber | undefined;
107
+
108
+ /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */
109
+ protected lastSlotForCheckpointProposalJob: SlotNumber | undefined;
110
+
111
+ /** Last successful checkpoint proposed */
112
+ private lastCheckpointProposed: Checkpoint | undefined;
113
+
114
+ /** The last epoch for which we logged strategy comparison in fisherman mode. */
115
+ private lastEpochForStrategyComparison: EpochNumber | undefined;
116
+
117
+ /** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */
118
+ protected lastCheckpointProposalJob: CheckpointProposalJob | undefined;
119
+
120
+ /**
121
+ * In-flight fire-and-forget requests that {@link stop} interrupts and drains, and {@link pause} awaits
122
+ * untouched: the checkpoint proposal jobs' backgrounded L1 submissions (each job is handed this shared
123
+ * tracker) plus the sequencer's own fallback submissions (votes/prune when we cannot build, or
124
+ * escape-hatch votes). Each fallback send is gated by its wrapper publisher's interruptible target-slot
125
+ * sleep; the tracked interrupt wakes that sleep so the send short-circuits without publishing. A wrapper
126
+ * is created for a single send and is never restarted, so once interrupted its sleeper can never publish
127
+ * a stale-slot tx, even after the pooled publishers are restarted by a later {@link start}.
128
+ */
129
+ protected readonly pendingRequests = new RequestsTracker();
130
+
131
+ /** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */
132
+ protected timetable!: ProposerTimetable;
133
+
134
+ /** Config for the sequencer */
135
+ protected config: ResolvedSequencerConfig = DefaultSequencerConfig;
136
+ private readonly signatureContext: CoordinationSignatureContext;
137
+
138
+ constructor(
139
+ protected publisherFactory: SequencerPublisherFactory,
140
+ protected validatorClient: ValidatorClient,
141
+ protected globalsBuilder: GlobalVariableBuilder,
142
+ protected p2pClient: P2P,
143
+ protected worldState: WorldStateSynchronizer,
144
+ protected slasherClient: SlasherClientInterface | undefined,
145
+ protected l2BlockSource: L2BlockSource & L2BlockSink & ProposedCheckpointSink,
146
+ protected l1ToL2MessageSource: L1ToL2MessageSource,
147
+ protected checkpointsBuilder: FullNodeCheckpointsBuilder,
148
+ protected l1Constants: SequencerRollupConstants,
149
+ protected dateProvider: DateProvider,
150
+ protected epochCache: EpochCache,
151
+ protected rollupContract: RollupContract,
152
+ config: SequencerConfig & Pick<ChainConfig, 'l1ChainId' | 'rollupAddress'>,
153
+ protected telemetry: TelemetryClient = getTelemetryClient(),
154
+ protected log = createLogger('sequencer'),
155
+ ) {
156
+ super();
157
+ this.stateLog = log.createChild('state');
158
+ this.stateEnteredAtMs = this.dateProvider.now();
159
+
160
+ // Add [FISHERMAN] prefix to logger if in fisherman mode
161
+ if (config.fishermanMode) {
162
+ this.log = log.createChild('[FISHERMAN]');
163
+ }
164
+
165
+ this.signatureContext = {
166
+ chainId: config.l1ChainId,
167
+ rollupAddress: config.rollupAddress,
168
+ };
169
+ this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
170
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
171
+ this.updateConfig(config);
172
+ }
173
+
174
+ /**
175
+ * Updates sequencer config by the defined values and rebuilds the timetable.
176
+ *
177
+ * The merged config is validated against a candidate before being committed: {@link buildTimetable} may
178
+ * reject the candidate (invalid timing geometry, or per-block allocation multipliers below the network
179
+ * minimums). On rejection we leave `this.config` and `this.timetable` untouched and rethrow, so a bad update
180
+ * never leaves the sequencer running with a rejected config and a stale timetable.
181
+ */
182
+ public updateConfig(config: Partial<SequencerConfig>) {
183
+ const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
184
+ const candidate = merge(this.config, filteredConfig);
185
+ let timetable: ProposerTimetable;
186
+ try {
187
+ timetable = this.buildTimetable(candidate);
188
+ } catch (err) {
189
+ this.log.warn(`Rejecting sequencer config update: ${(err as Error).message}`, {
190
+ rejectedConfig: omit(filteredConfig, 'txPublicSetupAllowListExtend'),
191
+ });
192
+ throw err;
193
+ }
194
+ this.config = candidate;
195
+ this.timetable = timetable;
196
+ this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
197
+ }
198
+
199
+ /**
200
+ * Builds the proposer timetable from the given config and L1 constants via the shared
201
+ * {@link buildProposerTimetable} helper, so the sequencer derives the same blocks-per-checkpoint as the p2p
202
+ * layer and `getNodeInfo`. The fast local/e2e profile and budget clamping happen inside
203
+ * {@link ProposerTimetable}.
204
+ *
205
+ * Throws if the timing geometry is invalid or the per-block allocation multipliers are below the network
206
+ * minimums; callers must treat a throw as a rejected config and not commit it.
207
+ */
208
+ private buildTimetable(config: ResolvedSequencerConfig): ProposerTimetable {
209
+ const timetable = buildProposerTimetable(config, this.l1Constants);
210
+
211
+ const maxNumberOfBlocks = timetable.getMaxBlocksPerCheckpoint();
212
+ this.log.info(`Sequencer timetable initialized with ${maxNumberOfBlocks} blocks per slot`, {
213
+ aztecSlotDuration: timetable.aztecSlotDuration,
214
+ ethereumSlotDuration: timetable.ethereumSlotDuration,
215
+ blockDuration: timetable.blockDuration,
216
+ minBlockDuration: timetable.minBlockDuration,
217
+ p2pPropagationTime: timetable.p2pPropagationTime,
218
+ checkpointProposalPrepareTime: timetable.checkpointProposalPrepareTime,
219
+ maxNumberOfBlocks,
220
+ });
221
+
222
+ this.assertConfigMeetsNetworkTxLimits(config, maxNumberOfBlocks);
223
+
224
+ return timetable;
225
+ }
226
+
227
+ /**
228
+ * Checks this node's configured per-block allocation against the network admission limit. A node
229
+ * advertises and admits txs up to the limit derived from the network-minimum multipliers (see
230
+ * {@link computeNetworkTxGasLimits}).
231
+ *
232
+ * Fails startup (and runtime config updates) only when the configured per-block allocation *multipliers*
233
+ * (`perBlockAllocationMultiplier` / `perBlockDAAllocationMultiplier`) are below the network minimums: such
234
+ * a node would accept txs over RPC/gossip that its builder can never pack into a block regardless of block
235
+ * size. Operators may configure a higher (more generous) multiplier, but not a lower one.
236
+ *
237
+ * When the multipliers meet the floor but an absolute per-block gas cap (`maxDABlockGas` / `maxL2BlockGas`)
238
+ * shrinks the builder's effective grant below the network limit, this is legitimate operator
239
+ * restrictiveness — the node simply builds smaller blocks and such txs stay in the pool for other
240
+ * proposers — so we only log a warning rather than failing startup. Restrictive tx-count caps
241
+ * (`maxTxsPerBlock` / `maxTxsPerCheckpoint`) can likewise make the builder skip admitted txs; they are
242
+ * intentionally not modeled here for the same reason.
243
+ */
244
+ private assertConfigMeetsNetworkTxLimits(config: ResolvedSequencerConfig, maxBlocksPerCheckpoint: number) {
245
+ // Mirror CheckpointBuilder.capLimitsByCheckpointBudgets: DA falls back to the general multiplier.
246
+ const l2Multiplier = config.perBlockAllocationMultiplier;
247
+ const daMultiplier = config.perBlockDAAllocationMultiplier ?? l2Multiplier;
248
+
249
+ // The allocation is monotonic in the multiplier, so a multiplier at or above the network minimum
250
+ // guarantees the builder grants at least the network admission limit. Checking the multipliers directly
251
+ // is sufficient (and strictly more conservative than modeling the resulting gas grant).
252
+ if (daMultiplier < MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER) {
253
+ throw new Error(
254
+ `perBlockDAAllocationMultiplier (${daMultiplier}) is below the network minimum ` +
255
+ `${MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
256
+ );
257
+ }
258
+ if (l2Multiplier < MIN_PER_BLOCK_ALLOCATION_MULTIPLIER) {
259
+ throw new Error(
260
+ `perBlockAllocationMultiplier (${l2Multiplier}) is below the network minimum ` +
261
+ `${MIN_PER_BLOCK_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`,
262
+ );
263
+ }
264
+
265
+ // Absolute per-block gas caps below the network admission limit are legitimate operator restrictiveness:
266
+ // the node simply builds smaller blocks and such txs stay in the pool for other proposers. Warn only.
267
+ const networkLimit = computeNetworkTxGasLimits({
268
+ maxBlocksPerCheckpoint,
269
+ manaCheckpointBudget: this.l1Constants.rollupManaLimit,
270
+ });
271
+ if (config.maxDABlockGas !== undefined && config.maxDABlockGas < networkLimit.daGas) {
272
+ this.log.warn(
273
+ `Sequencer maxDABlockGas (${config.maxDABlockGas}) is below the network DA admission limit ` +
274
+ `(${networkLimit.daGas}): txs declaring more DA gas are admitted over RPC/gossip but will be skipped ` +
275
+ `by this proposer's own blocks and left in the pool for other proposers.`,
276
+ { maxDABlockGas: config.maxDABlockGas, networkDaGas: networkLimit.daGas, maxBlocksPerCheckpoint },
277
+ );
278
+ }
279
+ if (config.maxL2BlockGas !== undefined && config.maxL2BlockGas < networkLimit.l2Gas) {
280
+ this.log.warn(
281
+ `Sequencer maxL2BlockGas (${config.maxL2BlockGas}) is below the network L2 admission limit ` +
282
+ `(${networkLimit.l2Gas}): txs declaring more L2 gas are admitted over RPC/gossip but will be skipped ` +
283
+ `by this proposer's own blocks and left in the pool for other proposers.`,
284
+ { maxL2BlockGas: config.maxL2BlockGas, networkL2Gas: networkLimit.l2Gas, maxBlocksPerCheckpoint },
285
+ );
286
+ }
287
+ }
288
+
289
+ /** Initializes the sequencer (precomputes tables). Takes about 3s. */
290
+ public init() {
291
+ getKzg();
292
+ }
293
+
294
+ /**
295
+ * Starts (or restarts) the sequencer and moves it to the IDLE state. Idempotent: a start while already
296
+ * running is a no-op, so it never orphans the previous poll loop. A start while STOPPING throws, since the
297
+ * in-flight stop would mark the fresh loop's state STOPPED and orphan it — silently doing nothing would
298
+ * leave the caller believing the sequencer is running when it is on its way to STOPPED. Safe to call after
299
+ * a previous {@link stop} has resolved; the caller must also restart the publishers (see
300
+ * {@link SequencerClient.start}) so L1 publishing is re-enabled.
301
+ */
302
+ public start() {
303
+ if (this.state === SequencerState.STOPPING) {
304
+ throw new Error('Cannot start sequencer while it is stopping');
305
+ }
306
+ if (this.runningPromise?.isRunning()) {
307
+ this.log.warn('Attempted to start sequencer that is already running');
308
+ return;
309
+ }
310
+ this.runningPromise = new RunningPromise(
311
+ this.safeWork.bind(this),
312
+ this.log,
313
+ this.config.sequencerPollingIntervalMS,
314
+ );
315
+ this.setState(SequencerState.IDLE, undefined, { force: true });
316
+ this.runningPromise.start();
317
+ this.log.info('Started sequencer');
318
+ }
319
+
320
+ /** Triggers an immediate run of the sequencer, bypassing the polling interval. */
321
+ public trigger() {
322
+ return this.runningPromise?.trigger();
323
+ }
324
+
325
+ /**
326
+ * Stops the sequencer from building blocks and moves it to STOPPED state, interrupting the in-flight
327
+ * work() iteration and its pending L1 submissions for a fast shutdown, then draining before returning.
328
+ * Idempotent: a second call while already stopped or stopping is a no-op. Lifecycle calls are expected
329
+ * to be serialized by the caller. For a restartable pause that lets in-flight work finish untouched
330
+ * (e.g. around a test clock warp), use {@link pause} instead.
331
+ */
332
+ public async stop(): Promise<void> {
333
+ if (this.state === SequencerState.STOPPED || this.state === SequencerState.STOPPING) {
334
+ this.log.debug(`Sequencer already ${this.state.toLowerCase()}, ignoring stop`);
335
+ return;
336
+ }
337
+ this.log.info(`Stopping sequencer`);
338
+ this.setState(SequencerState.STOPPING, undefined, { force: true });
339
+ this.lastCheckpointProposalJob?.interrupt();
340
+ await this.publisherFactory.stopAll();
341
+ // Stop the poll loop and await the in-flight work() iteration. work() registers its fire-and-forget
342
+ // requests synchronously before returning, so once the loop has stopped, pendingRequests holds every
343
+ // request that will ever exist. Interrupting any earlier could miss a request registered by the last
344
+ // in-flight iteration.
345
+ await this.runningPromise?.stop();
346
+ this.pendingRequests.interruptRequests();
347
+ await this.pendingRequests.awaitRequests();
348
+ this.setState(SequencerState.STOPPED, undefined, { force: true });
349
+ this.log.info('Stopped sequencer');
350
+ }
351
+
352
+ /**
353
+ * Gracefully pauses block production so the sequencer can later be resumed with {@link start}: halts the
354
+ * poll loop and waits for the in-flight work() iteration and every pending L1 submission / fallback send
355
+ * to finish, without interrupting them. No interrupt lands mid-build, so no spurious checkpoint-error is
356
+ * emitted and no enqueued checkpoint is dropped. Deliberately does not stop inner services (validator/HA
357
+ * signer, publishers), so the slashing-protection store stays open and the sequencer stays restartable.
358
+ * Used by tests that pause sequencers around an L1 clock warp. Idempotent.
359
+ */
360
+ public async pause(): Promise<void> {
361
+ if (!this.runningPromise?.isRunning()) {
362
+ this.log.debug('Sequencer not running, ignoring pause');
363
+ return;
364
+ }
365
+ this.log.info('Pausing sequencer');
366
+ // Halt the poll loop and let the in-flight iteration finish naturally — no interrupt, and no STOPPING
367
+ // state, since entering STOPPING would make the iteration's own setState calls throw and fail it.
368
+ // work() registers its fire-and-forget requests synchronously before returning, so once the loop has
369
+ // stopped pendingRequests holds every request that will ever exist; awaiting it lets them all finish.
370
+ await this.runningPromise.stop();
371
+ await this.pendingRequests.awaitRequests();
372
+ this.log.info('Paused sequencer');
373
+ }
374
+
375
+ /** Main sequencer loop with a try/catch */
376
+ protected async safeWork() {
377
+ try {
378
+ await this.work();
379
+ } catch (err) {
380
+ this.emit('checkpoint-error', { error: err as Error });
381
+ throw err;
382
+ } finally {
383
+ this.setState(SequencerState.IDLE, undefined);
384
+ }
385
+ }
386
+
387
+ /** Returns the current state of the sequencer. */
388
+ public status() {
389
+ return { state: this.state };
390
+ }
391
+
392
+ /**
393
+ * Main sequencer loop:
394
+ * - Checks if we are up to date
395
+ * - If we are and we are the sequencer, collect txs and build blocks
396
+ * - Build multiple blocks per slot when configured
397
+ * - Collect attestations for the final block
398
+ * - Submit checkpoint
399
+ */
400
+ @trackSpan('Sequencer.work')
401
+ protected async work() {
402
+ this.setState(SequencerState.SYNCHRONIZING, undefined);
403
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
404
+
405
+ // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
406
+ const checkpointProposalJob = await this.prepareCheckpointProposal(
407
+ slot,
408
+ targetSlot,
409
+ epoch,
410
+ targetEpoch,
411
+ ts,
412
+ nowSeconds,
413
+ );
414
+ if (!checkpointProposalJob) {
415
+ return;
416
+ }
417
+
418
+ // Track the job so we can await its pending L1 submission during shutdown
419
+ this.lastCheckpointProposalJob = checkpointProposalJob;
420
+
421
+ // Execute the checkpoint proposal job
422
+ const checkpoint = await checkpointProposalJob.execute();
423
+
424
+ // Update last checkpoint proposed (currently unused)
425
+ if (checkpoint) {
426
+ this.lastCheckpointProposed = checkpoint;
427
+ }
428
+
429
+ // Log fee strategy comparison if on fisherman (uses target epoch since we mirror the proposer's perspective)
430
+ if (
431
+ this.config.fishermanMode &&
432
+ (this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)
433
+ ) {
434
+ this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
435
+ this.lastEpochForStrategyComparison = targetEpoch;
436
+ }
437
+
438
+ return checkpoint;
439
+ }
440
+
441
+ /** Returns slot and target slot from a single clock snapshot. */
442
+ protected getSlotContextInNextL1Slot(): SequencerSlotContext {
443
+ const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
444
+ const targetSlot = SlotNumber(slot + PROPOSER_PIPELINING_SLOT_OFFSET);
445
+ return { slot, targetSlot, epoch, targetEpoch: getEpochAtSlot(targetSlot, this.l1Constants), ts, nowSeconds };
446
+ }
447
+
448
+ /**
449
+ * Prepares the checkpoint proposal by performing all necessary checks and setup.
450
+ * This is the initial step in the main loop.
451
+ * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
452
+ */
453
+ @trackSpan('Sequencer.prepareCheckpointProposal')
454
+ protected async prepareCheckpointProposal(
455
+ slot: SlotNumber,
456
+ targetSlot: SlotNumber,
457
+ epoch: EpochNumber,
458
+ targetEpoch: EpochNumber,
459
+ ts: bigint,
460
+ nowSeconds: bigint,
461
+ ): Promise<CheckpointProposalJob | undefined> {
462
+ // Check we have not already processed this target slot (cheapest check).
463
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot) {
464
+ this.log.trace(`Target slot ${targetSlot} has already been processed`);
465
+ return undefined;
466
+ }
467
+
468
+ // But if we have already proposed for this slot, then we definitely have to skip it, automining or not
469
+ if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= targetSlot) {
470
+ this.log.trace(
471
+ `Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`,
472
+ );
473
+ return undefined;
474
+ }
475
+
476
+ // Test-only: skip proposing for explicitly paused slots. Attestation paths run in the validator
477
+ // client and are not gated by this hook, so paused proposers still attest to others' proposals.
478
+ if (this.config.pauseProposingForSlots?.some(s => s === targetSlot)) {
479
+ this.log.warn(`Skipping proposal for paused slot ${targetSlot} (test-only pauseProposingForSlots hook)`, {
480
+ targetSlot,
481
+ });
482
+ return undefined;
483
+ }
484
+
485
+ // Cheap proposer check first: most nodes are not the proposer for most slots, so gate the
486
+ // expensive multi-subsystem checkSync (and the rest of the build path) behind it. Computed once
487
+ // here and reused for the escape-hatch voting path below. No setState/timing gate on this path:
488
+ // the build-start deadline gate runs only on the proposer build path after a successful checkSync.
489
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
490
+
491
+ // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
492
+ // Still perform governance/slashing voting (as proposer) once per slot.
493
+ // When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
494
+ const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
495
+
496
+ if (isEscapeHatchOpen) {
497
+ if (canPropose) {
498
+ await this.tryVoteWhenEscapeHatchOpen({ slot, targetSlot, proposer });
499
+ } else {
500
+ this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
501
+ slot,
502
+ epoch,
503
+ proposer,
504
+ });
505
+ }
506
+ return undefined;
507
+ }
508
+
509
+ // If we are not the proposer, check whether we should invalidate an invalid pending chain (a
510
+ // liveness backstop) and bail before any sync work or build-timing gate. This reads only the
511
+ // archiver's pending-chain validation status, which is authoritative on its own, instead of
512
+ // running the full sync check. Wrapped in try/catch because this leaner path skips the broader
513
+ // proposed-checkpoint/tip coherence screen that checkSync applied, so transient archiver
514
+ // incoherence surfaces as a quiet skip rather than a work-loop error.
515
+ if (!canPropose) {
516
+ try {
517
+ const pendingChainValidationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
518
+ await this.considerInvalidatingCheckpoint(pendingChainValidationStatus, slot);
519
+ } catch (err) {
520
+ this.log.warn(`Failed to consider invalidating checkpoint`, { err, slot, targetSlot });
521
+ }
522
+ return undefined;
523
+ }
524
+
525
+ // Explicit build-loop entry gate: if we are past the latest useful block-building start for the
526
+ // target slot, abandon building for this slot. The proposer prioritizes the ideal L1-publish path
527
+ // and does not plan around the late consensus-handoff path. This is the proposer build path's
528
+ // timing gate; it runs only after we know we are the synced proposer, so non-proposer invalidation
529
+ // and escape-hatch voting (which returned above) are never gated by build timing. Vote-only paths
530
+ // still run when block building is abandoned.
531
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
532
+ const nowForStartGate = this.dateProvider.now() / 1000;
533
+ if (nowForStartGate > startDeadline) {
534
+ this.log.debug(`Past start deadline for slot ${targetSlot}, abandoning block building`, {
535
+ targetSlot,
536
+ nowForStartGate,
537
+ startDeadline,
538
+ });
539
+ // Mark the slot as attempted so a deadline abort is not retried within the same slot. Vote-only actions
540
+ // still need to run because sync can succeed even when it is too late to start building a checkpoint.
541
+ await this.tryVoteAndPruneWhenCannotBuild({ slot, targetSlot });
542
+ this.lastSlotForCheckpointProposalJob = targetSlot;
543
+ return undefined;
544
+ }
545
+
546
+ // A proposal that cannot reach the committee is worse than not proposing: the slot is burned, and a
547
+ // node holding enough committee seats to reach quorum on its own would publish a checkpoint whose tx
548
+ // data was never gossiped to anyone, which is indistinguishable from data withholding. Skip building
549
+ // while peerless, but keep the vote/prune duties below. Only applies when p2p is enabled: setups that
550
+ // disable it (sandbox, single node, automine) legitimately propose with no peers.
551
+ const connectivity = await this.p2pClient.getP2PConnectivity();
552
+ const minPeersToPropose = this.config.minPeersToPropose;
553
+ if (connectivity.enabled && connectivity.connectedPeers < minPeersToPropose) {
554
+ this.log.warn(`Skipping checkpoint proposal for slot ${targetSlot} since we have too few connected peers`, {
555
+ targetSlot,
556
+ connectedPeers: connectivity.connectedPeers,
557
+ minPeersToPropose,
558
+ });
559
+ this.metrics.recordCheckpointPrecheckFailed('no_peers');
560
+ // Mark the slot as attempted so the gate is not re-evaluated on every tick within the slot. Vote-only
561
+ // actions still run: L1 duties (governance/slashing votes, prune) do not depend on gossip.
562
+ await this.tryVoteAndPruneWhenCannotBuild({ slot, targetSlot });
563
+ this.lastSlotForCheckpointProposalJob = targetSlot;
564
+ return undefined;
565
+ }
566
+
567
+ // We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
568
+ // Now run the full sync check before building.
569
+ const syncedTo = await this.checkSync({ ts, slot });
570
+ if (!syncedTo) {
571
+ return undefined;
572
+ }
573
+
574
+ // Next checkpoint follows from the last synced one
575
+ const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
576
+
577
+ const logCtx = {
578
+ nowSeconds,
579
+ syncedToL2Slot: syncedTo.syncedL2Slot,
580
+ slot,
581
+ targetSlot,
582
+ slotTs: ts,
583
+ checkpointNumber,
584
+ isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex'),
585
+ };
586
+
587
+ // We are the synced proposer within the build window; enter the proposer-check state and build.
588
+ this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
589
+
590
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
591
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
592
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
593
+ if (checkpointNumber > confirmedCkpt + 2) {
594
+ this.log.verbose(
595
+ `Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`,
596
+ );
597
+ return undefined;
598
+ }
599
+
600
+ // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
601
+ if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
602
+ this.log.warn(
603
+ `Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`,
604
+ { ...logCtx, block: syncedTo.blockData.header.toInspect() },
605
+ );
606
+ this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
607
+ return undefined;
608
+ }
609
+
610
+ // We now need to get ourselves a publisher.
611
+ // The returned attestor will be the one we provided if we provided one.
612
+ // Otherwise it will be a valid attestor for the returned publisher.
613
+ // In fisherman mode, pass undefined to use the fisherman's own keystore instead of the actual proposer's
614
+ const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
615
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
616
+ this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
617
+
618
+ // Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
619
+ // Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
620
+ // will invalidate the currently invalid checkpoint on L1.
621
+ const invalidateCheckpoint =
622
+ syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid
623
+ ? undefined
624
+ : await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
625
+
626
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
627
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
628
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
629
+ let archiveForCheck = syncedTo.archive;
630
+
631
+ if (syncedTo.hasProposedCheckpoint) {
632
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
633
+ this.log.verbose(
634
+ `Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`,
635
+ { targetSlot, parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1) },
636
+ );
637
+ // Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
638
+ // own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
639
+ // view and can transiently diverge from the proposed parent (e.g. before the proposed
640
+ // parent's blocks have been applied locally); diverging here would cause the canProposeAt
641
+ // override to set archives[pending] to one value while we present another for comparison.
642
+ archiveForCheck = syncedTo.proposedCheckpointData!.archive.root;
643
+ } else if (invalidateCheckpoint) {
644
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
645
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
646
+ archiveForCheck = invalidateCheckpoint.lastArchive;
647
+ this.metrics.recordPipelineDepth(0);
648
+ } else {
649
+ this.metrics.recordPipelineDepth(0);
650
+ }
651
+
652
+ // Build the simulation plan: pending/proven override from pipelining or invalidation (or the
653
+ // current snapshot when neither applies, to short-circuit any pending prune in simulation),
654
+ // plus the parent checkpoint cell and fee header when pipelining.
655
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
656
+ checkpointNumber,
657
+ proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
658
+ invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
659
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
660
+ rollup: this.rollupContract,
661
+ signatureContext: this.signatureContext,
662
+ log: this.log,
663
+ });
664
+
665
+ // The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
666
+ // so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
667
+ // simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
668
+ // actually fire at the target slot without it — so observers can spot "we are building
669
+ // optimistically across a pruning boundary" in the logs.
670
+ const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
671
+ if (provenOverride !== undefined && (await this.l2BlockSource.isPruneDueAtSlot(targetSlot))) {
672
+ this.log.warn(
673
+ `Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`,
674
+ { checkpointNumber, slot, targetSlot, provenOverride },
675
+ );
676
+ }
677
+
678
+ this.emit('preparing-checkpoint', {
679
+ targetSlot,
680
+ checkpointNumber,
681
+ hadProposedParent: syncedTo.hasProposedCheckpoint,
682
+ provenOverride,
683
+ simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending,
684
+ });
685
+
686
+ const canProposeCheck = await publisher.canProposeAt(
687
+ archiveForCheck,
688
+ proposer ?? EthAddress.ZERO,
689
+ simulationOverridesPlan,
690
+ );
691
+
692
+ const proposeContext = {
693
+ hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
694
+ proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
695
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
696
+ isInvalidating: !!invalidateCheckpoint,
697
+ invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
698
+ archiveForCheck: archiveForCheck.toString(),
699
+ overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
700
+ overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
701
+ overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader,
702
+ };
703
+
704
+ if (canProposeCheck === undefined) {
705
+ this.log.warn(
706
+ `Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`,
707
+ { ...logCtx, ...proposeContext },
708
+ );
709
+ this.emit('proposer-rollup-check-failed', { reason: 'Rollup contract check failed', slot });
710
+ this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
711
+ return undefined;
712
+ }
713
+
714
+ if (canProposeCheck.slot !== targetSlot) {
715
+ this.log.warn(
716
+ `Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${targetSlot} but got ${canProposeCheck.slot}.`,
717
+ { ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: targetSlot },
718
+ );
719
+ this.emit('proposer-rollup-check-failed', { reason: 'Slot mismatch', slot });
720
+ this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
721
+ return undefined;
722
+ }
723
+
724
+ if (canProposeCheck.checkpointNumber !== checkpointNumber) {
725
+ this.log.warn(
726
+ `Cannot propose due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected checkpoint ${checkpointNumber} but got ${canProposeCheck.checkpointNumber}.`,
727
+ { ...logCtx, ...proposeContext, rollup: canProposeCheck, expectedSlot: slot },
728
+ );
729
+ this.emit('proposer-rollup-check-failed', { reason: 'Block mismatch', slot });
730
+ this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
731
+ return undefined;
732
+ }
733
+
734
+ this.lastSlotForCheckpointProposalJob = targetSlot;
735
+
736
+ await this.p2pClient.prepareForSlot(targetSlot);
737
+ this.log.info(
738
+ `Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`,
739
+ {
740
+ ...logCtx,
741
+ ...proposeContext,
742
+ proposer,
743
+ },
744
+ );
745
+
746
+ // Create and return the checkpoint proposal job
747
+ return this.createCheckpointProposalJob(
748
+ targetSlot,
749
+ targetEpoch,
750
+ checkpointNumber,
751
+ syncedTo.blockNumber,
752
+ syncedTo.checkpointedCheckpointNumber,
753
+ proposer,
754
+ publisher,
755
+ attestorAddress,
756
+ invalidateCheckpoint,
757
+ syncedTo.proposedCheckpointData,
758
+ );
759
+ }
760
+
761
+ protected createCheckpointProposalJob(
762
+ targetSlot: SlotNumber,
763
+ targetEpoch: EpochNumber,
764
+ checkpointNumber: CheckpointNumber,
765
+ syncedToBlockNumber: BlockNumber,
766
+ checkpointedCheckpointNumber: CheckpointNumber,
767
+ proposer: EthAddress | undefined,
768
+ publisher: SequencerPublisher,
769
+ attestorAddress: EthAddress,
770
+ invalidateCheckpoint: InvalidateCheckpointRequest | undefined,
771
+ proposedCheckpointData?: ProposedCheckpointData,
772
+ ): CheckpointProposalJob {
773
+ return new CheckpointProposalJob(
774
+ targetSlot,
775
+ targetEpoch,
776
+ checkpointNumber,
777
+ syncedToBlockNumber,
778
+ checkpointedCheckpointNumber,
779
+ proposer,
780
+ publisher,
781
+ attestorAddress,
782
+ invalidateCheckpoint,
783
+ this.validatorClient,
784
+ this.globalsBuilder,
785
+ this.p2pClient,
786
+ this.worldState,
787
+ this.l1ToL2MessageSource,
788
+ this.l2BlockSource,
789
+ this.checkpointsBuilder,
790
+ this.l2BlockSource,
791
+ this.l1Constants,
792
+ this.signatureContext,
793
+ this.config,
794
+ this.timetable,
795
+ this.slasherClient,
796
+ this.epochCache,
797
+ this.dateProvider,
798
+ this.metrics,
799
+ this.checkpointProposalJobMetrics.createRecorder(),
800
+ this,
801
+ this.pendingRequests,
802
+ this.setState.bind(this),
803
+ this.tracer,
804
+ this.log.getBindings(),
805
+ proposedCheckpointData,
806
+ );
807
+ }
808
+
809
+ /**
810
+ * Returns the current sequencer state.
811
+ */
812
+ public getState(): SequencerState {
813
+ return this.state;
814
+ }
815
+
816
+ /**
817
+ * Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
818
+ * records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
819
+ * @param proposedState - The new state to transition to.
820
+ * @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
821
+ * and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
822
+ * @param force - Whether to force the transition even if the sequencer is stopped.
823
+ */
824
+ protected setState(
825
+ proposedState: SequencerState,
826
+ slotNumber: SlotNumber | undefined,
827
+ opts: { force?: boolean } = {},
828
+ ): void {
829
+ if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
830
+ this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
831
+ throw new SequencerInterruptedError();
832
+ }
833
+ if (this.state === SequencerState.STOPPED && !opts.force) {
834
+ this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
835
+ return;
836
+ }
837
+ const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
838
+
839
+ const oldState = this.state;
840
+ const oldStateSlotNumber = this.stateSlotNumber;
841
+ const stateChanged = proposedState !== oldState;
842
+ // Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
843
+ // calls, read from the date provider so it tracks simulated time under a test/manual clock.
844
+ const transitionAtMs = this.dateProvider.now();
845
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
846
+
847
+ const boringStates = [SequencerState.IDLE, SequencerState.SYNCHRONIZING];
848
+ const logLevel =
849
+ boringStates.includes(proposedState) && boringStates.includes(oldState) ? ('trace' as const) : ('debug' as const);
850
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
851
+ oldState,
852
+ newState: proposedState,
853
+ slotNumber,
854
+ stateSlotNumber: oldStateSlotNumber,
855
+ secondsIntoBuildFrame,
856
+ ...(stateChanged && { stateDurationMs: Math.ceil(stateDurationMs) }),
857
+ });
858
+
859
+ this.emit('state-changed', {
860
+ oldState,
861
+ newState: proposedState,
862
+ secondsIntoBuildFrame,
863
+ targetSlot: slotNumber,
864
+ });
865
+ if (stateChanged) {
866
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
867
+ this.stateEnteredAtMs = transitionAtMs;
868
+ this.stateSlotNumber = slotNumber;
869
+ }
870
+ this.state = proposedState;
871
+ }
872
+
873
+ /**
874
+ * Returns whether all dependencies have caught up.
875
+ * We don't check against the previous block submitted since it may have been reorg'd out.
876
+ */
877
+ protected async checkSync(args: { ts: bigint; slot: SlotNumber }): Promise<SequencerSyncCheckResult | undefined> {
878
+ // Check that the archiver has fully synced the L2 slot before the one we want to propose in.
879
+ // The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
880
+ // See getSyncedL2SlotNumber for how missed L1 blocks are handled.
881
+ const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
882
+ const { slot } = args;
883
+ if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
884
+ this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
885
+ slot,
886
+ syncedL2Slot,
887
+ });
888
+ return undefined;
889
+ }
890
+
891
+ const syncedBlocks = await Promise.all([
892
+ this.worldState.status().then(({ syncSummary }) => ({
893
+ number: syncSummary.latestBlockNumber,
894
+ hash: syncSummary.latestBlockHash,
895
+ })),
896
+ this.l2BlockSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
897
+ this.p2pClient.getStatus().then(p2p => p2p.syncedToL2Block),
898
+ this.l1ToL2MessageSource.getL2Tips().then(t => ({ proposed: t.proposed, checkpointed: t.checkpointed })),
899
+ this.l2BlockSource.getPendingChainValidationStatus(),
900
+ this.l2BlockSource.getProposedCheckpointData(),
901
+ ] as const);
902
+
903
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] =
904
+ syncedBlocks;
905
+
906
+ const result =
907
+ worldState.hash === l2Tips.proposed.hash &&
908
+ p2p.hash === l2Tips.proposed.hash &&
909
+ l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash &&
910
+ l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash &&
911
+ l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
912
+
913
+ if (!result) {
914
+ this.log.debug(`Sequencer sync check failed`, {
915
+ worldState,
916
+ l2BlockSource: l2Tips.proposed,
917
+ p2p,
918
+ l1ToL2MessageSourceTips,
919
+ });
920
+ return undefined;
921
+ }
922
+
923
+ const blockNumber = worldState.number;
924
+ const blockData = await this.l2BlockSource.getBlockData({ number: blockNumber });
925
+ if (!blockData) {
926
+ this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
927
+ blockNumber,
928
+ l2Tips,
929
+ syncedL2Slot,
930
+ ...args,
931
+ });
932
+ return undefined;
933
+ }
934
+
935
+ // Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
936
+ // proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
937
+ // our world-state tip past the checkpointed tip — while the proposing node never published the
938
+ // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
939
+ // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
940
+ // once their build slot ends; this guard is the correctness barrier during the grace window before.
941
+ // `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
942
+ // the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
943
+ // on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
944
+ if (
945
+ blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number &&
946
+ proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber
947
+ ) {
948
+ const logCtx = {
949
+ blockCheckpointNumber: blockData.checkpointNumber,
950
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
951
+ proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
952
+ blockNumber: blockData.header.getBlockNumber(),
953
+ blockSlot: blockData.header.getSlot(),
954
+ syncedL2Slot,
955
+ ...args,
956
+ };
957
+
958
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
959
+ return undefined;
960
+ }
961
+
962
+ const hasProposedCheckpoint = proposedCheckpointData !== undefined;
963
+
964
+ // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
965
+ // The checkpoint number to build is derived as blockData.checkpointNumber + 1
966
+ if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
967
+ this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
968
+ proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
969
+ blockCheckpointNumber: blockData.checkpointNumber,
970
+ syncedL2Slot,
971
+ ...args,
972
+ });
973
+ return undefined;
974
+ }
975
+
976
+ return {
977
+ blockData,
978
+ blockNumber: blockData.header.getBlockNumber(),
979
+ checkpointNumber: blockData.checkpointNumber,
980
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
981
+ archive: blockData.archive.root,
982
+ hasProposedCheckpoint,
983
+ proposedCheckpointData,
984
+ syncedL2Slot,
985
+ pendingChainValidationStatus,
986
+ };
987
+ }
988
+
989
+ /**
990
+ * Checks if we are the proposer for the next slot.
991
+ * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
992
+ */
993
+ protected async checkCanPropose(targetSlot: SlotNumber): Promise<[boolean, EthAddress | undefined]> {
994
+ let proposer: EthAddress | undefined;
995
+
996
+ try {
997
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
998
+ } catch (e) {
999
+ if (e instanceof NoCommitteeError) {
1000
+ const targetEpoch = getEpochAtSlot(targetSlot, this.l1Constants);
1001
+ if (this.lastEpochForNoCommitteeLog !== targetEpoch) {
1002
+ this.lastEpochForNoCommitteeLog = targetEpoch;
1003
+ await logMissingCommittee(targetSlot, targetEpoch, {
1004
+ epochCache: this.epochCache,
1005
+ rollupContract: this.rollupContract,
1006
+ l2BlockSource: this.l2BlockSource,
1007
+ l1Constants: this.l1Constants,
1008
+ dateProvider: this.dateProvider,
1009
+ logger: this.log,
1010
+ });
1011
+ }
1012
+ return [false, undefined];
1013
+ }
1014
+ this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
1015
+ return [false, undefined];
1016
+ }
1017
+
1018
+ // If proposer is undefined, then the committee is empty and anyone may propose
1019
+ if (proposer === undefined) {
1020
+ return [true, undefined];
1021
+ }
1022
+ // In fisherman mode, just return the current proposer
1023
+ if (this.config.fishermanMode) {
1024
+ return [true, proposer];
1025
+ }
1026
+
1027
+ const validatorAddresses = this.validatorClient.getValidatorAddresses();
1028
+ const weAreProposer = validatorAddresses.some(addr => addr.equals(proposer));
1029
+
1030
+ if (!weAreProposer) {
1031
+ this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
1032
+ targetSlot,
1033
+ validatorAddresses,
1034
+ proposer,
1035
+ });
1036
+ return [false, proposer];
1037
+ }
1038
+
1039
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
1040
+ targetSlot,
1041
+ proposer,
1042
+ });
1043
+ return [true, proposer];
1044
+ }
1045
+
1046
+ /**
1047
+ * Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
1048
+ * block-building window. This allows the sequencer to participate in governance/slashing votes even when it
1049
+ * cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
1050
+ */
1051
+ @trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
1052
+ protected async tryVoteAndPruneWhenCannotBuild(args: { slot: SlotNumber; targetSlot: SlotNumber }): Promise<void> {
1053
+ const { slot, targetSlot } = args;
1054
+
1055
+ // Prevent duplicate attempts in the same slot
1056
+ if (this.lastSlotForFallbackAction === slot) {
1057
+ this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
1058
+ return;
1059
+ }
1060
+
1061
+ // Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
1062
+ // Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
1063
+ // build-start deadline can miss the whole fallback window when the target advances with the clock.
1064
+ const nowSeconds = this.dateProvider.now() / 1000;
1065
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
1066
+
1067
+ this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
1068
+ nowSeconds,
1069
+ startDeadline,
1070
+ });
1071
+
1072
+ // Check if we're a proposer or proposal is open
1073
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
1074
+ if (!canPropose) {
1075
+ this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, { slot, proposer });
1076
+ return;
1077
+ }
1078
+
1079
+ // Mark this slot as attempted
1080
+ this.lastSlotForFallbackAction = slot;
1081
+
1082
+ // Get a publisher for voting
1083
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
1084
+
1085
+ this.log.debug(`Attempting to vote despite sync failure at slot ${slot}`, {
1086
+ attestorAddress,
1087
+ slot,
1088
+ });
1089
+
1090
+ // Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
1091
+ const voter = new CheckpointVoter(
1092
+ targetSlot,
1093
+ publisher,
1094
+ attestorAddress,
1095
+ this.validatorClient,
1096
+ this.slasherClient,
1097
+ this.l1Constants,
1098
+ this.config,
1099
+ this.metrics,
1100
+ this.log,
1101
+ );
1102
+ const votesPromises = voter.enqueueVotes();
1103
+ const votes = await Promise.all(votesPromises);
1104
+
1105
+ // Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
1106
+ // recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
1107
+ const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
1108
+
1109
+ // Bail if nothing to do
1110
+ if (votes.every(p => !p) && !pruneEnqueued) {
1111
+ this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
1112
+ return;
1113
+ }
1114
+
1115
+ const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
1116
+ this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
1117
+ slot,
1118
+ pruneEnqueued,
1119
+ governanceVoteEnqueued: !!governanceVoteEnqueued,
1120
+ slashingVoteEnqueued: !!slashingVoteEnqueued,
1121
+ });
1122
+
1123
+ // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
1124
+ // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
1125
+ // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
1126
+ // work loop while waiting for the target slot to start, but track it so stop() can drain it.
1127
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1128
+ this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, { slot });
1129
+ });
1130
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
1131
+ }
1132
+
1133
+ private async tryEnqueuePruneIfPrunable(targetSlot: SlotNumber, publisher: SequencerPublisher): Promise<boolean> {
1134
+ try {
1135
+ return await publisher.enqueuePruneIfPrunable(targetSlot);
1136
+ } catch (err) {
1137
+ this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, { targetSlot });
1138
+ return false;
1139
+ }
1140
+ }
1141
+
1142
+ /**
1143
+ * Tries to vote on slashing actions and governance proposals when escape hatch is open.
1144
+ * This allows the sequencer to participate in voting without performing checkpoint proposal work.
1145
+ */
1146
+ @trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot }) => ({ [Attributes.SLOT_NUMBER]: slot }))
1147
+ protected async tryVoteWhenEscapeHatchOpen(args: {
1148
+ slot: SlotNumber;
1149
+ targetSlot: SlotNumber;
1150
+ proposer: EthAddress | undefined;
1151
+ }): Promise<void> {
1152
+ const { slot, targetSlot, proposer } = args;
1153
+
1154
+ // Prevent duplicate attempts in the same slot
1155
+ if (this.lastSlotForFallbackAction === slot) {
1156
+ this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
1157
+ return;
1158
+ }
1159
+
1160
+ // Mark this slot as attempted
1161
+ this.lastSlotForFallbackAction = slot;
1162
+
1163
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
1164
+
1165
+ this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
1166
+ slot,
1167
+ targetSlot,
1168
+ attestorAddress,
1169
+ });
1170
+
1171
+ // Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
1172
+ // Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
1173
+ // L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
1174
+ // sign for `targetSlot` and delay submission to the start of `targetSlot`.
1175
+ const voter = new CheckpointVoter(
1176
+ targetSlot,
1177
+ publisher,
1178
+ attestorAddress,
1179
+ this.validatorClient,
1180
+ this.slasherClient,
1181
+ this.l1Constants,
1182
+ this.config,
1183
+ this.metrics,
1184
+ this.log,
1185
+ );
1186
+
1187
+ const votesPromises = voter.enqueueVotes();
1188
+ const votes = await Promise.all(votesPromises);
1189
+
1190
+ if (votes.every(p => !p)) {
1191
+ this.log.debug(`No votes to enqueue for slot ${slot} (escape hatch open)`);
1192
+ return;
1193
+ }
1194
+
1195
+ this.log.info(`Voting in slot ${slot} (escape hatch open)`, { slot, targetSlot });
1196
+ // Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
1197
+ // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1198
+ // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1199
+ // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1200
+ // waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
1201
+ // stop() can drain it.
1202
+ const send = publisher.sendRequestsAt(targetSlot).catch(err => {
1203
+ this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, { slot, targetSlot });
1204
+ });
1205
+ this.pendingRequests.trackRequest(send, () => publisher.interrupt());
1206
+ }
1207
+
1208
+ /**
1209
+ * Considers invalidating a block if the pending chain is invalid. Depends on how long the invalid block
1210
+ * has been there without being invalidated and whether the sequencer is in the committee or not. We always
1211
+ * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
1212
+ * and if they fail, any sequencer will try as well.
1213
+ * @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
1214
+ * @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
1215
+ */
1216
+ protected async considerInvalidatingCheckpoint(
1217
+ pendingChainValidationStatus: ValidateCheckpointResult,
1218
+ currentSlot: SlotNumber,
1219
+ ): Promise<void> {
1220
+ if (pendingChainValidationStatus.valid) {
1221
+ return;
1222
+ }
1223
+
1224
+ const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1225
+
1226
+ // Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
1227
+ // The guard is keyed by (checkpoint, slot) — so a different invalid checkpoint surfacing later in
1228
+ // the same slot is not suppressed — and is set only after a request is successfully simulated below,
1229
+ // so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
1230
+ if (
1231
+ this.lastInvalidationAttempt?.slot === currentSlot &&
1232
+ this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber
1233
+ ) {
1234
+ this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
1235
+ currentSlot,
1236
+ invalidCheckpointNumber,
1237
+ });
1238
+ return;
1239
+ }
1240
+
1241
+ const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
1242
+ const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
1243
+ const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
1244
+
1245
+ const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } =
1246
+ this.config;
1247
+
1248
+ const logData = {
1249
+ invalidL1Timestamp: invalidCheckpointTimestamp,
1250
+ invalidCheckpoint: pendingChainValidationStatus.checkpoint,
1251
+ secondsBeforeInvalidatingBlockAsCommitteeMember,
1252
+ secondsBeforeInvalidatingBlockAsNonCommitteeMember,
1253
+ ourValidatorAddresses,
1254
+ currentSlot,
1255
+ };
1256
+
1257
+ const inCurrentCommittee = () =>
1258
+ this.epochCache
1259
+ .getCommittee(currentSlot)
1260
+ .then(c => c?.committee?.some(member => ourValidatorAddresses.some(addr => addr.equals(member))));
1261
+
1262
+ const invalidateAsCommitteeMember =
1263
+ secondsBeforeInvalidatingBlockAsCommitteeMember !== undefined &&
1264
+ secondsBeforeInvalidatingBlockAsCommitteeMember > 0 &&
1265
+ timeSinceChainInvalid > secondsBeforeInvalidatingBlockAsCommitteeMember &&
1266
+ (await inCurrentCommittee());
1267
+
1268
+ const invalidateAsNonCommitteeMember =
1269
+ secondsBeforeInvalidatingBlockAsNonCommitteeMember !== undefined &&
1270
+ secondsBeforeInvalidatingBlockAsNonCommitteeMember > 0 &&
1271
+ timeSinceChainInvalid > secondsBeforeInvalidatingBlockAsNonCommitteeMember;
1272
+
1273
+ if (!invalidateAsCommitteeMember && !invalidateAsNonCommitteeMember) {
1274
+ this.log.debug(`Not invalidating pending chain`, logData);
1275
+ return;
1276
+ }
1277
+
1278
+ let validatorToUse: EthAddress;
1279
+ if (invalidateAsCommitteeMember) {
1280
+ // When invalidating as a committee member, use first validator that's actually in the committee
1281
+ const { committee } = await this.epochCache.getCommittee(currentSlot);
1282
+ if (committee) {
1283
+ const committeeSet = new Set(committee.map(addr => addr.toString()));
1284
+ validatorToUse =
1285
+ ourValidatorAddresses.find(addr => committeeSet.has(addr.toString())) ?? ourValidatorAddresses[0];
1286
+ } else {
1287
+ validatorToUse = ourValidatorAddresses[0];
1288
+ }
1289
+ } else {
1290
+ // When invalidating as a non-committee member, use the first validator
1291
+ validatorToUse = ourValidatorAddresses[0];
1292
+ }
1293
+
1294
+ const { publisher } = await this.publisherFactory.create(validatorToUse);
1295
+
1296
+ const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(pendingChainValidationStatus);
1297
+ if (!invalidateCheckpoint) {
1298
+ this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
1299
+ return;
1300
+ }
1301
+
1302
+ // We produced a valid invalidation request; record it so further ticks within this slot skip the
1303
+ // committee lookup, simulation, and submission above for this same invalid checkpoint.
1304
+ this.lastInvalidationAttempt = { slot: currentSlot, checkpointNumber: invalidCheckpointNumber };
1305
+
1306
+ this.log.info(
1307
+ invalidateAsCommitteeMember
1308
+ ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member`
1309
+ : `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`,
1310
+ logData,
1311
+ );
1312
+
1313
+ publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
1314
+
1315
+ if (!this.config.fishermanMode) {
1316
+ await publisher.sendRequests();
1317
+ } else {
1318
+ this.log.info('Invalidating checkpoint in fisherman mode, clearing pending requests');
1319
+ publisher.clearPendingRequests();
1320
+ }
1321
+ }
1322
+
1323
+ private logStrategyComparison(epoch: EpochNumber, publisher: SequencerPublisher): void {
1324
+ const feeAnalyzer = publisher.getL1FeeAnalyzer();
1325
+ if (!feeAnalyzer) {
1326
+ return;
1327
+ }
1328
+
1329
+ const comparison = feeAnalyzer.getStrategyComparison();
1330
+ if (comparison.length === 0) {
1331
+ this.log.debug(`No strategy data available yet for epoch ${epoch}`);
1332
+ return;
1333
+ }
1334
+
1335
+ this.log.info(`L1 Fee Strategy Performance Report - End of Epoch ${epoch}`, {
1336
+ epoch: Number(epoch),
1337
+ totalAnalyses: comparison[0]?.totalAnalyses,
1338
+ strategies: comparison.map(s => ({
1339
+ id: s.strategyId,
1340
+ name: s.strategyName,
1341
+ inclusionRate: `${(s.inclusionRate * 100).toFixed(1)}%`,
1342
+ inclusionCount: `${s.inclusionCount}/${s.totalAnalyses}`,
1343
+ avgCostEth: s.avgEstimatedCostEth.toFixed(6),
1344
+ totalCostEth: s.totalEstimatedCostEth.toFixed(6),
1345
+ avgOverpaymentEth: s.avgOverpaymentEth.toFixed(6),
1346
+ totalOverpaymentEth: s.totalOverpaymentEth.toFixed(6),
1347
+ avgPriorityFeeDeltaGwei: s.avgPriorityFeeDeltaGwei.toFixed(2),
1348
+ })),
1349
+ });
1350
+ }
1351
+
1352
+ /**
1353
+ * Wall-clock seconds elapsed since the build-frame start of the given target slot
1354
+ * (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
1355
+ */
1356
+ private getSecondsIntoBuildFrame(targetSlot: SlotNumber): number {
1357
+ const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
1358
+ return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
1359
+ }
1360
+
1361
+ public get aztecSlotDuration() {
1362
+ return this.l1Constants.slotDuration;
1363
+ }
1364
+
1365
+ public get maxL2BlockGas(): number | undefined {
1366
+ return this.config.maxL2BlockGas;
1367
+ }
1368
+
1369
+ public getSlasherClient(): SlasherClientInterface | undefined {
1370
+ return this.slasherClient;
1371
+ }
1372
+
1373
+ public get tracer(): Tracer {
1374
+ return this.metrics.tracer;
1375
+ }
1376
+
1377
+ public getValidatorAddresses() {
1378
+ return this.validatorClient?.getValidatorAddresses();
1379
+ }
1380
+
1381
+ /** Updates the publisher factory's node keystore adapter after a keystore reload. */
1382
+ public updatePublisherNodeKeyStore(adapter: NodeKeystoreAdapter): void {
1383
+ this.publisherFactory.updateNodeKeyStore(adapter);
1384
+ }
1385
+
1386
+ public getConfig() {
1387
+ return this.config;
1388
+ }
1389
+ }
1390
+
1391
+ type SequencerSyncCheckResult = {
1392
+ blockData?: BlockData;
1393
+ checkpointNumber: CheckpointNumber;
1394
+ checkpointedCheckpointNumber: CheckpointNumber;
1395
+ blockNumber: BlockNumber;
1396
+ archive: Fr;
1397
+ hasProposedCheckpoint: boolean;
1398
+ proposedCheckpointData?: ProposedCheckpointData;
1399
+ syncedL2Slot: SlotNumber;
1400
+ pendingChainValidationStatus: ValidateCheckpointResult;
1401
+ };