@aztec/sequencer-client 0.0.1-commit.9ef841308 → 0.0.1-commit.a4600f49

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 (114) 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 +11 -4
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +55 -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 +97 -68
  42. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  43. package/dest/publisher/sequencer-publisher.js +603 -536
  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 +690 -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 +724 -212
  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/events.d.ts +61 -5
  63. package/dest/sequencer/events.d.ts.map +1 -1
  64. package/dest/sequencer/metrics.d.ts +9 -10
  65. package/dest/sequencer/metrics.d.ts.map +1 -1
  66. package/dest/sequencer/metrics.js +34 -20
  67. package/dest/sequencer/requests_tracker.d.ts +22 -0
  68. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  69. package/dest/sequencer/requests_tracker.js +33 -0
  70. package/dest/sequencer/sequencer.d.ts +155 -33
  71. package/dest/sequencer/sequencer.d.ts.map +1 -1
  72. package/dest/sequencer/sequencer.js +543 -158
  73. package/dest/sequencer/types.d.ts +2 -2
  74. package/dest/sequencer/types.d.ts.map +1 -1
  75. package/dest/test/index.d.ts +3 -3
  76. package/dest/test/index.d.ts.map +1 -1
  77. package/dest/test/utils.d.ts +15 -1
  78. package/dest/test/utils.d.ts.map +1 -1
  79. package/dest/test/utils.js +25 -7
  80. package/package.json +30 -28
  81. package/src/client/sequencer-client.ts +37 -27
  82. package/src/config.ts +64 -26
  83. package/src/global_variable_builder/README.md +44 -0
  84. package/src/global_variable_builder/fee_predictor.ts +182 -0
  85. package/src/global_variable_builder/fee_provider.ts +97 -0
  86. package/src/global_variable_builder/global_builder.ts +12 -80
  87. package/src/global_variable_builder/index.ts +2 -0
  88. package/src/publisher/config.ts +30 -7
  89. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  90. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +117 -8
  91. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +4 -3
  92. package/src/publisher/l1_tx_failed_store/index.ts +1 -1
  93. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  94. package/src/publisher/sequencer-publisher-factory.ts +0 -3
  95. package/src/publisher/sequencer-publisher.ts +702 -598
  96. package/src/publisher/write_json.ts +78 -0
  97. package/src/sequencer/README.md +162 -450
  98. package/src/sequencer/automine/README.md +60 -0
  99. package/src/sequencer/automine/automine_factory.ts +152 -0
  100. package/src/sequencer/automine/automine_sequencer.ts +796 -0
  101. package/src/sequencer/automine/index.ts +6 -0
  102. package/src/sequencer/checkpoint_proposal_job.ts +844 -241
  103. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  104. package/src/sequencer/events.ts +66 -5
  105. package/src/sequencer/metrics.ts +43 -24
  106. package/src/sequencer/requests_tracker.ts +43 -0
  107. package/src/sequencer/sequencer.ts +625 -175
  108. package/src/sequencer/types.ts +1 -1
  109. package/src/test/index.ts +2 -2
  110. package/src/test/utils.ts +61 -10
  111. package/dest/sequencer/timetable.d.ts +0 -88
  112. package/dest/sequencer/timetable.d.ts.map +0 -1
  113. package/dest/sequencer/timetable.js +0 -222
  114. package/src/sequencer/timetable.ts +0 -283
@@ -372,29 +372,31 @@ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
372
372
  }
373
373
  var _dec, _dec1, _dec2, _dec3, _initProto;
374
374
  import { getKzg } from '@aztec/blob-lib';
375
- import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
375
+ import { PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
376
376
  import { NoCommitteeError } from '@aztec/ethereum/contracts';
377
- import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
377
+ import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
378
378
  import { merge, omit, pick } from '@aztec/foundation/collection';
379
- import { Fr } from '@aztec/foundation/curves/bn254';
380
379
  import { EthAddress } from '@aztec/foundation/eth-address';
381
380
  import { createLogger } from '@aztec/foundation/log';
382
381
  import { RunningPromise } from '@aztec/foundation/running-promise';
383
- import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
382
+ import { buildCheckpointSimulationOverridesPlan } from '@aztec/stdlib/checkpoint';
383
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
384
+ import { MIN_PER_BLOCK_ALLOCATION_MULTIPLIER, MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER, computeNetworkTxGasLimits } from '@aztec/stdlib/gas';
384
385
  import { SequencerConfigSchema } from '@aztec/stdlib/interfaces/server';
385
386
  import { pickFromSchema } from '@aztec/stdlib/schemas';
386
- import { MerkleTreeId } from '@aztec/stdlib/trees';
387
+ import { buildProposerTimetable } from '@aztec/stdlib/timetable';
387
388
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
388
389
  import EventEmitter from 'node:events';
389
390
  import { DefaultSequencerConfig } from '../config.js';
390
391
  import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
392
+ import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
391
393
  import { CheckpointVoter } from './checkpoint_voter.js';
392
- import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
394
+ import { SequencerInterruptedError } from './errors.js';
393
395
  import { SequencerMetrics } from './metrics.js';
394
- import { SequencerTimetable } from './timetable.js';
396
+ import { RequestsTracker } from './requests_tracker.js';
395
397
  import { SequencerState } from './utils.js';
396
398
  export { SequencerState };
397
- _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpointProposal'), _dec2 = trackSpan('Seqeuencer.tryVoteWhenSyncFails', ({ slot })=>({
399
+ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpointProposal'), _dec2 = trackSpan('Sequencer.tryVoteAndPruneWhenCannotBuild', ({ slot })=>({
398
400
  [Attributes.SLOT_NUMBER]: slot
399
401
  })), _dec3 = trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot })=>({
400
402
  [Attributes.SLOT_NUMBER]: slot
@@ -437,7 +439,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
437
439
  [
438
440
  _dec2,
439
441
  2,
440
- "tryVoteWhenSyncFails"
442
+ "tryVoteAndPruneWhenCannotBuild"
441
443
  ],
442
444
  [
443
445
  _dec3,
@@ -448,40 +450,161 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
448
450
  }
449
451
  runningPromise;
450
452
  state;
453
+ stateSlotNumber;
454
+ /** Wall-clock time (ms, via the date provider) at which the current state was entered. */ stateEnteredAtMs;
451
455
  metrics;
452
- /** The last slot for which we attempted to perform our voting duties with degraded block production */ lastSlotForFallbackVote;
456
+ checkpointProposalJobMetrics;
457
+ stateLog;
458
+ /** The last slot for which we attempted to perform our fallback duties (votes and/or prune) with degraded block production */ lastSlotForFallbackAction;
459
+ /** The (checkpoint, slot) of the last invalidation request we successfully simulated, to prevent
460
+ * re-simulating and re-submitting the same invalidation across the many ticks within a single slot. */ lastInvalidationAttempt;
453
461
  /** The last slot for which we logged "no committee" warning, to avoid spam */ lastSlotForNoCommitteeWarning;
454
462
  /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */ lastSlotForCheckpointProposalJob;
455
463
  /** Last successful checkpoint proposed */ lastCheckpointProposed;
456
464
  /** The last epoch for which we logged strategy comparison in fisherman mode. */ lastEpochForStrategyComparison;
457
- /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */ timetable;
465
+ /** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */ lastCheckpointProposalJob;
466
+ /**
467
+ * In-flight fire-and-forget requests that {@link stop} interrupts and drains, and {@link pause} awaits
468
+ * untouched: the checkpoint proposal jobs' backgrounded L1 submissions (each job is handed this shared
469
+ * tracker) plus the sequencer's own fallback submissions (votes/prune when we cannot build, or
470
+ * escape-hatch votes). Each fallback send is gated by its wrapper publisher's interruptible target-slot
471
+ * sleep; the tracked interrupt wakes that sleep so the send short-circuits without publishing. A wrapper
472
+ * is created for a single send and is never restarted, so once interrupted its sleeper can never publish
473
+ * a stale-slot tx, even after the pooled publishers are restarted by a later {@link start}.
474
+ */ pendingRequests;
475
+ /** Proposer schedule and block sub-slot timetable for the sequencer, rebuilt on every config update. */ timetable;
458
476
  /** Config for the sequencer */ config;
477
+ signatureContext;
459
478
  constructor(publisherFactory, validatorClient, globalsBuilder, p2pClient, worldState, slasherClient, l2BlockSource, l1ToL2MessageSource, checkpointsBuilder, l1Constants, dateProvider, epochCache, rollupContract, config, telemetry = getTelemetryClient(), log = createLogger('sequencer')){
460
- super(), this.publisherFactory = publisherFactory, this.validatorClient = validatorClient, this.globalsBuilder = globalsBuilder, this.p2pClient = p2pClient, this.worldState = worldState, this.slasherClient = slasherClient, this.l2BlockSource = l2BlockSource, this.l1ToL2MessageSource = l1ToL2MessageSource, this.checkpointsBuilder = checkpointsBuilder, this.l1Constants = l1Constants, this.dateProvider = dateProvider, this.epochCache = epochCache, this.rollupContract = rollupContract, this.telemetry = telemetry, this.log = log, this.state = (_initProto(this), SequencerState.STOPPED), this.config = DefaultSequencerConfig;
479
+ super(), this.publisherFactory = publisherFactory, this.validatorClient = validatorClient, this.globalsBuilder = globalsBuilder, this.p2pClient = p2pClient, this.worldState = worldState, this.slasherClient = slasherClient, this.l2BlockSource = l2BlockSource, this.l1ToL2MessageSource = l1ToL2MessageSource, this.checkpointsBuilder = checkpointsBuilder, this.l1Constants = l1Constants, this.dateProvider = dateProvider, this.epochCache = epochCache, this.rollupContract = rollupContract, this.telemetry = telemetry, this.log = log, this.state = (_initProto(this), SequencerState.STOPPED), this.pendingRequests = new RequestsTracker(), this.config = DefaultSequencerConfig;
480
+ this.stateLog = log.createChild('state');
481
+ this.stateEnteredAtMs = this.dateProvider.now();
461
482
  // Add [FISHERMAN] prefix to logger if in fisherman mode
462
483
  if (config.fishermanMode) {
463
484
  this.log = log.createChild('[FISHERMAN]');
464
485
  }
486
+ this.signatureContext = {
487
+ chainId: config.l1ChainId,
488
+ rollupAddress: config.rollupAddress
489
+ };
465
490
  this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
491
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
466
492
  this.updateConfig(config);
467
493
  }
468
- /** Updates sequencer config by the defined values and updates the timetable */ updateConfig(config) {
494
+ /**
495
+ * Updates sequencer config by the defined values and rebuilds the timetable.
496
+ *
497
+ * The merged config is validated against a candidate before being committed: {@link buildTimetable} may
498
+ * reject the candidate (invalid timing geometry, or per-block allocation multipliers below the network
499
+ * minimums). On rejection we leave `this.config` and `this.timetable` untouched and rethrow, so a bad update
500
+ * never leaves the sequencer running with a rejected config and a stale timetable.
501
+ */ updateConfig(config) {
469
502
  const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
503
+ const candidate = merge(this.config, filteredConfig);
504
+ let timetable;
505
+ try {
506
+ timetable = this.buildTimetable(candidate);
507
+ } catch (err) {
508
+ this.log.warn(`Rejecting sequencer config update: ${err.message}`, {
509
+ rejectedConfig: omit(filteredConfig, 'txPublicSetupAllowListExtend')
510
+ });
511
+ throw err;
512
+ }
513
+ this.config = candidate;
514
+ this.timetable = timetable;
470
515
  this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
471
- this.config = merge(this.config, filteredConfig);
472
- this.timetable = new SequencerTimetable({
473
- ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
474
- aztecSlotDuration: this.aztecSlotDuration,
475
- l1PublishingTime: this.l1PublishingTime,
476
- p2pPropagationTime: this.config.attestationPropagationTime,
477
- blockDurationMs: this.config.blockDurationMs,
478
- enforce: this.config.enforceTimeTable
479
- }, this.metrics, this.log);
516
+ }
517
+ /**
518
+ * Builds the proposer timetable from the given config and L1 constants via the shared
519
+ * {@link buildProposerTimetable} helper, so the sequencer derives the same blocks-per-checkpoint as the p2p
520
+ * layer and `getNodeInfo`. The fast local/e2e profile and budget clamping happen inside
521
+ * {@link ProposerTimetable}.
522
+ *
523
+ * Throws if the timing geometry is invalid or the per-block allocation multipliers are below the network
524
+ * minimums; callers must treat a throw as a rejected config and not commit it.
525
+ */ buildTimetable(config) {
526
+ const timetable = buildProposerTimetable(config, this.l1Constants);
527
+ const maxNumberOfBlocks = timetable.getMaxBlocksPerCheckpoint();
528
+ this.log.info(`Sequencer timetable initialized with ${maxNumberOfBlocks} blocks per slot`, {
529
+ aztecSlotDuration: timetable.aztecSlotDuration,
530
+ ethereumSlotDuration: timetable.ethereumSlotDuration,
531
+ blockDuration: timetable.blockDuration,
532
+ minBlockDuration: timetable.minBlockDuration,
533
+ p2pPropagationTime: timetable.p2pPropagationTime,
534
+ checkpointProposalPrepareTime: timetable.checkpointProposalPrepareTime,
535
+ maxNumberOfBlocks
536
+ });
537
+ this.assertConfigMeetsNetworkTxLimits(config, maxNumberOfBlocks);
538
+ return timetable;
539
+ }
540
+ /**
541
+ * Checks this node's configured per-block allocation against the network admission limit. A node
542
+ * advertises and admits txs up to the limit derived from the network-minimum multipliers (see
543
+ * {@link computeNetworkTxGasLimits}).
544
+ *
545
+ * Fails startup (and runtime config updates) only when the configured per-block allocation *multipliers*
546
+ * (`perBlockAllocationMultiplier` / `perBlockDAAllocationMultiplier`) are below the network minimums: such
547
+ * a node would accept txs over RPC/gossip that its builder can never pack into a block regardless of block
548
+ * size. Operators may configure a higher (more generous) multiplier, but not a lower one.
549
+ *
550
+ * When the multipliers meet the floor but an absolute per-block gas cap (`maxDABlockGas` / `maxL2BlockGas`)
551
+ * shrinks the builder's effective grant below the network limit, this is legitimate operator
552
+ * restrictiveness — the node simply builds smaller blocks and such txs stay in the pool for other
553
+ * proposers — so we only log a warning rather than failing startup. Restrictive tx-count caps
554
+ * (`maxTxsPerBlock` / `maxTxsPerCheckpoint`) can likewise make the builder skip admitted txs; they are
555
+ * intentionally not modeled here for the same reason.
556
+ */ assertConfigMeetsNetworkTxLimits(config, maxBlocksPerCheckpoint) {
557
+ // Mirror CheckpointBuilder.capLimitsByCheckpointBudgets: DA falls back to the general multiplier.
558
+ const l2Multiplier = config.perBlockAllocationMultiplier;
559
+ const daMultiplier = config.perBlockDAAllocationMultiplier ?? l2Multiplier;
560
+ // The allocation is monotonic in the multiplier, so a multiplier at or above the network minimum
561
+ // guarantees the builder grants at least the network admission limit. Checking the multipliers directly
562
+ // is sufficient (and strictly more conservative than modeling the resulting gas grant).
563
+ if (daMultiplier < MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER) {
564
+ throw new Error(`perBlockDAAllocationMultiplier (${daMultiplier}) is below the network minimum ` + `${MIN_PER_BLOCK_DA_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`);
565
+ }
566
+ if (l2Multiplier < MIN_PER_BLOCK_ALLOCATION_MULTIPLIER) {
567
+ throw new Error(`perBlockAllocationMultiplier (${l2Multiplier}) is below the network minimum ` + `${MIN_PER_BLOCK_ALLOCATION_MULTIPLIER}; the node would admit txs its own builder can never include.`);
568
+ }
569
+ // Absolute per-block gas caps below the network admission limit are legitimate operator restrictiveness:
570
+ // the node simply builds smaller blocks and such txs stay in the pool for other proposers. Warn only.
571
+ const networkLimit = computeNetworkTxGasLimits({
572
+ maxBlocksPerCheckpoint,
573
+ manaCheckpointBudget: this.l1Constants.rollupManaLimit
574
+ });
575
+ if (config.maxDABlockGas !== undefined && config.maxDABlockGas < networkLimit.daGas) {
576
+ this.log.warn(`Sequencer maxDABlockGas (${config.maxDABlockGas}) is below the network DA admission limit ` + `(${networkLimit.daGas}): txs declaring more DA gas are admitted over RPC/gossip but will be skipped ` + `by this proposer's own blocks and left in the pool for other proposers.`, {
577
+ maxDABlockGas: config.maxDABlockGas,
578
+ networkDaGas: networkLimit.daGas,
579
+ maxBlocksPerCheckpoint
580
+ });
581
+ }
582
+ if (config.maxL2BlockGas !== undefined && config.maxL2BlockGas < networkLimit.l2Gas) {
583
+ this.log.warn(`Sequencer maxL2BlockGas (${config.maxL2BlockGas}) is below the network L2 admission limit ` + `(${networkLimit.l2Gas}): txs declaring more L2 gas are admitted over RPC/gossip but will be skipped ` + `by this proposer's own blocks and left in the pool for other proposers.`, {
584
+ maxL2BlockGas: config.maxL2BlockGas,
585
+ networkL2Gas: networkLimit.l2Gas,
586
+ maxBlocksPerCheckpoint
587
+ });
588
+ }
480
589
  }
481
590
  /** Initializes the sequencer (precomputes tables). Takes about 3s. */ init() {
482
591
  getKzg();
483
592
  }
484
- /** Starts the sequencer and moves to IDLE state. */ start() {
593
+ /**
594
+ * Starts (or restarts) the sequencer and moves it to the IDLE state. Idempotent: a start while already
595
+ * running is a no-op, so it never orphans the previous poll loop. A start while STOPPING throws, since the
596
+ * in-flight stop would mark the fresh loop's state STOPPED and orphan it — silently doing nothing would
597
+ * leave the caller believing the sequencer is running when it is on its way to STOPPED. Safe to call after
598
+ * a previous {@link stop} has resolved; the caller must also restart the publishers (see
599
+ * {@link SequencerClient.start}) so L1 publishing is re-enabled.
600
+ */ start() {
601
+ if (this.state === SequencerState.STOPPING) {
602
+ throw new Error('Cannot start sequencer while it is stopping');
603
+ }
604
+ if (this.runningPromise?.isRunning()) {
605
+ this.log.warn('Attempted to start sequencer that is already running');
606
+ return;
607
+ }
485
608
  this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.config.sequencerPollingIntervalMS);
486
609
  this.setState(SequencerState.IDLE, undefined, {
487
610
  force: true
@@ -489,18 +612,59 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
489
612
  this.runningPromise.start();
490
613
  this.log.info('Started sequencer');
491
614
  }
492
- /** Stops the sequencer from building blocks and moves to STOPPED state. */ async stop() {
615
+ /** Triggers an immediate run of the sequencer, bypassing the polling interval. */ trigger() {
616
+ return this.runningPromise?.trigger();
617
+ }
618
+ /**
619
+ * Stops the sequencer from building blocks and moves it to STOPPED state, interrupting the in-flight
620
+ * work() iteration and its pending L1 submissions for a fast shutdown, then draining before returning.
621
+ * Idempotent: a second call while already stopped or stopping is a no-op. Lifecycle calls are expected
622
+ * to be serialized by the caller. For a restartable pause that lets in-flight work finish untouched
623
+ * (e.g. around a test clock warp), use {@link pause} instead.
624
+ */ async stop() {
625
+ if (this.state === SequencerState.STOPPED || this.state === SequencerState.STOPPING) {
626
+ this.log.debug(`Sequencer already ${this.state.toLowerCase()}, ignoring stop`);
627
+ return;
628
+ }
493
629
  this.log.info(`Stopping sequencer`);
494
630
  this.setState(SequencerState.STOPPING, undefined, {
495
631
  force: true
496
632
  });
633
+ this.lastCheckpointProposalJob?.interrupt();
497
634
  await this.publisherFactory.stopAll();
635
+ // Stop the poll loop and await the in-flight work() iteration. work() registers its fire-and-forget
636
+ // requests synchronously before returning, so once the loop has stopped, pendingRequests holds every
637
+ // request that will ever exist. Interrupting any earlier could miss a request registered by the last
638
+ // in-flight iteration.
498
639
  await this.runningPromise?.stop();
640
+ this.pendingRequests.interruptRequests();
641
+ await this.pendingRequests.awaitRequests();
499
642
  this.setState(SequencerState.STOPPED, undefined, {
500
643
  force: true
501
644
  });
502
645
  this.log.info('Stopped sequencer');
503
646
  }
647
+ /**
648
+ * Gracefully pauses block production so the sequencer can later be resumed with {@link start}: halts the
649
+ * poll loop and waits for the in-flight work() iteration and every pending L1 submission / fallback send
650
+ * to finish, without interrupting them. No interrupt lands mid-build, so no spurious checkpoint-error is
651
+ * emitted and no enqueued checkpoint is dropped. Deliberately does not stop inner services (validator/HA
652
+ * signer, publishers), so the slashing-protection store stays open and the sequencer stays restartable.
653
+ * Used by tests that pause sequencers around an L1 clock warp. Idempotent.
654
+ */ async pause() {
655
+ if (!this.runningPromise?.isRunning()) {
656
+ this.log.debug('Sequencer not running, ignoring pause');
657
+ return;
658
+ }
659
+ this.log.info('Pausing sequencer');
660
+ // Halt the poll loop and let the in-flight iteration finish naturally — no interrupt, and no STOPPING
661
+ // state, since entering STOPPING would make the iteration's own setState calls throw and fail it.
662
+ // work() registers its fire-and-forget requests synchronously before returning, so once the loop has
663
+ // stopped pendingRequests holds every request that will ever exist; awaiting it lets them all finish.
664
+ await this.runningPromise.stop();
665
+ await this.pendingRequests.awaitRequests();
666
+ this.log.info('Paused sequencer');
667
+ }
504
668
  /** Main sequencer loop with a try/catch */ async safeWork() {
505
669
  try {
506
670
  await this.work();
@@ -508,19 +672,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
508
672
  this.emit('checkpoint-error', {
509
673
  error: err
510
674
  });
511
- if (err instanceof SequencerTooSlowError) {
512
- // Log as warn only if we had to abort halfway through the block proposal
513
- const logLvl = [
514
- SequencerState.INITIALIZING_CHECKPOINT,
515
- SequencerState.PROPOSER_CHECK
516
- ].includes(err.proposedState) ? 'debug' : 'warn';
517
- this.log[logLvl](err.message, {
518
- now: this.dateProvider.nowInSeconds()
519
- });
520
- } else {
521
- // Re-throw other errors
522
- throw err;
523
- }
675
+ throw err;
524
676
  } finally{
525
677
  this.setState(SequencerState.IDLE, undefined);
526
678
  }
@@ -539,13 +691,14 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
539
691
  * - Submit checkpoint
540
692
  */ async work() {
541
693
  this.setState(SequencerState.SYNCHRONIZING, undefined);
542
- const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
543
- const { slot: targetSlot, epoch: targetEpoch } = this.epochCache.getTargetEpochAndSlotInNextL1Slot();
694
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
544
695
  // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
545
696
  const checkpointProposalJob = await this.prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds);
546
697
  if (!checkpointProposalJob) {
547
698
  return;
548
699
  }
700
+ // Track the job so we can await its pending L1 submission during shutdown
701
+ this.lastCheckpointProposalJob = checkpointProposalJob;
549
702
  // Execute the checkpoint proposal job
550
703
  const checkpoint = await checkpointProposalJob.execute();
551
704
  // Update last checkpoint proposed (currently unused)
@@ -559,15 +712,25 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
559
712
  }
560
713
  return checkpoint;
561
714
  }
715
+ /** Returns slot and target slot from a single clock snapshot. */ getSlotContextInNextL1Slot() {
716
+ const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
717
+ const targetSlot = SlotNumber(slot + PROPOSER_PIPELINING_SLOT_OFFSET);
718
+ return {
719
+ slot,
720
+ targetSlot,
721
+ epoch,
722
+ targetEpoch: getEpochAtSlot(targetSlot, this.l1Constants),
723
+ ts,
724
+ nowSeconds
725
+ };
726
+ }
562
727
  /**
563
728
  * Prepares the checkpoint proposal by performing all necessary checks and setup.
564
729
  * This is the initial step in the main loop.
565
730
  * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
566
731
  */ async prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds) {
567
- // Check we have not already processed this target slot (cheapest check)
568
- // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
569
- // running against actual time (eg when we use sandbox-style automining)
570
- if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot && this.config.enforceTimeTable) {
732
+ // Check we have not already processed this target slot (cheapest check).
733
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot) {
571
734
  this.log.trace(`Target slot ${targetSlot} has already been processed`);
572
735
  return undefined;
573
736
  }
@@ -576,29 +739,28 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
576
739
  this.log.trace(`Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`);
577
740
  return undefined;
578
741
  }
579
- // Check all components are synced to latest as seen by the archiver (queries all subsystems)
580
- const syncedTo = await this.checkSync({
581
- ts,
582
- slot
583
- });
584
- if (!syncedTo) {
585
- await this.tryVoteWhenSyncFails({
586
- slot,
587
- targetSlot,
588
- ts
742
+ // Test-only: skip proposing for explicitly paused slots. Attestation paths run in the validator
743
+ // client and are not gated by this hook, so paused proposers still attest to others' proposals.
744
+ if (this.config.pauseProposingForSlots?.some((s)=>s === targetSlot)) {
745
+ this.log.warn(`Skipping proposal for paused slot ${targetSlot} (test-only pauseProposingForSlots hook)`, {
746
+ targetSlot
589
747
  });
590
748
  return undefined;
591
749
  }
750
+ // Cheap proposer check first: most nodes are not the proposer for most slots, so gate the
751
+ // expensive multi-subsystem checkSync (and the rest of the build path) behind it. Computed once
752
+ // here and reused for the escape-hatch voting path below. No setState/timing gate on this path:
753
+ // the build-start deadline gate runs only on the proposer build path after a successful checkSync.
754
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
592
755
  // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
593
756
  // Still perform governance/slashing voting (as proposer) once per slot.
594
757
  // When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
595
758
  const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
596
759
  if (isEscapeHatchOpen) {
597
- this.setState(SequencerState.PROPOSER_CHECK, slot);
598
- const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
599
760
  if (canPropose) {
600
761
  await this.tryVoteWhenEscapeHatchOpen({
601
762
  slot,
763
+ targetSlot,
602
764
  proposer
603
765
  });
604
766
  } else {
@@ -610,6 +772,57 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
610
772
  }
611
773
  return undefined;
612
774
  }
775
+ // If we are not the proposer, check whether we should invalidate an invalid pending chain (a
776
+ // liveness backstop) and bail before any sync work or build-timing gate. This reads only the
777
+ // archiver's pending-chain validation status, which is authoritative on its own, instead of
778
+ // running the full sync check. Wrapped in try/catch because this leaner path skips the broader
779
+ // proposed-checkpoint/tip coherence screen that checkSync applied, so transient archiver
780
+ // incoherence surfaces as a quiet skip rather than a work-loop error.
781
+ if (!canPropose) {
782
+ try {
783
+ const pendingChainValidationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
784
+ await this.considerInvalidatingCheckpoint(pendingChainValidationStatus, slot);
785
+ } catch (err) {
786
+ this.log.warn(`Failed to consider invalidating checkpoint`, {
787
+ err,
788
+ slot,
789
+ targetSlot
790
+ });
791
+ }
792
+ return undefined;
793
+ }
794
+ // Explicit build-loop entry gate: if we are past the latest useful block-building start for the
795
+ // target slot, abandon building for this slot. The proposer prioritizes the ideal L1-publish path
796
+ // and does not plan around the late consensus-handoff path. This is the proposer build path's
797
+ // timing gate; it runs only after we know we are the synced proposer, so non-proposer invalidation
798
+ // and escape-hatch voting (which returned above) are never gated by build timing. Vote-only paths
799
+ // still run when block building is abandoned.
800
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
801
+ const nowForStartGate = this.dateProvider.now() / 1000;
802
+ if (nowForStartGate > startDeadline) {
803
+ this.log.debug(`Past start deadline for slot ${targetSlot}, abandoning block building`, {
804
+ targetSlot,
805
+ nowForStartGate,
806
+ startDeadline
807
+ });
808
+ // Mark the slot as attempted so a deadline abort is not retried within the same slot. Vote-only actions
809
+ // still need to run because sync can succeed even when it is too late to start building a checkpoint.
810
+ await this.tryVoteAndPruneWhenCannotBuild({
811
+ slot,
812
+ targetSlot
813
+ });
814
+ this.lastSlotForCheckpointProposalJob = targetSlot;
815
+ return undefined;
816
+ }
817
+ // We are the proposer, the escape hatch is closed, and we have time before the build start deadline.
818
+ // Now run the full sync check before building.
819
+ const syncedTo = await this.checkSync({
820
+ ts,
821
+ slot
822
+ });
823
+ if (!syncedTo) {
824
+ return undefined;
825
+ }
613
826
  // Next checkpoint follows from the last synced one
614
827
  const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
615
828
  const logCtx = {
@@ -621,12 +834,13 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
621
834
  checkpointNumber,
622
835
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex')
623
836
  };
624
- // Check that we are a proposer for the target slot.
625
- this.setState(SequencerState.PROPOSER_CHECK, slot);
626
- const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
627
- // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
628
- if (!canPropose) {
629
- await this.considerInvalidatingCheckpoint(syncedTo, slot);
837
+ // We are the synced proposer within the build window; enter the proposer-check state and build.
838
+ this.setState(SequencerState.PROPOSER_CHECK, targetSlot);
839
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
840
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
841
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
842
+ if (checkpointNumber > confirmedCkpt + 2) {
843
+ this.log.verbose(`Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`);
630
844
  return undefined;
631
845
  }
632
846
  // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
@@ -645,20 +859,84 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
645
859
  const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
646
860
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
647
861
  this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
648
- // In fisherman mode, set the actual proposer's address for simulations
649
- if (this.config.fishermanMode && proposer) {
650
- publisher.setProposerAddressForSimulation(proposer);
651
- this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
652
- }
653
- // Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
654
- const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
655
- // Check with the rollup contract if we can indeed propose at the target slot. This check should not fail
656
- // if all the previous checks are good, but we do it just in case.
657
- const canProposeCheck = await publisher.canProposeAt(syncedTo.archive, proposer ?? EthAddress.ZERO, {
658
- ...invalidateCheckpoint
862
+ // Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
863
+ // Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
864
+ // will invalidate the currently invalid checkpoint on L1.
865
+ const invalidateCheckpoint = syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid ? undefined : await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
866
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
867
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
868
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
869
+ let archiveForCheck = syncedTo.archive;
870
+ if (syncedTo.hasProposedCheckpoint) {
871
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
872
+ this.log.verbose(`Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`, {
873
+ targetSlot,
874
+ parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1)
875
+ });
876
+ // Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
877
+ // own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
878
+ // view and can transiently diverge from the proposed parent (e.g. before the proposed
879
+ // parent's blocks have been applied locally); diverging here would cause the canProposeAt
880
+ // override to set archives[pending] to one value while we present another for comparison.
881
+ archiveForCheck = syncedTo.proposedCheckpointData.archive.root;
882
+ } else if (invalidateCheckpoint) {
883
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
884
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
885
+ archiveForCheck = invalidateCheckpoint.lastArchive;
886
+ this.metrics.recordPipelineDepth(0);
887
+ } else {
888
+ this.metrics.recordPipelineDepth(0);
889
+ }
890
+ // Build the simulation plan: pending/proven override from pipelining or invalidation (or the
891
+ // current snapshot when neither applies, to short-circuit any pending prune in simulation),
892
+ // plus the parent checkpoint cell and fee header when pipelining.
893
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
894
+ checkpointNumber,
895
+ proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
896
+ invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
897
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
898
+ rollup: this.rollupContract,
899
+ signatureContext: this.signatureContext,
900
+ log: this.log
659
901
  });
902
+ // The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
903
+ // so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
904
+ // simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
905
+ // actually fire at the target slot without it — so observers can spot "we are building
906
+ // optimistically across a pruning boundary" in the logs.
907
+ const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
908
+ if (provenOverride !== undefined && await this.l2BlockSource.isPruneDueAtSlot(targetSlot)) {
909
+ this.log.warn(`Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`, {
910
+ checkpointNumber,
911
+ slot,
912
+ targetSlot,
913
+ provenOverride
914
+ });
915
+ }
916
+ this.emit('preparing-checkpoint', {
917
+ targetSlot,
918
+ checkpointNumber,
919
+ hadProposedParent: syncedTo.hasProposedCheckpoint,
920
+ provenOverride,
921
+ simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending
922
+ });
923
+ const canProposeCheck = await publisher.canProposeAt(archiveForCheck, proposer ?? EthAddress.ZERO, simulationOverridesPlan);
924
+ const proposeContext = {
925
+ hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
926
+ proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
927
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
928
+ isInvalidating: !!invalidateCheckpoint,
929
+ invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
930
+ archiveForCheck: archiveForCheck.toString(),
931
+ overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
932
+ overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
933
+ overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader
934
+ };
660
935
  if (canProposeCheck === undefined) {
661
- this.log.warn(`Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`, logCtx);
936
+ this.log.warn(`Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`, {
937
+ ...logCtx,
938
+ ...proposeContext
939
+ });
662
940
  this.emit('proposer-rollup-check-failed', {
663
941
  reason: 'Rollup contract check failed',
664
942
  slot
@@ -669,6 +947,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
669
947
  if (canProposeCheck.slot !== targetSlot) {
670
948
  this.log.warn(`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}.`, {
671
949
  ...logCtx,
950
+ ...proposeContext,
672
951
  rollup: canProposeCheck,
673
952
  expectedSlot: targetSlot
674
953
  });
@@ -682,6 +961,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
682
961
  if (canProposeCheck.checkpointNumber !== checkpointNumber) {
683
962
  this.log.warn(`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}.`, {
684
963
  ...logCtx,
964
+ ...proposeContext,
685
965
  rollup: canProposeCheck,
686
966
  expectedSlot: slot
687
967
  });
@@ -696,14 +976,14 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
696
976
  await this.p2pClient.prepareForSlot(targetSlot);
697
977
  this.log.info(`Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`, {
698
978
  ...logCtx,
699
- proposer,
700
- pipeliningEnabled: this.epochCache.isProposerPipeliningEnabled()
979
+ ...proposeContext,
980
+ proposer
701
981
  });
702
982
  // Create and return the checkpoint proposal job
703
- return this.createCheckpointProposalJob(slot, targetSlot, epoch, targetEpoch, checkpointNumber, syncedTo.blockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint);
983
+ return this.createCheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedTo.blockNumber, syncedTo.checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, syncedTo.proposedCheckpointData);
704
984
  }
705
- createCheckpointProposalJob(slot, targetSlot, epoch, targetEpoch, checkpointNumber, syncedToBlockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint) {
706
- return new CheckpointProposalJob(slot, targetSlot, epoch, targetEpoch, checkpointNumber, syncedToBlockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, this.validatorClient, this.globalsBuilder, this.p2pClient, this.worldState, this.l1ToL2MessageSource, this.l2BlockSource, this.checkpointsBuilder, this.l2BlockSource, this.l1Constants, this.config, this.timetable, this.slasherClient, this.epochCache, this.dateProvider, this.metrics, this, this.setState.bind(this), this.tracer, this.log.getBindings());
985
+ createCheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, proposedCheckpointData) {
986
+ return new CheckpointProposalJob(targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, this.validatorClient, this.globalsBuilder, this.p2pClient, this.worldState, this.l1ToL2MessageSource, this.l2BlockSource, this.checkpointsBuilder, this.l2BlockSource, this.l1Constants, this.signatureContext, this.config, this.timetable, this.slasherClient, this.epochCache, this.dateProvider, this.metrics, this.checkpointProposalJobMetrics.createRecorder(), this, this.pendingRequests, this.setState.bind(this), this.tracer, this.log.getBindings(), proposedCheckpointData);
707
987
  }
708
988
  /**
709
989
  * Returns the current sequencer state.
@@ -711,9 +991,11 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
711
991
  return this.state;
712
992
  }
713
993
  /**
714
- * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
994
+ * Internal helper for setting the sequencer state. Pure: sets the state, emits `state-changed`, and
995
+ * records metrics. Timing deadlines are queried explicitly at the relevant call sites, not gated here.
715
996
  * @param proposedState - The new state to transition to.
716
- * @param slotNumber - The current slot number.
997
+ * @param slotNumber - The target slot being proposed for, emitted as `targetSlot` on the event payload
998
+ * and used to anchor `secondsIntoBuildFrame`. Undefined for lifecycle states with no associated slot.
717
999
  * @param force - Whether to force the transition even if the sequencer is stopped.
718
1000
  */ setState(proposedState, slotNumber, opts = {}) {
719
1001
  if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
@@ -724,26 +1006,40 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
724
1006
  this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
725
1007
  return;
726
1008
  }
727
- let secondsIntoSlot = undefined;
728
- if (slotNumber !== undefined) {
729
- secondsIntoSlot = this.getSecondsIntoSlot(slotNumber);
730
- this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
731
- }
1009
+ const secondsIntoBuildFrame = slotNumber !== undefined ? this.getSecondsIntoBuildFrame(slotNumber) : undefined;
1010
+ const oldState = this.state;
1011
+ const oldStateSlotNumber = this.stateSlotNumber;
1012
+ const stateChanged = proposedState !== oldState;
1013
+ // Wall-clock time spent in the previous state: the delta between consecutive state-changing setState
1014
+ // calls, read from the date provider so it tracks simulated time under a test/manual clock.
1015
+ const transitionAtMs = this.dateProvider.now();
1016
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
732
1017
  const boringStates = [
733
1018
  SequencerState.IDLE,
734
1019
  SequencerState.SYNCHRONIZING
735
1020
  ];
736
- const logLevel = boringStates.includes(proposedState) && boringStates.includes(this.state) ? 'trace' : 'debug';
737
- this.log[logLevel](`Transitioning from ${this.state} to ${proposedState}`, {
1021
+ const logLevel = boringStates.includes(proposedState) && boringStates.includes(oldState) ? 'trace' : 'debug';
1022
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
1023
+ oldState,
1024
+ newState: proposedState,
738
1025
  slotNumber,
739
- secondsIntoSlot
1026
+ stateSlotNumber: oldStateSlotNumber,
1027
+ secondsIntoBuildFrame,
1028
+ ...stateChanged && {
1029
+ stateDurationMs: Math.ceil(stateDurationMs)
1030
+ }
740
1031
  });
741
1032
  this.emit('state-changed', {
742
- oldState: this.state,
1033
+ oldState,
743
1034
  newState: proposedState,
744
- secondsIntoSlot,
745
- slot: slotNumber
1035
+ secondsIntoBuildFrame,
1036
+ targetSlot: slotNumber
746
1037
  });
1038
+ if (stateChanged) {
1039
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
1040
+ this.stateEnteredAtMs = transitionAtMs;
1041
+ this.stateSlotNumber = slotNumber;
1042
+ }
747
1043
  this.state = proposedState;
748
1044
  }
749
1045
  /**
@@ -767,48 +1063,84 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
767
1063
  number: syncSummary.latestBlockNumber,
768
1064
  hash: syncSummary.latestBlockHash
769
1065
  })),
770
- this.l2BlockSource.getL2Tips().then((t)=>t.proposed),
1066
+ this.l2BlockSource.getL2Tips().then((t)=>({
1067
+ proposed: t.proposed,
1068
+ checkpointed: t.checkpointed
1069
+ })),
771
1070
  this.p2pClient.getStatus().then((p2p)=>p2p.syncedToL2Block),
772
- this.l1ToL2MessageSource.getL2Tips().then((t)=>t.proposed),
773
- this.l2BlockSource.getPendingChainValidationStatus()
1071
+ this.l1ToL2MessageSource.getL2Tips().then((t)=>({
1072
+ proposed: t.proposed,
1073
+ checkpointed: t.checkpointed
1074
+ })),
1075
+ this.l2BlockSource.getPendingChainValidationStatus(),
1076
+ this.l2BlockSource.getProposedCheckpointData()
774
1077
  ]);
775
- const [worldState, l2BlockSource, p2p, l1ToL2MessageSource, pendingChainValidationStatus] = syncedBlocks;
776
- // 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,
777
- // as the world state can compute the new genesis block hash, but other components use the hardcoded constant.
778
- // TODO(palla/mbps): Fix the above. All components should be able to handle dynamic genesis block hashes.
779
- const result = l2BlockSource.number === 0 && worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSource.number === 0 || worldState.hash === l2BlockSource.hash && p2p.hash === l2BlockSource.hash && l1ToL2MessageSource.hash === l2BlockSource.hash;
1078
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] = syncedBlocks;
1079
+ const result = worldState.hash === l2Tips.proposed.hash && p2p.hash === l2Tips.proposed.hash && l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash && l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash && l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
780
1080
  if (!result) {
781
1081
  this.log.debug(`Sequencer sync check failed`, {
782
1082
  worldState,
783
- l2BlockSource,
1083
+ l2BlockSource: l2Tips.proposed,
784
1084
  p2p,
785
- l1ToL2MessageSource
1085
+ l1ToL2MessageSourceTips
786
1086
  });
787
1087
  return undefined;
788
1088
  }
789
- // Special case for genesis state
790
1089
  const blockNumber = worldState.number;
791
- if (blockNumber < INITIAL_L2_BLOCK_NUM) {
792
- const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
793
- return {
794
- checkpointNumber: CheckpointNumber.ZERO,
795
- blockNumber: BlockNumber.ZERO,
796
- archive,
1090
+ const blockData = await this.l2BlockSource.getBlockData({
1091
+ number: blockNumber
1092
+ });
1093
+ if (!blockData) {
1094
+ this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
1095
+ blockNumber,
1096
+ l2Tips,
1097
+ syncedL2Slot,
1098
+ ...args
1099
+ });
1100
+ return undefined;
1101
+ }
1102
+ // Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
1103
+ // proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
1104
+ // our world-state tip past the checkpointed tip — while the proposing node never published the
1105
+ // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
1106
+ // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
1107
+ // once their build slot ends; this guard is the correctness barrier during the grace window before.
1108
+ // `getProposedCheckpointData()` returns the latest proposed checkpoint payload, which is always
1109
+ // the leading one (a proposed entry is only stored beyond the confirmed frontier and is deleted
1110
+ // on confirmation). It carries no tip, so there is no tip-vs-payload split read to reconcile.
1111
+ if (blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number && proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber) {
1112
+ const logCtx = {
1113
+ blockCheckpointNumber: blockData.checkpointNumber,
1114
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
1115
+ proposedCheckpointTipNumber: proposedCheckpointData?.checkpointNumber,
1116
+ blockNumber: blockData.header.getBlockNumber(),
1117
+ blockSlot: blockData.header.getSlot(),
797
1118
  syncedL2Slot,
798
- pendingChainValidationStatus
1119
+ ...args
799
1120
  };
1121
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
1122
+ return undefined;
800
1123
  }
801
- const blockData = await this.l2BlockSource.getBlockData(blockNumber);
802
- if (!blockData) {
803
- // this shouldn't really happen because a moment ago we checked that all components were in sync
804
- this.log.error(`Failed to get L2 block data ${blockNumber} from the archiver with all components in sync`);
1124
+ const hasProposedCheckpoint = proposedCheckpointData !== undefined;
1125
+ // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
1126
+ // The checkpoint number to build is derived as blockData.checkpointNumber + 1
1127
+ if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
1128
+ this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
1129
+ proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
1130
+ blockCheckpointNumber: blockData.checkpointNumber,
1131
+ syncedL2Slot,
1132
+ ...args
1133
+ });
805
1134
  return undefined;
806
1135
  }
807
1136
  return {
808
1137
  blockData,
809
1138
  blockNumber: blockData.header.getBlockNumber(),
810
1139
  checkpointNumber: blockData.checkpointNumber,
1140
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
811
1141
  archive: blockData.archive.root,
1142
+ hasProposedCheckpoint,
1143
+ proposedCheckpointData,
812
1144
  syncedL2Slot,
813
1145
  pendingChainValidationStatus
814
1146
  };
@@ -864,7 +1196,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
864
1196
  proposer
865
1197
  ];
866
1198
  }
867
- this.log.debug(`We are the proposer for target slot ${targetSlot}`, {
1199
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
868
1200
  targetSlot,
869
1201
  proposer
870
1202
  });
@@ -874,30 +1206,24 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
874
1206
  ];
875
1207
  }
876
1208
  /**
877
- * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
878
- * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
879
- */ async tryVoteWhenSyncFails(args) {
1209
+ * Tries to vote on slashing actions and governance and to prune when we cannot build and are past the
1210
+ * block-building window. This allows the sequencer to participate in governance/slashing votes even when it
1211
+ * cannot build blocks, and to prune the pending chain so it can recover from bad data that is blocking sync.
1212
+ */ async tryVoteAndPruneWhenCannotBuild(args) {
880
1213
  const { slot, targetSlot } = args;
881
1214
  // Prevent duplicate attempts in the same slot
882
- if (this.lastSlotForFallbackVote === slot) {
883
- this.log.trace(`Already attempted to vote in slot ${slot} (skipping)`);
1215
+ if (this.lastSlotForFallbackAction === slot) {
1216
+ this.log.trace(`Already attempted fallback actions in slot ${slot} (skipping)`);
884
1217
  return;
885
1218
  }
886
- // Check if we're past the max time for initializing a proposal
887
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
888
- const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_CHECKPOINT);
889
- // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
890
- // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
891
- if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
892
- this.log.trace(`Not attempting to vote since there is still time for block building`, {
893
- secondsIntoSlot,
894
- maxAllowedTime
895
- });
896
- return;
897
- }
898
- this.log.trace(`Sync for slot ${slot} failed, checking for voting opportunities`, {
899
- secondsIntoSlot,
900
- maxAllowedTime
1219
+ // Vote-only actions do not give up the slot: if sync recovers, a later work-loop iteration can still build.
1220
+ // Under proposer pipelining the work loop reasons about the next L1 slot, so waiting for the target slot's
1221
+ // build-start deadline can miss the whole fallback window when the target advances with the clock.
1222
+ const nowSeconds = this.dateProvider.now() / 1000;
1223
+ const startDeadline = this.timetable.getBuildStartDeadline(targetSlot);
1224
+ this.log.trace(`Cannot build for slot ${slot}, checking for voting opportunities`, {
1225
+ nowSeconds,
1226
+ startDeadline
901
1227
  });
902
1228
  // Check if we're a proposer or proposal is open
903
1229
  const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
@@ -909,7 +1235,7 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
909
1235
  return;
910
1236
  }
911
1237
  // Mark this slot as attempted
912
- this.lastSlotForFallbackVote = slot;
1238
+ this.lastSlotForFallbackAction = slot;
913
1239
  // Get a publisher for voting
914
1240
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
915
1241
  this.log.debug(`Attempting to vote despite sync failure at slot ${slot}`, {
@@ -920,33 +1246,65 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
920
1246
  const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
921
1247
  const votesPromises = voter.enqueueVotes();
922
1248
  const votes = await Promise.all(votesPromises);
923
- if (votes.every((p)=>!p)) {
924
- this.log.debug(`No votes to enqueue for slot ${slot}`);
1249
+ // Even if we cannot build, try to prune so a stuck pending chain (e.g. bad data blocking sync) can
1250
+ // recover. prune() is permissionless, so it rides the same fallback multicall as the votes.
1251
+ const pruneEnqueued = await this.tryEnqueuePruneIfPrunable(targetSlot, publisher);
1252
+ // Bail if nothing to do
1253
+ if (votes.every((p)=>!p) && !pruneEnqueued) {
1254
+ this.log.debug(`Nothing to enqueue for slot ${slot} (no votes, not prunable)`);
925
1255
  return;
926
1256
  }
927
- this.log.info(`Voting in slot ${slot} despite sync failure`, {
928
- slot
1257
+ const [governanceVoteEnqueued, slashingVoteEnqueued] = votes;
1258
+ this.log.info(`Submitting fallback requests in slot ${slot} despite sync failure`, {
1259
+ slot,
1260
+ pruneEnqueued,
1261
+ governanceVoteEnqueued: !!governanceVoteEnqueued,
1262
+ slashingVoteEnqueued: !!slashingVoteEnqueued
1263
+ });
1264
+ // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
1265
+ // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
1266
+ // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
1267
+ // work loop while waiting for the target slot to start, but track it so stop() can drain it.
1268
+ const send = publisher.sendRequestsAt(targetSlot).catch((err)=>{
1269
+ this.log.error(`Failed to publish fallback requests despite sync failure for slot ${slot}`, err, {
1270
+ slot
1271
+ });
929
1272
  });
930
- await publisher.sendRequests();
1273
+ this.pendingRequests.trackRequest(send, ()=>publisher.interrupt());
1274
+ }
1275
+ async tryEnqueuePruneIfPrunable(targetSlot, publisher) {
1276
+ try {
1277
+ return await publisher.enqueuePruneIfPrunable(targetSlot);
1278
+ } catch (err) {
1279
+ this.log.error(`Failed to enqueue rollup prune for slot ${targetSlot}`, err, {
1280
+ targetSlot
1281
+ });
1282
+ return false;
1283
+ }
931
1284
  }
932
1285
  /**
933
1286
  * Tries to vote on slashing actions and governance proposals when escape hatch is open.
934
1287
  * This allows the sequencer to participate in voting without performing checkpoint proposal work.
935
1288
  */ async tryVoteWhenEscapeHatchOpen(args) {
936
- const { slot, proposer } = args;
1289
+ const { slot, targetSlot, proposer } = args;
937
1290
  // Prevent duplicate attempts in the same slot
938
- if (this.lastSlotForFallbackVote === slot) {
1291
+ if (this.lastSlotForFallbackAction === slot) {
939
1292
  this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
940
1293
  return;
941
1294
  }
942
1295
  // Mark this slot as attempted
943
- this.lastSlotForFallbackVote = slot;
1296
+ this.lastSlotForFallbackAction = slot;
944
1297
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
945
1298
  this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
946
1299
  slot,
1300
+ targetSlot,
947
1301
  attestorAddress
948
1302
  });
949
- const voter = new CheckpointVoter(slot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
1303
+ // Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
1304
+ // Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
1305
+ // L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
1306
+ // sign for `targetSlot` and delay submission to the start of `targetSlot`.
1307
+ const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
950
1308
  const votesPromises = voter.enqueueVotes();
951
1309
  const votes = await Promise.all(votesPromises);
952
1310
  if (votes.every((p)=>!p)) {
@@ -954,28 +1312,52 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
954
1312
  return;
955
1313
  }
956
1314
  this.log.info(`Voting in slot ${slot} (escape hatch open)`, {
957
- slot
1315
+ slot,
1316
+ targetSlot
1317
+ });
1318
+ // Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
1319
+ // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1320
+ // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1321
+ // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1322
+ // waiting for the target slot to start, mirroring tryVoteAndPruneWhenCannotBuild, but tracked so
1323
+ // stop() can drain it.
1324
+ const send = publisher.sendRequestsAt(targetSlot).catch((err)=>{
1325
+ this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, {
1326
+ slot,
1327
+ targetSlot
1328
+ });
958
1329
  });
959
- await publisher.sendRequests();
1330
+ this.pendingRequests.trackRequest(send, ()=>publisher.interrupt());
960
1331
  }
961
1332
  /**
962
1333
  * Considers invalidating a block if the pending chain is invalid. Depends on how long the invalid block
963
1334
  * has been there without being invalidated and whether the sequencer is in the committee or not. We always
964
1335
  * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
965
1336
  * and if they fail, any sequencer will try as well.
966
- */ async considerInvalidatingCheckpoint(syncedTo, currentSlot) {
967
- const { pendingChainValidationStatus, syncedL2Slot } = syncedTo;
1337
+ * @param pendingChainValidationStatus - The archiver's pending-chain validation status, authoritative on its own.
1338
+ * @param currentSlot - The wall-clock slot, used for committee lookup, the per-(checkpoint, slot) dedup guard, and logging.
1339
+ */ async considerInvalidatingCheckpoint(pendingChainValidationStatus, currentSlot) {
968
1340
  if (pendingChainValidationStatus.valid) {
969
1341
  return;
970
1342
  }
971
1343
  const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1344
+ // Avoid re-running the committee lookup, simulation, and submission on every tick within a slot.
1345
+ // The guard is keyed by (checkpoint, slot) — so a different invalid checkpoint surfacing later in
1346
+ // the same slot is not suppressed — and is set only after a request is successfully simulated below,
1347
+ // so a transient simulation failure (or thresholds not yet met) still retries on the next tick.
1348
+ if (this.lastInvalidationAttempt?.slot === currentSlot && this.lastInvalidationAttempt.checkpointNumber === invalidCheckpointNumber) {
1349
+ this.log.trace(`Already attempted to invalidate checkpoint ${invalidCheckpointNumber} in slot ${currentSlot}`, {
1350
+ currentSlot,
1351
+ invalidCheckpointNumber
1352
+ });
1353
+ return;
1354
+ }
972
1355
  const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
973
1356
  const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
974
1357
  const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
975
1358
  const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } = this.config;
976
1359
  const logData = {
977
1360
  invalidL1Timestamp: invalidCheckpointTimestamp,
978
- syncedL2Slot,
979
1361
  invalidCheckpoint: pendingChainValidationStatus.checkpoint,
980
1362
  secondsBeforeInvalidatingBlockAsCommitteeMember,
981
1363
  secondsBeforeInvalidatingBlockAsNonCommitteeMember,
@@ -1009,6 +1391,12 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
1009
1391
  this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
1010
1392
  return;
1011
1393
  }
1394
+ // We produced a valid invalidation request; record it so further ticks within this slot skip the
1395
+ // committee lookup, simulation, and submission above for this same invalid checkpoint.
1396
+ this.lastInvalidationAttempt = {
1397
+ slot: currentSlot,
1398
+ checkpointNumber: invalidCheckpointNumber
1399
+ };
1012
1400
  this.log.info(invalidateAsCommitteeMember ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member` : `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`, logData);
1013
1401
  publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
1014
1402
  if (!this.config.fishermanMode) {
@@ -1044,12 +1432,12 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
1044
1432
  }))
1045
1433
  });
1046
1434
  }
1047
- getSlotStartBuildTimestamp(slotNumber) {
1048
- return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
1049
- }
1050
- getSecondsIntoSlot(slotNumber) {
1051
- const slotStartTimestamp = this.getSlotStartBuildTimestamp(slotNumber);
1052
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1435
+ /**
1436
+ * Wall-clock seconds elapsed since the build-frame start of the given target slot
1437
+ * (`now − getBuildFrameStart(targetSlot)`). May be negative if called before the build frame opens.
1438
+ */ getSecondsIntoBuildFrame(targetSlot) {
1439
+ const buildFrameStart = this.timetable.getBuildFrameStart(targetSlot);
1440
+ return Number((this.dateProvider.now() / 1000 - buildFrameStart).toFixed(3));
1053
1441
  }
1054
1442
  get aztecSlotDuration() {
1055
1443
  return this.l1Constants.slotDuration;
@@ -1072,7 +1460,4 @@ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpoi
1072
1460
  getConfig() {
1073
1461
  return this.config;
1074
1462
  }
1075
- get l1PublishingTime() {
1076
- return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
1077
- }
1078
1463
  }