@aztec/txe 0.0.1-commit.e558bd1c → 0.0.1-commit.e5a3663dd

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 (60) 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 +34 -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 +12 -12
  9. package/dest/oracle/txe_oracle_top_level_context.d.ts +31 -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 +159 -66
  12. package/dest/rpc_translator.d.ts +129 -83
  13. package/dest/rpc_translator.d.ts.map +1 -1
  14. package/dest/rpc_translator.js +479 -165
  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 +12 -12
  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/global_variable_builder.d.ts +9 -4
  22. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  23. package/dest/state_machine/global_variable_builder.js +9 -3
  24. package/dest/state_machine/index.d.ts +4 -2
  25. package/dest/state_machine/index.d.ts.map +1 -1
  26. package/dest/state_machine/index.js +8 -4
  27. package/dest/state_machine/mock_epoch_cache.d.ts +20 -3
  28. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  29. package/dest/state_machine/mock_epoch_cache.js +39 -2
  30. package/dest/state_machine/synchronizer.d.ts +5 -5
  31. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  32. package/dest/state_machine/synchronizer.js +3 -3
  33. package/dest/txe_session.d.ts +54 -6
  34. package/dest/txe_session.d.ts.map +1 -1
  35. package/dest/txe_session.js +152 -27
  36. package/dest/util/encoding.d.ts +71 -1
  37. package/dest/util/encoding.d.ts.map +1 -1
  38. package/dest/util/encoding.js +4 -0
  39. package/dest/util/txe_public_contract_data_source.d.ts +2 -3
  40. package/dest/util/txe_public_contract_data_source.d.ts.map +1 -1
  41. package/dest/util/txe_public_contract_data_source.js +6 -25
  42. package/package.json +15 -15
  43. package/src/index.ts +89 -52
  44. package/src/oracle/interfaces.ts +35 -32
  45. package/src/oracle/txe_oracle_public_context.ts +12 -12
  46. package/src/oracle/txe_oracle_top_level_context.ts +168 -117
  47. package/src/rpc_translator.ts +571 -196
  48. package/src/state_machine/archiver.ts +9 -9
  49. package/src/state_machine/dummy_p2p_client.ts +39 -22
  50. package/src/state_machine/global_variable_builder.ts +18 -3
  51. package/src/state_machine/index.ts +10 -2
  52. package/src/state_machine/mock_epoch_cache.ts +51 -3
  53. package/src/state_machine/synchronizer.ts +4 -4
  54. package/src/txe_session.ts +216 -76
  55. package/src/util/encoding.ts +5 -0
  56. package/src/util/txe_public_contract_data_source.ts +10 -38
  57. package/dest/util/txe_contract_store.d.ts +0 -12
  58. package/dest/util/txe_contract_store.d.ts.map +0 -1
  59. package/dest/util/txe_contract_store.js +0 -22
  60. 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, MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT, MAX_PROCESSABLE_L2_GAS, 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 } from '@aztec/pxe/server';
7
+ import { CapsuleService, ORACLE_VERSION_MAJOR, 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 { FALLBACK_TEARDOWN_DA_GAS_LIMIT, FALLBACK_TEARDOWN_L2_GAS_LIMIT, Gas, GasFees, GasSettings } 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,29 +221,28 @@ 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, jobId) {
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
  }
209
- // When `from` is the zero address (used when creating a new contract account for example),
210
- // we disable scope filtering by setting effectiveScopes to undefined. This allows these operations
211
- // to proceed without requiring keys registered for the zero address.
212
- const effectiveScopes = from.isZero() ? undefined : [
231
+ // When `from` is the zero address (e.g. when deploying a new account contract), we return an
232
+ // empty scope list which acts as deny-all: no notes are visible and no keys are accessible.
233
+ const effectiveScopes = from.isZero() ? [] : [
213
234
  from
214
235
  ];
215
236
  // Sync notes before executing private function to discover notes from previous transactions
216
- const utilityExecutor = async (call)=>{
217
- await this.executeUtilityCall(call, effectiveScopes);
237
+ const utilityExecutor = async (call, execScopes)=>{
238
+ await this.executeUtilityCall(call, execScopes, jobId);
218
239
  };
219
240
  const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
220
- await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress, functionSelector, utilityExecutor, blockHeader, this.jobId);
221
- const blockNumber = await this.txeGetNextBlockNumber();
241
+ await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress, functionSelector, utilityExecutor, blockHeader, jobId, effectiveScopes);
242
+ const blockNumber = await this.getNextBlockNumber();
222
243
  const callContext = new CallContext(from, targetContractAddress, functionSelector, isStaticCall);
223
- const gasLimits = new Gas(DEFAULT_DA_GAS_LIMIT, DEFAULT_L2_GAS_LIMIT);
224
- const teardownGasLimits = new Gas(DEFAULT_TEARDOWN_DA_GAS_LIMIT, DEFAULT_TEARDOWN_L2_GAS_LIMIT);
244
+ const gasLimits = new Gas(MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT, MAX_PROCESSABLE_L2_GAS);
245
+ const teardownGasLimits = new Gas(FALLBACK_TEARDOWN_DA_GAS_LIMIT, FALLBACK_TEARDOWN_L2_GAS_LIMIT);
225
246
  const gasSettings = new GasSettings(gasLimits, teardownGasLimits, GasFees.empty(), GasFees.empty());
226
247
  const txContext = new TxContext(this.chainId, this.version, gasSettings);
227
248
  const protocolNullifier = await computeProtocolNullifier(getSingleTxBlockRequestHash(blockNumber));
@@ -233,12 +254,41 @@ export class TXEOracleTopLevelContext {
233
254
  await noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter);
234
255
  const taggingIndexCache = new ExecutionTaggingIndexCache();
235
256
  const simulator = new WASMSimulator();
236
- 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([
237
- new HashedValues(args, argsHash)
238
- ]), noteCache, taggingIndexCache, this.contractStore, this.noteStore, this.keyStore, this.addressStore, this.stateMachine.node, this.senderTaggingStore, this.recipientTaggingStore, this.senderAddressBookStore, this.capsuleStore, this.privateEventStore, this.stateMachine.contractSyncService, this.jobId, 0, minRevertibleSideEffectCounter, undefined, effectiveScopes, /**
239
- * In TXE, the typical transaction entrypoint is skipped, so we need to simulate the actions that such a
240
- * contract would perform, including setting senderForTags.
241
- */ from, simulator);
257
+ const privateExecutionOracle = new PrivateExecutionOracle({
258
+ argsHash,
259
+ txContext,
260
+ callContext,
261
+ anchorBlockHeader: blockHeader,
262
+ utilityExecutor,
263
+ authWitnesses: Array.from(this.authwits.values()),
264
+ capsules: [],
265
+ executionCache: HashedValuesCache.create([
266
+ new HashedValues(args, argsHash)
267
+ ]),
268
+ noteCache,
269
+ taggingIndexCache,
270
+ contractStore: this.contractStore,
271
+ noteStore: this.noteStore,
272
+ keyStore: this.keyStore,
273
+ addressStore: this.addressStore,
274
+ aztecNode: this.stateMachine.node,
275
+ senderTaggingStore: this.senderTaggingStore,
276
+ recipientTaggingStore: this.recipientTaggingStore,
277
+ senderAddressBookStore: this.senderAddressBookStore,
278
+ capsuleService: new CapsuleService(this.capsuleStore, effectiveScopes),
279
+ privateEventStore: this.privateEventStore,
280
+ contractSyncService: this.stateMachine.contractSyncService,
281
+ jobId,
282
+ totalPublicCalldataCount: 0,
283
+ sideEffectCounter: minRevertibleSideEffectCounter,
284
+ scopes: effectiveScopes,
285
+ // In TXE, the typical transaction entrypoint is skipped, so we need to simulate the actions that such a
286
+ // contract would perform, including setting senderForTags.
287
+ senderForTags: from,
288
+ simulator,
289
+ messageContextService: this.stateMachine.messageContextService,
290
+ l2TipsStore: this.stateMachine.node
291
+ });
242
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.
243
293
  let result;
244
294
  let executionResult;
@@ -250,7 +300,7 @@ export class TXEOracleTopLevelContext {
250
300
  r.publicInputs.publicTeardownCallRequest
251
301
  ]));
252
302
  const publicFunctionsCalldata = await Promise.all(publicCallRequests.map(async (r)=>{
253
- const calldata = await privateExecutionOracle.privateLoadFromExecutionCache(r.calldataHash);
303
+ const calldata = await privateExecutionOracle.getHashPreimage(r.calldataHash);
254
304
  return new HashedValues(calldata, r.calldataHash);
255
305
  }));
256
306
  noteCache.finish();
@@ -262,7 +312,7 @@ export class TXEOracleTopLevelContext {
262
312
  // According to the protocol rules, there must be at least one nullifier in the tx. The first nullifier is used as
263
313
  // the nonce generator for the note hashes.
264
314
  // We pass the non-zero minRevertibleSideEffectCounter to make sure the side effects are split correctly.
265
- 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);
266
316
  const globals = makeGlobalVariables();
267
317
  globals.blockNumber = blockNumber;
268
318
  globals.timestamp = this.nextBlockTimestamp;
@@ -309,10 +359,20 @@ export class TXEOracleTopLevelContext {
309
359
  throw new Error('Contract execution has reverted');
310
360
  }
311
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));
312
369
  if (isStaticCall) {
313
370
  await checkpoint.revert();
314
371
  await forkedWorldTrees.close();
315
- return executionResult.returnValues ?? [];
372
+ return {
373
+ returnValues: executionResult.returnValues ?? [],
374
+ offchainEffects
375
+ };
316
376
  }
317
377
  const txEffect = TxEffect.empty();
318
378
  txEffect.noteHashes = processedTx.txEffect.noteHashes;
@@ -328,13 +388,16 @@ export class TXEOracleTopLevelContext {
328
388
  ]);
329
389
  await this.stateMachine.handleL2Block(l2Block);
330
390
  await forkedWorldTrees.close();
331
- return executionResult.returnValues ?? [];
391
+ return {
392
+ returnValues: executionResult.returnValues ?? [],
393
+ offchainEffects
394
+ };
332
395
  }
333
- async txePublicCallNewFlow(from, targetContractAddress, calldata, isStaticCall) {
396
+ async publicCallNewFlow(from, targetContractAddress, calldata, isStaticCall) {
334
397
  this.logger.verbose(`Executing public function ${await this.contractStore.getDebugFunctionName(targetContractAddress, FunctionSelector.fromField(calldata[0]))}@${targetContractAddress} isStaticCall=${isStaticCall}`);
335
- const blockNumber = await this.txeGetNextBlockNumber();
336
- const gasLimits = new Gas(DEFAULT_DA_GAS_LIMIT, DEFAULT_L2_GAS_LIMIT);
337
- const teardownGasLimits = new Gas(DEFAULT_TEARDOWN_DA_GAS_LIMIT, DEFAULT_TEARDOWN_L2_GAS_LIMIT);
398
+ const blockNumber = await this.getNextBlockNumber();
399
+ const gasLimits = new Gas(MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT, MAX_PROCESSABLE_L2_GAS);
400
+ const teardownGasLimits = new Gas(FALLBACK_TEARDOWN_DA_GAS_LIMIT, FALLBACK_TEARDOWN_L2_GAS_LIMIT);
338
401
  const gasSettings = new GasSettings(gasLimits, teardownGasLimits, GasFees.empty(), GasFees.empty());
339
402
  const txContext = new TxContext(this.chainId, this.version, gasSettings);
340
403
  const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
@@ -371,7 +434,7 @@ export class TXEOracleTopLevelContext {
371
434
  revertibleAccumulatedData.publicCallRequests[0] = new PublicCallRequest(from, targetContractAddress, isStaticCall, calldataHash);
372
435
  const inputsForPublic = new PartialPrivateTailPublicInputsForPublic(nonRevertibleAccumulatedData, revertibleAccumulatedData, PublicCallRequest.empty());
373
436
  const constantData = new TxConstantData(anchorBlockHeader, txContext, Fr.zero(), Fr.zero());
374
- const txData = new PrivateKernelTailCircuitPublicInputs(constantData, /*gasUsed=*/ new Gas(0, 0), /*feePayer=*/ AztecAddress.zero(), /*includeByTimestamp=*/ 0n, inputsForPublic, undefined);
437
+ const txData = new PrivateKernelTailCircuitPublicInputs(constantData, /*gasUsed=*/ new Gas(0, 0), /*feePayer=*/ AztecAddress.zero(), /*expirationTimestamp=*/ 0n, inputsForPublic, undefined);
375
438
  const tx = await Tx.create({
376
439
  data: txData,
377
440
  chonkProof: ChonkProof.empty(),
@@ -424,20 +487,29 @@ export class TXEOracleTopLevelContext {
424
487
  await forkedWorldTrees.close();
425
488
  return returnValues ?? [];
426
489
  }
427
- async txeSimulateUtilityFunction(targetContractAddress, functionSelector, args) {
490
+ async executeUtilityFunction(targetContractAddress, functionSelector, args, jobId) {
428
491
  const artifact = await this.contractStore.getFunctionArtifact(targetContractAddress, functionSelector);
429
492
  if (!artifact) {
430
493
  throw new Error(`Cannot call ${functionSelector} as there is no artifact found at ${targetContractAddress}.`);
431
494
  }
432
495
  // Sync notes before executing utility function to discover notes from previous transactions
433
496
  const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
434
- await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress, functionSelector, async (call)=>{
435
- await this.executeUtilityCall(call);
436
- }, blockHeader, this.jobId);
437
- const call = new FunctionCall(artifact.name, targetContractAddress, functionSelector, FunctionType.UTILITY, false, false, args, []);
438
- return this.executeUtilityCall(call);
497
+ await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress, functionSelector, async (call, execScopes)=>{
498
+ await this.executeUtilityCall(call, execScopes, jobId);
499
+ }, blockHeader, jobId, await this.keyStore.getAccounts());
500
+ const call = FunctionCall.from({
501
+ name: artifact.name,
502
+ to: targetContractAddress,
503
+ selector: functionSelector,
504
+ type: FunctionType.UTILITY,
505
+ hideMsgSender: false,
506
+ isStatic: false,
507
+ args,
508
+ returnTypes: []
509
+ });
510
+ return this.executeUtilityCall(call, await this.keyStore.getAccounts(), jobId);
439
511
  }
440
- async executeUtilityCall(call, scopes) {
512
+ async executeUtilityCall(call, scopes, jobId) {
441
513
  const entryPointArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
442
514
  if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
443
515
  throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
@@ -448,8 +520,29 @@ export class TXEOracleTopLevelContext {
448
520
  });
449
521
  try {
450
522
  const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
451
- const oracle = new UtilityExecutionOracle(call.to, [], [], anchorBlockHeader, this.contractStore, this.noteStore, this.keyStore, this.addressStore, this.stateMachine.node, this.recipientTaggingStore, this.senderAddressBookStore, this.capsuleStore, this.privateEventStore, this.jobId, undefined, scopes);
452
- const acirExecutionResult = await new WASMSimulator().executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback()).catch((err)=>{
523
+ const simulator = new WASMSimulator();
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
+ });
545
+ const acirExecutionResult = await simulator.executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback()).catch((err)=>{
453
546
  err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
454
547
  throw new ExecutionError(err.message, {
455
548
  contractAddress: call.to,
@@ -458,10 +551,10 @@ export class TXEOracleTopLevelContext {
458
551
  cause: err
459
552
  });
460
553
  });
461
- this.logger.verbose(`Utility simulation for ${call.to}.${call.selector} completed`);
554
+ this.logger.verbose(`Utility execution for ${call.to}.${call.selector} completed`);
462
555
  return witnessMapToFields(acirExecutionResult.returnWitness);
463
556
  } catch (err) {
464
- throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during utility simulation'));
557
+ throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during utility execution'));
465
558
  }
466
559
  }
467
560
  close() {