@aztec/sequencer-client 0.0.0-test.1 → 0.0.1-commit.001888fc

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