@aztec-labs/txe 6.0.0-nightly.20260829

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 (173) hide show
  1. package/dest/AuthRegistry-D4XJULH3.js +3 -0
  2. package/dest/AuthRegistry-D4XJULH3.js.map +7 -0
  3. package/dest/ContractClassRegistry-Q76MXQZD.js +3 -0
  4. package/dest/ContractClassRegistry-Q76MXQZD.js.map +7 -0
  5. package/dest/ContractInstanceRegistry-CTRARU77.js +3 -0
  6. package/dest/ContractInstanceRegistry-CTRARU77.js.map +7 -0
  7. package/dest/FeeJuice-YLTJXWYJ.js +3 -0
  8. package/dest/FeeJuice-YLTJXWYJ.js.map +7 -0
  9. package/dest/HandshakeRegistry-BRPEG7GL.js +3 -0
  10. package/dest/HandshakeRegistry-BRPEG7GL.js.map +7 -0
  11. package/dest/MultiCallEntrypoint-CJHMYQT5.js +3 -0
  12. package/dest/MultiCallEntrypoint-CJHMYQT5.js.map +7 -0
  13. package/dest/SchnorrAccount-OB4N4QIM.js +3 -0
  14. package/dest/SchnorrAccount-OB4N4QIM.js.map +7 -0
  15. package/dest/SchnorrInitializerlessAccount-TWGKRUSY.js +3 -0
  16. package/dest/SchnorrInitializerlessAccount-TWGKRUSY.js.map +7 -0
  17. package/dest/bin/check_txe_oracle_version.d.ts +2 -0
  18. package/dest/bin/check_txe_oracle_version.d.ts.map +1 -0
  19. package/dest/bin/check_txe_oracle_version.js +22 -0
  20. package/dest/bin/index.d.ts +3 -0
  21. package/dest/bin/index.d.ts.map +1 -0
  22. package/dest/bin/index.js +4 -0
  23. package/dest/bin/index.js.map +7 -0
  24. package/dest/bin/oracle_test_server.d.ts +3 -0
  25. package/dest/bin/oracle_test_server.d.ts.map +1 -0
  26. package/dest/bin/oracle_test_server.js +41 -0
  27. package/dest/chunk-32UHX7YY.js +3 -0
  28. package/dest/chunk-32UHX7YY.js.map +7 -0
  29. package/dest/chunk-F4QVFWNM.js +258 -0
  30. package/dest/chunk-F4QVFWNM.js.map +7 -0
  31. package/dest/chunk-LILEKW2X.js +304 -0
  32. package/dest/chunk-LILEKW2X.js.map +7 -0
  33. package/dest/constants.d.ts +7 -0
  34. package/dest/constants.d.ts.map +1 -0
  35. package/dest/constants.js +10 -0
  36. package/dest/dispatcher_pool.d.ts +67 -0
  37. package/dest/dispatcher_pool.d.ts.map +1 -0
  38. package/dest/dispatcher_pool.js +288 -0
  39. package/dest/index.d.ts +52 -0
  40. package/dest/index.d.ts.map +1 -0
  41. package/dest/index.js +102 -0
  42. package/dest/metafile.json +38805 -0
  43. package/dest/msgpackr_fr_extension.d.ts +2 -0
  44. package/dest/msgpackr_fr_extension.d.ts.map +1 -0
  45. package/dest/msgpackr_fr_extension.js +21 -0
  46. package/dest/oracle/interfaces.d.ts +90 -0
  47. package/dest/oracle/interfaces.d.ts.map +1 -0
  48. package/dest/oracle/interfaces.js +3 -0
  49. package/dest/oracle/noir-structs/gas_settings_data.d.ts +14 -0
  50. package/dest/oracle/noir-structs/gas_settings_data.d.ts.map +1 -0
  51. package/dest/oracle/noir-structs/gas_settings_data.js +1 -0
  52. package/dest/oracle/noir-structs/tx_effects_data.d.ts +11 -0
  53. package/dest/oracle/noir-structs/tx_effects_data.d.ts.map +1 -0
  54. package/dest/oracle/noir-structs/tx_effects_data.js +1 -0
  55. package/dest/oracle/tagging_secret_strategy.d.ts +12 -0
  56. package/dest/oracle/tagging_secret_strategy.d.ts.map +1 -0
  57. package/dest/oracle/tagging_secret_strategy.js +12 -0
  58. package/dest/oracle/test-resolver/default_fixtures.d.ts +16 -0
  59. package/dest/oracle/test-resolver/default_fixtures.d.ts.map +1 -0
  60. package/dest/oracle/test-resolver/default_fixtures.js +207 -0
  61. package/dest/oracle/test-resolver/index.d.ts +9 -0
  62. package/dest/oracle/test-resolver/index.d.ts.map +1 -0
  63. package/dest/oracle/test-resolver/index.js +32 -0
  64. package/dest/oracle/test-resolver/resolver.d.ts +48 -0
  65. package/dest/oracle/test-resolver/resolver.d.ts.map +1 -0
  66. package/dest/oracle/test-resolver/resolver.js +181 -0
  67. package/dest/oracle/txe_oracle_public_context.d.ts +58 -0
  68. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -0
  69. package/dest/oracle/txe_oracle_public_context.js +170 -0
  70. package/dest/oracle/txe_oracle_registry.d.ts +164 -0
  71. package/dest/oracle/txe_oracle_registry.d.ts.map +1 -0
  72. package/dest/oracle/txe_oracle_registry.js +753 -0
  73. package/dest/oracle/txe_oracle_top_level_context.d.ts +128 -0
  74. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -0
  75. package/dest/oracle/txe_oracle_top_level_context.js +815 -0
  76. package/dest/oracle/txe_oracle_version.d.ts +17 -0
  77. package/dest/oracle/txe_oracle_version.d.ts.map +1 -0
  78. package/dest/oracle/txe_oracle_version.js +14 -0
  79. package/dest/oracle/txe_private_execution_oracle.d.ts +17 -0
  80. package/dest/oracle/txe_private_execution_oracle.d.ts.map +1 -0
  81. package/dest/oracle/txe_private_execution_oracle.js +15 -0
  82. package/dest/rpc_server.d.ts +14 -0
  83. package/dest/rpc_server.d.ts.map +1 -0
  84. package/dest/rpc_server.js +78 -0
  85. package/dest/rpc_translator.d.ts +140 -0
  86. package/dest/rpc_translator.d.ts.map +1 -0
  87. package/dest/rpc_translator.js +976 -0
  88. package/dest/server.bundle.js +3 -0
  89. package/dest/server.bundle.js.map +7 -0
  90. package/dest/state_machine/archiver.d.ts +32 -0
  91. package/dest/state_machine/archiver.d.ts.map +1 -0
  92. package/dest/state_machine/archiver.js +95 -0
  93. package/dest/state_machine/dummy_p2p_client.d.ts +69 -0
  94. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -0
  95. package/dest/state_machine/dummy_p2p_client.js +180 -0
  96. package/dest/state_machine/global_variable_builder.d.ts +15 -0
  97. package/dest/state_machine/global_variable_builder.d.ts.map +1 -0
  98. package/dest/state_machine/global_variable_builder.js +25 -0
  99. package/dest/state_machine/index.d.ts +22 -0
  100. package/dest/state_machine/index.d.ts.map +1 -0
  101. package/dest/state_machine/index.js +110 -0
  102. package/dest/state_machine/mock_epoch_cache.d.ts +43 -0
  103. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -0
  104. package/dest/state_machine/mock_epoch_cache.js +88 -0
  105. package/dest/state_machine/synchronizer.d.ts +41 -0
  106. package/dest/state_machine/synchronizer.d.ts.map +1 -0
  107. package/dest/state_machine/synchronizer.js +70 -0
  108. package/dest/txe_session.d.ts +179 -0
  109. package/dest/txe_session.d.ts.map +1 -0
  110. package/dest/txe_session.js +697 -0
  111. package/dest/utils/block_creation.d.ts +28 -0
  112. package/dest/utils/block_creation.d.ts.map +1 -0
  113. package/dest/utils/block_creation.js +59 -0
  114. package/dest/utils/encoding.d.ts +194 -0
  115. package/dest/utils/encoding.d.ts.map +1 -0
  116. package/dest/utils/encoding.js +136 -0
  117. package/dest/utils/expected_failure_error.d.ts +4 -0
  118. package/dest/utils/expected_failure_error.d.ts.map +1 -0
  119. package/dest/utils/expected_failure_error.js +5 -0
  120. package/dest/utils/tx_effect_creation.d.ts +5 -0
  121. package/dest/utils/tx_effect_creation.d.ts.map +1 -0
  122. package/dest/utils/tx_effect_creation.js +12 -0
  123. package/dest/utils/txe_account_store.d.ts +10 -0
  124. package/dest/utils/txe_account_store.d.ts.map +1 -0
  125. package/dest/utils/txe_account_store.js +17 -0
  126. package/dest/utils/txe_artifact_resolver.d.ts +36 -0
  127. package/dest/utils/txe_artifact_resolver.d.ts.map +1 -0
  128. package/dest/utils/txe_artifact_resolver.js +160 -0
  129. package/dest/utils/txe_public_contract_data_source.d.ts +20 -0
  130. package/dest/utils/txe_public_contract_data_source.d.ts.map +1 -0
  131. package/dest/utils/txe_public_contract_data_source.js +51 -0
  132. package/dest/worker.bundle.js +3 -0
  133. package/dest/worker.bundle.js.map +7 -0
  134. package/dest/worker.d.ts +2 -0
  135. package/dest/worker.d.ts.map +1 -0
  136. package/dest/worker.js +92 -0
  137. package/package.json +115 -0
  138. package/src/bin/check_txe_oracle_version.ts +31 -0
  139. package/src/bin/index.ts +49 -0
  140. package/src/bin/oracle_test_server.ts +51 -0
  141. package/src/constants.ts +13 -0
  142. package/src/dispatcher_pool.ts +319 -0
  143. package/src/index.ts +152 -0
  144. package/src/msgpackr_fr_extension.ts +22 -0
  145. package/src/oracle/interfaces.ts +125 -0
  146. package/src/oracle/noir-structs/gas_settings_data.ts +16 -0
  147. package/src/oracle/noir-structs/tx_effects_data.ts +11 -0
  148. package/src/oracle/tagging_secret_strategy.ts +25 -0
  149. package/src/oracle/test-resolver/default_fixtures.ts +278 -0
  150. package/src/oracle/test-resolver/index.ts +43 -0
  151. package/src/oracle/test-resolver/resolver.ts +245 -0
  152. package/src/oracle/txe_oracle_public_context.ts +220 -0
  153. package/src/oracle/txe_oracle_registry.ts +501 -0
  154. package/src/oracle/txe_oracle_top_level_context.ts +1086 -0
  155. package/src/oracle/txe_oracle_version.ts +17 -0
  156. package/src/oracle/txe_private_execution_oracle.ts +30 -0
  157. package/src/rpc_server.ts +86 -0
  158. package/src/rpc_translator.ts +1229 -0
  159. package/src/state_machine/archiver.ts +118 -0
  160. package/src/state_machine/dummy_p2p_client.ts +264 -0
  161. package/src/state_machine/global_variable_builder.ts +39 -0
  162. package/src/state_machine/index.ts +152 -0
  163. package/src/state_machine/mock_epoch_cache.ts +111 -0
  164. package/src/state_machine/synchronizer.ts +105 -0
  165. package/src/txe_session.ts +1107 -0
  166. package/src/utils/block_creation.ts +91 -0
  167. package/src/utils/encoding.ts +171 -0
  168. package/src/utils/expected_failure_error.ts +5 -0
  169. package/src/utils/tx_effect_creation.ts +28 -0
  170. package/src/utils/txe_account_store.ts +23 -0
  171. package/src/utils/txe_artifact_resolver.ts +217 -0
  172. package/src/utils/txe_public_contract_data_source.ts +60 -0
  173. package/src/worker.ts +98 -0
@@ -0,0 +1,91 @@
1
+ import { MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, NULLIFIER_SUBTREE_HEIGHT } from '@aztec-labs/constants';
2
+ import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint } from '@aztec-labs/foundation/branded-types';
3
+ import { padArrayEnd } from '@aztec-labs/foundation/collection';
4
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
5
+ import { Body, L2Block } from '@aztec-labs/stdlib/block';
6
+ import { AppendOnlyTreeSnapshot, MerkleTreeId, type MerkleTreeWriteOperations } from '@aztec-labs/stdlib/trees';
7
+ import { BlockHeader, GlobalVariables, TxEffect } from '@aztec-labs/stdlib/tx';
8
+
9
+ /**
10
+ * Returns a transaction request hash that is valid for transactions that are the only ones in a block.
11
+ * @param blockNumber The number for the block in which there is a single transaction.
12
+ * @returns The transaction request hash.
13
+ */
14
+ export function getSingleTxBlockRequestHash(blockNumber: BlockNumber): Fr {
15
+ return new Fr(blockNumber + 9999); // Why does this need to be a high number? Why do small numbered nullifiers already exist?
16
+ }
17
+
18
+ export async function insertTxEffectIntoWorldTrees(
19
+ txEffect: TxEffect,
20
+ worldTrees: MerkleTreeWriteOperations,
21
+ l1ToL2Messages: Fr[] = [],
22
+ ): Promise<void> {
23
+ await worldTrees.appendLeaves(
24
+ MerkleTreeId.NOTE_HASH_TREE,
25
+ padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
26
+ );
27
+
28
+ await worldTrees.batchInsert(
29
+ MerkleTreeId.NULLIFIER_TREE,
30
+ padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map(nullifier => nullifier.toBuffer()),
31
+ NULLIFIER_SUBTREE_HEIGHT,
32
+ );
33
+
34
+ // Append the block's real message leaves unpadded at compact indices.
35
+ await worldTrees.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2Messages);
36
+
37
+ // We do not need to add public data writes because we apply them as we go.
38
+ }
39
+
40
+ export async function makeTXEBlockHeader(
41
+ worldTrees: MerkleTreeWriteOperations,
42
+ globalVariables: GlobalVariables,
43
+ ): Promise<BlockHeader> {
44
+ const stateReference = await worldTrees.getStateReference();
45
+ const archiveInfo = await worldTrees.getTreeInfo(MerkleTreeId.ARCHIVE);
46
+
47
+ return BlockHeader.from({
48
+ lastArchive: new AppendOnlyTreeSnapshot(new Fr(archiveInfo.root), Number(archiveInfo.size)),
49
+ spongeBlobHash: Fr.ZERO,
50
+ state: stateReference,
51
+ globalVariables,
52
+ totalFees: Fr.ZERO,
53
+ totalManaUsed: Fr.ZERO,
54
+ });
55
+ }
56
+
57
+ /**
58
+ * Creates an L2Block with proper archive chaining.
59
+ * This function:
60
+ * 1. Gets the current archive state as lastArchive for the header
61
+ * 2. Creates the block header
62
+ * 3. Updates the archive tree with the header hash
63
+ * 4. Gets the new archive state for the block's archive
64
+ *
65
+ * @param worldTrees - The world trees to read/write from
66
+ * @param globalVariables - Global variables for the block
67
+ * @param txEffects - Transaction effects to include in the block
68
+ * @returns The created L2Block with proper archive chaining
69
+ */
70
+ export async function makeTXEBlock(
71
+ worldTrees: MerkleTreeWriteOperations,
72
+ globalVariables: GlobalVariables,
73
+ txEffects: TxEffect[],
74
+ ): Promise<L2Block> {
75
+ const header = await makeTXEBlockHeader(worldTrees, globalVariables);
76
+
77
+ // Update the archive tree with this block's header hash
78
+ await worldTrees.updateArchive(header);
79
+
80
+ // Get the new archive state after updating
81
+ const newArchiveInfo = await worldTrees.getTreeInfo(MerkleTreeId.ARCHIVE);
82
+ const newArchive = new AppendOnlyTreeSnapshot(new Fr(newArchiveInfo.root), Number(newArchiveInfo.size));
83
+
84
+ // L2Block requires checkpointNumber and indexWithinCheckpoint.
85
+ // TXE uses 1-block-per-checkpoint for testing simplicity, so we can use block number as checkpoint number.
86
+ // This uses the deprecated fromBlockNumber method intentionally for the TXE testing environment.
87
+ const checkpointNumber = CheckpointNumber.fromBlockNumber(globalVariables.blockNumber);
88
+ const indexWithinCheckpoint = IndexWithinCheckpoint(0);
89
+
90
+ return new L2Block(newArchive, header, new Body(txEffects), checkpointNumber, indexWithinCheckpoint);
91
+ }
@@ -0,0 +1,171 @@
1
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
2
+ import type { EthAddress } from '@aztec-labs/foundation/eth-address';
3
+ import { hexToBuffer } from '@aztec-labs/foundation/string';
4
+ import { type ContractArtifact, ContractArtifactSchema } from '@aztec-labs/stdlib/abi';
5
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
6
+ import { BlockHash } from '@aztec-labs/stdlib/block';
7
+ import { type ContractInstanceWithAddress, ContractInstanceWithAddressSchema } from '@aztec-labs/stdlib/contract';
8
+ import { z } from 'zod';
9
+
10
+ export type ForeignCallSingle = string;
11
+
12
+ export type ForeignCallArray = string[];
13
+
14
+ export type ForeignCallArgs = (ForeignCallSingle | ForeignCallArray | ContractArtifact | ContractInstanceWithAddress)[];
15
+
16
+ export type ForeignCallResult = {
17
+ values: (ForeignCallSingle | ForeignCallArray)[];
18
+ };
19
+
20
+ export function fromSingle(obj: ForeignCallSingle) {
21
+ return Fr.fromBuffer(Buffer.from(obj, 'hex'));
22
+ }
23
+
24
+ export function addressFromSingle(obj: ForeignCallSingle) {
25
+ return new AztecAddress(fromSingle(obj));
26
+ }
27
+
28
+ export function blockHashFromSingle(obj: ForeignCallSingle) {
29
+ return new BlockHash(fromSingle(obj));
30
+ }
31
+
32
+ export function fromArray(obj: ForeignCallArray) {
33
+ return obj.map(str => Fr.fromBuffer(hexToBuffer(str)));
34
+ }
35
+
36
+ /**
37
+ * Converts an array of Noir unsigned integers to a single tightly-packed buffer.
38
+ * @param uintBitSize If it's an array of Noir u8's, put `8`, etc.
39
+ * @returns A buffer where each byte is correctly represented as a single byte in the buffer.
40
+ */
41
+ export function fromUintArray(obj: ForeignCallArray, uintBitSize: number): Buffer {
42
+ if (uintBitSize % 8 !== 0) {
43
+ throw new Error(`u${uintBitSize} is not a supported type in Noir`);
44
+ }
45
+ const uintByteSize = uintBitSize / 8;
46
+ return Buffer.concat(obj.map(str => hexToBuffer(str).slice(-uintByteSize)));
47
+ }
48
+
49
+ /**
50
+ * Converts a Noir BoundedVec of unsigned integers into a Buffer. Note that BoundedVecs are structs, and therefore
51
+ * translated as two separate ForeignCallArray and ForeignCallSingle values (an array and a single field).
52
+ *
53
+ * @param storage The array with the BoundedVec's storage (i.e. BoundedVec::storage())
54
+ * @param length The length of the BoundedVec (i.e. BoundedVec::len())
55
+ * @param uintBitSize If it's an array of Noir u8's, put `8`, etc.
56
+ * @returns A buffer containing the unsigned integers tightly packed
57
+ */
58
+ export function fromUintBoundedVec(storage: ForeignCallArray, length: ForeignCallSingle, uintBitSize: number): Buffer {
59
+ if (uintBitSize % 8 !== 0) {
60
+ throw new Error(`u${uintBitSize} is not a supported type in Noir`);
61
+ }
62
+ const uintByteSize = uintBitSize / 8;
63
+ const boundedStorage = storage.slice(0, fromSingle(length).toNumber());
64
+ return Buffer.concat(boundedStorage.map(str => hexToBuffer(str).slice(-uintByteSize)));
65
+ }
66
+
67
+ // Just like toACVMField in yarn-project/simulator/src/private/acvm/serialize.ts but returns a ForeignCallSingle
68
+ // instead of an ACVMField.
69
+ export function toSingle(
70
+ value: AztecAddress | EthAddress | Fr | Buffer | boolean | number | bigint,
71
+ ): ForeignCallSingle {
72
+ let valueAsField;
73
+ if (Buffer.isBuffer(value)) {
74
+ valueAsField = Fr.fromBuffer(value);
75
+ } else if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'bigint') {
76
+ valueAsField = new Fr(value);
77
+ } else if (typeof value === 'string') {
78
+ valueAsField = Fr.fromHexString(value);
79
+ } else {
80
+ valueAsField = value;
81
+ }
82
+ return valueAsField.toString().slice(2);
83
+ }
84
+
85
+ export function toArray(objs: Fr[]): ForeignCallArray {
86
+ return objs.map(obj => obj.toString());
87
+ }
88
+
89
+ export function toSingleOrArray(value: Fr | Fr[]) {
90
+ return Array.isArray(value) ? value.map(toSingle) : toSingle(value);
91
+ }
92
+
93
+ export function bufferToU8Array(buffer: Buffer): ForeignCallArray {
94
+ return toArray(Array.from(buffer).map(byte => new Fr(byte)));
95
+ }
96
+
97
+ /**
98
+ * Converts a ForeignCallArray into a tuple which represents a nr BoundedVec.
99
+ * If the input array is shorter than the maxLen, it pads the result with zeros,
100
+ * so that nr can correctly coerce this result into a BoundedVec.
101
+ * @param bVecStorage - The array underlying the BoundedVec.
102
+ * @param maxLen - the max length of the BoundedVec.
103
+ * @returns a tuple representing a BoundedVec.
104
+ */
105
+ export function arrayToBoundedVec(
106
+ bVecStorage: ForeignCallArray,
107
+ maxLen: number,
108
+ ): [ForeignCallArray, ForeignCallSingle] {
109
+ if (bVecStorage.length > maxLen) {
110
+ throw new Error(`Array of length ${bVecStorage.length} larger than maxLen ${maxLen}`);
111
+ }
112
+ const lengthDiff = maxLen - bVecStorage.length;
113
+ // We pad the array to the maxLen of the BoundedVec.
114
+ const zeroPaddingArray = toArray(Array(lengthDiff).fill(new Fr(0)));
115
+
116
+ // These variable names match with the BoundedVec members in nr:
117
+ const storage = bVecStorage.concat(zeroPaddingArray);
118
+ const len = toSingle(new Fr(bVecStorage.length));
119
+ return [storage, len];
120
+ }
121
+
122
+ /**
123
+ * Converts an array of arrays representing Noir BoundedVec of nested arrays into its Noir serialized form.
124
+ * @param bVecStorage - The array underlying the BoundedVec.
125
+ * @param maxLen - The max length of the BoundedVec (max num of the nested arrays in the BoundedVec).
126
+ * @param nestedArrayLength - The length of the nested arrays (each nested array has to have the same length).
127
+ * @returns Serialized BoundedVec following Noir intrinsic serialization.
128
+ */
129
+ export function arrayOfArraysToBoundedVecOfArrays(
130
+ bVecStorage: ForeignCallArray[],
131
+ maxLen: number,
132
+ nestedArrayLength: number,
133
+ ): [ForeignCallArray, ForeignCallSingle] {
134
+ if (bVecStorage.length > maxLen) {
135
+ throw new Error(`Array of length ${bVecStorage.length} larger than maxLen ${maxLen}`);
136
+ }
137
+
138
+ // Check that all nested arrays have length nestedArrayLength
139
+ if (!bVecStorage.every(nestedArray => nestedArray.length === nestedArrayLength)) {
140
+ throw new Error(
141
+ `Nested array length passed in from Noir does not correspond to the length obtained in TS: ${nestedArrayLength} !== ${bVecStorage[0].length}`,
142
+ );
143
+ }
144
+
145
+ const flattenedStorage = bVecStorage.flat();
146
+
147
+ const numFieldsToPad = maxLen * nestedArrayLength - flattenedStorage.length;
148
+
149
+ // Pad with hex-encoded zeros so the result is uniformly `ForeignCallSingle` (string); raw Fr
150
+ // instances would JSON-serialize as `{ asBigInt: "0" }` and nargo would reject the response.
151
+ const flattenedStorageWithPadding = flattenedStorage.concat(toArray(Array(numFieldsToPad).fill(new Fr(0))));
152
+
153
+ const len = toSingle(new Fr(bVecStorage.length));
154
+ return [flattenedStorageWithPadding, len];
155
+ }
156
+
157
+ export function toForeignCallResult(obj: (ForeignCallSingle | ForeignCallArray)[]) {
158
+ return { values: obj };
159
+ }
160
+
161
+ export const ForeignCallSingleSchema = z.string();
162
+
163
+ export const ForeignCallArraySchema = z.array(z.string());
164
+
165
+ export const ForeignCallArgsSchema = z.array(
166
+ z.union([ForeignCallSingleSchema, ForeignCallArraySchema, ContractArtifactSchema, ContractInstanceWithAddressSchema]),
167
+ );
168
+
169
+ export const ForeignCallResultSchema = z.object({
170
+ values: z.array(z.union([ForeignCallSingleSchema, ForeignCallArraySchema])),
171
+ });
@@ -0,0 +1,5 @@
1
+ export class ExpectedFailureError extends Error {
2
+ constructor(message: string) {
3
+ super(message);
4
+ }
5
+ }
@@ -0,0 +1,28 @@
1
+ import { BlockNumber } from '@aztec-labs/foundation/branded-types';
2
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
3
+ import type { ExecutionNoteCache } from '@aztec-labs/pxe/simulator';
4
+ import { computeNoteHashNonce, computeUniqueNoteHash, siloNoteHash } from '@aztec-labs/stdlib/hash';
5
+ import { TxEffect, TxHash } from '@aztec-labs/stdlib/tx';
6
+
7
+ export async function makeTxEffect(noteCache: ExecutionNoteCache, txBlockNumber: BlockNumber): Promise<TxEffect> {
8
+ const txEffect = TxEffect.empty();
9
+
10
+ const nonceGenerator = noteCache.getNonceGenerator();
11
+ txEffect.noteHashes = await Promise.all(
12
+ noteCache
13
+ .getAllNotes()
14
+ .map(async (pendingNote, i) =>
15
+ computeUniqueNoteHash(
16
+ await computeNoteHashNonce(nonceGenerator, i),
17
+ await siloNoteHash(pendingNote.note.contractAddress, pendingNote.noteHashForConsumption),
18
+ ),
19
+ ),
20
+ );
21
+
22
+ // Nullifiers are already siloed
23
+ txEffect.nullifiers = noteCache.getAllNullifiers();
24
+
25
+ txEffect.txHash = new TxHash(new Fr(txBlockNumber));
26
+
27
+ return txEffect;
28
+ }
@@ -0,0 +1,23 @@
1
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec-labs/kv-store';
2
+ import type { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
3
+ import { CompleteAddress } from '@aztec-labs/stdlib/contract';
4
+
5
+ export class TXEAccountStore {
6
+ #accounts: AztecAsyncMap<string, Buffer>;
7
+
8
+ constructor(store: AztecAsyncKVStore) {
9
+ this.#accounts = store.openMap('accounts');
10
+ }
11
+
12
+ async getAccount(key: AztecAddress) {
13
+ const completeAddress = await this.#accounts.getAsync(key.toString());
14
+ if (!completeAddress) {
15
+ throw new Error(`Account not found: ${key.toString()}`);
16
+ }
17
+ return CompleteAddress.fromBuffer(completeAddress);
18
+ }
19
+
20
+ async setAccount(key: AztecAddress, value: CompleteAddress) {
21
+ await this.#accounts.set(key.toString(), value.toBuffer());
22
+ }
23
+ }
@@ -0,0 +1,217 @@
1
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
2
+ import { createLogger } from '@aztec-labs/foundation/log';
3
+ import type { ContractStore } from '@aztec-labs/pxe/client/lazy';
4
+ import { loadContractArtifact } from '@aztec-labs/stdlib/abi';
5
+ import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
6
+ import {
7
+ type ContractArtifactWithHash,
8
+ type ContractInstanceWithAddress,
9
+ computeArtifactHash,
10
+ getContractInstanceFromInstantiationParams,
11
+ } from '@aztec-labs/stdlib/contract';
12
+ import { PublicKeys, deriveKeys } from '@aztec-labs/stdlib/keys';
13
+ import type { NoirCompiledContract } from '@aztec-labs/stdlib/noir';
14
+ import { createHash } from 'crypto';
15
+ import { createReadStream } from 'fs';
16
+ import { readFile, readdir } from 'fs/promises';
17
+ import { join, parse } from 'path';
18
+
19
+ export interface ResolvedArtifact {
20
+ artifact: ContractArtifactWithHash;
21
+ instance: ContractInstanceWithAddress;
22
+ }
23
+
24
+ /**
25
+ * Cache + in-flight map pair. Lookup hits the cache, then awaits an in-flight `compute()` if one
26
+ * exists, otherwise starts one and stores it. Guarantees `compute()` runs at most once per `key`
27
+ * across concurrent callers, which matters because `computeArtifactHash` is expensive.
28
+ */
29
+ class AsyncCache<K, V> {
30
+ #cache = new Map<K, V>();
31
+ #inFlight = new Map<K, Promise<V>>();
32
+
33
+ getOrCompute(key: K, compute: () => Promise<V>): Promise<V> {
34
+ const cached = this.#cache.get(key);
35
+ if (cached !== undefined) {
36
+ return Promise.resolve(cached);
37
+ }
38
+ let pending = this.#inFlight.get(key);
39
+ if (!pending) {
40
+ pending = (async () => {
41
+ try {
42
+ const value = await compute();
43
+ this.#cache.set(key, value);
44
+ return value;
45
+ } finally {
46
+ this.#inFlight.delete(key);
47
+ }
48
+ })();
49
+ this.#inFlight.set(key, pending);
50
+ }
51
+ return pending;
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Resolves and caches contract artifacts and their associated instances.
57
+ *
58
+ * Artifact hash computation is expensive, so this service deduplicates both completed and in-flight computations.
59
+ * Two cache levels are kept: full deploys (artifact + computed instance) keyed by the full deploy context, and loaded +
60
+ * hashed artifacts keyed by the compiled-bytecode hash so deploys of the same contract with different args / salt /
61
+ * deployer reuse the same `ContractArtifactWithHash`.
62
+ */
63
+ export class TXEArtifactResolver {
64
+ #deployments = new AsyncCache<string, ResolvedArtifact>();
65
+ #artifacts = new AsyncCache<string, ContractArtifactWithHash>();
66
+ #logger = createLogger('txe:artifact_resolver');
67
+
68
+ constructor(
69
+ private readonly contractStore: ContractStore,
70
+ private readonly schnorrClassId: Fr,
71
+ ) {}
72
+
73
+ /** Resolves the Schnorr account contract artifact and instance for the given secret, caching the result. */
74
+ resolveAccountArtifact(secret: Fr): Promise<ResolvedArtifact> {
75
+ return this.#deployments.getOrCompute(`SchnorrAccountContract-${secret}`, () =>
76
+ this.#computeAccountArtifact(secret),
77
+ );
78
+ }
79
+
80
+ /** Resolves a contract artifact from disk by path, computes its instance, and caches the result. */
81
+ async resolveDeployArtifact({
82
+ rootPath,
83
+ packageName,
84
+ contractPath,
85
+ initializer,
86
+ args,
87
+ secret,
88
+ salt,
89
+ deployer,
90
+ }: {
91
+ rootPath: string;
92
+ packageName: string;
93
+ contractPath: string;
94
+ initializer: string;
95
+ args: Fr[];
96
+ secret: Fr;
97
+ salt: Fr;
98
+ deployer: AztecAddress;
99
+ }): Promise<ResolvedArtifact> {
100
+ const publicKeys = secret.equals(Fr.ZERO) ? PublicKeys.default() : (await deriveKeys(secret)).publicKeys;
101
+ const publicKeysHash = await publicKeys.hash();
102
+
103
+ const artifactPath = await this.#resolveArtifactPath(rootPath, packageName, contractPath);
104
+ const fileHash = await this.#fastHashFile(artifactPath);
105
+
106
+ const { dir: contractDirectory, base: contractFilename } = parse(contractPath);
107
+ const cacheKey = `${contractDirectory ?? ''}-${contractFilename}-${initializer}-${args
108
+ .map(arg => arg.toString())
109
+ .join('-')}-${publicKeysHash}-${salt}-${deployer}-${fileHash}`;
110
+
111
+ return this.#deployments.getOrCompute(cacheKey, () =>
112
+ this.#computeDeployArtifact(
113
+ artifactPath,
114
+ fileHash,
115
+ initializer,
116
+ args,
117
+ salt,
118
+ publicKeys,
119
+ publicKeysHash,
120
+ deployer,
121
+ ),
122
+ );
123
+ }
124
+
125
+ async #resolveArtifactPath(rootPath: string, packageName: string, contractPath: string): Promise<string> {
126
+ const { dir: contractDirectory, base: contractFilename } = parse(contractPath);
127
+ if (contractDirectory) {
128
+ if (contractDirectory.includes('@')) {
129
+ // env.deploy("../path/to/workspace/root@packageName/contractName")
130
+ const [workspace, pkg] = contractDirectory.split('@');
131
+ const targetPath = join(rootPath, workspace, '/target');
132
+ this.#logger.debug(`Looking for compiled artifact in workspace ${targetPath}`);
133
+ return join(targetPath, `${pkg}-${contractFilename}.json`);
134
+ } else {
135
+ // env.deploy("../path/to/contract/root/contractName")
136
+ const targetPath = join(rootPath, contractDirectory, '/target');
137
+ this.#logger.debug(`Looking for compiled artifact in ${targetPath}`);
138
+ const [artifactPath] = (await readdir(targetPath)).filter(file => file.endsWith(`-${contractFilename}.json`));
139
+ return artifactPath;
140
+ }
141
+ } else {
142
+ // env.deploy("contractName")
143
+ return join(rootPath, './target', `${packageName}-${contractFilename}.json`);
144
+ }
145
+ }
146
+
147
+ async #computeAccountArtifact(secret: Fr): Promise<ResolvedArtifact> {
148
+ const [artifactFromStore, classWithPreimage] = await Promise.all([
149
+ this.contractStore.getContractArtifact(this.schnorrClassId),
150
+ this.contractStore.getContractClassWithPreimage(this.schnorrClassId),
151
+ ]);
152
+ if (!artifactFromStore || !classWithPreimage) {
153
+ throw new Error(
154
+ `SchnorrAccount not found in shared contract store at class id ${this.schnorrClassId.toString()}`,
155
+ );
156
+ }
157
+ const artifact: ContractArtifactWithHash = { ...artifactFromStore, artifactHash: classWithPreimage.artifactHash };
158
+ const keys = await deriveKeys(secret);
159
+ const args = [keys.publicKeys.ivpkM.x, keys.publicKeys.ivpkM.y];
160
+ const instance = await getContractInstanceFromInstantiationParams(artifact, {
161
+ constructorArgs: args,
162
+ skipArgsDecoding: true,
163
+ salt: Fr.ONE,
164
+ publicKeys: keys.publicKeys,
165
+ constructorArtifact: 'constructor',
166
+ deployer: AztecAddress.ZERO,
167
+ });
168
+ return { artifact, instance };
169
+ }
170
+
171
+ async #computeDeployArtifact(
172
+ artifactPath: string,
173
+ fileHash: string,
174
+ initializer: string,
175
+ args: Fr[],
176
+ salt: Fr,
177
+ publicKeys: PublicKeys,
178
+ publicKeysHash: Fr,
179
+ deployer: AztecAddress,
180
+ ): Promise<ResolvedArtifact> {
181
+ // Inner cache: artifact load + hash depends only on the compiled bytecode (`fileHash`), so subsequent deploys of
182
+ // the same contract — regardless of constructor args / deployer / salt — reuse the same `ContractArtifactWithHash`.
183
+ const artifact = await this.#artifacts.getOrCompute(fileHash, async () => {
184
+ this.#logger.debug(`Loading compiled artifact ${artifactPath}`);
185
+ const artifactJSON = JSON.parse(await readFile(artifactPath, 'utf-8')) as NoirCompiledContract;
186
+ const artifactWithoutHash = loadContractArtifact(artifactJSON);
187
+ return { ...artifactWithoutHash, artifactHash: await computeArtifactHash(artifactWithoutHash) };
188
+ });
189
+ this.#logger.debug(
190
+ `Deploy ${artifact.name} with initializer ${initializer}(${args}) and public keys hash ${publicKeysHash}`,
191
+ );
192
+ const instance = await getContractInstanceFromInstantiationParams(artifact, {
193
+ constructorArgs: args,
194
+ skipArgsDecoding: true,
195
+ salt,
196
+ publicKeys,
197
+ constructorArtifact: initializer || undefined,
198
+ deployer,
199
+ });
200
+ return { artifact, instance };
201
+ }
202
+
203
+ #fastHashFile(path: string): Promise<string> {
204
+ return new Promise(resolve => {
205
+ const fd = createReadStream(path);
206
+ const hash = createHash('sha1');
207
+ hash.setEncoding('hex');
208
+
209
+ fd.on('end', function () {
210
+ hash.end();
211
+ resolve(hash.read() as string);
212
+ });
213
+
214
+ fd.pipe(hash);
215
+ });
216
+ }
217
+ }
@@ -0,0 +1,60 @@
1
+ import { BlockNumber } from '@aztec-labs/foundation/branded-types';
2
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
3
+ import type { ContractStore } from '@aztec-labs/pxe/server';
4
+ import { type ContractArtifact, FunctionSelector } from '@aztec-labs/stdlib/abi';
5
+ import type { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
6
+ import type { ContractClassPublic, ContractDataSource, ContractInstanceWithAddress } from '@aztec-labs/stdlib/contract';
7
+
8
+ export class TXEPublicContractDataSource implements ContractDataSource {
9
+ constructor(
10
+ private blockNumber: BlockNumber,
11
+ private contractStore: ContractStore,
12
+ ) {}
13
+
14
+ getBlockNumber(): Promise<BlockNumber> {
15
+ return Promise.resolve(this.blockNumber);
16
+ }
17
+
18
+ async getContractClass(id: Fr): Promise<ContractClassPublic | undefined> {
19
+ const contractClass = await this.contractStore.getContractClassWithPreimage(id);
20
+ if (!contractClass) {
21
+ return;
22
+ }
23
+ return {
24
+ id: contractClass.id,
25
+ artifactHash: contractClass.artifactHash,
26
+ packedBytecode: contractClass.packedBytecode,
27
+ privateFunctionsRoot: contractClass.privateFunctionsRoot,
28
+ version: contractClass.version,
29
+ };
30
+ }
31
+
32
+ async getBytecodeCommitment(id: Fr): Promise<Fr | undefined> {
33
+ const contractClass = await this.contractStore.getContractClassWithPreimage(id);
34
+ return contractClass?.publicBytecodeCommitment;
35
+ }
36
+
37
+ async getContract(address: AztecAddress): Promise<ContractInstanceWithAddress | undefined> {
38
+ const instance = await this.contractStore.getContractInstance(address);
39
+ // TXE has no contract updates, so the current class always equals the original.
40
+ return instance && { ...instance, address, currentContractClassId: instance.originalContractClassId };
41
+ }
42
+
43
+ getContractClassIds(): Promise<Fr[]> {
44
+ throw new Error('Method not implemented.');
45
+ }
46
+
47
+ async getContractArtifact(address: AztecAddress): Promise<ContractArtifact | undefined> {
48
+ const instance = await this.getContract(address);
49
+ return instance && this.contractStore.getContractArtifact(instance.originalContractClassId);
50
+ }
51
+
52
+ async getDebugFunctionName(address: AztecAddress, selector: FunctionSelector): Promise<string | undefined> {
53
+ const instance = await this.getContract(address);
54
+ return instance && this.contractStore.getDebugFunctionName(instance.originalContractClassId, selector);
55
+ }
56
+
57
+ registerContractFunctionSignatures(_signatures: []): Promise<void> {
58
+ return Promise.resolve();
59
+ }
60
+ }