@aztec/archiver 4.0.0-nightly.20250907 → 4.0.0-nightly.20260107

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +27 -6
  2. package/dest/archiver/archiver.d.ts +127 -84
  3. package/dest/archiver/archiver.d.ts.map +1 -1
  4. package/dest/archiver/archiver.js +1128 -380
  5. package/dest/archiver/archiver_store.d.ts +122 -45
  6. package/dest/archiver/archiver_store.d.ts.map +1 -1
  7. package/dest/archiver/archiver_store_test_suite.d.ts +1 -1
  8. package/dest/archiver/archiver_store_test_suite.d.ts.map +1 -1
  9. package/dest/archiver/archiver_store_test_suite.js +2013 -343
  10. package/dest/archiver/config.d.ts +7 -20
  11. package/dest/archiver/config.d.ts.map +1 -1
  12. package/dest/archiver/config.js +21 -5
  13. package/dest/archiver/errors.d.ts +25 -1
  14. package/dest/archiver/errors.d.ts.map +1 -1
  15. package/dest/archiver/errors.js +37 -0
  16. package/dest/archiver/index.d.ts +2 -2
  17. package/dest/archiver/index.d.ts.map +1 -1
  18. package/dest/archiver/instrumentation.d.ts +5 -3
  19. package/dest/archiver/instrumentation.d.ts.map +1 -1
  20. package/dest/archiver/instrumentation.js +14 -0
  21. package/dest/archiver/kv_archiver_store/block_store.d.ts +83 -15
  22. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +1 -1
  23. package/dest/archiver/kv_archiver_store/block_store.js +396 -73
  24. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +2 -2
  25. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +1 -1
  26. package/dest/archiver/kv_archiver_store/contract_class_store.js +1 -1
  27. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +2 -2
  28. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +1 -1
  29. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +51 -55
  30. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +1 -1
  31. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +82 -46
  32. package/dest/archiver/kv_archiver_store/log_store.d.ts +12 -16
  33. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +1 -1
  34. package/dest/archiver/kv_archiver_store/log_store.js +149 -84
  35. package/dest/archiver/kv_archiver_store/message_store.d.ts +6 -5
  36. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +1 -1
  37. package/dest/archiver/kv_archiver_store/message_store.js +15 -14
  38. package/dest/archiver/l1/bin/retrieve-calldata.d.ts +3 -0
  39. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +1 -0
  40. package/dest/archiver/l1/bin/retrieve-calldata.js +149 -0
  41. package/dest/archiver/l1/calldata_retriever.d.ts +112 -0
  42. package/dest/archiver/l1/calldata_retriever.d.ts.map +1 -0
  43. package/dest/archiver/l1/calldata_retriever.js +471 -0
  44. package/dest/archiver/l1/data_retrieval.d.ts +90 -0
  45. package/dest/archiver/l1/data_retrieval.d.ts.map +1 -0
  46. package/dest/archiver/l1/data_retrieval.js +331 -0
  47. package/dest/archiver/l1/debug_tx.d.ts +19 -0
  48. package/dest/archiver/l1/debug_tx.d.ts.map +1 -0
  49. package/dest/archiver/l1/debug_tx.js +73 -0
  50. package/dest/archiver/l1/spire_proposer.d.ts +70 -0
  51. package/dest/archiver/l1/spire_proposer.d.ts.map +1 -0
  52. package/dest/archiver/l1/spire_proposer.js +157 -0
  53. package/dest/archiver/l1/trace_tx.d.ts +97 -0
  54. package/dest/archiver/l1/trace_tx.d.ts.map +1 -0
  55. package/dest/archiver/l1/trace_tx.js +91 -0
  56. package/dest/archiver/l1/types.d.ts +12 -0
  57. package/dest/archiver/l1/types.d.ts.map +1 -0
  58. package/dest/archiver/l1/types.js +3 -0
  59. package/dest/archiver/l1/validate_trace.d.ts +29 -0
  60. package/dest/archiver/l1/validate_trace.d.ts.map +1 -0
  61. package/dest/archiver/l1/validate_trace.js +150 -0
  62. package/dest/archiver/structs/data_retrieval.d.ts +1 -1
  63. package/dest/archiver/structs/inbox_message.d.ts +4 -4
  64. package/dest/archiver/structs/inbox_message.d.ts.map +1 -1
  65. package/dest/archiver/structs/inbox_message.js +6 -5
  66. package/dest/archiver/structs/published.d.ts +2 -2
  67. package/dest/archiver/structs/published.d.ts.map +1 -1
  68. package/dest/archiver/validation.d.ts +10 -4
  69. package/dest/archiver/validation.d.ts.map +1 -1
  70. package/dest/archiver/validation.js +66 -44
  71. package/dest/factory.d.ts +4 -6
  72. package/dest/factory.d.ts.map +1 -1
  73. package/dest/factory.js +5 -4
  74. package/dest/index.d.ts +2 -2
  75. package/dest/index.d.ts.map +1 -1
  76. package/dest/index.js +1 -1
  77. package/dest/rpc/index.d.ts +2 -2
  78. package/dest/test/index.d.ts +1 -1
  79. package/dest/test/mock_archiver.d.ts +16 -8
  80. package/dest/test/mock_archiver.d.ts.map +1 -1
  81. package/dest/test/mock_archiver.js +19 -14
  82. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  83. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  84. package/dest/test/mock_l1_to_l2_message_source.js +10 -9
  85. package/dest/test/mock_l2_block_source.d.ts +31 -20
  86. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  87. package/dest/test/mock_l2_block_source.js +85 -18
  88. package/dest/test/mock_structs.d.ts +3 -2
  89. package/dest/test/mock_structs.d.ts.map +1 -1
  90. package/dest/test/mock_structs.js +9 -8
  91. package/package.json +18 -17
  92. package/src/archiver/archiver.ts +971 -475
  93. package/src/archiver/archiver_store.ts +141 -44
  94. package/src/archiver/archiver_store_test_suite.ts +2114 -331
  95. package/src/archiver/config.ts +30 -35
  96. package/src/archiver/errors.ts +64 -0
  97. package/src/archiver/index.ts +1 -1
  98. package/src/archiver/instrumentation.ts +19 -2
  99. package/src/archiver/kv_archiver_store/block_store.ts +541 -83
  100. package/src/archiver/kv_archiver_store/contract_class_store.ts +1 -1
  101. package/src/archiver/kv_archiver_store/contract_instance_store.ts +1 -1
  102. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +107 -67
  103. package/src/archiver/kv_archiver_store/log_store.ts +209 -99
  104. package/src/archiver/kv_archiver_store/message_store.ts +21 -18
  105. package/src/archiver/l1/README.md +98 -0
  106. package/src/archiver/l1/bin/retrieve-calldata.ts +182 -0
  107. package/src/archiver/l1/calldata_retriever.ts +641 -0
  108. package/src/archiver/l1/data_retrieval.ts +512 -0
  109. package/src/archiver/l1/debug_tx.ts +99 -0
  110. package/src/archiver/l1/spire_proposer.ts +160 -0
  111. package/src/archiver/l1/trace_tx.ts +128 -0
  112. package/src/archiver/l1/types.ts +13 -0
  113. package/src/archiver/l1/validate_trace.ts +211 -0
  114. package/src/archiver/structs/inbox_message.ts +8 -8
  115. package/src/archiver/structs/published.ts +1 -1
  116. package/src/archiver/validation.ts +86 -32
  117. package/src/factory.ts +6 -7
  118. package/src/index.ts +1 -1
  119. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  120. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  121. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  122. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  123. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  124. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  125. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  126. package/src/test/mock_archiver.ts +22 -16
  127. package/src/test/mock_l1_to_l2_message_source.ts +10 -9
  128. package/src/test/mock_l2_block_source.ts +114 -27
  129. package/src/test/mock_structs.ts +10 -9
  130. package/dest/archiver/data_retrieval.d.ts +0 -78
  131. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  132. package/dest/archiver/data_retrieval.js +0 -354
  133. package/src/archiver/data_retrieval.ts +0 -535
@@ -0,0 +1,641 @@
1
+ import { MULTI_CALL_3_ADDRESS, type ViemCommitteeAttestations, type ViemHeader } from '@aztec/ethereum/contracts';
2
+ import type { ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
3
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
4
+ import { Fr } from '@aztec/foundation/curves/bn254';
5
+ import { EthAddress } from '@aztec/foundation/eth-address';
6
+ import type { ViemSignature } from '@aztec/foundation/eth-signature';
7
+ import type { Logger } from '@aztec/foundation/log';
8
+ import {
9
+ EmpireSlashingProposerAbi,
10
+ GovernanceProposerAbi,
11
+ RollupAbi,
12
+ SlashFactoryAbi,
13
+ TallySlashingProposerAbi,
14
+ } from '@aztec/l1-artifacts';
15
+ import { CommitteeAttestation } from '@aztec/stdlib/block';
16
+ import { ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
17
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
18
+
19
+ import {
20
+ type AbiParameter,
21
+ type Hex,
22
+ type Transaction,
23
+ decodeFunctionData,
24
+ encodeAbiParameters,
25
+ hexToBytes,
26
+ keccak256,
27
+ multicall3Abi,
28
+ toFunctionSelector,
29
+ } from 'viem';
30
+
31
+ import type { ArchiverInstrumentation } from '../instrumentation.js';
32
+ import { getSuccessfulCallsFromDebug } from './debug_tx.js';
33
+ import { getCallFromSpireProposer } from './spire_proposer.js';
34
+ import { getSuccessfulCallsFromTrace } from './trace_tx.js';
35
+ import type { CallInfo } from './types.js';
36
+
37
+ /**
38
+ * Extracts calldata to the `propose` method of the rollup contract from an L1 transaction
39
+ * in order to reconstruct an L2 block header.
40
+ */
41
+ export class CalldataRetriever {
42
+ /** Pre-computed valid contract calls for validation */
43
+ private readonly validContractCalls: ValidContractCall[];
44
+
45
+ private readonly rollupAddress: EthAddress;
46
+
47
+ constructor(
48
+ private readonly publicClient: ViemPublicClient,
49
+ private readonly debugClient: ViemPublicDebugClient,
50
+ private readonly targetCommitteeSize: number,
51
+ private readonly instrumentation: ArchiverInstrumentation | undefined,
52
+ private readonly logger: Logger,
53
+ contractAddresses: {
54
+ rollupAddress: EthAddress;
55
+ governanceProposerAddress: EthAddress;
56
+ slashingProposerAddress: EthAddress;
57
+ slashFactoryAddress?: EthAddress;
58
+ },
59
+ ) {
60
+ this.rollupAddress = contractAddresses.rollupAddress;
61
+ this.validContractCalls = computeValidContractCalls(contractAddresses);
62
+ }
63
+
64
+ /**
65
+ * Gets checkpoint header and metadata from the calldata of an L1 transaction.
66
+ * Tries multicall3 decoding, falls back to trace-based extraction.
67
+ * @param txHash - Hash of the tx that published it.
68
+ * @param blobHashes - Blob hashes for the checkpoint.
69
+ * @param checkpointNumber - Checkpoint number.
70
+ * @param expectedHashes - Optional expected hashes from the CheckpointProposed event for validation
71
+ * @returns Checkpoint header and metadata from the calldata, deserialized
72
+ */
73
+ async getCheckpointFromRollupTx(
74
+ txHash: `0x${string}`,
75
+ blobHashes: Buffer[],
76
+ checkpointNumber: CheckpointNumber,
77
+ expectedHashes: {
78
+ attestationsHash?: Hex;
79
+ payloadDigest?: Hex;
80
+ },
81
+ ): Promise<{
82
+ checkpointNumber: CheckpointNumber;
83
+ archiveRoot: Fr;
84
+ header: CheckpointHeader;
85
+ attestations: CommitteeAttestation[];
86
+ blockHash: string;
87
+ }> {
88
+ this.logger.trace(`Fetching checkpoint ${checkpointNumber} from rollup tx ${txHash}`, {
89
+ willValidateHashes: !!expectedHashes.attestationsHash || !!expectedHashes.payloadDigest,
90
+ hasAttestationsHash: !!expectedHashes.attestationsHash,
91
+ hasPayloadDigest: !!expectedHashes.payloadDigest,
92
+ });
93
+ const tx = await this.publicClient.getTransaction({ hash: txHash });
94
+ const proposeCalldata = await this.getProposeCallData(tx, checkpointNumber);
95
+ return this.decodeAndBuildCheckpoint(proposeCalldata, tx.blockHash!, checkpointNumber, expectedHashes);
96
+ }
97
+
98
+ /** Gets rollup propose calldata from a transaction */
99
+ protected async getProposeCallData(tx: Transaction, checkpointNumber: CheckpointNumber): Promise<Hex> {
100
+ // Try to decode as multicall3 with validation
101
+ const proposeCalldata = this.tryDecodeMulticall3(tx);
102
+ if (proposeCalldata) {
103
+ this.logger.trace(`Decoded propose calldata from multicall3 for tx ${tx.hash}`);
104
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
105
+ return proposeCalldata;
106
+ }
107
+
108
+ // Try to decode as direct propose call
109
+ const directProposeCalldata = this.tryDecodeDirectPropose(tx);
110
+ if (directProposeCalldata) {
111
+ this.logger.trace(`Decoded propose calldata from direct call for tx ${tx.hash}`);
112
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
113
+ return directProposeCalldata;
114
+ }
115
+
116
+ // Try to decode as Spire Proposer multicall wrapper
117
+ const spireProposeCalldata = await this.tryDecodeSpireProposer(tx);
118
+ if (spireProposeCalldata) {
119
+ this.logger.trace(`Decoded propose calldata from Spire Proposer for tx ${tx.hash}`);
120
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
121
+ return spireProposeCalldata;
122
+ }
123
+
124
+ // Fall back to trace-based extraction
125
+ this.logger.warn(
126
+ `Failed to decode multicall3, direct propose, or Spire proposer for L1 tx ${tx.hash}, falling back to trace for checkpoint ${checkpointNumber}`,
127
+ );
128
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to ?? EthAddress.ZERO.toString(), true);
129
+ return await this.extractCalldataViaTrace(tx.hash);
130
+ }
131
+
132
+ /**
133
+ * Attempts to decode a transaction as a Spire Proposer multicall wrapper.
134
+ * If successful, extracts the wrapped call and validates it as either multicall3 or direct propose.
135
+ * @param tx - The transaction to decode
136
+ * @returns The propose calldata if successfully decoded and validated, undefined otherwise
137
+ */
138
+ protected async tryDecodeSpireProposer(tx: Transaction): Promise<Hex | undefined> {
139
+ // Try to decode as Spire Proposer multicall (extracts the wrapped call)
140
+ const spireWrappedCall = await getCallFromSpireProposer(tx, this.publicClient, this.logger);
141
+ if (!spireWrappedCall) {
142
+ return undefined;
143
+ }
144
+
145
+ this.logger.trace(`Decoded Spire Proposer wrapping for tx ${tx.hash}, inner call to ${spireWrappedCall.to}`);
146
+
147
+ // Now try to decode the wrapped call as either multicall3 or direct propose
148
+ const wrappedTx = { to: spireWrappedCall.to, input: spireWrappedCall.data, hash: tx.hash };
149
+
150
+ const multicall3Calldata = this.tryDecodeMulticall3(wrappedTx);
151
+ if (multicall3Calldata) {
152
+ this.logger.trace(`Decoded propose calldata from Spire Proposer to multicall3 for tx ${tx.hash}`);
153
+ return multicall3Calldata;
154
+ }
155
+
156
+ const directProposeCalldata = this.tryDecodeDirectPropose(wrappedTx);
157
+ if (directProposeCalldata) {
158
+ this.logger.trace(`Decoded propose calldata from Spire Proposer to direct propose for tx ${tx.hash}`);
159
+ return directProposeCalldata;
160
+ }
161
+
162
+ this.logger.warn(
163
+ `Spire Proposer wrapped call could not be decoded as multicall3 or direct propose for tx ${tx.hash}`,
164
+ );
165
+ return undefined;
166
+ }
167
+
168
+ /**
169
+ * Attempts to decode transaction input as multicall3 and extract propose calldata.
170
+ * Returns undefined if validation fails.
171
+ * @param tx - The transaction-like object with to, input, and hash
172
+ * @returns The propose calldata if successfully validated, undefined otherwise
173
+ */
174
+ protected tryDecodeMulticall3(tx: { to: Hex | null | undefined; input: Hex; hash: Hex }): Hex | undefined {
175
+ const txHash = tx.hash;
176
+
177
+ try {
178
+ // Check if transaction is to Multicall3 address
179
+ if (!tx.to || !EthAddress.areEqual(tx.to, MULTI_CALL_3_ADDRESS)) {
180
+ this.logger.debug(`Transaction is not to Multicall3 address (to: ${tx.to})`, { txHash, to: tx.to });
181
+ return undefined;
182
+ }
183
+
184
+ // Try to decode as multicall3 aggregate3 call
185
+ const { functionName: multicall3Fn, args: multicall3Args } = decodeFunctionData({
186
+ abi: multicall3Abi,
187
+ data: tx.input,
188
+ });
189
+
190
+ // If not aggregate3, return undefined (not a multicall3 transaction)
191
+ if (multicall3Fn !== 'aggregate3') {
192
+ this.logger.warn(`Transaction is not multicall3 aggregate3 (got ${multicall3Fn})`, { txHash });
193
+ return undefined;
194
+ }
195
+
196
+ if (multicall3Args.length !== 1) {
197
+ this.logger.warn(`Unexpected number of arguments for multicall3 (got ${multicall3Args.length})`, { txHash });
198
+ return undefined;
199
+ }
200
+
201
+ const [calls] = multicall3Args;
202
+
203
+ // Validate all calls and find propose calls
204
+ const rollupAddressLower = this.rollupAddress.toString().toLowerCase();
205
+ const proposeCalls: Hex[] = [];
206
+
207
+ for (let i = 0; i < calls.length; i++) {
208
+ const addr = calls[i].target.toLowerCase();
209
+ const callData = calls[i].callData;
210
+
211
+ // Extract function selector (first 4 bytes)
212
+ if (callData.length < 10) {
213
+ // "0x" + 8 hex chars = 10 chars minimum for a valid function call
214
+ this.logger.warn(`Invalid calldata length at index ${i} (${callData.length})`, { txHash });
215
+ return undefined;
216
+ }
217
+ const functionSelector = callData.slice(0, 10) as Hex;
218
+
219
+ // Validate this call is allowed by searching through valid calls
220
+ const validCall = this.validContractCalls.find(
221
+ vc => vc.address === addr && vc.functionSelector === functionSelector,
222
+ );
223
+
224
+ if (!validCall) {
225
+ this.logger.warn(`Invalid contract call detected in multicall3`, {
226
+ index: i,
227
+ targetAddress: addr,
228
+ functionSelector,
229
+ validCalls: this.validContractCalls.map(c => ({ address: c.address, selector: c.functionSelector })),
230
+ txHash,
231
+ });
232
+ return undefined;
233
+ }
234
+
235
+ this.logger.trace(`Valid call found to ${addr}`, { validCall });
236
+
237
+ // Collect propose calls specifically
238
+ if (addr === rollupAddressLower && validCall.functionName === 'propose') {
239
+ proposeCalls.push(callData);
240
+ }
241
+ }
242
+
243
+ // Validate exactly ONE propose call
244
+ if (proposeCalls.length === 0) {
245
+ this.logger.warn(`No propose calls found in multicall3`, { txHash });
246
+ return undefined;
247
+ }
248
+
249
+ if (proposeCalls.length > 1) {
250
+ this.logger.warn(`Multiple propose calls found in multicall3 (${proposeCalls.length})`, { txHash });
251
+ return undefined;
252
+ }
253
+
254
+ // Successfully extracted single propose call
255
+ return proposeCalls[0];
256
+ } catch (err) {
257
+ // Any decoding error triggers fallback to trace
258
+ this.logger.warn(`Failed to decode multicall3: ${err}`, { txHash });
259
+ return undefined;
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Attempts to decode transaction as a direct propose call to the rollup contract.
265
+ * Returns undefined if validation fails.
266
+ * @param tx - The transaction-like object with to, input, and hash
267
+ * @returns The propose calldata if successfully validated, undefined otherwise
268
+ */
269
+ protected tryDecodeDirectPropose(tx: { to: Hex | null | undefined; input: Hex; hash: Hex }): Hex | undefined {
270
+ const txHash = tx.hash;
271
+ try {
272
+ // Check if transaction is to the rollup address
273
+ if (!tx.to || !EthAddress.areEqual(tx.to, this.rollupAddress)) {
274
+ this.logger.debug(`Transaction is not to rollup address (to: ${tx.to})`, { txHash });
275
+ return undefined;
276
+ }
277
+
278
+ // Try to decode as propose call
279
+ const { functionName } = decodeFunctionData({ abi: RollupAbi, data: tx.input });
280
+
281
+ // If not propose, return undefined
282
+ if (functionName !== 'propose') {
283
+ this.logger.warn(`Transaction to rollup is not propose (got ${functionName})`, { txHash });
284
+ return undefined;
285
+ }
286
+
287
+ // Successfully validated direct propose call
288
+ this.logger.trace(`Validated direct propose call to rollup`, { txHash });
289
+ return tx.input;
290
+ } catch (err) {
291
+ // Any decoding error means it's not a valid propose call
292
+ this.logger.warn(`Failed to decode as direct propose: ${err}`, { txHash });
293
+ return undefined;
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Uses debug/trace RPC to extract the actual calldata from the successful propose call.
299
+ * This is the definitive fallback that works for any transaction pattern.
300
+ * Tries trace_transaction first, then falls back to debug_traceTransaction.
301
+ * @param txHash - The transaction hash to trace
302
+ * @returns The propose calldata from the successful call
303
+ */
304
+ protected async extractCalldataViaTrace(txHash: Hex): Promise<Hex> {
305
+ const rollupAddress = this.rollupAddress;
306
+ const selector = PROPOSE_SELECTOR;
307
+
308
+ let calls: CallInfo[];
309
+ try {
310
+ // Try trace_transaction first (using Parity/OpenEthereum/Erigon RPC)
311
+ this.logger.debug(`Attempting to trace transaction ${txHash} using trace_transaction`);
312
+ calls = await getSuccessfulCallsFromTrace(this.debugClient, txHash, rollupAddress, selector, this.logger);
313
+ this.logger.debug(`Successfully traced using trace_transaction, found ${calls.length} calls`);
314
+ } catch (err) {
315
+ const traceError = err instanceof Error ? err : new Error(String(err));
316
+ this.logger.verbose(`Failed trace_transaction for ${txHash}`, { traceError });
317
+
318
+ try {
319
+ // Fall back to debug_traceTransaction (Geth RPC)
320
+ this.logger.debug(`Attempting to trace transaction ${txHash} using debug_traceTransaction`);
321
+ calls = await getSuccessfulCallsFromDebug(this.debugClient, txHash, rollupAddress, selector, this.logger);
322
+ this.logger.debug(`Successfully traced using debug_traceTransaction, found ${calls.length} calls`);
323
+ } catch (debugErr) {
324
+ const debugError = debugErr instanceof Error ? debugErr : new Error(String(debugErr));
325
+ this.logger.warn(`All tracing methods failed for tx ${txHash}`, {
326
+ traceError,
327
+ debugError,
328
+ txHash,
329
+ });
330
+ throw new Error(`Failed to trace transaction ${txHash} to extract propose calldata`);
331
+ }
332
+ }
333
+
334
+ // Validate exactly ONE successful propose call
335
+ if (calls.length === 0) {
336
+ throw new Error(`No successful propose calls found in transaction ${txHash}`);
337
+ }
338
+
339
+ if (calls.length > 1) {
340
+ throw new Error(`Multiple successful propose calls found in transaction ${txHash} (${calls.length})`);
341
+ }
342
+
343
+ // Return the calldata from the single successful propose call
344
+ return calls[0].input;
345
+ }
346
+
347
+ /**
348
+ * Extracts the CommitteeAttestations struct definition from RollupAbi.
349
+ * Finds the _attestations parameter by name in the propose function.
350
+ * Lazy-loaded to avoid issues during module initialization.
351
+ */
352
+ private getCommitteeAttestationsStructDef(): AbiParameter {
353
+ const proposeFunction = RollupAbi.find(item => item.type === 'function' && item.name === 'propose') as
354
+ | { type: 'function'; name: string; inputs: readonly AbiParameter[] }
355
+ | undefined;
356
+
357
+ if (!proposeFunction) {
358
+ throw new Error('propose function not found in RollupAbi');
359
+ }
360
+
361
+ // Find the _attestations parameter by name, not by index
362
+ const attestationsParam = proposeFunction.inputs.find(param => param.name === '_attestations');
363
+
364
+ if (!attestationsParam) {
365
+ throw new Error('_attestations parameter not found in propose function');
366
+ }
367
+
368
+ if (attestationsParam.type !== 'tuple') {
369
+ throw new Error(`Expected _attestations parameter to be a tuple, got ${attestationsParam.type}`);
370
+ }
371
+
372
+ // Extract the tuple components (struct fields)
373
+ const tupleParam = attestationsParam as unknown as {
374
+ type: 'tuple';
375
+ components?: readonly AbiParameter[];
376
+ };
377
+
378
+ return {
379
+ type: 'tuple',
380
+ components: tupleParam.components || [],
381
+ } as AbiParameter;
382
+ }
383
+
384
+ /**
385
+ * Decodes propose calldata and builds the checkpoint header structure.
386
+ * @param proposeCalldata - The propose function calldata
387
+ * @param blockHash - The L1 block hash containing this transaction
388
+ * @param checkpointNumber - The checkpoint number
389
+ * @param expectedHashes - Optional expected hashes from the CheckpointProposed event for validation
390
+ * @returns The decoded checkpoint header and metadata
391
+ */
392
+ protected decodeAndBuildCheckpoint(
393
+ proposeCalldata: Hex,
394
+ blockHash: Hex,
395
+ checkpointNumber: CheckpointNumber,
396
+ expectedHashes: {
397
+ attestationsHash?: Hex;
398
+ payloadDigest?: Hex;
399
+ },
400
+ ): {
401
+ checkpointNumber: CheckpointNumber;
402
+ archiveRoot: Fr;
403
+ header: CheckpointHeader;
404
+ attestations: CommitteeAttestation[];
405
+ blockHash: string;
406
+ } {
407
+ const { functionName: rollupFunctionName, args: rollupArgs } = decodeFunctionData({
408
+ abi: RollupAbi,
409
+ data: proposeCalldata,
410
+ });
411
+
412
+ if (rollupFunctionName !== 'propose') {
413
+ throw new Error(`Unexpected rollup method called ${rollupFunctionName}`);
414
+ }
415
+
416
+ const [decodedArgs, packedAttestations, _signers, _attestationsAndSignersSignature, _blobInput] =
417
+ rollupArgs! as readonly [
418
+ {
419
+ archive: Hex;
420
+ oracleInput: { feeAssetPriceModifier: bigint };
421
+ header: ViemHeader;
422
+ },
423
+ ViemCommitteeAttestations,
424
+ Hex[],
425
+ ViemSignature,
426
+ Hex,
427
+ ];
428
+
429
+ const attestations = CommitteeAttestation.fromPacked(packedAttestations, this.targetCommitteeSize);
430
+ const header = CheckpointHeader.fromViem(decodedArgs.header);
431
+ const archiveRoot = new Fr(Buffer.from(hexToBytes(decodedArgs.archive)));
432
+
433
+ // Validate attestationsHash if provided (skip for backwards compatibility with older events)
434
+ if (expectedHashes.attestationsHash) {
435
+ // Compute attestationsHash: keccak256(abi.encode(CommitteeAttestations))
436
+ const computedAttestationsHash = keccak256(
437
+ encodeAbiParameters([this.getCommitteeAttestationsStructDef()], [packedAttestations]),
438
+ );
439
+
440
+ // Compare as buffers to avoid case-sensitivity and string comparison issues
441
+ const computedBuffer = Buffer.from(hexToBytes(computedAttestationsHash));
442
+ const expectedBuffer = Buffer.from(hexToBytes(expectedHashes.attestationsHash));
443
+
444
+ if (!computedBuffer.equals(expectedBuffer)) {
445
+ throw new Error(
446
+ `Attestations hash mismatch for checkpoint ${checkpointNumber}: ` +
447
+ `computed=${computedAttestationsHash}, expected=${expectedHashes.attestationsHash}`,
448
+ );
449
+ }
450
+
451
+ this.logger.trace(`Validated attestationsHash for checkpoint ${checkpointNumber}`, {
452
+ computedAttestationsHash,
453
+ expectedAttestationsHash: expectedHashes.attestationsHash,
454
+ });
455
+ }
456
+
457
+ // Validate payloadDigest if provided (skip for backwards compatibility with older events)
458
+ if (expectedHashes.payloadDigest) {
459
+ // Use ConsensusPayload to compute the digest - this ensures we match the exact logic
460
+ // used by the network for signing and verification
461
+ const consensusPayload = new ConsensusPayload(header, archiveRoot);
462
+ const payloadToSign = consensusPayload.getPayloadToSign(SignatureDomainSeparator.blockAttestation);
463
+ const computedPayloadDigest = keccak256(payloadToSign);
464
+
465
+ // Compare as buffers to avoid case-sensitivity and string comparison issues
466
+ const computedBuffer = Buffer.from(hexToBytes(computedPayloadDigest));
467
+ const expectedBuffer = Buffer.from(hexToBytes(expectedHashes.payloadDigest));
468
+
469
+ if (!computedBuffer.equals(expectedBuffer)) {
470
+ throw new Error(
471
+ `Payload digest mismatch for checkpoint ${checkpointNumber}: ` +
472
+ `computed=${computedPayloadDigest}, expected=${expectedHashes.payloadDigest}`,
473
+ );
474
+ }
475
+
476
+ this.logger.trace(`Validated payloadDigest for checkpoint ${checkpointNumber}`, {
477
+ computedPayloadDigest,
478
+ expectedPayloadDigest: expectedHashes.payloadDigest,
479
+ });
480
+ }
481
+
482
+ this.logger.trace(`Decoded propose calldata`, {
483
+ checkpointNumber,
484
+ archive: decodedArgs.archive,
485
+ header: decodedArgs.header,
486
+ l1BlockHash: blockHash,
487
+ attestations,
488
+ packedAttestations,
489
+ targetCommitteeSize: this.targetCommitteeSize,
490
+ });
491
+
492
+ return {
493
+ checkpointNumber,
494
+ archiveRoot,
495
+ header,
496
+ attestations,
497
+ blockHash,
498
+ };
499
+ }
500
+ }
501
+
502
+ /**
503
+ * Pre-computed function selectors for all valid contract calls.
504
+ * These are computed once at module load time from the ABIs.
505
+ * Based on analysis of sequencer-client/src/publisher/sequencer-publisher.ts
506
+ */
507
+
508
+ // Rollup contract function selectors (always valid)
509
+ const PROPOSE_SELECTOR = toFunctionSelector(RollupAbi.find(x => x.type === 'function' && x.name === 'propose')!);
510
+ const INVALIDATE_BAD_ATTESTATION_SELECTOR = toFunctionSelector(
511
+ RollupAbi.find(x => x.type === 'function' && x.name === 'invalidateBadAttestation')!,
512
+ );
513
+ const INVALIDATE_INSUFFICIENT_ATTESTATIONS_SELECTOR = toFunctionSelector(
514
+ RollupAbi.find(x => x.type === 'function' && x.name === 'invalidateInsufficientAttestations')!,
515
+ );
516
+
517
+ // Governance proposer function selectors
518
+ const GOVERNANCE_SIGNAL_WITH_SIG_SELECTOR = toFunctionSelector(
519
+ GovernanceProposerAbi.find(x => x.type === 'function' && x.name === 'signalWithSig')!,
520
+ );
521
+
522
+ // Slash factory function selectors
523
+ const CREATE_SLASH_PAYLOAD_SELECTOR = toFunctionSelector(
524
+ SlashFactoryAbi.find(x => x.type === 'function' && x.name === 'createSlashPayload')!,
525
+ );
526
+
527
+ // Empire slashing proposer function selectors
528
+ const EMPIRE_SIGNAL_WITH_SIG_SELECTOR = toFunctionSelector(
529
+ EmpireSlashingProposerAbi.find(x => x.type === 'function' && x.name === 'signalWithSig')!,
530
+ );
531
+ const EMPIRE_SUBMIT_ROUND_WINNER_SELECTOR = toFunctionSelector(
532
+ EmpireSlashingProposerAbi.find(x => x.type === 'function' && x.name === 'submitRoundWinner')!,
533
+ );
534
+
535
+ // Tally slashing proposer function selectors
536
+ const TALLY_VOTE_SELECTOR = toFunctionSelector(
537
+ TallySlashingProposerAbi.find(x => x.type === 'function' && x.name === 'vote')!,
538
+ );
539
+ const TALLY_EXECUTE_ROUND_SELECTOR = toFunctionSelector(
540
+ TallySlashingProposerAbi.find(x => x.type === 'function' && x.name === 'executeRound')!,
541
+ );
542
+
543
+ /**
544
+ * Defines a valid contract call that can appear in a sequencer publisher transaction
545
+ */
546
+ interface ValidContractCall {
547
+ /** Contract address (lowercase for comparison) */
548
+ address: string;
549
+ /** Function selector (4 bytes) */
550
+ functionSelector: Hex;
551
+ /** Human-readable function name for logging */
552
+ functionName: string;
553
+ }
554
+
555
+ /**
556
+ * All valid contract calls that the sequencer publisher can make.
557
+ * Builds the list of valid (address, selector) pairs for validation.
558
+ *
559
+ * Alternatively, if we are absolutely sure that no code path from any of these
560
+ * contracts can eventually land on another call to `propose`, we can remove the
561
+ * function selectors.
562
+ */
563
+ function computeValidContractCalls(addresses: {
564
+ rollupAddress: EthAddress;
565
+ governanceProposerAddress?: EthAddress;
566
+ slashFactoryAddress?: EthAddress;
567
+ slashingProposerAddress?: EthAddress;
568
+ }): ValidContractCall[] {
569
+ const { rollupAddress, governanceProposerAddress, slashFactoryAddress, slashingProposerAddress } = addresses;
570
+ const calls: ValidContractCall[] = [];
571
+
572
+ // Rollup contract calls (always present)
573
+ calls.push(
574
+ {
575
+ address: rollupAddress.toString().toLowerCase(),
576
+ functionSelector: PROPOSE_SELECTOR,
577
+ functionName: 'propose',
578
+ },
579
+ {
580
+ address: rollupAddress.toString().toLowerCase(),
581
+ functionSelector: INVALIDATE_BAD_ATTESTATION_SELECTOR,
582
+ functionName: 'invalidateBadAttestation',
583
+ },
584
+ {
585
+ address: rollupAddress.toString().toLowerCase(),
586
+ functionSelector: INVALIDATE_INSUFFICIENT_ATTESTATIONS_SELECTOR,
587
+ functionName: 'invalidateInsufficientAttestations',
588
+ },
589
+ );
590
+
591
+ // Governance proposer calls (optional)
592
+ if (governanceProposerAddress && !governanceProposerAddress.isZero()) {
593
+ calls.push({
594
+ address: governanceProposerAddress.toString().toLowerCase(),
595
+ functionSelector: GOVERNANCE_SIGNAL_WITH_SIG_SELECTOR,
596
+ functionName: 'signalWithSig',
597
+ });
598
+ }
599
+
600
+ // Slash factory calls (optional)
601
+ if (slashFactoryAddress && !slashFactoryAddress.isZero()) {
602
+ calls.push({
603
+ address: slashFactoryAddress.toString().toLowerCase(),
604
+ functionSelector: CREATE_SLASH_PAYLOAD_SELECTOR,
605
+ functionName: 'createSlashPayload',
606
+ });
607
+ }
608
+
609
+ // Slashing proposer calls (optional, can be either Empire or Tally)
610
+ if (slashingProposerAddress && !slashingProposerAddress.isZero()) {
611
+ // Empire calls
612
+ calls.push(
613
+ {
614
+ address: slashingProposerAddress.toString().toLowerCase(),
615
+ functionSelector: EMPIRE_SIGNAL_WITH_SIG_SELECTOR,
616
+ functionName: 'signalWithSig (empire)',
617
+ },
618
+ {
619
+ address: slashingProposerAddress.toString().toLowerCase(),
620
+ functionSelector: EMPIRE_SUBMIT_ROUND_WINNER_SELECTOR,
621
+ functionName: 'submitRoundWinner',
622
+ },
623
+ );
624
+
625
+ // Tally calls
626
+ calls.push(
627
+ {
628
+ address: slashingProposerAddress.toString().toLowerCase(),
629
+ functionSelector: TALLY_VOTE_SELECTOR,
630
+ functionName: 'vote',
631
+ },
632
+ {
633
+ address: slashingProposerAddress.toString().toLowerCase(),
634
+ functionSelector: TALLY_EXECUTE_ROUND_SELECTOR,
635
+ functionName: 'executeRound',
636
+ },
637
+ );
638
+ }
639
+
640
+ return calls;
641
+ }