-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathfragments.ts
More file actions
1617 lines (1340 loc) · 51.5 KB
/
Copy pathfragments.ts
File metadata and controls
1617 lines (1340 loc) · 51.5 KB
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
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* A fragment is a single item from an ABI, which may represent any of:
*
* - [Functions](FunctionFragment)
* - [Events](EventFragment)
* - [Constructors](ConstructorFragment)
* - Custom [Errors](ErrorFragment)
* - [Fallback or Receive](FallbackFragment) functions
*
* @_subsection api/abi/abi-coder:Fragments [about-fragments]
*/
import {
defineProperties, getBigInt, getNumber,
assert, assertPrivate, assertArgument
} from "../utils/index.js";
import { id } from "../hash/index.js";
/**
* A Type description in a [JSON ABI format](link-solc-jsonabi).
*/
export interface JsonFragmentType {
/**
* The parameter name.
*/
readonly name?: string;
/**
* If the parameter is indexed.
*/
readonly indexed?: boolean;
/**
* The type of the parameter.
*/
readonly type?: string;
/**
* The internal Solidity type.
*/
readonly internalType?: string;
/**
* The components for a tuple.
*/
readonly components?: ReadonlyArray<JsonFragmentType>;
}
/**
* A fragment for a method, event or error in a [JSON ABI format](link-solc-jsonabi).
*/
export interface JsonFragment {
/**
* The name of the error, event, function, etc.
*/
readonly name?: string;
/**
* The type of the fragment (e.g. ``event``, ``"function"``, etc.)
*/
readonly type?: string;
/**
* If the event is anonymous.
*/
readonly anonymous?: boolean;
/**
* If the function is payable.
*/
readonly payable?: boolean;
/**
* If the function is constant.
*/
readonly constant?: boolean;
/**
* The mutability state of the function.
*/
readonly stateMutability?: string;
/**
* The input parameters.
*/
readonly inputs?: ReadonlyArray<JsonFragmentType>;
/**
* The output parameters.
*/
readonly outputs?: ReadonlyArray<JsonFragmentType>;
/**
* The gas limit to use when sending a transaction for this function.
*/
readonly gas?: string;
};
/**
* The format to serialize the output as.
*
* **``"sighash"``** - the bare formatting, used to compute the selector
* or topic hash; this format cannot be reversed (as it discards ``indexed``)
* so cannot by used to export an [[Interface]].
*
* **``"minimal"``** - Human-Readable ABI with minimal spacing and without
* names, so it is compact, but will result in Result objects that cannot
* be accessed by name.
*
* **``"full"``** - Full Human-Readable ABI, with readable spacing and names
* intact; this is generally the recommended format.
*
* **``"json"``** - The [JSON ABI format](link-solc-jsonabi).
*/
export type FormatType = "sighash" | "minimal" | "full" | "json";
// [ "a", "b" ] => { "a": 1, "b": 1 }
function setify(items: Array<string>): ReadonlySet<string> {
const result: Set<string> = new Set();
items.forEach((k) => result.add(k));
return Object.freeze(result);
}
const _kwVisibDeploy = "external public payable override";
const KwVisibDeploy = setify(_kwVisibDeploy.split(" "));
// Visibility Keywords
const _kwVisib = "constant external internal payable private public pure view override";
const KwVisib = setify(_kwVisib.split(" "));
const _kwTypes = "constructor error event fallback function receive struct";
const KwTypes = setify(_kwTypes.split(" "));
const _kwModifiers = "calldata memory storage payable indexed";
const KwModifiers = setify(_kwModifiers.split(" "));
const _kwOther = "tuple returns";
// All Keywords
const _keywords = [ _kwTypes, _kwModifiers, _kwOther, _kwVisib ].join(" ");
const Keywords = setify(_keywords.split(" "));
// Single character tokens
const SimpleTokens: Record<string, string> = {
"(": "OPEN_PAREN", ")": "CLOSE_PAREN",
"[": "OPEN_BRACKET", "]": "CLOSE_BRACKET",
",": "COMMA", "@": "AT"
};
// Parser regexes to consume the next token
const regexWhitespacePrefix = new RegExp("^(\\s*)");
const regexNumberPrefix = new RegExp("^([0-9]+)");
const regexIdPrefix = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)");
// Parser regexs to check validity
const regexId = new RegExp("^([a-zA-Z$_][a-zA-Z0-9$_]*)$");
const regexType = new RegExp("^(address|bool|bytes([0-9]*)|string|u?int([0-9]*))$");
/**
* @ignore:
*/
type Token = Readonly<{
// Type of token (e.g. TYPE, KEYWORD, NUMBER, etc)
type: string;
// Offset into the original source code
offset: number;
// Actual text content of the token
text: string;
// The parenthesis depth
depth: number;
// If a parenthesis, the offset (in tokens) that balances it
match: number;
// For parenthesis and commas, the offset (in tokens) to the
// previous/next parenthesis or comma in the list
linkBack: number;
linkNext: number;
// If a BRACKET, the value inside
value: number;
}>;
class TokenString {
#offset: number;
#tokens: ReadonlyArray<Token>;
get offset(): number { return this.#offset; }
get length(): number { return this.#tokens.length - this.#offset; }
constructor(tokens: ReadonlyArray<Token>) {
this.#offset = 0;
this.#tokens = tokens.slice();
}
clone(): TokenString { return new TokenString(this.#tokens); }
reset(): void { this.#offset = 0; }
#subTokenString(from: number = 0, to: number = 0): TokenString {
return new TokenString(this.#tokens.slice(from, to).map((t) => {
return Object.freeze(Object.assign({ }, t, {
match: (t.match - from),
linkBack: (t.linkBack - from),
linkNext: (t.linkNext - from),
}));
}));
}
// Pops and returns the value of the next token, if it is a keyword in allowed; throws if out of tokens
popKeyword(allowed: ReadonlySet<string>): string {
const top = this.peek();
if (top.type !== "KEYWORD" || !allowed.has(top.text)) { throw new Error(`expected keyword ${ top.text }`); }
return this.pop().text;
}
// Pops and returns the value of the next token if it is `type`; throws if out of tokens
popType(type: string): string {
if (this.peek().type !== type) {
const top = this.peek();
throw new Error(`expected ${ type }; got ${ top.type } ${ JSON.stringify(top.text) }`);
}
return this.pop().text;
}
// Pops and returns a "(" TOKENS ")"
popParen(): TokenString {
const top = this.peek();
if (top.type !== "OPEN_PAREN") { throw new Error("bad start"); }
const result = this.#subTokenString(this.#offset + 1, top.match + 1);
this.#offset = top.match + 1;
return result;
}
// Pops and returns the items within "(" ITEM1 "," ITEM2 "," ... ")"
popParams(): Array<TokenString> {
const top = this.peek();
if (top.type !== "OPEN_PAREN") { throw new Error("bad start"); }
const result: Array<TokenString> = [ ];
while(this.#offset < top.match - 1) {
const link = this.peek().linkNext;
result.push(this.#subTokenString(this.#offset + 1, link));
this.#offset = link;
}
this.#offset = top.match + 1;
return result;
}
// Returns the top Token, throwing if out of tokens
peek(): Token {
if (this.#offset >= this.#tokens.length) {
throw new Error("out-of-bounds");
}
return this.#tokens[this.#offset];
}
// Returns the next value, if it is a keyword in `allowed`
peekKeyword(allowed: ReadonlySet<string>): null | string {
const top = this.peekType("KEYWORD");
return (top != null && allowed.has(top)) ? top: null;
}
// Returns the value of the next token if it is `type`
peekType(type: string): null | string {
if (this.length === 0) { return null; }
const top = this.peek();
return (top.type === type) ? top.text: null;
}
// Returns the next token; throws if out of tokens
pop(): Token {
const result = this.peek();
this.#offset++;
return result;
}
toString(): string {
const tokens: Array<string> = [ ];
for (let i = this.#offset; i < this.#tokens.length; i++) {
const token = this.#tokens[i];
tokens.push(`${ token.type }:${ token.text }`);
}
return `<TokenString ${ tokens.join(" ") }>`
}
}
type Writeable<T> = { -readonly [P in keyof T]: T[P] };
function lex(text: string): TokenString {
const tokens: Array<Token> = [ ];
const throwError = (message: string) => {
const token = (offset < text.length) ? JSON.stringify(text[offset]): "$EOI";
throw new Error(`invalid token ${ token } at ${ offset }: ${ message }`);
};
let brackets: Array<number> = [ ];
let commas: Array<number> = [ ];
let offset = 0;
while (offset < text.length) {
// Strip off any leading whitespace
let cur = text.substring(offset);
let match = cur.match(regexWhitespacePrefix);
if (match) {
offset += match[1].length;
cur = text.substring(offset);
}
const token = { depth: brackets.length, linkBack: -1, linkNext: -1, match: -1, type: "", text: "", offset, value: -1 };
tokens.push(token);
let type = (SimpleTokens[cur[0]] || "");
if (type) {
token.type = type;
token.text = cur[0];
offset++;
if (type === "OPEN_PAREN") {
brackets.push(tokens.length - 1);
commas.push(tokens.length - 1);
} else if (type == "CLOSE_PAREN") {
if (brackets.length === 0) { throwError("no matching open bracket"); }
token.match = brackets.pop() as number;
(<Writeable<Token>>(tokens[token.match])).match = tokens.length - 1;
token.depth--;
token.linkBack = commas.pop() as number;
(<Writeable<Token>>(tokens[token.linkBack])).linkNext = tokens.length - 1;
} else if (type === "COMMA") {
token.linkBack = commas.pop() as number;
(<Writeable<Token>>(tokens[token.linkBack])).linkNext = tokens.length - 1;
commas.push(tokens.length - 1);
} else if (type === "OPEN_BRACKET") {
token.type = "BRACKET";
} else if (type === "CLOSE_BRACKET") {
// Remove the CLOSE_BRACKET
let suffix = (tokens.pop() as Token).text;
if (tokens.length > 0 && tokens[tokens.length - 1].type === "NUMBER") {
const value = (tokens.pop() as Token).text;
suffix = value + suffix;
(<Writeable<Token>>(tokens[tokens.length - 1])).value = getNumber(value);
}
if (tokens.length === 0 || tokens[tokens.length - 1].type !== "BRACKET") {
throw new Error("missing opening bracket");
}
(<Writeable<Token>>(tokens[tokens.length - 1])).text += suffix;
}
continue;
}
match = cur.match(regexIdPrefix);
if (match) {
token.text = match[1];
offset += token.text.length;
if (Keywords.has(token.text)) {
token.type = "KEYWORD";
continue;
}
if (token.text.match(regexType)) {
token.type = "TYPE";
continue;
}
token.type = "ID";
continue;
}
match = cur.match(regexNumberPrefix);
if (match) {
token.text = match[1];
token.type = "NUMBER";
offset += token.text.length;
continue;
}
throw new Error(`unexpected token ${ JSON.stringify(cur[0]) } at position ${ offset }`);
}
return new TokenString(tokens.map((t) => Object.freeze(t)));
}
// Check only one of `allowed` is in `set`
function allowSingle(set: ReadonlySet<string>, allowed: ReadonlySet<string>): void {
let included: Array<string> = [ ];
for (const key in allowed.keys()) {
if (set.has(key)) { included.push(key); }
}
if (included.length > 1) { throw new Error(`conflicting types: ${ included.join(", ") }`); }
}
// Functions to process a Solidity Signature TokenString from left-to-right for...
// ...the name with an optional type, returning the name
function consumeName(type: string, tokens: TokenString): string {
if (tokens.peekKeyword(KwTypes)) {
const keyword = tokens.pop().text;
if (keyword !== type) {
throw new Error(`expected ${ type }, got ${ keyword }`);
}
}
return tokens.popType("ID");
}
// ...all keywords matching allowed, returning the keywords
function consumeKeywords(tokens: TokenString, allowed?: ReadonlySet<string>): ReadonlySet<string> {
const keywords: Set<string> = new Set();
while (true) {
const keyword = tokens.peekType("KEYWORD");
if (keyword == null || (allowed && !allowed.has(keyword))) { break; }
tokens.pop();
if (keywords.has(keyword)) { throw new Error(`duplicate keywords: ${ JSON.stringify(keyword) }`); }
keywords.add(keyword);
}
return Object.freeze(keywords);
}
// ...all visibility keywords, returning the coalesced mutability
function consumeMutability(tokens: TokenString): "payable" | "nonpayable" | "view" | "pure" {
let modifiers = consumeKeywords(tokens, KwVisib);
// Detect conflicting modifiers
allowSingle(modifiers, setify("constant payable nonpayable".split(" ")));
allowSingle(modifiers, setify("pure view payable nonpayable".split(" ")));
// Process mutability states
if (modifiers.has("view")) { return "view"; }
if (modifiers.has("pure")) { return "pure"; }
if (modifiers.has("payable")) { return "payable"; }
if (modifiers.has("nonpayable")) { return "nonpayable"; }
// Process legacy `constant` last
if (modifiers.has("constant")) { return "view"; }
return "nonpayable";
}
// ...a parameter list, returning the ParamType list
function consumeParams(tokens: TokenString, allowIndexed?: boolean): Array<ParamType> {
return tokens.popParams().map((t) => ParamType.from(t, allowIndexed));
}
// ...a gas limit, returning a BigNumber or null if none
function consumeGas(tokens: TokenString): null | bigint {
if (tokens.peekType("AT")) {
tokens.pop();
if (tokens.peekType("NUMBER")) {
return getBigInt(tokens.pop().text);
}
throw new Error("invalid gas");
}
return null;
}
function consumeEoi(tokens: TokenString): void {
if (tokens.length) {
throw new Error(`unexpected tokens at offset ${ tokens.offset }: ${ tokens.toString() }`);
}
}
const regexArrayType = new RegExp(/^(.*)\[([0-9]*)\]$/);
function verifyBasicType(type: string): string {
const match = type.match(regexType);
assertArgument(match, "invalid type", "type", type);
if (type === "uint") { return "uint256"; }
if (type === "int") { return "int256"; }
if (match[2]) {
// bytesXX
const length = parseInt(match[2]);
assertArgument(length !== 0 && length <= 32, "invalid bytes length", "type", type);
} else if (match[3]) {
// intXX or uintXX
const size = parseInt(match[3] as string);
assertArgument(size !== 0 && size <= 256 && (size % 8) === 0, "invalid numeric width", "type", type);
}
return type;
}
// Make the Fragment constructors effectively private
const _guard = { };
/**
* When [walking](ParamType-walk) a [[ParamType]], this is called
* on each component.
*/
export type ParamTypeWalkFunc = (type: string, value: any) => any;
/**
* When [walking asynchronously](ParamType-walkAsync) a [[ParamType]],
* this is called on each component.
*/
export type ParamTypeWalkAsyncFunc = (type: string, value: any) => any | Promise<any>;
const internal = Symbol.for("_ethers_internal");
const ParamTypeInternal = "_ParamTypeInternal";
const ErrorFragmentInternal = "_ErrorInternal";
const EventFragmentInternal = "_EventInternal";
const ConstructorFragmentInternal = "_ConstructorInternal";
const FallbackFragmentInternal = "_FallbackInternal";
const FunctionFragmentInternal = "_FunctionInternal";
const StructFragmentInternal = "_StructInternal";
/**
* Each input and output of a [[Fragment]] is an Array of **ParamType**.
*/
export class ParamType {
/**
* The local name of the parameter (or ``""`` 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;
/**
* True if the parameters is indexed.
*
* For non-indexable types this is ``null``.
*/
readonly indexed!: null | boolean;
/**
* The components for the tuple.
*
* For non-tuple types this is ``null``.
*/
readonly components!: null | ReadonlyArray<ParamType>;
/**
* The array length, or ``-1`` for dynamic-lengthed arrays.
*
* For non-array types this is ``null``.
*/
readonly arrayLength!: null | number;
/**
* The type of each child in the array.
*
* For non-array types this is ``null``.
*/
readonly arrayChildren!: null | ParamType;
/**
* @private
*/
constructor(guard: any, name: string, type: string, baseType: string, indexed: null | boolean, components: null | ReadonlyArray<ParamType>, arrayLength: null | number, arrayChildren: null | ParamType) {
assertPrivate(guard, _guard, "ParamType");
Object.defineProperty(this, internal, { value: ParamTypeInternal });
if (components) { components = Object.freeze(components.slice()); }
if (baseType === "array") {
if (arrayLength == null || arrayChildren == null) {
throw new Error("");
}
} else if (arrayLength != null || arrayChildren != null) {
throw new Error("");
}
if (baseType === "tuple") {
if (components == null) { throw new Error(""); }
} else if (components != null) {
throw new Error("");
}
defineProperties<ParamType>(this, {
name, type, baseType, indexed, components, arrayLength, arrayChildren
});
}
/**
* Return a string representation of this type.
*
* For example,
*
* ``sighash" => "(uint256,address)"``
*
* ``"minimal" => "tuple(uint256,address) indexed"``
*
* ``"full" => "tuple(uint256 foo, address bar) indexed baz"``
*/
format(format?: FormatType): string {
if (format == null) { format = "sighash"; }
if (format === "json") {
const name = this.name || "";
if (this.isArray()) {
const result = JSON.parse(this.arrayChildren.format("json"));
result.name = name;
result.type += `[${ (this.arrayLength < 0 ? "": String(this.arrayLength)) }]`;
return JSON.stringify(result);
}
const result: any = {
type: ((this.baseType === "tuple") ? "tuple": this.type),
name
};
if (typeof(this.indexed) === "boolean") { result.indexed = this.indexed; }
if (this.isTuple()) {
result.components = this.components.map((c) => JSON.parse(c.format(format)));
}
return JSON.stringify(result);
}
let result = "";
// Array
if (this.isArray()) {
result += this.arrayChildren.format(format);
result += `[${ (this.arrayLength < 0 ? "": String(this.arrayLength)) }]`;
} else {
if (this.isTuple()) {
result += "(" + this.components.map(
(comp) => comp.format(format)
).join((format === "full") ? ", ": ",") + ")";
} else {
result += this.type;
}
}
if (format !== "sighash") {
if (this.indexed === true) { result += " indexed"; }
if (format === "full" && this.name) {
result += " " + this.name;
}
}
return result;
}
/**
* Returns true if %%this%% is an Array type.
*
* This provides a type gaurd ensuring that [[arrayChildren]]
* and [[arrayLength]] are non-null.
*/
isArray(): this is (ParamType & { arrayChildren: ParamType, arrayLength: number }) {
return (this.baseType === "array")
}
/**
* Returns true if %%this%% is a Tuple type.
*
* This provides a type gaurd ensuring that [[components]]
* is non-null.
*/
isTuple(): this is (ParamType & { components: ReadonlyArray<ParamType> }) {
return (this.baseType === "tuple");
}
/**
* Returns true if %%this%% is an Indexable type.
*
* This provides a type gaurd ensuring that [[indexed]]
* is non-null.
*/
isIndexable(): this is (ParamType & { indexed: boolean }) {
return (this.indexed != null);
}
/**
* Walks the **ParamType** with %%value%%, calling %%process%%
* on each type, destructing the %%value%% recursively.
*/
walk(value: any, process: ParamTypeWalkFunc): any {
if (this.isArray()) {
if (!Array.isArray(value)) { throw new Error("invalid array value"); }
if (this.arrayLength !== -1 && value.length !== this.arrayLength) {
throw new Error("array is wrong length");
}
const _this = this;
return value.map((v) => (_this.arrayChildren.walk(v, process)));
}
if (this.isTuple()) {
if (!Array.isArray(value)) { throw new Error("invalid tuple value"); }
if (value.length !== this.components.length) {
throw new Error("array is wrong length");
}
const _this = this;
return value.map((v, i) => (_this.components[i].walk(v, process)));
}
return process(this.type, value);
}
#walkAsync(promises: Array<Promise<void>>, value: any, process: ParamTypeWalkAsyncFunc, setValue: (value: any) => void): void {
if (this.isArray()) {
if (!Array.isArray(value)) { throw new Error("invalid array value"); }
if (this.arrayLength !== -1 && value.length !== this.arrayLength) {
throw new Error("array is wrong length");
}
const childType = this.arrayChildren;
const result = value.slice();
result.forEach((value, index) => {
childType.#walkAsync(promises, value, process, (value: any) => {
result[index] = value;
});
});
setValue(result);
return;
}
if (this.isTuple()) {
const components = this.components;
// Convert the object into an array
let result: Array<any>;
if (Array.isArray(value)) {
result = value.slice();
} else {
if (value == null || typeof(value) !== "object") {
throw new Error("invalid tuple value");
}
result = components.map((param) => {
if (!param.name) { throw new Error("cannot use object value with unnamed components"); }
if (!(param.name in value)) {
throw new Error(`missing value for component ${ param.name }`);
}
return value[param.name];
});
}
if (result.length !== this.components.length) {
throw new Error("array is wrong length");
}
result.forEach((value, index) => {
components[index].#walkAsync(promises, value, process, (value: any) => {
result[index] = value;
});
});
setValue(result);
return;
}
const result = process(this.type, value);
if (result.then) {
promises.push((async function() { setValue(await result); })());
} else {
setValue(result);
}
}
/**
* Walks the **ParamType** with %%value%%, asynchronously calling
* %%process%% on each type, destructing the %%value%% recursively.
*
* This can be used to resolve ENS names by walking and resolving each
* ``"address"`` type.
*/
async walkAsync(value: any, process: ParamTypeWalkAsyncFunc): Promise<any> {
const promises: Array<Promise<void>> = [ ];
const result: [ any ] = [ value ];
this.#walkAsync(promises, value, process, (value: any) => {
result[0] = value;
});
if (promises.length) { await Promise.all(promises); }
return result[0];
}
/**
* Creates a new **ParamType** for %%obj%%.
*
* If %%allowIndexed%% then the ``indexed`` keyword is permitted,
* otherwise the ``indexed`` keyword will throw an error.
*/
static from(obj: any, allowIndexed?: boolean): ParamType {
if (ParamType.isParamType(obj)) { return obj; }
if (typeof(obj) === "string") {
try {
return ParamType.from(lex(obj), allowIndexed);
} catch (error) {
assertArgument(false, "invalid param type", "obj", obj);
}
} else if (obj instanceof TokenString) {
let type = "", baseType = "";
let comps: null | Array<ParamType> = null;
if (consumeKeywords(obj, setify([ "tuple" ])).has("tuple") || obj.peekType("OPEN_PAREN")) {
// Tuple
baseType = "tuple";
comps = obj.popParams().map((t) => ParamType.from(t));
type = `tuple(${ comps.map((c) => c.format()).join(",") })`;
} else {
// Normal
type = verifyBasicType(obj.popType("TYPE"));
baseType = type;
}
// Check for Array
let arrayChildren: null | ParamType = null;
let arrayLength: null | number = null;
while (obj.length && obj.peekType("BRACKET")) {
const bracket = obj.pop(); //arrays[i];
arrayChildren = new ParamType(_guard, "", type, baseType, null, comps, arrayLength, arrayChildren);
arrayLength = bracket.value;
type += bracket.text;
baseType = "array";
comps = null;
}
let indexed: null | boolean = null;
const keywords = consumeKeywords(obj, KwModifiers);
if (keywords.has("indexed")) {
if (!allowIndexed) { throw new Error(""); }
indexed = true;
}
const name = (obj.peekType("ID") ? obj.pop().text: "");
if (obj.length) { throw new Error("leftover tokens"); }
return new ParamType(_guard, name, type, baseType, indexed, comps, arrayLength, arrayChildren);
}
const name = obj.name;
assertArgument(!name || (typeof(name) === "string" && name.match(regexId)),
"invalid name", "obj.name", name);
let indexed = obj.indexed;
if (indexed != null) {
assertArgument(allowIndexed, "parameter cannot be indexed", "obj.indexed", obj.indexed);
indexed = !!indexed;
}
let type = obj.type;
let arrayMatch = type.match(regexArrayType);
if (arrayMatch) {
const arrayLength = parseInt(arrayMatch[2] || "-1");
const arrayChildren = ParamType.from({
type: arrayMatch[1],
components: obj.components
});
return new ParamType(_guard, name || "", type, "array", indexed, null, arrayLength, arrayChildren);
}
if (type === "tuple" || type.startsWith("tuple("/* fix: ) */) || type.startsWith("(" /* fix: ) */)) {
const comps = (obj.components != null) ? obj.components.map((c: any) => ParamType.from(c)): null;
const tuple = new ParamType(_guard, name || "", type, "tuple", indexed, comps, null, null);
// @TODO: use lexer to validate and normalize type
return tuple;
}
type = verifyBasicType(obj.type);
return new ParamType(_guard, name || "", type, type, indexed, null, null, null);
}
/**
* Returns true if %%value%% is a **ParamType**.
*/
static isParamType(value: any): value is ParamType {
return (value && value[internal] === ParamTypeInternal);
}
}
/**
* The type of a [[Fragment]].
*/
export type FragmentType = "constructor" | "error" | "event" | "fallback" | "function" | "struct";
/**
* An abstract class to represent An individual fragment from a parse ABI.
*/
export abstract class Fragment {
/**
* The type of the fragment.
*/
readonly type!: FragmentType;
/**
* The inputs for the fragment.
*/
readonly inputs!: ReadonlyArray<ParamType>;
/**
* @private
*/
constructor(guard: any, type: FragmentType, inputs: ReadonlyArray<ParamType>) {
assertPrivate(guard, _guard, "Fragment");
inputs = Object.freeze(inputs.slice());
defineProperties<Fragment>(this, { type, inputs });
}
/**
* Returns a string representation of this fragment as %%format%%.
*/
abstract format(format?: FormatType): string;
/**
* Creates a new **Fragment** for %%obj%%, wich can be any supported
* ABI frgament type.
*/
static from(obj: any): Fragment {
if (typeof(obj) === "string") {
// Try parsing JSON...
try {
Fragment.from(JSON.parse(obj));
} catch (e) { }
// ...otherwise, use the human-readable lexer
return Fragment.from(lex(obj));
}
if (obj instanceof TokenString) {
// Human-readable ABI (already lexed)
const type = obj.peekKeyword(KwTypes);
switch (type) {
case "constructor": return ConstructorFragment.from(obj);
case "error": return ErrorFragment.from(obj);
case "event": return EventFragment.from(obj);
case "fallback": case "receive":
return FallbackFragment.from(obj);
case "function": return FunctionFragment.from(obj);
case "struct": return StructFragment.from(obj);
}
} else if (typeof(obj) === "object") {
// JSON ABI
switch (obj.type) {
case "constructor": return ConstructorFragment.from(obj);
case "error": return ErrorFragment.from(obj);
case "event": return EventFragment.from(obj);
case "fallback": case "receive":
return FallbackFragment.from(obj);
case "function": return FunctionFragment.from(obj);
case "struct": return StructFragment.from(obj);
}
assert(false, `unsupported type: ${ obj.type }`, "UNSUPPORTED_OPERATION", {
operation: "Fragment.from"
});
}
assertArgument(false, "unsupported frgament object", "obj", obj);
}
/**
* Returns true if %%value%% is a [[ConstructorFragment]].
*/
static isConstructor(value: any): value is ConstructorFragment {
return ConstructorFragment.isFragment(value);
}
/**
* Returns true if %%value%% is an [[ErrorFragment]].
*/
static isError(value: any): value is ErrorFragment {