@aztec/txe 4.0.0-nightly.20250907 → 4.0.0-nightly.20260108

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 (100) hide show
  1. package/dest/bin/index.d.ts +1 -1
  2. package/dest/bin/index.js +1 -1
  3. package/dest/constants.d.ts +3 -0
  4. package/dest/constants.d.ts.map +1 -0
  5. package/dest/constants.js +2 -0
  6. package/dest/index.d.ts +1 -1
  7. package/dest/index.d.ts.map +1 -1
  8. package/dest/index.js +8 -4
  9. package/dest/oracle/interfaces.d.ts +57 -0
  10. package/dest/oracle/interfaces.d.ts.map +1 -0
  11. package/dest/oracle/interfaces.js +3 -0
  12. package/dest/oracle/txe_oracle_public_context.d.ts +12 -12
  13. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  14. package/dest/oracle/txe_oracle_public_context.js +30 -34
  15. package/dest/oracle/txe_oracle_top_level_context.d.ts +65 -0
  16. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -0
  17. package/dest/oracle/txe_oracle_top_level_context.js +463 -0
  18. package/dest/rpc_translator.d.ts +246 -0
  19. package/dest/rpc_translator.d.ts.map +1 -0
  20. package/dest/{txe_service/txe_service.js → rpc_translator.js} +201 -124
  21. package/dest/state_machine/archiver.d.ts +34 -13
  22. package/dest/state_machine/archiver.d.ts.map +1 -1
  23. package/dest/state_machine/archiver.js +111 -16
  24. package/dest/state_machine/dummy_p2p_client.d.ts +5 -2
  25. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  26. package/dest/state_machine/dummy_p2p_client.js +9 -1
  27. package/dest/state_machine/global_variable_builder.d.ts +6 -17
  28. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  29. package/dest/state_machine/global_variable_builder.js +16 -23
  30. package/dest/state_machine/index.d.ts +5 -5
  31. package/dest/state_machine/index.d.ts.map +1 -1
  32. package/dest/state_machine/index.js +17 -21
  33. package/dest/state_machine/mock_epoch_cache.d.ts +6 -5
  34. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  35. package/dest/state_machine/mock_epoch_cache.js +8 -7
  36. package/dest/state_machine/synchronizer.d.ts +5 -4
  37. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  38. package/dest/state_machine/synchronizer.js +5 -4
  39. package/dest/txe_session.d.ts +42 -46
  40. package/dest/txe_session.d.ts.map +1 -1
  41. package/dest/txe_session.js +241 -93
  42. package/dest/util/encoding.d.ts +623 -24
  43. package/dest/util/encoding.d.ts.map +1 -1
  44. package/dest/util/encoding.js +1 -1
  45. package/dest/util/expected_failure_error.d.ts +1 -1
  46. package/dest/util/expected_failure_error.d.ts.map +1 -1
  47. package/dest/util/txe_account_store.d.ts +10 -0
  48. package/dest/util/txe_account_store.d.ts.map +1 -0
  49. package/dest/util/{txe_account_data_provider.js → txe_account_store.js} +1 -1
  50. package/dest/util/txe_contract_store.d.ts +12 -0
  51. package/dest/util/txe_contract_store.d.ts.map +1 -0
  52. package/dest/util/{txe_contract_data_provider.js → txe_contract_store.js} +4 -4
  53. package/dest/util/txe_public_contract_data_source.d.ts +8 -6
  54. package/dest/util/txe_public_contract_data_source.d.ts.map +1 -1
  55. package/dest/util/txe_public_contract_data_source.js +14 -12
  56. package/dest/utils/block_creation.d.ts +28 -0
  57. package/dest/utils/block_creation.d.ts.map +1 -0
  58. package/dest/utils/block_creation.js +45 -0
  59. package/dest/utils/tx_effect_creation.d.ts +6 -0
  60. package/dest/utils/tx_effect_creation.d.ts.map +1 -0
  61. package/dest/utils/tx_effect_creation.js +16 -0
  62. package/package.json +18 -17
  63. package/src/bin/index.ts +1 -1
  64. package/src/constants.ts +3 -0
  65. package/src/index.ts +20 -20
  66. package/src/oracle/interfaces.ts +86 -0
  67. package/src/oracle/txe_oracle_public_context.ts +37 -75
  68. package/src/oracle/txe_oracle_top_level_context.ts +716 -0
  69. package/src/{txe_service/txe_service.ts → rpc_translator.ts} +261 -125
  70. package/src/state_machine/archiver.ts +147 -29
  71. package/src/state_machine/dummy_p2p_client.ts +13 -2
  72. package/src/state_machine/global_variable_builder.ts +25 -42
  73. package/src/state_machine/index.ts +24 -21
  74. package/src/state_machine/mock_epoch_cache.ts +12 -11
  75. package/src/state_machine/synchronizer.ts +8 -7
  76. package/src/txe_session.ts +416 -115
  77. package/src/util/encoding.ts +1 -1
  78. package/src/util/{txe_account_data_provider.ts → txe_account_store.ts} +1 -1
  79. package/src/util/{txe_contract_data_provider.ts → txe_contract_store.ts} +5 -4
  80. package/src/util/txe_public_contract_data_source.ts +16 -13
  81. package/src/utils/block_creation.ts +94 -0
  82. package/src/utils/tx_effect_creation.ts +38 -0
  83. package/dest/oracle/txe_oracle.d.ts +0 -124
  84. package/dest/oracle/txe_oracle.d.ts.map +0 -1
  85. package/dest/oracle/txe_oracle.js +0 -770
  86. package/dest/oracle/txe_typed_oracle.d.ts +0 -42
  87. package/dest/oracle/txe_typed_oracle.d.ts.map +0 -1
  88. package/dest/oracle/txe_typed_oracle.js +0 -83
  89. package/dest/txe_constants.d.ts +0 -2
  90. package/dest/txe_constants.d.ts.map +0 -1
  91. package/dest/txe_constants.js +0 -7
  92. package/dest/txe_service/txe_service.d.ts +0 -231
  93. package/dest/txe_service/txe_service.d.ts.map +0 -1
  94. package/dest/util/txe_account_data_provider.d.ts +0 -10
  95. package/dest/util/txe_account_data_provider.d.ts.map +0 -1
  96. package/dest/util/txe_contract_data_provider.d.ts +0 -11
  97. package/dest/util/txe_contract_data_provider.d.ts.map +0 -1
  98. package/src/oracle/txe_oracle.ts +0 -1287
  99. package/src/oracle/txe_typed_oracle.ts +0 -142
  100. package/src/txe_constants.ts +0 -9
@@ -1,38 +1,27 @@
1
- import { AztecAddress, Fr } from '@aztec/aztec.js';
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
3
  import { createLogger } from '@aztec/foundation/log';
3
4
  import { KeyStore } from '@aztec/key-store';
4
5
  import { openTmpStore } from '@aztec/kv-store/lmdb-v2';
5
- import { AddressDataProvider, CapsuleDataProvider, NoteDataProvider, PrivateEventDataProvider, TaggingDataProvider } from '@aztec/pxe/server';
6
+ import { AddressStore, CapsuleStore, NoteService, NoteStore, PrivateEventStore, RecipientTaggingStore, SenderAddressBookStore, SenderTaggingStore } from '@aztec/pxe/server';
7
+ import { ExecutionNoteCache, ExecutionTaggingIndexCache, HashedValuesCache, Oracle, PrivateExecutionOracle, UtilityExecutionOracle } from '@aztec/pxe/simulator';
8
+ import { ExecutionError, WASMSimulator, createSimulationError, extractCallStack, resolveAssertionMessageFromError, toACVMWitness } from '@aztec/simulator/client';
9
+ import { FunctionSelector, FunctionType } from '@aztec/stdlib/abi';
10
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
11
+ import { GasSettings } from '@aztec/stdlib/gas';
12
+ import { computeProtocolNullifier } from '@aztec/stdlib/hash';
6
13
  import { makeGlobalVariables } from '@aztec/stdlib/testing';
7
- import { TXE } from './oracle/txe_oracle.js';
14
+ import { CallContext, TxContext } from '@aztec/stdlib/tx';
15
+ import { z } from 'zod';
16
+ import { DEFAULT_ADDRESS } from './constants.js';
8
17
  import { TXEOraclePublicContext } from './oracle/txe_oracle_public_context.js';
18
+ import { TXEOracleTopLevelContext } from './oracle/txe_oracle_top_level_context.js';
19
+ import { RPCTranslator } from './rpc_translator.js';
9
20
  import { TXEStateMachine } from './state_machine/index.js';
10
- import { TXEService } from './txe_service/txe_service.js';
11
- import { TXEAccountDataProvider } from './util/txe_account_data_provider.js';
12
- import { TXEContractDataProvider } from './util/txe_contract_data_provider.js';
13
- /**
14
- * A TXE Session can be ine one of four states, which change as the test progresses and different oracles are called.
15
- * The current state determines which oracles are available.
16
- */ var SessionState = /*#__PURE__*/ function(SessionState) {
17
- /**
18
- * The top-level state is the default state, before any other state has been entered. This is where contracts can be
19
- * deployed, accounts created, blocks mined, etc.
20
- */ SessionState[SessionState["TOP_LEVEL"] = 0] = "TOP_LEVEL";
21
- /**
22
- * The private state is entered via the `private_context` function. In this state the PXE oracles that `#[private]`
23
- * functions use are available, such as those related to note retrieval, notification of side-effects, capsule access,
24
- * etc. */ SessionState[SessionState["PRIVATE"] = 1] = "PRIVATE";
25
- /**
26
- * The public state is entered via the `public_context` function. In this state the AVM opcodes that `#[public]`
27
- * functions execute are resolved as oracles by TXE, since Noir tests are not transpiled. */ SessionState[SessionState["PUBLIC"] = 2] = "PUBLIC";
28
- /**
29
- * The utility state is entered via the `utility_context` function. In this state the PXE oracles that `#[utility]`
30
- * functions use are available, such as those related to (unconstrained) note retrieval, capsule access, public
31
- * storage reads, etc.
32
- */ SessionState[SessionState["UTILITY"] = 3] = "UTILITY";
33
- return SessionState;
34
- }(SessionState || {});
35
- const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
21
+ import { TXEAccountStore } from './util/txe_account_store.js';
22
+ import { TXEContractStore } from './util/txe_contract_store.js';
23
+ import { getSingleTxBlockRequestHash, insertTxEffectIntoWorldTrees, makeTXEBlock } from './utils/block_creation.js';
24
+ import { makeTxEffect } from './utils/tx_effect_creation.js';
36
25
  /**
37
26
  * A `TXESession` corresponds to a Noir `#[test]` function, and handles all of its oracle calls, stores test-specific
38
27
  * state, etc., independent of all other tests running in parallel.
@@ -40,34 +29,67 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
40
29
  logger;
41
30
  stateMachine;
42
31
  oracleHandler;
43
- legacyTXEOracle;
32
+ contractStore;
33
+ noteStore;
34
+ keyStore;
35
+ addressStore;
36
+ accountStore;
37
+ senderTaggingStore;
38
+ recipientTaggingStore;
39
+ senderAddressBookStore;
40
+ capsuleStore;
41
+ privateEventStore;
42
+ chainId;
43
+ version;
44
+ nextBlockTimestamp;
44
45
  state;
45
- constructor(logger, stateMachine, oracleHandler, legacyTXEOracle){
46
+ authwits;
47
+ constructor(logger, stateMachine, oracleHandler, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, senderAddressBookStore, capsuleStore, privateEventStore, chainId, version, nextBlockTimestamp){
46
48
  this.logger = logger;
47
49
  this.stateMachine = stateMachine;
48
50
  this.oracleHandler = oracleHandler;
49
- this.legacyTXEOracle = legacyTXEOracle;
50
- this.state = 0;
51
+ this.contractStore = contractStore;
52
+ this.noteStore = noteStore;
53
+ this.keyStore = keyStore;
54
+ this.addressStore = addressStore;
55
+ this.accountStore = accountStore;
56
+ this.senderTaggingStore = senderTaggingStore;
57
+ this.recipientTaggingStore = recipientTaggingStore;
58
+ this.senderAddressBookStore = senderAddressBookStore;
59
+ this.capsuleStore = capsuleStore;
60
+ this.privateEventStore = privateEventStore;
61
+ this.chainId = chainId;
62
+ this.version = version;
63
+ this.nextBlockTimestamp = nextBlockTimestamp;
64
+ this.state = {
65
+ name: 'TOP_LEVEL'
66
+ };
67
+ this.authwits = new Map();
51
68
  }
52
69
  static async init(protocolContracts) {
53
70
  const store = await openTmpStore('txe-session');
54
- const addressDataProvider = new AddressDataProvider(store);
55
- const privateEventDataProvider = new PrivateEventDataProvider(store);
56
- const contractDataProvider = new TXEContractDataProvider(store);
57
- const noteDataProvider = await NoteDataProvider.create(store);
58
- const taggingDataProvider = new TaggingDataProvider(store);
59
- const capsuleDataProvider = new CapsuleDataProvider(store);
71
+ const addressStore = new AddressStore(store);
72
+ const privateEventStore = new PrivateEventStore(store);
73
+ const contractStore = new TXEContractStore(store);
74
+ const noteStore = await NoteStore.create(store);
75
+ const senderTaggingStore = new SenderTaggingStore(store);
76
+ const recipientTaggingStore = new RecipientTaggingStore(store);
77
+ const senderAddressBookStore = new SenderAddressBookStore(store);
78
+ const capsuleStore = new CapsuleStore(store);
60
79
  const keyStore = new KeyStore(store);
61
- const accountDataProvider = new TXEAccountDataProvider(store);
80
+ const accountStore = new TXEAccountStore(store);
62
81
  // Register protocol contracts.
63
82
  for (const { contractClass, instance, artifact } of protocolContracts){
64
- await contractDataProvider.addContractArtifact(contractClass.id, artifact);
65
- await contractDataProvider.addContractInstance(instance);
83
+ await contractStore.addContractArtifact(contractClass.id, artifact);
84
+ await contractStore.addContractInstance(instance);
66
85
  }
67
86
  const stateMachine = await TXEStateMachine.create(store);
68
- const txeOracle = new TXE(keyStore, contractDataProvider, noteDataProvider, capsuleDataProvider, taggingDataProvider, addressDataProvider, privateEventDataProvider, accountDataProvider, DEFAULT_ADDRESS, await stateMachine.synchronizer.nativeWorldStateService.fork(), stateMachine);
69
- await txeOracle.txeAdvanceBlocksBy(1);
70
- return new TXESession(createLogger('txe:session'), stateMachine, txeOracle, txeOracle);
87
+ const nextBlockTimestamp = BigInt(Math.floor(new Date().getTime() / 1000));
88
+ const version = new Fr(await stateMachine.node.getVersion());
89
+ const chainId = new Fr(await stateMachine.node.getChainId());
90
+ const topLevelOracleHandler = new TXEOracleTopLevelContext(stateMachine, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, senderAddressBookStore, capsuleStore, privateEventStore, nextBlockTimestamp, version, chainId, new Map());
91
+ await topLevelOracleHandler.txeAdvanceBlocksBy(1);
92
+ return new TXESession(createLogger('txe:session'), stateMachine, topLevelOracleHandler, contractStore, noteStore, keyStore, addressStore, accountStore, senderTaggingStore, recipientTaggingStore, senderAddressBookStore, capsuleStore, privateEventStore, version, chainId, nextBlockTimestamp);
71
93
  }
72
94
  /**
73
95
  * Processes an oracle function invoked by the Noir test associated to this session.
@@ -75,64 +97,190 @@ const DEFAULT_ADDRESS = AztecAddress.fromNumber(42);
75
97
  * @param inputs The inputs of the oracle.
76
98
  * @returns The oracle return values.
77
99
  */ processFunction(functionName, inputs) {
78
- return new TXEService(this, this.oracleHandler)[functionName](...inputs);
100
+ try {
101
+ const translator = new RPCTranslator(this, this.oracleHandler);
102
+ // We perform a runtime validation to check that the function name corresponds to a real oracle handler.
103
+ const validatedFunctionName = z.string().refine((fn)=>typeof translator[fn] === 'function' && !fn.startsWith('handlerAs') && fn !== 'constructor').parse(functionName);
104
+ return translator[validatedFunctionName](...inputs);
105
+ } catch (error) {
106
+ if (error instanceof z.ZodError) {
107
+ throw new Error(`${functionName} does not correspond to any oracle handler available on RPCTranslator`);
108
+ } else if (error instanceof Error) {
109
+ throw new Error(`Execution error while processing function ${functionName} in state ${this.state.name}: ${error.message}`);
110
+ } else {
111
+ throw new Error(`Unknown execution error while processing function ${functionName} in state ${this.state.name}`);
112
+ }
113
+ }
79
114
  }
80
- async setTopLevelContext() {
81
- if (this.state == 1) {
82
- await this.oracleHandler.txeAdvanceBlocksBy(1);
83
- this.oracleHandler.txeSetContractAddress(DEFAULT_ADDRESS);
84
- } else if (this.state == 2) {
85
- const block = await this.oracleHandler.close();
86
- await this.stateMachine.handleL2Block(block);
87
- this.legacyTXEOracle.baseFork = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
88
- this.legacyTXEOracle.txeSetContractAddress(DEFAULT_ADDRESS);
89
- this.legacyTXEOracle.setBlockNumber(block.number + 1);
90
- this.oracleHandler = this.legacyTXEOracle;
91
- } else if (this.state == 3) {
92
- this.oracleHandler.txeSetContractAddress(DEFAULT_ADDRESS);
93
- } else if (this.state == 0) {
94
- throw new Error(`Expected to be in state other than ${SessionState[0]}`);
95
- } else {
96
- throw new Error(`Unexpected state '${this.state}'`);
115
+ async enterTopLevelState() {
116
+ switch(this.state.name){
117
+ case 'PRIVATE':
118
+ {
119
+ await this.exitPrivateState();
120
+ break;
121
+ }
122
+ case 'PUBLIC':
123
+ {
124
+ await this.exitPublicState();
125
+ break;
126
+ }
127
+ case 'UTILITY':
128
+ {
129
+ this.exitUtilityContext();
130
+ break;
131
+ }
132
+ case 'TOP_LEVEL':
133
+ {
134
+ throw new Error(`Expected to be in state other than TOP_LEVEL`);
135
+ }
136
+ default:
137
+ {
138
+ this.state;
139
+ }
97
140
  }
98
- this.state = 0;
99
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
141
+ this.oracleHandler = new TXEOracleTopLevelContext(this.stateMachine, this.contractStore, this.noteStore, this.keyStore, this.addressStore, this.accountStore, this.senderTaggingStore, this.recipientTaggingStore, this.senderAddressBookStore, this.capsuleStore, this.privateEventStore, this.nextBlockTimestamp, this.version, this.chainId, this.authwits);
142
+ this.state = {
143
+ name: 'TOP_LEVEL'
144
+ };
145
+ this.logger.debug(`Entered state ${this.state.name}`);
146
+ }
147
+ async enterPrivateState(contractAddress = DEFAULT_ADDRESS, anchorBlockNumber) {
148
+ this.exitTopLevelState();
149
+ await new NoteService(this.noteStore, this.stateMachine.node, this.stateMachine.anchorBlockStore).syncNoteNullifiers(contractAddress);
150
+ // Private execution has two associated block numbers: the anchor block (i.e. the historical block that is used to
151
+ // build the proof), and the *next* block, i.e. the one we'll create once the execution ends, and which will contain
152
+ // a single transaction with the effects of what was done in the test.
153
+ const anchorBlock = await this.stateMachine.node.getBlockHeader(anchorBlockNumber ?? 'latest');
154
+ const latestBlock = await this.stateMachine.node.getBlockHeader('latest');
155
+ const nextBlockGlobalVariables = makeGlobalVariables(undefined, {
156
+ blockNumber: BlockNumber(latestBlock.globalVariables.blockNumber + 1),
157
+ timestamp: this.nextBlockTimestamp,
158
+ version: this.version,
159
+ chainId: this.chainId
160
+ });
161
+ const txRequestHash = getSingleTxBlockRequestHash(nextBlockGlobalVariables.blockNumber);
162
+ const protocolNullifier = await computeProtocolNullifier(txRequestHash);
163
+ const noteCache = new ExecutionNoteCache(protocolNullifier);
164
+ const taggingIndexCache = new ExecutionTaggingIndexCache();
165
+ const utilityExecutor = this.utilityExecutorForContractSync(anchorBlock);
166
+ this.oracleHandler = new PrivateExecutionOracle(Fr.ZERO, new TxContext(this.chainId, this.version, GasSettings.empty()), new CallContext(AztecAddress.ZERO, contractAddress, FunctionSelector.empty(), false), anchorBlock, utilityExecutor, [], [], new HashedValuesCache(), 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);
167
+ // We store the note and tagging index caches fed into the PrivateExecutionOracle (along with some other auxiliary
168
+ // data) in order to refer to it later, mimicking the way this object is used by the ContractFunctionSimulator. The
169
+ // difference resides in that the simulator has all information needed in order to run the simulation, while ours
170
+ // will be ongoing as the different oracles will be invoked from the Noir test, until eventually the private
171
+ // execution finishes.
172
+ this.state = {
173
+ name: 'PRIVATE',
174
+ nextBlockGlobalVariables,
175
+ protocolNullifier,
176
+ noteCache,
177
+ taggingIndexCache
178
+ };
179
+ this.logger.debug(`Entered state ${this.state.name}`);
180
+ return this.oracleHandler.getPrivateContextInputs();
100
181
  }
101
- async setPublicContext(contractAddress) {
102
- this.assertInTopLevelState();
182
+ async enterPublicState(contractAddress) {
183
+ this.exitTopLevelState();
184
+ // The PublicContext will create a block with a single transaction in it, containing the effects of what was done in
185
+ // the test. The block therefore gets the *next* block number and timestamp.
186
+ const latestBlockNumber = (await this.stateMachine.node.getBlockHeader('latest')).globalVariables.blockNumber;
103
187
  const globalVariables = makeGlobalVariables(undefined, {
104
- blockNumber: await this.legacyTXEOracle.utilityGetBlockNumber(),
105
- timestamp: await this.legacyTXEOracle.utilityGetTimestamp(),
106
- version: await this.legacyTXEOracle.utilityGetVersion(),
107
- chainId: await this.legacyTXEOracle.utilityGetChainId()
188
+ blockNumber: BlockNumber(latestBlockNumber + 1),
189
+ timestamp: this.nextBlockTimestamp,
190
+ version: this.version,
191
+ chainId: this.chainId
108
192
  });
109
- const txRequestHash = new Fr(globalVariables.blockNumber + 6969);
110
- this.oracleHandler = new TXEOraclePublicContext(contractAddress ?? DEFAULT_ADDRESS, await this.stateMachine.synchronizer.nativeWorldStateService.fork(), txRequestHash, globalVariables);
111
- this.state = 2;
112
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
193
+ this.oracleHandler = new TXEOraclePublicContext(contractAddress ?? DEFAULT_ADDRESS, await this.stateMachine.synchronizer.nativeWorldStateService.fork(), getSingleTxBlockRequestHash(globalVariables.blockNumber), globalVariables);
194
+ this.state = {
195
+ name: 'PUBLIC'
196
+ };
197
+ this.logger.debug(`Entered state ${this.state.name}`);
198
+ }
199
+ async enterUtilityState(contractAddress = DEFAULT_ADDRESS) {
200
+ this.exitTopLevelState();
201
+ // There is no automatic message discovery and contract-driven syncing process in inlined private or utility
202
+ // contexts, which means that known nullifiers are also not searched for, since it is during the tagging sync that
203
+ // we perform this. We therefore search for known nullifiers now, as otherwise notes that were nullified would not
204
+ // be removed from the database.
205
+ // TODO(#12553): make the synchronizer sync here instead and remove this
206
+ await new NoteService(this.noteStore, this.stateMachine.node, this.stateMachine.anchorBlockStore).syncNoteNullifiers(contractAddress);
207
+ const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
208
+ this.oracleHandler = new UtilityExecutionOracle(contractAddress, [], [], anchorBlockHeader, this.contractStore, this.noteStore, this.keyStore, this.addressStore, this.stateMachine.node, this.stateMachine.anchorBlockStore, this.recipientTaggingStore, this.senderAddressBookStore, this.capsuleStore, this.privateEventStore);
209
+ this.state = {
210
+ name: 'UTILITY'
211
+ };
212
+ this.logger.debug(`Entered state ${this.state.name}`);
113
213
  }
114
- async setPrivateContext(contractAddress, historicalBlockNumber) {
115
- this.assertInTopLevelState();
116
- if (contractAddress) {
117
- this.oracleHandler.txeSetContractAddress(contractAddress);
214
+ exitTopLevelState() {
215
+ if (this.state.name != 'TOP_LEVEL') {
216
+ throw new Error(`Expected to be in state 'TOP_LEVEL', but got '${this.state.name}' instead`);
118
217
  }
119
- const privateContextInputs = await this.oracleHandler.txeGetPrivateContextInputs(historicalBlockNumber);
120
- this.state = 1;
121
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
122
- return privateContextInputs;
218
+ // Note that while all public and private contexts do is build a single block that we then process when exiting
219
+ // those, the top level context performs a large number of actions not captured in the following 'close' call. Among
220
+ // others, it will create empty blocks (via `txeAdvanceBlocksBy` and `deploy`), create blocks with transactions via
221
+ // `txePrivateCallNewFlow` and `txePublicCallNewFlow`, add accounts to PXE via `txeAddAccount`, etc. This is a
222
+ // slight inconsistency in the working model of this class, but is not too bad.
223
+ // TODO: it's quite unfortunate that we need to capture the authwits created to later pass them again when the top
224
+ // level context is re-created. This is because authwits create a temporary utility context that'd otherwise reset
225
+ // the authwits if not persisted, so we'd not be able to pass more than one per execution.
226
+ // Ideally authwits would be passed alongside a contract call instead of pre-seeded.
227
+ [this.nextBlockTimestamp, this.authwits] = this.oracleHandler.close();
123
228
  }
124
- setUtilityContext(contractAddress) {
125
- this.assertInTopLevelState();
126
- if (contractAddress) {
127
- this.oracleHandler.txeSetContractAddress(contractAddress);
229
+ async exitPrivateState() {
230
+ if (this.state.name != 'PRIVATE') {
231
+ throw new Error(`Expected to be in state 'PRIVATE', but got '${this.state.name}' instead`);
128
232
  }
129
- this.state = 3;
130
- this.logger.debug(`Entered state ${SessionState[this.state]}`);
131
- return Promise.resolve();
233
+ this.logger.debug('Exiting Private state, building block with collected side effects', {
234
+ blockNumber: this.state.nextBlockGlobalVariables.blockNumber
235
+ });
236
+ // We rely on the note cache to determine the effects of the transaction. This is incomplete as it doesn't private
237
+ // logs (other effects like enqueued public calls don't need to be considered since those are not allowed).
238
+ const txEffect = await makeTxEffect(this.state.noteCache, this.state.protocolNullifier, this.state.nextBlockGlobalVariables.blockNumber);
239
+ // We build a block holding just this transaction
240
+ const forkedWorldTrees = await this.stateMachine.synchronizer.nativeWorldStateService.fork();
241
+ await insertTxEffectIntoWorldTrees(txEffect, forkedWorldTrees);
242
+ const block = await makeTXEBlock(forkedWorldTrees, this.state.nextBlockGlobalVariables, [
243
+ txEffect
244
+ ]);
245
+ await this.stateMachine.handleL2Block(block);
246
+ await forkedWorldTrees.close();
247
+ this.logger.debug('Exited PublicContext with built block', {
248
+ blockNumber: block.number,
249
+ txEffects: block.body.txEffects
250
+ });
132
251
  }
133
- assertInTopLevelState() {
134
- if (this.state != 0) {
135
- throw new Error(`Expected to be in state ${SessionState[0]}, but got '${SessionState[this.state]}' instead`);
252
+ async exitPublicState() {
253
+ if (this.state.name != 'PUBLIC') {
254
+ throw new Error(`Expected to be in state 'PUBLIC', but got '${this.state.name}' instead`);
136
255
  }
256
+ const block = await this.oracleHandler.close();
257
+ await this.stateMachine.handleL2Block(block);
258
+ }
259
+ exitUtilityContext() {
260
+ if (this.state.name != 'UTILITY') {
261
+ throw new Error(`Expected to be in state 'UTILITY', but got '${this.state.name}' instead`);
262
+ }
263
+ }
264
+ utilityExecutorForContractSync(anchorBlock) {
265
+ return async (call)=>{
266
+ const entryPointArtifact = await this.contractStore.getFunctionArtifactWithDebugMetadata(call.to, call.selector);
267
+ if (entryPointArtifact.functionType !== FunctionType.UTILITY) {
268
+ throw new Error(`Cannot run ${entryPointArtifact.functionType} function as utility`);
269
+ }
270
+ try {
271
+ const oracle = new UtilityExecutionOracle(call.to, [], [], anchorBlock, this.contractStore, this.noteStore, this.keyStore, this.addressStore, this.stateMachine.node, this.stateMachine.anchorBlockStore, this.recipientTaggingStore, this.senderAddressBookStore, this.capsuleStore, this.privateEventStore);
272
+ await new WASMSimulator().executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback()).catch((err)=>{
273
+ err.message = resolveAssertionMessageFromError(err, entryPointArtifact);
274
+ throw new ExecutionError(err.message, {
275
+ contractAddress: call.to,
276
+ functionSelector: call.selector
277
+ }, extractCallStack(err, entryPointArtifact.debug), {
278
+ cause: err
279
+ });
280
+ });
281
+ } catch (err) {
282
+ throw createSimulationError(err instanceof Error ? err : new Error('Unknown error contract data sync'));
283
+ }
284
+ };
137
285
  }
138
286
  }