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