@aztec/txe 0.0.1-commit.3469e52 → 0.0.1-commit.350e0a4d

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 (170) hide show
  1. package/dest/AuthRegistry-2RDAZOGB.js +3 -0
  2. package/dest/AuthRegistry-2RDAZOGB.js.map +7 -0
  3. package/dest/ContractClassRegistry-L5F3G33N.js +3 -0
  4. package/dest/ContractClassRegistry-L5F3G33N.js.map +7 -0
  5. package/dest/ContractInstanceRegistry-IJOBAWAC.js +3 -0
  6. package/dest/ContractInstanceRegistry-IJOBAWAC.js.map +7 -0
  7. package/dest/FeeJuice-J3XDQPFS.js +3 -0
  8. package/dest/FeeJuice-J3XDQPFS.js.map +7 -0
  9. package/dest/HandshakeRegistry-QGWZJYVS.js +3 -0
  10. package/dest/HandshakeRegistry-QGWZJYVS.js.map +7 -0
  11. package/dest/MultiCallEntrypoint-WZHPRFJ6.js +3 -0
  12. package/dest/MultiCallEntrypoint-WZHPRFJ6.js.map +7 -0
  13. package/dest/SchnorrAccount-II4XD6MI.js +3 -0
  14. package/dest/SchnorrAccount-II4XD6MI.js.map +7 -0
  15. package/dest/SchnorrInitializerlessAccount-FXIOXUQQ.js +3 -0
  16. package/dest/SchnorrInitializerlessAccount-FXIOXUQQ.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 +61 -0
  20. package/dest/bin/index.js +3 -30
  21. package/dest/bin/index.js.map +7 -0
  22. package/dest/bin/oracle_test_server.d.ts +3 -0
  23. package/dest/bin/oracle_test_server.d.ts.map +1 -0
  24. package/dest/bin/oracle_test_server.js +41 -0
  25. package/dest/chunk-BJVAAXNA.js +3 -0
  26. package/dest/chunk-BJVAAXNA.js.map +7 -0
  27. package/dest/chunk-OMH3BDML.js +304 -0
  28. package/dest/chunk-OMH3BDML.js.map +7 -0
  29. package/dest/chunk-R3ZWQEFL.js +260 -0
  30. package/dest/chunk-R3ZWQEFL.js.map +7 -0
  31. package/dest/constants.d.ts +5 -1
  32. package/dest/constants.d.ts.map +1 -1
  33. package/dest/constants.js +9 -1
  34. package/dest/dispatcher_pool.d.ts +67 -0
  35. package/dest/dispatcher_pool.d.ts.map +1 -0
  36. package/dest/dispatcher_pool.js +286 -0
  37. package/dest/index.d.ts +51 -7
  38. package/dest/index.d.ts.map +1 -1
  39. package/dest/index.js +73 -157
  40. package/dest/metafile.json +38140 -0
  41. package/dest/msgpackr_fr_extension.d.ts +2 -0
  42. package/dest/msgpackr_fr_extension.d.ts.map +1 -0
  43. package/dest/msgpackr_fr_extension.js +21 -0
  44. package/dest/oracle/interfaces.d.ts +61 -30
  45. package/dest/oracle/interfaces.d.ts.map +1 -1
  46. package/dest/oracle/test-resolver/default_fixtures.d.ts +9 -0
  47. package/dest/oracle/test-resolver/default_fixtures.d.ts.map +1 -0
  48. package/dest/oracle/test-resolver/default_fixtures.js +207 -0
  49. package/dest/oracle/test-resolver/index.d.ts +9 -0
  50. package/dest/oracle/test-resolver/index.d.ts.map +1 -0
  51. package/dest/oracle/test-resolver/index.js +32 -0
  52. package/dest/oracle/test-resolver/resolver.d.ts +48 -0
  53. package/dest/oracle/test-resolver/resolver.d.ts.map +1 -0
  54. package/dest/oracle/test-resolver/resolver.js +181 -0
  55. package/dest/oracle/txe_oracle_public_context.d.ts +40 -16
  56. package/dest/oracle/txe_oracle_public_context.d.ts.map +1 -1
  57. package/dest/oracle/txe_oracle_public_context.js +65 -17
  58. package/dest/oracle/txe_oracle_registry.d.ts +169 -0
  59. package/dest/oracle/txe_oracle_registry.d.ts.map +1 -0
  60. package/dest/oracle/txe_oracle_registry.js +745 -0
  61. package/dest/oracle/txe_oracle_top_level_context.d.ts +55 -29
  62. package/dest/oracle/txe_oracle_top_level_context.d.ts.map +1 -1
  63. package/dest/oracle/txe_oracle_top_level_context.js +322 -104
  64. package/dest/oracle/txe_oracle_version.d.ts +17 -0
  65. package/dest/oracle/txe_oracle_version.d.ts.map +1 -0
  66. package/dest/oracle/txe_oracle_version.js +14 -0
  67. package/dest/oracle/txe_private_execution_oracle.d.ts +17 -0
  68. package/dest/oracle/txe_private_execution_oracle.d.ts.map +1 -0
  69. package/dest/oracle/txe_private_execution_oracle.js +15 -0
  70. package/dest/rpc_server.d.ts +14 -0
  71. package/dest/rpc_server.d.ts.map +1 -0
  72. package/dest/rpc_server.js +78 -0
  73. package/dest/rpc_translator.d.ts +112 -222
  74. package/dest/rpc_translator.d.ts.map +1 -1
  75. package/dest/rpc_translator.js +877 -600
  76. package/dest/server.bundle.js +3 -0
  77. package/dest/server.bundle.js.map +7 -0
  78. package/dest/state_machine/archiver.d.ts +7 -6
  79. package/dest/state_machine/archiver.d.ts.map +1 -1
  80. package/dest/state_machine/archiver.js +31 -22
  81. package/dest/state_machine/dummy_p2p_client.d.ts +29 -16
  82. package/dest/state_machine/dummy_p2p_client.d.ts.map +1 -1
  83. package/dest/state_machine/dummy_p2p_client.js +53 -20
  84. package/dest/state_machine/global_variable_builder.d.ts +10 -6
  85. package/dest/state_machine/global_variable_builder.d.ts.map +1 -1
  86. package/dest/state_machine/global_variable_builder.js +8 -5
  87. package/dest/state_machine/index.d.ts +13 -7
  88. package/dest/state_machine/index.d.ts.map +1 -1
  89. package/dest/state_machine/index.js +75 -21
  90. package/dest/state_machine/mock_epoch_cache.d.ts +21 -4
  91. package/dest/state_machine/mock_epoch_cache.d.ts.map +1 -1
  92. package/dest/state_machine/mock_epoch_cache.js +35 -3
  93. package/dest/state_machine/synchronizer.d.ts +9 -6
  94. package/dest/state_machine/synchronizer.d.ts.map +1 -1
  95. package/dest/state_machine/synchronizer.js +10 -6
  96. package/dest/txe_session.d.ts +89 -16
  97. package/dest/txe_session.d.ts.map +1 -1
  98. package/dest/txe_session.js +366 -58
  99. package/dest/utils/block_creation.d.ts +6 -6
  100. package/dest/utils/block_creation.d.ts.map +1 -1
  101. package/dest/utils/block_creation.js +9 -7
  102. package/dest/utils/encoding.d.ts +192 -0
  103. package/dest/utils/encoding.d.ts.map +1 -0
  104. package/dest/{util → utils}/encoding.js +7 -2
  105. package/dest/{util → utils}/expected_failure_error.d.ts +1 -1
  106. package/dest/utils/expected_failure_error.d.ts.map +1 -0
  107. package/dest/utils/tx_effect_creation.d.ts +1 -1
  108. package/dest/utils/tx_effect_creation.d.ts.map +1 -1
  109. package/dest/utils/tx_effect_creation.js +0 -1
  110. package/dest/{util → utils}/txe_account_store.d.ts +1 -1
  111. package/dest/utils/txe_account_store.d.ts.map +1 -0
  112. package/dest/utils/txe_artifact_resolver.d.ts +37 -0
  113. package/dest/utils/txe_artifact_resolver.d.ts.map +1 -0
  114. package/dest/utils/txe_artifact_resolver.js +161 -0
  115. package/dest/utils/txe_public_contract_data_source.d.ts +20 -0
  116. package/dest/utils/txe_public_contract_data_source.d.ts.map +1 -0
  117. package/dest/utils/txe_public_contract_data_source.js +51 -0
  118. package/dest/worker.bundle.js +3 -0
  119. package/dest/worker.bundle.js.map +7 -0
  120. package/dest/worker.d.ts +2 -0
  121. package/dest/worker.d.ts.map +1 -0
  122. package/dest/worker.js +92 -0
  123. package/package.json +38 -21
  124. package/src/bin/check_txe_oracle_version.ts +70 -0
  125. package/src/bin/index.ts +11 -2
  126. package/src/bin/oracle_test_server.ts +51 -0
  127. package/src/constants.ts +11 -1
  128. package/src/dispatcher_pool.ts +317 -0
  129. package/src/index.ts +99 -190
  130. package/src/msgpackr_fr_extension.ts +23 -0
  131. package/src/oracle/interfaces.ts +64 -35
  132. package/src/oracle/test-resolver/default_fixtures.ts +282 -0
  133. package/src/oracle/test-resolver/index.ts +44 -0
  134. package/src/oracle/test-resolver/resolver.ts +245 -0
  135. package/src/oracle/txe_oracle_public_context.ts +80 -20
  136. package/src/oracle/txe_oracle_registry.ts +536 -0
  137. package/src/oracle/txe_oracle_top_level_context.ts +430 -168
  138. package/src/oracle/txe_oracle_version.ts +17 -0
  139. package/src/oracle/txe_private_execution_oracle.ts +30 -0
  140. package/src/rpc_server.ts +87 -0
  141. package/src/rpc_translator.ts +1087 -974
  142. package/src/state_machine/archiver.ts +45 -26
  143. package/src/state_machine/dummy_p2p_client.ts +83 -32
  144. package/src/state_machine/global_variable_builder.ts +12 -11
  145. package/src/state_machine/index.ts +105 -40
  146. package/src/state_machine/mock_epoch_cache.ts +45 -4
  147. package/src/state_machine/synchronizer.ts +13 -7
  148. package/src/txe_session.ts +609 -128
  149. package/src/utils/block_creation.ts +10 -7
  150. package/src/{util → utils}/encoding.ts +8 -2
  151. package/src/utils/tx_effect_creation.ts +0 -2
  152. package/src/utils/txe_artifact_resolver.ts +217 -0
  153. package/src/utils/txe_public_contract_data_source.ts +60 -0
  154. package/src/worker.ts +98 -0
  155. package/dest/util/encoding.d.ts +0 -720
  156. package/dest/util/encoding.d.ts.map +0 -1
  157. package/dest/util/expected_failure_error.d.ts.map +0 -1
  158. package/dest/util/txe_account_store.d.ts.map +0 -1
  159. package/dest/util/txe_contract_store.d.ts +0 -12
  160. package/dest/util/txe_contract_store.d.ts.map +0 -1
  161. package/dest/util/txe_contract_store.js +0 -22
  162. package/dest/util/txe_public_contract_data_source.d.ts +0 -21
  163. package/dest/util/txe_public_contract_data_source.d.ts.map +0 -1
  164. package/dest/util/txe_public_contract_data_source.js +0 -67
  165. package/src/util/txe_contract_store.ts +0 -36
  166. package/src/util/txe_public_contract_data_source.ts +0 -86
  167. /package/dest/{util → utils}/expected_failure_error.js +0 -0
  168. /package/dest/{util → utils}/txe_account_store.js +0 -0
  169. /package/src/{util → utils}/expected_failure_error.ts +0 -0
  170. /package/src/{util → utils}/txe_account_store.ts +0 -0
@@ -7,7 +7,7 @@ import {
7
7
  import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint } from '@aztec/foundation/branded-types';
8
8
  import { padArrayEnd } from '@aztec/foundation/collection';
9
9
  import { Fr } from '@aztec/foundation/curves/bn254';
10
- import { Body, L2BlockNew } from '@aztec/stdlib/block';
10
+ import { Body, L2Block } from '@aztec/stdlib/block';
11
11
  import { AppendOnlyTreeSnapshot, MerkleTreeId, type MerkleTreeWriteOperations } from '@aztec/stdlib/trees';
12
12
  import { BlockHeader, GlobalVariables, TxEffect } from '@aztec/stdlib/tx';
13
13
 
@@ -23,6 +23,7 @@ export function getSingleTxBlockRequestHash(blockNumber: BlockNumber): Fr {
23
23
  export async function insertTxEffectIntoWorldTrees(
24
24
  txEffect: TxEffect,
25
25
  worldTrees: MerkleTreeWriteOperations,
26
+ l1ToL2Messages: Fr[] = [],
26
27
  ): Promise<void> {
27
28
  await worldTrees.appendLeaves(
28
29
  MerkleTreeId.NOTE_HASH_TREE,
@@ -37,7 +38,7 @@ export async function insertTxEffectIntoWorldTrees(
37
38
 
38
39
  await worldTrees.appendLeaves(
39
40
  MerkleTreeId.L1_TO_L2_MESSAGE_TREE,
40
- padArrayEnd<Fr, number>(txEffect.l2ToL1Msgs, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP),
41
+ padArrayEnd<Fr, number>(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP),
41
42
  );
42
43
 
43
44
  // We do not need to add public data writes because we apply them as we go.
@@ -61,7 +62,7 @@ export async function makeTXEBlockHeader(
61
62
  }
62
63
 
63
64
  /**
64
- * Creates an L2BlockNew with proper archive chaining.
65
+ * Creates an L2Block with proper archive chaining.
65
66
  * This function:
66
67
  * 1. Gets the current archive state as lastArchive for the header
67
68
  * 2. Creates the block header
@@ -71,13 +72,13 @@ export async function makeTXEBlockHeader(
71
72
  * @param worldTrees - The world trees to read/write from
72
73
  * @param globalVariables - Global variables for the block
73
74
  * @param txEffects - Transaction effects to include in the block
74
- * @returns The created L2BlockNew with proper archive chaining
75
+ * @returns The created L2Block with proper archive chaining
75
76
  */
76
77
  export async function makeTXEBlock(
77
78
  worldTrees: MerkleTreeWriteOperations,
78
79
  globalVariables: GlobalVariables,
79
80
  txEffects: TxEffect[],
80
- ): Promise<L2BlockNew> {
81
+ ): Promise<L2Block> {
81
82
  const header = await makeTXEBlockHeader(worldTrees, globalVariables);
82
83
 
83
84
  // Update the archive tree with this block's header hash
@@ -87,9 +88,11 @@ export async function makeTXEBlock(
87
88
  const newArchiveInfo = await worldTrees.getTreeInfo(MerkleTreeId.ARCHIVE);
88
89
  const newArchive = new AppendOnlyTreeSnapshot(new Fr(newArchiveInfo.root), Number(newArchiveInfo.size));
89
90
 
90
- // L2BlockNew requires checkpointNumber and indexWithinCheckpoint
91
+ // L2Block requires checkpointNumber and indexWithinCheckpoint.
92
+ // TXE uses 1-block-per-checkpoint for testing simplicity, so we can use block number as checkpoint number.
93
+ // This uses the deprecated fromBlockNumber method intentionally for the TXE testing environment.
91
94
  const checkpointNumber = CheckpointNumber.fromBlockNumber(globalVariables.blockNumber);
92
95
  const indexWithinCheckpoint = IndexWithinCheckpoint(0);
93
96
 
94
- return new L2BlockNew(newArchive, header, new Body(txEffects), checkpointNumber, indexWithinCheckpoint);
97
+ return new L2Block(newArchive, header, new Body(txEffects), checkpointNumber, indexWithinCheckpoint);
95
98
  }
@@ -3,6 +3,7 @@ import type { EthAddress } from '@aztec/foundation/eth-address';
3
3
  import { hexToBuffer } from '@aztec/foundation/string';
4
4
  import { type ContractArtifact, ContractArtifactSchema } from '@aztec/stdlib/abi';
5
5
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
6
+ import { BlockHash } from '@aztec/stdlib/block';
6
7
  import { type ContractInstanceWithAddress, ContractInstanceWithAddressSchema } from '@aztec/stdlib/contract';
7
8
 
8
9
  import { z } from 'zod';
@@ -25,6 +26,10 @@ export function addressFromSingle(obj: ForeignCallSingle) {
25
26
  return new AztecAddress(fromSingle(obj));
26
27
  }
27
28
 
29
+ export function blockHashFromSingle(obj: ForeignCallSingle) {
30
+ return new BlockHash(fromSingle(obj));
31
+ }
32
+
28
33
  export function fromArray(obj: ForeignCallArray) {
29
34
  return obj.map(str => Fr.fromBuffer(hexToBuffer(str)));
30
35
  }
@@ -142,9 +147,10 @@ export function arrayOfArraysToBoundedVecOfArrays(
142
147
 
143
148
  const numFieldsToPad = maxLen * nestedArrayLength - flattenedStorage.length;
144
149
 
145
- const flattenedStorageWithPadding = flattenedStorage.concat(Array(numFieldsToPad).fill(new Fr(0)));
150
+ // Pad with hex-encoded zeros so the result is uniformly `ForeignCallSingle` (string); raw Fr
151
+ // instances would JSON-serialize as `{ asBigInt: "0" }` and nargo would reject the response.
152
+ const flattenedStorageWithPadding = flattenedStorage.concat(toArray(Array(numFieldsToPad).fill(new Fr(0))));
146
153
 
147
- // At last we get the actual length of the BoundedVec and return the values.
148
154
  const len = toSingle(new Fr(bVecStorage.length));
149
155
  return [flattenedStorageWithPadding, len];
150
156
  }
@@ -7,8 +7,6 @@ import { TxEffect, TxHash } from '@aztec/stdlib/tx';
7
7
  export async function makeTxEffect(noteCache: ExecutionNoteCache, txBlockNumber: BlockNumber): Promise<TxEffect> {
8
8
  const txEffect = TxEffect.empty();
9
9
 
10
- noteCache.finish();
11
-
12
10
  const nonceGenerator = noteCache.getNonceGenerator();
13
11
  txEffect.noteHashes = await Promise.all(
14
12
  noteCache
@@ -0,0 +1,217 @@
1
+ import { type NoirCompiledContract, loadContractArtifact } from '@aztec/aztec.js/abi';
2
+ import { AztecAddress } from '@aztec/aztec.js/addresses';
3
+ import {
4
+ type ContractInstanceWithAddress,
5
+ getContractInstanceFromInstantiationParams,
6
+ } from '@aztec/aztec.js/contracts';
7
+ import { Fr } from '@aztec/aztec.js/fields';
8
+ import { PublicKeys, deriveKeys } from '@aztec/aztec.js/keys';
9
+ import { createLogger } from '@aztec/foundation/log';
10
+ import type { ContractStore } from '@aztec/pxe/client/lazy';
11
+ import type { ContractArtifactWithHash } from '@aztec/stdlib/contract';
12
+ import { computeArtifactHash } from '@aztec/stdlib/contract';
13
+
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/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import type { ContractStore } from '@aztec/pxe/server';
4
+ import { type ContractArtifact, FunctionSelector } from '@aztec/stdlib/abi';
5
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
6
+ import type { ContractClassPublic, ContractDataSource, ContractInstanceWithAddress } from '@aztec/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
+ }
package/src/worker.ts ADDED
@@ -0,0 +1,98 @@
1
+ import { BackendType, Barretenberg, BarretenbergSync } from '@aztec/bb.js';
2
+ import { type Logger, createLogger } from '@aztec/foundation/log';
3
+
4
+ import { parentPort, workerData } from 'node:worker_threads';
5
+
6
+ // Importing `./index.js` registers the msgpackr Fr extension transitively (via
7
+ // ./msgpackr_fr_extension.js); this must happen before any `sendMessage` call.
8
+ import { TXEDispatcher, type TXEDispatcherOptions, type TXEForeignCallInput, activeSessionCount } from './index.js';
9
+
10
+ // Seed both bb.js singletons with the WASM backend before any crypto call. `initSingleton`
11
+ // binds the singleton to whichever backend the first call requests, so this pre-empts the
12
+ // implicit `Barretenberg.initSingleton()` inside `poseidon2Hash` from `@aztec/foundation/crypto`.
13
+ // TXE only needs hashing (no proving, no verification), so WASM is sufficient and
14
+ // `skipSrsInit: true` skips the CRS load. `threads: 1` keeps the WASM backend on a single
15
+ // thread — additional threads would each spawn a nested worker_thread, multiplying memory cost
16
+ // per pool worker.
17
+ void Barretenberg.initSingleton({ backend: BackendType.Wasm, skipSrsInit: true, threads: 1 });
18
+ void BarretenbergSync.initSingleton({ backend: BackendType.Wasm });
19
+
20
+ if (!parentPort) {
21
+ throw new Error('worker.ts must be loaded as a worker_thread');
22
+ }
23
+
24
+ const port = parentPort;
25
+ const logger: Logger = createLogger('txe:worker');
26
+
27
+ // The pool builds a template LMDB containing the protocol contracts + the SchnorrAccount
28
+ // artifact on the main thread and passes its data dir via `workerData`. The dispatcher clones
29
+ // that LMDB into a per-worker store on first use, so this worker gets a writable copy already
30
+ // populated.
31
+ const dispatcherOpts: TXEDispatcherOptions = {
32
+ contractStoreSourceDir: workerData.contractStoreSourceDir,
33
+ schnorrClassId: workerData.schnorrClassId,
34
+ };
35
+ const dispatcher = new TXEDispatcher(logger, dispatcherOpts);
36
+
37
+ interface ForeignCallRequest {
38
+ type: 'foreign-call';
39
+ requestId: number;
40
+ callData: TXEForeignCallInput;
41
+ }
42
+
43
+ interface DisposeSessionMessage {
44
+ type: 'dispose-session';
45
+ sessionId: number;
46
+ }
47
+
48
+ type IncomingMessage = ForeignCallRequest | DisposeSessionMessage;
49
+
50
+ interface SerializedError {
51
+ message: string;
52
+ name?: string;
53
+ stack?: string;
54
+ }
55
+
56
+ function serializeError(err: unknown): SerializedError {
57
+ if (err instanceof Error) {
58
+ return { message: err.message, name: err.name, stack: err.stack };
59
+ }
60
+ return { message: String(err) };
61
+ }
62
+
63
+ // Periodic memstat for diagnostic builds — set TXE_WORKER_MEMSTAT=1 to enable. Posts JS-heap
64
+ // breakdown + active-session count back to the dispatcher so we can attribute RSS growth
65
+ // between V8 heap (would show in heapUsed) and native (LMDB / world-state / WASM).
66
+ if (process.env.TXE_WORKER_MEMSTAT === '1') {
67
+ setInterval(() => {
68
+ const m = process.memoryUsage();
69
+ port.postMessage({
70
+ type: 'memstat',
71
+ sessions: activeSessionCount(),
72
+ rss: m.rss,
73
+ heapTotal: m.heapTotal,
74
+ heapUsed: m.heapUsed,
75
+ external: m.external,
76
+ arrayBuffers: m.arrayBuffers,
77
+ });
78
+ }, 2000).unref();
79
+ }
80
+
81
+ port.on('message', (msg: IncomingMessage) => {
82
+ switch (msg.type) {
83
+ case 'foreign-call':
84
+ void (async () => {
85
+ try {
86
+ const value = await dispatcher.resolve_foreign_call(msg.callData);
87
+ port.postMessage({ type: 'result', requestId: msg.requestId, ok: true, value });
88
+ } catch (err) {
89
+ port.postMessage({ type: 'result', requestId: msg.requestId, ok: false, error: serializeError(err) });
90
+ }
91
+ })();
92
+ return;
93
+ case 'dispose-session':
94
+ // Fire-and-forget; the main thread does not wait for confirmation.
95
+ void dispatcher.disposeSession(msg.sessionId).catch(err => logger.warn(`disposeSession failed`, err));
96
+ return;
97
+ }
98
+ });