@aztec/sequencer-client 0.0.1-commit.001888fc → 0.0.1-commit.017a351

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 (105) hide show
  1. package/README.md +281 -21
  2. package/dest/client/sequencer-client.d.ts +8 -15
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +35 -87
  5. package/dest/config.d.ts +4 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +35 -17
  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 +128 -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 +58 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +14 -14
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +16 -51
  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/index.d.ts +2 -2
  21. package/dest/index.d.ts.map +1 -1
  22. package/dest/index.js +1 -1
  23. package/dest/publisher/config.d.ts +15 -3
  24. package/dest/publisher/config.d.ts.map +1 -1
  25. package/dest/publisher/config.js +19 -4
  26. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +3 -4
  27. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  28. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  29. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  30. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  31. package/dest/publisher/sequencer-publisher-factory.d.ts +3 -5
  32. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher-factory.js +2 -3
  34. package/dest/publisher/sequencer-publisher.d.ts +73 -65
  35. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  36. package/dest/publisher/sequencer-publisher.js +314 -532
  37. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  38. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  39. package/dest/sequencer/automine/automine_factory.js +84 -0
  40. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  41. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  42. package/dest/sequencer/automine/automine_sequencer.js +509 -0
  43. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  44. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  45. package/dest/sequencer/chain_state_overrides.js +98 -0
  46. package/dest/sequencer/checkpoint_proposal_job.d.ts +60 -10
  47. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  48. package/dest/sequencer/checkpoint_proposal_job.js +732 -180
  49. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  50. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  51. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  52. package/dest/sequencer/checkpoint_voter.d.ts +1 -2
  53. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -1
  54. package/dest/sequencer/checkpoint_voter.js +2 -5
  55. package/dest/sequencer/events.d.ts +48 -2
  56. package/dest/sequencer/events.d.ts.map +1 -1
  57. package/dest/sequencer/index.d.ts +3 -1
  58. package/dest/sequencer/index.d.ts.map +1 -1
  59. package/dest/sequencer/index.js +2 -0
  60. package/dest/sequencer/metrics.d.ts +13 -10
  61. package/dest/sequencer/metrics.d.ts.map +1 -1
  62. package/dest/sequencer/metrics.js +45 -20
  63. package/dest/sequencer/sequencer.d.ts +62 -14
  64. package/dest/sequencer/sequencer.d.ts.map +1 -1
  65. package/dest/sequencer/sequencer.js +349 -107
  66. package/dest/sequencer/timetable.d.ts +11 -1
  67. package/dest/sequencer/timetable.d.ts.map +1 -1
  68. package/dest/sequencer/timetable.js +41 -36
  69. package/dest/sequencer/types.d.ts +2 -2
  70. package/dest/sequencer/types.d.ts.map +1 -1
  71. package/dest/test/mock_checkpoint_builder.d.ts +4 -8
  72. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -1
  73. package/dest/test/utils.d.ts +1 -1
  74. package/dest/test/utils.d.ts.map +1 -1
  75. package/dest/test/utils.js +7 -6
  76. package/package.json +27 -27
  77. package/src/client/sequencer-client.ts +55 -116
  78. package/src/config.ts +40 -14
  79. package/src/global_variable_builder/README.md +44 -0
  80. package/src/global_variable_builder/fee_predictor.ts +172 -0
  81. package/src/global_variable_builder/fee_provider.ts +75 -0
  82. package/src/global_variable_builder/global_builder.ts +25 -63
  83. package/src/global_variable_builder/index.ts +3 -1
  84. package/src/index.ts +10 -1
  85. package/src/publisher/config.ts +40 -6
  86. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  87. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  88. package/src/publisher/sequencer-publisher-factory.ts +3 -6
  89. package/src/publisher/sequencer-publisher.ts +373 -577
  90. package/src/sequencer/README.md +162 -450
  91. package/src/sequencer/automine/README.md +46 -0
  92. package/src/sequencer/automine/automine_factory.ts +145 -0
  93. package/src/sequencer/automine/automine_sequencer.ts +595 -0
  94. package/src/sequencer/chain_state_overrides.ts +162 -0
  95. package/src/sequencer/checkpoint_proposal_job.ts +872 -207
  96. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  97. package/src/sequencer/checkpoint_voter.ts +1 -12
  98. package/src/sequencer/events.ts +51 -2
  99. package/src/sequencer/index.ts +2 -0
  100. package/src/sequencer/metrics.ts +57 -24
  101. package/src/sequencer/sequencer.ts +429 -121
  102. package/src/sequencer/timetable.ts +49 -44
  103. package/src/sequencer/types.ts +1 -1
  104. package/src/test/mock_checkpoint_builder.ts +3 -3
  105. package/src/test/utils.ts +28 -10
@@ -370,14 +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, 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
377
  import { MAX_L1_TX_LIMIT, WEI_CONST } from '@aztec/ethereum/l1-tx-utils';
378
- import { FormattedViemError, formatViemError, mergeAbis, tryExtractEvent } from '@aztec/ethereum/utils';
379
- import { sumBigint } from '@aztec/foundation/bigint';
380
- import { toHex as toPaddedHex } from '@aztec/foundation/bigint-buffer';
378
+ import { FormattedViemError, formatViemError, mergeAbis, tryDecodeRevertReason, tryExtractEvent } from '@aztec/ethereum/utils';
381
379
  import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
382
380
  import { trimmedBytesLength } from '@aztec/foundation/buffer';
383
381
  import { pick } from '@aztec/foundation/collection';
@@ -385,30 +383,39 @@ import { TimeoutError } from '@aztec/foundation/error';
385
383
  import { EthAddress } from '@aztec/foundation/eth-address';
386
384
  import { Signature } from '@aztec/foundation/eth-signature';
387
385
  import { createLogger } from '@aztec/foundation/log';
388
- import { makeBackoff, retry } from '@aztec/foundation/retry';
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';
392
+ import { getLastL1SlotTimestampForL2Slot, getNextL1SlotTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
394
393
  import { getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
395
- import { encodeFunctionData, keccak256, multicall3Abi, toHex } from 'viem';
394
+ import { encodeFunctionData, keccak256, toHex } from 'viem';
396
395
  import { createL1TxFailedStore } from './l1_tx_failed_store/index.js';
396
+ import { SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
397
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
+ }
398
408
  export const Actions = [
399
409
  'invalidate-by-invalid-attestation',
400
410
  'invalidate-by-insufficient-attestations',
401
411
  'propose',
402
412
  'governance-signal',
403
- 'empire-slashing-signal',
404
- 'create-empire-payload',
405
- 'execute-empire-payload',
406
413
  'vote-offenses',
407
414
  'execute-slash'
408
415
  ];
409
416
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
410
417
  export const compareActions = (a, b)=>Actions.indexOf(a) - Actions.indexOf(b);
411
- _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader'), _dec2 = trackSpan('SequencerPublisher.validateCheckpointForSubmission');
418
+ _dec = trackSpan('SequencerPublisher.sendRequests'), _dec1 = trackSpan('SequencerPublisher.validateBlockHeader');
412
419
  export class SequencerPublisher {
413
420
  config;
414
421
  static{
@@ -422,55 +429,55 @@ export class SequencerPublisher {
422
429
  _dec1,
423
430
  2,
424
431
  "validateBlockHeader"
425
- ],
426
- [
427
- _dec2,
428
- 2,
429
- "validateCheckpointForSubmission"
430
432
  ]
431
433
  ], []));
432
434
  }
433
435
  interrupted;
434
436
  metrics;
437
+ bundleSimulator;
435
438
  epochCache;
436
439
  failedTxStore;
437
- governanceLog;
438
- 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;
439
445
  lastActions;
440
- isPayloadEmptyCache;
441
- payloadProposedCache;
442
446
  log;
443
447
  ethereumSlotDuration;
448
+ aztecSlotDuration;
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
- // A CALL to a cold address is 2700 gas
450
- static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
451
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
452
- static VOTE_GAS_GUESS = 800_000n;
454
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */ interruptibleSleep;
453
455
  l1TxUtils;
454
456
  rollupContract;
455
457
  govProposerContract;
456
458
  slashingProposerContract;
457
- slashFactoryContract;
458
459
  tracer;
459
460
  requests;
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();
471
+ this.interruptibleSleep = new InterruptibleSleep();
468
472
  this.requests = [];
469
473
  this.log = deps.log ?? createLogger('sequencer:publisher');
470
474
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
475
+ this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
476
+ this.dateProvider = deps.dateProvider;
471
477
  this.epochCache = deps.epochCache;
472
478
  this.lastActions = deps.lastActions;
473
479
  this.blobClient = deps.blobClient;
480
+ this.dateProvider = deps.dateProvider;
474
481
  const telemetry = deps.telemetry ?? getTelemetryClient();
475
482
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
476
483
  this.tracer = telemetry.getTracer('SequencerPublisher');
@@ -484,15 +491,20 @@ export class SequencerPublisher {
484
491
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
485
492
  this.slashingProposerContract = newSlashingProposer;
486
493
  });
487
- this.slashFactoryContract = deps.slashFactoryContract;
488
494
  // Initialize L1 fee analyzer for fisherman mode
489
495
  if (config.fishermanMode) {
490
- 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'));
491
497
  }
492
498
  // Initialize fee asset price oracle
493
- 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'));
494
500
  // Initialize failed L1 tx store (optional, for test networks)
495
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
+ });
496
508
  }
497
509
  /**
498
510
  * Backs up a failed L1 transaction to the configured store for debugging.
@@ -515,9 +527,13 @@ export class SequencerPublisher {
515
527
  }
516
528
  /**
517
529
  * Gets the fee asset price modifier from the oracle.
518
- * Returns 0n if the oracle query fails.
519
- */ getFeeAssetPriceModifier() {
520
- 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);
521
537
  }
522
538
  getSenderAddress() {
523
539
  return this.l1TxUtils.getSenderAddress();
@@ -527,17 +543,11 @@ export class SequencerPublisher {
527
543
  */ getL1FeeAnalyzer() {
528
544
  return this.l1FeeAnalyzer;
529
545
  }
530
- /**
531
- * Sets the proposer address to use for simulations in fisherman mode.
532
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
533
- */ setProposerAddressForSimulation(proposerAddress) {
534
- this.proposerAddressForSimulation = proposerAddress;
535
- }
536
546
  addRequest(request) {
537
547
  this.requests.push(request);
538
548
  }
539
549
  getCurrentL2Slot() {
540
- return this.epochCache.getEpochAndSlotNow().slot;
550
+ return this.epochCache.getSlotNow();
541
551
  }
542
552
  /**
543
553
  * Clears all pending requests without sending them.
@@ -590,11 +600,15 @@ export class SequencerPublisher {
590
600
  }
591
601
  /**
592
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.
593
607
  * @returns one of:
594
608
  * - A receipt and stats if the tx succeeded
595
609
  * - a receipt and errorMsg if it failed on L1
596
610
  * - undefined if no valid requests are found OR the tx failed to send.
597
- */ async sendRequests() {
611
+ */ async sendRequests(targetSlot) {
598
612
  const requestsToProcess = [
599
613
  ...this.requests
600
614
  ];
@@ -602,10 +616,9 @@ export class SequencerPublisher {
602
616
  if (this.interrupted || requestsToProcess.length === 0) {
603
617
  return undefined;
604
618
  }
605
- const currentL2Slot = this.getCurrentL2Slot();
619
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
606
620
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
607
621
  const validRequests = requestsToProcess.filter((request)=>request.lastValidL2Slot >= currentL2Slot);
608
- const validActions = validRequests.map((x)=>x.action);
609
622
  const expiredActions = requestsToProcess.filter((request)=>request.lastValidL2Slot < currentL2Slot).map((x)=>x.action);
610
623
  if (validRequests.length !== requestsToProcess.length) {
611
624
  this.log.warn(`Some requests were expired for slot ${currentL2Slot}`, {
@@ -623,71 +636,53 @@ export class SequencerPublisher {
623
636
  this.log.debug(`No valid requests to send`);
624
637
  return undefined;
625
638
  }
626
- // @note - we can only have one blob config per bundle
627
- // find requests with gas and blob configs
628
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
629
- const gasConfigs = requestsToProcess.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
630
- const blobConfigs = requestsToProcess.filter((request)=>request.blobConfig).map((request)=>request.blobConfig);
631
- if (blobConfigs.length > 1) {
632
- throw new Error('Multiple blob configs found');
633
- }
634
- const blobConfig = blobConfigs[0];
635
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
636
- const gasLimits = gasConfigs.map((g)=>g?.gasLimit).filter((g)=>g !== undefined);
637
- let gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
638
- // Cap at L1 block gas limit so the node accepts the tx ("gas limit too high" otherwise).
639
- const maxGas = MAX_L1_TX_LIMIT;
640
- if (gasLimit !== undefined && gasLimit > maxGas) {
641
- this.log.debug('Capping bundled tx gas limit to L1 max', {
642
- requested: gasLimit,
643
- capped: maxGas
644
- });
645
- gasLimit = maxGas;
646
- }
639
+ // Collect earliest txTimeoutAt across all requests.
640
+ const gasConfigs = validRequests.filter((request)=>request.gasConfig).map((request)=>request.gasConfig);
647
641
  const txTimeoutAts = gasConfigs.map((g)=>g?.txTimeoutAt).filter((g)=>g !== undefined);
648
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined; // earliest
649
- const txConfig = {
650
- gasLimit,
651
- txTimeoutAt
652
- };
642
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map((g)=>g.getTime()))) : undefined;
653
643
  // Sort the requests so that proposals always go first
654
644
  // This ensures the committee gets precomputed correctly
655
645
  validRequests.sort((a, b)=>compareActions(a.action, b.action));
656
646
  try {
657
- // Capture context for failed tx backup before sending
658
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
659
- const multicallData = encodeFunctionData({
660
- abi: multicall3Abi,
661
- functionName: 'aggregate3',
662
- args: [
663
- validRequests.map((r)=>({
664
- target: r.request.to,
665
- callData: r.request.data,
666
- allowFailure: true
667
- }))
668
- ]
669
- });
670
- const blobDataHex = blobConfig?.blobs?.map((b)=>toHex(b));
671
- const txContext = {
672
- multicallData,
673
- blobData: blobDataHex,
674
- 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
675
666
  };
676
667
  this.log.debug('Forwarding transactions', {
677
- validRequests: validRequests.map((request)=>request.action),
668
+ requests: requests.map((request)=>request.action),
678
669
  txConfig
679
670
  });
680
- const result = await this.forwardWithPublisherRotation(validRequests, txConfig, blobConfig);
671
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
681
672
  if (result === undefined) {
682
673
  return undefined;
683
674
  }
684
- 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
+ ];
685
680
  return {
686
681
  result,
687
682
  expiredActions,
688
- sentActions: validActions,
683
+ sentActions: requests.map((x)=>x.action),
689
684
  successfulActions,
690
- failedActions
685
+ failedActions: allFailedActions
691
686
  };
692
687
  } catch (err) {
693
688
  const viemError = formatViemError(err);
@@ -701,23 +696,78 @@ export class SequencerPublisher {
701
696
  }
702
697
  }
703
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
+ }
704
736
  /**
705
737
  * Forwards transactions via Multicall3, rotating to the next available publisher if a send
706
738
  * failure occurs (i.e. the tx never reached the chain).
707
739
  * On-chain reverts and simulation errors are returned as-is without rotation.
708
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;
709
745
  const triedAddresses = [];
710
746
  let currentPublisher = this.l1TxUtils;
711
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
+ }
712
754
  triedAddresses.push(currentPublisher.getSenderAddress());
713
755
  try {
714
- 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
+ });
715
759
  this.l1TxUtils = currentPublisher;
716
760
  return result;
717
761
  } catch (err) {
718
762
  if (err instanceof TimeoutError) {
719
763
  throw err;
720
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
+ }
721
771
  const viemError = formatViemError(err);
722
772
  if (!this.getNextPublisher) {
723
773
  this.log.error('Failed to publish bundled transactions', viemError);
@@ -728,119 +778,91 @@ export class SequencerPublisher {
728
778
  ...triedAddresses
729
779
  ]);
730
780
  if (!nextPublisher) {
731
- 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
+ });
732
784
  return undefined;
733
785
  }
734
786
  currentPublisher = nextPublisher;
735
787
  }
736
788
  }
737
789
  }
738
- callbackBundledTransactions(requests, result, txContext) {
739
- const actionsListStr = requests.map((r)=>r.action).join(', ');
740
- if (result instanceof FormattedViemError) {
741
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
742
- this.backupFailedTx({
743
- id: keccak256(txContext.multicallData),
744
- failureType: 'send-error',
745
- request: {
746
- to: MULTI_CALL_3_ADDRESS,
747
- data: txContext.multicallData
748
- },
749
- blobData: txContext.blobData,
750
- l1BlockNumber: txContext.l1BlockNumber.toString(),
751
- error: {
752
- message: result.message,
753
- name: result.name
754
- },
755
- context: {
756
- actions: requests.map((r)=>r.action),
757
- requests: requests.map((r)=>({
758
- action: r.action,
759
- to: r.request.to,
760
- data: r.request.data
761
- })),
762
- sender: this.getSenderAddress().toString()
763
- }
764
- });
765
- return {
766
- failedActions: requests.map((r)=>r.action)
767
- };
768
- } else {
769
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
770
- result,
771
- requests: requests.map((r)=>({
772
- ...r,
773
- // Avoid logging large blob data
774
- blobConfig: r.blobConfig ? {
775
- ...r.blobConfig,
776
- blobs: r.blobConfig.blobs.map((b)=>({
777
- size: trimmedBytesLength(b)
778
- }))
779
- } : undefined
780
- }))
790
+ /*
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.
796
+ * Uses InterruptibleSleep so it can be cancelled via interrupt().
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;
804
+ const sleepMs = submitAfterMs - this.dateProvider.now();
805
+ if (sleepMs > 0) {
806
+ this.log.debug(`Sleeping ${sleepMs}ms before sending requests`, {
807
+ targetSlot,
808
+ submitAfterMs
781
809
  });
782
- const successfulActions = [];
783
- const failedActions = [];
784
- for (const request of requests){
785
- if (request.checkSuccess(request.request, result)) {
786
- successfulActions.push(request.action);
787
- } else {
788
- failedActions.push(request.action);
789
- }
790
- }
791
- // Single backup for the whole reverted tx
792
- if (failedActions.length > 0 && result?.receipt?.status === 'reverted') {
793
- this.backupFailedTx({
794
- id: result.receipt.transactionHash,
795
- failureType: 'revert',
796
- request: {
797
- to: MULTI_CALL_3_ADDRESS,
798
- data: txContext.multicallData
799
- },
800
- blobData: txContext.blobData,
801
- l1BlockNumber: result.receipt.blockNumber.toString(),
802
- receipt: {
803
- transactionHash: result.receipt.transactionHash,
804
- blockNumber: result.receipt.blockNumber.toString(),
805
- gasUsed: (result.receipt.gasUsed ?? 0n).toString(),
806
- status: 'reverted'
807
- },
808
- error: {
809
- message: result.errorMsg ?? 'Transaction reverted'
810
- },
811
- context: {
812
- actions: failedActions,
813
- requests: requests.filter((r)=>failedActions.includes(r.action)).map((r)=>({
814
- action: r.action,
815
- to: r.request.to,
816
- data: r.request.data
817
- })),
818
- sender: this.getSenderAddress().toString()
819
- }
820
- });
810
+ await this.interruptibleSleep.sleep(sleepMs);
811
+ }
812
+ if (this.interrupted) {
813
+ return undefined;
814
+ }
815
+ return this.sendRequests(targetSlot);
816
+ }
817
+ callbackBundledTransactions(requests, result) {
818
+ const actionsListStr = requests.map((r)=>r.action).join(', ');
819
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
820
+ result,
821
+ requests: requests.map((r)=>({
822
+ ...r,
823
+ // Avoid logging large blob data
824
+ blobConfig: r.blobConfig ? {
825
+ ...r.blobConfig,
826
+ blobs: r.blobConfig.blobs.map((b)=>({
827
+ size: trimmedBytesLength(b)
828
+ }))
829
+ } : undefined
830
+ }))
831
+ });
832
+ const successfulActions = [];
833
+ const failedActions = [];
834
+ for (const request of requests){
835
+ if (request.checkSuccess(request.request, result)) {
836
+ successfulActions.push(request.action);
837
+ } else {
838
+ failedActions.push(request.action);
821
839
  }
822
- return {
823
- successfulActions,
824
- failedActions
825
- };
826
840
  }
841
+ return {
842
+ successfulActions,
843
+ failedActions
844
+ };
827
845
  }
828
846
  /**
829
- * @notice Will call `canProposeAtNextEthBlock` to make sure that it is possible to propose
847
+ * @notice Will call `canProposeAt` to make sure that it is possible to propose
830
848
  * @param tipArchive - The archive to check
831
849
  * @returns The slot and block number if it is possible to propose, undefined otherwise
832
- */ canProposeAtNextEthBlock(tipArchive, msgSender, opts = {}) {
850
+ */ async canProposeAt(tipArchive, msgSender, simulationOverridesPlan) {
833
851
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
834
- const ignoredErrors = [
852
+ // These errors are expected when we cannot actually propose right now — usually because our
853
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
854
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
855
+ // skip the proposal; we do NOT treat these as bugs.
856
+ const expectedErrors = [
835
857
  'SlotAlreadyInChain',
836
858
  'InvalidProposer',
837
859
  'InvalidArchive'
838
860
  ];
839
- return this.rollupContract.canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
840
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber
841
- }).catch((err)=>{
842
- if (err instanceof FormattedViemError && ignoredErrors.find((e)=>err.message.includes(e))) {
843
- this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find((e)=>err.message.includes(e))}`, {
861
+ const slotOffset = this.aztecSlotDuration;
862
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
863
+ return this.rollupContract.canProposeAt(tipArchive.toBuffer(), msgSender.toString(), nextL1SlotTs, await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan)).catch((err)=>{
864
+ if (err instanceof FormattedViemError && expectedErrors.find((e)=>err.message.includes(e))) {
865
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find((e)=>err.message.includes(e))}`, {
844
866
  error: err.message
845
867
  });
846
868
  } else {
@@ -854,22 +876,23 @@ export class SequencerPublisher {
854
876
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
855
877
  * It will throw if the block header is invalid.
856
878
  * @param header - The block header to validate
857
- */ async validateBlockHeader(header, opts) {
879
+ */ async validateBlockHeader(header, simulationOverridesPlan) {
858
880
  const flags = {
859
881
  ignoreDA: true,
860
882
  ignoreSignatures: true
861
883
  };
862
884
  const args = [
863
885
  header.toViem(),
864
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
886
+ CommitteeAttestationsAndSigners.packAttestations([]),
865
887
  [],
866
888
  Signature.empty().toViemSignature(),
867
889
  `0x${'0'.repeat(64)}`,
868
890
  header.blobsHash.toString(),
869
891
  flags
870
892
  ];
871
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
872
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(opts?.forcePendingCheckpointNumber);
893
+ const l1Constants = this.epochCache.getL1Constants();
894
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
895
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
873
896
  let balance = 0n;
874
897
  if (this.config.fishermanMode) {
875
898
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -891,7 +914,7 @@ export class SequencerPublisher {
891
914
  }),
892
915
  from: MULTI_CALL_3_ADDRESS
893
916
  }, {
894
- time: ts + 1n
917
+ time: ts
895
918
  }, stateOverrides);
896
919
  this.log.debug(`Simulated validateHeader`);
897
920
  }
@@ -937,6 +960,7 @@ export class SequencerPublisher {
937
960
  gasUsed,
938
961
  checkpointNumber,
939
962
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
963
+ lastArchive: validationResult.checkpoint.lastArchive,
940
964
  reason
941
965
  };
942
966
  } catch (err) {
@@ -949,8 +973,8 @@ export class SequencerPublisher {
949
973
  request,
950
974
  error: viemError.message
951
975
  });
952
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
953
- if (latestPendingCheckpointNumber < checkpointNumber) {
976
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
977
+ if (latestProposedCheckpointNumber < checkpointNumber) {
954
978
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, {
955
979
  ...logData
956
980
  });
@@ -1000,7 +1024,7 @@ export class SequencerPublisher {
1000
1024
  reason
1001
1025
  };
1002
1026
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
1003
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(validationResult.attestations).getPackedAttestations();
1027
+ const attestationsAndSigners = CommitteeAttestationsAndSigners.packAttestations(validationResult.attestations);
1004
1028
  if (reason === 'invalid-attestation') {
1005
1029
  return this.rollupContract.buildInvalidateBadAttestationRequest(checkpoint.checkpointNumber, attestationsAndSigners, committee, validationResult.invalidIndex);
1006
1030
  } else if (reason === 'insufficient-attestations') {
@@ -1010,28 +1034,7 @@ export class SequencerPublisher {
1010
1034
  throw new Error(`Unknown reason for invalidation`);
1011
1035
  }
1012
1036
  }
1013
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */ async validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, options) {
1014
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
1015
- const blobFields = checkpoint.toBlobFields();
1016
- const blobs = await getBlobsPerL1Block(blobFields);
1017
- const blobInput = getPrefixedEthBlobCommitments(blobs);
1018
- const args = [
1019
- {
1020
- header: checkpoint.header.toViem(),
1021
- archive: toHex(checkpoint.archive.root.toBuffer()),
1022
- oracleInput: {
1023
- feeAssetPriceModifier: checkpoint.feeAssetPriceModifier
1024
- }
1025
- },
1026
- attestationsAndSigners.getPackedAttestations(),
1027
- attestationsAndSigners.getSigners().map((signer)=>signer.toString()),
1028
- attestationsAndSignersSignature.toViemSignature(),
1029
- blobInput
1030
- ];
1031
- await this.simulateProposeTx(args, ts, options);
1032
- return ts;
1033
- }
1034
- async enqueueCastSignalHelper(slotNumber, timestamp, signalType, payload, base, signerAddress, signer) {
1037
+ async enqueueCastSignalHelper(slotNumber, signalType, payload, base, signerAddress, signer) {
1035
1038
  if (this.lastActions[signalType] && this.lastActions[signalType] === slotNumber) {
1036
1039
  this.log.debug(`Skipping duplicate vote cast signal ${signalType} for slot ${slotNumber}`);
1037
1040
  return false;
@@ -1051,30 +1054,26 @@ export class SequencerPublisher {
1051
1054
  if (roundInfo.lastSignalSlot >= slotNumber) {
1052
1055
  return false;
1053
1056
  }
1054
- if (await this.isPayloadEmpty(payload)) {
1057
+ if (await base.isPayloadEmpty(payload)) {
1055
1058
  this.log.warn(`Skipping vote cast for payload with empty code`);
1056
1059
  return false;
1057
1060
  }
1058
- // Check if payload was already submitted to governance
1059
- const cacheKey = payload.toString();
1060
- if (!this.payloadProposedCache.has(cacheKey)) {
1061
- try {
1062
- const l1StartBlock = await this.rollupContract.getL1StartBlock();
1063
- const proposed = await retry(()=>base.hasPayloadBeenProposed(payload.toString(), l1StartBlock), 'Check if payload was proposed', makeBackoff([
1064
- 0,
1065
- 1,
1066
- 2
1067
- ]), this.log, true);
1068
- if (proposed) {
1069
- this.payloadProposedCache.add(cacheKey);
1070
- }
1071
- } catch (err) {
1072
- this.log.warn(`Failed to check if payload ${payload} was proposed after retries, skipping signal`, err);
1073
- return false;
1074
- }
1061
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
1062
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
1063
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
1064
+ // the same payload in a future round.
1065
+ let proposed = false;
1066
+ try {
1067
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
1068
+ } catch (err) {
1069
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
1070
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
1071
+ // participation entirely; failing open at worst produces a duplicate signal that the
1072
+ // contract will simply count alongside others in the round.
1073
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
1075
1074
  }
1076
- if (this.payloadProposedCache.has(cacheKey)) {
1077
- this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
1075
+ if (proposed) {
1076
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
1078
1077
  return false;
1079
1078
  }
1080
1079
  const cachedLastVote = this.lastActions[signalType];
@@ -1087,53 +1086,17 @@ export class SequencerPublisher {
1087
1086
  signer: this.l1TxUtils.client.account?.address,
1088
1087
  lastValidL2Slot: slotNumber
1089
1088
  });
1090
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1091
- try {
1092
- await this.l1TxUtils.simulate(request, {
1093
- time: timestamp
1094
- }, [], mergeAbis([
1095
- request.abi ?? [],
1096
- ErrorsAbi
1097
- ]));
1098
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, {
1099
- request
1100
- });
1101
- } catch (err) {
1102
- const viemError = formatViemError(err);
1103
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, viemError);
1104
- this.backupFailedTx({
1105
- id: keccak256(request.data),
1106
- failureType: 'simulation',
1107
- request: {
1108
- to: request.to,
1109
- data: request.data,
1110
- value: request.value?.toString()
1111
- },
1112
- l1BlockNumber: l1BlockNumber.toString(),
1113
- error: {
1114
- message: viemError.message,
1115
- name: viemError.name
1116
- },
1117
- context: {
1118
- actions: [
1119
- action
1120
- ],
1121
- slot: slotNumber,
1122
- sender: this.getSenderAddress().toString()
1123
- }
1124
- });
1125
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
1126
- }
1127
1089
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
1128
1090
  this.addRequest({
1129
- gasConfig: {
1130
- gasLimit: SequencerPublisher.VOTE_GAS_GUESS
1131
- },
1132
1091
  action,
1133
1092
  request,
1134
1093
  lastValidL2Slot: slotNumber,
1135
1094
  checkSuccess: (_request, result)=>{
1136
- const success = result && result.receipt && result.receipt.status === 'success' && tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
1095
+ const success = result && extractEventSuccess(result.receipt, {
1096
+ address: base.address.toString(),
1097
+ abi: EmpireBaseAbi,
1098
+ eventName: 'SignalCast'
1099
+ });
1137
1100
  const logData = {
1138
1101
  ...result,
1139
1102
  slotNumber,
@@ -1152,68 +1115,20 @@ export class SequencerPublisher {
1152
1115
  });
1153
1116
  return true;
1154
1117
  }
1155
- async isPayloadEmpty(payload) {
1156
- const key = payload.toString();
1157
- const cached = this.isPayloadEmptyCache.get(key);
1158
- if (cached) {
1159
- return cached;
1160
- }
1161
- const isEmpty = !await this.l1TxUtils.getCode(payload);
1162
- this.isPayloadEmptyCache.set(key, isEmpty);
1163
- return isEmpty;
1164
- }
1165
1118
  /**
1166
1119
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
1167
1120
  * @param slotNumber - The slot number to cast a signal for.
1168
- * @param timestamp - The timestamp of the slot to cast a signal for.
1169
1121
  * @returns True if the signal was successfully enqueued, false otherwise.
1170
- */ enqueueGovernanceCastSignal(governancePayload, slotNumber, timestamp, signerAddress, signer) {
1171
- return this.enqueueCastSignalHelper(slotNumber, timestamp, 'governance-signal', governancePayload, this.govProposerContract, signerAddress, signer);
1122
+ */ enqueueGovernanceCastSignal(governancePayload, slotNumber, signerAddress, signer) {
1123
+ return this.enqueueCastSignalHelper(slotNumber, 'governance-signal', governancePayload, this.govProposerContract, signerAddress, signer);
1172
1124
  }
1173
- /** Enqueues all slashing actions as returned by the slasher client. */ async enqueueSlashingActions(actions, slotNumber, timestamp, signerAddress, signer) {
1125
+ /** Enqueues all slashing actions as returned by the slasher client. */ async enqueueSlashingActions(actions, slotNumber, signerAddress, signer) {
1174
1126
  if (actions.length === 0) {
1175
1127
  this.log.debug(`No slashing actions to enqueue for slot ${slotNumber}`);
1176
1128
  return false;
1177
1129
  }
1178
1130
  for (const action of actions){
1179
1131
  switch(action.type){
1180
- case 'vote-empire-payload':
1181
- {
1182
- if (this.slashingProposerContract?.type !== 'empire') {
1183
- this.log.error('Cannot vote for empire payload on non-empire slashing contract');
1184
- break;
1185
- }
1186
- this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
1187
- signerAddress
1188
- });
1189
- await this.enqueueCastSignalHelper(slotNumber, timestamp, 'empire-slashing-signal', action.payload, this.slashingProposerContract, signerAddress, signer);
1190
- break;
1191
- }
1192
- case 'create-empire-payload':
1193
- {
1194
- this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, {
1195
- slotNumber,
1196
- signerAddress
1197
- });
1198
- const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
1199
- await this.simulateAndEnqueueRequest('create-empire-payload', request, (receipt)=>!!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs), slotNumber, timestamp);
1200
- break;
1201
- }
1202
- case 'execute-empire-payload':
1203
- {
1204
- this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, {
1205
- slotNumber,
1206
- signerAddress
1207
- });
1208
- if (this.slashingProposerContract?.type !== 'empire') {
1209
- this.log.error('Cannot execute slashing payload on non-empire slashing contract');
1210
- return false;
1211
- }
1212
- const empireSlashingProposer = this.slashingProposerContract;
1213
- const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
1214
- await this.simulateAndEnqueueRequest('execute-empire-payload', request, (receipt)=>!!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs), slotNumber, timestamp);
1215
- break;
1216
- }
1217
1132
  case 'vote-offenses':
1218
1133
  {
1219
1134
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
@@ -1222,14 +1137,17 @@ export class SequencerPublisher {
1222
1137
  votesCount: action.votes.length,
1223
1138
  signerAddress
1224
1139
  });
1225
- if (this.slashingProposerContract?.type !== 'tally') {
1226
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1140
+ if (!this.slashingProposerContract) {
1141
+ this.log.error('No slashing proposer contract available');
1227
1142
  return false;
1228
1143
  }
1229
- const tallySlashingProposer = this.slashingProposerContract;
1230
1144
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
1231
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
1232
- await this.simulateAndEnqueueRequest('vote-offenses', request, (receipt)=>!!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs), slotNumber, timestamp);
1145
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1146
+ this.enqueueRequest('vote-offenses', request, {
1147
+ address: this.slashingProposerContract.address.toString(),
1148
+ abi: SlashingProposerAbi,
1149
+ eventName: 'VoteCast'
1150
+ }, slotNumber);
1233
1151
  break;
1234
1152
  }
1235
1153
  case 'execute-slash':
@@ -1239,13 +1157,16 @@ export class SequencerPublisher {
1239
1157
  round: action.round,
1240
1158
  signerAddress
1241
1159
  });
1242
- if (this.slashingProposerContract?.type !== 'tally') {
1243
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1160
+ if (!this.slashingProposerContract) {
1161
+ this.log.error('No slashing proposer contract available');
1244
1162
  return false;
1245
1163
  }
1246
- const tallySlashingProposer = this.slashingProposerContract;
1247
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
1248
- await this.simulateAndEnqueueRequest('execute-slash', request, (receipt)=>!!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs), slotNumber, timestamp);
1164
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(action.round, action.committees);
1165
+ this.enqueueRequest('execute-slash', executeRequest, {
1166
+ address: this.slashingProposerContract.address.toString(),
1167
+ abi: SlashingProposerAbi,
1168
+ eventName: 'RoundExecuted'
1169
+ }, slotNumber);
1249
1170
  break;
1250
1171
  }
1251
1172
  default:
@@ -1257,7 +1178,7 @@ export class SequencerPublisher {
1257
1178
  }
1258
1179
  return true;
1259
1180
  }
1260
- /** Simulates and enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1181
+ /** Enqueues a proposal for a checkpoint on L1 */ async enqueueProposeCheckpoint(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts = {}) {
1261
1182
  const checkpointHeader = checkpoint.header;
1262
1183
  const blobFields = checkpoint.toBlobFields();
1263
1184
  const blobs = await getBlobsPerL1Block(blobFields);
@@ -1269,52 +1190,38 @@ export class SequencerPublisher {
1269
1190
  attestationsAndSignersSignature,
1270
1191
  feeAssetPriceModifier: checkpoint.feeAssetPriceModifier
1271
1192
  };
1272
- let ts;
1273
- try {
1274
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
1275
- // This means that we can avoid the simulation issues in later checks.
1276
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
1277
- // make time consistency checks break.
1278
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
1279
- ts = await this.validateCheckpointForSubmission(checkpoint, attestationsAndSigners, attestationsAndSignersSignature, opts);
1280
- } catch (err) {
1281
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
1282
- ...checkpoint.getStats(),
1283
- slotNumber: checkpoint.header.slotNumber,
1284
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber
1285
- });
1286
- throw err;
1287
- }
1288
1193
  this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1289
1194
  ...checkpoint.toCheckpointInfo(),
1290
- ...opts
1195
+ txTimeoutAt: opts.txTimeoutAt
1196
+ });
1197
+ await this.addProposeTx(checkpoint, proposeTxArgs, {
1198
+ txTimeoutAt: opts.txTimeoutAt
1291
1199
  });
1292
- await this.addProposeTx(checkpoint, proposeTxArgs, opts, ts);
1293
1200
  }
1294
1201
  enqueueInvalidateCheckpoint(request, opts = {}) {
1295
1202
  if (!request) {
1296
1203
  return;
1297
1204
  }
1298
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1299
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(request.gasUsed) * 64 / 63)));
1300
1205
  const { gasUsed, checkpointNumber } = request;
1301
1206
  const logData = {
1302
1207
  gasUsed,
1303
1208
  checkpointNumber,
1304
- gasLimit,
1305
1209
  opts
1306
1210
  };
1307
1211
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
1308
1212
  this.addRequest({
1309
1213
  action: `invalidate-by-${request.reason}`,
1310
1214
  request: request.request,
1311
- gasConfig: {
1312
- gasLimit,
1215
+ gasConfig: opts.txTimeoutAt ? {
1313
1216
  txTimeoutAt: opts.txTimeoutAt
1314
- },
1217
+ } : undefined,
1315
1218
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
1316
1219
  checkSuccess: (_req, result)=>{
1317
- const success = result && result.receipt && result.receipt.status === 'success' && tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1220
+ const success = result && extractEventSuccess(result.receipt, {
1221
+ address: this.rollupContract.address,
1222
+ abi: RollupAbi,
1223
+ eventName: 'CheckpointInvalidated'
1224
+ });
1318
1225
  if (!success) {
1319
1226
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, {
1320
1227
  ...result,
@@ -1330,89 +1237,36 @@ export class SequencerPublisher {
1330
1237
  }
1331
1238
  });
1332
1239
  }
1333
- async simulateAndEnqueueRequest(action, request, checkSuccess, slotNumber, timestamp) {
1334
- const logData = {
1335
- slotNumber,
1336
- timestamp,
1337
- gasLimit: undefined
1338
- };
1240
+ /**
1241
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1242
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1243
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1244
+ */ enqueueRequest(action, request, eventOpts, slotNumber) {
1339
1245
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
1340
1246
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
1341
1247
  return false;
1342
1248
  }
1343
1249
  const cachedLastActionSlot = this.lastActions[action];
1344
1250
  this.lastActions[action] = slotNumber;
1345
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1346
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1347
- let gasUsed;
1348
- const simulateAbi = mergeAbis([
1349
- request.abi ?? [],
1350
- ErrorsAbi
1351
- ]);
1352
- try {
1353
- ({ gasUsed } = await this.l1TxUtils.simulate(request, {
1354
- time: timestamp
1355
- }, [], simulateAbi)); // TODO(palla/slash): Check the timestamp logic
1356
- this.log.verbose(`Simulation for ${action} succeeded`, {
1357
- ...logData,
1358
- request,
1359
- gasUsed
1360
- });
1361
- } catch (err) {
1362
- const viemError = formatViemError(err, simulateAbi);
1363
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1364
- this.backupFailedTx({
1365
- id: keccak256(request.data),
1366
- failureType: 'simulation',
1367
- request: {
1368
- to: request.to,
1369
- data: request.data,
1370
- value: request.value?.toString()
1371
- },
1372
- l1BlockNumber: l1BlockNumber.toString(),
1373
- error: {
1374
- message: viemError.message,
1375
- name: viemError.name
1376
- },
1377
- context: {
1378
- actions: [
1379
- action
1380
- ],
1381
- slot: slotNumber,
1382
- sender: this.getSenderAddress().toString()
1383
- }
1384
- });
1385
- return false;
1386
- }
1387
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1388
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(gasUsed) * 64 / 63)));
1389
- logData.gasLimit = gasLimit;
1390
- // Store the ABI used for simulation on the request so Multicall3.forward can decode errors
1391
- // when the tx is sent and a revert is diagnosed via simulation.
1392
- const requestWithAbi = {
1393
- ...request,
1394
- abi: simulateAbi
1395
- };
1396
- this.log.debug(`Enqueuing ${action}`, logData);
1251
+ this.log.debug(`Enqueuing ${action}`, {
1252
+ slotNumber
1253
+ });
1397
1254
  this.addRequest({
1398
1255
  action,
1399
- request: requestWithAbi,
1400
- gasConfig: {
1401
- gasLimit
1402
- },
1256
+ request,
1403
1257
  lastValidL2Slot: slotNumber,
1404
- checkSuccess: (_req, result)=>{
1405
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1258
+ checkSuccess: (_request, result)=>{
1259
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1406
1260
  if (!success) {
1407
1261
  this.log.warn(`Action ${action} at ${slotNumber} failed`, {
1408
1262
  ...result,
1409
- ...logData
1263
+ slotNumber
1410
1264
  });
1411
1265
  this.lastActions[action] = cachedLastActionSlot;
1412
1266
  } else {
1413
1267
  this.log.info(`Action ${action} at ${slotNumber} succeeded`, {
1414
1268
  ...result,
1415
- ...logData
1269
+ slotNumber
1416
1270
  });
1417
1271
  }
1418
1272
  return !!success;
@@ -1427,13 +1281,14 @@ export class SequencerPublisher {
1427
1281
  * A call to `restart` is required before you can continue publishing.
1428
1282
  */ interrupt() {
1429
1283
  this.interrupted = true;
1284
+ this.interruptibleSleep.interrupt();
1430
1285
  this.l1TxUtils.interrupt();
1431
1286
  }
1432
1287
  /** Restarts the publisher after calling `interrupt`. */ restart() {
1433
1288
  this.interrupted = false;
1434
1289
  this.l1TxUtils.restart();
1435
1290
  }
1436
- async prepareProposeTx(encodedData, timestamp, options) {
1291
+ async prepareProposeTx(encodedData) {
1437
1292
  const kzg = Blob.getViemKzgInstance();
1438
1293
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1439
1294
  this.log.debug('Validating blob input', {
@@ -1447,7 +1302,11 @@ export class SequencerPublisher {
1447
1302
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1448
1303
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1449
1304
  } else {
1450
- // Normal mode - use estimateGas with blob inputs
1305
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1306
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1307
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1308
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1309
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1451
1310
  blobEvaluationGas = await this.l1TxUtils.estimateGas(this.getSenderAddress().toString(), {
1452
1311
  to: this.rollupContract.address,
1453
1312
  data: encodeFunctionData({
@@ -1510,109 +1369,23 @@ export class SequencerPublisher {
1510
1369
  encodedData.attestationsAndSignersSignature.toViemSignature(),
1511
1370
  blobInput
1512
1371
  ];
1513
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1514
- return {
1515
- args,
1516
- blobEvaluationGas,
1517
- rollupData,
1518
- simulationResult
1519
- };
1520
- }
1521
- /**
1522
- * Simulates the propose tx with eth_simulateV1
1523
- * @param args - The propose tx args
1524
- * @param timestamp - The timestamp to simulate proposal at
1525
- * @returns The simulation result
1526
- */ async simulateProposeTx(args, timestamp, options) {
1527
1372
  const rollupData = encodeFunctionData({
1528
1373
  abi: RollupAbi,
1529
1374
  functionName: 'propose',
1530
1375
  args
1531
1376
  });
1532
- // override the pending checkpoint number if requested
1533
- const forcePendingCheckpointNumberStateDiff = (options.forcePendingCheckpointNumber !== undefined ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber) : []).flatMap((override)=>override.stateDiff ?? []);
1534
- const stateOverrides = [
1535
- {
1536
- address: this.rollupContract.address,
1537
- // @note we override checkBlob to false since blobs are not part simulate()
1538
- stateDiff: [
1539
- {
1540
- slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true),
1541
- value: toPaddedHex(0n, true)
1542
- },
1543
- ...forcePendingCheckpointNumberStateDiff
1544
- ]
1545
- }
1546
- ];
1547
- // In fisherman mode, simulate as the proposer but with sufficient balance
1548
- if (this.proposerAddressForSimulation) {
1549
- stateOverrides.push({
1550
- address: this.proposerAddressForSimulation.toString(),
1551
- balance: 10n * WEI_CONST * WEI_CONST
1552
- });
1553
- }
1554
- const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1555
- const simulationResult = await this.l1TxUtils.simulate({
1556
- to: this.rollupContract.address,
1557
- data: rollupData,
1558
- gas: MAX_L1_TX_LIMIT,
1559
- ...this.proposerAddressForSimulation && {
1560
- from: this.proposerAddressForSimulation.toString()
1561
- }
1562
- }, {
1563
- // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
1564
- time: timestamp + 1n,
1565
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1566
- gasLimit: MAX_L1_TX_LIMIT * 2n
1567
- }, stateOverrides, RollupAbi, {
1568
- // @note fallback gas estimate to use if the node doesn't support simulation API
1569
- fallbackGasEstimate: MAX_L1_TX_LIMIT
1570
- }).catch((err)=>{
1571
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1572
- const viemError = formatViemError(err);
1573
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1574
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1575
- // Return a minimal simulation result with the fallback gas estimate
1576
- return {
1577
- gasUsed: MAX_L1_TX_LIMIT,
1578
- logs: []
1579
- };
1580
- }
1581
- this.log.error(`Failed to simulate propose tx`, viemError);
1582
- this.backupFailedTx({
1583
- id: keccak256(rollupData),
1584
- failureType: 'simulation',
1585
- request: {
1586
- to: this.rollupContract.address,
1587
- data: rollupData
1588
- },
1589
- l1BlockNumber: l1BlockNumber.toString(),
1590
- error: {
1591
- message: viemError.message,
1592
- name: viemError.name
1593
- },
1594
- context: {
1595
- actions: [
1596
- 'propose'
1597
- ],
1598
- slot: Number(args[0].header.slotNumber),
1599
- sender: this.getSenderAddress().toString()
1600
- }
1601
- });
1602
- throw err;
1603
- });
1604
1377
  return {
1605
- rollupData,
1606
- simulationResult
1378
+ args,
1379
+ blobEvaluationGas,
1380
+ rollupData
1607
1381
  };
1608
1382
  }
1609
- async addProposeTx(checkpoint, encodedData, opts = {}, timestamp) {
1383
+ async addProposeTx(checkpoint, encodedData, opts = {}) {
1610
1384
  const slot = checkpoint.header.slotNumber;
1611
1385
  const timer = new Timer();
1612
1386
  const kzg = Blob.getViemKzgInstance();
1613
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, timestamp, opts);
1387
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1614
1388
  const startBlock = await this.l1TxUtils.getBlockNumber();
1615
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil(Number(simulationResult.gasUsed) * 64 / 63)) + blobEvaluationGas + SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS);
1616
1389
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1617
1390
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
1618
1391
  void Promise.resolve().then(()=>this.blobClient.sendBlobsToFilestore(encodedData.blobs).catch((_err)=>{
@@ -1626,9 +1399,10 @@ export class SequencerPublisher {
1626
1399
  },
1627
1400
  lastValidL2Slot: checkpoint.header.slotNumber,
1628
1401
  gasConfig: {
1629
- ...opts,
1630
- gasLimit
1402
+ txTimeoutAt: opts.txTimeoutAt,
1403
+ gasLimit: undefined
1631
1404
  },
1405
+ blobEvaluationGas,
1632
1406
  blobConfig: {
1633
1407
  blobs: encodedData.blobs.map((b)=>b.data),
1634
1408
  kzg
@@ -1638,7 +1412,11 @@ export class SequencerPublisher {
1638
1412
  return false;
1639
1413
  }
1640
1414
  const { receipt, stats, errorMsg } = result;
1641
- const success = receipt && receipt.status === 'success' && tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1415
+ const success = extractEventSuccess(receipt, {
1416
+ address: this.rollupContract.address,
1417
+ abi: RollupAbi,
1418
+ eventName: 'CheckpointProposed'
1419
+ });
1642
1420
  if (success) {
1643
1421
  const endBlock = receipt.blockNumber;
1644
1422
  const inclusionBlocks = Number(endBlock - startBlock);
@@ -1675,4 +1453,8 @@ export class SequencerPublisher {
1675
1453
  }
1676
1454
  });
1677
1455
  }
1456
+ /** Returns the timestamp of the next L1 slot boundary after now. */ getNextL1SlotTimestamp() {
1457
+ const l1Constants = this.epochCache.getL1Constants();
1458
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1459
+ }
1678
1460
  }