@aztec/sequencer-client 0.0.1-commit.2ed92850 → 0.0.1-commit.3100065

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 (137) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +34 -11
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +77 -39
  5. package/dest/config.d.ts +32 -6
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +94 -46
  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 -28
  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 +51 -17
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +131 -42
  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 +58 -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 +1 -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 +34 -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 +2 -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 +11 -5
  44. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  45. package/dest/publisher/sequencer-publisher-factory.js +27 -3
  46. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -1
  47. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  48. package/dest/publisher/sequencer-publisher-metrics.js +12 -4
  49. package/dest/publisher/sequencer-publisher.d.ts +107 -68
  50. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  51. package/dest/publisher/sequencer-publisher.js +545 -363
  52. package/dest/publisher/write_json.d.ts +11 -0
  53. package/dest/publisher/write_json.d.ts.map +1 -0
  54. package/dest/publisher/write_json.js +57 -0
  55. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  56. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  57. package/dest/sequencer/automine/automine_factory.js +85 -0
  58. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  59. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  60. package/dest/sequencer/automine/automine_sequencer.js +690 -0
  61. package/dest/sequencer/automine/index.d.ts +3 -0
  62. package/dest/sequencer/automine/index.d.ts.map +1 -0
  63. package/dest/sequencer/automine/index.js +2 -0
  64. package/dest/sequencer/checkpoint_proposal_job.d.ts +101 -22
  65. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  66. package/dest/sequencer/checkpoint_proposal_job.js +922 -286
  67. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  68. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  69. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  70. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  71. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  72. package/dest/sequencer/checkpoint_voter.js +2 -5
  73. package/dest/sequencer/errors.d.ts +1 -8
  74. package/dest/sequencer/errors.d.ts.map +1 -1
  75. package/dest/sequencer/errors.js +0 -9
  76. package/dest/sequencer/events.d.ts +62 -5
  77. package/dest/sequencer/events.d.ts.map +1 -1
  78. package/dest/sequencer/metrics.d.ts +23 -8
  79. package/dest/sequencer/metrics.d.ts.map +1 -1
  80. package/dest/sequencer/metrics.js +142 -36
  81. package/dest/sequencer/requests_tracker.d.ts +22 -0
  82. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  83. package/dest/sequencer/requests_tracker.js +33 -0
  84. package/dest/sequencer/sequencer.d.ts +181 -44
  85. package/dest/sequencer/sequencer.d.ts.map +1 -1
  86. package/dest/sequencer/sequencer.js +614 -216
  87. package/dest/sequencer/types.d.ts +2 -2
  88. package/dest/sequencer/types.d.ts.map +1 -1
  89. package/dest/test/index.d.ts +5 -7
  90. package/dest/test/index.d.ts.map +1 -1
  91. package/dest/test/mock_checkpoint_builder.d.ts +12 -12
  92. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  93. package/dest/test/mock_checkpoint_builder.js +45 -36
  94. package/dest/test/utils.d.ts +17 -3
  95. package/dest/test/utils.d.ts.map +1 -1
  96. package/dest/test/utils.js +28 -9
  97. package/package.json +28 -28
  98. package/src/client/sequencer-client.ts +110 -47
  99. package/src/config.ts +120 -55
  100. package/src/global_variable_builder/README.md +44 -0
  101. package/src/global_variable_builder/fee_predictor.ts +182 -0
  102. package/src/global_variable_builder/fee_provider.ts +97 -0
  103. package/src/global_variable_builder/global_builder.ts +20 -89
  104. package/src/global_variable_builder/index.ts +3 -1
  105. package/src/publisher/config.ts +173 -40
  106. package/src/publisher/index.ts +3 -0
  107. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  108. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  109. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  110. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  111. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  112. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  113. package/src/publisher/sequencer-publisher-factory.ts +38 -9
  114. package/src/publisher/sequencer-publisher-metrics.ts +7 -3
  115. package/src/publisher/sequencer-publisher.ts +635 -460
  116. package/src/publisher/write_json.ts +78 -0
  117. package/src/sequencer/automine/README.md +60 -0
  118. package/src/sequencer/automine/automine_factory.ts +152 -0
  119. package/src/sequencer/automine/automine_sequencer.ts +796 -0
  120. package/src/sequencer/automine/index.ts +6 -0
  121. package/src/sequencer/checkpoint_proposal_job.ts +1133 -326
  122. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  123. package/src/sequencer/checkpoint_voter.ts +1 -12
  124. package/src/sequencer/errors.ts +0 -15
  125. package/src/sequencer/events.ts +66 -5
  126. package/src/sequencer/metrics.ts +164 -39
  127. package/src/sequencer/requests_tracker.ts +43 -0
  128. package/src/sequencer/sequencer.ts +729 -242
  129. package/src/sequencer/types.ts +1 -1
  130. package/src/test/index.ts +4 -6
  131. package/src/test/mock_checkpoint_builder.ts +65 -53
  132. package/src/test/utils.ts +64 -10
  133. package/dest/sequencer/timetable.d.ts +0 -90
  134. package/dest/sequencer/timetable.d.ts.map +0 -1
  135. package/dest/sequencer/timetable.js +0 -226
  136. package/src/sequencer/README.md +0 -531
  137. package/src/sequencer/timetable.ts +0 -282
@@ -370,41 +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 { MULTI_CALL_3_ADDRESS, Multicall3, RollupContract } 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
- import { WEI_CONST } from '@aztec/ethereum/l1-tx-utils';
378
- import { FormattedViemError, formatViemError, tryExtractEvent } from '@aztec/ethereum/utils';
379
- import { sumBigint } from '@aztec/foundation/bigint';
380
- import { toHex as toPaddedHex } from '@aztec/foundation/bigint-buffer';
377
+ import { 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 { InterruptibleSleep } from '@aztec/foundation/sleep';
386
387
  import { bufferToHex } from '@aztec/foundation/string';
387
388
  import { Timer } from '@aztec/foundation/timer';
388
- import { EmpireBaseAbi, ErrorsAbi, RollupAbi } from '@aztec/l1-artifacts';
389
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi, SlashingProposerAbi } from '@aztec/l1-artifacts';
389
390
  import { encodeSlashConsensusVotes } from '@aztec/slasher';
390
391
  import { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
392
+ import { getLastL1SlotTimestampForL2Slot, getNextL1SlotTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
391
393
  import { getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
392
- 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';
393
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
+ }
394
408
  export const Actions = [
395
409
  'invalidate-by-invalid-attestation',
396
410
  'invalidate-by-insufficient-attestations',
411
+ 'prune',
397
412
  'propose',
398
413
  'governance-signal',
399
- 'empire-slashing-signal',
400
- 'create-empire-payload',
401
- 'execute-empire-payload',
402
414
  'vote-offenses',
403
415
  'execute-slash'
404
416
  ];
405
417
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
406
418
  export const compareActions = (a, b)=>Actions.indexOf(a) - Actions.indexOf(b);
407
- _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader'), _dec2 = trackSpan('SequencerPublisher.validateCheckpointForSubmission');
419
+ _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader');
408
420
  export class SequencerPublisher {
409
421
  config;
410
422
  static{
@@ -418,58 +430,64 @@ export class SequencerPublisher {
418
430
  _dec1,
419
431
  2,
420
432
  "validateBlockHeader"
421
- ],
422
- [
423
- _dec2,
424
- 2,
425
- "validateCheckpointForSubmission"
426
433
  ]
427
434
  ], []));
428
435
  }
429
436
  interrupted;
430
437
  metrics;
438
+ bundleSimulator;
431
439
  epochCache;
432
- governanceLog;
433
- 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;
434
446
  lastActions;
435
- isPayloadEmptyCache;
436
447
  log;
437
448
  ethereumSlotDuration;
449
+ aztecSlotDuration;
450
+ previousL1BlockWaitTimeoutMs;
451
+ previousL1BlockWaitPollIntervalMs;
452
+ /** Date provider for wall-clock time. */ dateProvider;
438
453
  blobClient;
439
- /** 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;
440
455
  /** L1 fee analyzer for fisherman mode */ l1FeeAnalyzer;
441
- // @note - with blobs, the below estimate seems too large.
442
- // Total used for full block from int_l1_pub e2e test: 1m (of which 86k is 1x blob)
443
- // Total used for emptier block from above test: 429k (of which 84k is 1x blob)
444
- static PROPOSE_GAS_GUESS = 12_000_000n;
445
- // A CALL to a cold address is 2700 gas
446
- static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
447
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
448
- static VOTE_GAS_GUESS = 800_000n;
456
+ /** Fee asset price oracle for computing price modifiers from Uniswap V4 */ feeAssetPriceOracle;
457
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */ interruptibleSleep;
449
458
  l1TxUtils;
450
459
  rollupContract;
451
460
  govProposerContract;
452
461
  slashingProposerContract;
453
- slashFactoryContract;
454
462
  tracer;
455
463
  requests;
456
464
  constructor(config, deps){
457
465
  this.config = config;
458
466
  this.interrupted = (_initProto(this), false);
459
- this.governanceLog = createLogger('sequencer:publisher:governance');
460
- this.slashingLog = createLogger('sequencer:publisher:slashing');
467
+ this.revertDecoderAbi = mergeAbis([
468
+ RollupAbi,
469
+ SlashingProposerAbi,
470
+ EmpireBaseAbi,
471
+ ErrorsAbi
472
+ ]);
461
473
  this.lastActions = {};
462
- this.isPayloadEmptyCache = new Map();
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,15 +496,50 @@ 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'));
502
+ }
503
+ // Initialize fee asset 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
+ * Backs up a failed L1 transaction to the configured store for debugging.
516
+ * Does nothing if no store is configured.
517
+ */ backupFailedTx(failedTx) {
518
+ if (!this.failedTxStore) {
519
+ return;
485
520
  }
521
+ const tx = {
522
+ ...failedTx,
523
+ timestamp: Date.now()
524
+ };
525
+ // Fire and forget - don't block on backup
526
+ void this.failedTxStore.then((store)=>store?.saveFailedTx(tx)).catch((err)=>{
527
+ this.log.warn(`Failed to backup failed L1 tx to store`, err);
528
+ });
486
529
  }
487
530
  getRollupContract() {
488
531
  return this.rollupContract;
489
532
  }
533
+ /**
534
+ * Gets the fee asset price modifier from the oracle.
535
+ *
536
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
537
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
538
+ * modifier matches the parent L1 will use when applying it.
539
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
540
+ */ getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12) {
541
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
542
+ }
490
543
  getSenderAddress() {
491
544
  return this.l1TxUtils.getSenderAddress();
492
545
  }
@@ -495,17 +548,11 @@ export class SequencerPublisher {
495
548
  */ getL1FeeAnalyzer() {
496
549
  return this.l1FeeAnalyzer;
497
550
  }
498
- /**
499
- * Sets the proposer address to use for simulations in fisherman mode.
500
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
501
- */ setProposerAddressForSimulation(proposerAddress) {
502
- this.proposerAddressForSimulation = proposerAddress;
503
- }
504
551
  addRequest(request) {
505
552
  this.requests.push(request);
506
553
  }
507
554
  getCurrentL2Slot() {
508
- return this.epochCache.getEpochAndSlotNow().slot;
555
+ return this.epochCache.getSlotNow();
509
556
  }
510
557
  /**
511
558
  * Clears all pending requests without sending them.
@@ -544,7 +591,7 @@ export class SequencerPublisher {
544
591
  // Get the transaction requests
545
592
  const l1Requests = requestsToAnalyze.map((r)=>r.request);
546
593
  // Start the analysis
547
- const analysisId = await this.l1FeeAnalyzer.startAnalysis(l2SlotNumber, gasLimit > 0n ? gasLimit : SequencerPublisher.PROPOSE_GAS_GUESS, l1Requests, blobConfig, onComplete);
594
+ const analysisId = await this.l1FeeAnalyzer.startAnalysis(l2SlotNumber, gasLimit > 0n ? gasLimit : MAX_L1_TX_LIMIT, l1Requests, blobConfig, onComplete);
548
595
  this.log.info('Started L1 fee analysis', {
549
596
  analysisId,
550
597
  l2SlotNumber: l2SlotNumber.toString(),
@@ -558,11 +605,15 @@ export class SequencerPublisher {
558
605
  }
559
606
  /**
560
607
  * Sends all requests that are still valid.
608
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
609
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
610
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
611
+ * AutomineSequencer, which publishes synchronously within the current slot.
561
612
  * @returns one of:
562
613
  * - A receipt and stats if the tx succeeded
563
614
  * - a receipt and errorMsg if it failed on L1
564
615
  * - undefined if no valid requests are found OR the tx failed to send.
565
- */ async sendRequests() {
616
+ */ async sendRequests(targetSlot) {
566
617
  const requestsToProcess = [
567
618
  ...this.requests
568
619
  ];
@@ -570,10 +621,9 @@ export class SequencerPublisher {
570
621
  if (this.interrupted || requestsToProcess.length === 0) {
571
622
  return undefined;
572
623
  }
573
- const currentL2Slot = this.getCurrentL2Slot();
624
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
574
625
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
575
626
  const validRequests = requestsToProcess.filter((request)=>request.lastValidL2Slot >= currentL2Slot);
576
- const validActions = validRequests.map((x)=>x.action);
577
627
  const expiredActions = requestsToProcess.filter((request)=>request.lastValidL2Slot < currentL2Slot).map((x)=>x.action);
578
628
  if (validRequests.length !== requestsToProcess.length) {
579
629
  this.log.warn(`Some requests were expired for slot ${currentL2Slot}`, {
@@ -591,40 +641,53 @@ export class SequencerPublisher {
591
641
  this.log.debug(`No valid requests to send`);
592
642
  return undefined;
593
643
  }
594
- // @note - we can only have one blob config per bundle
595
- // find requests with gas and blob configs
596
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
597
- const gasConfigs = requestsToProcess.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
598
- const blobConfigs = requestsToProcess.filter((request)=>request.blobConfig).map((request)=>request.blobConfig);
599
- if (blobConfigs.length > 1) {
600
- throw new Error('Multiple blob configs found');
601
- }
602
- const blobConfig = blobConfigs[0];
603
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
604
- const gasLimits = gasConfigs.map((g)=>g?.gasLimit).filter((g)=>g !== undefined);
605
- const gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
644
+ // Collect earliest txTimeoutAt across all requests.
645
+ const gasConfigs = validRequests.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
606
646
  const txTimeoutAts = gasConfigs.map((g)=>g?.txTimeoutAt).filter((g)=>g !== undefined);
607
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined; // earliest
608
- const txConfig = {
609
- gasLimit,
610
- txTimeoutAt
611
- };
647
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined;
612
648
  // Sort the requests so that proposals always go first
613
649
  // This ensures the committee gets precomputed correctly
614
650
  validRequests.sort((a, b)=>compareActions(a.action, b.action));
615
651
  try {
652
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
653
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
654
+ if (bundleResult.kind === 'aborted') {
655
+ this.logDroppedInSim(bundleResult.droppedRequests);
656
+ void this.backupDroppedInSim(bundleResult.droppedRequests).catch((err)=>this.log.error(`Failed to backup requests dropped in simulation`, err));
657
+ return undefined;
658
+ }
659
+ const { requests, droppedRequests, gasLimit } = bundleResult.kind === 'fallback' ? {
660
+ requests: bundleResult.requests,
661
+ droppedRequests: bundleResult.droppedRequests,
662
+ gasLimit: MAX_L1_TX_LIMIT
663
+ } : bundleResult;
664
+ this.logDroppedInSim(droppedRequests);
665
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
666
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
667
+ const [blobConfig] = requests.filter((r)=>r.blobConfig).map((r)=>r.blobConfig);
668
+ const txConfig = {
669
+ gasLimit,
670
+ txTimeoutAt
671
+ };
616
672
  this.log.debug('Forwarding transactions', {
617
- validRequests: validRequests.map((request)=>request.action),
673
+ requests: requests.map((request)=>request.action),
618
674
  txConfig
619
675
  });
620
- const result = await Multicall3.forward(validRequests.map((request)=>request.request), this.l1TxUtils, txConfig, blobConfig, this.rollupContract.address, this.log);
621
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(validRequests, result);
676
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
677
+ if (result === undefined) {
678
+ return undefined;
679
+ }
680
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
681
+ const allFailedActions = [
682
+ ...failedActions,
683
+ ...droppedRequests.map((d)=>d.request.action)
684
+ ];
622
685
  return {
623
686
  result,
624
687
  expiredActions,
625
- sentActions: validActions,
688
+ sentActions: requests.map((x)=>x.action),
626
689
  successfulActions,
627
- failedActions
690
+ failedActions: allFailedActions
628
691
  };
629
692
  } catch (err) {
630
693
  const viemError = formatViemError(err);
@@ -638,49 +701,214 @@ export class SequencerPublisher {
638
701
  }
639
702
  }
640
703
  }
641
- callbackBundledTransactions(requests, result) {
642
- const actionsListStr = requests.map((r)=>r.action).join(', ');
643
- if (result instanceof FormattedViemError) {
644
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
645
- return {
646
- failedActions: requests.map((r)=>r.action)
647
- };
648
- } else {
649
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
650
- result,
651
- requests
704
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */ logDroppedInSim(dropped) {
705
+ for (const drop of dropped){
706
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
707
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
708
+ action: drop.request.action,
709
+ revertReason: revertReasonDecoded ?? drop.returnData,
710
+ revertReasonDecoded,
711
+ returnData: drop.returnData
652
712
  });
653
- const successfulActions = [];
654
- const failedActions = [];
655
- for (const request of requests){
656
- if (request.checkSuccess(request.request, result)) {
657
- successfulActions.push(request.action);
658
- } else {
659
- failedActions.push(request.action);
713
+ }
714
+ }
715
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */ async backupDroppedInSim(dropped) {
716
+ if (dropped.length === 0) {
717
+ return;
718
+ }
719
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
720
+ for (const { request: req } of dropped){
721
+ this.backupFailedTx({
722
+ id: keccak256(req.request.data),
723
+ failureType: 'simulation',
724
+ request: {
725
+ to: req.request.to,
726
+ data: req.request.data
727
+ },
728
+ l1BlockNumber: l1BlockNumber.toString(),
729
+ error: {
730
+ message: 'Bundle entry dropped: action reverted in sim'
731
+ },
732
+ context: {
733
+ actions: [
734
+ req.action
735
+ ],
736
+ sender: this.getSenderAddress().toString()
660
737
  }
738
+ });
739
+ }
740
+ }
741
+ /**
742
+ * Forwards transactions via Multicall3, rotating to the next available publisher if a send
743
+ * failure occurs (i.e. the tx never reached the chain).
744
+ * On-chain reverts and simulation errors are returned as-is without rotation.
745
+ */ async forwardWithPublisherRotation(validRequests, txConfig, blobConfig) {
746
+ if (!txConfig?.gasLimit) {
747
+ throw new Error('gasLimit is required for bundled transactions');
748
+ }
749
+ const txConfigWithGasLimit = txConfig;
750
+ const triedAddresses = [];
751
+ let currentPublisher = this.l1TxUtils;
752
+ while(true){
753
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
754
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
755
+ triedAddresses: triedAddresses.map((a)=>a.toString())
756
+ });
757
+ return undefined;
661
758
  }
662
- return {
663
- successfulActions,
664
- failedActions
665
- };
759
+ triedAddresses.push(currentPublisher.getSenderAddress());
760
+ try {
761
+ const result = await Multicall3.forward(validRequests.map((r)=>r.request), currentPublisher, txConfigWithGasLimit, blobConfig, {
762
+ gasLimitRequired: true
763
+ });
764
+ this.l1TxUtils = currentPublisher;
765
+ return result;
766
+ } catch (err) {
767
+ if (err instanceof TimeoutError) {
768
+ throw err;
769
+ }
770
+ if (err instanceof MulticallForwarderRevertedError) {
771
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
772
+ transactionHash: err.receipt.transactionHash
773
+ });
774
+ return undefined;
775
+ }
776
+ const viemError = formatViemError(err);
777
+ if (!this.getNextPublisher) {
778
+ this.log.error('Failed to publish bundled transactions', viemError);
779
+ return undefined;
780
+ }
781
+ this.log.warn(`Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`, viemError);
782
+ const nextPublisher = await this.getNextPublisher([
783
+ ...triedAddresses
784
+ ]);
785
+ if (!nextPublisher) {
786
+ this.log.error(`All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`, viemError, {
787
+ triedAddresses: triedAddresses.map((a)=>a.toString())
788
+ });
789
+ return undefined;
790
+ }
791
+ currentPublisher = nextPublisher;
792
+ }
793
+ }
794
+ }
795
+ /*
796
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
797
+ */ async sendRequestsAt(targetSlot) {
798
+ await this.waitForTargetSlot(targetSlot);
799
+ if (this.interrupted) {
800
+ return undefined;
666
801
  }
802
+ return this.sendRequests(targetSlot);
667
803
  }
668
804
  /**
669
- * @notice Will call `canProposeAtNextEthBlock` to make sure that it is possible to propose
805
+ * Sleeps until one L1 slot before the L2 slot boundary, and then waits for that L1 block
806
+ * to be mined, so we don't risk being included in it. If that block never gets mined after
807
+ * a timeout, we assume it got skipped on L1, so we send the tx anyway.
808
+ */ async waitForTargetSlot(targetSlot) {
809
+ const l1Constants = this.epochCache.getL1Constants();
810
+ const nowInSeconds = this.dateProvider.nowInSeconds();
811
+ const startOfTargetSlotTs = getTimestampForSlot(targetSlot, l1Constants);
812
+ const previousL1BlockTs = startOfTargetSlotTs - this.ethereumSlotDuration;
813
+ const waitDeadlineTs = previousL1BlockTs + BigInt(this.previousL1BlockWaitTimeoutMs / 1000);
814
+ const logCtx = {
815
+ targetSlot,
816
+ startOfTargetSlotTs,
817
+ nowInSeconds,
818
+ previousL1BlockTs,
819
+ waitDeadlineTs
820
+ };
821
+ // Check if we are already past time
822
+ if (nowInSeconds >= startOfTargetSlotTs) {
823
+ this.log.verbose(`Target slot ${targetSlot} already started, sending requests immediately`, logCtx);
824
+ return;
825
+ }
826
+ // Otherwise we wait
827
+ this.log.debug(`Waiting for slot ${targetSlot} before sending requests`, logCtx);
828
+ // Wait until previous L1 block timestamp first
829
+ const sleepMs = (Number(previousL1BlockTs) - nowInSeconds) * 1000;
830
+ if (sleepMs > 0 && !this.interrupted) {
831
+ this.log.trace(`Sleeping ${sleepMs}ms before waiting for previous L1 block`, logCtx);
832
+ await this.interruptibleSleep.sleep(sleepMs);
833
+ }
834
+ // Then loop until we see the previous L1 block, so we know that we cannot be included in it.
835
+ // We time out after a while, once we are sure that that block is skipped in L1.
836
+ while(!this.interrupted){
837
+ try {
838
+ const nowInSeconds = this.dateProvider.nowInSeconds();
839
+ logCtx.nowInSeconds = nowInSeconds;
840
+ if (nowInSeconds >= waitDeadlineTs) {
841
+ this.log.warn(`Timed out waiting for previous L1 block before sending requests, proceeding`, logCtx);
842
+ return;
843
+ }
844
+ const latestBlockTs = await this.l1TxUtils.getBlock().then((b)=>b.timestamp);
845
+ if (latestBlockTs >= previousL1BlockTs) {
846
+ this.log.debug(`Previous L1 block mined, proceeding to send requests`, {
847
+ ...logCtx,
848
+ latestBlockTs
849
+ });
850
+ return;
851
+ }
852
+ this.log.trace(`Previous L1 block not mined yet, continuing to wait`, {
853
+ ...logCtx,
854
+ latestBlockTs
855
+ });
856
+ } catch (err) {
857
+ this.log.error(`Error while waiting for previous L1 block before sending requests; retrying`, err, logCtx);
858
+ } finally{
859
+ await this.interruptibleSleep.sleep(this.previousL1BlockWaitPollIntervalMs);
860
+ }
861
+ }
862
+ }
863
+ callbackBundledTransactions(requests, result) {
864
+ const actionsListStr = requests.map((r)=>r.action).join(', ');
865
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
866
+ result,
867
+ requests: requests.map((r)=>({
868
+ ...r,
869
+ // Avoid logging large blob data
870
+ blobConfig: r.blobConfig ? {
871
+ ...r.blobConfig,
872
+ blobs: r.blobConfig.blobs.map((b)=>({
873
+ size: trimmedBytesLength(b)
874
+ }))
875
+ } : undefined
876
+ }))
877
+ });
878
+ const successfulActions = [];
879
+ const failedActions = [];
880
+ for (const request of requests){
881
+ if (request.checkSuccess(request.request, result)) {
882
+ successfulActions.push(request.action);
883
+ } else {
884
+ failedActions.push(request.action);
885
+ }
886
+ }
887
+ return {
888
+ successfulActions,
889
+ failedActions
890
+ };
891
+ }
892
+ /**
893
+ * @notice Will call `canProposeAt` to make sure that it is possible to propose
670
894
  * @param tipArchive - The archive to check
671
895
  * @returns The slot and block number if it is possible to propose, undefined otherwise
672
- */ canProposeAtNextEthBlock(tipArchive, msgSender, opts = {}) {
896
+ */ async canProposeAt(tipArchive, msgSender, simulationOverridesPlan) {
673
897
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
674
- const ignoredErrors = [
898
+ // These errors are expected when we cannot actually propose right now — usually because our
899
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
900
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
901
+ // skip the proposal; we do NOT treat these as bugs.
902
+ const expectedErrors = [
675
903
  'SlotAlreadyInChain',
676
904
  'InvalidProposer',
677
905
  'InvalidArchive'
678
906
  ];
679
- return this.rollupContract.canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
680
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber
681
- }).catch((err)=>{
682
- if (err instanceof FormattedViemError && ignoredErrors.find((e)=>err.message.includes(e))) {
683
- this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find((e)=>err.message.includes(e))}`, {
907
+ const slotOffset = this.aztecSlotDuration;
908
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
909
+ return this.rollupContract.canProposeAt(tipArchive.toBuffer(), msgSender.toString(), nextL1SlotTs, await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan)).catch((err)=>{
910
+ if (err instanceof FormattedViemError && expectedErrors.find((e)=>err.message.includes(e))) {
911
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find((e)=>err.message.includes(e))}`, {
684
912
  error: err.message
685
913
  });
686
914
  } else {
@@ -694,22 +922,23 @@ export class SequencerPublisher {
694
922
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
695
923
  * It will throw if the block header is invalid.
696
924
  * @param header - The block header to validate
697
- */ async validateBlockHeader(header, opts) {
925
+ */ async validateBlockHeader(header, simulationOverridesPlan) {
698
926
  const flags = {
699
927
  ignoreDA: true,
700
928
  ignoreSignatures: true
701
929
  };
702
930
  const args = [
703
931
  header.toViem(),
704
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
932
+ CommitteeAttestationsAndSigners.packAttestations([]),
705
933
  [],
706
934
  Signature.empty().toViemSignature(),
707
935
  `0x${'0'.repeat(64)}`,
708
936
  header.blobsHash.toString(),
709
937
  flags
710
938
  ];
711
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
712
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(opts?.forcePendingCheckpointNumber);
939
+ const l1Constants = this.epochCache.getL1Constants();
940
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
941
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
713
942
  let balance = 0n;
714
943
  if (this.config.fishermanMode) {
715
944
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -731,7 +960,7 @@ export class SequencerPublisher {
731
960
  }),
732
961
  from: MULTI_CALL_3_ADDRESS
733
962
  }, {
734
- time: ts + 1n
963
+ time: ts
735
964
  }, stateOverrides);
736
965
  this.log.debug(`Simulated validateHeader`);
737
966
  }
@@ -761,8 +990,12 @@ export class SequencerPublisher {
761
990
  ...logData,
762
991
  request
763
992
  });
993
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
764
994
  try {
765
- const { gasUsed } = await this.l1TxUtils.simulate(request, undefined, undefined, ErrorsAbi);
995
+ const { gasUsed } = await this.l1TxUtils.simulate(request, undefined, undefined, mergeAbis([
996
+ request.abi ?? [],
997
+ ErrorsAbi
998
+ ]));
766
999
  this.log.verbose(`Simulation for invalidate checkpoint ${checkpointNumber} succeeded`, {
767
1000
  ...logData,
768
1001
  request,
@@ -773,20 +1006,21 @@ export class SequencerPublisher {
773
1006
  gasUsed,
774
1007
  checkpointNumber,
775
1008
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
1009
+ lastArchive: validationResult.checkpoint.lastArchive,
776
1010
  reason
777
1011
  };
778
1012
  } catch (err) {
779
1013
  const viemError = formatViemError(err);
780
1014
  // If the error is due to the checkpoint not being in the pending chain, and it was indeed removed by someone else,
781
1015
  // we can safely ignore it and return undefined so we go ahead with checkpoint building.
782
- if (viemError.message?.includes('Rollup__BlockNotInPendingChain')) {
1016
+ if (viemError.message?.includes('Rollup__CheckpointNotInPendingChain')) {
783
1017
  this.log.verbose(`Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`, {
784
1018
  ...logData,
785
1019
  request,
786
1020
  error: viemError.message
787
1021
  });
788
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
789
- if (latestPendingCheckpointNumber < checkpointNumber) {
1022
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
1023
+ if (latestProposedCheckpointNumber < checkpointNumber) {
790
1024
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, {
791
1025
  ...logData
792
1026
  });
@@ -800,6 +1034,27 @@ export class SequencerPublisher {
800
1034
  }
801
1035
  // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
802
1036
  this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
1037
+ this.backupFailedTx({
1038
+ id: keccak256(request.data),
1039
+ failureType: 'simulation',
1040
+ request: {
1041
+ to: request.to,
1042
+ data: request.data,
1043
+ value: request.value?.toString()
1044
+ },
1045
+ l1BlockNumber: l1BlockNumber.toString(),
1046
+ error: {
1047
+ message: viemError.message,
1048
+ name: viemError.name
1049
+ },
1050
+ context: {
1051
+ actions: [
1052
+ `invalidate-${reason}`
1053
+ ],
1054
+ checkpointNumber,
1055
+ sender: this.getSenderAddress().toString()
1056
+ }
1057
+ });
803
1058
  throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, {
804
1059
  cause: viemError
805
1060
  });
@@ -815,7 +1070,11 @@ export class SequencerPublisher {
815
1070
  reason
816
1071
  };
817
1072
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
818
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(validationResult.attestations).getPackedAttestations();
1073
+ // Use the exact packed tuple posted to L1 verbatim. A repack via `packAttestations` is not a
1074
+ // byte-faithful inverse of `fromPacked` (a canonicalized yParity byte or an all-zero signature slot
1075
+ // round-trips differently), so it would diverge from the stored `attestationsHash` and revert the
1076
+ // invalidation.
1077
+ const attestationsAndSigners = validationResult.verbatimAttestations;
819
1078
  if (reason === 'invalid-attestation') {
820
1079
  return this.rollupContract.buildInvalidateBadAttestationRequest(checkpoint.checkpointNumber, attestationsAndSigners, committee, validationResult.invalidIndex);
821
1080
  } else if (reason === 'insufficient-attestations') {
@@ -825,42 +1084,7 @@ export class SequencerPublisher {
825
1084
  throw new Error(`Unknown reason for invalidation`);
826
1085
  }
827
1086
  }
828
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */ async validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, options) {
829
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
830
- // TODO(palla/mbps): This should not be needed, there's no flow where we propose with zero attestations. Or is there?
831
- // If we have no attestations, we still need to provide the empty attestations
832
- // so that the committee is recalculated correctly
833
- // const ignoreSignatures = attestationsAndSigners.attestations.length === 0;
834
- // if (ignoreSignatures) {
835
- // const { committee } = await this.epochCache.getCommittee(block.header.globalVariables.slotNumber);
836
- // if (!committee) {
837
- // this.log.warn(`No committee found for slot ${block.header.globalVariables.slotNumber}`);
838
- // throw new Error(`No committee found for slot ${block.header.globalVariables.slotNumber}`);
839
- // }
840
- // attestationsAndSigners.attestations = committee.map(committeeMember =>
841
- // CommitteeAttestation.fromAddress(committeeMember),
842
- // );
843
- // }
844
- const blobFields = checkpoint.toBlobFields();
845
- const blobs = getBlobsPerL1Block(blobFields);
846
- const blobInput = getPrefixedEthBlobCommitments(blobs);
847
- const args = [
848
- {
849
- header: checkpoint.header.toViem(),
850
- archive: toHex(checkpoint.archive.root.toBuffer()),
851
- oracleInput: {
852
- feeAssetPriceModifier: 0n
853
- }
854
- },
855
- attestationsAndSigners.getPackedAttestations(),
856
- attestationsAndSigners.getSigners().map((signer)=>signer.toString()),
857
- attestationsAndSignersSignature.toViemSignature(),
858
- blobInput
859
- ];
860
- await this.simulateProposeTx(args, ts, options);
861
- return ts;
862
- }
863
- async enqueueCastSignalHelper(slotNumber, timestamp, signalType, payload, base, signerAddress, signer) {
1087
+ async enqueueCastSignalHelper(slotNumber, signalType, payload, base, signerAddress, signer) {
864
1088
  if (this.lastActions[signalType] && this.lastActions[signalType] === slotNumber) {
865
1089
  this.log.debug(`Skipping duplicate vote cast signal ${signalType} for slot ${slotNumber}`);
866
1090
  return false;
@@ -880,10 +1104,28 @@ export class SequencerPublisher {
880
1104
  if (roundInfo.lastSignalSlot >= slotNumber) {
881
1105
  return false;
882
1106
  }
883
- if (await this.isPayloadEmpty(payload)) {
1107
+ if (await base.isPayloadEmpty(payload)) {
884
1108
  this.log.warn(`Skipping vote cast for payload with empty code`);
885
1109
  return false;
886
1110
  }
1111
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
1112
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
1113
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
1114
+ // the same payload in a future round.
1115
+ let proposed = false;
1116
+ try {
1117
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
1118
+ } catch (err) {
1119
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
1120
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
1121
+ // participation entirely; failing open at worst produces a duplicate signal that the
1122
+ // contract will simply count alongside others in the round.
1123
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
1124
+ }
1125
+ if (proposed) {
1126
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
1127
+ return false;
1128
+ }
887
1129
  const cachedLastVote = this.lastActions[signalType];
888
1130
  this.lastActions[signalType] = slotNumber;
889
1131
  const action = signalType;
@@ -894,27 +1136,17 @@ export class SequencerPublisher {
894
1136
  signer: this.l1TxUtils.client.account?.address,
895
1137
  lastValidL2Slot: slotNumber
896
1138
  });
897
- try {
898
- await this.l1TxUtils.simulate(request, {
899
- time: timestamp
900
- }, [], ErrorsAbi);
901
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, {
902
- request
903
- });
904
- } catch (err) {
905
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, err);
906
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
907
- }
908
1139
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
909
1140
  this.addRequest({
910
- gasConfig: {
911
- gasLimit: SequencerPublisher.VOTE_GAS_GUESS
912
- },
913
1141
  action,
914
1142
  request,
915
1143
  lastValidL2Slot: slotNumber,
916
1144
  checkSuccess: (_request, result)=>{
917
- const success = result && result.receipt && result.receipt.status === 'success' && tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
1145
+ const success = result && extractEventSuccess(result.receipt, {
1146
+ address: base.address.toString(),
1147
+ abi: EmpireBaseAbi,
1148
+ eventName: 'SignalCast'
1149
+ });
918
1150
  const logData = {
919
1151
  ...result,
920
1152
  slotNumber,
@@ -933,68 +1165,70 @@ export class SequencerPublisher {
933
1165
  });
934
1166
  return true;
935
1167
  }
936
- async isPayloadEmpty(payload) {
937
- const key = payload.toString();
938
- const cached = this.isPayloadEmptyCache.get(key);
939
- if (cached) {
940
- return cached;
941
- }
942
- const isEmpty = !await this.l1TxUtils.getCode(payload);
943
- this.isPayloadEmptyCache.set(key, isEmpty);
944
- return isEmpty;
945
- }
946
1168
  /**
947
1169
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
948
1170
  * @param slotNumber - The slot number to cast a signal for.
949
- * @param timestamp - The timestamp of the slot to cast a signal for.
950
1171
  * @returns True if the signal was successfully enqueued, false otherwise.
951
- */ enqueueGovernanceCastSignal(governancePayload, slotNumber, timestamp, signerAddress, signer) {
952
- return this.enqueueCastSignalHelper(slotNumber, timestamp, 'governance-signal', governancePayload, this.govProposerContract, signerAddress, signer);
1172
+ */ enqueueGovernanceCastSignal(governancePayload, slotNumber, signerAddress, signer) {
1173
+ return this.enqueueCastSignalHelper(slotNumber, 'governance-signal', governancePayload, this.govProposerContract, signerAddress, signer);
953
1174
  }
954
- /** Enqueues all slashing actions as returned by the slasher client. */ async enqueueSlashingActions(actions, slotNumber, timestamp, signerAddress, signer) {
1175
+ /**
1176
+ * Enqueues a `prune()` transaction if the rollup is prunable at the given slot's L1 timestamp.
1177
+ * `prune()` is permissionless and idempotent — if the chain is no longer prunable by send time the
1178
+ * bundle simulation usually drops the entry; on a node without `eth_simulateV1` the bundle is sent
1179
+ * as-is and the prune reverts `Rollup__NothingToPrune` inside `aggregate3(allowFailure: true)`
1180
+ * (a failed action, never a whole-tx revert). Used by the failed-sync fallback so a stuck pending
1181
+ * chain (e.g. bad data blocking sync) can be wound back to recover.
1182
+ * @returns true if a prune request was enqueued, false otherwise.
1183
+ */ async enqueuePruneIfPrunable(slotNumber) {
1184
+ if (this.lastActions['prune'] === slotNumber) {
1185
+ this.log.debug(`Skipping duplicate prune for slot ${slotNumber}`, {
1186
+ slotNumber
1187
+ });
1188
+ return false;
1189
+ }
1190
+ // Use the SAME timestamp the bundle simulator overrides block.timestamp with at send time
1191
+ // (sequencer-bundle-simulator.ts) so this upfront check and the send-time sim agree. Slot-start
1192
+ // and last-L1-slot both fall within the same L2 slot (and epoch, which is what `canPruneAtTime`
1193
+ // derives), so they agree today; matching the simulator keeps it robust if the contract ever uses
1194
+ // the timestamp more granularly.
1195
+ const ts = getLastL1SlotTimestampForL2Slot(slotNumber, this.epochCache.getL1Constants());
1196
+ const canPrune = await this.rollupContract.canPruneAtTime(ts).catch((err)=>{
1197
+ this.log.error(`Failed to check canPruneAtTime for slot ${slotNumber}`, err, {
1198
+ slotNumber
1199
+ });
1200
+ return false;
1201
+ });
1202
+ if (!canPrune) {
1203
+ this.log.debug(`Rollup not prunable at slot ${slotNumber}`, {
1204
+ slotNumber
1205
+ });
1206
+ return false;
1207
+ }
1208
+ const request = {
1209
+ to: this.rollupContract.address,
1210
+ data: encodeFunctionData({
1211
+ abi: RollupAbi,
1212
+ functionName: 'prune',
1213
+ args: []
1214
+ })
1215
+ };
1216
+ this.log.info(`Enqueuing rollup prune for slot ${slotNumber}`, {
1217
+ slotNumber
1218
+ });
1219
+ return this.enqueueRequest('prune', request, {
1220
+ address: this.rollupContract.address,
1221
+ abi: RollupAbi,
1222
+ eventName: 'PrunedPending'
1223
+ }, slotNumber);
1224
+ }
1225
+ /** Enqueues all slashing actions as returned by the slasher client. */ async enqueueSlashingActions(actions, slotNumber, signerAddress, signer) {
955
1226
  if (actions.length === 0) {
956
1227
  this.log.debug(`No slashing actions to enqueue for slot ${slotNumber}`);
957
1228
  return false;
958
1229
  }
959
1230
  for (const action of actions){
960
1231
  switch(action.type){
961
- case 'vote-empire-payload':
962
- {
963
- if (this.slashingProposerContract?.type !== 'empire') {
964
- this.log.error('Cannot vote for empire payload on non-empire slashing contract');
965
- break;
966
- }
967
- this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
968
- signerAddress
969
- });
970
- await this.enqueueCastSignalHelper(slotNumber, timestamp, 'empire-slashing-signal', action.payload, this.slashingProposerContract, signerAddress, signer);
971
- break;
972
- }
973
- case 'create-empire-payload':
974
- {
975
- this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, {
976
- slotNumber,
977
- signerAddress
978
- });
979
- const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
980
- await this.simulateAndEnqueueRequest('create-empire-payload', request, (receipt)=>!!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs), slotNumber, timestamp);
981
- break;
982
- }
983
- case 'execute-empire-payload':
984
- {
985
- this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, {
986
- slotNumber,
987
- signerAddress
988
- });
989
- if (this.slashingProposerContract?.type !== 'empire') {
990
- this.log.error('Cannot execute slashing payload on non-empire slashing contract');
991
- return false;
992
- }
993
- const empireSlashingProposer = this.slashingProposerContract;
994
- const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
995
- await this.simulateAndEnqueueRequest('execute-empire-payload', request, (receipt)=>!!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs), slotNumber, timestamp);
996
- break;
997
- }
998
1232
  case 'vote-offenses':
999
1233
  {
1000
1234
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
@@ -1003,14 +1237,17 @@ export class SequencerPublisher {
1003
1237
  votesCount: action.votes.length,
1004
1238
  signerAddress
1005
1239
  });
1006
- if (this.slashingProposerContract?.type !== 'tally') {
1007
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1240
+ if (!this.slashingProposerContract) {
1241
+ this.log.error('No slashing proposer contract available');
1008
1242
  return false;
1009
1243
  }
1010
- const tallySlashingProposer = this.slashingProposerContract;
1011
1244
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1012
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
1013
- await this.simulateAndEnqueueRequest('vote-offenses', request, (receipt)=>!!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs), slotNumber, timestamp);
1245
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1246
+ this.enqueueRequest('vote-offenses', request, {
1247
+ address: this.slashingProposerContract.address.toString(),
1248
+ abi: SlashingProposerAbi,
1249
+ eventName: 'VoteCast'
1250
+ }, slotNumber);
1014
1251
  break;
1015
1252
  }
1016
1253
  case 'execute-slash':
@@ -1020,13 +1257,16 @@ export class SequencerPublisher {
1020
1257
  round: action.round,
1021
1258
  signerAddress
1022
1259
  });
1023
- if (this.slashingProposerContract?.type !== 'tally') {
1024
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1260
+ if (!this.slashingProposerContract) {
1261
+ this.log.error('No slashing proposer contract available');
1025
1262
  return false;
1026
1263
  }
1027
- const tallySlashingProposer = this.slashingProposerContract;
1028
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
1029
- await this.simulateAndEnqueueRequest('execute-slash', request, (receipt)=>!!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs), slotNumber, timestamp);
1264
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(action.round, action.committees);
1265
+ this.enqueueRequest('execute-slash', executeRequest, {
1266
+ address: this.slashingProposerContract.address.toString(),
1267
+ abi: SlashingProposerAbi,
1268
+ eventName: 'RoundExecuted'
1269
+ }, slotNumber);
1030
1270
  break;
1031
1271
  }
1032
1272
  default:
@@ -1038,63 +1278,50 @@ export class SequencerPublisher {
1038
1278
  }
1039
1279
  return true;
1040
1280
  }
1041
- /** Simulates and enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1281
+ /** Enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1042
1282
  const checkpointHeader = checkpoint.header;
1043
1283
  const blobFields = checkpoint.toBlobFields();
1044
- const blobs = getBlobsPerL1Block(blobFields);
1284
+ const blobs = await getBlobsPerL1Block(blobFields);
1045
1285
  const proposeTxArgs = {
1046
1286
  header: checkpointHeader,
1047
1287
  archive: checkpoint.archive.root.toBuffer(),
1048
1288
  blobs,
1049
1289
  attestationsAndSigners,
1050
- attestationsAndSignersSignature
1290
+ attestationsAndSignersSignature,
1291
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier
1051
1292
  };
1052
- let ts;
1053
- try {
1054
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
1055
- // This means that we can avoid the simulation issues in later checks.
1056
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
1057
- // make time consistency checks break.
1058
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
1059
- ts = await this.validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts);
1060
- } catch (err) {
1061
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
1062
- ...checkpoint.getStats(),
1063
- slotNumber: checkpoint.header.slotNumber,
1064
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber
1065
- });
1066
- throw err;
1067
- }
1068
1293
  this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1069
1294
  ...checkpoint.toCheckpointInfo(),
1070
- ...opts
1295
+ txTimeoutAt: opts.txTimeoutAt
1296
+ });
1297
+ await this.addProposeTx(checkpoint, proposeTxArgs, {
1298
+ txTimeoutAt: opts.txTimeoutAt
1071
1299
  });
1072
- await this.addProposeTx(checkpoint, proposeTxArgs, opts, ts);
1073
1300
  }
1074
1301
  enqueueInvalidateCheckpoint(request, opts = {}) {
1075
1302
  if (!request) {
1076
1303
  return;
1077
1304
  }
1078
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1079
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(request.gasUsed) * 64 / 63)));
1080
1305
  const { gasUsed, checkpointNumber } = request;
1081
1306
  const logData = {
1082
1307
  gasUsed,
1083
1308
  checkpointNumber,
1084
- gasLimit,
1085
1309
  opts
1086
1310
  };
1087
1311
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1088
1312
  this.addRequest({
1089
1313
  action: `invalidate-by-${request.reason}`,
1090
1314
  request: request.request,
1091
- gasConfig: {
1092
- gasLimit,
1315
+ gasConfig: opts.txTimeoutAt ? {
1093
1316
  txTimeoutAt: opts.txTimeoutAt
1094
- },
1317
+ } : undefined,
1095
1318
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1096
1319
  checkSuccess: (_req, result)=>{
1097
- const success = result && result.receipt && result.receipt.status === 'success' && tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1320
+ const success = result && extractEventSuccess(result.receipt, {
1321
+ address: this.rollupContract.address,
1322
+ abi: RollupAbi,
1323
+ eventName: 'CheckpointInvalidated'
1324
+ });
1098
1325
  if (!success) {
1099
1326
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, {
1100
1327
  ...result,
@@ -1110,57 +1337,36 @@ export class SequencerPublisher {
1110
1337
  }
1111
1338
  });
1112
1339
  }
1113
- async simulateAndEnqueueRequest(action, request, checkSuccess, slotNumber, timestamp) {
1114
- const logData = {
1115
- slotNumber,
1116
- timestamp,
1117
- gasLimit: undefined
1118
- };
1340
+ /**
1341
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1342
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1343
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1344
+ */ enqueueRequest(action, request, eventOpts, slotNumber) {
1119
1345
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1120
1346
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1121
1347
  return false;
1122
1348
  }
1123
1349
  const cachedLastActionSlot = this.lastActions[action];
1124
1350
  this.lastActions[action] = slotNumber;
1125
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1126
- let gasUsed;
1127
- try {
1128
- ({ gasUsed } = await this.l1TxUtils.simulate(request, {
1129
- time: timestamp
1130
- }, [], ErrorsAbi)); // TODO(palla/slash): Check the timestamp logic
1131
- this.log.verbose(`Simulation for ${action} succeeded`, {
1132
- ...logData,
1133
- request,
1134
- gasUsed
1135
- });
1136
- } catch (err) {
1137
- const viemError = formatViemError(err);
1138
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1139
- return false;
1140
- }
1141
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1142
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(gasUsed) * 64 / 63)));
1143
- logData.gasLimit = gasLimit;
1144
- this.log.debug(`Enqueuing ${action}`, logData);
1351
+ this.log.debug(`Enqueuing ${action}`, {
1352
+ slotNumber
1353
+ });
1145
1354
  this.addRequest({
1146
1355
  action,
1147
1356
  request,
1148
- gasConfig: {
1149
- gasLimit
1150
- },
1151
1357
  lastValidL2Slot: slotNumber,
1152
- checkSuccess: (_req, result)=>{
1153
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1358
+ checkSuccess: (_request, result)=>{
1359
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1154
1360
  if (!success) {
1155
1361
  this.log.warn(`Action ${action} at ${slotNumber} failed`, {
1156
1362
  ...result,
1157
- ...logData
1363
+ slotNumber
1158
1364
  });
1159
1365
  this.lastActions[action] = cachedLastActionSlot;
1160
1366
  } else {
1161
1367
  this.log.info(`Action ${action} at ${slotNumber} succeeded`, {
1162
1368
  ...result,
1163
- ...logData
1369
+ slotNumber
1164
1370
  });
1165
1371
  }
1166
1372
  return !!success;
@@ -1175,13 +1381,14 @@ export class SequencerPublisher {
1175
1381
  * A call to `restart` is required before you can continue publishing.
1176
1382
  */ interrupt() {
1177
1383
  this.interrupted = true;
1384
+ this.interruptibleSleep.interrupt();
1178
1385
  this.l1TxUtils.interrupt();
1179
1386
  }
1180
1387
  /** Restarts the publisher after calling `interrupt`. */ restart() {
1181
1388
  this.interrupted = false;
1182
1389
  this.l1TxUtils.restart();
1183
1390
  }
1184
- async prepareProposeTx(encodedData, timestamp, options) {
1391
+ async prepareProposeTx(encodedData) {
1185
1392
  const kzg = Blob.getViemKzgInstance();
1186
1393
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1187
1394
  this.log.debug('Validating blob input', {
@@ -1195,7 +1402,11 @@ export class SequencerPublisher {
1195
1402
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1196
1403
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1197
1404
  } else {
1198
- // Normal mode - use estimateGas with blob inputs
1405
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1406
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1407
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1408
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1409
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1199
1410
  blobEvaluationGas = await this.l1TxUtils.estimateGas(this.getSenderAddress().toString(), {
1200
1411
  to: this.rollupContract.address,
1201
1412
  data: encodeFunctionData({
@@ -1208,10 +1419,38 @@ export class SequencerPublisher {
1208
1419
  }, {}, {
1209
1420
  blobs: encodedData.blobs.map((b)=>b.data),
1210
1421
  kzg
1211
- }).catch((err)=>{
1212
- const { message, metaMessages } = formatViemError(err);
1213
- this.log.error(`Failed to validate blobs`, message, {
1214
- metaMessages
1422
+ }).catch(async (err)=>{
1423
+ const viemError = formatViemError(err);
1424
+ this.log.error(`Failed to validate blobs`, viemError.message, {
1425
+ metaMessages: viemError.metaMessages
1426
+ });
1427
+ const validateBlobsData = encodeFunctionData({
1428
+ abi: RollupAbi,
1429
+ functionName: 'validateBlobs',
1430
+ args: [
1431
+ blobInput
1432
+ ]
1433
+ });
1434
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1435
+ this.backupFailedTx({
1436
+ id: keccak256(validateBlobsData),
1437
+ failureType: 'simulation',
1438
+ request: {
1439
+ to: this.rollupContract.address,
1440
+ data: validateBlobsData
1441
+ },
1442
+ blobData: encodedData.blobs.map((b)=>toHex(b.data)),
1443
+ l1BlockNumber: l1BlockNumber.toString(),
1444
+ error: {
1445
+ message: viemError.message,
1446
+ name: viemError.name
1447
+ },
1448
+ context: {
1449
+ actions: [
1450
+ 'validate-blobs'
1451
+ ],
1452
+ sender: this.getSenderAddress().toString()
1453
+ }
1215
1454
  });
1216
1455
  throw new Error('Failed to validate blobs');
1217
1456
  });
@@ -1222,8 +1461,7 @@ export class SequencerPublisher {
1222
1461
  header: encodedData.header.toViem(),
1223
1462
  archive: toHex(encodedData.archive),
1224
1463
  oracleInput: {
1225
- // We are currently not modifying these. See #9963
1226
- feeAssetPriceModifier: 0n
1464
+ feeAssetPriceModifier: encodedData.feeAssetPriceModifier
1227
1465
  }
1228
1466
  },
1229
1467
  encodedData.attestationsAndSigners.getPackedAttestations(),
@@ -1231,88 +1469,23 @@ export class SequencerPublisher {
1231
1469
  encodedData.attestationsAndSignersSignature.toViemSignature(),
1232
1470
  blobInput
1233
1471
  ];
1234
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1235
- return {
1236
- args,
1237
- blobEvaluationGas,
1238
- rollupData,
1239
- simulationResult
1240
- };
1241
- }
1242
- /**
1243
- * Simulates the propose tx with eth_simulateV1
1244
- * @param args - The propose tx args
1245
- * @param timestamp - The timestamp to simulate proposal at
1246
- * @returns The simulation result
1247
- */ async simulateProposeTx(args, timestamp, options) {
1248
1472
  const rollupData = encodeFunctionData({
1249
1473
  abi: RollupAbi,
1250
1474
  functionName: 'propose',
1251
1475
  args
1252
1476
  });
1253
- // override the pending checkpoint number if requested
1254
- const forcePendingCheckpointNumberStateDiff = (options.forcePendingCheckpointNumber !== undefined ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber) : []).flatMap((override)=>override.stateDiff ?? []);
1255
- const stateOverrides = [
1256
- {
1257
- address: this.rollupContract.address,
1258
- // @note we override checkBlob to false since blobs are not part simulate()
1259
- stateDiff: [
1260
- {
1261
- slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true),
1262
- value: toPaddedHex(0n, true)
1263
- },
1264
- ...forcePendingCheckpointNumberStateDiff
1265
- ]
1266
- }
1267
- ];
1268
- // In fisherman mode, simulate as the proposer but with sufficient balance
1269
- if (this.proposerAddressForSimulation) {
1270
- stateOverrides.push({
1271
- address: this.proposerAddressForSimulation.toString(),
1272
- balance: 10n * WEI_CONST * WEI_CONST
1273
- });
1274
- }
1275
- const simulationResult = await this.l1TxUtils.simulate({
1276
- to: this.rollupContract.address,
1277
- data: rollupData,
1278
- gas: SequencerPublisher.PROPOSE_GAS_GUESS,
1279
- ...this.proposerAddressForSimulation && {
1280
- from: this.proposerAddressForSimulation.toString()
1281
- }
1282
- }, {
1283
- // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
1284
- time: timestamp + 1n,
1285
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1286
- gasLimit: SequencerPublisher.PROPOSE_GAS_GUESS * 2n
1287
- }, stateOverrides, RollupAbi, {
1288
- // @note fallback gas estimate to use if the node doesn't support simulation API
1289
- fallbackGasEstimate: SequencerPublisher.PROPOSE_GAS_GUESS
1290
- }).catch((err)=>{
1291
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1292
- const viemError = formatViemError(err);
1293
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1294
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1295
- // Return a minimal simulation result with the fallback gas estimate
1296
- return {
1297
- gasUsed: SequencerPublisher.PROPOSE_GAS_GUESS,
1298
- logs: []
1299
- };
1300
- }
1301
- this.log.error(`Failed to simulate propose tx`, viemError);
1302
- throw err;
1303
- });
1304
1477
  return {
1305
- rollupData,
1306
- simulationResult
1478
+ args,
1479
+ blobEvaluationGas,
1480
+ rollupData
1307
1481
  };
1308
1482
  }
1309
- async addProposeTx(checkpoint, encodedData, opts = {}, timestamp) {
1483
+ async addProposeTx(checkpoint, encodedData, opts = {}) {
1310
1484
  const slot = checkpoint.header.slotNumber;
1311
1485
  const timer = new Timer();
1312
1486
  const kzg = Blob.getViemKzgInstance();
1313
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, timestamp, opts);
1487
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1314
1488
  const startBlock = await this.l1TxUtils.getBlockNumber();
1315
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(simulationResult.gasUsed) * 64 / 63)) + blobEvaluationGas + SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS);
1316
1489
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1317
1490
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
1318
1491
  void Promise.resolve().then(()=>this.blobClient.sendBlobsToFilestore(encodedData.blobs).catch((_err)=>{
@@ -1326,9 +1499,10 @@ export class SequencerPublisher {
1326
1499
  },
1327
1500
  lastValidL2Slot: checkpoint.header.slotNumber,
1328
1501
  gasConfig: {
1329
- ...opts,
1330
- gasLimit
1502
+ txTimeoutAt: opts.txTimeoutAt,
1503
+ gasLimit: undefined
1331
1504
  },
1505
+ blobEvaluationGas,
1332
1506
  blobConfig: {
1333
1507
  blobs: encodedData.blobs.map((b)=>b.data),
1334
1508
  kzg
@@ -1338,7 +1512,11 @@ export class SequencerPublisher {
1338
1512
  return false;
1339
1513
  }
1340
1514
  const { receipt, stats, errorMsg } = result;
1341
- const success = receipt && receipt.status === 'success' && tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1515
+ const success = extractEventSuccess(receipt, {
1516
+ address: this.rollupContract.address,
1517
+ abi: RollupAbi,
1518
+ eventName: 'CheckpointProposed'
1519
+ });
1342
1520
  if (success) {
1343
1521
  const endBlock = receipt.blockNumber;
1344
1522
  const inclusionBlocks = Number(endBlock - startBlock);
@@ -1375,4 +1553,8 @@ export class SequencerPublisher {
1375
1553
  }
1376
1554
  });
1377
1555
  }
1556
+ /** Returns the timestamp of the next L1 slot boundary after now. */ getNextL1SlotTimestamp() {
1557
+ const l1Constants = this.epochCache.getL1Constants();
1558
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1559
+ }
1378
1560
  }