@nomicfoundation/hardhat-utils 4.2.0 → 4.4.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 (45) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/src/abi.d.ts +79 -0
  3. package/dist/src/abi.d.ts.map +1 -0
  4. package/dist/src/abi.js +114 -0
  5. package/dist/src/abi.js.map +1 -0
  6. package/dist/src/errors/abi.d.ts +93 -0
  7. package/dist/src/errors/abi.d.ts.map +1 -0
  8. package/dist/src/errors/abi.js +117 -0
  9. package/dist/src/errors/abi.js.map +1 -0
  10. package/dist/src/errors/request.d.ts +4 -0
  11. package/dist/src/errors/request.d.ts.map +1 -1
  12. package/dist/src/errors/request.js +7 -0
  13. package/dist/src/errors/request.js.map +1 -1
  14. package/dist/src/eth.d.ts +9 -0
  15. package/dist/src/eth.d.ts.map +1 -1
  16. package/dist/src/eth.js +16 -1
  17. package/dist/src/eth.js.map +1 -1
  18. package/dist/src/internal/abi.d.ts +50 -0
  19. package/dist/src/internal/abi.d.ts.map +1 -0
  20. package/dist/src/internal/abi.js +248 -0
  21. package/dist/src/internal/abi.js.map +1 -0
  22. package/dist/src/internal/bytes.js +3 -3
  23. package/dist/src/internal/bytes.js.map +1 -1
  24. package/dist/src/internal/eth.d.ts +14 -5
  25. package/dist/src/internal/eth.d.ts.map +1 -1
  26. package/dist/src/internal/eth.js +16 -6
  27. package/dist/src/internal/eth.js.map +1 -1
  28. package/dist/src/internal/request.d.ts +37 -0
  29. package/dist/src/internal/request.d.ts.map +1 -1
  30. package/dist/src/internal/request.js +168 -1
  31. package/dist/src/internal/request.js.map +1 -1
  32. package/dist/src/request.d.ts +26 -9
  33. package/dist/src/request.d.ts.map +1 -1
  34. package/dist/src/request.js +31 -38
  35. package/dist/src/request.js.map +1 -1
  36. package/package.json +5 -3
  37. package/src/abi.ts +199 -0
  38. package/src/errors/abi.ts +156 -0
  39. package/src/errors/request.ts +12 -0
  40. package/src/eth.ts +22 -0
  41. package/src/internal/abi.ts +431 -0
  42. package/src/internal/bytes.ts +4 -4
  43. package/src/internal/eth.ts +23 -6
  44. package/src/internal/request.ts +218 -0
  45. package/src/request.ts +38 -45
@@ -22,6 +22,18 @@ export class DispatcherError extends CustomError {
22
22
  }
23
23
  }
24
24
 
25
+ export class InvalidProxyUrlError extends CustomError {
26
+ public readonly envVarName: string;
27
+
28
+ constructor(envVarName: string, cause?: Error) {
29
+ super(
30
+ `The proxy url configured in the ${envVarName} environment variable is not a valid url`,
31
+ cause,
32
+ );
33
+ this.envVarName = envVarName;
34
+ }
35
+ }
36
+
25
37
  export class RequestTimeoutError extends CustomError {
26
38
  constructor(url: string, cause?: Error) {
27
39
  super(`Request to ${sanitizeUrl(url)} timed out`, cause);
package/src/eth.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import type { PrefixedHexString } from "./hex.js";
2
2
 
3
+ import { InvalidParameterError } from "./common-errors.js";
3
4
  import { bytesToHexString, numberToHexString, setLengthLeft } from "./hex.js";
4
5
  import {
5
6
  getAddressGenerator,
6
7
  getHashGenerator,
7
8
  isValidChecksum,
9
+ toChecksumAddress as toChecksumAddressImpl,
8
10
  } from "./internal/eth.js";
9
11
 
10
12
  /**
@@ -27,6 +29,26 @@ export async function isValidChecksumAddress(value: unknown): Promise<boolean> {
27
29
  return await (isAddress(value) && isValidChecksum(value));
28
30
  }
29
31
 
32
+ /**
33
+ * Converts an Ethereum address to its EIP-55 checksummed representation.
34
+ *
35
+ * @param address The address to convert. It can be checksummed or not, but it
36
+ * must be a valid Ethereum address.
37
+ * @returns The EIP-55 checksummed representation of the address.
38
+ * @throws InvalidParameterError If the input is not an Ethereum address.
39
+ */
40
+ export async function toChecksumAddress(
41
+ address: string,
42
+ ): Promise<PrefixedHexString> {
43
+ if (!isAddress(address)) {
44
+ throw new InvalidParameterError(
45
+ `Expected an Ethereum address. Received: ${address}`,
46
+ );
47
+ }
48
+
49
+ return await toChecksumAddressImpl(address);
50
+ }
51
+
30
52
  /**
31
53
  * Checks if a value is an Ethereum hash.
32
54
  *
@@ -0,0 +1,431 @@
1
+ import type { AbiParameter } from "../abi.js";
2
+
3
+ import { getIntTypeRange, parseIntType } from "../abi.js";
4
+ import {
5
+ AbiValueOutOfBoundsError,
6
+ DuplicateAbiParameterNameError,
7
+ InvalidAbiValueError,
8
+ UnsupportedAbiTypeError,
9
+ } from "../errors/abi.js";
10
+ import { isAddress, isValidChecksumAddress } from "../eth.js";
11
+ import {
12
+ getPrefixedHexString,
13
+ getUnprefixedHexString,
14
+ hexStringToBytes,
15
+ isHexString,
16
+ isPrefixedHexString,
17
+ } from "../hex.js";
18
+ import { isObject } from "../lang.js";
19
+
20
+ /**
21
+ * A value in the shape that the encoder expects. Aggregates are always
22
+ * positional, because we strip the parameter names before encoding.
23
+ */
24
+ export type NormalizedAbiValue =
25
+ bigint | boolean | string | Uint8Array | NormalizedAbiValue[];
26
+
27
+ /**
28
+ * An ABI parameter with every name removed, recursively.
29
+ */
30
+ export interface UnnamedAbiParameter {
31
+ readonly type: string;
32
+ readonly components?: readonly UnnamedAbiParameter[];
33
+ }
34
+
35
+ // In Solidity the rightmost suffix is the outermost array, so `uint256[2][]` is
36
+ // a dynamic array of `uint256[2]`. The greedy `.+` matches that last suffix.
37
+ const ARRAY_REGEX = /^(.+)(\[(\d+)?\])$/;
38
+ const BYTES_N_REGEX = /^bytes([0-9]{1,2})$/;
39
+ const DECIMAL_REGEX = /^\d+$/;
40
+ const HEX_REGEX = /^0x[0-9a-f]+$/i;
41
+
42
+ /**
43
+ * Throws if two of the given parameters share a name.
44
+ *
45
+ * This is checked against the parameter list rather than the value, so that the
46
+ * array and object input shapes fail the same way.
47
+ *
48
+ * @param parameters The parameters to check.
49
+ * @param path The path of their container, or undefined at the top level.
50
+ * @throws DuplicateAbiParameterNameError If a name is repeated.
51
+ */
52
+ export function assertNoDuplicateAbiParameterNames(
53
+ parameters: readonly AbiParameter[],
54
+ path?: string,
55
+ ): void {
56
+ const seen = new Set<string>();
57
+ for (const { name } of parameters) {
58
+ if (name === undefined || name === "") {
59
+ continue;
60
+ }
61
+
62
+ if (seen.has(name)) {
63
+ throw new DuplicateAbiParameterNameError(path, name);
64
+ }
65
+
66
+ seen.add(name);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Removes the names of a list of ABI parameters, recursively.
72
+ *
73
+ * The encoder derives the shape of the value it expects from whether the
74
+ * parameters are named: named ones take an object keyed by name, unnamed ones
75
+ * take a positional array. Dropping the names makes every aggregate positional,
76
+ * at every nesting level.
77
+ *
78
+ * @param parameters The parameters to strip.
79
+ * @returns The same parameters, without their names.
80
+ */
81
+ export function toUnnamedAbiParameters(
82
+ parameters: readonly AbiParameter[],
83
+ ): UnnamedAbiParameter[] {
84
+ return parameters.map(({ type, components }) =>
85
+ components === undefined
86
+ ? { type }
87
+ : { type, components: toUnnamedAbiParameters(components) },
88
+ );
89
+ }
90
+
91
+ /**
92
+ * Converts a value into the shape that the encoder expects for a parameter,
93
+ * validating it against the parameter's Solidity type.
94
+ *
95
+ * @param parameter The ABI parameter to normalize the value for.
96
+ * @param value The value to normalize.
97
+ * @param path The path of the parameter, used to report errors.
98
+ * @returns The normalized value.
99
+ * @throws InvalidAbiValueError If the value can't be encoded as the type.
100
+ * @throws AbiValueOutOfBoundsError If a numeric value is out of the type's range.
101
+ * @throws UnsupportedAbiTypeError If the type itself can't be encoded.
102
+ */
103
+ export async function normalizeAbiValue(
104
+ parameter: AbiParameter,
105
+ value: unknown,
106
+ path: string,
107
+ ): Promise<NormalizedAbiValue> {
108
+ const { type } = parameter;
109
+
110
+ // Arrays must be checked first, as the check is recursive.
111
+ const arrayMatch = ARRAY_REGEX.exec(type);
112
+ if (arrayMatch !== null) {
113
+ return await normalizeArray(parameter, value, path, arrayMatch);
114
+ }
115
+
116
+ if (type === "tuple") {
117
+ return await normalizeTuple(parameter, value, path);
118
+ }
119
+
120
+ if (type === "address") {
121
+ return await normalizeAddress(value, path);
122
+ }
123
+
124
+ if (type === "bool") {
125
+ return normalizeBool(value, path);
126
+ }
127
+
128
+ if (type === "string") {
129
+ if (typeof value !== "string") {
130
+ throw new InvalidAbiValueError(path, type, value, "invalid string value");
131
+ }
132
+ return value;
133
+ }
134
+
135
+ if (type === "bytes") {
136
+ return normalizeBytes(value, path, type, undefined);
137
+ }
138
+
139
+ const bytesNMatch = BYTES_N_REGEX.exec(type);
140
+ if (bytesNMatch !== null) {
141
+ const length = Number(bytesNMatch[1]);
142
+ if (length < 1 || length > 32) {
143
+ throw new UnsupportedAbiTypeError(path, type);
144
+ }
145
+ return normalizeBytes(value, path, type, length);
146
+ }
147
+
148
+ const intType = parseIntType(type);
149
+ if (intType !== undefined) {
150
+ return normalizeInt(value, path, type, intType);
151
+ }
152
+
153
+ throw new UnsupportedAbiTypeError(path, type);
154
+ }
155
+
156
+ async function normalizeArray(
157
+ parameter: AbiParameter,
158
+ value: unknown,
159
+ path: string,
160
+ arrayMatch: RegExpExecArray,
161
+ ): Promise<NormalizedAbiValue[]> {
162
+ const { type } = parameter;
163
+ const elementType = arrayMatch[1];
164
+ const fixedLength = arrayMatch[3];
165
+
166
+ if (!Array.isArray(value)) {
167
+ throw new InvalidAbiValueError(
168
+ path,
169
+ type,
170
+ value,
171
+ "invalid array value, expected a JS array",
172
+ );
173
+ }
174
+
175
+ if (fixedLength !== undefined && value.length !== Number(fixedLength)) {
176
+ throw new InvalidAbiValueError(
177
+ path,
178
+ type,
179
+ value,
180
+ `invalid array length, expected ${fixedLength} elements but got ${value.length}`,
181
+ );
182
+ }
183
+
184
+ const elementParameter = { ...parameter, type: elementType };
185
+ const normalized: NormalizedAbiValue[] = [];
186
+ for (const [i, element] of value.entries()) {
187
+ normalized.push(
188
+ await normalizeAbiValue(elementParameter, element, `${path}[${i}]`),
189
+ );
190
+ }
191
+
192
+ return normalized;
193
+ }
194
+
195
+ async function normalizeTuple(
196
+ parameter: AbiParameter,
197
+ value: unknown,
198
+ path: string,
199
+ ): Promise<NormalizedAbiValue[]> {
200
+ const { type, components } = parameter;
201
+
202
+ // The encoder rejects zero-sized tuples, as arrays of them can be used to
203
+ // DoS the decoder.
204
+ if (components === undefined || components.length === 0) {
205
+ throw new UnsupportedAbiTypeError(path, type);
206
+ }
207
+
208
+ assertNoDuplicateAbiParameterNames(components, path);
209
+
210
+ if (Array.isArray(value)) {
211
+ if (value.length !== components.length) {
212
+ throw new InvalidAbiValueError(
213
+ path,
214
+ type,
215
+ value,
216
+ `invalid tuple length, expected ${components.length} components but got ${value.length}`,
217
+ );
218
+ }
219
+
220
+ const normalized: NormalizedAbiValue[] = [];
221
+ for (const [i, component] of components.entries()) {
222
+ normalized.push(
223
+ await normalizeAbiValue(
224
+ component,
225
+ value[i],
226
+ component.name === undefined
227
+ ? `${path}[${i}]`
228
+ : `${path}.${component.name}`,
229
+ ),
230
+ );
231
+ }
232
+
233
+ return normalized;
234
+ }
235
+
236
+ if (isObject(value)) {
237
+ const normalized: NormalizedAbiValue[] = [];
238
+ for (const component of components) {
239
+ const { name } = component;
240
+
241
+ if (name === undefined || name === "") {
242
+ throw new InvalidAbiValueError(
243
+ path,
244
+ type,
245
+ value,
246
+ "invalid tuple value, it has unnamed components so it must be provided as an array",
247
+ );
248
+ }
249
+
250
+ const componentPath = `${path}.${name}`;
251
+
252
+ if (!Object.hasOwn(value, name)) {
253
+ throw new InvalidAbiValueError(
254
+ componentPath,
255
+ component.type,
256
+ undefined,
257
+ `missing value for the tuple component "${name}"`,
258
+ );
259
+ }
260
+
261
+ normalized.push(
262
+ await normalizeAbiValue(component, value[name], componentPath),
263
+ );
264
+ }
265
+
266
+ return normalized;
267
+ }
268
+
269
+ throw new InvalidAbiValueError(
270
+ path,
271
+ type,
272
+ value,
273
+ "invalid tuple value, expected an array or an object",
274
+ );
275
+ }
276
+
277
+ function normalizeBool(value: unknown, path: string): boolean {
278
+ if (typeof value === "boolean") {
279
+ return value;
280
+ }
281
+
282
+ // Command line arguments always arrive as strings, so the two Solidity
283
+ // literals are accepted. Any other string is rejected.
284
+ if (value === "true") {
285
+ return true;
286
+ }
287
+
288
+ if (value === "false") {
289
+ return false;
290
+ }
291
+
292
+ throw new InvalidAbiValueError(path, "bool", value, "invalid boolean value");
293
+ }
294
+
295
+ async function normalizeAddress(value: unknown, path: string): Promise<string> {
296
+ if (typeof value !== "string") {
297
+ throw new InvalidAbiValueError(
298
+ path,
299
+ "address",
300
+ value,
301
+ "invalid address value, expected a string",
302
+ );
303
+ }
304
+
305
+ // The prefix is re-added in lowercase, so that a "0X"-prefixed address still
306
+ // matches the checksummed form it is compared against below.
307
+ const address = getPrefixedHexString(getUnprefixedHexString(value));
308
+ if (!isAddress(address)) {
309
+ throw new InvalidAbiValueError(
310
+ path,
311
+ "address",
312
+ value,
313
+ "invalid address value",
314
+ );
315
+ }
316
+
317
+ // A mixed-case address carries an EIP-55 checksum, so it is validated to
318
+ // catch mistyped addresses here instead of failing later, somewhere else.
319
+ // An all-lowercase or all-uppercase one carries no checksum to validate.
320
+ const hexAddress = getUnprefixedHexString(address);
321
+ const isCaseless =
322
+ hexAddress === hexAddress.toLowerCase() ||
323
+ hexAddress === hexAddress.toUpperCase();
324
+
325
+ if (!isCaseless && !(await isValidChecksumAddress(address))) {
326
+ throw new InvalidAbiValueError(
327
+ path,
328
+ "address",
329
+ value,
330
+ "invalid address checksum",
331
+ );
332
+ }
333
+
334
+ return address.toLowerCase();
335
+ }
336
+
337
+ function normalizeBytes(
338
+ value: unknown,
339
+ path: string,
340
+ type: string,
341
+ length: number | undefined,
342
+ ): Uint8Array {
343
+ let bytes: Uint8Array;
344
+
345
+ if (value instanceof Uint8Array) {
346
+ bytes = value;
347
+ // The "0x" prefix is required, as an unprefixed string is more likely to
348
+ // be a value that was meant to be something other than bytes.
349
+ } else if (
350
+ typeof value === "string" &&
351
+ isPrefixedHexString(value) &&
352
+ isHexString(value)
353
+ ) {
354
+ const unprefixed = getUnprefixedHexString(value);
355
+ if (unprefixed.length % 2 !== 0) {
356
+ throw new InvalidAbiValueError(
357
+ path,
358
+ type,
359
+ value,
360
+ "invalid bytes value, the hex string has an odd length",
361
+ );
362
+ }
363
+ bytes =
364
+ unprefixed.length === 0 ? new Uint8Array() : hexStringToBytes(unprefixed);
365
+ } else {
366
+ throw new InvalidAbiValueError(
367
+ path,
368
+ type,
369
+ value,
370
+ 'invalid bytes value, expected a "0x"-prefixed hex string or a Uint8Array',
371
+ );
372
+ }
373
+
374
+ if (length !== undefined && bytes.length !== length) {
375
+ throw new InvalidAbiValueError(
376
+ path,
377
+ type,
378
+ value,
379
+ `invalid bytes length, expected ${length} bytes but got ${bytes.length}`,
380
+ );
381
+ }
382
+
383
+ return bytes;
384
+ }
385
+
386
+ function normalizeInt(
387
+ value: unknown,
388
+ path: string,
389
+ type: string,
390
+ intType: { signed: boolean; bits: number },
391
+ ): bigint {
392
+ let normalized: bigint;
393
+
394
+ if (typeof value === "bigint") {
395
+ normalized = value;
396
+ } else if (typeof value === "number") {
397
+ if (!Number.isSafeInteger(value)) {
398
+ throw new InvalidAbiValueError(
399
+ path,
400
+ type,
401
+ value,
402
+ "invalid numeric value, it is not a safe integer; use a bigint or a string instead",
403
+ );
404
+ }
405
+ normalized = BigInt(value);
406
+ } else if (typeof value === "string") {
407
+ normalized = parseIntValue(value, path, type);
408
+ } else {
409
+ throw new InvalidAbiValueError(path, type, value, "invalid numeric value");
410
+ }
411
+
412
+ const { min, max } = getIntTypeRange(intType);
413
+ if (normalized < min || normalized > max) {
414
+ throw new AbiValueOutOfBoundsError(path, type, value, min, max);
415
+ }
416
+
417
+ return normalized;
418
+ }
419
+
420
+ function parseIntValue(value: string, path: string, type: string): bigint {
421
+ // BigInt() throws on a signed hex string, so the sign is handled here.
422
+ const negative = value.startsWith("-");
423
+ const magnitude = negative ? value.slice(1) : value;
424
+
425
+ if (!DECIMAL_REGEX.test(magnitude) && !HEX_REGEX.test(magnitude)) {
426
+ throw new InvalidAbiValueError(path, type, value, "invalid numeric value");
427
+ }
428
+
429
+ const parsed = BigInt(magnitude);
430
+ return negative ? -parsed : parsed;
431
+ }
@@ -20,17 +20,17 @@ export async function parseJsonStream<T>(stream: Readable): Promise<T> {
20
20
  streamParserJson = await import("@streamparser/json-node");
21
21
  }
22
22
 
23
- // NOTE: We set a separator to disable self-closing to be able to use the parser
24
- // in the stream.pipeline context; see https://github.com/juanjoDiaz/streamparser-json/issues/47
23
+ // We only emit the root value, as it's the only one we use, and emitting
24
+ // every nested value is much slower.
25
25
  const jsonParser = new streamParserJson.JSONParser({
26
- separator: "",
26
+ paths: ["$"],
27
27
  });
28
28
 
29
29
  const result: T | undefined = await pipeline(
30
30
  stream,
31
31
  jsonParser,
32
32
  async (
33
- elements: AsyncIterable<StreamParserJson.ParsedElementInfo.ParsedElementInfo>,
33
+ elements: AsyncIterable<StreamParserJson.ParsedElementInfo>,
34
34
  ): Promise<any | undefined> => {
35
35
  let value:
36
36
  | StreamParserJson.JsonTypes.JsonPrimitive
@@ -1,3 +1,5 @@
1
+ import type { PrefixedHexString } from "../hex.js";
2
+
1
3
  import { utf8StringToBytes } from "../bytes.js";
2
4
  import { keccak256 } from "../crypto.js";
3
5
  import { bytesToHexString, getUnprefixedHexString } from "../hex.js";
@@ -42,16 +44,19 @@ export async function getAddressGenerator(): Promise<RandomBytesGenerator> {
42
44
  }
43
45
 
44
46
  /**
45
- * Checks if a value is an Ethereum address and if the checksum is valid.
46
- * This method is a a an adaptation of the ethereumjs methods at this link:
47
+ * Converts an Ethereum address to its EIP-55 checksummed representation.
48
+ * This method is an adaptation of the ethereumjs methods at this link:
47
49
  * https://github.com/ethereumjs/ethereumjs-monorepo/blob/47f388bfeec553519d11259fee7e7161a77b29b2/packages/util/src/account.ts#L440-L478
48
50
  * The main differences are:
49
- * - the two methods have been merged into one
50
- * - tha `eip1191ChainId` parameter has been removed.
51
+ * - the `eip1191ChainId` parameter has been removed.
51
52
  * - the code has been modified to use the `hardhat-utils` methods
52
53
  *
54
+ * It doesn't validate that the input is an Ethereum address; callers must
55
+ * check that first (see the public wrappers in `../eth.ts`).
53
56
  */
54
- export async function isValidChecksum(hexAddress: string): Promise<boolean> {
57
+ export async function toChecksumAddress(
58
+ hexAddress: PrefixedHexString,
59
+ ): Promise<PrefixedHexString> {
55
60
  const address = getUnprefixedHexString(hexAddress).toLowerCase();
56
61
 
57
62
  const bytes = utf8StringToBytes(address);
@@ -67,5 +72,17 @@ export async function isValidChecksum(hexAddress: string): Promise<boolean> {
67
72
  }
68
73
  }
69
74
 
70
- return `0x${ret}` === hexAddress;
75
+ return `0x${ret}`;
76
+ }
77
+
78
+ /**
79
+ * Checks if the checksum of an address is valid.
80
+ *
81
+ * It doesn't validate that the input is an Ethereum address; callers must
82
+ * check that first (see the public wrappers in `../eth.ts`).
83
+ */
84
+ export async function isValidChecksum(
85
+ hexAddress: PrefixedHexString,
86
+ ): Promise<boolean> {
87
+ return (await toChecksumAddress(hexAddress)) === hexAddress;
71
88
  }