@aztec/archiver 0.0.1-commit.fce3e4f → 0.0.1-commit.ff7989d6c

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 (209) hide show
  1. package/README.md +156 -22
  2. package/dest/archiver.d.ts +139 -0
  3. package/dest/archiver.d.ts.map +1 -0
  4. package/dest/archiver.js +699 -0
  5. package/dest/config.d.ts +30 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/{archiver/config.js → config.js} +21 -5
  8. package/dest/errors.d.ts +41 -0
  9. package/dest/errors.d.ts.map +1 -0
  10. package/dest/errors.js +62 -0
  11. package/dest/factory.d.ts +9 -7
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +97 -13
  14. package/dest/index.d.ts +11 -4
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +9 -3
  17. package/dest/interfaces.d.ts +9 -0
  18. package/dest/interfaces.d.ts.map +1 -0
  19. package/dest/interfaces.js +3 -0
  20. package/dest/l1/bin/retrieve-calldata.d.ts +3 -0
  21. package/dest/l1/bin/retrieve-calldata.d.ts.map +1 -0
  22. package/dest/l1/bin/retrieve-calldata.js +148 -0
  23. package/dest/l1/calldata_retriever.d.ts +118 -0
  24. package/dest/l1/calldata_retriever.d.ts.map +1 -0
  25. package/dest/l1/calldata_retriever.js +484 -0
  26. package/dest/l1/data_retrieval.d.ts +89 -0
  27. package/dest/l1/data_retrieval.d.ts.map +1 -0
  28. package/dest/{archiver → l1}/data_retrieval.js +80 -153
  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 +157 -0
  35. package/dest/l1/trace_tx.d.ts +97 -0
  36. package/dest/l1/trace_tx.d.ts.map +1 -0
  37. package/dest/l1/trace_tx.js +91 -0
  38. package/dest/l1/types.d.ts +12 -0
  39. package/dest/l1/types.d.ts.map +1 -0
  40. package/dest/l1/types.js +3 -0
  41. package/dest/l1/validate_trace.d.ts +32 -0
  42. package/dest/l1/validate_trace.d.ts.map +1 -0
  43. package/dest/l1/validate_trace.js +154 -0
  44. package/dest/modules/data_source_base.d.ts +89 -0
  45. package/dest/modules/data_source_base.d.ts.map +1 -0
  46. package/dest/modules/data_source_base.js +216 -0
  47. package/dest/modules/data_store_updater.d.ts +80 -0
  48. package/dest/modules/data_store_updater.d.ts.map +1 -0
  49. package/dest/modules/data_store_updater.js +323 -0
  50. package/dest/modules/instrumentation.d.ts +39 -0
  51. package/dest/modules/instrumentation.d.ts.map +1 -0
  52. package/dest/{archiver → modules}/instrumentation.js +39 -62
  53. package/dest/modules/l1_synchronizer.d.ts +76 -0
  54. package/dest/modules/l1_synchronizer.d.ts.map +1 -0
  55. package/dest/modules/l1_synchronizer.js +1112 -0
  56. package/dest/modules/validation.d.ts +17 -0
  57. package/dest/modules/validation.d.ts.map +1 -0
  58. package/dest/{archiver → modules}/validation.js +7 -1
  59. package/dest/store/block_store.d.ts +196 -0
  60. package/dest/store/block_store.d.ts.map +1 -0
  61. package/dest/store/block_store.js +773 -0
  62. package/dest/store/contract_class_store.d.ts +18 -0
  63. package/dest/store/contract_class_store.d.ts.map +1 -0
  64. package/dest/{archiver/kv_archiver_store → store}/contract_class_store.js +13 -9
  65. package/dest/store/contract_instance_store.d.ts +24 -0
  66. package/dest/store/contract_instance_store.d.ts.map +1 -0
  67. package/dest/{archiver/kv_archiver_store → store}/contract_instance_store.js +1 -1
  68. package/dest/store/kv_archiver_store.d.ts +354 -0
  69. package/dest/store/kv_archiver_store.d.ts.map +1 -0
  70. package/dest/store/kv_archiver_store.js +464 -0
  71. package/dest/store/l2_tips_cache.d.ts +19 -0
  72. package/dest/store/l2_tips_cache.d.ts.map +1 -0
  73. package/dest/store/l2_tips_cache.js +89 -0
  74. package/dest/store/log_store.d.ts +54 -0
  75. package/dest/store/log_store.d.ts.map +1 -0
  76. package/dest/store/log_store.js +456 -0
  77. package/dest/store/message_store.d.ts +40 -0
  78. package/dest/store/message_store.d.ts.map +1 -0
  79. package/dest/{archiver/kv_archiver_store → store}/message_store.js +15 -14
  80. package/dest/{archiver/structs → structs}/data_retrieval.d.ts +1 -1
  81. package/dest/structs/data_retrieval.d.ts.map +1 -0
  82. package/dest/structs/inbox_message.d.ts +15 -0
  83. package/dest/structs/inbox_message.d.ts.map +1 -0
  84. package/dest/{archiver/structs → structs}/inbox_message.js +6 -5
  85. package/dest/structs/published.d.ts +2 -0
  86. package/dest/structs/published.d.ts.map +1 -0
  87. package/dest/test/fake_l1_state.d.ts +193 -0
  88. package/dest/test/fake_l1_state.d.ts.map +1 -0
  89. package/dest/test/fake_l1_state.js +389 -0
  90. package/dest/test/index.d.ts +2 -1
  91. package/dest/test/index.d.ts.map +1 -1
  92. package/dest/test/index.js +4 -1
  93. package/dest/test/mock_archiver.d.ts +16 -8
  94. package/dest/test/mock_archiver.d.ts.map +1 -1
  95. package/dest/test/mock_archiver.js +19 -14
  96. package/dest/test/mock_l1_to_l2_message_source.d.ts +7 -6
  97. package/dest/test/mock_l1_to_l2_message_source.d.ts.map +1 -1
  98. package/dest/test/mock_l1_to_l2_message_source.js +21 -11
  99. package/dest/test/mock_l2_block_source.d.ts +51 -18
  100. package/dest/test/mock_l2_block_source.d.ts.map +1 -1
  101. package/dest/test/mock_l2_block_source.js +245 -82
  102. package/dest/test/mock_structs.d.ts +80 -4
  103. package/dest/test/mock_structs.d.ts.map +1 -1
  104. package/dest/test/mock_structs.js +145 -11
  105. package/dest/test/noop_l1_archiver.d.ts +23 -0
  106. package/dest/test/noop_l1_archiver.d.ts.map +1 -0
  107. package/dest/test/noop_l1_archiver.js +68 -0
  108. package/package.json +20 -20
  109. package/src/archiver.ts +443 -0
  110. package/src/{archiver/config.ts → config.ts} +28 -12
  111. package/src/errors.ts +102 -0
  112. package/src/factory.ts +143 -13
  113. package/src/index.ts +11 -3
  114. package/src/interfaces.ts +9 -0
  115. package/src/l1/README.md +98 -0
  116. package/src/l1/bin/retrieve-calldata.ts +181 -0
  117. package/src/l1/calldata_retriever.ts +663 -0
  118. package/src/{archiver → l1}/data_retrieval.ts +146 -224
  119. package/src/l1/debug_tx.ts +99 -0
  120. package/src/l1/spire_proposer.ts +160 -0
  121. package/src/l1/trace_tx.ts +128 -0
  122. package/src/l1/types.ts +13 -0
  123. package/src/l1/validate_trace.ts +229 -0
  124. package/src/modules/data_source_base.ts +328 -0
  125. package/src/modules/data_store_updater.ts +448 -0
  126. package/src/{archiver → modules}/instrumentation.ts +43 -66
  127. package/src/modules/l1_synchronizer.ts +932 -0
  128. package/src/{archiver → modules}/validation.ts +11 -6
  129. package/src/store/block_store.ts +1015 -0
  130. package/src/{archiver/kv_archiver_store → store}/contract_class_store.ts +13 -9
  131. package/src/{archiver/kv_archiver_store → store}/contract_instance_store.ts +2 -2
  132. package/src/store/kv_archiver_store.ts +671 -0
  133. package/src/store/l2_tips_cache.ts +89 -0
  134. package/src/store/log_store.ts +637 -0
  135. package/src/{archiver/kv_archiver_store → store}/message_store.ts +21 -18
  136. package/src/{archiver/structs → structs}/inbox_message.ts +8 -8
  137. package/src/{archiver/structs → structs}/published.ts +0 -1
  138. package/src/test/fake_l1_state.ts +607 -0
  139. package/src/test/fixtures/debug_traceTransaction-multicall3.json +88 -0
  140. package/src/test/fixtures/debug_traceTransaction-multiplePropose.json +153 -0
  141. package/src/test/fixtures/debug_traceTransaction-proxied.json +122 -0
  142. package/src/test/fixtures/trace_transaction-multicall3.json +65 -0
  143. package/src/test/fixtures/trace_transaction-multiplePropose.json +319 -0
  144. package/src/test/fixtures/trace_transaction-proxied.json +128 -0
  145. package/src/test/fixtures/trace_transaction-randomRevert.json +216 -0
  146. package/src/test/index.ts +4 -0
  147. package/src/test/mock_archiver.ts +23 -16
  148. package/src/test/mock_l1_to_l2_message_source.ts +18 -11
  149. package/src/test/mock_l2_block_source.ts +296 -90
  150. package/src/test/mock_structs.ts +275 -13
  151. package/src/test/noop_l1_archiver.ts +109 -0
  152. package/dest/archiver/archiver.d.ts +0 -287
  153. package/dest/archiver/archiver.d.ts.map +0 -1
  154. package/dest/archiver/archiver.js +0 -1408
  155. package/dest/archiver/archiver_store.d.ts +0 -255
  156. package/dest/archiver/archiver_store.d.ts.map +0 -1
  157. package/dest/archiver/archiver_store.js +0 -4
  158. package/dest/archiver/archiver_store_test_suite.d.ts +0 -8
  159. package/dest/archiver/archiver_store_test_suite.d.ts.map +0 -1
  160. package/dest/archiver/archiver_store_test_suite.js +0 -1289
  161. package/dest/archiver/config.d.ts +0 -21
  162. package/dest/archiver/config.d.ts.map +0 -1
  163. package/dest/archiver/data_retrieval.d.ts +0 -79
  164. package/dest/archiver/data_retrieval.d.ts.map +0 -1
  165. package/dest/archiver/errors.d.ts +0 -12
  166. package/dest/archiver/errors.d.ts.map +0 -1
  167. package/dest/archiver/errors.js +0 -17
  168. package/dest/archiver/index.d.ts +0 -7
  169. package/dest/archiver/index.d.ts.map +0 -1
  170. package/dest/archiver/index.js +0 -4
  171. package/dest/archiver/instrumentation.d.ts +0 -35
  172. package/dest/archiver/instrumentation.d.ts.map +0 -1
  173. package/dest/archiver/kv_archiver_store/block_store.d.ts +0 -124
  174. package/dest/archiver/kv_archiver_store/block_store.d.ts.map +0 -1
  175. package/dest/archiver/kv_archiver_store/block_store.js +0 -370
  176. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts +0 -18
  177. package/dest/archiver/kv_archiver_store/contract_class_store.d.ts.map +0 -1
  178. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts +0 -24
  179. package/dest/archiver/kv_archiver_store/contract_instance_store.d.ts.map +0 -1
  180. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts +0 -168
  181. package/dest/archiver/kv_archiver_store/kv_archiver_store.d.ts.map +0 -1
  182. package/dest/archiver/kv_archiver_store/kv_archiver_store.js +0 -296
  183. package/dest/archiver/kv_archiver_store/log_store.d.ts +0 -49
  184. package/dest/archiver/kv_archiver_store/log_store.d.ts.map +0 -1
  185. package/dest/archiver/kv_archiver_store/log_store.js +0 -336
  186. package/dest/archiver/kv_archiver_store/message_store.d.ts +0 -39
  187. package/dest/archiver/kv_archiver_store/message_store.d.ts.map +0 -1
  188. package/dest/archiver/structs/data_retrieval.d.ts.map +0 -1
  189. package/dest/archiver/structs/inbox_message.d.ts +0 -15
  190. package/dest/archiver/structs/inbox_message.d.ts.map +0 -1
  191. package/dest/archiver/structs/published.d.ts +0 -3
  192. package/dest/archiver/structs/published.d.ts.map +0 -1
  193. package/dest/archiver/validation.d.ts +0 -17
  194. package/dest/archiver/validation.d.ts.map +0 -1
  195. package/dest/rpc/index.d.ts +0 -9
  196. package/dest/rpc/index.d.ts.map +0 -1
  197. package/dest/rpc/index.js +0 -15
  198. package/src/archiver/archiver.ts +0 -1858
  199. package/src/archiver/archiver_store.ts +0 -305
  200. package/src/archiver/archiver_store_test_suite.ts +0 -1264
  201. package/src/archiver/errors.ts +0 -26
  202. package/src/archiver/index.ts +0 -6
  203. package/src/archiver/kv_archiver_store/block_store.ts +0 -481
  204. package/src/archiver/kv_archiver_store/kv_archiver_store.ts +0 -422
  205. package/src/archiver/kv_archiver_store/log_store.ts +0 -406
  206. package/src/rpc/index.ts +0 -16
  207. /package/dest/{archiver/structs → structs}/data_retrieval.js +0 -0
  208. /package/dest/{archiver/structs → structs}/published.js +0 -0
  209. /package/src/{archiver/structs → structs}/data_retrieval.ts +0 -0
@@ -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/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,229 @@
1
+ import type { ViemPublicDebugClient } from '@aztec/ethereum/types';
2
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
3
+
4
+ import type { Hex } from 'viem';
5
+ import type { ZodSchema } from 'zod';
6
+
7
+ import { callTraceSchema } from './debug_tx.js';
8
+ import { traceTransactionResponseSchema } from './trace_tx.js';
9
+
10
+ /**
11
+ * Helper function to test a trace method with validation
12
+ *
13
+ * @param client - The Viem public debug client
14
+ * @param txHash - Transaction hash to trace
15
+ * @param schema - Zod schema to validate the response
16
+ * @param method - Name of the RPC method ('debug_traceTransaction' or 'trace_transaction')
17
+ * @param blockType - Type of block being tested ('recent' or 'old')
18
+ * @param logger - Logger instance
19
+ * @returns true if the method works and validation passes, false otherwise
20
+ */
21
+ async function testTraceMethod(
22
+ client: ViemPublicDebugClient,
23
+ txHash: Hex,
24
+ schema: ZodSchema,
25
+ method: 'debug_traceTransaction' | 'trace_transaction',
26
+ blockType: string,
27
+ logger: Logger,
28
+ ): Promise<boolean> {
29
+ try {
30
+ // Make request with appropriate params based on method name
31
+ const result = await client.request(
32
+ method === 'debug_traceTransaction'
33
+ ? { method, params: [txHash, { tracer: 'callTracer' }] }
34
+ : { method, params: [txHash] },
35
+ );
36
+
37
+ schema.parse(result);
38
+ logger.debug(`${method} works for ${blockType} blocks`);
39
+ return true;
40
+ } catch (error) {
41
+ logger.warn(`${method} failed for ${blockType} blocks: ${error}`);
42
+ return false;
43
+ }
44
+ }
45
+
46
+ /** Result of trace availability checks */
47
+ export interface TraceAvailability {
48
+ /** Whether debug_traceTransaction works for recent blocks */
49
+ debugTraceRecent: boolean;
50
+ /** Whether trace_transaction works for recent blocks */
51
+ traceTransactionRecent: boolean;
52
+ /** Whether debug_traceTransaction works for old blocks (512 blocks ago) */
53
+ debugTraceOld: boolean;
54
+ /** Whether trace_transaction works for old blocks (512 blocks ago) */
55
+ traceTransactionOld: boolean;
56
+ }
57
+
58
+ /**
59
+ * Validates the availability of debug/trace methods on the Ethereum client.
60
+ *
61
+ * @param client - The Viem public debug client
62
+ * @param bindings - Optional logger bindings for context
63
+ * @returns Object indicating which trace methods are available for recent and old blocks
64
+ */
65
+ export async function validateTraceAvailability(
66
+ client: ViemPublicDebugClient,
67
+ bindings?: LoggerBindings,
68
+ ): Promise<TraceAvailability> {
69
+ const logger = createLogger('archiver:validate_trace', bindings);
70
+ const result: TraceAvailability = {
71
+ debugTraceRecent: false,
72
+ traceTransactionRecent: false,
73
+ debugTraceOld: false,
74
+ traceTransactionOld: false,
75
+ };
76
+
77
+ try {
78
+ // Get the latest block
79
+ let latestBlock = await client.getBlock({ blockTag: 'latest' });
80
+ let attempts = 10;
81
+
82
+ // Loop back to find a block with transactions (handles dev/test scenarios)
83
+ while (!hasTxs(latestBlock) && latestBlock.number && latestBlock.number > 0n && --attempts > 0) {
84
+ logger.debug(`Block ${latestBlock.number} has no transactions, checking previous block`);
85
+ latestBlock = await client.getBlock({ blockNumber: latestBlock.number - 1n });
86
+ }
87
+
88
+ if (!hasTxs(latestBlock)) {
89
+ logger.warn('No blocks with transactions found from latest back to genesis, cannot validate trace availability');
90
+ return result;
91
+ }
92
+
93
+ // Get a transaction from the found block
94
+ const recentTxHash = latestBlock.transactions[0] as Hex;
95
+
96
+ // Test debug_traceTransaction with recent block
97
+ result.debugTraceRecent = await testTraceMethod(
98
+ client,
99
+ recentTxHash,
100
+ callTraceSchema,
101
+ 'debug_traceTransaction',
102
+ 'recent',
103
+ logger,
104
+ );
105
+
106
+ // Test trace_transaction with recent block
107
+ result.traceTransactionRecent = await testTraceMethod(
108
+ client,
109
+ recentTxHash,
110
+ traceTransactionResponseSchema,
111
+ 'trace_transaction',
112
+ 'recent',
113
+ logger,
114
+ );
115
+
116
+ // Get a block from 512 blocks ago
117
+ const oldBlockNumber = latestBlock.number ? latestBlock.number - 512n : null;
118
+ if (!oldBlockNumber || oldBlockNumber < 0n) {
119
+ logger.debug('Cannot test old blocks, blockchain too short');
120
+ return result;
121
+ }
122
+
123
+ let oldBlock = await client.getBlock({ blockNumber: oldBlockNumber });
124
+ attempts = 10;
125
+
126
+ // Loop back to find a block with transactions (handles dev/test scenarios)
127
+ while (!hasTxs(oldBlock) && oldBlock.number && oldBlock.number > 0n && --attempts > 0) {
128
+ logger.debug(`Block ${oldBlock.number} has no transactions, checking previous block`);
129
+ oldBlock = await client.getBlock({ blockNumber: oldBlock.number - 1n });
130
+ }
131
+
132
+ if (!hasTxs(oldBlock)) {
133
+ logger.debug(
134
+ 'No blocks with transactions found from old block back to genesis, cannot validate trace availability for old blocks',
135
+ );
136
+ return result;
137
+ }
138
+
139
+ const oldTxHash = oldBlock.transactions[0] as Hex;
140
+
141
+ // Test debug_traceTransaction with old block
142
+ result.debugTraceOld = await testTraceMethod(
143
+ client,
144
+ oldTxHash,
145
+ callTraceSchema,
146
+ 'debug_traceTransaction',
147
+ 'old',
148
+ logger,
149
+ );
150
+
151
+ // Test trace_transaction with old block
152
+ result.traceTransactionOld = await testTraceMethod(
153
+ client,
154
+ oldTxHash,
155
+ traceTransactionResponseSchema,
156
+ 'trace_transaction',
157
+ 'old',
158
+ logger,
159
+ );
160
+ } catch (error) {
161
+ logger.warn(`Error validating debug_traceTransaction and trace_transaction availability: ${error}`);
162
+ }
163
+
164
+ return result;
165
+ }
166
+
167
+ function hasTxs(block: { transactions?: Hex[] }): boolean {
168
+ return Array.isArray(block.transactions) && block.transactions.length > 0;
169
+ }
170
+
171
+ /**
172
+ * Validates trace availability and logs appropriate messages based on the results.
173
+ * Optionally throws an error if no trace methods are available and ethereumAllowNoDebugHosts is false.
174
+ *
175
+ * @param client - The Viem public debug client
176
+ * @param ethereumAllowNoDebugHosts - If false, throws an error when no trace methods are available
177
+ * @param bindings - Optional logger bindings for context
178
+ * @throws Error if ethereumAllowNoDebugHosts is false and no trace methods are available
179
+ */
180
+ export async function validateAndLogTraceAvailability(
181
+ client: ViemPublicDebugClient,
182
+ ethereumAllowNoDebugHosts: boolean,
183
+ bindings?: LoggerBindings,
184
+ ): Promise<void> {
185
+ const logger = createLogger('archiver:validate_trace', bindings);
186
+ logger.debug('Validating trace/debug method availability...');
187
+
188
+ const availability = await validateTraceAvailability(client, bindings);
189
+
190
+ // Check if we have support for old blocks (either debug or trace)
191
+ const hasOldBlockSupport = availability.debugTraceOld || availability.traceTransactionOld;
192
+
193
+ if (hasOldBlockSupport) {
194
+ // Ideal case: we have trace support for old blocks
195
+ const methods: string[] = [];
196
+ if (availability.debugTraceOld) {
197
+ methods.push('debug_traceTransaction');
198
+ }
199
+ if (availability.traceTransactionOld) {
200
+ methods.push('trace_transaction');
201
+ }
202
+ logger.info(
203
+ `Ethereum client supports trace methods for old blocks (${methods.join(', ')}). Archiver can retrieve historical transaction traces.`,
204
+ );
205
+ } else if (availability.debugTraceRecent || availability.traceTransactionRecent) {
206
+ // Warning case: only recent block support
207
+ const methods: string[] = [];
208
+ if (availability.debugTraceRecent) {
209
+ methods.push('debug_traceTransaction');
210
+ }
211
+ if (availability.traceTransactionRecent) {
212
+ methods.push('trace_transaction');
213
+ }
214
+ logger.warn(
215
+ `Ethereum client only supports trace methods for recent blocks (${methods.join(', ')}). Historical transaction traces may not be available.`,
216
+ );
217
+ } else {
218
+ // Error case: no support at all
219
+ const errorMessage =
220
+ 'Ethereum debug client does not support debug_traceTransaction or trace_transaction methods. Transaction tracing will not be available. This may impact archiver syncing.';
221
+
222
+ if (ethereumAllowNoDebugHosts) {
223
+ logger.warn(`${errorMessage} Continuing because ETHEREUM_ALLOW_NO_DEBUG_HOSTS is set to true.`);
224
+ } else {
225
+ logger.error(errorMessage);
226
+ throw new Error(`${errorMessage} Set ETHEREUM_ALLOW_NO_DEBUG_HOSTS=true to bypass this check.`);
227
+ }
228
+ }
229
+ }