@aztec/sequencer-client 0.0.1-commit.c2eed6949 → 0.0.1-commit.c52d6e7

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