@aztec/sequencer-client 0.0.0-test.1 → 0.0.1-commit.03f7ef2

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 (141) hide show
  1. package/dest/client/index.d.ts +1 -1
  2. package/dest/client/sequencer-client.d.ts +30 -29
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +82 -60
  5. package/dest/config.d.ts +15 -16
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +113 -70
  8. package/dest/global_variable_builder/global_builder.d.ts +25 -14
  9. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  10. package/dest/global_variable_builder/global_builder.js +60 -42
  11. package/dest/global_variable_builder/index.d.ts +1 -1
  12. package/dest/index.d.ts +2 -3
  13. package/dest/index.d.ts.map +1 -1
  14. package/dest/index.js +1 -2
  15. package/dest/publisher/config.d.ts +15 -12
  16. package/dest/publisher/config.d.ts.map +1 -1
  17. package/dest/publisher/config.js +32 -19
  18. package/dest/publisher/index.d.ts +3 -1
  19. package/dest/publisher/index.d.ts.map +1 -1
  20. package/dest/publisher/index.js +3 -0
  21. package/dest/publisher/sequencer-publisher-factory.d.ts +44 -0
  22. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  23. package/dest/publisher/sequencer-publisher-factory.js +51 -0
  24. package/dest/publisher/sequencer-publisher-metrics.d.ts +5 -4
  25. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  26. package/dest/publisher/sequencer-publisher-metrics.js +37 -2
  27. package/dest/publisher/sequencer-publisher.d.ts +132 -86
  28. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  29. package/dest/publisher/sequencer-publisher.js +755 -248
  30. package/dest/sequencer/block_builder.d.ts +26 -0
  31. package/dest/sequencer/block_builder.d.ts.map +1 -0
  32. package/dest/sequencer/block_builder.js +129 -0
  33. package/dest/sequencer/checkpoint_builder.d.ts +63 -0
  34. package/dest/sequencer/checkpoint_builder.d.ts.map +1 -0
  35. package/dest/sequencer/checkpoint_builder.js +131 -0
  36. package/dest/sequencer/checkpoint_proposal_job.d.ts +74 -0
  37. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  38. package/dest/sequencer/checkpoint_proposal_job.js +640 -0
  39. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  40. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  41. package/dest/sequencer/checkpoint_voter.js +85 -0
  42. package/dest/sequencer/config.d.ts +7 -1
  43. package/dest/sequencer/config.d.ts.map +1 -1
  44. package/dest/sequencer/errors.d.ts +11 -0
  45. package/dest/sequencer/errors.d.ts.map +1 -0
  46. package/dest/sequencer/errors.js +15 -0
  47. package/dest/sequencer/events.d.ts +46 -0
  48. package/dest/sequencer/events.d.ts.map +1 -0
  49. package/dest/sequencer/events.js +1 -0
  50. package/dest/sequencer/index.d.ts +6 -2
  51. package/dest/sequencer/index.d.ts.map +1 -1
  52. package/dest/sequencer/index.js +5 -1
  53. package/dest/sequencer/metrics.d.ts +48 -12
  54. package/dest/sequencer/metrics.d.ts.map +1 -1
  55. package/dest/sequencer/metrics.js +274 -48
  56. package/dest/sequencer/sequencer.d.ts +132 -135
  57. package/dest/sequencer/sequencer.d.ts.map +1 -1
  58. package/dest/sequencer/sequencer.js +519 -521
  59. package/dest/sequencer/timetable.d.ts +76 -24
  60. package/dest/sequencer/timetable.d.ts.map +1 -1
  61. package/dest/sequencer/timetable.js +177 -61
  62. package/dest/sequencer/types.d.ts +3 -0
  63. package/dest/sequencer/types.d.ts.map +1 -0
  64. package/dest/sequencer/types.js +1 -0
  65. package/dest/sequencer/utils.d.ts +20 -38
  66. package/dest/sequencer/utils.d.ts.map +1 -1
  67. package/dest/sequencer/utils.js +12 -47
  68. package/dest/test/index.d.ts +10 -1
  69. package/dest/test/index.d.ts.map +1 -1
  70. package/dest/test/index.js +0 -4
  71. package/dest/test/mock_checkpoint_builder.d.ts +83 -0
  72. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  73. package/dest/test/mock_checkpoint_builder.js +179 -0
  74. package/dest/test/utils.d.ts +49 -0
  75. package/dest/test/utils.d.ts.map +1 -0
  76. package/dest/test/utils.js +94 -0
  77. package/dest/tx_validator/nullifier_cache.d.ts +1 -3
  78. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -1
  79. package/dest/tx_validator/tx_validator_factory.d.ts +11 -11
  80. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -1
  81. package/dest/tx_validator/tx_validator_factory.js +28 -25
  82. package/package.json +45 -45
  83. package/src/client/sequencer-client.ts +105 -105
  84. package/src/config.ts +126 -81
  85. package/src/global_variable_builder/global_builder.ts +82 -53
  86. package/src/index.ts +8 -2
  87. package/src/publisher/config.ts +45 -32
  88. package/src/publisher/index.ts +4 -0
  89. package/src/publisher/sequencer-publisher-factory.ts +92 -0
  90. package/src/publisher/sequencer-publisher-metrics.ts +26 -4
  91. package/src/publisher/sequencer-publisher.ts +955 -293
  92. package/src/sequencer/README.md +531 -0
  93. package/src/sequencer/block_builder.ts +217 -0
  94. package/src/sequencer/checkpoint_builder.ts +217 -0
  95. package/src/sequencer/checkpoint_proposal_job.ts +703 -0
  96. package/src/sequencer/checkpoint_voter.ts +105 -0
  97. package/src/sequencer/config.ts +8 -0
  98. package/src/sequencer/errors.ts +21 -0
  99. package/src/sequencer/events.ts +27 -0
  100. package/src/sequencer/index.ts +5 -1
  101. package/src/sequencer/metrics.ts +355 -50
  102. package/src/sequencer/sequencer.ts +631 -594
  103. package/src/sequencer/timetable.ts +221 -62
  104. package/src/sequencer/types.ts +6 -0
  105. package/src/sequencer/utils.ts +28 -60
  106. package/src/test/index.ts +13 -4
  107. package/src/test/mock_checkpoint_builder.ts +247 -0
  108. package/src/test/utils.ts +137 -0
  109. package/src/tx_validator/tx_validator_factory.ts +46 -33
  110. package/dest/sequencer/allowed.d.ts +0 -3
  111. package/dest/sequencer/allowed.d.ts.map +0 -1
  112. package/dest/sequencer/allowed.js +0 -27
  113. package/dest/slasher/factory.d.ts +0 -7
  114. package/dest/slasher/factory.d.ts.map +0 -1
  115. package/dest/slasher/factory.js +0 -8
  116. package/dest/slasher/index.d.ts +0 -3
  117. package/dest/slasher/index.d.ts.map +0 -1
  118. package/dest/slasher/index.js +0 -2
  119. package/dest/slasher/slasher_client.d.ts +0 -75
  120. package/dest/slasher/slasher_client.d.ts.map +0 -1
  121. package/dest/slasher/slasher_client.js +0 -132
  122. package/dest/tx_validator/archive_cache.d.ts +0 -14
  123. package/dest/tx_validator/archive_cache.d.ts.map +0 -1
  124. package/dest/tx_validator/archive_cache.js +0 -22
  125. package/dest/tx_validator/gas_validator.d.ts +0 -14
  126. package/dest/tx_validator/gas_validator.d.ts.map +0 -1
  127. package/dest/tx_validator/gas_validator.js +0 -78
  128. package/dest/tx_validator/phases_validator.d.ts +0 -12
  129. package/dest/tx_validator/phases_validator.d.ts.map +0 -1
  130. package/dest/tx_validator/phases_validator.js +0 -80
  131. package/dest/tx_validator/test_utils.d.ts +0 -23
  132. package/dest/tx_validator/test_utils.d.ts.map +0 -1
  133. package/dest/tx_validator/test_utils.js +0 -26
  134. package/src/sequencer/allowed.ts +0 -36
  135. package/src/slasher/factory.ts +0 -15
  136. package/src/slasher/index.ts +0 -2
  137. package/src/slasher/slasher_client.ts +0 -193
  138. package/src/tx_validator/archive_cache.ts +0 -28
  139. package/src/tx_validator/gas_validator.ts +0 -101
  140. package/src/tx_validator/phases_validator.ts +0 -98
  141. package/src/tx_validator/test_utils.ts +0 -48
@@ -1,36 +1,48 @@
1
- import type { L2Block } from '@aztec/aztec.js';
2
- import { Blob } from '@aztec/blob-lib';
3
- import { type BlobSinkClientInterface, createBlobSinkClient } from '@aztec/blob-sink/client';
1
+ import { type BlobClientInterface, createBlobClient } from '@aztec/blob-client/client';
2
+ import { Blob, getBlobsPerL1Block, getPrefixedEthBlobCommitments } from '@aztec/blob-lib';
4
3
  import type { EpochCache } from '@aztec/epoch-cache';
4
+ import type { L1ContractsConfig } from '@aztec/ethereum/config';
5
5
  import {
6
- FormattedViemError,
7
- type ForwarderContract,
8
- type GasPrice,
6
+ type EmpireSlashingProposerContract,
9
7
  type GovernanceProposerContract,
10
8
  type IEmpireBase,
9
+ MULTI_CALL_3_ADDRESS,
10
+ Multicall3,
11
+ RollupContract,
12
+ type TallySlashingProposerContract,
13
+ type ViemCommitteeAttestations,
14
+ type ViemHeader,
15
+ } from '@aztec/ethereum/contracts';
16
+ import { type L1FeeAnalysisResult, L1FeeAnalyzer } from '@aztec/ethereum/l1-fee-analysis';
17
+ import {
11
18
  type L1BlobInputs,
12
- type L1ContractsConfig,
13
- type L1GasConfig,
19
+ type L1TxConfig,
14
20
  type L1TxRequest,
15
- RollupContract,
16
- type SlashingProposerContract,
17
21
  type TransactionStats,
18
- formatViemError,
19
- } from '@aztec/ethereum';
22
+ WEI_CONST,
23
+ } from '@aztec/ethereum/l1-tx-utils';
20
24
  import type { L1TxUtilsWithBlobs } from '@aztec/ethereum/l1-tx-utils-with-blobs';
21
- import { toHex } from '@aztec/foundation/bigint-buffer';
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';
28
+ import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
29
+ import { pick } from '@aztec/foundation/collection';
30
+ import type { Fr } from '@aztec/foundation/curves/bn254';
22
31
  import { EthAddress } from '@aztec/foundation/eth-address';
23
- import type { Signature } from '@aztec/foundation/eth-signature';
24
- import { createLogger } from '@aztec/foundation/log';
25
- import { Timer } from '@aztec/foundation/timer';
26
- import { ForwarderAbi, RollupAbi } from '@aztec/l1-artifacts';
27
- import { ConsensusPayload, SignatureDomainSeparator, getHashedSignaturePayload } from '@aztec/stdlib/p2p';
28
- import type { L1PublishBlockStats } from '@aztec/stdlib/stats';
29
- import { type BlockHeader, TxHash } from '@aztec/stdlib/tx';
32
+ import { Signature, type ViemSignature } from '@aztec/foundation/eth-signature';
33
+ import { type Logger, createLogger } from '@aztec/foundation/log';
34
+ import { bufferToHex } from '@aztec/foundation/string';
35
+ import { DateProvider, Timer } from '@aztec/foundation/timer';
36
+ import { EmpireBaseAbi, ErrorsAbi, RollupAbi } from '@aztec/l1-artifacts';
37
+ import { type ProposerSlashAction, encodeSlashConsensusVotes } from '@aztec/slasher';
38
+ import { CommitteeAttestationsAndSigners, type ValidateBlockResult } from '@aztec/stdlib/block';
39
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
40
+ import { SlashFactoryContract } from '@aztec/stdlib/l1-contracts';
41
+ import type { CheckpointHeader } from '@aztec/stdlib/rollup';
42
+ import type { L1PublishCheckpointStats } from '@aztec/stdlib/stats';
30
43
  import { type TelemetryClient, getTelemetryClient } from '@aztec/telemetry-client';
31
44
 
32
- import pick from 'lodash.pick';
33
- import { type TransactionReceipt, encodeFunctionData } from 'viem';
45
+ import { type StateOverride, type TransactionReceipt, type TypedDataDefinition, encodeFunctionData, toHex } from 'viem';
34
46
 
35
47
  import type { PublisherConfig, TxSenderConfig } from './config.js';
36
48
  import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
@@ -38,131 +50,246 @@ import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
38
50
  /** Arguments to the process method of the rollup contract */
39
51
  type L1ProcessArgs = {
40
52
  /** The L2 block header. */
41
- header: Buffer;
53
+ header: CheckpointHeader;
42
54
  /** A root of the archive tree after the L2 block is applied. */
43
55
  archive: Buffer;
44
- /** The L2 block's leaf in the archive tree. */
45
- blockHash: Buffer;
46
56
  /** L2 block blobs containing all tx effects. */
47
57
  blobs: Blob[];
48
- /** L2 block tx hashes */
49
- txHashes: TxHash[];
50
58
  /** Attestations */
51
- attestations?: Signature[];
59
+ attestationsAndSigners: CommitteeAttestationsAndSigners;
60
+ /** Attestations and signers signature */
61
+ attestationsAndSignersSignature: Signature;
52
62
  };
53
63
 
54
- export enum VoteType {
55
- GOVERNANCE,
56
- SLASHING,
57
- }
64
+ export const Actions = [
65
+ 'invalidate-by-invalid-attestation',
66
+ 'invalidate-by-insufficient-attestations',
67
+ 'propose',
68
+ 'governance-signal',
69
+ 'empire-slashing-signal',
70
+ 'create-empire-payload',
71
+ 'execute-empire-payload',
72
+ 'vote-offenses',
73
+ 'execute-slash',
74
+ ] as const;
58
75
 
59
- type GetSlashPayloadCallBack = (slotNumber: bigint) => Promise<EthAddress | undefined>;
76
+ export type Action = (typeof Actions)[number];
77
+
78
+ type GovernanceSignalAction = Extract<Action, 'governance-signal' | 'empire-slashing-signal'>;
79
+
80
+ // Sorting for actions such that invalidations go before proposals, and proposals go before votes
81
+ export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
82
+
83
+ export type InvalidateBlockRequest = {
84
+ request: L1TxRequest;
85
+ reason: 'invalid-attestation' | 'insufficient-attestations';
86
+ gasUsed: bigint;
87
+ blockNumber: BlockNumber;
88
+ forcePendingBlockNumber: BlockNumber;
89
+ };
60
90
 
61
- type Action = 'propose' | 'governance-vote' | 'slashing-vote';
62
91
  interface RequestWithExpiry {
63
92
  action: Action;
64
93
  request: L1TxRequest;
65
- lastValidL2Slot: bigint;
66
- gasConfig?: L1GasConfig;
94
+ lastValidL2Slot: SlotNumber;
95
+ gasConfig?: Pick<L1TxConfig, 'txTimeoutAt' | 'gasLimit'>;
67
96
  blobConfig?: L1BlobInputs;
68
- onResult?: (
97
+ checkSuccess: (
69
98
  request: L1TxRequest,
70
- result?: { receipt: TransactionReceipt; gasPrice: GasPrice; stats?: TransactionStats; errorMsg?: string },
71
- ) => void;
99
+ result?: { receipt: TransactionReceipt; stats?: TransactionStats; errorMsg?: string },
100
+ ) => boolean;
72
101
  }
73
102
 
74
103
  export class SequencerPublisher {
75
104
  private interrupted = false;
76
105
  private metrics: SequencerPublisherMetrics;
77
- private epochCache: EpochCache;
78
- private forwarderContract: ForwarderContract;
106
+ public epochCache: EpochCache;
79
107
 
80
108
  protected governanceLog = createLogger('sequencer:publisher:governance');
81
- protected governanceProposerAddress?: EthAddress;
82
- private governancePayload: EthAddress = EthAddress.ZERO;
83
-
84
109
  protected slashingLog = createLogger('sequencer:publisher:slashing');
85
- protected slashingProposerAddress?: EthAddress;
86
- private getSlashPayload?: GetSlashPayloadCallBack = undefined;
87
110
 
88
- private myLastVotes: Record<VoteType, bigint> = {
89
- [VoteType.GOVERNANCE]: 0n,
90
- [VoteType.SLASHING]: 0n,
91
- };
111
+ protected lastActions: Partial<Record<Action, SlotNumber>> = {};
92
112
 
93
- protected log = createLogger('sequencer:publisher');
113
+ private isPayloadEmptyCache: Map<string, boolean> = new Map<string, boolean>();
114
+
115
+ protected log: Logger;
94
116
  protected ethereumSlotDuration: bigint;
95
117
 
96
- private blobSinkClient: BlobSinkClientInterface;
118
+ private blobClient: BlobClientInterface;
119
+
120
+ /** Address to use for simulations in fisherman mode (actual proposer's address) */
121
+ private proposerAddressForSimulation?: EthAddress;
122
+
123
+ /** L1 fee analyzer for fisherman mode */
124
+ private l1FeeAnalyzer?: L1FeeAnalyzer;
97
125
  // @note - with blobs, the below estimate seems too large.
98
126
  // Total used for full block from int_l1_pub e2e test: 1m (of which 86k is 1x blob)
99
127
  // Total used for emptier block from above test: 429k (of which 84k is 1x blob)
100
128
  public static PROPOSE_GAS_GUESS: bigint = 12_000_000n;
101
129
 
130
+ // A CALL to a cold address is 2700 gas
131
+ public static MULTICALL_OVERHEAD_GAS_GUESS = 5000n;
132
+
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;
135
+
102
136
  public l1TxUtils: L1TxUtilsWithBlobs;
103
137
  public rollupContract: RollupContract;
104
138
  public govProposerContract: GovernanceProposerContract;
105
- public slashingProposerContract: SlashingProposerContract;
139
+ public slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
140
+ public slashFactoryContract: SlashFactoryContract;
106
141
 
107
142
  protected requests: RequestWithExpiry[] = [];
108
143
 
109
144
  constructor(
110
- config: TxSenderConfig & PublisherConfig & Pick<L1ContractsConfig, 'ethereumSlotDuration'>,
145
+ private config: TxSenderConfig & PublisherConfig & Pick<L1ContractsConfig, 'ethereumSlotDuration'>,
111
146
  deps: {
112
147
  telemetry?: TelemetryClient;
113
- blobSinkClient?: BlobSinkClientInterface;
114
- forwarderContract: ForwarderContract;
148
+ blobClient?: BlobClientInterface;
115
149
  l1TxUtils: L1TxUtilsWithBlobs;
116
150
  rollupContract: RollupContract;
117
- slashingProposerContract: SlashingProposerContract;
151
+ slashingProposerContract: EmpireSlashingProposerContract | TallySlashingProposerContract | undefined;
118
152
  governanceProposerContract: GovernanceProposerContract;
153
+ slashFactoryContract: SlashFactoryContract;
119
154
  epochCache: EpochCache;
155
+ dateProvider: DateProvider;
156
+ metrics: SequencerPublisherMetrics;
157
+ lastActions: Partial<Record<Action, SlotNumber>>;
158
+ log?: Logger;
120
159
  },
121
160
  ) {
161
+ this.log = deps.log ?? createLogger('sequencer:publisher');
122
162
  this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
123
163
  this.epochCache = deps.epochCache;
164
+ this.lastActions = deps.lastActions;
124
165
 
125
- this.blobSinkClient = deps.blobSinkClient ?? createBlobSinkClient(config);
166
+ this.blobClient =
167
+ deps.blobClient ?? createBlobClient(config, { logger: createLogger('sequencer:blob-client:client') });
126
168
 
127
169
  const telemetry = deps.telemetry ?? getTelemetryClient();
128
- this.metrics = new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
170
+ this.metrics = deps.metrics ?? new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
129
171
  this.l1TxUtils = deps.l1TxUtils;
130
172
 
131
173
  this.rollupContract = deps.rollupContract;
132
- this.forwarderContract = deps.forwarderContract;
133
174
 
134
175
  this.govProposerContract = deps.governanceProposerContract;
135
176
  this.slashingProposerContract = deps.slashingProposerContract;
136
- }
137
177
 
138
- public registerSlashPayloadGetter(callback: GetSlashPayloadCallBack) {
139
- this.getSlashPayload = callback;
178
+ this.rollupContract.listenToSlasherChanged(async () => {
179
+ this.log.info('Slashing proposer changed');
180
+ const newSlashingProposer = await this.rollupContract.getSlashingProposer();
181
+ this.slashingProposerContract = newSlashingProposer;
182
+ });
183
+ this.slashFactoryContract = deps.slashFactoryContract;
184
+
185
+ // Initialize L1 fee analyzer for fisherman mode
186
+ if (config.fishermanMode) {
187
+ this.l1FeeAnalyzer = new L1FeeAnalyzer(
188
+ this.l1TxUtils.client,
189
+ deps.dateProvider,
190
+ createLogger('sequencer:publisher:fee-analyzer'),
191
+ );
192
+ }
140
193
  }
141
194
 
142
- public getForwarderAddress() {
143
- return EthAddress.fromString(this.forwarderContract.getAddress());
195
+ public getRollupContract(): RollupContract {
196
+ return this.rollupContract;
144
197
  }
145
198
 
146
199
  public getSenderAddress() {
147
- return EthAddress.fromString(this.l1TxUtils.getSenderAddress());
200
+ return this.l1TxUtils.getSenderAddress();
148
201
  }
149
202
 
150
- public getGovernancePayload() {
151
- return this.governancePayload;
203
+ /**
204
+ * Gets the L1 fee analyzer instance (only available in fisherman mode)
205
+ */
206
+ public getL1FeeAnalyzer(): L1FeeAnalyzer | undefined {
207
+ return this.l1FeeAnalyzer;
152
208
  }
153
209
 
154
- public setGovernancePayload(payload: EthAddress) {
155
- this.governancePayload = payload;
210
+ /**
211
+ * Sets the proposer address to use for simulations in fisherman mode.
212
+ * @param proposerAddress - The actual proposer's address to use for balance lookups in simulations
213
+ */
214
+ public setProposerAddressForSimulation(proposerAddress: EthAddress | undefined) {
215
+ this.proposerAddressForSimulation = proposerAddress;
156
216
  }
157
217
 
158
218
  public addRequest(request: RequestWithExpiry) {
159
219
  this.requests.push(request);
160
220
  }
161
221
 
162
- public getCurrentL2Slot(): bigint {
222
+ public getCurrentL2Slot(): SlotNumber {
163
223
  return this.epochCache.getEpochAndSlotNow().slot;
164
224
  }
165
225
 
226
+ /**
227
+ * Clears all pending requests without sending them.
228
+ */
229
+ public clearPendingRequests(): void {
230
+ const count = this.requests.length;
231
+ this.requests = [];
232
+ if (count > 0) {
233
+ this.log.debug(`Cleared ${count} pending request(s)`);
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Analyzes L1 fees for the pending requests without sending them.
239
+ * This is used in fisherman mode to validate fee calculations.
240
+ * @param l2SlotNumber - The L2 slot number for this analysis
241
+ * @param onComplete - Optional callback to invoke when analysis completes (after block is mined)
242
+ * @returns The analysis result (incomplete until block mines), or undefined if no requests
243
+ */
244
+ public async analyzeL1Fees(
245
+ l2SlotNumber: SlotNumber,
246
+ onComplete?: (analysis: L1FeeAnalysisResult) => void,
247
+ ): Promise<L1FeeAnalysisResult | undefined> {
248
+ if (!this.l1FeeAnalyzer) {
249
+ this.log.warn('L1 fee analyzer not available (not in fisherman mode)');
250
+ return undefined;
251
+ }
252
+
253
+ const requestsToAnalyze = [...this.requests];
254
+ if (requestsToAnalyze.length === 0) {
255
+ this.log.debug('No requests to analyze for L1 fees');
256
+ return undefined;
257
+ }
258
+
259
+ // Extract blob config from requests (if any)
260
+ const blobConfigs = requestsToAnalyze.filter(request => request.blobConfig).map(request => request.blobConfig);
261
+ const blobConfig = blobConfigs[0];
262
+
263
+ // Get gas configs
264
+ const gasConfigs = requestsToAnalyze.filter(request => request.gasConfig).map(request => request.gasConfig);
265
+ const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
266
+ const gasLimit = gasLimits.length > 0 ? gasLimits.reduce((sum, g) => sum + g, 0n) : 0n;
267
+
268
+ // Get the transaction requests
269
+ const l1Requests = requestsToAnalyze.map(r => r.request);
270
+
271
+ // Start the analysis
272
+ const analysisId = await this.l1FeeAnalyzer.startAnalysis(
273
+ l2SlotNumber,
274
+ gasLimit > 0n ? gasLimit : SequencerPublisher.PROPOSE_GAS_GUESS,
275
+ l1Requests,
276
+ blobConfig,
277
+ onComplete,
278
+ );
279
+
280
+ this.log.info('Started L1 fee analysis', {
281
+ analysisId,
282
+ l2SlotNumber: l2SlotNumber.toString(),
283
+ requestCount: requestsToAnalyze.length,
284
+ hasBlobConfig: !!blobConfig,
285
+ gasLimit: gasLimit.toString(),
286
+ actions: requestsToAnalyze.map(r => r.action),
287
+ });
288
+
289
+ // Return the analysis result (will be incomplete until block mines)
290
+ return this.l1FeeAnalyzer.getAnalysis(analysisId);
291
+ }
292
+
166
293
  /**
167
294
  * Sends all requests that are still valid.
168
295
  * @returns one of:
@@ -173,12 +300,16 @@ export class SequencerPublisher {
173
300
  public async sendRequests() {
174
301
  const requestsToProcess = [...this.requests];
175
302
  this.requests = [];
176
- if (this.interrupted) {
303
+ if (this.interrupted || requestsToProcess.length === 0) {
177
304
  return undefined;
178
305
  }
179
306
  const currentL2Slot = this.getCurrentL2Slot();
180
- this.log.debug(`Current L2 slot: ${currentL2Slot}`);
307
+ this.log.debug(`Sending requests on L2 slot ${currentL2Slot}`);
181
308
  const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
309
+ const validActions = validRequests.map(x => x.action);
310
+ const expiredActions = requestsToProcess
311
+ .filter(request => request.lastValidL2Slot < currentL2Slot)
312
+ .map(x => x.action);
182
313
 
183
314
  if (validRequests.length !== requestsToProcess.length) {
184
315
  this.log.warn(`Some requests were expired for slot ${currentL2Slot}`, {
@@ -198,39 +329,54 @@ export class SequencerPublisher {
198
329
  return undefined;
199
330
  }
200
331
 
201
- // @note - we can only have one gas config and one blob config per bundle
332
+ // @note - we can only have one blob config per bundle
202
333
  // find requests with gas and blob configs
203
334
  // See https://github.com/AztecProtocol/aztec-packages/issues/11513
204
- const gasConfigs = requestsToProcess.filter(request => request.gasConfig);
205
- const blobConfigs = requestsToProcess.filter(request => request.blobConfig);
335
+ const gasConfigs = requestsToProcess.filter(request => request.gasConfig).map(request => request.gasConfig);
336
+ const blobConfigs = requestsToProcess.filter(request => request.blobConfig).map(request => request.blobConfig);
206
337
 
207
- if (gasConfigs.length > 1 || blobConfigs.length > 1) {
208
- throw new Error('Multiple gas or blob configs found');
338
+ if (blobConfigs.length > 1) {
339
+ throw new Error('Multiple blob configs found');
209
340
  }
210
341
 
211
- const gasConfig = gasConfigs[0]?.gasConfig;
212
- const blobConfig = blobConfigs[0]?.blobConfig;
342
+ const blobConfig = blobConfigs[0];
343
+
344
+ // Merge gasConfigs. Yields the sum of gasLimits, and the earliest txTimeoutAt, or undefined if no gasConfig sets them.
345
+ const gasLimits = gasConfigs.map(g => g?.gasLimit).filter((g): g is bigint => g !== undefined);
346
+ const gasLimit = gasLimits.length > 0 ? sumBigint(gasLimits) : undefined; // sum
347
+ const txTimeoutAts = gasConfigs.map(g => g?.txTimeoutAt).filter((g): g is Date => g !== undefined);
348
+ const txTimeoutAt = txTimeoutAts.length > 0 ? new Date(Math.min(...txTimeoutAts.map(g => g.getTime()))) : undefined; // earliest
349
+ const txConfig: RequestWithExpiry['gasConfig'] = { gasLimit, txTimeoutAt };
350
+
351
+ // Sort the requests so that proposals always go first
352
+ // This ensures the committee gets precomputed correctly
353
+ validRequests.sort((a, b) => compareActions(a.action, b.action));
213
354
 
214
355
  try {
215
356
  this.log.debug('Forwarding transactions', {
216
357
  validRequests: validRequests.map(request => request.action),
358
+ txConfig,
217
359
  });
218
- const result = await this.forwarderContract.forward(
360
+ const result = await Multicall3.forward(
219
361
  validRequests.map(request => request.request),
220
362
  this.l1TxUtils,
221
- gasConfig,
363
+ txConfig,
222
364
  blobConfig,
365
+ this.rollupContract.address,
223
366
  this.log,
224
367
  );
225
- this.callbackBundledTransactions(validRequests, result);
226
- return result;
368
+ const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(validRequests, result);
369
+ return { result, expiredActions, sentActions: validActions, successfulActions, failedActions };
227
370
  } catch (err) {
228
371
  const viemError = formatViemError(err);
229
372
  this.log.error(`Failed to publish bundled transactions`, viemError);
230
373
  return undefined;
231
374
  } finally {
232
375
  try {
233
- this.metrics.recordSenderBalance(await this.l1TxUtils.getSenderBalance(), this.l1TxUtils.getSenderAddress());
376
+ this.metrics.recordSenderBalance(
377
+ await this.l1TxUtils.getSenderBalance(),
378
+ this.l1TxUtils.getSenderAddress().toString(),
379
+ );
234
380
  } catch (err) {
235
381
  this.log.warn(`Failed to record balance after sending tx: ${err}`);
236
382
  }
@@ -239,13 +385,24 @@ export class SequencerPublisher {
239
385
 
240
386
  private callbackBundledTransactions(
241
387
  requests: RequestWithExpiry[],
242
- result?: { receipt: TransactionReceipt; gasPrice: GasPrice },
388
+ result?: { receipt: TransactionReceipt } | FormattedViemError,
243
389
  ) {
244
- const success = result?.receipt.status === 'success';
245
- const logger = success ? this.log.info : this.log.error;
246
- for (const request of requests) {
247
- logger(`Bundled [${request.action}] transaction [${success ? 'succeeded' : 'failed'}]`);
248
- request.onResult?.(request.request, result);
390
+ const actionsListStr = requests.map(r => r.action).join(', ');
391
+ if (result instanceof FormattedViemError) {
392
+ this.log.error(`Failed to publish bundled transactions (${actionsListStr})`, result);
393
+ return { failedActions: requests.map(r => r.action) };
394
+ } else {
395
+ this.log.verbose(`Published bundled transactions (${actionsListStr})`, { result, requests });
396
+ const successfulActions: Action[] = [];
397
+ const failedActions: Action[] = [];
398
+ for (const request of requests) {
399
+ if (request.checkSuccess(request.request, result)) {
400
+ successfulActions.push(request.action);
401
+ } else {
402
+ failedActions.push(request.action);
403
+ }
404
+ }
405
+ return { successfulActions, failedActions };
249
406
  }
250
407
  }
251
408
 
@@ -254,176 +411,610 @@ export class SequencerPublisher {
254
411
  * @param tipArchive - The archive to check
255
412
  * @returns The slot and block number if it is possible to propose, undefined otherwise
256
413
  */
257
- public canProposeAtNextEthBlock(tipArchive: Buffer) {
414
+ public canProposeAtNextEthBlock(
415
+ tipArchive: Fr,
416
+ msgSender: EthAddress,
417
+ opts: { forcePendingBlockNumber?: BlockNumber } = {},
418
+ ) {
419
+ // TODO: #14291 - should loop through multiple keys to check if any of them can propose
258
420
  const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer', 'InvalidArchive'];
421
+
259
422
  return this.rollupContract
260
- .canProposeAtNextEthBlock(tipArchive, this.getForwarderAddress().toString(), this.ethereumSlotDuration)
423
+ .canProposeAtNextEthBlock(tipArchive.toBuffer(), msgSender.toString(), Number(this.ethereumSlotDuration), {
424
+ forcePendingCheckpointNumber:
425
+ opts.forcePendingBlockNumber !== undefined
426
+ ? CheckpointNumber.fromBlockNumber(opts.forcePendingBlockNumber)
427
+ : undefined,
428
+ })
261
429
  .catch(err => {
262
430
  if (err instanceof FormattedViemError && ignoredErrors.find(e => err.message.includes(e))) {
263
- this.log.debug(err.message);
431
+ this.log.warn(`Failed canProposeAtTime check with ${ignoredErrors.find(e => err.message.includes(e))}`, {
432
+ error: err.message,
433
+ });
264
434
  } else {
265
435
  this.log.error(err.name, err);
266
436
  }
267
437
  return undefined;
268
438
  });
269
439
  }
440
+ /**
441
+ * @notice Will simulate `validateHeader` to make sure that the block header is valid
442
+ * @dev This is a convenience function that can be used by the sequencer to validate a "partial" header.
443
+ * It will throw if the block header is invalid.
444
+ * @param header - The block header to validate
445
+ */
446
+ public async validateBlockHeader(
447
+ header: CheckpointHeader,
448
+ opts?: { forcePendingBlockNumber: BlockNumber | undefined },
449
+ ) {
450
+ const flags = { ignoreDA: true, ignoreSignatures: true };
451
+
452
+ const args = [
453
+ header.toViem(),
454
+ CommitteeAttestationsAndSigners.empty().getPackedAttestations(),
455
+ [], // no signers
456
+ Signature.empty().toViemSignature(),
457
+ `0x${'0'.repeat(64)}`, // 32 empty bytes
458
+ header.contentCommitment.blobsHash.toString(),
459
+ flags,
460
+ ] as const;
461
+
462
+ const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
463
+ const optsForcePendingCheckpointNumber =
464
+ opts?.forcePendingBlockNumber !== undefined
465
+ ? CheckpointNumber.fromBlockNumber(opts.forcePendingBlockNumber)
466
+ : undefined;
467
+ const stateOverrides = await this.rollupContract.makePendingCheckpointNumberOverride(
468
+ optsForcePendingCheckpointNumber,
469
+ );
470
+ let balance = 0n;
471
+ if (this.config.fishermanMode) {
472
+ // In fisherman mode, we can't know where the proposer is publishing from
473
+ // so we just add sufficient balance to the multicall3 address
474
+ balance = 10n * WEI_CONST * WEI_CONST; // 10 ETH
475
+ } else {
476
+ balance = await this.l1TxUtils.getSenderBalance();
477
+ }
478
+ stateOverrides.push({
479
+ address: MULTI_CALL_3_ADDRESS,
480
+ balance,
481
+ });
482
+
483
+ await this.l1TxUtils.simulate(
484
+ {
485
+ to: this.rollupContract.address,
486
+ data: encodeFunctionData({ abi: RollupAbi, functionName: 'validateHeaderWithAttestations', args }),
487
+ from: MULTI_CALL_3_ADDRESS,
488
+ },
489
+ { time: ts + 1n },
490
+ stateOverrides,
491
+ );
492
+ this.log.debug(`Simulated validateHeader`);
493
+ }
270
494
 
271
495
  /**
272
- * @notice Will call `validateHeader` to make sure that it is possible to propose
273
- *
274
- * @dev Throws if unable to propose
275
- *
276
- * @param header - The header to propose
277
- * @param digest - The digest that attestations are signing over
278
- *
496
+ * Simulate making a call to invalidate a block with invalid attestations. Returns undefined if no need to invalidate.
497
+ * @param block - The block to invalidate and the criteria for invalidation (as returned by the archiver)
279
498
  */
280
- public async validateBlockForSubmission(
281
- header: BlockHeader,
282
- attestationData: { digest: Buffer; signatures: Signature[] } = {
283
- digest: Buffer.alloc(32),
284
- signatures: [],
285
- },
499
+ public async simulateInvalidateBlock(
500
+ validationResult: ValidateBlockResult,
501
+ ): Promise<InvalidateBlockRequest | undefined> {
502
+ if (validationResult.valid) {
503
+ return undefined;
504
+ }
505
+
506
+ const { reason, block } = validationResult;
507
+ const blockNumber = block.blockNumber;
508
+ const logData = { ...block, reason };
509
+
510
+ const currentBlockNumber = await this.rollupContract.getCheckpointNumber();
511
+ if (currentBlockNumber < validationResult.block.blockNumber) {
512
+ this.log.verbose(
513
+ `Skipping block ${blockNumber} invalidation since it has already been removed from the pending chain`,
514
+ { currentBlockNumber, ...logData },
515
+ );
516
+ return undefined;
517
+ }
518
+
519
+ const request = this.buildInvalidateBlockRequest(validationResult);
520
+ this.log.debug(`Simulating invalidate block ${blockNumber}`, { ...logData, request });
521
+
522
+ try {
523
+ const { gasUsed } = await this.l1TxUtils.simulate(request, undefined, undefined, ErrorsAbi);
524
+ this.log.verbose(`Simulation for invalidate block ${blockNumber} succeeded`, { ...logData, request, gasUsed });
525
+
526
+ return { request, gasUsed, blockNumber, forcePendingBlockNumber: BlockNumber(blockNumber - 1), reason };
527
+ } catch (err) {
528
+ const viemError = formatViemError(err);
529
+
530
+ // If the error is due to the block not being in the pending chain, and it was indeed removed by someone else,
531
+ // we can safely ignore it and return undefined so we go ahead with block building.
532
+ if (viemError.message?.includes('Rollup__BlockNotInPendingChain')) {
533
+ this.log.verbose(
534
+ `Simulation for invalidate block ${blockNumber} failed due to block not being in pending chain`,
535
+ { ...logData, request, error: viemError.message },
536
+ );
537
+ const latestPendingBlockNumber = await this.rollupContract.getCheckpointNumber();
538
+ if (latestPendingBlockNumber < blockNumber) {
539
+ this.log.verbose(`Block number ${blockNumber} has already been invalidated`, { ...logData });
540
+ return undefined;
541
+ } else {
542
+ this.log.error(
543
+ `Simulation for invalidate ${blockNumber} failed and it is still in pending chain`,
544
+ viemError,
545
+ logData,
546
+ );
547
+ throw new Error(`Failed to simulate invalidate block ${blockNumber} while it is still in pending chain`, {
548
+ cause: viemError,
549
+ });
550
+ }
551
+ }
552
+
553
+ // Otherwise, throw. We cannot build the next block if we cannot invalidate the previous one.
554
+ this.log.error(`Simulation for invalidate block ${blockNumber} failed`, viemError, logData);
555
+ throw new Error(`Failed to simulate invalidate block ${blockNumber}`, { cause: viemError });
556
+ }
557
+ }
558
+
559
+ private buildInvalidateBlockRequest(validationResult: ValidateBlockResult) {
560
+ if (validationResult.valid) {
561
+ throw new Error('Cannot invalidate a valid block');
562
+ }
563
+
564
+ const { block, committee, reason } = validationResult;
565
+ const logData = { ...block, reason };
566
+ this.log.debug(`Simulating invalidate block ${block.blockNumber}`, logData);
567
+
568
+ const attestationsAndSigners = new CommitteeAttestationsAndSigners(
569
+ validationResult.attestations,
570
+ ).getPackedAttestations();
571
+
572
+ if (reason === 'invalid-attestation') {
573
+ return this.rollupContract.buildInvalidateBadAttestationRequest(
574
+ CheckpointNumber.fromBlockNumber(block.blockNumber),
575
+ attestationsAndSigners,
576
+ committee,
577
+ validationResult.invalidIndex,
578
+ );
579
+ } else if (reason === 'insufficient-attestations') {
580
+ return this.rollupContract.buildInvalidateInsufficientAttestationsRequest(
581
+ CheckpointNumber.fromBlockNumber(block.blockNumber),
582
+ attestationsAndSigners,
583
+ committee,
584
+ );
585
+ } else {
586
+ const _: never = reason;
587
+ throw new Error(`Unknown reason for invalidation`);
588
+ }
589
+ }
590
+
591
+ /** Simulates `propose` to make sure that the checkpoint is valid for submission */
592
+ public async validateCheckpointForSubmission(
593
+ checkpoint: Checkpoint,
594
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
595
+ attestationsAndSignersSignature: Signature,
596
+ options: { forcePendingBlockNumber?: BlockNumber }, // TODO(palla/mbps): Should this be forcePendingCheckpointNumber?
286
597
  ): Promise<bigint> {
287
598
  const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
288
599
 
289
- const formattedSignatures = attestationData.signatures.map(attest => attest.toViemSignature());
290
- const flags = { ignoreDA: true, ignoreSignatures: formattedSignatures.length == 0 };
600
+ // TODO(palla/mbps): This should not be needed, there's no flow where we propose with zero attestations. Or is there?
601
+ // If we have no attestations, we still need to provide the empty attestations
602
+ // so that the committee is recalculated correctly
603
+ // const ignoreSignatures = attestationsAndSigners.attestations.length === 0;
604
+ // if (ignoreSignatures) {
605
+ // const { committee } = await this.epochCache.getCommittee(block.header.globalVariables.slotNumber);
606
+ // if (!committee) {
607
+ // this.log.warn(`No committee found for slot ${block.header.globalVariables.slotNumber}`);
608
+ // throw new Error(`No committee found for slot ${block.header.globalVariables.slotNumber}`);
609
+ // }
610
+ // attestationsAndSigners.attestations = committee.map(committeeMember =>
611
+ // CommitteeAttestation.fromAddress(committeeMember),
612
+ // );
613
+ // }
614
+
615
+ const blobFields = checkpoint.toBlobFields();
616
+ const blobs = getBlobsPerL1Block(blobFields);
617
+ const blobInput = getPrefixedEthBlobCommitments(blobs);
291
618
 
292
619
  const args = [
293
- `0x${header.toBuffer().toString('hex')}`,
294
- formattedSignatures,
295
- `0x${attestationData.digest.toString('hex')}`,
296
- ts,
297
- `0x${header.contentCommitment.blobsHash.toString('hex')}`,
298
- flags,
620
+ {
621
+ header: checkpoint.header.toViem(),
622
+ archive: toHex(checkpoint.archive.root.toBuffer()),
623
+ oracleInput: {
624
+ feeAssetPriceModifier: 0n,
625
+ },
626
+ },
627
+ attestationsAndSigners.getPackedAttestations(),
628
+ attestationsAndSigners.getSigners().map(signer => signer.toString()),
629
+ attestationsAndSignersSignature.toViemSignature(),
630
+ blobInput,
299
631
  ] as const;
300
632
 
301
- await this.rollupContract.validateHeader(args, this.getForwarderAddress().toString());
633
+ await this.simulateProposeTx(args, ts, options);
302
634
  return ts;
303
635
  }
304
636
 
305
- public async getCurrentEpochCommittee(): Promise<EthAddress[]> {
306
- const committee = await this.rollupContract.getCurrentEpochCommittee();
307
- return committee.map(EthAddress.fromString);
308
- }
309
-
310
- private async enqueueCastVoteHelper(
311
- slotNumber: bigint,
637
+ private async enqueueCastSignalHelper(
638
+ slotNumber: SlotNumber,
312
639
  timestamp: bigint,
313
- voteType: VoteType,
640
+ signalType: GovernanceSignalAction,
314
641
  payload: EthAddress,
315
642
  base: IEmpireBase,
643
+ signerAddress: EthAddress,
644
+ signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
316
645
  ): Promise<boolean> {
317
- if (this.myLastVotes[voteType] >= slotNumber) {
646
+ if (this.lastActions[signalType] && this.lastActions[signalType] === slotNumber) {
647
+ this.log.debug(`Skipping duplicate vote cast signal ${signalType} for slot ${slotNumber}`);
318
648
  return false;
319
649
  }
320
650
  if (payload.equals(EthAddress.ZERO)) {
321
651
  return false;
322
652
  }
653
+ if (signerAddress.equals(EthAddress.ZERO)) {
654
+ this.log.warn(`Cannot enqueue vote cast signal ${signalType} for address zero at slot ${slotNumber}`);
655
+ return false;
656
+ }
323
657
  const round = await base.computeRound(slotNumber);
324
- const [proposer, roundInfo] = await Promise.all([
325
- this.rollupContract.getProposerAt(timestamp),
326
- base.getRoundInfo(this.rollupContract.address, round),
327
- ]);
658
+ const roundInfo = await base.getRoundInfo(this.rollupContract.address, round);
328
659
 
329
- if (proposer.toLowerCase() !== this.getForwarderAddress().toString().toLowerCase()) {
660
+ if (roundInfo.quorumReached) {
330
661
  return false;
331
662
  }
332
- if (roundInfo.lastVote >= slotNumber) {
663
+
664
+ if (roundInfo.lastSignalSlot >= slotNumber) {
333
665
  return false;
334
666
  }
335
667
 
336
- const cachedLastVote = this.myLastVotes[voteType];
337
- this.myLastVotes[voteType] = slotNumber;
668
+ if (await this.isPayloadEmpty(payload)) {
669
+ this.log.warn(`Skipping vote cast for payload with empty code`);
670
+ return false;
671
+ }
338
672
 
673
+ const cachedLastVote = this.lastActions[signalType];
674
+ this.lastActions[signalType] = slotNumber;
675
+ const action = signalType;
676
+
677
+ const request = await base.createSignalRequestWithSignature(
678
+ payload.toString(),
679
+ slotNumber,
680
+ this.config.l1ChainId,
681
+ signerAddress.toString(),
682
+ signer,
683
+ );
684
+ this.log.debug(`Created ${action} request with signature`, {
685
+ request,
686
+ round,
687
+ signer: this.l1TxUtils.client.account?.address,
688
+ lastValidL2Slot: slotNumber,
689
+ });
690
+
691
+ try {
692
+ await this.l1TxUtils.simulate(request, { time: timestamp }, [], ErrorsAbi);
693
+ this.log.debug(`Simulation for ${action} at slot ${slotNumber} succeeded`, { request });
694
+ } catch (err) {
695
+ this.log.error(`Failed simulation for ${action} at slot ${slotNumber} (enqueuing the action anyway)`, err);
696
+ // Yes, we enqueue the request anyway, in case there was a bug with the simulation itself
697
+ }
698
+
699
+ // TODO(palla/slash): All votes (governance and slashing) should txTimeoutAt at the end of the slot.
339
700
  this.addRequest({
340
- action: voteType === VoteType.GOVERNANCE ? 'governance-vote' : 'slashing-vote',
341
- request: base.createVoteRequest(payload.toString()),
701
+ gasConfig: { gasLimit: SequencerPublisher.VOTE_GAS_GUESS },
702
+ action,
703
+ request,
342
704
  lastValidL2Slot: slotNumber,
343
- onResult: (_request, result) => {
344
- if (!result || result.receipt.status !== 'success') {
345
- this.myLastVotes[voteType] = cachedLastVote;
705
+ checkSuccess: (_request, result) => {
706
+ const success =
707
+ result &&
708
+ result.receipt &&
709
+ result.receipt.status === 'success' &&
710
+ tryExtractEvent(result.receipt.logs, base.address.toString(), EmpireBaseAbi, 'SignalCast');
711
+
712
+ const logData = { ...result, slotNumber, round, payload: payload.toString() };
713
+ if (!success) {
714
+ this.log.error(
715
+ `Signaling in ${action} for ${payload} at slot ${slotNumber} in round ${round} failed`,
716
+ logData,
717
+ );
718
+ this.lastActions[signalType] = cachedLastVote;
719
+ return false;
346
720
  } else {
347
- this.log.info(`Cast [${voteType}] vote for slot ${slotNumber}`);
721
+ this.log.info(
722
+ `Signaling in ${action} for ${payload} at slot ${slotNumber} in round ${round} succeeded`,
723
+ logData,
724
+ );
725
+ return true;
348
726
  }
349
727
  },
350
728
  });
351
729
  return true;
352
730
  }
353
731
 
354
- private async getVoteConfig(
355
- slotNumber: bigint,
356
- voteType: VoteType,
357
- ): Promise<{ payload: EthAddress; base: IEmpireBase } | undefined> {
358
- if (voteType === VoteType.GOVERNANCE) {
359
- return { payload: this.governancePayload, base: this.govProposerContract };
360
- } else if (voteType === VoteType.SLASHING) {
361
- if (!this.getSlashPayload) {
362
- return undefined;
363
- }
364
- const slashPayload = await this.getSlashPayload(slotNumber);
365
- if (!slashPayload) {
366
- return undefined;
367
- }
368
- return { payload: slashPayload, base: this.slashingProposerContract };
732
+ private async isPayloadEmpty(payload: EthAddress): Promise<boolean> {
733
+ const key = payload.toString();
734
+ const cached = this.isPayloadEmptyCache.get(key);
735
+ if (cached) {
736
+ return cached;
369
737
  }
370
- throw new Error('Unreachable: Invalid vote type');
738
+ const isEmpty = !(await this.l1TxUtils.getCode(payload));
739
+ this.isPayloadEmptyCache.set(key, isEmpty);
740
+ return isEmpty;
371
741
  }
372
742
 
373
743
  /**
374
- * Enqueues a castVote transaction to cast a vote for a given slot number.
375
- * @param slotNumber - The slot number to cast a vote for.
376
- * @param timestamp - The timestamp of the slot to cast a vote for.
377
- * @param voteType - The type of vote to cast.
378
- * @returns True if the vote was successfully enqueued, false otherwise.
744
+ * Enqueues a governance castSignal transaction to cast a signal for a given slot number.
745
+ * @param slotNumber - The slot number to cast a signal for.
746
+ * @param timestamp - The timestamp of the slot to cast a signal for.
747
+ * @returns True if the signal was successfully enqueued, false otherwise.
379
748
  */
380
- public async enqueueCastVote(slotNumber: bigint, timestamp: bigint, voteType: VoteType): Promise<boolean> {
381
- const voteConfig = await this.getVoteConfig(slotNumber, voteType);
382
- if (!voteConfig) {
749
+ public enqueueGovernanceCastSignal(
750
+ governancePayload: EthAddress,
751
+ slotNumber: SlotNumber,
752
+ timestamp: bigint,
753
+ signerAddress: EthAddress,
754
+ signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
755
+ ): Promise<boolean> {
756
+ return this.enqueueCastSignalHelper(
757
+ slotNumber,
758
+ timestamp,
759
+ 'governance-signal',
760
+ governancePayload,
761
+ this.govProposerContract,
762
+ signerAddress,
763
+ signer,
764
+ );
765
+ }
766
+
767
+ /** Enqueues all slashing actions as returned by the slasher client. */
768
+ public async enqueueSlashingActions(
769
+ actions: ProposerSlashAction[],
770
+ slotNumber: SlotNumber,
771
+ timestamp: bigint,
772
+ signerAddress: EthAddress,
773
+ signer: (msg: TypedDataDefinition) => Promise<`0x${string}`>,
774
+ ): Promise<boolean> {
775
+ if (actions.length === 0) {
776
+ this.log.debug(`No slashing actions to enqueue for slot ${slotNumber}`);
383
777
  return false;
384
778
  }
385
- const { payload, base } = voteConfig;
386
- return this.enqueueCastVoteHelper(slotNumber, timestamp, voteType, payload, base);
779
+
780
+ for (const action of actions) {
781
+ switch (action.type) {
782
+ case 'vote-empire-payload': {
783
+ if (this.slashingProposerContract?.type !== 'empire') {
784
+ this.log.error('Cannot vote for empire payload on non-empire slashing contract');
785
+ break;
786
+ }
787
+ this.log.debug(`Enqueuing slashing vote for payload ${action.payload} at slot ${slotNumber}`, {
788
+ signerAddress,
789
+ });
790
+ await this.enqueueCastSignalHelper(
791
+ slotNumber,
792
+ timestamp,
793
+ 'empire-slashing-signal',
794
+ action.payload,
795
+ this.slashingProposerContract,
796
+ signerAddress,
797
+ signer,
798
+ );
799
+ break;
800
+ }
801
+
802
+ case 'create-empire-payload': {
803
+ this.log.debug(`Enqueuing slashing create payload at slot ${slotNumber}`, { slotNumber, signerAddress });
804
+ const request = this.slashFactoryContract.buildCreatePayloadRequest(action.data);
805
+ await this.simulateAndEnqueueRequest(
806
+ 'create-empire-payload',
807
+ request,
808
+ (receipt: TransactionReceipt) =>
809
+ !!this.slashFactoryContract.tryExtractSlashPayloadCreatedEvent(receipt.logs),
810
+ slotNumber,
811
+ timestamp,
812
+ );
813
+ break;
814
+ }
815
+
816
+ case 'execute-empire-payload': {
817
+ this.log.debug(`Enqueuing slashing execute payload at slot ${slotNumber}`, { slotNumber, signerAddress });
818
+ if (this.slashingProposerContract?.type !== 'empire') {
819
+ this.log.error('Cannot execute slashing payload on non-empire slashing contract');
820
+ return false;
821
+ }
822
+ const empireSlashingProposer = this.slashingProposerContract as EmpireSlashingProposerContract;
823
+ const request = empireSlashingProposer.buildExecuteRoundRequest(action.round);
824
+ await this.simulateAndEnqueueRequest(
825
+ 'execute-empire-payload',
826
+ request,
827
+ (receipt: TransactionReceipt) => !!empireSlashingProposer.tryExtractPayloadSubmittedEvent(receipt.logs),
828
+ slotNumber,
829
+ timestamp,
830
+ );
831
+ break;
832
+ }
833
+
834
+ case 'vote-offenses': {
835
+ this.log.debug(`Enqueuing slashing vote for ${action.votes.length} votes at slot ${slotNumber}`, {
836
+ slotNumber,
837
+ round: action.round,
838
+ votesCount: action.votes.length,
839
+ signerAddress,
840
+ });
841
+ if (this.slashingProposerContract?.type !== 'tally') {
842
+ this.log.error('Cannot vote for slashing offenses on non-tally slashing contract');
843
+ return false;
844
+ }
845
+ const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
846
+ const votes = bufferToHex(encodeSlashConsensusVotes(action.votes));
847
+ const request = await tallySlashingProposer.buildVoteRequestFromSigner(votes, slotNumber, signer);
848
+ await this.simulateAndEnqueueRequest(
849
+ 'vote-offenses',
850
+ request,
851
+ (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractVoteCastEvent(receipt.logs),
852
+ slotNumber,
853
+ timestamp,
854
+ );
855
+ break;
856
+ }
857
+
858
+ case 'execute-slash': {
859
+ this.log.debug(`Enqueuing slash execution for round ${action.round} at slot ${slotNumber}`, {
860
+ slotNumber,
861
+ round: action.round,
862
+ signerAddress,
863
+ });
864
+ if (this.slashingProposerContract?.type !== 'tally') {
865
+ this.log.error('Cannot execute slashing offenses on non-tally slashing contract');
866
+ return false;
867
+ }
868
+ const tallySlashingProposer = this.slashingProposerContract as TallySlashingProposerContract;
869
+ const request = tallySlashingProposer.buildExecuteRoundRequest(action.round, action.committees);
870
+ await this.simulateAndEnqueueRequest(
871
+ 'execute-slash',
872
+ request,
873
+ (receipt: TransactionReceipt) => !!tallySlashingProposer.tryExtractRoundExecutedEvent(receipt.logs),
874
+ slotNumber,
875
+ timestamp,
876
+ );
877
+ break;
878
+ }
879
+
880
+ default: {
881
+ const _: never = action;
882
+ throw new Error(`Unknown slashing action type: ${(action as ProposerSlashAction).type}`);
883
+ }
884
+ }
885
+ }
886
+
887
+ return true;
387
888
  }
388
889
 
389
- /**
390
- * Proposes a L2 block on L1.
391
- *
392
- * @param block - L2 block to propose.
393
- * @returns True if the tx has been enqueued, throws otherwise. See #9315
394
- */
395
- public async enqueueProposeL2Block(
396
- block: L2Block,
397
- attestations?: Signature[],
398
- txHashes?: TxHash[],
399
- opts: { txTimeoutAt?: Date } = {},
400
- ): Promise<boolean> {
401
- const consensusPayload = new ConsensusPayload(block.header, block.archive.root, txHashes ?? []);
890
+ /** Simulates and enqueues a proposal for a checkpoint on L1 */
891
+ public async enqueueProposeCheckpoint(
892
+ checkpoint: Checkpoint,
893
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
894
+ attestationsAndSignersSignature: Signature,
895
+ opts: { txTimeoutAt?: Date; forcePendingBlockNumber?: BlockNumber } = {},
896
+ ): Promise<void> {
897
+ const checkpointHeader = checkpoint.header;
402
898
 
403
- const digest = await getHashedSignaturePayload(consensusPayload, SignatureDomainSeparator.blockAttestation);
899
+ const blobFields = checkpoint.toBlobFields();
900
+ const blobs = getBlobsPerL1Block(blobFields);
404
901
 
405
- const blobs = await Blob.getBlobs(block.body.toBlobFields());
406
902
  const proposeTxArgs = {
407
- header: block.header.toBuffer(),
408
- archive: block.archive.root.toBuffer(),
409
- blockHash: (await block.header.hash()).toBuffer(),
410
- body: block.body.toBuffer(),
903
+ header: checkpointHeader,
904
+ archive: checkpoint.archive.root.toBuffer(),
411
905
  blobs,
412
- attestations,
413
- txHashes: txHashes ?? [],
906
+ attestationsAndSigners,
907
+ attestationsAndSignersSignature,
414
908
  };
415
909
 
416
- // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
417
- // This means that we can avoid the simulation issues in later checks.
418
- // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
419
- // make time consistency checks break.
420
- const ts = await this.validateBlockForSubmission(block.header, {
421
- digest: digest.toBuffer(),
422
- signatures: attestations ?? [],
910
+ let ts: bigint;
911
+
912
+ try {
913
+ // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
914
+ // This means that we can avoid the simulation issues in later checks.
915
+ // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
916
+ // make time consistency checks break.
917
+ // TODO(palla): Check whether we're validating twice, once here and once within addProposeTx, since we call simulateProposeTx in both places.
918
+ ts = await this.validateCheckpointForSubmission(
919
+ checkpoint,
920
+ attestationsAndSigners,
921
+ attestationsAndSignersSignature,
922
+ opts,
923
+ );
924
+ } catch (err: any) {
925
+ this.log.error(`Checkpoint validation failed. ${err instanceof Error ? err.message : 'No error message'}`, err, {
926
+ ...checkpoint.getStats(),
927
+ slotNumber: checkpoint.header.slotNumber,
928
+ forcePendingBlockNumber: opts.forcePendingBlockNumber,
929
+ });
930
+ throw err;
931
+ }
932
+
933
+ this.log.verbose(`Enqueuing checkpoint propose transaction`, { ...checkpoint.toCheckpointInfo(), ...opts });
934
+ await this.addProposeTx(checkpoint, proposeTxArgs, opts, ts);
935
+ }
936
+
937
+ public enqueueInvalidateBlock(request: InvalidateBlockRequest | undefined, opts: { txTimeoutAt?: Date } = {}) {
938
+ if (!request) {
939
+ return;
940
+ }
941
+
942
+ // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
943
+ const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(request.gasUsed) * 64) / 63)));
944
+
945
+ const { gasUsed, blockNumber } = request;
946
+ const logData = { gasUsed, blockNumber, gasLimit, opts };
947
+ this.log.verbose(`Enqueuing invalidate block request`, logData);
948
+ this.addRequest({
949
+ action: `invalidate-by-${request.reason}`,
950
+ request: request.request,
951
+ gasConfig: { gasLimit, txTimeoutAt: opts.txTimeoutAt },
952
+ lastValidL2Slot: SlotNumber(this.getCurrentL2Slot() + 2),
953
+ checkSuccess: (_req, result) => {
954
+ const success =
955
+ result &&
956
+ result.receipt &&
957
+ result.receipt.status === 'success' &&
958
+ tryExtractEvent(result.receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointInvalidated');
959
+ if (!success) {
960
+ this.log.warn(`Invalidate block ${request.blockNumber} failed`, { ...result, ...logData });
961
+ } else {
962
+ this.log.info(`Invalidate block ${request.blockNumber} succeeded`, { ...result, ...logData });
963
+ }
964
+ return !!success;
965
+ },
423
966
  });
967
+ }
968
+
969
+ private async simulateAndEnqueueRequest(
970
+ action: Action,
971
+ request: L1TxRequest,
972
+ checkSuccess: (receipt: TransactionReceipt) => boolean | undefined,
973
+ slotNumber: SlotNumber,
974
+ timestamp: bigint,
975
+ ) {
976
+ const logData = { slotNumber, timestamp, gasLimit: undefined as bigint | undefined };
977
+ if (this.lastActions[action] && this.lastActions[action] === slotNumber) {
978
+ this.log.debug(`Skipping duplicate action ${action} for slot ${slotNumber}`);
979
+ return false;
980
+ }
981
+
982
+ const cachedLastActionSlot = this.lastActions[action];
983
+ this.lastActions[action] = slotNumber;
984
+
985
+ this.log.debug(`Simulating ${action} for slot ${slotNumber}`, logData);
986
+
987
+ let gasUsed: bigint;
988
+ try {
989
+ ({ gasUsed } = await this.l1TxUtils.simulate(request, { time: timestamp }, [], ErrorsAbi)); // TODO(palla/slash): Check the timestamp logic
990
+ this.log.verbose(`Simulation for ${action} succeeded`, { ...logData, request, gasUsed });
991
+ } catch (err) {
992
+ const viemError = formatViemError(err);
993
+ this.log.error(`Simulation for ${action} at ${slotNumber} failed`, viemError, logData);
994
+ return false;
995
+ }
424
996
 
425
- this.log.debug(`Submitting propose transaction`);
426
- await this.addProposeTx(block, proposeTxArgs, opts, ts);
997
+ // We issued the simulation against the rollup contract, so we need to account for the overhead of the multicall3
998
+ const gasLimit = this.l1TxUtils.bumpGasLimit(BigInt(Math.ceil((Number(gasUsed) * 64) / 63)));
999
+ logData.gasLimit = gasLimit;
1000
+
1001
+ this.log.debug(`Enqueuing ${action}`, logData);
1002
+ this.addRequest({
1003
+ action,
1004
+ request,
1005
+ gasConfig: { gasLimit },
1006
+ lastValidL2Slot: slotNumber,
1007
+ checkSuccess: (_req, result) => {
1008
+ const success = result && result.receipt && result.receipt.status === 'success' && checkSuccess(result.receipt);
1009
+ if (!success) {
1010
+ this.log.warn(`Action ${action} at ${slotNumber} failed`, { ...result, ...logData });
1011
+ this.lastActions[action] = cachedLastActionSlot;
1012
+ } else {
1013
+ this.log.info(`Action ${action} at ${slotNumber} succeeded`, { ...result, ...logData });
1014
+ }
1015
+ return !!success;
1016
+ },
1017
+ });
427
1018
  return true;
428
1019
  }
429
1020
 
@@ -444,114 +1035,194 @@ export class SequencerPublisher {
444
1035
  this.l1TxUtils.restart();
445
1036
  }
446
1037
 
447
- private async prepareProposeTx(encodedData: L1ProcessArgs, timestamp: bigint) {
1038
+ private async prepareProposeTx(
1039
+ encodedData: L1ProcessArgs,
1040
+ timestamp: bigint,
1041
+ options: { forcePendingBlockNumber?: BlockNumber },
1042
+ ) {
448
1043
  const kzg = Blob.getViemKzgInstance();
449
- const blobInput = Blob.getEthBlobEvaluationInputs(encodedData.blobs);
1044
+ const blobInput = getPrefixedEthBlobCommitments(encodedData.blobs);
450
1045
  this.log.debug('Validating blob input', { blobInput });
451
- const blobEvaluationGas = await this.l1TxUtils
452
- .estimateGas(
453
- this.l1TxUtils.walletClient.account,
454
- {
455
- to: this.rollupContract.address,
456
- data: encodeFunctionData({
457
- abi: RollupAbi,
458
- functionName: 'validateBlobs',
459
- args: [blobInput],
460
- }),
461
- },
462
- {},
463
- {
464
- blobs: encodedData.blobs.map(b => b.data),
465
- kzg,
466
- },
467
- )
468
- .catch(err => {
469
- const { message, metaMessages } = formatViemError(err);
470
- this.log.error(`Failed to validate blobs`, message, { metaMessages });
471
- throw new Error('Failed to validate blobs');
472
- });
473
1046
 
474
- const attestations = encodedData.attestations
475
- ? encodedData.attestations.map(attest => attest.toViemSignature())
476
- : [];
477
- const txHashes = encodedData.txHashes ? encodedData.txHashes.map(txHash => txHash.toString()) : [];
1047
+ // Get blob evaluation gas
1048
+ let blobEvaluationGas: bigint;
1049
+ if (this.config.fishermanMode) {
1050
+ // In fisherman mode, we can't estimate blob gas because estimateGas doesn't support state overrides
1051
+ // Use a fixed estimate.
1052
+ blobEvaluationGas = BigInt(encodedData.blobs.length) * 21_000n;
1053
+ this.log.debug(`Using fixed blob evaluation gas estimate in fisherman mode: ${blobEvaluationGas}`);
1054
+ } else {
1055
+ // Normal mode - use estimateGas with blob inputs
1056
+ blobEvaluationGas = await this.l1TxUtils
1057
+ .estimateGas(
1058
+ this.getSenderAddress().toString(),
1059
+ {
1060
+ to: this.rollupContract.address,
1061
+ data: encodeFunctionData({
1062
+ abi: RollupAbi,
1063
+ functionName: 'validateBlobs',
1064
+ args: [blobInput],
1065
+ }),
1066
+ },
1067
+ {},
1068
+ {
1069
+ blobs: encodedData.blobs.map(b => b.data),
1070
+ kzg,
1071
+ },
1072
+ )
1073
+ .catch(err => {
1074
+ const { message, metaMessages } = formatViemError(err);
1075
+ this.log.error(`Failed to validate blobs`, message, { metaMessages });
1076
+ throw new Error('Failed to validate blobs');
1077
+ });
1078
+ }
1079
+ const signers = encodedData.attestationsAndSigners.getSigners().map(signer => signer.toString());
1080
+
478
1081
  const args = [
479
1082
  {
480
- header: `0x${encodedData.header.toString('hex')}`,
481
- archive: `0x${encodedData.archive.toString('hex')}`,
1083
+ header: encodedData.header.toViem(),
1084
+ archive: toHex(encodedData.archive),
482
1085
  oracleInput: {
483
1086
  // We are currently not modifying these. See #9963
484
1087
  feeAssetPriceModifier: 0n,
485
1088
  },
486
- blockHash: `0x${encodedData.blockHash.toString('hex')}`,
487
- txHashes,
488
1089
  },
489
- attestations,
1090
+ encodedData.attestationsAndSigners.getPackedAttestations(),
1091
+ signers,
1092
+ encodedData.attestationsAndSignersSignature.toViemSignature(),
490
1093
  blobInput,
491
1094
  ] as const;
492
1095
 
1096
+ const { rollupData, simulationResult } = await this.simulateProposeTx(args, timestamp, options);
1097
+
1098
+ return { args, blobEvaluationGas, rollupData, simulationResult };
1099
+ }
1100
+
1101
+ /**
1102
+ * Simulates the propose tx with eth_simulateV1
1103
+ * @param args - The propose tx args
1104
+ * @param timestamp - The timestamp to simulate proposal at
1105
+ * @returns The simulation result
1106
+ */
1107
+ private async simulateProposeTx(
1108
+ args: readonly [
1109
+ {
1110
+ readonly header: ViemHeader;
1111
+ readonly archive: `0x${string}`;
1112
+ readonly oracleInput: {
1113
+ readonly feeAssetPriceModifier: 0n;
1114
+ };
1115
+ },
1116
+ ViemCommitteeAttestations,
1117
+ `0x${string}`[], // Signers
1118
+ ViemSignature,
1119
+ `0x${string}`,
1120
+ ],
1121
+ timestamp: bigint,
1122
+ options: { forcePendingBlockNumber?: BlockNumber },
1123
+ ) {
493
1124
  const rollupData = encodeFunctionData({
494
1125
  abi: RollupAbi,
495
1126
  functionName: 'propose',
496
1127
  args,
497
1128
  });
498
1129
 
499
- const forwarderData = encodeFunctionData({
500
- abi: ForwarderAbi,
501
- functionName: 'forward',
502
- args: [[this.rollupContract.address], [rollupData]],
503
- });
1130
+ // override the pending checkpoint number if requested
1131
+ const optsForcePendingCheckpointNumber =
1132
+ options.forcePendingBlockNumber !== undefined
1133
+ ? CheckpointNumber.fromBlockNumber(options.forcePendingBlockNumber)
1134
+ : undefined;
1135
+ const forcePendingCheckpointNumberStateDiff = (
1136
+ optsForcePendingCheckpointNumber !== undefined
1137
+ ? await this.rollupContract.makePendingCheckpointNumberOverride(optsForcePendingCheckpointNumber)
1138
+ : []
1139
+ ).flatMap(override => override.stateDiff ?? []);
1140
+
1141
+ const stateOverrides: StateOverride = [
1142
+ {
1143
+ address: this.rollupContract.address,
1144
+ // @note we override checkBlob to false since blobs are not part simulate()
1145
+ stateDiff: [
1146
+ { slot: toPaddedHex(RollupContract.checkBlobStorageSlot, true), value: toPaddedHex(0n, true) },
1147
+ ...forcePendingCheckpointNumberStateDiff,
1148
+ ],
1149
+ },
1150
+ ];
1151
+ // In fisherman mode, simulate as the proposer but with sufficient balance
1152
+ if (this.proposerAddressForSimulation) {
1153
+ stateOverrides.push({
1154
+ address: this.proposerAddressForSimulation.toString(),
1155
+ balance: 10n * WEI_CONST * WEI_CONST, // 10 ETH
1156
+ });
1157
+ }
504
1158
 
505
1159
  const simulationResult = await this.l1TxUtils
506
- .simulateGasUsed(
1160
+ .simulate(
507
1161
  {
508
- to: this.getForwarderAddress().toString(),
509
- data: forwarderData,
1162
+ to: this.rollupContract.address,
1163
+ data: rollupData,
510
1164
  gas: SequencerPublisher.PROPOSE_GAS_GUESS,
1165
+ ...(this.proposerAddressForSimulation && { from: this.proposerAddressForSimulation.toString() }),
511
1166
  },
512
1167
  {
513
1168
  // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
514
1169
  time: timestamp + 1n,
515
- // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit
1170
+ // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit so we increase here
516
1171
  gasLimit: SequencerPublisher.PROPOSE_GAS_GUESS * 2n,
517
1172
  },
518
- [
519
- {
520
- address: this.rollupContract.address,
521
- // @note we override checkBlob to false since blobs are not part simulate()
522
- stateDiff: [
523
- {
524
- slot: toHex(RollupContract.checkBlobStorageSlot, true),
525
- value: toHex(0n, true),
526
- },
527
- ],
528
- },
529
- ],
1173
+ stateOverrides,
1174
+ RollupAbi,
530
1175
  {
531
1176
  // @note fallback gas estimate to use if the node doesn't support simulation API
532
1177
  fallbackGasEstimate: SequencerPublisher.PROPOSE_GAS_GUESS,
533
1178
  },
534
1179
  )
535
1180
  .catch(err => {
536
- const { message, metaMessages } = formatViemError(err);
537
- this.log.error(`Failed to simulate gas used`, message, { metaMessages });
538
- throw new Error('Failed to simulate gas used');
1181
+ // In fisherman mode, we expect ValidatorSelection__MissingProposerSignature since fisherman doesn't have proposer signature
1182
+ const viemError = formatViemError(err);
1183
+ if (this.config.fishermanMode && viemError.message?.includes('ValidatorSelection__MissingProposerSignature')) {
1184
+ this.log.debug(`Ignoring expected ValidatorSelection__MissingProposerSignature error in fisherman mode`);
1185
+ // Return a minimal simulation result with the fallback gas estimate
1186
+ return {
1187
+ gasUsed: SequencerPublisher.PROPOSE_GAS_GUESS,
1188
+ logs: [],
1189
+ };
1190
+ }
1191
+ this.log.error(`Failed to simulate propose tx`, viemError);
1192
+ throw err;
539
1193
  });
540
1194
 
541
- return { args, blobEvaluationGas, rollupData, simulationResult };
1195
+ return { rollupData, simulationResult };
542
1196
  }
543
1197
 
544
1198
  private async addProposeTx(
545
- block: L2Block,
1199
+ checkpoint: Checkpoint,
546
1200
  encodedData: L1ProcessArgs,
547
- opts: { txTimeoutAt?: Date } = {},
1201
+ opts: { txTimeoutAt?: Date; forcePendingBlockNumber?: BlockNumber } = {},
548
1202
  timestamp: bigint,
549
1203
  ): Promise<void> {
1204
+ const slot = checkpoint.header.slotNumber;
550
1205
  const timer = new Timer();
551
1206
  const kzg = Blob.getViemKzgInstance();
552
- const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, timestamp);
1207
+ const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(
1208
+ encodedData,
1209
+ timestamp,
1210
+ opts,
1211
+ );
553
1212
  const startBlock = await this.l1TxUtils.getBlockNumber();
554
- const blockHash = await block.hash();
1213
+ const gasLimit = this.l1TxUtils.bumpGasLimit(
1214
+ BigInt(Math.ceil((Number(simulationResult.gasUsed) * 64) / 63)) +
1215
+ blobEvaluationGas +
1216
+ SequencerPublisher.MULTICALL_OVERHEAD_GAS_GUESS, // We issue the simulation against the rollup contract, so we need to account for the overhead of the multicall3
1217
+ );
1218
+
1219
+ // Send the blobs to the blob client preemptively. This helps in tests where the sequencer mistakingly thinks that the propose
1220
+ // tx fails but it does get mined. We make sure that the blobs are sent to the blob client regardless of the tx outcome.
1221
+ void Promise.resolve().then(() =>
1222
+ this.blobClient.sendBlobsToFilestore(encodedData.blobs).catch(_err => {
1223
+ this.log.error('Failed to send blobs to blob client');
1224
+ }),
1225
+ );
555
1226
 
556
1227
  return this.addRequest({
557
1228
  action: 'propose',
@@ -559,67 +1230,58 @@ export class SequencerPublisher {
559
1230
  to: this.rollupContract.address,
560
1231
  data: rollupData,
561
1232
  },
562
- lastValidL2Slot: block.header.globalVariables.slotNumber.toBigInt(),
563
- gasConfig: {
564
- ...opts,
565
- gasLimit: this.l1TxUtils.bumpGasLimit(simulationResult + blobEvaluationGas),
566
- },
1233
+ lastValidL2Slot: checkpoint.header.slotNumber,
1234
+ gasConfig: { ...opts, gasLimit },
567
1235
  blobConfig: {
568
1236
  blobs: encodedData.blobs.map(b => b.data),
569
1237
  kzg,
570
1238
  },
571
- onResult: (request, result) => {
1239
+ checkSuccess: (_request, result) => {
572
1240
  if (!result) {
573
- return;
1241
+ return false;
574
1242
  }
575
1243
  const { receipt, stats, errorMsg } = result;
576
- if (receipt.status === 'success') {
1244
+ const success =
1245
+ receipt &&
1246
+ receipt.status === 'success' &&
1247
+ tryExtractEvent(receipt.logs, this.rollupContract.address, RollupAbi, 'CheckpointProposed');
1248
+
1249
+ if (success) {
577
1250
  const endBlock = receipt.blockNumber;
578
1251
  const inclusionBlocks = Number(endBlock - startBlock);
579
- const publishStats: L1PublishBlockStats = {
1252
+ const { calldataGas, calldataSize, sender } = stats!;
1253
+ const publishStats: L1PublishCheckpointStats = {
580
1254
  gasPrice: receipt.effectiveGasPrice,
581
1255
  gasUsed: receipt.gasUsed,
582
1256
  blobGasUsed: receipt.blobGasUsed ?? 0n,
583
1257
  blobDataGas: receipt.blobGasPrice ?? 0n,
584
1258
  transactionHash: receipt.transactionHash,
585
- ...pick(stats!, 'calldataGas', 'calldataSize', 'sender'),
586
- ...block.getStats(),
1259
+ calldataGas,
1260
+ calldataSize,
1261
+ sender,
1262
+ ...checkpoint.getStats(),
587
1263
  eventName: 'rollup-published-to-l1',
588
1264
  blobCount: encodedData.blobs.length,
589
1265
  inclusionBlocks,
590
1266
  };
591
- this.log.verbose(`Published L2 block to L1 rollup contract`, { ...stats, ...block.getStats() });
592
- this.metrics.recordProcessBlockTx(timer.ms(), publishStats);
593
-
594
- // Send the blobs to the blob sink
595
- this.sendBlobsToBlobSink(receipt.blockHash, encodedData.blobs).catch(_err => {
596
- this.log.error('Failed to send blobs to blob sink');
1267
+ this.log.info(`Published checkpoint ${checkpoint.number} at slot ${slot} to rollup contract`, {
1268
+ ...stats,
1269
+ ...checkpoint.getStats(),
1270
+ ...pick(receipt, 'transactionHash', 'blockHash'),
597
1271
  });
1272
+ this.metrics.recordProcessBlockTx(timer.ms(), publishStats);
598
1273
 
599
1274
  return true;
600
1275
  } else {
601
1276
  this.metrics.recordFailedTx('process');
602
-
603
- this.log.error(`Rollup process tx reverted. ${errorMsg ?? 'No error message'}`, undefined, {
604
- ...block.getStats(),
605
- txHash: receipt.transactionHash,
606
- blockHash,
607
- slotNumber: block.header.globalVariables.slotNumber.toBigInt(),
608
- });
1277
+ this.log.error(
1278
+ `Publishing checkpoint at slot ${slot} failed with ${errorMsg ?? 'no error message'}`,
1279
+ undefined,
1280
+ { ...checkpoint.getStats(), ...receipt },
1281
+ );
1282
+ return false;
609
1283
  }
610
1284
  },
611
1285
  });
612
1286
  }
613
-
614
- /**
615
- * Send blobs to the blob sink
616
- *
617
- * If a blob sink url is configured, then we send blobs to the blob sink
618
- * - for now we use the blockHash as the identifier for the blobs;
619
- * In the future this will move to be the beacon block id - which takes a bit more work
620
- * to calculate and will need to be mocked in e2e tests
621
- */
622
- protected sendBlobsToBlobSink(blockHash: string, blobs: Blob[]): Promise<boolean> {
623
- return this.blobSinkClient.sendBlobsToBlobSink(blockHash, blobs);
624
- }
625
1287
  }