@aztec/pxe 0.0.1-commit.c0b82b2 → 0.0.1-commit.c2eed6949

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 (91) hide show
  1. package/dest/config/index.d.ts +2 -2
  2. package/dest/config/index.d.ts.map +1 -1
  3. package/dest/config/index.js +1 -1
  4. package/dest/contract_function_simulator/contract_function_simulator.d.ts +9 -3
  5. package/dest/contract_function_simulator/contract_function_simulator.d.ts.map +1 -1
  6. package/dest/contract_function_simulator/contract_function_simulator.js +28 -6
  7. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts +5 -5
  8. package/dest/contract_function_simulator/execution_tagging_index_cache.d.ts.map +1 -1
  9. package/dest/contract_function_simulator/execution_tagging_index_cache.js +17 -9
  10. package/dest/contract_function_simulator/index.d.ts +2 -1
  11. package/dest/contract_function_simulator/index.d.ts.map +1 -1
  12. package/dest/contract_function_simulator/index.js +1 -0
  13. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts +2 -3
  14. package/dest/contract_function_simulator/noir-structs/event_validation_request.d.ts.map +1 -1
  15. package/dest/contract_function_simulator/noir-structs/event_validation_request.js +5 -4
  16. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts +1 -1
  17. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.d.ts.map +1 -1
  18. package/dest/contract_function_simulator/noir-structs/log_retrieval_response.js +1 -3
  19. package/dest/contract_function_simulator/noir-structs/message_tx_context.d.ts +16 -0
  20. package/dest/contract_function_simulator/noir-structs/message_tx_context.d.ts.map +1 -0
  21. package/dest/contract_function_simulator/noir-structs/message_tx_context.js +57 -0
  22. package/dest/contract_function_simulator/noir-structs/note_validation_request.d.ts +2 -4
  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 +3 -5
  25. package/dest/contract_function_simulator/oracle/interfaces.d.ts +50 -45
  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 +42 -0
  30. package/dest/contract_function_simulator/oracle/oracle.d.ts +45 -44
  31. package/dest/contract_function_simulator/oracle/oracle.d.ts.map +1 -1
  32. package/dest/contract_function_simulator/oracle/oracle.js +163 -94
  33. package/dest/contract_function_simulator/oracle/private_execution.js +5 -3
  34. package/dest/contract_function_simulator/oracle/private_execution_oracle.d.ts +22 -47
  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 +30 -62
  37. package/dest/contract_function_simulator/oracle/utility_execution_oracle.d.ts +57 -39
  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 +134 -56
  40. package/dest/contract_sync/contract_sync_service.d.ts +5 -3
  41. package/dest/contract_sync/contract_sync_service.d.ts.map +1 -1
  42. package/dest/contract_sync/contract_sync_service.js +47 -30
  43. package/dest/messages/message_context_service.d.ts +17 -0
  44. package/dest/messages/message_context_service.d.ts.map +1 -0
  45. package/dest/messages/message_context_service.js +36 -0
  46. package/dest/oracle_version.d.ts +2 -2
  47. package/dest/oracle_version.js +3 -3
  48. package/dest/pxe.d.ts +6 -3
  49. package/dest/pxe.d.ts.map +1 -1
  50. package/dest/pxe.js +33 -19
  51. package/dest/storage/metadata.d.ts +1 -1
  52. package/dest/storage/metadata.js +1 -1
  53. package/dest/storage/tagging_store/sender_tagging_store.d.ts +26 -25
  54. package/dest/storage/tagging_store/sender_tagging_store.d.ts.map +1 -1
  55. package/dest/storage/tagging_store/sender_tagging_store.js +141 -115
  56. package/dest/tagging/index.d.ts +2 -2
  57. package/dest/tagging/index.d.ts.map +1 -1
  58. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts +1 -1
  59. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.d.ts.map +1 -1
  60. package/dest/tagging/sender_sync/sync_sender_tagging_indexes.js +10 -1
  61. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts +4 -3
  62. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.d.ts.map +1 -1
  63. package/dest/tagging/sender_sync/utils/get_status_change_of_pending.js +20 -10
  64. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts +2 -1
  65. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.d.ts.map +1 -1
  66. package/dest/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.js +24 -11
  67. package/package.json +16 -16
  68. package/src/config/index.ts +1 -1
  69. package/src/contract_function_simulator/contract_function_simulator.ts +39 -7
  70. package/src/contract_function_simulator/execution_tagging_index_cache.ts +16 -11
  71. package/src/contract_function_simulator/index.ts +1 -0
  72. package/src/contract_function_simulator/noir-structs/event_validation_request.ts +8 -5
  73. package/src/contract_function_simulator/noir-structs/log_retrieval_response.ts +1 -4
  74. package/src/contract_function_simulator/noir-structs/message_tx_context.ts +55 -0
  75. package/src/contract_function_simulator/noir-structs/note_validation_request.ts +3 -6
  76. package/src/contract_function_simulator/oracle/interfaces.ts +54 -54
  77. package/src/contract_function_simulator/oracle/legacy_oracle_mappings.ts +135 -0
  78. package/src/contract_function_simulator/oracle/oracle.ts +176 -138
  79. package/src/contract_function_simulator/oracle/private_execution.ts +4 -4
  80. package/src/contract_function_simulator/oracle/private_execution_oracle.ts +32 -80
  81. package/src/contract_function_simulator/oracle/utility_execution_oracle.ts +192 -73
  82. package/src/contract_sync/contract_sync_service.ts +67 -38
  83. package/src/messages/message_context_service.ts +45 -0
  84. package/src/oracle_version.ts +3 -3
  85. package/src/pxe.ts +51 -18
  86. package/src/storage/metadata.ts +1 -1
  87. package/src/storage/tagging_store/sender_tagging_store.ts +182 -135
  88. package/src/tagging/index.ts +1 -1
  89. package/src/tagging/sender_sync/sync_sender_tagging_indexes.ts +19 -1
  90. package/src/tagging/sender_sync/utils/get_status_change_of_pending.ts +26 -11
  91. package/src/tagging/sender_sync/utils/load_and_store_new_tagging_indexes.ts +19 -9
@@ -1,6 +1,7 @@
1
1
  import { Aes128 } from '@aztec/foundation/crypto/aes128';
2
2
  import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import { LogLevels, createLogger } from '@aztec/foundation/log';
4
+ import { isProtocolContract } from '@aztec/protocol-contracts';
4
5
  import { siloNullifier } from '@aztec/stdlib/hash';
5
6
  import { computeAddressSecret } from '@aztec/stdlib/keys';
6
7
  import { deriveEcdhSharedSecret } from '@aztec/stdlib/logs';
@@ -14,6 +15,7 @@ import { ORACLE_VERSION } from '../../oracle_version.js';
14
15
  import { EventValidationRequest } from '../noir-structs/event_validation_request.js';
15
16
  import { LogRetrievalRequest } from '../noir-structs/log_retrieval_request.js';
16
17
  import { LogRetrievalResponse } from '../noir-structs/log_retrieval_response.js';
18
+ import { MessageTxContext } from '../noir-structs/message_tx_context.js';
17
19
  import { NoteValidationRequest } from '../noir-structs/note_validation_request.js';
18
20
  import { UtilityContext } from '../noir-structs/utility_context.js';
19
21
  import { pickNotes } from '../pick_notes.js';
@@ -24,6 +26,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
24
26
  isMisc = true;
25
27
  isUtility = true;
26
28
  contractLogger;
29
+ offchainEffects = [];
27
30
  contractAddress;
28
31
  authWitnesses;
29
32
  capsules;
@@ -37,8 +40,10 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
37
40
  senderAddressBookStore;
38
41
  capsuleStore;
39
42
  privateEventStore;
43
+ messageContextService;
44
+ contractSyncService;
40
45
  jobId;
41
- log;
46
+ logger;
42
47
  scopes;
43
48
  constructor(args){
44
49
  this.contractAddress = args.contractAddress;
@@ -54,19 +59,33 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
54
59
  this.senderAddressBookStore = args.senderAddressBookStore;
55
60
  this.capsuleStore = args.capsuleStore;
56
61
  this.privateEventStore = args.privateEventStore;
62
+ this.messageContextService = args.messageContextService;
63
+ this.contractSyncService = args.contractSyncService;
57
64
  this.jobId = args.jobId;
58
- this.log = args.log ?? createLogger('simulator:client_view_context');
65
+ this.logger = args.log ?? createLogger('simulator:client_view_context');
59
66
  this.scopes = args.scopes;
60
67
  }
61
- utilityAssertCompatibleOracleVersion(version) {
68
+ assertCompatibleOracleVersion(version) {
69
+ // TODO(F-416): Remove this hack on v5 when protocol contracts are redeployed.
70
+ // Protocol contracts/canonical contracts shipped with committed bytecode that cannot be changed. Assert they use
71
+ // the expected pinned version or the current one. We want to allow for both the pinned and the current versions
72
+ // because we want this code to work with both the pinned and unpinned version since some branches do not have the
73
+ // pinned contracts (like e.g. next)
74
+ const LEGACY_ORACLE_VERSION = 12;
75
+ if (isProtocolContract(this.contractAddress)) {
76
+ if (version !== LEGACY_ORACLE_VERSION && version !== ORACLE_VERSION) {
77
+ throw new Error(`Expected legacy oracle version ${LEGACY_ORACLE_VERSION} or current oracle version ${ORACLE_VERSION} for alpha payload contract at ${this.contractAddress}, got ${version}.`);
78
+ }
79
+ return;
80
+ }
62
81
  if (version !== ORACLE_VERSION) {
63
82
  throw new Error(`Incompatible oracle version. Expected version ${ORACLE_VERSION}, got ${version}.`);
64
83
  }
65
84
  }
66
- utilityGetRandomField() {
85
+ getRandomField() {
67
86
  return Fr.random();
68
87
  }
69
- utilityGetUtilityContext() {
88
+ getUtilityContext() {
70
89
  return new UtilityContext(this.anchorBlockHeader, this.contractAddress);
71
90
  }
72
91
  /**
@@ -75,7 +94,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
75
94
  * @returns A Promise that resolves to nullifier keys.
76
95
  * @throws If the keys are not registered in the key store.
77
96
  * @throws If scopes are defined and the account is not in the scopes.
78
- */ async utilityGetKeyValidationRequest(pkMHash) {
97
+ */ async getKeyValidationRequest(pkMHash) {
79
98
  // If scopes are defined, check that the key belongs to an account in the scopes.
80
99
  if (this.scopes !== 'ALL_SCOPES' && this.scopes.length > 0) {
81
100
  let hasAccess = false;
@@ -92,12 +111,12 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
92
111
  }
93
112
  /**
94
113
  * Fetches the index and sibling path of a leaf at a given block from the note hash tree.
95
- * @param anchorBlockHash - The hash of a block that contains the note hash tree root in which to find the membership
96
- * witness.
114
+ * @param blockHash - The hash of a block that contains the note hash tree root in which to find the
115
+ * membership witness.
97
116
  * @param noteHash - The note hash to find in the note hash tree.
98
117
  * @returns The membership witness containing the leaf index and sibling path
99
- */ utilityGetNoteHashMembershipWitness(anchorBlockHash, noteHash) {
100
- return this.aztecNode.getNoteHashMembershipWitness(anchorBlockHash, noteHash);
118
+ */ getNoteHashMembershipWitness(blockHash, noteHash) {
119
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, ()=>this.aztecNode.getNoteHashMembershipWitness(blockHash, noteHash));
101
120
  }
102
121
  /**
103
122
  * Fetches the index and sibling path of a block hash in the archive tree.
@@ -105,20 +124,23 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
105
124
  * Block hashes are the leaves of the archive tree. Each time a new block is added to the chain,
106
125
  * its block hash is appended as a new leaf to the archive tree.
107
126
  *
108
- * @param anchorBlockHash - The hash of a block that contains the archive tree root in which to find the membership
127
+ * @param referenceBlockHash - The hash of a block that contains the archive tree root in which to find the membership
109
128
  * witness.
110
129
  * @param blockHash - The block hash to find in the archive tree.
111
130
  * @returns The membership witness containing the leaf index and sibling path
112
- */ utilityGetBlockHashMembershipWitness(anchorBlockHash, blockHash) {
113
- return this.aztecNode.getBlockHashMembershipWitness(anchorBlockHash, blockHash);
131
+ */ getBlockHashMembershipWitness(referenceBlockHash, blockHash) {
132
+ // Note that we validate that the reference block hash is at or before the anchor block - we don't test the block
133
+ // hash at all. If the block hash did not exist by the reference block hash, then the node will not return the
134
+ // membership witness as there is none.
135
+ return this.#queryWithBlockHashNotAfterAnchor(referenceBlockHash, ()=>this.aztecNode.getBlockHashMembershipWitness(referenceBlockHash, blockHash));
114
136
  }
115
137
  /**
116
138
  * Returns a nullifier membership witness for a given nullifier at a given block.
117
139
  * @param blockHash - The block hash at which to get the index.
118
140
  * @param nullifier - Nullifier we try to find witness for.
119
141
  * @returns The nullifier membership witness (if found).
120
- */ utilityGetNullifierMembershipWitness(blockHash, nullifier) {
121
- return this.aztecNode.getNullifierMembershipWitness(blockHash, nullifier);
142
+ */ getNullifierMembershipWitness(blockHash, nullifier) {
143
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, ()=>this.aztecNode.getNullifierMembershipWitness(blockHash, nullifier));
122
144
  }
123
145
  /**
124
146
  * Returns a low nullifier membership witness for a given nullifier at a given block.
@@ -128,22 +150,22 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
128
150
  * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
129
151
  * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
130
152
  * we are trying to prove non-inclusion for.
131
- */ utilityGetLowNullifierMembershipWitness(blockHash, nullifier) {
132
- return this.aztecNode.getLowNullifierMembershipWitness(blockHash, nullifier);
153
+ */ getLowNullifierMembershipWitness(blockHash, nullifier) {
154
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, ()=>this.aztecNode.getLowNullifierMembershipWitness(blockHash, nullifier));
133
155
  }
134
156
  /**
135
157
  * Returns a public data tree witness for a given leaf slot at a given block.
136
158
  * @param blockHash - The block hash at which to get the index.
137
159
  * @param leafSlot - The slot of the public data tree to get the witness for.
138
160
  * @returns - The witness
139
- */ utilityGetPublicDataWitness(blockHash, leafSlot) {
140
- return this.aztecNode.getPublicDataWitness(blockHash, leafSlot);
161
+ */ getPublicDataWitness(blockHash, leafSlot) {
162
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, ()=>this.aztecNode.getPublicDataWitness(blockHash, leafSlot));
141
163
  }
142
164
  /**
143
165
  * Fetches a block header of a given block.
144
166
  * @param blockNumber - The number of a block of which to get the block header.
145
167
  * @returns Block extracted from a block with block number `blockNumber`.
146
- */ async utilityGetBlockHeader(blockNumber) {
168
+ */ async getBlockHeader(blockNumber) {
147
169
  const anchorBlockNumber = this.anchorBlockHeader.getBlockNumber();
148
170
  if (blockNumber > anchorBlockNumber) {
149
171
  throw new Error(`Block number ${blockNumber} is higher than current block ${anchorBlockNumber}`);
@@ -152,11 +174,18 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
152
174
  return block?.header;
153
175
  }
154
176
  /**
155
- * Retrieve the complete address associated to a given address.
177
+ * Retrieve the public keys and partial address associated to a given address.
156
178
  * @param account - The account address.
157
- * @returns A complete address associated with the input address, or `undefined` if not registered.
158
- */ utilityTryGetPublicKeysAndPartialAddress(account) {
159
- return this.addressStore.getCompleteAddress(account);
179
+ * @returns The public keys and partial address, or `undefined` if the account is not registered.
180
+ */ async tryGetPublicKeysAndPartialAddress(account) {
181
+ const completeAddress = await this.addressStore.getCompleteAddress(account);
182
+ if (!completeAddress) {
183
+ return undefined;
184
+ }
185
+ return {
186
+ publicKeys: completeAddress.publicKeys,
187
+ partialAddress: completeAddress.partialAddress
188
+ };
160
189
  }
161
190
  async getCompleteAddressOrFail(account) {
162
191
  const completeAddress = await this.addressStore.getCompleteAddress(account);
@@ -170,10 +199,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
170
199
  * Returns a contract instance associated with an address or throws if not found.
171
200
  * @param address - Address.
172
201
  * @returns A contract instance.
173
- */ utilityGetContractInstance(address) {
174
- return this.getContractInstance(address);
175
- }
176
- async getContractInstance(address) {
202
+ */ async getContractInstance(address) {
177
203
  const instance = await this.contractStore.getContractInstance(address);
178
204
  if (!instance) {
179
205
  throw new Error(`No contract instance found for address ${address.toString()}`);
@@ -185,7 +211,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
185
211
  * for this transaction first, and falls back to the local database if not found.
186
212
  * @param messageHash - Hash of the message to authenticate.
187
213
  * @returns Authentication witness for the requested message hash.
188
- */ utilityGetAuthWitness(messageHash) {
214
+ */ getAuthWitness(messageHash) {
189
215
  return Promise.resolve(this.authWitnesses.find((w)=>w.requestHash.equals(messageHash))?.witness);
190
216
  }
191
217
  /**
@@ -209,7 +235,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
209
235
  * @param offset - The starting index for pagination.
210
236
  * @param status - The status of notes to fetch.
211
237
  * @returns Array of note data.
212
- */ async utilityGetNotes(owner, storageSlot, numSelects, selectByIndexes, selectByOffsets, selectByLengths, selectValues, selectComparators, sortByIndexes, sortByOffsets, sortByLengths, sortOrder, limit, offset, status) {
238
+ */ async getNotes(owner, storageSlot, numSelects, selectByIndexes, selectByOffsets, selectByLengths, selectValues, selectComparators, sortByIndexes, sortByOffsets, sortByLengths, sortOrder, limit, offset, status) {
213
239
  const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockHeader, this.jobId);
214
240
  const dbNotes = await noteService.getNotes(this.contractAddress, owner, storageSlot, status, this.scopes);
215
241
  return pickNotes(dbNotes, {
@@ -238,7 +264,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
238
264
  * Check if a nullifier exists in the nullifier tree.
239
265
  * @param innerNullifier - The inner nullifier.
240
266
  * @returns A boolean indicating whether the nullifier exists in the tree or not.
241
- */ async utilityCheckNullifierExists(innerNullifier) {
267
+ */ async checkNullifierExists(innerNullifier) {
242
268
  const [nullifier, anchorBlockHash] = await Promise.all([
243
269
  siloNullifier(this.contractAddress, innerNullifier),
244
270
  this.anchorBlockHeader.hash()
@@ -249,14 +275,14 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
249
275
  return leafIndex?.data !== undefined;
250
276
  }
251
277
  /**
252
- * Fetches a message from the executionStore, given its key.
278
+ * Returns the membership witness of an un-nullified L1 to L2 message.
253
279
  * @param contractAddress - Address of a contract by which the message was emitted.
254
280
  * @param messageHash - Hash of the message.
255
281
  * @param secret - Secret used to compute a nullifier.
256
282
  * @dev Contract address and secret are only used to compute the nullifier to get non-nullified messages
257
283
  * @returns The l1 to l2 membership witness (index of message in the tree and sibling path).
258
- */ async utilityGetL1ToL2MembershipWitness(contractAddress, messageHash, secret) {
259
- const [messageIndex, siblingPath] = await getNonNullifiedL1ToL2MessageWitness(this.aztecNode, contractAddress, messageHash, secret);
284
+ */ async getL1ToL2MembershipWitness(contractAddress, messageHash, secret) {
285
+ const [messageIndex, siblingPath] = await getNonNullifiedL1ToL2MessageWitness(this.aztecNode, contractAddress, messageHash, secret, await this.anchorBlockHeader.hash());
260
286
  return new MessageLoadOracleInputs(messageIndex, siblingPath);
261
287
  }
262
288
  /**
@@ -265,11 +291,13 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
265
291
  * @param contractAddress - The address to read storage from.
266
292
  * @param startStorageSlot - The starting storage slot.
267
293
  * @param numberOfElements - Number of elements to read from the starting storage slot.
268
- */ async utilityStorageRead(blockHash, contractAddress, startStorageSlot, numberOfElements) {
269
- const slots = Array(numberOfElements).fill(0).map((_, i)=>new Fr(startStorageSlot.value + BigInt(i)));
270
- const values = await Promise.all(slots.map((storageSlot)=>this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)));
271
- this.log.debug(`Oracle storage read: slots=[${slots.map((slot)=>slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`);
272
- return values;
294
+ */ storageRead(blockHash, contractAddress, startStorageSlot, numberOfElements) {
295
+ return this.#queryWithBlockHashNotAfterAnchor(blockHash, async ()=>{
296
+ const slots = Array(numberOfElements).fill(0).map((_, i)=>new Fr(startStorageSlot.value + BigInt(i)));
297
+ const values = await Promise.all(slots.map((storageSlot)=>this.aztecNode.getPublicStorageAt(blockHash, contractAddress, storageSlot)));
298
+ this.logger.debug(`Oracle storage read: slots=[${slots.map((slot)=>slot.toString()).join(', ')}] address=${contractAddress.toString()} values=[${values.join(', ')}]`);
299
+ return values;
300
+ });
273
301
  }
274
302
  /**
275
303
  * Returns a per-contract logger whose output is prefixed with `contract_log::<name>(<addrAbbrev>)`.
@@ -283,15 +311,15 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
283
311
  }
284
312
  return this.contractLogger;
285
313
  }
286
- async utilityLog(level, message, fields) {
314
+ async log(level, message, fields) {
287
315
  if (!LogLevels[level]) {
288
316
  throw new Error(`Invalid log level: ${level}`);
289
317
  }
290
318
  const logger = await this.#getContractLogger();
291
319
  logContractMessage(logger, LogLevels[level], message, fields);
292
320
  }
293
- async utilityFetchTaggedLogs(pendingTaggedLogArrayBaseSlot) {
294
- const logService = new LogService(this.aztecNode, this.anchorBlockHeader, this.keyStore, this.capsuleStore, this.recipientTaggingStore, this.senderAddressBookStore, this.addressStore, this.jobId, this.log.getBindings());
321
+ async fetchTaggedLogs(pendingTaggedLogArrayBaseSlot) {
322
+ const logService = new LogService(this.aztecNode, this.anchorBlockHeader, this.keyStore, this.capsuleStore, this.recipientTaggingStore, this.senderAddressBookStore, this.addressStore, this.jobId, this.logger.getBindings());
295
323
  await logService.fetchTaggedLogs(this.contractAddress, pendingTaggedLogArrayBaseSlot, this.scopes);
296
324
  }
297
325
  /**
@@ -303,15 +331,15 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
303
331
  * @param contractAddress - The address of the contract that the logs are tagged for.
304
332
  * @param noteValidationRequestsArrayBaseSlot - The base slot of capsule array containing note validation requests.
305
333
  * @param eventValidationRequestsArrayBaseSlot - The base slot of capsule array containing event validation requests.
306
- */ async utilityValidateAndStoreEnqueuedNotesAndEvents(contractAddress, noteValidationRequestsArrayBaseSlot, eventValidationRequestsArrayBaseSlot) {
334
+ */ async validateAndStoreEnqueuedNotesAndEvents(contractAddress, noteValidationRequestsArrayBaseSlot, eventValidationRequestsArrayBaseSlot, maxNotePackedLen, maxEventSerializedLen) {
307
335
  // TODO(#10727): allow other contracts to store notes
308
336
  if (!this.contractAddress.equals(contractAddress)) {
309
337
  throw new Error(`Got a note validation request from ${contractAddress}, expected ${this.contractAddress}`);
310
338
  }
311
339
  // We read all note and event validation requests and process them all concurrently. This makes the process much
312
340
  // faster as we don't need to wait for the network round-trip.
313
- const noteValidationRequests = (await this.capsuleStore.readCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, this.jobId)).map(NoteValidationRequest.fromFields);
314
- const eventValidationRequests = (await this.capsuleStore.readCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, this.jobId)).map(EventValidationRequest.fromFields);
341
+ const noteValidationRequests = (await this.capsuleStore.readCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, this.jobId)).map((fields)=>NoteValidationRequest.fromFields(fields, maxNotePackedLen));
342
+ const eventValidationRequests = (await this.capsuleStore.readCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, this.jobId)).map((fields)=>EventValidationRequest.fromFields(fields, maxEventSerializedLen));
315
343
  const noteService = new NoteService(this.noteStore, this.aztecNode, this.anchorBlockHeader, this.jobId);
316
344
  const noteStorePromises = noteValidationRequests.map((request)=>noteService.validateAndStoreNote(request.contractAddress, request.owner, request.storageSlot, request.randomness, request.noteNonce, request.content, request.noteHash, request.nullifier, request.txHash, request.recipient));
317
345
  const eventService = new EventService(this.anchorBlockHeader, this.aztecNode, this.privateEventStore, this.jobId);
@@ -324,7 +352,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
324
352
  await this.capsuleStore.setCapsuleArray(contractAddress, noteValidationRequestsArrayBaseSlot, [], this.jobId);
325
353
  await this.capsuleStore.setCapsuleArray(contractAddress, eventValidationRequestsArrayBaseSlot, [], this.jobId);
326
354
  }
327
- async utilityBulkRetrieveLogs(contractAddress, logRetrievalRequestsArrayBaseSlot, logRetrievalResponsesArrayBaseSlot) {
355
+ async bulkRetrieveLogs(contractAddress, logRetrievalRequestsArrayBaseSlot, logRetrievalResponsesArrayBaseSlot) {
328
356
  // TODO(#10727): allow other contracts to process partial notes
329
357
  if (!this.contractAddress.equals(contractAddress)) {
330
358
  throw new Error(`Got a note validation request from ${contractAddress}, expected ${this.contractAddress}`);
@@ -332,14 +360,33 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
332
360
  // We read all log retrieval requests and process them all concurrently. This makes the process much faster as we
333
361
  // don't need to wait for the network round-trip.
334
362
  const logRetrievalRequests = (await this.capsuleStore.readCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, this.jobId)).map(LogRetrievalRequest.fromFields);
335
- const logService = new LogService(this.aztecNode, this.anchorBlockHeader, this.keyStore, this.capsuleStore, this.recipientTaggingStore, this.senderAddressBookStore, this.addressStore, this.jobId, this.log.getBindings());
363
+ const logService = new LogService(this.aztecNode, this.anchorBlockHeader, this.keyStore, this.capsuleStore, this.recipientTaggingStore, this.senderAddressBookStore, this.addressStore, this.jobId, this.logger.getBindings());
336
364
  const maybeLogRetrievalResponses = await logService.bulkRetrieveLogs(logRetrievalRequests);
337
365
  // Requests are cleared once we're done.
338
366
  await this.capsuleStore.setCapsuleArray(contractAddress, logRetrievalRequestsArrayBaseSlot, [], this.jobId);
339
367
  // The responses are stored as Option<LogRetrievalResponse> in a second CapsuleArray.
340
368
  await this.capsuleStore.setCapsuleArray(contractAddress, logRetrievalResponsesArrayBaseSlot, maybeLogRetrievalResponses.map(LogRetrievalResponse.toSerializedOption), this.jobId);
341
369
  }
342
- utilityStoreCapsule(contractAddress, slot, capsule) {
370
+ async utilityResolveMessageContexts(contractAddress, messageContextRequestsArrayBaseSlot, messageContextResponsesArrayBaseSlot) {
371
+ try {
372
+ if (!this.contractAddress.equals(contractAddress)) {
373
+ throw new Error(`Got a message context request from ${contractAddress}, expected ${this.contractAddress}`);
374
+ }
375
+ const requestCapsules = await this.capsuleStore.readCapsuleArray(contractAddress, messageContextRequestsArrayBaseSlot, this.jobId);
376
+ const txHashes = requestCapsules.map((fields, i)=>{
377
+ if (fields.length !== 1) {
378
+ throw new Error(`Malformed message context request at index ${i}: expected 1 field (tx hash), got ${fields.length}`);
379
+ }
380
+ return fields[0];
381
+ });
382
+ const maybeMessageContexts = await this.messageContextService.resolveMessageContexts(txHashes, this.anchorBlockHeader.getBlockNumber());
383
+ // Leave response in response capsule array.
384
+ await this.capsuleStore.setCapsuleArray(contractAddress, messageContextResponsesArrayBaseSlot, maybeMessageContexts.map(MessageTxContext.toSerializedOption), this.jobId);
385
+ } finally{
386
+ await this.capsuleStore.setCapsuleArray(contractAddress, messageContextRequestsArrayBaseSlot, [], this.jobId);
387
+ }
388
+ }
389
+ storeCapsule(contractAddress, slot, capsule) {
343
390
  if (!contractAddress.equals(this.contractAddress)) {
344
391
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
345
392
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
@@ -347,7 +394,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
347
394
  this.capsuleStore.storeCapsule(this.contractAddress, slot, capsule, this.jobId);
348
395
  return Promise.resolve();
349
396
  }
350
- async utilityLoadCapsule(contractAddress, slot) {
397
+ async loadCapsule(contractAddress, slot) {
351
398
  if (!contractAddress.equals(this.contractAddress)) {
352
399
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
353
400
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
@@ -355,7 +402,7 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
355
402
  return(// TODO(#12425): On the following line, the pertinent capsule gets overshadowed by the transient one. Tackle this.
356
403
  this.capsules.find((c)=>c.contractAddress.equals(contractAddress) && c.storageSlot.equals(slot))?.data ?? await this.capsuleStore.loadCapsule(this.contractAddress, slot, this.jobId));
357
404
  }
358
- utilityDeleteCapsule(contractAddress, slot) {
405
+ deleteCapsule(contractAddress, slot) {
359
406
  if (!contractAddress.equals(this.contractAddress)) {
360
407
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
361
408
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
@@ -363,15 +410,24 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
363
410
  this.capsuleStore.deleteCapsule(this.contractAddress, slot, this.jobId);
364
411
  return Promise.resolve();
365
412
  }
366
- utilityCopyCapsule(contractAddress, srcSlot, dstSlot, numEntries) {
413
+ copyCapsule(contractAddress, srcSlot, dstSlot, numEntries) {
367
414
  if (!contractAddress.equals(this.contractAddress)) {
368
415
  // TODO(#10727): instead of this check that this.contractAddress is allowed to access the external DB
369
416
  throw new Error(`Contract ${contractAddress} is not allowed to access ${this.contractAddress}'s PXE DB`);
370
417
  }
371
418
  return this.capsuleStore.copyCapsule(this.contractAddress, srcSlot, dstSlot, numEntries, this.jobId);
372
419
  }
420
+ /**
421
+ * Clears cached sync state for a contract for a set of scopes, forcing re-sync on the next query so that newly
422
+ * stored notes or events are discovered.
423
+ */ invalidateContractSyncCache(contractAddress, scopes) {
424
+ if (!contractAddress.equals(this.contractAddress)) {
425
+ throw new Error(`Contract ${this.contractAddress} cannot invalidate sync cache of ${contractAddress}`);
426
+ }
427
+ this.contractSyncService.invalidateContractForScopes(contractAddress, scopes);
428
+ }
373
429
  // TODO(#11849): consider replacing this oracle with a pure Noir implementation of aes decryption.
374
- utilityAes128Decrypt(ciphertext, iv, symKey) {
430
+ aes128Decrypt(ciphertext, iv, symKey) {
375
431
  const aes128 = new Aes128();
376
432
  return aes128.decryptBufferCBC(ciphertext, iv, symKey);
377
433
  }
@@ -380,14 +436,36 @@ import { MessageLoadOracleInputs } from './message_load_oracle_inputs.js';
380
436
  * @param address - The address to get the secret for.
381
437
  * @param ephPk - The ephemeral public key to get the secret for.
382
438
  * @returns The secret for the given address.
383
- */ utilityGetSharedSecret(address, ephPk) {
384
- return this.getSharedSecret(address, ephPk);
385
- }
386
- async getSharedSecret(address, ephPk) {
439
+ */ async getSharedSecret(address, ephPk) {
387
440
  // TODO(#12656): return an app-siloed secret
388
441
  const recipientCompleteAddress = await this.getCompleteAddressOrFail(address);
389
442
  const ivskM = await this.keyStore.getMasterSecretKey(recipientCompleteAddress.publicKeys.masterIncomingViewingPublicKey);
390
443
  const addressSecret = await computeAddressSecret(await recipientCompleteAddress.getPreaddress(), ivskM);
391
444
  return deriveEcdhSharedSecret(addressSecret, ephPk);
392
445
  }
446
+ emitOffchainEffect(data) {
447
+ this.offchainEffects.push({
448
+ data,
449
+ contractAddress: this.contractAddress
450
+ });
451
+ return Promise.resolve();
452
+ }
453
+ /** Returns offchain effects collected during execution. */ getOffchainEffects() {
454
+ return this.offchainEffects;
455
+ }
456
+ /** Runs a query concurrently with a validation that the block hash is not ahead of the anchor block. */ async #queryWithBlockHashNotAfterAnchor(blockHash, query) {
457
+ const [response] = await Promise.all([
458
+ query(),
459
+ (async ()=>{
460
+ const header = await this.aztecNode.getBlockHeader(blockHash);
461
+ if (!header) {
462
+ throw new Error(`Could not find block header for block hash ${blockHash}`);
463
+ }
464
+ if (header.getBlockNumber() > this.anchorBlockHeader.getBlockNumber()) {
465
+ throw new Error(`Made a node query with a reference block hash ${blockHash} with block number ${header.getBlockNumber()}, which is ahead of the anchor block number ${this.anchorBlockHeader.getBlockNumber()} (from anchor block hash ${await this.anchorBlockHeader.hash()}).`);
466
+ }
467
+ })()
468
+ ]);
469
+ return response;
470
+ }
393
471
  }
@@ -21,10 +21,10 @@ export declare class ContractSyncService implements StagedStore {
21
21
  private log;
22
22
  readonly storeName = "contract_sync";
23
23
  private syncedContracts;
24
- private overriddenContracts;
24
+ private excludedFromSync;
25
25
  constructor(aztecNode: AztecNode, contractStore: ContractStore, noteStore: NoteStore, log: Logger);
26
26
  /** Sets contracts that should be skipped during sync for a specific job. */
27
- setOverriddenContracts(jobId: string, addresses: Set<string>): void;
27
+ setExcludedFromSync(jobId: string, addresses: Set<string>): void;
28
28
  /**
29
29
  * Ensures a contract's private state is synchronized and that the PXE holds the current class artifact.
30
30
  * Uses a cache to avoid redundant sync operations - the cache is wiped when the anchor block changes.
@@ -35,9 +35,11 @@ export declare class ContractSyncService implements StagedStore {
35
35
  * @param scopes - Access scopes to pass through to the utility executor (affects whose account's private state is discovered).
36
36
  */
37
37
  ensureContractSynced(contractAddress: AztecAddress, functionToInvokeAfterSync: FunctionSelector | null, utilityExecutor: (call: FunctionCall, scopes: AccessScopes) => Promise<any>, anchorBlockHeader: BlockHeader, jobId: string, scopes: AccessScopes): Promise<void>;
38
+ /** Clears sync cache entries for the given scopes of a contract. Also clears the ALL_SCOPES entry. */
39
+ invalidateContractForScopes(contractAddress: AztecAddress, scopes: AztecAddress[]): void;
38
40
  /** Clears sync cache. Called by BlockSynchronizer when anchor block changes. */
39
41
  wipe(): void;
40
42
  commit(jobId: string): Promise<void>;
41
43
  discardStaged(jobId: string): Promise<void>;
42
44
  }
43
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29udHJhY3Rfc3luY19zZXJ2aWNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvY29udHJhY3Rfc3luYy9jb250cmFjdF9zeW5jX3NlcnZpY2UudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxLQUFLLEVBQUUsTUFBTSxFQUFFLE1BQU0sdUJBQXVCLENBQUM7QUFDcEQsT0FBTyxLQUFLLEVBQUUsWUFBWSxFQUFFLGdCQUFnQixFQUFFLE1BQU0sbUJBQW1CLENBQUM7QUFDeEUsT0FBTyxLQUFLLEVBQUUsWUFBWSxFQUFFLE1BQU0sNkJBQTZCLENBQUM7QUFDaEUsT0FBTyxLQUFLLEVBQUUsU0FBUyxFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFDakUsT0FBTyxLQUFLLEVBQUUsV0FBVyxFQUFFLE1BQU0sa0JBQWtCLENBQUM7QUFFcEQsT0FBTyxLQUFLLEVBQUUsWUFBWSxFQUFFLE1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LElBQUksSUFBSSxJQUFJLENBR1g7SUFFRCxNQUFNLENBQUMsS0FBSyxFQUFFLE1BQU0sR0FBRyxPQUFPLENBQUMsSUFBSSxDQUFDLENBSW5DO0lBRUQsYUFBYSxDQUFDLEtBQUssRUFBRSxNQUFNLEdBQUcsT0FBTyxDQUFDLElBQUksQ0FBQyxDQU0xQztDQTJDRiJ9
@@ -1 +1 @@
1
- {"version":3,"file":"contract_sync_service.d.ts","sourceRoot":"","sources":["../../src/contract_sync/contract_sync_service.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,uCAAuC,CAAC;AACzE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,6CAA6C,CAAC;AACjF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qCAAqC,CAAC;AAGrE;;;;;GAKG;AACH,qBAAa,mBAAoB,YAAW,WAAW;;IAYnD,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,GAAG;IAdb,QAAQ,CAAC,SAAS,mBAAmB;IAKrC,OAAO,CAAC,eAAe,CAAyC;IAGhE,OAAO,CAAC,mBAAmB,CAAuC;IAElE,YACU,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,aAAa,EAC5B,SAAS,EAAE,SAAS,EACpB,GAAG,EAAE,MAAM,EACjB;IAEJ,4EAA4E;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G;AACH,qBAAa,mBAAoB,YAAW,WAAW;;IAYnD,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,GAAG;IAdb,QAAQ,CAAC,SAAS,mBAAmB;IAKrC,OAAO,CAAC,eAAe,CAAyC;IAGhE,OAAO,CAAC,gBAAgB,CAAuC;IAE/D,YACU,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,aAAa,EAC5B,SAAS,EAAE,SAAS,EACpB,GAAG,EAAE,MAAM,EACjB;IAEJ,4EAA4E;IAC5E,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,CAE/D;IAED;;;;;;;;OAQG;IACG,oBAAoB,CACxB,eAAe,EAAE,YAAY,EAC7B,yBAAyB,EAAE,gBAAgB,GAAG,IAAI,EAClD,eAAe,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,MAAM,EAAE,YAAY,KAAK,OAAO,CAAC,GAAG,CAAC,EAC3E,iBAAiB,EAAE,WAAW,EAC9B,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,YAAY,GACnB,OAAO,CAAC,IAAI,CAAC,CAiBf;IAED,sGAAsG;IACtG,2BAA2B,CAAC,eAAe,EAAE,YAAY,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI,CAMvF;IA4BD,gFAAgF;IAChF,IAAI,IAAI,IAAI,CAGX;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAInC;IAED,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAM1C;CA2CF"}
@@ -11,11 +11,11 @@ import { syncState, verifyCurrentClassId } from './helpers.js';
11
11
  log;
12
12
  storeName;
13
13
  // Tracks contracts synced since last wipe. The cache is keyed per individual scope address
14
- // (`contractAddress:scopeAddress`), or `contractAddress:*` for undefined scopes (all accounts).
14
+ // (`contractAddress:scopeAddress`), or `contractAddress:*` for all scopes (all accounts).
15
15
  // The value is a promise that resolves when the contract is synced.
16
16
  syncedContracts;
17
- // Per-job overridden contract addresses - these contracts should not be synced.
18
- overriddenContracts;
17
+ // Per-job excluded contract addresses - these contracts should not be synced.
18
+ excludedFromSync;
19
19
  constructor(aztecNode, contractStore, noteStore, log){
20
20
  this.aztecNode = aztecNode;
21
21
  this.contractStore = contractStore;
@@ -23,10 +23,10 @@ import { syncState, verifyCurrentClassId } from './helpers.js';
23
23
  this.log = log;
24
24
  this.storeName = 'contract_sync';
25
25
  this.syncedContracts = new Map();
26
- this.overriddenContracts = new Map();
26
+ this.excludedFromSync = new Map();
27
27
  }
28
- /** Sets contracts that should be skipped during sync for a specific job. */ setOverriddenContracts(jobId, addresses) {
29
- this.overriddenContracts.set(jobId, addresses);
28
+ /** Sets contracts that should be skipped during sync for a specific job. */ setExcludedFromSync(jobId, addresses) {
29
+ this.excludedFromSync.set(jobId, addresses);
30
30
  }
31
31
  /**
32
32
  * Ensures a contract's private state is synchronized and that the PXE holds the current class artifact.
@@ -37,32 +37,20 @@ import { syncState, verifyCurrentClassId } from './helpers.js';
37
37
  * @param utilityExecutor - Executor function for running the sync_state utility function.
38
38
  * @param scopes - Access scopes to pass through to the utility executor (affects whose account's private state is discovered).
39
39
  */ async ensureContractSynced(contractAddress, functionToInvokeAfterSync, utilityExecutor, anchorBlockHeader, jobId, scopes) {
40
- // Skip sync if this contract has an override for this job (overrides are keyed by contract address only)
41
- const overrides = this.overriddenContracts.get(jobId);
42
- if (overrides?.has(contractAddress.toString())) {
40
+ if (this.#shouldSkipSync(jobId, contractAddress)) {
43
41
  return;
44
42
  }
45
- // Skip sync if we already synced for "all scopes", or if we have an empty list of scopes
46
- const allScopesKey = toKey(contractAddress, 'ALL_SCOPES');
47
- const allScopesExisting = this.syncedContracts.get(allScopesKey);
48
- if (allScopesExisting || scopes !== 'ALL_SCOPES' && scopes.length == 0) {
43
+ this.#startSyncIfNeeded(contractAddress, scopes, (scopesToSync)=>this.#syncContract(contractAddress, functionToInvokeAfterSync, utilityExecutor, anchorBlockHeader, jobId, scopesToSync));
44
+ await this.#awaitSync(contractAddress, scopes);
45
+ }
46
+ /** Clears sync cache entries for the given scopes of a contract. Also clears the ALL_SCOPES entry. */ invalidateContractForScopes(contractAddress, scopes) {
47
+ if (scopes.length === 0) {
49
48
  return;
50
49
  }
51
- const unsyncedScopes = scopes === 'ALL_SCOPES' ? scopes : scopes.filter((scope)=>!this.syncedContracts.has(toKey(contractAddress, scope)));
52
- const unsyncedScopesKeys = toKeys(contractAddress, unsyncedScopes);
53
- if (unsyncedScopesKeys.length > 0) {
54
- // Start sync and store the promise for all unsynced scopes
55
- const promise = this.#doSync(contractAddress, functionToInvokeAfterSync, utilityExecutor, anchorBlockHeader, jobId, unsyncedScopes).catch((err)=>{
56
- // There was an error syncing the contract, so we remove it from the cache so that it can be retried.
57
- unsyncedScopesKeys.forEach((key)=>this.syncedContracts.delete(key));
58
- throw err;
59
- });
60
- unsyncedScopesKeys.forEach((key)=>this.syncedContracts.set(key, promise));
61
- }
62
- const promises = toKeys(contractAddress, scopes).map((key)=>this.syncedContracts.get(key));
63
- await Promise.all(promises);
50
+ scopes.forEach((scope)=>this.syncedContracts.delete(toKey(contractAddress, scope)));
51
+ this.syncedContracts.delete(toKey(contractAddress, 'ALL_SCOPES'));
64
52
  }
65
- async #doSync(contractAddress, functionToInvokeAfterSync, utilityExecutor, anchorBlockHeader, jobId, scopes) {
53
+ async #syncContract(contractAddress, functionToInvokeAfterSync, utilityExecutor, anchorBlockHeader, jobId, scopes) {
66
54
  this.log.debug(`Syncing contract ${contractAddress}`);
67
55
  await Promise.all([
68
56
  syncState(contractAddress, this.contractStore, functionToInvokeAfterSync, utilityExecutor, this.noteStore, this.aztecNode, anchorBlockHeader, jobId, scopes),
@@ -75,17 +63,46 @@ import { syncState, verifyCurrentClassId } from './helpers.js';
75
63
  this.syncedContracts.clear();
76
64
  }
77
65
  commit(jobId) {
78
- // Clear overridden contracts for this job
79
- this.overriddenContracts.delete(jobId);
66
+ // Clear excluded contracts for this job
67
+ this.excludedFromSync.delete(jobId);
80
68
  return Promise.resolve();
81
69
  }
82
70
  discardStaged(jobId) {
83
71
  // We clear the synced contracts cache here because, when the job is discarded, any associated database writes from
84
72
  // the sync are also undone.
85
73
  this.syncedContracts.clear();
86
- this.overriddenContracts.delete(jobId);
74
+ this.excludedFromSync.delete(jobId);
87
75
  return Promise.resolve();
88
76
  }
77
+ /** Returns true if sync should be skipped for this contract */ #shouldSkipSync(jobId, contractAddress) {
78
+ return !!this.excludedFromSync.get(jobId)?.has(contractAddress.toString());
79
+ }
80
+ /** If there are unsynced scopes, starts sync and stores the promise in cache with error cleanup. */ #startSyncIfNeeded(contractAddress, scopes, syncFn) {
81
+ const scopesToSync = this.#getScopesToSync(contractAddress, scopes);
82
+ const keys = toKeys(contractAddress, scopesToSync);
83
+ if (keys.length === 0) {
84
+ return;
85
+ }
86
+ const promise = syncFn(scopesToSync).catch((err)=>{
87
+ keys.forEach((key)=>this.syncedContracts.delete(key));
88
+ throw err;
89
+ });
90
+ keys.forEach((key)=>this.syncedContracts.set(key, promise));
91
+ }
92
+ /** Filters out scopes that are already cached, returning only those that still need syncing. */ #getScopesToSync(contractAddress, scopes) {
93
+ if (this.syncedContracts.has(toKey(contractAddress, 'ALL_SCOPES'))) {
94
+ // If we are already syncing all scopes, then return an empty list
95
+ return [];
96
+ }
97
+ if (scopes === 'ALL_SCOPES') {
98
+ return 'ALL_SCOPES';
99
+ }
100
+ return scopes.filter((scope)=>!this.syncedContracts.has(toKey(contractAddress, scope)));
101
+ }
102
+ /** Collects all relevant scope promises (including in-flight ones from concurrent calls) and awaits them. */ async #awaitSync(contractAddress, scopes) {
103
+ const promises = toKeys(contractAddress, scopes).map((key)=>this.syncedContracts.get(key)).filter((p)=>p !== undefined);
104
+ await Promise.all(promises);
105
+ }
89
106
  }
90
107
  function toKeys(contract, scopes) {
91
108
  return scopes === 'ALL_SCOPES' ? [
@@ -0,0 +1,17 @@
1
+ import { Fr } from '@aztec/foundation/curves/bn254';
2
+ import type { AztecNode } from '@aztec/stdlib/interfaces/server';
3
+ import { MessageTxContext } from '../contract_function_simulator/noir-structs/message_tx_context.js';
4
+ /** Resolves transaction hashes into the context needed to process messages. */
5
+ export declare class MessageContextService {
6
+ private readonly aztecNode;
7
+ constructor(aztecNode: AztecNode);
8
+ /**
9
+ * Resolves a list of tx hashes into their message contexts.
10
+ *
11
+ * For each tx hash, looks up the corresponding tx effect and extracts the note hashes and first nullifier needed to
12
+ * process messages that originated from that transaction. Returns `null` for tx hashes that are zero, not yet
13
+ * available, or in blocks beyond the anchor block.
14
+ */
15
+ resolveMessageContexts(txHashes: Fr[], anchorBlockNumber: number): Promise<(MessageTxContext | null)[]>;
16
+ }
17
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWVzc2FnZV9jb250ZXh0X3NlcnZpY2UuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9tZXNzYWdlcy9tZXNzYWdlX2NvbnRleHRfc2VydmljZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsRUFBRSxFQUFFLE1BQU0sZ0NBQWdDLENBQUM7QUFDcEQsT0FBTyxLQUFLLEVBQUUsU0FBUyxFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFHakUsT0FBTyxFQUFFLGdCQUFnQixFQUFFLE1BQU0sbUVBQW1FLENBQUM7QUFFckcsK0VBQStFO0FBQy9FLHFCQUFhLHFCQUFxQjtJQUNwQixPQUFPLENBQUMsUUFBUSxDQUFDLFNBQVM7SUFBdEMsWUFBNkIsU0FBUyxFQUFFLFNBQVMsRUFBSTtJQUVyRDs7Ozs7O09BTUc7SUFDSCxzQkFBc0IsQ0FBQyxRQUFRLEVBQUUsRUFBRSxFQUFFLEVBQUUsaUJBQWlCLEVBQUUsTUFBTSxHQUFHLE9BQU8sQ0FBQyxDQUFDLGdCQUFnQixHQUFHLElBQUksQ0FBQyxFQUFFLENBQUMsQ0EwQnRHO0NBQ0YifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"message_context_service.d.ts","sourceRoot":"","sources":["../../src/messages/message_context_service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,gCAAgC,CAAC;AACpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAGjE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mEAAmE,CAAC;AAErG,+EAA+E;AAC/E,qBAAa,qBAAqB;IACpB,OAAO,CAAC,QAAQ,CAAC,SAAS;IAAtC,YAA6B,SAAS,EAAE,SAAS,EAAI;IAErD;;;;;;OAMG;IACH,sBAAsB,CAAC,QAAQ,EAAE,EAAE,EAAE,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,gBAAgB,GAAG,IAAI,CAAC,EAAE,CAAC,CA0BtG;CACF"}