@aztec-labs/txe 6.0.0-nightly.20260829

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 (173) hide show
  1. package/dest/AuthRegistry-D4XJULH3.js +3 -0
  2. package/dest/AuthRegistry-D4XJULH3.js.map +7 -0
  3. package/dest/ContractClassRegistry-Q76MXQZD.js +3 -0
  4. package/dest/ContractClassRegistry-Q76MXQZD.js.map +7 -0
  5. package/dest/ContractInstanceRegistry-CTRARU77.js +3 -0
  6. package/dest/ContractInstanceRegistry-CTRARU77.js.map +7 -0
  7. package/dest/FeeJuice-YLTJXWYJ.js +3 -0
  8. package/dest/FeeJuice-YLTJXWYJ.js.map +7 -0
  9. package/dest/HandshakeRegistry-BRPEG7GL.js +3 -0
  10. package/dest/HandshakeRegistry-BRPEG7GL.js.map +7 -0
  11. package/dest/MultiCallEntrypoint-CJHMYQT5.js +3 -0
  12. package/dest/MultiCallEntrypoint-CJHMYQT5.js.map +7 -0
  13. package/dest/SchnorrAccount-OB4N4QIM.js +3 -0
  14. package/dest/SchnorrAccount-OB4N4QIM.js.map +7 -0
  15. package/dest/SchnorrInitializerlessAccount-TWGKRUSY.js +3 -0
  16. package/dest/SchnorrInitializerlessAccount-TWGKRUSY.js.map +7 -0
  17. package/dest/bin/check_txe_oracle_version.d.ts +2 -0
  18. package/dest/bin/check_txe_oracle_version.d.ts.map +1 -0
  19. package/dest/bin/check_txe_oracle_version.js +22 -0
  20. package/dest/bin/index.d.ts +3 -0
  21. package/dest/bin/index.d.ts.map +1 -0
  22. package/dest/bin/index.js +4 -0
  23. package/dest/bin/index.js.map +7 -0
  24. package/dest/bin/oracle_test_server.d.ts +3 -0
  25. package/dest/bin/oracle_test_server.d.ts.map +1 -0
  26. package/dest/bin/oracle_test_server.js +41 -0
  27. package/dest/chunk-32UHX7YY.js +3 -0
  28. package/dest/chunk-32UHX7YY.js.map +7 -0
  29. package/dest/chunk-F4QVFWNM.js +258 -0
  30. package/dest/chunk-F4QVFWNM.js.map +7 -0
  31. package/dest/chunk-LILEKW2X.js +304 -0
  32. package/dest/chunk-LILEKW2X.js.map +7 -0
  33. package/dest/constants.d.ts +7 -0
  34. package/dest/constants.d.ts.map +1 -0
  35. package/dest/constants.js +10 -0
  36. package/dest/dispatcher_pool.d.ts +67 -0
  37. package/dest/dispatcher_pool.d.ts.map +1 -0
  38. package/dest/dispatcher_pool.js +288 -0
  39. package/dest/index.d.ts +52 -0
  40. package/dest/index.d.ts.map +1 -0
  41. package/dest/index.js +102 -0
  42. package/dest/metafile.json +38805 -0
  43. package/dest/msgpackr_fr_extension.d.ts +2 -0
  44. package/dest/msgpackr_fr_extension.d.ts.map +1 -0
  45. package/dest/msgpackr_fr_extension.js +21 -0
  46. package/dest/oracle/interfaces.d.ts +90 -0
  47. package/dest/oracle/interfaces.d.ts.map +1 -0
  48. package/dest/oracle/interfaces.js +3 -0
  49. package/dest/oracle/noir-structs/gas_settings_data.d.ts +14 -0
  50. package/dest/oracle/noir-structs/gas_settings_data.d.ts.map +1 -0
  51. package/dest/oracle/noir-structs/gas_settings_data.js +1 -0
  52. package/dest/oracle/noir-structs/tx_effects_data.d.ts +11 -0
  53. package/dest/oracle/noir-structs/tx_effects_data.d.ts.map +1 -0
  54. package/dest/oracle/noir-structs/tx_effects_data.js +1 -0
  55. package/dest/oracle/tagging_secret_strategy.d.ts +12 -0
  56. package/dest/oracle/tagging_secret_strategy.d.ts.map +1 -0
  57. package/dest/oracle/tagging_secret_strategy.js +12 -0
  58. package/dest/oracle/test-resolver/default_fixtures.d.ts +16 -0
  59. package/dest/oracle/test-resolver/default_fixtures.d.ts.map +1 -0
  60. package/dest/oracle/test-resolver/default_fixtures.js +207 -0
  61. package/dest/oracle/test-resolver/index.d.ts +9 -0
  62. package/dest/oracle/test-resolver/index.d.ts.map +1 -0
  63. package/dest/oracle/test-resolver/index.js +32 -0
  64. package/dest/oracle/test-resolver/resolver.d.ts +48 -0
  65. package/dest/oracle/test-resolver/resolver.d.ts.map +1 -0
  66. package/dest/oracle/test-resolver/resolver.js +181 -0
  67. package/dest/oracle/txe_oracle_public_context.d.ts +58 -0
  68. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -0
  69. package/dest/oracle/txe_oracle_public_context.js +170 -0
  70. package/dest/oracle/txe_oracle_registry.d.ts +164 -0
  71. package/dest/oracle/txe_oracle_registry.d.ts.map +1 -0
  72. package/dest/oracle/txe_oracle_registry.js +753 -0
  73. package/dest/oracle/txe_oracle_top_level_context.d.ts +128 -0
  74. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -0
  75. package/dest/oracle/txe_oracle_top_level_context.js +815 -0
  76. package/dest/oracle/txe_oracle_version.d.ts +17 -0
  77. package/dest/oracle/txe_oracle_version.d.ts.map +1 -0
  78. package/dest/oracle/txe_oracle_version.js +14 -0
  79. package/dest/oracle/txe_private_execution_oracle.d.ts +17 -0
  80. package/dest/oracle/txe_private_execution_oracle.d.ts.map +1 -0
  81. package/dest/oracle/txe_private_execution_oracle.js +15 -0
  82. package/dest/rpc_server.d.ts +14 -0
  83. package/dest/rpc_server.d.ts.map +1 -0
  84. package/dest/rpc_server.js +78 -0
  85. package/dest/rpc_translator.d.ts +140 -0
  86. package/dest/rpc_translator.d.ts.map +1 -0
  87. package/dest/rpc_translator.js +976 -0
  88. package/dest/server.bundle.js +3 -0
  89. package/dest/server.bundle.js.map +7 -0
  90. package/dest/state_machine/archiver.d.ts +32 -0
  91. package/dest/state_machine/archiver.d.ts.map +1 -0
  92. package/dest/state_machine/archiver.js +95 -0
  93. package/dest/state_machine/dummy_p2p_client.d.ts +69 -0
  94. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -0
  95. package/dest/state_machine/dummy_p2p_client.js +180 -0
  96. package/dest/state_machine/global_variable_builder.d.ts +15 -0
  97. package/dest/state_machine/global_variable_builder.d.ts.map +1 -0
  98. package/dest/state_machine/global_variable_builder.js +25 -0
  99. package/dest/state_machine/index.d.ts +22 -0
  100. package/dest/state_machine/index.d.ts.map +1 -0
  101. package/dest/state_machine/index.js +110 -0
  102. package/dest/state_machine/mock_epoch_cache.d.ts +43 -0
  103. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -0
  104. package/dest/state_machine/mock_epoch_cache.js +88 -0
  105. package/dest/state_machine/synchronizer.d.ts +41 -0
  106. package/dest/state_machine/synchronizer.d.ts.map +1 -0
  107. package/dest/state_machine/synchronizer.js +70 -0
  108. package/dest/txe_session.d.ts +179 -0
  109. package/dest/txe_session.d.ts.map +1 -0
  110. package/dest/txe_session.js +697 -0
  111. package/dest/utils/block_creation.d.ts +28 -0
  112. package/dest/utils/block_creation.d.ts.map +1 -0
  113. package/dest/utils/block_creation.js +59 -0
  114. package/dest/utils/encoding.d.ts +194 -0
  115. package/dest/utils/encoding.d.ts.map +1 -0
  116. package/dest/utils/encoding.js +136 -0
  117. package/dest/utils/expected_failure_error.d.ts +4 -0
  118. package/dest/utils/expected_failure_error.d.ts.map +1 -0
  119. package/dest/utils/expected_failure_error.js +5 -0
  120. package/dest/utils/tx_effect_creation.d.ts +5 -0
  121. package/dest/utils/tx_effect_creation.d.ts.map +1 -0
  122. package/dest/utils/tx_effect_creation.js +12 -0
  123. package/dest/utils/txe_account_store.d.ts +10 -0
  124. package/dest/utils/txe_account_store.d.ts.map +1 -0
  125. package/dest/utils/txe_account_store.js +17 -0
  126. package/dest/utils/txe_artifact_resolver.d.ts +36 -0
  127. package/dest/utils/txe_artifact_resolver.d.ts.map +1 -0
  128. package/dest/utils/txe_artifact_resolver.js +160 -0
  129. package/dest/utils/txe_public_contract_data_source.d.ts +20 -0
  130. package/dest/utils/txe_public_contract_data_source.d.ts.map +1 -0
  131. package/dest/utils/txe_public_contract_data_source.js +51 -0
  132. package/dest/worker.bundle.js +3 -0
  133. package/dest/worker.bundle.js.map +7 -0
  134. package/dest/worker.d.ts +2 -0
  135. package/dest/worker.d.ts.map +1 -0
  136. package/dest/worker.js +92 -0
  137. package/package.json +115 -0
  138. package/src/bin/check_txe_oracle_version.ts +31 -0
  139. package/src/bin/index.ts +49 -0
  140. package/src/bin/oracle_test_server.ts +51 -0
  141. package/src/constants.ts +13 -0
  142. package/src/dispatcher_pool.ts +319 -0
  143. package/src/index.ts +152 -0
  144. package/src/msgpackr_fr_extension.ts +22 -0
  145. package/src/oracle/interfaces.ts +125 -0
  146. package/src/oracle/noir-structs/gas_settings_data.ts +16 -0
  147. package/src/oracle/noir-structs/tx_effects_data.ts +11 -0
  148. package/src/oracle/tagging_secret_strategy.ts +25 -0
  149. package/src/oracle/test-resolver/default_fixtures.ts +278 -0
  150. package/src/oracle/test-resolver/index.ts +43 -0
  151. package/src/oracle/test-resolver/resolver.ts +245 -0
  152. package/src/oracle/txe_oracle_public_context.ts +220 -0
  153. package/src/oracle/txe_oracle_registry.ts +501 -0
  154. package/src/oracle/txe_oracle_top_level_context.ts +1086 -0
  155. package/src/oracle/txe_oracle_version.ts +17 -0
  156. package/src/oracle/txe_private_execution_oracle.ts +30 -0
  157. package/src/rpc_server.ts +86 -0
  158. package/src/rpc_translator.ts +1229 -0
  159. package/src/state_machine/archiver.ts +118 -0
  160. package/src/state_machine/dummy_p2p_client.ts +264 -0
  161. package/src/state_machine/global_variable_builder.ts +39 -0
  162. package/src/state_machine/index.ts +152 -0
  163. package/src/state_machine/mock_epoch_cache.ts +111 -0
  164. package/src/state_machine/synchronizer.ts +105 -0
  165. package/src/txe_session.ts +1107 -0
  166. package/src/utils/block_creation.ts +91 -0
  167. package/src/utils/encoding.ts +171 -0
  168. package/src/utils/expected_failure_error.ts +5 -0
  169. package/src/utils/tx_effect_creation.ts +28 -0
  170. package/src/utils/txe_account_store.ts +23 -0
  171. package/src/utils/txe_artifact_resolver.ts +217 -0
  172. package/src/utils/txe_public_contract_data_source.ts +60 -0
  173. package/src/worker.ts +98 -0
@@ -0,0 +1,1107 @@
1
+ import { BlockNumber } from '@aztec-labs/foundation/branded-types';
2
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
3
+ import { type Logger, createLogger } from '@aztec-labs/foundation/log';
4
+ import { KeyStore } from '@aztec-labs/key-store';
5
+ import type { AztecAsyncKVStore } from '@aztec-labs/kv-store';
6
+ import { openEphemeralStore } from '@aztec-labs/kv-store/lmdb-v2';
7
+ import {
8
+ AddressStore,
9
+ AnchorBlockStore,
10
+ AnchoredContractData,
11
+ CapsuleService,
12
+ CapsuleStore,
13
+ ContractStore,
14
+ FactService,
15
+ FactStore,
16
+ NoteService,
17
+ NoteStore,
18
+ PrivateEventStore,
19
+ RecipientTaggingStore,
20
+ SenderTaggingStore,
21
+ StagedWriteCoordinator,
22
+ TaggingSecretSourcesStore,
23
+ composeHooks,
24
+ runOperation,
25
+ } from '@aztec-labs/pxe/server';
26
+ import type { ChangeSetId, OperationContributor } from '@aztec-labs/pxe/server';
27
+ import {
28
+ ExecutionNoteCache,
29
+ ExecutionTaggingIndexCache,
30
+ HashedValuesCache,
31
+ type IMiscOracle,
32
+ type IPrivateExecutionOracle,
33
+ type IUtilityExecutionOracle,
34
+ LEGACY_ORACLE_REGISTRY,
35
+ Option,
36
+ TransientArrayService,
37
+ UtilityExecutionOracle,
38
+ buildACIRCallback,
39
+ } from '@aztec-labs/pxe/simulator';
40
+ import {
41
+ ExecutionError,
42
+ WASMSimulator,
43
+ createSimulationError,
44
+ extractCallStack,
45
+ resolveAssertionMessageFromError,
46
+ toACVMWitness,
47
+ } from '@aztec-labs/simulator/client';
48
+ import { STANDARD_AUTH_REGISTRY_ADDRESS } from '@aztec-labs/standard-contracts/auth-registry/constants';
49
+ import { EventSelector, FunctionCall, FunctionSelector, FunctionType } from '@aztec-labs/stdlib/abi';
50
+ import type { AuthWitness } from '@aztec-labs/stdlib/auth-witness';
51
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
52
+ import { GasSettings } from '@aztec-labs/stdlib/gas';
53
+ import { computeProtocolNullifier } from '@aztec-labs/stdlib/hash';
54
+ import { PrivateContextInputs } from '@aztec-labs/stdlib/kernel';
55
+ import { makeGlobalVariables } from '@aztec-labs/stdlib/testing';
56
+ import { CallContext, GlobalVariables, OFFCHAIN_MESSAGE_IDENTIFIER, TxContext } from '@aztec-labs/stdlib/tx';
57
+ import { z } from 'zod';
58
+
59
+ import { DEFAULT_ADDRESS } from './constants.js';
60
+ import type { IAvmExecutionOracle, ITxeExecutionOracle } from './oracle/interfaces.js';
61
+ import type { GasSettingsData } from './oracle/noir-structs/gas_settings_data.js';
62
+ import {
63
+ type TXETaggingSecretStrategies,
64
+ makeResolveTaggingSecretStrategyHook,
65
+ } from './oracle/tagging_secret_strategy.js';
66
+ import { TXEOraclePublicContext } from './oracle/txe_oracle_public_context.js';
67
+ import { callTxeLegacyHandler } from './oracle/txe_oracle_registry.js';
68
+ import { TXEOracleTopLevelContext, authorizeAllUtilityCallsHook } from './oracle/txe_oracle_top_level_context.js';
69
+ import { TXE_ORACLE_VERSION_MAJOR, TXE_ORACLE_VERSION_MINOR } from './oracle/txe_oracle_version.js';
70
+ import { TXEPrivateExecutionOracle } from './oracle/txe_private_execution_oracle.js';
71
+ import { RPCTranslator, UnavailableOracleError } from './rpc_translator.js';
72
+ import { TXEArchiver } from './state_machine/archiver.js';
73
+ import { TXEStateMachine } from './state_machine/index.js';
74
+ import { getSingleTxBlockRequestHash, insertTxEffectIntoWorldTrees, makeTXEBlock } from './utils/block_creation.js';
75
+ import type { ForeignCallArgs, ForeignCallResult } from './utils/encoding.js';
76
+ import { makeTxEffect } from './utils/tx_effect_creation.js';
77
+ import { TXEAccountStore } from './utils/txe_account_store.js';
78
+ import type { TXEArtifactResolver } from './utils/txe_artifact_resolver.js';
79
+
80
+ /**
81
+ * A TXE Session can be in one of four states, which change as the test progresses and different oracles are called.
82
+ * The current state determines which oracles are available. Some states also have data associated with them.
83
+ */
84
+ type SessionState =
85
+ /**
86
+ * The top-level state is the default state, before any other state has been entered. This is where contracts can be
87
+ * deployed, accounts created, blocks mined, etc.
88
+ */
89
+ | {
90
+ name: 'TOP_LEVEL';
91
+ }
92
+ /**
93
+ * The private state is entered via the `private_context` function. In this state the PXE oracles that `#[external("private")]`
94
+ * functions use are available, such as those related to note retrieval, notification of side-effects, capsule access,
95
+ * etc. */
96
+ | {
97
+ name: 'PRIVATE';
98
+ nextBlockGlobalVariables: GlobalVariables;
99
+ noteCache: ExecutionNoteCache;
100
+ taggingIndexCache: ExecutionTaggingIndexCache;
101
+ }
102
+ /**
103
+ * The public state is entered via the `public_context` function. In this state the AVM opcodes that `#[external("public")]`
104
+ * functions execute are resolved as oracles by TXE, since Noir tests are not transpiled. */
105
+ | {
106
+ name: 'PUBLIC';
107
+ }
108
+ /**
109
+ * The utility state is entered via the `utility_context` function. In this state the PXE oracles that `#[external("utility")]`
110
+ * functions use are available, such as those related to (unconstrained) note retrieval, capsule access, public
111
+ * storage reads, etc.
112
+ */
113
+ | {
114
+ name: 'UTILITY';
115
+ };
116
+
117
+ type MethodNames<T> = {
118
+ [K in keyof T]: T[K] extends (...args: any[]) => any ? K : never;
119
+ }[keyof T];
120
+
121
+ /**
122
+ * The name of an oracle function that TXE supports, which are a combination of PXE oracles, non-transpiled AVM opcodes,
123
+ * and custom TXE oracles.
124
+ */
125
+ export type TXEOracleFunctionName = Exclude<
126
+ MethodNames<RPCTranslator>,
127
+ 'constructor' | 'handlerAsMisc' | 'handlerAsUtility' | 'handlerAsPrivate' | 'handlerAsAvm' | 'handlerAsTxe'
128
+ >;
129
+
130
+ export interface TXESessionStateHandler {
131
+ /** Records the TXE oracle version reported by the Noir test code for diagnostics. */
132
+ setTxeOracleVersion(major: number, minor: number): void;
133
+
134
+ enterTopLevelState(): Promise<void>;
135
+ enterPublicState(contractAddress: Option<AztecAddress>): Promise<void>;
136
+ enterPrivateState(
137
+ contractAddress: Option<AztecAddress>,
138
+ anchorBlockNumber: Option<BlockNumber>,
139
+ gasSettings: GasSettingsData,
140
+ ): Promise<PrivateContextInputs>;
141
+ enterUtilityState(contractAddress: Option<AztecAddress>): Promise<void>;
142
+
143
+ /**
144
+ * Executes a top-level private call: runs the private function, drains its offchain effects into the session buffer,
145
+ * commits the change set, and (for non-static calls) tags the result with the mined tx hash.
146
+ */
147
+ executePrivateCall(
148
+ from: Option<AztecAddress>,
149
+ targetContractAddress: AztecAddress,
150
+ functionSelector: FunctionSelector,
151
+ args: Fr[],
152
+ argsHash: Fr,
153
+ isStaticCall: boolean,
154
+ additionalScopes: AztecAddress[],
155
+ authorizedUtilityCallTargets: AztecAddress[],
156
+ gasSettings: GasSettingsData,
157
+ ): Promise<Fr[]>;
158
+
159
+ /** Executes a top-level utility function and commits the change set. */
160
+ executeUtilityFunction(
161
+ from: Option<AztecAddress>,
162
+ targetContractAddress: AztecAddress,
163
+ functionSelector: FunctionSelector,
164
+ args: Fr[],
165
+ authorizedUtilityCallTargets: AztecAddress[],
166
+ ): Promise<Fr[]>;
167
+
168
+ /**
169
+ * Executes a top-level public call, commits the change set, and (for non-static calls) tags the result with the mined
170
+ * tx hash.
171
+ */
172
+ executePublicCall(
173
+ from: Option<AztecAddress>,
174
+ targetContractAddress: AztecAddress,
175
+ calldata: Fr[],
176
+ isStaticCall: boolean,
177
+ gasSettings: GasSettingsData,
178
+ ): Promise<Fr[]>;
179
+
180
+ /** Syncs the target contract and returns the private events it emitted matching the given selector and scope. */
181
+ getPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress): Promise<Fr[][]>;
182
+
183
+ /**
184
+ * Captures a raw offchain effect payload for consumption from test environment. Called by the `emit_offchain_effect`
185
+ * oracle handler whenever a contract function emits an offchain message, at any call depth.
186
+ */
187
+ recordOffchainEffect(data: Fr[]): void;
188
+
189
+ /**
190
+ * Returns the raw offchain effect payloads emitted by the last top-level call. Each payload follows the protocol
191
+ * convention documented on `OFFCHAIN_MESSAGE_IDENTIFIER`, i.e. `[identifier, recipient, ...ciphertext]`. Decoding into
192
+ * `OffchainMessage` structs happens on the Noir side of the test helper. Marks the buffer as queried so the
193
+ * unqueried-messages warning doesn't fire on the next reset.
194
+ */
195
+ getLastCallOffchainEffects(): Fr[][];
196
+
197
+ /**
198
+ * Returns the context of the last top-level call: its tx hash (absent if the call was tx-less) and the anchor
199
+ * block timestamp captured at the start of the call. Does *not* mark the buffer as queried — context reads are
200
+ * metadata, not effect consumption.
201
+ */
202
+ getLastCallContext(): { txHash: Option<Fr>; anchorBlockTimestamp: bigint };
203
+ }
204
+
205
+ /**
206
+ * Session state tracking the most recently completed top-level call: the offchain effect buffer it produced, and the
207
+ * call's context (tx hash + anchor block timestamp). The context is refreshed on every top-level call, independently
208
+ * of whether the call produced offchain effects.
209
+ */
210
+ interface LastCallState {
211
+ /**
212
+ * Raw offchain effect payloads emitted by the currently-executing (or most recently completed) top-level call. Wiped
213
+ * at the start of every top-level entry point, appended to on every `emit_offchain_effect` oracle invocation.
214
+ */
215
+ offchainEffects: Fr[][];
216
+ /**
217
+ * Tracks whether the test has queried `effects` since the last reset. If a new top-level call clobbers the buffer
218
+ * without it being queried first, any accumulated messages are lost and we emit a warning so tests don't silently
219
+ * drop delivery.
220
+ */
221
+ queried: boolean;
222
+ /**
223
+ * Tx hash of the most recently completed top-level call, absent if the call was tx-less (context setters, utility
224
+ * execution). Populated by call executor handlers after execution completes.
225
+ */
226
+ txHash: Option<Fr>;
227
+ /**
228
+ * Anchor block timestamp of the most recently completed top-level call, captured from the anchor block header that
229
+ * was active when the call started. Populated by call executor handlers after execution completes.
230
+ */
231
+ anchorBlockTimestamp: bigint;
232
+ }
233
+
234
+ function emptyLastCallState(): LastCallState {
235
+ return { offchainEffects: [], queried: false, txHash: Option.none(), anchorBlockTimestamp: 0n };
236
+ }
237
+
238
+ /**
239
+ * A `TXESession` corresponds to a Noir `#[test]` function, and handles all of its oracle calls, stores test-specific
240
+ * state, etc., independent of all other tests running in parallel.
241
+ */
242
+ export class TXESession implements TXESessionStateHandler {
243
+ private state: SessionState = { name: 'TOP_LEVEL' };
244
+ private authwits: Map<string, AuthWitness> = new Map();
245
+ private taggingSecretStrategies: TXETaggingSecretStrategies = new Map();
246
+ private authorizeAllUtilityCallTargets = false;
247
+ private lastCallInfo: LastCallState = emptyLastCallState();
248
+ private txeOracleVersion: { major: number; minor: number } | undefined;
249
+
250
+ private disposed = false;
251
+
252
+ private logger: Logger;
253
+ private sessionStore: AztecAsyncKVStore;
254
+ private stateMachine: TXEStateMachine;
255
+ private oracleHandler:
256
+ | IMiscOracle
257
+ | IUtilityExecutionOracle
258
+ | IPrivateExecutionOracle
259
+ | IAvmExecutionOracle
260
+ | ITxeExecutionOracle;
261
+ private contractStore: ContractStore;
262
+ private noteStore: NoteStore;
263
+ private keyStore: KeyStore;
264
+ private addressStore: AddressStore;
265
+ private accountStore: TXEAccountStore;
266
+ private senderTaggingStore: SenderTaggingStore;
267
+ private recipientTaggingStore: RecipientTaggingStore;
268
+ private taggingSecretSourcesStore: TaggingSecretSourcesStore;
269
+ private capsuleStore: CapsuleStore;
270
+ private factStore: FactStore;
271
+ private privateEventStore: PrivateEventStore;
272
+ private readonly stagedWriteCoordinator: StagedWriteCoordinator;
273
+ private readonly operationContributors: OperationContributor[];
274
+ private currentChangeSetId: ChangeSetId;
275
+ private chainId: Fr;
276
+ private version: Fr;
277
+ private nextBlockTimestamp: bigint;
278
+ private readonly artifactResolver: TXEArtifactResolver;
279
+ private readonly rootPath: string;
280
+ private readonly packageName: string;
281
+
282
+ constructor(args: TXESessionCtorArgs) {
283
+ this.logger = args.logger;
284
+ this.sessionStore = args.sessionStore;
285
+ this.stateMachine = args.stateMachine;
286
+ this.oracleHandler = args.oracleHandler;
287
+ this.contractStore = args.contractStore;
288
+ this.noteStore = args.noteStore;
289
+ this.keyStore = args.keyStore;
290
+ this.addressStore = args.addressStore;
291
+ this.accountStore = args.accountStore;
292
+ this.senderTaggingStore = args.senderTaggingStore;
293
+ this.recipientTaggingStore = args.recipientTaggingStore;
294
+ this.taggingSecretSourcesStore = args.taggingSecretSourcesStore;
295
+ this.capsuleStore = args.capsuleStore;
296
+ this.factStore = args.factStore;
297
+ this.privateEventStore = args.privateEventStore;
298
+ this.stagedWriteCoordinator = args.stagedWriteCoordinator;
299
+ this.operationContributors = args.operationContributors;
300
+ this.currentChangeSetId = args.currentChangeSetId;
301
+ this.chainId = args.chainId;
302
+ this.version = args.version;
303
+ this.nextBlockTimestamp = args.nextBlockTimestamp;
304
+ this.artifactResolver = args.artifactResolver;
305
+ this.rootPath = args.rootPath;
306
+ this.packageName = args.packageName;
307
+ }
308
+
309
+ /**
310
+ * Tears down the per-session AVM simulator (process pool + CDB server), the `NativeWorldStateService`,
311
+ * and the `txe-session` LMDB. Called via IPC when the dispatcher detects the end of a test. Idempotent.
312
+ */
313
+ async dispose(): Promise<void> {
314
+ if (this.disposed) {
315
+ return;
316
+ }
317
+ this.disposed = true;
318
+ // Dispose the AVM pool before the world state: it kills the bb-avm-sim processes so they release their
319
+ // connection to the WSDB server, letting it shut down cleanly. Skipping this leaks a bb-avm-sim process
320
+ // (and keeps its WSDB alive) per session.
321
+ try {
322
+ await this.stateMachine.synchronizer.closeIpc();
323
+ } catch (err) {
324
+ this.logger.warn(`Error closing AVM simulator during session dispose`, err);
325
+ }
326
+ try {
327
+ await this.stateMachine.synchronizer.nativeWorldStateService.close();
328
+ } catch (err) {
329
+ this.logger.warn(`Error closing native world state during session dispose`, err);
330
+ }
331
+ try {
332
+ await this.sessionStore.close();
333
+ } catch (err) {
334
+ this.logger.warn(`Error closing session LMDB during dispose`, err);
335
+ }
336
+ }
337
+
338
+ static async init(
339
+ contractStore: ContractStore,
340
+ artifactResolver: TXEArtifactResolver,
341
+ rootPath: string,
342
+ packageName: string,
343
+ ) {
344
+ // Size LMDB's reader slots to the libuv pool (capped to 2 in bin/index.ts via
345
+ // HARDWARE_CONCURRENCY): each native LMDB read needs a libuv worker thread to run, so any
346
+ // slot beyond the pool size would sit idle while still consuming a semaphore + reader-table
347
+ // entry per session.
348
+ const store = await openEphemeralStore('txe-session', undefined, 2);
349
+
350
+ const addressStore = new AddressStore(store);
351
+ const privateEventStore = new PrivateEventStore(store);
352
+ const noteStore = new NoteStore(store);
353
+ const senderTaggingStore = new SenderTaggingStore(store);
354
+ const recipientTaggingStore = new RecipientTaggingStore(store);
355
+ const taggingSecretSourcesStore = new TaggingSecretSourcesStore(store);
356
+ const capsuleStore = new CapsuleStore(store);
357
+ const factStore = new FactStore(store);
358
+ const keyStore = new KeyStore(store);
359
+ const accountStore = new TXEAccountStore(store);
360
+
361
+ const archiver = new TXEArchiver(store);
362
+ const anchorBlockStore = new AnchorBlockStore(store);
363
+ const stateMachine = await TXEStateMachine.create(archiver, anchorBlockStore, contractStore, noteStore);
364
+
365
+ const stagedWriteCoordinator = new StagedWriteCoordinator({
366
+ kvStore: store,
367
+ stagedStores: [capsuleStore, factStore, senderTaggingStore, recipientTaggingStore, privateEventStore, noteStore],
368
+ });
369
+
370
+ const nextBlockTimestamp = BigInt(Math.floor(new Date().getTime() / 1000));
371
+ const version = new Fr(await stateMachine.node.getVersion());
372
+ const chainId = new Fr(await stateMachine.node.getChainId());
373
+
374
+ const logger = createLogger('txe:session');
375
+
376
+ const initialChangeSetId = stagedWriteCoordinator.begin();
377
+
378
+ const topLevelOracleHandler = new TXEOracleTopLevelContext({
379
+ stateMachine,
380
+ contractStore,
381
+ noteStore,
382
+ keyStore,
383
+ addressStore,
384
+ accountStore,
385
+ senderTaggingStore,
386
+ recipientTaggingStore,
387
+ taggingSecretSourcesStore,
388
+ capsuleStore,
389
+ factStore,
390
+ privateEventStore,
391
+ nextBlockTimestamp,
392
+ chainId,
393
+ version,
394
+ authwits: new Map(),
395
+ taggingSecretStrategies: new Map(),
396
+ authorizeAllUtilityCallTargets: false,
397
+ artifactResolver,
398
+ rootPath,
399
+ packageName,
400
+ });
401
+
402
+ await topLevelOracleHandler.mineDeploymentNullifiers([STANDARD_AUTH_REGISTRY_ADDRESS]);
403
+
404
+ return new TXESession({
405
+ logger,
406
+ sessionStore: store,
407
+ stateMachine,
408
+ oracleHandler: topLevelOracleHandler,
409
+ contractStore,
410
+ noteStore,
411
+ keyStore,
412
+ addressStore,
413
+ accountStore,
414
+ senderTaggingStore,
415
+ recipientTaggingStore,
416
+ taggingSecretSourcesStore,
417
+ capsuleStore,
418
+ factStore,
419
+ privateEventStore,
420
+ stagedWriteCoordinator,
421
+ operationContributors: [stateMachine.contractSyncService],
422
+ currentChangeSetId: initialChangeSetId,
423
+ chainId,
424
+ version,
425
+ nextBlockTimestamp,
426
+ artifactResolver,
427
+ rootPath,
428
+ packageName,
429
+ });
430
+ }
431
+
432
+ /**
433
+ * Processes an oracle function invoked by the Noir test associated to this session.
434
+ * @param functionName The name of the oracle.
435
+ * @param inputs The inputs of the oracle.
436
+ * @returns The oracle return values.
437
+ */
438
+ processFunction(functionName: TXEOracleFunctionName, inputs: ForeignCallArgs): Promise<ForeignCallResult> {
439
+ try {
440
+ // Oracles retired into the PXE legacy registry have no translator method; dispatch them through the same
441
+ // buildACIRCallback legacy path that contract execution uses, keeping TXE's two oracle paths in sync.
442
+ // Use an own-property check: `in` would match inherited `Object.prototype` keys (e.g. `constructor`), routing
443
+ // them into the legacy path instead of letting them fall through to the unknown-oracle error.
444
+ if (Object.hasOwn(LEGACY_ORACLE_REGISTRY, functionName)) {
445
+ return callTxeLegacyHandler(
446
+ functionName,
447
+ inputs,
448
+ this.oracleHandler as Parameters<typeof buildACIRCallback>[0],
449
+ );
450
+ }
451
+
452
+ const translator = new RPCTranslator(this, this.oracleHandler) as any;
453
+ // We perform a runtime validation to check that the function name corresponds to a real oracle handler.
454
+ const validatedFunctionName = z
455
+ .string()
456
+ .refine(fn => typeof translator[fn] === 'function' && !fn.startsWith('handlerAs') && fn !== 'constructor')
457
+ .parse(functionName) as TXEOracleFunctionName;
458
+
459
+ return translator[validatedFunctionName](...inputs);
460
+ } catch (error) {
461
+ if (error instanceof z.ZodError) {
462
+ let versionHint: string;
463
+ if (!this.txeOracleVersion) {
464
+ versionHint =
465
+ ' The test appears to use an older version of Aztec.nr that does not' +
466
+ ' support test environment oracle versioning. Update Aztec.nr to a compatible version.' +
467
+ ' See https://docs.aztec.network/errors/12';
468
+ } else if (this.txeOracleVersion.minor > TXE_ORACLE_VERSION_MINOR) {
469
+ versionHint =
470
+ ` The test uses Aztec.nr test oracle version` +
471
+ ` ${this.txeOracleVersion.major}.${this.txeOracleVersion.minor}, but this test environment` +
472
+ ` only supports up to ${TXE_ORACLE_VERSION_MAJOR}.${TXE_ORACLE_VERSION_MINOR}.` +
473
+ ` Upgrade the Aztec CLI to a compatible version.` +
474
+ ` See https://docs.aztec.network/errors/12`;
475
+ } else {
476
+ versionHint =
477
+ ` The test's oracle version (${this.txeOracleVersion.major}.${this.txeOracleVersion.minor})` +
478
+ ` is compatible with this test environment` +
479
+ ` (${TXE_ORACLE_VERSION_MAJOR}.${TXE_ORACLE_VERSION_MINOR}), so this oracle should be` +
480
+ ` available. This is an unexpected error, please report it.` +
481
+ ` See https://docs.aztec.network/errors/13`;
482
+ }
483
+ throw new Error(`Unknown oracle '${functionName}'.${versionHint}`);
484
+ } else if (error instanceof Error) {
485
+ throw new Error(
486
+ `Execution error while processing function ${functionName} in state ${this.state.name}: ${error.message}`,
487
+ );
488
+ } else {
489
+ throw new Error(
490
+ `Unknown execution error while processing function ${functionName} in state ${this.state.name}`,
491
+ );
492
+ }
493
+ }
494
+ }
495
+
496
+ /** Ends the current operation (committing its change set, or discarding it on failure) and begins a new one. */
497
+ private async cycleOperation(): Promise<string> {
498
+ const operationArgs = {
499
+ stagedWriteCoordinator: this.stagedWriteCoordinator,
500
+ contributors: this.operationContributors,
501
+ changeSetId: this.currentChangeSetId,
502
+ log: this.logger,
503
+ };
504
+ try {
505
+ // The operation's work already happened through the session's oracles, so there is nothing left to run.
506
+ await runOperation(operationArgs, () => Promise.resolve());
507
+ } finally {
508
+ this.currentChangeSetId = this.stagedWriteCoordinator.begin();
509
+ }
510
+ return this.currentChangeSetId;
511
+ }
512
+
513
+ private resetLastCall(): void {
514
+ const notQueriedMessageCount = this.lastCallInfo.queried
515
+ ? 0
516
+ : this.lastCallInfo.offchainEffects.filter(payload => payload[0]?.equals(OFFCHAIN_MESSAGE_IDENTIFIER)).length;
517
+ if (notQueriedMessageCount > 0) {
518
+ this.logger.warn(
519
+ `Dropping ${notQueriedMessageCount} unqueried offchain message(s) from the previous top-level call. ` +
520
+ `To deliver them, call \`env.offchain_messages()\` and forward the result to the recipient contract's ` +
521
+ `\`offchain_receive\` utility before issuing another top-level call. To intentionally discard, assign ` +
522
+ `to \`let _ = env.offchain_messages()\` to silence this warning.`,
523
+ );
524
+ }
525
+ this.lastCallInfo = emptyLastCallState();
526
+ }
527
+
528
+ recordOffchainEffect(data: Fr[]): void {
529
+ this.lastCallInfo.offchainEffects.push(data);
530
+ }
531
+
532
+ private setLastCallContext(txHash: Option<Fr>, anchorBlockTimestamp: bigint): void {
533
+ this.lastCallInfo.txHash = txHash;
534
+ this.lastCallInfo.anchorBlockTimestamp = anchorBlockTimestamp;
535
+ }
536
+
537
+ private async withTopLevelCallTracking<T>(work: () => Promise<{ result: T; txHash?: Fr }>): Promise<T> {
538
+ this.resetLastCall();
539
+ // Capture the anchor *before* `work` runs: private/public executor calls mine a new block as a
540
+ // side effect, and that block's timestamp should not be attributed to this call's anchor.
541
+ const anchorBlockTimestamp = (await this.stateMachine.node.getBlockData('latest'))!.header.globalVariables
542
+ .timestamp;
543
+ const { result, txHash } = await work();
544
+ this.setLastCallContext(txHash ? Option.some(txHash) : Option.none(), anchorBlockTimestamp);
545
+ return result;
546
+ }
547
+
548
+ getLastCallOffchainEffects(): Fr[][] {
549
+ this.lastCallInfo.queried = true;
550
+ const effects = this.lastCallInfo.offchainEffects;
551
+
552
+ return effects;
553
+ }
554
+
555
+ getLastCallContext(): { txHash: Option<Fr>; anchorBlockTimestamp: bigint } {
556
+ const { txHash, anchorBlockTimestamp } = this.lastCallInfo;
557
+ return { txHash, anchorBlockTimestamp };
558
+ }
559
+
560
+ async executePrivateCall(
561
+ from: Option<AztecAddress>,
562
+ targetContractAddress: AztecAddress,
563
+ functionSelector: FunctionSelector,
564
+ args: Fr[],
565
+ argsHash: Fr,
566
+ isStaticCall: boolean,
567
+ additionalScopes: AztecAddress[],
568
+ authorizedUtilityCallTargets: AztecAddress[],
569
+ gasSettings: GasSettingsData,
570
+ ): Promise<Fr[]> {
571
+ const handler = this.handlerAsTxe();
572
+ return await this.withTopLevelCallTracking(async () => {
573
+ const { returnValues, offchainEffects } = await handler.privateCallNewFlow(
574
+ from?.value,
575
+ targetContractAddress,
576
+ functionSelector,
577
+ args,
578
+ argsHash,
579
+ isStaticCall,
580
+ additionalScopes,
581
+ this.currentChangeSetId,
582
+ authorizedUtilityCallTargets,
583
+ GasSettings.from(gasSettings),
584
+ );
585
+
586
+ // Private execution collects offchain effects inside PXE's PrivateExecutionOracle rather than round-tripping
587
+ // them through `aztec_utl_emitOffchainEffect`, so the session buffer is empty at this point. Drain the effects
588
+ // from the execution tree into the session buffer so the next `env.offchain_messages()` call in the test sees
589
+ // them.
590
+ for (const data of offchainEffects) {
591
+ this.recordOffchainEffect(data);
592
+ }
593
+
594
+ await this.cycleOperation();
595
+
596
+ if (isStaticCall) {
597
+ // Static calls revert their checkpoint and mine no block, so there is no tx hash to tag offchain effects
598
+ // with. Querying `getLastTxEffects()` here would return an unrelated predecessor tx.
599
+ return { result: returnValues };
600
+ }
601
+ const { txHash } = await handler.getLastTxEffects();
602
+ return { result: returnValues, txHash: txHash.hash };
603
+ });
604
+ }
605
+
606
+ async executeUtilityFunction(
607
+ from: Option<AztecAddress>,
608
+ targetContractAddress: AztecAddress,
609
+ functionSelector: FunctionSelector,
610
+ args: Fr[],
611
+ authorizedUtilityCallTargets: AztecAddress[],
612
+ ): Promise<Fr[]> {
613
+ const handler = this.handlerAsTxe();
614
+ return await this.withTopLevelCallTracking(async () => {
615
+ const returnValues = await handler.executeUtilityFunction(
616
+ from?.value,
617
+ targetContractAddress,
618
+ functionSelector,
619
+ args,
620
+ this.currentChangeSetId,
621
+ authorizedUtilityCallTargets,
622
+ );
623
+
624
+ await this.cycleOperation();
625
+
626
+ return { result: returnValues };
627
+ });
628
+ }
629
+
630
+ async executePublicCall(
631
+ from: Option<AztecAddress>,
632
+ targetContractAddress: AztecAddress,
633
+ calldata: Fr[],
634
+ isStaticCall: boolean,
635
+ gasSettings: GasSettingsData,
636
+ ): Promise<Fr[]> {
637
+ const handler = this.handlerAsTxe();
638
+ return await this.withTopLevelCallTracking(async () => {
639
+ const returnValues = await handler.publicCallNewFlow(
640
+ from?.value,
641
+ targetContractAddress,
642
+ calldata,
643
+ isStaticCall,
644
+ GasSettings.from(gasSettings),
645
+ );
646
+
647
+ await this.cycleOperation();
648
+
649
+ if (isStaticCall) {
650
+ // See the equivalent branch in `executePrivateCall`.
651
+ return { result: returnValues };
652
+ }
653
+ const { txHash } = await handler.getLastTxEffects();
654
+ return { result: returnValues, txHash: txHash.hash };
655
+ });
656
+ }
657
+
658
+ async getPrivateEvents(selector: EventSelector, contractAddress: AztecAddress, scope: AztecAddress): Promise<Fr[][]> {
659
+ const handler = this.handlerAsTxe();
660
+ await handler.syncContractNonOracleMethod(contractAddress, scope, this.currentChangeSetId);
661
+ // Cycle the change set to commit the stores after the contract sync.
662
+ await this.cycleOperation();
663
+ return handler.getPrivateEvents(selector, contractAddress, scope);
664
+ }
665
+
666
+ private handlerAsTxe(): ITxeExecutionOracle {
667
+ if (!('isTxe' in this.oracleHandler)) {
668
+ throw new UnavailableOracleError('Txe');
669
+ }
670
+ return this.oracleHandler;
671
+ }
672
+
673
+ setTxeOracleVersion(major: number, minor: number): void {
674
+ if (major !== TXE_ORACLE_VERSION_MAJOR) {
675
+ const hint =
676
+ major > TXE_ORACLE_VERSION_MAJOR
677
+ ? 'The test was compiled with a newer version of Aztec.nr than your test environment supports. Upgrade your test environment to a compatible version.'
678
+ : 'The test was compiled with an older version of Aztec.nr than your test environment supports. Recompile the test with a compatible version of Aztec.nr.';
679
+ throw new Error(
680
+ `Incompatible test environment version: ${hint} See https://docs.aztec.network/errors/12 (expected test oracle major version ${TXE_ORACLE_VERSION_MAJOR}, got ${major})`,
681
+ );
682
+ }
683
+
684
+ this.txeOracleVersion = { major, minor };
685
+ this.logger.debug(`Test compiled with test oracle version ${major}.${minor}`);
686
+ }
687
+
688
+ async enterTopLevelState() {
689
+ switch (this.state.name) {
690
+ case 'PRIVATE': {
691
+ await this.exitPrivateState();
692
+ break;
693
+ }
694
+ case 'PUBLIC': {
695
+ await this.exitPublicState();
696
+ break;
697
+ }
698
+ case 'UTILITY': {
699
+ this.exitUtilityContext();
700
+ break;
701
+ }
702
+ case 'TOP_LEVEL': {
703
+ throw new Error(`Expected to be in state other than TOP_LEVEL`);
704
+ }
705
+ default: {
706
+ this.state satisfies never;
707
+ }
708
+ }
709
+
710
+ // Commit all staged stores from the change set that was just completed, then begin a new change set
711
+ await this.cycleOperation();
712
+
713
+ this.oracleHandler = new TXEOracleTopLevelContext({
714
+ stateMachine: this.stateMachine,
715
+ contractStore: this.contractStore,
716
+ noteStore: this.noteStore,
717
+ keyStore: this.keyStore,
718
+ addressStore: this.addressStore,
719
+ accountStore: this.accountStore,
720
+ senderTaggingStore: this.senderTaggingStore,
721
+ recipientTaggingStore: this.recipientTaggingStore,
722
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
723
+ capsuleStore: this.capsuleStore,
724
+ factStore: this.factStore,
725
+ privateEventStore: this.privateEventStore,
726
+ nextBlockTimestamp: this.nextBlockTimestamp,
727
+ chainId: this.chainId,
728
+ version: this.version,
729
+ authwits: this.authwits,
730
+ taggingSecretStrategies: this.taggingSecretStrategies,
731
+ authorizeAllUtilityCallTargets: this.authorizeAllUtilityCallTargets,
732
+ artifactResolver: this.artifactResolver,
733
+ rootPath: this.rootPath,
734
+ packageName: this.packageName,
735
+ });
736
+
737
+ this.state = { name: 'TOP_LEVEL' };
738
+ this.logger.debug(`Entered state ${this.state.name}`);
739
+ }
740
+
741
+ async enterPrivateState(
742
+ contractAddressOpt: Option<AztecAddress>,
743
+ anchorBlockNumberOpt: Option<BlockNumber>,
744
+ gasSettings: GasSettingsData,
745
+ ): Promise<PrivateContextInputs> {
746
+ const contractAddress = contractAddressOpt?.value ?? DEFAULT_ADDRESS;
747
+ const anchorBlockNumber = anchorBlockNumberOpt?.value;
748
+ this.exitTopLevelState();
749
+ this.resetLastCall();
750
+
751
+ // Private execution has two associated block numbers: the anchor block (i.e. the historical block that is used to
752
+ // build the proof), and the *next* block, i.e. the one we'll create once the execution ends, and which will contain
753
+ // a single transaction with the effects of what was done in the test.
754
+ const anchorBlock = await this.stateMachine.node.getBlock(anchorBlockNumber ?? 'latest').then(b => b?.header);
755
+
756
+ await new NoteService(
757
+ this.noteStore,
758
+ this.stateMachine.node,
759
+ anchorBlock!,
760
+ this.currentChangeSetId,
761
+ ).syncNoteNullifiers(contractAddress, await this.keyStore.getAccounts());
762
+ const latestBlock = await this.stateMachine.node.getBlock('latest').then(b => b?.header);
763
+
764
+ const nextBlockGlobalVariables = makeGlobalVariables(undefined, {
765
+ blockNumber: BlockNumber(latestBlock!.globalVariables.blockNumber + 1),
766
+ timestamp: this.nextBlockTimestamp,
767
+ version: this.version,
768
+ chainId: this.chainId,
769
+ });
770
+
771
+ const txRequestHash = getSingleTxBlockRequestHash(nextBlockGlobalVariables.blockNumber);
772
+ const protocolNullifier = await computeProtocolNullifier(txRequestHash);
773
+ const noteCache = new ExecutionNoteCache(protocolNullifier);
774
+ const taggingIndexCache = new ExecutionTaggingIndexCache();
775
+
776
+ const utilityExecutor = this.utilityExecutorForContractSync(anchorBlock);
777
+ const transientArrayService = new TransientArrayService();
778
+ const anchoredContractData = new AnchoredContractData(
779
+ this.contractStore,
780
+ this.stateMachine.contractClassService,
781
+ anchorBlock!,
782
+ );
783
+ this.oracleHandler = new TXEPrivateExecutionOracle({
784
+ argsHash: Fr.ZERO,
785
+ txContext: new TxContext(this.chainId, this.version, GasSettings.from(gasSettings)),
786
+ txRequestSalt: Fr.ZERO,
787
+ callContext: new CallContext(AztecAddress.ZERO, contractAddress, FunctionSelector.empty(), false),
788
+ anchorBlockHeader: anchorBlock!,
789
+ utilityExecutor,
790
+ authWitnesses: [],
791
+ capsules: [],
792
+ executionCache: new HashedValuesCache(),
793
+ noteCache,
794
+ taggingIndexCache,
795
+ anchoredContractData,
796
+ noteStore: this.noteStore,
797
+ keyStore: this.keyStore,
798
+ addressStore: this.addressStore,
799
+ aztecNode: this.stateMachine.node,
800
+ senderTaggingStore: this.senderTaggingStore,
801
+ recipientTaggingStore: this.recipientTaggingStore,
802
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
803
+ capsuleService: new CapsuleService(this.capsuleStore, await this.keyStore.getAccounts()),
804
+ factService: new FactService(this.factStore, await this.keyStore.getAccounts()),
805
+ privateEventStore: this.privateEventStore,
806
+ contractSyncService: this.stateMachine.contractSyncService,
807
+ l2TipsStore: this.stateMachine.l2TipsProvider,
808
+ changeSetId: this.currentChangeSetId,
809
+ scopes: await this.keyStore.getAccounts(),
810
+ txResolver: this.stateMachine.txResolver,
811
+ simulator: new WASMSimulator(),
812
+ hooks: this.buildExecutionHooks(),
813
+ transientArrayService,
814
+ });
815
+
816
+ // We store the note and tagging index caches fed into the PrivateExecutionOracle (along with some other auxiliary
817
+ // data) in order to refer to it later, mimicking the way this object is used by the ContractFunctionSimulator. The
818
+ // difference resides in that the simulator has all information needed in order to run the simulation, while ours
819
+ // will be ongoing as the different oracles will be invoked from the Noir test, until eventually the private
820
+ // execution finishes.
821
+ this.state = { name: 'PRIVATE', nextBlockGlobalVariables, noteCache, taggingIndexCache };
822
+ this.logger.debug(`Entered state ${this.state.name}`);
823
+
824
+ // Record the *resolved* anchor's timestamp — if the caller pinned the anchor to a past block
825
+ // via `anchorBlockNumber`, "latest" would be the wrong anchor for offchain-message semantics.
826
+ this.setLastCallContext(Option.none(), anchorBlock!.globalVariables.timestamp);
827
+
828
+ return (this.oracleHandler as TXEPrivateExecutionOracle).getPrivateContextInputs();
829
+ }
830
+
831
+ async enterPublicState(contractAddressOpt: Option<AztecAddress>) {
832
+ const contractAddress = contractAddressOpt?.value ?? DEFAULT_ADDRESS;
833
+ this.exitTopLevelState();
834
+ this.resetLastCall();
835
+
836
+ // The PublicContext will create a block with a single transaction in it, containing the effects of what was done in
837
+ // the test. The block therefore gets the *next* block number and timestamp.
838
+ const latestHeader = (await this.stateMachine.node.getBlockData('latest'))!.header;
839
+ const globalVariables = makeGlobalVariables(undefined, {
840
+ blockNumber: BlockNumber(latestHeader.globalVariables.blockNumber + 1),
841
+ timestamp: this.nextBlockTimestamp,
842
+ version: this.version,
843
+ chainId: this.chainId,
844
+ });
845
+
846
+ this.oracleHandler = new TXEOraclePublicContext(
847
+ contractAddress,
848
+ await this.stateMachine.synchronizer.nativeWorldStateService.fork(),
849
+ getSingleTxBlockRequestHash(globalVariables.blockNumber),
850
+ globalVariables,
851
+ this.contractStore,
852
+ );
853
+
854
+ this.state = { name: 'PUBLIC' };
855
+ this.logger.debug(`Entered state ${this.state.name}`);
856
+
857
+ // Public state is anchored at the latest block.
858
+ this.setLastCallContext(Option.none(), latestHeader.globalVariables.timestamp);
859
+ }
860
+
861
+ async enterUtilityState(contractAddressOpt: Option<AztecAddress>) {
862
+ const contractAddress = contractAddressOpt?.value ?? DEFAULT_ADDRESS;
863
+ this.exitTopLevelState();
864
+ this.resetLastCall();
865
+
866
+ const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
867
+
868
+ // There is no automatic message discovery and contract-driven syncing process in inlined private or utility
869
+ // contexts, which means that known nullifiers are also not searched for, since it is during the tagging sync that
870
+ // we perform this. We therefore search for known nullifiers now, as otherwise notes that were nullified would not
871
+ // be removed from the database.
872
+ // TODO(#12553): make the synchronizer sync here instead and remove this
873
+ await new NoteService(
874
+ this.noteStore,
875
+ this.stateMachine.node,
876
+ anchorBlockHeader,
877
+ this.currentChangeSetId,
878
+ ).syncNoteNullifiers(contractAddress, await this.keyStore.getAccounts());
879
+
880
+ this.oracleHandler = new UtilityExecutionOracle({
881
+ callContext: CallContext.from({
882
+ msgSender: AztecAddress.NULL_MSG_SENDER,
883
+ contractAddress,
884
+ // No specific function is being executed in this inlined utility context, hence the empty selector.
885
+ functionSelector: FunctionSelector.empty(),
886
+ isStaticCall: true,
887
+ }),
888
+ authWitnesses: [],
889
+ capsules: [],
890
+ anchorBlockHeader,
891
+ anchoredContractData: new AnchoredContractData(
892
+ this.contractStore,
893
+ this.stateMachine.contractClassService,
894
+ anchorBlockHeader,
895
+ ),
896
+ noteStore: this.noteStore,
897
+ keyStore: this.keyStore,
898
+ addressStore: this.addressStore,
899
+ aztecNode: this.stateMachine.node,
900
+ recipientTaggingStore: this.recipientTaggingStore,
901
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
902
+ capsuleService: new CapsuleService(this.capsuleStore, await this.keyStore.getAccounts()),
903
+ factService: new FactService(this.factStore, await this.keyStore.getAccounts()),
904
+ privateEventStore: this.privateEventStore,
905
+ txResolver: this.stateMachine.txResolver,
906
+ contractSyncService: this.stateMachine.contractSyncService,
907
+ l2TipsStore: this.stateMachine.l2TipsProvider,
908
+ changeSetId: this.currentChangeSetId,
909
+ scopes: await this.keyStore.getAccounts(),
910
+ simulator: new WASMSimulator(),
911
+ utilityExecutor: this.utilityExecutorForContractSync(anchorBlockHeader),
912
+ hooks: this.buildExecutionHooks(),
913
+ // Execution-tree root (top-level utility run): own store; nested frames inherit it.
914
+ transientArrayService: new TransientArrayService(),
915
+ });
916
+
917
+ this.state = { name: 'UTILITY' };
918
+ this.logger.debug(`Entered state ${this.state.name}`);
919
+
920
+ // Utility state anchors at whatever the anchor block store is pointing to (tracked as latest).
921
+ this.setLastCallContext(Option.none(), anchorBlockHeader.globalVariables.timestamp);
922
+ }
923
+
924
+ private exitTopLevelState() {
925
+ if (this.state.name != 'TOP_LEVEL') {
926
+ throw new Error(`Expected to be in state 'TOP_LEVEL', but got '${this.state.name}' instead`);
927
+ }
928
+
929
+ // Note that while all public and private contexts do is build a single block that we then process when exiting
930
+ // them, the top level context does most of its work as it goes: it creates empty blocks (via `advanceBlocksBy`
931
+ // and `deploy`), creates blocks with transactions (via `privateCallNewFlow` and `publicCallNewFlow`), adds
932
+ // accounts to PXE (via `addAccount`), etc. This is a slight inconsistency in the working model of this class, but
933
+ // is not too bad. The `close` call below therefore only hands back the session-scoped values that a test
934
+ // sets directly at the top level, outside any contract execution (e.g. via `advanceTimestampBy`,
935
+ // `addAuthWitness`, `setTaggingSecretStrategies`). The oracle handler is discarded on every state transition,
936
+ // so the session must seed these values into the contexts it creates later.
937
+
938
+ // TODO: persisting authwits this way is quite unfortunate: they create a temporary utility context that would
939
+ // otherwise reset them, so we'd not be able to pass more than one per execution. Ideally authwits would be passed
940
+ // alongside a contract call instead of pre-seeded.
941
+ ({
942
+ nextBlockTimestamp: this.nextBlockTimestamp,
943
+ authwits: this.authwits,
944
+ taggingSecretStrategies: this.taggingSecretStrategies,
945
+ authorizeAllUtilityCallTargets: this.authorizeAllUtilityCallTargets,
946
+ } = (this.oracleHandler as TXEOracleTopLevelContext).close());
947
+ }
948
+
949
+ private async exitPrivateState() {
950
+ if (this.state.name != 'PRIVATE') {
951
+ throw new Error(`Expected to be in state 'PRIVATE', but got '${this.state.name}' instead`);
952
+ }
953
+
954
+ this.logger.debug('Exiting Private state, building block with collected side effects', {
955
+ blockNumber: this.state.nextBlockGlobalVariables.blockNumber,
956
+ });
957
+
958
+ // We rely on the note cache to determine the effects of the transaction. This is incomplete as it doesn't private
959
+ // logs (other effects like enqueued public calls don't need to be considered since those are not allowed).
960
+
961
+ const txEffect = await makeTxEffect(this.state.noteCache, this.state.nextBlockGlobalVariables.blockNumber);
962
+
963
+ // We build a block holding just this transaction
964
+ const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
965
+ await insertTxEffectIntoWorldTrees(txEffect, forkedWorldTrees);
966
+
967
+ const block = await makeTXEBlock(forkedWorldTrees, this.state.nextBlockGlobalVariables, [txEffect]);
968
+ await this.stateMachine.handleL2Block(block);
969
+
970
+ await forkedWorldTrees.close();
971
+
972
+ this.logger.debug('Exited PublicContext with built block', {
973
+ blockNumber: block.number,
974
+ txEffects: block.body.txEffects,
975
+ });
976
+ }
977
+
978
+ private async exitPublicState() {
979
+ if (this.state.name != 'PUBLIC') {
980
+ throw new Error(`Expected to be in state 'PUBLIC', but got '${this.state.name}' instead`);
981
+ }
982
+
983
+ const block = await (this.oracleHandler as TXEOraclePublicContext).close();
984
+ await this.stateMachine.handleL2Block(block);
985
+ }
986
+
987
+ private exitUtilityContext() {
988
+ if (this.state.name != 'UTILITY') {
989
+ throw new Error(`Expected to be in state 'UTILITY', but got '${this.state.name}' instead`);
990
+ }
991
+ }
992
+
993
+ private utilityExecutorForContractSync(anchorBlock: any) {
994
+ return async (call: FunctionCall, scopes: AztecAddress[]) => {
995
+ const anchoredContractData = new AnchoredContractData(
996
+ this.contractStore,
997
+ this.stateMachine.contractClassService,
998
+ anchorBlock!,
999
+ );
1000
+ const entryPointArtifact = await anchoredContractData.getFunctionArtifactWithDebugMetadata(
1001
+ call.to,
1002
+ call.selector,
1003
+ );
1004
+ if (!entryPointArtifact) {
1005
+ throw new Error(`Cannot run function ${call.selector} on ${call.to}: the contract is not registered.`);
1006
+ }
1007
+ if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
1008
+ throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
1009
+ }
1010
+
1011
+ try {
1012
+ const simulator = new WASMSimulator();
1013
+ const oracle = new UtilityExecutionOracle({
1014
+ callContext: CallContext.from({
1015
+ msgSender: AztecAddress.NULL_MSG_SENDER,
1016
+ contractAddress: call.to,
1017
+ functionSelector: call.selector,
1018
+ isStaticCall: true,
1019
+ }),
1020
+ authWitnesses: [],
1021
+ capsules: [],
1022
+ anchorBlockHeader: anchorBlock!,
1023
+ anchoredContractData,
1024
+ noteStore: this.noteStore,
1025
+ keyStore: this.keyStore,
1026
+ addressStore: this.addressStore,
1027
+ aztecNode: this.stateMachine.node,
1028
+ recipientTaggingStore: this.recipientTaggingStore,
1029
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
1030
+ capsuleService: new CapsuleService(this.capsuleStore, scopes),
1031
+ factService: new FactService(this.factStore, scopes),
1032
+ privateEventStore: this.privateEventStore,
1033
+ txResolver: this.stateMachine.txResolver,
1034
+ contractSyncService: this.stateMachine.contractSyncService,
1035
+ l2TipsStore: this.stateMachine.l2TipsProvider,
1036
+ changeSetId: this.currentChangeSetId,
1037
+ scopes,
1038
+ simulator,
1039
+ utilityExecutor: this.utilityExecutorForContractSync(anchorBlock),
1040
+ hooks: this.buildExecutionHooks(),
1041
+ // Top-level utility entrypoint: gets a fresh store. Nested frames inherit it via UtilityExecutionOracle.
1042
+ transientArrayService: new TransientArrayService(),
1043
+ });
1044
+ await simulator
1045
+ .executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, buildACIRCallback(oracle))
1046
+ .catch((err: Error) => {
1047
+ err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
1048
+ throw new ExecutionError(
1049
+ err.message,
1050
+ {
1051
+ contractAddress: call.to,
1052
+ functionSelector: call.selector,
1053
+ },
1054
+ extractCallStack(err, entryPointArtifact.debug),
1055
+ { cause: err },
1056
+ );
1057
+ });
1058
+ } catch (err) {
1059
+ throw createSimulationError(err instanceof Error ? err : new Error('Unknown error contract data sync'));
1060
+ }
1061
+ };
1062
+ }
1063
+
1064
+ /** Execution hooks for the oracles this session builds. Every oracle construction site must use this. */
1065
+ private buildExecutionHooks() {
1066
+ return composeHooks({
1067
+ resolveTaggingSecretStrategy: makeResolveTaggingSecretStrategyHook(this.taggingSecretStrategies),
1068
+ authorizeUtilityCall: this.authorizeAllUtilityCallTargets ? authorizeAllUtilityCallsHook : undefined,
1069
+ });
1070
+ }
1071
+ }
1072
+
1073
+ /**
1074
+ * Collaborators and session-scoped values a {@link TXESession} owns. Built by {@link TXESession.init}; passed as a
1075
+ * single object so that call sites name each dependency instead of relying on positional order.
1076
+ */
1077
+ type TXESessionCtorArgs = {
1078
+ logger: Logger;
1079
+ sessionStore: AztecAsyncKVStore;
1080
+ stateMachine: TXEStateMachine;
1081
+ oracleHandler:
1082
+ | IMiscOracle
1083
+ | IUtilityExecutionOracle
1084
+ | IPrivateExecutionOracle
1085
+ | IAvmExecutionOracle
1086
+ | ITxeExecutionOracle;
1087
+ contractStore: ContractStore;
1088
+ noteStore: NoteStore;
1089
+ keyStore: KeyStore;
1090
+ addressStore: AddressStore;
1091
+ accountStore: TXEAccountStore;
1092
+ senderTaggingStore: SenderTaggingStore;
1093
+ recipientTaggingStore: RecipientTaggingStore;
1094
+ taggingSecretSourcesStore: TaggingSecretSourcesStore;
1095
+ capsuleStore: CapsuleStore;
1096
+ factStore: FactStore;
1097
+ privateEventStore: PrivateEventStore;
1098
+ stagedWriteCoordinator: StagedWriteCoordinator;
1099
+ operationContributors: OperationContributor[];
1100
+ currentChangeSetId: ChangeSetId;
1101
+ chainId: Fr;
1102
+ version: Fr;
1103
+ nextBlockTimestamp: bigint;
1104
+ artifactResolver: TXEArtifactResolver;
1105
+ rootPath: string;
1106
+ packageName: string;
1107
+ };