@aztec/pxe 0.0.1-commit.6d63667d → 0.0.1-commit.7035c9bd6

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 (194) hide show
  1. package/dest/access_scopes.d.ts +9 -0
  2. package/dest/access_scopes.d.ts.map +1 -0
  3. package/dest/access_scopes.js +6 -0
  4. package/dest/config/index.d.ts +2 -2
  5. package/dest/config/index.d.ts.map +1 -1
  6. package/dest/config/index.js +1 -1
  7. package/dest/config/package_info.js +1 -1
  8. package/dest/contract_function_simulator/contract_function_simulator.d.ts +60 -30
  9. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  10. package/dest/contract_function_simulator/contract_function_simulator.js +199 -73
  11. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts +7 -7
  12. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts.map +1 -1
  13. package/dest/contract_function_simulator/execution_tagging_index_cache.js +19 -11
  14. package/dest/contract_function_simulator/index.d.ts +2 -1
  15. package/dest/contract_function_simulator/index.d.ts.map +1 -1
  16. package/dest/contract_function_simulator/index.js +1 -0
  17. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts +2 -3
  18. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts.map +1 -1
  19. package/dest/contract_function_simulator/noir-structs/event_validation_request.js +5 -4
  20. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts +1 -1
  21. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts.map +1 -1
  22. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.js +1 -3
  23. package/dest/contract_function_simulator/noir-structs/message_tx_context.d.ts +16 -0
  24. package/dest/contract_function_simulator/noir-structs/message_tx_context.d.ts.map +1 -0
  25. package/dest/contract_function_simulator/noir-structs/message_tx_context.js +57 -0
  26. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts +2 -4
  27. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts.map +1 -1
  28. package/dest/contract_function_simulator/noir-structs/note_validation_request.js +3 -5
  29. package/dest/contract_function_simulator/oracle/interfaces.d.ts +50 -45
  30. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  31. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts +9 -0
  32. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts.map +1 -0
  33. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.js +42 -0
  34. package/dest/contract_function_simulator/oracle/oracle.d.ts +45 -44
  35. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  36. package/dest/contract_function_simulator/oracle/oracle.js +164 -95
  37. package/dest/contract_function_simulator/oracle/private_execution.js +5 -3
  38. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +54 -80
  39. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  40. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +98 -85
  41. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +81 -43
  42. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  43. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +153 -77
  44. package/dest/contract_logging.d.ts +22 -0
  45. package/dest/contract_logging.d.ts.map +1 -0
  46. package/dest/contract_logging.js +23 -0
  47. package/dest/contract_sync/contract_sync_service.d.ts +8 -4
  48. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -1
  49. package/dest/contract_sync/contract_sync_service.js +61 -29
  50. package/dest/contract_sync/helpers.d.ts +3 -2
  51. package/dest/contract_sync/helpers.d.ts.map +1 -1
  52. package/dest/contract_sync/helpers.js +3 -3
  53. package/dest/debug/pxe_debug_utils.d.ts +6 -7
  54. package/dest/debug/pxe_debug_utils.d.ts.map +1 -1
  55. package/dest/debug/pxe_debug_utils.js +4 -7
  56. package/dest/entrypoints/client/bundle/index.d.ts +4 -1
  57. package/dest/entrypoints/client/bundle/index.d.ts.map +1 -1
  58. package/dest/entrypoints/client/bundle/index.js +3 -0
  59. package/dest/entrypoints/client/bundle/utils.d.ts +1 -1
  60. package/dest/entrypoints/client/bundle/utils.d.ts.map +1 -1
  61. package/dest/entrypoints/client/bundle/utils.js +9 -1
  62. package/dest/entrypoints/client/lazy/index.d.ts +4 -1
  63. package/dest/entrypoints/client/lazy/index.d.ts.map +1 -1
  64. package/dest/entrypoints/client/lazy/index.js +3 -0
  65. package/dest/entrypoints/client/lazy/utils.d.ts +1 -1
  66. package/dest/entrypoints/client/lazy/utils.d.ts.map +1 -1
  67. package/dest/entrypoints/client/lazy/utils.js +9 -1
  68. package/dest/entrypoints/server/index.d.ts +3 -1
  69. package/dest/entrypoints/server/index.d.ts.map +1 -1
  70. package/dest/entrypoints/server/index.js +2 -0
  71. package/dest/entrypoints/server/utils.js +9 -1
  72. package/dest/logs/log_service.d.ts +3 -2
  73. package/dest/logs/log_service.d.ts.map +1 -1
  74. package/dest/logs/log_service.js +9 -14
  75. package/dest/messages/message_context_service.d.ts +17 -0
  76. package/dest/messages/message_context_service.d.ts.map +1 -0
  77. package/dest/messages/message_context_service.js +36 -0
  78. package/dest/notes/note_service.d.ts +4 -3
  79. package/dest/notes/note_service.d.ts.map +1 -1
  80. package/dest/notes/note_service.js +3 -2
  81. package/dest/notes_filter.d.ts +25 -0
  82. package/dest/notes_filter.d.ts.map +1 -0
  83. package/dest/notes_filter.js +4 -0
  84. package/dest/oracle_version.d.ts +2 -2
  85. package/dest/oracle_version.js +3 -3
  86. package/dest/private_kernel/hints/compute_tx_expiration_timestamp.d.ts +4 -0
  87. package/dest/private_kernel/hints/compute_tx_expiration_timestamp.d.ts.map +1 -0
  88. package/dest/private_kernel/hints/{compute_tx_include_by_timestamp.js → compute_tx_expiration_timestamp.js} +12 -12
  89. package/dest/private_kernel/hints/index.d.ts +1 -1
  90. package/dest/private_kernel/hints/index.js +1 -1
  91. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.d.ts +4 -3
  92. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.d.ts.map +1 -1
  93. package/dest/private_kernel/hints/private_kernel_reset_private_inputs_builder.js +129 -68
  94. package/dest/private_kernel/hints/test_utils.d.ts +122 -0
  95. package/dest/private_kernel/hints/test_utils.d.ts.map +1 -0
  96. package/dest/private_kernel/hints/test_utils.js +203 -0
  97. package/dest/private_kernel/private_kernel_execution_prover.d.ts +1 -1
  98. package/dest/private_kernel/private_kernel_execution_prover.d.ts.map +1 -1
  99. package/dest/private_kernel/private_kernel_execution_prover.js +19 -11
  100. package/dest/private_kernel/private_kernel_oracle.d.ts +6 -2
  101. package/dest/private_kernel/private_kernel_oracle.d.ts.map +1 -1
  102. package/dest/private_kernel/private_kernel_oracle.js +7 -3
  103. package/dest/pxe.d.ts +73 -24
  104. package/dest/pxe.d.ts.map +1 -1
  105. package/dest/pxe.js +112 -73
  106. package/dest/storage/contract_store/contract_store.d.ts +42 -15
  107. package/dest/storage/contract_store/contract_store.d.ts.map +1 -1
  108. package/dest/storage/contract_store/contract_store.js +145 -69
  109. package/dest/storage/metadata.d.ts +1 -1
  110. package/dest/storage/metadata.js +1 -1
  111. package/dest/storage/note_store/note_store.d.ts +3 -3
  112. package/dest/storage/note_store/note_store.d.ts.map +1 -1
  113. package/dest/storage/note_store/note_store.js +6 -4
  114. package/dest/storage/tagging_store/recipient_tagging_store.d.ts +6 -6
  115. package/dest/storage/tagging_store/recipient_tagging_store.d.ts.map +1 -1
  116. package/dest/storage/tagging_store/sender_tagging_store.d.ts +29 -28
  117. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  118. package/dest/storage/tagging_store/sender_tagging_store.js +141 -115
  119. package/dest/tagging/get_all_logs_by_tags.d.ts +1 -1
  120. package/dest/tagging/get_all_logs_by_tags.d.ts.map +1 -1
  121. package/dest/tagging/get_all_logs_by_tags.js +17 -3
  122. package/dest/tagging/index.d.ts +3 -3
  123. package/dest/tagging/index.d.ts.map +1 -1
  124. package/dest/tagging/index.js +1 -1
  125. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.d.ts +4 -5
  126. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.d.ts.map +1 -1
  127. package/dest/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.js +7 -7
  128. package/dest/tagging/recipient_sync/utils/find_highest_indexes.js +2 -2
  129. package/dest/tagging/recipient_sync/utils/load_logs_for_range.d.ts +6 -7
  130. package/dest/tagging/recipient_sync/utils/load_logs_for_range.d.ts.map +1 -1
  131. package/dest/tagging/recipient_sync/utils/load_logs_for_range.js +12 -11
  132. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +4 -8
  133. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  134. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +13 -7
  135. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +4 -3
  136. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  137. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +20 -10
  138. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +5 -7
  139. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  140. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +36 -24
  141. package/package.json +16 -16
  142. package/src/access_scopes.ts +9 -0
  143. package/src/config/index.ts +1 -1
  144. package/src/config/package_info.ts +1 -1
  145. package/src/contract_function_simulator/contract_function_simulator.ts +359 -135
  146. package/src/contract_function_simulator/execution_tagging_index_cache.ts +19 -14
  147. package/src/contract_function_simulator/index.ts +1 -0
  148. package/src/contract_function_simulator/noir-structs/event_validation_request.ts +8 -5
  149. package/src/contract_function_simulator/noir-structs/log_retrieval_response.ts +1 -4
  150. package/src/contract_function_simulator/noir-structs/message_tx_context.ts +55 -0
  151. package/src/contract_function_simulator/noir-structs/note_validation_request.ts +3 -6
  152. package/src/contract_function_simulator/oracle/interfaces.ts +54 -54
  153. package/src/contract_function_simulator/oracle/legacy_oracle_mappings.ts +135 -0
  154. package/src/contract_function_simulator/oracle/oracle.ts +177 -139
  155. package/src/contract_function_simulator/oracle/private_execution.ts +4 -4
  156. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +122 -177
  157. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +232 -84
  158. package/src/contract_logging.ts +39 -0
  159. package/src/contract_sync/contract_sync_service.ts +87 -35
  160. package/src/contract_sync/helpers.ts +7 -2
  161. package/src/debug/pxe_debug_utils.ts +12 -15
  162. package/src/entrypoints/client/bundle/index.ts +3 -0
  163. package/src/entrypoints/client/bundle/utils.ts +9 -1
  164. package/src/entrypoints/client/lazy/index.ts +3 -0
  165. package/src/entrypoints/client/lazy/utils.ts +9 -1
  166. package/src/entrypoints/server/index.ts +2 -0
  167. package/src/entrypoints/server/utils.ts +7 -7
  168. package/src/logs/log_service.ts +17 -24
  169. package/src/messages/message_context_service.ts +45 -0
  170. package/src/notes/note_service.ts +4 -3
  171. package/src/notes_filter.ts +26 -0
  172. package/src/oracle_version.ts +3 -3
  173. package/src/private_kernel/hints/{compute_tx_include_by_timestamp.ts → compute_tx_expiration_timestamp.ts} +13 -13
  174. package/src/private_kernel/hints/index.ts +1 -1
  175. package/src/private_kernel/hints/private_kernel_reset_private_inputs_builder.ts +164 -117
  176. package/src/private_kernel/hints/test_utils.ts +325 -0
  177. package/src/private_kernel/private_kernel_execution_prover.ts +19 -12
  178. package/src/private_kernel/private_kernel_oracle.ts +7 -7
  179. package/src/pxe.ts +201 -117
  180. package/src/storage/contract_store/contract_store.ts +174 -75
  181. package/src/storage/metadata.ts +1 -1
  182. package/src/storage/note_store/note_store.ts +12 -5
  183. package/src/storage/tagging_store/recipient_tagging_store.ts +9 -5
  184. package/src/storage/tagging_store/sender_tagging_store.ts +185 -138
  185. package/src/tagging/get_all_logs_by_tags.ts +28 -4
  186. package/src/tagging/index.ts +2 -2
  187. package/src/tagging/recipient_sync/load_private_logs_for_sender_recipient_pair.ts +7 -10
  188. package/src/tagging/recipient_sync/utils/find_highest_indexes.ts +2 -2
  189. package/src/tagging/recipient_sync/utils/load_logs_for_range.ts +10 -15
  190. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +23 -10
  191. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +26 -11
  192. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +27 -26
  193. package/dest/private_kernel/hints/compute_tx_include_by_timestamp.d.ts +0 -4
  194. package/dest/private_kernel/hints/compute_tx_include_by_timestamp.d.ts.map +0 -1
package/src/pxe.ts CHANGED
@@ -33,6 +33,7 @@ import type {
33
33
  PrivateKernelTailCircuitPublicInputs,
34
34
  } from '@aztec/stdlib/kernel';
35
35
  import {
36
+ BlockHeader,
36
37
  type ContractOverrides,
37
38
  type InTx,
38
39
  PrivateExecutionResult,
@@ -46,11 +47,12 @@ import {
46
47
  TxProfileResult,
47
48
  TxProvingResult,
48
49
  TxSimulationResult,
49
- UtilitySimulationResult,
50
+ UtilityExecutionResult,
50
51
  } from '@aztec/stdlib/tx';
51
52
 
52
53
  import { inspect } from 'util';
53
54
 
55
+ import type { AccessScopes } from './access_scopes.js';
54
56
  import { BlockSynchronizer } from './block_synchronizer/index.js';
55
57
  import type { PXEConfig } from './config/index.js';
56
58
  import { BenchmarkedNodeFactory } from './contract_function_simulator/benchmarked_node.js';
@@ -59,12 +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';
64
+ import { displayDebugLogs } from './contract_logging.js';
62
65
  import { ContractSyncService } from './contract_sync/contract_sync_service.js';
63
66
  import { readCurrentClassId } from './contract_sync/helpers.js';
64
67
  import { PXEDebugUtils } from './debug/pxe_debug_utils.js';
65
68
  import { enrichPublicSimulationError, enrichSimulationError } from './error_enriching.js';
66
69
  import { PrivateEventFilterValidator } from './events/private_event_filter_validator.js';
67
70
  import { JobCoordinator } from './job_coordinator/job_coordinator.js';
71
+ import { MessageContextService } from './messages/message_context_service.js';
68
72
  import {
69
73
  PrivateKernelExecutionProver,
70
74
  type PrivateKernelExecutionProverConfig,
@@ -85,6 +89,58 @@ export type PackedPrivateEvent = InTx & {
85
89
  eventSelector: EventSelector;
86
90
  };
87
91
 
92
+ /** Options for PXE.profileTx. */
93
+ export type ProfileTxOpts = {
94
+ /** The profiling mode to use. */
95
+ profileMode: 'full' | 'execution-steps' | 'gates';
96
+ /** If true, proof generation is skipped during profiling. Defaults to true. */
97
+ skipProofGeneration?: boolean;
98
+ /** Addresses whose private state and keys are accessible during private execution. */
99
+ scopes: AccessScopes;
100
+ };
101
+
102
+ /** Options for PXE.simulateTx. */
103
+ export type SimulateTxOpts = {
104
+ /** Whether to simulate the public part of the transaction. */
105
+ simulatePublic: boolean;
106
+ /** If false, this function throws if the transaction is unable to be included in a block at the current state. */
107
+ skipTxValidation?: boolean;
108
+ /** If false, fees are enforced. */
109
+ skipFeeEnforcement?: boolean;
110
+ /** If true, kernel logic is emulated in TS for simulation */
111
+ skipKernels?: boolean;
112
+ /** State overrides for the simulation, such as contract instances and artifacts. Requires skipKernels: true */
113
+ overrides?: SimulationOverrides;
114
+ /** Addresses whose private state and keys are accessible during private execution */
115
+ scopes: AccessScopes;
116
+ };
117
+
118
+ /** Options for PXE.executeUtility. */
119
+ export type ExecuteUtilityOpts = {
120
+ /** The authentication witnesses required for the function call. */
121
+ authwits?: AuthWitness[];
122
+ /** The accounts whose notes we can access in this call */
123
+ scopes: AccessScopes;
124
+ };
125
+
126
+ /** Args for PXE.create. */
127
+ export type PXECreateArgs = {
128
+ /** The Aztec node to connect to. */
129
+ node: AztecNode;
130
+ /** The key-value store for persisting PXE state. */
131
+ store: AztecAsyncKVStore;
132
+ /** The prover for generating private kernel proofs. */
133
+ proofCreator: PrivateKernelProver;
134
+ /** The circuit simulator for executing ACIR circuits. */
135
+ simulator: CircuitSimulator;
136
+ /** Provider for protocol contract artifacts and instances. */
137
+ protocolContractsProvider: ProtocolContractsProvider;
138
+ /** PXE configuration options. */
139
+ config: PXEConfig;
140
+ /** Optional logger instance or string suffix for the logger name. */
141
+ loggerOrSuffix?: string | Logger;
142
+ };
143
+
88
144
  /**
89
145
  * Private eXecution Environment (PXE) is a library used by wallets to simulate private phase of transactions and to
90
146
  * manage private state of users.
@@ -92,6 +148,7 @@ export type PackedPrivateEvent = InTx & {
92
148
  export class PXE {
93
149
  private constructor(
94
150
  private node: AztecNode,
151
+ private db: AztecAsyncKVStore,
95
152
  private blockStateSynchronizer: BlockSynchronizer,
96
153
  private keyStore: KeyStore,
97
154
  private contractStore: ContractStore,
@@ -104,6 +161,7 @@ export class PXE {
104
161
  private addressStore: AddressStore,
105
162
  private privateEventStore: PrivateEventStore,
106
163
  private contractSyncService: ContractSyncService,
164
+ private messageContextService: MessageContextService,
107
165
  private simulator: CircuitSimulator,
108
166
  private proverEnabled: boolean,
109
167
  private proofCreator: PrivateKernelProver,
@@ -121,15 +179,15 @@ export class PXE {
121
179
  *
122
180
  * @returns A promise that resolves PXE is ready to be used.
123
181
  */
124
- public static async create(
125
- node: AztecNode,
126
- store: AztecAsyncKVStore,
127
- proofCreator: PrivateKernelProver,
128
- simulator: CircuitSimulator,
129
- protocolContractsProvider: ProtocolContractsProvider,
130
- config: PXEConfig,
131
- loggerOrSuffix?: string | Logger,
132
- ) {
182
+ public static async create({
183
+ node,
184
+ store,
185
+ proofCreator,
186
+ simulator,
187
+ protocolContractsProvider,
188
+ config,
189
+ loggerOrSuffix,
190
+ }: PXECreateArgs) {
133
191
  // Extract bindings from the logger, or use empty bindings if a string suffix is provided.
134
192
  const bindings: LoggerBindings | undefined =
135
193
  loggerOrSuffix && typeof loggerOrSuffix !== 'string' ? loggerOrSuffix.getBindings() : undefined;
@@ -139,7 +197,9 @@ export class PXE {
139
197
  ? createLogger(loggerOrSuffix ? `pxe:service:${loggerOrSuffix}` : `pxe:service`)
140
198
  : loggerOrSuffix;
141
199
 
142
- const proverEnabled = !!config.proverEnabled;
200
+ const info = await node.getNodeInfo();
201
+
202
+ const proverEnabled = config.proverEnabled !== undefined ? config.proverEnabled : info.realProofs;
143
203
  const addressStore = new AddressStore(store);
144
204
  const privateEventStore = new PrivateEventStore(store);
145
205
  const contractStore = new ContractStore(store);
@@ -157,6 +217,8 @@ export class PXE {
157
217
  noteStore,
158
218
  createLogger('pxe:contract_sync', bindings),
159
219
  );
220
+ const messageContextService = new MessageContextService(node);
221
+
160
222
  const synchronizer = new BlockSynchronizer(
161
223
  node,
162
224
  store,
@@ -185,6 +247,7 @@ export class PXE {
185
247
 
186
248
  const pxe = new PXE(
187
249
  node,
250
+ store,
188
251
  synchronizer,
189
252
  keyStore,
190
253
  contractStore,
@@ -197,6 +260,7 @@ export class PXE {
197
260
  addressStore,
198
261
  privateEventStore,
199
262
  contractSyncService,
263
+ messageContextService,
200
264
  simulator,
201
265
  proverEnabled,
202
266
  proofCreator,
@@ -210,13 +274,12 @@ export class PXE {
210
274
  debugUtils.setPXEHelpers(
211
275
  pxe.#putInJobQueue.bind(pxe),
212
276
  pxe.#getSimulatorForTx.bind(pxe),
213
- pxe.#simulateUtility.bind(pxe),
277
+ pxe.#executeUtility.bind(pxe),
214
278
  );
215
279
 
216
280
  pxe.jobQueue.start();
217
281
 
218
282
  await pxe.#registerProtocolContracts();
219
- const info = await node.getNodeInfo();
220
283
  log.info(`Started PXE connected to chain ${info.l1ChainId} version ${info.rollupVersion}`);
221
284
  return pxe;
222
285
  }
@@ -226,20 +289,21 @@ export class PXE {
226
289
  #getSimulatorForTx(overrides?: { contracts?: ContractOverrides }) {
227
290
  const proxyContractStore = ProxiedContractStoreFactory.create(this.contractStore, overrides?.contracts);
228
291
 
229
- return new ContractFunctionSimulator(
230
- proxyContractStore,
231
- this.noteStore,
232
- this.keyStore,
233
- this.addressStore,
234
- BenchmarkedNodeFactory.create(this.node),
235
- this.senderTaggingStore,
236
- this.recipientTaggingStore,
237
- this.senderAddressBookStore,
238
- this.capsuleStore,
239
- this.privateEventStore,
240
- this.simulator,
241
- this.contractSyncService,
242
- );
292
+ return new ContractFunctionSimulator({
293
+ contractStore: proxyContractStore,
294
+ noteStore: this.noteStore,
295
+ keyStore: this.keyStore,
296
+ addressStore: this.addressStore,
297
+ aztecNode: BenchmarkedNodeFactory.create(this.node),
298
+ senderTaggingStore: this.senderTaggingStore,
299
+ recipientTaggingStore: this.recipientTaggingStore,
300
+ senderAddressBookStore: this.senderAddressBookStore,
301
+ capsuleStore: this.capsuleStore,
302
+ privateEventStore: this.privateEventStore,
303
+ simulator: this.simulator,
304
+ contractSyncService: this.contractSyncService,
305
+ messageContextService: this.messageContextService,
306
+ });
243
307
  }
244
308
 
245
309
  #contextualizeError(err: Error, ...context: string[]): Error {
@@ -291,9 +355,8 @@ export class PXE {
291
355
  async #registerProtocolContracts() {
292
356
  const registered: Record<string, string> = {};
293
357
  for (const name of protocolContractNames) {
294
- const { address, contractClass, instance, artifact } =
295
- await this.protocolContractsProvider.getProtocolContractArtifact(name);
296
- await this.contractStore.addContractArtifact(contractClass.id, artifact);
358
+ const { address, instance, artifact } = await this.protocolContractsProvider.getProtocolContractArtifact(name);
359
+ await this.contractStore.addContractArtifact(artifact);
297
360
  await this.contractStore.addContractInstance(instance);
298
361
  registered[name] = address.toString();
299
362
  }
@@ -305,7 +368,7 @@ export class PXE {
305
368
  async #executePrivate(
306
369
  contractFunctionSimulator: ContractFunctionSimulator,
307
370
  txRequest: TxExecutionRequest,
308
- scopes: AztecAddress[] | undefined,
371
+ scopes: AccessScopes,
309
372
  jobId: string,
310
373
  ): Promise<PrivateExecutionResult> {
311
374
  const { origin: contractAddress, functionSelector } = txRequest;
@@ -316,23 +379,20 @@ export class PXE {
316
379
  await this.contractSyncService.ensureContractSynced(
317
380
  contractAddress,
318
381
  functionSelector,
319
- privateSyncCall => this.#simulateUtility(contractFunctionSimulator, privateSyncCall, [], undefined, jobId),
382
+ (privateSyncCall, execScopes) =>
383
+ this.#executeUtility(contractFunctionSimulator, privateSyncCall, [], execScopes, jobId),
320
384
  anchorBlockHeader,
321
385
  jobId,
386
+ scopes,
322
387
  );
323
388
 
324
- const result = await contractFunctionSimulator.run(
325
- txRequest,
389
+ const result = await contractFunctionSimulator.run(txRequest, {
326
390
  contractAddress,
327
- functionSelector,
328
- undefined,
391
+ selector: functionSelector,
329
392
  anchorBlockHeader,
330
- // The sender for tags is set by contracts, typically by an account
331
- // contract entrypoint
332
- undefined, // senderForTags
333
393
  scopes,
334
394
  jobId,
335
- );
395
+ });
336
396
  this.log.debug(`Private simulation completed for ${contractAddress.toString()}:${functionSelector}`);
337
397
  return result;
338
398
  } catch (err) {
@@ -344,25 +404,32 @@ export class PXE {
344
404
  }
345
405
 
346
406
  /**
347
- * Simulate a utility function call on the given contract.
407
+ * Execute a utility function call on the given contract.
348
408
  * @param contractFunctionSimulator - The simulator to use for the function call.
349
409
  * @param call - The function call to execute.
350
410
  * @param authWitnesses - Authentication witnesses required for the function call.
351
411
  * @param scopes - Optional array of account addresses whose notes can be accessed in this call. Defaults to all
352
412
  * accounts if not specified.
353
413
  * @param jobId - The job ID for staged writes.
354
- * @returns The simulation result containing the outputs of the utility function.
414
+ * @returns The execution result containing the outputs of the utility function.
355
415
  */
356
- async #simulateUtility(
416
+ async #executeUtility(
357
417
  contractFunctionSimulator: ContractFunctionSimulator,
358
418
  call: FunctionCall,
359
419
  authWitnesses: AuthWitness[] | undefined,
360
- scopes: AztecAddress[] | undefined,
420
+ scopes: AccessScopes,
361
421
  jobId: string,
362
422
  ) {
363
423
  try {
364
424
  const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
365
- return contractFunctionSimulator.runUtility(call, authWitnesses ?? [], anchorBlockHeader, scopes, jobId);
425
+ const { result, offchainEffects } = await contractFunctionSimulator.runUtility(
426
+ call,
427
+ authWitnesses ?? [],
428
+ anchorBlockHeader,
429
+ scopes,
430
+ jobId,
431
+ );
432
+ return { result, offchainEffects };
366
433
  } catch (err) {
367
434
  if (err instanceof SimulationError) {
368
435
  await enrichSimulationError(err, this.contractStore, this.log);
@@ -430,6 +497,19 @@ export class PXE {
430
497
 
431
498
  // Public API
432
499
 
500
+ /**
501
+ * Returns the block header up to which the PXE has synced.
502
+ * @returns The synced block header
503
+ */
504
+ public getSyncedBlockHeader(): Promise<BlockHeader> {
505
+ return this.anchorBlockStore.getBlockHeader();
506
+ }
507
+
508
+ /**
509
+ * Returns the contract instance for a given address, if it's registered in the PXE.
510
+ * @param address - The contract address.
511
+ * @returns The contract instance if found, undefined otherwise.
512
+ */
433
513
  public getContractInstance(address: AztecAddress): Promise<ContractInstanceWithAddress | undefined> {
434
514
  return this.contractStore.getContractInstance(address);
435
515
  }
@@ -489,6 +569,9 @@ export class PXE {
489
569
 
490
570
  if (wasAdded) {
491
571
  this.log.info(`Added sender:\n ${sender.toString()}`);
572
+ // Wipe the entire sync cache: the new sender's tagged logs could contain notes/events for any contract, so
573
+ // all contracts must re-sync to discover them.
574
+ this.contractSyncService.wipe();
492
575
  } else {
493
576
  this.log.info(`Sender:\n "${sender.toString()}"\n already registered.`);
494
577
  }
@@ -538,8 +621,7 @@ export class PXE {
538
621
  * @param artifact - The build artifact for the contract class.
539
622
  */
540
623
  public async registerContractClass(artifact: ContractArtifact): Promise<void> {
541
- const { id: contractClassId } = await getContractClassFromArtifact(artifact);
542
- await this.contractStore.addContractArtifact(contractClassId, artifact);
624
+ const contractClassId = await this.contractStore.addContractArtifact(artifact);
543
625
  this.log.info(`Added contract class ${artifact.name} with id ${contractClassId}`);
544
626
  }
545
627
 
@@ -558,17 +640,17 @@ export class PXE {
558
640
  if (artifact) {
559
641
  // If the user provides an artifact, validate it against the expected class id and register it
560
642
  const contractClass = await getContractClassFromArtifact(artifact);
561
- const contractClassId = contractClass.id;
562
- if (!contractClassId.equals(instance.currentContractClassId)) {
643
+ if (!contractClass.id.equals(instance.currentContractClassId)) {
563
644
  throw new Error(
564
- `Artifact does not match expected class id (computed ${contractClassId} but instance refers to ${instance.currentContractClassId})`,
645
+ `Artifact does not match expected class id (computed ${contractClass.id} but instance refers to ${instance.currentContractClassId})`,
565
646
  );
566
647
  }
567
648
  const computedAddress = await computeContractAddressFromInstance(instance);
568
649
  if (!computedAddress.equals(instance.address)) {
569
650
  throw new Error('Added a contract in which the address does not match the contract instance.');
570
651
  }
571
- await this.contractStore.addContractArtifact(contractClass.id, artifact);
652
+
653
+ await this.contractStore.addContractArtifact(artifact, contractClass);
572
654
 
573
655
  const publicFunctionSignatures = artifact.functions
574
656
  .filter(fn => fn.functionType === FunctionType.PUBLIC)
@@ -617,15 +699,16 @@ export class PXE {
617
699
  throw new Error('Could not update contract to a class different from the current one.');
618
700
  }
619
701
 
620
- await this.contractStore.addContractArtifact(contractClass.id, artifact);
621
-
622
702
  const publicFunctionSignatures = artifact.functions
623
703
  .filter(fn => fn.functionType === FunctionType.PUBLIC)
624
704
  .map(fn => decodeFunctionSignature(fn.name, fn.parameters));
625
705
  await this.node.registerContractFunctionSignatures(publicFunctionSignatures);
626
706
 
627
707
  currentInstance.currentContractClassId = contractClass.id;
628
- await this.contractStore.addContractInstance(currentInstance);
708
+ await Promise.all([
709
+ this.contractStore.addContractArtifact(artifact, contractClass),
710
+ this.contractStore.addContractInstance(currentInstance),
711
+ ]);
629
712
  this.log.info(`Updated contract ${artifact.name} at ${contractAddress.toString()} to class ${contractClass.id}`);
630
713
  });
631
714
  }
@@ -643,11 +726,12 @@ export class PXE {
643
726
  * (where validators prove the public portion).
644
727
  *
645
728
  * @param txRequest - An authenticated tx request ready for proving
729
+ * @param scopes - Addresses whose private state and keys are accessible during private execution.
646
730
  * @returns A result containing the proof and public inputs of the tail circuit.
647
731
  * @throws If contract code not found, or public simulation reverts.
648
732
  * Also throws if simulatePublic is true and public simulation reverts.
649
733
  */
650
- public proveTx(txRequest: TxExecutionRequest): Promise<TxProvingResult> {
734
+ public proveTx(txRequest: TxExecutionRequest, scopes: AztecAddress[]): Promise<TxProvingResult> {
651
735
  let privateExecutionResult: PrivateExecutionResult;
652
736
  // We disable proving concurrently mostly out of caution, since it accesses some of our stores. Proving is so
653
737
  // computationally demanding that it'd be rare for someone to try to do it concurrently regardless.
@@ -658,7 +742,7 @@ export class PXE {
658
742
  await this.blockStateSynchronizer.sync();
659
743
  const syncTime = syncTimer.ms();
660
744
  const contractFunctionSimulator = this.#getSimulatorForTx();
661
- privateExecutionResult = await this.#executePrivate(contractFunctionSimulator, txRequest, undefined, jobId);
745
+ privateExecutionResult = await this.#executePrivate(contractFunctionSimulator, txRequest, scopes, jobId);
662
746
 
663
747
  const {
664
748
  publicInputs,
@@ -700,17 +784,17 @@ export class PXE {
700
784
  // transaction before this one is included in a block from this PXE, and that transaction contains a log with
701
785
  // a tag derived from the same secret, we would reuse the tag and the transactions would be linked. Hence
702
786
  // storing the tags here prevents linkage of txs sent from the same PXE.
703
- const preTagsUsedInTheTx = privateExecutionResult.entrypoint.preTags;
704
- if (preTagsUsedInTheTx.length > 0) {
787
+ const taggingIndexRangesUsedInTheTx = privateExecutionResult.entrypoint.taggingIndexRanges;
788
+ if (taggingIndexRangesUsedInTheTx.length > 0) {
705
789
  // TODO(benesjan): The following is an expensive operation. Figure out a way to avoid it.
706
790
  const txHash = (await txProvingResult.toTx()).txHash;
707
791
 
708
- await this.senderTaggingStore.storePendingIndexes(preTagsUsedInTheTx, txHash, jobId);
709
- this.log.debug(`Stored used pre-tags as sender for the tx`, {
710
- preTagsUsedInTheTx,
792
+ await this.senderTaggingStore.storePendingIndexes(taggingIndexRangesUsedInTheTx, txHash, jobId);
793
+ this.log.debug(`Stored used tagging index ranges as sender for the tx`, {
794
+ taggingIndexRangesUsedInTheTx,
711
795
  });
712
796
  } else {
713
- this.log.debug(`No pre-tags used in the tx`);
797
+ this.log.debug(`No tagging index ranges used in the tx`);
714
798
  }
715
799
 
716
800
  return txProvingResult;
@@ -722,17 +806,13 @@ export class PXE {
722
806
 
723
807
  /**
724
808
  * Profiles a transaction, reporting gate counts (unless disabled) and returns an execution trace.
725
- *
726
- * @param txRequest - An authenticated tx request ready for simulation
727
- * @param msgSender - (Optional) The message sender to use for the simulation.
728
- * @param skipTxValidation - (Optional) If false, this function throws if the transaction is unable to be included in a block at the current state.
809
+ * @param txRequest - An authenticated tx request ready for simulation.
729
810
  * @returns A trace of the program execution with gate counts.
730
811
  * @throws If the code for the functions executed in this transaction have not been made available via `addContracts`.
731
812
  */
732
813
  public profileTx(
733
814
  txRequest: TxExecutionRequest,
734
- profileMode: 'full' | 'execution-steps' | 'gates',
735
- skipProofGeneration: boolean = true,
815
+ { profileMode, skipProofGeneration = true, scopes }: ProfileTxOpts,
736
816
  ): Promise<TxProfileResult> {
737
817
  // We disable concurrent profiles for consistency with simulateTx.
738
818
  return this.#putInJobQueue(async jobId => {
@@ -755,12 +835,7 @@ export class PXE {
755
835
  const syncTime = syncTimer.ms();
756
836
 
757
837
  const contractFunctionSimulator = this.#getSimulatorForTx();
758
- const privateExecutionResult = await this.#executePrivate(
759
- contractFunctionSimulator,
760
- txRequest,
761
- undefined,
762
- jobId,
763
- );
838
+ const privateExecutionResult = await this.#executePrivate(contractFunctionSimulator, txRequest, scopes, jobId);
764
839
 
765
840
  const { executionSteps, timings: { proving } = {} } = await this.#prove(
766
841
  txRequest,
@@ -817,12 +892,7 @@ export class PXE {
817
892
  * In that case, the transaction returned is only potentially ready to be sent to the network for execution.
818
893
  *
819
894
  *
820
- * @param txRequest - An authenticated tx request ready for simulation
821
- * @param simulatePublic - Whether to simulate the public part of the transaction.
822
- * @param skipTxValidation - (Optional) If false, this function throws if the transaction is unable to be included in a block at the current state.
823
- * @param skipFeeEnforcement - (Optional) If false, fees are enforced.
824
- * @param overrides - (Optional) State overrides for the simulation, such as msgSender, contract instances and artifacts.
825
- * @param scopes - (Optional) The accounts whose notes we can access in this call. Currently optional and will default to all.
895
+ * @param txRequest - An authenticated tx request ready for simulation.
826
896
  * @returns A simulated transaction result object that includes public and private return values.
827
897
  * @throws If the code for the functions executed in this transaction have not been made available via `addContracts`.
828
898
  * Also throws if simulatePublic is true and public simulation reverts.
@@ -831,11 +901,14 @@ export class PXE {
831
901
  */
832
902
  public simulateTx(
833
903
  txRequest: TxExecutionRequest,
834
- simulatePublic: boolean,
835
- skipTxValidation: boolean = false,
836
- skipFeeEnforcement: boolean = false,
837
- overrides?: SimulationOverrides,
838
- scopes?: AztecAddress[],
904
+ {
905
+ simulatePublic,
906
+ skipTxValidation = false,
907
+ skipFeeEnforcement = false,
908
+ skipKernels = true,
909
+ overrides,
910
+ scopes,
911
+ }: SimulateTxOpts,
839
912
  ): Promise<TxSimulationResult> {
840
913
  // We disable concurrent simulations since those might execute oracles which read and write to the PXE stores (e.g.
841
914
  // to the capsules), and we need to prevent concurrent runs from interfering with one another (e.g. attempting to
@@ -859,17 +932,20 @@ export class PXE {
859
932
  await this.blockStateSynchronizer.sync();
860
933
  const syncTime = syncTimer.ms();
861
934
 
862
- const contractFunctionSimulator = this.#getSimulatorForTx(overrides);
863
- // Temporary: in case there are overrides, we have to skip the kernels or validations
864
- // will fail. Consider handing control to the user/wallet on whether they want to run them
865
- // or not.
866
935
  const overriddenContracts = overrides?.contracts ? new Set(Object.keys(overrides.contracts)) : undefined;
867
936
  const hasOverriddenContracts = overriddenContracts !== undefined && overriddenContracts.size > 0;
868
- const skipKernels = hasOverriddenContracts;
869
937
 
870
- // Set overridden contracts on the sync service so it knows to skip syncing them
938
+ if (hasOverriddenContracts && !skipKernels) {
939
+ throw new Error(
940
+ 'Simulating with overridden contracts is not compatible with kernel execution. Please set skipKernels to true when simulating with overridden contracts.',
941
+ );
942
+ }
943
+ const contractFunctionSimulator = this.#getSimulatorForTx(overrides);
944
+
871
945
  if (hasOverriddenContracts) {
872
- this.contractSyncService.setOverriddenContracts(jobId, overriddenContracts);
946
+ // Overridden contracts don't have a sync function, so calling sync on them would fail.
947
+ // We exclude them so the sync service skips them entirely.
948
+ this.contractSyncService.setExcludedFromSync(jobId, overriddenContracts);
873
949
  }
874
950
 
875
951
  // Execution of private functions only; no proving, and no kernel logic.
@@ -881,7 +957,8 @@ export class PXE {
881
957
  if (skipKernels) {
882
958
  ({ publicInputs, executionSteps } = await generateSimulatedProvingResult(
883
959
  privateExecutionResult,
884
- this.contractStore,
960
+ (addr, sel) => this.contractStore.getDebugFunctionName(addr, sel),
961
+ this.node,
885
962
  ));
886
963
  } else {
887
964
  // Kernel logic, plus proving of all private functions and kernels.
@@ -900,6 +977,9 @@ export class PXE {
900
977
  const publicSimulationTimer = new Timer();
901
978
  publicOutput = await this.#simulatePublicCalls(simulatedTx, skipFeeEnforcement);
902
979
  publicSimulationTime = publicSimulationTimer.ms();
980
+ if (publicOutput?.debugLogs?.length) {
981
+ await displayDebugLogs(publicOutput.debugLogs, addr => this.contractStore.getDebugContractName(addr));
982
+ }
903
983
  }
904
984
 
905
985
  let validationTime: number | undefined;
@@ -908,7 +988,8 @@ export class PXE {
908
988
  const validationResult = await this.node.isValidTx(simulatedTx, { isSimulation: true, skipFeeEnforcement });
909
989
  validationTime = validationTimer.ms();
910
990
  if (validationResult.result === 'invalid') {
911
- throw new Error('The simulated transaction is unable to be added to state and is invalid.');
991
+ const reason = validationResult.reason.length > 0 ? ` Reason: ${validationResult.reason.join(', ')}` : '';
992
+ throw new Error(`The simulated transaction is unable to be added to state and is invalid.${reason}`);
912
993
  }
913
994
  }
914
995
 
@@ -959,29 +1040,23 @@ export class PXE {
959
1040
  inspect(txRequest),
960
1041
  `simulatePublic=${simulatePublic}`,
961
1042
  `skipTxValidation=${skipTxValidation}`,
962
- `scopes=${scopes?.map(s => s.toString()).join(', ') ?? 'undefined'}`,
1043
+ `scopes=${scopes === 'ALL_SCOPES' ? scopes : scopes.map(s => s.toString()).join(', ')}`,
963
1044
  );
964
1045
  }
965
1046
  });
966
1047
  }
967
1048
 
968
1049
  /**
969
- * Simulate the execution of a contract utility function.
970
- *
1050
+ * Executes a contract utility function.
971
1051
  * @param call - The function call containing the function details, arguments, and target contract address.
972
- * @param authwits - (Optional) The authentication witnesses required for the function call.
973
- * @param scopes - (Optional) The accounts whose notes we can access in this call. Currently optional and will
974
- * default to all.
975
- * @returns The result of the utility function call, structured based on the function ABI.
976
1052
  */
977
- public simulateUtility(
1053
+ public executeUtility(
978
1054
  call: FunctionCall,
979
- authwits?: AuthWitness[],
980
- scopes?: AztecAddress[],
981
- ): Promise<UtilitySimulationResult> {
982
- // We disable concurrent simulations since those might execute oracles which read and write to the PXE stores (e.g.
1055
+ { authwits, scopes }: ExecuteUtilityOpts = { scopes: 'ALL_SCOPES' },
1056
+ ): Promise<UtilityExecutionResult> {
1057
+ // We disable concurrent executions since those might execute oracles which read and write to the PXE stores (e.g.
983
1058
  // to the capsules), and we need to prevent concurrent runs from interfering with one another (e.g. attempting to
984
- // delete the same read value, or reading values that another simulation is currently modifying).
1059
+ // delete the same read value, or reading values that another execution is currently modifying).
985
1060
  return this.#putInJobQueue(async jobId => {
986
1061
  try {
987
1062
  const totalTimer = new Timer();
@@ -995,12 +1070,14 @@ export class PXE {
995
1070
  await this.contractSyncService.ensureContractSynced(
996
1071
  call.to,
997
1072
  call.selector,
998
- privateSyncCall => this.#simulateUtility(contractFunctionSimulator, privateSyncCall, [], undefined, jobId),
1073
+ (privateSyncCall, execScopes) =>
1074
+ this.#executeUtility(contractFunctionSimulator, privateSyncCall, [], execScopes, jobId),
999
1075
  anchorBlockHeader,
1000
1076
  jobId,
1077
+ scopes,
1001
1078
  );
1002
1079
 
1003
- const executionResult = await this.#simulateUtility(
1080
+ const { result: executionResult, offchainEffects } = await this.#executeUtility(
1004
1081
  contractFunctionSimulator,
1005
1082
  call,
1006
1083
  authwits ?? [],
@@ -1021,14 +1098,19 @@ export class PXE {
1021
1098
  };
1022
1099
 
1023
1100
  const simulationStats = contractFunctionSimulator.getStats();
1024
- return { result: executionResult, stats: { timings, nodeRPCCalls: simulationStats.nodeRPCCalls } };
1101
+ return {
1102
+ result: executionResult,
1103
+ offchainEffects,
1104
+ anchorBlockTimestamp: anchorBlockHeader.globalVariables.timestamp,
1105
+ stats: { timings, nodeRPCCalls: simulationStats.nodeRPCCalls },
1106
+ };
1025
1107
  } catch (err: any) {
1026
1108
  const { to, name, args } = call;
1027
1109
  const stringifiedArgs = args.map(arg => arg.toString()).join(', ');
1028
1110
  throw this.#contextualizeError(
1029
1111
  err,
1030
- `simulateUtility ${to}:${name}(${stringifiedArgs})`,
1031
- `scopes=${scopes?.map(s => s.toString()).join(', ') ?? 'undefined'}`,
1112
+ `executeUtility ${to}:${name}(${stringifiedArgs})`,
1113
+ `scopes=${scopes === 'ALL_SCOPES' ? scopes : scopes.map(s => s.toString()).join(', ')}`,
1032
1114
  );
1033
1115
  }
1034
1116
  });
@@ -1064,10 +1146,11 @@ export class PXE {
1064
1146
  await this.contractSyncService.ensureContractSynced(
1065
1147
  filter.contractAddress,
1066
1148
  null,
1067
- async privateSyncCall =>
1068
- await this.#simulateUtility(contractFunctionSimulator, privateSyncCall, [], undefined, jobId),
1149
+ async (privateSyncCall, execScopes) =>
1150
+ await this.#executeUtility(contractFunctionSimulator, privateSyncCall, [], execScopes, jobId),
1069
1151
  anchorBlockHeader,
1070
1152
  jobId,
1153
+ filter.scopes,
1071
1154
  );
1072
1155
  });
1073
1156
 
@@ -1082,9 +1165,10 @@ export class PXE {
1082
1165
  }
1083
1166
 
1084
1167
  /**
1085
- * Stops the PXE's job queue.
1168
+ * Stops the PXE's job queue and closes the backing store.
1086
1169
  */
1087
- public stop(): Promise<void> {
1088
- return this.jobQueue.end();
1170
+ public async stop(): Promise<void> {
1171
+ await this.jobQueue.end();
1172
+ await this.db.close();
1089
1173
  }
1090
1174
  }