@aztec/txe 0.0.1-commit.0dc957cde → 0.0.1-commit.0ec55a70b

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.
@@ -1,4 +1,4 @@
1
- import { ArchiverDataSourceBase, ArchiverDataStoreUpdater, KVArchiverDataStore } from '@aztec/archiver';
1
+ import { ArchiverDataSourceBase, ArchiverDataStoreUpdater, createArchiverDataStores } from '@aztec/archiver';
2
2
  import { GENESIS_ARCHIVE_ROOT } from '@aztec/constants';
3
3
  import { CheckpointNumber, type EpochNumber, type SlotNumber } from '@aztec/foundation/branded-types';
4
4
  import { Fr } from '@aztec/foundation/curves/bn254';
@@ -14,11 +14,10 @@ import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
14
14
  * without needing any of the extra overhead that the Archiver itself requires (i.e. an L1 client).
15
15
  */
16
16
  export class TXEArchiver extends ArchiverDataSourceBase {
17
- private readonly updater = new ArchiverDataStoreUpdater(this.store);
17
+ private readonly updater = new ArchiverDataStoreUpdater(this.stores);
18
18
 
19
19
  constructor(db: AztecAsyncKVStore) {
20
- const store = new KVArchiverDataStore(db, 9999);
21
- super(store);
20
+ super(createArchiverDataStores(db, { logsMaxPageSize: 9999 }));
22
21
  }
23
22
 
24
23
  public async addCheckpoints(checkpoints: PublishedCheckpoint[], result?: ValidateCheckpointResult): Promise<void> {
@@ -61,7 +60,7 @@ export class TXEArchiver extends ArchiverDataSourceBase {
61
60
  }
62
61
  // TXE uses 1-block-per-checkpoint for testing simplicity, so we can use block number as checkpoint number.
63
62
  // This uses the deprecated fromBlockNumber method intentionally for the TXE testing environment.
64
- const checkpoint = await this.store.getRangeOfCheckpoints(CheckpointNumber.fromBlockNumber(number), 1);
63
+ const checkpoint = await this.stores.blocks.getRangeOfCheckpoints(CheckpointNumber.fromBlockNumber(number), 1);
65
64
  if (checkpoint.length === 0) {
66
65
  throw new Error(`L2Tips requested from TXE Archiver but no checkpoint found for block number ${number}`);
67
66
  }
@@ -53,6 +53,7 @@ export class TXEStateMachine {
53
53
  undefined,
54
54
  undefined,
55
55
  undefined,
56
+ undefined,
56
57
  VERSION,
57
58
  CHAIN_ID,
58
59
  new TXEGlobalVariablesBuilder(),
@@ -9,7 +9,6 @@ import {
9
9
  CapsuleService,
10
10
  CapsuleStore,
11
11
  ContractStore,
12
- ContractSyncService,
13
12
  JobCoordinator,
14
13
  NoteService,
15
14
  NoteStore,
@@ -43,7 +42,7 @@ import { GasSettings } from '@aztec/stdlib/gas';
43
42
  import { computeProtocolNullifier } from '@aztec/stdlib/hash';
44
43
  import { PrivateContextInputs } from '@aztec/stdlib/kernel';
45
44
  import { makeGlobalVariables } from '@aztec/stdlib/testing';
46
- import { CallContext, GlobalVariables, TxContext } from '@aztec/stdlib/tx';
45
+ import { CallContext, GlobalVariables, OFFCHAIN_MESSAGE_IDENTIFIER, TxContext } from '@aztec/stdlib/tx';
47
46
 
48
47
  import { z } from 'zod';
49
48
 
@@ -118,6 +117,65 @@ export interface TXESessionStateHandler {
118
117
  // TODO(F-335): Exposing the job info is abstraction breakage - drop the following 2 functions.
119
118
  cycleJob(): Promise<string>;
120
119
  getCurrentJob(): string;
120
+
121
+ /**
122
+ * Runs an executor-style top-level call (private/public call, utility execution) with last-call tracking.
123
+ */
124
+ withTopLevelCallTracking<T>(work: () => Promise<{ result: T; txHash?: Fr }>): Promise<T>;
125
+
126
+ /**
127
+ * Captures a raw offchain effect payload for consumption from test environment. Called by the `emit_offchain_effect`
128
+ * oracle handler whenever a contract function emits an offchain message, at any call depth.
129
+ */
130
+ recordOffchainEffect(data: Fr[]): void;
131
+
132
+ /**
133
+ * Returns the raw offchain effect payloads emitted by the last top-level call. Each payload follows the protocol
134
+ * convention documented on `OFFCHAIN_MESSAGE_IDENTIFIER`, i.e. `[identifier, recipient, ...ciphertext]`. Decoding into
135
+ * `OffchainMessage` structs happens on the Noir side of the test helper. Marks the buffer as queried so the
136
+ * unqueried-messages warning doesn't fire on the next reset.
137
+ */
138
+ getLastCallOffchainEffects(): { effects: Fr[][] };
139
+
140
+ /**
141
+ * Returns the context of the last top-level call: its tx hash (`Fr.ZERO` if the call was tx-less) and the anchor
142
+ * block timestamp captured at the start of the call. Does *not* mark the buffer as queried — context reads are
143
+ * metadata, not effect consumption.
144
+ */
145
+ getLastCallContext(): { txHash: Fr; anchorBlockTimestamp: bigint };
146
+ }
147
+
148
+ /**
149
+ * Session state tracking the most recently completed top-level call: the offchain effect buffer it produced, and the
150
+ * call's context (tx hash + anchor block timestamp). The context is refreshed on every top-level call, independently
151
+ * of whether the call produced offchain effects.
152
+ */
153
+ interface LastCallState {
154
+ /**
155
+ * Raw offchain effect payloads emitted by the currently-executing (or most recently completed) top-level call. Wiped
156
+ * at the start of every top-level entry point, appended to on every `emit_offchain_effect` oracle invocation.
157
+ */
158
+ offchainEffects: Fr[][];
159
+ /**
160
+ * Tracks whether the test has queried `effects` since the last reset. If a new top-level call clobbers the buffer
161
+ * without it being queried first, any accumulated messages are lost and we emit a warning so tests don't silently
162
+ * drop delivery.
163
+ */
164
+ queried: boolean;
165
+ /**
166
+ * Tx hash of the most recently completed top-level call, or `Fr.ZERO` if the call was tx-less (context setters,
167
+ * utility execution). Populated by call executor handlers after execution completes.
168
+ */
169
+ txHash: Fr;
170
+ /**
171
+ * Anchor block timestamp of the most recently completed top-level call, captured from the anchor block header that
172
+ * was active when the call started. Populated by call executor handlers after execution completes.
173
+ */
174
+ anchorBlockTimestamp: bigint;
175
+ }
176
+
177
+ function emptyLastCallState(): LastCallState {
178
+ return { offchainEffects: [], queried: false, txHash: Fr.ZERO, anchorBlockTimestamp: 0n };
121
179
  }
122
180
 
123
181
  /**
@@ -127,6 +185,7 @@ export interface TXESessionStateHandler {
127
185
  export class TXESession implements TXESessionStateHandler {
128
186
  private state: SessionState = { name: 'TOP_LEVEL' };
129
187
  private authwits: Map<string, AuthWitness> = new Map();
188
+ private lastCallInfo: LastCallState = emptyLastCallState();
130
189
 
131
190
  constructor(
132
191
  private logger: Logger,
@@ -151,7 +210,6 @@ export class TXESession implements TXESessionStateHandler {
151
210
  private chainId: Fr,
152
211
  private version: Fr,
153
212
  private nextBlockTimestamp: bigint,
154
- private contractSyncService: ContractSyncService,
155
213
  ) {}
156
214
 
157
215
  static async init(contractStore: ContractStore) {
@@ -188,7 +246,6 @@ export class TXESession implements TXESessionStateHandler {
188
246
  const initialJobId = jobCoordinator.beginJob();
189
247
 
190
248
  const logger = createLogger('txe:session');
191
- const contractSyncService = new ContractSyncService(stateMachine.node, contractStore, noteStore, logger);
192
249
 
193
250
  const topLevelOracleHandler = new TXEOracleTopLevelContext(
194
251
  stateMachine,
@@ -206,7 +263,6 @@ export class TXESession implements TXESessionStateHandler {
206
263
  version,
207
264
  chainId,
208
265
  new Map(),
209
- contractSyncService,
210
266
  );
211
267
  await topLevelOracleHandler.advanceBlocksBy(1);
212
268
 
@@ -229,7 +285,6 @@ export class TXESession implements TXESessionStateHandler {
229
285
  version,
230
286
  chainId,
231
287
  nextBlockTimestamp,
232
- contractSyncService,
233
288
  );
234
289
  }
235
290
 
@@ -275,6 +330,50 @@ export class TXESession implements TXESessionStateHandler {
275
330
  return this.currentJobId;
276
331
  }
277
332
 
333
+ private resetLastCall(): void {
334
+ const notQueriedMessageCount = this.lastCallInfo.queried
335
+ ? 0
336
+ : this.lastCallInfo.offchainEffects.filter(payload => payload[0]?.equals(OFFCHAIN_MESSAGE_IDENTIFIER)).length;
337
+ if (notQueriedMessageCount > 0) {
338
+ this.logger.warn(
339
+ `Dropping ${notQueriedMessageCount} unqueried offchain message(s) from the previous top-level call. ` +
340
+ `To deliver them, call \`env.offchain_messages()\` and forward the result to the recipient contract's ` +
341
+ `\`offchain_receive\` utility before issuing another top-level call. To intentionally discard, assign ` +
342
+ `to \`let _ = env.offchain_messages()\` to silence this warning.`,
343
+ );
344
+ }
345
+ this.lastCallInfo = emptyLastCallState();
346
+ }
347
+
348
+ recordOffchainEffect(data: Fr[]): void {
349
+ this.lastCallInfo.offchainEffects.push(data);
350
+ }
351
+
352
+ private setLastCallContext(txHash: Fr, anchorBlockTimestamp: bigint): void {
353
+ this.lastCallInfo.txHash = txHash;
354
+ this.lastCallInfo.anchorBlockTimestamp = anchorBlockTimestamp;
355
+ }
356
+
357
+ async withTopLevelCallTracking<T>(work: () => Promise<{ result: T; txHash?: Fr }>): Promise<T> {
358
+ this.resetLastCall();
359
+ // Capture the anchor *before* `work` runs: private/public executor calls mine a new block as a
360
+ // side effect, and that block's timestamp should not be attributed to this call's anchor.
361
+ const anchorBlockTimestamp = (await this.stateMachine.node.getBlockHeader('latest'))!.globalVariables.timestamp;
362
+ const { result, txHash } = await work();
363
+ this.setLastCallContext(txHash ?? Fr.ZERO, anchorBlockTimestamp);
364
+ return result;
365
+ }
366
+
367
+ getLastCallOffchainEffects(): { effects: Fr[][] } {
368
+ this.lastCallInfo.queried = true;
369
+ return { effects: this.lastCallInfo.offchainEffects };
370
+ }
371
+
372
+ getLastCallContext(): { txHash: Fr; anchorBlockTimestamp: bigint } {
373
+ const { txHash, anchorBlockTimestamp } = this.lastCallInfo;
374
+ return { txHash, anchorBlockTimestamp };
375
+ }
376
+
278
377
  async enterTopLevelState() {
279
378
  switch (this.state.name) {
280
379
  case 'PRIVATE': {
@@ -316,7 +415,6 @@ export class TXESession implements TXESessionStateHandler {
316
415
  this.version,
317
416
  this.chainId,
318
417
  this.authwits,
319
- this.contractSyncService,
320
418
  );
321
419
 
322
420
  this.state = { name: 'TOP_LEVEL' };
@@ -328,6 +426,7 @@ export class TXESession implements TXESessionStateHandler {
328
426
  anchorBlockNumber?: BlockNumber,
329
427
  ): Promise<PrivateContextInputs> {
330
428
  this.exitTopLevelState();
429
+ this.resetLastCall();
331
430
 
332
431
  // Private execution has two associated block numbers: the anchor block (i.e. the historical block that is used to
333
432
  // build the proof), and the *next* block, i.e. the one we'll create once the execution ends, and which will contain
@@ -379,6 +478,7 @@ export class TXESession implements TXESessionStateHandler {
379
478
  jobId: this.currentJobId,
380
479
  scopes: await this.keyStore.getAccounts(),
381
480
  messageContextService: this.stateMachine.messageContextService,
481
+ simulator: new WASMSimulator(),
382
482
  });
383
483
 
384
484
  // We store the note and tagging index caches fed into the PrivateExecutionOracle (along with some other auxiliary
@@ -389,17 +489,22 @@ export class TXESession implements TXESessionStateHandler {
389
489
  this.state = { name: 'PRIVATE', nextBlockGlobalVariables, noteCache, taggingIndexCache };
390
490
  this.logger.debug(`Entered state ${this.state.name}`);
391
491
 
492
+ // Record the *resolved* anchor's timestamp — if the caller pinned the anchor to a past block
493
+ // via `anchorBlockNumber`, "latest" would be the wrong anchor for offchain-message semantics.
494
+ this.setLastCallContext(Fr.ZERO, anchorBlock!.globalVariables.timestamp);
495
+
392
496
  return (this.oracleHandler as PrivateExecutionOracle).getPrivateContextInputs();
393
497
  }
394
498
 
395
499
  async enterPublicState(contractAddress?: AztecAddress) {
396
500
  this.exitTopLevelState();
501
+ this.resetLastCall();
397
502
 
398
503
  // The PublicContext will create a block with a single transaction in it, containing the effects of what was done in
399
504
  // the test. The block therefore gets the *next* block number and timestamp.
400
- const latestBlockNumber = (await this.stateMachine.node.getBlockHeader('latest'))!.globalVariables.blockNumber;
505
+ const latestHeader = (await this.stateMachine.node.getBlockHeader('latest'))!;
401
506
  const globalVariables = makeGlobalVariables(undefined, {
402
- blockNumber: BlockNumber(latestBlockNumber + 1),
507
+ blockNumber: BlockNumber(latestHeader.globalVariables.blockNumber + 1),
403
508
  timestamp: this.nextBlockTimestamp,
404
509
  version: this.version,
405
510
  chainId: this.chainId,
@@ -414,10 +519,14 @@ export class TXESession implements TXESessionStateHandler {
414
519
 
415
520
  this.state = { name: 'PUBLIC' };
416
521
  this.logger.debug(`Entered state ${this.state.name}`);
522
+
523
+ // Public state is anchored at the latest block.
524
+ this.setLastCallContext(Fr.ZERO, latestHeader.globalVariables.timestamp);
417
525
  }
418
526
 
419
527
  async enterUtilityState(contractAddress: AztecAddress = DEFAULT_ADDRESS) {
420
528
  this.exitTopLevelState();
529
+ this.resetLastCall();
421
530
 
422
531
  const anchorBlockHeader = await this.stateMachine.anchorBlockStore.getBlockHeader();
423
532
 
@@ -448,14 +557,18 @@ export class TXESession implements TXESessionStateHandler {
448
557
  capsuleService: new CapsuleService(this.capsuleStore, await this.keyStore.getAccounts()),
449
558
  privateEventStore: this.privateEventStore,
450
559
  messageContextService: this.stateMachine.messageContextService,
451
- contractSyncService: this.contractSyncService,
560
+ contractSyncService: this.stateMachine.contractSyncService,
452
561
  l2TipsStore: this.stateMachine.node,
453
562
  jobId: this.currentJobId,
454
563
  scopes: await this.keyStore.getAccounts(),
564
+ simulator: new WASMSimulator(),
455
565
  });
456
566
 
457
567
  this.state = { name: 'UTILITY' };
458
568
  this.logger.debug(`Entered state ${this.state.name}`);
569
+
570
+ // Utility state anchors at whatever the anchor block store is pointing to (tracked as latest).
571
+ this.setLastCallContext(Fr.ZERO, anchorBlockHeader.globalVariables.timestamp);
459
572
  }
460
573
 
461
574
  private exitTopLevelState() {
@@ -527,6 +640,7 @@ export class TXESession implements TXESessionStateHandler {
527
640
  }
528
641
 
529
642
  try {
643
+ const simulator = new WASMSimulator();
530
644
  const oracle = new UtilityExecutionOracle({
531
645
  contractAddress: call.to,
532
646
  authWitnesses: [],
@@ -542,12 +656,13 @@ export class TXESession implements TXESessionStateHandler {
542
656
  capsuleService: new CapsuleService(this.capsuleStore, scopes),
543
657
  privateEventStore: this.privateEventStore,
544
658
  messageContextService: this.stateMachine.messageContextService,
545
- contractSyncService: this.contractSyncService,
659
+ contractSyncService: this.stateMachine.contractSyncService,
546
660
  l2TipsStore: this.stateMachine.node,
547
661
  jobId: this.currentJobId,
548
662
  scopes,
663
+ simulator,
549
664
  });
550
- await new WASMSimulator()
665
+ await simulator
551
666
  .executeUserCircuit(toACVMWitness(0, call.args), entryPointArtifact, new Oracle(oracle).toACIRCallback())
552
667
  .catch((err: Error) => {
553
668
  err.message = resolveAssertionMessageFromError(err, entryPointArtifact);