@aztec/sequencer-client 0.0.0-test.1 → 0.0.1-commit.017a351

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