@aztec/archiver 0.0.1-commit.9b94fc1 → 0.0.1-commit.9badcec54

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 (213) hide show
  1. package/README.md +162 -22
  2. package/dest/archiver.d.ts +140 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +750 -0
  5. package/dest/config.d.ts +30 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +24 -7
  8. package/dest/errors.d.ts +65 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +91 -0
  11. package/dest/factory.d.ts +8 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +99 -15
  14. package/dest/index.d.ts +11 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +9 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +152 -0
  23. package/dest/l1/calldata_retriever.d.ts +135 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +403 -0
  26. package/dest/l1/data_retrieval.d.ts +88 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +87 -160
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +149 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_trace.d.ts +32 -0
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/l1/validate_trace.js +154 -0
  44. package/dest/modules/data_source_base.d.ts +91 -0
  45. package/dest/modules/data_source_base.d.ts.map +1 -0
  46. package/dest/modules/data_source_base.js +222 -0
  47. package/dest/modules/data_store_updater.d.ts +86 -0
  48. package/dest/modules/data_store_updater.d.ts.map +1 -0
  49. package/dest/modules/data_store_updater.js +333 -0
  50. package/dest/modules/instrumentation.d.ts +52 -0
  51. package/dest/modules/instrumentation.d.ts.map +1 -0
  52. package/dest/modules/instrumentation.js +138 -0
  53. package/dest/modules/l1_synchronizer.d.ts +73 -0
  54. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  55. package/dest/modules/l1_synchronizer.js +1154 -0
  56. package/dest/modules/validation.d.ts +17 -0
  57. package/dest/modules/validation.d.ts.map +1 -0
  58. package/dest/{archiver → modules}/validation.js +9 -3
  59. package/dest/store/block_store.d.ts +230 -0
  60. package/dest/store/block_store.d.ts.map +1 -0
  61. package/dest/store/block_store.js +942 -0
  62. package/dest/store/contract_class_store.d.ts +17 -0
  63. package/dest/store/contract_class_store.d.ts.map +1 -0
  64. package/dest/store/contract_class_store.js +64 -0
  65. package/dest/store/contract_instance_store.d.ts +24 -0
  66. package/dest/store/contract_instance_store.d.ts.map +1 -0
  67. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +7 -3
  68. package/dest/store/kv_archiver_store.d.ts +377 -0
  69. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  70. package/dest/store/kv_archiver_store.js +494 -0
  71. package/dest/store/l2_tips_cache.d.ts +20 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +109 -0
  74. package/dest/store/log_store.d.ts +57 -0
  75. package/dest/store/log_store.d.ts.map +1 -0
  76. package/dest/store/log_store.js +531 -0
  77. package/dest/store/message_store.d.ts +44 -0
  78. package/dest/store/message_store.d.ts.map +1 -0
  79. package/dest/{archiver/kv_archiver_store → store}/message_store.js +36 -23
  80. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  81. package/dest/structs/data_retrieval.d.ts.map +1 -0
  82. package/dest/structs/inbox_message.d.ts +15 -0
  83. package/dest/structs/inbox_message.d.ts.map +1 -0
  84. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  85. package/dest/structs/published.d.ts +2 -0
  86. package/dest/structs/published.d.ts.map +1 -0
  87. package/dest/test/fake_l1_state.d.ts +210 -0
  88. package/dest/test/fake_l1_state.d.ts.map +1 -0
  89. package/dest/test/fake_l1_state.js +490 -0
  90. package/dest/test/index.d.ts +2 -1
  91. package/dest/test/index.d.ts.map +1 -1
  92. package/dest/test/index.js +4 -1
  93. package/dest/test/mock_archiver.d.ts +16 -8
  94. package/dest/test/mock_archiver.d.ts.map +1 -1
  95. package/dest/test/mock_archiver.js +19 -14
  96. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  97. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  98. package/dest/test/mock_l1_to_l2_message_source.js +23 -12
  99. package/dest/test/mock_l2_block_source.d.ts +59 -20
  100. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  101. package/dest/test/mock_l2_block_source.js +276 -85
  102. package/dest/test/mock_structs.d.ts +83 -4
  103. package/dest/test/mock_structs.d.ts.map +1 -1
  104. package/dest/test/mock_structs.js +157 -11
  105. package/dest/test/noop_l1_archiver.d.ts +26 -0
  106. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  107. package/dest/test/noop_l1_archiver.js +71 -0
  108. package/package.json +20 -20
  109. package/src/archiver.ts +510 -0
  110. package/src/{archiver/config.ts → config.ts} +37 -14
  111. package/src/errors.ts +146 -0
  112. package/src/factory.ts +154 -17
  113. package/src/index.ts +11 -3
  114. package/src/interfaces.ts +9 -0
  115. package/src/l1/README.md +55 -0
  116. package/src/l1/bin/retrieve-calldata.ts +194 -0
  117. package/src/l1/calldata_retriever.ts +512 -0
  118. package/src/{archiver → l1}/data_retrieval.ts +146 -233
  119. package/src/l1/debug_tx.ts +99 -0
  120. package/src/l1/spire_proposer.ts +152 -0
  121. package/src/l1/trace_tx.ts +128 -0
  122. package/src/l1/types.ts +13 -0
  123. package/src/l1/validate_trace.ts +229 -0
  124. package/src/modules/data_source_base.ts +347 -0
  125. package/src/modules/data_store_updater.ts +437 -0
  126. package/src/modules/instrumentation.ts +196 -0
  127. package/src/modules/l1_synchronizer.ts +961 -0
  128. package/src/{archiver → modules}/validation.ts +13 -8
  129. package/src/store/block_store.ts +1245 -0
  130. package/src/store/contract_class_store.ts +82 -0
  131. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +10 -7
  132. package/src/store/kv_archiver_store.ts +713 -0
  133. package/src/store/l2_tips_cache.ts +134 -0
  134. package/src/store/log_store.ts +733 -0
  135. package/src/{archiver/kv_archiver_store → store}/message_store.ts +48 -28
  136. package/src/{archiver/structs → structs}/inbox_message.ts +7 -7
  137. package/src/{archiver/structs → structs}/published.ts +0 -1
  138. package/src/test/fake_l1_state.ts +747 -0
  139. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  140. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  141. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  142. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  143. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  144. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  145. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  146. package/src/test/index.ts +4 -0
  147. package/src/test/mock_archiver.ts +23 -16
  148. package/src/test/mock_l1_to_l2_message_source.ts +19 -11
  149. package/src/test/mock_l2_block_source.ts +346 -93
  150. package/src/test/mock_structs.ts +289 -13
  151. package/src/test/noop_l1_archiver.ts +114 -0
  152. package/dest/archiver/archiver.d.ts +0 -287
  153. package/dest/archiver/archiver.d.ts.map +0 -1
  154. package/dest/archiver/archiver.js +0 -1408
  155. package/dest/archiver/archiver_store.d.ts +0 -255
  156. package/dest/archiver/archiver_store.d.ts.map +0 -1
  157. package/dest/archiver/archiver_store.js +0 -4
  158. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  159. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  160. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  161. package/dest/archiver/config.d.ts +0 -21
  162. package/dest/archiver/config.d.ts.map +0 -1
  163. package/dest/archiver/data_retrieval.d.ts +0 -79
  164. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  165. package/dest/archiver/errors.d.ts +0 -12
  166. package/dest/archiver/errors.d.ts.map +0 -1
  167. package/dest/archiver/errors.js +0 -17
  168. package/dest/archiver/index.d.ts +0 -7
  169. package/dest/archiver/index.d.ts.map +0 -1
  170. package/dest/archiver/index.js +0 -4
  171. package/dest/archiver/instrumentation.d.ts +0 -35
  172. package/dest/archiver/instrumentation.d.ts.map +0 -1
  173. package/dest/archiver/instrumentation.js +0 -140
  174. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  175. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  176. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  177. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  178. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  179. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  180. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  181. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  182. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  183. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  184. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  185. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  186. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  187. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  188. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  189. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  190. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  191. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  192. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  193. package/dest/archiver/structs/published.d.ts +0 -3
  194. package/dest/archiver/structs/published.d.ts.map +0 -1
  195. package/dest/archiver/validation.d.ts +0 -17
  196. package/dest/archiver/validation.d.ts.map +0 -1
  197. package/dest/rpc/index.d.ts +0 -9
  198. package/dest/rpc/index.d.ts.map +0 -1
  199. package/dest/rpc/index.js +0 -15
  200. package/src/archiver/archiver.ts +0 -1858
  201. package/src/archiver/archiver_store.ts +0 -305
  202. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  203. package/src/archiver/errors.ts +0 -26
  204. package/src/archiver/index.ts +0 -6
  205. package/src/archiver/instrumentation.ts +0 -187
  206. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  207. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  208. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  209. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  210. package/src/rpc/index.ts +0 -16
  211. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  212. /package/dest/{archiver/structs → structs}/published.js +0 -0
  213. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -0,0 +1,512 @@
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 { LruSet } from '@aztec/foundation/collection';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
6
+ import { EthAddress } from '@aztec/foundation/eth-address';
7
+ import type { Logger } from '@aztec/foundation/log';
8
+ import { RollupAbi } from '@aztec/l1-artifacts';
9
+ import { CommitteeAttestation } from '@aztec/stdlib/block';
10
+ import { ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
11
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
12
+
13
+ import {
14
+ type AbiParameter,
15
+ type Hex,
16
+ type Transaction,
17
+ decodeFunctionData,
18
+ encodeAbiParameters,
19
+ hexToBytes,
20
+ keccak256,
21
+ multicall3Abi,
22
+ toFunctionSelector,
23
+ } from 'viem';
24
+
25
+ import type { ArchiverInstrumentation } from '../modules/instrumentation.js';
26
+ import { getSuccessfulCallsFromDebug } from './debug_tx.js';
27
+ import { getCallsFromSpireProposer } from './spire_proposer.js';
28
+ import { getSuccessfulCallsFromTrace } from './trace_tx.js';
29
+ import type { CallInfo } from './types.js';
30
+
31
+ /** Decoded checkpoint data from a propose calldata. */
32
+ type CheckpointData = {
33
+ checkpointNumber: CheckpointNumber;
34
+ archiveRoot: Fr;
35
+ header: CheckpointHeader;
36
+ attestations: CommitteeAttestation[];
37
+ blockHash: string;
38
+ feeAssetPriceModifier: bigint;
39
+ };
40
+
41
+ /**
42
+ * Extracts calldata to the `propose` method of the rollup contract from an L1 transaction
43
+ * in order to reconstruct an L2 block header. Uses hash matching against expected hashes
44
+ * from the CheckpointProposed event to verify the correct propose calldata.
45
+ */
46
+ export class CalldataRetriever {
47
+ /** Tx hashes we've already logged for trace+debug failure (log once per tx per process). */
48
+ private static readonly traceFailureWarnedTxHashes = new LruSet<string>(1000);
49
+
50
+ /** Clears the trace-failure warned set. For testing only. */
51
+ static resetTraceFailureWarnedForTesting(): void {
52
+ CalldataRetriever.traceFailureWarnedTxHashes.clear();
53
+ }
54
+
55
+ constructor(
56
+ private readonly publicClient: ViemPublicClient,
57
+ private readonly debugClient: ViemPublicDebugClient,
58
+ private readonly targetCommitteeSize: number,
59
+ private readonly instrumentation: ArchiverInstrumentation | undefined,
60
+ private readonly logger: Logger,
61
+ private readonly rollupAddress: EthAddress,
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 - 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<CheckpointData> {
82
+ this.logger.trace(`Fetching checkpoint ${checkpointNumber} from rollup tx ${txHash}`);
83
+ const tx = await this.publicClient.getTransaction({ hash: txHash });
84
+ return this.getCheckpointFromTx(tx, checkpointNumber, expectedHashes);
85
+ }
86
+
87
+ /** Gets checkpoint data from a transaction by trying decode strategies then falling back to trace. */
88
+ protected async getCheckpointFromTx(
89
+ tx: Transaction,
90
+ checkpointNumber: CheckpointNumber,
91
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
92
+ ): Promise<CheckpointData> {
93
+ // Try to decode as multicall3 with hash-verified matching
94
+ const multicall3Result = this.tryDecodeMulticall3(tx, expectedHashes, checkpointNumber, tx.blockHash!);
95
+ if (multicall3Result) {
96
+ this.logger.trace(`Decoded propose calldata from multicall3 for tx ${tx.hash}`);
97
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
98
+ return multicall3Result;
99
+ }
100
+
101
+ // Try to decode as direct propose call
102
+ const directResult = this.tryDecodeDirectPropose(tx, expectedHashes, checkpointNumber, tx.blockHash!);
103
+ if (directResult) {
104
+ this.logger.trace(`Decoded propose calldata from direct call for tx ${tx.hash}`);
105
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
106
+ return directResult;
107
+ }
108
+
109
+ // Try to decode as Spire Proposer multicall wrapper
110
+ const spireResult = await this.tryDecodeSpireProposer(tx, expectedHashes, checkpointNumber, tx.blockHash!);
111
+ if (spireResult) {
112
+ this.logger.trace(`Decoded propose calldata from Spire Proposer for tx ${tx.hash}`);
113
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to!, false);
114
+ return spireResult;
115
+ }
116
+
117
+ // Fall back to trace-based extraction
118
+ this.logger.warn(
119
+ `Failed to decode multicall3, direct propose, or Spire proposer for L1 tx ${tx.hash}, falling back to trace for checkpoint ${checkpointNumber}`,
120
+ );
121
+ this.instrumentation?.recordBlockProposalTxTarget(tx.to ?? EthAddress.ZERO.toString(), true);
122
+ const tracedCalldata = await this.extractCalldataViaTrace(tx.hash);
123
+ const tracedResult = this.tryDecodeAndVerifyPropose(
124
+ tracedCalldata,
125
+ expectedHashes,
126
+ checkpointNumber,
127
+ tx.blockHash!,
128
+ );
129
+ if (!tracedResult) {
130
+ throw new Error(`Hash mismatch for traced propose calldata in tx ${tx.hash} for checkpoint ${checkpointNumber}`);
131
+ }
132
+ return tracedResult;
133
+ }
134
+
135
+ /**
136
+ * Attempts to decode a transaction as a Spire Proposer multicall wrapper.
137
+ * If successful, iterates all wrapped calls and validates each as either multicall3
138
+ * or direct propose, verifying against expected hashes.
139
+ * @param tx - The transaction to decode
140
+ * @param expectedHashes - Expected hashes for hash-verified matching
141
+ * @param checkpointNumber - The checkpoint number
142
+ * @param blockHash - The L1 block hash
143
+ * @returns The checkpoint data if successfully decoded and validated, undefined otherwise
144
+ */
145
+ protected async tryDecodeSpireProposer(
146
+ tx: Transaction,
147
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
148
+ checkpointNumber: CheckpointNumber,
149
+ blockHash: Hex,
150
+ ): Promise<CheckpointData | undefined> {
151
+ // Try to decode as Spire Proposer multicall (extracts all wrapped calls)
152
+ const spireWrappedCalls = await getCallsFromSpireProposer(tx, this.publicClient, this.logger);
153
+ if (!spireWrappedCalls) {
154
+ return undefined;
155
+ }
156
+
157
+ this.logger.trace(`Decoded Spire Proposer wrapping for tx ${tx.hash}, ${spireWrappedCalls.length} inner call(s)`);
158
+
159
+ // Try each wrapped call as either multicall3 or direct propose
160
+ for (const spireWrappedCall of spireWrappedCalls) {
161
+ const wrappedTx = { to: spireWrappedCall.to, input: spireWrappedCall.data, hash: tx.hash };
162
+
163
+ const multicall3Result = this.tryDecodeMulticall3(wrappedTx, expectedHashes, checkpointNumber, blockHash);
164
+ if (multicall3Result) {
165
+ this.logger.trace(`Decoded propose calldata from Spire Proposer to multicall3 for tx ${tx.hash}`);
166
+ return multicall3Result;
167
+ }
168
+
169
+ const directResult = this.tryDecodeDirectPropose(wrappedTx, expectedHashes, checkpointNumber, blockHash);
170
+ if (directResult) {
171
+ this.logger.trace(`Decoded propose calldata from Spire Proposer to direct propose for tx ${tx.hash}`);
172
+ return directResult;
173
+ }
174
+ }
175
+
176
+ this.logger.warn(
177
+ `Spire Proposer wrapped calls could not be decoded as multicall3 or direct propose for tx ${tx.hash}`,
178
+ );
179
+ return undefined;
180
+ }
181
+
182
+ /**
183
+ * Attempts to decode transaction input as multicall3 and extract propose calldata.
184
+ * Finds all calls matching the rollup address and propose selector, then decodes
185
+ * and verifies each candidate against expected hashes from the CheckpointProposed event.
186
+ * @param tx - The transaction-like object with to, input, and hash
187
+ * @param expectedHashes - Expected hashes from CheckpointProposed event
188
+ * @param checkpointNumber - The checkpoint number
189
+ * @param blockHash - The L1 block hash
190
+ * @returns The checkpoint data if successfully validated, undefined otherwise
191
+ */
192
+ protected tryDecodeMulticall3(
193
+ tx: { to: Hex | null | undefined; input: Hex; hash: Hex },
194
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
195
+ checkpointNumber: CheckpointNumber,
196
+ blockHash: Hex,
197
+ ): CheckpointData | undefined {
198
+ const txHash = tx.hash;
199
+
200
+ try {
201
+ // Check if transaction is to Multicall3 address
202
+ if (!tx.to || !EthAddress.areEqual(tx.to, MULTI_CALL_3_ADDRESS)) {
203
+ this.logger.debug(`Transaction is not to Multicall3 address (to: ${tx.to})`, { txHash, to: tx.to });
204
+ return undefined;
205
+ }
206
+
207
+ // Try to decode as multicall3 aggregate3 call
208
+ const { functionName: multicall3Fn, args: multicall3Args } = decodeFunctionData({
209
+ abi: multicall3Abi,
210
+ data: tx.input,
211
+ });
212
+
213
+ // If not aggregate3, return undefined (not a multicall3 transaction)
214
+ if (multicall3Fn !== 'aggregate3') {
215
+ this.logger.warn(`Transaction is not multicall3 aggregate3 (got ${multicall3Fn})`, { txHash });
216
+ return undefined;
217
+ }
218
+
219
+ if (multicall3Args.length !== 1) {
220
+ this.logger.warn(`Unexpected number of arguments for multicall3 (got ${multicall3Args.length})`, { txHash });
221
+ return undefined;
222
+ }
223
+
224
+ const [calls] = multicall3Args;
225
+
226
+ // Find all calls matching rollup address + propose selector
227
+ const rollupAddressLower = this.rollupAddress.toString().toLowerCase();
228
+ const proposeSelectorLower = PROPOSE_SELECTOR.toLowerCase();
229
+ const candidates: Hex[] = [];
230
+
231
+ for (const call of calls) {
232
+ const addr = call.target.toLowerCase();
233
+ const callData = call.callData;
234
+
235
+ if (callData.length < 10) {
236
+ continue;
237
+ }
238
+
239
+ const selector = callData.slice(0, 10).toLowerCase();
240
+ if (addr === rollupAddressLower && selector === proposeSelectorLower) {
241
+ candidates.push(callData);
242
+ }
243
+ }
244
+
245
+ if (candidates.length === 0) {
246
+ this.logger.debug(`No propose candidates found in multicall3`, { txHash });
247
+ return undefined;
248
+ }
249
+
250
+ // Decode, verify, and build for each candidate
251
+ const verified: CheckpointData[] = [];
252
+ for (const candidate of candidates) {
253
+ const result = this.tryDecodeAndVerifyPropose(candidate, expectedHashes, checkpointNumber, blockHash);
254
+ if (result) {
255
+ verified.push(result);
256
+ }
257
+ }
258
+
259
+ if (verified.length === 1) {
260
+ this.logger.trace(`Verified single propose candidate via hash matching`, { txHash });
261
+ return verified[0];
262
+ }
263
+
264
+ if (verified.length > 1) {
265
+ this.logger.warn(
266
+ `Multiple propose candidates verified (${verified.length}), returning first (identical data)`,
267
+ { txHash },
268
+ );
269
+ return verified[0];
270
+ }
271
+
272
+ this.logger.debug(`No candidates verified against expected hashes`, { txHash });
273
+ return undefined;
274
+ } catch (err) {
275
+ // Any decoding error triggers fallback to trace
276
+ this.logger.warn(`Failed to decode multicall3: ${err}`, { txHash });
277
+ return undefined;
278
+ }
279
+ }
280
+
281
+ /**
282
+ * Attempts to decode transaction as a direct propose call to the rollup contract.
283
+ * Decodes, verifies hashes, and builds checkpoint data in a single pass.
284
+ * @param tx - The transaction-like object with to, input, and hash
285
+ * @param expectedHashes - Expected hashes from CheckpointProposed event
286
+ * @param checkpointNumber - The checkpoint number
287
+ * @param blockHash - The L1 block hash
288
+ * @returns The checkpoint data if successfully validated, undefined otherwise
289
+ */
290
+ protected tryDecodeDirectPropose(
291
+ tx: { to: Hex | null | undefined; input: Hex; hash: Hex },
292
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
293
+ checkpointNumber: CheckpointNumber,
294
+ blockHash: Hex,
295
+ ): CheckpointData | undefined {
296
+ const txHash = tx.hash;
297
+ try {
298
+ // Check if transaction is to the rollup address
299
+ if (!tx.to || !EthAddress.areEqual(tx.to, this.rollupAddress)) {
300
+ this.logger.debug(`Transaction is not to rollup address (to: ${tx.to})`, { txHash });
301
+ return undefined;
302
+ }
303
+
304
+ // Validate it's a propose call before full decode+verify
305
+ const { functionName } = decodeFunctionData({ abi: RollupAbi, data: tx.input });
306
+ if (functionName !== 'propose') {
307
+ this.logger.warn(`Transaction to rollup is not propose (got ${functionName})`, { txHash });
308
+ return undefined;
309
+ }
310
+
311
+ // Decode, verify hashes, and build checkpoint data
312
+ this.logger.trace(`Validated direct propose call to rollup`, { txHash });
313
+ return this.tryDecodeAndVerifyPropose(tx.input, expectedHashes, checkpointNumber, blockHash);
314
+ } catch (err) {
315
+ // Any decoding error means it's not a valid propose call
316
+ this.logger.warn(`Failed to decode as direct propose: ${err}`, { txHash });
317
+ return undefined;
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Uses debug/trace RPC to extract the actual calldata from the successful propose call.
323
+ * This is the definitive fallback that works for any transaction pattern.
324
+ * Tries trace_transaction first, then falls back to debug_traceTransaction.
325
+ * @param txHash - The transaction hash to trace
326
+ * @returns The propose calldata from the successful call
327
+ */
328
+ protected async extractCalldataViaTrace(txHash: Hex): Promise<Hex> {
329
+ const rollupAddress = this.rollupAddress;
330
+ const selector = PROPOSE_SELECTOR;
331
+
332
+ let calls: CallInfo[];
333
+ try {
334
+ // Try trace_transaction first (using Parity/OpenEthereum/Erigon RPC)
335
+ this.logger.debug(`Attempting to trace transaction ${txHash} using trace_transaction`);
336
+ calls = await getSuccessfulCallsFromTrace(this.debugClient, txHash, rollupAddress, selector, this.logger);
337
+ this.logger.debug(`Successfully traced using trace_transaction, found ${calls.length} calls`);
338
+ } catch (err) {
339
+ const traceError = err instanceof Error ? err : new Error(String(err));
340
+ this.logger.verbose(`Failed trace_transaction for ${txHash}: ${traceError.message}`);
341
+ this.logger.debug(`Trace failure details for ${txHash}`, { traceError });
342
+
343
+ try {
344
+ // Fall back to debug_traceTransaction (Geth RPC)
345
+ this.logger.debug(`Attempting to trace transaction ${txHash} using debug_traceTransaction`);
346
+ calls = await getSuccessfulCallsFromDebug(this.debugClient, txHash, rollupAddress, selector, this.logger);
347
+ this.logger.debug(`Successfully traced using debug_traceTransaction, found ${calls.length} calls`);
348
+ } catch (debugErr) {
349
+ const debugError = debugErr instanceof Error ? debugErr : new Error(String(debugErr));
350
+ // Log once per tx so we don't spam on every sync cycle when sync point doesn't advance
351
+ if (!CalldataRetriever.traceFailureWarnedTxHashes.has(txHash)) {
352
+ CalldataRetriever.traceFailureWarnedTxHashes.add(txHash);
353
+ this.logger.warn(
354
+ `Cannot decode L1 tx ${txHash}: trace and debug RPC failed or unavailable. ` +
355
+ `trace_transaction: ${traceError.message}; debug_traceTransaction: ${debugError.message}`,
356
+ );
357
+ }
358
+ // Full error objects can be very long; keep at debug only
359
+ this.logger.debug(`Trace/debug failure details for tx ${txHash}`, {
360
+ traceError,
361
+ debugError,
362
+ txHash,
363
+ });
364
+ throw new Error(`Failed to trace transaction ${txHash} to extract propose calldata`);
365
+ }
366
+ }
367
+
368
+ // Validate exactly ONE successful propose call
369
+ if (calls.length === 0) {
370
+ throw new Error(`No successful propose calls found in transaction ${txHash}`);
371
+ }
372
+
373
+ if (calls.length > 1) {
374
+ throw new Error(`Multiple successful propose calls found in transaction ${txHash} (${calls.length})`);
375
+ }
376
+
377
+ // Return the calldata from the single successful propose call
378
+ return calls[0].input;
379
+ }
380
+
381
+ /**
382
+ * Decodes propose calldata, verifies against expected hashes, and builds checkpoint data.
383
+ * Returns undefined on decode errors or hash mismatches (soft failure for try-based callers).
384
+ * @param proposeCalldata - The propose function calldata
385
+ * @param expectedHashes - Expected hashes from the CheckpointProposed event
386
+ * @param checkpointNumber - The checkpoint number
387
+ * @param blockHash - The L1 block hash
388
+ * @returns The decoded checkpoint data, or undefined on failure
389
+ */
390
+ protected tryDecodeAndVerifyPropose(
391
+ proposeCalldata: Hex,
392
+ expectedHashes: { attestationsHash: Hex; payloadDigest: Hex },
393
+ checkpointNumber: CheckpointNumber,
394
+ blockHash: Hex,
395
+ ): CheckpointData | undefined {
396
+ try {
397
+ const { functionName, args } = decodeFunctionData({ abi: RollupAbi, data: proposeCalldata });
398
+ if (functionName !== 'propose') {
399
+ return undefined;
400
+ }
401
+
402
+ const [decodedArgs, packedAttestations] = args! as readonly [
403
+ { archive: Hex; oracleInput: { feeAssetPriceModifier: bigint }; header: ViemHeader },
404
+ ViemCommitteeAttestations,
405
+ ...unknown[],
406
+ ];
407
+
408
+ // Verify attestationsHash
409
+ const computedAttestationsHash = this.computeAttestationsHash(packedAttestations);
410
+ if (
411
+ !Buffer.from(hexToBytes(computedAttestationsHash)).equals(
412
+ Buffer.from(hexToBytes(expectedHashes.attestationsHash)),
413
+ )
414
+ ) {
415
+ this.logger.warn(`Attestations hash mismatch during verification`, {
416
+ computed: computedAttestationsHash,
417
+ expected: expectedHashes.attestationsHash,
418
+ });
419
+ return undefined;
420
+ }
421
+
422
+ // Verify payloadDigest
423
+ const header = CheckpointHeader.fromViem(decodedArgs.header);
424
+ const archiveRoot = new Fr(Buffer.from(hexToBytes(decodedArgs.archive)));
425
+ const feeAssetPriceModifier = decodedArgs.oracleInput.feeAssetPriceModifier;
426
+ const computedPayloadDigest = this.computePayloadDigest(header, archiveRoot, feeAssetPriceModifier);
427
+ if (
428
+ !Buffer.from(hexToBytes(computedPayloadDigest)).equals(Buffer.from(hexToBytes(expectedHashes.payloadDigest)))
429
+ ) {
430
+ this.logger.warn(`Payload digest mismatch during verification`, {
431
+ computed: computedPayloadDigest,
432
+ expected: expectedHashes.payloadDigest,
433
+ });
434
+ return undefined;
435
+ }
436
+
437
+ const attestations = CommitteeAttestation.fromPacked(packedAttestations, this.targetCommitteeSize);
438
+
439
+ this.logger.trace(`Validated and decoded propose calldata for checkpoint ${checkpointNumber}`, {
440
+ checkpointNumber,
441
+ archive: decodedArgs.archive,
442
+ header: decodedArgs.header,
443
+ l1BlockHash: blockHash,
444
+ attestations,
445
+ packedAttestations,
446
+ targetCommitteeSize: this.targetCommitteeSize,
447
+ });
448
+
449
+ return {
450
+ checkpointNumber,
451
+ archiveRoot,
452
+ header,
453
+ attestations,
454
+ blockHash,
455
+ feeAssetPriceModifier,
456
+ };
457
+ } catch {
458
+ return undefined;
459
+ }
460
+ }
461
+
462
+ /** Computes the keccak256 hash of ABI-encoded CommitteeAttestations. */
463
+ private computeAttestationsHash(packedAttestations: ViemCommitteeAttestations): Hex {
464
+ return keccak256(encodeAbiParameters([this.getCommitteeAttestationsStructDef()], [packedAttestations]));
465
+ }
466
+
467
+ /** Computes the keccak256 payload digest from the checkpoint header, archive root, and fee asset price modifier. */
468
+ private computePayloadDigest(header: CheckpointHeader, archiveRoot: Fr, feeAssetPriceModifier: bigint): Hex {
469
+ const consensusPayload = new ConsensusPayload(header, archiveRoot, feeAssetPriceModifier);
470
+ const payloadToSign = consensusPayload.getPayloadToSign(SignatureDomainSeparator.checkpointAttestation);
471
+ return keccak256(payloadToSign);
472
+ }
473
+
474
+ /**
475
+ * Extracts the CommitteeAttestations struct definition from RollupAbi.
476
+ * Finds the _attestations parameter by name in the propose function.
477
+ */
478
+ private getCommitteeAttestationsStructDef(): AbiParameter {
479
+ const proposeFunction = RollupAbi.find(item => item.type === 'function' && item.name === 'propose') as
480
+ | { type: 'function'; name: string; inputs: readonly AbiParameter[] }
481
+ | undefined;
482
+
483
+ if (!proposeFunction) {
484
+ throw new Error('propose function not found in RollupAbi');
485
+ }
486
+
487
+ // Find the _attestations parameter by name, not by index
488
+ const attestationsParam = proposeFunction.inputs.find(param => param.name === '_attestations');
489
+
490
+ if (!attestationsParam) {
491
+ throw new Error('_attestations parameter not found in propose function');
492
+ }
493
+
494
+ if (attestationsParam.type !== 'tuple') {
495
+ throw new Error(`Expected _attestations parameter to be a tuple, got ${attestationsParam.type}`);
496
+ }
497
+
498
+ // Extract the tuple components (struct fields)
499
+ const tupleParam = attestationsParam as unknown as {
500
+ type: 'tuple';
501
+ components?: readonly AbiParameter[];
502
+ };
503
+
504
+ return {
505
+ type: 'tuple',
506
+ components: tupleParam.components || [],
507
+ } as AbiParameter;
508
+ }
509
+ }
510
+
511
+ /** Function selector for the `propose` method of the rollup contract. */
512
+ const PROPOSE_SELECTOR = toFunctionSelector(RollupAbi.find(x => x.type === 'function' && x.name === 'propose')!);