@aztec/simulator 0.65.2 → 0.67.0

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 (136) hide show
  1. package/dest/acvm/acvm.js +3 -3
  2. package/dest/acvm/oracle/oracle.d.ts +1 -4
  3. package/dest/acvm/oracle/oracle.d.ts.map +1 -1
  4. package/dest/acvm/oracle/oracle.js +3 -19
  5. package/dest/acvm/oracle/typed_oracle.d.ts +2 -7
  6. package/dest/acvm/oracle/typed_oracle.d.ts.map +1 -1
  7. package/dest/acvm/oracle/typed_oracle.js +3 -12
  8. package/dest/acvm/serialize.js +2 -2
  9. package/dest/avm/avm_context.d.ts +2 -2
  10. package/dest/avm/avm_context.d.ts.map +1 -1
  11. package/dest/avm/avm_context.js +3 -4
  12. package/dest/avm/avm_execution_environment.d.ts +4 -6
  13. package/dest/avm/avm_execution_environment.d.ts.map +1 -1
  14. package/dest/avm/avm_execution_environment.js +8 -13
  15. package/dest/avm/avm_memory_types.d.ts +2 -2
  16. package/dest/avm/avm_memory_types.d.ts.map +1 -1
  17. package/dest/avm/avm_memory_types.js +7 -7
  18. package/dest/avm/avm_simulator.d.ts +3 -3
  19. package/dest/avm/avm_simulator.d.ts.map +1 -1
  20. package/dest/avm/avm_simulator.js +26 -16
  21. package/dest/avm/avm_tree.d.ts +31 -14
  22. package/dest/avm/avm_tree.d.ts.map +1 -1
  23. package/dest/avm/avm_tree.js +34 -40
  24. package/dest/avm/errors.d.ts +3 -3
  25. package/dest/avm/errors.d.ts.map +1 -1
  26. package/dest/avm/errors.js +8 -15
  27. package/dest/avm/fixtures/index.d.ts.map +1 -1
  28. package/dest/avm/fixtures/index.js +4 -4
  29. package/dest/avm/journal/journal.d.ts +15 -4
  30. package/dest/avm/journal/journal.d.ts.map +1 -1
  31. package/dest/avm/journal/journal.js +121 -36
  32. package/dest/avm/opcodes/environment_getters.d.ts +10 -11
  33. package/dest/avm/opcodes/environment_getters.d.ts.map +1 -1
  34. package/dest/avm/opcodes/environment_getters.js +12 -15
  35. package/dest/avm/opcodes/external_calls.d.ts.map +1 -1
  36. package/dest/avm/opcodes/external_calls.js +4 -11
  37. package/dest/avm/opcodes/misc.d.ts.map +1 -1
  38. package/dest/avm/opcodes/misc.js +3 -3
  39. package/dest/client/client_execution_context.d.ts +6 -33
  40. package/dest/client/client_execution_context.d.ts.map +1 -1
  41. package/dest/client/client_execution_context.js +18 -54
  42. package/dest/client/db_oracle.d.ts +2 -2
  43. package/dest/client/db_oracle.d.ts.map +1 -1
  44. package/dest/client/execution_note_cache.d.ts +9 -1
  45. package/dest/client/execution_note_cache.d.ts.map +1 -1
  46. package/dest/client/execution_note_cache.js +10 -3
  47. package/dest/client/private_execution.d.ts.map +1 -1
  48. package/dest/client/private_execution.js +5 -7
  49. package/dest/client/simulator.d.ts.map +1 -1
  50. package/dest/client/simulator.js +4 -4
  51. package/dest/client/unconstrained_execution.d.ts.map +1 -1
  52. package/dest/client/unconstrained_execution.js +3 -3
  53. package/dest/client/view_data_oracle.d.ts +2 -2
  54. package/dest/client/view_data_oracle.d.ts.map +1 -1
  55. package/dest/client/view_data_oracle.js +5 -6
  56. package/dest/common/debug_fn_name.d.ts +2 -2
  57. package/dest/common/debug_fn_name.d.ts.map +1 -1
  58. package/dest/common/debug_fn_name.js +8 -14
  59. package/dest/providers/acvm_native.js +4 -4
  60. package/dest/providers/factory.d.ts +2 -2
  61. package/dest/providers/factory.d.ts.map +1 -1
  62. package/dest/providers/factory.js +4 -4
  63. package/dest/public/enqueued_call_side_effect_trace.d.ts +11 -23
  64. package/dest/public/enqueued_call_side_effect_trace.d.ts.map +1 -1
  65. package/dest/public/enqueued_call_side_effect_trace.js +51 -72
  66. package/dest/public/executor_metrics.d.ts.map +1 -1
  67. package/dest/public/executor_metrics.js +2 -5
  68. package/dest/public/fixtures/index.d.ts +25 -7
  69. package/dest/public/fixtures/index.d.ts.map +1 -1
  70. package/dest/public/fixtures/index.js +20 -17
  71. package/dest/public/index.d.ts +0 -1
  72. package/dest/public/index.d.ts.map +1 -1
  73. package/dest/public/index.js +1 -2
  74. package/dest/public/public_db_sources.d.ts.map +1 -1
  75. package/dest/public/public_db_sources.js +30 -16
  76. package/dest/public/public_processor.d.ts +7 -8
  77. package/dest/public/public_processor.d.ts.map +1 -1
  78. package/dest/public/public_processor.js +37 -26
  79. package/dest/public/public_processor_metrics.d.ts +1 -1
  80. package/dest/public/public_processor_metrics.d.ts.map +1 -1
  81. package/dest/public/public_tx_context.d.ts +13 -14
  82. package/dest/public/public_tx_context.d.ts.map +1 -1
  83. package/dest/public/public_tx_context.js +63 -54
  84. package/dest/public/public_tx_simulator.d.ts +2 -2
  85. package/dest/public/public_tx_simulator.d.ts.map +1 -1
  86. package/dest/public/public_tx_simulator.js +43 -25
  87. package/dest/public/side_effect_trace_interface.d.ts +4 -17
  88. package/dest/public/side_effect_trace_interface.d.ts.map +1 -1
  89. package/dest/public/transitional_adapters.d.ts +2 -6
  90. package/dest/public/transitional_adapters.d.ts.map +1 -1
  91. package/dest/public/transitional_adapters.js +29 -88
  92. package/package.json +16 -9
  93. package/src/acvm/acvm.ts +2 -2
  94. package/src/acvm/oracle/oracle.ts +2 -32
  95. package/src/acvm/oracle/typed_oracle.ts +3 -20
  96. package/src/acvm/serialize.ts +1 -1
  97. package/src/avm/avm_context.ts +2 -3
  98. package/src/avm/avm_execution_environment.ts +6 -31
  99. package/src/avm/avm_memory_types.ts +6 -6
  100. package/src/avm/avm_simulator.ts +28 -23
  101. package/src/avm/avm_tree.ts +67 -53
  102. package/src/avm/errors.ts +12 -14
  103. package/src/avm/fixtures/index.ts +2 -3
  104. package/src/avm/journal/journal.ts +206 -68
  105. package/src/avm/opcodes/environment_getters.ts +1 -4
  106. package/src/avm/opcodes/external_calls.ts +3 -19
  107. package/src/avm/opcodes/misc.ts +2 -2
  108. package/src/client/client_execution_context.ts +22 -68
  109. package/src/client/db_oracle.ts +2 -2
  110. package/src/client/execution_note_cache.ts +13 -3
  111. package/src/client/private_execution.ts +3 -7
  112. package/src/client/simulator.ts +4 -4
  113. package/src/client/unconstrained_execution.ts +2 -2
  114. package/src/client/view_data_oracle.ts +5 -6
  115. package/src/common/debug_fn_name.ts +7 -13
  116. package/src/providers/acvm_native.ts +3 -3
  117. package/src/providers/factory.ts +3 -3
  118. package/src/public/enqueued_call_side_effect_trace.ts +68 -90
  119. package/src/public/executor_metrics.ts +0 -4
  120. package/src/public/fixtures/index.ts +28 -17
  121. package/src/public/index.ts +0 -1
  122. package/src/public/public_db_sources.ts +32 -19
  123. package/src/public/public_processor.ts +52 -55
  124. package/src/public/public_processor_metrics.ts +1 -1
  125. package/src/public/public_tx_context.ts +89 -76
  126. package/src/public/public_tx_simulator.ts +58 -49
  127. package/src/public/side_effect_trace_interface.ts +8 -15
  128. package/src/public/transitional_adapters.ts +43 -215
  129. package/dest/public/dual_side_effect_trace.d.ts +0 -77
  130. package/dest/public/dual_side_effect_trace.d.ts.map +0 -1
  131. package/dest/public/dual_side_effect_trace.js +0 -119
  132. package/dest/public/side_effect_trace.d.ts +0 -96
  133. package/dest/public/side_effect_trace.d.ts.map +0 -1
  134. package/dest/public/side_effect_trace.js +0 -309
  135. package/src/public/dual_side_effect_trace.ts +0 -242
  136. package/src/public/side_effect_trace.ts +0 -536
@@ -13,20 +13,19 @@ import {
13
13
  } from '@aztec/circuit-types';
14
14
  import {
15
15
  type AztecAddress,
16
- ContractClassRegisteredEvent,
16
+ type BlockHeader,
17
17
  type ContractDataSource,
18
18
  Fr,
19
19
  type GlobalVariables,
20
- type Header,
21
20
  MAX_NOTE_HASHES_PER_TX,
22
21
  MAX_NULLIFIERS_PER_TX,
23
22
  NULLIFIER_SUBTREE_HEIGHT,
24
23
  PublicDataWrite,
25
24
  } from '@aztec/circuits.js';
26
25
  import { padArrayEnd } from '@aztec/foundation/collection';
27
- import { createDebugLogger } from '@aztec/foundation/log';
26
+ import { createLogger } from '@aztec/foundation/log';
28
27
  import { Timer } from '@aztec/foundation/timer';
29
- import { ProtocolContractAddress } from '@aztec/protocol-contracts';
28
+ import { ContractClassRegisteredEvent, ProtocolContractAddress } from '@aztec/protocol-contracts';
30
29
  import { Attributes, type TelemetryClient, type Tracer, trackSpan } from '@aztec/telemetry-client';
31
30
 
32
31
  import { computeFeePayerBalanceLeafSlot, computeFeePayerBalanceStorageSlot } from './fee_payment.js';
@@ -48,13 +47,19 @@ export class PublicProcessorFactory {
48
47
  */
49
48
  public create(
50
49
  merkleTree: MerkleTreeWriteOperations,
51
- maybeHistoricalHeader: Header | undefined,
50
+ maybeHistoricalHeader: BlockHeader | undefined,
52
51
  globalVariables: GlobalVariables,
53
52
  ): PublicProcessor {
54
53
  const historicalHeader = maybeHistoricalHeader ?? merkleTree.getInitialHeader();
55
54
 
56
55
  const worldStateDB = new WorldStateDB(merkleTree, this.contractDataSource);
57
- const publicTxSimulator = new PublicTxSimulator(merkleTree, worldStateDB, this.telemetryClient, globalVariables);
56
+ const publicTxSimulator = new PublicTxSimulator(
57
+ merkleTree,
58
+ worldStateDB,
59
+ this.telemetryClient,
60
+ globalVariables,
61
+ /*doMerkleOperations=*/ true,
62
+ );
58
63
 
59
64
  return new PublicProcessor(
60
65
  merkleTree,
@@ -76,11 +81,11 @@ export class PublicProcessor {
76
81
  constructor(
77
82
  protected db: MerkleTreeWriteOperations,
78
83
  protected globalVariables: GlobalVariables,
79
- protected historicalHeader: Header,
84
+ protected historicalHeader: BlockHeader,
80
85
  protected worldStateDB: WorldStateDB,
81
86
  protected publicTxSimulator: PublicTxSimulator,
82
87
  telemetryClient: TelemetryClient,
83
- private log = createDebugLogger('aztec:simulator:public-processor'),
88
+ private log = createLogger('simulator:public-processor'),
84
89
  ) {
85
90
  this.metrics = new PublicProcessorMetrics(telemetryClient, 'PublicProcessor');
86
91
  }
@@ -116,12 +121,26 @@ export class PublicProcessor {
116
121
  const [processedTx, returnValues] = !tx.hasPublicCalls()
117
122
  ? await this.processPrivateOnlyTx(tx)
118
123
  : await this.processTxWithPublicCalls(tx);
119
- this.log.debug(`Processed tx`, {
120
- txHash: processedTx.hash,
121
- historicalHeaderHash: processedTx.constants.historicalHeader.hash(),
122
- blockNumber: processedTx.constants.globalVariables.blockNumber,
123
- lastArchiveRoot: processedTx.constants.historicalHeader.lastArchive.root,
124
- });
124
+
125
+ this.log.verbose(
126
+ !tx.hasPublicCalls()
127
+ ? `Processed tx ${processedTx.hash} with no public calls`
128
+ : `Processed tx ${processedTx.hash} with ${tx.enqueuedPublicFunctionCalls.length} public calls`,
129
+ {
130
+ txHash: processedTx.hash,
131
+ txFee: processedTx.txEffect.transactionFee.toBigInt(),
132
+ revertCode: processedTx.txEffect.revertCode.getCode(),
133
+ revertReason: processedTx.revertReason,
134
+ gasUsed: processedTx.gasUsed,
135
+ publicDataWriteCount: processedTx.txEffect.publicDataWrites.length,
136
+ nullifierCount: processedTx.txEffect.nullifiers.length,
137
+ noteHashCount: processedTx.txEffect.noteHashes.length,
138
+ contractClassLogCount: processedTx.txEffect.contractClassLogs.getTotalLogCount(),
139
+ unencryptedLogCount: processedTx.txEffect.unencryptedLogs.getTotalLogCount(),
140
+ privateLogCount: processedTx.txEffect.privateLogs.length,
141
+ l2ToL1MessageCount: processedTx.txEffect.l2ToL1Msgs.length,
142
+ },
143
+ );
125
144
 
126
145
  // Commit the state updates from this transaction
127
146
  await this.worldStateDB.commit();
@@ -167,10 +186,9 @@ export class PublicProcessor {
167
186
  }
168
187
  }
169
188
 
170
- await this.db.batchInsert(
189
+ await this.db.sequentialInsert(
171
190
  MerkleTreeId.PUBLIC_DATA_TREE,
172
191
  processedTx.txEffect.publicDataWrites.map(x => x.toBuffer()),
173
- 0,
174
192
  );
175
193
  result.push(processedTx);
176
194
  returns = returns.concat(returnValues ?? []);
@@ -190,16 +208,11 @@ export class PublicProcessor {
190
208
  }
191
209
 
192
210
  /**
193
- * Creates the final set of data update requests for the transaction. This includes the
194
- * set of public data update requests as returned by the public kernel, plus a data update
195
- * request for updating fee balance. It also updates the local public state db.
196
- * See build_or_patch_payment_update_request in base_rollup_inputs.nr for more details.
211
+ * Creates the public data write for paying the tx fee.
212
+ * This is used in private only txs, since for txs with public calls
213
+ * the avm handles the fee payment itself.
197
214
  */
198
- private async getFeePaymentPublicDataWrite(
199
- publicDataWrites: PublicDataWrite[],
200
- txFee: Fr,
201
- feePayer: AztecAddress,
202
- ): Promise<PublicDataWrite | undefined> {
215
+ private async getFeePaymentPublicDataWrite(txFee: Fr, feePayer: AztecAddress): Promise<PublicDataWrite | undefined> {
203
216
  if (feePayer.isZero()) {
204
217
  this.log.debug(`No one is paying the fee of ${txFee.toBigInt()}`);
205
218
  return;
@@ -211,11 +224,7 @@ export class PublicProcessor {
211
224
 
212
225
  this.log.debug(`Deducting ${txFee.toBigInt()} balance in Fee Juice for ${feePayer}`);
213
226
 
214
- const existingBalanceWrite = publicDataWrites.find(write => write.leafSlot.equals(leafSlot));
215
-
216
- const balance = existingBalanceWrite
217
- ? existingBalanceWrite.value
218
- : await this.worldStateDB.storageRead(feeJuiceAddress, balanceSlot);
227
+ const balance = await this.worldStateDB.storageRead(feeJuiceAddress, balanceSlot);
219
228
 
220
229
  if (balance.lt(txFee)) {
221
230
  throw new Error(
@@ -236,12 +245,7 @@ export class PublicProcessor {
236
245
  const gasFees = this.globalVariables.gasFees;
237
246
  const transactionFee = tx.data.gasUsed.computeFee(gasFees);
238
247
 
239
- const accumulatedData = tx.data.forRollup!.end;
240
- const feePaymentPublicDataWrite = await this.getFeePaymentPublicDataWrite(
241
- accumulatedData.publicDataWrites,
242
- transactionFee,
243
- tx.data.feePayer,
244
- );
248
+ const feePaymentPublicDataWrite = await this.getFeePaymentPublicDataWrite(transactionFee, tx.data.feePayer);
245
249
 
246
250
  const processedTx = makeProcessedTxFromPrivateOnlyTx(
247
251
  tx,
@@ -249,6 +253,13 @@ export class PublicProcessor {
249
253
  feePaymentPublicDataWrite,
250
254
  this.globalVariables,
251
255
  );
256
+
257
+ this.metrics.recordClassRegistration(
258
+ ...tx.contractClassLogs
259
+ .unrollLogs()
260
+ .filter(log => ContractClassRegisteredEvent.isContractClassRegisteredEvent(log.data))
261
+ .map(log => ContractClassRegisteredEvent.fromLog(log.data)),
262
+ );
252
263
  return [processedTx];
253
264
  }
254
265
 
@@ -275,31 +286,17 @@ export class PublicProcessor {
275
286
  });
276
287
 
277
288
  this.metrics.recordClassRegistration(
278
- ...ContractClassRegisteredEvent.fromLogs(
279
- tx.contractClassLogs.unrollLogs(),
280
- ProtocolContractAddress.ContractClassRegisterer,
281
- ),
289
+ ...tx.contractClassLogs
290
+ .unrollLogs()
291
+ .filter(log => ContractClassRegisteredEvent.isContractClassRegisteredEvent(log.data))
292
+ .map(log => ContractClassRegisteredEvent.fromLog(log.data)),
282
293
  );
283
294
 
284
295
  const phaseCount = processedPhases.length;
285
296
  const durationMs = timer.ms();
286
297
  this.metrics.recordTx(phaseCount, durationMs);
287
298
 
288
- const data = avmProvingRequest.inputs.output;
289
- const feePaymentPublicDataWrite = await this.getFeePaymentPublicDataWrite(
290
- data.accumulatedData.publicDataWrites,
291
- data.transactionFee,
292
- tx.data.feePayer,
293
- );
294
-
295
- const processedTx = makeProcessedTxFromTxWithPublicCalls(
296
- tx,
297
- avmProvingRequest,
298
- feePaymentPublicDataWrite,
299
- gasUsed,
300
- revertCode,
301
- revertReason,
302
- );
299
+ const processedTx = makeProcessedTxFromTxWithPublicCalls(tx, avmProvingRequest, gasUsed, revertCode, revertReason);
303
300
 
304
301
  const returnValues = processedPhases.find(({ phase }) => phase === TxExecutionPhase.APP_LOGIC)?.returnValues ?? [];
305
302
 
@@ -1,5 +1,5 @@
1
1
  import { type TxExecutionPhase } from '@aztec/circuit-types';
2
- import { type ContractClassRegisteredEvent } from '@aztec/circuits.js';
2
+ import { type ContractClassRegisteredEvent } from '@aztec/protocol-contracts';
3
3
  import {
4
4
  Attributes,
5
5
  type Histogram,
@@ -2,6 +2,7 @@ import {
2
2
  type AvmProvingRequest,
3
3
  MerkleTreeId,
4
4
  type MerkleTreeReadOperations,
5
+ ProvingRequestType,
5
6
  type PublicExecutionRequest,
6
7
  type SimulationError,
7
8
  type Tx,
@@ -9,40 +10,42 @@ import {
9
10
  TxHash,
10
11
  } from '@aztec/circuit-types';
11
12
  import {
13
+ AppendOnlyTreeSnapshot,
14
+ AvmCircuitInputs,
12
15
  type AvmCircuitPublicInputs,
16
+ type AztecAddress,
13
17
  Fr,
14
18
  Gas,
15
19
  type GasSettings,
16
20
  type GlobalVariables,
17
- type Header,
21
+ MAX_L2_GAS_PER_TX_PUBLIC_PORTION,
18
22
  type PrivateToPublicAccumulatedData,
19
23
  type PublicCallRequest,
24
+ PublicCircuitPublicInputs,
20
25
  RevertCode,
21
26
  type StateReference,
27
+ TreeSnapshots,
22
28
  countAccumulatedItems,
23
29
  } from '@aztec/circuits.js';
24
- import { type DebugLogger, createDebugLogger } from '@aztec/foundation/log';
30
+ import { type Logger, createLogger } from '@aztec/foundation/log';
25
31
 
26
32
  import { strict as assert } from 'assert';
27
33
  import { inspect } from 'util';
28
34
 
29
- import { type AvmFinalizedCallResult } from '../avm/avm_contract_call_result.js';
30
35
  import { AvmPersistableStateManager } from '../avm/index.js';
31
- import { DualSideEffectTrace } from './dual_side_effect_trace.js';
32
36
  import { PublicEnqueuedCallSideEffectTrace, SideEffectArrayLengths } from './enqueued_call_side_effect_trace.js';
33
37
  import { type WorldStateDB } from './public_db_sources.js';
34
- import { PublicSideEffectTrace } from './side_effect_trace.js';
35
- import { generateAvmCircuitPublicInputs, generateAvmProvingRequest } from './transitional_adapters.js';
38
+ import { generateAvmCircuitPublicInputs } from './transitional_adapters.js';
36
39
  import { getCallRequestsByPhase, getExecutionRequestsByPhase } from './utils.js';
37
40
 
38
41
  /**
39
42
  * The transaction-level context for public execution.
40
43
  */
41
44
  export class PublicTxContext {
42
- private log: DebugLogger;
45
+ private log: Logger;
43
46
 
44
47
  /* Gas used including private, teardown gas _limit_, setup and app logic */
45
- private gasUsed: Gas;
48
+ private gasUsedByPublic: Gas = Gas.empty();
46
49
  /* Gas actually used during teardown (different from limit) */
47
50
  public teardownGasUsed: Gas = Gas.empty();
48
51
 
@@ -58,10 +61,10 @@ export class PublicTxContext {
58
61
  constructor(
59
62
  public readonly state: PhaseStateManager,
60
63
  private readonly globalVariables: GlobalVariables,
61
- private readonly historicalHeader: Header, // FIXME(dbanks12): remove
62
64
  private readonly startStateReference: StateReference,
63
- private readonly startGasUsed: Gas,
64
65
  private readonly gasSettings: GasSettings,
66
+ private readonly gasUsedByPrivate: Gas,
67
+ private readonly gasAllocatedToPublic: Gas,
65
68
  private readonly setupCallRequests: PublicCallRequest[],
66
69
  private readonly appLogicCallRequests: PublicCallRequest[],
67
70
  private readonly teardownCallRequests: PublicCallRequest[],
@@ -70,10 +73,10 @@ export class PublicTxContext {
70
73
  private readonly teardownExecutionRequests: PublicExecutionRequest[],
71
74
  public readonly nonRevertibleAccumulatedDataFromPrivate: PrivateToPublicAccumulatedData,
72
75
  public readonly revertibleAccumulatedDataFromPrivate: PrivateToPublicAccumulatedData,
76
+ public readonly feePayer: AztecAddress,
73
77
  public trace: PublicEnqueuedCallSideEffectTrace, // FIXME(dbanks12): should be private
74
78
  ) {
75
- this.log = createDebugLogger(`aztec:public_tx_context`);
76
- this.gasUsed = startGasUsed;
79
+ this.log = createLogger(`simulator:public_tx_context`);
77
80
  }
78
81
 
79
82
  public static async create(
@@ -85,11 +88,11 @@ export class PublicTxContext {
85
88
  ) {
86
89
  const nonRevertibleAccumulatedDataFromPrivate = tx.data.forPublic!.nonRevertibleAccumulatedData;
87
90
 
88
- const innerCallTrace = new PublicSideEffectTrace();
89
91
  const previousAccumulatedDataArrayLengths = new SideEffectArrayLengths(
90
92
  /*publicDataWrites*/ 0,
93
+ /*protocolPublicDataWrites*/ 0,
91
94
  countAccumulatedItems(nonRevertibleAccumulatedDataFromPrivate.noteHashes),
92
- countAccumulatedItems(nonRevertibleAccumulatedDataFromPrivate.nullifiers),
95
+ /*nullifiers=*/ 0,
93
96
  countAccumulatedItems(nonRevertibleAccumulatedDataFromPrivate.l2ToL1Msgs),
94
97
  /*unencryptedLogsHashes*/ 0,
95
98
  );
@@ -97,18 +100,22 @@ export class PublicTxContext {
97
100
  /*startSideEffectCounter=*/ 0,
98
101
  previousAccumulatedDataArrayLengths,
99
102
  );
100
- const trace = new DualSideEffectTrace(innerCallTrace, enqueuedCallTrace);
101
103
 
102
104
  // Transaction level state manager that will be forked for revertible phases.
103
- const txStateManager = await AvmPersistableStateManager.create(worldStateDB, trace, doMerkleOperations);
105
+ const txStateManager = await AvmPersistableStateManager.create(worldStateDB, enqueuedCallTrace, doMerkleOperations);
106
+
107
+ const gasSettings = tx.data.constants.txContext.gasSettings;
108
+ const gasUsedByPrivate = tx.data.gasUsed;
109
+ // Gas allocated to public is "whatever's left" after private, but with some max applied.
110
+ const gasAllocatedToPublic = applyMaxToAvailableGas(gasSettings.gasLimits.sub(gasUsedByPrivate));
104
111
 
105
112
  return new PublicTxContext(
106
113
  new PhaseStateManager(txStateManager),
107
114
  globalVariables,
108
- tx.data.constants.historicalHeader,
109
115
  await db.getStateReference(),
110
- tx.data.gasUsed,
111
- tx.data.constants.txContext.gasSettings,
116
+ gasSettings,
117
+ gasUsedByPrivate,
118
+ gasAllocatedToPublic,
112
119
  getCallRequestsByPhase(tx, TxExecutionPhase.SETUP),
113
120
  getCallRequestsByPhase(tx, TxExecutionPhase.APP_LOGIC),
114
121
  getCallRequestsByPhase(tx, TxExecutionPhase.TEARDOWN),
@@ -117,6 +124,7 @@ export class PublicTxContext {
117
124
  getExecutionRequestsByPhase(tx, TxExecutionPhase.TEARDOWN),
118
125
  tx.data.forPublic!.nonRevertibleAccumulatedData,
119
126
  tx.data.forPublic!.revertibleAccumulatedData,
127
+ tx.data.feePayer,
120
128
  enqueuedCallTrace,
121
129
  );
122
130
  }
@@ -229,13 +237,14 @@ export class PublicTxContext {
229
237
  }
230
238
 
231
239
  /**
232
- * How much gas is left for the specified phase?
240
+ * How much gas is left as of the specified phase?
233
241
  */
234
- getGasLeftForPhase(phase: TxExecutionPhase): Gas {
242
+ getGasLeftAtPhase(phase: TxExecutionPhase): Gas {
235
243
  if (phase === TxExecutionPhase.TEARDOWN) {
236
- return this.gasSettings.teardownGasLimits;
244
+ return applyMaxToAvailableGas(this.gasSettings.teardownGasLimits);
237
245
  } else {
238
- return this.gasSettings.gasLimits.sub(this.gasUsed);
246
+ const gasLeftForPublic = this.gasAllocatedToPublic.sub(this.gasUsedByPublic);
247
+ return gasLeftForPublic;
239
248
  }
240
249
  }
241
250
 
@@ -246,10 +255,18 @@ export class PublicTxContext {
246
255
  if (phase === TxExecutionPhase.TEARDOWN) {
247
256
  this.teardownGasUsed = this.teardownGasUsed.add(gas);
248
257
  } else {
249
- this.gasUsed = this.gasUsed.add(gas);
258
+ this.gasUsedByPublic = this.gasUsedByPublic.add(gas);
250
259
  }
251
260
  }
252
261
 
262
+ /**
263
+ * The gasUsed by public and private,
264
+ * as if the entire teardown gas limit was consumed.
265
+ */
266
+ getTotalGasUsed(): Gas {
267
+ return this.gasUsedByPrivate.add(this.gasUsedByPublic);
268
+ }
269
+
253
270
  /**
254
271
  * Compute the gas used using the actual gas used during teardown instead
255
272
  * of the teardown gas limit.
@@ -260,14 +277,7 @@ export class PublicTxContext {
260
277
  assert(this.halted, 'Can only compute actual gas used after tx execution ends');
261
278
  const requireTeardown = this.teardownCallRequests.length > 0;
262
279
  const teardownGasLimits = requireTeardown ? this.gasSettings.teardownGasLimits : Gas.empty();
263
- return this.gasUsed.sub(teardownGasLimits).add(this.teardownGasUsed);
264
- }
265
-
266
- /**
267
- * The gasUsed as if the entire teardown gas limit was consumed.
268
- */
269
- getGasUsedForFee(): Gas {
270
- return this.gasUsed;
280
+ return this.getTotalGasUsed().sub(teardownGasLimits).add(this.teardownGasUsed);
271
281
  }
272
282
 
273
283
  /**
@@ -287,10 +297,10 @@ export class PublicTxContext {
287
297
  * Should only be called during or after teardown.
288
298
  */
289
299
  private getTransactionFeeUnsafe(): Fr {
290
- const txFee = this.gasUsed.computeFee(this.globalVariables.gasFees);
300
+ const txFee = this.getTotalGasUsed().computeFee(this.globalVariables.gasFees);
291
301
  this.log.debug(`Computed tx fee`, {
292
302
  txFee,
293
- gasUsed: inspect(this.gasUsed),
303
+ gasUsed: inspect(this.getTotalGasUsed()),
294
304
  gasFees: inspect(this.globalVariables.gasFees),
295
305
  });
296
306
  return txFee;
@@ -301,24 +311,38 @@ export class PublicTxContext {
301
311
  */
302
312
  private generateAvmCircuitPublicInputs(endStateReference: StateReference): AvmCircuitPublicInputs {
303
313
  assert(this.halted, 'Can only get AvmCircuitPublicInputs after tx execution ends');
304
- // TODO(dbanks12): use the state roots from ephemeral trees
305
- endStateReference.partial.nullifierTree.root = this.state
306
- .getActiveStateManager()
307
- .merkleTrees.treeMap.get(MerkleTreeId.NULLIFIER_TREE)!
308
- .getRoot();
314
+ const ephemeralTrees = this.state.getActiveStateManager().merkleTrees.treeMap;
315
+
316
+ const getAppendSnaphot = (id: MerkleTreeId) => {
317
+ const tree = ephemeralTrees.get(id)!;
318
+ return new AppendOnlyTreeSnapshot(tree.getRoot(), Number(tree.leafCount));
319
+ };
320
+
321
+ const noteHashTree = getAppendSnaphot(MerkleTreeId.NOTE_HASH_TREE);
322
+ const nullifierTree = getAppendSnaphot(MerkleTreeId.NULLIFIER_TREE);
323
+ const publicDataTree = getAppendSnaphot(MerkleTreeId.PUBLIC_DATA_TREE);
324
+
325
+ const endTreeSnapshots = new TreeSnapshots(
326
+ endStateReference.l1ToL2MessageTree,
327
+ noteHashTree,
328
+ nullifierTree,
329
+ publicDataTree,
330
+ );
331
+
309
332
  return generateAvmCircuitPublicInputs(
310
333
  this.trace,
311
334
  this.globalVariables,
312
335
  this.startStateReference,
313
- this.startGasUsed,
336
+ /*startGasUsed=*/ this.gasUsedByPrivate,
314
337
  this.gasSettings,
338
+ this.feePayer,
315
339
  this.setupCallRequests,
316
340
  this.appLogicCallRequests,
317
341
  this.teardownCallRequests,
318
342
  this.nonRevertibleAccumulatedDataFromPrivate,
319
343
  this.revertibleAccumulatedDataFromPrivate,
320
- endStateReference,
321
- /*endGasUsed=*/ this.gasUsed,
344
+ endTreeSnapshots,
345
+ /*endGasUsed=*/ this.getTotalGasUsed(),
322
346
  this.getTransactionFeeUnsafe(),
323
347
  this.revertCode,
324
348
  );
@@ -328,38 +352,17 @@ export class PublicTxContext {
328
352
  * Generate the proving request for the AVM circuit.
329
353
  */
330
354
  generateProvingRequest(endStateReference: StateReference): AvmProvingRequest {
331
- // TODO(dbanks12): Once we actually have tx-level proving, this will generate the entire
332
- // proving request for the first time
333
- this.avmProvingRequest!.inputs.output = this.generateAvmCircuitPublicInputs(endStateReference);
334
- return this.avmProvingRequest!;
335
- }
336
-
337
- // TODO(dbanks12): remove once AVM proves entire public tx
338
- updateProvingRequest(
339
- real: boolean,
340
- phase: TxExecutionPhase,
341
- fnName: string,
342
- stateManager: AvmPersistableStateManager,
343
- executionRequest: PublicExecutionRequest,
344
- result: AvmFinalizedCallResult,
345
- allocatedGas: Gas,
346
- ) {
347
- if (this.avmProvingRequest === undefined) {
348
- // Propagate the very first avmProvingRequest of the tx for now.
349
- // Eventually this will be the proof for the entire public portion of the transaction.
350
- this.avmProvingRequest = generateAvmProvingRequest(
351
- real,
352
- fnName,
353
- stateManager,
354
- this.historicalHeader,
355
- this.globalVariables,
356
- executionRequest,
357
- // TODO(dbanks12): do we need this return type unless we are doing an isolated call?
358
- stateManager.trace.toPublicEnqueuedCallExecutionResult(result),
359
- allocatedGas,
360
- this.getTransactionFee(phase),
361
- );
362
- }
355
+ const hints = this.trace.getAvmCircuitHints();
356
+ return {
357
+ type: ProvingRequestType.PUBLIC_VM,
358
+ inputs: new AvmCircuitInputs(
359
+ 'public_dispatch',
360
+ [],
361
+ PublicCircuitPublicInputs.empty(),
362
+ hints,
363
+ this.generateAvmCircuitPublicInputs(endStateReference),
364
+ ),
365
+ };
363
366
  }
364
367
  }
365
368
 
@@ -374,12 +377,12 @@ export class PublicTxContext {
374
377
  * transaction level one.
375
378
  */
376
379
  class PhaseStateManager {
377
- private log: DebugLogger;
380
+ private log: Logger;
378
381
 
379
382
  private currentlyActiveStateManager: AvmPersistableStateManager | undefined;
380
383
 
381
384
  constructor(private readonly txStateManager: AvmPersistableStateManager) {
382
- this.log = createDebugLogger(`aztec:public_phase_state_manager`);
385
+ this.log = createLogger(`simulator:public_phase_state_manager`);
383
386
  }
384
387
 
385
388
  fork() {
@@ -412,3 +415,13 @@ class PhaseStateManager {
412
415
  this.currentlyActiveStateManager = undefined;
413
416
  }
414
417
  }
418
+
419
+ /**
420
+ * Apply L2 gas maximum.
421
+ */
422
+ function applyMaxToAvailableGas(availableGas: Gas) {
423
+ return new Gas(
424
+ /*daGas=*/ availableGas.daGas,
425
+ /*l2Gas=*/ Math.min(availableGas.l2Gas, MAX_L2_GAS_PER_TX_PUBLIC_PORTION),
426
+ );
427
+ }