@aztec/archiver 3.0.0-nightly.20251209 → 3.0.0-nightly.20251211

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 (108) hide show
  1. package/dest/archiver/archiver.d.ts +16 -14
  2. package/dest/archiver/archiver.d.ts.map +1 -1
  3. package/dest/archiver/archiver.js +59 -28
  4. package/dest/archiver/archiver_store.d.ts +9 -9
  5. package/dest/archiver/archiver_store.d.ts.map +1 -1
  6. package/dest/archiver/archiver_store_test_suite.d.ts +1 -1
  7. package/dest/archiver/archiver_store_test_suite.d.ts.map +1 -1
  8. package/dest/archiver/archiver_store_test_suite.js +47 -46
  9. package/dest/archiver/config.d.ts +3 -2
  10. package/dest/archiver/config.d.ts.map +1 -1
  11. package/dest/archiver/config.js +8 -1
  12. package/dest/archiver/instrumentation.d.ts +3 -1
  13. package/dest/archiver/instrumentation.d.ts.map +1 -1
  14. package/dest/archiver/instrumentation.js +11 -0
  15. package/dest/archiver/kv_archiver_store/block_store.d.ts +2 -2
  16. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +1 -1
  17. package/dest/archiver/kv_archiver_store/block_store.js +1 -1
  18. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +2 -2
  19. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +1 -1
  20. package/dest/archiver/kv_archiver_store/contract_class_store.js +1 -1
  21. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +2 -2
  22. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +1 -1
  23. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +8 -8
  24. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +1 -1
  25. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +6 -6
  26. package/dest/archiver/kv_archiver_store/log_store.d.ts +2 -2
  27. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +1 -1
  28. package/dest/archiver/kv_archiver_store/message_store.d.ts +6 -5
  29. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +1 -1
  30. package/dest/archiver/kv_archiver_store/message_store.js +15 -14
  31. package/dest/archiver/l1/bin/retrieve-calldata.d.ts +3 -0
  32. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +1 -0
  33. package/dest/archiver/l1/bin/retrieve-calldata.js +147 -0
  34. package/dest/archiver/l1/calldata_retriever.d.ts +98 -0
  35. package/dest/archiver/l1/calldata_retriever.d.ts.map +1 -0
  36. package/dest/archiver/l1/calldata_retriever.js +403 -0
  37. package/dest/archiver/l1/data_retrieval.d.ts +87 -0
  38. package/dest/archiver/l1/data_retrieval.d.ts.map +1 -0
  39. package/dest/archiver/{data_retrieval.js → l1/data_retrieval.js} +26 -95
  40. package/dest/archiver/l1/debug_tx.d.ts +19 -0
  41. package/dest/archiver/l1/debug_tx.d.ts.map +1 -0
  42. package/dest/archiver/l1/debug_tx.js +73 -0
  43. package/dest/archiver/l1/spire_proposer.d.ts +70 -0
  44. package/dest/archiver/l1/spire_proposer.d.ts.map +1 -0
  45. package/dest/archiver/l1/spire_proposer.js +157 -0
  46. package/dest/archiver/l1/trace_tx.d.ts +97 -0
  47. package/dest/archiver/l1/trace_tx.d.ts.map +1 -0
  48. package/dest/archiver/l1/trace_tx.js +91 -0
  49. package/dest/archiver/l1/types.d.ts +12 -0
  50. package/dest/archiver/l1/types.d.ts.map +1 -0
  51. package/dest/archiver/l1/types.js +3 -0
  52. package/dest/archiver/l1/validate_trace.d.ts +29 -0
  53. package/dest/archiver/l1/validate_trace.d.ts.map +1 -0
  54. package/dest/archiver/l1/validate_trace.js +150 -0
  55. package/dest/archiver/structs/inbox_message.d.ts +4 -4
  56. package/dest/archiver/structs/inbox_message.d.ts.map +1 -1
  57. package/dest/archiver/structs/inbox_message.js +6 -6
  58. package/dest/index.d.ts +2 -2
  59. package/dest/index.d.ts.map +1 -1
  60. package/dest/index.js +1 -1
  61. package/dest/test/mock_archiver.d.ts +4 -5
  62. package/dest/test/mock_archiver.d.ts.map +1 -1
  63. package/dest/test/mock_archiver.js +5 -9
  64. package/dest/test/mock_l1_to_l2_message_source.d.ts +5 -6
  65. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  66. package/dest/test/mock_l1_to_l2_message_source.js +7 -11
  67. package/dest/test/mock_l2_block_source.d.ts +2 -2
  68. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  69. package/dest/test/mock_l2_block_source.js +2 -2
  70. package/dest/test/mock_structs.d.ts +3 -2
  71. package/dest/test/mock_structs.d.ts.map +1 -1
  72. package/dest/test/mock_structs.js +9 -9
  73. package/package.json +15 -14
  74. package/src/archiver/archiver.ts +79 -40
  75. package/src/archiver/archiver_store.ts +8 -8
  76. package/src/archiver/archiver_store_test_suite.ts +56 -48
  77. package/src/archiver/config.ts +8 -7
  78. package/src/archiver/instrumentation.ts +14 -0
  79. package/src/archiver/kv_archiver_store/block_store.ts +1 -1
  80. package/src/archiver/kv_archiver_store/contract_class_store.ts +1 -1
  81. package/src/archiver/kv_archiver_store/contract_instance_store.ts +1 -1
  82. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +9 -9
  83. package/src/archiver/kv_archiver_store/log_store.ts +1 -1
  84. package/src/archiver/kv_archiver_store/message_store.ts +21 -18
  85. package/src/archiver/l1/README.md +98 -0
  86. package/src/archiver/l1/bin/retrieve-calldata.ts +182 -0
  87. package/src/archiver/l1/calldata_retriever.ts +531 -0
  88. package/src/archiver/{data_retrieval.ts → l1/data_retrieval.ts} +57 -143
  89. package/src/archiver/l1/debug_tx.ts +99 -0
  90. package/src/archiver/l1/spire_proposer.ts +160 -0
  91. package/src/archiver/l1/trace_tx.ts +128 -0
  92. package/src/archiver/l1/types.ts +13 -0
  93. package/src/archiver/l1/validate_trace.ts +211 -0
  94. package/src/archiver/structs/inbox_message.ts +7 -8
  95. package/src/index.ts +1 -1
  96. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  97. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  98. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  99. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  100. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  101. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  102. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  103. package/src/test/mock_archiver.ts +6 -11
  104. package/src/test/mock_l1_to_l2_message_source.ts +6 -11
  105. package/src/test/mock_l2_block_source.ts +2 -2
  106. package/src/test/mock_structs.ts +10 -10
  107. package/dest/archiver/data_retrieval.d.ts +0 -80
  108. package/dest/archiver/data_retrieval.d.ts.map +0 -1
@@ -6,19 +6,13 @@ import {
6
6
  encodeBlockBlobData,
7
7
  } from '@aztec/blob-lib';
8
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';
17
- import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
12
+ import { CheckpointNumber } from '@aztec/foundation/branded-types';
18
13
  import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
19
- import type { EthAddress } from '@aztec/foundation/eth-address';
20
- import type { ViemSignature } from '@aztec/foundation/eth-signature';
21
- import { Fr } from '@aztec/foundation/fields';
14
+ import { Fr } from '@aztec/foundation/curves/bn254';
15
+ import { EthAddress } from '@aztec/foundation/eth-address';
22
16
  import { type Logger, createLogger } from '@aztec/foundation/log';
23
17
  import { type InboxAbi, RollupAbi } from '@aztec/l1-artifacts';
24
18
  import { Body, CommitteeAttestation, L2BlockNew } from '@aztec/stdlib/block';
@@ -35,13 +29,14 @@ import {
35
29
  decodeFunctionData,
36
30
  getAbiItem,
37
31
  hexToBytes,
38
- multicall3Abi,
39
32
  } from 'viem';
40
33
 
41
- import { NoBlobBodiesFoundError } from './errors.js';
42
- import type { DataRetrieval } from './structs/data_retrieval.js';
43
- import type { InboxMessage } from './structs/inbox_message.js';
44
- 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 type { L1PublishedData } from '../structs/published.js';
39
+ import { CalldataRetriever } from './calldata_retriever.js';
45
40
 
46
41
  export type RetrievedCheckpoint = {
47
42
  checkpointNumber: CheckpointNumber;
@@ -72,8 +67,8 @@ export async function retrievedToPublishedCheckpoint({
72
67
  .slice(1)
73
68
  .concat([archiveRoot]);
74
69
 
75
- // `blocksBlobData` is created from `decodeCheckpointBlobDataFromBlobs`. An error will be thrown if it can't read a
76
- // field for the `l1ToL2MessageRoot` of the first block. So below we can safely assume it exists:
70
+ // An error will be thrown from `decodeCheckpointBlobDataFromBlobs` if it can't read a field for the
71
+ // `l1ToL2MessageRoot` of the first block. So below we can safely assume it exists:
77
72
  const l1toL2MessageTreeRoot = blocksBlobData[0].l1ToL2MessageRoot!;
78
73
 
79
74
  const spongeBlob = SpongeBlob.init();
@@ -127,7 +122,7 @@ export async function retrievedToPublishedCheckpoint({
127
122
 
128
123
  const newArchive = new AppendOnlyTreeSnapshot(newArchiveRoots[i], l2BlockNumber + 1);
129
124
 
130
- l2Blocks.push(new L2BlockNew(newArchive, header, body));
125
+ l2Blocks.push(new L2BlockNew(newArchive, header, body, checkpointNumber, i));
131
126
  }
132
127
 
133
128
  const lastBlock = l2Blocks.at(-1)!;
@@ -144,6 +139,7 @@ export async function retrievedToPublishedCheckpoint({
144
139
  /**
145
140
  * Fetches new checkpoints.
146
141
  * @param publicClient - The viem public client to use for transaction retrieval.
142
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
147
143
  * @param rollupAddress - The address of the rollup contract.
148
144
  * @param searchStartBlock - The block number to use for starting the search.
149
145
  * @param searchEndBlock - The highest block number that we should search up to.
@@ -153,9 +149,16 @@ export async function retrievedToPublishedCheckpoint({
153
149
  export async function retrieveCheckpointsFromRollup(
154
150
  rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>,
155
151
  publicClient: ViemPublicClient,
152
+ debugClient: ViemPublicDebugClient,
156
153
  blobSinkClient: BlobSinkClientInterface,
157
154
  searchStartBlock: bigint,
158
155
  searchEndBlock: bigint,
156
+ contractAddresses: {
157
+ governanceProposerAddress: EthAddress;
158
+ slashFactoryAddress?: EthAddress;
159
+ slashingProposerAddress: EthAddress;
160
+ },
161
+ instrumentation: ArchiverInstrumentation,
159
162
  logger: Logger = createLogger('archiver'),
160
163
  ): Promise<RetrievedCheckpoint[]> {
161
164
  const retrievedCheckpoints: RetrievedCheckpoint[] = [];
@@ -201,9 +204,12 @@ export async function retrieveCheckpointsFromRollup(
201
204
  const newCheckpoints = await processCheckpointProposedLogs(
202
205
  rollup,
203
206
  publicClient,
207
+ debugClient,
204
208
  blobSinkClient,
205
209
  checkpointProposedLogs,
206
210
  rollupConstants,
211
+ contractAddresses,
212
+ instrumentation,
207
213
  logger,
208
214
  );
209
215
  retrievedCheckpoints.push(...newCheckpoints);
@@ -218,18 +224,35 @@ export async function retrieveCheckpointsFromRollup(
218
224
  * Processes newly received CheckpointProposed logs.
219
225
  * @param rollup - The rollup contract
220
226
  * @param publicClient - The viem public client to use for transaction retrieval.
227
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
221
228
  * @param logs - CheckpointProposed logs.
222
229
  * @returns - An array of checkpoints.
223
230
  */
224
231
  async function processCheckpointProposedLogs(
225
232
  rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>,
226
233
  publicClient: ViemPublicClient,
234
+ debugClient: ViemPublicDebugClient,
227
235
  blobSinkClient: BlobSinkClientInterface,
228
236
  logs: GetContractEventsReturnType<typeof RollupAbi, 'CheckpointProposed'>,
229
237
  { chainId, version, targetCommitteeSize }: { chainId: Fr; version: Fr; targetCommitteeSize: number },
238
+ contractAddresses: {
239
+ governanceProposerAddress: EthAddress;
240
+ slashFactoryAddress?: EthAddress;
241
+ slashingProposerAddress: EthAddress;
242
+ },
243
+ instrumentation: ArchiverInstrumentation,
230
244
  logger: Logger,
231
245
  ): Promise<RetrievedCheckpoint[]> {
232
246
  const retrievedCheckpoints: RetrievedCheckpoint[] = [];
247
+ const calldataRetriever = new CalldataRetriever(
248
+ publicClient,
249
+ debugClient,
250
+ targetCommitteeSize,
251
+ instrumentation,
252
+ logger,
253
+ { ...contractAddresses, rollupAddress: EthAddress.fromString(rollup.address) },
254
+ );
255
+
233
256
  await asyncPool(10, logs, async log => {
234
257
  const checkpointNumber = CheckpointNumber.fromBigInt(log.args.checkpointNumber!);
235
258
  const archive = log.args.archive!;
@@ -238,14 +261,16 @@ async function processCheckpointProposedLogs(
238
261
 
239
262
  // The value from the event and contract will match only if the checkpoint is in the chain.
240
263
  if (archive === archiveFromChain) {
241
- const checkpoint = await getCheckpointFromRollupTx(
242
- publicClient,
243
- blobSinkClient,
264
+ const checkpoint = await calldataRetriever.getCheckpointFromRollupTx(
244
265
  log.transactionHash!,
245
266
  blobHashes,
246
267
  checkpointNumber,
247
- rollup.address,
248
- targetCommitteeSize,
268
+ );
269
+ const checkpointBlobData = await getCheckpointBlobDataFromBlobs(
270
+ blobSinkClient,
271
+ checkpoint.blockHash,
272
+ blobHashes,
273
+ checkpointNumber,
249
274
  logger,
250
275
  );
251
276
 
@@ -255,7 +280,7 @@ async function processCheckpointProposedLogs(
255
280
  timestamp: await getL1BlockTime(publicClient, log.blockNumber),
256
281
  };
257
282
 
258
- retrievedCheckpoints.push({ ...checkpoint, l1, chainId, version });
283
+ retrievedCheckpoints.push({ ...checkpoint, checkpointBlobData, l1, chainId, version });
259
284
  logger.trace(`Retrieved checkpoint ${checkpointNumber} from L1 tx ${log.transactionHash}`, {
260
285
  l1BlockNumber: log.blockNumber,
261
286
  checkpointNumber,
@@ -278,117 +303,13 @@ export async function getL1BlockTime(publicClient: ViemPublicClient, blockNumber
278
303
  return block.timestamp;
279
304
  }
280
305
 
281
- /**
282
- * Extracts the first 'propose' method calldata from a multicall3 transaction's data.
283
- * @param multicall3Data - The multicall3 transaction input data
284
- * @param rollupAddress - The address of the rollup contract
285
- * @returns The calldata for the first 'propose' method call to the rollup contract
286
- */
287
- function extractRollupProposeCalldata(multicall3Data: Hex, rollupAddress: Hex): Hex {
288
- const { functionName: multicall3FunctionName, args: multicall3Args } = decodeFunctionData({
289
- abi: multicall3Abi,
290
- data: multicall3Data,
291
- });
292
-
293
- if (multicall3FunctionName !== 'aggregate3') {
294
- throw new Error(`Unexpected multicall3 method called ${multicall3FunctionName}`);
295
- }
296
-
297
- if (multicall3Args.length !== 1) {
298
- throw new Error(`Unexpected number of arguments for multicall3`);
299
- }
300
-
301
- const [calls] = multicall3Args;
302
-
303
- // Find all rollup calls
304
- const rollupAddressLower = rollupAddress.toLowerCase();
305
-
306
- for (let i = 0; i < calls.length; i++) {
307
- const addr = calls[i].target;
308
- if (addr.toLowerCase() !== rollupAddressLower) {
309
- continue;
310
- }
311
- const callData = calls[i].callData;
312
-
313
- try {
314
- const { functionName: rollupFunctionName } = decodeFunctionData({
315
- abi: RollupAbi,
316
- data: callData,
317
- });
318
-
319
- if (rollupFunctionName === 'propose') {
320
- return callData;
321
- }
322
- } catch {
323
- // Skip invalid function data
324
- continue;
325
- }
326
- }
327
-
328
- throw new Error(`Rollup address not found in multicall3 args`);
329
- }
330
-
331
- /**
332
- * Gets checkpoint from the calldata of an L1 transaction.
333
- * Assumes that the checkpoint was published from an EOA.
334
- * TODO: Add retries and error management.
335
- * @param publicClient - The viem public client to use for transaction retrieval.
336
- * @param txHash - Hash of the tx that published it.
337
- * @param checkpointNumber - Checkpoint number.
338
- * @returns Checkpoint from the calldata, deserialized
339
- */
340
- async function getCheckpointFromRollupTx(
341
- publicClient: ViemPublicClient,
306
+ export async function getCheckpointBlobDataFromBlobs(
342
307
  blobSinkClient: BlobSinkClientInterface,
343
- txHash: `0x${string}`,
344
- blobHashes: Buffer[], // TODO(md): buffer32?
308
+ blockHash: string,
309
+ blobHashes: Buffer<ArrayBufferLike>[],
345
310
  checkpointNumber: CheckpointNumber,
346
- rollupAddress: Hex,
347
- targetCommitteeSize: number,
348
311
  logger: Logger,
349
- ): Promise<Omit<RetrievedCheckpoint, 'l1' | 'chainId' | 'version'>> {
350
- logger.trace(`Fetching checkpoint ${checkpointNumber} from rollup tx ${txHash}`);
351
- const { input: forwarderData, blockHash } = await publicClient.getTransaction({ hash: txHash });
352
-
353
- const rollupData = extractRollupProposeCalldata(forwarderData, rollupAddress);
354
- const { functionName: rollupFunctionName, args: rollupArgs } = decodeFunctionData({
355
- abi: RollupAbi,
356
- data: rollupData,
357
- });
358
-
359
- if (rollupFunctionName !== 'propose') {
360
- throw new Error(`Unexpected rollup method called ${rollupFunctionName}`);
361
- }
362
-
363
- const [decodedArgs, packedAttestations, _signers, _blobInput] = rollupArgs! as readonly [
364
- {
365
- archive: Hex;
366
- oracleInput: {
367
- feeAssetPriceModifier: bigint;
368
- };
369
- header: ViemHeader;
370
- txHashes: readonly Hex[];
371
- },
372
- ViemCommitteeAttestations,
373
- Hex[],
374
- ViemSignature,
375
- Hex,
376
- ];
377
-
378
- const attestations = CommitteeAttestation.fromPacked(packedAttestations, targetCommitteeSize);
379
-
380
- logger.trace(`Recovered propose calldata from tx ${txHash}`, {
381
- checkpointNumber,
382
- archive: decodedArgs.archive,
383
- header: decodedArgs.header,
384
- l1BlockHash: blockHash,
385
- blobHashes,
386
- attestations,
387
- packedAttestations,
388
- targetCommitteeSize,
389
- });
390
-
391
- const header = CheckpointHeader.fromViem(decodedArgs.header);
312
+ ): Promise<CheckpointBlobData> {
392
313
  const blobBodies = await blobSinkClient.getBlobSidecar(blockHash, blobHashes);
393
314
  if (blobBodies.length === 0) {
394
315
  throw new NoBlobBodiesFoundError(checkpointNumber);
@@ -404,18 +325,11 @@ async function getCheckpointFromRollupTx(
404
325
  } else {
405
326
  logger.fatal('Unable to sync: failed to decode fetched blob, this blob was likely not created by us');
406
327
  }
328
+ // Throwing an error since this is most likely caused by a bug.
407
329
  throw err;
408
330
  }
409
331
 
410
- const archiveRoot = new Fr(Buffer.from(hexToBytes(decodedArgs.archive)));
411
-
412
- return {
413
- checkpointNumber,
414
- archiveRoot,
415
- header,
416
- checkpointBlobData,
417
- attestations,
418
- };
332
+ return checkpointBlobData;
419
333
  }
420
334
 
421
335
  /** Given an L1 to L2 message, retrieves its corresponding event from the Inbox within a specific block range. */
@@ -470,7 +384,7 @@ function mapLogsInboxMessage(logs: GetContractEventsReturnType<typeof InboxAbi,
470
384
  leaf: Fr.fromHexString(hash!),
471
385
  l1BlockNumber: log.blockNumber,
472
386
  l1BlockHash: Buffer32.fromString(log.blockHash),
473
- l2BlockNumber: BlockNumber(Number(checkpointNumber!)),
387
+ checkpointNumber: CheckpointNumber.fromBigInt(checkpointNumber!),
474
388
  rollingHash: Buffer16.fromString(rollingHash!),
475
389
  };
476
390
  });
@@ -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
+ }