@nomicfoundation/hardhat-utils 5.1.0 → 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.
Files changed (38) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/src/abi.d.ts +110 -1
  3. package/dist/src/abi.d.ts.map +1 -1
  4. package/dist/src/abi.js +109 -3
  5. package/dist/src/abi.js.map +1 -1
  6. package/dist/src/bytes.js +1 -1
  7. package/dist/src/bytes.js.map +1 -1
  8. package/dist/src/errors/abi.d.ts +26 -3
  9. package/dist/src/errors/abi.d.ts.map +1 -1
  10. package/dist/src/errors/abi.js +42 -5
  11. package/dist/src/errors/abi.js.map +1 -1
  12. package/dist/src/hex.d.ts +2 -2
  13. package/dist/src/hex.js +3 -3
  14. package/dist/src/hex.js.map +1 -1
  15. package/dist/src/internal/abi-signature.d.ts +34 -0
  16. package/dist/src/internal/abi-signature.d.ts.map +1 -0
  17. package/dist/src/internal/abi-signature.js +335 -0
  18. package/dist/src/internal/abi-signature.js.map +1 -0
  19. package/dist/src/internal/abi.d.ts +8 -0
  20. package/dist/src/internal/abi.d.ts.map +1 -1
  21. package/dist/src/internal/abi.js +21 -12
  22. package/dist/src/internal/abi.js.map +1 -1
  23. package/dist/src/internal/hex.d.ts.map +1 -1
  24. package/dist/src/internal/hex.js +1 -9
  25. package/dist/src/internal/hex.js.map +1 -1
  26. package/dist/src/internal/request.d.ts +1 -0
  27. package/dist/src/internal/request.d.ts.map +1 -1
  28. package/dist/src/internal/request.js +12 -0
  29. package/dist/src/internal/request.js.map +1 -1
  30. package/package.json +1 -1
  31. package/src/abi.ts +197 -1
  32. package/src/bytes.ts +1 -1
  33. package/src/errors/abi.ts +68 -11
  34. package/src/hex.ts +3 -3
  35. package/src/internal/abi-signature.ts +428 -0
  36. package/src/internal/abi.ts +25 -12
  37. package/src/internal/hex.ts +1 -8
  38. package/src/internal/request.ts +14 -0
package/src/abi.ts CHANGED
@@ -5,8 +5,13 @@ import { ensureError } from "./error.js";
5
5
  import {
6
6
  AbiEncodingFailedError,
7
7
  AbiParametersLengthMismatchError,
8
+ InvalidAbiSignatureError,
8
9
  } from "./errors/abi.js";
9
- import { getPrefixedHexString } from "./hex.js";
10
+ import { bytesToHexString, getPrefixedHexString } from "./hex.js";
11
+ import {
12
+ AbiSignatureParser,
13
+ hashCanonicalAbiSignature,
14
+ } from "./internal/abi-signature.js";
10
15
  import {
11
16
  assertNoDuplicateAbiParameterNames,
12
17
  normalizeAbiValue,
@@ -24,6 +29,7 @@ export interface AbiParameter {
24
29
  readonly name?: string;
25
30
  readonly type: string;
26
31
  readonly components?: readonly AbiParameter[];
32
+ readonly indexed?: boolean;
27
33
  }
28
34
 
29
35
  /**
@@ -36,6 +42,52 @@ export interface AbiFragment {
36
42
  readonly inputs?: readonly AbiParameter[];
37
43
  }
38
44
 
45
+ /**
46
+ * A parsed human-readable signature of a function, event or error.
47
+ */
48
+ export interface AbiSignature {
49
+ /** The keyword the signature starts with, if any. */
50
+ readonly kind?: "function" | "event" | "error" | "constructor";
51
+ /**
52
+ * The name, or "" for a constructor or a bare parameter list, like
53
+ * `(uint256,bool)`.
54
+ */
55
+ readonly name: string;
56
+ readonly inputs: readonly AbiParameter[];
57
+ /**
58
+ * The return types, written as `f(uint256)(bool)` or
59
+ * `f(uint256) returns (bool)`. They can hold custom types, like `IPool`, kept
60
+ * as written, which aren't ABI types and must be resolved before decoding.
61
+ */
62
+ readonly outputs: readonly AbiParameter[];
63
+ /** Set to true if the signature has the `anonymous` modifier of events. */
64
+ readonly anonymous?: boolean;
65
+ }
66
+
67
+ /**
68
+ * A parsed human-readable signature of a function or error.
69
+ */
70
+ export interface AbiFunctionSignature {
71
+ /** The keyword the signature starts with, if any. */
72
+ readonly kind?: "function" | "error";
73
+ readonly name: string;
74
+ readonly inputs: readonly AbiParameter[];
75
+ /** The return types. See `AbiSignature#outputs`. */
76
+ readonly outputs: readonly AbiParameter[];
77
+ }
78
+
79
+ /**
80
+ * A parsed human-readable signature of an event.
81
+ */
82
+ export interface AbiEventSignature {
83
+ /** The keyword the signature starts with, if any. */
84
+ readonly kind?: "event";
85
+ readonly name: string;
86
+ readonly inputs: readonly AbiParameter[];
87
+ /** Whether the event is anonymous, so it doesn't log its topic. */
88
+ readonly anonymous: boolean;
89
+ }
90
+
39
91
  /**
40
92
  * The signedness and size of a Solidity integer type.
41
93
  */
@@ -185,15 +237,159 @@ export async function encodeAbiParameters(
185
237
  return getPrefixedHexString(encoded);
186
238
  }
187
239
 
240
+ /**
241
+ * Parses a human-readable signature, like `transfer(address,uint256)`.
242
+ *
243
+ * It also accepts parameter names, the `indexed` and data location keywords,
244
+ * tuples written as `(...)` or `tuple(...)`, and whole Solidity declarations,
245
+ * like `function balanceOf(address owner) external view returns (uint256);`.
246
+ * Type aliases are normalized, so `uint` becomes `uint256` and `byte` becomes
247
+ * `bytes1`, and function types must be written as `function`. Custom types,
248
+ * like structs or contracts, are only accepted as return types, as resolving
249
+ * them to ABI types needs their definitions.
250
+ *
251
+ * @param signature The signature to parse.
252
+ * @returns The parsed signature.
253
+ * @throws InvalidAbiSignatureError If the signature is invalid.
254
+ */
255
+ export function parseAbiSignature(signature: string): AbiSignature {
256
+ return new AbiSignatureParser(signature).parse();
257
+ }
258
+
259
+ /**
260
+ * Parses a human-readable signature of a function or error, like
261
+ * `transfer(address,uint256)` or `error Unauthorized(address)`, accepting the
262
+ * same syntax as `parseAbiSignature`.
263
+ *
264
+ * @param signature The signature to parse.
265
+ * @returns The parsed signature.
266
+ * @throws InvalidAbiSignatureError If the signature is invalid, has no name, or
267
+ * is of an event or a constructor.
268
+ */
269
+ export function parseAbiFunctionSignature(
270
+ signature: string,
271
+ ): AbiFunctionSignature {
272
+ const { kind, name, inputs, outputs, anonymous } =
273
+ parseAbiSignature(signature);
274
+
275
+ if (
276
+ kind === "event" ||
277
+ anonymous === true ||
278
+ inputs.some((input) => input.indexed === true)
279
+ ) {
280
+ throw new InvalidAbiSignatureError(
281
+ signature,
282
+ "it's an event, not a function or error",
283
+ );
284
+ }
285
+
286
+ if (kind === "constructor") {
287
+ throw new InvalidAbiSignatureError(
288
+ signature,
289
+ "it's a constructor, not a function or error",
290
+ );
291
+ }
292
+
293
+ if (name === "") {
294
+ throw new InvalidAbiSignatureError(signature, "it must include a name");
295
+ }
296
+
297
+ return { ...(kind !== undefined && { kind }), name, inputs, outputs };
298
+ }
299
+
300
+ /**
301
+ * Parses a human-readable signature of an event, like
302
+ * `Transfer(address,address,uint256)`, accepting the same syntax as
303
+ * `parseAbiSignature`.
304
+ *
305
+ * @param signature The signature to parse.
306
+ * @returns The parsed signature.
307
+ * @throws InvalidAbiSignatureError If the signature is invalid, has no name, has
308
+ * return types, or is of a function, error or constructor.
309
+ */
310
+ export function parseAbiEventSignature(signature: string): AbiEventSignature {
311
+ const { kind, name, inputs, outputs, anonymous } =
312
+ parseAbiSignature(signature);
313
+
314
+ if (kind === "function" || kind === "error" || kind === "constructor") {
315
+ throw new InvalidAbiSignatureError(
316
+ signature,
317
+ `it's ${kind === "error" ? "an" : "a"} ${kind}, not an event`,
318
+ );
319
+ }
320
+
321
+ if (outputs.length > 0) {
322
+ throw new InvalidAbiSignatureError(
323
+ signature,
324
+ "events can't have return types",
325
+ );
326
+ }
327
+
328
+ if (name === "") {
329
+ throw new InvalidAbiSignatureError(signature, "it must include a name");
330
+ }
331
+
332
+ return {
333
+ ...(kind !== undefined && { kind }),
334
+ name,
335
+ inputs,
336
+ anonymous: anonymous === true,
337
+ };
338
+ }
339
+
340
+ /**
341
+ * Parses a single human-readable parameter, like `uint256`, `address payable`
342
+ * or `(address to, uint256 amount)[]`, accepting the same syntax as the
343
+ * parameters of `parseAbiSignature`.
344
+ *
345
+ * @param parameter The parameter to parse.
346
+ * @returns The parsed parameter.
347
+ * @throws InvalidAbiSignatureError If the parameter is invalid, or isn't a
348
+ * single one.
349
+ */
350
+ export function parseAbiParameter(parameter: string): AbiParameter {
351
+ return new AbiSignatureParser(parameter).parseSingleParameter();
352
+ }
353
+
354
+ /**
355
+ * Returns the selector of a function or error: the first 4 bytes of the
356
+ * keccak256 hash of its canonical signature.
357
+ *
358
+ * @param signature The parsed signature.
359
+ * @returns The 4-byte selector, like `0xa9059cbb`.
360
+ */
361
+ export async function getAbiSelector(
362
+ signature: AbiFunctionSignature,
363
+ ): Promise<PrefixedHexString> {
364
+ const hash = await hashCanonicalAbiSignature(signature);
365
+
366
+ return bytesToHexString(hash.subarray(0, 4));
367
+ }
368
+
369
+ /**
370
+ * Returns the topic of an event: the keccak256 hash of its canonical
371
+ * signature, which non-anonymous events log as their first topic.
372
+ *
373
+ * @param signature The parsed signature.
374
+ * @returns The 32-byte topic.
375
+ */
376
+ export async function getAbiEventTopic(
377
+ signature: AbiEventSignature,
378
+ ): Promise<PrefixedHexString> {
379
+ return bytesToHexString(await hashCanonicalAbiSignature(signature));
380
+ }
381
+
188
382
  export {
189
383
  AbiEncodingError,
190
384
  AbiEncodingFailedError,
191
385
  AbiParametersLengthMismatchError,
192
386
  AbiValueOutOfBoundsError,
193
387
  DuplicateAbiParameterNameError,
388
+ InvalidAbiSignatureError,
194
389
  InvalidAbiValueError,
195
390
  UnsupportedAbiTypeError,
196
391
  isAbiEncodingError,
392
+ isInvalidAbiSignatureError,
197
393
  type AbiEncodingErrorKind,
198
394
  type AnyAbiEncodingError,
199
395
  } from "./errors/abi.js";
package/src/bytes.ts CHANGED
@@ -34,7 +34,7 @@ export function setLengthLeft(bytes: Uint8Array, length: number): Uint8Array {
34
34
  return padded;
35
35
  }
36
36
 
37
- return bytes.subarray(-length);
37
+ return length === 0 ? bytes.subarray(0, 0) : bytes.subarray(-length);
38
38
  }
39
39
 
40
40
  /**
package/src/errors/abi.ts CHANGED
@@ -1,15 +1,23 @@
1
1
  import { CustomError } from "../error.js";
2
2
 
3
+ const ABI_ENCODING_ERROR_KINDS = [
4
+ "parameters-length-mismatch",
5
+ "invalid-value",
6
+ "value-out-of-bounds",
7
+ "unsupported-type",
8
+ "duplicate-parameter-name",
9
+ "encoding-failed",
10
+ ] as const;
11
+
3
12
  /**
4
13
  * Discriminates the errors that ABI encoding can throw.
5
14
  */
6
- export type AbiEncodingErrorKind =
7
- | "parameters-length-mismatch"
8
- | "invalid-value"
9
- | "value-out-of-bounds"
10
- | "unsupported-type"
11
- | "duplicate-parameter-name"
12
- | "encoding-failed";
15
+ export type AbiEncodingErrorKind = (typeof ABI_ENCODING_ERROR_KINDS)[number];
16
+
17
+ // unknown so that any `kind` can be looked up without narrowing it first
18
+ const ABI_ENCODING_ERROR_KIND_SET: ReadonlySet<unknown> = new Set(
19
+ ABI_ENCODING_ERROR_KINDS,
20
+ );
13
21
 
14
22
  /**
15
23
  * Base class of every error thrown while ABI-encoding values.
@@ -142,15 +150,64 @@ export type AnyAbiEncodingError =
142
150
  | AbiEncodingFailedError;
143
151
 
144
152
  /**
145
- * Checks whether a value is the ABI encoding error of the given kind.
153
+ * Checks whether a value is an ABI encoding error, optionally of a given kind.
146
154
  *
147
155
  * @param error The value to check.
148
- * @param kind The kind of error to check for.
156
+ * @param kind The kind of error to check for. If omitted, any kind matches.
149
157
  * @returns True if the value is an ABI encoding error of that kind.
150
158
  */
159
+ export function isAbiEncodingError(
160
+ error: unknown,
161
+ ): error is AnyAbiEncodingError;
151
162
  export function isAbiEncodingError<KindT extends AbiEncodingErrorKind>(
152
163
  error: unknown,
153
164
  kind: KindT,
154
- ): error is Extract<AnyAbiEncodingError, { kind: KindT }> {
155
- return error instanceof Error && "kind" in error && error.kind === kind;
165
+ ): error is Extract<AnyAbiEncodingError, { kind: KindT }>;
166
+ export function isAbiEncodingError(
167
+ error: unknown,
168
+ kind?: AbiEncodingErrorKind,
169
+ ): error is AnyAbiEncodingError {
170
+ if (!(error instanceof Error) || !("kind" in error)) {
171
+ return false;
172
+ }
173
+
174
+ if (kind === undefined) {
175
+ return ABI_ENCODING_ERROR_KIND_SET.has(error.kind);
176
+ }
177
+
178
+ return error.kind === kind;
179
+ }
180
+
181
+ /**
182
+ * Thrown when a human-readable ABI signature can't be parsed.
183
+ *
184
+ * Consumers should discriminate with `isInvalidAbiSignatureError` rather than
185
+ * `instanceof`, for the same reason as `isAbiEncodingError`.
186
+ */
187
+ export class InvalidAbiSignatureError extends CustomError {
188
+ public readonly kind: "invalid-signature" = "invalid-signature";
189
+
190
+ constructor(
191
+ public readonly input: string,
192
+ public readonly reason: string,
193
+ ) {
194
+ super(`The ABI signature "${input}" is invalid: ${reason}.`);
195
+ }
196
+ }
197
+
198
+ /**
199
+ * Whether an error is an `InvalidAbiSignatureError`, even if thrown by another
200
+ * copy of this package.
201
+ *
202
+ * @param error The value to check.
203
+ * @returns Whether it's an `InvalidAbiSignatureError`.
204
+ */
205
+ export function isInvalidAbiSignatureError(
206
+ error: unknown,
207
+ ): error is InvalidAbiSignatureError {
208
+ return (
209
+ error instanceof Error &&
210
+ "kind" in error &&
211
+ error.kind === "invalid-signature"
212
+ );
156
213
  }
package/src/hex.ts CHANGED
@@ -101,8 +101,8 @@ export function bytesToHexString(bytes: Uint8Array): PrefixedHexString {
101
101
  /**
102
102
  * Converts a hexadecimal string to a Uint8Array. The string must be a valid
103
103
  * hexadecimal string. The string may be prefixed with "0x" or not. The empty
104
- * string is considered a valid hexadecimal string, so is the string "0x" and
105
- * will be converted to Uint8Array([0]).
104
+ * string is considered a valid hexadecimal string, so is the string "0x", and
105
+ * both are converted to an empty Uint8Array.
106
106
  *
107
107
  * @param hexString The hexadecimal string to convert.
108
108
  * @returns The byte representation of the hexadecimal string.
@@ -224,7 +224,7 @@ export function setLengthLeft(
224
224
 
225
225
  // if the string is longer than the desired length, truncate it
226
226
  if (unprefixedHexString.length > length) {
227
- return `0x${unprefixedHexString.slice(-length)}`;
227
+ return length === 0 ? "0x" : `0x${unprefixedHexString.slice(-length)}`;
228
228
  }
229
229
 
230
230
  const paddedHexString = unprefixedHexString.padStart(length, "0");