@aztec/foundation 0.72.1 → 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 (115) 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/event_selector.d.ts +1 -1
  5. package/dest/abi/event_selector.d.ts.map +1 -1
  6. package/dest/abi/event_selector.js +3 -3
  7. package/dest/abi/function_selector.d.ts +3 -13
  8. package/dest/abi/function_selector.d.ts.map +1 -1
  9. package/dest/abi/function_selector.js +5 -16
  10. package/dest/blob/blob.d.ts +150 -0
  11. package/dest/blob/blob.d.ts.map +1 -0
  12. package/dest/blob/blob.js +249 -0
  13. package/dest/blob/encoding.d.ts +53 -0
  14. package/dest/blob/encoding.d.ts.map +1 -0
  15. package/dest/blob/encoding.js +87 -0
  16. package/dest/blob/index.d.ts +4 -58
  17. package/dest/blob/index.d.ts.map +1 -1
  18. package/dest/blob/index.js +6 -142
  19. package/dest/blob/interface.d.ts +10 -0
  20. package/dest/blob/interface.d.ts.map +1 -0
  21. package/dest/blob/interface.js +2 -0
  22. package/dest/blob/mocks.d.ts +5 -0
  23. package/dest/blob/mocks.d.ts.map +1 -0
  24. package/dest/blob/mocks.js +25 -0
  25. package/dest/config/env_var.d.ts +1 -1
  26. package/dest/config/env_var.d.ts.map +1 -1
  27. package/dest/config/index.d.ts +1 -0
  28. package/dest/config/index.d.ts.map +1 -1
  29. package/dest/config/index.js +11 -14
  30. package/dest/crypto/index.d.ts +0 -7
  31. package/dest/crypto/index.d.ts.map +1 -1
  32. package/dest/crypto/index.js +1 -11
  33. package/dest/crypto/keys/index.d.ts +1 -1
  34. package/dest/crypto/keys/index.d.ts.map +1 -1
  35. package/dest/crypto/keys/index.js +5 -5
  36. package/dest/crypto/pedersen/pedersen.wasm.d.ts +3 -3
  37. package/dest/crypto/pedersen/pedersen.wasm.d.ts.map +1 -1
  38. package/dest/crypto/pedersen/pedersen.wasm.js +13 -10
  39. package/dest/crypto/poseidon/index.d.ts +5 -5
  40. package/dest/crypto/poseidon/index.d.ts.map +1 -1
  41. package/dest/crypto/poseidon/index.js +20 -19
  42. package/dest/crypto/sync/index.d.ts +3 -0
  43. package/dest/crypto/sync/index.d.ts.map +1 -0
  44. package/dest/crypto/sync/index.js +5 -0
  45. package/dest/crypto/sync/pedersen/index.d.ts +21 -0
  46. package/dest/crypto/sync/pedersen/index.d.ts.map +1 -0
  47. package/dest/crypto/sync/pedersen/index.js +37 -0
  48. package/dest/crypto/sync/poseidon/index.d.ts +26 -0
  49. package/dest/crypto/sync/poseidon/index.d.ts.map +1 -0
  50. package/dest/crypto/sync/poseidon/index.js +57 -0
  51. package/dest/fields/fields.js +4 -4
  52. package/dest/fields/point.d.ts +1 -1
  53. package/dest/iterable/toArray.d.ts +1 -1
  54. package/dest/iterable/toArray.d.ts.map +1 -1
  55. package/dest/iterable/toArray.js +1 -1
  56. package/dest/json-rpc/client/safe_json_rpc_client.js +2 -2
  57. package/dest/json-rpc/convert.d.ts +1 -1
  58. package/dest/json-rpc/convert.d.ts.map +1 -1
  59. package/dest/json-rpc/convert.js +2 -2
  60. package/dest/json-rpc/server/safe_json_rpc_server.d.ts.map +1 -1
  61. package/dest/json-rpc/server/safe_json_rpc_server.js +4 -2
  62. package/dest/message/index.d.ts +32 -0
  63. package/dest/message/index.d.ts.map +1 -0
  64. package/dest/message/index.js +23 -0
  65. package/dest/mutex/index.d.ts.map +1 -1
  66. package/dest/mutex/index.js +6 -4
  67. package/dest/promise/running-promise.d.ts +2 -1
  68. package/dest/promise/running-promise.d.ts.map +1 -1
  69. package/dest/promise/running-promise.js +6 -3
  70. package/dest/schemas/parse.d.ts +1 -1
  71. package/dest/schemas/parse.d.ts.map +1 -1
  72. package/dest/schemas/parse.js +2 -2
  73. package/dest/serialize/field_reader.d.ts +18 -0
  74. package/dest/serialize/field_reader.d.ts.map +1 -1
  75. package/dest/serialize/field_reader.js +32 -2
  76. package/dest/worker/browser/start_web_module.d.ts.map +1 -1
  77. package/dest/worker/browser/start_web_module.js +2 -1
  78. package/dest/worker/browser/web_worker.d.ts.map +1 -1
  79. package/dest/worker/browser/web_worker.js +2 -1
  80. package/dest/worker/node/node_worker.d.ts.map +1 -1
  81. package/dest/worker/node/node_worker.js +2 -1
  82. package/dest/worker/node/start_node_module.d.ts.map +1 -1
  83. package/dest/worker/node/start_node_module.js +2 -1
  84. package/package.json +5 -3
  85. package/src/abi/abi.ts +28 -8
  86. package/src/abi/event_selector.ts +2 -2
  87. package/src/abi/function_selector.ts +7 -27
  88. package/src/blob/blob.ts +294 -0
  89. package/src/blob/encoding.ts +98 -0
  90. package/src/blob/index.ts +5 -183
  91. package/src/blob/interface.ts +11 -0
  92. package/src/blob/mocks.ts +30 -0
  93. package/src/config/env_var.ts +7 -4
  94. package/src/config/index.ts +10 -12
  95. package/src/crypto/index.ts +0 -12
  96. package/src/crypto/keys/index.ts +5 -4
  97. package/src/crypto/pedersen/pedersen.wasm.ts +13 -14
  98. package/src/crypto/poseidon/index.ts +24 -39
  99. package/src/crypto/sync/index.ts +6 -0
  100. package/src/crypto/sync/pedersen/index.ts +45 -0
  101. package/src/crypto/sync/poseidon/index.ts +76 -0
  102. package/src/fields/fields.ts +3 -3
  103. package/src/iterable/toArray.ts +3 -1
  104. package/src/json-rpc/client/safe_json_rpc_client.ts +1 -1
  105. package/src/json-rpc/convert.ts +2 -2
  106. package/src/json-rpc/server/safe_json_rpc_server.ts +3 -1
  107. package/src/message/index.ts +43 -0
  108. package/src/mutex/index.ts +5 -4
  109. package/src/promise/running-promise.ts +4 -1
  110. package/src/schemas/parse.ts +2 -2
  111. package/src/serialize/field_reader.ts +34 -1
  112. package/src/worker/browser/start_web_module.ts +1 -0
  113. package/src/worker/browser/web_worker.ts +1 -0
  114. package/src/worker/node/node_worker.ts +1 -0
  115. package/src/worker/node/start_node_module.ts +1 -0
@@ -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
+ }
@@ -1,4 +1,4 @@
1
- import { BarretenbergLazy } from '@aztec/bb.js';
1
+ import { BarretenbergSync } from '@aztec/bb.js';
2
2
 
3
3
  import { inspect } from 'util';
4
4
 
@@ -319,8 +319,8 @@ export class Fr extends BaseField {
319
319
  * @returns A square root of the field element (null if it does not exist).
320
320
  */
321
321
  async sqrt(): Promise<Fr | null> {
322
- const wasm = (await BarretenbergLazy.getSingleton()).getWasm();
323
- const [buf] = await wasm.callWasmExport('bn254_fr_sqrt', [this.toBuffer()], [Fr.SIZE_IN_BYTES + 1]);
322
+ const wasm = (await BarretenbergSync.initSingleton()).getWasm();
323
+ const [buf] = wasm.callWasmExport('bn254_fr_sqrt', [this.toBuffer()], [Fr.SIZE_IN_BYTES + 1]);
324
324
  const isSqrt = buf[0] === 1;
325
325
  if (!isSqrt) {
326
326
  // Field element is not a quadratic residue mod p so it has no square root.
@@ -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);
@@ -40,7 +40,7 @@ export function createSafeJsonRpcClient<T extends object>(
40
40
  if ([null, undefined, 'null', 'undefined'].includes(res.result)) {
41
41
  return;
42
42
  }
43
- return (schema as ApiSchema)[methodName].returnType().parse(res.result);
43
+ return (schema as ApiSchema)[methodName].returnType().parseAsync(res.result);
44
44
  };
45
45
 
46
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
  /**
@@ -151,6 +151,7 @@ export class SafeJsonRpcServer {
151
151
  throw new Error('Server is already listening');
152
152
  }
153
153
 
154
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
154
155
  this.httpServer = http.createServer(this.getApp(prefix).callback());
155
156
  this.httpServer.listen(port);
156
157
  }
@@ -217,7 +218,7 @@ export class SafeJsonProxy<T extends object = any> implements Proxy {
217
218
  assert(schemaHasMethod(this.schema, methodName), `Method ${methodName} not found in schema`);
218
219
  const method = this.handler[methodName as keyof T];
219
220
  assert(typeof method === 'function', `Method ${methodName} is not a function`);
220
- const args = parseWithOptionals(jsonParams, this.schema[methodName].parameters());
221
+ const args = await parseWithOptionals(jsonParams, this.schema[methodName].parameters());
221
222
  const ret = await method.apply(this.handler, args);
222
223
  this.log.debug(format('response', methodName, ret));
223
224
  return ret;
@@ -355,6 +356,7 @@ export async function startHttpRpcServer(
355
356
  const statusRouter = createStatusRouter(rpcServer.isHealthy.bind(rpcServer), options.apiPrefix);
356
357
  app.use(statusRouter.routes()).use(statusRouter.allowedMethods());
357
358
 
359
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
358
360
  const httpServer = http.createServer(app.callback());
359
361
  if (options.timeoutMs) {
360
362
  httpServer.timeout = options.timeoutMs;
@@ -0,0 +1,43 @@
1
+ export type MessageHeaderInit = {
2
+ /** The message ID. Optional, if not set defaults to 0 */
3
+ messageId?: number;
4
+ /** Identifies the original request. Optional */
5
+ requestId?: number;
6
+ };
7
+
8
+ export class MessageHeader {
9
+ /** An number to identify this message */
10
+ public readonly messageId: number;
11
+ /** If this message is a response to a request, the messageId of the request */
12
+ public readonly requestId: number;
13
+
14
+ constructor({ messageId, requestId }: MessageHeaderInit) {
15
+ this.messageId = messageId ?? 0;
16
+ this.requestId = requestId ?? 0;
17
+ }
18
+
19
+ static fromMessagePack(data: object): MessageHeader {
20
+ return new MessageHeader(data as MessageHeaderInit);
21
+ }
22
+ }
23
+
24
+ interface TypedMessageLike {
25
+ msgType: number;
26
+ header: {
27
+ messageId?: number;
28
+ requestId?: number;
29
+ };
30
+ value: any;
31
+ }
32
+
33
+ export class TypedMessage<T, B> {
34
+ public constructor(public readonly msgType: T, public readonly header: MessageHeader, public readonly value: B) {}
35
+
36
+ static fromMessagePack<T, B>(data: TypedMessageLike): TypedMessage<T, B> {
37
+ return new TypedMessage<T, B>(data['msgType'] as T, MessageHeader.fromMessagePack(data['header']), data['value']);
38
+ }
39
+
40
+ static isTypedMessageLike(obj: any): obj is TypedMessageLike {
41
+ return typeof obj === 'object' && obj !== null && 'msgType' in obj && 'header' in obj && 'value' in obj;
42
+ }
43
+ }
@@ -72,12 +72,13 @@ export class Mutex {
72
72
  *
73
73
  * @param id - The id of the current lock instance.
74
74
  */
75
- private async ping(id: number) {
75
+ private ping(id: number) {
76
76
  if (id !== this.id) {
77
77
  return;
78
78
  }
79
-
80
- await this.db.extendLock(this.name, this.timeout);
81
- this.pingTimeout = setTimeout(() => this.ping(id), this.pingInterval);
79
+ void (async () => {
80
+ await this.db.extendLock(this.name, this.timeout);
81
+ this.pingTimeout = setTimeout(() => this.ping(id), this.pingInterval);
82
+ })();
82
83
  }
83
84
  }
@@ -17,6 +17,7 @@ export class RunningPromise {
17
17
  private fn: () => void | Promise<void>,
18
18
  private logger = createLogger('running-promise'),
19
19
  private pollingIntervalMS = 10000,
20
+ private ignoredErrors: (new (...args: any[]) => Error)[] = [],
20
21
  ) {}
21
22
 
22
23
  /**
@@ -35,7 +36,9 @@ export class RunningPromise {
35
36
  try {
36
37
  await this.fn();
37
38
  } catch (err) {
38
- this.logger.error('Error in running promise', err);
39
+ if (err instanceof Error && !this.ignoredErrors.some(ErrorType => err instanceof ErrorType)) {
40
+ this.logger.error('Error in running promise', err);
41
+ }
39
42
  }
40
43
 
41
44
  // If an immediate run had been requested *before* the function started running, resolve the request.
@@ -11,12 +11,12 @@ export function parse<T extends [] | [z.ZodTypeAny, ...z.ZodTypeAny[]]>(args: IA
11
11
  * Parses the given arguments against a tuple, allowing empty for optional items.
12
12
  * @dev Zod doesn't like tuplues with optional items. See https://github.com/colinhacks/zod/discussions/949.
13
13
  */
14
- export function parseWithOptionals<T extends z.AnyZodTuple>(args: any[], schema: T): T['_output'] {
14
+ export function parseWithOptionals<T extends z.AnyZodTuple>(args: any[], schema: T): Promise<T['_output']> {
15
15
  const missingCount = schema.items.length - args.length;
16
16
  const optionalCount = schema.items.filter(isOptional).length;
17
17
  const toParse =
18
18
  missingCount > 0 && missingCount <= optionalCount ? args.concat(times(missingCount, () => undefined)) : args;
19
- return schema.parse(toParse);
19
+ return schema.parseAsync(toParse);
20
20
  }
21
21
 
22
22
  function isOptional(schema: z.ZodTypeAny) {
@@ -34,6 +34,27 @@ export class FieldReader {
34
34
  return new FieldReader(fields);
35
35
  }
36
36
 
37
+ /**
38
+ * Skips the next n fields.
39
+ *
40
+ * @param n - The number of fields to skip.
41
+ */
42
+ public skip(n: number) {
43
+ if (this.index + n > this.length) {
44
+ throw new Error('Not enough fields to be consumed.');
45
+ }
46
+ this.index += n;
47
+ }
48
+
49
+ /**
50
+ * Returns the current cursor position.
51
+ *
52
+ * @returns The current cursor position.
53
+ */
54
+ public get cursor() {
55
+ return this.index;
56
+ }
57
+
37
58
  /**
38
59
  * Reads a single field from the array.
39
60
  *
@@ -46,6 +67,18 @@ export class FieldReader {
46
67
  return this.fields[this.index++];
47
68
  }
48
69
 
70
+ /**
71
+ * Peeks at the next field without advancing the cursor.
72
+ *
73
+ * @returns A field.
74
+ */
75
+ public peekField(): Fr {
76
+ if (this.index === this.length) {
77
+ throw new Error('Not enough fields to be consumed.');
78
+ }
79
+ return this.fields[this.index];
80
+ }
81
+
49
82
  /**
50
83
  * Reads a Fq from the array.
51
84
  *
@@ -146,6 +179,6 @@ export class FieldReader {
146
179
  * @returns A bool.
147
180
  */
148
181
  public isFinished(): boolean {
149
- return this.index === this.length;
182
+ return this.index >= this.length;
150
183
  }
151
184
  }
@@ -18,6 +18,7 @@ export function startWebModule(module: WasmModule) {
18
18
  };
19
19
  const transportListener = new WorkerListener(self);
20
20
  const transportServer = new TransportServer<DispatchMsg>(transportListener, dispatch);
21
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
21
22
  module.addLogger((...args: any[]) => transportServer.broadcast({ fn: 'emit', args: ['log', ...args] }));
22
23
  transportServer.start();
23
24
  }
@@ -15,6 +15,7 @@ export async function createWebWorker(url: string, initialMem?: number, maxMem?:
15
15
  const transportClient = new TransportClient<DispatchMsg>(transportConnect);
16
16
  await transportClient.open();
17
17
  const remoteModule = createDispatchProxy(WasmModule, transportClient) as WasmWorker;
18
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
18
19
  remoteModule.destroyWorker = async () => {
19
20
  await transportClient.request({ fn: '__destroyWorker__', args: [] });
20
21
  transportClient.close();
@@ -13,6 +13,7 @@ export async function createNodeWorker(filepath: string, initialMem?: number, ma
13
13
  const transportClient = new TransportClient<DispatchMsg>(transportConnect);
14
14
  await transportClient.open();
15
15
  const remoteModule = createDispatchProxy(WasmModule, transportClient) as WasmWorker;
16
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
16
17
  remoteModule.destroyWorker = async () => {
17
18
  await transportClient.request({ fn: '__destroyWorker__', args: [] });
18
19
  transportClient.close();
@@ -24,6 +24,7 @@ export function startNodeModule(module: WasmModule) {
24
24
  };
25
25
  const transportListener = new NodeListener();
26
26
  const transportServer = new TransportServer<DispatchMsg>(transportListener, dispatch);
27
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
27
28
  module.addLogger((...args: any[]) => transportServer.broadcast({ fn: 'emit', args: ['log', ...args] }));
28
29
  transportServer.start();
29
30
  }