@aztec/sequencer-client 0.71.0 → 0.73.0

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 (66) hide show
  1. package/dest/client/sequencer-client.d.ts +11 -6
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +41 -10
  4. package/dest/config.d.ts +1 -1
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +3 -4
  7. package/dest/publisher/config.d.ts +5 -0
  8. package/dest/publisher/config.d.ts.map +1 -1
  9. package/dest/publisher/config.js +9 -2
  10. package/dest/publisher/index.d.ts +1 -1
  11. package/dest/publisher/index.d.ts.map +1 -1
  12. package/dest/publisher/index.js +2 -2
  13. package/dest/publisher/{l1-publisher-metrics.d.ts → sequencer-publisher-metrics.d.ts} +6 -2
  14. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -0
  15. package/dest/publisher/sequencer-publisher-metrics.js +111 -0
  16. package/dest/publisher/sequencer-publisher.d.ts +158 -0
  17. package/dest/publisher/sequencer-publisher.d.ts.map +1 -0
  18. package/dest/publisher/sequencer-publisher.js +555 -0
  19. package/dest/sequencer/allowed.d.ts +1 -1
  20. package/dest/sequencer/allowed.d.ts.map +1 -1
  21. package/dest/sequencer/allowed.js +6 -6
  22. package/dest/sequencer/metrics.d.ts +1 -1
  23. package/dest/sequencer/metrics.d.ts.map +1 -1
  24. package/dest/sequencer/metrics.js +3 -4
  25. package/dest/sequencer/sequencer.d.ts +18 -12
  26. package/dest/sequencer/sequencer.d.ts.map +1 -1
  27. package/dest/sequencer/sequencer.js +118 -125
  28. package/dest/sequencer/utils.d.ts +1 -1
  29. package/dest/sequencer/utils.d.ts.map +1 -1
  30. package/dest/sequencer/utils.js +3 -3
  31. package/dest/slasher/slasher_client.d.ts.map +1 -1
  32. package/dest/slasher/slasher_client.js +6 -3
  33. package/dest/test/index.d.ts +3 -3
  34. package/dest/test/index.d.ts.map +1 -1
  35. package/dest/test/index.js +1 -2
  36. package/dest/tx_validator/gas_validator.d.ts +1 -1
  37. package/dest/tx_validator/gas_validator.d.ts.map +1 -1
  38. package/dest/tx_validator/gas_validator.js +10 -5
  39. package/dest/tx_validator/test_utils.d.ts +4 -4
  40. package/dest/tx_validator/test_utils.d.ts.map +1 -1
  41. package/dest/tx_validator/test_utils.js +3 -3
  42. package/package.json +22 -21
  43. package/src/client/sequencer-client.ts +60 -14
  44. package/src/config.ts +3 -3
  45. package/src/publisher/config.ts +13 -1
  46. package/src/publisher/index.ts +1 -1
  47. package/src/publisher/{l1-publisher-metrics.ts → sequencer-publisher-metrics.ts} +41 -2
  48. package/src/publisher/sequencer-publisher.ts +730 -0
  49. package/src/sequencer/allowed.ts +5 -5
  50. package/src/sequencer/metrics.ts +2 -3
  51. package/src/sequencer/sequencer.ts +153 -150
  52. package/src/sequencer/utils.ts +5 -2
  53. package/src/slasher/slasher_client.ts +7 -2
  54. package/src/test/index.ts +2 -4
  55. package/src/tx_validator/gas_validator.ts +17 -4
  56. package/src/tx_validator/test_utils.ts +5 -5
  57. package/dest/publisher/l1-publisher-metrics.d.ts.map +0 -1
  58. package/dest/publisher/l1-publisher-metrics.js +0 -85
  59. package/dest/publisher/l1-publisher.d.ts +0 -195
  60. package/dest/publisher/l1-publisher.d.ts.map +0 -1
  61. package/dest/publisher/l1-publisher.js +0 -864
  62. package/dest/test/test-l1-publisher.d.ts +0 -9
  63. package/dest/test/test-l1-publisher.d.ts.map +0 -1
  64. package/dest/test/test-l1-publisher.js +0 -11
  65. package/src/publisher/l1-publisher.ts +0 -1208
  66. package/src/test/test-l1-publisher.ts +0 -20
@@ -0,0 +1,730 @@
1
+ import { type BlobSinkClientInterface, createBlobSinkClient } from '@aztec/blob-sink/client';
2
+ import {
3
+ ConsensusPayload,
4
+ type EpochProofQuote,
5
+ type L2Block,
6
+ SignatureDomainSeparator,
7
+ type TxHash,
8
+ getHashedSignaturePayload,
9
+ } from '@aztec/circuit-types';
10
+ import type { L1PublishBlockStats, L1PublishStats } from '@aztec/circuit-types/stats';
11
+ import { type BlockHeader, EthAddress } from '@aztec/circuits.js';
12
+ import { type EpochCache } from '@aztec/epoch-cache';
13
+ import {
14
+ FormattedViemError,
15
+ type ForwarderContract,
16
+ type GasPrice,
17
+ type L1BlobInputs,
18
+ type L1ContractsConfig,
19
+ type L1GasConfig,
20
+ type L1TxRequest,
21
+ type L1TxUtilsWithBlobs,
22
+ type RollupContract,
23
+ type TransactionStats,
24
+ formatViemError,
25
+ } from '@aztec/ethereum';
26
+ import { toHex } from '@aztec/foundation/bigint-buffer';
27
+ import { Blob } from '@aztec/foundation/blob';
28
+ import { type Signature } from '@aztec/foundation/eth-signature';
29
+ import { type Logger, createLogger } from '@aztec/foundation/log';
30
+ import { Timer } from '@aztec/foundation/timer';
31
+ import { EmpireBaseAbi, ForwarderAbi, RollupAbi } from '@aztec/l1-artifacts';
32
+ import { type TelemetryClient, getTelemetryClient } from '@aztec/telemetry-client';
33
+
34
+ import pick from 'lodash.pick';
35
+ import { type TransactionReceipt, encodeFunctionData, getAddress, getContract } from 'viem';
36
+
37
+ import { type PublisherConfig, type TxSenderConfig } from './config.js';
38
+ import { SequencerPublisherMetrics } from './sequencer-publisher-metrics.js';
39
+
40
+ /** Arguments to the process method of the rollup contract */
41
+ type L1ProcessArgs = {
42
+ /** The L2 block header. */
43
+ header: Buffer;
44
+ /** A root of the archive tree after the L2 block is applied. */
45
+ archive: Buffer;
46
+ /** The L2 block's leaf in the archive tree. */
47
+ blockHash: Buffer;
48
+ /** L2 block body. TODO(#9101): Remove block body once we can extract blobs. */
49
+ body: Buffer;
50
+ /** L2 block blobs containing all tx effects. */
51
+ blobs: Blob[];
52
+ /** L2 block tx hashes */
53
+ txHashes: TxHash[];
54
+ /** Attestations */
55
+ attestations?: Signature[];
56
+ };
57
+
58
+ export enum VoteType {
59
+ GOVERNANCE,
60
+ SLASHING,
61
+ }
62
+
63
+ type GetSlashPayloadCallBack = (slotNumber: bigint) => Promise<EthAddress | undefined>;
64
+
65
+ type Action = 'propose' | 'claim' | 'governance-vote' | 'slashing-vote';
66
+ interface RequestWithExpiry {
67
+ action: Action;
68
+ request: L1TxRequest;
69
+ lastValidL2Slot: bigint;
70
+ gasConfig?: L1GasConfig;
71
+ blobConfig?: L1BlobInputs;
72
+ onResult?: (
73
+ request: L1TxRequest,
74
+ result?: { receipt: TransactionReceipt; gasPrice: GasPrice; stats?: TransactionStats; errorMsg?: string },
75
+ ) => void;
76
+ }
77
+
78
+ export class SequencerPublisher {
79
+ private interrupted = false;
80
+ private metrics: SequencerPublisherMetrics;
81
+ private epochCache: EpochCache;
82
+ private forwarderContract: ForwarderContract;
83
+
84
+ protected governanceLog = createLogger('sequencer:publisher:governance');
85
+ protected governanceProposerAddress?: EthAddress;
86
+ private governancePayload: EthAddress = EthAddress.ZERO;
87
+
88
+ protected slashingLog = createLogger('sequencer:publisher:slashing');
89
+ protected slashingProposerAddress?: EthAddress;
90
+ private getSlashPayload?: GetSlashPayloadCallBack = undefined;
91
+
92
+ private myLastVotes: Record<VoteType, bigint> = {
93
+ [VoteType.GOVERNANCE]: 0n,
94
+ [VoteType.SLASHING]: 0n,
95
+ };
96
+
97
+ protected log = createLogger('sequencer:publisher');
98
+ protected ethereumSlotDuration: bigint;
99
+
100
+ private blobSinkClient: BlobSinkClientInterface;
101
+ // @note - with blobs, the below estimate seems too large.
102
+ // Total used for full block from int_l1_pub e2e test: 1m (of which 86k is 1x blob)
103
+ // Total used for emptier block from above test: 429k (of which 84k is 1x blob)
104
+ public static PROPOSE_GAS_GUESS: bigint = 12_000_000n;
105
+ public static PROPOSE_AND_CLAIM_GAS_GUESS: bigint = this.PROPOSE_GAS_GUESS + 100_000n;
106
+
107
+ public l1TxUtils: L1TxUtilsWithBlobs;
108
+ public rollupContract: RollupContract;
109
+
110
+ protected requests: RequestWithExpiry[] = [];
111
+
112
+ constructor(
113
+ config: TxSenderConfig & PublisherConfig & Pick<L1ContractsConfig, 'ethereumSlotDuration'>,
114
+ deps: {
115
+ telemetry?: TelemetryClient;
116
+ blobSinkClient?: BlobSinkClientInterface;
117
+ forwarderContract: ForwarderContract;
118
+ l1TxUtils: L1TxUtilsWithBlobs;
119
+ rollupContract: RollupContract;
120
+ epochCache: EpochCache;
121
+ },
122
+ ) {
123
+ this.ethereumSlotDuration = BigInt(config.ethereumSlotDuration);
124
+ this.epochCache = deps.epochCache;
125
+
126
+ if (config.l1Contracts.governanceProposerAddress) {
127
+ this.governanceProposerAddress = EthAddress.fromString(config.l1Contracts.governanceProposerAddress.toString());
128
+ }
129
+ this.blobSinkClient = deps.blobSinkClient ?? createBlobSinkClient(config);
130
+
131
+ const telemetry = deps.telemetry ?? getTelemetryClient();
132
+ this.metrics = new SequencerPublisherMetrics(telemetry, 'SequencerPublisher');
133
+ this.l1TxUtils = deps.l1TxUtils;
134
+
135
+ this.rollupContract = deps.rollupContract;
136
+ this.forwarderContract = deps.forwarderContract;
137
+ }
138
+
139
+ public registerSlashPayloadGetter(callback: GetSlashPayloadCallBack) {
140
+ this.getSlashPayload = callback;
141
+ }
142
+
143
+ public getForwarderAddress() {
144
+ return EthAddress.fromString(this.forwarderContract.getAddress());
145
+ }
146
+
147
+ public getSenderAddress() {
148
+ return EthAddress.fromString(this.l1TxUtils.getSenderAddress());
149
+ }
150
+
151
+ public getGovernancePayload() {
152
+ return this.governancePayload;
153
+ }
154
+
155
+ public setGovernancePayload(payload: EthAddress) {
156
+ this.governancePayload = payload;
157
+ }
158
+
159
+ public addRequest(request: RequestWithExpiry) {
160
+ this.requests.push(request);
161
+ }
162
+
163
+ public getCurrentL2Slot(): bigint {
164
+ return this.epochCache.getEpochAndSlotNow().slot;
165
+ }
166
+
167
+ /**
168
+ * Sends all requests that are still valid.
169
+ * @returns one of:
170
+ * - A receipt and stats if the tx succeeded
171
+ * - a receipt and errorMsg if it failed on L1
172
+ * - undefined if no valid requests are found OR the tx failed to send.
173
+ */
174
+ public async sendRequests() {
175
+ const requestsToProcess = [...this.requests];
176
+ this.requests = [];
177
+ if (this.interrupted) {
178
+ return undefined;
179
+ }
180
+ const currentL2Slot = this.getCurrentL2Slot();
181
+ this.log.debug(`Current L2 slot: ${currentL2Slot}`);
182
+ const validRequests = requestsToProcess.filter(request => request.lastValidL2Slot >= currentL2Slot);
183
+
184
+ if (validRequests.length !== requestsToProcess.length) {
185
+ this.log.warn(`Some requests were expired for slot ${currentL2Slot}`, {
186
+ validRequests: validRequests.map(request => ({
187
+ action: request.action,
188
+ lastValidL2Slot: request.lastValidL2Slot,
189
+ })),
190
+ requests: requestsToProcess.map(request => ({
191
+ action: request.action,
192
+ lastValidL2Slot: request.lastValidL2Slot,
193
+ })),
194
+ });
195
+ }
196
+
197
+ if (validRequests.length === 0) {
198
+ this.log.debug(`No valid requests to send`);
199
+ return undefined;
200
+ }
201
+
202
+ // @note - we can only have one gas config and one blob config per bundle
203
+ // find requests with gas and blob configs
204
+ // See https://github.com/AztecProtocol/aztec-packages/issues/11513
205
+ const gasConfigs = requestsToProcess.filter(request => request.gasConfig);
206
+ const blobConfigs = requestsToProcess.filter(request => request.blobConfig);
207
+
208
+ if (gasConfigs.length > 1 || blobConfigs.length > 1) {
209
+ throw new Error('Multiple gas or blob configs found');
210
+ }
211
+
212
+ const gasConfig = gasConfigs[0]?.gasConfig;
213
+ const blobConfig = blobConfigs[0]?.blobConfig;
214
+
215
+ try {
216
+ this.log.debug('Forwarding transactions', {
217
+ validRequests: validRequests.map(request => request.action),
218
+ });
219
+ const result = await this.forwarderContract.forward(
220
+ validRequests.map(request => request.request),
221
+ this.l1TxUtils,
222
+ gasConfig,
223
+ blobConfig,
224
+ );
225
+ this.callbackBundledTransactions(validRequests, result);
226
+ return result;
227
+ } catch (err) {
228
+ const { message, metaMessages } = formatViemError(err);
229
+ this.log.error(`Failed to publish bundled transactions`, message, { metaMessages });
230
+ return undefined;
231
+ }
232
+ }
233
+
234
+ private callbackBundledTransactions(
235
+ requests: RequestWithExpiry[],
236
+ result?: { receipt: TransactionReceipt; gasPrice: GasPrice },
237
+ ) {
238
+ const success = result?.receipt.status === 'success';
239
+ const logger = success ? this.log.info : this.log.error;
240
+ for (const request of requests) {
241
+ logger(`Bundled [${request.action}] transaction [${success ? 'succeeded' : 'failed'}]`);
242
+ request.onResult?.(request.request, result);
243
+ }
244
+ }
245
+
246
+ /**
247
+ * @notice Will call `canProposeAtNextEthBlock` to make sure that it is possible to propose
248
+ * @param tipArchive - The archive to check
249
+ * @returns The slot and block number if it is possible to propose, undefined otherwise
250
+ */
251
+ public canProposeAtNextEthBlock(tipArchive: Buffer) {
252
+ const ignoredErrors = ['SlotAlreadyInChain', 'InvalidProposer'];
253
+ return this.rollupContract
254
+ .canProposeAtNextEthBlock(tipArchive, this.getForwarderAddress().toString(), this.ethereumSlotDuration)
255
+ .catch(err => {
256
+ if (err instanceof FormattedViemError && ignoredErrors.find(e => err.message.includes(e))) {
257
+ this.log.debug(err.message);
258
+ } else {
259
+ this.log.error(err.name, err);
260
+ }
261
+ return undefined;
262
+ });
263
+ }
264
+
265
+ /**
266
+ * @returns The epoch that is currently claimable, undefined otherwise
267
+ */
268
+ public getClaimableEpoch() {
269
+ const acceptedErrors = ['Rollup__NoEpochToProve', 'Rollup__ProofRightAlreadyClaimed'] as const;
270
+ return this.rollupContract.getClaimableEpoch().catch(err => {
271
+ if (acceptedErrors.find(e => err.message.includes(e))) {
272
+ return undefined;
273
+ }
274
+ throw err;
275
+ });
276
+ }
277
+
278
+ /**
279
+ * @notice Will filter out invalid quotes according to L1
280
+ * @param quotes - The quotes to filter
281
+ * @returns The filtered quotes
282
+ */
283
+ public filterValidQuotes(quotes: EpochProofQuote[]): Promise<EpochProofQuote[]> {
284
+ return Promise.all(
285
+ quotes.map(x =>
286
+ this.rollupContract
287
+ // validate throws if the quote is not valid
288
+ // else returns void
289
+ .validateProofQuote(x.toViemArgs(), this.getForwarderAddress().toString(), this.ethereumSlotDuration)
290
+ .then(() => x)
291
+ .catch(err => {
292
+ this.log.error(`Failed to validate proof quote`, err, { quote: x.toInspect() });
293
+ return undefined;
294
+ }),
295
+ ),
296
+ ).then(quotes => quotes.filter((q): q is EpochProofQuote => !!q));
297
+ }
298
+
299
+ /**
300
+ * @notice Will call `validateHeader` to make sure that it is possible to propose
301
+ *
302
+ * @dev Throws if unable to propose
303
+ *
304
+ * @param header - The header to propose
305
+ * @param digest - The digest that attestations are signing over
306
+ *
307
+ */
308
+ public async validateBlockForSubmission(
309
+ header: BlockHeader,
310
+ attestationData: { digest: Buffer; signatures: Signature[] } = {
311
+ digest: Buffer.alloc(32),
312
+ signatures: [],
313
+ },
314
+ ): Promise<bigint> {
315
+ const ts = BigInt((await this.l1TxUtils.getBlock()).timestamp + this.ethereumSlotDuration);
316
+
317
+ const formattedSignatures = attestationData.signatures.map(attest => attest.toViemSignature());
318
+ const flags = { ignoreDA: true, ignoreSignatures: formattedSignatures.length == 0 };
319
+
320
+ const args = [
321
+ `0x${header.toBuffer().toString('hex')}`,
322
+ formattedSignatures,
323
+ `0x${attestationData.digest.toString('hex')}`,
324
+ ts,
325
+ `0x${header.contentCommitment.blobsHash.toString('hex')}`,
326
+ flags,
327
+ ] as const;
328
+
329
+ await this.rollupContract.validateHeader(args, this.getForwarderAddress().toString());
330
+ return ts;
331
+ }
332
+
333
+ public async getCurrentEpochCommittee(): Promise<EthAddress[]> {
334
+ const committee = await this.rollupContract.getCurrentEpochCommittee();
335
+ return committee.map(EthAddress.fromString);
336
+ }
337
+
338
+ /**
339
+ * Enqueues a castVote transaction to cast a vote for a given slot number.
340
+ * @param slotNumber - The slot number to cast a vote for.
341
+ * @param timestamp - The timestamp of the slot to cast a vote for.
342
+ * @param voteType - The type of vote to cast.
343
+ * @returns True if the vote was successfully enqueued, false otherwise.
344
+ */
345
+ public async enqueueCastVote(slotNumber: bigint, timestamp: bigint, voteType: VoteType): Promise<boolean> {
346
+ // @todo This function can be optimized by doing some of the computations locally instead of calling the L1 contracts
347
+ if (this.myLastVotes[voteType] >= slotNumber) {
348
+ return false;
349
+ }
350
+
351
+ const voteConfig = async (): Promise<
352
+ { payload: EthAddress; voteContractAddress: EthAddress; logger: Logger } | undefined
353
+ > => {
354
+ if (voteType === VoteType.GOVERNANCE) {
355
+ if (this.governancePayload.equals(EthAddress.ZERO)) {
356
+ return undefined;
357
+ }
358
+ if (!this.governanceProposerAddress) {
359
+ return undefined;
360
+ }
361
+ return {
362
+ payload: this.governancePayload,
363
+ voteContractAddress: this.governanceProposerAddress,
364
+ logger: this.governanceLog,
365
+ };
366
+ } else if (voteType === VoteType.SLASHING) {
367
+ if (!this.getSlashPayload) {
368
+ return undefined;
369
+ }
370
+ const slashingProposerAddress = await this.rollupContract.getSlashingProposerAddress();
371
+ if (!slashingProposerAddress) {
372
+ return undefined;
373
+ }
374
+
375
+ const slashPayload = await this.getSlashPayload(slotNumber);
376
+
377
+ if (!slashPayload) {
378
+ return undefined;
379
+ }
380
+
381
+ return {
382
+ payload: slashPayload,
383
+ voteContractAddress: slashingProposerAddress,
384
+ logger: this.slashingLog,
385
+ };
386
+ } else {
387
+ throw new Error('Invalid vote type');
388
+ }
389
+ };
390
+
391
+ const vConfig = await voteConfig();
392
+
393
+ if (!vConfig) {
394
+ return false;
395
+ }
396
+
397
+ const { payload, voteContractAddress } = vConfig;
398
+
399
+ const voteContract = getContract({
400
+ address: getAddress(voteContractAddress.toString()),
401
+ abi: EmpireBaseAbi,
402
+ client: this.l1TxUtils.walletClient,
403
+ });
404
+
405
+ const [proposer, roundNumber] = await Promise.all([
406
+ this.rollupContract.getProposerAt(timestamp),
407
+ voteContract.read.computeRound([slotNumber]),
408
+ ]);
409
+
410
+ if (proposer.toLowerCase() !== this.getForwarderAddress().toString().toLowerCase()) {
411
+ return false;
412
+ }
413
+
414
+ const [slotForLastVote] = await voteContract.read.rounds([this.rollupContract.address, roundNumber]);
415
+
416
+ if (slotForLastVote >= slotNumber) {
417
+ return false;
418
+ }
419
+
420
+ const cachedLastVote = this.myLastVotes[voteType];
421
+
422
+ this.myLastVotes[voteType] = slotNumber;
423
+
424
+ this.addRequest({
425
+ action: voteType === VoteType.GOVERNANCE ? 'governance-vote' : 'slashing-vote',
426
+ request: {
427
+ to: voteContractAddress.toString(),
428
+ data: encodeFunctionData({
429
+ abi: EmpireBaseAbi,
430
+ functionName: 'vote',
431
+ args: [payload.toString()],
432
+ }),
433
+ },
434
+ lastValidL2Slot: slotNumber,
435
+ onResult: (_request, result) => {
436
+ if (!result || result.receipt.status !== 'success') {
437
+ this.myLastVotes[voteType] = cachedLastVote;
438
+ } else {
439
+ this.log.info(`Cast ${voteType} vote for slot ${slotNumber}`);
440
+ }
441
+ },
442
+ });
443
+ return true;
444
+ }
445
+
446
+ /**
447
+ * Proposes a L2 block on L1.
448
+ *
449
+ * @param block - L2 block to propose.
450
+ * @returns True if the tx has been enqueued, throws otherwise. See #9315
451
+ */
452
+ public async enqueueProposeL2Block(
453
+ block: L2Block,
454
+ attestations?: Signature[],
455
+ txHashes?: TxHash[],
456
+ opts: { txTimeoutAt?: Date } = {},
457
+ ): Promise<boolean> {
458
+ const consensusPayload = new ConsensusPayload(block.header, block.archive.root, txHashes ?? []);
459
+
460
+ const digest = await getHashedSignaturePayload(consensusPayload, SignatureDomainSeparator.blockAttestation);
461
+
462
+ const blobs = await Blob.getBlobs(block.body.toBlobFields());
463
+ const proposeTxArgs = {
464
+ header: block.header.toBuffer(),
465
+ archive: block.archive.root.toBuffer(),
466
+ blockHash: (await block.header.hash()).toBuffer(),
467
+ body: block.body.toBuffer(),
468
+ blobs,
469
+ attestations,
470
+ txHashes: txHashes ?? [],
471
+ };
472
+
473
+ // @note This will make sure that we are passing the checks for our header ASSUMING that the data is also made available
474
+ // This means that we can avoid the simulation issues in later checks.
475
+ // By simulation issue, I mean the fact that the block.timestamp is equal to the last block, not the next, which
476
+ // make time consistency checks break.
477
+ const ts = await this.validateBlockForSubmission(block.header, {
478
+ digest: digest.toBuffer(),
479
+ signatures: attestations ?? [],
480
+ });
481
+
482
+ this.log.debug(`Submitting propose transaction`);
483
+ await this.addProposeTx(block, proposeTxArgs, opts, ts);
484
+ return true;
485
+ }
486
+
487
+ /** Enqueues a claimEpochProofRight transaction to submit a chosen prover quote for the previous epoch. */
488
+ public enqueueClaimEpochProofRight(proofQuote: EpochProofQuote): boolean {
489
+ const timer = new Timer();
490
+ this.addRequest({
491
+ action: 'claim',
492
+ request: {
493
+ to: this.rollupContract.address,
494
+ data: encodeFunctionData({
495
+ abi: RollupAbi,
496
+ functionName: 'claimEpochProofRight',
497
+ args: [proofQuote.toViemArgs()],
498
+ }),
499
+ },
500
+ lastValidL2Slot: this.getCurrentL2Slot(),
501
+ onResult: (_request, result) => {
502
+ if (!result) {
503
+ return;
504
+ }
505
+ const { receipt, stats } = result;
506
+ if (receipt.status === 'success') {
507
+ const publishStats: L1PublishStats = {
508
+ gasPrice: receipt.effectiveGasPrice,
509
+ gasUsed: receipt.gasUsed,
510
+ transactionHash: receipt.transactionHash,
511
+ blobDataGas: 0n,
512
+ blobGasUsed: 0n,
513
+ ...pick(stats!, 'calldataGas', 'calldataSize', 'sender'),
514
+ };
515
+ this.log.verbose(`Submitted claim epoch proof right to L1 rollup contract`, {
516
+ ...publishStats,
517
+ ...proofQuote.toInspect(),
518
+ });
519
+ this.metrics.recordClaimEpochProofRightTx(timer.ms(), publishStats);
520
+ } else {
521
+ this.metrics.recordFailedTx('claimEpochProofRight');
522
+ // TODO: Get the error message from the reverted tx
523
+ this.log.error(`Claim epoch proof right tx reverted`, {
524
+ txHash: receipt.transactionHash,
525
+ ...proofQuote.toInspect(),
526
+ });
527
+ }
528
+ },
529
+ });
530
+ return true;
531
+ }
532
+
533
+ /**
534
+ * Calling `interrupt` will cause any in progress call to `publishRollup` to return `false` asap.
535
+ * Be warned, the call may return false even if the tx subsequently gets successfully mined.
536
+ * In practice this shouldn't matter, as we'll only ever be calling `interrupt` when we know it's going to fail.
537
+ * A call to `restart` is required before you can continue publishing.
538
+ */
539
+ public interrupt() {
540
+ this.interrupted = true;
541
+ this.l1TxUtils.interrupt();
542
+ }
543
+
544
+ /** Restarts the publisher after calling `interrupt`. */
545
+ public restart() {
546
+ this.interrupted = false;
547
+ this.l1TxUtils.restart();
548
+ }
549
+
550
+ private async prepareProposeTx(encodedData: L1ProcessArgs, timestamp: bigint) {
551
+ const kzg = Blob.getViemKzgInstance();
552
+ const blobInput = Blob.getEthBlobEvaluationInputs(encodedData.blobs);
553
+ this.log.debug('Validating blob input', { blobInput });
554
+ const blobEvaluationGas = await this.l1TxUtils
555
+ .estimateGas(
556
+ this.l1TxUtils.walletClient.account,
557
+ {
558
+ to: this.rollupContract.address,
559
+ data: encodeFunctionData({
560
+ abi: RollupAbi,
561
+ functionName: 'validateBlobs',
562
+ args: [blobInput],
563
+ }),
564
+ },
565
+ {},
566
+ {
567
+ blobs: encodedData.blobs.map(b => b.data),
568
+ kzg,
569
+ },
570
+ )
571
+ .catch(err => {
572
+ const { message, metaMessages } = formatViemError(err);
573
+ this.log.error(`Failed to validate blobs`, message, { metaMessages });
574
+ throw new Error('Failed to validate blobs');
575
+ });
576
+
577
+ const attestations = encodedData.attestations
578
+ ? encodedData.attestations.map(attest => attest.toViemSignature())
579
+ : [];
580
+ const txHashes = encodedData.txHashes ? encodedData.txHashes.map(txHash => txHash.toString()) : [];
581
+ const args = [
582
+ {
583
+ header: `0x${encodedData.header.toString('hex')}`,
584
+ archive: `0x${encodedData.archive.toString('hex')}`,
585
+ oracleInput: {
586
+ // We are currently not modifying these. See #9963
587
+ feeAssetPriceModifier: 0n,
588
+ provingCostModifier: 0n,
589
+ },
590
+ blockHash: `0x${encodedData.blockHash.toString('hex')}`,
591
+ txHashes,
592
+ },
593
+ attestations,
594
+ // TODO(#9101): Extract blobs from beacon chain => calldata will only contain what's needed to verify blob and body input can be removed
595
+ `0x${encodedData.body.toString('hex')}`,
596
+ blobInput,
597
+ ] as const;
598
+
599
+ const rollupData = encodeFunctionData({
600
+ abi: RollupAbi,
601
+ functionName: 'propose',
602
+ args,
603
+ });
604
+
605
+ const forwarderData = encodeFunctionData({
606
+ abi: ForwarderAbi,
607
+ functionName: 'forward',
608
+ args: [[this.rollupContract.address], [rollupData]],
609
+ });
610
+
611
+ const simulationResult = await this.l1TxUtils
612
+ .simulateGasUsed(
613
+ {
614
+ to: this.getForwarderAddress().toString(),
615
+ data: forwarderData,
616
+ gas: SequencerPublisher.PROPOSE_GAS_GUESS,
617
+ },
618
+ {
619
+ // @note we add 1n to the timestamp because geth implementation doesn't like simulation timestamp to be equal to the current block timestamp
620
+ time: timestamp + 1n,
621
+ // @note reth should have a 30m gas limit per block but throws errors that this tx is beyond limit
622
+ gasLimit: SequencerPublisher.PROPOSE_GAS_GUESS * 2n,
623
+ },
624
+ [
625
+ {
626
+ address: this.rollupContract.address,
627
+ // @note we override checkBlob to false since blobs are not part simulate()
628
+ stateDiff: [
629
+ {
630
+ slot: toHex(9n, true),
631
+ value: toHex(0n, true),
632
+ },
633
+ ],
634
+ },
635
+ ],
636
+ {
637
+ // @note fallback gas estimate to use if the node doesn't support simulation API
638
+ fallbackGasEstimate: SequencerPublisher.PROPOSE_GAS_GUESS,
639
+ },
640
+ )
641
+ .catch(err => {
642
+ const { message, metaMessages } = formatViemError(err);
643
+ this.log.error(`Failed to simulate gas used`, message, { metaMessages });
644
+ throw new Error('Failed to simulate gas used');
645
+ });
646
+
647
+ return { args, blobEvaluationGas, rollupData, simulationResult };
648
+ }
649
+
650
+ private async addProposeTx(
651
+ block: L2Block,
652
+ encodedData: L1ProcessArgs,
653
+ opts: { txTimeoutAt?: Date } = {},
654
+ timestamp: bigint,
655
+ ): Promise<void> {
656
+ const timer = new Timer();
657
+ const kzg = Blob.getViemKzgInstance();
658
+ const { rollupData, simulationResult, blobEvaluationGas } = await this.prepareProposeTx(encodedData, timestamp);
659
+ const startBlock = await this.l1TxUtils.getBlockNumber();
660
+
661
+ return this.addRequest({
662
+ action: 'propose',
663
+ request: {
664
+ to: this.rollupContract.address,
665
+ data: rollupData,
666
+ },
667
+ lastValidL2Slot: block.header.globalVariables.slotNumber.toBigInt(),
668
+ gasConfig: {
669
+ ...opts,
670
+ gasLimit: this.l1TxUtils.bumpGasLimit(simulationResult + blobEvaluationGas),
671
+ },
672
+ blobConfig: {
673
+ blobs: encodedData.blobs.map(b => b.data),
674
+ kzg,
675
+ },
676
+ onResult: (request, result) => {
677
+ if (!result) {
678
+ return;
679
+ }
680
+ const { receipt, stats, errorMsg } = result;
681
+ if (receipt.status === 'success') {
682
+ const endBlock = receipt.blockNumber;
683
+ const inclusionBlocks = Number(endBlock - startBlock);
684
+ const publishStats: L1PublishBlockStats = {
685
+ gasPrice: receipt.effectiveGasPrice,
686
+ gasUsed: receipt.gasUsed,
687
+ blobGasUsed: receipt.blobGasUsed ?? 0n,
688
+ blobDataGas: receipt.blobGasPrice ?? 0n,
689
+ transactionHash: receipt.transactionHash,
690
+ ...pick(stats!, 'calldataGas', 'calldataSize', 'sender'),
691
+ ...block.getStats(),
692
+ eventName: 'rollup-published-to-l1',
693
+ blobCount: encodedData.blobs.length,
694
+ inclusionBlocks,
695
+ };
696
+ this.log.verbose(`Published L2 block to L1 rollup contract`, { ...stats, ...block.getStats() });
697
+ this.metrics.recordProcessBlockTx(timer.ms(), publishStats);
698
+
699
+ // Send the blobs to the blob sink
700
+ this.sendBlobsToBlobSink(receipt.blockHash, encodedData.blobs).catch(_err => {
701
+ this.log.error('Failed to send blobs to blob sink');
702
+ });
703
+
704
+ return true;
705
+ } else {
706
+ this.metrics.recordFailedTx('process');
707
+
708
+ this.log.error(`Rollup process tx reverted. ${errorMsg ?? 'No error message'}`, undefined, {
709
+ ...block.getStats(),
710
+ txHash: receipt.transactionHash,
711
+ blockHash: block.hash().toString(),
712
+ slotNumber: block.header.globalVariables.slotNumber.toBigInt(),
713
+ });
714
+ }
715
+ },
716
+ });
717
+ }
718
+
719
+ /**
720
+ * Send blobs to the blob sink
721
+ *
722
+ * If a blob sink url is configured, then we send blobs to the blob sink
723
+ * - for now we use the blockHash as the identifier for the blobs;
724
+ * In the future this will move to be the beacon block id - which takes a bit more work
725
+ * to calculate and will need to be mocked in e2e tests
726
+ */
727
+ protected sendBlobsToBlobSink(blockHash: string, blobs: Blob[]): Promise<boolean> {
728
+ return this.blobSinkClient.sendBlobsToBlobSink(blockHash, blobs);
729
+ }
730
+ }