@aztec/foundation 0.0.1-commit.2d9cb6034 → 0.0.1-commit.2e20a94

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 (82) hide show
  1. package/dest/branded-types/buffer32_hash.d.ts +24 -0
  2. package/dest/branded-types/buffer32_hash.d.ts.map +1 -0
  3. package/dest/branded-types/buffer32_hash.js +19 -0
  4. package/dest/branded-types/checkpoint_number.d.ts +4 -1
  5. package/dest/branded-types/checkpoint_number.d.ts.map +1 -1
  6. package/dest/branded-types/checkpoint_number.js +3 -0
  7. package/dest/branded-types/index.d.ts +2 -1
  8. package/dest/branded-types/index.d.ts.map +1 -1
  9. package/dest/branded-types/index.js +1 -0
  10. package/dest/buffer/buffer16.d.ts +3 -3
  11. package/dest/buffer/buffer16.d.ts.map +1 -1
  12. package/dest/buffer/buffer32.d.ts +28 -63
  13. package/dest/buffer/buffer32.d.ts.map +1 -1
  14. package/dest/buffer/buffer32.js +26 -60
  15. package/dest/config/env_var.d.ts +2 -2
  16. package/dest/config/env_var.d.ts.map +1 -1
  17. package/dest/config/index.d.ts +48 -30
  18. package/dest/config/index.d.ts.map +1 -1
  19. package/dest/config/index.js +21 -30
  20. package/dest/crypto/aes128/index.d.ts +2 -1
  21. package/dest/crypto/aes128/index.d.ts.map +1 -1
  22. package/dest/crypto/aes128/index.js +11 -2
  23. package/dest/crypto/bls/bn254_keystore.d.ts +1 -10
  24. package/dest/crypto/bls/bn254_keystore.d.ts.map +1 -1
  25. package/dest/crypto/bls/bn254_keystore.js +0 -17
  26. package/dest/curves/bls12/field.d.ts +1 -1
  27. package/dest/curves/bls12/field.d.ts.map +1 -1
  28. package/dest/curves/bls12/field.js +0 -5
  29. package/dest/curves/bn254/field.d.ts +17 -16
  30. package/dest/curves/bn254/field.d.ts.map +1 -1
  31. package/dest/curves/bn254/field.js +18 -13
  32. package/dest/curves/grumpkin/point.d.ts +3 -3
  33. package/dest/curves/grumpkin/point.d.ts.map +1 -1
  34. package/dest/curves/grumpkin/point.js +6 -3
  35. package/dest/eth-address/index.d.ts +1 -1
  36. package/dest/eth-address/index.d.ts.map +1 -1
  37. package/dest/eth-address/index.js +0 -3
  38. package/dest/json-rpc/client/fetch.d.ts +1 -1
  39. package/dest/json-rpc/client/fetch.d.ts.map +1 -1
  40. package/dest/json-rpc/client/fetch.js +4 -3
  41. package/dest/json-rpc/client/undici.d.ts +1 -1
  42. package/dest/json-rpc/client/undici.d.ts.map +1 -1
  43. package/dest/json-rpc/client/undici.js +5 -3
  44. package/dest/log/pino-logger.js +15 -1
  45. package/dest/queue/batch_queue.d.ts +1 -1
  46. package/dest/queue/batch_queue.d.ts.map +1 -1
  47. package/dest/queue/batch_queue.js +1 -0
  48. package/dest/retry/index.d.ts +12 -1
  49. package/dest/retry/index.d.ts.map +1 -1
  50. package/dest/retry/index.js +21 -0
  51. package/dest/string/index.js +1 -1
  52. package/dest/transport/dispatch/create_dispatch_proxy.d.ts +11 -2
  53. package/dest/transport/dispatch/create_dispatch_proxy.d.ts.map +1 -1
  54. package/dest/transport/index.d.ts +1 -2
  55. package/dest/transport/index.d.ts.map +1 -1
  56. package/dest/transport/index.js +0 -1
  57. package/package.json +2 -2
  58. package/src/branded-types/buffer32_hash.ts +42 -0
  59. package/src/branded-types/checkpoint_number.ts +5 -0
  60. package/src/branded-types/index.ts +1 -0
  61. package/src/buffer/buffer16.ts +2 -2
  62. package/src/buffer/buffer32.ts +36 -68
  63. package/src/config/env_var.ts +3 -5
  64. package/src/config/index.ts +96 -84
  65. package/src/crypto/aes128/index.ts +11 -2
  66. package/src/crypto/bls/bn254_keystore.ts +0 -23
  67. package/src/curves/bls12/field.ts +0 -7
  68. package/src/curves/bn254/field.ts +25 -31
  69. package/src/curves/grumpkin/point.ts +5 -2
  70. package/src/eth-address/index.ts +0 -4
  71. package/src/json-rpc/client/fetch.ts +4 -3
  72. package/src/json-rpc/client/undici.ts +5 -3
  73. package/src/log/pino-logger.ts +16 -1
  74. package/src/queue/batch_queue.ts +1 -0
  75. package/src/retry/index.ts +30 -0
  76. package/src/string/index.ts +1 -1
  77. package/src/transport/dispatch/create_dispatch_proxy.ts +11 -1
  78. package/src/transport/index.ts +0 -1
  79. package/dest/transport/dispatch/create_dispatch_fn.d.ts +0 -25
  80. package/dest/transport/dispatch/create_dispatch_fn.d.ts.map +0 -1
  81. package/dest/transport/dispatch/create_dispatch_fn.js +0 -17
  82. package/src/transport/dispatch/create_dispatch_fn.ts +0 -35
@@ -6,9 +6,6 @@ import { toBigIntBE, toBufferBE } from '../../bigint-buffer/index.js';
6
6
  import { randomBytes } from '../../crypto/random/index.js';
7
7
  import { hexSchemaFor } from '../../schemas/utils.js';
8
8
  import { BufferReader } from '../../serialize/buffer_reader.js';
9
- import { TypeRegistry } from '../../serialize/type_registry.js';
10
-
11
- /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */
12
9
 
13
10
  /**
14
11
  * Represents a field derived from BaseField.
@@ -187,10 +184,25 @@ function fromHexString<T extends BaseField>(buf: string, f: DerivedField<T>) {
187
184
  return new f(toBigIntBE(buffer));
188
185
  }
189
186
 
190
- /** Branding to ensure fields are not interchangeable types. */
191
- export interface Fr {
192
- /** Brand. */
193
- _branding: 'Fr';
187
+ /**
188
+ * Abstract unbranded base class for BN254 scalar field elements.
189
+ * Extend this instead of Fr when defining a branded subtype (e.g. BlockHash)
190
+ * to avoid inheriting Fr's `_branding`.
191
+ */
192
+ export abstract class BaseFr extends BaseField {
193
+ static MODULUS = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001n;
194
+
195
+ constructor(value: number | bigint | boolean | BaseField | Buffer) {
196
+ super(value);
197
+ }
198
+
199
+ protected modulus() {
200
+ return BaseFr.MODULUS;
201
+ }
202
+
203
+ toJSON() {
204
+ return this.toString();
205
+ }
194
206
  }
195
207
 
196
208
  /**
@@ -198,10 +210,12 @@ export interface Fr {
198
210
  * @dev This class is used to represent elements of BN254 scalar field or elements in the base field of Grumpkin.
199
211
  * (Grumpkin's scalar field corresponds to BN254's base field and vice versa.)
200
212
  */
201
- export class Fr extends BaseField {
213
+ export class Fr extends BaseFr {
214
+ /** Branding for nominal typing. */
215
+ declare private readonly _branding: 'Fr';
216
+ static override MODULUS = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001n;
202
217
  static ZERO = new Fr(0n);
203
218
  static ONE = new Fr(1n);
204
- static MODULUS = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001n;
205
219
  static MAX_FIELD_VALUE = new Fr(this.MODULUS - 1n);
206
220
 
207
221
  constructor(value: number | bigint | boolean | Fr | Buffer) {
@@ -212,10 +226,6 @@ export class Fr extends BaseField {
212
226
  return `Fr<${this.toString()}>`;
213
227
  }
214
228
 
215
- protected modulus() {
216
- return Fr.MODULUS;
217
- }
218
-
219
229
  static random() {
220
230
  return random(Fr);
221
231
  }
@@ -320,10 +330,6 @@ export class Fr extends BaseField {
320
330
  return Fr.fromBuffer(Buffer.from(response.value));
321
331
  }
322
332
 
323
- toJSON() {
324
- return this.toString();
325
- }
326
-
327
333
  /**
328
334
  * Creates an Fr instance from a plain object without Zod validation.
329
335
  * This method is optimized for performance and skips validation, making it suitable
@@ -345,23 +351,14 @@ export class Fr extends BaseField {
345
351
  }
346
352
  }
347
353
 
348
- // For deserializing JSON.
349
- TypeRegistry.register('Fr', Fr);
350
-
351
- /**
352
- * Branding to ensure fields are not interchangeable types.
353
- */
354
- export interface Fq {
355
- /** Brand. */
356
- _branding: 'Fq';
357
- }
358
-
359
354
  /**
360
355
  * Fq field class.
361
356
  * @dev This class is used to represent elements of BN254 base field or elements in the scalar field of Grumpkin.
362
357
  * (Grumpkin's scalar field corresponds to BN254's base field and vice versa.)
363
358
  */
364
359
  export class Fq extends BaseField {
360
+ /** Branding for nominal typing. */
361
+ declare private readonly _branding: 'Fq';
365
362
  static ZERO = new Fq(0n);
366
363
  static MODULUS = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47n;
367
364
  private static HIGH_SHIFT = BigInt((BaseField.SIZE_IN_BYTES / 2) * 8);
@@ -470,9 +467,6 @@ export class Fq extends BaseField {
470
467
  }
471
468
  }
472
469
 
473
- // For deserializing JSON.
474
- TypeRegistry.register('Fq', Fq);
475
-
476
470
  // Beware: Performance bottleneck below
477
471
 
478
472
  /**
@@ -125,9 +125,12 @@ export class Point {
125
125
  }
126
126
 
127
127
  /**
128
- * Returns the contents of the point as an array of 2 fields.
129
- * @returns The point as an array of 2 fields
128
+ * Returns the contents of the point as an array of 3 fields.
129
+ * @returns The point as an array of 3 fields
130
130
  */
131
+ // TODO(F-553): Once we take the breaking change and drop the custom Noir `Point` wrapper in
132
+ // `noir-projects/noir-protocol-circuits/crates/types/src/point.nr`, revert this to serialize as `[x, y]` (2 fields)
133
+ // and drop the `is_infinite` flag from `fromFields` / `toNoirStruct` below.
131
134
  toFields() {
132
135
  return [this.x, this.y, new Fr(this.isInfinite)];
133
136
  }
@@ -5,7 +5,6 @@ import { randomBytes } from '../crypto/random/index.js';
5
5
  import { Fr } from '../curves/bn254/index.js';
6
6
  import { hexSchemaFor } from '../schemas/utils.js';
7
7
  import { BufferReader, FieldReader } from '../serialize/index.js';
8
- import { TypeRegistry } from '../serialize/type_registry.js';
9
8
  import { bufferToHex } from '../string/index.js';
10
9
 
11
10
  /**
@@ -268,6 +267,3 @@ export class EthAddress {
268
267
  return addrA.equals(addrB);
269
268
  }
270
269
  }
271
-
272
- // For deserializing JSON.
273
- TypeRegistry.register('EthAddress', EthAddress);
@@ -43,17 +43,18 @@ export async function defaultFetch(
43
43
  }
44
44
 
45
45
  let responseJson;
46
+ const responseText = await resp.text();
46
47
  try {
47
- responseJson = await resp.json();
48
+ responseJson = JSON.parse(responseText);
48
49
  } catch {
49
50
  if (!resp.ok) {
50
51
  throw new Error(resp.statusText);
51
52
  }
52
- throw new Error(`Failed to parse body as JSON: ${await resp.text()}`);
53
+ throw new Error(`Failed to parse body as JSON: ${responseText}`);
53
54
  }
54
55
 
55
56
  if (!resp.ok) {
56
- const errorMessage = `Error ${resp.status} from server ${host}: ${responseJson.error.message}`;
57
+ const errorMessage = `Error ${resp.status} from server ${host}: ${responseJson?.error?.message ?? JSON.stringify(responseJson)}`;
57
58
  if (noRetry || (resp.status >= 400 && resp.status < 500)) {
58
59
  throw new NoRetryError(errorMessage);
59
60
  } else {
@@ -44,18 +44,20 @@ export function makeUndiciFetch(client = new Agent()): JsonRpcFetch {
44
44
  let responseJson: any;
45
45
  const responseOk = resp.statusCode >= 200 && resp.statusCode <= 299;
46
46
  const contentEncoding = resp.headers['content-encoding'];
47
+ let responseText: string;
47
48
  try {
48
49
  if (contentEncoding === 'gzip') {
49
50
  const jsonBuffer = await gunzip(await resp.body.arrayBuffer());
50
- responseJson = JSON.parse(jsonBuffer.toString('utf-8'));
51
+ responseText = jsonBuffer.toString('utf-8');
51
52
  } else {
52
- responseJson = await resp.body.json();
53
+ responseText = await resp.body.text();
53
54
  }
55
+ responseJson = JSON.parse(responseText);
54
56
  } catch {
55
57
  if (!responseOk) {
56
58
  throw new Error('HTTP ' + resp.statusCode);
57
59
  }
58
- throw new Error(`Failed to parse body as JSON. encoding: ${contentEncoding}, body: ${await resp.body.text()}`);
60
+ throw new Error(`Failed to parse body as JSON. encoding: ${contentEncoding}, body: ${responseText!}`);
59
61
  }
60
62
 
61
63
  if (!responseOk) {
@@ -377,5 +377,20 @@ export type Logger = { [K in LogLevel]: LogFn } & { /** Error log function */ er
377
377
  * @returns A string with both the log message and the error message.
378
378
  */
379
379
  function formatErr(msg: string, err?: unknown): string {
380
- return err ? `${msg}: ${inspect(err)}` : msg;
380
+ if (!err) {
381
+ return msg;
382
+ }
383
+
384
+ try {
385
+ return `${msg}: ${inspect(err)}`;
386
+ } catch {
387
+ // inspect can crash on error objects with broken property descriptors
388
+ try {
389
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
390
+ return `${msg}: ${err instanceof Error ? `${err.name}: ${err.message}` : String(err)}`;
391
+ } catch {
392
+ // if even String(err) fails, return the original message with a note about the error
393
+ return `${msg}: [unserializable error]`;
394
+ }
395
+ }
381
396
  }
@@ -105,6 +105,7 @@ export class BatchQueue<T, K extends string | number> {
105
105
  return Promise.resolve();
106
106
  }
107
107
 
108
+ this.flushCurrentBatch();
108
109
  this.container.end();
109
110
  return runningPromise;
110
111
  }
@@ -104,6 +104,36 @@ export async function retryUntil<T>(
104
104
  }
105
105
  }
106
106
 
107
+ /**
108
+ * Retry an asynchronous function until it returns a truthy value or the maximum number of retries is exceeded.
109
+ * The function is retried periodically with a fixed interval between attempts.
110
+ *
111
+ * @param fn - The asynchronous function to be retried, which should return a truthy value upon success or undefined otherwise.
112
+ * @param name - The optional name of the operation, used for generating error messages.
113
+ * @param maxRetries - The maximum number of retry attempts before throwing an error.
114
+ * @param retryInterval - The optional interval, in seconds, between retry attempts. Defaults to 1 second.
115
+ * @returns A Promise that resolves with the successful (truthy) result of the provided function, or rejects if retries are exhausted.
116
+ */
117
+ export async function retryTimes<T>(
118
+ fn: () => (T | undefined) | Promise<T | undefined>,
119
+ name = '',
120
+ maxRetries: number,
121
+ retryInterval = 1,
122
+ ) {
123
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
124
+ const result = await fn();
125
+ if (result) {
126
+ return result;
127
+ }
128
+
129
+ if (attempt < maxRetries) {
130
+ await sleep(retryInterval * 1000);
131
+ }
132
+ }
133
+
134
+ throw new Error(name ? `Retries exhausted awaiting ${name}` : 'Retries exhausted');
135
+ }
136
+
107
137
  /**
108
138
  * Convenience wrapper around retryUntil with fast polling for tests.
109
139
  * Uses 10s timeout and 100ms polling interval by default.
@@ -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
  }
@@ -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';
@@ -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,35 +0,0 @@
1
- import { format } from 'util';
2
-
3
- import { createLogger } from '../../log/index.js';
4
-
5
- /**
6
- * Represents a message object for dispatching function calls.
7
- * Contains the function name ('fn') and an array of arguments ('args') required to call the target method.
8
- */
9
- export interface DispatchMsg {
10
- /**
11
- * Name of the target method to be called.
12
- */
13
- fn: string;
14
- /**
15
- * An array of arguments to be passed to the target method.
16
- */
17
- args: any[];
18
- }
19
-
20
- /**
21
- * Creates a dispatch function that calls the target's specified method with provided arguments.
22
- * The created dispatch function takes a DispatchMsg object as input, which contains the name of
23
- * the method to be called ('fn') and an array of arguments to be passed to the method ('args').
24
- *
25
- * @param targetFn - A function that returns the target object containing the methods to be dispatched.
26
- * @param log - Optional logging function for debugging purposes.
27
- * @returns A dispatch function that accepts a DispatchMsg object and calls the target's method with provided arguments.
28
- */
29
- export function createDispatchFn(targetFn: () => any, log = createLogger('foundation:dispatch')) {
30
- return async ({ fn, args }: DispatchMsg) => {
31
- const target = targetFn();
32
- log.debug(format(`dispatching to ${target}: ${fn}`, args));
33
- return await target[fn](...args);
34
- };
35
- }