@aztec/foundation 0.71.0 → 0.73.0

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 (167) hide show
  1. package/dest/abi/abi.d.ts +3 -2
  2. package/dest/abi/abi.d.ts.map +1 -1
  3. package/dest/abi/abi.js +22 -5
  4. package/dest/abi/decoder.d.ts +1 -1
  5. package/dest/abi/decoder.d.ts.map +1 -1
  6. package/dest/abi/decoder.js +11 -2
  7. package/dest/abi/encoder.d.ts.map +1 -1
  8. package/dest/abi/encoder.js +12 -2
  9. package/dest/abi/event_selector.d.ts +2 -3
  10. package/dest/abi/event_selector.d.ts.map +1 -1
  11. package/dest/abi/event_selector.js +4 -5
  12. package/dest/abi/function_selector.d.ts +4 -15
  13. package/dest/abi/function_selector.d.ts.map +1 -1
  14. package/dest/abi/function_selector.js +6 -18
  15. package/dest/abi/index.d.ts +1 -0
  16. package/dest/abi/index.d.ts.map +1 -1
  17. package/dest/abi/index.js +2 -1
  18. package/dest/abi/u128.d.ts +13 -0
  19. package/dest/abi/u128.d.ts.map +1 -0
  20. package/dest/abi/u128.js +58 -0
  21. package/dest/abi/utils.d.ts +5 -0
  22. package/dest/abi/utils.d.ts.map +1 -1
  23. package/dest/abi/utils.js +8 -1
  24. package/dest/array/array.d.ts +8 -0
  25. package/dest/array/array.d.ts.map +1 -1
  26. package/dest/array/array.js +13 -1
  27. package/dest/aztec-address/index.d.ts +3 -3
  28. package/dest/aztec-address/index.d.ts.map +1 -1
  29. package/dest/aztec-address/index.js +5 -5
  30. package/dest/blob/blob.d.ts +150 -0
  31. package/dest/blob/blob.d.ts.map +1 -0
  32. package/dest/blob/blob.js +249 -0
  33. package/dest/blob/encoding.d.ts +53 -0
  34. package/dest/blob/encoding.d.ts.map +1 -0
  35. package/dest/blob/encoding.js +87 -0
  36. package/dest/blob/index.d.ts +4 -58
  37. package/dest/blob/index.d.ts.map +1 -1
  38. package/dest/blob/index.js +6 -142
  39. package/dest/blob/interface.d.ts +10 -0
  40. package/dest/blob/interface.d.ts.map +1 -0
  41. package/dest/blob/interface.js +2 -0
  42. package/dest/blob/mocks.d.ts +5 -0
  43. package/dest/blob/mocks.d.ts.map +1 -0
  44. package/dest/blob/mocks.js +25 -0
  45. package/dest/collection/array.d.ts +7 -0
  46. package/dest/collection/array.d.ts.map +1 -1
  47. package/dest/collection/array.js +13 -1
  48. package/dest/config/env_var.d.ts +1 -1
  49. package/dest/config/env_var.d.ts.map +1 -1
  50. package/dest/config/index.d.ts +1 -0
  51. package/dest/config/index.d.ts.map +1 -1
  52. package/dest/config/index.js +11 -14
  53. package/dest/crypto/index.d.ts +0 -7
  54. package/dest/crypto/index.d.ts.map +1 -1
  55. package/dest/crypto/index.js +1 -11
  56. package/dest/crypto/keys/index.d.ts +1 -1
  57. package/dest/crypto/keys/index.d.ts.map +1 -1
  58. package/dest/crypto/keys/index.js +5 -5
  59. package/dest/crypto/pedersen/pedersen.wasm.d.ts +3 -3
  60. package/dest/crypto/pedersen/pedersen.wasm.d.ts.map +1 -1
  61. package/dest/crypto/pedersen/pedersen.wasm.js +13 -10
  62. package/dest/crypto/poseidon/index.d.ts +5 -5
  63. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  64. package/dest/crypto/poseidon/index.js +20 -19
  65. package/dest/crypto/sync/index.d.ts +3 -0
  66. package/dest/crypto/sync/index.d.ts.map +1 -0
  67. package/dest/crypto/sync/index.js +5 -0
  68. package/dest/crypto/sync/pedersen/index.d.ts +21 -0
  69. package/dest/crypto/sync/pedersen/index.d.ts.map +1 -0
  70. package/dest/crypto/sync/pedersen/index.js +37 -0
  71. package/dest/crypto/sync/poseidon/index.d.ts +26 -0
  72. package/dest/crypto/sync/poseidon/index.d.ts.map +1 -0
  73. package/dest/crypto/sync/poseidon/index.js +57 -0
  74. package/dest/fields/fields.d.ts +10 -1
  75. package/dest/fields/fields.d.ts.map +1 -1
  76. package/dest/fields/fields.js +18 -9
  77. package/dest/fields/point.d.ts +5 -5
  78. package/dest/fields/point.d.ts.map +1 -1
  79. package/dest/fields/point.js +5 -5
  80. package/dest/iterable/toArray.d.ts +1 -1
  81. package/dest/iterable/toArray.d.ts.map +1 -1
  82. package/dest/iterable/toArray.js +1 -1
  83. package/dest/json-rpc/client/fetch.d.ts +2 -2
  84. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  85. package/dest/json-rpc/client/fetch.js +7 -7
  86. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  87. package/dest/json-rpc/client/safe_json_rpc_client.js +2 -2
  88. package/dest/json-rpc/convert.d.ts +1 -1
  89. package/dest/json-rpc/convert.d.ts.map +1 -1
  90. package/dest/json-rpc/convert.js +2 -2
  91. package/dest/json-rpc/server/safe_json_rpc_server.d.ts +17 -5
  92. package/dest/json-rpc/server/safe_json_rpc_server.d.ts.map +1 -1
  93. package/dest/json-rpc/server/safe_json_rpc_server.js +19 -10
  94. package/dest/json-rpc/server/telemetry.d.ts +2 -0
  95. package/dest/json-rpc/server/telemetry.d.ts.map +1 -0
  96. package/dest/json-rpc/server/telemetry.js +2 -0
  97. package/dest/message/index.d.ts +32 -0
  98. package/dest/message/index.d.ts.map +1 -0
  99. package/dest/message/index.js +23 -0
  100. package/dest/mutex/index.d.ts.map +1 -1
  101. package/dest/mutex/index.js +6 -4
  102. package/dest/promise/running-promise.d.ts +2 -1
  103. package/dest/promise/running-promise.d.ts.map +1 -1
  104. package/dest/promise/running-promise.js +6 -3
  105. package/dest/schemas/parse.d.ts +1 -1
  106. package/dest/schemas/parse.d.ts.map +1 -1
  107. package/dest/schemas/parse.js +2 -2
  108. package/dest/serialize/field_reader.d.ts +18 -0
  109. package/dest/serialize/field_reader.d.ts.map +1 -1
  110. package/dest/serialize/field_reader.js +32 -2
  111. package/dest/testing/files/index.d.ts +1 -1
  112. package/dest/testing/files/index.d.ts.map +1 -1
  113. package/dest/testing/files/index.js +3 -3
  114. package/dest/timer/timeout.js +2 -2
  115. package/dest/worker/browser/start_web_module.d.ts.map +1 -1
  116. package/dest/worker/browser/start_web_module.js +2 -1
  117. package/dest/worker/browser/web_worker.d.ts.map +1 -1
  118. package/dest/worker/browser/web_worker.js +2 -1
  119. package/dest/worker/node/node_worker.d.ts.map +1 -1
  120. package/dest/worker/node/node_worker.js +2 -1
  121. package/dest/worker/node/start_node_module.d.ts.map +1 -1
  122. package/dest/worker/node/start_node_module.js +2 -1
  123. package/package.json +6 -4
  124. package/src/abi/abi.ts +28 -8
  125. package/src/abi/decoder.ts +11 -2
  126. package/src/abi/encoder.ts +11 -1
  127. package/src/abi/event_selector.ts +3 -4
  128. package/src/abi/function_selector.ts +8 -29
  129. package/src/abi/index.ts +1 -0
  130. package/src/abi/u128.ts +71 -0
  131. package/src/abi/utils.ts +8 -0
  132. package/src/array/array.ts +15 -0
  133. package/src/aztec-address/index.ts +5 -5
  134. package/src/blob/blob.ts +294 -0
  135. package/src/blob/encoding.ts +98 -0
  136. package/src/blob/index.ts +5 -183
  137. package/src/blob/interface.ts +11 -0
  138. package/src/blob/mocks.ts +30 -0
  139. package/src/collection/array.ts +15 -0
  140. package/src/config/env_var.ts +8 -5
  141. package/src/config/index.ts +10 -12
  142. package/src/crypto/index.ts +0 -12
  143. package/src/crypto/keys/index.ts +5 -4
  144. package/src/crypto/pedersen/pedersen.wasm.ts +13 -14
  145. package/src/crypto/poseidon/index.ts +24 -39
  146. package/src/crypto/sync/index.ts +6 -0
  147. package/src/crypto/sync/pedersen/index.ts +45 -0
  148. package/src/crypto/sync/poseidon/index.ts +76 -0
  149. package/src/fields/fields.ts +18 -9
  150. package/src/fields/point.ts +6 -6
  151. package/src/iterable/toArray.ts +3 -1
  152. package/src/json-rpc/client/fetch.ts +14 -6
  153. package/src/json-rpc/client/safe_json_rpc_client.ts +1 -2
  154. package/src/json-rpc/convert.ts +2 -2
  155. package/src/json-rpc/server/safe_json_rpc_server.ts +30 -12
  156. package/src/json-rpc/server/telemetry.ts +0 -0
  157. package/src/message/index.ts +43 -0
  158. package/src/mutex/index.ts +5 -4
  159. package/src/promise/running-promise.ts +4 -1
  160. package/src/schemas/parse.ts +2 -2
  161. package/src/serialize/field_reader.ts +34 -1
  162. package/src/testing/files/index.ts +2 -2
  163. package/src/timer/timeout.ts +1 -1
  164. package/src/worker/browser/start_web_module.ts +1 -0
  165. package/src/worker/browser/web_worker.ts +1 -0
  166. package/src/worker/node/node_worker.ts +1 -0
  167. package/src/worker/node/start_node_module.ts +1 -0
@@ -16,6 +16,8 @@ export type EnvVar =
16
16
  | 'BB_SKIP_CLEANUP'
17
17
  | 'BB_WORKING_DIRECTORY'
18
18
  | 'BOOTSTRAP_NODES'
19
+ | 'BLOB_SINK_PORT'
20
+ | 'BLOB_SINK_URL'
19
21
  | 'BOT_DA_GAS_LIMIT'
20
22
  | 'BOT_FEE_PAYMENT_METHOD'
21
23
  | 'BOT_FLUSH_SETUP_TRANSACTIONS'
@@ -42,7 +44,6 @@ export type EnvVar =
42
44
  | 'DEBUG'
43
45
  | 'DEPLOY_AZTEC_CONTRACTS_SALT'
44
46
  | 'DEPLOY_AZTEC_CONTRACTS'
45
- | 'ENABLE_GAS'
46
47
  | 'ENFORCE_FEES'
47
48
  | 'ETHEREUM_HOST'
48
49
  | 'FEE_JUICE_CONTRACT_ADDRESS'
@@ -52,7 +53,9 @@ export type EnvVar =
52
53
  | 'GOVERNANCE_PROPOSER_PAYLOAD_ADDRESS'
53
54
  | 'INBOX_CONTRACT_ADDRESS'
54
55
  | 'L1_CHAIN_ID'
55
- | 'L1_CONSENSUS_CLIENT_URL'
56
+ | 'L1_CONSENSUS_HOST_URL'
57
+ | 'L1_CONSENSUS_HOST_API_KEY'
58
+ | 'L1_CONSENSUS_HOST_API_KEY_HEADER'
56
59
  | 'L1_PRIVATE_KEY'
57
60
  | 'L2_QUEUE_SIZE'
58
61
  | 'LOG_ELAPSED_TIME'
@@ -70,6 +73,7 @@ export type EnvVar =
70
73
  | 'OTEL_EXPORTER_OTLP_LOGS_ENDPOINT'
71
74
  | 'OTEL_SERVICE_NAME'
72
75
  | 'OTEL_COLLECT_INTERVAL_MS'
76
+ | 'OTEL_EXCLUDE_METRICS'
73
77
  | 'OTEL_EXPORT_TIMEOUT_MS'
74
78
  | 'OUTBOX_CONTRACT_ADDRESS'
75
79
  | 'P2P_BLOCK_CHECK_INTERVAL_MS'
@@ -102,7 +106,6 @@ export type EnvVar =
102
106
  | 'P2P_UDP_LISTEN_ADDR'
103
107
  | 'P2P_ARCHIVED_TX_LIMIT'
104
108
  | 'PEER_ID_PRIVATE_KEY'
105
- | 'PROVER_BLOB_SINK_URL'
106
109
  | 'PROOF_VERIFIER_L1_START_BLOCK'
107
110
  | 'PROOF_VERIFIER_POLL_INTERVAL_MS'
108
111
  | 'PROVER_AGENT_ENABLED'
@@ -142,7 +145,6 @@ export type EnvVar =
142
145
  | 'REGISTRY_CONTRACT_ADDRESS'
143
146
  | 'ROLLUP_CONTRACT_ADDRESS'
144
147
  | 'SEQ_ALLOWED_SETUP_FN'
145
- | 'SEQ_BLOB_SINK_URL'
146
148
  | 'SEQ_MAX_BLOCK_SIZE_IN_BYTES'
147
149
  | 'SEQ_MAX_TX_PER_BLOCK'
148
150
  | 'SEQ_MIN_TX_PER_BLOCK'
@@ -205,4 +207,5 @@ export type EnvVar =
205
207
  | 'FAUCET_L1_ASSETS'
206
208
  | 'K8S_POD_NAME'
207
209
  | 'K8S_POD_UID'
208
- | 'K8S_NAMESPACE_NAME';
210
+ | 'K8S_NAMESPACE_NAME'
211
+ | 'CUSTOM_FORWARDER_CONTRACT_ADDRESS';
@@ -9,6 +9,7 @@ export interface ConfigMapping {
9
9
  printDefault?: (val: any) => string;
10
10
  description: string;
11
11
  isBoolean?: boolean;
12
+ nested?: Record<string, ConfigMapping>;
12
13
  }
13
14
 
14
15
  export function isBooleanConfigValue<T>(obj: T, key: keyof T): boolean {
@@ -21,18 +22,15 @@ export function getConfigFromMappings<T>(configMappings: ConfigMappingsType<T>):
21
22
  const config = {} as T;
22
23
 
23
24
  for (const key in configMappings) {
24
- if (configMappings[key]) {
25
- const { env, parseEnv, defaultValue: def } = configMappings[key];
26
- // Special case for L1 contract addresses which is an object of config values
27
- if (key === 'l1Contracts' && def) {
28
- (config as any)[key] = getConfigFromMappings(def);
29
- } else {
30
- const val = env ? process.env[env] : undefined;
31
- if (val !== undefined) {
32
- (config as any)[key] = parseEnv ? parseEnv(val) : val;
33
- } else if (def !== undefined) {
34
- (config as any)[key] = def;
35
- }
25
+ const { env, parseEnv, defaultValue: def, nested } = configMappings[key];
26
+ if (nested) {
27
+ (config as any)[key] = getConfigFromMappings(nested);
28
+ } else {
29
+ const val = env ? process.env[env] : undefined;
30
+ if (val !== undefined) {
31
+ (config as any)[key] = parseEnv ? parseEnv(val) : val;
32
+ } else if (def !== undefined) {
33
+ (config as any)[key] = def;
36
34
  }
37
35
  }
38
36
  }
@@ -1,5 +1,3 @@
1
- import { BarretenbergSync } from '@aztec/bb.js';
2
-
3
1
  export * from './keccak/index.js';
4
2
  export * from './random/index.js';
5
3
  export * from './sha256/index.js';
@@ -8,13 +6,3 @@ export * from './pedersen/index.js';
8
6
  export * from './poseidon/index.js';
9
7
  export * from './secp256k1-signer/index.js';
10
8
  export * from './keys/index.js';
11
-
12
- /**
13
- * Init the bb singleton. This constructs (if not already) the barretenberg sync api within bb.js itself.
14
- * It takes about 100-200ms to initialize. It may not seem like much, but when in conjunction with many other things
15
- * initializing, developers may want to pick precisely when to incur this cost.
16
- * If in a test environment, we'll just do it on module load.
17
- */
18
- export async function init() {
19
- await BarretenbergSync.initSingleton();
20
- }
@@ -2,8 +2,9 @@ import { BarretenbergSync, RawBuffer } from '@aztec/bb.js';
2
2
 
3
3
  import { Fr } from '../../fields/fields.js';
4
4
 
5
- export function vkAsFieldsMegaHonk(input: Buffer): Fr[] {
6
- return BarretenbergSync.getSingleton()
7
- .acirVkAsFieldsMegaHonk(new RawBuffer(input))
8
- .map(bbFr => Fr.fromBuffer(Buffer.from(bbFr.toBuffer()))); // TODO(#4189): remove this conversion
5
+ export async function vkAsFieldsMegaHonk(input: Buffer): Promise<Fr[]> {
6
+ const api = await BarretenbergSync.initSingleton();
7
+ const result = api.acirVkAsFieldsMegaHonk(new RawBuffer(input));
8
+
9
+ return result.map(bbFr => Fr.fromBuffer(Buffer.from(bbFr.toBuffer()))); // TODO(#4189): remove this conversion
9
10
  }
@@ -7,12 +7,13 @@ import { type Fieldable, serializeToFields } from '../../serialize/serialize.js'
7
7
  * Create a pedersen commitment (point) from an array of input fields.
8
8
  * Left pads any inputs less than 32 bytes.
9
9
  */
10
- export function pedersenCommit(input: Buffer[], offset = 0) {
10
+ export async function pedersenCommit(input: Buffer[], offset = 0) {
11
11
  if (!input.every(i => i.length <= 32)) {
12
12
  throw new Error('All Pedersen Commit input buffers must be <= 32 bytes.');
13
13
  }
14
14
  input = input.map(i => (i.length < 32 ? Buffer.concat([Buffer.alloc(32 - i.length, 0), i]) : i));
15
- const point = BarretenbergSync.getSingleton().pedersenCommit(
15
+ const api = await BarretenbergSync.initSingleton();
16
+ const point = api.pedersenCommit(
16
17
  input.map(i => new FrBarretenberg(i)),
17
18
  offset,
18
19
  );
@@ -27,23 +28,21 @@ export function pedersenCommit(input: Buffer[], offset = 0) {
27
28
  * @param index - The separator index to use for the hash.
28
29
  * @returns The pedersen hash.
29
30
  */
30
- export function pedersenHash(input: Fieldable[], index = 0): Fr {
31
+ export async function pedersenHash(input: Fieldable[], index = 0): Promise<Fr> {
31
32
  const inputFields = serializeToFields(input);
32
- return Fr.fromBuffer(
33
- Buffer.from(
34
- BarretenbergSync.getSingleton()
35
- .pedersenHash(
36
- inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
37
- index,
38
- )
39
- .toBuffer(),
40
- ),
33
+ const api = await BarretenbergSync.initSingleton();
34
+ const hash = api.pedersenHash(
35
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
36
+ index,
41
37
  );
38
+ return Fr.fromBuffer(Buffer.from(hash.toBuffer()));
42
39
  }
43
40
 
44
41
  /**
45
42
  * Create a pedersen hash from an arbitrary length buffer.
46
43
  */
47
- export function pedersenHashBuffer(input: Buffer, index = 0) {
48
- return Buffer.from(BarretenbergSync.getSingleton().pedersenHashBuffer(input, index).toBuffer());
44
+ export async function pedersenHashBuffer(input: Buffer, index = 0) {
45
+ const api = await BarretenbergSync.initSingleton();
46
+ const result = api.pedersenHashBuffer(input, index);
47
+ return Buffer.from(result.toBuffer());
49
48
  }
@@ -8,17 +8,13 @@ import { type Fieldable, serializeToFields } from '../../serialize/serialize.js'
8
8
  * @param input - The input fields to hash.
9
9
  * @returns The poseidon hash.
10
10
  */
11
- export function poseidon2Hash(input: Fieldable[]): Fr {
11
+ export async function poseidon2Hash(input: Fieldable[]): Promise<Fr> {
12
12
  const inputFields = serializeToFields(input);
13
- return Fr.fromBuffer(
14
- Buffer.from(
15
- BarretenbergSync.getSingleton()
16
- .poseidon2Hash(
17
- inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
18
- )
19
- .toBuffer(),
20
- ),
13
+ const api = await BarretenbergSync.initSingleton();
14
+ const hash = api.poseidon2Hash(
15
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
21
16
  );
17
+ return Fr.fromBuffer(Buffer.from(hash.toBuffer()));
22
18
  }
23
19
 
24
20
  /**
@@ -27,29 +23,22 @@ export function poseidon2Hash(input: Fieldable[]): Fr {
27
23
  * @param separator - The domain separator.
28
24
  * @returns The poseidon hash.
29
25
  */
30
- export function poseidon2HashWithSeparator(input: Fieldable[], separator: number): Fr {
26
+ export async function poseidon2HashWithSeparator(input: Fieldable[], separator: number): Promise<Fr> {
31
27
  const inputFields = serializeToFields(input);
32
28
  inputFields.unshift(new Fr(separator));
33
- return Fr.fromBuffer(
34
- Buffer.from(
35
- BarretenbergSync.getSingleton()
36
- .poseidon2Hash(
37
- inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
38
- )
39
- .toBuffer(),
40
- ),
29
+ const api = await BarretenbergSync.initSingleton();
30
+
31
+ const hash = api.poseidon2Hash(
32
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
41
33
  );
34
+ return Fr.fromBuffer(Buffer.from(hash.toBuffer()));
42
35
  }
43
36
 
44
- export function poseidon2HashAccumulate(input: Fieldable[]): Fr {
37
+ export async function poseidon2HashAccumulate(input: Fieldable[]): Promise<Fr> {
45
38
  const inputFields = serializeToFields(input);
46
- return Fr.fromBuffer(
47
- Buffer.from(
48
- BarretenbergSync.getSingleton()
49
- .poseidon2HashAccumulate(inputFields.map(i => new FrBarretenberg(i.toBuffer())))
50
- .toBuffer(),
51
- ),
52
- );
39
+ const api = await BarretenbergSync.initSingleton();
40
+ const result = api.poseidon2HashAccumulate(inputFields.map(i => new FrBarretenberg(i.toBuffer())));
41
+ return Fr.fromBuffer(Buffer.from(result.toBuffer()));
53
42
  }
54
43
 
55
44
  /**
@@ -57,19 +46,18 @@ export function poseidon2HashAccumulate(input: Fieldable[]): Fr {
57
46
  * @param input the input state. Expected to be of size 4.
58
47
  * @returns the output state, size 4.
59
48
  */
60
- export function poseidon2Permutation(input: Fieldable[]): Fr[] {
49
+ export async function poseidon2Permutation(input: Fieldable[]): Promise<Fr[]> {
61
50
  const inputFields = serializeToFields(input);
62
51
  // We'd like this assertion but it's not possible to use it in the browser.
63
52
  // assert(input.length === 4, 'Input state must be of size 4');
64
- const res = BarretenbergSync.getSingleton().poseidon2Permutation(
65
- inputFields.map(i => new FrBarretenberg(i.toBuffer())),
66
- );
53
+ const api = await BarretenbergSync.initSingleton();
54
+ const res = api.poseidon2Permutation(inputFields.map(i => new FrBarretenberg(i.toBuffer())));
67
55
  // We'd like this assertion but it's not possible to use it in the browser.
68
56
  // assert(res.length === 4, 'Output state must be of size 4');
69
57
  return res.map(o => Fr.fromBuffer(Buffer.from(o.toBuffer())));
70
58
  }
71
59
 
72
- export function poseidon2HashBytes(input: Buffer): Fr {
60
+ export async function poseidon2HashBytes(input: Buffer): Promise<Fr> {
73
61
  const inputFields = [];
74
62
  for (let i = 0; i < input.length; i += 31) {
75
63
  const fieldBytes = Buffer.alloc(32, 0);
@@ -80,13 +68,10 @@ export function poseidon2HashBytes(input: Buffer): Fr {
80
68
  inputFields.push(Fr.fromBuffer(fieldBytes));
81
69
  }
82
70
 
83
- return Fr.fromBuffer(
84
- Buffer.from(
85
- BarretenbergSync.getSingleton()
86
- .poseidon2Hash(
87
- inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
88
- )
89
- .toBuffer(),
90
- ),
71
+ const api = await BarretenbergSync.initSingleton();
72
+ const res = api.poseidon2Hash(
73
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
91
74
  );
75
+
76
+ return Fr.fromBuffer(Buffer.from(res.toBuffer()));
92
77
  }
@@ -0,0 +1,6 @@
1
+ import { BarretenbergSync } from '@aztec/bb.js';
2
+
3
+ export * from './poseidon/index.js';
4
+ export * from './pedersen/index.js';
5
+
6
+ await BarretenbergSync.initSingleton();
@@ -0,0 +1,45 @@
1
+ import { BarretenbergSync, Fr as FrBarretenberg } from '@aztec/bb.js';
2
+
3
+ import { Fr } from '../../../fields/fields.js';
4
+ import { type Fieldable, serializeToFields } from '../../../serialize/serialize.js';
5
+
6
+ /**
7
+ * Create a pedersen commitment (point) from an array of input fields.
8
+ * Left pads any inputs less than 32 bytes.
9
+ */
10
+ export function pedersenCommit(input: Buffer[], offset = 0) {
11
+ if (!input.every(i => i.length <= 32)) {
12
+ throw new Error('All Pedersen Commit input buffers must be <= 32 bytes.');
13
+ }
14
+ input = input.map(i => (i.length < 32 ? Buffer.concat([Buffer.alloc(32 - i.length, 0), i]) : i));
15
+ const point = BarretenbergSync.getSingleton().pedersenCommit(
16
+ input.map(i => new FrBarretenberg(i)),
17
+ offset,
18
+ );
19
+ // toBuffer returns Uint8Arrays (browser/worker-boundary friendly).
20
+ // TODO: rename toTypedArray()?
21
+ return [Buffer.from(point.x.toBuffer()), Buffer.from(point.y.toBuffer())];
22
+ }
23
+
24
+ /**
25
+ * Create a pedersen hash (field) from an array of input fields.
26
+ * @param input - The input fieldables to hash.
27
+ * @param index - The separator index to use for the hash.
28
+ * @returns The pedersen hash.
29
+ */
30
+ export function pedersenHash(input: Fieldable[], index = 0): Fr {
31
+ const inputFields = serializeToFields(input);
32
+ const hash = BarretenbergSync.getSingleton().pedersenHash(
33
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
34
+ index,
35
+ );
36
+ return Fr.fromBuffer(Buffer.from(hash.toBuffer()));
37
+ }
38
+
39
+ /**
40
+ * Create a pedersen hash from an arbitrary length buffer.
41
+ */
42
+ export function pedersenHashBuffer(input: Buffer, index = 0) {
43
+ const result = BarretenbergSync.getSingleton().pedersenHashBuffer(input, index);
44
+ return Buffer.from(result.toBuffer());
45
+ }
@@ -0,0 +1,76 @@
1
+ import { BarretenbergSync, Fr as FrBarretenberg } from '@aztec/bb.js';
2
+
3
+ import { Fr } from '../../../fields/fields.js';
4
+ import { type Fieldable, serializeToFields } from '../../../serialize/serialize.js';
5
+
6
+ /**
7
+ * Create a poseidon hash (field) from an array of input fields.
8
+ * @param input - The input fields to hash.
9
+ * @returns The poseidon hash.
10
+ */
11
+ export function poseidon2Hash(input: Fieldable[]): Fr {
12
+ const inputFields = serializeToFields(input);
13
+ const hash = BarretenbergSync.getSingleton().poseidon2Hash(
14
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
15
+ );
16
+ return Fr.fromBuffer(Buffer.from(hash.toBuffer()));
17
+ }
18
+
19
+ /**
20
+ * Create a poseidon hash (field) from an array of input fields and a domain separator.
21
+ * @param input - The input fields to hash.
22
+ * @param separator - The domain separator.
23
+ * @returns The poseidon hash.
24
+ */
25
+ export function poseidon2HashWithSeparator(input: Fieldable[], separator: number): Fr {
26
+ const inputFields = serializeToFields(input);
27
+ inputFields.unshift(new Fr(separator));
28
+
29
+ const hash = BarretenbergSync.getSingleton().poseidon2Hash(
30
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
31
+ );
32
+ return Fr.fromBuffer(Buffer.from(hash.toBuffer()));
33
+ }
34
+
35
+ export function poseidon2HashAccumulate(input: Fieldable[]): Fr {
36
+ const inputFields = serializeToFields(input);
37
+ const result = BarretenbergSync.getSingleton().poseidon2HashAccumulate(
38
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())),
39
+ );
40
+ return Fr.fromBuffer(Buffer.from(result.toBuffer()));
41
+ }
42
+
43
+ /**
44
+ * Runs a Poseidon2 permutation.
45
+ * @param input the input state. Expected to be of size 4.
46
+ * @returns the output state, size 4.
47
+ */
48
+ export function poseidon2Permutation(input: Fieldable[]): Fr[] {
49
+ const inputFields = serializeToFields(input);
50
+ // We'd like this assertion but it's not possible to use it in the browser.
51
+ // assert(input.length === 4, 'Input state must be of size 4');
52
+ const res = BarretenbergSync.getSingleton().poseidon2Permutation(
53
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())),
54
+ );
55
+ // We'd like this assertion but it's not possible to use it in the browser.
56
+ // assert(res.length === 4, 'Output state must be of size 4');
57
+ return res.map(o => Fr.fromBuffer(Buffer.from(o.toBuffer())));
58
+ }
59
+
60
+ export function poseidon2HashBytes(input: Buffer): Fr {
61
+ const inputFields = [];
62
+ for (let i = 0; i < input.length; i += 31) {
63
+ const fieldBytes = Buffer.alloc(32, 0);
64
+ input.slice(i, i + 31).copy(fieldBytes);
65
+
66
+ // Noir builds the bytes as little-endian, so we need to reverse them.
67
+ fieldBytes.reverse();
68
+ inputFields.push(Fr.fromBuffer(fieldBytes));
69
+ }
70
+
71
+ const res = BarretenbergSync.getSingleton().poseidon2Hash(
72
+ inputFields.map(i => new FrBarretenberg(i.toBuffer())), // TODO(#4189): remove this stupid conversion
73
+ );
74
+
75
+ return Fr.fromBuffer(Buffer.from(res.toBuffer()));
76
+ }
@@ -99,6 +99,10 @@ abstract class BaseField {
99
99
  return Boolean(this.toBigInt());
100
100
  }
101
101
 
102
+ /**
103
+ * Converts this field to a number.
104
+ * Throws if the underlying value is greater than MAX_SAFE_INTEGER.
105
+ */
102
106
  toNumber(): number {
103
107
  const value = this.toBigInt();
104
108
  if (value > Number.MAX_SAFE_INTEGER) {
@@ -107,6 +111,15 @@ abstract class BaseField {
107
111
  return Number(value);
108
112
  }
109
113
 
114
+ /**
115
+ * Converts this field to a number.
116
+ * May cause loss of precision if the underlying value is greater than MAX_SAFE_INTEGER.
117
+ */
118
+ toNumberUnsafe(): number {
119
+ const value = this.toBigInt();
120
+ return Number(value);
121
+ }
122
+
110
123
  toShortString(): string {
111
124
  const str = this.toString();
112
125
  return `${str.slice(0, 10)}...${str.slice(-4)}`;
@@ -305,19 +318,15 @@ export class Fr extends BaseField {
305
318
  * Computes a square root of the field element.
306
319
  * @returns A square root of the field element (null if it does not exist).
307
320
  */
308
- sqrt(): Fr | null {
309
- const wasm = BarretenbergSync.getSingleton().getWasm();
310
- wasm.writeMemory(0, this.toBuffer());
311
- wasm.call('bn254_fr_sqrt', 0, Fr.SIZE_IN_BYTES);
312
- const isSqrtBuf = Buffer.from(wasm.getMemorySlice(Fr.SIZE_IN_BYTES, Fr.SIZE_IN_BYTES + 1));
313
- const isSqrt = isSqrtBuf[0] === 1;
321
+ async sqrt(): Promise<Fr | null> {
322
+ const wasm = (await BarretenbergSync.initSingleton()).getWasm();
323
+ const [buf] = wasm.callWasmExport('bn254_fr_sqrt', [this.toBuffer()], [Fr.SIZE_IN_BYTES + 1]);
324
+ const isSqrt = buf[0] === 1;
314
325
  if (!isSqrt) {
315
326
  // Field element is not a quadratic residue mod p so it has no square root.
316
327
  return null;
317
328
  }
318
-
319
- const rootBuf = Buffer.from(wasm.getMemorySlice(Fr.SIZE_IN_BYTES + 1, Fr.SIZE_IN_BYTES * 2 + 1));
320
- return Fr.fromBuffer(rootBuf);
329
+ return new Fr(Buffer.from(buf.slice(1)));
321
330
  }
322
331
 
323
332
  toJSON() {
@@ -50,10 +50,10 @@ export class Point {
50
50
  *
51
51
  * @returns A randomly generated Point instance.
52
52
  */
53
- static random() {
53
+ static async random() {
54
54
  while (true) {
55
55
  try {
56
- return Point.fromXAndSign(Fr.random(), randomBoolean());
56
+ return await Point.fromXAndSign(Fr.random(), randomBoolean());
57
57
  } catch (e: any) {
58
58
  if (!(e instanceof NotOnCurveError)) {
59
59
  throw e;
@@ -83,7 +83,7 @@ export class Point {
83
83
  * @param buffer - The buffer containing the x coordinate and the sign of the y coordinate.
84
84
  * @returns A Point instance.
85
85
  */
86
- static fromCompressedBuffer(buffer: Buffer | BufferReader) {
86
+ static fromCompressedBuffer(buffer: Buffer | BufferReader): Promise<Point> {
87
87
  const reader = BufferReader.asReader(buffer);
88
88
  const value = toBigIntBE(reader.readBytes(Point.COMPRESSED_SIZE_IN_BYTES));
89
89
 
@@ -127,8 +127,8 @@ export class Point {
127
127
  * Instead it is a boolean flag that determines whether the y coordinate is <= (Fr.MODULUS - 1) / 2
128
128
  * @returns The point as an array of 2 fields
129
129
  */
130
- static fromXAndSign(x: Fr, sign: boolean) {
131
- const y = Point.YFromX(x);
130
+ static async fromXAndSign(x: Fr, sign: boolean) {
131
+ const y = await Point.YFromX(x);
132
132
  if (y == null) {
133
133
  throw new NotOnCurveError(x);
134
134
  }
@@ -146,7 +146,7 @@ export class Point {
146
146
  /**
147
147
  * @returns
148
148
  */
149
- static YFromX(x: Fr): Fr | null {
149
+ static YFromX(x: Fr): Promise<Fr | null> {
150
150
  // Calculate y^2 = x^3 - 17 (i.e. the Grumpkin curve equation)
151
151
  const ySquared = x.square().mul(x).sub(new Fr(17));
152
152
 
@@ -1,4 +1,6 @@
1
- export async function toArray<T>(iterator: AsyncIterableIterator<T> | IterableIterator<T>): Promise<T[]> {
1
+ export async function toArray<T>(
2
+ iterator: Iterable<T> | AsyncIterableIterator<T> | AsyncIterable<T> | IterableIterator<T>,
3
+ ): Promise<T[]> {
2
4
  const arr = [];
3
5
  for await (const i of iterator) {
4
6
  arr.push(i);
@@ -21,6 +21,7 @@ export async function defaultFetch(
21
21
  rpcMethod: string,
22
22
  body: any,
23
23
  useApiEndpoints: boolean,
24
+ extraHeaders: Record<string, string> = {},
24
25
  noRetry = false,
25
26
  ) {
26
27
  log.debug(format(`JsonRpcClient.fetch`, host, rpcMethod, '->', body));
@@ -30,13 +31,13 @@ export async function defaultFetch(
30
31
  resp = await fetch(`${host}/${rpcMethod}`, {
31
32
  method: 'POST',
32
33
  body: jsonStringify(body),
33
- headers: { 'content-type': 'application/json' },
34
+ headers: { 'content-type': 'application/json', ...extraHeaders },
34
35
  });
35
36
  } else {
36
37
  resp = await fetch(host, {
37
38
  method: 'POST',
38
39
  body: jsonStringify({ ...body, method: rpcMethod }),
39
- headers: { 'content-type': 'application/json' },
40
+ headers: { 'content-type': 'application/json', ...extraHeaders },
40
41
  });
41
42
  }
42
43
  } catch (err) {
@@ -55,7 +56,7 @@ export async function defaultFetch(
55
56
  }
56
57
 
57
58
  if (!resp.ok) {
58
- const errorMessage = `(JSON-RPC PROPAGATED) (host ${host}) (method ${rpcMethod}) (code ${resp.status}) ${responseJson.error.message}`;
59
+ const errorMessage = `Error ${resp.status} from server ${host} on ${rpcMethod}: ${responseJson.error.message}`;
59
60
  if (noRetry || (resp.status >= 400 && resp.status < 500)) {
60
61
  throw new NoRetryError(errorMessage);
61
62
  } else {
@@ -73,10 +74,17 @@ export async function defaultFetch(
73
74
  * @param log - Optional logger for logging attempts.
74
75
  * @returns A fetch function.
75
76
  */
76
- export function makeFetch(retries: number[], defaultNoRetry: boolean, log?: Logger) {
77
- return async (host: string, rpcMethod: string, body: any, useApiEndpoints: boolean, noRetry?: boolean) => {
77
+ export function makeFetch(retries: number[], defaultNoRetry: boolean, log?: Logger): typeof defaultFetch {
78
+ return async (
79
+ host: string,
80
+ rpcMethod: string,
81
+ body: any,
82
+ useApiEndpoints: boolean,
83
+ extraHeaders: Record<string, string> = {},
84
+ noRetry?: boolean,
85
+ ) => {
78
86
  return await retry(
79
- () => defaultFetch(host, rpcMethod, body, useApiEndpoints, noRetry ?? defaultNoRetry),
87
+ () => defaultFetch(host, rpcMethod, body, useApiEndpoints, extraHeaders, noRetry ?? defaultNoRetry),
80
88
  `JsonRpcClient request ${rpcMethod} to ${host}`,
81
89
  makeBackoff(retries),
82
90
  log,
@@ -40,8 +40,7 @@ export function createSafeJsonRpcClient<T extends object>(
40
40
  if ([null, undefined, 'null', 'undefined'].includes(res.result)) {
41
41
  return;
42
42
  }
43
-
44
- return (schema as ApiSchema)[methodName].returnType().parse(res.result);
43
+ return (schema as ApiSchema)[methodName].returnType().parseAsync(res.result);
45
44
  };
46
45
 
47
46
  const proxy: any = {};
@@ -8,8 +8,8 @@ import { type ZodFor } from '../schemas/types.js';
8
8
  * @param schema - Zod schema.
9
9
  * @returns Result of parsing json with schema.
10
10
  */
11
- export function jsonParseWithSchema<T>(json: string, schema: ZodFor<T>): T {
12
- return schema.parse(JSON.parse(json));
11
+ export function jsonParseWithSchema<T>(json: string, schema: ZodFor<T>): Promise<T> {
12
+ return schema.parseAsync(JSON.parse(json));
13
13
  }
14
14
 
15
15
  /**