-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathfragments.ts
987 lines (796 loc) · 31 KB
/
fragments.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
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
"use strict";
import { BigNumber } from "@ethersproject/bignumber";
import { defineReadOnly } from "@ethersproject/properties";
import { Logger } from "@ethersproject/logger";
import { version } from "./_version";
const logger = new Logger(version);
export interface JsonFragmentType {
name?: string;
indexed?: boolean;
type?: string;
components?: Array<JsonFragmentType>;
}
export interface JsonFragment {
name?: string;
type?: string;
anonymous?: boolean;
payable?: boolean;
constant?: boolean;
stateMutability?: string;
inputs?: Array<JsonFragmentType>;
outputs?: Array<JsonFragmentType>;
gas?: string;
};
const _constructorGuard = { };
// AST Node parser state
type ParseState = {
allowArray?: boolean,
allowName?: boolean,
allowParams?: boolean,
allowType?: boolean,
readArray?: boolean,
};
// AST Node
type ParseNode = {
parent?: any,
type?: string,
name?: string,
state?: ParseState,
indexed?: boolean,
components?: Array<ParseNode>
};
let ModifiersBytes: { [ name: string ]: boolean } = { calldata: true, memory: true, storage: true };
let ModifiersNest: { [ name: string ]: boolean } = { calldata: true, memory: true };
function checkModifier(type: string, name: string): boolean {
if (type === "bytes" || type === "string") {
if (ModifiersBytes[name]) { return true; }
} else if (type === "address") {
if (name === "payable") { return true; }
} else if (type.indexOf("[") >= 0 || type === "tuple") {
if (ModifiersNest[name]) { return true; }
}
if (ModifiersBytes[name] || name === "payable") {
logger.throwArgumentError("invalid modifier", "name", name);
}
return false;
}
// @TODO: Make sure that children of an indexed tuple are marked with a null indexed
function parseParamType(param: string, allowIndexed: boolean): ParseNode {
let originalParam = param;
function throwError(i: number) {
logger.throwArgumentError(`unexpected character at position ${ i }`, "param", param);
}
param = param.replace(/\s/g, " ");
function newNode(parent: ParseNode): ParseNode {
let node: ParseNode = { type: "", name: "", parent: parent, state: { allowType: true } };
if (allowIndexed) { node.indexed = false; }
return node
}
let parent: ParseNode = { type: "", name: "", state: { allowType: true } };
let node = parent;
for (let i = 0; i < param.length; i++) {
let c = param[i];
switch (c) {
case "(":
if (node.state.allowType && node.type === "") {
node.type = "tuple";
} else if (!node.state.allowParams) {
throwError(i);
}
node.state.allowType = false;
node.type = verifyType(node.type);
node.components = [ newNode(node) ];
node = node.components[0];
break;
case ")":
delete node.state;
if (node.name === "indexed") {
if (!allowIndexed) { throwError(i); }
node.indexed = true;
node.name = "";
}
if (checkModifier(node.type, node.name)) { node.name = ""; }
node.type = verifyType(node.type);
let child = node;
node = node.parent;
if (!node) { throwError(i); }
delete child.parent;
node.state.allowParams = false;
node.state.allowName = true;
node.state.allowArray = true;
break;
case ",":
delete node.state;
if (node.name === "indexed") {
if (!allowIndexed) { throwError(i); }
node.indexed = true;
node.name = "";
}
if (checkModifier(node.type, node.name)) { node.name = ""; }
node.type = verifyType(node.type);
let sibling: ParseNode = newNode(node.parent);
//{ type: "", name: "", parent: node.parent, state: { allowType: true } };
node.parent.components.push(sibling);
delete node.parent;
node = sibling;
break;
// Hit a space...
case " ":
// If reading type, the type is done and may read a param or name
if (node.state.allowType) {
if (node.type !== "") {
node.type = verifyType(node.type);
delete node.state.allowType;
node.state.allowName = true;
node.state.allowParams = true;
}
}
// If reading name, the name is done
if (node.state.allowName) {
if (node.name !== "") {
if (node.name === "indexed") {
if (!allowIndexed) { throwError(i); }
if (node.indexed) { throwError(i); }
node.indexed = true;
node.name = "";
} else if (checkModifier(node.type, node.name)) {
node.name = "";
} else {
node.state.allowName = false;
}
}
}
break;
case "[":
if (!node.state.allowArray) { throwError(i); }
node.type += c;
node.state.allowArray = false;
node.state.allowName = false;
node.state.readArray = true;
break;
case "]":
if (!node.state.readArray) { throwError(i); }
node.type += c;
node.state.readArray = false;
node.state.allowArray = true;
node.state.allowName = true;
break;
default:
if (node.state.allowType) {
node.type += c;
node.state.allowParams = true;
node.state.allowArray = true;
} else if (node.state.allowName) {
node.name += c;
delete node.state.allowArray;
} else if (node.state.readArray) {
node.type += c;
} else {
throwError(i);
}
}
}
if (node.parent) { logger.throwArgumentError("unexpected eof", "param", param); }
delete parent.state;
if (node.name === "indexed") {
if (!allowIndexed) { throwError(originalParam.length - 7); }
if (node.indexed) { throwError(originalParam.length - 7); }
node.indexed = true;
node.name = "";
} else if (checkModifier(node.type, node.name)) {
node.name = "";
}
parent.type = verifyType(parent.type);
return parent;
}
function populate(object: any, params: any) {
for (let key in params) { defineReadOnly(object, key, params[key]); }
}
export const FormatTypes: { [ name: string ]: string } = Object.freeze({
// Bare formatting, as is needed for computing a sighash of an event or function
sighash: "sighash",
// Human-Readable with Minimal spacing and without names (compact human-readable)
minimal: "minimal",
// Human-Readble with nice spacing, including all names
full: "full",
// JSON-format a la Solidity
json: "json"
});
const paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/);
export class ParamType {
// The local name of the parameter (of null if unbound)
readonly name: string;
// The fully qualified type (e.g. "address", "tuple(address)", "uint256[3][]"
readonly type: string;
// The base type (e.g. "address", "tuple", "array")
readonly baseType: string;
// Indexable Paramters ONLY (otherwise null)
readonly indexed: boolean;
// Tuples ONLY: (otherwise null)
// - sub-components
readonly components: Array<ParamType>;
// Arrays ONLY: (otherwise null)
// - length of the array (-1 for dynamic length)
// - child type
readonly arrayLength: number;
readonly arrayChildren: ParamType;
readonly _isParamType: boolean;
constructor(constructorGuard: any, params: any) {
if (constructorGuard !== _constructorGuard) { logger.throwError("use fromString", Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new ParamType()"
}); }
populate(this, params);
let match = this.type.match(paramTypeArray);
if (match) {
populate(this, {
arrayLength: parseInt(match[2] || "-1"),
arrayChildren: ParamType.fromObject({
type: match[1],
components: this.components
}),
baseType: "array"
});
} else {
populate(this, {
arrayLength: null,
arrayChildren: null,
baseType: ((this.components != null) ? "tuple": this.type)
});
}
this._isParamType = true;
Object.freeze(this);
}
// Format the parameter fragment
// - sighash: "(uint256,address)"
// - minimal: "tuple(uint256,address) indexed"
// - full: "tuple(uint256 foo, addres bar) indexed baz"
format(format?: string): string {
if (!format) { format = FormatTypes.sighash; }
if (!FormatTypes[format]) {
logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
let result: any = {
type: ((this.baseType === "tuple") ? "tuple": this.type),
name: (this.name || undefined)
};
if (typeof(this.indexed) === "boolean") { result.indexed = this.indexed; }
if (this.components) {
result.components = this.components.map((comp) => JSON.parse(comp.format(format)));
}
return JSON.stringify(result);
}
let result = "";
// Array
if (this.baseType === "array") {
result += this.arrayChildren.format(format);
result += "[" + (this.arrayLength < 0 ? "": String(this.arrayLength)) + "]";
} else {
if (this.baseType === "tuple") {
if (format !== FormatTypes.sighash) {
result += this.type;
}
result += "(" + this.components.map(
(comp) => comp.format(format)
).join((format === FormatTypes.full) ? ", ": ",") + ")";
} else {
result += this.type;
}
}
if (format !== FormatTypes.sighash) {
if (this.indexed === true) { result += " indexed"; }
if (format === FormatTypes.full && this.name) {
result += " " + this.name;
}
}
return result;
}
static from(value: string | JsonFragmentType | ParamType, allowIndexed?: boolean): ParamType {
if (typeof(value) === "string") {
return ParamType.fromString(value, allowIndexed);
}
return ParamType.fromObject(value);
}
static fromObject(value: JsonFragmentType | ParamType): ParamType {
if (ParamType.isParamType(value)) { return value; }
return new ParamType(_constructorGuard, {
name: (value.name || null),
type: verifyType(value.type),
indexed: ((value.indexed == null) ? null: !!value.indexed),
components: (value.components ? value.components.map(ParamType.fromObject): null)
});
}
static fromString(value: string, allowIndexed?: boolean): ParamType {
function ParamTypify(node: ParseNode): ParamType {
return ParamType.fromObject({
name: node.name,
type: node.type,
indexed: node.indexed,
components: node.components
});
}
return ParamTypify(parseParamType(value, !!allowIndexed));
}
static isParamType(value: any): value is ParamType {
return !!(value != null && value._isParamType);
}
};
function parseParams(value: string, allowIndex: boolean): Array<ParamType> {
return splitNesting(value).map((param) => ParamType.fromString(param, allowIndex));
}
type TypeCheck<T> = { -readonly [ K in keyof T ]: T[K] };
interface _Fragment {
readonly type: string;
readonly name: string;
readonly inputs: Array<ParamType>;
}
export abstract class Fragment {
readonly type: string;
readonly name: string;
readonly inputs: Array<ParamType>;
readonly _isFragment: boolean;
constructor(constructorGuard: any, params: any) {
if (constructorGuard !== _constructorGuard) {
logger.throwError("use a static from method", Logger.errors.UNSUPPORTED_OPERATION, {
operation: "new Fragment()"
});
}
populate(this, params);
this._isFragment = true;
Object.freeze(this);
}
abstract format(format?: string): string;
static from(value: Fragment | JsonFragment | string): Fragment {
if (Fragment.isFragment(value)) { return value; }
if (typeof(value) === "string") {
return Fragment.fromString(value);
}
return Fragment.fromObject(value);
}
static fromObject(value: Fragment | JsonFragment): Fragment {
if (Fragment.isFragment(value)) { return value; }
switch (value.type) {
case "function":
return FunctionFragment.fromObject(value);
case "event":
return EventFragment.fromObject(value);
case "constructor":
return ConstructorFragment.fromObject(value);
case "fallback":
case "receive":
// @TODO: Something? Maybe return a FunctionFragment? A custom DefaultFunctionFragment?
return null;
}
return logger.throwArgumentError("invalid fragment object", "value", value);
}
static fromString(value: string): Fragment {
// Make sure the "returns" is surrounded by a space and all whitespace is exactly one space
value = value.replace(/\s/g, " ");
value = value.replace(/\(/g, " (").replace(/\)/g, ") ").replace(/\s+/g, " ");
value = value.trim();
if (value.split(" ")[0] === "event") {
return EventFragment.fromString(value.substring(5).trim());
} else if (value.split(" ")[0] === "function") {
return FunctionFragment.fromString(value.substring(8).trim());
} else if (value.split("(")[0].trim() === "constructor") {
return ConstructorFragment.fromString(value.trim());
}
return logger.throwArgumentError("unsupported fragment", "value", value);
}
static isFragment(value: any): value is Fragment {
return !!(value && value._isFragment);
}
}
interface _EventFragment extends _Fragment {
readonly anonymous: boolean;
}
export class EventFragment extends Fragment {
readonly anonymous: boolean;
format(format?: string): string {
if (!format) { format = FormatTypes.sighash; }
if (!FormatTypes[format]) {
logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
return JSON.stringify({
type: "event",
anonymous: this.anonymous,
name: this.name,
inputs: this.inputs.map((input) => JSON.parse(input.format(format)))
});
}
let result = "";
if (format !== FormatTypes.sighash) {
result += "event ";
}
result += this.name + "(" + this.inputs.map(
(input) => input.format(format)
).join((format === FormatTypes.full) ? ", ": ",") + ") ";
if (format !== FormatTypes.sighash) {
if (this.anonymous) {
result += "anonymous ";
}
}
return result.trim();
}
static from(value: EventFragment | JsonFragment | string): EventFragment {
if (typeof(value) === "string") {
return EventFragment.fromString(value);
}
return EventFragment.fromObject(value);
}
static fromObject(value: JsonFragment | EventFragment): EventFragment {
if (EventFragment.isEventFragment(value)) { return value; }
if (value.type !== "event") {
logger.throwArgumentError("invalid event object", "value", value);
}
const params: TypeCheck<_EventFragment> = {
name: verifyIdentifier(value.name),
anonymous: value.anonymous,
inputs: (value.inputs ? value.inputs.map(ParamType.fromObject) : []),
type: "event"
};
return new EventFragment(_constructorGuard, params);
}
static fromString(value: string): EventFragment {
let match = value.match(regexParen);
if (!match) {
logger.throwArgumentError("invalid event string", "value", value);
}
let anonymous = false;
match[3].split(" ").forEach((modifier) => {
switch(modifier.trim()) {
case "anonymous":
anonymous = true;
break;
case "":
break;
default:
logger.warn("unknown modifier: " + modifier);
}
});
return EventFragment.fromObject({
name: match[1].trim(),
anonymous: anonymous,
inputs: parseParams(match[2], true),
type: "event"
});
}
static isEventFragment(value: any): value is EventFragment {
return (value && value._isFragment && value.type === "event");
}
}
function parseGas(value: string, params: any): string {
params.gas = null;
let comps = value.split("@");
if (comps.length !== 1) {
if (comps.length > 2) {
logger.throwArgumentError("invalid human-readable ABI signature", "value", value);
}
if (!comps[1].match(/^[0-9]+$/)) {
logger.throwArgumentError("invalid human-readable ABI signature gas", "value", value);
}
params.gas = BigNumber.from(comps[1]);
return comps[0];
}
return value;
}
function parseModifiers(value: string, params: any): void {
params.constant = false;
params.payable = false;
params.stateMutability = "nonpayable";
value.split(" ").forEach((modifier) => {
switch (modifier.trim()) {
case "constant":
params.constant = true;
break;
case "payable":
params.payable = true;
params.stateMutability = "payable";
break;
case "nonpayable":
params.payable = false;
params.stateMutability = "nonpayable";
break;
case "pure":
params.constant = true;
params.stateMutability = "pure";
break;
case "view":
params.constant = true;
params.stateMutability = "view";
break;
case "external":
case "public":
case "":
break;
default:
console.log("unknown modifier: " + modifier);
}
});
}
type StateInputValue = {
constant?: boolean;
payable?: boolean;
stateMutability?: string;
type?: string;
};
type StateOutputValue = {
constant: boolean;
payable: boolean;
stateMutability: string;
};
function verifyState(value: StateInputValue): StateOutputValue {
let result: any = {
constant: false,
payable: true,
stateMutability: "payable"
};
if (value.stateMutability != null) {
result.stateMutability = value.stateMutability;
// Set (and check things are consistent) the constant property
result.constant = (result.stateMutability === "view" || result.stateMutability === "pure");
if (value.constant != null) {
if ((!!value.constant) !== result.constant) {
logger.throwArgumentError("cannot have constant function with mutability " + result.stateMutability, "value", value);
}
}
// Set (and check things are consistent) the payable property
result.payable = (result.stateMutability === "payable");
if (value.payable != null) {
if ((!!value.payable) !== result.payable) {
logger.throwArgumentError("cannot have payable function with mutability " + result.stateMutability, "value", value);
}
}
} else if (value.payable != null) {
result.payable = !!value.payable;
// If payable we can assume non-constant; otherwise we can't assume
if (value.constant == null && !result.payable && value.type !== "constructor") {
logger.throwArgumentError("unable to determine stateMutability", "value", value);
}
result.constant = !!value.constant;
if (result.constant) {
result.stateMutability = "view";
} else {
result.stateMutability = (result.payable ? "payable": "nonpayable");
}
if (result.payable && result.constant) {
logger.throwArgumentError("cannot have constant payable function", "value", value);
}
} else if (value.constant != null) {
result.constant = !!value.constant;
result.payable = !result.constant;
result.stateMutability = (result.constant ? "view": "payable");
} else if (value.type !== "constructor") {
logger.throwArgumentError("unable to determine stateMutability", "value", value);
}
return result;
}
interface _ConstructorFragment extends _Fragment {
stateMutability: string;
payable: boolean;
gas?: BigNumber;
}
export class ConstructorFragment extends Fragment {
stateMutability: string;
payable: boolean;
gas?: BigNumber;
format(format?: string): string {
if (!format) { format = FormatTypes.sighash; }
if (!FormatTypes[format]) {
logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
return JSON.stringify({
type: "constructor",
stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability: undefined),
payble: this.payable,
gas: (this.gas ? this.gas.toNumber(): undefined),
inputs: this.inputs.map((input) => JSON.parse(input.format(format)))
});
}
if (format === FormatTypes.sighash) {
logger.throwError("cannot format a constructor for sighash", Logger.errors.UNSUPPORTED_OPERATION, {
operation: "format(sighash)"
});
}
let result = "constructor(" + this.inputs.map(
(input) => input.format(format)
).join((format === FormatTypes.full) ? ", ": ",") + ") ";
if (this.stateMutability && this.stateMutability !== "nonpayable") {
result += this.stateMutability + " ";
}
return result.trim();
}
static from(value: ConstructorFragment | JsonFragment | string): ConstructorFragment {
if (typeof(value) === "string") {
return ConstructorFragment.fromString(value);
}
return ConstructorFragment.fromObject(value);
}
static fromObject(value: ConstructorFragment | JsonFragment): ConstructorFragment {
if (ConstructorFragment.isConstructorFragment(value)) { return value; }
if (value.type !== "constructor") {
logger.throwArgumentError("invalid constructor object", "value", value);
}
let state = verifyState(value);
if (state.constant) {
logger.throwArgumentError("constructor cannot be constant", "value", value);
}
const params: TypeCheck<_ConstructorFragment> = {
name: null,
type: value.type,
inputs: (value.inputs ? value.inputs.map(ParamType.fromObject): []),
payable: state.payable,
stateMutability: state.stateMutability,
gas: (value.gas ? BigNumber.from(value.gas): null)
};
return new ConstructorFragment(_constructorGuard, params);
}
static fromString(value: string): ConstructorFragment {
let params: any = { type: "constructor" };
value = parseGas(value, params);
let parens = value.match(regexParen);
if (!parens || parens[1].trim() !== "constructor") {
logger.throwArgumentError("invalid constructor string", "value", value);
}
params.inputs = parseParams(parens[2].trim(), false);
parseModifiers(parens[3].trim(), params);
return ConstructorFragment.fromObject(params);
}
static isConstructorFragment(value: any): value is ConstructorFragment {
return (value && value._isFragment && value.type === "constructor");
}
}
interface _FunctionFragment extends _ConstructorFragment {
constant: boolean;
outputs?: Array<ParamType>;
}
export class FunctionFragment extends ConstructorFragment {
constant: boolean;
outputs?: Array<ParamType>;
format(format?: string): string {
if (!format) { format = FormatTypes.sighash; }
if (!FormatTypes[format]) {
logger.throwArgumentError("invalid format type", "format", format);
}
if (format === FormatTypes.json) {
return JSON.stringify({
type: "function",
name: this.name,
constant: this.constant,
stateMutability: ((this.stateMutability !== "nonpayable") ? this.stateMutability: undefined),
payble: this.payable,
gas: (this.gas ? this.gas.toNumber(): undefined),
inputs: this.inputs.map((input) => JSON.parse(input.format(format))),
ouputs: this.outputs.map((output) => JSON.parse(output.format(format))),
});
}
let result = "";
if (format !== FormatTypes.sighash) {
result += "function ";
}
result += this.name + "(" + this.inputs.map(
(input) => input.format(format)
).join((format === FormatTypes.full) ? ", ": ",") + ") ";
if (format !== FormatTypes.sighash) {
if (this.stateMutability) {
if (this.stateMutability !== "nonpayable") {
result += (this.stateMutability + " ");
}
} else if (this.constant) {
result += "view ";
}
if (this.outputs && this.outputs.length) {
result += "returns (" + this.outputs.map(
(output) => output.format(format)
).join(", ") + ") ";
}
if (this.gas != null) {
result += "@" + this.gas.toString() + " ";
}
}
return result.trim();
}
static from(value: FunctionFragment | JsonFragment | string): FunctionFragment {
if (typeof(value) === "string") {
return FunctionFragment.fromString(value);
}
return FunctionFragment.fromObject(value);
}
static fromObject(value: FunctionFragment | JsonFragment): FunctionFragment {
if (FunctionFragment.isFunctionFragment(value)) { return value; }
if (value.type !== "function") {
logger.throwArgumentError("invalid function object", "value", value);
}
let state = verifyState(value);
const params: TypeCheck<_FunctionFragment> = {
type: value.type,
name: verifyIdentifier(value.name),
constant: state.constant,
inputs: (value.inputs ? value.inputs.map(ParamType.fromObject): []),
outputs: (value.outputs ? value.outputs.map(ParamType.fromObject): [ ]),
payable: state.payable,
stateMutability: state.stateMutability,
gas: (value.gas ? BigNumber.from(value.gas): null)
};
return new FunctionFragment(_constructorGuard, params);
}
static fromString(value: string): FunctionFragment {
let params: any = { type: "function" };
value = parseGas(value, params);
let comps = value.split(" returns ");
if (comps.length > 2) {
logger.throwArgumentError("invalid function string", "value", value);
}
let parens = comps[0].match(regexParen);
if (!parens) {
logger.throwArgumentError("invalid function signature", "value", value);
}
params.name = parens[1].trim();
if (params.name) { verifyIdentifier(params.name); }
params.inputs = parseParams(parens[2], false);
parseModifiers(parens[3].trim(), params);
// We have outputs
if (comps.length > 1) {
let returns = comps[1].match(regexParen);
if (returns[1].trim() != "" || returns[3].trim() != "") {
logger.throwArgumentError("unexpected tokens", "value", value);
}
params.outputs = parseParams(returns[2], false);
} else {
params.outputs = [ ];
}
return FunctionFragment.fromObject(params);
}
static isFunctionFragment(value: any): value is FunctionFragment {
return (value && value._isFragment && value.type === "function");
}
}
//export class ErrorFragment extends Fragment {
//}
//export class StructFragment extends Fragment {
//}
function verifyType(type: string): string {
// These need to be transformed to their full description
if (type.match(/^uint($|[^1-9])/)) {
type = "uint256" + type.substring(4);
} else if (type.match(/^int($|[^1-9])/)) {
type = "int256" + type.substring(3);
}
// @TODO: more verification
return type;
}
const regexIdentifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$");
function verifyIdentifier(value: string): string {
if (!value || !value.match(regexIdentifier)) {
logger.throwArgumentError(`invalid identifier "${ value }"`, "value", value);
}
return value;
}
const regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$");
function splitNesting(value: string): Array<any> {
value = value.trim();
let result = [];
let accum = "";
let depth = 0;
for (let offset = 0; offset < value.length; offset++) {
let c = value[offset];
if (c === "," && depth === 0) {
result.push(accum);
accum = "";
} else {
accum += c;
if (c === "(") {
depth++;
} else if (c === ")") {
depth--;
if (depth === -1) {
logger.throwArgumentError("unbalanced parenthesis", "value", value);
}
}
}
}
if (accum) { result.push(accum); }
return result;
}