@aztec/archiver 0.0.1-commit.9593d84 → 0.0.1-commit.96bb3f7

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 (128) hide show
  1. package/README.md +14 -14
  2. package/dest/archiver/archiver.d.ts +105 -85
  3. package/dest/archiver/archiver.d.ts.map +1 -1
  4. package/dest/archiver/archiver.js +949 -255
  5. package/dest/archiver/archiver_store.d.ts +109 -49
  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 +1871 -390
  10. package/dest/archiver/config.d.ts +5 -4
  11. package/dest/archiver/config.d.ts.map +1 -1
  12. package/dest/archiver/config.js +12 -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 +3 -1
  19. package/dest/archiver/instrumentation.d.ts.map +1 -1
  20. package/dest/archiver/instrumentation.js +22 -59
  21. package/dest/archiver/kv_archiver_store/block_store.d.ts +60 -20
  22. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +1 -1
  23. package/dest/archiver/kv_archiver_store/block_store.js +345 -89
  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 +49 -58
  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 +68 -48
  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/{data_retrieval.js → l1/data_retrieval.js} +52 -107
  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/inbox_message.d.ts +4 -4
  63. package/dest/archiver/structs/inbox_message.d.ts.map +1 -1
  64. package/dest/archiver/structs/inbox_message.js +6 -5
  65. package/dest/archiver/structs/published.d.ts +1 -2
  66. package/dest/archiver/structs/published.d.ts.map +1 -1
  67. package/dest/archiver/validation.d.ts +4 -4
  68. package/dest/archiver/validation.d.ts.map +1 -1
  69. package/dest/archiver/validation.js +1 -1
  70. package/dest/factory.d.ts +2 -2
  71. package/dest/factory.d.ts.map +1 -1
  72. package/dest/factory.js +4 -3
  73. package/dest/index.d.ts +2 -2
  74. package/dest/index.d.ts.map +1 -1
  75. package/dest/index.js +1 -1
  76. package/dest/test/mock_archiver.d.ts +16 -8
  77. package/dest/test/mock_archiver.d.ts.map +1 -1
  78. package/dest/test/mock_archiver.js +19 -14
  79. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  80. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  81. package/dest/test/mock_l1_to_l2_message_source.js +21 -11
  82. package/dest/test/mock_l2_block_source.d.ts +23 -8
  83. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  84. package/dest/test/mock_l2_block_source.js +95 -35
  85. package/dest/test/mock_structs.d.ts +3 -2
  86. package/dest/test/mock_structs.d.ts.map +1 -1
  87. package/dest/test/mock_structs.js +9 -8
  88. package/package.json +17 -16
  89. package/src/archiver/archiver.ts +751 -344
  90. package/src/archiver/archiver_store.ts +123 -48
  91. package/src/archiver/archiver_store_test_suite.ts +1943 -365
  92. package/src/archiver/config.ts +17 -12
  93. package/src/archiver/errors.ts +64 -0
  94. package/src/archiver/index.ts +1 -1
  95. package/src/archiver/instrumentation.ts +24 -59
  96. package/src/archiver/kv_archiver_store/block_store.ts +475 -106
  97. package/src/archiver/kv_archiver_store/contract_class_store.ts +1 -1
  98. package/src/archiver/kv_archiver_store/contract_instance_store.ts +1 -1
  99. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +92 -72
  100. package/src/archiver/kv_archiver_store/log_store.ts +209 -99
  101. package/src/archiver/kv_archiver_store/message_store.ts +21 -18
  102. package/src/archiver/l1/README.md +98 -0
  103. package/src/archiver/l1/bin/retrieve-calldata.ts +182 -0
  104. package/src/archiver/l1/calldata_retriever.ts +641 -0
  105. package/src/archiver/{data_retrieval.ts → l1/data_retrieval.ts} +101 -165
  106. package/src/archiver/l1/debug_tx.ts +99 -0
  107. package/src/archiver/l1/spire_proposer.ts +160 -0
  108. package/src/archiver/l1/trace_tx.ts +128 -0
  109. package/src/archiver/l1/types.ts +13 -0
  110. package/src/archiver/l1/validate_trace.ts +211 -0
  111. package/src/archiver/structs/inbox_message.ts +8 -8
  112. package/src/archiver/structs/published.ts +0 -1
  113. package/src/archiver/validation.ts +6 -6
  114. package/src/factory.ts +4 -3
  115. package/src/index.ts +1 -1
  116. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  117. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  118. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  119. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  120. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  121. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  122. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  123. package/src/test/mock_archiver.ts +22 -16
  124. package/src/test/mock_l1_to_l2_message_source.ts +18 -11
  125. package/src/test/mock_l2_block_source.ts +115 -37
  126. package/src/test/mock_structs.ts +10 -9
  127. package/dest/archiver/data_retrieval.d.ts +0 -79
  128. package/dest/archiver/data_retrieval.d.ts.map +0 -1
@@ -1,3 +1,4 @@
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
1
2
  import {
2
3
  BlobDeserializationError,
3
4
  type CheckpointBlobData,
@@ -5,23 +6,17 @@ import {
5
6
  decodeCheckpointBlobDataFromBlobs,
6
7
  encodeBlockBlobData,
7
8
  } from '@aztec/blob-lib';
8
- import type { BlobSinkClientInterface } from '@aztec/blob-sink/client';
9
- import type {
10
- EpochProofPublicInputArgs,
11
- ViemClient,
12
- ViemCommitteeAttestations,
13
- ViemHeader,
14
- ViemPublicClient,
15
- } from '@aztec/ethereum';
9
+ import type { EpochProofPublicInputArgs } from '@aztec/ethereum/contracts';
10
+ import type { ViemClient, ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum/types';
16
11
  import { asyncPool } from '@aztec/foundation/async-pool';
12
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
17
13
  import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
18
- import type { EthAddress } from '@aztec/foundation/eth-address';
19
- import type { ViemSignature } from '@aztec/foundation/eth-signature';
20
- import { Fr } from '@aztec/foundation/fields';
14
+ import { Fr } from '@aztec/foundation/curves/bn254';
15
+ import { EthAddress } from '@aztec/foundation/eth-address';
21
16
  import { type Logger, createLogger } from '@aztec/foundation/log';
22
17
  import { type InboxAbi, RollupAbi } from '@aztec/l1-artifacts';
23
18
  import { Body, CommitteeAttestation, L2BlockNew } from '@aztec/stdlib/block';
24
- import { Checkpoint, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
19
+ import { Checkpoint, L1PublishedData, PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
25
20
  import { Proof } from '@aztec/stdlib/proofs';
26
21
  import { CheckpointHeader } from '@aztec/stdlib/rollup';
27
22
  import { AppendOnlyTreeSnapshot } from '@aztec/stdlib/trees';
@@ -34,16 +29,16 @@ import {
34
29
  decodeFunctionData,
35
30
  getAbiItem,
36
31
  hexToBytes,
37
- multicall3Abi,
38
32
  } from 'viem';
39
33
 
40
- import { NoBlobBodiesFoundError } from './errors.js';
41
- import type { DataRetrieval } from './structs/data_retrieval.js';
42
- import type { InboxMessage } from './structs/inbox_message.js';
43
- import type { L1PublishedData } from './structs/published.js';
34
+ import { NoBlobBodiesFoundError } from '../errors.js';
35
+ import type { ArchiverInstrumentation } from '../instrumentation.js';
36
+ import type { DataRetrieval } from '../structs/data_retrieval.js';
37
+ import type { InboxMessage } from '../structs/inbox_message.js';
38
+ import { CalldataRetriever } from './calldata_retriever.js';
44
39
 
45
40
  export type RetrievedCheckpoint = {
46
- checkpointNumber: number;
41
+ checkpointNumber: CheckpointNumber;
47
42
  archiveRoot: Fr;
48
43
  header: CheckpointHeader;
49
44
  checkpointBlobData: CheckpointBlobData;
@@ -71,8 +66,8 @@ export async function retrievedToPublishedCheckpoint({
71
66
  .slice(1)
72
67
  .concat([archiveRoot]);
73
68
 
74
- // `blocksBlobData` is created from `decodeCheckpointBlobDataFromBlobs`. An error will be thrown if it can't read a
75
- // field for the `l1ToL2MessageRoot` of the first block. So below we can safely assume it exists:
69
+ // An error will be thrown from `decodeCheckpointBlobDataFromBlobs` if it can't read a field for the
70
+ // `l1ToL2MessageRoot` of the first block. So below we can safely assume it exists:
76
71
  const l1toL2MessageTreeRoot = blocksBlobData[0].l1ToL2MessageRoot!;
77
72
 
78
73
  const spongeBlob = SpongeBlob.init();
@@ -126,7 +121,7 @@ export async function retrievedToPublishedCheckpoint({
126
121
 
127
122
  const newArchive = new AppendOnlyTreeSnapshot(newArchiveRoots[i], l2BlockNumber + 1);
128
123
 
129
- l2Blocks.push(new L2BlockNew(newArchive, header, body));
124
+ l2Blocks.push(new L2BlockNew(newArchive, header, body, checkpointNumber, i));
130
125
  }
131
126
 
132
127
  const lastBlock = l2Blocks.at(-1)!;
@@ -142,20 +137,33 @@ export async function retrievedToPublishedCheckpoint({
142
137
 
143
138
  /**
144
139
  * Fetches new checkpoints.
140
+ * @param rollup - The rollup contract instance.
145
141
  * @param publicClient - The viem public client to use for transaction retrieval.
146
- * @param rollupAddress - The address of the rollup contract.
142
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
143
+ * @param blobClient - The blob client client for fetching blob data.
147
144
  * @param searchStartBlock - The block number to use for starting the search.
148
145
  * @param searchEndBlock - The highest block number that we should search up to.
149
- * @param expectedNextL2BlockNum - The next L2 block number that we expect to find.
150
- * @returns An array of block; as well as the next eth block to search from.
146
+ * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
147
+ * @param instrumentation - The archiver instrumentation instance.
148
+ * @param logger - The logger instance.
149
+ * @param isHistoricalSync - Whether this is a historical sync.
150
+ * @returns An array of retrieved checkpoints.
151
151
  */
152
152
  export async function retrieveCheckpointsFromRollup(
153
153
  rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>,
154
154
  publicClient: ViemPublicClient,
155
- blobSinkClient: BlobSinkClientInterface,
155
+ debugClient: ViemPublicDebugClient,
156
+ blobClient: BlobClientInterface,
156
157
  searchStartBlock: bigint,
157
158
  searchEndBlock: bigint,
159
+ contractAddresses: {
160
+ governanceProposerAddress: EthAddress;
161
+ slashFactoryAddress?: EthAddress;
162
+ slashingProposerAddress: EthAddress;
163
+ },
164
+ instrumentation: ArchiverInstrumentation,
158
165
  logger: Logger = createLogger('archiver'),
166
+ isHistoricalSync: boolean = false,
159
167
  ): Promise<RetrievedCheckpoint[]> {
160
168
  const retrievedCheckpoints: RetrievedCheckpoint[] = [];
161
169
 
@@ -200,10 +208,14 @@ export async function retrieveCheckpointsFromRollup(
200
208
  const newCheckpoints = await processCheckpointProposedLogs(
201
209
  rollup,
202
210
  publicClient,
203
- blobSinkClient,
211
+ debugClient,
212
+ blobClient,
204
213
  checkpointProposedLogs,
205
214
  rollupConstants,
215
+ contractAddresses,
216
+ instrumentation,
206
217
  logger,
218
+ isHistoricalSync,
207
219
  );
208
220
  retrievedCheckpoints.push(...newCheckpoints);
209
221
  searchStartBlock = lastLog.blockNumber! + 1n;
@@ -215,46 +227,80 @@ export async function retrieveCheckpointsFromRollup(
215
227
 
216
228
  /**
217
229
  * Processes newly received CheckpointProposed logs.
218
- * @param rollup - The rollup contract
230
+ * @param rollup - The rollup contract instance.
219
231
  * @param publicClient - The viem public client to use for transaction retrieval.
232
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
233
+ * @param blobClient - The blob client client for fetching blob data.
220
234
  * @param logs - CheckpointProposed logs.
221
- * @returns - An array of checkpoints.
235
+ * @param rollupConstants - The rollup constants (chainId, version, targetCommitteeSize).
236
+ * @param contractAddresses - The contract addresses (governanceProposerAddress, slashFactoryAddress, slashingProposerAddress).
237
+ * @param instrumentation - The archiver instrumentation instance.
238
+ * @param logger - The logger instance.
239
+ * @param isHistoricalSync - Whether this is a historical sync.
240
+ * @returns An array of retrieved checkpoints.
222
241
  */
223
242
  async function processCheckpointProposedLogs(
224
243
  rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>,
225
244
  publicClient: ViemPublicClient,
226
- blobSinkClient: BlobSinkClientInterface,
245
+ debugClient: ViemPublicDebugClient,
246
+ blobClient: BlobClientInterface,
227
247
  logs: GetContractEventsReturnType<typeof RollupAbi, 'CheckpointProposed'>,
228
248
  { chainId, version, targetCommitteeSize }: { chainId: Fr; version: Fr; targetCommitteeSize: number },
249
+ contractAddresses: {
250
+ governanceProposerAddress: EthAddress;
251
+ slashFactoryAddress?: EthAddress;
252
+ slashingProposerAddress: EthAddress;
253
+ },
254
+ instrumentation: ArchiverInstrumentation,
229
255
  logger: Logger,
256
+ isHistoricalSync: boolean,
230
257
  ): Promise<RetrievedCheckpoint[]> {
231
258
  const retrievedCheckpoints: RetrievedCheckpoint[] = [];
259
+ const calldataRetriever = new CalldataRetriever(
260
+ publicClient,
261
+ debugClient,
262
+ targetCommitteeSize,
263
+ instrumentation,
264
+ logger,
265
+ { ...contractAddresses, rollupAddress: EthAddress.fromString(rollup.address) },
266
+ );
267
+
232
268
  await asyncPool(10, logs, async log => {
233
- const checkpointNumber = Number(log.args.checkpointNumber!);
269
+ const checkpointNumber = CheckpointNumber.fromBigInt(log.args.checkpointNumber!);
234
270
  const archive = log.args.archive!;
235
271
  const archiveFromChain = await rollup.read.archiveAt([BigInt(checkpointNumber)]);
236
272
  const blobHashes = log.args.versionedBlobHashes!.map(blobHash => Buffer.from(blobHash.slice(2), 'hex'));
237
273
 
238
274
  // The value from the event and contract will match only if the checkpoint is in the chain.
239
275
  if (archive === archiveFromChain) {
240
- const checkpoint = await getCheckpointFromRollupTx(
241
- publicClient,
242
- blobSinkClient,
276
+ // Build expected hashes object (fields may be undefined for backwards compatibility with older events)
277
+ const expectedHashes = {
278
+ attestationsHash: log.args.attestationsHash,
279
+ payloadDigest: log.args.payloadDigest,
280
+ };
281
+
282
+ const checkpoint = await calldataRetriever.getCheckpointFromRollupTx(
243
283
  log.transactionHash!,
244
284
  blobHashes,
245
285
  checkpointNumber,
246
- rollup.address,
247
- targetCommitteeSize,
286
+ expectedHashes,
287
+ );
288
+ const checkpointBlobData = await getCheckpointBlobDataFromBlobs(
289
+ blobClient,
290
+ checkpoint.blockHash,
291
+ blobHashes,
292
+ checkpointNumber,
248
293
  logger,
294
+ isHistoricalSync,
249
295
  );
250
296
 
251
- const l1: L1PublishedData = {
252
- blockNumber: log.blockNumber,
253
- blockHash: log.blockHash,
254
- timestamp: await getL1BlockTime(publicClient, log.blockNumber),
255
- };
297
+ const l1 = new L1PublishedData(
298
+ log.blockNumber,
299
+ await getL1BlockTime(publicClient, log.blockNumber),
300
+ log.blockHash,
301
+ );
256
302
 
257
- retrievedCheckpoints.push({ ...checkpoint, l1, chainId, version });
303
+ retrievedCheckpoints.push({ ...checkpoint, checkpointBlobData, l1, chainId, version });
258
304
  logger.trace(`Retrieved checkpoint ${checkpointNumber} from L1 tx ${log.transactionHash}`, {
259
305
  l1BlockNumber: log.blockNumber,
260
306
  checkpointNumber,
@@ -277,118 +323,15 @@ export async function getL1BlockTime(publicClient: ViemPublicClient, blockNumber
277
323
  return block.timestamp;
278
324
  }
279
325
 
280
- /**
281
- * Extracts the first 'propose' method calldata from a multicall3 transaction's data.
282
- * @param multicall3Data - The multicall3 transaction input data
283
- * @param rollupAddress - The address of the rollup contract
284
- * @returns The calldata for the first 'propose' method call to the rollup contract
285
- */
286
- function extractRollupProposeCalldata(multicall3Data: Hex, rollupAddress: Hex): Hex {
287
- const { functionName: multicall3FunctionName, args: multicall3Args } = decodeFunctionData({
288
- abi: multicall3Abi,
289
- data: multicall3Data,
290
- });
291
-
292
- if (multicall3FunctionName !== 'aggregate3') {
293
- throw new Error(`Unexpected multicall3 method called ${multicall3FunctionName}`);
294
- }
295
-
296
- if (multicall3Args.length !== 1) {
297
- throw new Error(`Unexpected number of arguments for multicall3`);
298
- }
299
-
300
- const [calls] = multicall3Args;
301
-
302
- // Find all rollup calls
303
- const rollupAddressLower = rollupAddress.toLowerCase();
304
-
305
- for (let i = 0; i < calls.length; i++) {
306
- const addr = calls[i].target;
307
- if (addr.toLowerCase() !== rollupAddressLower) {
308
- continue;
309
- }
310
- const callData = calls[i].callData;
311
-
312
- try {
313
- const { functionName: rollupFunctionName } = decodeFunctionData({
314
- abi: RollupAbi,
315
- data: callData,
316
- });
317
-
318
- if (rollupFunctionName === 'propose') {
319
- return callData;
320
- }
321
- } catch {
322
- // Skip invalid function data
323
- continue;
324
- }
325
- }
326
-
327
- throw new Error(`Rollup address not found in multicall3 args`);
328
- }
329
-
330
- /**
331
- * Gets checkpoint from the calldata of an L1 transaction.
332
- * Assumes that the checkpoint was published from an EOA.
333
- * TODO: Add retries and error management.
334
- * @param publicClient - The viem public client to use for transaction retrieval.
335
- * @param txHash - Hash of the tx that published it.
336
- * @param checkpointNumber - Checkpoint number.
337
- * @returns Checkpoint from the calldata, deserialized
338
- */
339
- async function getCheckpointFromRollupTx(
340
- publicClient: ViemPublicClient,
341
- blobSinkClient: BlobSinkClientInterface,
342
- txHash: `0x${string}`,
343
- blobHashes: Buffer[], // TODO(md): buffer32?
344
- checkpointNumber: number,
345
- rollupAddress: Hex,
346
- targetCommitteeSize: number,
326
+ export async function getCheckpointBlobDataFromBlobs(
327
+ blobClient: BlobClientInterface,
328
+ blockHash: string,
329
+ blobHashes: Buffer<ArrayBufferLike>[],
330
+ checkpointNumber: CheckpointNumber,
347
331
  logger: Logger,
348
- ): Promise<Omit<RetrievedCheckpoint, 'l1' | 'chainId' | 'version'>> {
349
- logger.trace(`Fetching checkpoint ${checkpointNumber} from rollup tx ${txHash}`);
350
- const { input: forwarderData, blockHash } = await publicClient.getTransaction({ hash: txHash });
351
-
352
- const rollupData = extractRollupProposeCalldata(forwarderData, rollupAddress);
353
- const { functionName: rollupFunctionName, args: rollupArgs } = decodeFunctionData({
354
- abi: RollupAbi,
355
- data: rollupData,
356
- });
357
-
358
- if (rollupFunctionName !== 'propose') {
359
- throw new Error(`Unexpected rollup method called ${rollupFunctionName}`);
360
- }
361
-
362
- const [decodedArgs, packedAttestations, _signers, _blobInput] = rollupArgs! as readonly [
363
- {
364
- archive: Hex;
365
- oracleInput: {
366
- feeAssetPriceModifier: bigint;
367
- };
368
- header: ViemHeader;
369
- txHashes: readonly Hex[];
370
- },
371
- ViemCommitteeAttestations,
372
- Hex[],
373
- ViemSignature,
374
- Hex,
375
- ];
376
-
377
- const attestations = CommitteeAttestation.fromPacked(packedAttestations, targetCommitteeSize);
378
-
379
- logger.trace(`Recovered propose calldata from tx ${txHash}`, {
380
- checkpointNumber,
381
- archive: decodedArgs.archive,
382
- header: decodedArgs.header,
383
- l1BlockHash: blockHash,
384
- blobHashes,
385
- attestations,
386
- packedAttestations,
387
- targetCommitteeSize,
388
- });
389
-
390
- const header = CheckpointHeader.fromViem(decodedArgs.header);
391
- const blobBodies = await blobSinkClient.getBlobSidecar(blockHash, blobHashes);
332
+ isHistoricalSync: boolean,
333
+ ): Promise<CheckpointBlobData> {
334
+ const blobBodies = await blobClient.getBlobSidecar(blockHash, blobHashes, { isHistoricalSync });
392
335
  if (blobBodies.length === 0) {
393
336
  throw new NoBlobBodiesFoundError(checkpointNumber);
394
337
  }
@@ -396,25 +339,18 @@ async function getCheckpointFromRollupTx(
396
339
  let checkpointBlobData: CheckpointBlobData;
397
340
  try {
398
341
  // Attempt to decode the checkpoint blob data.
399
- checkpointBlobData = decodeCheckpointBlobDataFromBlobs(blobBodies.map(b => b.blob));
342
+ checkpointBlobData = decodeCheckpointBlobDataFromBlobs(blobBodies);
400
343
  } catch (err: any) {
401
344
  if (err instanceof BlobDeserializationError) {
402
345
  logger.fatal(err.message);
403
346
  } else {
404
347
  logger.fatal('Unable to sync: failed to decode fetched blob, this blob was likely not created by us');
405
348
  }
349
+ // Throwing an error since this is most likely caused by a bug.
406
350
  throw err;
407
351
  }
408
352
 
409
- const archiveRoot = new Fr(Buffer.from(hexToBytes(decodedArgs.archive)));
410
-
411
- return {
412
- checkpointNumber,
413
- archiveRoot,
414
- header,
415
- checkpointBlobData,
416
- attestations,
417
- };
353
+ return checkpointBlobData;
418
354
  }
419
355
 
420
356
  /** Given an L1 to L2 message, retrieves its corresponding event from the Inbox within a specific block range. */
@@ -469,7 +405,7 @@ function mapLogsInboxMessage(logs: GetContractEventsReturnType<typeof InboxAbi,
469
405
  leaf: Fr.fromHexString(hash!),
470
406
  l1BlockNumber: log.blockNumber,
471
407
  l1BlockHash: Buffer32.fromString(log.blockHash),
472
- l2BlockNumber: Number(checkpointNumber!),
408
+ checkpointNumber: CheckpointNumber.fromBigInt(checkpointNumber!),
473
409
  rollingHash: Buffer16.fromString(rollingHash!),
474
410
  };
475
411
  });
@@ -481,7 +417,7 @@ export async function retrieveL2ProofVerifiedEvents(
481
417
  rollupAddress: EthAddress,
482
418
  searchStartBlock: bigint,
483
419
  searchEndBlock?: bigint,
484
- ): Promise<{ l1BlockNumber: bigint; checkpointNumber: number; proverId: Fr; txHash: Hex }[]> {
420
+ ): Promise<{ l1BlockNumber: bigint; checkpointNumber: CheckpointNumber; proverId: Fr; txHash: Hex }[]> {
485
421
  const logs = await publicClient.getLogs({
486
422
  address: rollupAddress.toString(),
487
423
  fromBlock: searchStartBlock,
@@ -492,7 +428,7 @@ export async function retrieveL2ProofVerifiedEvents(
492
428
 
493
429
  return logs.map(log => ({
494
430
  l1BlockNumber: log.blockNumber,
495
- checkpointNumber: Number(log.args.checkpointNumber),
431
+ checkpointNumber: CheckpointNumber.fromBigInt(log.args.checkpointNumber),
496
432
  proverId: Fr.fromHexString(log.args.proverId),
497
433
  txHash: log.transactionHash,
498
434
  }));
@@ -0,0 +1,99 @@
1
+ import type { DebugCallTrace, ViemPublicDebugClient } from '@aztec/ethereum/types';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import type { Logger } from '@aztec/foundation/log';
4
+ import { type ZodFor, schemas } from '@aztec/foundation/schemas';
5
+ import { withHexPrefix } from '@aztec/foundation/string';
6
+
7
+ import type { Hex } from 'viem';
8
+ import { z } from 'zod';
9
+
10
+ import type { CallInfo } from './types.js';
11
+
12
+ /** Zod schema for validating call trace from debug_traceTransaction */
13
+ export const callTraceSchema: ZodFor<DebugCallTrace> = z.lazy(() =>
14
+ z.object({
15
+ from: schemas.HexStringWith0x,
16
+ to: schemas.HexStringWith0x.optional(),
17
+ type: z.string(),
18
+ input: schemas.HexStringWith0x.optional(),
19
+ output: schemas.HexStringWith0x.optional(),
20
+ gas: schemas.HexStringWith0x.optional(),
21
+ gasUsed: schemas.HexStringWith0x.optional(),
22
+ value: schemas.HexStringWith0x.optional(),
23
+ error: z.string().optional(),
24
+ calls: z.array(callTraceSchema).optional(),
25
+ }),
26
+ );
27
+
28
+ /**
29
+ * Traces a transaction and extracts all CALL operations to a specific contract and function selector.
30
+ *
31
+ * @param client - The Viem public client
32
+ * @param txHash - The transaction hash to trace
33
+ * @param targetAddress - The contract address to filter for
34
+ * @param functionSelector - The 4-byte function selector to filter for (with or without 0x prefix)
35
+ * @returns Array of CallInfo objects containing from, gasUsed, input, and value for matching calls
36
+ */
37
+ export async function getSuccessfulCallsFromDebug(
38
+ client: ViemPublicDebugClient,
39
+ txHash: Hex,
40
+ targetAddress: EthAddress,
41
+ functionSelector: string,
42
+ logger?: Logger,
43
+ ): Promise<CallInfo[]> {
44
+ // Normalize inputs for comparison
45
+ const normalizedTarget = targetAddress.toString().toLowerCase();
46
+ const normalizedSelector = withHexPrefix(functionSelector.toLowerCase());
47
+
48
+ // Call debug_traceTransaction with callTracer
49
+ // Using 'any' here because debug_traceTransaction is not in viem's standard RPC types
50
+ const rawTrace = await client.request({
51
+ method: 'debug_traceTransaction',
52
+ params: [txHash, { tracer: 'callTracer' }],
53
+ });
54
+
55
+ if (rawTrace === null || rawTrace === undefined) {
56
+ throw new Error(`Failed to retrieve debug_traceTransaction for ${txHash}`);
57
+ }
58
+
59
+ logger?.trace(`Retrieved debug_traceTransaction for ${txHash}`, { trace: rawTrace });
60
+
61
+ // Validate the response with zod
62
+ const trace = callTraceSchema.parse(rawTrace);
63
+
64
+ const results: CallInfo[] = [];
65
+
66
+ /**
67
+ * Recursively traverse the call trace tree
68
+ */
69
+ function traverseCalls(callTrace: DebugCallTrace) {
70
+ // Skip calls that have errors, and all its descendants
71
+ if (callTrace.error) {
72
+ return;
73
+ }
74
+
75
+ // Check if this is a CALL (not DELEGATECALL or STATICCALL) to the target address with matching selector
76
+ if (
77
+ callTrace.type.toUpperCase() === 'CALL' &&
78
+ callTrace.to?.toLowerCase() === normalizedTarget &&
79
+ callTrace.input?.toLowerCase().startsWith(normalizedSelector)
80
+ ) {
81
+ results.push({
82
+ from: EthAddress.fromString(callTrace.from),
83
+ gasUsed: callTrace.gasUsed === undefined ? undefined : BigInt(callTrace.gasUsed),
84
+ input: callTrace.input,
85
+ value: callTrace.value ? BigInt(callTrace.value) : 0n,
86
+ });
87
+ }
88
+
89
+ // Recursively process nested calls
90
+ for (const nestedCall of callTrace.calls ?? []) {
91
+ traverseCalls(nestedCall);
92
+ }
93
+ }
94
+
95
+ // Start traversal from the root trace
96
+ traverseCalls(trace);
97
+
98
+ return results;
99
+ }
@@ -0,0 +1,160 @@
1
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
+ import type { Logger } from '@aztec/foundation/log';
3
+
4
+ import { type Hex, type Transaction, decodeFunctionData, getAddress, trim } from 'viem';
5
+
6
+ // Spire Proposer Multicall constants
7
+ export const SPIRE_PROPOSER_ADDRESS = '0x9ccc2f3ecde026230e11a5c8799ac7524f2bb294';
8
+ export const SPIRE_PROPOSER_EXPECTED_IMPLEMENTATION = '0x7d38d47e7c82195e6e607d3b0f1c20c615c7bf42';
9
+
10
+ // EIP-1967 storage slot for implementation address
11
+ // keccak256("eip1967.proxy.implementation") - 1 = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
12
+ export const EIP1967_IMPLEMENTATION_SLOT =
13
+ '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc' as const;
14
+
15
+ // Spire Proposer Multicall ABI
16
+ export const SpireProposerAbi = [
17
+ {
18
+ inputs: [
19
+ {
20
+ components: [
21
+ { internalType: 'address', name: 'proposer', type: 'address' },
22
+ { internalType: 'address', name: 'target', type: 'address' },
23
+ { internalType: 'bytes', name: 'data', type: 'bytes' },
24
+ { internalType: 'uint256', name: 'value', type: 'uint256' },
25
+ { internalType: 'uint256', name: 'gasLimit', type: 'uint256' },
26
+ ],
27
+ internalType: 'struct IProposerMulticall.Call[]',
28
+ name: '_calls',
29
+ type: 'tuple[]',
30
+ },
31
+ ],
32
+ name: 'multicall',
33
+ outputs: [],
34
+ stateMutability: 'nonpayable',
35
+ type: 'function',
36
+ },
37
+ ] as const;
38
+
39
+ /**
40
+ * Verifies that a proxy contract points to the expected implementation using EIP-1967.
41
+ * @param publicClient - The viem public client
42
+ * @param proxyAddress - The proxy contract address
43
+ * @param expectedImplementation - The expected implementation address
44
+ * @param logger - Logger instance
45
+ * @returns True if the proxy points to the expected implementation
46
+ */
47
+ export async function verifyProxyImplementation(
48
+ publicClient: { getStorageAt: (params: { address: Hex; slot: Hex }) => Promise<Hex | undefined> },
49
+ proxyAddress: Hex,
50
+ expectedImplementation: Hex,
51
+ logger: Logger,
52
+ ): Promise<boolean> {
53
+ try {
54
+ // Read the EIP-1967 implementation slot
55
+ const implementationData = await publicClient.getStorageAt({
56
+ address: proxyAddress,
57
+ slot: EIP1967_IMPLEMENTATION_SLOT,
58
+ });
59
+
60
+ if (!implementationData) {
61
+ logger.warn(`No implementation found in EIP-1967 slot for proxy ${proxyAddress}`);
62
+ return false;
63
+ }
64
+
65
+ // The implementation address is stored in the last 20 bytes of the slot
66
+ // We need to extract and normalize it for comparison
67
+ const implementationAddress = getAddress(trim(implementationData));
68
+ const expectedAddress = getAddress(expectedImplementation);
69
+
70
+ const matches = implementationAddress.toLowerCase() === expectedAddress.toLowerCase();
71
+
72
+ if (!matches) {
73
+ logger.warn(`Proxy implementation mismatch: expected ${expectedAddress}, got ${implementationAddress}`, {
74
+ proxyAddress,
75
+ expectedImplementation,
76
+ actualImplementation: implementationAddress,
77
+ });
78
+ }
79
+
80
+ return matches;
81
+ } catch (err) {
82
+ logger.warn(`Failed to verify proxy implementation for ${proxyAddress}: ${err}`);
83
+ return false;
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Attempts to decode transaction as a Spire Proposer Multicall.
89
+ * Spire Proposer is a proxy contract that wraps multiple calls.
90
+ * Returns the target address and calldata of the wrapped call if validation succeeds and there is a single call.
91
+ * @param tx - The transaction to decode
92
+ * @param publicClient - The viem public client for proxy verification
93
+ * @param logger - Logger instance
94
+ * @returns Object with 'to' and 'data' of the wrapped call, or undefined if validation fails
95
+ */
96
+ export async function getCallFromSpireProposer(
97
+ tx: Transaction,
98
+ publicClient: { getStorageAt: (params: { address: Hex; slot: Hex }) => Promise<Hex | undefined> },
99
+ logger: Logger,
100
+ ): Promise<{ to: Hex; data: Hex } | undefined> {
101
+ const txHash = tx.hash;
102
+
103
+ try {
104
+ // Check if transaction is to the Spire Proposer address
105
+ if (!tx.to || !EthAddress.areEqual(tx.to, SPIRE_PROPOSER_ADDRESS)) {
106
+ logger.debug(`Transaction is not to Spire Proposer address (to: ${tx.to})`, { txHash });
107
+ return undefined;
108
+ }
109
+
110
+ // Verify the proxy points to the expected implementation
111
+ const isValidProxy = await verifyProxyImplementation(
112
+ publicClient,
113
+ tx.to as Hex,
114
+ SPIRE_PROPOSER_EXPECTED_IMPLEMENTATION as Hex,
115
+ logger,
116
+ );
117
+
118
+ if (!isValidProxy) {
119
+ logger.warn(`Spire Proposer proxy implementation verification failed`, { txHash, to: tx.to });
120
+ return undefined;
121
+ }
122
+
123
+ // Try to decode as Spire Proposer multicall
124
+ const { functionName: spireFunctionName, args: spireArgs } = decodeFunctionData({
125
+ abi: SpireProposerAbi,
126
+ data: tx.input,
127
+ });
128
+
129
+ // If not multicall, return undefined
130
+ if (spireFunctionName !== 'multicall') {
131
+ logger.warn(`Transaction to Spire Proposer is not multicall (got ${spireFunctionName})`, { txHash });
132
+ return undefined;
133
+ }
134
+
135
+ if (spireArgs.length !== 1) {
136
+ logger.warn(`Unexpected number of arguments for Spire Proposer multicall (got ${spireArgs.length})`, {
137
+ txHash,
138
+ });
139
+ return undefined;
140
+ }
141
+
142
+ const [calls] = spireArgs;
143
+
144
+ // Validate exactly ONE call (see ./README.md for rationale)
145
+ if (calls.length !== 1) {
146
+ logger.warn(`Spire Proposer multicall must contain exactly one call (got ${calls.length})`, { txHash });
147
+ return undefined;
148
+ }
149
+
150
+ const call = calls[0];
151
+
152
+ // Successfully extracted the single wrapped call
153
+ logger.trace(`Decoded Spire Proposer with single call to ${call.target}`, { txHash });
154
+ return { to: call.target, data: call.data };
155
+ } catch (err) {
156
+ // Any decoding error triggers fallback to trace
157
+ logger.warn(`Failed to decode Spire Proposer: ${err}`, { txHash });
158
+ return undefined;
159
+ }
160
+ }