@aztec/pxe 0.0.1-commit.321f6a9 → 0.0.1-commit.330febf

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 (124) hide show
  1. package/dest/bin/check_oracle_version.js +2 -38
  2. package/dest/bin/index.d.ts +2 -2
  3. package/dest/bin/index.d.ts.map +1 -1
  4. package/dest/bin/index.js +1 -1
  5. package/dest/bin/oracle_version_helpers.d.ts +1 -15
  6. package/dest/bin/oracle_version_helpers.d.ts.map +1 -1
  7. package/dest/bin/oracle_version_helpers.js +0 -21
  8. package/dest/block_synchronizer/block_synchronizer.d.ts +3 -5
  9. package/dest/block_synchronizer/block_synchronizer.d.ts.map +1 -1
  10. package/dest/block_synchronizer/block_synchronizer.js +5 -18
  11. package/dest/contract/contract_class_service.d.ts +1 -8
  12. package/dest/contract/contract_class_service.d.ts.map +1 -1
  13. package/dest/contract/contract_class_service.js +8 -40
  14. package/dest/contract_function_simulator/contract_function_simulator.d.ts +1 -8
  15. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  16. package/dest/contract_function_simulator/contract_function_simulator.js +0 -17
  17. package/dest/contract_function_simulator/oracle/oracle_type_mappings.d.ts +1 -1
  18. package/dest/contract_function_simulator/oracle/oracle_type_mappings.d.ts.map +1 -1
  19. package/dest/contract_function_simulator/oracle/oracle_type_mappings.js +11 -1
  20. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +1 -1
  21. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  22. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +6 -2
  23. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +10 -2
  24. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  25. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +128 -38
  26. package/dest/events/event_service.d.ts +13 -6
  27. package/dest/events/event_service.d.ts.map +1 -1
  28. package/dest/events/event_service.js +13 -13
  29. package/dest/logs/log_service.d.ts +13 -5
  30. package/dest/logs/log_service.d.ts.map +1 -1
  31. package/dest/logs/log_service.js +20 -36
  32. package/dest/messages/tx_resolver_service.d.ts +18 -7
  33. package/dest/messages/tx_resolver_service.d.ts.map +1 -1
  34. package/dest/messages/tx_resolver_service.js +9 -8
  35. package/dest/node/benchmarked_node.d.ts +20 -0
  36. package/dest/node/benchmarked_node.d.ts.map +1 -0
  37. package/dest/node/benchmarked_node.js +94 -0
  38. package/dest/node/caching_aztec_node.d.ts +24 -0
  39. package/dest/node/caching_aztec_node.d.ts.map +1 -0
  40. package/dest/node/caching_aztec_node.js +267 -0
  41. package/dest/notes/note_service.d.ts +12 -6
  42. package/dest/notes/note_service.d.ts.map +1 -1
  43. package/dest/notes/note_service.js +9 -9
  44. package/dest/oracle_version.js +2 -2
  45. package/dest/pxe.d.ts +1 -1
  46. package/dest/pxe.d.ts.map +1 -1
  47. package/dest/pxe.js +31 -14
  48. package/dest/storage/contract_store/contract_store.d.ts +1 -1
  49. package/dest/storage/contract_store/contract_store.d.ts.map +1 -1
  50. package/dest/storage/contract_store/contract_store.js +2 -2
  51. package/dest/storage/fact_store/origin_state.d.ts +1 -1
  52. package/dest/storage/fact_store/origin_state.js +1 -1
  53. package/dest/storage/tagging_store/sender_tagging_store.d.ts +23 -8
  54. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  55. package/dest/storage/tagging_store/sender_tagging_store.js +33 -18
  56. package/dest/tagging/constants.d.ts +9 -1
  57. package/dest/tagging/constants.d.ts.map +1 -1
  58. package/dest/tagging/constants.js +10 -0
  59. package/dest/tagging/get_all_logs_by_tags.d.ts +29 -8
  60. package/dest/tagging/get_all_logs_by_tags.d.ts.map +1 -1
  61. package/dest/tagging/get_all_logs_by_tags.js +29 -10
  62. package/dest/tagging/index.d.ts +2 -2
  63. package/dest/tagging/index.d.ts.map +1 -1
  64. package/dest/tagging/index.js +1 -1
  65. package/dest/tagging/recipient_sync/sync_tagged_private_logs.d.ts +2 -2
  66. package/dest/tagging/recipient_sync/sync_tagged_private_logs.d.ts.map +1 -1
  67. package/dest/tagging/recipient_sync/sync_tagged_private_logs.js +13 -17
  68. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +6 -3
  69. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  70. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +23 -38
  71. package/dest/tagging/sender_sync/utils/classify_pending_txs.d.ts +22 -0
  72. package/dest/tagging/sender_sync/utils/classify_pending_txs.d.ts.map +1 -0
  73. package/dest/tagging/sender_sync/utils/classify_pending_txs.js +61 -0
  74. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +15 -5
  75. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  76. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +30 -33
  77. package/dest/tagging/sender_sync/utils/resolve_pending_txs.d.ts +29 -0
  78. package/dest/tagging/sender_sync/utils/resolve_pending_txs.d.ts.map +1 -0
  79. package/dest/tagging/sender_sync/utils/resolve_pending_txs.js +41 -0
  80. package/dest/tagging/sender_sync/utils/test_utils.d.ts +16 -0
  81. package/dest/tagging/sender_sync/utils/test_utils.d.ts.map +1 -0
  82. package/dest/tagging/sender_sync/utils/test_utils.js +24 -0
  83. package/package.json +17 -17
  84. package/src/bin/check_oracle_version.ts +2 -46
  85. package/src/bin/index.ts +1 -1
  86. package/src/bin/oracle_version_helpers.ts +0 -24
  87. package/src/block_synchronizer/block_synchronizer.ts +6 -23
  88. package/src/contract/contract_class_service.ts +8 -46
  89. package/src/contract_function_simulator/contract_function_simulator.ts +0 -17
  90. package/src/contract_function_simulator/oracle/oracle_type_mappings.ts +16 -1
  91. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +7 -2
  92. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +130 -40
  93. package/src/events/event_service.ts +24 -14
  94. package/src/logs/log_service.ts +37 -44
  95. package/src/messages/tx_resolver_service.ts +22 -11
  96. package/src/node/benchmarked_node.ts +140 -0
  97. package/src/node/caching_aztec_node.ts +406 -0
  98. package/src/notes/note_service.ts +19 -13
  99. package/src/oracle_version.ts +2 -2
  100. package/src/pxe.ts +32 -16
  101. package/src/storage/contract_store/contract_store.ts +2 -1
  102. package/src/storage/fact_store/origin_state.ts +1 -1
  103. package/src/storage/tagging_store/sender_tagging_store.ts +51 -26
  104. package/src/tagging/constants.ts +12 -0
  105. package/src/tagging/get_all_logs_by_tags.ts +47 -11
  106. package/src/tagging/index.ts +6 -1
  107. package/src/tagging/recipient_sync/sync_tagged_private_logs.ts +19 -22
  108. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +27 -57
  109. package/src/tagging/sender_sync/utils/classify_pending_txs.ts +91 -0
  110. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +40 -38
  111. package/src/tagging/sender_sync/utils/resolve_pending_txs.ts +64 -0
  112. package/src/tagging/sender_sync/utils/test_utils.ts +46 -0
  113. package/dest/contract_function_simulator/aztec_node_read_cache.d.ts +0 -39
  114. package/dest/contract_function_simulator/aztec_node_read_cache.d.ts.map +0 -1
  115. package/dest/contract_function_simulator/aztec_node_read_cache.js +0 -60
  116. package/dest/contract_function_simulator/benchmarked_node.d.ts +0 -9
  117. package/dest/contract_function_simulator/benchmarked_node.d.ts.map +0 -1
  118. package/dest/contract_function_simulator/benchmarked_node.js +0 -77
  119. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +0 -17
  120. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +0 -1
  121. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +0 -60
  122. package/src/contract_function_simulator/aztec_node_read_cache.ts +0 -89
  123. package/src/contract_function_simulator/benchmarked_node.ts +0 -103
  124. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +0 -66
@@ -1,10 +1,10 @@
1
- import { PRIVATE_LOG_CIPHERTEXT_LEN } from '@aztec/constants';
2
1
  import type { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import type { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import type { GrumpkinScalar, Point } from '@aztec/foundation/curves/grumpkin';
4
4
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
5
5
  import type { KeyStore } from '@aztec/key-store';
6
6
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
7
- import type { BlockHash, L2TipsProvider } from '@aztec/stdlib/block';
7
+ import type { L2TipsProvider } from '@aztec/stdlib/block';
8
8
  import type { CompleteAddress } from '@aztec/stdlib/contract';
9
9
  import type { AztecNode } from '@aztec/stdlib/interfaces/server';
10
10
  import {
@@ -15,20 +15,22 @@ import {
15
15
  computeSharedTaggingSecret,
16
16
  } from '@aztec/stdlib/logs';
17
17
  import type { BlockHeader } from '@aztec/stdlib/tx';
18
+ import type { UInt64 } from '@aztec/stdlib/types';
18
19
 
19
20
  import {
20
21
  type LogRetrievalRequest,
21
22
  LogSource,
22
23
  } from '../contract_function_simulator/noir-structs/log_retrieval_request.js';
23
- import type { LogRetrievalResponse } from '../contract_function_simulator/noir-structs/log_retrieval_response.js';
24
- import type { PendingTaggedLog } from '../contract_function_simulator/noir-structs/pending_tagged_log.js';
24
+ import type { TxOnchainContext } from '../messages/tx_resolver_service.js';
25
25
  import { AddressStore } from '../storage/address_store/address_store.js';
26
26
  import { assertAllowedScope } from '../storage/allowed_scopes.js';
27
27
  import type { RecipientTaggingStore } from '../storage/tagging_store/recipient_tagging_store.js';
28
28
  import type { TaggingSecretSourcesStore } from '../storage/tagging_store/tagging_secret_sources_store.js';
29
29
  import {
30
+ type LogQueryAnchor,
30
31
  getAllPrivateLogsByTags,
31
32
  getAllPublicLogsByTagsFromContract,
33
+ logQueryAnchorOf,
32
34
  syncTaggedPrivateLogs,
33
35
  } from '../tagging/index.js';
34
36
 
@@ -58,7 +60,7 @@ export class LogService {
58
60
  public async fetchLogsByTag(
59
61
  contractAddress: AztecAddress,
60
62
  logRetrievalRequests: LogRetrievalRequest[],
61
- ): Promise<LogRetrievalResponse[][]> {
63
+ ): Promise<RetrievedTaggedLog[][]> {
62
64
  for (const request of logRetrievalRequests) {
63
65
  if (!contractAddress.equals(request.contractAddress)) {
64
66
  throw new Error(`Got a log retrieval request from ${request.contractAddress}, expected ${contractAddress}`);
@@ -69,23 +71,23 @@ export class LogService {
69
71
  return [];
70
72
  }
71
73
 
72
- const anchorBlockHash = await this.anchorBlockHeader.hash();
74
+ const anchor = await logQueryAnchorOf(this.anchorBlockHeader);
73
75
 
74
76
  const [publicLogsPerRequest, privateLogsPerRequest] = await Promise.all([
75
- this.#fetchPublicLogs(contractAddress, logRetrievalRequests, anchorBlockHash),
76
- this.#fetchPrivateLogs(logRetrievalRequests, anchorBlockHash),
77
+ this.#fetchPublicLogs(contractAddress, logRetrievalRequests, anchor),
78
+ this.#fetchPrivateLogs(logRetrievalRequests, anchor),
77
79
  ]);
78
80
 
79
81
  return logRetrievalRequests.map((_request, i) => [
80
- ...publicLogsPerRequest[i].map(LogService.#toLogRetrievalResponse),
81
- ...privateLogsPerRequest[i].map(LogService.#toLogRetrievalResponse),
82
+ ...publicLogsPerRequest[i].map(LogService.#toRetrievedTaggedLog),
83
+ ...privateLogsPerRequest[i].map(LogService.#toRetrievedTaggedLog),
82
84
  ]);
83
85
  }
84
86
 
85
87
  async #fetchPublicLogs(
86
88
  contractAddress: AztecAddress,
87
89
  requests: LogRetrievalRequest[],
88
- anchorBlockHash: BlockHash,
90
+ anchor: LogQueryAnchor,
89
91
  ): Promise<LogResult[][]> {
90
92
  const indices = requests.flatMap((r, i) => (r.source !== LogSource.PRIVATE ? [i] : []));
91
93
  if (indices.length === 0) {
@@ -98,13 +100,11 @@ export class LogService {
98
100
  await Promise.all(
99
101
  Array.from(groups.values()).map(async group => {
100
102
  const tags = group.entries.map(e => e.request.tag);
101
- const results = await getAllPublicLogsByTagsFromContract(
102
- this.aztecNode,
103
- contractAddress,
104
- tags,
105
- anchorBlockHash,
106
- { fromBlock: group.fromBlock, toBlock: group.toBlock, includeEffects: true },
107
- );
103
+ const results = await getAllPublicLogsByTagsFromContract(this.aztecNode, contractAddress, tags, anchor, {
104
+ fromBlock: group.fromBlock,
105
+ toBlock: group.toBlock,
106
+ includeEffects: true,
107
+ });
108
108
  group.entries.forEach((entry, i) => {
109
109
  resultsPerRequest[entry.index] = results[i];
110
110
  });
@@ -114,7 +114,7 @@ export class LogService {
114
114
  return resultsPerRequest;
115
115
  }
116
116
 
117
- async #fetchPrivateLogs(requests: LogRetrievalRequest[], anchorBlockHash: BlockHash): Promise<LogResult[][]> {
117
+ async #fetchPrivateLogs(requests: LogRetrievalRequest[], anchor: LogQueryAnchor): Promise<LogResult[][]> {
118
118
  const indices = requests.flatMap((r, i) => (r.source !== LogSource.PUBLIC ? [i] : []));
119
119
  if (indices.length === 0) {
120
120
  return requests.map(() => []);
@@ -128,7 +128,7 @@ export class LogService {
128
128
  const siloedTags = await Promise.all(
129
129
  group.entries.map(e => SiloedTag.computeFromTagAndApp(e.request.tag, e.request.contractAddress)),
130
130
  );
131
- const results = await getAllPrivateLogsByTags(this.aztecNode, siloedTags, anchorBlockHash, {
131
+ const results = await getAllPrivateLogsByTags(this.aztecNode, siloedTags, anchor, {
132
132
  fromBlock: group.fromBlock,
133
133
  toBlock: group.toBlock,
134
134
  includeEffects: true,
@@ -164,7 +164,7 @@ export class LogService {
164
164
  return groups;
165
165
  }
166
166
 
167
- static #toLogRetrievalResponse(log: LogResult): LogRetrievalResponse {
167
+ static #toRetrievedTaggedLog(log: LogResult): RetrievedTaggedLog {
168
168
  // includeEffects: true was used, so noteHashes and nullifiers are populated. Every tx has at least one nullifier
169
169
  // (the first nullifier derived from the tx hash); empty here would indicate a buggy node.
170
170
  const noteHashes = log.noteHashes!;
@@ -173,23 +173,25 @@ export class LogService {
173
173
  throw new Error(`Log for tx ${log.txHash} returned no nullifiers from the node`);
174
174
  }
175
175
  return {
176
- // Skip the tag, and clip to the wire cap: public logs can exceed PRIVATE_LOG_CIPHERTEXT_LEN, which is the fixed
177
- // size of the oracle's BoundedVec slot. A no-op for private logs, which are already within the cap.
178
- logPayload: log.logData.slice(1, 1 + PRIVATE_LOG_CIPHERTEXT_LEN),
176
+ logData: log.logData,
179
177
  txHash: log.txHash,
180
- uniqueNoteHashesInTx: noteHashes,
181
- firstNullifierInTx: nullifiers[0],
178
+ noteHashes,
179
+ nullifiers,
182
180
  blockNumber: log.blockNumber,
183
181
  blockTimestamp: log.blockTimestamp,
184
182
  blockHash: log.blockHash,
183
+ // The log index and the tx receipt both count the tx's position in `block.body.txEffects`, so this is the same
184
+ // index a receipt reports. Note ordering depends on the two staying in agreement.
185
+ txIndexInBlock: log.txIndexWithinBlock,
185
186
  };
186
187
  }
187
188
 
189
+ /** Fetches the pending tagged logs for a recipient across all its tagging secrets for the contract. */
188
190
  public async fetchTaggedLogs(
189
191
  contractAddress: AztecAddress,
190
192
  recipient: AztecAddress,
191
193
  providedSecrets: AppTaggingSecret[],
192
- ): Promise<PendingTaggedLog[]> {
194
+ ): Promise<RetrievedTaggedLog[]> {
193
195
  assertAllowedScope(recipient, this.scopes);
194
196
 
195
197
  this.log.verbose(
@@ -216,23 +218,7 @@ export class LogService {
216
218
  this.jobId,
217
219
  );
218
220
 
219
- return logs.map(log => {
220
- const noteHashes = log.noteHashes!;
221
- const nullifiers = log.nullifiers!;
222
- if (nullifiers.length === 0) {
223
- throw new Error(`Log for tx ${log.txHash} returned no nullifiers from the node`);
224
- }
225
- return {
226
- log: log.logData,
227
- context: {
228
- txHash: log.txHash,
229
- uniqueNoteHashesInTx: noteHashes,
230
- firstNullifierInTx: nullifiers[0],
231
- blockNumber: log.blockNumber,
232
- blockHash: log.blockHash.toFr(),
233
- },
234
- };
235
- });
221
+ return logs.map(log => LogService.#toRetrievedTaggedLog(log));
236
222
  }
237
223
 
238
224
  /**
@@ -298,3 +284,10 @@ export class LogService {
298
284
  );
299
285
  }
300
286
  }
287
+
288
+ /** A tagged log fetched from the node, together with the onchain context of the tx that emitted it. */
289
+ export type RetrievedTaggedLog = TxOnchainContext & {
290
+ /** The raw log payload, tag included. */
291
+ logData: Fr[];
292
+ blockTimestamp: UInt64;
293
+ };
@@ -1,22 +1,22 @@
1
+ import type { BlockNumber } from '@aztec/foundation/branded-types';
1
2
  import { uniqueBy } from '@aztec/foundation/collection';
2
3
  import { Fr } from '@aztec/foundation/curves/bn254';
4
+ import type { BlockHash } from '@aztec/stdlib/block';
3
5
  import type { AztecNode } from '@aztec/stdlib/interfaces/server';
4
6
  import { type IndexedTxEffect, TxHash } from '@aztec/stdlib/tx';
5
7
 
6
- import type { ResolvedTx } from '../contract_function_simulator/noir-structs/resolved_tx.js';
7
-
8
- /** Resolves transaction hashes into their on-chain context (note hashes, first nullifier, and mined block). */
8
+ /** Resolves transaction hashes into their on-chain context (note hashes, nullifiers, and mined position). */
9
9
  export class TxResolverService {
10
10
  constructor(private readonly aztecNode: AztecNode) {}
11
11
 
12
12
  /**
13
13
  * Resolves a list of tx hashes into their on-chain context.
14
14
  *
15
- * For each tx hash, looks up the corresponding tx effect and extracts the note hashes, first nullifier, and the
16
- * number and hash of the block it was mined in. Returns `null` for tx hashes that are zero, not yet available, or in
17
- * blocks beyond the anchor block.
15
+ * For each tx hash, looks up the corresponding tx effect and extracts its note hashes and nullifiers, and the
16
+ * position it was mined at. Returns `null` for tx hashes that are zero, not yet available, or in blocks beyond the
17
+ * anchor block.
18
18
  */
19
- async resolveTxs(txHashes: Fr[], anchorBlockNumber: number): Promise<(ResolvedTx | null)[]> {
19
+ async resolveTxs(txHashes: Fr[], anchorBlockNumber: number): Promise<(TxOnchainContext | null)[]> {
20
20
  const nonZeroTxHashes = txHashes.filter(h => !h.isZero()).map(h => TxHash.fromField(h));
21
21
  const uniqueTxHashes = uniqueBy(nonZeroTxHashes, h => h.toString());
22
22
  const fetched = await Promise.all(
@@ -51,7 +51,7 @@ export class TxResolverService {
51
51
  }
52
52
 
53
53
  // Every tx has at least one nullifier (the first nullifier derived from the tx hash). Hitting this condition
54
- // would mean a buggy node, but since we need to access data.nullifiers[0], the defensive check does no harm.
54
+ // would mean a buggy node, but since consumers rely on nullifiers[0], the defensive check does no harm.
55
55
  const data = txEffect.data;
56
56
  if (data.nullifiers.length === 0) {
57
57
  throw new Error(`Tx effect for ${txHash} has no nullifiers`);
@@ -59,11 +59,22 @@ export class TxResolverService {
59
59
 
60
60
  return {
61
61
  txHash: data.txHash,
62
- uniqueNoteHashesInTx: data.noteHashes,
63
- firstNullifierInTx: data.nullifiers[0],
62
+ noteHashes: data.noteHashes,
63
+ nullifiers: data.nullifiers,
64
64
  blockNumber: txEffect.l2BlockNumber,
65
- blockHash: txEffect.l2BlockHash.toFr(),
65
+ blockHash: txEffect.l2BlockHash,
66
+ txIndexInBlock: txEffect.txIndexInBlock,
66
67
  };
67
68
  });
68
69
  }
69
70
  }
71
+
72
+ /** The onchain context of a tx: the position it was mined at, and the effects it produced. */
73
+ export type TxOnchainContext = {
74
+ txHash: TxHash;
75
+ noteHashes: Fr[];
76
+ nullifiers: Fr[];
77
+ blockNumber: BlockNumber;
78
+ blockHash: BlockHash;
79
+ txIndexInBlock: number;
80
+ };
@@ -0,0 +1,140 @@
1
+ import { Timer } from '@aztec/foundation/timer';
2
+ import type { AztecNode } from '@aztec/stdlib/interfaces/client';
3
+ import type { NodeStats } from '@aztec/stdlib/tx';
4
+
5
+ /*
6
+ * Proxy generator for an AztecNode that tracks the time taken for each RPC call and the number of round trips (actual
7
+ * blocking waits for node responses).
8
+ *
9
+ * A round trip is counted when we transition from 0 to 1 in-flight calls, and ends when all concurrent calls complete.
10
+ * This means parallel calls in Promise.all count as a single round trip.
11
+ *
12
+ * Note that batching of RPC calls in `safe_json_rpc_client.ts` could affect the round trip counts but in places we
13
+ * currently use this information we do not even use HTTP as we have direct access to the Aztec Node instance in TS
14
+ * (i.e. not running against external node) so this is not a problem for now.
15
+ *
16
+ * If you want to use this against external node and the info gets skewed by batching you can set the `maxBatchSize`
17
+ * value in `safe_json_rpc_client.ts` to 1 (the main motivation for batching was to get around parallel http requests
18
+ * limits in web browsers which is not a problem when debugging in node.js).
19
+ */
20
+ export interface Recording {
21
+ /** Closes the recording and returns what it saw. Reads served after this are not recorded. */
22
+ stop(): NodeStats;
23
+ }
24
+
25
+ /** An {@link AztecNode} wrapper that can report the reads it serves. */
26
+ export interface BenchmarkedAztecNode extends AztecNode {
27
+ /**
28
+ * Opens a recording of the reads this wrapper serves, until {@link Recording.stop}. Recordings are independent, so
29
+ * several may run at once: one measuring a whole run sees the same reads as one measuring a single operation.
30
+ *
31
+ * Nothing is measured while none is open, which is what keeps a long-lived wrapper from accumulating a run's worth
32
+ * of timings nobody asked for.
33
+ */
34
+ startRecording(): Recording;
35
+ }
36
+
37
+ /** Wraps `node` so that the reads it answers can be recorded. */
38
+ export function withRecording(node: AztecNode): BenchmarkedAztecNode {
39
+ // The stats of every recording currently open
40
+ const open = new Set<NodeStats>();
41
+
42
+ // Round trip tracking
43
+ let inFlightCount = 0;
44
+ let currentRoundTripTimer: Timer | null = null;
45
+ let currentRoundTripMethods: string[] = [];
46
+
47
+ return new Proxy(node, {
48
+ get(target, prop) {
49
+ if (prop === 'startRecording') {
50
+ return (): Recording => {
51
+ const stats: NodeStats = {
52
+ perMethod: {},
53
+ roundTrips: { roundTrips: 0, totalBlockingTime: 0, roundTripDurations: [], roundTripMethods: [] },
54
+ };
55
+ open.add(stats);
56
+ return {
57
+ stop: () => {
58
+ open.delete(stats);
59
+ return stats;
60
+ },
61
+ };
62
+ };
63
+ }
64
+
65
+ const value = Reflect.get(target, prop);
66
+ if (typeof value !== 'function' || typeof prop !== 'string') {
67
+ return value;
68
+ }
69
+
70
+ return (...args: unknown[]) => {
71
+ // With no recording open there is nobody to report to, so the read is left untimed.
72
+ if (open.size === 0) {
73
+ return value.apply(target, args);
74
+ }
75
+
76
+ // Start of a new round trip batch?
77
+ if (inFlightCount === 0) {
78
+ currentRoundTripTimer = new Timer();
79
+ currentRoundTripMethods = [];
80
+ }
81
+ inFlightCount++;
82
+ currentRoundTripMethods.push(prop);
83
+
84
+ const callTimer = new Timer();
85
+ const result = value.apply(target, args);
86
+
87
+ // Handle completion - called when the call finishes (after Promise resolves)
88
+ const handleCompletion = () => {
89
+ const callTime = callTimer.ms();
90
+ for (const stats of open) {
91
+ timesFor(stats, prop).push(callTime);
92
+ }
93
+
94
+ inFlightCount--;
95
+
96
+ // End of round trip batch - all concurrent calls completed
97
+ if (inFlightCount === 0 && currentRoundTripTimer) {
98
+ const roundTripTime = currentRoundTripTimer.ms();
99
+ for (const { roundTrips } of open) {
100
+ roundTrips.roundTrips++;
101
+ roundTrips.totalBlockingTime += roundTripTime;
102
+ roundTrips.roundTripDurations.push(roundTripTime);
103
+ roundTrips.roundTripMethods.push(currentRoundTripMethods);
104
+ }
105
+ currentRoundTripTimer = null;
106
+ currentRoundTripMethods = [];
107
+ }
108
+ };
109
+
110
+ // If the result is a Promise, chain the completion handler
111
+ if (isThenable(result)) {
112
+ return result.then(
113
+ resolved => {
114
+ handleCompletion();
115
+ return resolved;
116
+ },
117
+ error => {
118
+ handleCompletion();
119
+ throw error;
120
+ },
121
+ );
122
+ } else {
123
+ // Synchronous method - handle completion immediately
124
+ handleCompletion();
125
+ return result;
126
+ }
127
+ };
128
+ },
129
+ }) as BenchmarkedAztecNode;
130
+ }
131
+
132
+ /** The times `stats` holds for `method`, added on first use. */
133
+ function timesFor(stats: NodeStats, method: string) {
134
+ return (stats.perMethod[method as keyof AztecNode] ??= { times: [] }).times;
135
+ }
136
+
137
+ /** Whether completion can be chained onto `value` with `.then`, which a promise from any implementation allows. */
138
+ function isThenable(value: unknown): value is PromiseLike<unknown> {
139
+ return typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function';
140
+ }