@aztec/sequencer-client 0.0.1-commit.96bb3f7 → 0.0.1-commit.993d240

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