@aztec/sequencer-client 0.0.1-commit.24de95ac → 0.0.1-commit.2606882

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