@aztec/txe 0.0.1-commit.fffb133c → 0.0.1-dev

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 (62) hide show
  1. package/dest/index.d.ts +1 -1
  2. package/dest/index.d.ts.map +1 -1
  3. package/dest/index.js +88 -54
  4. package/dest/oracle/interfaces.d.ts +35 -28
  5. package/dest/oracle/interfaces.d.ts.map +1 -1
  6. package/dest/oracle/txe_oracle_public_context.d.ts +13 -13
  7. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  8. package/dest/oracle/txe_oracle_public_context.js +14 -15
  9. package/dest/oracle/txe_oracle_top_level_context.d.ts +33 -23
  10. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
  11. package/dest/oracle/txe_oracle_top_level_context.js +185 -71
  12. package/dest/rpc_translator.d.ts +135 -83
  13. package/dest/rpc_translator.d.ts.map +1 -1
  14. package/dest/rpc_translator.js +540 -178
  15. package/dest/state_machine/archiver.d.ts +3 -3
  16. package/dest/state_machine/archiver.d.ts.map +1 -1
  17. package/dest/state_machine/archiver.js +7 -7
  18. package/dest/state_machine/dummy_p2p_client.d.ts +16 -12
  19. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  20. package/dest/state_machine/dummy_p2p_client.js +28 -16
  21. package/dest/state_machine/index.d.ts +7 -5
  22. package/dest/state_machine/index.d.ts.map +1 -1
  23. package/dest/state_machine/index.js +19 -10
  24. package/dest/state_machine/mock_epoch_cache.d.ts +3 -1
  25. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  26. package/dest/state_machine/mock_epoch_cache.js +4 -0
  27. package/dest/state_machine/synchronizer.d.ts +5 -5
  28. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  29. package/dest/state_machine/synchronizer.js +3 -3
  30. package/dest/txe_oracle_version.d.ts +10 -0
  31. package/dest/txe_oracle_version.d.ts.map +1 -0
  32. package/dest/txe_oracle_version.js +8 -0
  33. package/dest/txe_session.d.ts +67 -8
  34. package/dest/txe_session.d.ts.map +1 -1
  35. package/dest/txe_session.js +175 -32
  36. package/dest/util/encoding.d.ts +43 -41
  37. package/dest/util/encoding.d.ts.map +1 -1
  38. package/dest/util/txe_public_contract_data_source.d.ts +2 -3
  39. package/dest/util/txe_public_contract_data_source.d.ts.map +1 -1
  40. package/dest/util/txe_public_contract_data_source.js +5 -22
  41. package/dest/utils/block_creation.d.ts +1 -1
  42. package/dest/utils/block_creation.d.ts.map +1 -1
  43. package/dest/utils/block_creation.js +3 -1
  44. package/package.json +15 -15
  45. package/src/index.ts +89 -52
  46. package/src/oracle/interfaces.ts +43 -34
  47. package/src/oracle/txe_oracle_public_context.ts +14 -16
  48. package/src/oracle/txe_oracle_top_level_context.ts +231 -132
  49. package/src/rpc_translator.ts +673 -208
  50. package/src/state_machine/archiver.ts +7 -5
  51. package/src/state_machine/dummy_p2p_client.ts +40 -22
  52. package/src/state_machine/index.ts +30 -10
  53. package/src/state_machine/mock_epoch_cache.ts +5 -0
  54. package/src/state_machine/synchronizer.ts +4 -4
  55. package/src/txe_oracle_version.ts +9 -0
  56. package/src/txe_session.ts +270 -93
  57. package/src/util/txe_public_contract_data_source.ts +10 -36
  58. package/src/utils/block_creation.ts +3 -1
  59. package/dest/util/txe_contract_store.d.ts +0 -12
  60. package/dest/util/txe_contract_store.d.ts.map +0 -1
  61. package/dest/util/txe_contract_store.js +0 -22
  62. package/src/util/txe_contract_store.ts +0 -36
@@ -1,10 +1,10 @@
1
- import { CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS, DEFAULT_DA_GAS_LIMIT, DEFAULT_L2_GAS_LIMIT, DEFAULT_TEARDOWN_DA_GAS_LIMIT, DEFAULT_TEARDOWN_L2_GAS_LIMIT, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/constants';
1
+ import { CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/constants';
2
2
  import { BlockNumber } from '@aztec/foundation/branded-types';
3
3
  import { Schnorr } from '@aztec/foundation/crypto/schnorr';
4
4
  import { Fr } from '@aztec/foundation/curves/bn254';
5
5
  import { LogLevels, applyStringFormatting, createLogger } from '@aztec/foundation/log';
6
6
  import { TestDateProvider } from '@aztec/foundation/timer';
7
- import { ORACLE_VERSION, enrichPublicSimulationError, syncState } from '@aztec/pxe/server';
7
+ import { CapsuleService, ORACLE_VERSION_MAJOR, composeHooks, enrichPublicSimulationError } from '@aztec/pxe/server';
8
8
  import { ExecutionNoteCache, ExecutionTaggingIndexCache, HashedValuesCache, Oracle, PrivateExecutionOracle, UtilityExecutionOracle, executePrivateFunction, generateSimulatedProvingResult } from '@aztec/pxe/simulator';
9
9
  import { ExecutionError, WASMSimulator, createSimulationError, extractCallStack, resolveAssertionMessageFromError, toACVMWitness, witnessMapToFields } from '@aztec/simulator/client';
10
10
  import { CppPublicTxSimulator, GuardedMerkleTreeOperations, PublicContractsDB, PublicProcessor } from '@aztec/simulator/server';
@@ -13,7 +13,7 @@ import { AuthWitness } from '@aztec/stdlib/auth-witness';
13
13
  import { PublicSimulatorConfig } from '@aztec/stdlib/avm';
14
14
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
15
15
  import { computePartialAddress } from '@aztec/stdlib/contract';
16
- import { Gas, GasFees, GasSettings } from '@aztec/stdlib/gas';
16
+ import { Gas, GasFees } from '@aztec/stdlib/gas';
17
17
  import { computeCalldataHash, computeProtocolNullifier, siloNullifier } from '@aztec/stdlib/hash';
18
18
  import { PartialPrivateTailPublicInputsForPublic, PrivateKernelTailCircuitPublicInputs, PrivateToPublicAccumulatedData, PublicCallRequest } from '@aztec/stdlib/kernel';
19
19
  import { ChonkProof } from '@aztec/stdlib/proofs';
@@ -36,7 +36,6 @@ export class TXEOracleTopLevelContext {
36
36
  senderAddressBookStore;
37
37
  capsuleStore;
38
38
  privateEventStore;
39
- jobId;
40
39
  nextBlockTimestamp;
41
40
  version;
42
41
  chainId;
@@ -44,7 +43,7 @@ export class TXEOracleTopLevelContext {
44
43
  isMisc;
45
44
  isTxe;
46
45
  logger;
47
- constructor(stateMachine, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, senderAddressBookStore, capsuleStore, privateEventStore, jobId, nextBlockTimestamp, version, chainId, authwits){
46
+ constructor(stateMachine, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, senderAddressBookStore, capsuleStore, privateEventStore, nextBlockTimestamp, version, chainId, authwits){
48
47
  this.stateMachine = stateMachine;
49
48
  this.contractStore = contractStore;
50
49
  this.noteStore = noteStore;
@@ -56,7 +55,6 @@ export class TXEOracleTopLevelContext {
56
55
  this.senderAddressBookStore = senderAddressBookStore;
57
56
  this.capsuleStore = capsuleStore;
58
57
  this.privateEventStore = privateEventStore;
59
- this.jobId = jobId;
60
58
  this.nextBlockTimestamp = nextBlockTimestamp;
61
59
  this.version = version;
62
60
  this.chainId = chainId;
@@ -66,39 +64,50 @@ export class TXEOracleTopLevelContext {
66
64
  this.logger = createLogger('txe:top_level_context');
67
65
  this.logger.debug('Entering Top Level Context');
68
66
  }
69
- utilityAssertCompatibleOracleVersion(version) {
70
- if (version !== ORACLE_VERSION) {
71
- throw new Error(`Incompatible oracle version. TXE is using version '${ORACLE_VERSION}', but got a request for '${version}'.`);
67
+ contractOracleVersion;
68
+ assertCompatibleOracleVersion(major, minor) {
69
+ if (major !== ORACLE_VERSION_MAJOR) {
70
+ const hint = major > ORACLE_VERSION_MAJOR ? 'The contract was compiled with a newer version of Aztec.nr than this aztec cli version supports. Upgrade your aztec cli version to a compatible version.' : 'The contract was compiled with an older version of Aztec.nr than this aztec cli version supports. Recompile the contract with a compatible version of Aztec.nr.';
71
+ throw new Error(`Incompatible aztec cli version: ${hint} See https://docs.aztec.network/errors/8 (expected oracle major version ${ORACLE_VERSION_MAJOR}, got ${major})`);
72
72
  }
73
+ this.contractOracleVersion = {
74
+ major,
75
+ minor
76
+ };
77
+ }
78
+ // Prefixed with "nonOracleFunction" as it is not used as an oracle handler.
79
+ nonOracleFunctionGetContractOracleVersion() {
80
+ return this.contractOracleVersion;
73
81
  }
74
82
  // This is typically only invoked in private contexts, but it is convenient to also have it in top-level for testing
75
83
  // setup.
76
- utilityGetRandomField() {
84
+ getRandomField() {
77
85
  return Fr.random();
78
86
  }
79
87
  // We instruct users to debug contracts via this oracle, so it makes sense that they'd expect it to also work in tests
80
- utilityDebugLog(level, message, fields) {
88
+ log(level, message, fields) {
81
89
  if (!LogLevels[level]) {
82
- throw new Error(`Invalid debug log level: ${level}`);
90
+ throw new Error(`Invalid log level: ${level}`);
83
91
  }
84
92
  const levelName = LogLevels[level];
85
93
  this.logger[levelName](`${applyStringFormatting(message, fields)}`, {
86
94
  module: `${this.logger.module}:debug_log`
87
95
  });
96
+ return Promise.resolve();
88
97
  }
89
- txeGetDefaultAddress() {
98
+ getDefaultAddress() {
90
99
  return DEFAULT_ADDRESS;
91
100
  }
92
- async txeGetNextBlockNumber() {
101
+ async getNextBlockNumber() {
93
102
  return BlockNumber(await this.getLastBlockNumber() + 1);
94
103
  }
95
- txeGetNextBlockTimestamp() {
104
+ getNextBlockTimestamp() {
96
105
  return Promise.resolve(this.nextBlockTimestamp);
97
106
  }
98
- async txeGetLastBlockTimestamp() {
107
+ async getLastBlockTimestamp() {
99
108
  return (await this.stateMachine.node.getBlockHeader('latest')).globalVariables.timestamp;
100
109
  }
101
- async txeGetLastTxEffects() {
110
+ async getLastTxEffects() {
102
111
  const latestBlockNumber = await this.stateMachine.archiver.getBlockNumber();
103
112
  const block = await this.stateMachine.archiver.getBlock(latestBlockNumber);
104
113
  if (block.body.txEffects.length != 1) {
@@ -109,10 +118,23 @@ export class TXEOracleTopLevelContext {
109
118
  return {
110
119
  txHash: txEffects.txHash,
111
120
  noteHashes: txEffects.noteHashes,
112
- nullifiers: txEffects.nullifiers
121
+ nullifiers: txEffects.nullifiers,
122
+ privateLogs: txEffects.privateLogs
113
123
  };
114
124
  }
115
- async txeGetPrivateEvents(selector, contractAddress, scope) {
125
+ async syncContractNonOracleMethod(contractAddress, scope, jobId) {
126
+ if (contractAddress.equals(DEFAULT_ADDRESS)) {
127
+ this.logger.debug(`Skipping sync in getPrivateEvents because the events correspond to the default address.`);
128
+ return;
129
+ }
130
+ const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
131
+ await this.stateMachine.contractSyncService.ensureContractSynced(contractAddress, null, async (call, execScopes)=>{
132
+ await this.executeUtilityCall(call, execScopes, jobId);
133
+ }, blockHeader, jobId, [
134
+ scope
135
+ ]);
136
+ }
137
+ async getPrivateEvents(selector, contractAddress, scope) {
116
138
  return (await this.privateEventStore.getPrivateEvents(selector, {
117
139
  contractAddress,
118
140
  scopes: [
@@ -122,17 +144,17 @@ export class TXEOracleTopLevelContext {
122
144
  toBlock: await this.getLastBlockNumber() + 1
123
145
  })).map((e)=>e.packedEvent);
124
146
  }
125
- async txeAdvanceBlocksBy(blocks) {
147
+ async advanceBlocksBy(blocks) {
126
148
  this.logger.debug(`time traveling ${blocks} blocks`);
127
149
  for(let i = 0; i < blocks; i++){
128
150
  await this.mineBlock();
129
151
  }
130
152
  }
131
- txeAdvanceTimestampBy(duration) {
153
+ advanceTimestampBy(duration) {
132
154
  this.logger.debug(`time traveling ${duration} seconds`);
133
155
  this.nextBlockTimestamp += duration;
134
156
  }
135
- async txeDeploy(artifact, instance, secret) {
157
+ async deploy(artifact, instance, secret) {
136
158
  // Emit deployment nullifier
137
159
  await this.mineBlock({
138
160
  nullifiers: [
@@ -140,25 +162,25 @@ export class TXEOracleTopLevelContext {
140
162
  ]
141
163
  });
142
164
  if (!secret.equals(Fr.ZERO)) {
143
- await this.txeAddAccount(artifact, instance, secret);
165
+ await this.addAccount(artifact, instance, secret);
144
166
  } else {
145
167
  await this.contractStore.addContractInstance(instance);
146
- await this.contractStore.addContractArtifact(instance.currentContractClassId, artifact);
168
+ await this.contractStore.addContractArtifact(artifact);
147
169
  this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`);
148
170
  }
149
171
  }
150
- async txeAddAccount(artifact, instance, secret) {
172
+ async addAccount(artifact, instance, secret) {
151
173
  const partialAddress = await computePartialAddress(instance);
152
174
  this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`);
153
175
  await this.contractStore.addContractInstance(instance);
154
- await this.contractStore.addContractArtifact(instance.currentContractClassId, artifact);
176
+ await this.contractStore.addContractArtifact(artifact);
155
177
  const completeAddress = await this.keyStore.addAccount(secret, partialAddress);
156
178
  await this.accountStore.setAccount(completeAddress.address, completeAddress);
157
179
  await this.addressStore.addCompleteAddress(completeAddress);
158
180
  this.logger.debug(`Created account ${completeAddress.address}`);
159
181
  return completeAddress;
160
182
  }
161
- async txeCreateAccount(secret) {
183
+ async createAccount(secret) {
162
184
  // This is a foot gun !
163
185
  const completeAddress = await this.keyStore.addAccount(secret, secret);
164
186
  await this.accountStore.setAccount(completeAddress.address, completeAddress);
@@ -166,7 +188,7 @@ export class TXEOracleTopLevelContext {
166
188
  this.logger.debug(`Created account ${completeAddress.address}`);
167
189
  return completeAddress;
168
190
  }
169
- async txeAddAuthWitness(address, messageHash) {
191
+ async addAuthWitness(address, messageHash) {
170
192
  const account = await this.accountStore.getAccount(address);
171
193
  const privateKey = await this.keyStore.getMasterSecretKey(account.publicKeys.masterIncomingViewingPublicKey);
172
194
  const schnorr = new Schnorr();
@@ -177,7 +199,7 @@ export class TXEOracleTopLevelContext {
177
199
  this.authwits.set(authWitness.requestHash.toString(), authWitness);
178
200
  }
179
201
  async mineBlock(options = {}) {
180
- const blockNumber = await this.txeGetNextBlockNumber();
202
+ const blockNumber = await this.getNextBlockNumber();
181
203
  const txEffect = TxEffect.empty();
182
204
  txEffect.nullifiers = [
183
205
  getSingleTxBlockRequestHash(blockNumber),
@@ -199,25 +221,27 @@ export class TXEOracleTopLevelContext {
199
221
  this.logger.info(`Created block ${blockNumber} with timestamp ${block.header.globalVariables.timestamp}`);
200
222
  await this.stateMachine.handleL2Block(block);
201
223
  }
202
- async txePrivateCallNewFlow(from, targetContractAddress = AztecAddress.zero(), functionSelector = FunctionSelector.empty(), args, argsHash = Fr.zero(), isStaticCall = false) {
224
+ async privateCallNewFlow(from, targetContractAddress = AztecAddress.zero(), functionSelector = FunctionSelector.empty(), args, argsHash = Fr.zero(), isStaticCall = false, additionalScopes = [], jobId, authorizedUtilityCallTargets, gasSettings) {
203
225
  this.logger.verbose(`Executing external function ${await this.contractStore.getDebugFunctionName(targetContractAddress, functionSelector)}@${targetContractAddress} isStaticCall=${isStaticCall}`);
204
226
  const artifact = await this.contractStore.getFunctionArtifact(targetContractAddress, functionSelector);
205
227
  if (!artifact) {
206
228
  const message = functionSelector.equals(await FunctionSelector.fromSignature('verify_private_authwit(Field)')) ? 'Found no account contract artifact for a private authwit check - use `create_contract_account` instead of `create_light_account` for authwit support.' : 'Function Artifact does not exist';
207
229
  throw new Error(message);
208
230
  }
231
+ const scopes = from === undefined ? additionalScopes : [
232
+ from,
233
+ ...additionalScopes
234
+ ];
209
235
  // Sync notes before executing private function to discover notes from previous transactions
210
- const utilityExecutor = async (call)=>{
211
- await this.executeUtilityCall(call);
236
+ const utilityExecutor = async (call, execScopes)=>{
237
+ await this.executeUtilityCall(call, execScopes, jobId);
212
238
  };
213
- await syncState(targetContractAddress, this.contractStore, functionSelector, utilityExecutor);
214
- const blockNumber = await this.txeGetNextBlockNumber();
215
- const callContext = new CallContext(from, targetContractAddress, functionSelector, isStaticCall);
216
- const gasLimits = new Gas(DEFAULT_DA_GAS_LIMIT, DEFAULT_L2_GAS_LIMIT);
217
- const teardownGasLimits = new Gas(DEFAULT_TEARDOWN_DA_GAS_LIMIT, DEFAULT_TEARDOWN_L2_GAS_LIMIT);
218
- const gasSettings = new GasSettings(gasLimits, teardownGasLimits, GasFees.empty(), GasFees.empty());
219
- const txContext = new TxContext(this.chainId, this.version, gasSettings);
220
239
  const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
240
+ await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress, functionSelector, utilityExecutor, blockHeader, jobId, scopes);
241
+ const blockNumber = await this.getNextBlockNumber();
242
+ const msgSender = from ?? AztecAddress.NULL_MSG_SENDER;
243
+ const callContext = new CallContext(msgSender, targetContractAddress, functionSelector, isStaticCall);
244
+ const txContext = new TxContext(this.chainId, this.version, gasSettings);
221
245
  const protocolNullifier = await computeProtocolNullifier(getSingleTxBlockRequestHash(blockNumber));
222
246
  const noteCache = new ExecutionNoteCache(protocolNullifier);
223
247
  // In production, the account contract sets the min revertible counter before calling the app function.
@@ -227,12 +251,44 @@ export class TXEOracleTopLevelContext {
227
251
  await noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter);
228
252
  const taggingIndexCache = new ExecutionTaggingIndexCache();
229
253
  const simulator = new WASMSimulator();
230
- const privateExecutionOracle = new PrivateExecutionOracle(argsHash, txContext, callContext, /** Header of a block whose state is used during private execution (not the block the transaction is included in). */ blockHeader, utilityExecutor, /** List of transient auth witnesses to be used during this simulation */ Array.from(this.authwits.values()), /** List of transient auth witnesses to be used during this simulation */ [], HashedValuesCache.create([
231
- new HashedValues(args, argsHash)
232
- ]), noteCache, taggingIndexCache, this.contractStore, this.noteStore, this.keyStore, this.addressStore, this.stateMachine.node, this.stateMachine.anchorBlockStore, this.senderTaggingStore, this.recipientTaggingStore, this.senderAddressBookStore, this.capsuleStore, this.privateEventStore, this.jobId, 0, minRevertibleSideEffectCounter, undefined, undefined, /**
233
- * In TXE, the typical transaction entrypoint is skipped, so we need to simulate the actions that such a
234
- * contract would perform, including setting senderForTags.
235
- */ from, simulator);
254
+ const privateExecutionOracle = new PrivateExecutionOracle({
255
+ argsHash,
256
+ txContext,
257
+ callContext,
258
+ anchorBlockHeader: blockHeader,
259
+ utilityExecutor,
260
+ authWitnesses: Array.from(this.authwits.values()),
261
+ capsules: [],
262
+ executionCache: HashedValuesCache.create([
263
+ new HashedValues(args, argsHash)
264
+ ]),
265
+ noteCache,
266
+ taggingIndexCache,
267
+ contractStore: this.contractStore,
268
+ noteStore: this.noteStore,
269
+ keyStore: this.keyStore,
270
+ addressStore: this.addressStore,
271
+ aztecNode: this.stateMachine.node,
272
+ senderTaggingStore: this.senderTaggingStore,
273
+ recipientTaggingStore: this.recipientTaggingStore,
274
+ senderAddressBookStore: this.senderAddressBookStore,
275
+ capsuleService: new CapsuleService(this.capsuleStore, scopes),
276
+ privateEventStore: this.privateEventStore,
277
+ contractSyncService: this.stateMachine.contractSyncService,
278
+ jobId,
279
+ totalPublicCalldataCount: 0,
280
+ sideEffectCounter: minRevertibleSideEffectCounter,
281
+ scopes,
282
+ // In TXE, the typical transaction entrypoint is skipped, so we need to simulate the actions that such a
283
+ // contract would perform, including setting senderForTags.
284
+ senderForTags: from,
285
+ simulator,
286
+ messageContextService: this.stateMachine.messageContextService,
287
+ l2TipsStore: this.stateMachine.node,
288
+ hooks: composeHooks({
289
+ authorizeUtilityCall: this.buildAuthorizeUtilityCallHook('private', authorizedUtilityCallTargets)
290
+ })
291
+ });
236
292
  // Note: This is a slight modification of simulator.run without any of the checks. Maybe we should modify simulator.run with a boolean value to skip checks.
237
293
  let result;
238
294
  let executionResult;
@@ -244,7 +300,7 @@ export class TXEOracleTopLevelContext {
244
300
  r.publicInputs.publicTeardownCallRequest
245
301
  ]));
246
302
  const publicFunctionsCalldata = await Promise.all(publicCallRequests.map(async (r)=>{
247
- const calldata = await privateExecutionOracle.privateLoadFromExecutionCache(r.calldataHash);
303
+ const calldata = await privateExecutionOracle.getHashPreimage(r.calldataHash);
248
304
  return new HashedValues(calldata, r.calldataHash);
249
305
  }));
250
306
  noteCache.finish();
@@ -256,7 +312,7 @@ export class TXEOracleTopLevelContext {
256
312
  // According to the protocol rules, there must be at least one nullifier in the tx. The first nullifier is used as
257
313
  // the nonce generator for the note hashes.
258
314
  // We pass the non-zero minRevertibleSideEffectCounter to make sure the side effects are split correctly.
259
- const { publicInputs } = await generateSimulatedProvingResult(result, this.contractStore, minRevertibleSideEffectCounter);
315
+ const { publicInputs } = await generateSimulatedProvingResult(result, (addr, sel)=>this.contractStore.getDebugFunctionName(addr, sel), this.stateMachine.node, minRevertibleSideEffectCounter);
260
316
  const globals = makeGlobalVariables();
261
317
  globals.blockNumber = blockNumber;
262
318
  globals.timestamp = this.nextBlockTimestamp;
@@ -264,7 +320,8 @@ export class TXEOracleTopLevelContext {
264
320
  globals.version = this.version;
265
321
  globals.gasFees = GasFees.empty();
266
322
  const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
267
- const contractsDB = new PublicContractsDB(new TXEPublicContractDataSource(blockNumber, this.contractStore));
323
+ const bindings = this.logger.getBindings();
324
+ const contractsDB = new PublicContractsDB(new TXEPublicContractDataSource(blockNumber, this.contractStore), bindings);
268
325
  const guardedMerkleTrees = new GuardedMerkleTreeOperations(forkedWorldTrees);
269
326
  const config = PublicSimulatorConfig.from({
270
327
  skipFeeEnforcement: true,
@@ -273,7 +330,7 @@ export class TXEOracleTopLevelContext {
273
330
  collectStatistics: false,
274
331
  collectCallMetadata: true
275
332
  });
276
- const processor = new PublicProcessor(globals, guardedMerkleTrees, contractsDB, new CppPublicTxSimulator(guardedMerkleTrees, contractsDB, globals, config), new TestDateProvider());
333
+ const processor = new PublicProcessor(globals, guardedMerkleTrees, contractsDB, new CppPublicTxSimulator(guardedMerkleTrees, contractsDB, globals, config, bindings), new TestDateProvider(), undefined, createLogger('simulator:public-processor', bindings));
277
334
  const tx = await Tx.create({
278
335
  data: publicInputs,
279
336
  chonkProof: ChonkProof.empty(),
@@ -302,10 +359,20 @@ export class TXEOracleTopLevelContext {
302
359
  throw new Error('Contract execution has reverted');
303
360
  }
304
361
  }
362
+ // Walk the nested private-call tree and collect every offchain effect the transaction emitted.
363
+ // PXE stores these on each `PrivateCallExecutionResult` and they never reach TXE via the
364
+ // `aztec_utl_emitOffchainEffect` foreign-call path (that path only fires at the top-level), so
365
+ // we pull them out here and the RPC wrapper will hand them to `TXESession` for buffering.
366
+ const offchainEffects = collectNested([
367
+ executionResult
368
+ ], (r)=>r.offchainEffects.map((e)=>e.data));
305
369
  if (isStaticCall) {
306
370
  await checkpoint.revert();
307
371
  await forkedWorldTrees.close();
308
- return executionResult.returnValues ?? [];
372
+ return {
373
+ returnValues: executionResult.returnValues ?? [],
374
+ offchainEffects
375
+ };
309
376
  }
310
377
  const txEffect = TxEffect.empty();
311
378
  txEffect.noteHashes = processedTx.txEffect.noteHashes;
@@ -321,14 +388,14 @@ export class TXEOracleTopLevelContext {
321
388
  ]);
322
389
  await this.stateMachine.handleL2Block(l2Block);
323
390
  await forkedWorldTrees.close();
324
- return executionResult.returnValues ?? [];
391
+ return {
392
+ returnValues: executionResult.returnValues ?? [],
393
+ offchainEffects
394
+ };
325
395
  }
326
- async txePublicCallNewFlow(from, targetContractAddress, calldata, isStaticCall) {
396
+ async publicCallNewFlow(from, targetContractAddress, calldata, isStaticCall, gasSettings) {
327
397
  this.logger.verbose(`Executing public function ${await this.contractStore.getDebugFunctionName(targetContractAddress, FunctionSelector.fromField(calldata[0]))}@${targetContractAddress} isStaticCall=${isStaticCall}`);
328
- const blockNumber = await this.txeGetNextBlockNumber();
329
- const gasLimits = new Gas(DEFAULT_DA_GAS_LIMIT, DEFAULT_L2_GAS_LIMIT);
330
- const teardownGasLimits = new Gas(DEFAULT_TEARDOWN_DA_GAS_LIMIT, DEFAULT_TEARDOWN_L2_GAS_LIMIT);
331
- const gasSettings = new GasSettings(gasLimits, teardownGasLimits, GasFees.empty(), GasFees.empty());
398
+ const blockNumber = await this.getNextBlockNumber();
332
399
  const txContext = new TxContext(this.chainId, this.version, gasSettings);
333
400
  const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
334
401
  const calldataHash = await computeCalldataHash(calldata);
@@ -340,7 +407,8 @@ export class TXEOracleTopLevelContext {
340
407
  globals.version = this.version;
341
408
  globals.gasFees = GasFees.empty();
342
409
  const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
343
- const contractsDB = new PublicContractsDB(new TXEPublicContractDataSource(blockNumber, this.contractStore));
410
+ const bindings2 = this.logger.getBindings();
411
+ const contractsDB = new PublicContractsDB(new TXEPublicContractDataSource(blockNumber, this.contractStore), bindings2);
344
412
  const guardedMerkleTrees = new GuardedMerkleTreeOperations(forkedWorldTrees);
345
413
  const config = PublicSimulatorConfig.from({
346
414
  skipFeeEnforcement: true,
@@ -349,8 +417,8 @@ export class TXEOracleTopLevelContext {
349
417
  collectStatistics: false,
350
418
  collectCallMetadata: true
351
419
  });
352
- const simulator = new CppPublicTxSimulator(guardedMerkleTrees, contractsDB, globals, config);
353
- const processor = new PublicProcessor(globals, guardedMerkleTrees, contractsDB, simulator, new TestDateProvider());
420
+ const simulator = new CppPublicTxSimulator(guardedMerkleTrees, contractsDB, globals, config, bindings2);
421
+ const processor = new PublicProcessor(globals, guardedMerkleTrees, contractsDB, simulator, new TestDateProvider(), undefined, createLogger('simulator:public-processor', bindings2));
354
422
  // We're simulating a scenario in which private execution immediately enqueues a public call and halts. The private
355
423
  // kernel init would in this case inject a nullifier with the transaction request hash as a non-revertible
356
424
  // side-effect, which the AVM then expects to exist in order to use it as the nonce generator when siloing notes as
@@ -360,10 +428,10 @@ export class TXEOracleTopLevelContext {
360
428
  // The enqueued public call itself we make be revertible so that the public execution is itself revertible, as tests
361
429
  // may require producing reverts.
362
430
  const revertibleAccumulatedData = PrivateToPublicAccumulatedData.empty();
363
- revertibleAccumulatedData.publicCallRequests[0] = new PublicCallRequest(from, targetContractAddress, isStaticCall, calldataHash);
431
+ revertibleAccumulatedData.publicCallRequests[0] = new PublicCallRequest(from ?? AztecAddress.NULL_MSG_SENDER, targetContractAddress, isStaticCall, calldataHash);
364
432
  const inputsForPublic = new PartialPrivateTailPublicInputsForPublic(nonRevertibleAccumulatedData, revertibleAccumulatedData, PublicCallRequest.empty());
365
433
  const constantData = new TxConstantData(anchorBlockHeader, txContext, Fr.zero(), Fr.zero());
366
- const txData = new PrivateKernelTailCircuitPublicInputs(constantData, /*gasUsed=*/ new Gas(0, 0), /*feePayer=*/ AztecAddress.zero(), /*includeByTimestamp=*/ 0n, inputsForPublic, undefined);
434
+ const txData = new PrivateKernelTailCircuitPublicInputs(constantData, /*gasUsed=*/ new Gas(0, 0), /*feePayer=*/ AztecAddress.zero(), /*expirationTimestamp=*/ 0n, inputsForPublic, undefined);
367
435
  const tx = await Tx.create({
368
436
  data: txData,
369
437
  chonkProof: ChonkProof.empty(),
@@ -416,19 +484,29 @@ export class TXEOracleTopLevelContext {
416
484
  await forkedWorldTrees.close();
417
485
  return returnValues ?? [];
418
486
  }
419
- async txeSimulateUtilityFunction(targetContractAddress, functionSelector, args) {
487
+ async executeUtilityFunction(targetContractAddress, functionSelector, args, jobId, authorizedUtilityCallTargets) {
420
488
  const artifact = await this.contractStore.getFunctionArtifact(targetContractAddress, functionSelector);
421
489
  if (!artifact) {
422
490
  throw new Error(`Cannot call ${functionSelector} as there is no artifact found at ${targetContractAddress}.`);
423
491
  }
424
492
  // Sync notes before executing utility function to discover notes from previous transactions
425
- await syncState(targetContractAddress, this.contractStore, functionSelector, async (call)=>{
426
- await this.executeUtilityCall(call);
493
+ const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
494
+ await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress, functionSelector, async (call, execScopes)=>{
495
+ await this.executeUtilityCall(call, execScopes, jobId);
496
+ }, blockHeader, jobId, await this.keyStore.getAccounts());
497
+ const call = FunctionCall.from({
498
+ name: artifact.name,
499
+ to: targetContractAddress,
500
+ selector: functionSelector,
501
+ type: FunctionType.UTILITY,
502
+ hideMsgSender: false,
503
+ isStatic: false,
504
+ args,
505
+ returnTypes: []
427
506
  });
428
- const call = new FunctionCall(artifact.name, targetContractAddress, functionSelector, FunctionType.UTILITY, false, false, args, []);
429
- return this.executeUtilityCall(call);
507
+ return this.executeUtilityCall(call, await this.keyStore.getAccounts(), jobId, authorizedUtilityCallTargets);
430
508
  }
431
- async executeUtilityCall(call) {
509
+ async executeUtilityCall(call, scopes, jobId, authorizedUtilityCallTargets = []) {
432
510
  const entryPointArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
433
511
  if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
434
512
  throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
@@ -439,8 +517,36 @@ export class TXEOracleTopLevelContext {
439
517
  });
440
518
  try {
441
519
  const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
442
- const oracle = new UtilityExecutionOracle(call.to, [], [], anchorBlockHeader, this.contractStore, this.noteStore, this.keyStore, this.addressStore, this.stateMachine.node, this.stateMachine.anchorBlockStore, this.recipientTaggingStore, this.senderAddressBookStore, this.capsuleStore, this.privateEventStore, this.jobId);
443
- const acirExecutionResult = await new WASMSimulator().executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback()).catch((err)=>{
520
+ const simulator = new WASMSimulator();
521
+ const utilityExecutor = async (syncCall, execScopes)=>{
522
+ await this.executeUtilityCall(syncCall, execScopes, jobId);
523
+ };
524
+ const oracle = new UtilityExecutionOracle({
525
+ contractAddress: call.to,
526
+ authWitnesses: [],
527
+ capsules: [],
528
+ anchorBlockHeader,
529
+ contractStore: this.contractStore,
530
+ noteStore: this.noteStore,
531
+ keyStore: this.keyStore,
532
+ addressStore: this.addressStore,
533
+ aztecNode: this.stateMachine.node,
534
+ recipientTaggingStore: this.recipientTaggingStore,
535
+ senderAddressBookStore: this.senderAddressBookStore,
536
+ capsuleService: new CapsuleService(this.capsuleStore, scopes),
537
+ privateEventStore: this.privateEventStore,
538
+ messageContextService: this.stateMachine.messageContextService,
539
+ contractSyncService: this.stateMachine.contractSyncService,
540
+ l2TipsStore: this.stateMachine.node,
541
+ jobId,
542
+ scopes,
543
+ simulator,
544
+ hooks: composeHooks({
545
+ authorizeUtilityCall: this.buildAuthorizeUtilityCallHook('utility', authorizedUtilityCallTargets)
546
+ }),
547
+ utilityExecutor
548
+ });
549
+ const acirExecutionResult = await simulator.executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback()).catch((err)=>{
444
550
  err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
445
551
  throw new ExecutionError(err.message, {
446
552
  contractAddress: call.to,
@@ -449,10 +555,10 @@ export class TXEOracleTopLevelContext {
449
555
  cause: err
450
556
  });
451
557
  });
452
- this.logger.verbose(`Utility simulation for ${call.to}.${call.selector} completed`);
558
+ this.logger.verbose(`Utility execution for ${call.to}.${call.selector} completed`);
453
559
  return witnessMapToFields(acirExecutionResult.returnWitness);
454
560
  } catch (err) {
455
- throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during utility simulation'));
561
+ throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during utility execution'));
456
562
  }
457
563
  }
458
564
  close() {
@@ -466,4 +572,12 @@ export class TXEOracleTopLevelContext {
466
572
  const header = await this.stateMachine.node.getBlockHeader('latest');
467
573
  return header ? header.globalVariables.blockNumber : BlockNumber.ZERO;
468
574
  }
575
+ buildAuthorizeUtilityCallHook(callerContext, authorizedTargets) {
576
+ if (authorizedTargets.length === 0) {
577
+ return undefined;
578
+ }
579
+ return (req)=>Promise.resolve({
580
+ authorized: req.callerContext === callerContext && authorizedTargets.some((t)=>t.equals(req.target))
581
+ });
582
+ }
469
583
  }