@aztec/sequencer-client 0.0.1-commit.b2a5d0dd1 → 0.0.1-commit.b3d3157a

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 (75) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +3 -3
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +6 -6
  5. package/dest/config.d.ts +6 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +33 -10
  8. package/dest/global_variable_builder/fee_provider.js +1 -1
  9. package/dest/global_variable_builder/global_builder.d.ts +2 -3
  10. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  11. package/dest/global_variable_builder/global_builder.js +1 -1
  12. package/dest/index.d.ts +2 -2
  13. package/dest/index.d.ts.map +1 -1
  14. package/dest/index.js +1 -1
  15. package/dest/publisher/config.d.ts +3 -3
  16. package/dest/publisher/config.d.ts.map +1 -1
  17. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  18. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  19. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  20. package/dest/publisher/sequencer-publisher.d.ts +36 -36
  21. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  22. package/dest/publisher/sequencer-publisher.js +271 -500
  23. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  24. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  25. package/dest/sequencer/automine/automine_factory.js +84 -0
  26. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  27. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  28. package/dest/sequencer/automine/automine_sequencer.js +509 -0
  29. package/dest/sequencer/chain_state_overrides.d.ts +52 -16
  30. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -1
  31. package/dest/sequencer/chain_state_overrides.js +86 -27
  32. package/dest/sequencer/checkpoint_proposal_job.d.ts +24 -6
  33. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  34. package/dest/sequencer/checkpoint_proposal_job.js +373 -83
  35. package/dest/sequencer/events.d.ts +42 -2
  36. package/dest/sequencer/events.d.ts.map +1 -1
  37. package/dest/sequencer/index.d.ts +3 -1
  38. package/dest/sequencer/index.d.ts.map +1 -1
  39. package/dest/sequencer/index.js +2 -0
  40. package/dest/sequencer/metrics.d.ts +3 -1
  41. package/dest/sequencer/metrics.d.ts.map +1 -1
  42. package/dest/sequencer/metrics.js +7 -0
  43. package/dest/sequencer/sequencer.d.ts +44 -9
  44. package/dest/sequencer/sequencer.d.ts.map +1 -1
  45. package/dest/sequencer/sequencer.js +256 -79
  46. package/dest/sequencer/timetable.d.ts +3 -6
  47. package/dest/sequencer/timetable.d.ts.map +1 -1
  48. package/dest/sequencer/timetable.js +3 -7
  49. package/dest/sequencer/types.d.ts +2 -2
  50. package/dest/sequencer/types.d.ts.map +1 -1
  51. package/dest/test/utils.d.ts +1 -1
  52. package/dest/test/utils.d.ts.map +1 -1
  53. package/dest/test/utils.js +7 -6
  54. package/package.json +27 -27
  55. package/src/client/sequencer-client.ts +12 -7
  56. package/src/config.ts +38 -10
  57. package/src/global_variable_builder/fee_provider.ts +1 -1
  58. package/src/global_variable_builder/global_builder.ts +2 -3
  59. package/src/index.ts +10 -1
  60. package/src/publisher/config.ts +2 -2
  61. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  62. package/src/publisher/sequencer-publisher.ts +286 -521
  63. package/src/sequencer/README.md +162 -520
  64. package/src/sequencer/automine/README.md +46 -0
  65. package/src/sequencer/automine/automine_factory.ts +145 -0
  66. package/src/sequencer/automine/automine_sequencer.ts +595 -0
  67. package/src/sequencer/chain_state_overrides.ts +133 -58
  68. package/src/sequencer/checkpoint_proposal_job.ts +420 -100
  69. package/src/sequencer/events.ts +46 -2
  70. package/src/sequencer/index.ts +2 -0
  71. package/src/sequencer/metrics.ts +9 -0
  72. package/src/sequencer/sequencer.ts +284 -95
  73. package/src/sequencer/timetable.ts +2 -9
  74. package/src/sequencer/types.ts +1 -1
  75. package/src/test/utils.ts +28 -10
@@ -370,13 +370,12 @@ 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, SimulationOverridesBuilder, buildSimulationOverridesStateOverride } from '@aztec/ethereum/contracts';
375
+ import { FeeAssetPriceOracle, MULTI_CALL_3_ADDRESS, Multicall3, MulticallForwarderRevertedError, buildSimulationOverridesStateOverride } from '@aztec/ethereum/contracts';
376
376
  import { L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
377
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';
378
+ import { FormattedViemError, formatViemError, mergeAbis, tryDecodeRevertReason, tryExtractEvent } from '@aztec/ethereum/utils';
380
379
  import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
381
380
  import { trimmedBytesLength } from '@aztec/foundation/buffer';
382
381
  import { pick } from '@aztec/foundation/collection';
@@ -384,18 +383,28 @@ import { TimeoutError } from '@aztec/foundation/error';
384
383
  import { EthAddress } from '@aztec/foundation/eth-address';
385
384
  import { Signature } from '@aztec/foundation/eth-signature';
386
385
  import { createLogger } from '@aztec/foundation/log';
387
- import { makeBackoff, retry } from '@aztec/foundation/retry';
388
386
  import { InterruptibleSleep } from '@aztec/foundation/sleep';
389
387
  import { bufferToHex } from '@aztec/foundation/string';
390
388
  import { Timer } from '@aztec/foundation/timer';
391
- import { EmpireBaseAbi, ErrorsAbi, RollupAbi } from '@aztec/l1-artifacts';
389
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi, SlashingProposerAbi } from '@aztec/l1-artifacts';
392
390
  import { encodeSlashConsensusVotes } from '@aztec/slasher';
393
391
  import { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
394
- import { getLastL1SlotTimestampForL2Slot, getNextL1SlotTimestamp } from '@aztec/stdlib/epoch-helpers';
392
+ import { getLastL1SlotTimestampForL2Slot, getNextL1SlotTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
395
393
  import { getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
396
- import { encodeFunctionData, keccak256, multicall3Abi, toHex } from 'viem';
394
+ import { encodeFunctionData, keccak256, toHex } from 'viem';
397
395
  import { createL1TxFailedStore } from './l1_tx_failed_store/index.js';
396
+ import { SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
398
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
+ }
399
408
  export const Actions = [
400
409
  'invalidate-by-invalid-attestation',
401
410
  'invalidate-by-insufficient-attestations',
@@ -406,7 +415,7 @@ export const Actions = [
406
415
  ];
407
416
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
408
417
  export const compareActions = (a, b)=>Actions.indexOf(a) - Actions.indexOf(b);
409
- _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader'), _dec2 = trackSpan('SequencerPublisher.validateCheckpointForSubmission');
418
+ _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader');
410
419
  export class SequencerPublisher {
411
420
  config;
412
421
  static{
@@ -420,37 +429,29 @@ export class SequencerPublisher {
420
429
  _dec1,
421
430
  2,
422
431
  "validateBlockHeader"
423
- ],
424
- [
425
- _dec2,
426
- 2,
427
- "validateCheckpointForSubmission"
428
432
  ]
429
433
  ], []));
430
434
  }
431
435
  interrupted;
432
436
  metrics;
437
+ bundleSimulator;
433
438
  epochCache;
434
439
  failedTxStore;
435
- governanceLog;
436
- slashingLog;
440
+ /**
441
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
442
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
443
+ * publisher can route to so any of their custom errors decode against it.
444
+ */ revertDecoderAbi;
437
445
  lastActions;
438
- isPayloadEmptyCache;
439
- payloadProposedCache;
440
446
  log;
441
447
  ethereumSlotDuration;
442
448
  aztecSlotDuration;
443
449
  /** Date provider for wall-clock time. */ dateProvider;
444
450
  blobClient;
445
- /** Address to use for simulations in fisherman mode (actual proposer's address) */ proposerAddressForSimulation;
446
451
  /** Optional callback to obtain a replacement publisher when the current one fails to send. */ getNextPublisher;
447
452
  /** L1 fee analyzer for fisherman mode */ l1FeeAnalyzer;
448
453
  /** Fee asset price oracle for computing price modifiers from Uniswap V4 */ feeAssetPriceOracle;
449
454
  /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */ interruptibleSleep;
450
- // A CALL to a cold address is 2700 gas
451
- static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
452
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
453
- static VOTE_GAS_GUESS = 800_000n;
454
455
  l1TxUtils;
455
456
  rollupContract;
456
457
  govProposerContract;
@@ -460,11 +461,13 @@ export class SequencerPublisher {
460
461
  constructor(config, deps){
461
462
  this.config = config;
462
463
  this.interrupted = (_initProto(this), false);
463
- this.governanceLog = createLogger('sequencer:publisher:governance');
464
- this.slashingLog = createLogger('sequencer:publisher:slashing');
464
+ this.revertDecoderAbi = mergeAbis([
465
+ RollupAbi,
466
+ SlashingProposerAbi,
467
+ EmpireBaseAbi,
468
+ ErrorsAbi
469
+ ]);
465
470
  this.lastActions = {};
466
- this.isPayloadEmptyCache = new Map();
467
- this.payloadProposedCache = new Set();
468
471
  this.interruptibleSleep = new InterruptibleSleep();
469
472
  this.requests = [];
470
473
  this.log = deps.log ?? createLogger('sequencer:publisher');
@@ -490,12 +493,18 @@ export class SequencerPublisher {
490
493
  });
491
494
  // Initialize L1 fee analyzer for fisherman mode
492
495
  if (config.fishermanMode) {
493
- this.l1FeeAnalyzer = new L1FeeAnalyzer(this.l1TxUtils.client, deps.dateProvider, createLogger('sequencer:publisher:fee-analyzer'));
496
+ this.l1FeeAnalyzer = new L1FeeAnalyzer(this.l1TxUtils.client, deps.dateProvider, this.log.createChild('fee-analyzer'));
494
497
  }
495
498
  // Initialize fee asset price oracle
496
- this.feeAssetPriceOracle = new FeeAssetPriceOracle(this.l1TxUtils.client, this.rollupContract, createLogger('sequencer:publisher:price-oracle'));
499
+ this.feeAssetPriceOracle = new FeeAssetPriceOracle(this.l1TxUtils.client, this.rollupContract, this.log.createChild('price-oracle'));
497
500
  // Initialize failed L1 tx store (optional, for test networks)
498
501
  this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
502
+ this.bundleSimulator = new SequencerBundleSimulator({
503
+ getL1TxUtils: ()=>this.l1TxUtils,
504
+ rollupContract: this.rollupContract,
505
+ epochCache: this.epochCache,
506
+ log: this.log.createChild('bundle-simulator')
507
+ });
499
508
  }
500
509
  /**
501
510
  * Backs up a failed L1 transaction to the configured store for debugging.
@@ -518,9 +527,13 @@ export class SequencerPublisher {
518
527
  }
519
528
  /**
520
529
  * Gets the fee asset price modifier from the oracle.
521
- * Returns 0n if the oracle query fails.
522
- */ getFeeAssetPriceModifier() {
523
- return this.feeAssetPriceOracle.computePriceModifier();
530
+ *
531
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
532
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
533
+ * modifier matches the parent L1 will use when applying it.
534
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
535
+ */ getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12) {
536
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
524
537
  }
525
538
  getSenderAddress() {
526
539
  return this.l1TxUtils.getSenderAddress();
@@ -530,12 +543,6 @@ export class SequencerPublisher {
530
543
  */ getL1FeeAnalyzer() {
531
544
  return this.l1FeeAnalyzer;
532
545
  }
533
- /**
534
- * Sets the proposer address to use for simulations in fisherman mode.
535
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
536
- */ setProposerAddressForSimulation(proposerAddress) {
537
- this.proposerAddressForSimulation = proposerAddress;
538
- }
539
546
  addRequest(request) {
540
547
  this.requests.push(request);
541
548
  }
@@ -593,11 +600,15 @@ export class SequencerPublisher {
593
600
  }
594
601
  /**
595
602
  * Sends all requests that are still valid.
603
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
604
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
605
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
606
+ * AutomineSequencer, which publishes synchronously within the current slot.
596
607
  * @returns one of:
597
608
  * - A receipt and stats if the tx succeeded
598
609
  * - a receipt and errorMsg if it failed on L1
599
610
  * - undefined if no valid requests are found OR the tx failed to send.
600
- */ async sendRequests() {
611
+ */ async sendRequests(targetSlot) {
601
612
  const requestsToProcess = [
602
613
  ...this.requests
603
614
  ];
@@ -605,10 +616,9 @@ export class SequencerPublisher {
605
616
  if (this.interrupted || requestsToProcess.length === 0) {
606
617
  return undefined;
607
618
  }
608
- const currentL2Slot = this.getCurrentL2Slot();
619
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
609
620
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
610
621
  const validRequests = requestsToProcess.filter((request)=>request.lastValidL2Slot >= currentL2Slot);
611
- const validActions = validRequests.map((x)=>x.action);
612
622
  const expiredActions = requestsToProcess.filter((request)=>request.lastValidL2Slot < currentL2Slot).map((x)=>x.action);
613
623
  if (validRequests.length !== requestsToProcess.length) {
614
624
  this.log.warn(`Some requests were expired for slot ${currentL2Slot}`, {
@@ -626,71 +636,53 @@ export class SequencerPublisher {
626
636
  this.log.debug(`No valid requests to send`);
627
637
  return undefined;
628
638
  }
629
- // @note - we can only have one blob config per bundle
630
- // find requests with gas and blob configs
631
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
639
+ // Collect earliest txTimeoutAt across all requests.
632
640
  const gasConfigs = validRequests.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
633
- const blobConfigs = validRequests.filter((request)=>request.blobConfig).map((request)=>request.blobConfig);
634
- if (blobConfigs.length > 1) {
635
- throw new Error('Multiple blob configs found');
636
- }
637
- const blobConfig = blobConfigs[0];
638
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
639
- const gasLimits = gasConfigs.map((g)=>g?.gasLimit).filter((g)=>g !== undefined);
640
- let gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
641
- // Cap at L1 block gas limit so the node accepts the tx ("gas limit too high" otherwise).
642
- const maxGas = MAX_L1_TX_LIMIT;
643
- if (gasLimit !== undefined && gasLimit > maxGas) {
644
- this.log.debug('Capping bundled tx gas limit to L1 max', {
645
- requested: gasLimit,
646
- capped: maxGas
647
- });
648
- gasLimit = maxGas;
649
- }
650
641
  const txTimeoutAts = gasConfigs.map((g)=>g?.txTimeoutAt).filter((g)=>g !== undefined);
651
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined; // earliest
652
- const txConfig = {
653
- gasLimit,
654
- txTimeoutAt
655
- };
642
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined;
656
643
  // Sort the requests so that proposals always go first
657
644
  // This ensures the committee gets precomputed correctly
658
645
  validRequests.sort((a, b)=>compareActions(a.action, b.action));
659
646
  try {
660
- // Capture context for failed tx backup before sending
661
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
662
- const multicallData = encodeFunctionData({
663
- abi: multicall3Abi,
664
- functionName: 'aggregate3',
665
- args: [
666
- validRequests.map((r)=>({
667
- target: r.request.to,
668
- callData: r.request.data,
669
- allowFailure: true
670
- }))
671
- ]
672
- });
673
- const blobDataHex = blobConfig?.blobs?.map((b)=>toHex(b));
674
- const txContext = {
675
- multicallData,
676
- blobData: blobDataHex,
677
- l1BlockNumber
647
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
648
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
649
+ if (bundleResult.kind === 'aborted') {
650
+ this.logDroppedInSim(bundleResult.droppedRequests);
651
+ void this.backupDroppedInSim(bundleResult.droppedRequests);
652
+ return undefined;
653
+ }
654
+ const { requests, droppedRequests, gasLimit } = bundleResult.kind === 'fallback' ? {
655
+ requests: bundleResult.requests,
656
+ droppedRequests: bundleResult.droppedRequests,
657
+ gasLimit: MAX_L1_TX_LIMIT
658
+ } : bundleResult;
659
+ this.logDroppedInSim(droppedRequests);
660
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
661
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
662
+ const [blobConfig] = requests.filter((r)=>r.blobConfig).map((r)=>r.blobConfig);
663
+ const txConfig = {
664
+ gasLimit,
665
+ txTimeoutAt
678
666
  };
679
667
  this.log.debug('Forwarding transactions', {
680
- validRequests: validRequests.map((request)=>request.action),
668
+ requests: requests.map((request)=>request.action),
681
669
  txConfig
682
670
  });
683
- const result = await this.forwardWithPublisherRotation(validRequests, txConfig, blobConfig);
671
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
684
672
  if (result === undefined) {
685
673
  return undefined;
686
674
  }
687
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(validRequests, result, txContext);
675
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
676
+ const allFailedActions = [
677
+ ...failedActions,
678
+ ...droppedRequests.map((d)=>d.request.action)
679
+ ];
688
680
  return {
689
681
  result,
690
682
  expiredActions,
691
- sentActions: validActions,
683
+ sentActions: requests.map((x)=>x.action),
692
684
  successfulActions,
693
- failedActions
685
+ failedActions: allFailedActions
694
686
  };
695
687
  } catch (err) {
696
688
  const viemError = formatViemError(err);
@@ -704,23 +696,78 @@ export class SequencerPublisher {
704
696
  }
705
697
  }
706
698
  }
699
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */ logDroppedInSim(dropped) {
700
+ for (const drop of dropped){
701
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
702
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
703
+ action: drop.request.action,
704
+ revertReason: revertReasonDecoded ?? drop.returnData,
705
+ revertReasonDecoded,
706
+ returnData: drop.returnData
707
+ });
708
+ }
709
+ }
710
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */ async backupDroppedInSim(dropped) {
711
+ if (dropped.length === 0) {
712
+ return;
713
+ }
714
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
715
+ for (const { request: req } of dropped){
716
+ this.backupFailedTx({
717
+ id: keccak256(req.request.data),
718
+ failureType: 'simulation',
719
+ request: {
720
+ to: req.request.to,
721
+ data: req.request.data
722
+ },
723
+ l1BlockNumber: l1BlockNumber.toString(),
724
+ error: {
725
+ message: 'Bundle entry dropped: action reverted in sim'
726
+ },
727
+ context: {
728
+ actions: [
729
+ req.action
730
+ ],
731
+ sender: this.getSenderAddress().toString()
732
+ }
733
+ });
734
+ }
735
+ }
707
736
  /**
708
737
  * Forwards transactions via Multicall3, rotating to the next available publisher if a send
709
738
  * failure occurs (i.e. the tx never reached the chain).
710
739
  * On-chain reverts and simulation errors are returned as-is without rotation.
711
740
  */ async forwardWithPublisherRotation(validRequests, txConfig, blobConfig) {
741
+ if (!txConfig?.gasLimit) {
742
+ throw new Error('gasLimit is required for bundled transactions');
743
+ }
744
+ const txConfigWithGasLimit = txConfig;
712
745
  const triedAddresses = [];
713
746
  let currentPublisher = this.l1TxUtils;
714
747
  while(true){
748
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
749
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
750
+ triedAddresses: triedAddresses.map((a)=>a.toString())
751
+ });
752
+ return undefined;
753
+ }
715
754
  triedAddresses.push(currentPublisher.getSenderAddress());
716
755
  try {
717
- const result = await Multicall3.forward(validRequests.map((r)=>r.request), currentPublisher, txConfig, blobConfig, this.rollupContract.address, this.log);
756
+ const result = await Multicall3.forward(validRequests.map((r)=>r.request), currentPublisher, txConfigWithGasLimit, blobConfig, {
757
+ gasLimitRequired: true
758
+ });
718
759
  this.l1TxUtils = currentPublisher;
719
760
  return result;
720
761
  } catch (err) {
721
762
  if (err instanceof TimeoutError) {
722
763
  throw err;
723
764
  }
765
+ if (err instanceof MulticallForwarderRevertedError) {
766
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
767
+ transactionHash: err.receipt.transactionHash
768
+ });
769
+ return undefined;
770
+ }
724
771
  const viemError = formatViemError(err);
725
772
  if (!this.getNextPublisher) {
726
773
  this.log.error('Failed to publish bundled transactions', viemError);
@@ -731,7 +778,9 @@ export class SequencerPublisher {
731
778
  ...triedAddresses
732
779
  ]);
733
780
  if (!nextPublisher) {
734
- this.log.error('All available publishers exhausted, failed to publish bundled transactions');
781
+ this.log.error(`All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`, viemError, {
782
+ triedAddresses: triedAddresses.map((a)=>a.toString())
783
+ });
735
784
  return undefined;
736
785
  }
737
786
  currentPublisher = nextPublisher;
@@ -739,129 +788,63 @@ export class SequencerPublisher {
739
788
  }
740
789
  }
741
790
  /*
742
- * Schedules sending all enqueued requests at (or after) the given timestamp.
791
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
792
+ * Sleeps until one L1 slot before the L2 slot boundary so the tx has a chance of being
793
+ * picked up by the first L1 block of the L2 slot.
794
+ * NB: there is a known correctness risk — being included in the L1 block right before the
795
+ * L2 slot starts would revert propose with HeaderLib__InvalidSlotNumber.
743
796
  * Uses InterruptibleSleep so it can be cancelled via interrupt().
744
- * Returns the promise for the L1 response (caller should NOT await this in the work loop).
745
- */ async sendRequestsAt(submitAfter) {
746
- const ms = submitAfter.getTime() - this.dateProvider.now();
747
- if (ms > 0) {
748
- this.log.debug(`Sleeping ${ms}ms before sending requests`, {
749
- submitAfter
750
- });
751
- await this.interruptibleSleep.sleep(ms);
752
- }
797
+ */ async sendRequestsAt(targetSlot) {
798
+ const l1Constants = this.epochCache.getL1Constants();
799
+ // Start of the target L2 slot, in ms (getTimestampForSlot returns seconds).
800
+ const startOfTargetSlotMs = Number(getTimestampForSlot(targetSlot, l1Constants)) * 1000;
801
+ // Aim to be in the mempool one L1 slot before the L2 slot starts, so we have a chance of
802
+ // being picked up by the first L1 block of the L2 slot.
803
+ const submitAfterMs = startOfTargetSlotMs - Number(this.ethereumSlotDuration) * 1000;
753
804
  if (this.interrupted) {
754
805
  return undefined;
755
806
  }
756
- // Re-validate enqueued requests after the sleep (state may have changed, e.g. prune or L1 reorg)
757
- const validRequests = [];
758
- for (const request of this.requests){
759
- if (!request.preCheck) {
760
- validRequests.push(request);
761
- continue;
762
- }
763
- try {
764
- await request.preCheck();
765
- validRequests.push(request);
766
- } catch (err) {
767
- this.log.warn(`Pre-send validation failed for ${request.action}, discarding request`, err);
768
- }
807
+ const sleepMs = submitAfterMs - this.dateProvider.now();
808
+ if (sleepMs > 0) {
809
+ this.log.debug(`Sleeping ${sleepMs}ms before sending requests`, {
810
+ targetSlot,
811
+ submitAfterMs
812
+ });
813
+ await this.interruptibleSleep.sleep(sleepMs);
769
814
  }
770
- this.requests = validRequests;
771
- if (this.requests.length === 0) {
815
+ if (this.interrupted) {
772
816
  return undefined;
773
817
  }
774
- return this.sendRequests();
818
+ return this.sendRequests(targetSlot);
775
819
  }
776
- callbackBundledTransactions(requests, result, txContext) {
820
+ callbackBundledTransactions(requests, result) {
777
821
  const actionsListStr = requests.map((r)=>r.action).join(', ');
778
- if (result instanceof FormattedViemError) {
779
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
780
- this.backupFailedTx({
781
- id: keccak256(txContext.multicallData),
782
- failureType: 'send-error',
783
- request: {
784
- to: MULTI_CALL_3_ADDRESS,
785
- data: txContext.multicallData
786
- },
787
- blobData: txContext.blobData,
788
- l1BlockNumber: txContext.l1BlockNumber.toString(),
789
- error: {
790
- message: result.message,
791
- name: result.name
792
- },
793
- context: {
794
- actions: requests.map((r)=>r.action),
795
- requests: requests.map((r)=>({
796
- action: r.action,
797
- to: r.request.to,
798
- data: r.request.data
799
- })),
800
- sender: this.getSenderAddress().toString()
801
- }
802
- });
803
- return {
804
- failedActions: requests.map((r)=>r.action)
805
- };
806
- } else {
807
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
808
- result,
809
- requests: requests.map((r)=>({
810
- ...r,
811
- // Avoid logging large blob data
812
- blobConfig: r.blobConfig ? {
813
- ...r.blobConfig,
814
- blobs: r.blobConfig.blobs.map((b)=>({
815
- size: trimmedBytesLength(b)
816
- }))
817
- } : undefined
818
- }))
819
- });
820
- const successfulActions = [];
821
- const failedActions = [];
822
- for (const request of requests){
823
- if (request.checkSuccess(request.request, result)) {
824
- successfulActions.push(request.action);
825
- } else {
826
- failedActions.push(request.action);
827
- }
828
- }
829
- // Single backup for the whole reverted tx
830
- if (failedActions.length > 0 && result?.receipt?.status === 'reverted') {
831
- this.backupFailedTx({
832
- id: result.receipt.transactionHash,
833
- failureType: 'revert',
834
- request: {
835
- to: MULTI_CALL_3_ADDRESS,
836
- data: txContext.multicallData
837
- },
838
- blobData: txContext.blobData,
839
- l1BlockNumber: result.receipt.blockNumber.toString(),
840
- receipt: {
841
- transactionHash: result.receipt.transactionHash,
842
- blockNumber: result.receipt.blockNumber.toString(),
843
- gasUsed: (result.receipt.gasUsed ?? 0n).toString(),
844
- status: 'reverted'
845
- },
846
- error: {
847
- message: result.errorMsg ?? 'Transaction reverted'
848
- },
849
- context: {
850
- actions: failedActions,
851
- requests: requests.filter((r)=>failedActions.includes(r.action)).map((r)=>({
852
- action: r.action,
853
- to: r.request.to,
854
- data: r.request.data
855
- })),
856
- sender: this.getSenderAddress().toString()
857
- }
858
- });
822
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
823
+ result,
824
+ requests: requests.map((r)=>({
825
+ ...r,
826
+ // Avoid logging large blob data
827
+ blobConfig: r.blobConfig ? {
828
+ ...r.blobConfig,
829
+ blobs: r.blobConfig.blobs.map((b)=>({
830
+ size: trimmedBytesLength(b)
831
+ }))
832
+ } : undefined
833
+ }))
834
+ });
835
+ const successfulActions = [];
836
+ const failedActions = [];
837
+ for (const request of requests){
838
+ if (request.checkSuccess(request.request, result)) {
839
+ successfulActions.push(request.action);
840
+ } else {
841
+ failedActions.push(request.action);
859
842
  }
860
- return {
861
- successfulActions,
862
- failedActions
863
- };
864
843
  }
844
+ return {
845
+ successfulActions,
846
+ failedActions
847
+ };
865
848
  }
866
849
  /**
867
850
  * @notice Will call `canProposeAt` to make sure that it is possible to propose
@@ -869,17 +852,20 @@ export class SequencerPublisher {
869
852
  * @returns The slot and block number if it is possible to propose, undefined otherwise
870
853
  */ async canProposeAt(tipArchive, msgSender, simulationOverridesPlan) {
871
854
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
872
- const ignoredErrors = [
855
+ // These errors are expected when we cannot actually propose right now — usually because our
856
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
857
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
858
+ // skip the proposal; we do NOT treat these as bugs.
859
+ const expectedErrors = [
873
860
  'SlotAlreadyInChain',
874
861
  'InvalidProposer',
875
862
  'InvalidArchive'
876
863
  ];
877
- const pipelined = this.epochCache.isProposerPipeliningEnabled();
878
- const slotOffset = pipelined ? this.aztecSlotDuration : 0n;
864
+ const slotOffset = this.aztecSlotDuration;
879
865
  const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
880
866
  return this.rollupContract.canProposeAt(tipArchive.toBuffer(), msgSender.toString(), nextL1SlotTs, await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan)).catch((err)=>{
881
- if (err instanceof FormattedViemError && ignoredErrors.find((e)=>err.message.includes(e))) {
882
- this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find((e)=>err.message.includes(e))}`, {
867
+ if (err instanceof FormattedViemError && expectedErrors.find((e)=>err.message.includes(e))) {
868
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find((e)=>err.message.includes(e))}`, {
883
869
  error: err.message
884
870
  });
885
871
  } else {
@@ -900,14 +886,15 @@ export class SequencerPublisher {
900
886
  };
901
887
  const args = [
902
888
  header.toViem(),
903
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
889
+ CommitteeAttestationsAndSigners.packAttestations([]),
904
890
  [],
905
891
  Signature.empty().toViemSignature(),
906
892
  `0x${'0'.repeat(64)}`,
907
893
  header.blobsHash.toString(),
908
894
  flags
909
895
  ];
910
- const ts = this.getSimulationTimestamp(header.slotNumber);
896
+ const l1Constants = this.epochCache.getL1Constants();
897
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
911
898
  const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
912
899
  let balance = 0n;
913
900
  if (this.config.fishermanMode) {
@@ -1040,7 +1027,7 @@ export class SequencerPublisher {
1040
1027
  reason
1041
1028
  };
1042
1029
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
1043
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(validationResult.attestations).getPackedAttestations();
1030
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
1044
1031
  if (reason === 'invalid-attestation') {
1045
1032
  return this.rollupContract.buildInvalidateBadAttestationRequest(checkpoint.checkpointNumber, attestationsAndSigners, committee, validationResult.invalidIndex);
1046
1033
  } else if (reason === 'insufficient-attestations') {
@@ -1050,25 +1037,6 @@ export class SequencerPublisher {
1050
1037
  throw new Error(`Unknown reason for invalidation`);
1051
1038
  }
1052
1039
  }
1053
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */ async validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, simulationOverridesPlan) {
1054
- const blobFields = checkpoint.toBlobFields();
1055
- const blobs = await getBlobsPerL1Block(blobFields);
1056
- const blobInput = getPrefixedEthBlobCommitments(blobs);
1057
- const args = [
1058
- {
1059
- header: checkpoint.header.toViem(),
1060
- archive: toHex(checkpoint.archive.root.toBuffer()),
1061
- oracleInput: {
1062
- feeAssetPriceModifier: checkpoint.feeAssetPriceModifier
1063
- }
1064
- },
1065
- attestationsAndSigners.getPackedAttestations(),
1066
- attestationsAndSigners.getSigners().map((signer)=>signer.toString()),
1067
- attestationsAndSignersSignature.toViemSignature(),
1068
- blobInput
1069
- ];
1070
- await this.simulateProposeTx(args, simulationOverridesPlan);
1071
- }
1072
1040
  async enqueueCastSignalHelper(slotNumber, signalType, payload, base, signerAddress, signer) {
1073
1041
  if (this.lastActions[signalType] && this.lastActions[signalType] === slotNumber) {
1074
1042
  this.log.debug(`Skipping duplicate vote cast signal ${signalType} for slot ${slotNumber}`);
@@ -1089,30 +1057,26 @@ export class SequencerPublisher {
1089
1057
  if (roundInfo.lastSignalSlot >= slotNumber) {
1090
1058
  return false;
1091
1059
  }
1092
- if (await this.isPayloadEmpty(payload)) {
1060
+ if (await base.isPayloadEmpty(payload)) {
1093
1061
  this.log.warn(`Skipping vote cast for payload with empty code`);
1094
1062
  return false;
1095
1063
  }
1096
- // Check if payload was already submitted to governance
1097
- const cacheKey = payload.toString();
1098
- if (!this.payloadProposedCache.has(cacheKey)) {
1099
- try {
1100
- const l1StartBlock = await this.rollupContract.getL1StartBlock();
1101
- const proposed = await retry(()=>base.hasPayloadBeenProposed(payload.toString(), l1StartBlock), 'Check if payload was proposed', makeBackoff([
1102
- 0,
1103
- 1,
1104
- 2
1105
- ]), this.log, true);
1106
- if (proposed) {
1107
- this.payloadProposedCache.add(cacheKey);
1108
- }
1109
- } catch (err) {
1110
- this.log.warn(`Failed to check if payload ${payload} was proposed after retries, skipping signal`, err);
1111
- return false;
1112
- }
1064
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
1065
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
1066
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
1067
+ // the same payload in a future round.
1068
+ let proposed = false;
1069
+ try {
1070
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
1071
+ } catch (err) {
1072
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
1073
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
1074
+ // participation entirely; failing open at worst produces a duplicate signal that the
1075
+ // contract will simply count alongside others in the round.
1076
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
1113
1077
  }
1114
- if (this.payloadProposedCache.has(cacheKey)) {
1115
- this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
1078
+ if (proposed) {
1079
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
1116
1080
  return false;
1117
1081
  }
1118
1082
  const cachedLastVote = this.lastActions[signalType];
@@ -1125,57 +1089,17 @@ export class SequencerPublisher {
1125
1089
  signer: this.l1TxUtils.client.account?.address,
1126
1090
  lastValidL2Slot: slotNumber
1127
1091
  });
1128
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1129
- const timestamp = this.getSimulationTimestamp(slotNumber);
1130
- try {
1131
- await this.l1TxUtils.simulate(request, {
1132
- time: timestamp
1133
- }, [], mergeAbis([
1134
- request.abi ?? [],
1135
- ErrorsAbi
1136
- ]));
1137
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, {
1138
- request
1139
- });
1140
- } catch (err) {
1141
- const viemError = formatViemError(err);
1142
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, viemError, {
1143
- simulationTimestamp: timestamp,
1144
- l1BlockNumber
1145
- });
1146
- this.backupFailedTx({
1147
- id: keccak256(request.data),
1148
- failureType: 'simulation',
1149
- request: {
1150
- to: request.to,
1151
- data: request.data,
1152
- value: request.value?.toString()
1153
- },
1154
- l1BlockNumber: l1BlockNumber.toString(),
1155
- error: {
1156
- message: viemError.message,
1157
- name: viemError.name
1158
- },
1159
- context: {
1160
- actions: [
1161
- action
1162
- ],
1163
- slot: slotNumber,
1164
- sender: this.getSenderAddress().toString()
1165
- }
1166
- });
1167
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
1168
- }
1169
1092
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
1170
1093
  this.addRequest({
1171
- gasConfig: {
1172
- gasLimit: SequencerPublisher.VOTE_GAS_GUESS
1173
- },
1174
1094
  action,
1175
1095
  request,
1176
1096
  lastValidL2Slot: slotNumber,
1177
1097
  checkSuccess: (_request, result)=>{
1178
- const success = result && result.receipt && result.receipt.status === 'success' && tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
1098
+ const success = result && extractEventSuccess(result.receipt, {
1099
+ address: base.address.toString(),
1100
+ abi: EmpireBaseAbi,
1101
+ eventName: 'SignalCast'
1102
+ });
1179
1103
  const logData = {
1180
1104
  ...result,
1181
1105
  slotNumber,
@@ -1194,16 +1118,6 @@ export class SequencerPublisher {
1194
1118
  });
1195
1119
  return true;
1196
1120
  }
1197
- async isPayloadEmpty(payload) {
1198
- const key = payload.toString();
1199
- const cached = this.isPayloadEmptyCache.get(key);
1200
- if (cached) {
1201
- return cached;
1202
- }
1203
- const isEmpty = !await this.l1TxUtils.getCode(payload);
1204
- this.isPayloadEmptyCache.set(key, isEmpty);
1205
- return isEmpty;
1206
- }
1207
1121
  /**
1208
1122
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
1209
1123
  * @param slotNumber - The slot number to cast a signal for.
@@ -1232,7 +1146,11 @@ export class SequencerPublisher {
1232
1146
  }
1233
1147
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1234
1148
  const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1235
- await this.simulateAndEnqueueRequest('vote-offenses', request, (receipt)=>!!this.slashingProposerContract.tryExtractVoteCastEvent(receipt.logs), slotNumber);
1149
+ this.enqueueRequest('vote-offenses', request, {
1150
+ address: this.slashingProposerContract.address.toString(),
1151
+ abi: SlashingProposerAbi,
1152
+ eventName: 'VoteCast'
1153
+ }, slotNumber);
1236
1154
  break;
1237
1155
  }
1238
1156
  case 'execute-slash':
@@ -1247,7 +1165,11 @@ export class SequencerPublisher {
1247
1165
  return false;
1248
1166
  }
1249
1167
  const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(action.round, action.committees);
1250
- await this.simulateAndEnqueueRequest('execute-slash', executeRequest, (receipt)=>!!this.slashingProposerContract.tryExtractRoundExecutedEvent(receipt.logs), slotNumber);
1168
+ this.enqueueRequest('execute-slash', executeRequest, {
1169
+ address: this.slashingProposerContract.address.toString(),
1170
+ abi: SlashingProposerAbi,
1171
+ eventName: 'RoundExecuted'
1172
+ }, slotNumber);
1251
1173
  break;
1252
1174
  }
1253
1175
  default:
@@ -1259,7 +1181,7 @@ export class SequencerPublisher {
1259
1181
  }
1260
1182
  return true;
1261
1183
  }
1262
- /** Simulates and enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1184
+ /** Enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1263
1185
  const checkpointHeader = checkpoint.header;
1264
1186
  const blobFields = checkpoint.toBlobFields();
1265
1187
  const blobs = await getBlobsPerL1Block(blobFields);
@@ -1271,65 +1193,38 @@ export class SequencerPublisher {
1271
1193
  attestationsAndSignersSignature,
1272
1194
  feeAssetPriceModifier: checkpoint.feeAssetPriceModifier
1273
1195
  };
1274
- const simulationOverridesPlan = SimulationOverridesBuilder.from(opts.simulationOverridesPlan).withoutBlobCheck().build();
1275
- try {
1276
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
1277
- // This means that we can avoid the simulation issues in later checks.
1278
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
1279
- // make time consistency checks break.
1280
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
1281
- await this.validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, simulationOverridesPlan);
1282
- } catch (err) {
1283
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
1284
- ...checkpoint.getStats(),
1285
- slotNumber: checkpoint.header.slotNumber,
1286
- simulationOverridesPlan
1287
- });
1288
- throw err;
1289
- }
1290
- // Build a pre-check callback that re-validates the checkpoint before L1 submission.
1291
- // During pipelining this catches stale proposals due to prunes or L1 reorgs that occur during the pipeline sleep.
1292
- let preCheck = undefined;
1293
- if (this.epochCache.isProposerPipeliningEnabled()) {
1294
- preCheck = async ()=>{
1295
- this.log.debug(`Re-validating checkpoint ${checkpoint.number} before L1 submission`);
1296
- await this.validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, simulationOverridesPlan);
1297
- };
1298
- }
1299
1196
  this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1300
1197
  ...checkpoint.toCheckpointInfo(),
1301
- txTimeoutAt: opts.txTimeoutAt,
1302
- simulationOverridesPlan
1198
+ txTimeoutAt: opts.txTimeoutAt
1303
1199
  });
1304
1200
  await this.addProposeTx(checkpoint, proposeTxArgs, {
1305
- txTimeoutAt: opts.txTimeoutAt,
1306
- simulationOverridesPlan
1307
- }, preCheck);
1201
+ txTimeoutAt: opts.txTimeoutAt
1202
+ });
1308
1203
  }
1309
1204
  enqueueInvalidateCheckpoint(request, opts = {}) {
1310
1205
  if (!request) {
1311
1206
  return;
1312
1207
  }
1313
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1314
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(request.gasUsed) * 64 / 63)));
1315
1208
  const { gasUsed, checkpointNumber } = request;
1316
1209
  const logData = {
1317
1210
  gasUsed,
1318
1211
  checkpointNumber,
1319
- gasLimit,
1320
1212
  opts
1321
1213
  };
1322
1214
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1323
1215
  this.addRequest({
1324
1216
  action: `invalidate-by-${request.reason}`,
1325
1217
  request: request.request,
1326
- gasConfig: {
1327
- gasLimit,
1218
+ gasConfig: opts.txTimeoutAt ? {
1328
1219
  txTimeoutAt: opts.txTimeoutAt
1329
- },
1220
+ } : undefined,
1330
1221
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1331
1222
  checkSuccess: (_req, result)=>{
1332
- const success = result && result.receipt && result.receipt.status === 'success' && tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1223
+ const success = result && extractEventSuccess(result.receipt, {
1224
+ address: this.rollupContract.address,
1225
+ abi: RollupAbi,
1226
+ eventName: 'CheckpointInvalidated'
1227
+ });
1333
1228
  if (!success) {
1334
1229
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, {
1335
1230
  ...result,
@@ -1345,90 +1240,36 @@ export class SequencerPublisher {
1345
1240
  }
1346
1241
  });
1347
1242
  }
1348
- async simulateAndEnqueueRequest(action, request, checkSuccess, slotNumber) {
1349
- const timestamp = this.getSimulationTimestamp(slotNumber);
1350
- const logData = {
1351
- slotNumber,
1352
- timestamp,
1353
- gasLimit: undefined
1354
- };
1243
+ /**
1244
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1245
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1246
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1247
+ */ enqueueRequest(action, request, eventOpts, slotNumber) {
1355
1248
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1356
1249
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1357
1250
  return false;
1358
1251
  }
1359
1252
  const cachedLastActionSlot = this.lastActions[action];
1360
1253
  this.lastActions[action] = slotNumber;
1361
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1362
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1363
- let gasUsed;
1364
- const simulateAbi = mergeAbis([
1365
- request.abi ?? [],
1366
- ErrorsAbi
1367
- ]);
1368
- try {
1369
- ({ gasUsed } = await this.l1TxUtils.simulate(request, {
1370
- time: timestamp
1371
- }, [], simulateAbi));
1372
- this.log.verbose(`Simulation for ${action} succeeded`, {
1373
- ...logData,
1374
- request,
1375
- gasUsed
1376
- });
1377
- } catch (err) {
1378
- const viemError = formatViemError(err, simulateAbi);
1379
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1380
- this.backupFailedTx({
1381
- id: keccak256(request.data),
1382
- failureType: 'simulation',
1383
- request: {
1384
- to: request.to,
1385
- data: request.data,
1386
- value: request.value?.toString()
1387
- },
1388
- l1BlockNumber: l1BlockNumber.toString(),
1389
- error: {
1390
- message: viemError.message,
1391
- name: viemError.name
1392
- },
1393
- context: {
1394
- actions: [
1395
- action
1396
- ],
1397
- slot: slotNumber,
1398
- sender: this.getSenderAddress().toString()
1399
- }
1400
- });
1401
- return false;
1402
- }
1403
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1404
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(gasUsed) * 64 / 63)));
1405
- logData.gasLimit = gasLimit;
1406
- // Store the ABI used for simulation on the request so Multicall3.forward can decode errors
1407
- // when the tx is sent and a revert is diagnosed via simulation.
1408
- const requestWithAbi = {
1409
- ...request,
1410
- abi: simulateAbi
1411
- };
1412
- this.log.debug(`Enqueuing ${action}`, logData);
1254
+ this.log.debug(`Enqueuing ${action}`, {
1255
+ slotNumber
1256
+ });
1413
1257
  this.addRequest({
1414
1258
  action,
1415
- request: requestWithAbi,
1416
- gasConfig: {
1417
- gasLimit
1418
- },
1259
+ request,
1419
1260
  lastValidL2Slot: slotNumber,
1420
- checkSuccess: (_req, result)=>{
1421
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1261
+ checkSuccess: (_request, result)=>{
1262
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1422
1263
  if (!success) {
1423
1264
  this.log.warn(`Action ${action} at ${slotNumber} failed`, {
1424
1265
  ...result,
1425
- ...logData
1266
+ slotNumber
1426
1267
  });
1427
1268
  this.lastActions[action] = cachedLastActionSlot;
1428
1269
  } else {
1429
1270
  this.log.info(`Action ${action} at ${slotNumber} succeeded`, {
1430
1271
  ...result,
1431
- ...logData
1272
+ slotNumber
1432
1273
  });
1433
1274
  }
1434
1275
  return !!success;
@@ -1450,7 +1291,7 @@ export class SequencerPublisher {
1450
1291
  this.interrupted = false;
1451
1292
  this.l1TxUtils.restart();
1452
1293
  }
1453
- async prepareProposeTx(encodedData, simulationOverridesPlan) {
1294
+ async prepareProposeTx(encodedData) {
1454
1295
  const kzg = Blob.getViemKzgInstance();
1455
1296
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1456
1297
  this.log.debug('Validating blob input', {
@@ -1464,7 +1305,11 @@ export class SequencerPublisher {
1464
1305
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1465
1306
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1466
1307
  } else {
1467
- // Normal mode - use estimateGas with blob inputs
1308
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1309
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1310
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1311
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1312
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1468
1313
  blobEvaluationGas = await this.l1TxUtils.estimateGas(this.getSenderAddress().toString(), {
1469
1314
  to: this.rollupContract.address,
1470
1315
  data: encodeFunctionData({
@@ -1527,96 +1372,23 @@ export class SequencerPublisher {
1527
1372
  encodedData.attestationsAndSignersSignature.toViemSignature(),
1528
1373
  blobInput
1529
1374
  ];
1530
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, simulationOverridesPlan);
1531
- return {
1532
- args,
1533
- blobEvaluationGas,
1534
- rollupData,
1535
- simulationResult
1536
- };
1537
- }
1538
- /**
1539
- * Simulates the propose tx with eth_simulateV1
1540
- * @param args - The propose tx args
1541
- * @returns The simulation result
1542
- */ async simulateProposeTx(args, simulationOverridesPlan) {
1543
1375
  const rollupData = encodeFunctionData({
1544
1376
  abi: RollupAbi,
1545
1377
  functionName: 'propose',
1546
1378
  args
1547
1379
  });
1548
- const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
1549
- // In fisherman mode, simulate as the proposer but with sufficient balance
1550
- if (this.proposerAddressForSimulation) {
1551
- stateOverrides.push({
1552
- address: this.proposerAddressForSimulation.toString(),
1553
- balance: 10n * WEI_CONST * WEI_CONST
1554
- });
1555
- }
1556
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1557
- const simTs = this.getSimulationTimestamp(SlotNumber.fromBigInt(args[0].header.slotNumber));
1558
- const simulationResult = await this.l1TxUtils.simulate({
1559
- to: this.rollupContract.address,
1560
- data: rollupData,
1561
- gas: MAX_L1_TX_LIMIT,
1562
- ...this.proposerAddressForSimulation && {
1563
- from: this.proposerAddressForSimulation.toString()
1564
- }
1565
- }, {
1566
- time: simTs,
1567
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1568
- gasLimit: MAX_L1_TX_LIMIT * 2n
1569
- }, stateOverrides, RollupAbi, {
1570
- // @note fallback gas estimate to use if the node doesn't support simulation API
1571
- fallbackGasEstimate: MAX_L1_TX_LIMIT
1572
- }).catch((err)=>{
1573
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1574
- const viemError = formatViemError(err);
1575
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1576
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1577
- // Return a minimal simulation result with the fallback gas estimate
1578
- return {
1579
- gasUsed: MAX_L1_TX_LIMIT,
1580
- logs: []
1581
- };
1582
- }
1583
- this.log.error(`Failed to simulate propose tx`, viemError, {
1584
- simulationTimestamp: simTs
1585
- });
1586
- this.backupFailedTx({
1587
- id: keccak256(rollupData),
1588
- failureType: 'simulation',
1589
- request: {
1590
- to: this.rollupContract.address,
1591
- data: rollupData
1592
- },
1593
- l1BlockNumber: l1BlockNumber.toString(),
1594
- error: {
1595
- message: viemError.message,
1596
- name: viemError.name
1597
- },
1598
- context: {
1599
- actions: [
1600
- 'propose'
1601
- ],
1602
- slot: Number(args[0].header.slotNumber),
1603
- sender: this.getSenderAddress().toString()
1604
- }
1605
- });
1606
- throw err;
1607
- });
1608
1380
  return {
1609
- rollupData,
1610
- simulationResult
1381
+ args,
1382
+ blobEvaluationGas,
1383
+ rollupData
1611
1384
  };
1612
1385
  }
1613
- async addProposeTx(checkpoint, encodedData, opts = {}, preCheck) {
1386
+ async addProposeTx(checkpoint, encodedData, opts = {}) {
1614
1387
  const slot = checkpoint.header.slotNumber;
1615
1388
  const timer = new Timer();
1616
1389
  const kzg = Blob.getViemKzgInstance();
1617
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, opts.simulationOverridesPlan);
1390
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1618
1391
  const startBlock = await this.l1TxUtils.getBlockNumber();
1619
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(simulationResult.gasUsed) * 64 / 63)) + blobEvaluationGas + SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS);
1620
1392
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1621
1393
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
1622
1394
  void Promise.resolve().then(()=>this.blobClient.sendBlobsToFilestore(encodedData.blobs).catch((_err)=>{
@@ -1631,9 +1403,9 @@ export class SequencerPublisher {
1631
1403
  lastValidL2Slot: checkpoint.header.slotNumber,
1632
1404
  gasConfig: {
1633
1405
  txTimeoutAt: opts.txTimeoutAt,
1634
- gasLimit
1406
+ gasLimit: undefined
1635
1407
  },
1636
- preCheck,
1408
+ blobEvaluationGas,
1637
1409
  blobConfig: {
1638
1410
  blobs: encodedData.blobs.map((b)=>b.data),
1639
1411
  kzg
@@ -1643,7 +1415,11 @@ export class SequencerPublisher {
1643
1415
  return false;
1644
1416
  }
1645
1417
  const { receipt, stats, errorMsg } = result;
1646
- const success = receipt && receipt.status === 'success' && tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1418
+ const success = extractEventSuccess(receipt, {
1419
+ address: this.rollupContract.address,
1420
+ abi: RollupAbi,
1421
+ eventName: 'CheckpointProposed'
1422
+ });
1647
1423
  if (success) {
1648
1424
  const endBlock = receipt.blockNumber;
1649
1425
  const inclusionBlocks = Number(endBlock - startBlock);
@@ -1680,11 +1456,6 @@ export class SequencerPublisher {
1680
1456
  }
1681
1457
  });
1682
1458
  }
1683
- /** Returns the timestamp of the last L1 slot within a given L2 slot. Used as the simulation timestamp
1684
- * for eth_simulateV1 calls, since it's guaranteed to be greater than any L1 block produced during the slot. */ getSimulationTimestamp(slot) {
1685
- const l1Constants = this.epochCache.getL1Constants();
1686
- return getLastL1SlotTimestampForL2Slot(slot, l1Constants);
1687
- }
1688
1459
  /** Returns the timestamp of the next L1 slot boundary after now. */ getNextL1SlotTimestamp() {
1689
1460
  const l1Constants = this.epochCache.getL1Constants();
1690
1461
  return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);