@aztec/pxe 0.0.1-commit.f504929 → 0.0.1-commit.f5d02921e

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 (123) hide show
  1. package/dest/block_synchronizer/block_synchronizer.d.ts +1 -1
  2. package/dest/block_synchronizer/block_synchronizer.d.ts.map +1 -1
  3. package/dest/block_synchronizer/block_synchronizer.js +6 -0
  4. package/dest/config/index.d.ts +2 -2
  5. package/dest/config/index.d.ts.map +1 -1
  6. package/dest/config/index.js +1 -1
  7. package/dest/contract_function_simulator/contract_function_simulator.d.ts +9 -3
  8. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  9. package/dest/contract_function_simulator/contract_function_simulator.js +29 -6
  10. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts +5 -5
  11. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts.map +1 -1
  12. package/dest/contract_function_simulator/execution_tagging_index_cache.js +17 -9
  13. package/dest/contract_function_simulator/index.d.ts +2 -1
  14. package/dest/contract_function_simulator/index.d.ts.map +1 -1
  15. package/dest/contract_function_simulator/index.js +1 -0
  16. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts +3 -5
  17. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts.map +1 -1
  18. package/dest/contract_function_simulator/noir-structs/event_validation_request.js +7 -9
  19. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts +1 -1
  20. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts.map +1 -1
  21. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.js +1 -3
  22. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts +3 -6
  23. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts.map +1 -1
  24. package/dest/contract_function_simulator/noir-structs/note_validation_request.js +5 -10
  25. package/dest/contract_function_simulator/oracle/interfaces.d.ts +26 -21
  26. package/dest/contract_function_simulator/oracle/interfaces.d.ts.map +1 -1
  27. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts +9 -0
  28. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.d.ts.map +1 -0
  29. package/dest/contract_function_simulator/oracle/legacy_oracle_mappings.js +38 -0
  30. package/dest/contract_function_simulator/oracle/oracle.d.ts +39 -19
  31. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  32. package/dest/contract_function_simulator/oracle/oracle.js +91 -44
  33. package/dest/contract_function_simulator/oracle/private_execution.js +5 -3
  34. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +11 -36
  35. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts.map +1 -1
  36. package/dest/contract_function_simulator/oracle/private_execution_oracle.js +12 -44
  37. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +50 -28
  38. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts.map +1 -1
  39. package/dest/contract_function_simulator/oracle/utility_execution_oracle.js +167 -64
  40. package/dest/contract_logging.d.ts +9 -4
  41. package/dest/contract_logging.d.ts.map +1 -1
  42. package/dest/contract_logging.js +21 -6
  43. package/dest/contract_sync/contract_sync_service.d.ts +7 -4
  44. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -1
  45. package/dest/contract_sync/contract_sync_service.js +59 -32
  46. package/dest/contract_sync/helpers.d.ts +2 -2
  47. package/dest/contract_sync/helpers.d.ts.map +1 -1
  48. package/dest/contract_sync/helpers.js +7 -2
  49. package/dest/events/event_service.d.ts +3 -2
  50. package/dest/events/event_service.d.ts.map +1 -1
  51. package/dest/events/event_service.js +16 -4
  52. package/dest/logs/log_service.d.ts +6 -7
  53. package/dest/logs/log_service.d.ts.map +1 -1
  54. package/dest/logs/log_service.js +24 -28
  55. package/dest/messages/message_context_service.d.ts +17 -0
  56. package/dest/messages/message_context_service.d.ts.map +1 -0
  57. package/dest/messages/message_context_service.js +36 -0
  58. package/dest/notes/note_service.d.ts +2 -2
  59. package/dest/notes/note_service.d.ts.map +1 -1
  60. package/dest/notes/note_service.js +14 -5
  61. package/dest/oracle_version.d.ts +2 -2
  62. package/dest/oracle_version.js +2 -2
  63. package/dest/pxe.d.ts +6 -3
  64. package/dest/pxe.d.ts.map +1 -1
  65. package/dest/pxe.js +37 -21
  66. package/dest/storage/capsule_store/capsule_service.d.ts +22 -0
  67. package/dest/storage/capsule_store/capsule_service.d.ts.map +1 -0
  68. package/dest/storage/capsule_store/capsule_service.js +50 -0
  69. package/dest/storage/capsule_store/capsule_store.d.ts +9 -9
  70. package/dest/storage/capsule_store/capsule_store.d.ts.map +1 -1
  71. package/dest/storage/capsule_store/capsule_store.js +33 -28
  72. package/dest/storage/capsule_store/index.d.ts +2 -1
  73. package/dest/storage/capsule_store/index.d.ts.map +1 -1
  74. package/dest/storage/capsule_store/index.js +1 -0
  75. package/dest/storage/metadata.d.ts +1 -1
  76. package/dest/storage/metadata.js +1 -1
  77. package/dest/storage/tagging_store/sender_tagging_store.d.ts +26 -25
  78. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  79. package/dest/storage/tagging_store/sender_tagging_store.js +141 -115
  80. package/dest/tagging/index.d.ts +2 -2
  81. package/dest/tagging/index.d.ts.map +1 -1
  82. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +1 -1
  83. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  84. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +10 -1
  85. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +4 -3
  86. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  87. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +20 -10
  88. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +2 -1
  89. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  90. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +24 -11
  91. package/package.json +16 -16
  92. package/src/block_synchronizer/block_synchronizer.ts +6 -0
  93. package/src/config/index.ts +1 -1
  94. package/src/contract_function_simulator/contract_function_simulator.ts +40 -7
  95. package/src/contract_function_simulator/execution_tagging_index_cache.ts +16 -11
  96. package/src/contract_function_simulator/index.ts +1 -0
  97. package/src/contract_function_simulator/noir-structs/event_validation_request.ts +8 -8
  98. package/src/contract_function_simulator/noir-structs/log_retrieval_response.ts +1 -4
  99. package/src/contract_function_simulator/noir-structs/note_validation_request.ts +3 -9
  100. package/src/contract_function_simulator/oracle/interfaces.ts +38 -29
  101. package/src/contract_function_simulator/oracle/legacy_oracle_mappings.ts +98 -0
  102. package/src/contract_function_simulator/oracle/oracle.ts +120 -64
  103. package/src/contract_function_simulator/oracle/private_execution.ts +4 -4
  104. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +14 -62
  105. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +290 -77
  106. package/src/contract_logging.ts +18 -5
  107. package/src/contract_sync/contract_sync_service.ts +89 -49
  108. package/src/contract_sync/helpers.ts +3 -2
  109. package/src/events/event_service.ts +17 -4
  110. package/src/logs/log_service.ts +51 -46
  111. package/src/messages/message_context_service.ts +44 -0
  112. package/src/notes/note_service.ts +16 -5
  113. package/src/oracle_version.ts +2 -2
  114. package/src/pxe.ts +55 -19
  115. package/src/storage/capsule_store/capsule_service.ts +91 -0
  116. package/src/storage/capsule_store/capsule_store.ts +34 -26
  117. package/src/storage/capsule_store/index.ts +1 -0
  118. package/src/storage/metadata.ts +1 -1
  119. package/src/storage/tagging_store/sender_tagging_store.ts +182 -135
  120. package/src/tagging/index.ts +1 -1
  121. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +19 -1
  122. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +26 -11
  123. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +19 -9
package/src/pxe.ts CHANGED
@@ -68,6 +68,7 @@ import { PXEDebugUtils } from './debug/pxe_debug_utils.js';
68
68
  import { enrichPublicSimulationError, enrichSimulationError } from './error_enriching.js';
69
69
  import { PrivateEventFilterValidator } from './events/private_event_filter_validator.js';
70
70
  import { JobCoordinator } from './job_coordinator/job_coordinator.js';
71
+ import { MessageContextService } from './messages/message_context_service.js';
71
72
  import {
72
73
  PrivateKernelExecutionProver,
73
74
  type PrivateKernelExecutionProverConfig,
@@ -106,7 +107,9 @@ export type SimulateTxOpts = {
106
107
  skipTxValidation?: boolean;
107
108
  /** If false, fees are enforced. */
108
109
  skipFeeEnforcement?: boolean;
109
- /** State overrides for the simulation, such as contract instances and artifacts. */
110
+ /** If true, kernel logic is emulated in TS for simulation */
111
+ skipKernels?: boolean;
112
+ /** State overrides for the simulation, such as contract instances and artifacts. Requires skipKernels: true */
110
113
  overrides?: SimulationOverrides;
111
114
  /** Addresses whose private state and keys are accessible during private execution */
112
115
  scopes: AccessScopes;
@@ -158,6 +161,7 @@ export class PXE {
158
161
  private addressStore: AddressStore,
159
162
  private privateEventStore: PrivateEventStore,
160
163
  private contractSyncService: ContractSyncService,
164
+ private messageContextService: MessageContextService,
161
165
  private simulator: CircuitSimulator,
162
166
  private proverEnabled: boolean,
163
167
  private proofCreator: PrivateKernelProver,
@@ -211,8 +215,11 @@ export class PXE {
211
215
  node,
212
216
  contractStore,
213
217
  noteStore,
218
+ () => keyStore.getAccounts(),
214
219
  createLogger('pxe:contract_sync', bindings),
215
220
  );
221
+ const messageContextService = new MessageContextService(node);
222
+
216
223
  const synchronizer = new BlockSynchronizer(
217
224
  node,
218
225
  store,
@@ -254,6 +261,7 @@ export class PXE {
254
261
  addressStore,
255
262
  privateEventStore,
256
263
  contractSyncService,
264
+ messageContextService,
257
265
  simulator,
258
266
  proverEnabled,
259
267
  proofCreator,
@@ -295,6 +303,7 @@ export class PXE {
295
303
  privateEventStore: this.privateEventStore,
296
304
  simulator: this.simulator,
297
305
  contractSyncService: this.contractSyncService,
306
+ messageContextService: this.messageContextService,
298
307
  });
299
308
  }
300
309
 
@@ -414,7 +423,14 @@ export class PXE {
414
423
  ) {
415
424
  try {
416
425
  const anchorBlockHeader = await this.anchorBlockStore.getBlockHeader();
417
- return contractFunctionSimulator.runUtility(call, authWitnesses ?? [], anchorBlockHeader, scopes, jobId);
426
+ const { result, offchainEffects } = await contractFunctionSimulator.runUtility(
427
+ call,
428
+ authWitnesses ?? [],
429
+ anchorBlockHeader,
430
+ scopes,
431
+ jobId,
432
+ );
433
+ return { result, offchainEffects };
418
434
  } catch (err) {
419
435
  if (err instanceof SimulationError) {
420
436
  await enrichSimulationError(err, this.contractStore, this.log);
@@ -487,7 +503,9 @@ export class PXE {
487
503
  * @returns The synced block header
488
504
  */
489
505
  public getSyncedBlockHeader(): Promise<BlockHeader> {
490
- return this.anchorBlockStore.getBlockHeader();
506
+ return this.#putInJobQueue(() => {
507
+ return this.anchorBlockStore.getBlockHeader();
508
+ });
491
509
  }
492
510
 
493
511
  /**
@@ -554,6 +572,9 @@ export class PXE {
554
572
 
555
573
  if (wasAdded) {
556
574
  this.log.info(`Added sender:\n ${sender.toString()}`);
575
+ // Wipe the entire sync cache: the new sender's tagged logs could contain notes/events for any contract, so
576
+ // all contracts must re-sync to discover them.
577
+ this.contractSyncService.wipe();
557
578
  } else {
558
579
  this.log.info(`Sender:\n "${sender.toString()}"\n already registered.`);
559
580
  }
@@ -766,17 +787,17 @@ export class PXE {
766
787
  // transaction before this one is included in a block from this PXE, and that transaction contains a log with
767
788
  // a tag derived from the same secret, we would reuse the tag and the transactions would be linked. Hence
768
789
  // storing the tags here prevents linkage of txs sent from the same PXE.
769
- const preTagsUsedInTheTx = privateExecutionResult.entrypoint.preTags;
770
- if (preTagsUsedInTheTx.length > 0) {
790
+ const taggingIndexRangesUsedInTheTx = privateExecutionResult.entrypoint.taggingIndexRanges;
791
+ if (taggingIndexRangesUsedInTheTx.length > 0) {
771
792
  // TODO(benesjan): The following is an expensive operation. Figure out a way to avoid it.
772
793
  const txHash = (await txProvingResult.toTx()).txHash;
773
794
 
774
- await this.senderTaggingStore.storePendingIndexes(preTagsUsedInTheTx, txHash, jobId);
775
- this.log.debug(`Stored used pre-tags as sender for the tx`, {
776
- preTagsUsedInTheTx,
795
+ await this.senderTaggingStore.storePendingIndexes(taggingIndexRangesUsedInTheTx, txHash, jobId);
796
+ this.log.debug(`Stored used tagging index ranges as sender for the tx`, {
797
+ taggingIndexRangesUsedInTheTx,
777
798
  });
778
799
  } else {
779
- this.log.debug(`No pre-tags used in the tx`);
800
+ this.log.debug(`No tagging index ranges used in the tx`);
780
801
  }
781
802
 
782
803
  return txProvingResult;
@@ -883,7 +904,14 @@ export class PXE {
883
904
  */
884
905
  public simulateTx(
885
906
  txRequest: TxExecutionRequest,
886
- { simulatePublic, skipTxValidation = false, skipFeeEnforcement = false, overrides, scopes }: SimulateTxOpts,
907
+ {
908
+ simulatePublic,
909
+ skipTxValidation = false,
910
+ skipFeeEnforcement = false,
911
+ skipKernels = true,
912
+ overrides,
913
+ scopes,
914
+ }: SimulateTxOpts,
887
915
  ): Promise<TxSimulationResult> {
888
916
  // We disable concurrent simulations since those might execute oracles which read and write to the PXE stores (e.g.
889
917
  // to the capsules), and we need to prevent concurrent runs from interfering with one another (e.g. attempting to
@@ -907,17 +935,20 @@ export class PXE {
907
935
  await this.blockStateSynchronizer.sync();
908
936
  const syncTime = syncTimer.ms();
909
937
 
910
- const contractFunctionSimulator = this.#getSimulatorForTx(overrides);
911
- // Temporary: in case there are overrides, we have to skip the kernels or validations
912
- // will fail. Consider handing control to the user/wallet on whether they want to run them
913
- // or not.
914
938
  const overriddenContracts = overrides?.contracts ? new Set(Object.keys(overrides.contracts)) : undefined;
915
939
  const hasOverriddenContracts = overriddenContracts !== undefined && overriddenContracts.size > 0;
916
- const skipKernels = hasOverriddenContracts;
917
940
 
918
- // Set overridden contracts on the sync service so it knows to skip syncing them
941
+ if (hasOverriddenContracts && !skipKernels) {
942
+ throw new Error(
943
+ 'Simulating with overridden contracts is not compatible with kernel execution. Please set skipKernels to true when simulating with overridden contracts.',
944
+ );
945
+ }
946
+ const contractFunctionSimulator = this.#getSimulatorForTx(overrides);
947
+
919
948
  if (hasOverriddenContracts) {
920
- this.contractSyncService.setOverriddenContracts(jobId, overriddenContracts);
949
+ // Overridden contracts don't have a sync function, so calling sync on them would fail.
950
+ // We exclude them so the sync service skips them entirely.
951
+ this.contractSyncService.setExcludedFromSync(jobId, overriddenContracts);
921
952
  }
922
953
 
923
954
  // Execution of private functions only; no proving, and no kernel logic.
@@ -1049,7 +1080,7 @@ export class PXE {
1049
1080
  scopes,
1050
1081
  );
1051
1082
 
1052
- const executionResult = await this.#executeUtility(
1083
+ const { result: executionResult, offchainEffects } = await this.#executeUtility(
1053
1084
  contractFunctionSimulator,
1054
1085
  call,
1055
1086
  authwits ?? [],
@@ -1070,7 +1101,12 @@ export class PXE {
1070
1101
  };
1071
1102
 
1072
1103
  const simulationStats = contractFunctionSimulator.getStats();
1073
- return { result: executionResult, stats: { timings, nodeRPCCalls: simulationStats.nodeRPCCalls } };
1104
+ return {
1105
+ result: executionResult,
1106
+ offchainEffects,
1107
+ anchorBlockTimestamp: anchorBlockHeader.globalVariables.timestamp,
1108
+ stats: { timings, nodeRPCCalls: simulationStats.nodeRPCCalls },
1109
+ };
1074
1110
  } catch (err: any) {
1075
1111
  const { to, name, args } = call;
1076
1112
  const stringifiedArgs = args.map(arg => arg.toString()).join(', ');
@@ -0,0 +1,91 @@
1
+ import type { Fr } from '@aztec/foundation/curves/bn254';
2
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
3
+ import type { Capsule } from '@aztec/stdlib/tx';
4
+
5
+ import type { AccessScopes } from '../../access_scopes.js';
6
+ import type { CapsuleStore } from './capsule_store.js';
7
+
8
+ /**
9
+ * Wraps a CapsuleStore with scope-based access control. Each operation asserts that the requested scope is in the
10
+ * allowed scopes list before delegating to the underlying store.
11
+ */
12
+ export class CapsuleService {
13
+ constructor(
14
+ private readonly capsuleStore: CapsuleStore,
15
+ private readonly allowedScopes: AccessScopes,
16
+ ) {}
17
+
18
+ setCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[], jobId: string, scope: AztecAddress) {
19
+ assertAllowedScope(scope, this.allowedScopes);
20
+ this.capsuleStore.setCapsule(contractAddress, slot, capsule, jobId, scope);
21
+ }
22
+
23
+ async getCapsule(
24
+ contractAddress: AztecAddress,
25
+ slot: Fr,
26
+ jobId: string,
27
+ scope: AztecAddress,
28
+ transientCapsules?: Capsule[],
29
+ ): Promise<Fr[] | null> {
30
+ assertAllowedScope(scope, this.allowedScopes);
31
+
32
+ // TODO(#12425): On the following line, the pertinent capsule gets overshadowed by the transient one. Tackle this.
33
+ const maybeTransientCapsule = transientCapsules?.find(
34
+ c =>
35
+ c.contractAddress.equals(contractAddress) &&
36
+ c.storageSlot.equals(slot) &&
37
+ (c.scope ?? AztecAddress.ZERO).equals(scope),
38
+ )?.data;
39
+
40
+ return maybeTransientCapsule ?? (await this.capsuleStore.getCapsule(contractAddress, slot, jobId, scope));
41
+ }
42
+
43
+ deleteCapsule(contractAddress: AztecAddress, slot: Fr, jobId: string, scope: AztecAddress) {
44
+ assertAllowedScope(scope, this.allowedScopes);
45
+ this.capsuleStore.deleteCapsule(contractAddress, slot, jobId, scope);
46
+ }
47
+
48
+ copyCapsule(
49
+ contractAddress: AztecAddress,
50
+ srcSlot: Fr,
51
+ dstSlot: Fr,
52
+ numEntries: number,
53
+ jobId: string,
54
+ scope: AztecAddress,
55
+ ): Promise<void> {
56
+ assertAllowedScope(scope, this.allowedScopes);
57
+ return this.capsuleStore.copyCapsule(contractAddress, srcSlot, dstSlot, numEntries, jobId, scope);
58
+ }
59
+
60
+ appendToCapsuleArray(
61
+ contractAddress: AztecAddress,
62
+ baseSlot: Fr,
63
+ content: Fr[][],
64
+ jobId: string,
65
+ scope: AztecAddress,
66
+ ): Promise<void> {
67
+ assertAllowedScope(scope, this.allowedScopes);
68
+ return this.capsuleStore.appendToCapsuleArray(contractAddress, baseSlot, content, jobId, scope);
69
+ }
70
+
71
+ readCapsuleArray(contractAddress: AztecAddress, baseSlot: Fr, jobId: string, scope: AztecAddress): Promise<Fr[][]> {
72
+ assertAllowedScope(scope, this.allowedScopes);
73
+ return this.capsuleStore.readCapsuleArray(contractAddress, baseSlot, jobId, scope);
74
+ }
75
+
76
+ setCapsuleArray(contractAddress: AztecAddress, baseSlot: Fr, content: Fr[][], jobId: string, scope: AztecAddress) {
77
+ assertAllowedScope(scope, this.allowedScopes);
78
+ return this.capsuleStore.setCapsuleArray(contractAddress, baseSlot, content, jobId, scope);
79
+ }
80
+ }
81
+
82
+ function assertAllowedScope(scope: AztecAddress, allowedScopes: AccessScopes) {
83
+ if (allowedScopes === 'ALL_SCOPES' || scope.equals(AztecAddress.ZERO)) {
84
+ return;
85
+ }
86
+ if (!allowedScopes.some(allowed => allowed.equals(scope))) {
87
+ throw new Error(
88
+ `Scope ${scope.toString()} is not in the allowed scopes list: [${allowedScopes.map(s => s.toString()).join(', ')}]. See https://docs.aztec.network/errors/10`,
89
+ );
90
+ }
91
+ }
@@ -1,7 +1,7 @@
1
1
  import { Fr } from '@aztec/foundation/curves/bn254';
2
2
  import { type Logger, createLogger } from '@aztec/foundation/log';
3
3
  import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
4
- import type { AztecAddress } from '@aztec/stdlib/aztec-address';
4
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
5
5
 
6
6
  import type { StagedStore } from '../../job_coordinator/job_coordinator.js';
7
7
 
@@ -10,11 +10,12 @@ export class CapsuleStore implements StagedStore {
10
10
 
11
11
  #store: AztecAsyncKVStore;
12
12
 
13
- // Arbitrary data stored by contracts. Key is computed as `${contractAddress}:${key}`
13
+ // Arbitrary data stored by contracts. Key is computed as `${contractAddress}:${scope}:${key}`, using the zero
14
+ // address for the global scope.
14
15
  #capsules: AztecAsyncMap<string, Buffer>;
15
16
 
16
- // jobId => `${contractAddress}:${key}` => capsule data
17
- // when `#stagedCapsules.get('some-job-id').get('${some-contract-address:some-key') === null`,
17
+ // jobId => `${contractAddress}:${scope}:${key}` => capsule data
18
+ // when `#stagedCapsules.get('some-job-id').get('${some-contract-address}:${some-scope}:${some-key}') === null`,
18
19
  // it signals that the capsule was deleted during the job, so it needs to be deleted on commit
19
20
  #stagedCapsules: Map<string, Map<string, Buffer | null>>;
20
21
 
@@ -134,8 +135,8 @@ export class CapsuleStore implements StagedStore {
134
135
  * to public contract storage in that it's indexed by the contract address and storage slot but instead of the global
135
136
  * network state it's backed by local PXE db.
136
137
  */
137
- storeCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[], jobId: string) {
138
- const dbSlotKey = dbSlotToKey(contractAddress, slot);
138
+ setCapsule(contractAddress: AztecAddress, slot: Fr, capsule: Fr[], jobId: string, scope: AztecAddress) {
139
+ const dbSlotKey = dbSlotToKey(contractAddress, slot, scope);
139
140
 
140
141
  // A store overrides any pre-existing data on the slot
141
142
  this.#setOnStage(jobId, dbSlotKey, Buffer.concat(capsule.map(value => value.toBuffer())));
@@ -147,8 +148,8 @@ export class CapsuleStore implements StagedStore {
147
148
  * @param slot - The slot in the database to read.
148
149
  * @returns The stored data or `null` if no data is stored under the slot.
149
150
  */
150
- async loadCapsule(contractAddress: AztecAddress, slot: Fr, jobId: string): Promise<Fr[] | null> {
151
- const dataBuffer = await this.#getFromStage(jobId, dbSlotToKey(contractAddress, slot));
151
+ async getCapsule(contractAddress: AztecAddress, slot: Fr, jobId: string, scope: AztecAddress): Promise<Fr[] | null> {
152
+ const dataBuffer = await this.#getFromStage(jobId, dbSlotToKey(contractAddress, slot, scope));
152
153
  if (!dataBuffer) {
153
154
  this.logger.trace(`Data not found for contract ${contractAddress.toString()} and slot ${slot.toString()}`);
154
155
  return null;
@@ -165,9 +166,9 @@ export class CapsuleStore implements StagedStore {
165
166
  * @param contractAddress - The contract address under which the data is scoped.
166
167
  * @param slot - The slot in the database to delete.
167
168
  */
168
- deleteCapsule(contractAddress: AztecAddress, slot: Fr, jobId: string) {
169
+ deleteCapsule(contractAddress: AztecAddress, slot: Fr, jobId: string, scope: AztecAddress) {
169
170
  // When we commit this, we will interpret null as a deletion, so we'll propagate the delete to the KV store
170
- this.#deleteOnStage(jobId, dbSlotToKey(contractAddress, slot));
171
+ this.#deleteOnStage(jobId, dbSlotToKey(contractAddress, slot, scope));
171
172
  }
172
173
 
173
174
  /**
@@ -187,6 +188,7 @@ export class CapsuleStore implements StagedStore {
187
188
  dstSlot: Fr,
188
189
  numEntries: number,
189
190
  jobId: string,
191
+ scope: AztecAddress,
190
192
  ): Promise<void> {
191
193
  // This transactional context gives us "copy atomicity":
192
194
  // there shouldn't be concurrent writes to what's being copied here.
@@ -203,8 +205,8 @@ export class CapsuleStore implements StagedStore {
203
205
  }
204
206
 
205
207
  for (const i of indexes) {
206
- const currentSrcSlot = dbSlotToKey(contractAddress, srcSlot.add(new Fr(i)));
207
- const currentDstSlot = dbSlotToKey(contractAddress, dstSlot.add(new Fr(i)));
208
+ const currentSrcSlot = dbSlotToKey(contractAddress, srcSlot.add(new Fr(i)), scope);
209
+ const currentDstSlot = dbSlotToKey(contractAddress, dstSlot.add(new Fr(i)), scope);
208
210
 
209
211
  const toCopy = await this.#getFromStage(jobId, currentSrcSlot);
210
212
  if (!toCopy) {
@@ -224,7 +226,13 @@ export class CapsuleStore implements StagedStore {
224
226
  * @param baseSlot - The slot where the array length is stored
225
227
  * @param content - Array of capsule data to append
226
228
  */
227
- appendToCapsuleArray(contractAddress: AztecAddress, baseSlot: Fr, content: Fr[][], jobId: string): Promise<void> {
229
+ appendToCapsuleArray(
230
+ contractAddress: AztecAddress,
231
+ baseSlot: Fr,
232
+ content: Fr[][],
233
+ jobId: string,
234
+ scope: AztecAddress,
235
+ ): Promise<void> {
228
236
  // We wrap this in a transaction to serialize concurrent calls from Promise.all.
229
237
  // Without this, concurrent appends to the same array could race: both read length=0,
230
238
  // both write at the same slots, one overwrites the other.
@@ -232,22 +240,22 @@ export class CapsuleStore implements StagedStore {
232
240
  // and not using a transaction here would heavily impact performance.
233
241
  return this.#store.transactionAsync(async () => {
234
242
  // Load current length, defaulting to 0 if not found
235
- const lengthData = await this.loadCapsule(contractAddress, baseSlot, jobId);
243
+ const lengthData = await this.getCapsule(contractAddress, baseSlot, jobId, scope);
236
244
  const currentLength = lengthData ? lengthData[0].toNumber() : 0;
237
245
 
238
246
  // Store each capsule at consecutive slots after baseSlot + 1 + currentLength
239
247
  for (let i = 0; i < content.length; i++) {
240
248
  const nextSlot = arraySlot(baseSlot, currentLength + i);
241
- this.storeCapsule(contractAddress, nextSlot, content[i], jobId);
249
+ this.setCapsule(contractAddress, nextSlot, content[i], jobId, scope);
242
250
  }
243
251
 
244
252
  // Update length to include all new capsules
245
253
  const newLength = currentLength + content.length;
246
- this.storeCapsule(contractAddress, baseSlot, [new Fr(newLength)], jobId);
254
+ this.setCapsule(contractAddress, baseSlot, [new Fr(newLength)], jobId, scope);
247
255
  });
248
256
  }
249
257
 
250
- readCapsuleArray(contractAddress: AztecAddress, baseSlot: Fr, jobId: string): Promise<Fr[][]> {
258
+ readCapsuleArray(contractAddress: AztecAddress, baseSlot: Fr, jobId: string, scope: AztecAddress): Promise<Fr[][]> {
251
259
  // I'm leaving this transactional context here though because I'm assuming this
252
260
  // gives us "read array atomicity": there shouldn't be concurrent writes to what's being copied
253
261
  // here.
@@ -255,14 +263,14 @@ export class CapsuleStore implements StagedStore {
255
263
  // of jobs: different calls running concurrently on the same contract may cause trouble.
256
264
  return this.#store.transactionAsync(async () => {
257
265
  // Load length, defaulting to 0 if not found
258
- const maybeLength = await this.loadCapsule(contractAddress, baseSlot, jobId);
266
+ const maybeLength = await this.getCapsule(contractAddress, baseSlot, jobId, scope);
259
267
  const length = maybeLength ? maybeLength[0].toBigInt() : 0n;
260
268
 
261
269
  const values: Fr[][] = [];
262
270
 
263
271
  // Read each capsule at consecutive slots after baseSlot
264
272
  for (let i = 0; i < length; i++) {
265
- const currentValue = await this.loadCapsule(contractAddress, arraySlot(baseSlot, i), jobId);
273
+ const currentValue = await this.getCapsule(contractAddress, arraySlot(baseSlot, i), jobId, scope);
266
274
  if (currentValue == undefined) {
267
275
  throw new Error(
268
276
  `Expected non-empty value at capsule array in base slot ${baseSlot} at index ${i} for contract ${contractAddress}`,
@@ -276,7 +284,7 @@ export class CapsuleStore implements StagedStore {
276
284
  });
277
285
  }
278
286
 
279
- setCapsuleArray(contractAddress: AztecAddress, baseSlot: Fr, content: Fr[][], jobId: string) {
287
+ setCapsuleArray(contractAddress: AztecAddress, baseSlot: Fr, content: Fr[][], jobId: string, scope: AztecAddress) {
280
288
  // This transactional context in theory isn't so critical now because we aren't
281
289
  // writing to DB so if there's exceptions midway and it blows up, no visible impact
282
290
  // to persistent storage will happen.
@@ -287,27 +295,27 @@ export class CapsuleStore implements StagedStore {
287
295
  // of jobs: different calls running concurrently on the same contract may cause trouble.
288
296
  return this.#store.transactionAsync(async () => {
289
297
  // Load current length, defaulting to 0 if not found
290
- const maybeLength = await this.loadCapsule(contractAddress, baseSlot, jobId);
298
+ const maybeLength = await this.getCapsule(contractAddress, baseSlot, jobId, scope);
291
299
  const originalLength = maybeLength ? maybeLength[0].toNumber() : 0;
292
300
 
293
301
  // Set the new length
294
- this.storeCapsule(contractAddress, baseSlot, [new Fr(content.length)], jobId);
302
+ this.setCapsule(contractAddress, baseSlot, [new Fr(content.length)], jobId, scope);
295
303
 
296
304
  // Store the new content, possibly overwriting existing values
297
305
  for (let i = 0; i < content.length; i++) {
298
- this.storeCapsule(contractAddress, arraySlot(baseSlot, i), content[i], jobId);
306
+ this.setCapsule(contractAddress, arraySlot(baseSlot, i), content[i], jobId, scope);
299
307
  }
300
308
 
301
309
  // Clear any stragglers
302
310
  for (let i = content.length; i < originalLength; i++) {
303
- this.deleteCapsule(contractAddress, arraySlot(baseSlot, i), jobId);
311
+ this.deleteCapsule(contractAddress, arraySlot(baseSlot, i), jobId, scope);
304
312
  }
305
313
  });
306
314
  }
307
315
  }
308
316
 
309
- function dbSlotToKey(contractAddress: AztecAddress, slot: Fr): string {
310
- return `${contractAddress.toString()}:${slot.toString()}`;
317
+ function dbSlotToKey(contractAddress: AztecAddress, slot: Fr, scope: AztecAddress): string {
318
+ return [contractAddress.toString(), scope.toString(), slot.toString()].join(':');
311
319
  }
312
320
 
313
321
  function arraySlot(baseSlot: Fr, index: number) {
@@ -1 +1,2 @@
1
+ export { CapsuleService } from './capsule_service.js';
1
2
  export { CapsuleStore } from './capsule_store.js';
@@ -1 +1 @@
1
- export const PXE_DATA_SCHEMA_VERSION = 3;
1
+ export const PXE_DATA_SCHEMA_VERSION = 5;