@aztec/foundation 0.0.1-commit.179ed20 → 0.0.1-commit.189eedb3

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 (307) hide show
  1. package/dest/array/sorted_array.d.ts +6 -1
  2. package/dest/array/sorted_array.d.ts.map +1 -1
  3. package/dest/array/sorted_array.js +18 -15
  4. package/dest/bigint-buffer/index.d.ts +1 -1
  5. package/dest/bigint-buffer/index.d.ts.map +1 -1
  6. package/dest/bigint-buffer/index.js +6 -1
  7. package/dest/branded-types/block_number.d.ts +3 -3
  8. package/dest/branded-types/block_number.d.ts.map +1 -1
  9. package/dest/branded-types/block_number.js +15 -4
  10. package/dest/branded-types/buffer32_hash.d.ts +27 -0
  11. package/dest/branded-types/buffer32_hash.d.ts.map +1 -0
  12. package/dest/branded-types/buffer32_hash.js +12 -0
  13. package/dest/branded-types/checkpoint_number.d.ts +9 -3
  14. package/dest/branded-types/checkpoint_number.d.ts.map +1 -1
  15. package/dest/branded-types/checkpoint_number.js +11 -0
  16. package/dest/branded-types/epoch.d.ts +2 -2
  17. package/dest/branded-types/epoch.d.ts.map +1 -1
  18. package/dest/branded-types/index.d.ts +2 -1
  19. package/dest/branded-types/index.d.ts.map +1 -1
  20. package/dest/branded-types/index.js +1 -0
  21. package/dest/branded-types/index_within_checkpoint.d.ts +2 -2
  22. package/dest/branded-types/index_within_checkpoint.d.ts.map +1 -1
  23. package/dest/branded-types/slot.d.ts +5 -2
  24. package/dest/branded-types/slot.d.ts.map +1 -1
  25. package/dest/branded-types/slot.js +3 -0
  26. package/dest/buffer/buffer16.d.ts +3 -1
  27. package/dest/buffer/buffer16.d.ts.map +1 -1
  28. package/dest/buffer/buffer32.d.ts +28 -61
  29. package/dest/buffer/buffer32.d.ts.map +1 -1
  30. package/dest/buffer/buffer32.js +29 -63
  31. package/dest/buffer/index.d.ts +2 -1
  32. package/dest/buffer/index.d.ts.map +1 -1
  33. package/dest/buffer/index.js +1 -0
  34. package/dest/buffer/utils.d.ts +3 -0
  35. package/dest/buffer/utils.d.ts.map +1 -0
  36. package/dest/buffer/utils.js +7 -0
  37. package/dest/collection/array.d.ts +11 -1
  38. package/dest/collection/array.d.ts.map +1 -1
  39. package/dest/collection/array.js +33 -0
  40. package/dest/collection/index.d.ts +3 -1
  41. package/dest/collection/index.d.ts.map +1 -1
  42. package/dest/collection/index.js +2 -0
  43. package/dest/collection/lru_map.d.ts +41 -0
  44. package/dest/collection/lru_map.d.ts.map +1 -0
  45. package/dest/collection/lru_map.js +119 -0
  46. package/dest/collection/lru_set.d.ts +35 -0
  47. package/dest/collection/lru_set.d.ts.map +1 -0
  48. package/dest/collection/lru_set.js +95 -0
  49. package/dest/committable/committable.js +1 -1
  50. package/dest/config/env_var.d.ts +2 -2
  51. package/dest/config/env_var.d.ts.map +1 -1
  52. package/dest/config/index.d.ts +47 -30
  53. package/dest/config/index.d.ts.map +1 -1
  54. package/dest/config/index.js +44 -44
  55. package/dest/config/network_config.d.ts +15 -41
  56. package/dest/config/network_config.d.ts.map +1 -1
  57. package/dest/config/network_config.js +4 -1
  58. package/dest/config/network_name.d.ts +2 -2
  59. package/dest/config/network_name.d.ts.map +1 -1
  60. package/dest/config/network_name.js +3 -3
  61. package/dest/config/secret_value.d.ts +2 -2
  62. package/dest/config/secret_value.d.ts.map +1 -1
  63. package/dest/crypto/aes128/index.d.ts +2 -1
  64. package/dest/crypto/aes128/index.d.ts.map +1 -1
  65. package/dest/crypto/aes128/index.js +11 -2
  66. package/dest/crypto/bls/bn254_keystore.d.ts +9 -176
  67. package/dest/crypto/bls/bn254_keystore.d.ts.map +1 -1
  68. package/dest/crypto/bls/bn254_keystore.js +0 -17
  69. package/dest/crypto/poseidon/index.d.ts +1 -1
  70. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  71. package/dest/crypto/poseidon/index.js +40 -33
  72. package/dest/crypto/schnorr/index.d.ts +8 -7
  73. package/dest/crypto/schnorr/index.d.ts.map +1 -1
  74. package/dest/crypto/schnorr/index.js +6 -6
  75. package/dest/crypto/schnorr/signature.d.ts +9 -29
  76. package/dest/crypto/schnorr/signature.d.ts.map +1 -1
  77. package/dest/crypto/schnorr/signature.js +20 -36
  78. package/dest/crypto/secp256k1-signer/utils.d.ts +12 -1
  79. package/dest/crypto/secp256k1-signer/utils.d.ts.map +1 -1
  80. package/dest/crypto/secp256k1-signer/utils.js +26 -0
  81. package/dest/curves/bls12/field.d.ts +3 -3
  82. package/dest/curves/bls12/field.d.ts.map +1 -1
  83. package/dest/curves/bls12/field.js +0 -5
  84. package/dest/curves/bls12/point.d.ts +2 -2
  85. package/dest/curves/bls12/point.d.ts.map +1 -1
  86. package/dest/curves/bn254/field.d.ts +24 -19
  87. package/dest/curves/bn254/field.d.ts.map +1 -1
  88. package/dest/curves/bn254/field.js +28 -19
  89. package/dest/curves/grumpkin/point.d.ts +14 -28
  90. package/dest/curves/grumpkin/point.d.ts.map +1 -1
  91. package/dest/curves/grumpkin/point.js +29 -43
  92. package/dest/eth-address/index.d.ts +2 -2
  93. package/dest/eth-address/index.d.ts.map +1 -1
  94. package/dest/eth-address/index.js +0 -3
  95. package/dest/eth-signature/eth_signature.d.ts +3 -2
  96. package/dest/eth-signature/eth_signature.d.ts.map +1 -1
  97. package/dest/eth-signature/eth_signature.js +7 -2
  98. package/dest/fifo/fifo_frame_reader.d.ts +41 -0
  99. package/dest/fifo/fifo_frame_reader.d.ts.map +1 -0
  100. package/dest/fifo/fifo_frame_reader.js +91 -0
  101. package/dest/fifo/index.d.ts +2 -0
  102. package/dest/fifo/index.d.ts.map +1 -0
  103. package/dest/fifo/index.js +1 -0
  104. package/dest/fifo_set/fifo_set.d.ts +15 -0
  105. package/dest/fifo_set/fifo_set.d.ts.map +1 -0
  106. package/dest/fifo_set/fifo_set.js +39 -0
  107. package/dest/fifo_set/index.d.ts +2 -0
  108. package/dest/fifo_set/index.d.ts.map +1 -0
  109. package/dest/fifo_set/index.js +1 -0
  110. package/dest/jest/setup.js +24 -0
  111. package/dest/json-rpc/client/fetch.d.ts +1 -1
  112. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  113. package/dest/json-rpc/client/fetch.js +4 -3
  114. package/dest/json-rpc/client/safe_json_rpc_client.d.ts +2 -1
  115. package/dest/json-rpc/client/safe_json_rpc_client.d.ts.map +1 -1
  116. package/dest/json-rpc/client/safe_json_rpc_client.js +3 -3
  117. package/dest/json-rpc/client/undici.d.ts +1 -1
  118. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  119. package/dest/json-rpc/client/undici.js +5 -3
  120. package/dest/json-rpc/fixtures/test_state.d.ts +4 -8
  121. package/dest/json-rpc/fixtures/test_state.d.ts.map +1 -1
  122. package/dest/json-rpc/fixtures/test_state.js +57 -17
  123. package/dest/json-rpc/server/api_key_auth.d.ts +19 -0
  124. package/dest/json-rpc/server/api_key_auth.d.ts.map +1 -0
  125. package/dest/json-rpc/server/api_key_auth.js +57 -0
  126. package/dest/json-rpc/server/index.d.ts +2 -1
  127. package/dest/json-rpc/server/index.d.ts.map +1 -1
  128. package/dest/json-rpc/server/index.js +1 -0
  129. package/dest/json-rpc/server/safe_json_rpc_server.d.ts +8 -3
  130. package/dest/json-rpc/server/safe_json_rpc_server.d.ts.map +1 -1
  131. package/dest/json-rpc/server/safe_json_rpc_server.js +27 -13
  132. package/dest/log/bigint-utils.d.ts +5 -0
  133. package/dest/log/bigint-utils.d.ts.map +1 -0
  134. package/dest/log/bigint-utils.js +21 -0
  135. package/dest/log/gcloud-logger-config.d.ts +1 -1
  136. package/dest/log/gcloud-logger-config.d.ts.map +1 -1
  137. package/dest/log/gcloud-logger-config.js +3 -0
  138. package/dest/log/log-filters.d.ts +17 -4
  139. package/dest/log/log-filters.d.ts.map +1 -1
  140. package/dest/log/log-filters.js +26 -12
  141. package/dest/log/pino-logger.d.ts +1 -1
  142. package/dest/log/pino-logger.d.ts.map +1 -1
  143. package/dest/log/pino-logger.js +23 -4
  144. package/dest/noir/noir_package_config.d.ts +19 -104
  145. package/dest/noir/noir_package_config.d.ts.map +1 -1
  146. package/dest/noir/noir_package_config.js +1 -1
  147. package/dest/queue/base_memory_queue.d.ts +2 -2
  148. package/dest/queue/base_memory_queue.d.ts.map +1 -1
  149. package/dest/queue/batch_queue.d.ts +1 -1
  150. package/dest/queue/batch_queue.d.ts.map +1 -1
  151. package/dest/queue/batch_queue.js +1 -0
  152. package/dest/retry/index.d.ts +12 -1
  153. package/dest/retry/index.d.ts.map +1 -1
  154. package/dest/retry/index.js +21 -0
  155. package/dest/schemas/api.d.ts +12 -10
  156. package/dest/schemas/api.d.ts.map +1 -1
  157. package/dest/schemas/api.js +7 -1
  158. package/dest/schemas/parse.d.ts +4 -4
  159. package/dest/schemas/parse.d.ts.map +1 -1
  160. package/dest/schemas/parse.js +6 -5
  161. package/dest/schemas/schemas.d.ts +15 -15
  162. package/dest/schemas/types.d.ts +3 -3
  163. package/dest/schemas/types.d.ts.map +1 -1
  164. package/dest/schemas/utils.d.ts +7 -11
  165. package/dest/schemas/utils.d.ts.map +1 -1
  166. package/dest/schemas/utils.js +2 -18
  167. package/dest/serialize/buffer_reader.d.ts +8 -1
  168. package/dest/serialize/buffer_reader.d.ts.map +1 -1
  169. package/dest/serialize/buffer_reader.js +13 -0
  170. package/dest/serialize/buffer_sink.d.ts +134 -0
  171. package/dest/serialize/buffer_sink.d.ts.map +1 -0
  172. package/dest/serialize/buffer_sink.js +297 -0
  173. package/dest/serialize/index.d.ts +2 -1
  174. package/dest/serialize/index.d.ts.map +1 -1
  175. package/dest/serialize/index.js +1 -0
  176. package/dest/serialize/serialize.d.ts +19 -1
  177. package/dest/serialize/serialize.d.ts.map +1 -1
  178. package/dest/serialize/serialize.js +31 -0
  179. package/dest/sleep/index.d.ts +2 -1
  180. package/dest/sleep/index.d.ts.map +1 -1
  181. package/dest/sleep/index.js +10 -1
  182. package/dest/string/index.js +1 -1
  183. package/dest/timer/date.d.ts +25 -1
  184. package/dest/timer/date.d.ts.map +1 -1
  185. package/dest/timer/date.js +33 -0
  186. package/dest/timer/index.d.ts +2 -2
  187. package/dest/timer/index.d.ts.map +1 -1
  188. package/dest/timer/index.js +1 -1
  189. package/dest/timer/timeout.d.ts +3 -1
  190. package/dest/timer/timeout.d.ts.map +1 -1
  191. package/dest/timer/timeout.js +26 -0
  192. package/dest/transport/dispatch/create_dispatch_proxy.d.ts +11 -2
  193. package/dest/transport/dispatch/create_dispatch_proxy.d.ts.map +1 -1
  194. package/dest/transport/index.d.ts +1 -2
  195. package/dest/transport/index.d.ts.map +1 -1
  196. package/dest/transport/index.js +0 -1
  197. package/dest/transport/transport_client.js +2 -2
  198. package/dest/trees/balanced_merkle_tree_root.d.ts +2 -3
  199. package/dest/trees/balanced_merkle_tree_root.d.ts.map +1 -1
  200. package/dest/trees/balanced_merkle_tree_root.js +2 -3
  201. package/dest/trees/hasher.d.ts +3 -2
  202. package/dest/trees/hasher.d.ts.map +1 -1
  203. package/dest/trees/hasher.js +5 -5
  204. package/dest/trees/indexed_merkle_tree_calculator.d.ts +1 -1
  205. package/dest/trees/indexed_merkle_tree_calculator.d.ts.map +1 -1
  206. package/dest/trees/indexed_merkle_tree_calculator.js +5 -1
  207. package/dest/trees/membership_witness.d.ts +2 -2
  208. package/dest/trees/membership_witness.d.ts.map +1 -1
  209. package/dest/trees/merkle_tree_calculator.d.ts +4 -2
  210. package/dest/trees/merkle_tree_calculator.d.ts.map +1 -1
  211. package/dest/trees/merkle_tree_calculator.js +1 -5
  212. package/dest/trees/sibling_path.d.ts +5 -4
  213. package/dest/trees/sibling_path.d.ts.map +1 -1
  214. package/dest/trees/sibling_path.js +10 -8
  215. package/dest/trees/unbalanced_merkle_tree_root.d.ts +2 -3
  216. package/dest/trees/unbalanced_merkle_tree_root.d.ts.map +1 -1
  217. package/dest/trees/unbalanced_merkle_tree_root.js +2 -3
  218. package/dest/types/index.d.ts +23 -1
  219. package/dest/types/index.d.ts.map +1 -1
  220. package/dest/types/index.js +15 -0
  221. package/package.json +26 -4
  222. package/src/array/sorted_array.ts +22 -17
  223. package/src/bigint-buffer/index.ts +6 -1
  224. package/src/branded-types/block_number.ts +20 -2
  225. package/src/branded-types/buffer32_hash.ts +38 -0
  226. package/src/branded-types/checkpoint_number.ts +16 -1
  227. package/src/branded-types/epoch.ts +1 -1
  228. package/src/branded-types/index.ts +1 -0
  229. package/src/branded-types/index_within_checkpoint.ts +1 -1
  230. package/src/branded-types/slot.ts +6 -1
  231. package/src/buffer/buffer16.ts +3 -0
  232. package/src/buffer/buffer32.ts +39 -68
  233. package/src/buffer/index.ts +1 -0
  234. package/src/buffer/utils.ts +8 -0
  235. package/src/collection/array.ts +34 -0
  236. package/src/collection/index.ts +2 -0
  237. package/src/collection/lru_map.ts +143 -0
  238. package/src/collection/lru_set.ts +115 -0
  239. package/src/committable/committable.ts +1 -1
  240. package/src/config/env_var.ts +69 -22
  241. package/src/config/index.ts +116 -96
  242. package/src/config/network_config.ts +3 -0
  243. package/src/config/network_name.ts +6 -6
  244. package/src/config/secret_value.ts +1 -1
  245. package/src/crypto/aes128/index.ts +11 -2
  246. package/src/crypto/bls/bn254_keystore.ts +0 -23
  247. package/src/crypto/poseidon/index.ts +42 -34
  248. package/src/crypto/schnorr/index.ts +9 -8
  249. package/src/crypto/schnorr/signature.ts +17 -46
  250. package/src/crypto/secp256k1-signer/utils.ts +32 -0
  251. package/src/curves/bls12/field.ts +0 -7
  252. package/src/curves/bn254/field.ts +41 -36
  253. package/src/curves/grumpkin/point.ts +23 -40
  254. package/src/eth-address/index.ts +0 -4
  255. package/src/eth-signature/eth_signature.ts +7 -1
  256. package/src/fifo/fifo_frame_reader.ts +113 -0
  257. package/src/fifo/index.ts +1 -0
  258. package/src/fifo_set/fifo_set.ts +52 -0
  259. package/src/fifo_set/index.ts +1 -0
  260. package/src/jest/setup.mjs +27 -0
  261. package/src/json-rpc/client/fetch.ts +4 -3
  262. package/src/json-rpc/client/safe_json_rpc_client.ts +4 -2
  263. package/src/json-rpc/client/undici.ts +5 -3
  264. package/src/json-rpc/fixtures/test_state.ts +10 -10
  265. package/src/json-rpc/server/api_key_auth.ts +63 -0
  266. package/src/json-rpc/server/index.ts +1 -0
  267. package/src/json-rpc/server/safe_json_rpc_server.ts +31 -13
  268. package/src/log/bigint-utils.ts +25 -0
  269. package/src/log/gcloud-logger-config.ts +5 -0
  270. package/src/log/log-filters.ts +29 -11
  271. package/src/log/pino-logger.ts +25 -4
  272. package/src/noir/noir_package_config.ts +32 -20
  273. package/src/queue/base_memory_queue.ts +1 -1
  274. package/src/queue/batch_queue.ts +1 -0
  275. package/src/retry/index.ts +30 -0
  276. package/src/schemas/api.ts +25 -25
  277. package/src/schemas/parse.ts +9 -6
  278. package/src/schemas/schemas.ts +4 -4
  279. package/src/schemas/types.ts +2 -2
  280. package/src/schemas/utils.ts +4 -38
  281. package/src/serialize/buffer_reader.ts +15 -0
  282. package/src/serialize/buffer_sink.ts +350 -0
  283. package/src/serialize/index.ts +1 -0
  284. package/src/serialize/serialize.ts +32 -0
  285. package/src/sleep/index.ts +10 -1
  286. package/src/string/index.ts +1 -1
  287. package/src/timer/date.ts +48 -0
  288. package/src/timer/index.ts +1 -1
  289. package/src/timer/timeout.ts +31 -0
  290. package/src/transport/dispatch/create_dispatch_proxy.ts +11 -1
  291. package/src/transport/index.ts +0 -1
  292. package/src/transport/transport_client.ts +2 -2
  293. package/src/trees/balanced_merkle_tree_root.ts +2 -5
  294. package/src/trees/hasher.ts +6 -3
  295. package/src/trees/indexed_merkle_tree_calculator.ts +5 -1
  296. package/src/trees/merkle_tree_calculator.ts +4 -10
  297. package/src/trees/sibling_path.ts +11 -6
  298. package/src/trees/unbalanced_merkle_tree_root.ts +2 -5
  299. package/src/types/index.ts +47 -0
  300. package/dest/crypto/serialize.d.ts +0 -51
  301. package/dest/crypto/serialize.d.ts.map +0 -1
  302. package/dest/crypto/serialize.js +0 -68
  303. package/dest/transport/dispatch/create_dispatch_fn.d.ts +0 -25
  304. package/dest/transport/dispatch/create_dispatch_fn.d.ts.map +0 -1
  305. package/dest/transport/dispatch/create_dispatch_fn.js +0 -17
  306. package/src/crypto/serialize.ts +0 -85
  307. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
@@ -22,6 +22,7 @@ import { InterruptError } from '../error/index.js';
22
22
  */
23
23
  export class InterruptibleSleep {
24
24
  private interrupts: Array<(shouldThrow: boolean) => void> = [];
25
+ private timeoutIds: NodeJS.Timeout[] = [];
25
26
 
26
27
  /**
27
28
  * Sleep for a specified amount of time in milliseconds.
@@ -38,9 +39,15 @@ export class InterruptibleSleep {
38
39
  this.interrupts.push(resolve);
39
40
  });
40
41
 
41
- const timeoutPromise = new Promise<boolean>(resolve => setTimeout(() => resolve(false), ms));
42
+ let timeoutId: NodeJS.Timeout;
43
+ const timeoutPromise = new Promise<boolean>(resolve => {
44
+ timeoutId = setTimeout(() => resolve(false), ms);
45
+ this.timeoutIds.push(timeoutId);
46
+ });
42
47
  const shouldThrow = await Promise.race([interruptPromise, timeoutPromise]);
43
48
 
49
+ clearTimeout(timeoutId!);
50
+ this.timeoutIds = this.timeoutIds.filter(id => id !== timeoutId);
44
51
  this.interrupts = this.interrupts.filter(res => res !== interruptResolve);
45
52
 
46
53
  if (shouldThrow) {
@@ -58,6 +65,8 @@ export class InterruptibleSleep {
58
65
  public interrupt(sleepShouldThrow = false): void {
59
66
  this.interrupts.forEach(resolve => resolve(sleepShouldThrow));
60
67
  this.interrupts = [];
68
+ this.timeoutIds.forEach(id => clearTimeout(id));
69
+ this.timeoutIds = [];
61
70
  }
62
71
  }
63
72
 
@@ -58,7 +58,7 @@ export function urlJoin(...args: string[]): string {
58
58
  end--;
59
59
  }
60
60
 
61
- if (start < end) {
61
+ if (start <= end) {
62
62
  processed.push(arg.slice(start, end + 1));
63
63
  }
64
64
  }
package/src/timer/date.ts CHANGED
@@ -31,4 +31,52 @@ export class TestDateProvider extends DateProvider {
31
31
  this.offset = timeMs - Date.now();
32
32
  this.logger.warn(`Time set to ${new Date(timeMs).toISOString()}`, { offset: this.offset, timeMs });
33
33
  }
34
+
35
+ /** Resets the time back to real time (offset = 0). */
36
+ public reset() {
37
+ this.offset = 0;
38
+ this.logger.warn('Time reset to real time');
39
+ }
40
+
41
+ /** Advances the time by the given number of seconds. */
42
+ public advanceTime(seconds: number) {
43
+ this.offset += seconds * 1000;
44
+ }
45
+ }
46
+
47
+ /**
48
+ * A date provider for tests that only advances time via explicit advanceTime() calls.
49
+ * Unlike TestDateProvider, this does NOT track real time progression - time is completely
50
+ * frozen until explicitly advanced. This eliminates flakiness from tests taking
51
+ * varying amounts of real time to execute.
52
+ */
53
+ export class ManualDateProvider extends DateProvider {
54
+ private currentTimeMs: number;
55
+
56
+ /**
57
+ * @param initialTimeMs - Initial time in milliseconds. Defaults to a round timestamp for easy visualization.
58
+ */
59
+ constructor(initialTimeMs: number = Date.UTC(2025, 0, 1, 0, 0, 0)) {
60
+ super();
61
+ this.currentTimeMs = initialTimeMs;
62
+ }
63
+
64
+ public override now(): number {
65
+ return this.currentTimeMs;
66
+ }
67
+
68
+ /** Sets the current time to the given timestamp in milliseconds. */
69
+ public setTime(timeMs: number) {
70
+ this.currentTimeMs = timeMs;
71
+ }
72
+
73
+ /** Advances the time by the given number of seconds. */
74
+ public advanceTime(seconds: number) {
75
+ this.currentTimeMs += seconds * 1000;
76
+ }
77
+
78
+ /** Advances the time by the given number of milliseconds. */
79
+ public advanceTimeMs(ms: number) {
80
+ this.currentTimeMs += ms;
81
+ }
34
82
  }
@@ -1,4 +1,4 @@
1
1
  export * from './date.js';
2
2
  export { elapsed, elapsedSync } from './elapsed.js';
3
- export { TimeoutTask, executeTimeout, timeoutPromise } from './timeout.js';
3
+ export { TimeoutTask, execWithSignal, executeTimeout, timeoutPromise } from './timeout.js';
4
4
  export { Timer } from './timer.js';
@@ -92,6 +92,37 @@ export async function executeTimeout<T>(
92
92
  return await task.exec();
93
93
  }
94
94
 
95
+ function defaultSignalError(signal: AbortSignal) {
96
+ if (signal.reason instanceof Error) {
97
+ return signal.reason;
98
+ }
99
+
100
+ return new Error(signal.reason ? String(signal.reason) : 'Operation aborted');
101
+ }
102
+
103
+ /** Executes a function until it completes or the given signal aborts. */
104
+ export async function execWithSignal<T>(
105
+ fn: (signal: AbortSignal) => Promise<T>,
106
+ signal: AbortSignal,
107
+ errorFn: (signal: AbortSignal) => Error = defaultSignalError,
108
+ ) {
109
+ if (signal.aborted) {
110
+ throw errorFn(signal);
111
+ }
112
+
113
+ const abortPromise = promiseWithResolvers<never>();
114
+ const abortListener = () => abortPromise.reject(errorFn(signal));
115
+ signal.addEventListener('abort', abortListener, { once: true });
116
+
117
+ try {
118
+ return await Promise.race<T>([fn(signal), abortPromise.promise]);
119
+ } finally {
120
+ if (abortListener) {
121
+ signal.removeEventListener('abort', abortListener);
122
+ }
123
+ }
124
+ }
125
+
95
126
  /** Returns a promise that rejects after the given timeout */
96
127
  export function timeoutPromise(timeoutMs: number, errorMessage?: string) {
97
128
  const promise = promiseWithResolvers<never>();
@@ -2,7 +2,17 @@ import { EventEmitter } from 'events';
2
2
 
3
3
  import { type TransferDescriptor, isTransferDescriptor } from '../interface/transferable.js';
4
4
  import type { TransportClient } from '../transport_client.js';
5
- import type { DispatchMsg } from './create_dispatch_fn.js';
5
+
6
+ /**
7
+ * Represents a message object for dispatching function calls.
8
+ * Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
9
+ */
10
+ export interface DispatchMsg {
11
+ /** Name of the target method to be called. */
12
+ fn: string;
13
+ /** An array of arguments to be passed to the target method. */
14
+ args: any[];
15
+ }
6
16
 
7
17
  /**
8
18
  * FilterOutAttributes type filters out all non-method properties of an object, leaving only the attributes
@@ -1,4 +1,3 @@
1
- export * from './dispatch/create_dispatch_fn.js';
2
1
  export * from './dispatch/create_dispatch_proxy.js';
3
2
  export * from './dispatch/messages.js';
4
3
  export * from './interface/connector.js';
@@ -91,7 +91,7 @@ export class TransportClient<Payload> extends EventEmitter {
91
91
  }
92
92
  const msgId = this.msgId++;
93
93
  const msg = { msgId, payload };
94
- log.debug(format(`->`, msg));
94
+ log.trace(format(`->`, msg));
95
95
  return new Promise<any>((resolve, reject) => {
96
96
  this.pendingRequests.push({ resolve, reject, msgId });
97
97
  this.socket!.send(msg, transfer).catch(reject);
@@ -111,7 +111,7 @@ export class TransportClient<Payload> extends EventEmitter {
111
111
  this.close();
112
112
  return;
113
113
  }
114
- log.debug(format(`<-`, msg));
114
+ log.trace(format(`<-`, msg));
115
115
  if (isEventMessage(msg)) {
116
116
  this.emit('event_msg', msg.payload);
117
117
  return;
@@ -1,10 +1,7 @@
1
- import { poseidonMerkleHash, shaMerkleHash } from './hasher.js';
1
+ import { shaMerkleHash } from './hasher.js';
2
2
 
3
3
  export const computeBalancedShaRoot = (leaves: Buffer[]) => computeBalancedMerkleTreeRoot(leaves);
4
4
 
5
- export const computeBalancedPoseidonRoot = async (leaves: Buffer[]) =>
6
- await computeBalancedMerkleTreeRootAsync(leaves, poseidonMerkleHash);
7
-
8
5
  /**
9
6
  * Computes the Merkle root with the provided leaves **synchronously**.
10
7
  * This method uses a synchronous hash function (defaults to `sha256Trunc`).
@@ -36,7 +33,7 @@ export function computeBalancedMerkleTreeRoot(leaves: Buffer[], hasher = shaMerk
36
33
  */
37
34
  export async function computeBalancedMerkleTreeRootAsync(
38
35
  leaves: Buffer[],
39
- hasher = poseidonMerkleHash,
36
+ hasher: (left: Buffer, right: Buffer) => Promise<Buffer<ArrayBuffer>>,
40
37
  ): Promise<Buffer> {
41
38
  const height = getTreeHeight(leaves);
42
39
  let nodes = leaves.slice();
@@ -1,4 +1,4 @@
1
- import { poseidon2Hash } from '../crypto/poseidon/index.js';
1
+ import { poseidon2HashWithSeparator } from '../crypto/poseidon/index.js';
2
2
  import { sha256Trunc } from '../crypto/sha256/index.js';
3
3
 
4
4
  /**
@@ -44,5 +44,8 @@ export interface AsyncHasher {
44
44
  export const shaMerkleHash: Hasher['hash'] = (left: Buffer, right: Buffer) =>
45
45
  sha256Trunc(Buffer.concat([left, right])) as Buffer<ArrayBuffer>;
46
46
 
47
- export const poseidonMerkleHash: AsyncHasher['hash'] = async (left: Buffer, right: Buffer) =>
48
- (await poseidon2Hash([left, right])).toBuffer() as Buffer<ArrayBuffer>;
47
+ /** Creates a poseidon2 merkle hasher with the given domain separator. */
48
+ export const makePoseidonMerkleHash =
49
+ (separator: number): AsyncHasher['hash'] =>
50
+ async (left: Buffer, right: Buffer) =>
51
+ (await poseidon2HashWithSeparator([left, right], separator)).toBuffer() as Buffer<ArrayBuffer>;
@@ -40,7 +40,11 @@ export class IndexedMerkleTreeCalculator<T extends IndexedTreeLeafPreimage, N ex
40
40
  }
41
41
  const sorted = values
42
42
  .map((v, i) => ({ value: v, index: i }))
43
- .sort((a, b) => Number(toBigIntBE(b.value) - toBigIntBE(a.value)));
43
+ .sort((a, b): -1 | 0 | 1 => {
44
+ const aBigInt = toBigIntBE(a.value);
45
+ const bBigInt = toBigIntBE(b.value);
46
+ return aBigInt < bBigInt ? 1 : aBigInt > bBigInt ? -1 : 0;
47
+ });
44
48
  const indexedLeaves = sorted.map((item, i) => ({
45
49
  leaf: this.factory.fromBuffer(
46
50
  Buffer.concat([
@@ -1,8 +1,7 @@
1
- import { poseidon2Hash } from '@aztec/foundation/crypto/poseidon';
2
-
3
- import type { AsyncHasher } from './hasher.js';
4
1
  import { MerkleTree } from './merkle_tree.js';
5
2
 
3
+ type MerkleHashFn = (left: Buffer, right: Buffer) => Promise<Buffer<ArrayBuffer>>;
4
+
6
5
  /**
7
6
  * Merkle tree calculator.
8
7
  */
@@ -10,17 +9,12 @@ export class MerkleTreeCalculator {
10
9
  private constructor(
11
10
  private height: number,
12
11
  private zeroHashes: Buffer[],
13
- private hasher: AsyncHasher['hash'],
12
+ private hasher: MerkleHashFn,
14
13
  ) {
15
14
  this.hasher = hasher;
16
15
  }
17
16
 
18
- static async create(
19
- height: number,
20
- zeroLeaf: Buffer = Buffer.alloc(32),
21
- hasher = async (left: Buffer, right: Buffer) =>
22
- (await poseidon2Hash([left, right])).toBuffer() as Buffer<ArrayBuffer>,
23
- ) {
17
+ static async create(height: number, zeroLeaf: Buffer = Buffer.alloc(32), hasher: MerkleHashFn) {
24
18
  const zeroHashes = [zeroLeaf];
25
19
  for (let i = 0; i < height; i++) {
26
20
  zeroHashes.push((await hasher(zeroHashes[i], zeroHashes[i])) as Buffer<ArrayBuffer>);
@@ -1,5 +1,6 @@
1
+ import { z } from 'zod';
2
+
1
3
  import { makeTuple } from '../array/array.js';
2
- import { poseidon2Hash } from '../crypto/poseidon/index.js';
3
4
  import { Fr } from '../curves/bn254/index.js';
4
5
  import { schemas } from '../schemas/index.js';
5
6
  import {
@@ -43,10 +44,14 @@ export class SiblingPath<N extends number> {
43
44
  }
44
45
 
45
46
  static schemaFor<N extends number>(size: N) {
46
- return schemas.Buffer.transform(b => SiblingPath.fromBuffer(b) as SiblingPath<N>).refine(
47
- path => path.pathSize === size,
48
- path => ({ message: `Expected sibling path size ${size} but got ${path.pathSize}` }),
49
- );
47
+ return schemas.Buffer.transform(b => SiblingPath.fromBuffer(b) as SiblingPath<N>).superRefine((path, ctx) => {
48
+ if (path.pathSize !== size) {
49
+ ctx.addIssue({
50
+ code: z.ZodIssueCode.custom,
51
+ message: `Expected sibling path size ${size} but got ${path.pathSize}`,
52
+ });
53
+ }
54
+ });
50
55
  }
51
56
 
52
57
  toJSON() {
@@ -172,7 +177,7 @@ export async function computeRootFromSiblingPath(
172
177
  leaf: Buffer,
173
178
  siblingPath: Buffer[],
174
179
  index: number,
175
- hasher = async (left: Buffer, right: Buffer) => (await poseidon2Hash([left, right])).toBuffer(),
180
+ hasher: (left: Buffer, right: Buffer) => Promise<Buffer>,
176
181
  ) {
177
182
  let result = leaf;
178
183
  for (const sibling of siblingPath) {
@@ -1,12 +1,9 @@
1
1
  import { computeBalancedMerkleTreeRoot, computeBalancedMerkleTreeRootAsync } from './balanced_merkle_tree_root.js';
2
- import { poseidonMerkleHash, shaMerkleHash } from './hasher.js';
2
+ import { shaMerkleHash } from './hasher.js';
3
3
  import { UnbalancedMerkleTreeCalculator } from './unbalanced_merkle_tree_calculator.js';
4
4
 
5
5
  export const computeUnbalancedShaRoot = (leaves: Buffer[]) => computeUnbalancedMerkleTreeRoot(leaves, shaMerkleHash);
6
6
 
7
- export const computeUnbalancedPoseidonRoot = async (leaves: Buffer[]) =>
8
- await computeUnbalancedMerkleTreeRootAsync(leaves, poseidonMerkleHash);
9
-
10
7
  export const computeWonkyShaRoot = (leaves: Buffer[]) => computeWonkyMerkleTreeRoot(leaves);
11
8
 
12
9
  /**
@@ -67,7 +64,7 @@ export function computeUnbalancedMerkleTreeRoot(
67
64
 
68
65
  export async function computeUnbalancedMerkleTreeRootAsync(
69
66
  leaves: Buffer[],
70
- hasher = poseidonMerkleHash,
67
+ hasher: (left: Uint8Array, right: Uint8Array) => Promise<Buffer<ArrayBuffer>>,
71
68
  emptyRoot = Buffer.alloc(32),
72
69
  ): Promise<Buffer> {
73
70
  if (!leaves.length) {
@@ -29,11 +29,58 @@ export function isErrorClass<T extends Error>(value: unknown, errorClass: new (.
29
29
  return value instanceof errorClass || (value instanceof Error && value.name === errorClass.name);
30
30
  }
31
31
 
32
+ const MAX_ERR_DEPTH = 10;
33
+
34
+ /** Returns the first error in the cause chain matching the given error class. */
35
+ export function getErrorCause<T extends Error>(err: unknown, errorClass: new (...args: any[]) => T): T | undefined {
36
+ let current = err;
37
+ for (let i = 0; current !== undefined && current !== null && i < MAX_ERR_DEPTH; i++) {
38
+ if (isErrorClass(current, errorClass)) {
39
+ return current;
40
+ }
41
+
42
+ if (typeof current === 'object' && Object.hasOwn(current, 'cause')) {
43
+ current = (current as { cause: unknown }).cause;
44
+ } else {
45
+ return undefined;
46
+ }
47
+ }
48
+ return undefined;
49
+ }
50
+
32
51
  /** Resolves a record-like type. Lifted from viem. */
33
52
  export type Prettify<T> = {
34
53
  [K in keyof T]: T[K];
35
54
  } & {};
36
55
 
56
+ /** Returns a type T based on a flag: T if true, undefined if false, optional otherwise. */
57
+ export type DefineIfFlag<Opts, Key extends keyof Opts, T> = Opts extends {
58
+ [K in Key]: true;
59
+ }
60
+ ? T
61
+ : Opts extends { [K in Key]: false }
62
+ ? never
63
+ : Opts extends { [K in Key]?: boolean }
64
+ ? T | undefined
65
+ : never;
66
+
67
+ /** Returns a type with fields conditionally required based on a flag */
68
+ export type PickIfFlag<
69
+ OptsSchema,
70
+ Opts extends OptsSchema,
71
+ Key extends keyof OptsSchema,
72
+ Field extends object,
73
+ > = Opts extends { [K in Key]: true }
74
+ ? Field
75
+ : Opts extends { [K in Key]: false }
76
+ ? {}
77
+ : Opts extends { [K in Key]?: boolean }
78
+ ? Partial<Field>
79
+ : {};
80
+
81
+ /** Picks only the defined (non-undefined) properties of a type. */
82
+ export type PickDefined<T> = Prettify<Pick<T, { [K in keyof T]: T[K] extends undefined ? never : K }[keyof T]>>;
83
+
37
84
  /**
38
85
  * Type-safe Event Emitter type
39
86
  * @example
@@ -1,51 +0,0 @@
1
- import { Buffer } from 'buffer';
2
- /**
3
- * For serializing an array of fixed length buffers.
4
- * TODO move to foundation pkg.
5
- * @param arr - Array of bufffers.
6
- * @returns The serialized buffers.
7
- */
8
- export declare function serializeBufferArrayToVector(arr: Buffer[]): Buffer<ArrayBuffer>;
9
- /**
10
- * Helper function for deserializeArrayFromVector.
11
- */
12
- type DeserializeFn<T> = (buf: Buffer, offset: number) => {
13
- /**
14
- * The deserialized type.
15
- */
16
- elem: T;
17
- /**
18
- * How many bytes to advance by.
19
- */
20
- adv: number;
21
- };
22
- /**
23
- * For deserializing numbers to 32-bit little-endian form.
24
- * TODO move to foundation pkg.
25
- * @param n - The number.
26
- * @returns The endian-corrected number.
27
- */
28
- export declare function deserializeArrayFromVector<T>(deserialize: DeserializeFn<T>, vector: Buffer, offset?: number): {
29
- elem: T[];
30
- adv: number;
31
- };
32
- /**
33
- * For serializing numbers to 32 bit little-endian form.
34
- * TODO move to foundation pkg.
35
- * @param n - The number.
36
- * @returns The endian-corrected number.
37
- */
38
- export declare function numToUInt32LE(n: number, bufferSize?: number): Buffer<ArrayBuffer>;
39
- /**
40
- * Deserialize the 256-bit number at address `offset`.
41
- * @param buf - The buffer.
42
- * @param offset - The address.
43
- * @returns The derserialized 256-bit field.
44
- */
45
- export declare function deserializeField(buf: Buffer, offset?: number): {
46
- elem: Buffer<ArrayBuffer>;
47
- adv: number;
48
- };
49
- export declare function concatenateUint8Arrays(arrayOfUint8Arrays: Uint8Array[]): Uint8Array<ArrayBuffer>;
50
- export {};
51
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2VyaWFsaXplLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvY3J5cHRvL3NlcmlhbGl6ZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFFQSxPQUFPLEVBQUUsTUFBTSxFQUFFLE1BQU0sUUFBUSxDQUFDO0FBRWhDOzs7OztHQUtHO0FBQ0gsd0JBQWdCLDRCQUE0QixDQUFDLEdBQUcsRUFBRSxNQUFNLEVBQUUsdUJBSXpEO0FBRUQ7O0dBRUc7QUFDSCxLQUFLLGFBQWEsQ0FBQyxDQUFDLElBQUksQ0FDdEIsR0FBRyxFQUFFLE1BQU0sRUFDWCxNQUFNLEVBQUUsTUFBTSxLQUNYO0lBQ0g7O09BRUc7SUFDSCxJQUFJLEVBQUUsQ0FBQyxDQUFDO0lBQ1I7O09BRUc7SUFDSCxHQUFHLEVBQUUsTUFBTSxDQUFDO0NBQ2IsQ0FBQztBQUVGOzs7OztHQUtHO0FBQ0gsd0JBQWdCLDBCQUEwQixDQUFDLENBQUMsRUFBRSxXQUFXLEVBQUUsYUFBYSxDQUFDLENBQUMsQ0FBQyxFQUFFLE1BQU0sRUFBRSxNQUFNLEVBQUUsTUFBTSxTQUFJOzs7RUFXdEc7QUFFRDs7Ozs7R0FLRztBQUNILHdCQUFnQixhQUFhLENBQUMsQ0FBQyxFQUFFLE1BQU0sRUFBRSxVQUFVLFNBQUksdUJBSXREO0FBRUQ7Ozs7O0dBS0c7QUFDSCx3QkFBZ0IsZ0JBQWdCLENBQUMsR0FBRyxFQUFFLE1BQU0sRUFBRSxNQUFNLFNBQUk7OztFQUd2RDtBQUVELHdCQUFnQixzQkFBc0IsQ0FBQyxrQkFBa0IsRUFBRSxVQUFVLEVBQUUsMkJBU3RFIn0=
@@ -1 +0,0 @@
1
- {"version":3,"file":"serialize.d.ts","sourceRoot":"","sources":["../../src/crypto/serialize.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAAC,GAAG,EAAE,MAAM,EAAE,uBAIzD;AAED;;GAEG;AACH,KAAK,aAAa,CAAC,CAAC,IAAI,CACtB,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,KACX;IACH;;OAEG;IACH,IAAI,EAAE,CAAC,CAAC;IACR;;OAEG;IACH,GAAG,EAAE,MAAM,CAAC;CACb,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,CAAC,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,SAAI;;;EAWtG;AAED;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,UAAU,SAAI,uBAItD;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,SAAI;;;EAGvD;AAED,wBAAgB,sBAAsB,CAAC,kBAAkB,EAAE,UAAU,EAAE,2BAStE"}
@@ -1,68 +0,0 @@
1
- // TODO find a new home for this as we move to external bb.js
2
- // See https://github.com/AztecProtocol/aztec-packages/issues/782
3
- import { Buffer } from 'buffer';
4
- /**
5
- * For serializing an array of fixed length buffers.
6
- * TODO move to foundation pkg.
7
- * @param arr - Array of bufffers.
8
- * @returns The serialized buffers.
9
- */ export function serializeBufferArrayToVector(arr) {
10
- const lengthBuf = Buffer.alloc(4);
11
- lengthBuf.writeUInt32BE(arr.length, 0);
12
- return Buffer.concat([
13
- lengthBuf,
14
- ...arr
15
- ]);
16
- }
17
- /**
18
- * For deserializing numbers to 32-bit little-endian form.
19
- * TODO move to foundation pkg.
20
- * @param n - The number.
21
- * @returns The endian-corrected number.
22
- */ export function deserializeArrayFromVector(deserialize, vector, offset = 0) {
23
- let pos = offset;
24
- const size = vector.readUInt32BE(pos);
25
- pos += 4;
26
- const arr = new Array(size);
27
- for(let i = 0; i < size; ++i){
28
- const { elem, adv } = deserialize(vector, pos);
29
- pos += adv;
30
- arr[i] = elem;
31
- }
32
- return {
33
- elem: arr,
34
- adv: pos - offset
35
- };
36
- }
37
- /**
38
- * For serializing numbers to 32 bit little-endian form.
39
- * TODO move to foundation pkg.
40
- * @param n - The number.
41
- * @returns The endian-corrected number.
42
- */ export function numToUInt32LE(n, bufferSize = 4) {
43
- const buf = Buffer.alloc(bufferSize);
44
- buf.writeUInt32LE(n, bufferSize - 4);
45
- return buf;
46
- }
47
- /**
48
- * Deserialize the 256-bit number at address `offset`.
49
- * @param buf - The buffer.
50
- * @param offset - The address.
51
- * @returns The derserialized 256-bit field.
52
- */ export function deserializeField(buf, offset = 0) {
53
- const adv = 32;
54
- return {
55
- elem: buf.slice(offset, offset + adv),
56
- adv
57
- };
58
- }
59
- export function concatenateUint8Arrays(arrayOfUint8Arrays) {
60
- const totalLength = arrayOfUint8Arrays.reduce((prev, curr)=>prev + curr.length, 0);
61
- const result = new Uint8Array(totalLength);
62
- let length = 0;
63
- for (const array of arrayOfUint8Arrays){
64
- result.set(array, length);
65
- length += array.length;
66
- }
67
- return result;
68
- }
@@ -1,25 +0,0 @@
1
- /**
2
- * Represents a message object for dispatching function calls.
3
- * Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
4
- */
5
- export interface DispatchMsg {
6
- /**
7
- * Name of the target method to be called.
8
- */
9
- fn: string;
10
- /**
11
- * An array of arguments to be passed to the target method.
12
- */
13
- args: any[];
14
- }
15
- /**
16
- * Creates a dispatch function that calls the target's specified method with provided arguments.
17
- * The created dispatch function takes a DispatchMsg object as input, which contains the name of
18
- * the method to be called ('fn') and an array of arguments to be passed to the method ('args').
19
- *
20
- * @param targetFn - A function that returns the target object containing the methods to be dispatched.
21
- * @param log - Optional logging function for debugging purposes.
22
- * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
23
- */
24
- export declare function createDispatchFn(targetFn: () => any, log?: import("../../log/pino-logger.js").Logger): ({ fn, args }: DispatchMsg) => Promise<any>;
25
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY3JlYXRlX2Rpc3BhdGNoX2ZuLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvdHJhbnNwb3J0L2Rpc3BhdGNoL2NyZWF0ZV9kaXNwYXRjaF9mbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFJQTs7O0dBR0c7QUFDSCxNQUFNLFdBQVcsV0FBVztJQUMxQjs7T0FFRztJQUNILEVBQUUsRUFBRSxNQUFNLENBQUM7SUFDWDs7T0FFRztJQUNILElBQUksRUFBRSxHQUFHLEVBQUUsQ0FBQztDQUNiO0FBRUQ7Ozs7Ozs7O0dBUUc7QUFDSCx3QkFBZ0IsZ0JBQWdCLENBQUMsUUFBUSxFQUFFLE1BQU0sR0FBRyxFQUFFLEdBQUcsNENBQXNDLCtDQU05RiJ9
@@ -1 +0,0 @@
1
- {"version":3,"file":"create_dispatch_fn.d.ts","sourceRoot":"","sources":["../../../src/transport/dispatch/create_dispatch_fn.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,WAAW,WAAW;IAC1B;;OAEG;IACH,EAAE,EAAE,MAAM,CAAC;IACX;;OAEG;IACH,IAAI,EAAE,GAAG,EAAE,CAAC;CACb;AAED;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,EAAE,GAAG,4CAAsC,+CAM9F"}
@@ -1,17 +0,0 @@
1
- import { format } from 'util';
2
- import { createLogger } from '../../log/index.js';
3
- /**
4
- * Creates a dispatch function that calls the target's specified method with provided arguments.
5
- * The created dispatch function takes a DispatchMsg object as input, which contains the name of
6
- * the method to be called ('fn') and an array of arguments to be passed to the method ('args').
7
- *
8
- * @param targetFn - A function that returns the target object containing the methods to be dispatched.
9
- * @param log - Optional logging function for debugging purposes.
10
- * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
11
- */ export function createDispatchFn(targetFn, log = createLogger('foundation:dispatch')) {
12
- return async ({ fn, args })=>{
13
- const target = targetFn();
14
- log.debug(format(`dispatching to ${target}: ${fn}`, args));
15
- return await target[fn](...args);
16
- };
17
- }
@@ -1,85 +0,0 @@
1
- // TODO find a new home for this as we move to external bb.js
2
- // See https://github.com/AztecProtocol/aztec-packages/issues/782
3
- import { Buffer } from 'buffer';
4
-
5
- /**
6
- * For serializing an array of fixed length buffers.
7
- * TODO move to foundation pkg.
8
- * @param arr - Array of bufffers.
9
- * @returns The serialized buffers.
10
- */
11
- export function serializeBufferArrayToVector(arr: Buffer[]) {
12
- const lengthBuf = Buffer.alloc(4);
13
- lengthBuf.writeUInt32BE(arr.length, 0);
14
- return Buffer.concat([lengthBuf, ...arr]);
15
- }
16
-
17
- /**
18
- * Helper function for deserializeArrayFromVector.
19
- */
20
- type DeserializeFn<T> = (
21
- buf: Buffer,
22
- offset: number,
23
- ) => {
24
- /**
25
- * The deserialized type.
26
- */
27
- elem: T;
28
- /**
29
- * How many bytes to advance by.
30
- */
31
- adv: number;
32
- };
33
-
34
- /**
35
- * For deserializing numbers to 32-bit little-endian form.
36
- * TODO move to foundation pkg.
37
- * @param n - The number.
38
- * @returns The endian-corrected number.
39
- */
40
- export function deserializeArrayFromVector<T>(deserialize: DeserializeFn<T>, vector: Buffer, offset = 0) {
41
- let pos = offset;
42
- const size = vector.readUInt32BE(pos);
43
- pos += 4;
44
- const arr = new Array<T>(size);
45
- for (let i = 0; i < size; ++i) {
46
- const { elem, adv } = deserialize(vector, pos);
47
- pos += adv;
48
- arr[i] = elem;
49
- }
50
- return { elem: arr, adv: pos - offset };
51
- }
52
-
53
- /**
54
- * For serializing numbers to 32 bit little-endian form.
55
- * TODO move to foundation pkg.
56
- * @param n - The number.
57
- * @returns The endian-corrected number.
58
- */
59
- export function numToUInt32LE(n: number, bufferSize = 4) {
60
- const buf = Buffer.alloc(bufferSize);
61
- buf.writeUInt32LE(n, bufferSize - 4);
62
- return buf;
63
- }
64
-
65
- /**
66
- * Deserialize the 256-bit number at address `offset`.
67
- * @param buf - The buffer.
68
- * @param offset - The address.
69
- * @returns The derserialized 256-bit field.
70
- */
71
- export function deserializeField(buf: Buffer, offset = 0) {
72
- const adv = 32;
73
- return { elem: buf.slice(offset, offset + adv), adv };
74
- }
75
-
76
- export function concatenateUint8Arrays(arrayOfUint8Arrays: Uint8Array[]) {
77
- const totalLength = arrayOfUint8Arrays.reduce((prev, curr) => prev + curr.length, 0);
78
- const result = new Uint8Array(totalLength);
79
- let length = 0;
80
- for (const array of arrayOfUint8Arrays) {
81
- result.set(array, length);
82
- length += array.length;
83
- }
84
- return result;
85
- }