@aztec/sequencer-client 0.0.1-fake-c83136db25 → 0.0.1-private.d0bedffd

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 (119) hide show
  1. package/dest/client/index.d.ts +1 -1
  2. package/dest/client/sequencer-client.d.ts +32 -16
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +118 -27
  5. package/dest/config.d.ts +33 -8
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +106 -42
  8. package/dest/global_variable_builder/global_builder.d.ts +20 -16
  9. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  10. package/dest/global_variable_builder/global_builder.js +52 -39
  11. package/dest/global_variable_builder/index.d.ts +1 -1
  12. package/dest/index.d.ts +2 -3
  13. package/dest/index.d.ts.map +1 -1
  14. package/dest/index.js +1 -2
  15. package/dest/publisher/config.d.ts +43 -20
  16. package/dest/publisher/config.d.ts.map +1 -1
  17. package/dest/publisher/config.js +109 -34
  18. package/dest/publisher/index.d.ts +2 -1
  19. package/dest/publisher/index.d.ts.map +1 -1
  20. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  21. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  22. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  23. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +59 -0
  24. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  25. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  26. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  27. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  28. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  29. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  30. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  31. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  32. package/dest/publisher/sequencer-publisher-factory.d.ts +15 -6
  33. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  34. package/dest/publisher/sequencer-publisher-factory.js +28 -3
  35. package/dest/publisher/sequencer-publisher-metrics.d.ts +3 -3
  36. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  37. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  38. package/dest/publisher/sequencer-publisher.d.ts +99 -67
  39. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  40. package/dest/publisher/sequencer-publisher.js +976 -183
  41. package/dest/sequencer/checkpoint_proposal_job.d.ts +100 -0
  42. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  43. package/dest/sequencer/checkpoint_proposal_job.js +1244 -0
  44. package/dest/sequencer/checkpoint_voter.d.ts +35 -0
  45. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  46. package/dest/sequencer/checkpoint_voter.js +109 -0
  47. package/dest/sequencer/config.d.ts +3 -2
  48. package/dest/sequencer/config.d.ts.map +1 -1
  49. package/dest/sequencer/errors.d.ts +1 -1
  50. package/dest/sequencer/errors.d.ts.map +1 -1
  51. package/dest/sequencer/events.d.ts +46 -0
  52. package/dest/sequencer/events.d.ts.map +1 -0
  53. package/dest/sequencer/events.js +1 -0
  54. package/dest/sequencer/index.d.ts +4 -2
  55. package/dest/sequencer/index.d.ts.map +1 -1
  56. package/dest/sequencer/index.js +3 -1
  57. package/dest/sequencer/metrics.d.ts +44 -3
  58. package/dest/sequencer/metrics.d.ts.map +1 -1
  59. package/dest/sequencer/metrics.js +232 -50
  60. package/dest/sequencer/sequencer.d.ts +125 -144
  61. package/dest/sequencer/sequencer.d.ts.map +1 -1
  62. package/dest/sequencer/sequencer.js +740 -525
  63. package/dest/sequencer/timetable.d.ts +54 -16
  64. package/dest/sequencer/timetable.d.ts.map +1 -1
  65. package/dest/sequencer/timetable.js +147 -62
  66. package/dest/sequencer/types.d.ts +6 -0
  67. package/dest/sequencer/types.d.ts.map +1 -0
  68. package/dest/sequencer/types.js +1 -0
  69. package/dest/sequencer/utils.d.ts +14 -8
  70. package/dest/sequencer/utils.d.ts.map +1 -1
  71. package/dest/sequencer/utils.js +7 -4
  72. package/dest/test/index.d.ts +6 -7
  73. package/dest/test/index.d.ts.map +1 -1
  74. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  75. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  76. package/dest/test/mock_checkpoint_builder.js +231 -0
  77. package/dest/test/utils.d.ts +53 -0
  78. package/dest/test/utils.d.ts.map +1 -0
  79. package/dest/test/utils.js +104 -0
  80. package/package.json +33 -30
  81. package/src/client/sequencer-client.ts +158 -52
  82. package/src/config.ts +122 -52
  83. package/src/global_variable_builder/global_builder.ts +67 -59
  84. package/src/index.ts +1 -7
  85. package/src/publisher/config.ts +139 -50
  86. package/src/publisher/index.ts +3 -0
  87. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  88. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +55 -0
  89. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  90. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  91. package/src/publisher/sequencer-publisher-factory.ts +45 -11
  92. package/src/publisher/sequencer-publisher-metrics.ts +19 -71
  93. package/src/publisher/sequencer-publisher.ts +692 -241
  94. package/src/sequencer/README.md +531 -0
  95. package/src/sequencer/checkpoint_proposal_job.ts +960 -0
  96. package/src/sequencer/checkpoint_voter.ts +130 -0
  97. package/src/sequencer/config.ts +2 -1
  98. package/src/sequencer/events.ts +27 -0
  99. package/src/sequencer/index.ts +3 -1
  100. package/src/sequencer/metrics.ts +296 -61
  101. package/src/sequencer/sequencer.ts +494 -717
  102. package/src/sequencer/timetable.ts +178 -83
  103. package/src/sequencer/types.ts +9 -0
  104. package/src/sequencer/utils.ts +18 -9
  105. package/src/test/index.ts +5 -6
  106. package/src/test/mock_checkpoint_builder.ts +323 -0
  107. package/src/test/utils.ts +167 -0
  108. package/dest/sequencer/block_builder.d.ts +0 -27
  109. package/dest/sequencer/block_builder.d.ts.map +0 -1
  110. package/dest/sequencer/block_builder.js +0 -130
  111. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  112. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  113. package/dest/tx_validator/nullifier_cache.js +0 -24
  114. package/dest/tx_validator/tx_validator_factory.d.ts +0 -17
  115. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  116. package/dest/tx_validator/tx_validator_factory.js +0 -53
  117. package/src/sequencer/block_builder.ts +0 -218
  118. package/src/tx_validator/nullifier_cache.ts +0 -30
  119. package/src/tx_validator/tx_validator_factory.ts +0 -132
@@ -1,48 +1,64 @@
1
- import { L2Block } from '@aztec/aztec.js/block';
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
2
2
  import { Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec/blob-lib';
3
- import { type BlobSinkClientInterface, createBlobSinkClient } from '@aztec/blob-sink/client';
4
3
  import type { EpochCache } from '@aztec/epoch-cache';
4
+ import type { L1ContractsConfig } from '@aztec/ethereum/config';
5
5
  import {
6
6
  type EmpireSlashingProposerContract,
7
- FormattedViemError,
7
+ FeeAssetPriceOracle,
8
8
  type GovernanceProposerContract,
9
9
  type IEmpireBase,
10
- type L1BlobInputs,
11
- type L1ContractsConfig,
12
- type L1TxConfig,
13
- type L1TxRequest,
14
10
  MULTI_CALL_3_ADDRESS,
15
11
  Multicall3,
16
12
  RollupContract,
17
13
  type TallySlashingProposerContract,
18
- type TransactionStats,
19
14
  type ViemCommitteeAttestations,
20
15
  type ViemHeader,
21
- type ViemStateReference,
22
- formatViemError,
23
- tryExtractEvent,
24
- } from '@aztec/ethereum';
25
- import type { L1TxUtilsWithBlobs } from '@aztec/ethereum/l1-tx-utils-with-blobs';
16
+ } from '@aztec/ethereum/contracts';
17
+ import { type L1FeeAnalysisResult, L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
18
+ import {
19
+ type L1BlobInputs,
20
+ type L1TxConfig,
21
+ type L1TxRequest,
22
+ type L1TxUtils,
23
+ MAX_L1_TX_LIMIT,
24
+ type TransactionStats,
25
+ WEI_CONST,
26
+ } from '@aztec/ethereum/l1-tx-utils';
27
+ import { FormattedViemError, formatViemError, mergeAbis, tryExtractEvent } from '@aztec/ethereum/utils';
26
28
  import { sumBigint } from '@aztec/foundation/bigint';
27
29
  import { toHex as toPaddedHex } from '@aztec/foundation/bigint-buffer';
30
+ import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
31
+ import { pick } from '@aztec/foundation/collection';
32
+ import type { Fr } from '@aztec/foundation/curves/bn254';
33
+ import { TimeoutError } from '@aztec/foundation/error';
28
34
  import { EthAddress } from '@aztec/foundation/eth-address';
29
35
  import { Signature, type ViemSignature } from '@aztec/foundation/eth-signature';
30
- import type { Fr } from '@aztec/foundation/fields';
31
36
  import { type Logger, createLogger } from '@aztec/foundation/log';
37
+ import { makeBackoff, retry } from '@aztec/foundation/retry';
32
38
  import { bufferToHex } from '@aztec/foundation/string';
33
39
  import { DateProvider, Timer } from '@aztec/foundation/timer';
34
40
  import { EmpireBaseAbi, ErrorsAbi, RollupAbi } from '@aztec/l1-artifacts';
35
41
  import { type ProposerSlashAction, encodeSlashConsensusVotes } from '@aztec/slasher';
36
- import { CommitteeAttestation, CommitteeAttestationsAndSigners, type ValidateBlockResult } from '@aztec/stdlib/block';
42
+ import { CommitteeAttestationsAndSigners, type ValidateCheckpointResult } from '@aztec/stdlib/block';
43
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
37
44
  import { SlashFactoryContract } from '@aztec/stdlib/l1-contracts';
38
45
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
39
- import type { L1PublishBlockStats } from '@aztec/stdlib/stats';
40
- import { StateReference } from '@aztec/stdlib/tx';
41
- import { type TelemetryClient, getTelemetryClient } from '@aztec/telemetry-client';
42
-
43
- import { type TransactionReceipt, type TypedDataDefinition, encodeFunctionData, toHex } from 'viem';
46
+ import type { L1PublishCheckpointStats } from '@aztec/stdlib/stats';
47
+ import { type TelemetryClient, type Tracer, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
44
48
 
45
- import type { PublisherConfig, TxSenderConfig } from './config.js';
49
+ import {
50
+ type Hex,
51
+ type StateOverride,
52
+ type TransactionReceipt,
53
+ type TypedDataDefinition,
54
+ encodeFunctionData,
55
+ keccak256,
56
+ multicall3Abi,
57
+ toHex,
58
+ } from 'viem';
59
+
60
+ import type { SequencerPublisherConfig } from './config.js';
61
+ import { type FailedL1Tx, type L1TxFailedStore, createL1TxFailedStore } from './l1_tx_failed_store/index.js';
46
62
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
47
63
 
48
64
  /** Arguments to the process method of the rollup contract */
@@ -51,14 +67,14 @@ type L1ProcessArgs = {
51
67
  header: CheckpointHeader;
52
68
  /** A root of the archive tree after the L2 block is applied. */
53
69
  archive: Buffer;
54
- /** State reference after the L2 block is applied. */
55
- stateReference: StateReference;
56
70
  /** L2 block blobs containing all tx effects. */
57
71
  blobs: Blob[];
58
72
  /** Attestations */
59
73
  attestationsAndSigners: CommitteeAttestationsAndSigners;
60
74
  /** Attestations and signers signature */
61
75
  attestationsAndSignersSignature: Signature;
76
+ /** The fee asset price modifier in basis points (from oracle) */
77
+ feeAssetPriceModifier: bigint;
62
78
  };
63
79
 
64
80
  export const Actions = [
@@ -80,18 +96,18 @@ type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slas
80
96
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
81
97
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
82
98
 
83
- export type InvalidateBlockRequest = {
99
+ export type InvalidateCheckpointRequest = {
84
100
  request: L1TxRequest;
85
101
  reason: 'invalid-attestation' | 'insufficient-attestations';
86
102
  gasUsed: bigint;
87
- blockNumber: number;
88
- forcePendingBlockNumber: number;
103
+ checkpointNumber: CheckpointNumber;
104
+ forcePendingCheckpointNumber: CheckpointNumber;
89
105
  };
90
106
 
91
107
  interface RequestWithExpiry {
92
108
  action: Action;
93
109
  request: L1TxRequest;
94
- lastValidL2Slot: bigint;
110
+ lastValidL2Slot: SlotNumber;
95
111
  gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
96
112
  blobConfig?: L1BlobInputs;
97
113
  checkSuccess: (
@@ -104,20 +120,32 @@ export class SequencerPublisher {
104
120
  private interrupted = false;
105
121
  private metrics: SequencerPublisherMetrics;
106
122
  public epochCache: EpochCache;
123
+ private failedTxStore?: Promise<L1TxFailedStore | undefined>;
107
124
 
108
125
  protected governanceLog = createLogger('sequencer:publisher:governance');
109
126
  protected slashingLog = createLogger('sequencer:publisher:slashing');
110
127
 
111
- protected lastActions: Partial<Record<Action, bigint>> = {};
128
+ protected lastActions: Partial<Record<Action, SlotNumber>> = {};
129
+
130
+ private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
131
+ private payloadProposedCache: Set<string> = new Set<string>();
112
132
 
113
133
  protected log: Logger;
114
134
  protected ethereumSlotDuration: bigint;
115
135
 
116
- private blobSinkClient: BlobSinkClientInterface;
117
- // @note - with blobs, the below estimate seems too large.
118
- // Total used for full block from int_l1_pub e2e test: 1m (of which 86k is 1x blob)
119
- // Total used for emptier block from above test: 429k (of which 84k is 1x blob)
120
- public static PROPOSE_GAS_GUESS: bigint = 12_000_000n;
136
+ private blobClient: BlobClientInterface;
137
+
138
+ /** Address to use for simulations in fisherman mode (actual proposer's address) */
139
+ private proposerAddressForSimulation?: EthAddress;
140
+
141
+ /** Optional callback to obtain a replacement publisher when the current one fails to send. */
142
+ private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
143
+
144
+ /** L1 fee analyzer for fisherman mode */
145
+ private l1FeeAnalyzer?: L1FeeAnalyzer;
146
+
147
+ /** Fee asset price oracle for computing price modifiers from Uniswap V4 */
148
+ private feeAssetPriceOracle: FeeAssetPriceOracle;
121
149
 
122
150
  // A CALL to a cold address is 2700 gas
123
151
  public static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
@@ -125,20 +153,23 @@ export class SequencerPublisher {
125
153
  // Gas report for VotingWithSigTest shows a max gas of 100k, but we've seen it cost 700k+ in testnet
126
154
  public static VOTE_GAS_GUESS: bigint = 800_000n;
127
155
 
128
- public l1TxUtils: L1TxUtilsWithBlobs;
156
+ public l1TxUtils: L1TxUtils;
129
157
  public rollupContract: RollupContract;
130
158
  public govProposerContract: GovernanceProposerContract;
131
159
  public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
132
160
  public slashFactoryContract: SlashFactoryContract;
133
161
 
162
+ public readonly tracer: Tracer;
163
+
134
164
  protected requests: RequestWithExpiry[] = [];
135
165
 
136
166
  constructor(
137
- private config: TxSenderConfig & PublisherConfig & Pick<L1ContractsConfig, 'ethereumSlotDuration'>,
167
+ private config: Pick<SequencerPublisherConfig, 'fishermanMode' | 'l1TxFailedStore'> &
168
+ Pick<L1ContractsConfig, 'ethereumSlotDuration'> & { l1ChainId: number },
138
169
  deps: {
139
170
  telemetry?: TelemetryClient;
140
- blobSinkClient?: BlobSinkClientInterface;
141
- l1TxUtils: L1TxUtilsWithBlobs;
171
+ blobClient: BlobClientInterface;
172
+ l1TxUtils: L1TxUtils;
142
173
  rollupContract: RollupContract;
143
174
  slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
144
175
  governanceProposerContract: GovernanceProposerContract;
@@ -146,8 +177,9 @@ export class SequencerPublisher {
146
177
  epochCache: EpochCache;
147
178
  dateProvider: DateProvider;
148
179
  metrics: SequencerPublisherMetrics;
149
- lastActions: Partial<Record<Action, bigint>>;
180
+ lastActions: Partial<Record<Action, SlotNumber>>;
150
181
  log?: Logger;
182
+ getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
151
183
  },
152
184
  ) {
153
185
  this.log = deps.log ?? createLogger('sequencer:publisher');
@@ -155,12 +187,13 @@ export class SequencerPublisher {
155
187
  this.epochCache = deps.epochCache;
156
188
  this.lastActions = deps.lastActions;
157
189
 
158
- this.blobSinkClient =
159
- deps.blobSinkClient ?? createBlobSinkClient(config, { logger: createLogger('sequencer:blob-sink:client') });
190
+ this.blobClient = deps.blobClient;
160
191
 
161
192
  const telemetry = deps.telemetry ?? getTelemetryClient();
162
193
  this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
194
+ this.tracer = telemetry.getTracer('SequencerPublisher');
163
195
  this.l1TxUtils = deps.l1TxUtils;
196
+ this.getNextPublisher = deps.getNextPublisher;
164
197
 
165
198
  this.rollupContract = deps.rollupContract;
166
199
 
@@ -173,24 +206,155 @@ export class SequencerPublisher {
173
206
  this.slashingProposerContract = newSlashingProposer;
174
207
  });
175
208
  this.slashFactoryContract = deps.slashFactoryContract;
209
+
210
+ // Initialize L1 fee analyzer for fisherman mode
211
+ if (config.fishermanMode) {
212
+ this.l1FeeAnalyzer = new L1FeeAnalyzer(
213
+ this.l1TxUtils.client,
214
+ deps.dateProvider,
215
+ createLogger('sequencer:publisher:fee-analyzer'),
216
+ );
217
+ }
218
+
219
+ // Initialize fee asset price oracle
220
+ this.feeAssetPriceOracle = new FeeAssetPriceOracle(
221
+ this.l1TxUtils.client,
222
+ this.rollupContract,
223
+ createLogger('sequencer:publisher:price-oracle'),
224
+ );
225
+
226
+ // Initialize failed L1 tx store (optional, for test networks)
227
+ this.failedTxStore = createL1TxFailedStore(config.l1TxFailedStore, this.log);
228
+ }
229
+
230
+ /**
231
+ * Backs up a failed L1 transaction to the configured store for debugging.
232
+ * Does nothing if no store is configured.
233
+ */
234
+ private backupFailedTx(failedTx: Omit<FailedL1Tx, 'timestamp'>): void {
235
+ if (!this.failedTxStore) {
236
+ return;
237
+ }
238
+
239
+ const tx: FailedL1Tx = {
240
+ ...failedTx,
241
+ timestamp: Date.now(),
242
+ };
243
+
244
+ // Fire and forget - don't block on backup
245
+ void this.failedTxStore
246
+ .then(store => store?.saveFailedTx(tx))
247
+ .catch(err => {
248
+ this.log.warn(`Failed to backup failed L1 tx to store`, err);
249
+ });
176
250
  }
177
251
 
178
252
  public getRollupContract(): RollupContract {
179
253
  return this.rollupContract;
180
254
  }
181
255
 
256
+ /**
257
+ * Gets the fee asset price modifier from the oracle.
258
+ * Returns 0n if the oracle query fails.
259
+ */
260
+ public getFeeAssetPriceModifier(): Promise<bigint> {
261
+ return this.feeAssetPriceOracle.computePriceModifier();
262
+ }
263
+
182
264
  public getSenderAddress() {
183
265
  return this.l1TxUtils.getSenderAddress();
184
266
  }
185
267
 
268
+ /**
269
+ * Gets the L1 fee analyzer instance (only available in fisherman mode)
270
+ */
271
+ public getL1FeeAnalyzer(): L1FeeAnalyzer | undefined {
272
+ return this.l1FeeAnalyzer;
273
+ }
274
+
275
+ /**
276
+ * Sets the proposer address to use for simulations in fisherman mode.
277
+ * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
278
+ */
279
+ public setProposerAddressForSimulation(proposerAddress: EthAddress | undefined) {
280
+ this.proposerAddressForSimulation = proposerAddress;
281
+ }
282
+
186
283
  public addRequest(request: RequestWithExpiry) {
187
284
  this.requests.push(request);
188
285
  }
189
286
 
190
- public getCurrentL2Slot(): bigint {
287
+ public getCurrentL2Slot(): SlotNumber {
191
288
  return this.epochCache.getEpochAndSlotNow().slot;
192
289
  }
193
290
 
291
+ /**
292
+ * Clears all pending requests without sending them.
293
+ */
294
+ public clearPendingRequests(): void {
295
+ const count = this.requests.length;
296
+ this.requests = [];
297
+ if (count > 0) {
298
+ this.log.debug(`Cleared ${count} pending request(s)`);
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Analyzes L1 fees for the pending requests without sending them.
304
+ * This is used in fisherman mode to validate fee calculations.
305
+ * @param l2SlotNumber - The L2 slot number for this analysis
306
+ * @param onComplete - Optional callback to invoke when analysis completes (after block is mined)
307
+ * @returns The analysis result (incomplete until block mines), or undefined if no requests
308
+ */
309
+ public async analyzeL1Fees(
310
+ l2SlotNumber: SlotNumber,
311
+ onComplete?: (analysis: L1FeeAnalysisResult) => void,
312
+ ): Promise<L1FeeAnalysisResult | undefined> {
313
+ if (!this.l1FeeAnalyzer) {
314
+ this.log.warn('L1 fee analyzer not available (not in fisherman mode)');
315
+ return undefined;
316
+ }
317
+
318
+ const requestsToAnalyze = [...this.requests];
319
+ if (requestsToAnalyze.length === 0) {
320
+ this.log.debug('No requests to analyze for L1 fees');
321
+ return undefined;
322
+ }
323
+
324
+ // Extract blob config from requests (if any)
325
+ const blobConfigs = requestsToAnalyze.filter(request => request.blobConfig).map(request => request.blobConfig);
326
+ const blobConfig = blobConfigs[0];
327
+
328
+ // Get gas configs
329
+ const gasConfigs = requestsToAnalyze.filter(request => request.gasConfig).map(request => request.gasConfig);
330
+ const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
331
+ const gasLimit = gasLimits.length > 0 ? gasLimits.reduce((sum, g) => sum + g, 0n) : 0n;
332
+
333
+ // Get the transaction requests
334
+ const l1Requests = requestsToAnalyze.map(r => r.request);
335
+
336
+ // Start the analysis
337
+ const analysisId = await this.l1FeeAnalyzer.startAnalysis(
338
+ l2SlotNumber,
339
+ gasLimit > 0n ? gasLimit : MAX_L1_TX_LIMIT,
340
+ l1Requests,
341
+ blobConfig,
342
+ onComplete,
343
+ );
344
+
345
+ this.log.info('Started L1 fee analysis', {
346
+ analysisId,
347
+ l2SlotNumber: l2SlotNumber.toString(),
348
+ requestCount: requestsToAnalyze.length,
349
+ hasBlobConfig: !!blobConfig,
350
+ gasLimit: gasLimit.toString(),
351
+ actions: requestsToAnalyze.map(r => r.action),
352
+ });
353
+
354
+ // Return the analysis result (will be incomplete until block mines)
355
+ return this.l1FeeAnalyzer.getAnalysis(analysisId);
356
+ }
357
+
194
358
  /**
195
359
  * Sends all requests that are still valid.
196
360
  * @returns one of:
@@ -198,10 +362,11 @@ export class SequencerPublisher {
198
362
  * - a receipt and errorMsg if it failed on L1
199
363
  * - undefined if no valid requests are found OR the tx failed to send.
200
364
  */
365
+ @trackSpan('SequencerPublisher.sendRequests')
201
366
  public async sendRequests() {
202
367
  const requestsToProcess = [...this.requests];
203
368
  this.requests = [];
204
- if (this.interrupted) {
369
+ if (this.interrupted || requestsToProcess.length === 0) {
205
370
  return undefined;
206
371
  }
207
372
  const currentL2Slot = this.getCurrentL2Slot();
@@ -244,7 +409,16 @@ export class SequencerPublisher {
244
409
 
245
410
  // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
246
411
  const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
247
- const gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
412
+ let gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
413
+ // Cap at L1 block gas limit so the node accepts the tx ("gas limit too high" otherwise).
414
+ const maxGas = MAX_L1_TX_LIMIT;
415
+ if (gasLimit !== undefined && gasLimit > maxGas) {
416
+ this.log.debug('Capping bundled tx gas limit to L1 max', {
417
+ requested: gasLimit,
418
+ capped: maxGas,
419
+ });
420
+ gasLimit = maxGas;
421
+ }
248
422
  const txTimeoutAts = gasConfigs.map(g => g?.txTimeoutAt).filter((g): g is Date => g !== undefined);
249
423
  const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined; // earliest
250
424
  const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
@@ -254,19 +428,36 @@ export class SequencerPublisher {
254
428
  validRequests.sort((a, b) => compareActions(a.action, b.action));
255
429
 
256
430
  try {
431
+ // Capture context for failed tx backup before sending
432
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
433
+ const multicallData = encodeFunctionData({
434
+ abi: multicall3Abi,
435
+ functionName: 'aggregate3',
436
+ args: [
437
+ validRequests.map(r => ({
438
+ target: r.request.to!,
439
+ callData: r.request.data!,
440
+ allowFailure: true,
441
+ })),
442
+ ],
443
+ });
444
+ const blobDataHex = blobConfig?.blobs?.map(b => toHex(b)) as Hex[] | undefined;
445
+
446
+ const txContext = { multicallData, blobData: blobDataHex, l1BlockNumber };
447
+
257
448
  this.log.debug('Forwarding transactions', {
258
449
  validRequests: validRequests.map(request => request.action),
259
450
  txConfig,
260
451
  });
261
- const result = await Multicall3.forward(
262
- validRequests.map(request => request.request),
263
- this.l1TxUtils,
264
- txConfig,
265
- blobConfig,
266
- this.rollupContract.address,
267
- this.log,
452
+ const result = await this.forwardWithPublisherRotation(validRequests, txConfig, blobConfig);
453
+ if (result === undefined) {
454
+ return undefined;
455
+ }
456
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(
457
+ validRequests,
458
+ result,
459
+ txContext,
268
460
  );
269
- const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(validRequests, result);
270
461
  return { result, expiredActions, sentActions: validActions, successfulActions, failedActions };
271
462
  } catch (err) {
272
463
  const viemError = formatViemError(err);
@@ -284,13 +475,76 @@ export class SequencerPublisher {
284
475
  }
285
476
  }
286
477
 
478
+ /**
479
+ * Forwards transactions via Multicall3, rotating to the next available publisher if a send
480
+ * failure occurs (i.e. the tx never reached the chain).
481
+ * On-chain reverts and simulation errors are returned as-is without rotation.
482
+ */
483
+ private async forwardWithPublisherRotation(
484
+ validRequests: RequestWithExpiry[],
485
+ txConfig: RequestWithExpiry['gasConfig'],
486
+ blobConfig: L1BlobInputs | undefined,
487
+ ) {
488
+ const triedAddresses: EthAddress[] = [];
489
+ let currentPublisher = this.l1TxUtils;
490
+
491
+ while (true) {
492
+ triedAddresses.push(currentPublisher.getSenderAddress());
493
+ try {
494
+ const result = await Multicall3.forward(
495
+ validRequests.map(r => r.request),
496
+ currentPublisher,
497
+ txConfig,
498
+ blobConfig,
499
+ this.rollupContract.address,
500
+ this.log,
501
+ );
502
+ this.l1TxUtils = currentPublisher;
503
+ return result;
504
+ } catch (err) {
505
+ if (err instanceof TimeoutError) {
506
+ throw err;
507
+ }
508
+ const viemError = formatViemError(err);
509
+ if (!this.getNextPublisher) {
510
+ this.log.error('Failed to publish bundled transactions', viemError);
511
+ return undefined;
512
+ }
513
+ this.log.warn(
514
+ `Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`,
515
+ viemError,
516
+ );
517
+ const nextPublisher = await this.getNextPublisher([...triedAddresses]);
518
+ if (!nextPublisher) {
519
+ this.log.error('All available publishers exhausted, failed to publish bundled transactions');
520
+ return undefined;
521
+ }
522
+ currentPublisher = nextPublisher;
523
+ }
524
+ }
525
+ }
526
+
287
527
  private callbackBundledTransactions(
288
528
  requests: RequestWithExpiry[],
289
- result?: { receipt: TransactionReceipt } | FormattedViemError,
529
+ result: { receipt: TransactionReceipt; errorMsg?: string } | FormattedViemError | undefined,
530
+ txContext: { multicallData: Hex; blobData?: Hex[]; l1BlockNumber: bigint },
290
531
  ) {
291
532
  const actionsListStr = requests.map(r => r.action).join(', ');
292
533
  if (result instanceof FormattedViemError) {
293
534
  this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
535
+ this.backupFailedTx({
536
+ id: keccak256(txContext.multicallData),
537
+ failureType: 'send-error',
538
+ request: { to: MULTI_CALL_3_ADDRESS, data: txContext.multicallData },
539
+ blobData: txContext.blobData,
540
+ l1BlockNumber: txContext.l1BlockNumber.toString(),
541
+ error: { message: result.message, name: result.name },
542
+ context: {
543
+ actions: requests.map(r => r.action),
544
+ requests: requests.map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
545
+ sender: this.getSenderAddress().toString(),
546
+ },
547
+ });
294
548
  return { failedActions: requests.map(r => r.action) };
295
549
  } else {
296
550
  this.log.verbose(`Published bundled transactions (${actionsListStr})`, { result, requests });
@@ -303,6 +557,30 @@ export class SequencerPublisher {
303
557
  failedActions.push(request.action);
304
558
  }
305
559
  }
560
+ // Single backup for the whole reverted tx
561
+ if (failedActions.length > 0 && result?.receipt?.status === 'reverted') {
562
+ this.backupFailedTx({
563
+ id: result.receipt.transactionHash,
564
+ failureType: 'revert',
565
+ request: { to: MULTI_CALL_3_ADDRESS, data: txContext.multicallData },
566
+ blobData: txContext.blobData,
567
+ l1BlockNumber: result.receipt.blockNumber.toString(),
568
+ receipt: {
569
+ transactionHash: result.receipt.transactionHash,
570
+ blockNumber: result.receipt.blockNumber.toString(),
571
+ gasUsed: (result.receipt.gasUsed ?? 0n).toString(),
572
+ status: 'reverted',
573
+ },
574
+ error: { message: result.errorMsg ?? 'Transaction reverted' },
575
+ context: {
576
+ actions: failedActions,
577
+ requests: requests
578
+ .filter(r => failedActions.includes(r.action))
579
+ .map(r => ({ action: r.action, to: r.request.to! as Hex, data: r.request.data! })),
580
+ sender: this.getSenderAddress().toString(),
581
+ },
582
+ });
583
+ }
306
584
  return { successfulActions, failedActions };
307
585
  }
308
586
  }
@@ -315,13 +593,15 @@ export class SequencerPublisher {
315
593
  public canProposeAtNextEthBlock(
316
594
  tipArchive: Fr,
317
595
  msgSender: EthAddress,
318
- opts: { forcePendingBlockNumber?: number } = {},
596
+ opts: { forcePendingCheckpointNumber?: CheckpointNumber } = {},
319
597
  ) {
320
598
  // TODO: #14291 - should loop through multiple keys to check if any of them can propose
321
599
  const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
322
600
 
323
601
  return this.rollupContract
324
- .canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), this.ethereumSlotDuration, opts)
602
+ .canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
603
+ forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
604
+ })
325
605
  .catch(err => {
326
606
  if (err instanceof FormattedViemError && ignoredErrors.find(e => err.message.includes(e))) {
327
607
  this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find(e => err.message.includes(e))}`, {
@@ -339,7 +619,11 @@ export class SequencerPublisher {
339
619
  * It will throw if the block header is invalid.
340
620
  * @param header - The block header to validate
341
621
  */
342
- public async validateBlockHeader(header: CheckpointHeader, opts?: { forcePendingBlockNumber: number | undefined }) {
622
+ @trackSpan('SequencerPublisher.validateBlockHeader')
623
+ public async validateBlockHeader(
624
+ header: CheckpointHeader,
625
+ opts?: { forcePendingCheckpointNumber: CheckpointNumber | undefined },
626
+ ): Promise<void> {
343
627
  const flags = { ignoreDA: true, ignoreSignatures: true };
344
628
 
345
629
  const args = [
@@ -348,15 +632,27 @@ export class SequencerPublisher {
348
632
  [], // no signers
349
633
  Signature.empty().toViemSignature(),
350
634
  `0x${'0'.repeat(64)}`, // 32 empty bytes
351
- header.contentCommitment.blobsHash.toString(),
635
+ header.blobsHash.toString(),
352
636
  flags,
353
637
  ] as const;
354
638
 
355
639
  const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
640
+ const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
641
+ opts?.forcePendingCheckpointNumber,
642
+ );
643
+ let balance = 0n;
644
+ if (this.config.fishermanMode) {
645
+ // In fisherman mode, we can't know where the proposer is publishing from
646
+ // so we just add sufficient balance to the multicall3 address
647
+ balance = 10n * WEI_CONST * WEI_CONST; // 10 ETH
648
+ } else {
649
+ balance = await this.l1TxUtils.getSenderBalance();
650
+ }
651
+ stateOverrides.push({
652
+ address: MULTI_CALL_3_ADDRESS,
653
+ balance,
654
+ });
356
655
 
357
- // use sender balance to simulate
358
- const balance = await this.l1TxUtils.getSenderBalance();
359
- this.log.debug(`Simulating validateHeader with balance: ${balance}`);
360
656
  await this.l1TxUtils.simulate(
361
657
  {
362
658
  to: this.rollupContract.address,
@@ -364,86 +660,115 @@ export class SequencerPublisher {
364
660
  from: MULTI_CALL_3_ADDRESS,
365
661
  },
366
662
  { time: ts + 1n },
367
- [
368
- { address: MULTI_CALL_3_ADDRESS, balance },
369
- ...(await this.rollupContract.makePendingBlockNumberOverride(opts?.forcePendingBlockNumber)),
370
- ],
663
+ stateOverrides,
371
664
  );
372
665
  this.log.debug(`Simulated validateHeader`);
373
666
  }
374
667
 
375
668
  /**
376
- * Simulate making a call to invalidate a block with invalid attestations. Returns undefined if no need to invalidate.
377
- * @param block - The block to invalidate and the criteria for invalidation (as returned by the archiver)
669
+ * Simulate making a call to invalidate a checkpoint with invalid attestations. Returns undefined if no need to invalidate.
670
+ * @param validationResult - The validation result indicating which checkpoint to invalidate (as returned by the archiver)
378
671
  */
379
- public async simulateInvalidateBlock(
380
- validationResult: ValidateBlockResult,
381
- ): Promise<InvalidateBlockRequest | undefined> {
672
+ public async simulateInvalidateCheckpoint(
673
+ validationResult: ValidateCheckpointResult,
674
+ ): Promise<InvalidateCheckpointRequest | undefined> {
382
675
  if (validationResult.valid) {
383
676
  return undefined;
384
677
  }
385
678
 
386
- const { reason, block } = validationResult;
387
- const blockNumber = block.blockNumber;
388
- const logData = { ...block, reason };
679
+ const { reason, checkpoint } = validationResult;
680
+ const checkpointNumber = checkpoint.checkpointNumber;
681
+ const logData = { ...checkpoint, reason };
389
682
 
390
- const currentBlockNumber = await this.rollupContract.getBlockNumber();
391
- if (currentBlockNumber < validationResult.block.blockNumber) {
683
+ const currentCheckpointNumber = await this.rollupContract.getCheckpointNumber();
684
+ if (currentCheckpointNumber < checkpointNumber) {
392
685
  this.log.verbose(
393
- `Skipping block ${blockNumber} invalidation since it has already been removed from the pending chain`,
394
- { currentBlockNumber, ...logData },
686
+ `Skipping checkpoint ${checkpointNumber} invalidation since it has already been removed from the pending chain`,
687
+ { currentCheckpointNumber, ...logData },
395
688
  );
396
689
  return undefined;
397
690
  }
398
691
 
399
- const request = this.buildInvalidateBlockRequest(validationResult);
400
- this.log.debug(`Simulating invalidate block ${blockNumber}`, { ...logData, request });
692
+ const request = this.buildInvalidateCheckpointRequest(validationResult);
693
+ this.log.debug(`Simulating invalidate checkpoint ${checkpointNumber}`, { ...logData, request });
694
+
695
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
401
696
 
402
697
  try {
403
- const { gasUsed } = await this.l1TxUtils.simulate(request, undefined, undefined, ErrorsAbi);
404
- this.log.verbose(`Simulation for invalidate block ${blockNumber} succeeded`, { ...logData, request, gasUsed });
698
+ const { gasUsed } = await this.l1TxUtils.simulate(
699
+ request,
700
+ undefined,
701
+ undefined,
702
+ mergeAbis([request.abi ?? [], ErrorsAbi]),
703
+ );
704
+ this.log.verbose(`Simulation for invalidate checkpoint ${checkpointNumber} succeeded`, {
705
+ ...logData,
706
+ request,
707
+ gasUsed,
708
+ });
405
709
 
406
- return { request, gasUsed, blockNumber, forcePendingBlockNumber: blockNumber - 1, reason };
710
+ return {
711
+ request,
712
+ gasUsed,
713
+ checkpointNumber,
714
+ forcePendingCheckpointNumber: CheckpointNumber(checkpointNumber - 1),
715
+ reason,
716
+ };
407
717
  } catch (err) {
408
718
  const viemError = formatViemError(err);
409
719
 
410
- // If the error is due to the block not being in the pending chain, and it was indeed removed by someone else,
411
- // we can safely ignore it and return undefined so we go ahead with block building.
412
- if (viemError.message?.includes('Rollup__BlockNotInPendingChain')) {
720
+ // If the error is due to the checkpoint not being in the pending chain, and it was indeed removed by someone else,
721
+ // we can safely ignore it and return undefined so we go ahead with checkpoint building.
722
+ if (viemError.message?.includes('Rollup__CheckpointNotInPendingChain')) {
413
723
  this.log.verbose(
414
- `Simulation for invalidate block ${blockNumber} failed due to block not being in pending chain`,
724
+ `Simulation for invalidate checkpoint ${checkpointNumber} failed due to checkpoint not being in pending chain`,
415
725
  { ...logData, request, error: viemError.message },
416
726
  );
417
- const latestPendingBlockNumber = await this.rollupContract.getBlockNumber();
418
- if (latestPendingBlockNumber < blockNumber) {
419
- this.log.verbose(`Block number ${blockNumber} has already been invalidated`, { ...logData });
727
+ const latestPendingCheckpointNumber = await this.rollupContract.getCheckpointNumber();
728
+ if (latestPendingCheckpointNumber < checkpointNumber) {
729
+ this.log.verbose(`Checkpoint ${checkpointNumber} has already been invalidated`, { ...logData });
420
730
  return undefined;
421
731
  } else {
422
732
  this.log.error(
423
- `Simulation for invalidate ${blockNumber} failed and it is still in pending chain`,
733
+ `Simulation for invalidate checkpoint ${checkpointNumber} failed and it is still in pending chain`,
424
734
  viemError,
425
735
  logData,
426
736
  );
427
- throw new Error(`Failed to simulate invalidate block ${blockNumber} while it is still in pending chain`, {
428
- cause: viemError,
429
- });
737
+ throw new Error(
738
+ `Failed to simulate invalidate checkpoint ${checkpointNumber} while it is still in pending chain`,
739
+ {
740
+ cause: viemError,
741
+ },
742
+ );
430
743
  }
431
744
  }
432
745
 
433
- // Otherwise, throw. We cannot build the next block if we cannot invalidate the previous one.
434
- this.log.error(`Simulation for invalidate block ${blockNumber} failed`, viemError, logData);
435
- throw new Error(`Failed to simulate invalidate block ${blockNumber}`, { cause: viemError });
746
+ // Otherwise, throw. We cannot build the next checkpoint if we cannot invalidate the previous one.
747
+ this.log.error(`Simulation for invalidate checkpoint ${checkpointNumber} failed`, viemError, logData);
748
+ this.backupFailedTx({
749
+ id: keccak256(request.data!),
750
+ failureType: 'simulation',
751
+ request: { to: request.to!, data: request.data!, value: request.value?.toString() },
752
+ l1BlockNumber: l1BlockNumber.toString(),
753
+ error: { message: viemError.message, name: viemError.name },
754
+ context: {
755
+ actions: [`invalidate-${reason}`],
756
+ checkpointNumber,
757
+ sender: this.getSenderAddress().toString(),
758
+ },
759
+ });
760
+ throw new Error(`Failed to simulate invalidate checkpoint ${checkpointNumber}`, { cause: viemError });
436
761
  }
437
762
  }
438
763
 
439
- private buildInvalidateBlockRequest(validationResult: ValidateBlockResult) {
764
+ private buildInvalidateCheckpointRequest(validationResult: ValidateCheckpointResult) {
440
765
  if (validationResult.valid) {
441
- throw new Error('Cannot invalidate a valid block');
766
+ throw new Error('Cannot invalidate a valid checkpoint');
442
767
  }
443
768
 
444
- const { block, committee, reason } = validationResult;
445
- const logData = { ...block, reason };
446
- this.log.debug(`Simulating invalidate block ${block.blockNumber}`, logData);
769
+ const { checkpoint, committee, reason } = validationResult;
770
+ const logData = { ...checkpoint, reason };
771
+ this.log.debug(`Building invalidate checkpoint ${checkpoint.checkpointNumber} request`, logData);
447
772
 
448
773
  const attestationsAndSigners = new CommitteeAttestationsAndSigners(
449
774
  validationResult.attestations,
@@ -451,14 +776,14 @@ export class SequencerPublisher {
451
776
 
452
777
  if (reason === 'invalid-attestation') {
453
778
  return this.rollupContract.buildInvalidateBadAttestationRequest(
454
- block.blockNumber,
779
+ checkpoint.checkpointNumber,
455
780
  attestationsAndSigners,
456
781
  committee,
457
782
  validationResult.invalidIndex,
458
783
  );
459
784
  } else if (reason === 'insufficient-attestations') {
460
785
  return this.rollupContract.buildInvalidateInsufficientAttestationsRequest(
461
- block.blockNumber,
786
+ checkpoint.checkpointNumber,
462
787
  attestationsAndSigners,
463
788
  committee,
464
789
  );
@@ -468,48 +793,25 @@ export class SequencerPublisher {
468
793
  }
469
794
  }
470
795
 
471
- /**
472
- * @notice Will simulate `propose` to make sure that the block is valid for submission
473
- *
474
- * @dev Throws if unable to propose
475
- *
476
- * @param block - The block to propose
477
- * @param attestationData - The block's attestation data
478
- *
479
- */
480
- public async validateBlockForSubmission(
481
- block: L2Block,
796
+ /** Simulates `propose` to make sure that the checkpoint is valid for submission */
797
+ @trackSpan('SequencerPublisher.validateCheckpointForSubmission')
798
+ public async validateCheckpointForSubmission(
799
+ checkpoint: Checkpoint,
482
800
  attestationsAndSigners: CommitteeAttestationsAndSigners,
483
801
  attestationsAndSignersSignature: Signature,
484
- options: { forcePendingBlockNumber?: number },
802
+ options: { forcePendingCheckpointNumber?: CheckpointNumber },
485
803
  ): Promise<bigint> {
486
804
  const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
487
-
488
- // If we have no attestations, we still need to provide the empty attestations
489
- // so that the committee is recalculated correctly
490
- const ignoreSignatures = attestationsAndSigners.attestations.length === 0;
491
- if (ignoreSignatures) {
492
- const { committee } = await this.epochCache.getCommittee(block.header.globalVariables.slotNumber.toBigInt());
493
- if (!committee) {
494
- this.log.warn(`No committee found for slot ${block.header.globalVariables.slotNumber.toBigInt()}`);
495
- throw new Error(`No committee found for slot ${block.header.globalVariables.slotNumber.toBigInt()}`);
496
- }
497
- attestationsAndSigners.attestations = committee.map(committeeMember =>
498
- CommitteeAttestation.fromAddress(committeeMember),
499
- );
500
- }
501
-
502
- const blobFields = block.getCheckpointBlobFields();
503
- const blobs = getBlobsPerL1Block(blobFields);
805
+ const blobFields = checkpoint.toBlobFields();
806
+ const blobs = await getBlobsPerL1Block(blobFields);
504
807
  const blobInput = getPrefixedEthBlobCommitments(blobs);
505
808
 
506
809
  const args = [
507
810
  {
508
- header: block.getCheckpointHeader().toViem(),
509
- archive: toHex(block.archive.root.toBuffer()),
510
- stateReference: block.header.state.toViem(),
811
+ header: checkpoint.header.toViem(),
812
+ archive: toHex(checkpoint.archive.root.toBuffer()),
511
813
  oracleInput: {
512
- feeAssetPriceModifier: 0n,
814
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
513
815
  },
514
816
  },
515
817
  attestationsAndSigners.getPackedAttestations(),
@@ -523,7 +825,7 @@ export class SequencerPublisher {
523
825
  }
524
826
 
525
827
  private async enqueueCastSignalHelper(
526
- slotNumber: bigint,
828
+ slotNumber: SlotNumber,
527
829
  timestamp: bigint,
528
830
  signalType: GovernanceSignalAction,
529
831
  payload: EthAddress,
@@ -545,10 +847,45 @@ export class SequencerPublisher {
545
847
  const round = await base.computeRound(slotNumber);
546
848
  const roundInfo = await base.getRoundInfo(this.rollupContract.address, round);
547
849
 
850
+ if (roundInfo.quorumReached) {
851
+ return false;
852
+ }
853
+
548
854
  if (roundInfo.lastSignalSlot >= slotNumber) {
549
855
  return false;
550
856
  }
551
857
 
858
+ if (await this.isPayloadEmpty(payload)) {
859
+ this.log.warn(`Skipping vote cast for payload with empty code`);
860
+ return false;
861
+ }
862
+
863
+ // Check if payload was already submitted to governance
864
+ const cacheKey = payload.toString();
865
+ if (!this.payloadProposedCache.has(cacheKey)) {
866
+ try {
867
+ const l1StartBlock = await this.rollupContract.getL1StartBlock();
868
+ const proposed = await retry(
869
+ () => base.hasPayloadBeenProposed(payload.toString(), l1StartBlock),
870
+ 'Check if payload was proposed',
871
+ makeBackoff([0, 1, 2]),
872
+ this.log,
873
+ true,
874
+ );
875
+ if (proposed) {
876
+ this.payloadProposedCache.add(cacheKey);
877
+ }
878
+ } catch (err) {
879
+ this.log.warn(`Failed to check if payload ${payload} was proposed after retries, skipping signal`, err);
880
+ return false;
881
+ }
882
+ }
883
+
884
+ if (this.payloadProposedCache.has(cacheKey)) {
885
+ this.log.info(`Payload ${payload} was already proposed to governance, stopping signals`);
886
+ return false;
887
+ }
888
+
552
889
  const cachedLastVote = this.lastActions[signalType];
553
890
  this.lastActions[signalType] = slotNumber;
554
891
  const action = signalType;
@@ -567,11 +904,26 @@ export class SequencerPublisher {
567
904
  lastValidL2Slot: slotNumber,
568
905
  });
569
906
 
907
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
908
+
570
909
  try {
571
- await this.l1TxUtils.simulate(request, { time: timestamp }, [], ErrorsAbi);
910
+ await this.l1TxUtils.simulate(request, { time: timestamp }, [], mergeAbis([request.abi ?? [], ErrorsAbi]));
572
911
  this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, { request });
573
912
  } catch (err) {
574
- this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, err);
913
+ const viemError = formatViemError(err);
914
+ this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, viemError);
915
+ this.backupFailedTx({
916
+ id: keccak256(request.data!),
917
+ failureType: 'simulation',
918
+ request: { to: request.to!, data: request.data!, value: request.value?.toString() },
919
+ l1BlockNumber: l1BlockNumber.toString(),
920
+ error: { message: viemError.message, name: viemError.name },
921
+ context: {
922
+ actions: [action],
923
+ slot: slotNumber,
924
+ sender: this.getSenderAddress().toString(),
925
+ },
926
+ });
575
927
  // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
576
928
  }
577
929
 
@@ -591,14 +943,14 @@ export class SequencerPublisher {
591
943
  const logData = { ...result, slotNumber, round, payload: payload.toString() };
592
944
  if (!success) {
593
945
  this.log.error(
594
- `Signaling in [${action}] for ${payload} at slot ${slotNumber} in round ${round} failed`,
946
+ `Signaling in ${action} for ${payload} at slot ${slotNumber} in round ${round} failed`,
595
947
  logData,
596
948
  );
597
949
  this.lastActions[signalType] = cachedLastVote;
598
950
  return false;
599
951
  } else {
600
952
  this.log.info(
601
- `Signaling in [${action}] for ${payload} at slot ${slotNumber} in round ${round} succeeded`,
953
+ `Signaling in ${action} for ${payload} at slot ${slotNumber} in round ${round} succeeded`,
602
954
  logData,
603
955
  );
604
956
  return true;
@@ -608,6 +960,17 @@ export class SequencerPublisher {
608
960
  return true;
609
961
  }
610
962
 
963
+ private async isPayloadEmpty(payload: EthAddress): Promise<boolean> {
964
+ const key = payload.toString();
965
+ const cached = this.isPayloadEmptyCache.get(key);
966
+ if (cached) {
967
+ return cached;
968
+ }
969
+ const isEmpty = !(await this.l1TxUtils.getCode(payload));
970
+ this.isPayloadEmptyCache.set(key, isEmpty);
971
+ return isEmpty;
972
+ }
973
+
611
974
  /**
612
975
  * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
613
976
  * @param slotNumber - The slot number to cast a signal for.
@@ -616,7 +979,7 @@ export class SequencerPublisher {
616
979
  */
617
980
  public enqueueGovernanceCastSignal(
618
981
  governancePayload: EthAddress,
619
- slotNumber: bigint,
982
+ slotNumber: SlotNumber,
620
983
  timestamp: bigint,
621
984
  signerAddress: EthAddress,
622
985
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
@@ -635,7 +998,7 @@ export class SequencerPublisher {
635
998
  /** Enqueues all slashing actions as returned by the slasher client. */
636
999
  public async enqueueSlashingActions(
637
1000
  actions: ProposerSlashAction[],
638
- slotNumber: bigint,
1001
+ slotNumber: SlotNumber,
639
1002
  timestamp: bigint,
640
1003
  signerAddress: EthAddress,
641
1004
  signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
@@ -755,31 +1118,25 @@ export class SequencerPublisher {
755
1118
  return true;
756
1119
  }
757
1120
 
758
- /**
759
- * Proposes a L2 block on L1.
760
- *
761
- * @param block - L2 block to propose.
762
- * @returns True if the tx has been enqueued, throws otherwise. See #9315
763
- */
764
- public async enqueueProposeL2Block(
765
- block: L2Block,
1121
+ /** Simulates and enqueues a proposal for a checkpoint on L1 */
1122
+ public async enqueueProposeCheckpoint(
1123
+ checkpoint: Checkpoint,
766
1124
  attestationsAndSigners: CommitteeAttestationsAndSigners,
767
1125
  attestationsAndSignersSignature: Signature,
768
- opts: { txTimeoutAt?: Date; forcePendingBlockNumber?: number } = {},
769
- ): Promise<boolean> {
770
- const checkpointHeader = block.getCheckpointHeader();
1126
+ opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1127
+ ): Promise<void> {
1128
+ const checkpointHeader = checkpoint.header;
771
1129
 
772
- const blobFields = block.getCheckpointBlobFields();
773
- const blobs = getBlobsPerL1Block(blobFields);
1130
+ const blobFields = checkpoint.toBlobFields();
1131
+ const blobs = await getBlobsPerL1Block(blobFields);
774
1132
 
775
- const proposeTxArgs = {
1133
+ const proposeTxArgs: L1ProcessArgs = {
776
1134
  header: checkpointHeader,
777
- archive: block.archive.root.toBuffer(),
778
- stateReference: block.header.state,
779
- body: block.body.toBuffer(),
1135
+ archive: checkpoint.archive.root.toBuffer(),
780
1136
  blobs,
781
1137
  attestationsAndSigners,
782
1138
  attestationsAndSignersSignature,
1139
+ feeAssetPriceModifier: checkpoint.feeAssetPriceModifier,
783
1140
  };
784
1141
 
785
1142
  let ts: bigint;
@@ -790,22 +1147,29 @@ export class SequencerPublisher {
790
1147
  // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
791
1148
  // make time consistency checks break.
792
1149
  // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
793
- ts = await this.validateBlockForSubmission(block, attestationsAndSigners, attestationsAndSignersSignature, opts);
1150
+ ts = await this.validateCheckpointForSubmission(
1151
+ checkpoint,
1152
+ attestationsAndSigners,
1153
+ attestationsAndSignersSignature,
1154
+ opts,
1155
+ );
794
1156
  } catch (err: any) {
795
- this.log.error(`Block validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
796
- ...block.getStats(),
797
- slotNumber: block.header.globalVariables.slotNumber.toBigInt(),
798
- forcePendingBlockNumber: opts.forcePendingBlockNumber,
1157
+ this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
1158
+ ...checkpoint.getStats(),
1159
+ slotNumber: checkpoint.header.slotNumber,
1160
+ forcePendingCheckpointNumber: opts.forcePendingCheckpointNumber,
799
1161
  });
800
1162
  throw err;
801
1163
  }
802
1164
 
803
- this.log.verbose(`Enqueuing block propose transaction`, { ...block.toBlockInfo(), ...opts });
804
- await this.addProposeTx(block, proposeTxArgs, opts, ts);
805
- return true;
1165
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, { ...checkpoint.toCheckpointInfo(), ...opts });
1166
+ await this.addProposeTx(checkpoint, proposeTxArgs, opts, ts);
806
1167
  }
807
1168
 
808
- public enqueueInvalidateBlock(request: InvalidateBlockRequest | undefined, opts: { txTimeoutAt?: Date } = {}) {
1169
+ public enqueueInvalidateCheckpoint(
1170
+ request: InvalidateCheckpointRequest | undefined,
1171
+ opts: { txTimeoutAt?: Date } = {},
1172
+ ) {
809
1173
  if (!request) {
810
1174
  return;
811
1175
  }
@@ -813,24 +1177,24 @@ export class SequencerPublisher {
813
1177
  // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
814
1178
  const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(request.gasUsed) * 64) / 63)));
815
1179
 
816
- const { gasUsed, blockNumber } = request;
817
- const logData = { gasUsed, blockNumber, gasLimit, opts };
818
- this.log.verbose(`Enqueuing invalidate block request`, logData);
1180
+ const { gasUsed, checkpointNumber } = request;
1181
+ const logData = { gasUsed, checkpointNumber, gasLimit, opts };
1182
+ this.log.verbose(`Enqueuing invalidate checkpoint request`, logData);
819
1183
  this.addRequest({
820
1184
  action: `invalidate-by-${request.reason}`,
821
1185
  request: request.request,
822
1186
  gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
823
- lastValidL2Slot: this.getCurrentL2Slot() + 2n,
1187
+ lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
824
1188
  checkSuccess: (_req, result) => {
825
1189
  const success =
826
1190
  result &&
827
1191
  result.receipt &&
828
1192
  result.receipt.status === 'success' &&
829
- tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'BlockInvalidated');
1193
+ tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
830
1194
  if (!success) {
831
- this.log.warn(`Invalidate block ${request.blockNumber} failed`, { ...result, ...logData });
1195
+ this.log.warn(`Invalidate checkpoint ${request.checkpointNumber} failed`, { ...result, ...logData });
832
1196
  } else {
833
- this.log.info(`Invalidate block ${request.blockNumber} succeeded`, { ...result, ...logData });
1197
+ this.log.info(`Invalidate checkpoint ${request.checkpointNumber} succeeded`, { ...result, ...logData });
834
1198
  }
835
1199
  return !!success;
836
1200
  },
@@ -841,7 +1205,7 @@ export class SequencerPublisher {
841
1205
  action: Action,
842
1206
  request: L1TxRequest,
843
1207
  checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
844
- slotNumber: bigint,
1208
+ slotNumber: SlotNumber,
845
1209
  timestamp: bigint,
846
1210
  ) {
847
1211
  const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
@@ -855,13 +1219,30 @@ export class SequencerPublisher {
855
1219
 
856
1220
  this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
857
1221
 
1222
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1223
+
858
1224
  let gasUsed: bigint;
1225
+ const simulateAbi = mergeAbis([request.abi ?? [], ErrorsAbi]);
859
1226
  try {
860
- ({ gasUsed } = await this.l1TxUtils.simulate(request, { time: timestamp }, [], ErrorsAbi)); // TODO(palla/slash): Check the timestamp logic
1227
+ ({ gasUsed } = await this.l1TxUtils.simulate(request, { time: timestamp }, [], simulateAbi)); // TODO(palla/slash): Check the timestamp logic
861
1228
  this.log.verbose(`Simulation for ${action} succeeded`, { ...logData, request, gasUsed });
862
1229
  } catch (err) {
863
- const viemError = formatViemError(err);
1230
+ const viemError = formatViemError(err, simulateAbi);
864
1231
  this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
1232
+
1233
+ this.backupFailedTx({
1234
+ id: keccak256(request.data!),
1235
+ failureType: 'simulation',
1236
+ request: { to: request.to!, data: request.data!, value: request.value?.toString() },
1237
+ l1BlockNumber: l1BlockNumber.toString(),
1238
+ error: { message: viemError.message, name: viemError.name },
1239
+ context: {
1240
+ actions: [action],
1241
+ slot: slotNumber,
1242
+ sender: this.getSenderAddress().toString(),
1243
+ },
1244
+ });
1245
+
865
1246
  return false;
866
1247
  }
867
1248
 
@@ -869,10 +1250,14 @@ export class SequencerPublisher {
869
1250
  const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(gasUsed) * 64) / 63)));
870
1251
  logData.gasLimit = gasLimit;
871
1252
 
1253
+ // Store the ABI used for simulation on the request so Multicall3.forward can decode errors
1254
+ // when the tx is sent and a revert is diagnosed via simulation.
1255
+ const requestWithAbi = { ...request, abi: simulateAbi };
1256
+
872
1257
  this.log.debug(`Enqueuing ${action}`, logData);
873
1258
  this.addRequest({
874
1259
  action,
875
- request,
1260
+ request: requestWithAbi,
876
1261
  gasConfig: { gasLimit },
877
1262
  lastValidL2Slot: slotNumber,
878
1263
  checkSuccess: (_req, result) => {
@@ -909,44 +1294,70 @@ export class SequencerPublisher {
909
1294
  private async prepareProposeTx(
910
1295
  encodedData: L1ProcessArgs,
911
1296
  timestamp: bigint,
912
- options: { forcePendingBlockNumber?: number },
1297
+ options: { forcePendingCheckpointNumber?: CheckpointNumber },
913
1298
  ) {
914
1299
  const kzg = Blob.getViemKzgInstance();
915
1300
  const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
916
1301
  this.log.debug('Validating blob input', { blobInput });
917
- const blobEvaluationGas = await this.l1TxUtils
918
- .estimateGas(
919
- this.getSenderAddress().toString(),
920
- {
921
- to: this.rollupContract.address,
922
- data: encodeFunctionData({
1302
+
1303
+ // Get blob evaluation gas
1304
+ let blobEvaluationGas: bigint;
1305
+ if (this.config.fishermanMode) {
1306
+ // In fisherman mode, we can't estimate blob gas because estimateGas doesn't support state overrides
1307
+ // Use a fixed estimate.
1308
+ blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1309
+ this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1310
+ } else {
1311
+ // Normal mode - use estimateGas with blob inputs
1312
+ blobEvaluationGas = await this.l1TxUtils
1313
+ .estimateGas(
1314
+ this.getSenderAddress().toString(),
1315
+ {
1316
+ to: this.rollupContract.address,
1317
+ data: encodeFunctionData({
1318
+ abi: RollupAbi,
1319
+ functionName: 'validateBlobs',
1320
+ args: [blobInput],
1321
+ }),
1322
+ },
1323
+ {},
1324
+ {
1325
+ blobs: encodedData.blobs.map(b => b.data),
1326
+ kzg,
1327
+ },
1328
+ )
1329
+ .catch(async err => {
1330
+ const viemError = formatViemError(err);
1331
+ this.log.error(`Failed to validate blobs`, viemError.message, { metaMessages: viemError.metaMessages });
1332
+ const validateBlobsData = encodeFunctionData({
923
1333
  abi: RollupAbi,
924
1334
  functionName: 'validateBlobs',
925
1335
  args: [blobInput],
926
- }),
927
- },
928
- {},
929
- {
930
- blobs: encodedData.blobs.map(b => b.data),
931
- kzg,
932
- },
933
- )
934
- .catch(err => {
935
- const { message, metaMessages } = formatViemError(err);
936
- this.log.error(`Failed to validate blobs`, message, { metaMessages });
937
- throw new Error('Failed to validate blobs');
938
- });
939
-
1336
+ });
1337
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1338
+ this.backupFailedTx({
1339
+ id: keccak256(validateBlobsData),
1340
+ failureType: 'simulation',
1341
+ request: { to: this.rollupContract.address as Hex, data: validateBlobsData },
1342
+ blobData: encodedData.blobs.map(b => toHex(b.data)) as Hex[],
1343
+ l1BlockNumber: l1BlockNumber.toString(),
1344
+ error: { message: viemError.message, name: viemError.name },
1345
+ context: {
1346
+ actions: ['validate-blobs'],
1347
+ sender: this.getSenderAddress().toString(),
1348
+ },
1349
+ });
1350
+ throw new Error('Failed to validate blobs');
1351
+ });
1352
+ }
940
1353
  const signers = encodedData.attestationsAndSigners.getSigners().map(signer => signer.toString());
941
1354
 
942
1355
  const args = [
943
1356
  {
944
1357
  header: encodedData.header.toViem(),
945
1358
  archive: toHex(encodedData.archive),
946
- stateReference: encodedData.stateReference.toViem(),
947
1359
  oracleInput: {
948
- // We are currently not modifying these. See #9963
949
- feeAssetPriceModifier: 0n,
1360
+ feeAssetPriceModifier: encodedData.feeAssetPriceModifier,
950
1361
  },
951
1362
  },
952
1363
  encodedData.attestationsAndSigners.getPackedAttestations(),
@@ -971,9 +1382,8 @@ export class SequencerPublisher {
971
1382
  {
972
1383
  readonly header: ViemHeader;
973
1384
  readonly archive: `0x${string}`;
974
- readonly stateReference: ViemStateReference;
975
1385
  readonly oracleInput: {
976
- readonly feeAssetPriceModifier: 0n;
1386
+ readonly feeAssetPriceModifier: bigint;
977
1387
  };
978
1388
  },
979
1389
  ViemCommitteeAttestations,
@@ -982,7 +1392,7 @@ export class SequencerPublisher {
982
1392
  `0x${string}`,
983
1393
  ],
984
1394
  timestamp: bigint,
985
- options: { forcePendingBlockNumber?: number },
1395
+ options: { forcePendingCheckpointNumber?: CheckpointNumber },
986
1396
  ) {
987
1397
  const rollupData = encodeFunctionData({
988
1398
  abi: RollupAbi,
@@ -990,44 +1400,78 @@ export class SequencerPublisher {
990
1400
  args,
991
1401
  });
992
1402
 
993
- // override the pending block number if requested
994
- const forcePendingBlockNumberStateDiff = (
995
- options.forcePendingBlockNumber !== undefined
996
- ? await this.rollupContract.makePendingBlockNumberOverride(options.forcePendingBlockNumber)
1403
+ // override the pending checkpoint number if requested
1404
+ const forcePendingCheckpointNumberStateDiff = (
1405
+ options.forcePendingCheckpointNumber !== undefined
1406
+ ? await this.rollupContract.makePendingCheckpointNumberOverride(options.forcePendingCheckpointNumber)
997
1407
  : []
998
1408
  ).flatMap(override => override.stateDiff ?? []);
999
1409
 
1410
+ const stateOverrides: StateOverride = [
1411
+ {
1412
+ address: this.rollupContract.address,
1413
+ // @note we override checkBlob to false since blobs are not part simulate()
1414
+ stateDiff: [
1415
+ { slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true), value: toPaddedHex(0n, true) },
1416
+ ...forcePendingCheckpointNumberStateDiff,
1417
+ ],
1418
+ },
1419
+ ];
1420
+ // In fisherman mode, simulate as the proposer but with sufficient balance
1421
+ if (this.proposerAddressForSimulation) {
1422
+ stateOverrides.push({
1423
+ address: this.proposerAddressForSimulation.toString(),
1424
+ balance: 10n * WEI_CONST * WEI_CONST, // 10 ETH
1425
+ });
1426
+ }
1427
+
1428
+ const l1BlockNumber = await this.l1TxUtils.getBlockNumber();
1429
+
1000
1430
  const simulationResult = await this.l1TxUtils
1001
1431
  .simulate(
1002
1432
  {
1003
1433
  to: this.rollupContract.address,
1004
1434
  data: rollupData,
1005
- gas: SequencerPublisher.PROPOSE_GAS_GUESS,
1435
+ gas: MAX_L1_TX_LIMIT,
1436
+ ...(this.proposerAddressForSimulation && { from: this.proposerAddressForSimulation.toString() }),
1006
1437
  },
1007
1438
  {
1008
1439
  // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
1009
1440
  time: timestamp + 1n,
1010
1441
  // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
1011
- gasLimit: SequencerPublisher.PROPOSE_GAS_GUESS * 2n,
1442
+ gasLimit: MAX_L1_TX_LIMIT * 2n,
1012
1443
  },
1013
- [
1014
- {
1015
- address: this.rollupContract.address,
1016
- // @note we override checkBlob to false since blobs are not part simulate()
1017
- stateDiff: [
1018
- { slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true), value: toPaddedHex(0n, true) },
1019
- ...forcePendingBlockNumberStateDiff,
1020
- ],
1021
- },
1022
- ],
1444
+ stateOverrides,
1023
1445
  RollupAbi,
1024
1446
  {
1025
1447
  // @note fallback gas estimate to use if the node doesn't support simulation API
1026
- fallbackGasEstimate: SequencerPublisher.PROPOSE_GAS_GUESS,
1448
+ fallbackGasEstimate: MAX_L1_TX_LIMIT,
1027
1449
  },
1028
1450
  )
1029
1451
  .catch(err => {
1030
- this.log.error(`Failed to simulate propose tx`, err);
1452
+ // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1453
+ const viemError = formatViemError(err);
1454
+ if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1455
+ this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1456
+ // Return a minimal simulation result with the fallback gas estimate
1457
+ return {
1458
+ gasUsed: MAX_L1_TX_LIMIT,
1459
+ logs: [],
1460
+ };
1461
+ }
1462
+ this.log.error(`Failed to simulate propose tx`, viemError);
1463
+ this.backupFailedTx({
1464
+ id: keccak256(rollupData),
1465
+ failureType: 'simulation',
1466
+ request: { to: this.rollupContract.address, data: rollupData },
1467
+ l1BlockNumber: l1BlockNumber.toString(),
1468
+ error: { message: viemError.message, name: viemError.name },
1469
+ context: {
1470
+ actions: ['propose'],
1471
+ slot: Number(args[0].header.slotNumber),
1472
+ sender: this.getSenderAddress().toString(),
1473
+ },
1474
+ });
1031
1475
  throw err;
1032
1476
  });
1033
1477
 
@@ -1035,11 +1479,12 @@ export class SequencerPublisher {
1035
1479
  }
1036
1480
 
1037
1481
  private async addProposeTx(
1038
- block: L2Block,
1482
+ checkpoint: Checkpoint,
1039
1483
  encodedData: L1ProcessArgs,
1040
- opts: { txTimeoutAt?: Date; forcePendingBlockNumber?: number } = {},
1484
+ opts: { txTimeoutAt?: Date; forcePendingCheckpointNumber?: CheckpointNumber } = {},
1041
1485
  timestamp: bigint,
1042
1486
  ): Promise<void> {
1487
+ const slot = checkpoint.header.slotNumber;
1043
1488
  const timer = new Timer();
1044
1489
  const kzg = Blob.getViemKzgInstance();
1045
1490
  const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
@@ -1054,11 +1499,13 @@ export class SequencerPublisher {
1054
1499
  SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS, // We issue the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1055
1500
  );
1056
1501
 
1057
- // Send the blobs to the blob sink preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1058
- // tx fails but it does get mined. We make sure that the blobs are sent to the blob sink regardless of the tx outcome.
1059
- void this.blobSinkClient.sendBlobsToBlobSink(encodedData.blobs).catch(_err => {
1060
- this.log.error('Failed to send blobs to blob sink');
1061
- });
1502
+ // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1503
+ // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
1504
+ void Promise.resolve().then(() =>
1505
+ this.blobClient.sendBlobsToFilestore(encodedData.blobs).catch(_err => {
1506
+ this.log.error('Failed to send blobs to blob client');
1507
+ }),
1508
+ );
1062
1509
 
1063
1510
  return this.addRequest({
1064
1511
  action: 'propose',
@@ -1066,7 +1513,7 @@ export class SequencerPublisher {
1066
1513
  to: this.rollupContract.address,
1067
1514
  data: rollupData,
1068
1515
  },
1069
- lastValidL2Slot: block.header.globalVariables.slotNumber.toBigInt(),
1516
+ lastValidL2Slot: checkpoint.header.slotNumber,
1070
1517
  gasConfig: { ...opts, gasLimit },
1071
1518
  blobConfig: {
1072
1519
  blobs: encodedData.blobs.map(b => b.data),
@@ -1080,12 +1527,13 @@ export class SequencerPublisher {
1080
1527
  const success =
1081
1528
  receipt &&
1082
1529
  receipt.status === 'success' &&
1083
- tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'L2BlockProposed');
1530
+ tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1531
+
1084
1532
  if (success) {
1085
1533
  const endBlock = receipt.blockNumber;
1086
1534
  const inclusionBlocks = Number(endBlock - startBlock);
1087
1535
  const { calldataGas, calldataSize, sender } = stats!;
1088
- const publishStats: L1PublishBlockStats = {
1536
+ const publishStats: L1PublishCheckpointStats = {
1089
1537
  gasPrice: receipt.effectiveGasPrice,
1090
1538
  gasUsed: receipt.gasUsed,
1091
1539
  blobGasUsed: receipt.blobGasUsed ?? 0n,
@@ -1094,23 +1542,26 @@ export class SequencerPublisher {
1094
1542
  calldataGas,
1095
1543
  calldataSize,
1096
1544
  sender,
1097
- ...block.getStats(),
1545
+ ...checkpoint.getStats(),
1098
1546
  eventName: 'rollup-published-to-l1',
1099
1547
  blobCount: encodedData.blobs.length,
1100
1548
  inclusionBlocks,
1101
1549
  };
1102
- this.log.info(`Published L2 block to L1 rollup contract`, { ...stats, ...block.getStats(), ...receipt });
1550
+ this.log.info(`Published checkpoint ${checkpoint.number} at slot ${slot} to rollup contract`, {
1551
+ ...stats,
1552
+ ...checkpoint.getStats(),
1553
+ ...pick(receipt, 'transactionHash', 'blockHash'),
1554
+ });
1103
1555
  this.metrics.recordProcessBlockTx(timer.ms(), publishStats);
1104
1556
 
1105
1557
  return true;
1106
1558
  } else {
1107
1559
  this.metrics.recordFailedTx('process');
1108
- this.log.error(`Rollup process tx failed: ${errorMsg ?? 'no error message'}`, undefined, {
1109
- ...block.getStats(),
1110
- receipt,
1111
- txHash: receipt.transactionHash,
1112
- slotNumber: block.header.globalVariables.slotNumber.toBigInt(),
1113
- });
1560
+ this.log.error(
1561
+ `Publishing checkpoint at slot ${slot} failed with ${errorMsg ?? 'no error message'}`,
1562
+ undefined,
1563
+ { ...checkpoint.getStats(), ...receipt },
1564
+ );
1114
1565
  return false;
1115
1566
  }
1116
1567
  },