-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathabi.ts
876 lines (755 loc) · 23.7 KB
/
abi.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
import type {
EventFragment,
Fragment,
FunctionFragment,
Interface,
ParamType,
Result,
} from "ethers";
import { IgnitionError } from "../../errors";
import { Artifact } from "../../types/artifact";
import { ArgumentType, SolidityParameterType } from "../../types/module";
import { ERRORS } from "../errors-list";
import { assertIgnitionInvariant } from "../utils/assertions";
import { linkLibraries } from "./libraries";
import {
EvmExecutionResultTypes,
EvmTuple,
EvmValue,
FailedEvmExecutionResult,
InvalidResultError,
RevertWithCustomError,
RevertWithInvalidData,
RevertWithPanicCode,
RevertWithReason,
SuccessfulEvmExecutionResult,
} from "./types/evm-execution";
import { TransactionReceipt } from "./types/jsonrpc";
import { equalAddresses } from "./utils/address";
const REVERT_REASON_SIGNATURE = "0x08c379a0";
const PANIC_CODE_SIGNATURE = "0x4e487b71";
const PANIC_CODE_NAMES: { [key: number]: string | undefined } = {
[0x00]: "GENERIC_PANIC",
[0x01]: "ASSERT_FALSE",
[0x11]: "OVERFLOW",
[0x12]: "DIVIDE_BY_ZERO",
[0x21]: "ENUM_RANGE_ERROR",
[0x22]: "BAD_STORAGE_DATA",
[0x31]: "STACK_UNDERFLOW",
[0x32]: "ARRAY_RANGE_ERROR",
[0x41]: "OUT_OF_MEMORY",
[0x51]: "UNINITIALIZED_FUNCTION_CALL",
};
/**
* Encodes the constructor arguments for a deployment.
*/
export function encodeDeploymentArguments(
artifact: Artifact,
args: SolidityParameterType[]
): string {
const { ethers } = require("ethers") as typeof import("ethers");
const iface = new ethers.Interface(artifact.abi);
const encodedArgs = iface.encodeDeploy(args);
return encodedArgs.slice(2);
}
/**
* Links the libraries in the artifact's deployment bytecode, encodes the constructor
* arguments and returns the result, which can be used as the `data` field of a
* deployment.
*/
export function encodeArtifactDeploymentData(
artifact: Artifact,
args: SolidityParameterType[],
libraries: { [libraryName: string]: string }
): string {
const linkedBytecode = linkLibraries(artifact, libraries);
const encodedArgs = encodeDeploymentArguments(artifact, args);
return linkedBytecode + encodedArgs;
}
/**
* Encodes a function call for the given artifact and function name.
*/
export function encodeArtifactFunctionCall(
artifact: Artifact,
functionName: string,
args: SolidityParameterType[]
): string {
const validationErrors = validateArtifactFunctionName(artifact, functionName);
if (validationErrors.length > 0) {
throw validationErrors[0];
}
const { ethers } = require("ethers") as typeof import("ethers");
const iface = new ethers.Interface(artifact.abi);
const functionFragment = getFunctionFragment(iface, functionName);
return iface.encodeFunctionData(functionFragment, args);
}
/**
* Decodes a custom error from the given return data, if it's recognized
* as one of the artifact's custom errors.
*/
export function decodeArtifactCustomError(
artifact: Artifact,
returnData: string
): RevertWithCustomError | RevertWithInvalidData | undefined {
const { ethers } = require("ethers") as typeof import("ethers");
const iface = ethers.Interface.from(artifact.abi);
const errorFragment = iface.fragments
.filter(ethers.Fragment.isError)
.find((ef) => returnData.startsWith(ef.selector));
if (errorFragment === undefined) {
return undefined;
}
try {
const decoded = iface.decodeErrorResult(errorFragment, returnData);
return {
type: EvmExecutionResultTypes.REVERT_WITH_CUSTOM_ERROR,
errorName: errorFragment.name,
args: ethersResultIntoEvmTuple(decoded, errorFragment.inputs),
};
} catch {
return {
type: EvmExecutionResultTypes.REVERT_WITH_INVALID_DATA,
data: returnData,
};
}
}
/**
* Decode the result of a successful function call.
*/
export function decodeArtifactFunctionCallResult(
artifact: Artifact,
functionName: string,
returnData: string
): InvalidResultError | SuccessfulEvmExecutionResult {
const validationErrors = validateArtifactFunctionName(artifact, functionName);
if (validationErrors.length > 0) {
throw validationErrors[0];
}
const { ethers } = require("ethers") as typeof import("ethers");
const iface = ethers.Interface.from(artifact.abi);
const functionFragment = getFunctionFragment(iface, functionName);
try {
const decoded = iface.decodeFunctionResult(functionFragment, returnData);
const values = ethersResultIntoEvmTuple(decoded, functionFragment.outputs);
return { type: EvmExecutionResultTypes.SUCESSFUL_RESULT, values };
} catch {
return {
type: EvmExecutionResultTypes.INVALID_RESULT_ERROR,
data: returnData,
};
}
}
/**
* Validate that the given args length matches the artifact's abi's args length.
*
* @param artifact - the artifact for the contract being validated
* @param contractName - the name of the contract for error messages
* @param args - the args to validate against
*/
export function validateContractConstructorArgsLength(
artifact: Artifact,
contractName: string,
args: ArgumentType[]
): IgnitionError[] {
const errors: IgnitionError[] = [];
const argsLength = args.length;
const { ethers } = require("ethers") as typeof import("ethers");
const iface = new ethers.Interface(artifact.abi);
const expectedArgsLength = iface.deploy.inputs.length;
if (argsLength !== expectedArgsLength) {
errors.push(
new IgnitionError(ERRORS.VALIDATION.INVALID_CONSTRUCTOR_ARGS_LENGTH, {
contractName,
argsLength,
expectedArgsLength,
})
);
}
return errors;
}
/**
* Validates that a function is valid for the given artifact. That means:
* - It's a valid function name
* - The function name exists in the artifact's ABI
* - If the function is not overlaoded, its bare name is used.
* - If the function is overloaded, the function name is includes the argument types
* in parentheses.
* - The function has the correct number of arguments
*
* Optionally checks further static call constraints:
* - The function is has a pure or view state mutability
*/
export function validateArtifactFunction(
artifact: Artifact,
contractName: string,
functionName: string,
args: ArgumentType[],
isStaticCall: boolean
): IgnitionError[] {
try {
validateOverloadedName(artifact, functionName, false);
} catch (e) {
assertIgnitionInvariant(
e instanceof IgnitionError,
"validateOverloadedName should only throw IgnitionErrors"
);
return [e];
}
const errors: IgnitionError[] = [];
const { ethers } = require("ethers") as typeof import("ethers");
const iface = new ethers.Interface(artifact.abi);
const fragment = getFunctionFragment(iface, functionName);
// Check that the number of arguments is correct
if (fragment.inputs.length !== args.length) {
errors.push(
new IgnitionError(ERRORS.VALIDATION.INVALID_FUNCTION_ARGS_LENGTH, {
functionName,
contractName,
argsLength: args.length,
expectedLength: fragment.inputs.length,
})
);
}
// Check that the function is pure or view, which is required for a static call
if (isStaticCall && !fragment.constant) {
errors.push(
new IgnitionError(ERRORS.VALIDATION.INVALID_STATIC_CALL, {
functionName,
contractName,
})
);
}
return errors;
}
/**
* Validates that a function name is valid for the given artifact. That means:
* - It's a valid function name
* - The function name exists in the artifact's ABI
* - If the function is not overlaoded, its bare name is used.
* - If the function is overloaded, the function name is includes the argument types
* in parentheses.
*/
export function validateArtifactFunctionName(
artifact: Artifact,
functionName: string
): IgnitionError[] {
try {
validateOverloadedName(artifact, functionName, false);
} catch (e) {
assertIgnitionInvariant(
e instanceof IgnitionError,
"validateOverloadedName should only throw IgnitionError"
);
return [e];
}
return [];
}
/**
* Validates that the event exists in the artifact, it's name is valid, handles overloads
* correctly, and that the arugment exists in the event.
*
* @param emitterArtifact The artifact of the contract emitting the event.
* @param eventName The name of the event.
* @param argument The argument name or index.
*/
export function validateArtifactEventArgumentParams(
emitterArtifact: Artifact,
eventName: string,
argument: string | number
): IgnitionError[] {
try {
validateOverloadedName(emitterArtifact, eventName, true);
} catch (e) {
assertIgnitionInvariant(
e instanceof IgnitionError,
"validateOverloadedName should only throw IgnitionError"
);
return [e];
}
const { ethers } = require("ethers") as typeof import("ethers");
const iface = new ethers.Interface(emitterArtifact.abi);
let eventFragment: EventFragment;
try {
eventFragment = getEventFragment(iface, eventName);
} catch (e) {
assertIgnitionInvariant(
e instanceof IgnitionError,
"getEventFragment should only throw IgnitionError"
);
return [e];
}
let paramType: ParamType;
try {
paramType = getEventArgumentParamType(
emitterArtifact.contractName,
eventName,
eventFragment,
argument
);
} catch (e) {
assertIgnitionInvariant(
e instanceof IgnitionError,
"getEventArgumentParamType should only throw IgnitionError"
);
return [e];
}
if (paramType.indexed === true) {
// We can't access the value of indexed arguments with dynamic size
// as their hash is stored in a topic, and its actual value isn't stored
// anywhere
if (hasDynamicSize(paramType)) {
return [
new IgnitionError(ERRORS.VALIDATION.INDEXED_EVENT_ARG, {
eventName,
argument,
contractName: emitterArtifact.contractName,
}),
];
}
}
return [];
}
/**
* Returns the value of an argument in an event emitted by the contract
* at emitterAddress with a certain artifact.
*
* @param receipt The receipt of the transaction that emitted the event.
* @param emitterArtifact The artifact of the contract emitting the event.
* @param emitterAddress The address of the contract emitting the event.
* @param eventName The name of the event. It MUST be validated first.
* @param eventIndex The index of the event, in case there are multiple events emitted with the same name
* @param argument The name or index of the argument to extract from the event.
* @returns The EvmValue of the argument.
*/
export function getEventArgumentFromReceipt(
receipt: TransactionReceipt,
emitterArtifact: Artifact,
emitterAddress: string,
eventName: string,
eventIndex: number,
nameOrIndex: string | number
): EvmValue {
const emitterLogs = receipt.logs.filter((l) =>
equalAddresses(l.address, emitterAddress)
);
const { ethers } = require("ethers") as typeof import("ethers");
const iface = new ethers.Interface(emitterArtifact.abi);
const eventFragment = getEventFragment(iface, eventName);
const eventLogs = emitterLogs.filter(
(l) => l.topics[0] === eventFragment.topicHash
);
const log = eventLogs[eventIndex];
const ethersResult = iface.decodeEventLog(
eventFragment,
log.data,
log.topics
);
const evmTuple = ethersResultIntoEvmTuple(ethersResult, eventFragment.inputs);
if (typeof nameOrIndex === "string") {
return evmTuple.named[nameOrIndex];
}
return evmTuple.positional[nameOrIndex];
}
/**
* Decodes an error from a failed evm execution.
*
* @param returnData The data, as returned by the JSON-RPC.
* @param customErrorReported A value indicating if the JSON-RPC error
* reported that it was due to a custom error.
* @param decodeCustomError A function that decodes custom errors, returning
* `RevertWithCustomError` if succesfully decoded, `RevertWithInvalidData`
* if a custom error was recognized but couldn't be decoded, and `undefined`
* it it wasn't recognized.
* @returns A `FailedEvmExecutionResult` with the decoded error.
*/
export function decodeError(
returnData: string,
customErrorReported: boolean,
decodeCustomError?: (
returnData: string
) => RevertWithCustomError | RevertWithInvalidData | undefined
): FailedEvmExecutionResult {
if (returnData === "0x") {
return { type: EvmExecutionResultTypes.REVERT_WITHOUT_REASON };
}
const revertWithReasonError = tryToDecodeReason(returnData);
if (revertWithReasonError !== undefined) {
return revertWithReasonError;
}
const revertWithPanicCodeError = tryToDecodePanicCode(returnData);
if (revertWithPanicCodeError !== undefined) {
return revertWithPanicCodeError;
}
if (decodeCustomError !== undefined) {
const decodedCustomError = decodeCustomError(returnData);
if (decodedCustomError !== undefined) {
return decodedCustomError;
}
}
if (customErrorReported === true) {
return {
type: EvmExecutionResultTypes.REVERT_WITH_UNKNOWN_CUSTOM_ERROR,
signature: returnData.slice(0, 10),
data: returnData,
};
}
return {
type: EvmExecutionResultTypes.REVERT_WITH_INVALID_DATA_OR_UNKNOWN_CUSTOM_ERROR,
signature: returnData.slice(0, 10),
data: returnData,
};
}
function tryToDecodeReason(
returnData: string
): RevertWithReason | RevertWithInvalidData | undefined {
if (!returnData.startsWith(REVERT_REASON_SIGNATURE)) {
return undefined;
}
const { ethers } = require("ethers") as typeof import("ethers");
const abiCoder = ethers.AbiCoder.defaultAbiCoder();
try {
const [reason] = abiCoder.decode(
["string"],
Buffer.from(returnData.slice(REVERT_REASON_SIGNATURE.length), "hex")
);
return {
type: EvmExecutionResultTypes.REVERT_WITH_REASON,
message: reason,
};
} catch {
return {
type: EvmExecutionResultTypes.REVERT_WITH_INVALID_DATA,
data: returnData,
};
}
}
function tryToDecodePanicCode(
returnData: string
): RevertWithPanicCode | RevertWithInvalidData | undefined {
if (!returnData.startsWith(PANIC_CODE_SIGNATURE)) {
return undefined;
}
const { ethers } = require("ethers") as typeof import("ethers");
const abiCoder = ethers.AbiCoder.defaultAbiCoder();
try {
const decoded = abiCoder.decode(
["uint256"],
Buffer.from(returnData.slice(REVERT_REASON_SIGNATURE.length), "hex")
);
const panicCode = Number(decoded[0]);
const panicName = PANIC_CODE_NAMES[panicCode];
if (panicName === undefined) {
return {
type: EvmExecutionResultTypes.REVERT_WITH_INVALID_DATA,
data: returnData,
};
}
return {
type: EvmExecutionResultTypes.REVERT_WITH_PANIC_CODE,
panicCode,
panicName,
};
} catch {
return {
type: EvmExecutionResultTypes.REVERT_WITH_INVALID_DATA,
data: returnData,
};
}
}
function ethersValueIntoEvmValue(
ethersValue: any,
paramType: ParamType
): EvmValue {
const { ethers } = require("ethers") as typeof import("ethers");
if (typeof ethersValue === "bigint") {
return ethersValue;
}
if (typeof ethersValue === "string") {
return ethersValue;
}
if (typeof ethersValue === "number") {
return BigInt(ethersValue);
}
if (typeof ethersValue === "boolean") {
return ethersValue;
}
if (ethersValue instanceof ethers.Result) {
if (paramType.baseType === "array") {
assertIgnitionInvariant(
paramType.arrayChildren !== null,
`[ethers.js values decoding] arrayChildren must be defined for array ${paramType.type}`
);
return ethersResultIntoEvmValueArray(
ethersValue,
paramType.arrayChildren
);
}
assertIgnitionInvariant(
paramType.components !== null,
`[ethers.js values decoding] components must be defined for tuple ${paramType.type}`
);
return ethersResultIntoEvmTuple(ethersValue, paramType.components);
}
throw new IgnitionError(ERRORS.GENERAL.UNSUPPORTED_DECODE, {
type: paramType.type,
value: JSON.stringify(ethersValue, undefined, 2),
});
}
function ethersResultIntoEvmValueArray(
result: Result,
elementParamType: ParamType
): EvmValue[] {
return Array.from(result).map((ethersValue) =>
ethersValueIntoEvmValue(ethersValue, elementParamType)
);
}
function ethersResultIntoEvmTuple(
result: Result,
paramsParamType: readonly ParamType[]
): EvmTuple {
const positional: EvmValue[] = [];
const named: Record<string, EvmValue> = {};
for (const [i, param] of paramsParamType.entries()) {
const transformedValue = ethersValueIntoEvmValue(result[i], param);
positional[i] = transformedValue;
if (param.name !== "") {
named[param.name] = transformedValue;
}
}
return { positional, named };
}
/**
* Returns a function fragment for the given function name in the given interface.
*
* @param iface The interface to search in.
* @param functionName The function name to search for. MUST be validated first.
*/
function getFunctionFragment(
iface: Interface,
functionName: string
): FunctionFragment {
const { ethers } = require("ethers") as typeof import("ethers");
const fragment = iface.fragments
.filter(ethers.Fragment.isFunction)
.find(
(fr) =>
fr.name === functionName ||
getFunctionNameWithParams(fr) === functionName
);
assertIgnitionInvariant(
fragment !== undefined,
"Called getFunctionFragment with an invalid function name"
);
return fragment;
}
/**
* Returns an event fragment for the given event name in the given interface.
*
* @param iface The interface to search in.
* @param eventName The event name to search for. MUST be validated first.
*/
function getEventFragment(iface: Interface, eventName: string): EventFragment {
const { ethers } = require("ethers") as typeof import("ethers");
// TODO: Add support for event overloading
const fragment = iface.fragments
.filter(ethers.Fragment.isEvent)
.find(
(fr) => fr.name === eventName || getEventNameWithParams(fr) === eventName
);
assertIgnitionInvariant(
fragment !== undefined,
"Called getEventFragment with an invalid event name"
);
return fragment;
}
function getFunctionNameWithParams(functionFragment: FunctionFragment): string {
return functionFragment.format("sighash");
}
function getEventNameWithParams(eventFragment: EventFragment): string {
return eventFragment.format("sighash");
}
/**
* Returns the bare name of a function or event name. The bare name is the
* function or event name without the parameter types.
*
* @param functionOrEventName The name, either with or without parames.
* @returns The bare name, or undefined if the given name is not valid.
*/
function getBareName(functionOrEventName: string): string | undefined {
const NAME_REGEX = /^[_\\$a-zA-Z][_\\$a-zA-Z0-9]*(\(.*\))?$/;
if (functionOrEventName.match(NAME_REGEX) === null) {
return undefined;
}
return functionOrEventName.includes("(")
? functionOrEventName.substring(0, functionOrEventName.indexOf("("))
: functionOrEventName;
}
function validateOverloadedName(
artifact: Artifact,
name: string,
isEvent: boolean
): void {
const eventOrFunction = isEvent ? "event" : "function";
const eventOrFunctionCapitalized = isEvent ? "Event" : "Function";
const bareName = getBareName(name);
if (bareName === undefined) {
throw new IgnitionError(ERRORS.VALIDATION.INVALID_OVERLOAD_NAME, {
eventOrFunction,
name,
});
}
const { ethers } = require("ethers") as typeof import("ethers");
const iface = new ethers.Interface(artifact.abi);
const fragments = iface.fragments
.filter((f: Fragment): f is EventFragment | FunctionFragment => {
if (isEvent) {
return ethers.Fragment.isEvent(f);
}
return ethers.Fragment.isFunction(f);
})
.filter((fragment) => fragment.name === bareName);
if (fragments.length === 0) {
throw new IgnitionError(ERRORS.VALIDATION.OVERLOAD_NOT_FOUND, {
name,
eventOrFunction: eventOrFunctionCapitalized,
contractName: artifact.contractName,
});
} else if (fragments.length === 1) {
// If it is not overloaded we force the user to use the bare name
// because having a single representation is more friendly with our reconciliation
// process.
if (bareName !== name) {
throw new IgnitionError(ERRORS.VALIDATION.REQUIRE_BARE_NAME, {
name,
bareName,
eventOrFunction: eventOrFunctionCapitalized,
contractName: artifact.contractName,
});
}
} else {
// If it's overloaded, we force the user to use the full name
const normalizedNames = fragments.map((f) => {
if (ethers.Fragment.isEvent(f)) {
return getEventNameWithParams(f);
}
return getFunctionNameWithParams(f);
});
const normalizedNameList = normalizedNames
.map((nn) => `* ${nn}`)
.join("\n");
if (bareName === name) {
throw new IgnitionError(ERRORS.VALIDATION.OVERLOAD_NAME_REQUIRED, {
name,
normalizedNameList,
eventOrFunction: eventOrFunctionCapitalized,
contractName: artifact.contractName,
});
}
if (!normalizedNames.includes(name)) {
throw new IgnitionError(ERRORS.VALIDATION.INVALID_OVERLOAD_GIVEN, {
name,
bareName,
normalizedNameList,
eventOrFunction: eventOrFunctionCapitalized,
contractName: artifact.contractName,
});
}
}
}
/**
* Returns teh param type of an event argument, throwing a validation error if it's not found.
* @param eventFragment
* @param argument
*/
function getEventArgumentParamType(
contractName: string,
eventName: string,
eventFragment: EventFragment,
argument: string | number
): ParamType {
if (typeof argument === "string") {
for (const input of eventFragment.inputs) {
if (input.name === argument) {
return input;
}
}
throw new IgnitionError(ERRORS.VALIDATION.EVENT_ARG_NOT_FOUND, {
eventName,
argument,
contractName,
});
}
const paramType = eventFragment.inputs[argument];
if (paramType === undefined) {
throw new IgnitionError(ERRORS.VALIDATION.INVALID_EVENT_ARG_INDEX, {
eventName,
argument,
contractName,
expectedLength: eventFragment.inputs.length,
});
}
return paramType;
}
/**
* Validates the param type of a static call return value, throwing a validation error if it's not found.
*/
export function validateFunctionArgumentParamType(
contractName: string,
functionName: string,
artifact: Artifact,
argument: string | number
): IgnitionError[] {
const { ethers } = require("ethers") as typeof import("ethers");
const iface = new ethers.Interface(artifact.abi);
let functionFragment: FunctionFragment;
try {
functionFragment = getFunctionFragment(iface, functionName);
} catch (e) {
assertIgnitionInvariant(
e instanceof IgnitionError,
"getFunctionFragment should only throw IgnitionError"
);
return [e];
}
if (typeof argument === "string") {
let hasArg = false;
for (const output of functionFragment.outputs) {
if (output.name === argument) {
hasArg = true;
}
}
if (!hasArg) {
return [
new IgnitionError(ERRORS.VALIDATION.FUNCTION_ARG_NOT_FOUND, {
functionName,
argument,
contractName,
}),
];
}
} else {
const paramType = functionFragment.outputs[argument];
if (paramType === undefined) {
return [
new IgnitionError(ERRORS.VALIDATION.INVALID_FUNCTION_ARG_INDEX, {
functionName,
argument,
contractName,
expectedLength: functionFragment.outputs.length,
}),
];
}
}
return [];
}
/**
* Returns true if the given param type has a dynamic size.
*/
function hasDynamicSize(paramType: ParamType): boolean {
return (
paramType.isArray() ||
paramType.isTuple() ||
paramType.type === "bytes" ||
paramType.type === "string"
);
}