@aztec/sequencer-client 0.0.1-commit.b655e406 → 0.0.1-commit.b8a057fa

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