@aztec/pxe 0.0.1-commit.9372f48 → 0.0.1-commit.949a33fd8

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 (248) hide show
  1. package/dest/bin/check_oracle_version.js +4 -4
  2. package/dest/block_synchronizer/block_stream_source.d.ts +10 -0
  3. package/dest/block_synchronizer/block_stream_source.d.ts.map +1 -0
  4. package/dest/block_synchronizer/block_stream_source.js +37 -0
  5. package/dest/block_synchronizer/block_synchronizer.d.ts +9 -3
  6. package/dest/block_synchronizer/block_synchronizer.d.ts.map +1 -1
  7. package/dest/block_synchronizer/block_synchronizer.js +37 -11
  8. package/dest/config/index.d.ts +2 -2
  9. package/dest/config/index.d.ts.map +1 -1
  10. package/dest/config/index.js +8 -15
  11. package/dest/config/package_info.js +1 -1
  12. package/dest/contract_function_simulator/contract_function_simulator.d.ts +63 -29
  13. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  14. package/dest/contract_function_simulator/contract_function_simulator.js +207 -75
  15. package/dest/contract_function_simulator/ephemeral_array_service.d.ts +28 -0
  16. package/dest/contract_function_simulator/ephemeral_array_service.d.ts.map +1 -0
  17. package/dest/contract_function_simulator/ephemeral_array_service.js +78 -0
  18. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts +7 -7
  19. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts.map +1 -1
  20. package/dest/contract_function_simulator/execution_tagging_index_cache.js +19 -11
  21. package/dest/contract_function_simulator/index.d.ts +2 -1
  22. package/dest/contract_function_simulator/index.d.ts.map +1 -1
  23. package/dest/contract_function_simulator/index.js +1 -0
  24. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts +4 -6
  25. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts.map +1 -1
  26. package/dest/contract_function_simulator/noir-structs/event_validation_request.js +8 -10
  27. package/dest/contract_function_simulator/noir-structs/log_retrieval_request.d.ts +1 -1
  28. package/dest/contract_function_simulator/noir-structs/log_retrieval_request.js +1 -1
  29. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts +2 -2
  30. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts.map +1 -1
  31. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.js +2 -4
  32. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts +4 -7
  33. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts.map +1 -1
  34. package/dest/contract_function_simulator/noir-structs/note_validation_request.js +6 -11
  35. package/dest/contract_function_simulator/oracle/interfaces.d.ts +63 -45
  36. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  37. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts +9 -0
  38. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts.map +1 -0
  39. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.js +47 -0
  40. package/dest/contract_function_simulator/oracle/oracle.d.ts +76 -44
  41. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  42. package/dest/contract_function_simulator/oracle/oracle.js +307 -103
  43. package/dest/contract_function_simulator/oracle/private_execution.js +5 -3
  44. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +58 -84
  45. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  46. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +122 -96
  47. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +126 -66
  48. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  49. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +366 -134
  50. package/dest/contract_function_simulator/pick_notes.d.ts +1 -1
  51. package/dest/contract_function_simulator/pick_notes.d.ts.map +1 -1
  52. package/dest/contract_function_simulator/pick_notes.js +20 -3
  53. package/dest/contract_function_simulator/proxied_contract_data_source.d.ts +1 -1
  54. package/dest/contract_function_simulator/proxied_contract_data_source.d.ts.map +1 -1
  55. package/dest/contract_function_simulator/proxied_contract_data_source.js +3 -0
  56. package/dest/contract_logging.d.ts +27 -0
  57. package/dest/contract_logging.d.ts.map +1 -0
  58. package/dest/contract_logging.js +38 -0
  59. package/dest/contract_sync/contract_sync_service.d.ts +44 -0
  60. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -0
  61. package/dest/contract_sync/contract_sync_service.js +116 -0
  62. package/dest/contract_sync/helpers.d.ts +28 -0
  63. package/dest/contract_sync/helpers.d.ts.map +1 -0
  64. package/dest/contract_sync/{index.js → helpers.js} +19 -13
  65. package/dest/debug/pxe_debug_utils.d.ts +14 -10
  66. package/dest/debug/pxe_debug_utils.d.ts.map +1 -1
  67. package/dest/debug/pxe_debug_utils.js +16 -15
  68. package/dest/entrypoints/client/bundle/index.d.ts +3 -1
  69. package/dest/entrypoints/client/bundle/index.d.ts.map +1 -1
  70. package/dest/entrypoints/client/bundle/index.js +2 -0
  71. package/dest/entrypoints/client/bundle/utils.d.ts +2 -2
  72. package/dest/entrypoints/client/bundle/utils.d.ts.map +1 -1
  73. package/dest/entrypoints/client/bundle/utils.js +11 -3
  74. package/dest/entrypoints/client/lazy/index.d.ts +3 -1
  75. package/dest/entrypoints/client/lazy/index.d.ts.map +1 -1
  76. package/dest/entrypoints/client/lazy/index.js +2 -0
  77. package/dest/entrypoints/client/lazy/utils.d.ts +2 -2
  78. package/dest/entrypoints/client/lazy/utils.d.ts.map +1 -1
  79. package/dest/entrypoints/client/lazy/utils.js +11 -3
  80. package/dest/entrypoints/pxe_creation_options.d.ts +3 -1
  81. package/dest/entrypoints/pxe_creation_options.d.ts.map +1 -1
  82. package/dest/entrypoints/pxe_creation_options.js +3 -1
  83. package/dest/entrypoints/server/index.d.ts +4 -3
  84. package/dest/entrypoints/server/index.d.ts.map +1 -1
  85. package/dest/entrypoints/server/index.js +3 -2
  86. package/dest/entrypoints/server/utils.d.ts +2 -2
  87. package/dest/entrypoints/server/utils.d.ts.map +1 -1
  88. package/dest/entrypoints/server/utils.js +11 -3
  89. package/dest/events/event_service.d.ts +3 -2
  90. package/dest/events/event_service.d.ts.map +1 -1
  91. package/dest/events/event_service.js +26 -5
  92. package/dest/events/private_event_filter_validator.d.ts +3 -2
  93. package/dest/events/private_event_filter_validator.d.ts.map +1 -1
  94. package/dest/events/private_event_filter_validator.js +15 -0
  95. package/dest/logs/log_service.d.ts +7 -7
  96. package/dest/logs/log_service.d.ts.map +1 -1
  97. package/dest/logs/log_service.js +34 -51
  98. package/dest/messages/message_context_service.d.ts +17 -0
  99. package/dest/messages/message_context_service.d.ts.map +1 -0
  100. package/dest/messages/message_context_service.js +36 -0
  101. package/dest/notes/note_service.d.ts +4 -4
  102. package/dest/notes/note_service.d.ts.map +1 -1
  103. package/dest/notes/note_service.js +17 -7
  104. package/dest/notes_filter.d.ts +24 -0
  105. package/dest/notes_filter.d.ts.map +1 -0
  106. package/dest/notes_filter.js +4 -0
  107. package/dest/oracle_version.d.ts +4 -3
  108. package/dest/oracle_version.d.ts.map +1 -1
  109. package/dest/oracle_version.js +20 -10
  110. package/dest/private_kernel/hints/compute_tx_expiration_timestamp.d.ts +4 -0
  111. package/dest/private_kernel/hints/compute_tx_expiration_timestamp.d.ts.map +1 -0
  112. package/dest/private_kernel/hints/{compute_tx_include_by_timestamp.js → compute_tx_expiration_timestamp.js} +12 -12
  113. package/dest/private_kernel/hints/index.d.ts +1 -1
  114. package/dest/private_kernel/hints/index.js +1 -1
  115. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.d.ts +4 -3
  116. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.d.ts.map +1 -1
  117. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.js +129 -68
  118. package/dest/private_kernel/hints/test_utils.d.ts +122 -0
  119. package/dest/private_kernel/hints/test_utils.d.ts.map +1 -0
  120. package/dest/private_kernel/hints/test_utils.js +203 -0
  121. package/dest/private_kernel/private_kernel_execution_prover.d.ts +1 -1
  122. package/dest/private_kernel/private_kernel_execution_prover.d.ts.map +1 -1
  123. package/dest/private_kernel/private_kernel_execution_prover.js +18 -13
  124. package/dest/private_kernel/private_kernel_oracle.d.ts +10 -6
  125. package/dest/private_kernel/private_kernel_oracle.d.ts.map +1 -1
  126. package/dest/private_kernel/private_kernel_oracle.js +19 -18
  127. package/dest/pxe.d.ts +85 -24
  128. package/dest/pxe.d.ts.map +1 -1
  129. package/dest/pxe.js +165 -84
  130. package/dest/storage/anchor_block_store/anchor_block_store.js +1 -1
  131. package/dest/storage/capsule_store/capsule_service.d.ts +21 -0
  132. package/dest/storage/capsule_store/capsule_service.d.ts.map +1 -0
  133. package/dest/storage/capsule_store/capsule_service.js +50 -0
  134. package/dest/storage/capsule_store/capsule_store.d.ts +9 -9
  135. package/dest/storage/capsule_store/capsule_store.d.ts.map +1 -1
  136. package/dest/storage/capsule_store/capsule_store.js +36 -28
  137. package/dest/storage/capsule_store/index.d.ts +2 -1
  138. package/dest/storage/capsule_store/index.d.ts.map +1 -1
  139. package/dest/storage/capsule_store/index.js +1 -0
  140. package/dest/storage/contract_store/contract_store.d.ts +42 -15
  141. package/dest/storage/contract_store/contract_store.d.ts.map +1 -1
  142. package/dest/storage/contract_store/contract_store.js +148 -70
  143. package/dest/storage/metadata.d.ts +1 -1
  144. package/dest/storage/metadata.js +1 -1
  145. package/dest/storage/note_store/note_store.d.ts +3 -3
  146. package/dest/storage/note_store/note_store.d.ts.map +1 -1
  147. package/dest/storage/note_store/note_store.js +6 -4
  148. package/dest/storage/private_event_store/private_event_store.d.ts +1 -1
  149. package/dest/storage/private_event_store/private_event_store.d.ts.map +1 -1
  150. package/dest/storage/private_event_store/private_event_store.js +3 -0
  151. package/dest/storage/private_event_store/stored_private_event.js +1 -1
  152. package/dest/storage/tagging_store/recipient_tagging_store.d.ts +6 -6
  153. package/dest/storage/tagging_store/recipient_tagging_store.d.ts.map +1 -1
  154. package/dest/storage/tagging_store/sender_tagging_store.d.ts +29 -28
  155. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  156. package/dest/storage/tagging_store/sender_tagging_store.js +141 -115
  157. package/dest/tagging/get_all_logs_by_tags.d.ts +1 -1
  158. package/dest/tagging/get_all_logs_by_tags.d.ts.map +1 -1
  159. package/dest/tagging/get_all_logs_by_tags.js +17 -3
  160. package/dest/tagging/index.d.ts +3 -3
  161. package/dest/tagging/index.d.ts.map +1 -1
  162. package/dest/tagging/index.js +1 -1
  163. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.d.ts +4 -5
  164. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.d.ts.map +1 -1
  165. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.js +8 -22
  166. package/dest/tagging/recipient_sync/utils/find_highest_indexes.js +2 -2
  167. package/dest/tagging/recipient_sync/utils/load_logs_for_range.d.ts +6 -7
  168. package/dest/tagging/recipient_sync/utils/load_logs_for_range.d.ts.map +1 -1
  169. package/dest/tagging/recipient_sync/utils/load_logs_for_range.js +12 -11
  170. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +4 -8
  171. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  172. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +13 -7
  173. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +4 -3
  174. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  175. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +20 -10
  176. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +5 -7
  177. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  178. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +36 -24
  179. package/package.json +25 -16
  180. package/src/bin/check_oracle_version.ts +4 -4
  181. package/src/block_synchronizer/block_stream_source.ts +52 -0
  182. package/src/block_synchronizer/block_synchronizer.ts +39 -11
  183. package/src/config/index.ts +3 -9
  184. package/src/config/package_info.ts +1 -1
  185. package/src/contract_function_simulator/contract_function_simulator.ts +367 -136
  186. package/src/contract_function_simulator/ephemeral_array_service.ts +110 -0
  187. package/src/contract_function_simulator/execution_tagging_index_cache.ts +19 -14
  188. package/src/contract_function_simulator/index.ts +1 -0
  189. package/src/contract_function_simulator/noir-structs/event_validation_request.ts +9 -9
  190. package/src/contract_function_simulator/noir-structs/log_retrieval_request.ts +1 -1
  191. package/src/contract_function_simulator/noir-structs/log_retrieval_response.ts +2 -5
  192. package/src/contract_function_simulator/noir-structs/note_validation_request.ts +4 -10
  193. package/src/contract_function_simulator/oracle/interfaces.ts +91 -53
  194. package/src/contract_function_simulator/oracle/legacy_oracle_mappings.ts +104 -0
  195. package/src/contract_function_simulator/oracle/oracle.ts +387 -142
  196. package/src/contract_function_simulator/oracle/private_execution.ts +4 -4
  197. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +154 -185
  198. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +610 -165
  199. package/src/contract_function_simulator/pick_notes.ts +22 -3
  200. package/src/contract_function_simulator/proxied_contract_data_source.ts +8 -1
  201. package/src/contract_logging.ts +52 -0
  202. package/src/contract_sync/contract_sync_service.ts +176 -0
  203. package/src/contract_sync/{index.ts → helpers.ts} +22 -22
  204. package/src/debug/pxe_debug_utils.ts +48 -18
  205. package/src/entrypoints/client/bundle/index.ts +2 -0
  206. package/src/entrypoints/client/bundle/utils.ts +11 -4
  207. package/src/entrypoints/client/lazy/index.ts +2 -0
  208. package/src/entrypoints/client/lazy/utils.ts +11 -4
  209. package/src/entrypoints/pxe_creation_options.ts +7 -0
  210. package/src/entrypoints/server/index.ts +3 -2
  211. package/src/entrypoints/server/utils.ts +9 -10
  212. package/src/events/event_service.ts +30 -5
  213. package/src/events/private_event_filter_validator.ts +21 -1
  214. package/src/logs/log_service.ts +64 -92
  215. package/src/messages/message_context_service.ts +44 -0
  216. package/src/notes/note_service.ts +19 -8
  217. package/src/notes_filter.ts +24 -0
  218. package/src/oracle_version.ts +20 -10
  219. package/src/private_kernel/hints/{compute_tx_include_by_timestamp.ts → compute_tx_expiration_timestamp.ts} +13 -13
  220. package/src/private_kernel/hints/index.ts +1 -1
  221. package/src/private_kernel/hints/private_kernel_reset_private_inputs_builder.ts +164 -117
  222. package/src/private_kernel/hints/test_utils.ts +325 -0
  223. package/src/private_kernel/private_kernel_execution_prover.ts +18 -16
  224. package/src/private_kernel/private_kernel_oracle.ts +21 -21
  225. package/src/pxe.ts +305 -138
  226. package/src/storage/anchor_block_store/anchor_block_store.ts +1 -1
  227. package/src/storage/capsule_store/capsule_service.ts +90 -0
  228. package/src/storage/capsule_store/capsule_store.ts +44 -26
  229. package/src/storage/capsule_store/index.ts +1 -0
  230. package/src/storage/contract_store/contract_store.ts +181 -80
  231. package/src/storage/metadata.ts +1 -1
  232. package/src/storage/note_store/note_store.ts +9 -5
  233. package/src/storage/private_event_store/private_event_store.ts +4 -0
  234. package/src/storage/private_event_store/stored_private_event.ts +1 -1
  235. package/src/storage/tagging_store/recipient_tagging_store.ts +9 -5
  236. package/src/storage/tagging_store/sender_tagging_store.ts +185 -138
  237. package/src/tagging/get_all_logs_by_tags.ts +28 -4
  238. package/src/tagging/index.ts +2 -2
  239. package/src/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.ts +12 -25
  240. package/src/tagging/recipient_sync/utils/find_highest_indexes.ts +2 -2
  241. package/src/tagging/recipient_sync/utils/load_logs_for_range.ts +10 -15
  242. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +23 -10
  243. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +26 -11
  244. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +27 -26
  245. package/dest/contract_sync/index.d.ts +0 -23
  246. package/dest/contract_sync/index.d.ts.map +0 -1
  247. package/dest/private_kernel/hints/compute_tx_include_by_timestamp.d.ts +0 -4
  248. package/dest/private_kernel/hints/compute_tx_include_by_timestamp.d.ts.map +0 -1
package/src/pxe.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  } from '@aztec/stdlib/abi';
19
19
  import type { AuthWitness } from '@aztec/stdlib/auth-witness';
20
20
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
21
+ import type { L2TipsProvider } from '@aztec/stdlib/block';
21
22
  import {
22
23
  CompleteAddress,
23
24
  type ContractInstanceWithAddress,
@@ -33,6 +34,7 @@ import type {
33
34
  PrivateKernelTailCircuitPublicInputs,
34
35
  } from '@aztec/stdlib/kernel';
35
36
  import {
37
+ BlockHeader,
36
38
  type ContractOverrides,
37
39
  type InTx,
38
40
  PrivateExecutionResult,
@@ -46,7 +48,7 @@ import {
46
48
  TxProfileResult,
47
49
  TxProvingResult,
48
50
  TxSimulationResult,
49
- UtilitySimulationResult,
51
+ UtilityExecutionResult,
50
52
  } from '@aztec/stdlib/tx';
51
53
 
52
54
  import { inspect } from 'util';
@@ -59,11 +61,14 @@ import {
59
61
  generateSimulatedProvingResult,
60
62
  } from './contract_function_simulator/contract_function_simulator.js';
61
63
  import { ProxiedContractStoreFactory } from './contract_function_simulator/proxied_contract_data_source.js';
62
- import { ensureContractSynced, readCurrentClassId } from './contract_sync/index.js';
64
+ import { displayDebugLogs } from './contract_logging.js';
65
+ import { ContractSyncService } from './contract_sync/contract_sync_service.js';
66
+ import { readCurrentClassId } from './contract_sync/helpers.js';
63
67
  import { PXEDebugUtils } from './debug/pxe_debug_utils.js';
64
68
  import { enrichPublicSimulationError, enrichSimulationError } from './error_enriching.js';
65
69
  import { PrivateEventFilterValidator } from './events/private_event_filter_validator.js';
66
70
  import { JobCoordinator } from './job_coordinator/job_coordinator.js';
71
+ import { MessageContextService } from './messages/message_context_service.js';
67
72
  import {
68
73
  PrivateKernelExecutionProver,
69
74
  type PrivateKernelExecutionProverConfig,
@@ -84,6 +89,70 @@ export type PackedPrivateEvent = InTx & {
84
89
  eventSelector: EventSelector;
85
90
  };
86
91
 
92
+ /** Options for PXE.proveTx. */
93
+ export type ProveTxOpts = {
94
+ /** Addresses whose private state and keys are accessible during private execution. */
95
+ scopes: AztecAddress[];
96
+ /** Sender address used to derive discovery tags for private messages (notes, events, logs) this tx emits. */
97
+ senderForTags?: AztecAddress;
98
+ };
99
+
100
+ /** Options for PXE.profileTx. */
101
+ export type ProfileTxOpts = {
102
+ /** The profiling mode to use. */
103
+ profileMode: 'full' | 'execution-steps' | 'gates';
104
+ /** If true, proof generation is skipped during profiling. Defaults to true. */
105
+ skipProofGeneration?: boolean;
106
+ /** Addresses whose private state and keys are accessible during private execution. */
107
+ scopes: AztecAddress[];
108
+ /** Sender address used to derive discovery tags for private messages (notes, events, logs) this tx emits. */
109
+ senderForTags?: AztecAddress;
110
+ };
111
+
112
+ /** Options for PXE.simulateTx. */
113
+ export type SimulateTxOpts = {
114
+ /** Whether to simulate the public part of the transaction. */
115
+ simulatePublic: boolean;
116
+ /** If false, this function throws if the transaction is unable to be included in a block at the current state. */
117
+ skipTxValidation?: boolean;
118
+ /** If false, fees are enforced. */
119
+ skipFeeEnforcement?: boolean;
120
+ /** If true, kernel logic is emulated in TS for simulation */
121
+ skipKernels?: boolean;
122
+ /** State overrides for the simulation, such as contract instances and artifacts. Requires skipKernels: true */
123
+ overrides?: SimulationOverrides;
124
+ /** Addresses whose private state and keys are accessible during private execution */
125
+ scopes: AztecAddress[];
126
+ /** Sender address used to derive discovery tags for private messages (notes, events, logs) this tx emits. */
127
+ senderForTags?: AztecAddress;
128
+ };
129
+
130
+ /** Options for PXE.executeUtility. */
131
+ export type ExecuteUtilityOpts = {
132
+ /** The authentication witnesses required for the function call. */
133
+ authwits?: AuthWitness[];
134
+ /** The accounts whose notes we can access in this call */
135
+ scopes: AztecAddress[];
136
+ };
137
+
138
+ /** Args for PXE.create. */
139
+ export type PXECreateArgs = {
140
+ /** The Aztec node to connect to. */
141
+ node: AztecNode;
142
+ /** The key-value store for persisting PXE state. */
143
+ store: AztecAsyncKVStore;
144
+ /** The prover for generating private kernel proofs. */
145
+ proofCreator: PrivateKernelProver;
146
+ /** The circuit simulator for executing ACIR circuits. */
147
+ simulator: CircuitSimulator;
148
+ /** Provider for protocol contract artifacts and instances. */
149
+ protocolContractsProvider: ProtocolContractsProvider;
150
+ /** PXE configuration options. */
151
+ config: PXEConfig;
152
+ /** Optional logger instance or string suffix for the logger name. */
153
+ loggerOrSuffix?: string | Logger;
154
+ };
155
+
87
156
  /**
88
157
  * Private eXecution Environment (PXE) is a library used by wallets to simulate private phase of transactions and to
89
158
  * manage private state of users.
@@ -91,6 +160,7 @@ export type PackedPrivateEvent = InTx & {
91
160
  export class PXE {
92
161
  private constructor(
93
162
  private node: AztecNode,
163
+ private db: AztecAsyncKVStore,
94
164
  private blockStateSynchronizer: BlockSynchronizer,
95
165
  private keyStore: KeyStore,
96
166
  private contractStore: ContractStore,
@@ -102,6 +172,9 @@ export class PXE {
102
172
  private recipientTaggingStore: RecipientTaggingStore,
103
173
  private addressStore: AddressStore,
104
174
  private privateEventStore: PrivateEventStore,
175
+ private contractSyncService: ContractSyncService,
176
+ private messageContextService: MessageContextService,
177
+ private l2TipsStore: L2TipsProvider,
105
178
  private simulator: CircuitSimulator,
106
179
  private proverEnabled: boolean,
107
180
  private proofCreator: PrivateKernelProver,
@@ -119,15 +192,15 @@ export class PXE {
119
192
  *
120
193
  * @returns A promise that resolves PXE is ready to be used.
121
194
  */
122
- public static async create(
123
- node: AztecNode,
124
- store: AztecAsyncKVStore,
125
- proofCreator: PrivateKernelProver,
126
- simulator: CircuitSimulator,
127
- protocolContractsProvider: ProtocolContractsProvider,
128
- config: PXEConfig,
129
- loggerOrSuffix?: string | Logger,
130
- ) {
195
+ public static async create({
196
+ node,
197
+ store,
198
+ proofCreator,
199
+ simulator,
200
+ protocolContractsProvider,
201
+ config,
202
+ loggerOrSuffix,
203
+ }: PXECreateArgs) {
131
204
  // Extract bindings from the logger, or use empty bindings if a string suffix is provided.
132
205
  const bindings: LoggerBindings | undefined =
133
206
  loggerOrSuffix && typeof loggerOrSuffix !== 'string' ? loggerOrSuffix.getBindings() : undefined;
@@ -137,7 +210,9 @@ export class PXE {
137
210
  ? createLogger(loggerOrSuffix ? `pxe:service:${loggerOrSuffix}` : `pxe:service`)
138
211
  : loggerOrSuffix;
139
212
 
140
- const proverEnabled = !!config.proverEnabled;
213
+ const info = await node.getNodeInfo();
214
+
215
+ const proverEnabled = config.proverEnabled !== undefined ? config.proverEnabled : info.realProofs;
141
216
  const addressStore = new AddressStore(store);
142
217
  const privateEventStore = new PrivateEventStore(store);
143
218
  const contractStore = new ContractStore(store);
@@ -149,6 +224,14 @@ export class PXE {
149
224
  const capsuleStore = new CapsuleStore(store);
150
225
  const keyStore = new KeyStore(store);
151
226
  const tipsStore = new L2TipsKVStore(store, 'pxe');
227
+ const contractSyncService = new ContractSyncService(
228
+ node,
229
+ contractStore,
230
+ noteStore,
231
+ createLogger('pxe:contract_sync', bindings),
232
+ );
233
+ const messageContextService = new MessageContextService(node);
234
+
152
235
  const synchronizer = new BlockSynchronizer(
153
236
  node,
154
237
  store,
@@ -156,6 +239,7 @@ export class PXE {
156
239
  noteStore,
157
240
  privateEventStore,
158
241
  tipsStore,
242
+ contractSyncService,
159
243
  config,
160
244
  bindings,
161
245
  );
@@ -167,14 +251,16 @@ export class PXE {
167
251
  recipientTaggingStore,
168
252
  privateEventStore,
169
253
  noteStore,
254
+ contractSyncService,
170
255
  ]);
171
256
 
172
- const debugUtils = new PXEDebugUtils(contractStore, noteStore, synchronizer, anchorBlockStore);
257
+ const debugUtils = new PXEDebugUtils(contractSyncService, noteStore, synchronizer, anchorBlockStore);
173
258
 
174
259
  const jobQueue = new SerialQueue();
175
260
 
176
261
  const pxe = new PXE(
177
262
  node,
263
+ store,
178
264
  synchronizer,
179
265
  keyStore,
180
266
  contractStore,
@@ -186,6 +272,9 @@ export class PXE {
186
272
  recipientTaggingStore,
187
273
  addressStore,
188
274
  privateEventStore,
275
+ contractSyncService,
276
+ messageContextService,
277
+ tipsStore,
189
278
  simulator,
190
279
  proverEnabled,
191
280
  proofCreator,
@@ -196,12 +285,15 @@ export class PXE {
196
285
  debugUtils,
197
286
  );
198
287
 
199
- debugUtils.setPXE(pxe, pxe.#putInJobQueue.bind(pxe));
288
+ debugUtils.setPXEHelpers(
289
+ pxe.#putInJobQueue.bind(pxe),
290
+ pxe.#getSimulatorForTx.bind(pxe),
291
+ pxe.#executeUtility.bind(pxe),
292
+ );
200
293
 
201
294
  pxe.jobQueue.start();
202
295
 
203
296
  await pxe.#registerProtocolContracts();
204
- const info = await node.getNodeInfo();
205
297
  log.info(`Started PXE connected to chain ${info.l1ChainId} version ${info.rollupVersion}`);
206
298
  return pxe;
207
299
  }
@@ -211,19 +303,22 @@ export class PXE {
211
303
  #getSimulatorForTx(overrides?: { contracts?: ContractOverrides }) {
212
304
  const proxyContractStore = ProxiedContractStoreFactory.create(this.contractStore, overrides?.contracts);
213
305
 
214
- return new ContractFunctionSimulator(
215
- proxyContractStore,
216
- this.noteStore,
217
- this.keyStore,
218
- this.addressStore,
219
- BenchmarkedNodeFactory.create(this.node),
220
- this.senderTaggingStore,
221
- this.recipientTaggingStore,
222
- this.senderAddressBookStore,
223
- this.capsuleStore,
224
- this.privateEventStore,
225
- this.simulator,
226
- );
306
+ return new ContractFunctionSimulator({
307
+ contractStore: proxyContractStore,
308
+ noteStore: this.noteStore,
309
+ keyStore: this.keyStore,
310
+ addressStore: this.addressStore,
311
+ aztecNode: BenchmarkedNodeFactory.create(this.node),
312
+ l2TipsStore: this.l2TipsStore,
313
+ senderTaggingStore: this.senderTaggingStore,
314
+ recipientTaggingStore: this.recipientTaggingStore,
315
+ senderAddressBookStore: this.senderAddressBookStore,
316
+ capsuleStore: this.capsuleStore,
317
+ privateEventStore: this.privateEventStore,
318
+ simulator: this.simulator,
319
+ contractSyncService: this.contractSyncService,
320
+ messageContextService: this.messageContextService,
321
+ });
227
322
  }
228
323
 
229
324
  #contextualizeError(err: Error, ...context: string[]): Error {
@@ -275,9 +370,8 @@ export class PXE {
275
370
  async #registerProtocolContracts() {
276
371
  const registered: Record<string, string> = {};
277
372
  for (const name of protocolContractNames) {
278
- const { address, contractClass, instance, artifact } =
279
- await this.protocolContractsProvider.getProtocolContractArtifact(name);
280
- await this.contractStore.addContractArtifact(contractClass.id, artifact);
373
+ const { address, instance, artifact } = await this.protocolContractsProvider.getProtocolContractArtifact(name);
374
+ await this.contractStore.addContractArtifact(artifact);
281
375
  await this.contractStore.addContractInstance(instance);
282
376
  registered[name] = address.toString();
283
377
  }
@@ -286,38 +380,42 @@ export class PXE {
286
380
 
287
381
  // Executes the entrypoint private function, as well as all nested private
288
382
  // functions that might arise.
289
- async #executePrivate(
290
- contractFunctionSimulator: ContractFunctionSimulator,
291
- txRequest: TxExecutionRequest,
292
- scopes: AztecAddress[] | undefined,
293
- jobId: string,
294
- ): Promise<PrivateExecutionResult> {
383
+ async #executePrivate({
384
+ contractFunctionSimulator,
385
+ txRequest,
386
+ anchorBlockHeader,
387
+ scopes,
388
+ jobId,
389
+ senderForTags,
390
+ }: {
391
+ contractFunctionSimulator: ContractFunctionSimulator;
392
+ txRequest: TxExecutionRequest;
393
+ anchorBlockHeader: BlockHeader;
394
+ scopes: AztecAddress[];
395
+ jobId: string;
396
+ senderForTags?: AztecAddress;
397
+ }): Promise<PrivateExecutionResult> {
295
398
  const { origin: contractAddress, functionSelector } = txRequest;
296
399
 
297
400
  try {
298
- const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
299
-
300
- await ensureContractSynced(
401
+ await this.contractSyncService.ensureContractSynced(
301
402
  contractAddress,
302
403
  functionSelector,
303
- privateSyncCall => this.#simulateUtility(contractFunctionSimulator, privateSyncCall, [], undefined, jobId),
304
- this.node,
305
- this.contractStore,
404
+ (privateSyncCall, execScopes) =>
405
+ this.#executeUtility(contractFunctionSimulator, privateSyncCall, [], execScopes, jobId),
306
406
  anchorBlockHeader,
407
+ jobId,
408
+ scopes,
307
409
  );
308
410
 
309
- const result = await contractFunctionSimulator.run(
310
- txRequest,
411
+ const result = await contractFunctionSimulator.run(txRequest, {
311
412
  contractAddress,
312
- functionSelector,
313
- undefined,
413
+ selector: functionSelector,
314
414
  anchorBlockHeader,
315
- // The sender for tags is set by contracts, typically by an account
316
- // contract entrypoint
317
- undefined, // senderForTags
318
415
  scopes,
319
416
  jobId,
320
- );
417
+ senderForTags,
418
+ });
321
419
  this.log.debug(`Private simulation completed for ${contractAddress.toString()}:${functionSelector}`);
322
420
  return result;
323
421
  } catch (err) {
@@ -329,25 +427,32 @@ export class PXE {
329
427
  }
330
428
 
331
429
  /**
332
- * Simulate a utility function call on the given contract.
430
+ * Execute a utility function call on the given contract.
333
431
  * @param contractFunctionSimulator - The simulator to use for the function call.
334
432
  * @param call - The function call to execute.
335
433
  * @param authWitnesses - Authentication witnesses required for the function call.
336
434
  * @param scopes - Optional array of account addresses whose notes can be accessed in this call. Defaults to all
337
435
  * accounts if not specified.
338
436
  * @param jobId - The job ID for staged writes.
339
- * @returns The simulation result containing the outputs of the utility function.
437
+ * @returns The execution result containing the outputs of the utility function.
340
438
  */
341
- async #simulateUtility(
439
+ async #executeUtility(
342
440
  contractFunctionSimulator: ContractFunctionSimulator,
343
441
  call: FunctionCall,
344
442
  authWitnesses: AuthWitness[] | undefined,
345
- scopes: AztecAddress[] | undefined,
443
+ scopes: AztecAddress[],
346
444
  jobId: string,
347
445
  ) {
348
446
  try {
349
447
  const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
350
- return contractFunctionSimulator.runUtility(call, authWitnesses ?? [], anchorBlockHeader, scopes, jobId);
448
+ const { result, offchainEffects } = await contractFunctionSimulator.runUtility(
449
+ call,
450
+ authWitnesses ?? [],
451
+ anchorBlockHeader,
452
+ scopes,
453
+ jobId,
454
+ );
455
+ return { result, offchainEffects };
351
456
  } catch (err) {
352
457
  if (err instanceof SimulationError) {
353
458
  await enrichSimulationError(err, this.contractStore, this.log);
@@ -398,11 +503,10 @@ export class PXE {
398
503
  txExecutionRequest: TxExecutionRequest,
399
504
  proofCreator: PrivateKernelProver,
400
505
  privateExecutionResult: PrivateExecutionResult,
506
+ anchorBlockHeader: BlockHeader,
401
507
  config: PrivateKernelExecutionProverConfig,
402
508
  ): Promise<PrivateKernelExecutionProofOutput<PrivateKernelTailCircuitPublicInputs>> {
403
- const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
404
- const anchorBlockHash = await anchorBlockHeader.hash();
405
- const kernelOracle = new PrivateKernelOracle(this.contractStore, this.keyStore, this.node, anchorBlockHash);
509
+ const kernelOracle = new PrivateKernelOracle(this.contractStore, this.keyStore, this.node, anchorBlockHeader);
406
510
  const kernelTraceProver = new PrivateKernelExecutionProver(
407
511
  kernelOracle,
408
512
  proofCreator,
@@ -415,6 +519,21 @@ export class PXE {
415
519
 
416
520
  // Public API
417
521
 
522
+ /**
523
+ * Returns the block header up to which the PXE has synced.
524
+ * @returns The synced block header
525
+ */
526
+ public getSyncedBlockHeader(): Promise<BlockHeader> {
527
+ return this.#putInJobQueue(() => {
528
+ return this.anchorBlockStore.getBlockHeader();
529
+ });
530
+ }
531
+
532
+ /**
533
+ * Returns the contract instance for a given address, if it's registered in the PXE.
534
+ * @param address - The contract address.
535
+ * @returns The contract instance if found, undefined otherwise.
536
+ */
418
537
  public getContractInstance(address: AztecAddress): Promise<ContractInstanceWithAddress | undefined> {
419
538
  return this.contractStore.getContractInstance(address);
420
539
  }
@@ -464,6 +583,12 @@ export class PXE {
464
583
  * TODO: It's strange that we return the address here and I (benesjan) think we should drop the return value.
465
584
  */
466
585
  public async registerSender(sender: AztecAddress): Promise<AztecAddress> {
586
+ if (!(await sender.isValid())) {
587
+ throw new Error(
588
+ `Address ${sender} is not valid: it does not correspond to a point on the Grumpkin curve. Cannot register it as a sender.`,
589
+ );
590
+ }
591
+
467
592
  const accounts = await this.keyStore.getAccounts();
468
593
  if (accounts.includes(sender)) {
469
594
  this.log.info(`Sender:\n "${sender.toString()}"\n already registered.`);
@@ -474,6 +599,9 @@ export class PXE {
474
599
 
475
600
  if (wasAdded) {
476
601
  this.log.info(`Added sender:\n ${sender.toString()}`);
602
+ // Wipe the entire sync cache: the new sender's tagged logs could contain notes/events for any contract, so
603
+ // all contracts must re-sync to discover them. Queued to avoid wiping while a job is in flight.
604
+ await this.#putInJobQueue(() => Promise.resolve(this.contractSyncService.wipe()));
477
605
  } else {
478
606
  this.log.info(`Sender:\n "${sender.toString()}"\n already registered.`);
479
607
  }
@@ -523,8 +651,7 @@ export class PXE {
523
651
  * @param artifact - The build artifact for the contract class.
524
652
  */
525
653
  public async registerContractClass(artifact: ContractArtifact): Promise<void> {
526
- const { id: contractClassId } = await getContractClassFromArtifact(artifact);
527
- await this.contractStore.addContractArtifact(contractClassId, artifact);
654
+ const contractClassId = await this.contractStore.addContractArtifact(artifact);
528
655
  this.log.info(`Added contract class ${artifact.name} with id ${contractClassId}`);
529
656
  }
530
657
 
@@ -543,17 +670,17 @@ export class PXE {
543
670
  if (artifact) {
544
671
  // If the user provides an artifact, validate it against the expected class id and register it
545
672
  const contractClass = await getContractClassFromArtifact(artifact);
546
- const contractClassId = contractClass.id;
547
- if (!contractClassId.equals(instance.currentContractClassId)) {
673
+ if (!contractClass.id.equals(instance.currentContractClassId)) {
548
674
  throw new Error(
549
- `Artifact does not match expected class id (computed ${contractClassId} but instance refers to ${instance.currentContractClassId})`,
675
+ `Artifact does not match expected class id (computed ${contractClass.id} but instance refers to ${instance.currentContractClassId})`,
550
676
  );
551
677
  }
552
678
  const computedAddress = await computeContractAddressFromInstance(instance);
553
679
  if (!computedAddress.equals(instance.address)) {
554
680
  throw new Error('Added a contract in which the address does not match the contract instance.');
555
681
  }
556
- await this.contractStore.addContractArtifact(contractClass.id, artifact);
682
+
683
+ await this.contractStore.addContractArtifact(artifact, contractClass);
557
684
 
558
685
  const publicFunctionSignatures = artifact.functions
559
686
  .filter(fn => fn.functionType === FunctionType.PUBLIC)
@@ -602,15 +729,16 @@ export class PXE {
602
729
  throw new Error('Could not update contract to a class different from the current one.');
603
730
  }
604
731
 
605
- await this.contractStore.addContractArtifact(contractClass.id, artifact);
606
-
607
732
  const publicFunctionSignatures = artifact.functions
608
733
  .filter(fn => fn.functionType === FunctionType.PUBLIC)
609
734
  .map(fn => decodeFunctionSignature(fn.name, fn.parameters));
610
735
  await this.node.registerContractFunctionSignatures(publicFunctionSignatures);
611
736
 
612
737
  currentInstance.currentContractClassId = contractClass.id;
613
- await this.contractStore.addContractInstance(currentInstance);
738
+ await Promise.all([
739
+ this.contractStore.addContractArtifact(artifact, contractClass),
740
+ this.contractStore.addContractInstance(currentInstance),
741
+ ]);
614
742
  this.log.info(`Updated contract ${artifact.name} at ${contractAddress.toString()} to class ${contractClass.id}`);
615
743
  });
616
744
  }
@@ -628,11 +756,12 @@ export class PXE {
628
756
  * (where validators prove the public portion).
629
757
  *
630
758
  * @param txRequest - An authenticated tx request ready for proving
759
+ * @param scopes - Addresses whose private state and keys are accessible during private execution.
631
760
  * @returns A result containing the proof and public inputs of the tail circuit.
632
761
  * @throws If contract code not found, or public simulation reverts.
633
762
  * Also throws if simulatePublic is true and public simulation reverts.
634
763
  */
635
- public proveTx(txRequest: TxExecutionRequest): Promise<TxProvingResult> {
764
+ public proveTx(txRequest: TxExecutionRequest, { scopes, senderForTags }: ProveTxOpts): Promise<TxProvingResult> {
636
765
  let privateExecutionResult: PrivateExecutionResult;
637
766
  // We disable proving concurrently mostly out of caution, since it accesses some of our stores. Proving is so
638
767
  // computationally demanding that it'd be rare for someone to try to do it concurrently regardless.
@@ -641,16 +770,24 @@ export class PXE {
641
770
  try {
642
771
  const syncTimer = new Timer();
643
772
  await this.blockStateSynchronizer.sync();
773
+ const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
644
774
  const syncTime = syncTimer.ms();
645
775
  const contractFunctionSimulator = this.#getSimulatorForTx();
646
- privateExecutionResult = await this.#executePrivate(contractFunctionSimulator, txRequest, undefined, jobId);
776
+ privateExecutionResult = await this.#executePrivate({
777
+ contractFunctionSimulator,
778
+ txRequest,
779
+ anchorBlockHeader,
780
+ scopes,
781
+ jobId,
782
+ senderForTags,
783
+ });
647
784
 
648
785
  const {
649
786
  publicInputs,
650
787
  chonkProof,
651
788
  executionSteps,
652
789
  timings: { proving } = {},
653
- } = await this.#prove(txRequest, this.proofCreator, privateExecutionResult, {
790
+ } = await this.#prove(txRequest, this.proofCreator, privateExecutionResult, anchorBlockHeader, {
654
791
  simulate: false,
655
792
  skipFeeEnforcement: false,
656
793
  profileMode: 'none',
@@ -685,17 +822,17 @@ export class PXE {
685
822
  // transaction before this one is included in a block from this PXE, and that transaction contains a log with
686
823
  // a tag derived from the same secret, we would reuse the tag and the transactions would be linked. Hence
687
824
  // storing the tags here prevents linkage of txs sent from the same PXE.
688
- const preTagsUsedInTheTx = privateExecutionResult.entrypoint.preTags;
689
- if (preTagsUsedInTheTx.length > 0) {
825
+ const taggingIndexRangesUsedInTheTx = privateExecutionResult.entrypoint.taggingIndexRanges;
826
+ if (taggingIndexRangesUsedInTheTx.length > 0) {
690
827
  // TODO(benesjan): The following is an expensive operation. Figure out a way to avoid it.
691
828
  const txHash = (await txProvingResult.toTx()).txHash;
692
829
 
693
- await this.senderTaggingStore.storePendingIndexes(preTagsUsedInTheTx, txHash, jobId);
694
- this.log.debug(`Stored used pre-tags as sender for the tx`, {
695
- preTagsUsedInTheTx,
830
+ await this.senderTaggingStore.storePendingIndexes(taggingIndexRangesUsedInTheTx, txHash, jobId);
831
+ this.log.debug(`Stored used tagging index ranges as sender for the tx`, {
832
+ taggingIndexRangesUsedInTheTx,
696
833
  });
697
834
  } else {
698
- this.log.debug(`No pre-tags used in the tx`);
835
+ this.log.debug(`No tagging index ranges used in the tx`);
699
836
  }
700
837
 
701
838
  return txProvingResult;
@@ -707,17 +844,13 @@ export class PXE {
707
844
 
708
845
  /**
709
846
  * Profiles a transaction, reporting gate counts (unless disabled) and returns an execution trace.
710
- *
711
- * @param txRequest - An authenticated tx request ready for simulation
712
- * @param msgSender - (Optional) The message sender to use for the simulation.
713
- * @param skipTxValidation - (Optional) If false, this function throws if the transaction is unable to be included in a block at the current state.
847
+ * @param txRequest - An authenticated tx request ready for simulation.
714
848
  * @returns A trace of the program execution with gate counts.
715
849
  * @throws If the code for the functions executed in this transaction have not been made available via `addContracts`.
716
850
  */
717
851
  public profileTx(
718
852
  txRequest: TxExecutionRequest,
719
- profileMode: 'full' | 'execution-steps' | 'gates',
720
- skipProofGeneration: boolean = true,
853
+ { profileMode, skipProofGeneration = true, scopes, senderForTags }: ProfileTxOpts,
721
854
  ): Promise<TxProfileResult> {
722
855
  // We disable concurrent profiles for consistency with simulateTx.
723
856
  return this.#putInJobQueue(async jobId => {
@@ -737,20 +870,24 @@ export class PXE {
737
870
  );
738
871
  const syncTimer = new Timer();
739
872
  await this.blockStateSynchronizer.sync();
873
+ const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
740
874
  const syncTime = syncTimer.ms();
741
875
 
742
876
  const contractFunctionSimulator = this.#getSimulatorForTx();
743
- const privateExecutionResult = await this.#executePrivate(
877
+ const privateExecutionResult = await this.#executePrivate({
744
878
  contractFunctionSimulator,
745
879
  txRequest,
746
- undefined,
880
+ anchorBlockHeader,
881
+ scopes,
747
882
  jobId,
748
- );
883
+ senderForTags,
884
+ });
749
885
 
750
886
  const { executionSteps, timings: { proving } = {} } = await this.#prove(
751
887
  txRequest,
752
888
  this.proofCreator,
753
889
  privateExecutionResult,
890
+ anchorBlockHeader,
754
891
  {
755
892
  simulate: skipProofGeneration,
756
893
  skipFeeEnforcement: false,
@@ -802,12 +939,7 @@ export class PXE {
802
939
  * In that case, the transaction returned is only potentially ready to be sent to the network for execution.
803
940
  *
804
941
  *
805
- * @param txRequest - An authenticated tx request ready for simulation
806
- * @param simulatePublic - Whether to simulate the public part of the transaction.
807
- * @param skipTxValidation - (Optional) If false, this function throws if the transaction is unable to be included in a block at the current state.
808
- * @param skipFeeEnforcement - (Optional) If false, fees are enforced.
809
- * @param overrides - (Optional) State overrides for the simulation, such as msgSender, contract instances and artifacts.
810
- * @param scopes - (Optional) The accounts whose notes we can access in this call. Currently optional and will default to all.
942
+ * @param txRequest - An authenticated tx request ready for simulation.
811
943
  * @returns A simulated transaction result object that includes public and private return values.
812
944
  * @throws If the code for the functions executed in this transaction have not been made available via `addContracts`.
813
945
  * Also throws if simulatePublic is true and public simulation reverts.
@@ -816,11 +948,15 @@ export class PXE {
816
948
  */
817
949
  public simulateTx(
818
950
  txRequest: TxExecutionRequest,
819
- simulatePublic: boolean,
820
- skipTxValidation: boolean = false,
821
- skipFeeEnforcement: boolean = false,
822
- overrides?: SimulationOverrides,
823
- scopes?: AztecAddress[],
951
+ {
952
+ simulatePublic,
953
+ skipTxValidation = false,
954
+ skipFeeEnforcement = false,
955
+ skipKernels = true,
956
+ overrides,
957
+ scopes,
958
+ senderForTags,
959
+ }: SimulateTxOpts,
824
960
  ): Promise<TxSimulationResult> {
825
961
  // We disable concurrent simulations since those might execute oracles which read and write to the PXE stores (e.g.
826
962
  // to the capsules), and we need to prevent concurrent runs from interfering with one another (e.g. attempting to
@@ -842,16 +978,34 @@ export class PXE {
842
978
  );
843
979
  const syncTimer = new Timer();
844
980
  await this.blockStateSynchronizer.sync();
981
+ const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
845
982
  const syncTime = syncTimer.ms();
846
983
 
984
+ const overriddenContracts = overrides?.contracts ? new Set(Object.keys(overrides.contracts)) : undefined;
985
+ const hasOverriddenContracts = overriddenContracts !== undefined && overriddenContracts.size > 0;
986
+
987
+ if (hasOverriddenContracts && !skipKernels) {
988
+ throw new Error(
989
+ 'Simulating with overridden contracts is not compatible with kernel execution. Please set skipKernels to true when simulating with overridden contracts.',
990
+ );
991
+ }
847
992
  const contractFunctionSimulator = this.#getSimulatorForTx(overrides);
848
- // Temporary: in case there are overrides, we have to skip the kernels or validations
849
- // will fail. Consider handing control to the user/wallet on whether they want to run them
850
- // or not.
851
- const skipKernels = overrides?.contracts !== undefined && Object.keys(overrides.contracts ?? {}).length > 0;
993
+
994
+ if (hasOverriddenContracts) {
995
+ // Overridden contracts don't have a sync function, so calling sync on them would fail.
996
+ // We exclude them so the sync service skips them entirely.
997
+ this.contractSyncService.setExcludedFromSync(jobId, overriddenContracts);
998
+ }
852
999
 
853
1000
  // Execution of private functions only; no proving, and no kernel logic.
854
- const privateExecutionResult = await this.#executePrivate(contractFunctionSimulator, txRequest, scopes, jobId);
1001
+ const privateExecutionResult = await this.#executePrivate({
1002
+ contractFunctionSimulator,
1003
+ txRequest,
1004
+ anchorBlockHeader,
1005
+ scopes,
1006
+ jobId,
1007
+ senderForTags,
1008
+ });
855
1009
 
856
1010
  let publicInputs: PrivateKernelTailCircuitPublicInputs | undefined;
857
1011
  let executionSteps: PrivateExecutionStep[] = [];
@@ -859,15 +1013,22 @@ export class PXE {
859
1013
  if (skipKernels) {
860
1014
  ({ publicInputs, executionSteps } = await generateSimulatedProvingResult(
861
1015
  privateExecutionResult,
862
- this.contractStore,
1016
+ (addr, sel) => this.contractStore.getDebugFunctionName(addr, sel),
1017
+ this.node,
863
1018
  ));
864
1019
  } else {
865
1020
  // Kernel logic, plus proving of all private functions and kernels.
866
- ({ publicInputs, executionSteps } = await this.#prove(txRequest, this.proofCreator, privateExecutionResult, {
867
- simulate: true,
868
- skipFeeEnforcement,
869
- profileMode: 'none',
870
- }));
1021
+ ({ publicInputs, executionSteps } = await this.#prove(
1022
+ txRequest,
1023
+ this.proofCreator,
1024
+ privateExecutionResult,
1025
+ anchorBlockHeader,
1026
+ {
1027
+ simulate: true,
1028
+ skipFeeEnforcement,
1029
+ profileMode: 'none',
1030
+ },
1031
+ ));
871
1032
  }
872
1033
 
873
1034
  const privateSimulationResult = new PrivateSimulationResult(privateExecutionResult, publicInputs);
@@ -878,6 +1039,9 @@ export class PXE {
878
1039
  const publicSimulationTimer = new Timer();
879
1040
  publicOutput = await this.#simulatePublicCalls(simulatedTx, skipFeeEnforcement);
880
1041
  publicSimulationTime = publicSimulationTimer.ms();
1042
+ if (publicOutput?.debugLogs?.length) {
1043
+ await displayDebugLogs(publicOutput.debugLogs, addr => this.contractStore.getDebugContractName(addr));
1044
+ }
881
1045
  }
882
1046
 
883
1047
  let validationTime: number | undefined;
@@ -886,7 +1050,8 @@ export class PXE {
886
1050
  const validationResult = await this.node.isValidTx(simulatedTx, { isSimulation: true, skipFeeEnforcement });
887
1051
  validationTime = validationTimer.ms();
888
1052
  if (validationResult.result === 'invalid') {
889
- throw new Error('The simulated transaction is unable to be added to state and is invalid.');
1053
+ const reason = validationResult.reason.length > 0 ? ` Reason: ${validationResult.reason.join(', ')}` : '';
1054
+ throw new Error(`The simulated transaction is unable to be added to state and is invalid.${reason}`);
890
1055
  }
891
1056
  }
892
1057
 
@@ -937,29 +1102,23 @@ export class PXE {
937
1102
  inspect(txRequest),
938
1103
  `simulatePublic=${simulatePublic}`,
939
1104
  `skipTxValidation=${skipTxValidation}`,
940
- `scopes=${scopes?.map(s => s.toString()).join(', ') ?? 'undefined'}`,
1105
+ `scopes=${scopes.map(s => s.toString()).join(', ')}`,
941
1106
  );
942
1107
  }
943
1108
  });
944
1109
  }
945
1110
 
946
1111
  /**
947
- * Simulate the execution of a contract utility function.
948
- *
1112
+ * Executes a contract utility function.
949
1113
  * @param call - The function call containing the function details, arguments, and target contract address.
950
- * @param authwits - (Optional) The authentication witnesses required for the function call.
951
- * @param scopes - (Optional) The accounts whose notes we can access in this call. Currently optional and will
952
- * default to all.
953
- * @returns The result of the utility function call, structured based on the function ABI.
954
1114
  */
955
- public simulateUtility(
1115
+ public executeUtility(
956
1116
  call: FunctionCall,
957
- authwits?: AuthWitness[],
958
- scopes?: AztecAddress[],
959
- ): Promise<UtilitySimulationResult> {
960
- // We disable concurrent simulations since those might execute oracles which read and write to the PXE stores (e.g.
1117
+ { authwits, scopes }: ExecuteUtilityOpts = { scopes: [] },
1118
+ ): Promise<UtilityExecutionResult> {
1119
+ // We disable concurrent executions since those might execute oracles which read and write to the PXE stores (e.g.
961
1120
  // to the capsules), and we need to prevent concurrent runs from interfering with one another (e.g. attempting to
962
- // delete the same read value, or reading values that another simulation is currently modifying).
1121
+ // delete the same read value, or reading values that another execution is currently modifying).
963
1122
  return this.#putInJobQueue(async jobId => {
964
1123
  try {
965
1124
  const totalTimer = new Timer();
@@ -970,16 +1129,17 @@ export class PXE {
970
1129
  const contractFunctionSimulator = this.#getSimulatorForTx();
971
1130
 
972
1131
  const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
973
- await ensureContractSynced(
1132
+ await this.contractSyncService.ensureContractSynced(
974
1133
  call.to,
975
1134
  call.selector,
976
- privateSyncCall => this.#simulateUtility(contractFunctionSimulator, privateSyncCall, [], undefined, jobId),
977
- this.node,
978
- this.contractStore,
1135
+ (privateSyncCall, execScopes) =>
1136
+ this.#executeUtility(contractFunctionSimulator, privateSyncCall, [], execScopes, jobId),
979
1137
  anchorBlockHeader,
1138
+ jobId,
1139
+ scopes,
980
1140
  );
981
1141
 
982
- const executionResult = await this.#simulateUtility(
1142
+ const { result: executionResult, offchainEffects } = await this.#executeUtility(
983
1143
  contractFunctionSimulator,
984
1144
  call,
985
1145
  authwits ?? [],
@@ -1000,14 +1160,19 @@ export class PXE {
1000
1160
  };
1001
1161
 
1002
1162
  const simulationStats = contractFunctionSimulator.getStats();
1003
- return { result: executionResult, stats: { timings, nodeRPCCalls: simulationStats.nodeRPCCalls } };
1163
+ return {
1164
+ result: executionResult,
1165
+ offchainEffects,
1166
+ anchorBlockTimestamp: anchorBlockHeader.globalVariables.timestamp,
1167
+ stats: { timings, nodeRPCCalls: simulationStats.nodeRPCCalls },
1168
+ };
1004
1169
  } catch (err: any) {
1005
1170
  const { to, name, args } = call;
1006
1171
  const stringifiedArgs = args.map(arg => arg.toString()).join(', ');
1007
1172
  throw this.#contextualizeError(
1008
1173
  err,
1009
- `simulateUtility ${to}:${name}(${stringifiedArgs})`,
1010
- `scopes=${scopes?.map(s => s.toString()).join(', ') ?? 'undefined'}`,
1174
+ `executeUtility ${to}:${name}(${stringifiedArgs})`,
1175
+ `scopes=${scopes.map(s => s.toString()).join(', ')}`,
1011
1176
  );
1012
1177
  }
1013
1178
  });
@@ -1040,14 +1205,14 @@ export class PXE {
1040
1205
 
1041
1206
  const contractFunctionSimulator = this.#getSimulatorForTx();
1042
1207
 
1043
- await ensureContractSynced(
1208
+ await this.contractSyncService.ensureContractSynced(
1044
1209
  filter.contractAddress,
1045
1210
  null,
1046
- async privateSyncCall =>
1047
- await this.#simulateUtility(contractFunctionSimulator, privateSyncCall, [], undefined, jobId),
1048
- this.node,
1049
- this.contractStore,
1211
+ async (privateSyncCall, execScopes) =>
1212
+ await this.#executeUtility(contractFunctionSimulator, privateSyncCall, [], execScopes, jobId),
1050
1213
  anchorBlockHeader,
1214
+ jobId,
1215
+ filter.scopes,
1051
1216
  );
1052
1217
  });
1053
1218
 
@@ -1062,9 +1227,11 @@ export class PXE {
1062
1227
  }
1063
1228
 
1064
1229
  /**
1065
- * Stops the PXE's job queue.
1230
+ * Stops the PXE's job queue and closes the backing store.
1066
1231
  */
1067
- public stop(): Promise<void> {
1068
- return this.jobQueue.end();
1232
+ public async stop(): Promise<void> {
1233
+ await this.jobQueue.end();
1234
+ await this.blockStateSynchronizer.stop();
1235
+ await this.db.close();
1069
1236
  }
1070
1237
  }