@aztec/sequencer-client 0.0.1-commit.993d52e → 0.0.1-commit.9a89641

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 (133) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +23 -5
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +63 -36
  5. package/dest/config.d.ts +32 -4
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +76 -32
  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 +13 -26
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +9 -66
  17. package/dest/global_variable_builder/index.d.ts +4 -2
  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 +23 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +36 -6
  23. package/dest/publisher/index.d.ts +2 -1
  24. package/dest/publisher/index.d.ts.map +1 -1
  25. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  26. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  27. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  28. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  29. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  31. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +98 -0
  32. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  33. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
  34. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  35. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  36. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
  37. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  38. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  39. package/dest/publisher/l1_tx_failed_store/index.js +3 -0
  40. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  41. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  42. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  43. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -5
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +16 -3
  46. package/dest/publisher/sequencer-publisher.d.ts +112 -65
  47. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher.js +758 -388
  49. package/dest/publisher/write_json.d.ts +11 -0
  50. package/dest/publisher/write_json.d.ts.map +1 -0
  51. package/dest/publisher/write_json.js +57 -0
  52. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  53. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  54. package/dest/sequencer/automine/automine_factory.js +85 -0
  55. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  56. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  57. package/dest/sequencer/automine/automine_sequencer.js +696 -0
  58. package/dest/sequencer/automine/index.d.ts +3 -0
  59. package/dest/sequencer/automine/index.d.ts.map +1 -0
  60. package/dest/sequencer/automine/index.js +2 -0
  61. package/dest/sequencer/checkpoint_proposal_job.d.ts +75 -19
  62. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  63. package/dest/sequencer/checkpoint_proposal_job.js +846 -264
  64. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  65. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  66. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  67. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  68. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  69. package/dest/sequencer/checkpoint_voter.js +2 -5
  70. package/dest/sequencer/events.d.ts +62 -5
  71. package/dest/sequencer/events.d.ts.map +1 -1
  72. package/dest/sequencer/metrics.d.ts +13 -10
  73. package/dest/sequencer/metrics.d.ts.map +1 -1
  74. package/dest/sequencer/metrics.js +45 -20
  75. package/dest/sequencer/missing_committee.d.ts +72 -0
  76. package/dest/sequencer/missing_committee.d.ts.map +1 -0
  77. package/dest/sequencer/missing_committee.js +139 -0
  78. package/dest/sequencer/requests_tracker.d.ts +22 -0
  79. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  80. package/dest/sequencer/requests_tracker.js +33 -0
  81. package/dest/sequencer/sequencer.d.ts +167 -41
  82. package/dest/sequencer/sequencer.d.ts.map +1 -1
  83. package/dest/sequencer/sequencer.js +604 -200
  84. package/dest/sequencer/types.d.ts +2 -2
  85. package/dest/sequencer/types.d.ts.map +1 -1
  86. package/dest/test/index.d.ts +3 -3
  87. package/dest/test/index.d.ts.map +1 -1
  88. package/dest/test/mock_checkpoint_builder.d.ts +7 -9
  89. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  90. package/dest/test/mock_checkpoint_builder.js +39 -30
  91. package/dest/test/utils.d.ts +15 -1
  92. package/dest/test/utils.d.ts.map +1 -1
  93. package/dest/test/utils.js +25 -7
  94. package/package.json +29 -29
  95. package/src/client/sequencer-client.ts +90 -45
  96. package/src/config.ts +92 -33
  97. package/src/global_variable_builder/README.md +44 -0
  98. package/src/global_variable_builder/fee_predictor.ts +182 -0
  99. package/src/global_variable_builder/fee_provider.ts +97 -0
  100. package/src/global_variable_builder/global_builder.ts +19 -88
  101. package/src/global_variable_builder/index.ts +3 -1
  102. package/src/publisher/config.ts +71 -7
  103. package/src/publisher/index.ts +3 -0
  104. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  105. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  106. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +164 -0
  107. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
  108. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  109. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  110. package/src/publisher/sequencer-publisher-factory.ts +18 -6
  111. package/src/publisher/sequencer-publisher.ts +847 -474
  112. package/src/publisher/write_json.ts +78 -0
  113. package/src/sequencer/README.md +162 -450
  114. package/src/sequencer/automine/README.md +60 -0
  115. package/src/sequencer/automine/automine_factory.ts +152 -0
  116. package/src/sequencer/automine/automine_sequencer.ts +800 -0
  117. package/src/sequencer/automine/index.ts +6 -0
  118. package/src/sequencer/checkpoint_proposal_job.ts +1002 -298
  119. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  120. package/src/sequencer/checkpoint_voter.ts +1 -12
  121. package/src/sequencer/events.ts +66 -5
  122. package/src/sequencer/metrics.ts +57 -24
  123. package/src/sequencer/missing_committee.ts +192 -0
  124. package/src/sequencer/requests_tracker.ts +43 -0
  125. package/src/sequencer/sequencer.ts +711 -223
  126. package/src/sequencer/types.ts +1 -1
  127. package/src/test/index.ts +2 -2
  128. package/src/test/mock_checkpoint_builder.ts +51 -48
  129. package/src/test/utils.ts +61 -10
  130. package/dest/sequencer/timetable.d.ts +0 -87
  131. package/dest/sequencer/timetable.d.ts.map +0 -1
  132. package/dest/sequencer/timetable.js +0 -223
  133. package/src/sequencer/timetable.ts +0 -283
@@ -370,42 +370,53 @@ function applyDecs2203RFactory() {
370
370
  function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
371
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
372
  }
373
- var _dec, _dec1, _dec2, _initProto;
373
+ var _dec, _dec1, _initProto;
374
374
  import { Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec/blob-lib';
375
- import { FeeAssetPriceOracle, MULTI_CALL_3_ADDRESS, Multicall3, RollupContract } from '@aztec/ethereum/contracts';
376
- import { L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
377
- import { MAX_L1_TX_LIMIT, WEI_CONST } from '@aztec/ethereum/l1-tx-utils';
378
- import { FormattedViemError, formatViemError, mergeAbis, tryExtractEvent } from '@aztec/ethereum/utils';
379
- import { sumBigint } from '@aztec/foundation/bigint';
380
- import { toHex as toPaddedHex } from '@aztec/foundation/bigint-buffer';
375
+ import { FeeAssetPriceOracle, MULTI_CALL_3_ADDRESS, Multicall3, MulticallForwarderRevertedError, buildSimulationOverridesStateOverride } from '@aztec/ethereum/contracts';
376
+ import { L1FeeAnalyzer, captureWindowBlockFees } from '@aztec/ethereum/l1-fee-analysis';
377
+ import { L1TxTimeoutError, MAX_L1_TX_LIMIT, WEI_CONST } from '@aztec/ethereum/l1-tx-utils';
378
+ import { FormattedViemError, formatViemError, mergeAbis, tryDecodeRevertReason, tryExtractEvent } from '@aztec/ethereum/utils';
381
379
  import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
380
+ import { trimmedBytesLength } from '@aztec/foundation/buffer';
382
381
  import { pick } from '@aztec/foundation/collection';
382
+ import { TimeoutError } from '@aztec/foundation/error';
383
383
  import { EthAddress } from '@aztec/foundation/eth-address';
384
384
  import { Signature } from '@aztec/foundation/eth-signature';
385
385
  import { createLogger } from '@aztec/foundation/log';
386
- import { makeBackoff, retry } from '@aztec/foundation/retry';
386
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
387
387
  import { bufferToHex } from '@aztec/foundation/string';
388
388
  import { Timer } from '@aztec/foundation/timer';
389
- import { EmpireBaseAbi, ErrorsAbi, RollupAbi } from '@aztec/l1-artifacts';
389
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi, SlashingProposerAbi } from '@aztec/l1-artifacts';
390
390
  import { encodeSlashConsensusVotes } from '@aztec/slasher';
391
391
  import { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
392
+ import { getLastL1SlotTimestampForL2Slot, getNextL1SlotTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
392
393
  import { getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
393
- import { encodeFunctionData, toHex } from 'viem';
394
+ import { encodeFunctionData, keccak256, toHex } from 'viem';
395
+ import { createL1TxFailedStore } from './l1_tx_failed_store/index.js';
396
+ import { SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
394
397
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
398
+ /**
399
+ * Returns true if the receipt indicates a successful send AND the expected event was emitted
400
+ * by the target contract. Both pieces are required: an aggregate3 entry that reverted will
401
+ * have receipt.status === 'success' but no event log.
402
+ */ function extractEventSuccess(receipt, opts) {
403
+ if (!receipt || receipt.status !== 'success') {
404
+ return false;
405
+ }
406
+ return !!tryExtractEvent(receipt.logs, opts.address.toString(), opts.abi, opts.eventName);
407
+ }
395
408
  export const Actions = [
396
409
  'invalidate-by-invalid-attestation',
397
410
  'invalidate-by-insufficient-attestations',
411
+ 'prune',
398
412
  'propose',
399
413
  'governance-signal',
400
- 'empire-slashing-signal',
401
- 'create-empire-payload',
402
- 'execute-empire-payload',
403
414
  'vote-offenses',
404
415
  'execute-slash'
405
416
  ];
406
417
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
407
418
  export const compareActions = (a, b)=>Actions.indexOf(a) - Actions.indexOf(b);
408
- _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader'), _dec2 = trackSpan('SequencerPublisher.validateCheckpointForSubmission');
419
+ _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader');
409
420
  export class SequencerPublisher {
410
421
  config;
411
422
  static{
@@ -419,57 +430,64 @@ export class SequencerPublisher {
419
430
  _dec1,
420
431
  2,
421
432
  "validateBlockHeader"
422
- ],
423
- [
424
- _dec2,
425
- 2,
426
- "validateCheckpointForSubmission"
427
433
  ]
428
434
  ], []));
429
435
  }
430
436
  interrupted;
431
437
  metrics;
438
+ bundleSimulator;
432
439
  epochCache;
433
- governanceLog;
434
- slashingLog;
440
+ failedTxStore;
441
+ /**
442
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
443
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
444
+ * publisher can route to so any of their custom errors decode against it.
445
+ */ revertDecoderAbi;
435
446
  lastActions;
436
- isPayloadEmptyCache;
437
- payloadProposedCache;
438
447
  log;
439
448
  ethereumSlotDuration;
449
+ aztecSlotDuration;
450
+ previousL1BlockWaitTimeoutMs;
451
+ previousL1BlockWaitPollIntervalMs;
452
+ /** Date provider for wall-clock time. */ dateProvider;
440
453
  blobClient;
441
- /** Address to use for simulations in fisherman mode (actual proposer's address) */ proposerAddressForSimulation;
454
+ /** Optional callback to obtain a replacement publisher when the current one fails to send. */ getNextPublisher;
442
455
  /** L1 fee analyzer for fisherman mode */ l1FeeAnalyzer;
443
456
  /** Fee asset price oracle for computing price modifiers from Uniswap V4 */ feeAssetPriceOracle;
444
- // A CALL to a cold address is 2700 gas
445
- static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
446
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
447
- static VOTE_GAS_GUESS = 800_000n;
457
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */ interruptibleSleep;
448
458
  l1TxUtils;
449
459
  rollupContract;
450
460
  govProposerContract;
451
461
  slashingProposerContract;
452
- slashFactoryContract;
453
462
  tracer;
454
463
  requests;
455
464
  constructor(config, deps){
456
465
  this.config = config;
457
466
  this.interrupted = (_initProto(this), false);
458
- this.governanceLog = createLogger('sequencer:publisher:governance');
459
- this.slashingLog = createLogger('sequencer:publisher:slashing');
467
+ this.revertDecoderAbi = mergeAbis([
468
+ RollupAbi,
469
+ SlashingProposerAbi,
470
+ EmpireBaseAbi,
471
+ ErrorsAbi
472
+ ]);
460
473
  this.lastActions = {};
461
- this.isPayloadEmptyCache = new Map();
462
- this.payloadProposedCache = new Set();
474
+ this.interruptibleSleep = new InterruptibleSleep();
463
475
  this.requests = [];
464
476
  this.log = deps.log ?? createLogger('sequencer:publisher');
465
477
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
478
+ this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
479
+ this.previousL1BlockWaitTimeoutMs = config.sequencerPublisherPreviousL1BlockWaitTimeoutMs;
480
+ this.previousL1BlockWaitPollIntervalMs = config.sequencerPublisherPreviousL1BlockWaitPollIntervalMs;
481
+ this.dateProvider = deps.dateProvider;
466
482
  this.epochCache = deps.epochCache;
467
483
  this.lastActions = deps.lastActions;
468
484
  this.blobClient = deps.blobClient;
485
+ this.dateProvider = deps.dateProvider;
469
486
  const telemetry = deps.telemetry ?? getTelemetryClient();
470
487
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
471
488
  this.tracer = telemetry.getTracer('SequencerPublisher');
472
489
  this.l1TxUtils = deps.l1TxUtils;
490
+ this.getNextPublisher = deps.getNextPublisher;
473
491
  this.rollupContract = deps.rollupContract;
474
492
  this.govProposerContract = deps.governanceProposerContract;
475
493
  this.slashingProposerContract = deps.slashingProposerContract;
@@ -478,22 +496,116 @@ export class SequencerPublisher {
478
496
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
479
497
  this.slashingProposerContract = newSlashingProposer;
480
498
  });
481
- this.slashFactoryContract = deps.slashFactoryContract;
482
499
  // Initialize L1 fee analyzer for fisherman mode
483
500
  if (config.fishermanMode) {
484
- this.l1FeeAnalyzer = new L1FeeAnalyzer(this.l1TxUtils.client, deps.dateProvider, createLogger('sequencer:publisher:fee-analyzer'));
501
+ this.l1FeeAnalyzer = new L1FeeAnalyzer(this.l1TxUtils.client, deps.dateProvider, this.log.createChild('fee-analyzer'));
485
502
  }
486
503
  // Initialize fee asset price oracle
487
- this.feeAssetPriceOracle = new FeeAssetPriceOracle(this.l1TxUtils.client, this.rollupContract, createLogger('sequencer:publisher:price-oracle'));
504
+ this.feeAssetPriceOracle = new FeeAssetPriceOracle(this.l1TxUtils.client, this.rollupContract, this.log.createChild('price-oracle'));
505
+ // Initialize failed L1 tx store (optional, for test networks)
506
+ this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
507
+ this.bundleSimulator = new SequencerBundleSimulator({
508
+ getL1TxUtils: ()=>this.l1TxUtils,
509
+ rollupContract: this.rollupContract,
510
+ epochCache: this.epochCache,
511
+ log: this.log.createChild('bundle-simulator')
512
+ });
513
+ }
514
+ /**
515
+ * Logs the gas-pricing data of a failed L1 transaction at warn — so underpricing is diagnosable
516
+ * from logs even with no failed-tx store configured — and backs the record up to the store when
517
+ * one is. When captureFeeSummary is true, also records the fee data of the already-mined L1
518
+ * blocks in the target slot's inclusion window.
519
+ */ backupFailedTx(failedTx, opts) {
520
+ const tx = {
521
+ ...failedTx,
522
+ timestamp: Date.now()
523
+ };
524
+ // Fire and forget - don't block on backup
525
+ void (async ()=>{
526
+ try {
527
+ // Prefer a pre-captured summary (shared across a batch of failures in the same slot) so we
528
+ // don't re-read the fee window per record. A capture error must not lose the record itself.
529
+ const feeSummary = opts?.sharedFeeSummary ?? (opts?.captureFeeSummary ? await this.captureFeeEnvironment(opts.targetSlot).catch(()=>undefined) : undefined);
530
+ if (feeSummary) {
531
+ tx.gasInfo = {
532
+ ...tx.gasInfo,
533
+ ...feeSummary
534
+ };
535
+ }
536
+ if (tx.gasInfo) {
537
+ this.log.warn(`Gas pricing data for failed L1 tx (${tx.failureType})`, {
538
+ failureType: tx.failureType,
539
+ actions: tx.context.actions,
540
+ slot: tx.context.slot,
541
+ ...tx.gasInfo,
542
+ ...tx.timing
543
+ });
544
+ }
545
+ const store = await this.failedTxStore;
546
+ if (store) {
547
+ await store.saveFailedTx(tx);
548
+ }
549
+ } catch (err) {
550
+ this.log.warn(`Failed to backup failed L1 tx to store`, err);
551
+ }
552
+ })();
553
+ }
554
+ /**
555
+ * Captures per-block fee data for the L1 blocks in the target slot's inclusion window (the blocks the
556
+ * tx could have landed in) for underpricing diagnostics. Reads only already-mined blocks, so it never
557
+ * waits on the chain. Safe to call off the critical path: the underlying capture never throws, and this
558
+ * returns undefined when there is no target slot or the window is not yet mined (e.g. an early send
559
+ * failure), in which case the record simply carries no window data.
560
+ */ async captureFeeEnvironment(targetL2Slot) {
561
+ if (targetL2Slot === undefined) {
562
+ return undefined;
563
+ }
564
+ const l1Constants = this.epochCache.getL1Constants();
565
+ // The inclusion window is [start of slot N, start of slot N+1): all L1 blocks that can include a tx
566
+ // for this L2 slot. getTimestampForSlot returns seconds, matching block.timestamp.
567
+ const windowStartS = getTimestampForSlot(targetL2Slot, l1Constants);
568
+ const windowEndS = getTimestampForSlot(SlotNumber(Number(targetL2Slot) + 1), l1Constants);
569
+ const windowBlocks = await captureWindowBlockFees(this.l1TxUtils.client, windowStartS, windowEndS);
570
+ if (windowBlocks.length === 0) {
571
+ return undefined;
572
+ }
573
+ return {
574
+ windowBlocks
575
+ };
576
+ }
577
+ /** Computes timing info relative to the L2 slot deadline. */ computeTimingInfo(targetL2Slot) {
578
+ if (targetL2Slot === undefined) {
579
+ return undefined;
580
+ }
581
+ const l1Constants = this.epochCache.getL1Constants();
582
+ const slotDeadlineS = getTimestampForSlot(SlotNumber(Number(targetL2Slot) + 1), l1Constants);
583
+ const slotDeadlineMs = Number(slotDeadlineS) * 1000;
584
+ return {
585
+ targetL2Slot: Number(targetL2Slot),
586
+ slotDeadlineTimestampS: slotDeadlineS,
587
+ msUntilSlotDeadline: slotDeadlineMs - this.dateProvider.now()
588
+ };
589
+ }
590
+ /**
591
+ * Builds an id for a synthetic failure record (send-error/timeout) that has no on-chain tx hash.
592
+ * Includes the failure time so each attempt — including retries of the same slot — is stored as its
593
+ * own record rather than overwriting the previous one.
594
+ */ failureRecordId(actions, targetSlot) {
595
+ return keccak256(toHex(`${actions.join(',')}:${targetSlot ?? ''}:${Date.now()}`));
488
596
  }
489
597
  getRollupContract() {
490
598
  return this.rollupContract;
491
599
  }
492
600
  /**
493
601
  * Gets the fee asset price modifier from the oracle.
494
- * Returns 0n if the oracle query fails.
495
- */ getFeeAssetPriceModifier() {
496
- return this.feeAssetPriceOracle.computePriceModifier();
602
+ *
603
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
604
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
605
+ * modifier matches the parent L1 will use when applying it.
606
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
607
+ */ getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12) {
608
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
497
609
  }
498
610
  getSenderAddress() {
499
611
  return this.l1TxUtils.getSenderAddress();
@@ -503,17 +615,11 @@ export class SequencerPublisher {
503
615
  */ getL1FeeAnalyzer() {
504
616
  return this.l1FeeAnalyzer;
505
617
  }
506
- /**
507
- * Sets the proposer address to use for simulations in fisherman mode.
508
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
509
- */ setProposerAddressForSimulation(proposerAddress) {
510
- this.proposerAddressForSimulation = proposerAddress;
511
- }
512
618
  addRequest(request) {
513
619
  this.requests.push(request);
514
620
  }
515
621
  getCurrentL2Slot() {
516
- return this.epochCache.getEpochAndSlotNow().slot;
622
+ return this.epochCache.getSlotNow();
517
623
  }
518
624
  /**
519
625
  * Clears all pending requests without sending them.
@@ -566,11 +672,15 @@ export class SequencerPublisher {
566
672
  }
567
673
  /**
568
674
  * Sends all requests that are still valid.
675
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
676
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
677
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
678
+ * AutomineSequencer, which publishes synchronously within the current slot.
569
679
  * @returns one of:
570
680
  * - A receipt and stats if the tx succeeded
571
681
  * - a receipt and errorMsg if it failed on L1
572
682
  * - undefined if no valid requests are found OR the tx failed to send.
573
- */ async sendRequests() {
683
+ */ async sendRequests(targetSlot) {
574
684
  const requestsToProcess = [
575
685
  ...this.requests
576
686
  ];
@@ -578,10 +688,9 @@ export class SequencerPublisher {
578
688
  if (this.interrupted || requestsToProcess.length === 0) {
579
689
  return undefined;
580
690
  }
581
- const currentL2Slot = this.getCurrentL2Slot();
691
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
582
692
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
583
693
  const validRequests = requestsToProcess.filter((request)=>request.lastValidL2Slot >= currentL2Slot);
584
- const validActions = validRequests.map((x)=>x.action);
585
694
  const expiredActions = requestsToProcess.filter((request)=>request.lastValidL2Slot < currentL2Slot).map((x)=>x.action);
586
695
  if (validRequests.length !== requestsToProcess.length) {
587
696
  this.log.warn(`Some requests were expired for slot ${currentL2Slot}`, {
@@ -599,53 +708,98 @@ export class SequencerPublisher {
599
708
  this.log.debug(`No valid requests to send`);
600
709
  return undefined;
601
710
  }
602
- // @note - we can only have one blob config per bundle
603
- // find requests with gas and blob configs
604
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
605
- const gasConfigs = requestsToProcess.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
606
- const blobConfigs = requestsToProcess.filter((request)=>request.blobConfig).map((request)=>request.blobConfig);
607
- if (blobConfigs.length > 1) {
608
- throw new Error('Multiple blob configs found');
609
- }
610
- const blobConfig = blobConfigs[0];
611
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
612
- const gasLimits = gasConfigs.map((g)=>g?.gasLimit).filter((g)=>g !== undefined);
613
- let gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
614
- // Cap at L1 block gas limit so the node accepts the tx ("gas limit too high" otherwise).
615
- const maxGas = MAX_L1_TX_LIMIT;
616
- if (gasLimit !== undefined && gasLimit > maxGas) {
617
- this.log.debug('Capping bundled tx gas limit to L1 max', {
618
- requested: gasLimit,
619
- capped: maxGas
620
- });
621
- gasLimit = maxGas;
622
- }
711
+ // Collect earliest txTimeoutAt across all requests.
712
+ const gasConfigs = validRequests.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
623
713
  const txTimeoutAts = gasConfigs.map((g)=>g?.txTimeoutAt).filter((g)=>g !== undefined);
624
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined; // earliest
625
- const txConfig = {
626
- gasLimit,
627
- txTimeoutAt
628
- };
714
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined;
629
715
  // Sort the requests so that proposals always go first
630
716
  // This ensures the committee gets precomputed correctly
631
717
  validRequests.sort((a, b)=>compareActions(a.action, b.action));
632
718
  try {
719
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
720
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
721
+ if (bundleResult.kind === 'aborted') {
722
+ this.logDroppedInSim(bundleResult.droppedRequests);
723
+ void this.backupDroppedInSim(bundleResult.droppedRequests, currentL2Slot).catch((err)=>this.log.error(`Failed to backup requests dropped in simulation`, err));
724
+ return undefined;
725
+ }
726
+ const { requests, droppedRequests, gasLimit } = bundleResult.kind === 'fallback' ? {
727
+ requests: bundleResult.requests,
728
+ droppedRequests: bundleResult.droppedRequests,
729
+ gasLimit: MAX_L1_TX_LIMIT
730
+ } : bundleResult;
731
+ this.logDroppedInSim(droppedRequests);
732
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
733
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
734
+ const [blobConfig] = requests.filter((r)=>r.blobConfig).map((r)=>r.blobConfig);
735
+ const txConfig = {
736
+ gasLimit,
737
+ txTimeoutAt
738
+ };
633
739
  this.log.debug('Forwarding transactions', {
634
- validRequests: validRequests.map((request)=>request.action),
740
+ requests: requests.map((request)=>request.action),
635
741
  txConfig
636
742
  });
637
- const result = await Multicall3.forward(validRequests.map((request)=>request.request), this.l1TxUtils, txConfig, blobConfig, this.rollupContract.address, this.log);
638
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(validRequests, result);
743
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig, currentL2Slot);
744
+ if (result === undefined) {
745
+ return undefined;
746
+ }
747
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
748
+ const allFailedActions = [
749
+ ...failedActions,
750
+ ...droppedRequests.map((d)=>d.request.action)
751
+ ];
639
752
  return {
640
753
  result,
641
754
  expiredActions,
642
- sentActions: validActions,
755
+ sentActions: requests.map((x)=>x.action),
643
756
  successfulActions,
644
- failedActions
757
+ failedActions: allFailedActions
645
758
  };
646
759
  } catch (err) {
647
760
  const viemError = formatViemError(err);
648
761
  this.log.error(`Failed to publish bundled transactions`, viemError);
762
+ if (err instanceof TimeoutError) {
763
+ const timeoutState = err instanceof L1TxTimeoutError ? err.txState : undefined;
764
+ void (async ()=>{
765
+ // The RPC is likely degraded right after a timeout, so back up without the block number
766
+ // rather than leaking an unhandled rejection.
767
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber().catch(()=>0n);
768
+ this.backupFailedTx({
769
+ id: this.failureRecordId(validRequests.map((r)=>r.action), currentL2Slot),
770
+ failureType: 'timeout',
771
+ request: {
772
+ to: MULTI_CALL_3_ADDRESS,
773
+ data: '0x'
774
+ },
775
+ l1BlockNumber,
776
+ error: {
777
+ message: viemError.message,
778
+ name: 'TimeoutError'
779
+ },
780
+ context: {
781
+ actions: validRequests.map((r)=>r.action),
782
+ requests: validRequests.filter((r)=>r.request.to !== null).map((r)=>({
783
+ action: r.action,
784
+ to: r.request.to,
785
+ data: r.request.data
786
+ })),
787
+ sender: this.getSenderAddress().toString(),
788
+ slot: Number(currentL2Slot)
789
+ },
790
+ timing: this.computeTimingInfo(currentL2Slot),
791
+ gasInfo: timeoutState ? {
792
+ sentGasPriceLadder: timeoutState.gasPriceHistory,
793
+ attempts: timeoutState.attempts,
794
+ gasLimit: timeoutState.gasLimit,
795
+ nonce: timeoutState.nonce
796
+ } : undefined
797
+ }, {
798
+ captureFeeSummary: true,
799
+ targetSlot: currentL2Slot
800
+ });
801
+ })();
802
+ }
649
803
  return undefined;
650
804
  } finally{
651
805
  try {
@@ -655,49 +809,302 @@ export class SequencerPublisher {
655
809
  }
656
810
  }
657
811
  }
658
- callbackBundledTransactions(requests, result) {
659
- const actionsListStr = requests.map((r)=>r.action).join(', ');
660
- if (result instanceof FormattedViemError) {
661
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
662
- return {
663
- failedActions: requests.map((r)=>r.action)
664
- };
665
- } else {
666
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
667
- result,
668
- requests
812
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */ logDroppedInSim(dropped) {
813
+ for (const drop of dropped){
814
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
815
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
816
+ action: drop.request.action,
817
+ revertReason: revertReasonDecoded ?? drop.returnData,
818
+ revertReasonDecoded,
819
+ returnData: drop.returnData
669
820
  });
670
- const successfulActions = [];
671
- const failedActions = [];
672
- for (const request of requests){
673
- if (request.checkSuccess(request.request, result)) {
674
- successfulActions.push(request.action);
675
- } else {
676
- failedActions.push(request.action);
821
+ }
822
+ }
823
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */ async backupDroppedInSim(dropped, targetSlot) {
824
+ if (dropped.length === 0) {
825
+ return;
826
+ }
827
+ // Invoked as `void backupDroppedInSim(...)` on the publish path, so it must not throw.
828
+ try {
829
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
830
+ // Every dropped entry failed in the same slot against the same L1 fee conditions, so capture
831
+ // the fee environment once and share it rather than re-reading the window per entry.
832
+ const sharedFeeSummary = await this.captureFeeEnvironment(targetSlot).catch(()=>undefined);
833
+ const timing = this.computeTimingInfo(targetSlot);
834
+ for (const { request: req } of dropped){
835
+ this.backupFailedTx({
836
+ id: keccak256(req.request.data),
837
+ failureType: 'simulation',
838
+ request: {
839
+ to: req.request.to,
840
+ data: req.request.data
841
+ },
842
+ l1BlockNumber,
843
+ error: {
844
+ message: 'Bundle entry dropped: action reverted in sim'
845
+ },
846
+ context: {
847
+ actions: [
848
+ req.action
849
+ ],
850
+ sender: this.getSenderAddress().toString(),
851
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined
852
+ },
853
+ timing
854
+ }, {
855
+ sharedFeeSummary
856
+ });
857
+ }
858
+ } catch (err) {
859
+ this.log.warn(`Failed to back up dropped-in-sim entries`, err);
860
+ }
861
+ }
862
+ /**
863
+ * Forwards transactions via Multicall3, rotating to the next available publisher if a send
864
+ * failure occurs (i.e. the tx never reached the chain).
865
+ * On-chain reverts and simulation errors are returned as-is without rotation.
866
+ */ async forwardWithPublisherRotation(validRequests, txConfig, blobConfig, targetSlot) {
867
+ if (!txConfig?.gasLimit) {
868
+ throw new Error('gasLimit is required for bundled transactions');
869
+ }
870
+ const txConfigWithGasLimit = txConfig;
871
+ const triedAddresses = [];
872
+ let currentPublisher = this.l1TxUtils;
873
+ while(true){
874
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
875
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
876
+ triedAddresses: triedAddresses.map((a)=>a.toString())
877
+ });
878
+ return undefined;
879
+ }
880
+ triedAddresses.push(currentPublisher.getSenderAddress());
881
+ try {
882
+ const result = await Multicall3.forward(validRequests.map((r)=>r.request), currentPublisher, txConfigWithGasLimit, blobConfig, {
883
+ gasLimitRequired: true
884
+ });
885
+ this.l1TxUtils = currentPublisher;
886
+ return result;
887
+ } catch (err) {
888
+ if (err instanceof TimeoutError) {
889
+ throw err;
890
+ }
891
+ if (err instanceof MulticallForwarderRevertedError) {
892
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
893
+ transactionHash: err.receipt.transactionHash
894
+ });
895
+ this.backupRevertFailure(validRequests, err, currentPublisher, targetSlot);
896
+ return undefined;
897
+ }
898
+ const viemError = formatViemError(err);
899
+ if (!this.getNextPublisher) {
900
+ this.log.error('Failed to publish bundled transactions', viemError);
901
+ this.backupSendFailure(validRequests, viemError, currentPublisher, targetSlot);
902
+ return undefined;
903
+ }
904
+ this.log.warn(`Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`, viemError);
905
+ const nextPublisher = await this.getNextPublisher([
906
+ ...triedAddresses
907
+ ]);
908
+ if (!nextPublisher) {
909
+ this.log.error(`All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`, viemError, {
910
+ triedAddresses: triedAddresses.map((a)=>a.toString())
911
+ });
912
+ this.backupSendFailure(validRequests, viemError, currentPublisher, targetSlot);
913
+ return undefined;
677
914
  }
915
+ currentPublisher = nextPublisher;
678
916
  }
679
- return {
680
- successfulActions,
681
- failedActions
682
- };
683
917
  }
684
918
  }
919
+ /** Backs up an on-chain revert failure to the failed tx store. */ backupRevertFailure(requests, err, publisher, targetSlot) {
920
+ this.backupFailedTx({
921
+ id: err.receipt.transactionHash,
922
+ failureType: 'revert',
923
+ request: {
924
+ to: MULTI_CALL_3_ADDRESS,
925
+ data: '0x'
926
+ },
927
+ l1BlockNumber: err.receipt.blockNumber,
928
+ receipt: {
929
+ transactionHash: err.receipt.transactionHash,
930
+ blockNumber: err.receipt.blockNumber,
931
+ gasUsed: err.receipt.gasUsed,
932
+ status: 'reverted'
933
+ },
934
+ error: {
935
+ message: err.message,
936
+ name: err.name
937
+ },
938
+ context: {
939
+ actions: requests.map((r)=>r.action),
940
+ requests: requests.filter((r)=>r.request.to !== null).map((r)=>({
941
+ action: r.action,
942
+ to: r.request.to,
943
+ data: r.request.data
944
+ })),
945
+ sender: publisher.getSenderAddress().toString(),
946
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined
947
+ },
948
+ gasInfo: err.txState ? {
949
+ sentGasPrice: err.txState.gasPrice,
950
+ gasLimit: err.txState.gasLimit,
951
+ nonce: err.txState.nonce
952
+ } : undefined,
953
+ timing: this.computeTimingInfo(targetSlot)
954
+ }, {
955
+ captureFeeSummary: true,
956
+ targetSlot
957
+ });
958
+ }
959
+ /** Backs up a send failure (tx never reached chain) to the failed tx store. */ backupSendFailure(requests, error, publisher, targetSlot) {
960
+ // If we can't get the block number, still back up without it.
961
+ void this.l1TxUtils.getBlockNumber().catch(()=>0n).then((l1BlockNumber)=>{
962
+ this.backupFailedTx({
963
+ id: this.failureRecordId(requests.map((r)=>r.action), targetSlot),
964
+ failureType: 'send-error',
965
+ request: {
966
+ to: MULTI_CALL_3_ADDRESS,
967
+ data: '0x'
968
+ },
969
+ l1BlockNumber,
970
+ error: {
971
+ message: error.message,
972
+ name: 'name' in error ? error.name : undefined
973
+ },
974
+ context: {
975
+ actions: requests.map((r)=>r.action),
976
+ requests: requests.filter((r)=>r.request.to !== null).map((r)=>({
977
+ action: r.action,
978
+ to: r.request.to,
979
+ data: r.request.data
980
+ })),
981
+ sender: publisher.getSenderAddress().toString(),
982
+ slot: targetSlot !== undefined ? Number(targetSlot) : undefined
983
+ },
984
+ timing: this.computeTimingInfo(targetSlot)
985
+ }, {
986
+ captureFeeSummary: true,
987
+ targetSlot
988
+ });
989
+ });
990
+ }
991
+ /*
992
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
993
+ */ async sendRequestsAt(targetSlot) {
994
+ await this.waitForTargetSlot(targetSlot);
995
+ if (this.interrupted) {
996
+ return undefined;
997
+ }
998
+ return this.sendRequests(targetSlot);
999
+ }
685
1000
  /**
686
- * @notice Will call `canProposeAtNextEthBlock` to make sure that it is possible to propose
1001
+ * Sleeps until one L1 slot before the L2 slot boundary, and then waits for that L1 block
1002
+ * to be mined, so we don't risk being included in it. If that block never gets mined after
1003
+ * a timeout, we assume it got skipped on L1, so we send the tx anyway.
1004
+ */ async waitForTargetSlot(targetSlot) {
1005
+ const l1Constants = this.epochCache.getL1Constants();
1006
+ const nowInSeconds = this.dateProvider.nowInSeconds();
1007
+ const startOfTargetSlotTs = getTimestampForSlot(targetSlot, l1Constants);
1008
+ const previousL1BlockTs = startOfTargetSlotTs - this.ethereumSlotDuration;
1009
+ const waitDeadlineTs = previousL1BlockTs + BigInt(this.previousL1BlockWaitTimeoutMs / 1000);
1010
+ const logCtx = {
1011
+ targetSlot,
1012
+ startOfTargetSlotTs,
1013
+ nowInSeconds,
1014
+ previousL1BlockTs,
1015
+ waitDeadlineTs
1016
+ };
1017
+ // Check if we are already past time
1018
+ if (nowInSeconds >= startOfTargetSlotTs) {
1019
+ this.log.verbose(`Target slot ${targetSlot} already started, sending requests immediately`, logCtx);
1020
+ return;
1021
+ }
1022
+ // Otherwise we wait
1023
+ this.log.debug(`Waiting for slot ${targetSlot} before sending requests`, logCtx);
1024
+ // Wait until previous L1 block timestamp first
1025
+ const sleepMs = (Number(previousL1BlockTs) - nowInSeconds) * 1000;
1026
+ if (sleepMs > 0 && !this.interrupted) {
1027
+ this.log.trace(`Sleeping ${sleepMs}ms before waiting for previous L1 block`, logCtx);
1028
+ await this.interruptibleSleep.sleep(sleepMs);
1029
+ }
1030
+ // Then loop until we see the previous L1 block, so we know that we cannot be included in it.
1031
+ // We time out after a while, once we are sure that that block is skipped in L1.
1032
+ while(!this.interrupted){
1033
+ try {
1034
+ const nowInSeconds = this.dateProvider.nowInSeconds();
1035
+ logCtx.nowInSeconds = nowInSeconds;
1036
+ if (nowInSeconds >= waitDeadlineTs) {
1037
+ this.log.warn(`Timed out waiting for previous L1 block before sending requests, proceeding`, logCtx);
1038
+ return;
1039
+ }
1040
+ const latestBlockTs = await this.l1TxUtils.getBlock().then((b)=>b.timestamp);
1041
+ if (latestBlockTs >= previousL1BlockTs) {
1042
+ this.log.debug(`Previous L1 block mined, proceeding to send requests`, {
1043
+ ...logCtx,
1044
+ latestBlockTs
1045
+ });
1046
+ return;
1047
+ }
1048
+ this.log.trace(`Previous L1 block not mined yet, continuing to wait`, {
1049
+ ...logCtx,
1050
+ latestBlockTs
1051
+ });
1052
+ } catch (err) {
1053
+ this.log.error(`Error while waiting for previous L1 block before sending requests; retrying`, err, logCtx);
1054
+ } finally{
1055
+ await this.interruptibleSleep.sleep(this.previousL1BlockWaitPollIntervalMs);
1056
+ }
1057
+ }
1058
+ }
1059
+ callbackBundledTransactions(requests, result) {
1060
+ const actionsListStr = requests.map((r)=>r.action).join(', ');
1061
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
1062
+ result,
1063
+ requests: requests.map((r)=>({
1064
+ ...r,
1065
+ // Avoid logging large blob data
1066
+ blobConfig: r.blobConfig ? {
1067
+ ...r.blobConfig,
1068
+ blobs: r.blobConfig.blobs.map((b)=>({
1069
+ size: trimmedBytesLength(b)
1070
+ }))
1071
+ } : undefined
1072
+ }))
1073
+ });
1074
+ const successfulActions = [];
1075
+ const failedActions = [];
1076
+ for (const request of requests){
1077
+ if (request.checkSuccess(request.request, result)) {
1078
+ successfulActions.push(request.action);
1079
+ } else {
1080
+ failedActions.push(request.action);
1081
+ }
1082
+ }
1083
+ return {
1084
+ successfulActions,
1085
+ failedActions
1086
+ };
1087
+ }
1088
+ /**
1089
+ * @notice Will call `canProposeAt` to make sure that it is possible to propose
687
1090
  * @param tipArchive - The archive to check
688
1091
  * @returns The slot and block number if it is possible to propose, undefined otherwise
689
- */ canProposeAtNextEthBlock(tipArchive, msgSender, opts = {}) {
1092
+ */ async canProposeAt(tipArchive, msgSender, simulationOverridesPlan) {
690
1093
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
691
- const ignoredErrors = [
1094
+ // These errors are expected when we cannot actually propose right now — usually because our
1095
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
1096
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
1097
+ // skip the proposal; we do NOT treat these as bugs.
1098
+ const expectedErrors = [
692
1099
  'SlotAlreadyInChain',
693
1100
  'InvalidProposer',
694
1101
  'InvalidArchive'
695
1102
  ];
696
- return this.rollupContract.canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
697
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber
698
- }).catch((err)=>{
699
- if (err instanceof FormattedViemError && ignoredErrors.find((e)=>err.message.includes(e))) {
700
- this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find((e)=>err.message.includes(e))}`, {
1103
+ const slotOffset = this.aztecSlotDuration;
1104
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
1105
+ return this.rollupContract.canProposeAt(tipArchive.toBuffer(), msgSender.toString(), nextL1SlotTs, await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan)).catch((err)=>{
1106
+ if (err instanceof FormattedViemError && expectedErrors.find((e)=>err.message.includes(e))) {
1107
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find((e)=>err.message.includes(e))}`, {
701
1108
  error: err.message
702
1109
  });
703
1110
  } else {
@@ -711,22 +1118,23 @@ export class SequencerPublisher {
711
1118
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
712
1119
  * It will throw if the block header is invalid.
713
1120
  * @param header - The block header to validate
714
- */ async validateBlockHeader(header, opts) {
1121
+ */ async validateBlockHeader(header, simulationOverridesPlan) {
715
1122
  const flags = {
716
1123
  ignoreDA: true,
717
1124
  ignoreSignatures: true
718
1125
  };
719
1126
  const args = [
720
1127
  header.toViem(),
721
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
1128
+ CommitteeAttestationsAndSigners.packAttestations([]),
722
1129
  [],
723
1130
  Signature.empty().toViemSignature(),
724
1131
  `0x${'0'.repeat(64)}`,
725
1132
  header.blobsHash.toString(),
726
1133
  flags
727
1134
  ];
728
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
729
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(opts?.forcePendingCheckpointNumber);
1135
+ const l1Constants = this.epochCache.getL1Constants();
1136
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
1137
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
730
1138
  let balance = 0n;
731
1139
  if (this.config.fishermanMode) {
732
1140
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -748,7 +1156,7 @@ export class SequencerPublisher {
748
1156
  }),
749
1157
  from: MULTI_CALL_3_ADDRESS
750
1158
  }, {
751
- time: ts + 1n
1159
+ time: ts
752
1160
  }, stateOverrides);
753
1161
  this.log.debug(`Simulated validateHeader`);
754
1162
  }
@@ -778,6 +1186,7 @@ export class SequencerPublisher {
778
1186
  ...logData,
779
1187
  request
780
1188
  });
1189
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
781
1190
  try {
782
1191
  const { gasUsed } = await this.l1TxUtils.simulate(request, undefined, undefined, mergeAbis([
783
1192
  request.abi ?? [],
@@ -793,6 +1202,7 @@ export class SequencerPublisher {
793
1202
  gasUsed,
794
1203
  checkpointNumber,
795
1204
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
1205
+ lastArchive: validationResult.checkpoint.lastArchive,
796
1206
  reason
797
1207
  };
798
1208
  } catch (err) {
@@ -805,8 +1215,8 @@ export class SequencerPublisher {
805
1215
  request,
806
1216
  error: viemError.message
807
1217
  });
808
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
809
- if (latestPendingCheckpointNumber < checkpointNumber) {
1218
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
1219
+ if (latestProposedCheckpointNumber < checkpointNumber) {
810
1220
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, {
811
1221
  ...logData
812
1222
  });
@@ -820,6 +1230,31 @@ export class SequencerPublisher {
820
1230
  }
821
1231
  // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
822
1232
  this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
1233
+ this.backupFailedTx({
1234
+ id: keccak256(request.data),
1235
+ failureType: 'simulation',
1236
+ request: {
1237
+ to: request.to,
1238
+ data: request.data,
1239
+ value: request.value
1240
+ },
1241
+ l1BlockNumber,
1242
+ error: {
1243
+ message: viemError.message,
1244
+ name: viemError.name
1245
+ },
1246
+ context: {
1247
+ actions: [
1248
+ `invalidate-${reason}`
1249
+ ],
1250
+ checkpointNumber,
1251
+ sender: this.getSenderAddress().toString()
1252
+ },
1253
+ timing: this.computeTimingInfo(this.getCurrentL2Slot())
1254
+ }, {
1255
+ captureFeeSummary: true,
1256
+ targetSlot: this.getCurrentL2Slot()
1257
+ });
823
1258
  throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, {
824
1259
  cause: viemError
825
1260
  });
@@ -835,7 +1270,11 @@ export class SequencerPublisher {
835
1270
  reason
836
1271
  };
837
1272
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
838
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(validationResult.attestations).getPackedAttestations();
1273
+ // Use the exact packed tuple posted to L1 verbatim. A repack via `packAttestations` is not a
1274
+ // byte-faithful inverse of `fromPacked` (a canonicalized yParity byte or an all-zero signature slot
1275
+ // round-trips differently), so it would diverge from the stored `attestationsHash` and revert the
1276
+ // invalidation.
1277
+ const attestationsAndSigners = validationResult.verbatimAttestations;
839
1278
  if (reason === 'invalid-attestation') {
840
1279
  return this.rollupContract.buildInvalidateBadAttestationRequest(checkpoint.checkpointNumber, attestationsAndSigners, committee, validationResult.invalidIndex);
841
1280
  } else if (reason === 'insufficient-attestations') {
@@ -845,28 +1284,7 @@ export class SequencerPublisher {
845
1284
  throw new Error(`Unknown reason for invalidation`);
846
1285
  }
847
1286
  }
848
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */ async validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, options) {
849
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
850
- const blobFields = checkpoint.toBlobFields();
851
- const blobs = await getBlobsPerL1Block(blobFields);
852
- const blobInput = getPrefixedEthBlobCommitments(blobs);
853
- const args = [
854
- {
855
- header: checkpoint.header.toViem(),
856
- archive: toHex(checkpoint.archive.root.toBuffer()),
857
- oracleInput: {
858
- feeAssetPriceModifier: checkpoint.feeAssetPriceModifier
859
- }
860
- },
861
- attestationsAndSigners.getPackedAttestations(),
862
- attestationsAndSigners.getSigners().map((signer)=>signer.toString()),
863
- attestationsAndSignersSignature.toViemSignature(),
864
- blobInput
865
- ];
866
- await this.simulateProposeTx(args, ts, options);
867
- return ts;
868
- }
869
- async enqueueCastSignalHelper(slotNumber, timestamp, signalType, payload, base, signerAddress, signer) {
1287
+ async enqueueCastSignalHelper(slotNumber, signalType, payload, base, signerAddress, signer) {
870
1288
  if (this.lastActions[signalType] && this.lastActions[signalType] === slotNumber) {
871
1289
  this.log.debug(`Skipping duplicate vote cast signal ${signalType} for slot ${slotNumber}`);
872
1290
  return false;
@@ -878,6 +1296,17 @@ export class SequencerPublisher {
878
1296
  this.log.warn(`Cannot enqueue vote cast signal ${signalType} for address zero at slot ${slotNumber}`);
879
1297
  return false;
880
1298
  }
1299
+ const canonicalRollup = await base.getRollupAddress();
1300
+ if (!canonicalRollup.equals(EthAddress.fromString(this.rollupContract.address))) {
1301
+ this.log.warn(`Rollup ${this.rollupContract.address} is not canonical, skipping governance signal`, {
1302
+ slotNumber,
1303
+ signalType,
1304
+ canonicalRollup,
1305
+ targetRollup: this.rollupContract.address,
1306
+ payload: payload.toString()
1307
+ });
1308
+ return false;
1309
+ }
881
1310
  const round = await base.computeRound(slotNumber);
882
1311
  const roundInfo = await base.getRoundInfo(this.rollupContract.address, round);
883
1312
  if (roundInfo.quorumReached) {
@@ -886,30 +1315,40 @@ export class SequencerPublisher {
886
1315
  if (roundInfo.lastSignalSlot >= slotNumber) {
887
1316
  return false;
888
1317
  }
889
- if (await this.isPayloadEmpty(payload)) {
1318
+ if (await base.isPayloadEmpty(payload)) {
890
1319
  this.log.warn(`Skipping vote cast for payload with empty code`);
891
1320
  return false;
892
1321
  }
893
- // Check if payload was already submitted to governance
894
- const cacheKey = payload.toString();
895
- if (!this.payloadProposedCache.has(cacheKey)) {
896
- try {
897
- const l1StartBlock = await this.rollupContract.getL1StartBlock();
898
- const proposed = await retry(()=>base.hasPayloadBeenProposed(payload.toString(), l1StartBlock), 'Check if payload was proposed', makeBackoff([
899
- 0,
900
- 1,
901
- 2
902
- ]), this.log, true);
903
- if (proposed) {
904
- this.payloadProposedCache.add(cacheKey);
905
- }
906
- } catch (err) {
907
- this.log.warn(`Failed to check if payload ${payload} was proposed after retries, skipping signal`, err);
908
- return false;
909
- }
1322
+ // Classify the payload against the Governance proposal history so we stop signalling once its
1323
+ // proposal is live or was already executed, while still re-signalling one whose proposal was
1324
+ // merely rejected/dropped/expired.
1325
+ let status = 'none';
1326
+ try {
1327
+ status = await base.getPayloadProposalStatus(payload.toString());
1328
+ } catch (err) {
1329
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
1330
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
1331
+ // participation entirely; failing open at worst produces a duplicate signal that the
1332
+ // contract will simply count alongside others in the round.
1333
+ this.log.error(`Failed to check governance proposal status for payload ${payload} (signalling anyway)`, err, {
1334
+ slotNumber,
1335
+ signalType
1336
+ });
910
1337
  }
911
- if (this.payloadProposedCache.has(cacheKey)) {
912
- this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
1338
+ if (status === 'live') {
1339
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`, {
1340
+ slotNumber,
1341
+ signalType,
1342
+ payload: payload.toString()
1343
+ });
1344
+ return false;
1345
+ }
1346
+ if (status === 'executed' && !this.config.governanceProposerForcePayloadVote) {
1347
+ this.log.info(`Payload ${payload} was executed by governance within lookback, stopping signals ` + `(set GOVERNANCE_PROPOSER_FORCE_PAYLOAD_VOTE to re-signal)`, {
1348
+ slotNumber,
1349
+ signalType,
1350
+ payload: payload.toString()
1351
+ });
913
1352
  return false;
914
1353
  }
915
1354
  const cachedLastVote = this.lastActions[signalType];
@@ -922,30 +1361,17 @@ export class SequencerPublisher {
922
1361
  signer: this.l1TxUtils.client.account?.address,
923
1362
  lastValidL2Slot: slotNumber
924
1363
  });
925
- try {
926
- await this.l1TxUtils.simulate(request, {
927
- time: timestamp
928
- }, [], mergeAbis([
929
- request.abi ?? [],
930
- ErrorsAbi
931
- ]));
932
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, {
933
- request
934
- });
935
- } catch (err) {
936
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, err);
937
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
938
- }
939
1364
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
940
1365
  this.addRequest({
941
- gasConfig: {
942
- gasLimit: SequencerPublisher.VOTE_GAS_GUESS
943
- },
944
1366
  action,
945
1367
  request,
946
1368
  lastValidL2Slot: slotNumber,
947
1369
  checkSuccess: (_request, result)=>{
948
- const success = result && result.receipt && result.receipt.status === 'success' && tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
1370
+ const success = result && extractEventSuccess(result.receipt, {
1371
+ address: base.address.toString(),
1372
+ abi: EmpireBaseAbi,
1373
+ eventName: 'SignalCast'
1374
+ });
949
1375
  const logData = {
950
1376
  ...result,
951
1377
  slotNumber,
@@ -964,68 +1390,70 @@ export class SequencerPublisher {
964
1390
  });
965
1391
  return true;
966
1392
  }
967
- async isPayloadEmpty(payload) {
968
- const key = payload.toString();
969
- const cached = this.isPayloadEmptyCache.get(key);
970
- if (cached) {
971
- return cached;
972
- }
973
- const isEmpty = !await this.l1TxUtils.getCode(payload);
974
- this.isPayloadEmptyCache.set(key, isEmpty);
975
- return isEmpty;
976
- }
977
1393
  /**
978
1394
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
979
1395
  * @param slotNumber - The slot number to cast a signal for.
980
- * @param timestamp - The timestamp of the slot to cast a signal for.
981
1396
  * @returns True if the signal was successfully enqueued, false otherwise.
982
- */ enqueueGovernanceCastSignal(governancePayload, slotNumber, timestamp, signerAddress, signer) {
983
- return this.enqueueCastSignalHelper(slotNumber, timestamp, 'governance-signal', governancePayload, this.govProposerContract, signerAddress, signer);
1397
+ */ enqueueGovernanceCastSignal(governancePayload, slotNumber, signerAddress, signer) {
1398
+ return this.enqueueCastSignalHelper(slotNumber, 'governance-signal', governancePayload, this.govProposerContract, signerAddress, signer);
984
1399
  }
985
- /** Enqueues all slashing actions as returned by the slasher client. */ async enqueueSlashingActions(actions, slotNumber, timestamp, signerAddress, signer) {
1400
+ /**
1401
+ * Enqueues a `prune()` transaction if the rollup is prunable at the given slot's L1 timestamp.
1402
+ * `prune()` is permissionless and idempotent — if the chain is no longer prunable by send time the
1403
+ * bundle simulation usually drops the entry; on a node without `eth_simulateV1` the bundle is sent
1404
+ * as-is and the prune reverts `Rollup__NothingToPrune` inside `aggregate3(allowFailure: true)`
1405
+ * (a failed action, never a whole-tx revert). Used by the failed-sync fallback so a stuck pending
1406
+ * chain (e.g. bad data blocking sync) can be wound back to recover.
1407
+ * @returns true if a prune request was enqueued, false otherwise.
1408
+ */ async enqueuePruneIfPrunable(slotNumber) {
1409
+ if (this.lastActions['prune'] === slotNumber) {
1410
+ this.log.debug(`Skipping duplicate prune for slot ${slotNumber}`, {
1411
+ slotNumber
1412
+ });
1413
+ return false;
1414
+ }
1415
+ // Use the SAME timestamp the bundle simulator overrides block.timestamp with at send time
1416
+ // (sequencer-bundle-simulator.ts) so this upfront check and the send-time sim agree. Slot-start
1417
+ // and last-L1-slot both fall within the same L2 slot (and epoch, which is what `canPruneAtTime`
1418
+ // derives), so they agree today; matching the simulator keeps it robust if the contract ever uses
1419
+ // the timestamp more granularly.
1420
+ const ts = getLastL1SlotTimestampForL2Slot(slotNumber, this.epochCache.getL1Constants());
1421
+ const canPrune = await this.rollupContract.canPruneAtTime(ts).catch((err)=>{
1422
+ this.log.error(`Failed to check canPruneAtTime for slot ${slotNumber}`, err, {
1423
+ slotNumber
1424
+ });
1425
+ return false;
1426
+ });
1427
+ if (!canPrune) {
1428
+ this.log.debug(`Rollup not prunable at slot ${slotNumber}`, {
1429
+ slotNumber
1430
+ });
1431
+ return false;
1432
+ }
1433
+ const request = {
1434
+ to: this.rollupContract.address,
1435
+ data: encodeFunctionData({
1436
+ abi: RollupAbi,
1437
+ functionName: 'prune',
1438
+ args: []
1439
+ })
1440
+ };
1441
+ this.log.info(`Enqueuing rollup prune for slot ${slotNumber}`, {
1442
+ slotNumber
1443
+ });
1444
+ return this.enqueueRequest('prune', request, {
1445
+ address: this.rollupContract.address,
1446
+ abi: RollupAbi,
1447
+ eventName: 'PrunedPending'
1448
+ }, slotNumber);
1449
+ }
1450
+ /** Enqueues all slashing actions as returned by the slasher client. */ async enqueueSlashingActions(actions, slotNumber, signerAddress, signer) {
986
1451
  if (actions.length === 0) {
987
1452
  this.log.debug(`No slashing actions to enqueue for slot ${slotNumber}`);
988
1453
  return false;
989
1454
  }
990
1455
  for (const action of actions){
991
1456
  switch(action.type){
992
- case 'vote-empire-payload':
993
- {
994
- if (this.slashingProposerContract?.type !== 'empire') {
995
- this.log.error('Cannot vote for empire payload on non-empire slashing contract');
996
- break;
997
- }
998
- this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
999
- signerAddress
1000
- });
1001
- await this.enqueueCastSignalHelper(slotNumber, timestamp, 'empire-slashing-signal', action.payload, this.slashingProposerContract, signerAddress, signer);
1002
- break;
1003
- }
1004
- case 'create-empire-payload':
1005
- {
1006
- this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, {
1007
- slotNumber,
1008
- signerAddress
1009
- });
1010
- const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
1011
- await this.simulateAndEnqueueRequest('create-empire-payload', request, (receipt)=>!!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs), slotNumber, timestamp);
1012
- break;
1013
- }
1014
- case 'execute-empire-payload':
1015
- {
1016
- this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, {
1017
- slotNumber,
1018
- signerAddress
1019
- });
1020
- if (this.slashingProposerContract?.type !== 'empire') {
1021
- this.log.error('Cannot execute slashing payload on non-empire slashing contract');
1022
- return false;
1023
- }
1024
- const empireSlashingProposer = this.slashingProposerContract;
1025
- const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
1026
- await this.simulateAndEnqueueRequest('execute-empire-payload', request, (receipt)=>!!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs), slotNumber, timestamp);
1027
- break;
1028
- }
1029
1457
  case 'vote-offenses':
1030
1458
  {
1031
1459
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
@@ -1034,14 +1462,17 @@ export class SequencerPublisher {
1034
1462
  votesCount: action.votes.length,
1035
1463
  signerAddress
1036
1464
  });
1037
- if (this.slashingProposerContract?.type !== 'tally') {
1038
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1465
+ if (!this.slashingProposerContract) {
1466
+ this.log.error('No slashing proposer contract available');
1039
1467
  return false;
1040
1468
  }
1041
- const tallySlashingProposer = this.slashingProposerContract;
1042
1469
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1043
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
1044
- await this.simulateAndEnqueueRequest('vote-offenses', request, (receipt)=>!!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs), slotNumber, timestamp);
1470
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1471
+ this.enqueueRequest('vote-offenses', request, {
1472
+ address: this.slashingProposerContract.address.toString(),
1473
+ abi: SlashingProposerAbi,
1474
+ eventName: 'VoteCast'
1475
+ }, slotNumber);
1045
1476
  break;
1046
1477
  }
1047
1478
  case 'execute-slash':
@@ -1051,13 +1482,16 @@ export class SequencerPublisher {
1051
1482
  round: action.round,
1052
1483
  signerAddress
1053
1484
  });
1054
- if (this.slashingProposerContract?.type !== 'tally') {
1055
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1485
+ if (!this.slashingProposerContract) {
1486
+ this.log.error('No slashing proposer contract available');
1056
1487
  return false;
1057
1488
  }
1058
- const tallySlashingProposer = this.slashingProposerContract;
1059
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
1060
- await this.simulateAndEnqueueRequest('execute-slash', request, (receipt)=>!!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs), slotNumber, timestamp);
1489
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(action.round, action.committees);
1490
+ this.enqueueRequest('execute-slash', executeRequest, {
1491
+ address: this.slashingProposerContract.address.toString(),
1492
+ abi: SlashingProposerAbi,
1493
+ eventName: 'RoundExecuted'
1494
+ }, slotNumber);
1061
1495
  break;
1062
1496
  }
1063
1497
  default:
@@ -1069,7 +1503,7 @@ export class SequencerPublisher {
1069
1503
  }
1070
1504
  return true;
1071
1505
  }
1072
- /** Simulates and enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1506
+ /** Enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1073
1507
  const checkpointHeader = checkpoint.header;
1074
1508
  const blobFields = checkpoint.toBlobFields();
1075
1509
  const blobs = await getBlobsPerL1Block(blobFields);
@@ -1081,52 +1515,38 @@ export class SequencerPublisher {
1081
1515
  attestationsAndSignersSignature,
1082
1516
  feeAssetPriceModifier: checkpoint.feeAssetPriceModifier
1083
1517
  };
1084
- let ts;
1085
- try {
1086
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
1087
- // This means that we can avoid the simulation issues in later checks.
1088
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
1089
- // make time consistency checks break.
1090
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
1091
- ts = await this.validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts);
1092
- } catch (err) {
1093
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
1094
- ...checkpoint.getStats(),
1095
- slotNumber: checkpoint.header.slotNumber,
1096
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber
1097
- });
1098
- throw err;
1099
- }
1100
1518
  this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1101
1519
  ...checkpoint.toCheckpointInfo(),
1102
- ...opts
1520
+ txTimeoutAt: opts.txTimeoutAt
1521
+ });
1522
+ await this.addProposeTx(checkpoint, proposeTxArgs, {
1523
+ txTimeoutAt: opts.txTimeoutAt
1103
1524
  });
1104
- await this.addProposeTx(checkpoint, proposeTxArgs, opts, ts);
1105
1525
  }
1106
1526
  enqueueInvalidateCheckpoint(request, opts = {}) {
1107
1527
  if (!request) {
1108
1528
  return;
1109
1529
  }
1110
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1111
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(request.gasUsed) * 64 / 63)));
1112
1530
  const { gasUsed, checkpointNumber } = request;
1113
1531
  const logData = {
1114
1532
  gasUsed,
1115
1533
  checkpointNumber,
1116
- gasLimit,
1117
1534
  opts
1118
1535
  };
1119
1536
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1120
1537
  this.addRequest({
1121
1538
  action: `invalidate-by-${request.reason}`,
1122
1539
  request: request.request,
1123
- gasConfig: {
1124
- gasLimit,
1540
+ gasConfig: opts.txTimeoutAt ? {
1125
1541
  txTimeoutAt: opts.txTimeoutAt
1126
- },
1542
+ } : undefined,
1127
1543
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1128
1544
  checkSuccess: (_req, result)=>{
1129
- const success = result && result.receipt && result.receipt.status === 'success' && tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1545
+ const success = result && extractEventSuccess(result.receipt, {
1546
+ address: this.rollupContract.address,
1547
+ abi: RollupAbi,
1548
+ eventName: 'CheckpointInvalidated'
1549
+ });
1130
1550
  if (!success) {
1131
1551
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, {
1132
1552
  ...result,
@@ -1142,67 +1562,36 @@ export class SequencerPublisher {
1142
1562
  }
1143
1563
  });
1144
1564
  }
1145
- async simulateAndEnqueueRequest(action, request, checkSuccess, slotNumber, timestamp) {
1146
- const logData = {
1147
- slotNumber,
1148
- timestamp,
1149
- gasLimit: undefined
1150
- };
1565
+ /**
1566
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1567
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1568
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1569
+ */ enqueueRequest(action, request, eventOpts, slotNumber) {
1151
1570
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1152
1571
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1153
1572
  return false;
1154
1573
  }
1155
1574
  const cachedLastActionSlot = this.lastActions[action];
1156
1575
  this.lastActions[action] = slotNumber;
1157
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1158
- let gasUsed;
1159
- const simulateAbi = mergeAbis([
1160
- request.abi ?? [],
1161
- ErrorsAbi
1162
- ]);
1163
- try {
1164
- ({ gasUsed } = await this.l1TxUtils.simulate(request, {
1165
- time: timestamp
1166
- }, [], simulateAbi)); // TODO(palla/slash): Check the timestamp logic
1167
- this.log.verbose(`Simulation for ${action} succeeded`, {
1168
- ...logData,
1169
- request,
1170
- gasUsed
1171
- });
1172
- } catch (err) {
1173
- const viemError = formatViemError(err, simulateAbi);
1174
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1175
- return false;
1176
- }
1177
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1178
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(gasUsed) * 64 / 63)));
1179
- logData.gasLimit = gasLimit;
1180
- // Store the ABI used for simulation on the request so Multicall3.forward can decode errors
1181
- // when the tx is sent and a revert is diagnosed via simulation.
1182
- const requestWithAbi = {
1183
- ...request,
1184
- abi: simulateAbi
1185
- };
1186
- this.log.debug(`Enqueuing ${action}`, logData);
1576
+ this.log.debug(`Enqueuing ${action}`, {
1577
+ slotNumber
1578
+ });
1187
1579
  this.addRequest({
1188
1580
  action,
1189
- request: requestWithAbi,
1190
- gasConfig: {
1191
- gasLimit
1192
- },
1581
+ request,
1193
1582
  lastValidL2Slot: slotNumber,
1194
- checkSuccess: (_req, result)=>{
1195
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1583
+ checkSuccess: (_request, result)=>{
1584
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1196
1585
  if (!success) {
1197
1586
  this.log.warn(`Action ${action} at ${slotNumber} failed`, {
1198
1587
  ...result,
1199
- ...logData
1588
+ slotNumber
1200
1589
  });
1201
1590
  this.lastActions[action] = cachedLastActionSlot;
1202
1591
  } else {
1203
1592
  this.log.info(`Action ${action} at ${slotNumber} succeeded`, {
1204
1593
  ...result,
1205
- ...logData
1594
+ slotNumber
1206
1595
  });
1207
1596
  }
1208
1597
  return !!success;
@@ -1217,13 +1606,14 @@ export class SequencerPublisher {
1217
1606
  * A call to `restart` is required before you can continue publishing.
1218
1607
  */ interrupt() {
1219
1608
  this.interrupted = true;
1609
+ this.interruptibleSleep.interrupt();
1220
1610
  this.l1TxUtils.interrupt();
1221
1611
  }
1222
1612
  /** Restarts the publisher after calling `interrupt`. */ restart() {
1223
1613
  this.interrupted = false;
1224
1614
  this.l1TxUtils.restart();
1225
1615
  }
1226
- async prepareProposeTx(encodedData, timestamp, options) {
1616
+ async prepareProposeTx(encodedData) {
1227
1617
  const kzg = Blob.getViemKzgInstance();
1228
1618
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1229
1619
  this.log.debug('Validating blob input', {
@@ -1237,7 +1627,11 @@ export class SequencerPublisher {
1237
1627
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1238
1628
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1239
1629
  } else {
1240
- // Normal mode - use estimateGas with blob inputs
1630
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1631
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1632
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1633
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1634
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1241
1635
  blobEvaluationGas = await this.l1TxUtils.estimateGas(this.getSenderAddress().toString(), {
1242
1636
  to: this.rollupContract.address,
1243
1637
  data: encodeFunctionData({
@@ -1250,10 +1644,42 @@ export class SequencerPublisher {
1250
1644
  }, {}, {
1251
1645
  blobs: encodedData.blobs.map((b)=>b.data),
1252
1646
  kzg
1253
- }).catch((err)=>{
1254
- const { message, metaMessages } = formatViemError(err);
1255
- this.log.error(`Failed to validate blobs`, message, {
1256
- metaMessages
1647
+ }).catch(async (err)=>{
1648
+ const viemError = formatViemError(err);
1649
+ this.log.error(`Failed to validate blobs`, viemError.message, {
1650
+ metaMessages: viemError.metaMessages
1651
+ });
1652
+ const validateBlobsData = encodeFunctionData({
1653
+ abi: RollupAbi,
1654
+ functionName: 'validateBlobs',
1655
+ args: [
1656
+ blobInput
1657
+ ]
1658
+ });
1659
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1660
+ this.backupFailedTx({
1661
+ id: keccak256(validateBlobsData),
1662
+ failureType: 'simulation',
1663
+ request: {
1664
+ to: this.rollupContract.address,
1665
+ data: validateBlobsData
1666
+ },
1667
+ blobData: encodedData.blobs.map((b)=>toHex(b.data)),
1668
+ l1BlockNumber,
1669
+ error: {
1670
+ message: viemError.message,
1671
+ name: viemError.name
1672
+ },
1673
+ context: {
1674
+ actions: [
1675
+ 'validate-blobs'
1676
+ ],
1677
+ sender: this.getSenderAddress().toString()
1678
+ },
1679
+ timing: this.computeTimingInfo(this.getCurrentL2Slot())
1680
+ }, {
1681
+ captureFeeSummary: true,
1682
+ targetSlot: this.getCurrentL2Slot()
1257
1683
  });
1258
1684
  throw new Error('Failed to validate blobs');
1259
1685
  });
@@ -1272,88 +1698,23 @@ export class SequencerPublisher {
1272
1698
  encodedData.attestationsAndSignersSignature.toViemSignature(),
1273
1699
  blobInput
1274
1700
  ];
1275
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1276
- return {
1277
- args,
1278
- blobEvaluationGas,
1279
- rollupData,
1280
- simulationResult
1281
- };
1282
- }
1283
- /**
1284
- * Simulates the propose tx with eth_simulateV1
1285
- * @param args - The propose tx args
1286
- * @param timestamp - The timestamp to simulate proposal at
1287
- * @returns The simulation result
1288
- */ async simulateProposeTx(args, timestamp, options) {
1289
1701
  const rollupData = encodeFunctionData({
1290
1702
  abi: RollupAbi,
1291
1703
  functionName: 'propose',
1292
1704
  args
1293
1705
  });
1294
- // override the pending checkpoint number if requested
1295
- const forcePendingCheckpointNumberStateDiff = (options.forcePendingCheckpointNumber !== undefined ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber) : []).flatMap((override)=>override.stateDiff ?? []);
1296
- const stateOverrides = [
1297
- {
1298
- address: this.rollupContract.address,
1299
- // @note we override checkBlob to false since blobs are not part simulate()
1300
- stateDiff: [
1301
- {
1302
- slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true),
1303
- value: toPaddedHex(0n, true)
1304
- },
1305
- ...forcePendingCheckpointNumberStateDiff
1306
- ]
1307
- }
1308
- ];
1309
- // In fisherman mode, simulate as the proposer but with sufficient balance
1310
- if (this.proposerAddressForSimulation) {
1311
- stateOverrides.push({
1312
- address: this.proposerAddressForSimulation.toString(),
1313
- balance: 10n * WEI_CONST * WEI_CONST
1314
- });
1315
- }
1316
- const simulationResult = await this.l1TxUtils.simulate({
1317
- to: this.rollupContract.address,
1318
- data: rollupData,
1319
- gas: MAX_L1_TX_LIMIT,
1320
- ...this.proposerAddressForSimulation && {
1321
- from: this.proposerAddressForSimulation.toString()
1322
- }
1323
- }, {
1324
- // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
1325
- time: timestamp + 1n,
1326
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1327
- gasLimit: MAX_L1_TX_LIMIT * 2n
1328
- }, stateOverrides, RollupAbi, {
1329
- // @note fallback gas estimate to use if the node doesn't support simulation API
1330
- fallbackGasEstimate: MAX_L1_TX_LIMIT
1331
- }).catch((err)=>{
1332
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1333
- const viemError = formatViemError(err);
1334
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1335
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1336
- // Return a minimal simulation result with the fallback gas estimate
1337
- return {
1338
- gasUsed: MAX_L1_TX_LIMIT,
1339
- logs: []
1340
- };
1341
- }
1342
- this.log.error(`Failed to simulate propose tx`, viemError);
1343
- throw err;
1344
- });
1345
1706
  return {
1346
- rollupData,
1347
- simulationResult
1707
+ args,
1708
+ blobEvaluationGas,
1709
+ rollupData
1348
1710
  };
1349
1711
  }
1350
- async addProposeTx(checkpoint, encodedData, opts = {}, timestamp) {
1712
+ async addProposeTx(checkpoint, encodedData, opts = {}) {
1351
1713
  const slot = checkpoint.header.slotNumber;
1352
1714
  const timer = new Timer();
1353
1715
  const kzg = Blob.getViemKzgInstance();
1354
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, timestamp, opts);
1716
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1355
1717
  const startBlock = await this.l1TxUtils.getBlockNumber();
1356
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(simulationResult.gasUsed) * 64 / 63)) + blobEvaluationGas + SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS);
1357
1718
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1358
1719
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
1359
1720
  void Promise.resolve().then(()=>this.blobClient.sendBlobsToFilestore(encodedData.blobs).catch((_err)=>{
@@ -1367,9 +1728,10 @@ export class SequencerPublisher {
1367
1728
  },
1368
1729
  lastValidL2Slot: checkpoint.header.slotNumber,
1369
1730
  gasConfig: {
1370
- ...opts,
1371
- gasLimit
1731
+ txTimeoutAt: opts.txTimeoutAt,
1732
+ gasLimit: undefined
1372
1733
  },
1734
+ blobEvaluationGas,
1373
1735
  blobConfig: {
1374
1736
  blobs: encodedData.blobs.map((b)=>b.data),
1375
1737
  kzg
@@ -1379,7 +1741,11 @@ export class SequencerPublisher {
1379
1741
  return false;
1380
1742
  }
1381
1743
  const { receipt, stats, errorMsg } = result;
1382
- const success = receipt && receipt.status === 'success' && tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1744
+ const success = extractEventSuccess(receipt, {
1745
+ address: this.rollupContract.address,
1746
+ abi: RollupAbi,
1747
+ eventName: 'CheckpointProposed'
1748
+ });
1383
1749
  if (success) {
1384
1750
  const endBlock = receipt.blockNumber;
1385
1751
  const inclusionBlocks = Number(endBlock - startBlock);
@@ -1416,4 +1782,8 @@ export class SequencerPublisher {
1416
1782
  }
1417
1783
  });
1418
1784
  }
1785
+ /** Returns the timestamp of the next L1 slot boundary after now. */ getNextL1SlotTimestamp() {
1786
+ const l1Constants = this.epochCache.getL1Constants();
1787
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1788
+ }
1419
1789
  }