@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
@@ -3,50 +3,101 @@ import { Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec/
3
3
  import type { EpochCache } from '@aztec/epoch-cache';
4
4
  import type { L1ContractsConfig } from '@aztec/ethereum/config';
5
5
  import {
6
- type EmpireSlashingProposerContract,
6
+ FeeAssetPriceOracle,
7
7
  type GovernanceProposerContract,
8
- type IEmpireBase,
9
8
  MULTI_CALL_3_ADDRESS,
10
9
  Multicall3,
11
- RollupContract,
12
- type TallySlashingProposerContract,
13
- type ViemCommitteeAttestations,
14
- type ViemHeader,
10
+ MulticallForwarderRevertedError,
11
+ type RollupContract,
12
+ type SimulationOverridesPlan,
13
+ type SlashingProposerContract,
14
+ buildSimulationOverridesStateOverride,
15
15
  } from '@aztec/ethereum/contracts';
16
16
  import { type L1FeeAnalysisResult, L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
17
17
  import {
18
18
  type L1BlobInputs,
19
19
  type L1TxConfig,
20
20
  type L1TxRequest,
21
+ type L1TxUtils,
22
+ MAX_L1_TX_LIMIT,
21
23
  type TransactionStats,
22
24
  WEI_CONST,
23
25
  } from '@aztec/ethereum/l1-tx-utils';
24
- import type { L1TxUtilsWithBlobs } from '@aztec/ethereum/l1-tx-utils-with-blobs';
25
- import { FormattedViemError, formatViemError, tryExtractEvent } from '@aztec/ethereum/utils';
26
- import { sumBigint } from '@aztec/foundation/bigint';
27
- import { toHex as toPaddedHex } from '@aztec/foundation/bigint-buffer';
26
+ import {
27
+ FormattedViemError,
28
+ formatViemError,
29
+ mergeAbis,
30
+ tryDecodeRevertReason,
31
+ tryExtractEvent,
32
+ } from '@aztec/ethereum/utils';
28
33
  import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
34
+ import { trimmedBytesLength } from '@aztec/foundation/buffer';
29
35
  import { pick } from '@aztec/foundation/collection';
30
36
  import type { Fr } from '@aztec/foundation/curves/bn254';
37
+ import { TimeoutError } from '@aztec/foundation/error';
31
38
  import { EthAddress } from '@aztec/foundation/eth-address';
32
- import { Signature, type ViemSignature } from '@aztec/foundation/eth-signature';
39
+ import { Signature } from '@aztec/foundation/eth-signature';
33
40
  import { type Logger, createLogger } from '@aztec/foundation/log';
41
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
34
42
  import { bufferToHex } from '@aztec/foundation/string';
35
- import { DateProvider, Timer } from '@aztec/foundation/timer';
36
- import { EmpireBaseAbi, ErrorsAbi, RollupAbi } from '@aztec/l1-artifacts';
43
+ import { type DateProvider, Timer } from '@aztec/foundation/timer';
44
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi, SlashingProposerAbi } from '@aztec/l1-artifacts';
37
45
  import { type ProposerSlashAction, encodeSlashConsensusVotes } from '@aztec/slasher';
38
46
  import { CommitteeAttestationsAndSigners, type ValidateCheckpointResult } from '@aztec/stdlib/block';
39
47
  import type { Checkpoint } from '@aztec/stdlib/checkpoint';
40
- import { SlashFactoryContract } from '@aztec/stdlib/l1-contracts';
48
+ import {
49
+ getLastL1SlotTimestampForL2Slot,
50
+ getNextL1SlotTimestamp,
51
+ getTimestampForSlot,
52
+ } from '@aztec/stdlib/epoch-helpers';
41
53
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
42
54
  import type { L1PublishCheckpointStats } from '@aztec/stdlib/stats';
43
55
  import { type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
44
56
 
45
- import { type StateOverride, type TransactionReceipt, type TypedDataDefinition, encodeFunctionData, toHex } from 'viem';
46
-
47
- import type { PublisherConfig, TxSenderConfig } from './config.js';
57
+ import {
58
+ type Abi,
59
+ type Hex,
60
+ type TransactionReceipt,
61
+ type TypedDataDefinition,
62
+ encodeFunctionData,
63
+ keccak256,
64
+ toHex,
65
+ } from 'viem';
66
+
67
+ import type { SequencerPublisherConfig } from './config.js';
68
+ import { type FailedL1Tx, type L1TxFailedStore, createL1TxFailedStore } from './l1_tx_failed_store/index.js';
69
+ import { type DroppedRequest, SequencerBundleSimulator } from './sequencer-bundle-simulator.js';
48
70
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
49
71
 
72
+ /**
73
+ * Returns true if the receipt indicates a successful send AND the expected event was emitted
74
+ * by the target contract. Both pieces are required: an aggregate3 entry that reverted will
75
+ * have receipt.status === 'success' but no event log.
76
+ */
77
+ function extractEventSuccess(
78
+ receipt: TransactionReceipt | undefined,
79
+ opts: { address: string; abi: Abi; eventName: string },
80
+ ): boolean {
81
+ if (!receipt || receipt.status !== 'success') {
82
+ return false;
83
+ }
84
+ return !!tryExtractEvent(receipt.logs, opts.address.toString() as Hex, opts.abi, opts.eventName);
85
+ }
86
+
87
+ /** Result of a sendRequests call, returned by both sendRequests() and sendRequestsAt(). */
88
+ export type SendRequestsResult = {
89
+ /** The L1 transaction receipt from the bundled multicall. */
90
+ result: { receipt: TransactionReceipt };
91
+ /** Actions that expired (past their deadline) before the request was sent. */
92
+ expiredActions: Action[];
93
+ /** Actions that were included in the sent L1 transaction. */
94
+ sentActions: Action[];
95
+ /** Actions whose L1 simulation succeeded (subset of sentActions). */
96
+ successfulActions: Action[];
97
+ /** Actions whose L1 simulation failed (subset of sentActions). */
98
+ failedActions: Action[];
99
+ };
100
+
50
101
  /** Arguments to the process method of the rollup contract */
51
102
  type L1ProcessArgs = {
52
103
  /** The L2 block header. */
@@ -59,23 +110,23 @@ type L1ProcessArgs = {
59
110
  attestationsAndSigners: CommitteeAttestationsAndSigners;
60
111
  /** Attestations and signers signature */
61
112
  attestationsAndSignersSignature: Signature;
113
+ /** The fee asset price modifier in basis points (from oracle) */
114
+ feeAssetPriceModifier: bigint;
62
115
  };
63
116
 
64
117
  export const Actions = [
65
118
  'invalidate-by-invalid-attestation',
66
119
  'invalidate-by-insufficient-attestations',
120
+ 'prune',
67
121
  'propose',
68
122
  'governance-signal',
69
- 'empire-slashing-signal',
70
- 'create-empire-payload',
71
- 'execute-empire-payload',
72
123
  'vote-offenses',
73
124
  'execute-slash',
74
125
  ] as const;
75
126
 
76
127
  export type Action = (typeof Actions)[number];
77
128
 
78
- type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slashing-signal'>;
129
+ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
79
130
 
80
131
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
81
132
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
@@ -86,14 +137,22 @@ export type InvalidateCheckpointRequest = {
86
137
  gasUsed: bigint;
87
138
  checkpointNumber: CheckpointNumber;
88
139
  forcePendingCheckpointNumber: CheckpointNumber;
140
+ /** Archive at the rollback target checkpoint (checkpoint N-1). */
141
+ lastArchive: Fr;
89
142
  };
90
143
 
91
- interface RequestWithExpiry {
144
+ type EnqueueProposeCheckpointOpts = {
145
+ txTimeoutAt?: Date;
146
+ };
147
+
148
+ export interface RequestWithExpiry {
92
149
  action: Action;
93
150
  request: L1TxRequest;
94
151
  lastValidL2Slot: SlotNumber;
95
152
  gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
96
153
  blobConfig?: L1BlobInputs;
154
+ /** Gas consumed by validateBlobs; stashed for the bundle simulate at send time. */
155
+ blobEvaluationGas?: bigint;
97
156
  checkSuccess: (
98
157
  request: L1TxRequest,
99
158
  result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
@@ -103,74 +162,92 @@ interface RequestWithExpiry {
103
162
  export class SequencerPublisher {
104
163
  private interrupted = false;
105
164
  private metrics: SequencerPublisherMetrics;
165
+ private bundleSimulator: SequencerBundleSimulator;
106
166
  public epochCache: EpochCache;
167
+ private failedTxStore?: Promise<L1TxFailedStore | undefined>;
107
168
 
108
- protected governanceLog = createLogger('sequencer:publisher:governance');
109
- protected slashingLog = createLogger('sequencer:publisher:slashing');
169
+ /**
170
+ * ABI used to decode raw revert payloads from dropped bundle entries when the original
171
+ * request did not carry an abi (e.g. the propose request). Merges every contract the
172
+ * publisher can route to so any of their custom errors decode against it.
173
+ */
174
+ private readonly revertDecoderAbi: Abi = mergeAbis([RollupAbi, SlashingProposerAbi, EmpireBaseAbi, ErrorsAbi]);
110
175
 
111
176
  protected lastActions: Partial<Record<Action, SlotNumber>> = {};
112
177
 
113
- private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
114
-
115
178
  protected log: Logger;
116
179
  protected ethereumSlotDuration: bigint;
180
+ protected aztecSlotDuration: bigint;
181
+ private readonly previousL1BlockWaitTimeoutMs: number;
182
+ private readonly previousL1BlockWaitPollIntervalMs: number;
183
+
184
+ /** Date provider for wall-clock time. */
185
+ private readonly dateProvider: DateProvider;
117
186
 
118
187
  private blobClient: BlobClientInterface;
119
188
 
120
- /** Address to use for simulations in fisherman mode (actual proposer's address) */
121
- private proposerAddressForSimulation?: EthAddress;
189
+ /** Optional callback to obtain a replacement publisher when the current one fails to send. */
190
+ private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
122
191
 
123
192
  /** L1 fee analyzer for fisherman mode */
124
193
  private l1FeeAnalyzer?: L1FeeAnalyzer;
125
- // @note - with blobs, the below estimate seems too large.
126
- // Total used for full block from int_l1_pub e2e test: 1m (of which 86k is 1x blob)
127
- // Total used for emptier block from above test: 429k (of which 84k is 1x blob)
128
- public static PROPOSE_GAS_GUESS: bigint = 12_000_000n;
129
194
 
130
- // A CALL to a cold address is 2700 gas
131
- public static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
195
+ /** Fee asset price oracle for computing price modifiers from Uniswap V4 */
196
+ private feeAssetPriceOracle: FeeAssetPriceOracle;
132
197
 
133
- // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
134
- public static VOTE_GAS_GUESS: bigint = 800_000n;
198
+ /** Interruptible sleep used by sendRequestsAt to wait until a target timestamp. */
199
+ private readonly interruptibleSleep = new InterruptibleSleep();
135
200
 
136
- public l1TxUtils: L1TxUtilsWithBlobs;
201
+ public l1TxUtils: L1TxUtils;
137
202
  public rollupContract: RollupContract;
138
203
  public govProposerContract: GovernanceProposerContract;
139
- public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
140
- public slashFactoryContract: SlashFactoryContract;
204
+ public slashingProposerContract: SlashingProposerContract | undefined;
141
205
 
142
206
  public readonly tracer: Tracer;
143
207
 
144
208
  protected requests: RequestWithExpiry[] = [];
145
209
 
146
210
  constructor(
147
- private config: TxSenderConfig & PublisherConfig & Pick<L1ContractsConfig, 'ethereumSlotDuration'>,
211
+ private config: Pick<
212
+ SequencerPublisherConfig,
213
+ | 'fishermanMode'
214
+ | 'l1TxFailedStore'
215
+ | 'sequencerPublisherPreviousL1BlockWaitTimeoutMs'
216
+ | 'sequencerPublisherPreviousL1BlockWaitPollIntervalMs'
217
+ > &
218
+ Pick<L1ContractsConfig, 'ethereumSlotDuration' | 'aztecSlotDuration'> & { l1ChainId: number },
148
219
  deps: {
149
220
  telemetry?: TelemetryClient;
150
221
  blobClient: BlobClientInterface;
151
- l1TxUtils: L1TxUtilsWithBlobs;
222
+ l1TxUtils: L1TxUtils;
152
223
  rollupContract: RollupContract;
153
- slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
224
+ slashingProposerContract: SlashingProposerContract | undefined;
154
225
  governanceProposerContract: GovernanceProposerContract;
155
- slashFactoryContract: SlashFactoryContract;
156
226
  epochCache: EpochCache;
157
227
  dateProvider: DateProvider;
158
228
  metrics: SequencerPublisherMetrics;
159
229
  lastActions: Partial<Record<Action, SlotNumber>>;
160
230
  log?: Logger;
231
+ getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
161
232
  },
162
233
  ) {
163
234
  this.log = deps.log ?? createLogger('sequencer:publisher');
164
235
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
236
+ this.aztecSlotDuration = BigInt(config.aztecSlotDuration);
237
+ this.previousL1BlockWaitTimeoutMs = config.sequencerPublisherPreviousL1BlockWaitTimeoutMs;
238
+ this.previousL1BlockWaitPollIntervalMs = config.sequencerPublisherPreviousL1BlockWaitPollIntervalMs;
239
+ this.dateProvider = deps.dateProvider;
165
240
  this.epochCache = deps.epochCache;
166
241
  this.lastActions = deps.lastActions;
167
242
 
168
243
  this.blobClient = deps.blobClient;
244
+ this.dateProvider = deps.dateProvider;
169
245
 
170
246
  const telemetry = deps.telemetry ?? getTelemetryClient();
171
247
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
172
248
  this.tracer = telemetry.getTracer('SequencerPublisher');
173
249
  this.l1TxUtils = deps.l1TxUtils;
250
+ this.getNextPublisher = deps.getNextPublisher;
174
251
 
175
252
  this.rollupContract = deps.rollupContract;
176
253
 
@@ -182,22 +259,71 @@ export class SequencerPublisher {
182
259
  const newSlashingProposer = await this.rollupContract.getSlashingProposer();
183
260
  this.slashingProposerContract = newSlashingProposer;
184
261
  });
185
- this.slashFactoryContract = deps.slashFactoryContract;
186
-
187
262
  // Initialize L1 fee analyzer for fisherman mode
188
263
  if (config.fishermanMode) {
189
264
  this.l1FeeAnalyzer = new L1FeeAnalyzer(
190
265
  this.l1TxUtils.client,
191
266
  deps.dateProvider,
192
- createLogger('sequencer:publisher:fee-analyzer'),
267
+ this.log.createChild('fee-analyzer'),
193
268
  );
194
269
  }
270
+
271
+ // Initialize fee asset price oracle
272
+ this.feeAssetPriceOracle = new FeeAssetPriceOracle(
273
+ this.l1TxUtils.client,
274
+ this.rollupContract,
275
+ this.log.createChild('price-oracle'),
276
+ );
277
+
278
+ // Initialize failed L1 tx store (optional, for test networks)
279
+ this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
280
+
281
+ this.bundleSimulator = new SequencerBundleSimulator({
282
+ getL1TxUtils: () => this.l1TxUtils,
283
+ rollupContract: this.rollupContract,
284
+ epochCache: this.epochCache,
285
+ log: this.log.createChild('bundle-simulator'),
286
+ });
287
+ }
288
+
289
+ /**
290
+ * Backs up a failed L1 transaction to the configured store for debugging.
291
+ * Does nothing if no store is configured.
292
+ */
293
+ private backupFailedTx(failedTx: Omit<FailedL1Tx, 'timestamp'>): void {
294
+ if (!this.failedTxStore) {
295
+ return;
296
+ }
297
+
298
+ const tx: FailedL1Tx = {
299
+ ...failedTx,
300
+ timestamp: Date.now(),
301
+ };
302
+
303
+ // Fire and forget - don't block on backup
304
+ void this.failedTxStore
305
+ .then(store => store?.saveFailedTx(tx))
306
+ .catch(err => {
307
+ this.log.warn(`Failed to backup failed L1 tx to store`, err);
308
+ });
195
309
  }
196
310
 
197
311
  public getRollupContract(): RollupContract {
198
312
  return this.rollupContract;
199
313
  }
200
314
 
315
+ /**
316
+ * Gets the fee asset price modifier from the oracle.
317
+ *
318
+ * @param predictedParentEthPerFeeAssetE12 - Optional predicted parent eth-per-fee-asset (E12).
319
+ * Pipelined proposers should pass the value from the predicted parent fee header so the
320
+ * modifier matches the parent L1 will use when applying it.
321
+ * @returns The fee asset price modifier in basis points, or 0n if the oracle query fails.
322
+ */
323
+ public getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12?: bigint): Promise<bigint> {
324
+ return this.feeAssetPriceOracle.computePriceModifier(predictedParentEthPerFeeAssetE12);
325
+ }
326
+
201
327
  public getSenderAddress() {
202
328
  return this.l1TxUtils.getSenderAddress();
203
329
  }
@@ -209,20 +335,12 @@ export class SequencerPublisher {
209
335
  return this.l1FeeAnalyzer;
210
336
  }
211
337
 
212
- /**
213
- * Sets the proposer address to use for simulations in fisherman mode.
214
- * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
215
- */
216
- public setProposerAddressForSimulation(proposerAddress: EthAddress | undefined) {
217
- this.proposerAddressForSimulation = proposerAddress;
218
- }
219
-
220
338
  public addRequest(request: RequestWithExpiry) {
221
339
  this.requests.push(request);
222
340
  }
223
341
 
224
342
  public getCurrentL2Slot(): SlotNumber {
225
- return this.epochCache.getEpochAndSlotNow().slot;
343
+ return this.epochCache.getSlotNow();
226
344
  }
227
345
 
228
346
  /**
@@ -273,7 +391,7 @@ export class SequencerPublisher {
273
391
  // Start the analysis
274
392
  const analysisId = await this.l1FeeAnalyzer.startAnalysis(
275
393
  l2SlotNumber,
276
- gasLimit > 0n ? gasLimit : SequencerPublisher.PROPOSE_GAS_GUESS,
394
+ gasLimit > 0n ? gasLimit : MAX_L1_TX_LIMIT,
277
395
  l1Requests,
278
396
  blobConfig,
279
397
  onComplete,
@@ -294,22 +412,26 @@ export class SequencerPublisher {
294
412
 
295
413
  /**
296
414
  * Sends all requests that are still valid.
415
+ * @param targetSlot - The target L2 slot for this send. When provided (the production path, via
416
+ * sendRequestsAt), it is threaded into bundleSimulate so the block.timestamp override matches
417
+ * the slot the propose is built for. When omitted, falls back to getCurrentL2Slot() for the
418
+ * AutomineSequencer, which publishes synchronously within the current slot.
297
419
  * @returns one of:
298
420
  * - A receipt and stats if the tx succeeded
299
421
  * - a receipt and errorMsg if it failed on L1
300
422
  * - undefined if no valid requests are found OR the tx failed to send.
301
423
  */
302
424
  @trackSpan('SequencerPublisher.sendRequests')
303
- public async sendRequests() {
425
+ public async sendRequests(targetSlot?: SlotNumber): Promise<SendRequestsResult | undefined> {
304
426
  const requestsToProcess = [...this.requests];
305
427
  this.requests = [];
428
+
306
429
  if (this.interrupted || requestsToProcess.length === 0) {
307
430
  return undefined;
308
431
  }
309
- const currentL2Slot = this.getCurrentL2Slot();
432
+ const currentL2Slot = targetSlot ?? this.getCurrentL2Slot();
310
433
  this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
311
434
  const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
312
- const validActions = validRequests.map(x => x.action);
313
435
  const expiredActions = requestsToProcess
314
436
  .filter(request => request.lastValidL2Slot < currentL2Slot)
315
437
  .map(x => x.action);
@@ -332,44 +454,60 @@ export class SequencerPublisher {
332
454
  return undefined;
333
455
  }
334
456
 
335
- // @note - we can only have one blob config per bundle
336
- // find requests with gas and blob configs
337
- // See https://github.com/AztecProtocol/aztec-packages/issues/11513
338
- const gasConfigs = requestsToProcess.filter(request => request.gasConfig).map(request => request.gasConfig);
339
- const blobConfigs = requestsToProcess.filter(request => request.blobConfig).map(request => request.blobConfig);
340
-
341
- if (blobConfigs.length > 1) {
342
- throw new Error('Multiple blob configs found');
343
- }
344
-
345
- const blobConfig = blobConfigs[0];
346
-
347
- // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
348
- const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
349
- const gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
457
+ // Collect earliest txTimeoutAt across all requests.
458
+ const gasConfigs = validRequests.filter(request => request.gasConfig).map(request => request.gasConfig);
350
459
  const txTimeoutAts = gasConfigs.map(g => g?.txTimeoutAt).filter((g): g is Date => g !== undefined);
351
- const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined; // earliest
352
- const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
460
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined;
353
461
 
354
462
  // Sort the requests so that proposals always go first
355
463
  // This ensures the committee gets precomputed correctly
356
464
  validRequests.sort((a, b) => compareActions(a.action, b.action));
357
465
 
358
466
  try {
467
+ // Bundle-level eth_simulateV1: filters out entries that revert and derives the gasLimit.
468
+ const bundleResult = await this.bundleSimulator.simulate(validRequests, currentL2Slot);
469
+
470
+ if (bundleResult.kind === 'aborted') {
471
+ this.logDroppedInSim(bundleResult.droppedRequests);
472
+ void this.backupDroppedInSim(bundleResult.droppedRequests).catch(err =>
473
+ this.log.error(`Failed to backup requests dropped in simulation`, err),
474
+ );
475
+ return undefined;
476
+ }
477
+
478
+ const { requests, droppedRequests, gasLimit } =
479
+ bundleResult.kind === 'fallback'
480
+ ? {
481
+ requests: bundleResult.requests,
482
+ droppedRequests: bundleResult.droppedRequests,
483
+ gasLimit: MAX_L1_TX_LIMIT,
484
+ }
485
+ : bundleResult;
486
+
487
+ this.logDroppedInSim(droppedRequests);
488
+
489
+ // Compute blobConfig from survivors (not original validRequests) so that if the propose
490
+ // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
491
+ const [blobConfig] = requests.filter(r => r.blobConfig).map(r => r.blobConfig);
492
+ const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
493
+
359
494
  this.log.debug('Forwarding transactions', {
360
- validRequests: validRequests.map(request => request.action),
495
+ requests: requests.map(request => request.action),
361
496
  txConfig,
362
497
  });
363
- const result = await Multicall3.forward(
364
- validRequests.map(request => request.request),
365
- this.l1TxUtils,
366
- txConfig,
367
- blobConfig,
368
- this.rollupContract.address,
369
- this.log,
370
- );
371
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(validRequests, result);
372
- return { result, expiredActions, sentActions: validActions, successfulActions, failedActions };
498
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig);
499
+ if (result === undefined) {
500
+ return undefined;
501
+ }
502
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
503
+ const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action)];
504
+ return {
505
+ result,
506
+ expiredActions,
507
+ sentActions: requests.map(x => x.action),
508
+ successfulActions,
509
+ failedActions: allFailedActions,
510
+ };
373
511
  } catch (err) {
374
512
  const viemError = formatViemError(err);
375
513
  this.log.error(`Failed to publish bundled transactions`, viemError);
@@ -386,49 +524,230 @@ export class SequencerPublisher {
386
524
  }
387
525
  }
388
526
 
527
+ /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */
528
+ private logDroppedInSim(dropped: DroppedRequest[]): void {
529
+ for (const drop of dropped) {
530
+ const revertReasonDecoded = drop.revertReason ?? tryDecodeRevertReason(drop.returnData, this.revertDecoderAbi);
531
+ this.log.warn('Bundle entry dropped: action reverted in sim', {
532
+ action: drop.request.action,
533
+ revertReason: revertReasonDecoded ?? drop.returnData,
534
+ revertReasonDecoded,
535
+ returnData: drop.returnData,
536
+ });
537
+ }
538
+ }
539
+
540
+ /** Backs up entries dropped by bundle simulation, one record per dropped action. */
541
+ private async backupDroppedInSim(dropped: DroppedRequest[]): Promise<void> {
542
+ if (dropped.length === 0) {
543
+ return;
544
+ }
545
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
546
+ for (const { request: req } of dropped) {
547
+ this.backupFailedTx({
548
+ id: keccak256(req.request.data!),
549
+ failureType: 'simulation',
550
+ request: { to: req.request.to! as Hex, data: req.request.data! },
551
+ l1BlockNumber: l1BlockNumber.toString(),
552
+ error: { message: 'Bundle entry dropped: action reverted in sim' },
553
+ context: {
554
+ actions: [req.action],
555
+ sender: this.getSenderAddress().toString(),
556
+ },
557
+ });
558
+ }
559
+ }
560
+
561
+ /**
562
+ * Forwards transactions via Multicall3, rotating to the next available publisher if a send
563
+ * failure occurs (i.e. the tx never reached the chain).
564
+ * On-chain reverts and simulation errors are returned as-is without rotation.
565
+ */
566
+ private async forwardWithPublisherRotation(
567
+ validRequests: RequestWithExpiry[],
568
+ txConfig: RequestWithExpiry['gasConfig'],
569
+ blobConfig: L1BlobInputs | undefined,
570
+ ) {
571
+ if (!txConfig?.gasLimit) {
572
+ throw new Error('gasLimit is required for bundled transactions');
573
+ }
574
+ const txConfigWithGasLimit = txConfig as L1TxConfig & { gasLimit: bigint };
575
+
576
+ const triedAddresses: EthAddress[] = [];
577
+ let currentPublisher = this.l1TxUtils;
578
+
579
+ while (true) {
580
+ if (txConfig.txTimeoutAt && new Date() > txConfig.txTimeoutAt) {
581
+ this.log.warn(`Tx timeout (${txConfig.txTimeoutAt.toISOString()}) elapsed; stopping publisher rotation`, {
582
+ triedAddresses: triedAddresses.map(a => a.toString()),
583
+ });
584
+ return undefined;
585
+ }
586
+ triedAddresses.push(currentPublisher.getSenderAddress());
587
+
588
+ try {
589
+ const result = await Multicall3.forward(
590
+ validRequests.map(r => r.request),
591
+ currentPublisher,
592
+ txConfigWithGasLimit,
593
+ blobConfig,
594
+ { gasLimitRequired: true },
595
+ );
596
+ this.l1TxUtils = currentPublisher;
597
+ return result;
598
+ } catch (err) {
599
+ if (err instanceof TimeoutError) {
600
+ throw err;
601
+ }
602
+ if (err instanceof MulticallForwarderRevertedError) {
603
+ this.log.error('Forwarder transaction reverted on-chain; not rotating publisher', err, {
604
+ transactionHash: err.receipt.transactionHash,
605
+ });
606
+ return undefined;
607
+ }
608
+ const viemError = formatViemError(err);
609
+ if (!this.getNextPublisher) {
610
+ this.log.error('Failed to publish bundled transactions', viemError);
611
+ return undefined;
612
+ }
613
+ this.log.warn(
614
+ `Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`,
615
+ viemError,
616
+ );
617
+ const nextPublisher = await this.getNextPublisher([...triedAddresses]);
618
+ if (!nextPublisher) {
619
+ this.log.error(
620
+ `All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`,
621
+ viemError,
622
+ { triedAddresses: triedAddresses.map(a => a.toString()) },
623
+ );
624
+ return undefined;
625
+ }
626
+ currentPublisher = nextPublisher;
627
+ }
628
+ }
629
+ }
630
+
631
+ /*
632
+ * Schedules sending all enqueued requests at (or after) the start of the given L2 slot.
633
+ */
634
+ public async sendRequestsAt(targetSlot: SlotNumber): Promise<SendRequestsResult | undefined> {
635
+ await this.waitForTargetSlot(targetSlot);
636
+ if (this.interrupted) {
637
+ return undefined;
638
+ }
639
+
640
+ return this.sendRequests(targetSlot);
641
+ }
642
+
643
+ /**
644
+ * Sleeps until one L1 slot before the L2 slot boundary, and then waits for that L1 block
645
+ * to be mined, so we don't risk being included in it. If that block never gets mined after
646
+ * a timeout, we assume it got skipped on L1, so we send the tx anyway.
647
+ */
648
+ private async waitForTargetSlot(targetSlot: SlotNumber): Promise<void> {
649
+ const l1Constants = this.epochCache.getL1Constants();
650
+ const nowInSeconds = this.dateProvider.nowInSeconds();
651
+ const startOfTargetSlotTs = getTimestampForSlot(targetSlot, l1Constants);
652
+ const previousL1BlockTs = startOfTargetSlotTs - this.ethereumSlotDuration;
653
+ const waitDeadlineTs = previousL1BlockTs + BigInt(this.previousL1BlockWaitTimeoutMs / 1000);
654
+ const logCtx = { targetSlot, startOfTargetSlotTs, nowInSeconds, previousL1BlockTs, waitDeadlineTs };
655
+
656
+ // Check if we are already past time
657
+ if (nowInSeconds >= startOfTargetSlotTs) {
658
+ this.log.verbose(`Target slot ${targetSlot} already started, sending requests immediately`, logCtx);
659
+ return;
660
+ }
661
+
662
+ // Otherwise we wait
663
+ this.log.debug(`Waiting for slot ${targetSlot} before sending requests`, logCtx);
664
+
665
+ // Wait until previous L1 block timestamp first
666
+ const sleepMs = (Number(previousL1BlockTs) - nowInSeconds) * 1000;
667
+ if (sleepMs > 0 && !this.interrupted) {
668
+ this.log.trace(`Sleeping ${sleepMs}ms before waiting for previous L1 block`, logCtx);
669
+ await this.interruptibleSleep.sleep(sleepMs);
670
+ }
671
+
672
+ // Then loop until we see the previous L1 block, so we know that we cannot be included in it.
673
+ // We time out after a while, once we are sure that that block is skipped in L1.
674
+ while (!this.interrupted) {
675
+ try {
676
+ const nowInSeconds = this.dateProvider.nowInSeconds();
677
+ logCtx.nowInSeconds = nowInSeconds;
678
+
679
+ if (nowInSeconds >= waitDeadlineTs) {
680
+ this.log.warn(`Timed out waiting for previous L1 block before sending requests, proceeding`, logCtx);
681
+ return;
682
+ }
683
+
684
+ const latestBlockTs = await this.l1TxUtils.getBlock().then(b => b.timestamp);
685
+ if (latestBlockTs >= previousL1BlockTs) {
686
+ this.log.debug(`Previous L1 block mined, proceeding to send requests`, { ...logCtx, latestBlockTs });
687
+ return;
688
+ }
689
+ this.log.trace(`Previous L1 block not mined yet, continuing to wait`, { ...logCtx, latestBlockTs });
690
+ } catch (err) {
691
+ this.log.error(`Error while waiting for previous L1 block before sending requests; retrying`, err, logCtx);
692
+ } finally {
693
+ await this.interruptibleSleep.sleep(this.previousL1BlockWaitPollIntervalMs);
694
+ }
695
+ }
696
+ }
697
+
389
698
  private callbackBundledTransactions(
390
699
  requests: RequestWithExpiry[],
391
- result?: { receipt: TransactionReceipt } | FormattedViemError,
700
+ result: { receipt: TransactionReceipt; multicallData: Hex },
392
701
  ) {
393
702
  const actionsListStr = requests.map(r => r.action).join(', ');
394
- if (result instanceof FormattedViemError) {
395
- this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
396
- return { failedActions: requests.map(r => r.action) };
397
- } else {
398
- this.log.verbose(`Published bundled transactions (${actionsListStr})`, { result, requests });
399
- const successfulActions: Action[] = [];
400
- const failedActions: Action[] = [];
401
- for (const request of requests) {
402
- if (request.checkSuccess(request.request, result)) {
403
- successfulActions.push(request.action);
404
- } else {
405
- failedActions.push(request.action);
406
- }
703
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, {
704
+ result,
705
+ requests: requests.map(r => ({
706
+ ...r,
707
+ // Avoid logging large blob data
708
+ blobConfig: r.blobConfig
709
+ ? { ...r.blobConfig, blobs: r.blobConfig.blobs.map(b => ({ size: trimmedBytesLength(b) })) }
710
+ : undefined,
711
+ })),
712
+ });
713
+ const successfulActions: Action[] = [];
714
+ const failedActions: Action[] = [];
715
+ for (const request of requests) {
716
+ if (request.checkSuccess(request.request, result)) {
717
+ successfulActions.push(request.action);
718
+ } else {
719
+ failedActions.push(request.action);
407
720
  }
408
- return { successfulActions, failedActions };
409
721
  }
722
+ return { successfulActions, failedActions };
410
723
  }
411
724
 
412
725
  /**
413
- * @notice Will call `canProposeAtNextEthBlock` to make sure that it is possible to propose
726
+ * @notice Will call `canProposeAt` to make sure that it is possible to propose
414
727
  * @param tipArchive - The archive to check
415
728
  * @returns The slot and block number if it is possible to propose, undefined otherwise
416
729
  */
417
- public canProposeAtNextEthBlock(
418
- tipArchive: Fr,
419
- msgSender: EthAddress,
420
- opts: { forcePendingCheckpointNumber?: CheckpointNumber } = {},
421
- ) {
730
+ public async canProposeAt(tipArchive: Fr, msgSender: EthAddress, simulationOverridesPlan?: SimulationOverridesPlan) {
422
731
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
423
- const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
732
+ // These errors are expected when we cannot actually propose right now — usually because our
733
+ // local view of the chain is ahead of L1 (proposed parent hasn't landed yet, or someone
734
+ // else has just landed the slot, or the archive override doesn't match). We log a warn and
735
+ // skip the proposal; we do NOT treat these as bugs.
736
+ const expectedErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
737
+
738
+ const slotOffset = this.aztecSlotDuration;
739
+ const nextL1SlotTs = this.getNextL1SlotTimestamp() + slotOffset;
424
740
 
425
741
  return this.rollupContract
426
- .canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
427
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
428
- })
742
+ .canProposeAt(
743
+ tipArchive.toBuffer(),
744
+ msgSender.toString(),
745
+ nextL1SlotTs,
746
+ await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan),
747
+ )
429
748
  .catch(err => {
430
- if (err instanceof FormattedViemError && ignoredErrors.find(e => err.message.includes(e))) {
431
- this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find(e => err.message.includes(e))}`, {
749
+ if (err instanceof FormattedViemError && expectedErrors.find(e => err.message.includes(e))) {
750
+ this.log.warn(`Failed canProposeAtTime check with ${expectedErrors.find(e => err.message.includes(e))}`, {
432
751
  error: err.message,
433
752
  });
434
753
  } else {
@@ -437,6 +756,7 @@ export class SequencerPublisher {
437
756
  return undefined;
438
757
  });
439
758
  }
759
+
440
760
  /**
441
761
  * @notice Will simulate `validateHeader` to make sure that the block header is valid
442
762
  * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
@@ -446,13 +766,13 @@ export class SequencerPublisher {
446
766
  @trackSpan('SequencerPublisher.validateBlockHeader')
447
767
  public async validateBlockHeader(
448
768
  header: CheckpointHeader,
449
- opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
769
+ simulationOverridesPlan?: SimulationOverridesPlan,
450
770
  ): Promise<void> {
451
771
  const flags = { ignoreDA: true, ignoreSignatures: true };
452
772
 
453
773
  const args = [
454
774
  header.toViem(),
455
- CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
775
+ CommitteeAttestationsAndSigners.packAttestations([]),
456
776
  [], // no signers
457
777
  Signature.empty().toViemSignature(),
458
778
  `0x${'0'.repeat(64)}`, // 32 empty bytes
@@ -460,10 +780,9 @@ export class SequencerPublisher {
460
780
  flags,
461
781
  ] as const;
462
782
 
463
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
464
- const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
465
- opts?.forcePendingCheckpointNumber,
466
- );
783
+ const l1Constants = this.epochCache.getL1Constants();
784
+ const ts = getLastL1SlotTimestampForL2Slot(header.slotNumber, l1Constants);
785
+ const stateOverrides = await buildSimulationOverridesStateOverride(this.rollupContract, simulationOverridesPlan);
467
786
  let balance = 0n;
468
787
  if (this.config.fishermanMode) {
469
788
  // In fisherman mode, we can't know where the proposer is publishing from
@@ -483,7 +802,7 @@ export class SequencerPublisher {
483
802
  data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
484
803
  from: MULTI_CALL_3_ADDRESS,
485
804
  },
486
- { time: ts + 1n },
805
+ { time: ts },
487
806
  stateOverrides,
488
807
  );
489
808
  this.log.debug(`Simulated validateHeader`);
@@ -516,8 +835,15 @@ export class SequencerPublisher {
516
835
  const request = this.buildInvalidateCheckpointRequest(validationResult);
517
836
  this.log.debug(`Simulating invalidate checkpoint ${checkpointNumber}`, { ...logData, request });
518
837
 
838
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
839
+
519
840
  try {
520
- const { gasUsed } = await this.l1TxUtils.simulate(request, undefined, undefined, ErrorsAbi);
841
+ const { gasUsed } = await this.l1TxUtils.simulate(
842
+ request,
843
+ undefined,
844
+ undefined,
845
+ mergeAbis([request.abi ?? [], ErrorsAbi]),
846
+ );
521
847
  this.log.verbose(`Simulation for invalidate checkpoint ${checkpointNumber} succeeded`, {
522
848
  ...logData,
523
849
  request,
@@ -529,6 +855,7 @@ export class SequencerPublisher {
529
855
  gasUsed,
530
856
  checkpointNumber,
531
857
  forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
858
+ lastArchive: validationResult.checkpoint.lastArchive,
532
859
  reason,
533
860
  };
534
861
  } catch (err) {
@@ -536,13 +863,13 @@ export class SequencerPublisher {
536
863
 
537
864
  // If the error is due to the checkpoint not being in the pending chain, and it was indeed removed by someone else,
538
865
  // we can safely ignore it and return undefined so we go ahead with checkpoint building.
539
- if (viemError.message?.includes('Rollup__BlockNotInPendingChain')) {
866
+ if (viemError.message?.includes('Rollup__CheckpointNotInPendingChain')) {
540
867
  this.log.verbose(
541
868
  `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
542
869
  { ...logData, request, error: viemError.message },
543
870
  );
544
- const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
545
- if (latestPendingCheckpointNumber < checkpointNumber) {
871
+ const latestProposedCheckpointNumber = await this.rollupContract.getCheckpointNumber();
872
+ if (latestProposedCheckpointNumber < checkpointNumber) {
546
873
  this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
547
874
  return undefined;
548
875
  } else {
@@ -562,6 +889,18 @@ export class SequencerPublisher {
562
889
 
563
890
  // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
564
891
  this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
892
+ this.backupFailedTx({
893
+ id: keccak256(request.data!),
894
+ failureType: 'simulation',
895
+ request: { to: request.to!, data: request.data!, value: request.value?.toString() },
896
+ l1BlockNumber: l1BlockNumber.toString(),
897
+ error: { message: viemError.message, name: viemError.name },
898
+ context: {
899
+ actions: [`invalidate-${reason}`],
900
+ checkpointNumber,
901
+ sender: this.getSenderAddress().toString(),
902
+ },
903
+ });
565
904
  throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, { cause: viemError });
566
905
  }
567
906
  }
@@ -575,9 +914,11 @@ export class SequencerPublisher {
575
914
  const logData = { ...checkpoint, reason };
576
915
  this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
577
916
 
578
- const attestationsAndSigners = new CommitteeAttestationsAndSigners(
579
- validationResult.attestations,
580
- ).getPackedAttestations();
917
+ // Use the exact packed tuple posted to L1 verbatim. A repack via `packAttestations` is not a
918
+ // byte-faithful inverse of `fromPacked` (a canonicalized yParity byte or an all-zero signature slot
919
+ // round-trips differently), so it would diverge from the stored `attestationsHash` and revert the
920
+ // invalidation.
921
+ const attestationsAndSigners = validationResult.verbatimAttestations;
581
922
 
582
923
  if (reason === 'invalid-attestation') {
583
924
  return this.rollupContract.buildInvalidateBadAttestationRequest(
@@ -598,59 +939,11 @@ export class SequencerPublisher {
598
939
  }
599
940
  }
600
941
 
601
- /** Simulates `propose` to make sure that the checkpoint is valid for submission */
602
- @trackSpan('SequencerPublisher.validateCheckpointForSubmission')
603
- public async validateCheckpointForSubmission(
604
- checkpoint: Checkpoint,
605
- attestationsAndSigners: CommitteeAttestationsAndSigners,
606
- attestationsAndSignersSignature: Signature,
607
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
608
- ): Promise<bigint> {
609
- const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
610
-
611
- // TODO(palla/mbps): This should not be needed, there's no flow where we propose with zero attestations. Or is there?
612
- // If we have no attestations, we still need to provide the empty attestations
613
- // so that the committee is recalculated correctly
614
- // const ignoreSignatures = attestationsAndSigners.attestations.length === 0;
615
- // if (ignoreSignatures) {
616
- // const { committee } = await this.epochCache.getCommittee(block.header.globalVariables.slotNumber);
617
- // if (!committee) {
618
- // this.log.warn(`No committee found for slot ${block.header.globalVariables.slotNumber}`);
619
- // throw new Error(`No committee found for slot ${block.header.globalVariables.slotNumber}`);
620
- // }
621
- // attestationsAndSigners.attestations = committee.map(committeeMember =>
622
- // CommitteeAttestation.fromAddress(committeeMember),
623
- // );
624
- // }
625
-
626
- const blobFields = checkpoint.toBlobFields();
627
- const blobs = getBlobsPerL1Block(blobFields);
628
- const blobInput = getPrefixedEthBlobCommitments(blobs);
629
-
630
- const args = [
631
- {
632
- header: checkpoint.header.toViem(),
633
- archive: toHex(checkpoint.archive.root.toBuffer()),
634
- oracleInput: {
635
- feeAssetPriceModifier: 0n,
636
- },
637
- },
638
- attestationsAndSigners.getPackedAttestations(),
639
- attestationsAndSigners.getSigners().map(signer => signer.toString()),
640
- attestationsAndSignersSignature.toViemSignature(),
641
- blobInput,
642
- ] as const;
643
-
644
- await this.simulateProposeTx(args, ts, options);
645
- return ts;
646
- }
647
-
648
942
  private async enqueueCastSignalHelper(
649
943
  slotNumber: SlotNumber,
650
- timestamp: bigint,
651
944
  signalType: GovernanceSignalAction,
652
945
  payload: EthAddress,
653
- base: IEmpireBase,
946
+ base: GovernanceProposerContract,
654
947
  signerAddress: EthAddress,
655
948
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
656
949
  ): Promise<boolean> {
@@ -676,11 +969,31 @@ export class SequencerPublisher {
676
969
  return false;
677
970
  }
678
971
 
679
- if (await this.isPayloadEmpty(payload)) {
972
+ if (await base.isPayloadEmpty(payload)) {
680
973
  this.log.warn(`Skipping vote cast for payload with empty code`);
681
974
  return false;
682
975
  }
683
976
 
977
+ // Skip signaling if there is already a live (non-terminal) Governance proposal for this
978
+ // payload. This is intentionally not cached: a previously-live proposal may transition to
979
+ // a terminal state (Dropped/Rejected/Expired/Executed), at which point we may want to re-signal
980
+ // the same payload in a future round.
981
+ let proposed = false;
982
+ try {
983
+ proposed = await base.hasActiveProposalWithPayload(payload.toString());
984
+ } catch (err) {
985
+ // We deliberately swallow the error and proceed to signal. Failing closed (skipping the
986
+ // signal) on transient RPC errors would let a flaky L1 endpoint silence governance
987
+ // participation entirely; failing open at worst produces a duplicate signal that the
988
+ // contract will simply count alongside others in the round.
989
+ this.log.error(`Failed to check if payload ${payload} was already proposed (signalling anyway)`, err);
990
+ }
991
+
992
+ if (proposed) {
993
+ this.log.info(`Payload ${payload} has a live governance proposal, stopping signals`);
994
+ return false;
995
+ }
996
+
684
997
  const cachedLastVote = this.lastActions[signalType];
685
998
  this.lastActions[signalType] = slotNumber;
686
999
  const action = signalType;
@@ -699,26 +1012,19 @@ export class SequencerPublisher {
699
1012
  lastValidL2Slot: slotNumber,
700
1013
  });
701
1014
 
702
- try {
703
- await this.l1TxUtils.simulate(request, { time: timestamp }, [], ErrorsAbi);
704
- this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, { request });
705
- } catch (err) {
706
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, err);
707
- // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
708
- }
709
-
710
1015
  // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
711
1016
  this.addRequest({
712
- gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
713
1017
  action,
714
1018
  request,
715
1019
  lastValidL2Slot: slotNumber,
716
1020
  checkSuccess: (_request, result) => {
717
1021
  const success =
718
1022
  result &&
719
- result.receipt &&
720
- result.receipt.status === 'success' &&
721
- tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
1023
+ extractEventSuccess(result.receipt, {
1024
+ address: base.address.toString(),
1025
+ abi: EmpireBaseAbi,
1026
+ eventName: 'SignalCast',
1027
+ });
722
1028
 
723
1029
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
724
1030
  if (!success) {
@@ -740,33 +1046,19 @@ export class SequencerPublisher {
740
1046
  return true;
741
1047
  }
742
1048
 
743
- private async isPayloadEmpty(payload: EthAddress): Promise<boolean> {
744
- const key = payload.toString();
745
- const cached = this.isPayloadEmptyCache.get(key);
746
- if (cached) {
747
- return cached;
748
- }
749
- const isEmpty = !(await this.l1TxUtils.getCode(payload));
750
- this.isPayloadEmptyCache.set(key, isEmpty);
751
- return isEmpty;
752
- }
753
-
754
1049
  /**
755
1050
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
756
1051
  * @param slotNumber - The slot number to cast a signal for.
757
- * @param timestamp - The timestamp of the slot to cast a signal for.
758
1052
  * @returns True if the signal was successfully enqueued, false otherwise.
759
1053
  */
760
1054
  public enqueueGovernanceCastSignal(
761
1055
  governancePayload: EthAddress,
762
1056
  slotNumber: SlotNumber,
763
- timestamp: bigint,
764
1057
  signerAddress: EthAddress,
765
1058
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
766
1059
  ): Promise<boolean> {
767
1060
  return this.enqueueCastSignalHelper(
768
1061
  slotNumber,
769
- timestamp,
770
1062
  'governance-signal',
771
1063
  governancePayload,
772
1064
  this.govProposerContract,
@@ -775,11 +1067,51 @@ export class SequencerPublisher {
775
1067
  );
776
1068
  }
777
1069
 
1070
+ /**
1071
+ * Enqueues a `prune()` transaction if the rollup is prunable at the given slot's L1 timestamp.
1072
+ * `prune()` is permissionless and idempotent — if the chain is no longer prunable by send time the
1073
+ * bundle simulation usually drops the entry; on a node without `eth_simulateV1` the bundle is sent
1074
+ * as-is and the prune reverts `Rollup__NothingToPrune` inside `aggregate3(allowFailure: true)`
1075
+ * (a failed action, never a whole-tx revert). Used by the failed-sync fallback so a stuck pending
1076
+ * chain (e.g. bad data blocking sync) can be wound back to recover.
1077
+ * @returns true if a prune request was enqueued, false otherwise.
1078
+ */
1079
+ public async enqueuePruneIfPrunable(slotNumber: SlotNumber): Promise<boolean> {
1080
+ if (this.lastActions['prune'] === slotNumber) {
1081
+ this.log.debug(`Skipping duplicate prune for slot ${slotNumber}`, { slotNumber });
1082
+ return false;
1083
+ }
1084
+ // Use the SAME timestamp the bundle simulator overrides block.timestamp with at send time
1085
+ // (sequencer-bundle-simulator.ts) so this upfront check and the send-time sim agree. Slot-start
1086
+ // and last-L1-slot both fall within the same L2 slot (and epoch, which is what `canPruneAtTime`
1087
+ // derives), so they agree today; matching the simulator keeps it robust if the contract ever uses
1088
+ // the timestamp more granularly.
1089
+ const ts = getLastL1SlotTimestampForL2Slot(slotNumber, this.epochCache.getL1Constants());
1090
+ const canPrune = await this.rollupContract.canPruneAtTime(ts).catch(err => {
1091
+ this.log.error(`Failed to check canPruneAtTime for slot ${slotNumber}`, err, { slotNumber });
1092
+ return false;
1093
+ });
1094
+ if (!canPrune) {
1095
+ this.log.debug(`Rollup not prunable at slot ${slotNumber}`, { slotNumber });
1096
+ return false;
1097
+ }
1098
+ const request: L1TxRequest = {
1099
+ to: this.rollupContract.address,
1100
+ data: encodeFunctionData({ abi: RollupAbi, functionName: 'prune', args: [] }),
1101
+ };
1102
+ this.log.info(`Enqueuing rollup prune for slot ${slotNumber}`, { slotNumber });
1103
+ return this.enqueueRequest(
1104
+ 'prune',
1105
+ request,
1106
+ { address: this.rollupContract.address, abi: RollupAbi, eventName: 'PrunedPending' },
1107
+ slotNumber,
1108
+ );
1109
+ }
1110
+
778
1111
  /** Enqueues all slashing actions as returned by the slasher client. */
779
1112
  public async enqueueSlashingActions(
780
1113
  actions: ProposerSlashAction[],
781
1114
  slotNumber: SlotNumber,
782
- timestamp: bigint,
783
1115
  signerAddress: EthAddress,
784
1116
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
785
1117
  ): Promise<boolean> {
@@ -790,58 +1122,6 @@ export class SequencerPublisher {
790
1122
 
791
1123
  for (const action of actions) {
792
1124
  switch (action.type) {
793
- case 'vote-empire-payload': {
794
- if (this.slashingProposerContract?.type !== 'empire') {
795
- this.log.error('Cannot vote for empire payload on non-empire slashing contract');
796
- break;
797
- }
798
- this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
799
- signerAddress,
800
- });
801
- await this.enqueueCastSignalHelper(
802
- slotNumber,
803
- timestamp,
804
- 'empire-slashing-signal',
805
- action.payload,
806
- this.slashingProposerContract,
807
- signerAddress,
808
- signer,
809
- );
810
- break;
811
- }
812
-
813
- case 'create-empire-payload': {
814
- this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, { slotNumber, signerAddress });
815
- const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
816
- await this.simulateAndEnqueueRequest(
817
- 'create-empire-payload',
818
- request,
819
- (receipt: TransactionReceipt) =>
820
- !!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs),
821
- slotNumber,
822
- timestamp,
823
- );
824
- break;
825
- }
826
-
827
- case 'execute-empire-payload': {
828
- this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, { slotNumber, signerAddress });
829
- if (this.slashingProposerContract?.type !== 'empire') {
830
- this.log.error('Cannot execute slashing payload on non-empire slashing contract');
831
- return false;
832
- }
833
- const empireSlashingProposer = this.slashingProposerContract as EmpireSlashingProposerContract;
834
- const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
835
- await this.simulateAndEnqueueRequest(
836
- 'execute-empire-payload',
837
- request,
838
- (receipt: TransactionReceipt) => !!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs),
839
- slotNumber,
840
- timestamp,
841
- );
842
- break;
843
- }
844
-
845
1125
  case 'vote-offenses': {
846
1126
  this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
847
1127
  slotNumber,
@@ -849,19 +1129,21 @@ export class SequencerPublisher {
849
1129
  votesCount: action.votes.length,
850
1130
  signerAddress,
851
1131
  });
852
- if (this.slashingProposerContract?.type !== 'tally') {
853
- this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
1132
+ if (!this.slashingProposerContract) {
1133
+ this.log.error('No slashing proposer contract available');
854
1134
  return false;
855
1135
  }
856
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
857
1136
  const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
858
- const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
859
- await this.simulateAndEnqueueRequest(
1137
+ const request = await this.slashingProposerContract.buildVoteRequestFromSigner(votes, slotNumber, signer);
1138
+ this.enqueueRequest(
860
1139
  'vote-offenses',
861
1140
  request,
862
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
1141
+ {
1142
+ address: this.slashingProposerContract.address.toString(),
1143
+ abi: SlashingProposerAbi,
1144
+ eventName: 'VoteCast',
1145
+ },
863
1146
  slotNumber,
864
- timestamp,
865
1147
  );
866
1148
  break;
867
1149
  }
@@ -872,18 +1154,23 @@ export class SequencerPublisher {
872
1154
  round: action.round,
873
1155
  signerAddress,
874
1156
  });
875
- if (this.slashingProposerContract?.type !== 'tally') {
876
- this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
1157
+ if (!this.slashingProposerContract) {
1158
+ this.log.error('No slashing proposer contract available');
877
1159
  return false;
878
1160
  }
879
- const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
880
- const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
881
- await this.simulateAndEnqueueRequest(
1161
+ const executeRequest = this.slashingProposerContract.buildExecuteRoundRequest(
1162
+ action.round,
1163
+ action.committees,
1164
+ );
1165
+ this.enqueueRequest(
882
1166
  'execute-slash',
883
- request,
884
- (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
1167
+ executeRequest,
1168
+ {
1169
+ address: this.slashingProposerContract.address.toString(),
1170
+ abi: SlashingProposerAbi,
1171
+ eventName: 'RoundExecuted',
1172
+ },
885
1173
  slotNumber,
886
- timestamp,
887
1174
  );
888
1175
  break;
889
1176
  }
@@ -898,51 +1185,32 @@ export class SequencerPublisher {
898
1185
  return true;
899
1186
  }
900
1187
 
901
- /** Simulates and enqueues a proposal for a checkpoint on L1 */
1188
+ /** Enqueues a proposal for a checkpoint on L1 */
902
1189
  public async enqueueProposeCheckpoint(
903
1190
  checkpoint: Checkpoint,
904
1191
  attestationsAndSigners: CommitteeAttestationsAndSigners,
905
1192
  attestationsAndSignersSignature: Signature,
906
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1193
+ opts: EnqueueProposeCheckpointOpts = {},
907
1194
  ): Promise<void> {
908
1195
  const checkpointHeader = checkpoint.header;
909
1196
 
910
1197
  const blobFields = checkpoint.toBlobFields();
911
- const blobs = getBlobsPerL1Block(blobFields);
1198
+ const blobs = await getBlobsPerL1Block(blobFields);
912
1199
 
913
- const proposeTxArgs = {
1200
+ const proposeTxArgs: L1ProcessArgs = {
914
1201
  header: checkpointHeader,
915
1202
  archive: checkpoint.archive.root.toBuffer(),
916
1203
  blobs,
917
1204
  attestationsAndSigners,
918
1205
  attestationsAndSignersSignature,
1206
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
919
1207
  };
920
1208
 
921
- let ts: bigint;
922
-
923
- try {
924
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
925
- // This means that we can avoid the simulation issues in later checks.
926
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
927
- // make time consistency checks break.
928
- // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
929
- ts = await this.validateCheckpointForSubmission(
930
- checkpoint,
931
- attestationsAndSigners,
932
- attestationsAndSignersSignature,
933
- opts,
934
- );
935
- } catch (err: any) {
936
- this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
937
- ...checkpoint.getStats(),
938
- slotNumber: checkpoint.header.slotNumber,
939
- forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
940
- });
941
- throw err;
942
- }
943
-
944
- this.log.verbose(`Enqueuing checkpoint propose transaction`, { ...checkpoint.toCheckpointInfo(), ...opts });
945
- await this.addProposeTx(checkpoint, proposeTxArgs, opts, ts);
1209
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, {
1210
+ ...checkpoint.toCheckpointInfo(),
1211
+ txTimeoutAt: opts.txTimeoutAt,
1212
+ });
1213
+ await this.addProposeTx(checkpoint, proposeTxArgs, { txTimeoutAt: opts.txTimeoutAt });
946
1214
  }
947
1215
 
948
1216
  public enqueueInvalidateCheckpoint(
@@ -953,23 +1221,22 @@ export class SequencerPublisher {
953
1221
  return;
954
1222
  }
955
1223
 
956
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
957
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(request.gasUsed) * 64) / 63)));
958
-
959
1224
  const { gasUsed, checkpointNumber } = request;
960
- const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1225
+ const logData = { gasUsed, checkpointNumber, opts };
961
1226
  this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
962
1227
  this.addRequest({
963
1228
  action: `invalidate-by-${request.reason}`,
964
1229
  request: request.request,
965
- gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
1230
+ gasConfig: opts.txTimeoutAt ? { txTimeoutAt: opts.txTimeoutAt } : undefined,
966
1231
  lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
967
1232
  checkSuccess: (_req, result) => {
968
1233
  const success =
969
1234
  result &&
970
- result.receipt &&
971
- result.receipt.status === 'success' &&
972
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
1235
+ extractEventSuccess(result.receipt, {
1236
+ address: this.rollupContract.address,
1237
+ abi: RollupAbi,
1238
+ eventName: 'CheckpointInvalidated',
1239
+ });
973
1240
  if (!success) {
974
1241
  this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
975
1242
  } else {
@@ -980,51 +1247,36 @@ export class SequencerPublisher {
980
1247
  });
981
1248
  }
982
1249
 
983
- private async simulateAndEnqueueRequest(
1250
+ /**
1251
+ * Dedup-checked enqueue helper for actions that are simulated at bundle-send time rather
1252
+ * than at enqueue time. Validates the (action, slot) dedup key, sets `lastActions`, and
1253
+ * enqueues without a gasLimit so the bundle simulate sets the only gasLimit that matters.
1254
+ */
1255
+ private enqueueRequest(
984
1256
  action: Action,
985
1257
  request: L1TxRequest,
986
- checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
1258
+ eventOpts: { address: string; abi: Abi; eventName: string },
987
1259
  slotNumber: SlotNumber,
988
- timestamp: bigint,
989
- ) {
990
- const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
1260
+ ): boolean {
991
1261
  if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
992
1262
  this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
993
1263
  return false;
994
1264
  }
995
-
996
1265
  const cachedLastActionSlot = this.lastActions[action];
997
1266
  this.lastActions[action] = slotNumber;
998
1267
 
999
- this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
1000
-
1001
- let gasUsed: bigint;
1002
- try {
1003
- ({ gasUsed } = await this.l1TxUtils.simulate(request, { time: timestamp }, [], ErrorsAbi)); // TODO(palla/slash): Check the timestamp logic
1004
- this.log.verbose(`Simulation for ${action} succeeded`, { ...logData, request, gasUsed });
1005
- } catch (err) {
1006
- const viemError = formatViemError(err);
1007
- this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1008
- return false;
1009
- }
1010
-
1011
- // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1012
- const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(gasUsed) * 64) / 63)));
1013
- logData.gasLimit = gasLimit;
1014
-
1015
- this.log.debug(`Enqueuing ${action}`, logData);
1268
+ this.log.debug(`Enqueuing ${action}`, { slotNumber });
1016
1269
  this.addRequest({
1017
1270
  action,
1018
1271
  request,
1019
- gasConfig: { gasLimit },
1020
1272
  lastValidL2Slot: slotNumber,
1021
- checkSuccess: (_req, result) => {
1022
- const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1273
+ checkSuccess: (_request, result) => {
1274
+ const success = result && extractEventSuccess(result.receipt, eventOpts);
1023
1275
  if (!success) {
1024
- this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1276
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, slotNumber });
1025
1277
  this.lastActions[action] = cachedLastActionSlot;
1026
1278
  } else {
1027
- this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1279
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, slotNumber });
1028
1280
  }
1029
1281
  return !!success;
1030
1282
  },
@@ -1040,6 +1292,7 @@ export class SequencerPublisher {
1040
1292
  */
1041
1293
  public interrupt() {
1042
1294
  this.interrupted = true;
1295
+ this.interruptibleSleep.interrupt();
1043
1296
  this.l1TxUtils.interrupt();
1044
1297
  }
1045
1298
 
@@ -1049,11 +1302,7 @@ export class SequencerPublisher {
1049
1302
  this.l1TxUtils.restart();
1050
1303
  }
1051
1304
 
1052
- private async prepareProposeTx(
1053
- encodedData: L1ProcessArgs,
1054
- timestamp: bigint,
1055
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1056
- ) {
1305
+ private async prepareProposeTx(encodedData: L1ProcessArgs) {
1057
1306
  const kzg = Blob.getViemKzgInstance();
1058
1307
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
1059
1308
  this.log.debug('Validating blob input', { blobInput });
@@ -1066,7 +1315,11 @@ export class SequencerPublisher {
1066
1315
  blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1067
1316
  this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1068
1317
  } else {
1069
- // Normal mode - use estimateGas with blob inputs
1318
+ // We call validateBlobs via estimateGas with real blob+kzg sidecars as a consistency check
1319
+ // that our locally-built blob commitments match the blob data. The bundle simulate at send
1320
+ // time uses eth_simulateV1, which cannot carry blob inputs, so the rollup's on-chain blob
1321
+ // check is forced off there — making this the only pre-flight detector of a commitment/data
1322
+ // mismatch. The returned gas estimate is stashed on the request for the bundle path to read.
1070
1323
  blobEvaluationGas = await this.l1TxUtils
1071
1324
  .estimateGas(
1072
1325
  this.getSenderAddress().toString(),
@@ -1084,9 +1337,27 @@ export class SequencerPublisher {
1084
1337
  kzg,
1085
1338
  },
1086
1339
  )
1087
- .catch(err => {
1088
- const { message, metaMessages } = formatViemError(err);
1089
- this.log.error(`Failed to validate blobs`, message, { metaMessages });
1340
+ .catch(async err => {
1341
+ const viemError = formatViemError(err);
1342
+ this.log.error(`Failed to validate blobs`, viemError.message, { metaMessages: viemError.metaMessages });
1343
+ const validateBlobsData = encodeFunctionData({
1344
+ abi: RollupAbi,
1345
+ functionName: 'validateBlobs',
1346
+ args: [blobInput],
1347
+ });
1348
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1349
+ this.backupFailedTx({
1350
+ id: keccak256(validateBlobsData),
1351
+ failureType: 'simulation',
1352
+ request: { to: this.rollupContract.address as Hex, data: validateBlobsData },
1353
+ blobData: encodedData.blobs.map(b => toHex(b.data)) as Hex[],
1354
+ l1BlockNumber: l1BlockNumber.toString(),
1355
+ error: { message: viemError.message, name: viemError.name },
1356
+ context: {
1357
+ actions: ['validate-blobs'],
1358
+ sender: this.getSenderAddress().toString(),
1359
+ },
1360
+ });
1090
1361
  throw new Error('Failed to validate blobs');
1091
1362
  });
1092
1363
  }
@@ -1097,8 +1368,7 @@ export class SequencerPublisher {
1097
1368
  header: encodedData.header.toViem(),
1098
1369
  archive: toHex(encodedData.archive),
1099
1370
  oracleInput: {
1100
- // We are currently not modifying these. See #9963
1101
- feeAssetPriceModifier: 0n,
1371
+ feeAssetPriceModifier: encodedData.feeAssetPriceModifier,
1102
1372
  },
1103
1373
  },
1104
1374
  encodedData.attestationsAndSigners.getPackedAttestations(),
@@ -1107,124 +1377,21 @@ export class SequencerPublisher {
1107
1377
  blobInput,
1108
1378
  ] as const;
1109
1379
 
1110
- const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1111
-
1112
- return { args, blobEvaluationGas, rollupData, simulationResult };
1113
- }
1114
-
1115
- /**
1116
- * Simulates the propose tx with eth_simulateV1
1117
- * @param args - The propose tx args
1118
- * @param timestamp - The timestamp to simulate proposal at
1119
- * @returns The simulation result
1120
- */
1121
- private async simulateProposeTx(
1122
- args: readonly [
1123
- {
1124
- readonly header: ViemHeader;
1125
- readonly archive: `0x${string}`;
1126
- readonly oracleInput: {
1127
- readonly feeAssetPriceModifier: 0n;
1128
- };
1129
- },
1130
- ViemCommitteeAttestations,
1131
- `0x${string}`[], // Signers
1132
- ViemSignature,
1133
- `0x${string}`,
1134
- ],
1135
- timestamp: bigint,
1136
- options: { forcePendingCheckpointNumber?: CheckpointNumber },
1137
- ) {
1138
- const rollupData = encodeFunctionData({
1139
- abi: RollupAbi,
1140
- functionName: 'propose',
1141
- args,
1142
- });
1143
-
1144
- // override the pending checkpoint number if requested
1145
- const forcePendingCheckpointNumberStateDiff = (
1146
- options.forcePendingCheckpointNumber !== undefined
1147
- ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber)
1148
- : []
1149
- ).flatMap(override => override.stateDiff ?? []);
1150
-
1151
- const stateOverrides: StateOverride = [
1152
- {
1153
- address: this.rollupContract.address,
1154
- // @note we override checkBlob to false since blobs are not part simulate()
1155
- stateDiff: [
1156
- { slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true), value: toPaddedHex(0n, true) },
1157
- ...forcePendingCheckpointNumberStateDiff,
1158
- ],
1159
- },
1160
- ];
1161
- // In fisherman mode, simulate as the proposer but with sufficient balance
1162
- if (this.proposerAddressForSimulation) {
1163
- stateOverrides.push({
1164
- address: this.proposerAddressForSimulation.toString(),
1165
- balance: 10n * WEI_CONST * WEI_CONST, // 10 ETH
1166
- });
1167
- }
1168
-
1169
- const simulationResult = await this.l1TxUtils
1170
- .simulate(
1171
- {
1172
- to: this.rollupContract.address,
1173
- data: rollupData,
1174
- gas: SequencerPublisher.PROPOSE_GAS_GUESS,
1175
- ...(this.proposerAddressForSimulation && { from: this.proposerAddressForSimulation.toString() }),
1176
- },
1177
- {
1178
- // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
1179
- time: timestamp + 1n,
1180
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1181
- gasLimit: SequencerPublisher.PROPOSE_GAS_GUESS * 2n,
1182
- },
1183
- stateOverrides,
1184
- RollupAbi,
1185
- {
1186
- // @note fallback gas estimate to use if the node doesn't support simulation API
1187
- fallbackGasEstimate: SequencerPublisher.PROPOSE_GAS_GUESS,
1188
- },
1189
- )
1190
- .catch(err => {
1191
- // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1192
- const viemError = formatViemError(err);
1193
- if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1194
- this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1195
- // Return a minimal simulation result with the fallback gas estimate
1196
- return {
1197
- gasUsed: SequencerPublisher.PROPOSE_GAS_GUESS,
1198
- logs: [],
1199
- };
1200
- }
1201
- this.log.error(`Failed to simulate propose tx`, viemError);
1202
- throw err;
1203
- });
1380
+ const rollupData = encodeFunctionData({ abi: RollupAbi, functionName: 'propose', args });
1204
1381
 
1205
- return { rollupData, simulationResult };
1382
+ return { args, blobEvaluationGas, rollupData };
1206
1383
  }
1207
1384
 
1208
1385
  private async addProposeTx(
1209
1386
  checkpoint: Checkpoint,
1210
1387
  encodedData: L1ProcessArgs,
1211
- opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1212
- timestamp: bigint,
1388
+ opts: EnqueueProposeCheckpointOpts = {},
1213
1389
  ): Promise<void> {
1214
1390
  const slot = checkpoint.header.slotNumber;
1215
1391
  const timer = new Timer();
1216
1392
  const kzg = Blob.getViemKzgInstance();
1217
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
1218
- encodedData,
1219
- timestamp,
1220
- opts,
1221
- );
1393
+ const { rollupData, blobEvaluationGas } = await this.prepareProposeTx(encodedData);
1222
1394
  const startBlock = await this.l1TxUtils.getBlockNumber();
1223
- const gasLimit = this.l1TxUtils.bumpGasLimit(
1224
- BigInt(Math.ceil((Number(simulationResult.gasUsed) * 64) / 63)) +
1225
- blobEvaluationGas +
1226
- SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS, // We issue the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1227
- );
1228
1395
 
1229
1396
  // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1230
1397
  // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
@@ -1241,7 +1408,8 @@ export class SequencerPublisher {
1241
1408
  data: rollupData,
1242
1409
  },
1243
1410
  lastValidL2Slot: checkpoint.header.slotNumber,
1244
- gasConfig: { ...opts, gasLimit },
1411
+ gasConfig: { txTimeoutAt: opts.txTimeoutAt, gasLimit: undefined },
1412
+ blobEvaluationGas,
1245
1413
  blobConfig: {
1246
1414
  blobs: encodedData.blobs.map(b => b.data),
1247
1415
  kzg,
@@ -1251,10 +1419,11 @@ export class SequencerPublisher {
1251
1419
  return false;
1252
1420
  }
1253
1421
  const { receipt, stats, errorMsg } = result;
1254
- const success =
1255
- receipt &&
1256
- receipt.status === 'success' &&
1257
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1422
+ const success = extractEventSuccess(receipt, {
1423
+ address: this.rollupContract.address,
1424
+ abi: RollupAbi,
1425
+ eventName: 'CheckpointProposed',
1426
+ });
1258
1427
 
1259
1428
  if (success) {
1260
1429
  const endBlock = receipt.blockNumber;
@@ -1294,4 +1463,10 @@ export class SequencerPublisher {
1294
1463
  },
1295
1464
  });
1296
1465
  }
1466
+
1467
+ /** Returns the timestamp of the next L1 slot boundary after now. */
1468
+ private getNextL1SlotTimestamp(): bigint {
1469
+ const l1Constants = this.epochCache.getL1Constants();
1470
+ return getNextL1SlotTimestamp(this.dateProvider.nowInSeconds(), l1Constants);
1471
+ }
1297
1472
  }