@aztec/archiver 2.1.8 → 2.1.9

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 (57) hide show
  1. package/dest/archiver/archiver.d.ts +6 -5
  2. package/dest/archiver/archiver.d.ts.map +1 -1
  3. package/dest/archiver/archiver.js +26 -9
  4. package/dest/archiver/config.d.ts.map +1 -1
  5. package/dest/archiver/config.js +5 -0
  6. package/dest/archiver/instrumentation.d.ts +2 -0
  7. package/dest/archiver/instrumentation.d.ts.map +1 -1
  8. package/dest/archiver/instrumentation.js +11 -0
  9. package/dest/archiver/l1/bin/retrieve-calldata.d.ts +3 -0
  10. package/dest/archiver/l1/bin/retrieve-calldata.d.ts.map +1 -0
  11. package/dest/archiver/l1/bin/retrieve-calldata.js +149 -0
  12. package/dest/archiver/l1/calldata_retriever.d.ts +87 -0
  13. package/dest/archiver/l1/calldata_retriever.d.ts.map +1 -0
  14. package/dest/archiver/l1/calldata_retriever.js +406 -0
  15. package/dest/archiver/{data_retrieval.d.ts → l1/data_retrieval.d.ts} +13 -6
  16. package/dest/archiver/l1/data_retrieval.d.ts.map +1 -0
  17. package/dest/archiver/{data_retrieval.js → l1/data_retrieval.js} +22 -99
  18. package/dest/archiver/l1/debug_tx.d.ts +19 -0
  19. package/dest/archiver/l1/debug_tx.d.ts.map +1 -0
  20. package/dest/archiver/l1/debug_tx.js +73 -0
  21. package/dest/archiver/l1/spire_proposer.d.ts +70 -0
  22. package/dest/archiver/l1/spire_proposer.d.ts.map +1 -0
  23. package/dest/archiver/l1/spire_proposer.js +157 -0
  24. package/dest/archiver/l1/trace_tx.d.ts +97 -0
  25. package/dest/archiver/l1/trace_tx.d.ts.map +1 -0
  26. package/dest/archiver/l1/trace_tx.js +91 -0
  27. package/dest/archiver/l1/types.d.ts +12 -0
  28. package/dest/archiver/l1/types.d.ts.map +1 -0
  29. package/dest/archiver/l1/types.js +3 -0
  30. package/dest/archiver/l1/validate_trace.d.ts +29 -0
  31. package/dest/archiver/l1/validate_trace.d.ts.map +1 -0
  32. package/dest/archiver/l1/validate_trace.js +150 -0
  33. package/dest/index.d.ts +1 -1
  34. package/dest/index.d.ts.map +1 -1
  35. package/dest/index.js +1 -1
  36. package/package.json +15 -14
  37. package/src/archiver/archiver.ts +42 -12
  38. package/src/archiver/config.ts +5 -0
  39. package/src/archiver/instrumentation.ts +14 -0
  40. package/src/archiver/l1/README.md +98 -0
  41. package/src/archiver/l1/bin/retrieve-calldata.ts +186 -0
  42. package/src/archiver/l1/calldata_retriever.ts +528 -0
  43. package/src/archiver/{data_retrieval.ts → l1/data_retrieval.ts} +45 -155
  44. package/src/archiver/l1/debug_tx.ts +99 -0
  45. package/src/archiver/l1/spire_proposer.ts +160 -0
  46. package/src/archiver/l1/trace_tx.ts +128 -0
  47. package/src/archiver/l1/types.ts +13 -0
  48. package/src/archiver/l1/validate_trace.ts +211 -0
  49. package/src/index.ts +1 -1
  50. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  51. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  52. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  53. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  54. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  55. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  56. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  57. package/dest/archiver/data_retrieval.d.ts.map +0 -1
@@ -1,17 +1,9 @@
1
1
  import { Blob, BlobDeserializationError, EMPTY_BLOB_VERSIONED_HASH } from '@aztec/blob-lib';
2
2
  import type { BlobSinkClientInterface } from '@aztec/blob-sink/client';
3
- import type {
4
- EpochProofPublicInputArgs,
5
- ViemClient,
6
- ViemCommitteeAttestations,
7
- ViemHeader,
8
- ViemPublicClient,
9
- ViemStateReference,
10
- } from '@aztec/ethereum';
3
+ import type { EpochProofPublicInputArgs, ViemClient, ViemPublicClient, ViemPublicDebugClient } from '@aztec/ethereum';
11
4
  import { asyncPool } from '@aztec/foundation/async-pool';
12
5
  import { Buffer16, Buffer32 } from '@aztec/foundation/buffer';
13
- import type { EthAddress } from '@aztec/foundation/eth-address';
14
- import type { ViemSignature } from '@aztec/foundation/eth-signature';
6
+ import { EthAddress } from '@aztec/foundation/eth-address';
15
7
  import { Fr } from '@aztec/foundation/fields';
16
8
  import { type Logger, createLogger } from '@aztec/foundation/log';
17
9
  import { bufferToHex } from '@aztec/foundation/string';
@@ -28,13 +20,14 @@ import {
28
20
  decodeFunctionData,
29
21
  getAbiItem,
30
22
  hexToBytes,
31
- multicall3Abi,
32
23
  } from 'viem';
33
24
 
34
- import { NoBlobBodiesFoundError } from './errors.js';
35
- import type { DataRetrieval } from './structs/data_retrieval.js';
36
- import type { InboxMessage } from './structs/inbox_message.js';
37
- import type { L1PublishedData } from './structs/published.js';
25
+ import { NoBlobBodiesFoundError } from '../errors.js';
26
+ import type { ArchiverInstrumentation } from '../instrumentation.js';
27
+ import type { DataRetrieval } from '../structs/data_retrieval.js';
28
+ import type { InboxMessage } from '../structs/inbox_message.js';
29
+ import type { L1PublishedData } from '../structs/published.js';
30
+ import { CalldataRetriever } from './calldata_retriever.js';
38
31
 
39
32
  export type RetrievedL2Block = {
40
33
  l2BlockNumber: number;
@@ -94,6 +87,7 @@ export function retrievedBlockToPublishedL2Block(retrievedBlock: RetrievedL2Bloc
94
87
  /**
95
88
  * Fetches new L2 blocks.
96
89
  * @param publicClient - The viem public client to use for transaction retrieval.
90
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
97
91
  * @param rollupAddress - The address of the rollup contract.
98
92
  * @param searchStartBlock - The block number to use for starting the search.
99
93
  * @param searchEndBlock - The highest block number that we should search up to.
@@ -103,9 +97,16 @@ export function retrievedBlockToPublishedL2Block(retrievedBlock: RetrievedL2Bloc
103
97
  export async function retrieveBlocksFromRollup(
104
98
  rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>,
105
99
  publicClient: ViemPublicClient,
100
+ debugClient: ViemPublicDebugClient,
106
101
  blobSinkClient: BlobSinkClientInterface,
107
102
  searchStartBlock: bigint,
108
103
  searchEndBlock: bigint,
104
+ contractAddresses: {
105
+ governanceProposerAddress: EthAddress;
106
+ slashFactoryAddress?: EthAddress;
107
+ slashingProposerAddress: EthAddress;
108
+ },
109
+ instrumentation: ArchiverInstrumentation,
109
110
  logger: Logger = createLogger('archiver'),
110
111
  ): Promise<RetrievedL2Block[]> {
111
112
  const retrievedBlocks: RetrievedL2Block[] = [];
@@ -151,9 +152,12 @@ export async function retrieveBlocksFromRollup(
151
152
  const newBlocks = await processL2BlockProposedLogs(
152
153
  rollup,
153
154
  publicClient,
155
+ debugClient,
154
156
  blobSinkClient,
155
157
  l2BlockProposedLogs,
156
158
  rollupConstants,
159
+ contractAddresses,
160
+ instrumentation,
157
161
  logger,
158
162
  );
159
163
  retrievedBlocks.push(...newBlocks);
@@ -168,18 +172,35 @@ export async function retrieveBlocksFromRollup(
168
172
  * Processes newly received L2BlockProposed logs.
169
173
  * @param rollup - The rollup contract
170
174
  * @param publicClient - The viem public client to use for transaction retrieval.
175
+ * @param debugClient - The viem debug client to use for trace/debug RPC methods (optional).
171
176
  * @param logs - L2BlockProposed logs.
172
177
  * @returns - An array blocks.
173
178
  */
174
179
  async function processL2BlockProposedLogs(
175
180
  rollup: GetContractReturnType<typeof RollupAbi, ViemPublicClient>,
176
181
  publicClient: ViemPublicClient,
182
+ debugClient: ViemPublicDebugClient,
177
183
  blobSinkClient: BlobSinkClientInterface,
178
184
  logs: GetContractEventsReturnType<typeof RollupAbi, 'L2BlockProposed'>,
179
185
  { chainId, version, targetCommitteeSize }: { chainId: Fr; version: Fr; targetCommitteeSize: number },
186
+ contractAddresses: {
187
+ governanceProposerAddress: EthAddress;
188
+ slashFactoryAddress?: EthAddress;
189
+ slashingProposerAddress: EthAddress;
190
+ },
191
+ instrumentation: ArchiverInstrumentation,
180
192
  logger: Logger,
181
193
  ): Promise<RetrievedL2Block[]> {
182
194
  const retrievedBlocks: RetrievedL2Block[] = [];
195
+ const calldataRetriever = new CalldataRetriever(
196
+ publicClient,
197
+ debugClient,
198
+ targetCommitteeSize,
199
+ instrumentation,
200
+ logger,
201
+ { ...contractAddresses, rollupAddress: EthAddress.fromString(rollup.address) },
202
+ );
203
+
183
204
  await asyncPool(10, logs, async log => {
184
205
  const l2BlockNumber = Number(log.args.blockNumber!);
185
206
  const archive = log.args.archive!;
@@ -188,14 +209,13 @@ async function processL2BlockProposedLogs(
188
209
 
189
210
  // The value from the event and contract will match only if the block is in the chain.
190
211
  if (archive === archiveFromChain) {
191
- const block = await getBlockFromRollupTx(
192
- publicClient,
212
+ const blockHeader = await calldataRetriever.getBlockHeaderFromRollupTx(log.transactionHash!, l2BlockNumber);
213
+
214
+ const body = await getBlockBodyFromBlobs(
193
215
  blobSinkClient,
194
- log.transactionHash!,
216
+ blockHeader.blockHash,
195
217
  blobHashes,
196
218
  l2BlockNumber,
197
- rollup.address,
198
- targetCommitteeSize,
199
219
  logger,
200
220
  );
201
221
 
@@ -205,12 +225,13 @@ async function processL2BlockProposedLogs(
205
225
  timestamp: await getL1BlockTime(publicClient, log.blockNumber),
206
226
  };
207
227
 
208
- retrievedBlocks.push({ ...block, l1, chainId, version });
228
+ const { blockHash: _blockHash, ...blockData } = blockHeader;
229
+ retrievedBlocks.push({ ...blockData, body, l1, chainId, version });
209
230
  logger.trace(`Retrieved L2 block ${l2BlockNumber} from L1 tx ${log.transactionHash}`, {
210
231
  l1BlockNumber: log.blockNumber,
211
232
  l2BlockNumber,
212
233
  archive: archive.toString(),
213
- attestations: block.attestations,
234
+ attestations: blockHeader.attestations,
214
235
  });
215
236
  } else {
216
237
  logger.warn(`Ignoring L2 block ${l2BlockNumber} due to archive root mismatch`, {
@@ -228,144 +249,13 @@ export async function getL1BlockTime(publicClient: ViemPublicClient, blockNumber
228
249
  return block.timestamp;
229
250
  }
230
251
 
231
- /**
232
- * Extracts the first 'propose' method calldata from a multicall3 transaction's data.
233
- * @param multicall3Data - The multicall3 transaction input data
234
- * @param rollupAddress - The address of the rollup contract
235
- * @returns The calldata for the first 'propose' method call to the rollup contract
236
- */
237
- function extractRollupProposeCalldata(multicall3Data: Hex, rollupAddress: Hex): Hex {
238
- const { functionName: multicall3FunctionName, args: multicall3Args } = decodeFunctionData({
239
- abi: multicall3Abi,
240
- data: multicall3Data,
241
- });
242
-
243
- if (multicall3FunctionName !== 'aggregate3') {
244
- throw new Error(`Unexpected multicall3 method called ${multicall3FunctionName}`);
245
- }
246
-
247
- if (multicall3Args.length !== 1) {
248
- throw new Error(`Unexpected number of arguments for multicall3`);
249
- }
250
-
251
- const [calls] = multicall3Args;
252
-
253
- // Find all rollup calls
254
- const rollupAddressLower = rollupAddress.toLowerCase();
255
-
256
- for (let i = 0; i < calls.length; i++) {
257
- const addr = calls[i].target;
258
- if (addr.toLowerCase() !== rollupAddressLower) {
259
- continue;
260
- }
261
- const callData = calls[i].callData;
262
-
263
- try {
264
- const { functionName: rollupFunctionName } = decodeFunctionData({
265
- abi: RollupAbi,
266
- data: callData,
267
- });
268
-
269
- if (rollupFunctionName === 'propose') {
270
- return callData;
271
- }
272
- } catch {
273
- // Skip invalid function data
274
- continue;
275
- }
276
- }
277
-
278
- throw new Error(`Rollup address not found in multicall3 args`);
279
- }
280
-
281
- /**
282
- * Gets block from the calldata of an L1 transaction.
283
- * Assumes that the block was published from an EOA.
284
- * TODO: Add retries and error management.
285
- * @param publicClient - The viem public client to use for transaction retrieval.
286
- * @param txHash - Hash of the tx that published it.
287
- * @param l2BlockNumber - L2 block number.
288
- * @returns L2 block from the calldata, deserialized
289
- */
290
- async function getBlockFromRollupTx(
291
- publicClient: ViemPublicClient,
292
- blobSinkClient: BlobSinkClientInterface,
293
- txHash: `0x${string}`,
294
- blobHashes: Buffer[], // TODO(md): buffer32?
295
- l2BlockNumber: number,
296
- rollupAddress: Hex,
297
- targetCommitteeSize: number,
298
- logger: Logger,
299
- ): Promise<Omit<RetrievedL2Block, 'l1' | 'chainId' | 'version'>> {
300
- logger.trace(`Fetching L2 block ${l2BlockNumber} from rollup tx ${txHash}`);
301
- const { input: forwarderData, blockHash } = await publicClient.getTransaction({ hash: txHash });
302
-
303
- const rollupData = extractRollupProposeCalldata(forwarderData, rollupAddress);
304
- const { functionName: rollupFunctionName, args: rollupArgs } = decodeFunctionData({
305
- abi: RollupAbi,
306
- data: rollupData,
307
- });
308
-
309
- if (rollupFunctionName !== 'propose') {
310
- throw new Error(`Unexpected rollup method called ${rollupFunctionName}`);
311
- }
312
-
313
- const [decodedArgs, packedAttestations, _signers, _blobInput] = rollupArgs! as readonly [
314
- {
315
- archive: Hex;
316
- stateReference: ViemStateReference;
317
- oracleInput: {
318
- feeAssetPriceModifier: bigint;
319
- };
320
- header: ViemHeader;
321
- txHashes: readonly Hex[];
322
- },
323
- ViemCommitteeAttestations,
324
- Hex[],
325
- ViemSignature,
326
- Hex,
327
- ];
328
-
329
- const attestations = CommitteeAttestation.fromPacked(packedAttestations, targetCommitteeSize);
330
-
331
- logger.trace(`Recovered propose calldata from tx ${txHash}`, {
332
- l2BlockNumber,
333
- archive: decodedArgs.archive,
334
- stateReference: decodedArgs.stateReference,
335
- header: decodedArgs.header,
336
- l1BlockHash: blockHash,
337
- blobHashes,
338
- attestations,
339
- packedAttestations,
340
- targetCommitteeSize,
341
- });
342
-
343
- // TODO(md): why is the proposed block header different to the actual block header?
344
- // This is likely going to be a footgun
345
- const header = ProposedBlockHeader.fromViem(decodedArgs.header);
346
- const body = await getBlockBodyFromBlobs(blobSinkClient, blockHash!, blobHashes, l2BlockNumber, logger);
347
-
348
- const archiveRoot = new Fr(Buffer.from(hexToBytes(decodedArgs.archive)));
349
-
350
- const stateReference = StateReference.fromViem(decodedArgs.stateReference);
351
-
352
- return {
353
- l2BlockNumber,
354
- archiveRoot,
355
- stateReference,
356
- header,
357
- body,
358
- attestations,
359
- };
360
- }
361
-
362
- async function getBlockBodyFromBlobs(
252
+ export async function getBlockBodyFromBlobs(
363
253
  blobSinkClient: BlobSinkClientInterface,
364
254
  blockHash: string,
365
255
  blobHashes: Buffer<ArrayBufferLike>[],
366
256
  l2BlockNumber: number,
367
257
  logger: Logger,
368
- ) {
258
+ ): Promise<Body> {
369
259
  const blobBodies = await blobSinkClient.getBlobSidecar(blockHash, blobHashes);
370
260
  logger.trace(`Fetched ${blobBodies.length} blob bodies for L2 block ${l2BlockNumber}`, {
371
261
  blobHashes: blobHashes.map(bufferToHex),
@@ -0,0 +1,99 @@
1
+ import type { DebugCallTrace, ViemPublicDebugClient } from '@aztec/ethereum';
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
+ }
@@ -0,0 +1,128 @@
1
+ import type { ViemPublicDebugClient } from '@aztec/ethereum';
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 trace action from trace_transaction */
13
+ const traceActionSchema = z.object({
14
+ from: schemas.HexStringWith0x,
15
+ to: schemas.HexStringWith0x.optional(),
16
+ callType: z.string(),
17
+ gas: schemas.HexStringWith0x.optional(),
18
+ input: schemas.HexStringWith0x.optional(),
19
+ value: schemas.HexStringWith0x.optional(),
20
+ });
21
+
22
+ /** Zod schema for trace result from trace_transaction */
23
+ const traceResultSchema = z.object({
24
+ gasUsed: schemas.HexStringWith0x.optional(),
25
+ output: schemas.HexStringWith0x.optional(),
26
+ });
27
+
28
+ /** Zod schema for a single trace from trace_transaction */
29
+ export const traceSchema = z.object({
30
+ action: traceActionSchema,
31
+ result: traceResultSchema.optional(),
32
+ error: z.string().optional(),
33
+ subtraces: z.number(),
34
+ traceAddress: z.array(z.number()),
35
+ type: z.string(),
36
+ });
37
+
38
+ /** Type for trace_transaction response */
39
+ type TraceTransaction = z.infer<typeof traceSchema>;
40
+
41
+ /** Zod schema for the full trace_transaction response (array of traces) */
42
+ export const traceTransactionResponseSchema: ZodFor<TraceTransaction[]> = z.array(traceSchema);
43
+
44
+ /**
45
+ * Traces a transaction and extracts all CALL operations to a specific contract and function selector.
46
+ * Uses the trace_transaction RPC method which returns a flat array of traces.
47
+ *
48
+ * @param client - The Viem public debug client
49
+ * @param txHash - The transaction hash to trace
50
+ * @param targetAddress - The contract address to filter for
51
+ * @param functionSelector - The 4-byte function selector to filter for (with or without 0x prefix)
52
+ * @returns Array of CallInfo objects containing from, gasUsed, input, and value for matching calls
53
+ */
54
+ export async function getSuccessfulCallsFromTrace(
55
+ client: ViemPublicDebugClient,
56
+ txHash: Hex,
57
+ targetAddress: EthAddress,
58
+ functionSelector: string,
59
+ logger?: Logger,
60
+ ): Promise<CallInfo[]> {
61
+ // Normalize inputs for comparison
62
+ const normalizedTarget = targetAddress.toString().toLowerCase();
63
+ const normalizedSelector = withHexPrefix(functionSelector.toLowerCase());
64
+
65
+ // Call trace_transaction (no options needed)
66
+ const rawTrace = await client.request({
67
+ method: 'trace_transaction',
68
+ params: [txHash],
69
+ });
70
+
71
+ if (rawTrace === null || rawTrace === undefined) {
72
+ throw new Error(`Failed to retrieve trace_transaction for ${txHash}`);
73
+ }
74
+
75
+ logger?.trace(`Retrieved trace_transaction for ${txHash}`, { trace: rawTrace });
76
+
77
+ // Validate the response with zod
78
+ const traces = traceTransactionResponseSchema.parse(rawTrace);
79
+
80
+ const results: CallInfo[] = [];
81
+
82
+ // Build a set of trace addresses that errored - we should skip their descendants
83
+ // A trace address is the path in the trace tree, represented as an array of indices
84
+ const erroredTraceAddresses = new Set<string>();
85
+ for (const trace of traces) {
86
+ if (trace.error) {
87
+ erroredTraceAddresses.add(JSON.stringify(trace.traceAddress));
88
+ }
89
+ }
90
+
91
+ // Helper to check if a trace is a descendant of an errored trace
92
+ function isDescendantOfError(traceAddress: number[]): boolean {
93
+ // Check all possible ancestor paths
94
+ for (let i = 1; i < traceAddress.length; i++) {
95
+ const ancestorAddress = traceAddress.slice(0, i);
96
+ if (erroredTraceAddresses.has(JSON.stringify(ancestorAddress))) {
97
+ return true;
98
+ }
99
+ }
100
+ return false;
101
+ }
102
+
103
+ // Process each trace
104
+ for (const trace of traces) {
105
+ // Skip if this has an error or is a descendant of an errored trace
106
+ if (trace.error || isDescendantOfError(trace.traceAddress)) {
107
+ continue;
108
+ }
109
+
110
+ // Check if this is a CALL type trace to the target address with matching selector and result
111
+ if (
112
+ trace.type === 'call' &&
113
+ trace.action.callType.toLowerCase() === 'call' &&
114
+ trace.action.to?.toLowerCase() === normalizedTarget &&
115
+ trace.action.input?.toLowerCase().startsWith(normalizedSelector) &&
116
+ trace.result
117
+ ) {
118
+ results.push({
119
+ from: EthAddress.fromString(trace.action.from),
120
+ gasUsed: trace.result.gasUsed === undefined ? undefined : BigInt(trace.result.gasUsed),
121
+ input: trace.action.input,
122
+ value: trace.action.value ? BigInt(trace.action.value) : 0n,
123
+ });
124
+ }
125
+ }
126
+
127
+ return results;
128
+ }
@@ -0,0 +1,13 @@
1
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
+
3
+ import type { Hex } from 'viem';
4
+
5
+ /**
6
+ * Information about a matching CALL
7
+ */
8
+ export interface CallInfo {
9
+ from: EthAddress;
10
+ gasUsed?: bigint;
11
+ input: Hex;
12
+ value: bigint;
13
+ }