@aztec/archiver 0.0.1-commit.5daedc8 → 0.0.1-commit.6201a7b05

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 (218) hide show
  1. package/README.md +162 -22
  2. package/dest/archiver.d.ts +147 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +788 -0
  5. package/dest/config.d.ts +32 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +83 -0
  8. package/dest/errors.d.ts +92 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +136 -0
  11. package/dest/factory.d.ts +8 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +100 -15
  14. package/dest/index.d.ts +12 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +10 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +152 -0
  23. package/dest/l1/calldata_retriever.d.ts +136 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +408 -0
  26. package/dest/l1/data_retrieval.d.ts +97 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +86 -165
  29. package/dest/l1/debug_tx.d.ts +19 -0
  30. package/dest/l1/debug_tx.d.ts.map +1 -0
  31. package/dest/l1/debug_tx.js +73 -0
  32. package/dest/l1/spire_proposer.d.ts +70 -0
  33. package/dest/l1/spire_proposer.d.ts.map +1 -0
  34. package/dest/l1/spire_proposer.js +149 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_historical_logs.d.ts +23 -0
  42. package/dest/l1/validate_historical_logs.d.ts.map +1 -0
  43. package/dest/l1/validate_historical_logs.js +108 -0
  44. package/dest/l1/validate_trace.d.ts +32 -0
  45. package/dest/l1/validate_trace.d.ts.map +1 -0
  46. package/dest/l1/validate_trace.js +154 -0
  47. package/dest/modules/data_source_base.d.ts +95 -0
  48. package/dest/modules/data_source_base.d.ts.map +1 -0
  49. package/dest/modules/data_source_base.js +234 -0
  50. package/dest/modules/data_store_updater.d.ts +93 -0
  51. package/dest/modules/data_store_updater.d.ts.map +1 -0
  52. package/dest/modules/data_store_updater.js +345 -0
  53. package/dest/modules/instrumentation.d.ts +55 -0
  54. package/dest/modules/instrumentation.d.ts.map +1 -0
  55. package/dest/modules/instrumentation.js +143 -0
  56. package/dest/modules/l1_synchronizer.d.ts +77 -0
  57. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  58. package/dest/modules/l1_synchronizer.js +1265 -0
  59. package/dest/modules/validation.d.ts +18 -0
  60. package/dest/modules/validation.d.ts.map +1 -0
  61. package/dest/{archiver → modules}/validation.js +13 -7
  62. package/dest/store/block_store.d.ts +262 -0
  63. package/dest/store/block_store.d.ts.map +1 -0
  64. package/dest/store/block_store.js +1048 -0
  65. package/dest/store/contract_class_store.d.ts +17 -0
  66. package/dest/store/contract_class_store.d.ts.map +1 -0
  67. package/dest/store/contract_class_store.js +64 -0
  68. package/dest/store/contract_instance_store.d.ts +24 -0
  69. package/dest/store/contract_instance_store.d.ts.map +1 -0
  70. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +7 -3
  71. package/dest/store/kv_archiver_store.d.ts +401 -0
  72. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  73. package/dest/store/kv_archiver_store.js +525 -0
  74. package/dest/store/l2_tips_cache.d.ts +20 -0
  75. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  76. package/dest/store/l2_tips_cache.js +109 -0
  77. package/dest/store/log_store.d.ts +57 -0
  78. package/dest/store/log_store.d.ts.map +1 -0
  79. package/dest/store/log_store.js +531 -0
  80. package/dest/store/message_store.d.ts +44 -0
  81. package/dest/store/message_store.d.ts.map +1 -0
  82. package/dest/{archiver/kv_archiver_store → store}/message_store.js +36 -23
  83. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  84. package/dest/structs/data_retrieval.d.ts.map +1 -0
  85. package/dest/structs/inbox_message.d.ts +15 -0
  86. package/dest/structs/inbox_message.d.ts.map +1 -0
  87. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  88. package/dest/structs/published.d.ts +2 -0
  89. package/dest/structs/published.d.ts.map +1 -0
  90. package/dest/test/fake_l1_state.d.ts +214 -0
  91. package/dest/test/fake_l1_state.d.ts.map +1 -0
  92. package/dest/test/fake_l1_state.js +517 -0
  93. package/dest/test/index.d.ts +2 -1
  94. package/dest/test/index.d.ts.map +1 -1
  95. package/dest/test/index.js +4 -1
  96. package/dest/test/mock_archiver.d.ts +16 -8
  97. package/dest/test/mock_archiver.d.ts.map +1 -1
  98. package/dest/test/mock_archiver.js +19 -14
  99. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  100. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  101. package/dest/test/mock_l1_to_l2_message_source.js +23 -12
  102. package/dest/test/mock_l2_block_source.d.ts +68 -20
  103. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  104. package/dest/test/mock_l2_block_source.js +298 -85
  105. package/dest/test/mock_structs.d.ts +83 -4
  106. package/dest/test/mock_structs.d.ts.map +1 -1
  107. package/dest/test/mock_structs.js +157 -11
  108. package/dest/test/noop_l1_archiver.d.ts +26 -0
  109. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  110. package/dest/test/noop_l1_archiver.js +74 -0
  111. package/package.json +20 -20
  112. package/src/archiver.ts +566 -0
  113. package/src/{archiver/config.ts → config.ts} +51 -14
  114. package/src/errors.ts +213 -0
  115. package/src/factory.ts +155 -17
  116. package/src/index.ts +12 -3
  117. package/src/interfaces.ts +9 -0
  118. package/src/l1/README.md +55 -0
  119. package/src/l1/bin/retrieve-calldata.ts +194 -0
  120. package/src/l1/calldata_retriever.ts +523 -0
  121. package/src/{archiver → l1}/data_retrieval.ts +155 -247
  122. package/src/l1/debug_tx.ts +99 -0
  123. package/src/l1/spire_proposer.ts +152 -0
  124. package/src/l1/trace_tx.ts +128 -0
  125. package/src/l1/types.ts +13 -0
  126. package/src/l1/validate_historical_logs.ts +140 -0
  127. package/src/l1/validate_trace.ts +229 -0
  128. package/src/modules/data_source_base.ts +364 -0
  129. package/src/modules/data_store_updater.ts +465 -0
  130. package/src/modules/instrumentation.ts +204 -0
  131. package/src/modules/l1_synchronizer.ts +1126 -0
  132. package/src/{archiver → modules}/validation.ts +21 -15
  133. package/src/store/block_store.ts +1361 -0
  134. package/src/store/contract_class_store.ts +82 -0
  135. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +10 -7
  136. package/src/store/kv_archiver_store.ts +765 -0
  137. package/src/store/l2_tips_cache.ts +134 -0
  138. package/src/store/log_store.ts +733 -0
  139. package/src/{archiver/kv_archiver_store → store}/message_store.ts +48 -28
  140. package/src/{archiver/structs → structs}/inbox_message.ts +7 -7
  141. package/src/{archiver/structs → structs}/published.ts +0 -1
  142. package/src/test/fake_l1_state.ts +770 -0
  143. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  144. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  145. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  146. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  147. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  148. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  149. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  150. package/src/test/index.ts +4 -0
  151. package/src/test/mock_archiver.ts +23 -16
  152. package/src/test/mock_l1_to_l2_message_source.ts +19 -11
  153. package/src/test/mock_l2_block_source.ts +367 -93
  154. package/src/test/mock_structs.ts +289 -13
  155. package/src/test/noop_l1_archiver.ts +117 -0
  156. package/dest/archiver/archiver.d.ts +0 -287
  157. package/dest/archiver/archiver.d.ts.map +0 -1
  158. package/dest/archiver/archiver.js +0 -1408
  159. package/dest/archiver/archiver_store.d.ts +0 -255
  160. package/dest/archiver/archiver_store.d.ts.map +0 -1
  161. package/dest/archiver/archiver_store.js +0 -4
  162. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  163. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  164. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  165. package/dest/archiver/config.d.ts +0 -21
  166. package/dest/archiver/config.d.ts.map +0 -1
  167. package/dest/archiver/config.js +0 -55
  168. package/dest/archiver/data_retrieval.d.ts +0 -79
  169. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  170. package/dest/archiver/errors.d.ts +0 -12
  171. package/dest/archiver/errors.d.ts.map +0 -1
  172. package/dest/archiver/errors.js +0 -17
  173. package/dest/archiver/index.d.ts +0 -7
  174. package/dest/archiver/index.d.ts.map +0 -1
  175. package/dest/archiver/index.js +0 -4
  176. package/dest/archiver/instrumentation.d.ts +0 -35
  177. package/dest/archiver/instrumentation.d.ts.map +0 -1
  178. package/dest/archiver/instrumentation.js +0 -140
  179. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  180. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  181. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  182. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  183. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  184. package/dest/archiver/kv_archiver_store/contract_class_store.js +0 -120
  185. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  186. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  187. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  188. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  189. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  190. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  191. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  192. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  193. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  194. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  195. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  196. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  197. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  198. package/dest/archiver/structs/published.d.ts +0 -3
  199. package/dest/archiver/structs/published.d.ts.map +0 -1
  200. package/dest/archiver/validation.d.ts +0 -17
  201. package/dest/archiver/validation.d.ts.map +0 -1
  202. package/dest/rpc/index.d.ts +0 -9
  203. package/dest/rpc/index.d.ts.map +0 -1
  204. package/dest/rpc/index.js +0 -15
  205. package/src/archiver/archiver.ts +0 -1858
  206. package/src/archiver/archiver_store.ts +0 -305
  207. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  208. package/src/archiver/errors.ts +0 -26
  209. package/src/archiver/index.ts +0 -6
  210. package/src/archiver/instrumentation.ts +0 -187
  211. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  212. package/src/archiver/kv_archiver_store/contract_class_store.ts +0 -176
  213. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  214. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  215. package/src/rpc/index.ts +0 -16
  216. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  217. /package/dest/{archiver/structs → structs}/published.js +0 -0
  218. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -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,152 @@
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 all wrapped calls if validation succeeds (caller handles hash matching to find the propose 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 Array of wrapped calls with 'to' and 'data', or undefined if not a valid Spire Proposer tx
95
+ */
96
+ export async function getCallsFromSpireProposer(
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
+ // Return all wrapped calls (hash matching in the caller determines which is the propose call)
145
+ logger.trace(`Decoded Spire Proposer with ${calls.length} call(s)`, { txHash });
146
+ return calls.map(call => ({ to: call.target, data: call.data }));
147
+ } catch (err) {
148
+ // Any decoding error triggers fallback to trace
149
+ logger.warn(`Failed to decode Spire Proposer: ${err}`, { txHash });
150
+ return undefined;
151
+ }
152
+ }
@@ -0,0 +1,128 @@
1
+ import type { 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 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
+ }
@@ -0,0 +1,140 @@
1
+ import { getPublicClient, getRpcUrlsFromClient } from '@aztec/ethereum/client';
2
+ import { RollupContract } from '@aztec/ethereum/contracts';
3
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
4
+ import type { ViemPublicClient } from '@aztec/ethereum/types';
5
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
6
+
7
+ /** Subset of L1 contract addresses whose historical logs the Aztec node relies on. */
8
+ export type HistoricalLogsContractAddresses = Pick<
9
+ L1ContractAddresses,
10
+ 'rollupAddress' | 'inboxAddress' | 'registryAddress' | 'governanceProposerAddress'
11
+ >;
12
+
13
+ /** Result of probing a single RPC URL. */
14
+ type ProbeResult = { ok: true } | { ok: false; reason: string; clientVersion: string | undefined };
15
+
16
+ /**
17
+ * Validates that every configured L1 RPC URL returns historical logs for the Rollup contract.
18
+ *
19
+ * Some RPC providers prune old logs, which would cause L1 syncing to silently fail. To detect this,
20
+ * we query for the `OwnershipTransferred` event which every Rollup emits in its constructor (via
21
+ * Ownable) on the block it was deployed (`l1StartBlock`). The `client` is typically a viem fallback
22
+ * transport over several user-configured RPC URLs — checking only the first URL would miss a bad
23
+ * secondary, so we probe each URL independently. The first URL that fails aborts startup, unless
24
+ * the operator has explicitly opted out.
25
+ *
26
+ * @param client - The L1 public client built from the user-configured RPC URLs.
27
+ * @param addresses - The subset of L1 contract addresses we rely on for historical log retrieval.
28
+ * @param skipCheck - If true, log warnings instead of throwing.
29
+ * @param bindings - Optional logger bindings for context.
30
+ * @throws Error if any URL fails the probe and skipCheck is false.
31
+ */
32
+ export async function validateAndLogHistoricalLogsAvailability(
33
+ client: ViemPublicClient,
34
+ addresses: HistoricalLogsContractAddresses,
35
+ skipCheck: boolean,
36
+ bindings?: LoggerBindings,
37
+ ): Promise<void> {
38
+ const logger = createLogger('archiver:validate_historical_logs', bindings);
39
+ logger.debug('Validating historical log availability on L1 RPCs');
40
+
41
+ const urls = getRpcUrlsFromClient(client);
42
+ if (urls.length === 0) {
43
+ logger.warn('Could not determine L1 RPC URLs from the public client; skipping historical logs check.');
44
+ return;
45
+ }
46
+
47
+ const chainId = client.chain?.id;
48
+ if (chainId === undefined) {
49
+ logger.warn('Could not determine L1 chain ID from the public client; skipping historical logs check.');
50
+ return;
51
+ }
52
+
53
+ for (const url of urls) {
54
+ const probeClient = getPublicClient({ l1RpcUrls: [url], l1ChainId: chainId });
55
+ const rollup = new RollupContract(probeClient, addresses.rollupAddress.toString());
56
+ const result = await probeRpcUrl(rollup, probeClient, logger);
57
+
58
+ if (result.ok) {
59
+ logger.debug(`L1 RPC ${url} returned historical OwnershipTransferred log for the Rollup contract.`);
60
+ continue;
61
+ }
62
+
63
+ const errorMessage = buildErrorMessage(url, result, addresses);
64
+ if (skipCheck) {
65
+ logger.warn(`${errorMessage}\nContinuing because ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK is true.`);
66
+ continue;
67
+ }
68
+
69
+ logger.error(errorMessage);
70
+ throw new Error(errorMessage);
71
+ }
72
+ }
73
+
74
+ /** Runs the OwnershipTransferred probe against a single RPC and queries its client version. */
75
+ async function probeRpcUrl(rollup: RollupContract, client: ViemPublicClient, logger: Logger): Promise<ProbeResult> {
76
+ let queryError: unknown;
77
+ try {
78
+ const logs = await rollup.getOwnershipTransferredEventsAtDeploy();
79
+ if (logs.length > 0) {
80
+ return { ok: true };
81
+ }
82
+ } catch (err) {
83
+ queryError = err;
84
+ }
85
+
86
+ const clientVersion = await getClientVersion(client, logger);
87
+
88
+ let reason: string;
89
+ if (queryError instanceof Error) {
90
+ reason = `Query for historical logs failed: ${queryError.message}`;
91
+ } else if (queryError !== undefined) {
92
+ reason = 'Query for historical logs failed with a non-Error value.';
93
+ } else {
94
+ reason = 'No OwnershipTransferred event was returned by the L1 RPC for the Rollup deploy block.';
95
+ }
96
+ return { ok: false, reason, clientVersion };
97
+ }
98
+
99
+ /** Builds the operator-facing error message for a failing RPC URL. */
100
+ function buildErrorMessage(
101
+ url: string,
102
+ result: Extract<ProbeResult, { ok: false }>,
103
+ addresses: HistoricalLogsContractAddresses,
104
+ ): string {
105
+ return [
106
+ `L1 RPC at ${url} does not return historical logs for the Rollup contract. ${result.reason}`,
107
+ `This likely means this Ethereum RPC node prunes old logs, which would cause the archiver ` +
108
+ `to silently miss data during L1 sync.`,
109
+ result.clientVersion
110
+ ? `Detected L1 client version for ${url}: ${result.clientVersion}.`
111
+ : `Could not determine L1 client version for ${url}.`,
112
+ `The following L1 contract addresses must have their historical logs retained by the RPC node:`,
113
+ ` - Rollup: ${addresses.rollupAddress.toString()}`,
114
+ ` - Inbox: ${addresses.inboxAddress.toString()}`,
115
+ ` - Registry: ${addresses.registryAddress.toString()}`,
116
+ ` - GovernanceProposer: ${addresses.governanceProposerAddress.toString()}`,
117
+ isReth(result.clientVersion)
118
+ ? `To retain logs for these contracts, configure reth with a ` +
119
+ `prune.segments.receipts_log_filter entry for each address above ` +
120
+ `so reth does not prune their receipts/logs. See https://reth.rs/run/pruning.html for details.`
121
+ : `Point this RPC endpoint at a node that retains full log history for the addresses above.`,
122
+ `Set ARCHIVER_SKIP_HISTORICAL_LOGS_CHECK=true to bypass this check at your own risk.`,
123
+ ].join('\n');
124
+ }
125
+
126
+ /** Queries `web3_clientVersion` on the L1 RPC. Returns undefined if the call fails or returns a non-string. */
127
+ async function getClientVersion(client: ViemPublicClient, logger: Logger): Promise<string | undefined> {
128
+ try {
129
+ const result = await client.request({ method: 'web3_clientVersion' });
130
+ return typeof result === 'string' ? result : undefined;
131
+ } catch (err) {
132
+ logger.debug(`Failed to query web3_clientVersion: ${err instanceof Error ? err.message : err}`);
133
+ return undefined;
134
+ }
135
+ }
136
+
137
+ /** Heuristic check for reth based on the web3_clientVersion string (reth returns e.g. "reth/v1.0.0-..."). */
138
+ function isReth(clientVersion: string | undefined): boolean {
139
+ return !!clientVersion && /reth/i.test(clientVersion);
140
+ }