@nomicfoundation/hardhat-utils 5.1.1 → 5.1.2

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.
@@ -0,0 +1,428 @@
1
+ import type { AbiParameter, AbiSignature } from "../abi.js";
2
+
3
+ import { parseIntType } from "../abi.js";
4
+ import { utf8StringToBytes } from "../bytes.js";
5
+ import { keccak256 } from "../crypto.js";
6
+ import { InvalidAbiSignatureError } from "../errors/abi.js";
7
+
8
+ import { parseFixedBytesType } from "./abi.js";
9
+
10
+ // A word, an array suffix, or any other character, after optional whitespace
11
+ const TOKEN_PATTERN = /\s*(?:[A-Za-z_$][\w$]*|\[(?:[1-9]\d*)?\]|\S)/gy;
12
+
13
+ const ARRAY_SUFFIX_PATTERN = /^\[(?:[1-9]\d*)?\]$/;
14
+
15
+ // The elementary types that aren't integers nor fixed-size bytes
16
+ const ELEMENTARY_TYPE_NAMES = new Set([
17
+ "address",
18
+ "bool",
19
+ "string",
20
+ "bytes",
21
+ "function",
22
+ ]);
23
+
24
+ // The type aliases other than the integer ones, which `parseIntType` handles
25
+ const TYPE_ALIASES = new Map([["byte", "bytes1"]]);
26
+
27
+ // Only library functions have `storage` parameters, and their selectors follow
28
+ // different rules, so it isn't accepted
29
+ const DATA_LOCATIONS = new Set(["memory", "calldata"]);
30
+
31
+ // The keywords that can't be names. Others, like `error` or `tuple`, are only
32
+ // keywords in some contexts, so they can.
33
+ const RESERVED_KEYWORDS = new Set([
34
+ "payable",
35
+ "indexed",
36
+ "anonymous",
37
+ "memory",
38
+ "calldata",
39
+ "storage",
40
+ "returns",
41
+ "function",
42
+ "event",
43
+ "constructor",
44
+ ]);
45
+
46
+ const UNKNOWN_TYPE_HINT =
47
+ "write structs as tuples like (address,uint256), contracts as address, enums as uint8 and user-defined value types as their underlying type";
48
+
49
+ /**
50
+ * Returns the canonical form of a signature, as used to compute its selector
51
+ * or topic: its name and input types, without spaces nor parameter names.
52
+ *
53
+ * @param signature The parsed signature.
54
+ * @returns The canonical signature, like `transfer(address,uint256)`.
55
+ */
56
+ export function getCanonicalAbiSignature({
57
+ name,
58
+ inputs,
59
+ }: Pick<AbiSignature, "name" | "inputs">): string {
60
+ return `${name}(${inputs.map(getCanonicalAbiType).join(",")})`;
61
+ }
62
+
63
+ /**
64
+ * Returns the keccak256 hash of a signature's canonical form. Its first 4 bytes
65
+ * are a function's or error's selector, and the whole hash is an event's topic.
66
+ *
67
+ * @param signature The parsed signature.
68
+ * @returns The 32-byte hash.
69
+ */
70
+ export async function hashCanonicalAbiSignature(
71
+ signature: Pick<AbiSignature, "name" | "inputs">,
72
+ ): Promise<Uint8Array> {
73
+ return await keccak256(
74
+ utf8StringToBytes(getCanonicalAbiSignature(signature)),
75
+ );
76
+ }
77
+
78
+ function getCanonicalAbiType({ type, components }: AbiParameter): string {
79
+ if (components === undefined) {
80
+ return type;
81
+ }
82
+
83
+ // Keep the array suffix of types like `tuple[2][]`
84
+ return `(${components.map(getCanonicalAbiType).join(",")})${type.slice("tuple".length)}`;
85
+ }
86
+
87
+ /**
88
+ * A parser of human-readable ABI signatures, or of a single parameter of one.
89
+ * See `parseAbiSignature` for the syntax it accepts.
90
+ */
91
+ export class AbiSignatureParser {
92
+ /** The signature or parameter being parsed, used to report errors. */
93
+ readonly #input: string;
94
+
95
+ /** The input split into words, array suffixes and single characters. */
96
+ readonly #tokens: string[];
97
+
98
+ /** The index of the current token, the next one to read. */
99
+ #position = 0;
100
+
101
+ /** Whether custom types, like `IPool`, are accepted. Only outputs can be. */
102
+ #allowCustomTypes = false;
103
+
104
+ /**
105
+ * Splits the input into tokens. Call `parse` to parse it as a signature, or
106
+ * `parseSingleParameter` to parse it as a parameter.
107
+ */
108
+ constructor(input: string) {
109
+ this.#input = input;
110
+ this.#tokens = Array.from(input.matchAll(TOKEN_PATTERN), ([token]) =>
111
+ token.trim(),
112
+ );
113
+ }
114
+
115
+ /** Parses the whole input as a single parameter, like `uint256 amount`. */
116
+ public parseSingleParameter(): AbiParameter {
117
+ const parameter = this.#parseParameter();
118
+
119
+ if (this.#peek() !== "") {
120
+ this.#fail("it must be a single type, like uint256 or (address,bool)[]");
121
+ }
122
+
123
+ return parameter;
124
+ }
125
+
126
+ /** Parses the whole input as a signature, like `transfer(address,uint)`. */
127
+ public parse(): AbiSignature {
128
+ const kind = this.#parseDeclarationKeyword();
129
+
130
+ // A constructor has no name
131
+ let name = "";
132
+ if (kind !== "constructor" && isWord(this.#peek())) {
133
+ if (!isName(this.#peek())) {
134
+ this.#fail(`"${this.#peek()}" can't be a name`);
135
+ }
136
+
137
+ name = this.#next();
138
+ }
139
+
140
+ if (name === "" && kind !== undefined && kind !== "constructor") {
141
+ this.#fail("it must include a name");
142
+ }
143
+
144
+ const inputs = this.#parseParameterList();
145
+
146
+ let outputs: AbiParameter[] = [];
147
+ let anonymous = false;
148
+
149
+ if (kind === "event") {
150
+ anonymous = this.#consume("anonymous");
151
+ } else if (kind !== "error") {
152
+ // Return types don't affect the signature, so they can't be wrong in a
153
+ // way that matters here, and declarations often return custom types
154
+ this.#allowCustomTypes = true;
155
+
156
+ if (this.#peek() === "(") {
157
+ outputs = this.#parseParameterList();
158
+ } else {
159
+ // Skip a declaration's modifiers, like `external` or `override(A, B)`,
160
+ // as they don't affect the signature
161
+ while (isWord(this.#peek()) && this.#peek() !== "returns") {
162
+ if (this.#peek() === "anonymous") {
163
+ // Only a signature without a keyword can be an event's
164
+ if (kind !== undefined) {
165
+ this.#failUnexpected();
166
+ }
167
+
168
+ anonymous = true;
169
+ }
170
+
171
+ this.#next();
172
+
173
+ if (this.#peek() === "(") {
174
+ this.#skipModifierArguments();
175
+ }
176
+ }
177
+
178
+ if (anonymous && this.#peek() === "returns") {
179
+ this.#failUnexpected();
180
+ }
181
+
182
+ if (this.#consume("returns")) {
183
+ outputs = this.#parseParameterList();
184
+ }
185
+ }
186
+ }
187
+
188
+ // Ignore a function's body, or a declaration's trailing ";"
189
+ if (
190
+ kind === "event" ||
191
+ kind === "error" ||
192
+ anonymous ||
193
+ !this.#consume("{")
194
+ ) {
195
+ this.#consume(";");
196
+
197
+ if (this.#peek() !== "") {
198
+ this.#failUnexpected();
199
+ }
200
+ }
201
+
202
+ return {
203
+ ...(kind !== undefined && { kind }),
204
+ name,
205
+ inputs,
206
+ outputs,
207
+ ...(anonymous && { anonymous }),
208
+ };
209
+ }
210
+
211
+ /** Consumes the keyword that starts a declaration, if any, and returns it. */
212
+ #parseDeclarationKeyword(): AbiSignature["kind"] {
213
+ const keyword = this.#peek();
214
+
215
+ // `error` can also be a function's name, like in `error(string)`, as it
216
+ // isn't reserved. It starts a declaration only when a name follows it.
217
+ if (
218
+ keyword === "function" ||
219
+ keyword === "event" ||
220
+ keyword === "constructor" ||
221
+ (keyword === "error" && isWord(this.#peek(1)))
222
+ ) {
223
+ this.#position++;
224
+ return keyword;
225
+ }
226
+
227
+ return undefined;
228
+ }
229
+
230
+ /**
231
+ * Skips a modifier's arguments: a parenthesized list that can be nested,
232
+ * like `(getRoleAdmin(role))`.
233
+ */
234
+ #skipModifierArguments(): void {
235
+ let depth = 0;
236
+
237
+ do {
238
+ const token = this.#next();
239
+
240
+ if (token === "") {
241
+ this.#failUnexpected();
242
+ } else if (token === "(") {
243
+ depth++;
244
+ } else if (token === ")") {
245
+ depth--;
246
+ }
247
+ } while (depth > 0);
248
+ }
249
+
250
+ /** Parses a parenthesized and comma-separated list of parameters. */
251
+ #parseParameterList(): AbiParameter[] {
252
+ this.#expect("(");
253
+
254
+ const parameters: AbiParameter[] = [];
255
+ if (this.#consume(")")) {
256
+ return parameters;
257
+ }
258
+
259
+ do {
260
+ parameters.push(this.#parseParameter());
261
+ } while (this.#consume(","));
262
+
263
+ this.#expect(")");
264
+
265
+ return parameters;
266
+ }
267
+
268
+ /** Parses a parameter: its type, array suffixes, modifiers and name. */
269
+ #parseParameter(): AbiParameter {
270
+ let type: string;
271
+ let components: AbiParameter[] | undefined;
272
+
273
+ if (this.#consume("tuple") || this.#peek() === "(") {
274
+ type = "tuple";
275
+ components = this.#parseParameterList();
276
+ } else {
277
+ type = this.#parseTypeName();
278
+ }
279
+
280
+ while (ARRAY_SUFFIX_PATTERN.test(this.#peek())) {
281
+ type += this.#next();
282
+ }
283
+
284
+ // At most one `indexed` and one data location, in any order
285
+ let indexed = false;
286
+ let hasDataLocation = false;
287
+ while (
288
+ (!indexed && this.#peek() === "indexed") ||
289
+ (!hasDataLocation && DATA_LOCATIONS.has(this.#peek()))
290
+ ) {
291
+ if (this.#next() === "indexed") {
292
+ indexed = true;
293
+ } else {
294
+ hasDataLocation = true;
295
+ }
296
+ }
297
+
298
+ if (this.#peek() === "storage") {
299
+ this.#fail(
300
+ '"storage" parameters aren\'t supported, as library selectors follow different rules',
301
+ );
302
+ }
303
+
304
+ // A type or a keyword isn't a name, but what follows a missing "," or a
305
+ // repeated modifier
306
+ const name = isName(this.#peek()) ? this.#next() : undefined;
307
+
308
+ return {
309
+ type,
310
+ ...(components !== undefined && { components }),
311
+ ...(name !== undefined && { name }),
312
+ ...(indexed && { indexed: true }),
313
+ };
314
+ }
315
+
316
+ /**
317
+ * Parses a type name other than a tuple, normalizing aliases. Custom types
318
+ * are only accepted if `#allowCustomTypes` is set.
319
+ */
320
+ #parseTypeName(): string {
321
+ if (!isWord(this.#peek())) {
322
+ this.#failUnexpected();
323
+ }
324
+
325
+ const word = this.#next();
326
+ const intType = parseIntType(word);
327
+
328
+ if (intType !== undefined) {
329
+ return `${intType.signed ? "" : "u"}int${intType.bits}`;
330
+ }
331
+
332
+ const alias = TYPE_ALIASES.get(word);
333
+ if (alias !== undefined) {
334
+ return alias;
335
+ }
336
+
337
+ if (isElementaryType(word)) {
338
+ // `address payable` is encoded as `address`
339
+ if (word === "address") {
340
+ this.#consume("payable");
341
+ }
342
+
343
+ // A function type is encoded as `function`, whatever its parameters
344
+ if (word === "function" && this.#peek() === "(") {
345
+ this.#fail('write function types as just "function"');
346
+ }
347
+
348
+ return word;
349
+ }
350
+
351
+ // Custom types can be qualified, like `DataTypes.ReserveData`
352
+ let type = word;
353
+ while (this.#consume(".")) {
354
+ if (!isWord(this.#peek())) {
355
+ this.#failUnexpected();
356
+ }
357
+
358
+ type += `.${this.#next()}`;
359
+ }
360
+
361
+ if (!this.#allowCustomTypes) {
362
+ this.#fail(`unknown type "${type}"; ${UNKNOWN_TYPE_HINT}`);
363
+ }
364
+
365
+ return type;
366
+ }
367
+
368
+ /** Returns the token `offset` positions ahead, or "" past the end. */
369
+ #peek(offset = 0): string {
370
+ return this.#tokens[this.#position + offset] ?? "";
371
+ }
372
+
373
+ /** Returns the current token and moves past it. */
374
+ #next(): string {
375
+ const token = this.#peek();
376
+ this.#position++;
377
+ return token;
378
+ }
379
+
380
+ /** If the current token is the given one, moves past it and returns true. */
381
+ #consume(token: string): boolean {
382
+ if (this.#peek() !== token) {
383
+ return false;
384
+ }
385
+
386
+ this.#position++;
387
+ return true;
388
+ }
389
+
390
+ /** Moves past the current token, failing if it isn't the given one. */
391
+ #expect(token: string): void {
392
+ if (!this.#consume(token)) {
393
+ this.#failUnexpected();
394
+ }
395
+ }
396
+
397
+ /** Fails on the current token, or because the input ended early. */
398
+ #failUnexpected(): never {
399
+ const token = this.#peek();
400
+
401
+ this.#fail(token === "" ? "it's incomplete" : `unexpected "${token}"`);
402
+ }
403
+
404
+ /** Throws an `InvalidAbiSignatureError` for the given reason. */
405
+ #fail(reason: string): never {
406
+ throw new InvalidAbiSignatureError(this.#input, reason);
407
+ }
408
+ }
409
+
410
+ function isElementaryType(word: string): boolean {
411
+ return (
412
+ ELEMENTARY_TYPE_NAMES.has(word) ||
413
+ TYPE_ALIASES.has(word) ||
414
+ parseIntType(word) !== undefined ||
415
+ parseFixedBytesType(word) !== undefined
416
+ );
417
+ }
418
+
419
+ /** Whether a token can be a signature's or a parameter's name. */
420
+ function isName(token: string): boolean {
421
+ return (
422
+ isWord(token) && !isElementaryType(token) && !RESERVED_KEYWORDS.has(token)
423
+ );
424
+ }
425
+
426
+ function isWord(token: string): boolean {
427
+ return /^[A-Za-z_$]/.test(token);
428
+ }
@@ -35,10 +35,29 @@ export interface UnnamedAbiParameter {
35
35
  // In Solidity the rightmost suffix is the outermost array, so `uint256[2][]` is
36
36
  // a dynamic array of `uint256[2]`. The greedy `.+` matches that last suffix.
37
37
  const ARRAY_REGEX = /^(.+)(\[(\d+)?\])$/;
38
- const BYTES_N_REGEX = /^bytes([0-9]{1,2})$/;
38
+ const FIXED_BYTES_TYPE_REGEX = /^bytes([1-9]\d?)$/;
39
39
  const DECIMAL_REGEX = /^\d+$/;
40
40
  const HEX_REGEX = /^0x[0-9a-f]+$/i;
41
41
 
42
+ /**
43
+ * Parses a Solidity fixed-size bytes type name, like `bytes32`, into its size.
44
+ *
45
+ * @param type The type name to parse.
46
+ * @returns The size in bytes, from 1 to 32, or `undefined` if it isn't a
47
+ * fixed-size bytes type.
48
+ */
49
+ export function parseFixedBytesType(type: string): number | undefined {
50
+ const match = FIXED_BYTES_TYPE_REGEX.exec(type);
51
+
52
+ if (match === null) {
53
+ return undefined;
54
+ }
55
+
56
+ const size = Number(match[1]);
57
+
58
+ return size <= 32 ? size : undefined;
59
+ }
60
+
42
61
  /**
43
62
  * Throws if two of the given parameters share a name.
44
63
  *
@@ -136,13 +155,9 @@ export async function normalizeAbiValue(
136
155
  return normalizeBytes(value, path, type, undefined);
137
156
  }
138
157
 
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);
158
+ const fixedBytesSize = parseFixedBytesType(type);
159
+ if (fixedBytesSize !== undefined) {
160
+ return normalizeBytes(value, path, type, fixedBytesSize);
146
161
  }
147
162
 
148
163
  const intType = parseIntType(type);
@@ -51,6 +51,12 @@ const DEFAULT_PORTS: Map<string, number> = new Map([
51
51
  ["https:", 443],
52
52
  ]);
53
53
 
54
+ // Node tries each resolved address in turn, giving all but the last one only
55
+ // 250ms by default. On hosts without IPv6, the IPv6 addresses fail instantly,
56
+ // so a single lost SYN on IPv4 (resent after 1s) fails the whole request.
57
+ // 1250ms leaves room for that resend plus the round trip.
58
+ export const AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_IN_MILLISECONDS = 1250;
59
+
54
60
  export async function generateTempFilePath(filePath: string): Promise<string> {
55
61
  const { dir, ext, name } = path.parse(filePath);
56
62
 
@@ -279,6 +285,9 @@ export async function getProxyDispatcher(
279
285
  undici = await import("undici");
280
286
  }
281
287
 
288
+ // TODO: ProxyAgent connects to the proxy with its own connector, built from
289
+ // `proxyTls`, so the `autoSelectFamily` options from `getBaseDispatcherOptions`
290
+ // don't reach that connection.
282
291
  return new undici.ProxyAgent({
283
292
  uri: proxy,
284
293
  ...options,
@@ -321,6 +330,11 @@ export function getBaseDispatcherOptions(
321
330
  headersTimeout: timeout,
322
331
  bodyTimeout: timeout,
323
332
  connectTimeout: timeout,
333
+ // `true` is already Node's default, but undici only forwards the attempt
334
+ // timeout when `autoSelectFamily` is set
335
+ autoSelectFamily: true,
336
+ autoSelectFamilyAttemptTimeout:
337
+ AUTO_SELECT_FAMILY_ATTEMPT_TIMEOUT_IN_MILLISECONDS,
324
338
  ...keepAliveTimeouts,
325
339
  };
326
340
  }