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

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