@aztec/txe 0.0.1-commit.3469e52 → 0.0.1-commit.350e0a4d

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 (170) hide show
  1. package/dest/AuthRegistry-2RDAZOGB.js +3 -0
  2. package/dest/AuthRegistry-2RDAZOGB.js.map +7 -0
  3. package/dest/ContractClassRegistry-L5F3G33N.js +3 -0
  4. package/dest/ContractClassRegistry-L5F3G33N.js.map +7 -0
  5. package/dest/ContractInstanceRegistry-IJOBAWAC.js +3 -0
  6. package/dest/ContractInstanceRegistry-IJOBAWAC.js.map +7 -0
  7. package/dest/FeeJuice-J3XDQPFS.js +3 -0
  8. package/dest/FeeJuice-J3XDQPFS.js.map +7 -0
  9. package/dest/HandshakeRegistry-QGWZJYVS.js +3 -0
  10. package/dest/HandshakeRegistry-QGWZJYVS.js.map +7 -0
  11. package/dest/MultiCallEntrypoint-WZHPRFJ6.js +3 -0
  12. package/dest/MultiCallEntrypoint-WZHPRFJ6.js.map +7 -0
  13. package/dest/SchnorrAccount-II4XD6MI.js +3 -0
  14. package/dest/SchnorrAccount-II4XD6MI.js.map +7 -0
  15. package/dest/SchnorrInitializerlessAccount-FXIOXUQQ.js +3 -0
  16. package/dest/SchnorrInitializerlessAccount-FXIOXUQQ.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 +61 -0
  20. package/dest/bin/index.js +3 -30
  21. package/dest/bin/index.js.map +7 -0
  22. package/dest/bin/oracle_test_server.d.ts +3 -0
  23. package/dest/bin/oracle_test_server.d.ts.map +1 -0
  24. package/dest/bin/oracle_test_server.js +41 -0
  25. package/dest/chunk-BJVAAXNA.js +3 -0
  26. package/dest/chunk-BJVAAXNA.js.map +7 -0
  27. package/dest/chunk-OMH3BDML.js +304 -0
  28. package/dest/chunk-OMH3BDML.js.map +7 -0
  29. package/dest/chunk-R3ZWQEFL.js +260 -0
  30. package/dest/chunk-R3ZWQEFL.js.map +7 -0
  31. package/dest/constants.d.ts +5 -1
  32. package/dest/constants.d.ts.map +1 -1
  33. package/dest/constants.js +9 -1
  34. package/dest/dispatcher_pool.d.ts +67 -0
  35. package/dest/dispatcher_pool.d.ts.map +1 -0
  36. package/dest/dispatcher_pool.js +286 -0
  37. package/dest/index.d.ts +51 -7
  38. package/dest/index.d.ts.map +1 -1
  39. package/dest/index.js +73 -157
  40. package/dest/metafile.json +38140 -0
  41. package/dest/msgpackr_fr_extension.d.ts +2 -0
  42. package/dest/msgpackr_fr_extension.d.ts.map +1 -0
  43. package/dest/msgpackr_fr_extension.js +21 -0
  44. package/dest/oracle/interfaces.d.ts +61 -30
  45. package/dest/oracle/interfaces.d.ts.map +1 -1
  46. package/dest/oracle/test-resolver/default_fixtures.d.ts +9 -0
  47. package/dest/oracle/test-resolver/default_fixtures.d.ts.map +1 -0
  48. package/dest/oracle/test-resolver/default_fixtures.js +207 -0
  49. package/dest/oracle/test-resolver/index.d.ts +9 -0
  50. package/dest/oracle/test-resolver/index.d.ts.map +1 -0
  51. package/dest/oracle/test-resolver/index.js +32 -0
  52. package/dest/oracle/test-resolver/resolver.d.ts +48 -0
  53. package/dest/oracle/test-resolver/resolver.d.ts.map +1 -0
  54. package/dest/oracle/test-resolver/resolver.js +181 -0
  55. package/dest/oracle/txe_oracle_public_context.d.ts +40 -16
  56. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  57. package/dest/oracle/txe_oracle_public_context.js +65 -17
  58. package/dest/oracle/txe_oracle_registry.d.ts +169 -0
  59. package/dest/oracle/txe_oracle_registry.d.ts.map +1 -0
  60. package/dest/oracle/txe_oracle_registry.js +745 -0
  61. package/dest/oracle/txe_oracle_top_level_context.d.ts +55 -29
  62. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
  63. package/dest/oracle/txe_oracle_top_level_context.js +322 -104
  64. package/dest/oracle/txe_oracle_version.d.ts +17 -0
  65. package/dest/oracle/txe_oracle_version.d.ts.map +1 -0
  66. package/dest/oracle/txe_oracle_version.js +14 -0
  67. package/dest/oracle/txe_private_execution_oracle.d.ts +17 -0
  68. package/dest/oracle/txe_private_execution_oracle.d.ts.map +1 -0
  69. package/dest/oracle/txe_private_execution_oracle.js +15 -0
  70. package/dest/rpc_server.d.ts +14 -0
  71. package/dest/rpc_server.d.ts.map +1 -0
  72. package/dest/rpc_server.js +78 -0
  73. package/dest/rpc_translator.d.ts +112 -222
  74. package/dest/rpc_translator.d.ts.map +1 -1
  75. package/dest/rpc_translator.js +877 -600
  76. package/dest/server.bundle.js +3 -0
  77. package/dest/server.bundle.js.map +7 -0
  78. package/dest/state_machine/archiver.d.ts +7 -6
  79. package/dest/state_machine/archiver.d.ts.map +1 -1
  80. package/dest/state_machine/archiver.js +31 -22
  81. package/dest/state_machine/dummy_p2p_client.d.ts +29 -16
  82. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  83. package/dest/state_machine/dummy_p2p_client.js +53 -20
  84. package/dest/state_machine/global_variable_builder.d.ts +10 -6
  85. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  86. package/dest/state_machine/global_variable_builder.js +8 -5
  87. package/dest/state_machine/index.d.ts +13 -7
  88. package/dest/state_machine/index.d.ts.map +1 -1
  89. package/dest/state_machine/index.js +75 -21
  90. package/dest/state_machine/mock_epoch_cache.d.ts +21 -4
  91. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  92. package/dest/state_machine/mock_epoch_cache.js +35 -3
  93. package/dest/state_machine/synchronizer.d.ts +9 -6
  94. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  95. package/dest/state_machine/synchronizer.js +10 -6
  96. package/dest/txe_session.d.ts +89 -16
  97. package/dest/txe_session.d.ts.map +1 -1
  98. package/dest/txe_session.js +366 -58
  99. package/dest/utils/block_creation.d.ts +6 -6
  100. package/dest/utils/block_creation.d.ts.map +1 -1
  101. package/dest/utils/block_creation.js +9 -7
  102. package/dest/utils/encoding.d.ts +192 -0
  103. package/dest/utils/encoding.d.ts.map +1 -0
  104. package/dest/{util → utils}/encoding.js +7 -2
  105. package/dest/{util → utils}/expected_failure_error.d.ts +1 -1
  106. package/dest/utils/expected_failure_error.d.ts.map +1 -0
  107. package/dest/utils/tx_effect_creation.d.ts +1 -1
  108. package/dest/utils/tx_effect_creation.d.ts.map +1 -1
  109. package/dest/utils/tx_effect_creation.js +0 -1
  110. package/dest/{util → utils}/txe_account_store.d.ts +1 -1
  111. package/dest/utils/txe_account_store.d.ts.map +1 -0
  112. package/dest/utils/txe_artifact_resolver.d.ts +37 -0
  113. package/dest/utils/txe_artifact_resolver.d.ts.map +1 -0
  114. package/dest/utils/txe_artifact_resolver.js +161 -0
  115. package/dest/utils/txe_public_contract_data_source.d.ts +20 -0
  116. package/dest/utils/txe_public_contract_data_source.d.ts.map +1 -0
  117. package/dest/utils/txe_public_contract_data_source.js +51 -0
  118. package/dest/worker.bundle.js +3 -0
  119. package/dest/worker.bundle.js.map +7 -0
  120. package/dest/worker.d.ts +2 -0
  121. package/dest/worker.d.ts.map +1 -0
  122. package/dest/worker.js +92 -0
  123. package/package.json +38 -21
  124. package/src/bin/check_txe_oracle_version.ts +70 -0
  125. package/src/bin/index.ts +11 -2
  126. package/src/bin/oracle_test_server.ts +51 -0
  127. package/src/constants.ts +11 -1
  128. package/src/dispatcher_pool.ts +317 -0
  129. package/src/index.ts +99 -190
  130. package/src/msgpackr_fr_extension.ts +23 -0
  131. package/src/oracle/interfaces.ts +64 -35
  132. package/src/oracle/test-resolver/default_fixtures.ts +282 -0
  133. package/src/oracle/test-resolver/index.ts +44 -0
  134. package/src/oracle/test-resolver/resolver.ts +245 -0
  135. package/src/oracle/txe_oracle_public_context.ts +80 -20
  136. package/src/oracle/txe_oracle_registry.ts +536 -0
  137. package/src/oracle/txe_oracle_top_level_context.ts +430 -168
  138. package/src/oracle/txe_oracle_version.ts +17 -0
  139. package/src/oracle/txe_private_execution_oracle.ts +30 -0
  140. package/src/rpc_server.ts +87 -0
  141. package/src/rpc_translator.ts +1087 -974
  142. package/src/state_machine/archiver.ts +45 -26
  143. package/src/state_machine/dummy_p2p_client.ts +83 -32
  144. package/src/state_machine/global_variable_builder.ts +12 -11
  145. package/src/state_machine/index.ts +105 -40
  146. package/src/state_machine/mock_epoch_cache.ts +45 -4
  147. package/src/state_machine/synchronizer.ts +13 -7
  148. package/src/txe_session.ts +609 -128
  149. package/src/utils/block_creation.ts +10 -7
  150. package/src/{util → utils}/encoding.ts +8 -2
  151. package/src/utils/tx_effect_creation.ts +0 -2
  152. package/src/utils/txe_artifact_resolver.ts +217 -0
  153. package/src/utils/txe_public_contract_data_source.ts +60 -0
  154. package/src/worker.ts +98 -0
  155. package/dest/util/encoding.d.ts +0 -720
  156. package/dest/util/encoding.d.ts.map +0 -1
  157. package/dest/util/expected_failure_error.d.ts.map +0 -1
  158. package/dest/util/txe_account_store.d.ts.map +0 -1
  159. package/dest/util/txe_contract_store.d.ts +0 -12
  160. package/dest/util/txe_contract_store.d.ts.map +0 -1
  161. package/dest/util/txe_contract_store.js +0 -22
  162. package/dest/util/txe_public_contract_data_source.d.ts +0 -21
  163. package/dest/util/txe_public_contract_data_source.d.ts.map +0 -1
  164. package/dest/util/txe_public_contract_data_source.js +0 -67
  165. package/src/util/txe_contract_store.ts +0 -36
  166. package/src/util/txe_public_contract_data_source.ts +0 -86
  167. /package/dest/{util → utils}/expected_failure_error.js +0 -0
  168. /package/dest/{util → utils}/txe_account_store.js +0 -0
  169. /package/src/{util → utils}/expected_failure_error.ts +0 -0
  170. /package/src/{util → utils}/txe_account_store.ts +0 -0
@@ -1,29 +1,31 @@
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_PRIVATE_LOGS_PER_TX, 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';
8
- import { ExecutionNoteCache, ExecutionTaggingIndexCache, HashedValuesCache, Oracle, PrivateExecutionOracle, UtilityExecutionOracle, executePrivateFunction, generateSimulatedProvingResult } from '@aztec/pxe/simulator';
7
+ import { AnchoredContractData, CapsuleService, FactService, ORACLE_VERSION_MAJOR, composeHooks, enrichPublicSimulationError } from '@aztec/pxe/server';
8
+ import { CONTRACT_INSTANCE, ExecutionNoteCache, ExecutionTaggingIndexCache, HashedValuesCache, PrivateExecutionOracle, TransientArrayService, UtilityExecutionOracle, buildACIRCallback, executePrivateFunction, generateSimulatedProvingResult } from '@aztec/pxe/simulator';
9
9
  import { ExecutionError, WASMSimulator, createSimulationError, extractCallStack, resolveAssertionMessageFromError, toACVMWitness, witnessMapToFields } from '@aztec/simulator/client';
10
- import { CppPublicTxSimulator, GuardedMerkleTreeOperations, PublicContractsDB, PublicProcessor } from '@aztec/simulator/server';
10
+ import { GuardedMerkleTreeOperations, PublicContractsDB, PublicProcessor, PublicTxSimulator } from '@aztec/simulator/server';
11
11
  import { FunctionCall, FunctionSelector, FunctionType } from '@aztec/stdlib/abi';
12
12
  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
+ import { deriveKeys, hashPublicKey } from '@aztec/stdlib/keys';
20
+ import { L1Actor, L1ToL2Message, L2Actor } from '@aztec/stdlib/messaging';
19
21
  import { ChonkProof } from '@aztec/stdlib/proofs';
20
22
  import { makeGlobalVariables } from '@aztec/stdlib/testing';
21
23
  import { MerkleTreeId } from '@aztec/stdlib/trees';
22
24
  import { CallContext, HashedValues, PrivateExecutionResult, Tx, TxConstantData, TxContext, TxEffect, TxHash, collectNested } from '@aztec/stdlib/tx';
23
- import { ForkCheckpoint } from '@aztec/world-state';
24
- import { DEFAULT_ADDRESS } from '../constants.js';
25
- import { TXEPublicContractDataSource } from '../util/txe_public_contract_data_source.js';
25
+ import { ForkCheckpoint } from '@aztec/world-state/native';
26
+ import { DEFAULT_ADDRESS, MAX_PRIVATE_EVENTS_PER_TXE_QUERY, MAX_PRIVATE_EVENT_LEN } from '../constants.js';
26
27
  import { getSingleTxBlockRequestHash, insertTxEffectIntoWorldTrees, makeTXEBlock } from '../utils/block_creation.js';
28
+ import { TXEPublicContractDataSource } from '../utils/txe_public_contract_data_source.js';
27
29
  export class TXEOracleTopLevelContext {
28
30
  stateMachine;
29
31
  contractStore;
@@ -33,18 +35,22 @@ export class TXEOracleTopLevelContext {
33
35
  accountStore;
34
36
  senderTaggingStore;
35
37
  recipientTaggingStore;
36
- senderAddressBookStore;
38
+ taggingSecretSourcesStore;
37
39
  capsuleStore;
40
+ factStore;
38
41
  privateEventStore;
39
- jobId;
40
42
  nextBlockTimestamp;
41
43
  version;
42
44
  chainId;
43
45
  authwits;
46
+ taggingSecretStrategy;
47
+ artifactResolver;
48
+ rootPath;
49
+ packageName;
44
50
  isMisc;
45
51
  isTxe;
46
52
  logger;
47
- constructor(stateMachine, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, senderAddressBookStore, capsuleStore, privateEventStore, jobId, nextBlockTimestamp, version, chainId, authwits){
53
+ constructor(stateMachine, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, taggingSecretSourcesStore, capsuleStore, factStore, privateEventStore, nextBlockTimestamp, version, chainId, authwits, taggingSecretStrategy, artifactResolver, rootPath, packageName){
48
54
  this.stateMachine = stateMachine;
49
55
  this.contractStore = contractStore;
50
56
  this.noteStore = noteStore;
@@ -53,67 +59,104 @@ export class TXEOracleTopLevelContext {
53
59
  this.accountStore = accountStore;
54
60
  this.senderTaggingStore = senderTaggingStore;
55
61
  this.recipientTaggingStore = recipientTaggingStore;
56
- this.senderAddressBookStore = senderAddressBookStore;
62
+ this.taggingSecretSourcesStore = taggingSecretSourcesStore;
57
63
  this.capsuleStore = capsuleStore;
64
+ this.factStore = factStore;
58
65
  this.privateEventStore = privateEventStore;
59
- this.jobId = jobId;
60
66
  this.nextBlockTimestamp = nextBlockTimestamp;
61
67
  this.version = version;
62
68
  this.chainId = chainId;
63
69
  this.authwits = authwits;
70
+ this.taggingSecretStrategy = taggingSecretStrategy;
71
+ this.artifactResolver = artifactResolver;
72
+ this.rootPath = rootPath;
73
+ this.packageName = packageName;
64
74
  this.isMisc = true;
65
75
  this.isTxe = true;
66
76
  this.logger = createLogger('txe:top_level_context');
67
77
  this.logger.debug('Entering Top Level Context');
68
78
  }
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}'.`);
79
+ contractOracleVersion;
80
+ assertCompatibleOracleVersion(major, minor) {
81
+ if (major !== ORACLE_VERSION_MAJOR) {
82
+ 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.';
83
+ 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
84
  }
85
+ this.contractOracleVersion = {
86
+ major,
87
+ minor
88
+ };
89
+ }
90
+ // Prefixed with "nonOracleFunction" as it is not used as an oracle handler.
91
+ nonOracleFunctionGetContractOracleVersion() {
92
+ return this.contractOracleVersion;
73
93
  }
74
94
  // This is typically only invoked in private contexts, but it is convenient to also have it in top-level for testing
75
95
  // setup.
76
- utilityGetRandomField() {
96
+ getRandomField() {
77
97
  return Fr.random();
78
98
  }
79
99
  // 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) {
100
+ log(level, message, _fieldsSize, fields) {
81
101
  if (!LogLevels[level]) {
82
- throw new Error(`Invalid debug log level: ${level}`);
102
+ throw new Error(`Invalid log level: ${level}`);
83
103
  }
84
104
  const levelName = LogLevels[level];
85
105
  this.logger[levelName](`${applyStringFormatting(message, fields)}`, {
86
106
  module: `${this.logger.module}:debug_log`
87
107
  });
108
+ return Promise.resolve();
88
109
  }
89
- txeGetDefaultAddress() {
110
+ getDefaultAddress() {
90
111
  return DEFAULT_ADDRESS;
91
112
  }
92
- async txeGetNextBlockNumber() {
113
+ async getNextBlockNumber() {
93
114
  return BlockNumber(await this.getLastBlockNumber() + 1);
94
115
  }
95
- txeGetNextBlockTimestamp() {
116
+ getNextBlockTimestamp() {
96
117
  return Promise.resolve(this.nextBlockTimestamp);
97
118
  }
98
- async txeGetLastBlockTimestamp() {
99
- return (await this.stateMachine.node.getBlockHeader('latest')).globalVariables.timestamp;
119
+ async getLastBlockTimestamp() {
120
+ return (await this.stateMachine.node.getBlockData('latest')).header.globalVariables.timestamp;
100
121
  }
101
- async txeGetLastTxEffects() {
122
+ async getLastTxEffects() {
102
123
  const latestBlockNumber = await this.stateMachine.archiver.getBlockNumber();
103
- const block = await this.stateMachine.archiver.getBlock(latestBlockNumber);
124
+ const block = await this.stateMachine.archiver.getBlock({
125
+ number: latestBlockNumber
126
+ });
104
127
  if (block.body.txEffects.length != 1) {
105
128
  // Note that calls like env.mine() will result in blocks with no transactions, hitting this
106
129
  throw new Error(`Expected a single transaction in the last block, found ${block.body.txEffects.length}`);
107
130
  }
108
131
  const txEffects = block.body.txEffects[0];
132
+ const privateLogs = txEffects.privateLogs;
133
+ if (privateLogs.length > MAX_PRIVATE_LOGS_PER_TX) {
134
+ throw new Error(`${privateLogs.length} private logs exceed max ${MAX_PRIVATE_LOGS_PER_TX}`);
135
+ }
109
136
  return {
110
137
  txHash: txEffects.txHash,
111
138
  noteHashes: txEffects.noteHashes,
112
- nullifiers: txEffects.nullifiers
139
+ nullifiers: txEffects.nullifiers,
140
+ privateLogs
113
141
  };
114
142
  }
115
- async txeGetPrivateEvents(selector, contractAddress, scope) {
116
- return (await this.privateEventStore.getPrivateEvents(selector, {
143
+ async syncContractNonOracleMethod(contractAddress, scope, jobId) {
144
+ if (contractAddress.equals(DEFAULT_ADDRESS)) {
145
+ this.logger.debug(`Skipping sync in getPrivateEvents because the events correspond to the default address.`);
146
+ return;
147
+ }
148
+ const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
149
+ await this.stateMachine.contractSyncService.ensureContractSynced(contractAddress, null, async (call, execScopes)=>{
150
+ await this.executeUtilityCall(call, {
151
+ scopes: execScopes,
152
+ jobId
153
+ });
154
+ }, blockHeader, jobId, [
155
+ scope
156
+ ]);
157
+ }
158
+ async getPrivateEvents(selector, contractAddress, scope) {
159
+ const events = (await this.privateEventStore.getPrivateEvents(selector, {
117
160
  contractAddress,
118
161
  scopes: [
119
162
  scope
@@ -121,63 +164,109 @@ export class TXEOracleTopLevelContext {
121
164
  fromBlock: 0,
122
165
  toBlock: await this.getLastBlockNumber() + 1
123
166
  })).map((e)=>e.packedEvent);
167
+ if (events.length > MAX_PRIVATE_EVENTS_PER_TXE_QUERY) {
168
+ throw new Error(`Array of length ${events.length} larger than maxLen ${MAX_PRIVATE_EVENTS_PER_TXE_QUERY}`);
169
+ }
170
+ if (events.some((e)=>e.length > MAX_PRIVATE_EVENT_LEN)) {
171
+ throw new Error(`Some private event has length larger than maxLen ${MAX_PRIVATE_EVENT_LEN}`);
172
+ }
173
+ return events;
124
174
  }
125
- async txeAdvanceBlocksBy(blocks) {
175
+ async advanceBlocksBy(blocks) {
126
176
  this.logger.debug(`time traveling ${blocks} blocks`);
127
177
  for(let i = 0; i < blocks; i++){
128
178
  await this.mineBlock();
129
179
  }
130
180
  }
131
- txeAdvanceTimestampBy(duration) {
181
+ advanceTimestampBy(duration) {
132
182
  this.logger.debug(`time traveling ${duration} seconds`);
133
183
  this.nextBlockTimestamp += duration;
134
184
  }
135
- async txeDeploy(artifact, instance, secret) {
185
+ deploymentNullifier(address) {
186
+ return siloNullifier(AztecAddress.fromNumberUnsafe(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS), address.toField());
187
+ }
188
+ async deploy(contractPath, initializer, args, secret, salt, deployer) {
189
+ const { artifact, instance } = await this.artifactResolver.resolveDeployArtifact({
190
+ rootPath: this.rootPath,
191
+ packageName: this.packageName,
192
+ contractPath,
193
+ initializer,
194
+ args,
195
+ secret,
196
+ salt,
197
+ deployer
198
+ });
136
199
  // Emit deployment nullifier
137
200
  await this.mineBlock({
138
201
  nullifiers: [
139
- await siloNullifier(AztecAddress.fromNumber(CONTRACT_INSTANCE_REGISTRY_CONTRACT_ADDRESS), instance.address.toField())
202
+ await this.deploymentNullifier(instance.address)
140
203
  ]
141
204
  });
142
205
  if (!secret.equals(Fr.ZERO)) {
143
- await this.txeAddAccount(artifact, instance, secret);
206
+ await this.registerContractAndAddAccount(artifact, instance, secret);
144
207
  } else {
145
208
  await this.contractStore.addContractInstance(instance);
146
- await this.contractStore.addContractArtifact(instance.currentContractClassId, artifact);
209
+ await this.contractStore.addContractArtifact(artifact);
147
210
  this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`);
148
211
  }
212
+ return CONTRACT_INSTANCE.serialization.fn(instance).flat();
213
+ }
214
+ /**
215
+ * Mines a single block containing only the deployment nullifiers for the contracts at the given addresses.
216
+ */ async mineDeploymentNullifiers(addresses) {
217
+ await this.mineBlock({
218
+ nullifiers: await Promise.all(addresses.map((address)=>this.deploymentNullifier(address)))
219
+ });
220
+ }
221
+ async addAccount(secret) {
222
+ const { artifact, instance } = await this.artifactResolver.resolveAccountArtifact(secret);
223
+ return this.registerContractAndAddAccount(artifact, instance, secret);
149
224
  }
150
- async txeAddAccount(artifact, instance, secret) {
225
+ async registerContractAndAddAccount(artifact, instance, secret) {
151
226
  const partialAddress = await computePartialAddress(instance);
152
227
  this.logger.debug(`Deployed ${artifact.name} at ${instance.address}`);
153
228
  await this.contractStore.addContractInstance(instance);
154
- await this.contractStore.addContractArtifact(instance.currentContractClassId, artifact);
155
- const completeAddress = await this.keyStore.addAccount(secret, partialAddress);
229
+ await this.contractStore.addContractArtifact(artifact);
230
+ const completeAddress = await this.keyStore.addAccount(await deriveKeys(secret), partialAddress);
156
231
  await this.accountStore.setAccount(completeAddress.address, completeAddress);
157
232
  await this.addressStore.addCompleteAddress(completeAddress);
158
233
  this.logger.debug(`Created account ${completeAddress.address}`);
159
234
  return completeAddress;
160
235
  }
161
- async txeCreateAccount(secret) {
236
+ async createAccount(secret) {
162
237
  // This is a foot gun !
163
- const completeAddress = await this.keyStore.addAccount(secret, secret);
238
+ const completeAddress = await this.keyStore.addAccount(await deriveKeys(secret), secret);
164
239
  await this.accountStore.setAccount(completeAddress.address, completeAddress);
165
240
  await this.addressStore.addCompleteAddress(completeAddress);
166
241
  this.logger.debug(`Created account ${completeAddress.address}`);
167
242
  return completeAddress;
168
243
  }
169
- async txeAddAuthWitness(address, messageHash) {
244
+ async addAuthWitness(address, messageHash) {
170
245
  const account = await this.accountStore.getAccount(address);
171
- const privateKey = await this.keyStore.getMasterSecretKey(account.publicKeys.masterIncomingViewingPublicKey);
246
+ const ivpkMHash = await hashPublicKey(account.publicKeys.ivpkM);
247
+ const privateKey = await this.keyStore.getMasterSecretKey(ivpkMHash);
172
248
  const schnorr = new Schnorr();
173
- const signature = await schnorr.constructSignature(messageHash.toBuffer(), privateKey);
174
- const authWitness = new AuthWitness(messageHash, [
175
- ...signature.toBuffer()
176
- ]);
249
+ const signature = await schnorr.constructSignature(messageHash, privateKey);
250
+ const authWitness = new AuthWitness(messageHash, signature.toLimbFields());
177
251
  this.authwits.set(authWitness.requestHash.toString(), authWitness);
178
252
  }
253
+ setTaggingSecretStrategy(strategy) {
254
+ this.taggingSecretStrategy = strategy.value;
255
+ }
256
+ async sendL1ToL2Message(content, secretHash, sender, recipient) {
257
+ // Messages are appended to the tree, so the next free slot is simply the current tree size.
258
+ const { size } = await this.stateMachine.synchronizer.getCommitted().getTreeInfo(MerkleTreeId.L1_TO_L2_MESSAGE_TREE);
259
+ const leafIndex = new Fr(size);
260
+ const message = new L1ToL2Message(new L1Actor(sender, this.chainId.toNumber()), new L2Actor(recipient, this.version.toNumber()), content, secretHash, leafIndex);
261
+ await this.mineBlock({
262
+ l1ToL2Messages: [
263
+ message.hash()
264
+ ]
265
+ });
266
+ return leafIndex;
267
+ }
179
268
  async mineBlock(options = {}) {
180
- const blockNumber = await this.txeGetNextBlockNumber();
269
+ const blockNumber = await this.getNextBlockNumber();
181
270
  const txEffect = TxEffect.empty();
182
271
  txEffect.nullifiers = [
183
272
  getSingleTxBlockRequestHash(blockNumber),
@@ -185,7 +274,7 @@ export class TXEOracleTopLevelContext {
185
274
  ];
186
275
  txEffect.txHash = new TxHash(new Fr(blockNumber));
187
276
  const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
188
- await insertTxEffectIntoWorldTrees(txEffect, forkedWorldTrees);
277
+ await insertTxEffectIntoWorldTrees(txEffect, forkedWorldTrees, options.l1ToL2Messages ?? []);
189
278
  const globals = makeGlobalVariables(undefined, {
190
279
  blockNumber,
191
280
  timestamp: this.nextBlockTimestamp,
@@ -197,27 +286,33 @@ export class TXEOracleTopLevelContext {
197
286
  ]);
198
287
  await forkedWorldTrees.close();
199
288
  this.logger.info(`Created block ${blockNumber} with timestamp ${block.header.globalVariables.timestamp}`);
200
- await this.stateMachine.handleL2Block(block);
289
+ await this.stateMachine.handleL2Block(block, options.l1ToL2Messages ?? []);
201
290
  }
202
- async txePrivateCallNewFlow(from, targetContractAddress = AztecAddress.zero(), functionSelector = FunctionSelector.empty(), args, argsHash = Fr.zero(), isStaticCall = false) {
203
- this.logger.verbose(`Executing external function ${await this.contractStore.getDebugFunctionName(targetContractAddress, functionSelector)}@${targetContractAddress} isStaticCall=${isStaticCall}`);
204
- const artifact = await this.contractStore.getFunctionArtifact(targetContractAddress, functionSelector);
291
+ async privateCallNewFlow(from, targetContractAddress = AztecAddress.zero(), functionSelector = FunctionSelector.empty(), args, argsHash = Fr.zero(), isStaticCall = false, additionalScopes = [], jobId, authorizedUtilityCallTargets, gasSettings) {
292
+ const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
293
+ const anchoredContractData = new AnchoredContractData(this.contractStore, this.stateMachine.contractClassService, blockHeader);
294
+ this.logger.verbose(`Executing external function ${await anchoredContractData.getDebugFunctionName(targetContractAddress, functionSelector)}@${targetContractAddress} isStaticCall=${isStaticCall}`);
295
+ const artifact = await anchoredContractData.getFunctionArtifact(targetContractAddress, functionSelector);
205
296
  if (!artifact) {
206
297
  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
298
  throw new Error(message);
208
299
  }
300
+ const scopes = from === undefined ? additionalScopes : [
301
+ from,
302
+ ...additionalScopes
303
+ ];
209
304
  // Sync notes before executing private function to discover notes from previous transactions
210
- const utilityExecutor = async (call)=>{
211
- await this.executeUtilityCall(call);
305
+ const utilityExecutor = async (call, execScopes)=>{
306
+ await this.executeUtilityCall(call, {
307
+ scopes: execScopes,
308
+ jobId
309
+ });
212
310
  };
213
- await this.contractStore.syncPrivateState(targetContractAddress, 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());
311
+ await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress, functionSelector, utilityExecutor, blockHeader, jobId, scopes);
312
+ const blockNumber = await this.getNextBlockNumber();
313
+ const msgSender = from ?? AztecAddress.NULL_MSG_SENDER;
314
+ const callContext = new CallContext(msgSender, targetContractAddress, functionSelector, isStaticCall);
219
315
  const txContext = new TxContext(this.chainId, this.version, gasSettings);
220
- const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
221
316
  const protocolNullifier = await computeProtocolNullifier(getSingleTxBlockRequestHash(blockNumber));
222
317
  const noteCache = new ExecutionNoteCache(protocolNullifier);
223
318
  // In production, the account contract sets the min revertible counter before calling the app function.
@@ -227,12 +322,52 @@ export class TXEOracleTopLevelContext {
227
322
  await noteCache.setMinRevertibleSideEffectCounter(minRevertibleSideEffectCounter);
228
323
  const taggingIndexCache = new ExecutionTaggingIndexCache();
229
324
  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);
325
+ const transientArrayService = new TransientArrayService();
326
+ const taggingSecretStrategy = this.taggingSecretStrategy;
327
+ const privateExecutionOracle = new PrivateExecutionOracle({
328
+ argsHash,
329
+ txContext,
330
+ txRequestSalt: Fr.ZERO,
331
+ callContext,
332
+ anchorBlockHeader: blockHeader,
333
+ utilityExecutor,
334
+ authWitnesses: Array.from(this.authwits.values()),
335
+ capsules: [],
336
+ executionCache: HashedValuesCache.create([
337
+ new HashedValues(args, argsHash)
338
+ ]),
339
+ noteCache,
340
+ taggingIndexCache,
341
+ anchoredContractData,
342
+ noteStore: this.noteStore,
343
+ keyStore: this.keyStore,
344
+ addressStore: this.addressStore,
345
+ aztecNode: this.stateMachine.node,
346
+ senderTaggingStore: this.senderTaggingStore,
347
+ recipientTaggingStore: this.recipientTaggingStore,
348
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
349
+ capsuleService: new CapsuleService(this.capsuleStore, scopes),
350
+ factService: new FactService(this.factStore, scopes),
351
+ privateEventStore: this.privateEventStore,
352
+ contractSyncService: this.stateMachine.contractSyncService,
353
+ jobId,
354
+ totalPublicCalldataCount: 0,
355
+ sideEffectCounter: minRevertibleSideEffectCounter,
356
+ scopes,
357
+ // In TXE, the typical transaction entrypoint is skipped, so we need to simulate the actions that such a
358
+ // contract would perform, including setting senderForTags.
359
+ senderForTags: from,
360
+ simulator,
361
+ txResolver: this.stateMachine.txResolver,
362
+ l2TipsStore: this.stateMachine.l2TipsProvider,
363
+ hooks: composeHooks({
364
+ authorizeUtilityCall: this.buildAuthorizeUtilityCallHook(isStaticCall ? 'private view' : 'private', authorizedUtilityCallTargets),
365
+ // Only configure the hook when a strategy was explicitly set, so that otherwise the default tagging secret
366
+ // strategy is exercised.
367
+ resolveTaggingSecretStrategy: taggingSecretStrategy ? ()=>Promise.resolve(taggingSecretStrategy) : undefined
368
+ }),
369
+ transientArrayService
370
+ });
236
371
  // 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
372
  let result;
238
373
  let executionResult;
@@ -244,10 +379,9 @@ export class TXEOracleTopLevelContext {
244
379
  r.publicInputs.publicTeardownCallRequest
245
380
  ]));
246
381
  const publicFunctionsCalldata = await Promise.all(publicCallRequests.map(async (r)=>{
247
- const calldata = await privateExecutionOracle.privateLoadFromExecutionCache(r.calldataHash);
382
+ const calldata = await privateExecutionOracle.getHashPreimage(r.calldataHash);
248
383
  return new HashedValues(calldata, r.calldataHash);
249
384
  }));
250
- noteCache.finish();
251
385
  const nonceGenerator = noteCache.getNonceGenerator();
252
386
  result = new PrivateExecutionResult(executionResult, nonceGenerator, publicFunctionsCalldata);
253
387
  } catch (err) {
@@ -256,7 +390,7 @@ export class TXEOracleTopLevelContext {
256
390
  // According to the protocol rules, there must be at least one nullifier in the tx. The first nullifier is used as
257
391
  // the nonce generator for the note hashes.
258
392
  // We pass the non-zero minRevertibleSideEffectCounter to make sure the side effects are split correctly.
259
- const { publicInputs } = await generateSimulatedProvingResult(result, this.contractStore, minRevertibleSideEffectCounter);
393
+ const { publicInputs } = await generateSimulatedProvingResult(result, (addr, sel)=>anchoredContractData.getDebugFunctionName(addr, sel), this.stateMachine.node, minRevertibleSideEffectCounter);
260
394
  const globals = makeGlobalVariables();
261
395
  globals.blockNumber = blockNumber;
262
396
  globals.timestamp = this.nextBlockTimestamp;
@@ -264,7 +398,8 @@ export class TXEOracleTopLevelContext {
264
398
  globals.version = this.version;
265
399
  globals.gasFees = GasFees.empty();
266
400
  const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
267
- const contractsDB = new PublicContractsDB(new TXEPublicContractDataSource(blockNumber, this.contractStore));
401
+ const bindings = this.logger.getBindings();
402
+ const contractsDB = new PublicContractsDB(new TXEPublicContractDataSource(blockNumber, this.contractStore), bindings);
268
403
  const guardedMerkleTrees = new GuardedMerkleTreeOperations(forkedWorldTrees);
269
404
  const config = PublicSimulatorConfig.from({
270
405
  skipFeeEnforcement: true,
@@ -273,7 +408,7 @@ export class TXEOracleTopLevelContext {
273
408
  collectStatistics: false,
274
409
  collectCallMetadata: true
275
410
  });
276
- const processor = new PublicProcessor(globals, guardedMerkleTrees, contractsDB, new CppPublicTxSimulator(guardedMerkleTrees, contractsDB, globals, config), new TestDateProvider());
411
+ const processor = new PublicProcessor(globals, guardedMerkleTrees, contractsDB, new PublicTxSimulator(guardedMerkleTrees, contractsDB, globals, config, bindings), new TestDateProvider(), undefined, createLogger('simulator:public-processor', bindings));
277
412
  const tx = await Tx.create({
278
413
  data: publicInputs,
279
414
  chonkProof: ChonkProof.empty(),
@@ -294,7 +429,7 @@ export class TXEOracleTopLevelContext {
294
429
  } else if (!processedTx.revertCode.isOK()) {
295
430
  if (processedTx.revertReason) {
296
431
  try {
297
- await enrichPublicSimulationError(processedTx.revertReason, this.contractStore, this.logger);
432
+ await enrichPublicSimulationError(processedTx.revertReason, this.contractStore, this.stateMachine.contractClassService, await this.stateMachine.anchorBlockStore.getBlockHeader(), this.logger);
298
433
  // eslint-disable-next-line no-empty
299
434
  } catch {}
300
435
  throw new Error(`Contract execution has reverted: ${processedTx.revertReason.getMessage()}`);
@@ -302,10 +437,20 @@ export class TXEOracleTopLevelContext {
302
437
  throw new Error('Contract execution has reverted');
303
438
  }
304
439
  }
440
+ // Walk the nested private-call tree and collect every offchain effect the transaction emitted.
441
+ // PXE stores these on each `PrivateCallExecutionResult` and they never reach TXE via the
442
+ // `aztec_utl_emitOffchainEffect` foreign-call path (that path only fires at the top-level), so
443
+ // we pull them out here and the RPC wrapper will hand them to `TXESession` for buffering.
444
+ const offchainEffects = collectNested([
445
+ executionResult
446
+ ], (r)=>r.offchainEffects.map((e)=>e.data));
305
447
  if (isStaticCall) {
306
448
  await checkpoint.revert();
307
449
  await forkedWorldTrees.close();
308
- return executionResult.returnValues ?? [];
450
+ return {
451
+ returnValues: executionResult.returnValues ?? [],
452
+ offchainEffects
453
+ };
309
454
  }
310
455
  const txEffect = TxEffect.empty();
311
456
  txEffect.noteHashes = processedTx.txEffect.noteHashes;
@@ -321,16 +466,17 @@ export class TXEOracleTopLevelContext {
321
466
  ]);
322
467
  await this.stateMachine.handleL2Block(l2Block);
323
468
  await forkedWorldTrees.close();
324
- return executionResult.returnValues ?? [];
469
+ return {
470
+ returnValues: executionResult.returnValues ?? [],
471
+ offchainEffects
472
+ };
325
473
  }
326
- async txePublicCallNewFlow(from, targetContractAddress, calldata, isStaticCall) {
327
- 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());
332
- const txContext = new TxContext(this.chainId, this.version, gasSettings);
474
+ async publicCallNewFlow(from, targetContractAddress, calldata, isStaticCall, gasSettings) {
333
475
  const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
476
+ const anchoredContractData = new AnchoredContractData(this.contractStore, this.stateMachine.contractClassService, anchorBlockHeader);
477
+ this.logger.verbose(`Executing public function ${await anchoredContractData.getDebugFunctionName(targetContractAddress, FunctionSelector.fromField(calldata[0]))}@${targetContractAddress} isStaticCall=${isStaticCall}`);
478
+ const blockNumber = await this.getNextBlockNumber();
479
+ const txContext = new TxContext(this.chainId, this.version, gasSettings);
334
480
  const calldataHash = await computeCalldataHash(calldata);
335
481
  const calldataHashedValues = new HashedValues(calldata, calldataHash);
336
482
  const globals = makeGlobalVariables();
@@ -340,7 +486,8 @@ export class TXEOracleTopLevelContext {
340
486
  globals.version = this.version;
341
487
  globals.gasFees = GasFees.empty();
342
488
  const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
343
- const contractsDB = new PublicContractsDB(new TXEPublicContractDataSource(blockNumber, this.contractStore));
489
+ const bindings2 = this.logger.getBindings();
490
+ const contractsDB = new PublicContractsDB(new TXEPublicContractDataSource(blockNumber, this.contractStore), bindings2);
344
491
  const guardedMerkleTrees = new GuardedMerkleTreeOperations(forkedWorldTrees);
345
492
  const config = PublicSimulatorConfig.from({
346
493
  skipFeeEnforcement: true,
@@ -349,8 +496,8 @@ export class TXEOracleTopLevelContext {
349
496
  collectStatistics: false,
350
497
  collectCallMetadata: true
351
498
  });
352
- const simulator = new CppPublicTxSimulator(guardedMerkleTrees, contractsDB, globals, config);
353
- const processor = new PublicProcessor(globals, guardedMerkleTrees, contractsDB, simulator, new TestDateProvider());
499
+ const simulator = new PublicTxSimulator(guardedMerkleTrees, contractsDB, globals, config, bindings2);
500
+ const processor = new PublicProcessor(globals, guardedMerkleTrees, contractsDB, simulator, new TestDateProvider(), undefined, createLogger('simulator:public-processor', bindings2));
354
501
  // We're simulating a scenario in which private execution immediately enqueues a public call and halts. The private
355
502
  // kernel init would in this case inject a nullifier with the transaction request hash as a non-revertible
356
503
  // side-effect, which the AVM then expects to exist in order to use it as the nonce generator when siloing notes as
@@ -360,10 +507,10 @@ export class TXEOracleTopLevelContext {
360
507
  // The enqueued public call itself we make be revertible so that the public execution is itself revertible, as tests
361
508
  // may require producing reverts.
362
509
  const revertibleAccumulatedData = PrivateToPublicAccumulatedData.empty();
363
- revertibleAccumulatedData.publicCallRequests[0] = new PublicCallRequest(from, targetContractAddress, isStaticCall, calldataHash);
510
+ revertibleAccumulatedData.publicCallRequests[0] = new PublicCallRequest(from ?? AztecAddress.NULL_MSG_SENDER, targetContractAddress, isStaticCall, calldataHash);
364
511
  const inputsForPublic = new PartialPrivateTailPublicInputsForPublic(nonRevertibleAccumulatedData, revertibleAccumulatedData, PublicCallRequest.empty());
365
512
  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);
513
+ const txData = new PrivateKernelTailCircuitPublicInputs(constantData, /*gasUsed=*/ new Gas(0, 0), /*feePayer=*/ AztecAddress.zero(), /*expirationTimestamp=*/ 0n, inputsForPublic, undefined);
367
514
  const tx = await Tx.create({
368
515
  data: txData,
369
516
  chonkProof: ChonkProof.empty(),
@@ -386,7 +533,7 @@ export class TXEOracleTopLevelContext {
386
533
  } else if (!processedTx.revertCode.isOK()) {
387
534
  if (processedTx.revertReason) {
388
535
  try {
389
- await enrichPublicSimulationError(processedTx.revertReason, this.contractStore, this.logger);
536
+ await enrichPublicSimulationError(processedTx.revertReason, this.contractStore, this.stateMachine.contractClassService, anchorBlockHeader, this.logger);
390
537
  // eslint-disable-next-line no-empty
391
538
  } catch {}
392
539
  throw new Error(`Contract execution has reverted: ${processedTx.revertReason.getMessage()}`);
@@ -416,20 +563,44 @@ export class TXEOracleTopLevelContext {
416
563
  await forkedWorldTrees.close();
417
564
  return returnValues ?? [];
418
565
  }
419
- async txeSimulateUtilityFunction(targetContractAddress, functionSelector, args) {
420
- const artifact = await this.contractStore.getFunctionArtifact(targetContractAddress, functionSelector);
566
+ async executeUtilityFunction(from, targetContractAddress, functionSelector, args, jobId, authorizedUtilityCallTargets) {
567
+ const blockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
568
+ const anchoredContractData = new AnchoredContractData(this.contractStore, this.stateMachine.contractClassService, blockHeader);
569
+ const artifact = await anchoredContractData.getFunctionArtifact(targetContractAddress, functionSelector);
421
570
  if (!artifact) {
422
571
  throw new Error(`Cannot call ${functionSelector} as there is no artifact found at ${targetContractAddress}.`);
423
572
  }
424
573
  // Sync notes before executing utility function to discover notes from previous transactions
425
- await this.contractStore.syncPrivateState(targetContractAddress, functionSelector, async (call)=>{
426
- await this.executeUtilityCall(call);
574
+ await this.stateMachine.contractSyncService.ensureContractSynced(targetContractAddress, functionSelector, async (call, execScopes)=>{
575
+ await this.executeUtilityCall(call, {
576
+ scopes: execScopes,
577
+ jobId
578
+ });
579
+ }, blockHeader, jobId, await this.keyStore.getAccounts());
580
+ const call = FunctionCall.from({
581
+ name: artifact.name,
582
+ to: targetContractAddress,
583
+ selector: functionSelector,
584
+ type: FunctionType.UTILITY,
585
+ hideMsgSender: false,
586
+ isStatic: false,
587
+ args,
588
+ returnTypes: []
589
+ });
590
+ return this.executeUtilityCall(call, {
591
+ from,
592
+ scopes: await this.keyStore.getAccounts(),
593
+ jobId,
594
+ authorizedUtilityCallTargets
427
595
  });
428
- const call = new FunctionCall(artifact.name, targetContractAddress, functionSelector, FunctionType.UTILITY, false, false, args, []);
429
- return this.executeUtilityCall(call);
430
596
  }
431
- async executeUtilityCall(call) {
432
- const entryPointArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
597
+ async executeUtilityCall(call, { from = AztecAddress.NULL_MSG_SENDER, scopes, jobId, authorizedUtilityCallTargets = [] }) {
598
+ const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
599
+ const anchoredContractData = new AnchoredContractData(this.contractStore, this.stateMachine.contractClassService, anchorBlockHeader);
600
+ const entryPointArtifact = await anchoredContractData.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
601
+ if (!entryPointArtifact) {
602
+ throw new Error(`Cannot run function ${call.selector} on ${call.to}: the contract is not registered.`);
603
+ }
433
604
  if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
434
605
  throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
435
606
  }
@@ -438,9 +609,47 @@ export class TXEOracleTopLevelContext {
438
609
  selector: call.selector
439
610
  });
440
611
  try {
441
- 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)=>{
612
+ const simulator = new WASMSimulator();
613
+ const utilityExecutor = async (syncCall, execScopes)=>{
614
+ await this.executeUtilityCall(syncCall, {
615
+ scopes: execScopes,
616
+ jobId
617
+ });
618
+ };
619
+ const oracle = new UtilityExecutionOracle({
620
+ callContext: CallContext.from({
621
+ msgSender: from,
622
+ contractAddress: call.to,
623
+ functionSelector: call.selector,
624
+ isStaticCall: true
625
+ }),
626
+ authWitnesses: [],
627
+ capsules: [],
628
+ anchorBlockHeader,
629
+ anchoredContractData,
630
+ noteStore: this.noteStore,
631
+ keyStore: this.keyStore,
632
+ addressStore: this.addressStore,
633
+ aztecNode: this.stateMachine.node,
634
+ recipientTaggingStore: this.recipientTaggingStore,
635
+ taggingSecretSourcesStore: this.taggingSecretSourcesStore,
636
+ capsuleService: new CapsuleService(this.capsuleStore, scopes),
637
+ factService: new FactService(this.factStore, scopes),
638
+ privateEventStore: this.privateEventStore,
639
+ txResolver: this.stateMachine.txResolver,
640
+ contractSyncService: this.stateMachine.contractSyncService,
641
+ l2TipsStore: this.stateMachine.l2TipsProvider,
642
+ jobId,
643
+ scopes,
644
+ simulator,
645
+ hooks: composeHooks({
646
+ authorizeUtilityCall: this.buildAuthorizeUtilityCallHook('utility', authorizedUtilityCallTargets)
647
+ }),
648
+ utilityExecutor,
649
+ // Execution-tree root (top-level utility run or contract sync): own store; nested frames inherit it.
650
+ transientArrayService: new TransientArrayService()
651
+ });
652
+ const acirExecutionResult = await simulator.executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, buildACIRCallback(oracle)).catch((err)=>{
444
653
  err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
445
654
  throw new ExecutionError(err.message, {
446
655
  contractAddress: call.to,
@@ -449,21 +658,30 @@ export class TXEOracleTopLevelContext {
449
658
  cause: err
450
659
  });
451
660
  });
452
- this.logger.verbose(`Utility simulation for ${call.to}.${call.selector} completed`);
661
+ this.logger.verbose(`Utility execution for ${call.to}.${call.selector} completed`);
453
662
  return witnessMapToFields(acirExecutionResult.returnWitness);
454
663
  } catch (err) {
455
- throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during utility simulation'));
664
+ throw createSimulationError(err instanceof Error ? err : new Error('Unknown error during utility execution'));
456
665
  }
457
666
  }
458
667
  close() {
459
668
  this.logger.debug('Exiting Top Level Context');
460
669
  return [
461
670
  this.nextBlockTimestamp,
462
- this.authwits
671
+ this.authwits,
672
+ this.taggingSecretStrategy
463
673
  ];
464
674
  }
465
675
  async getLastBlockNumber() {
466
- const header = await this.stateMachine.node.getBlockHeader('latest');
467
- return header ? header.globalVariables.blockNumber : BlockNumber.ZERO;
676
+ const block = await this.stateMachine.node.getBlock('latest');
677
+ return block ? block.header.globalVariables.blockNumber : BlockNumber.ZERO;
678
+ }
679
+ buildAuthorizeUtilityCallHook(callerContext, authorizedTargets) {
680
+ if (authorizedTargets.length === 0) {
681
+ return undefined;
682
+ }
683
+ return (req)=>Promise.resolve({
684
+ authorized: req.callerContext === callerContext && authorizedTargets.some((t)=>t.equals(req.target))
685
+ });
468
686
  }
469
687
  }