All files / ethers.js/src.ts/abi interface.ts

78.04% Statements 992/1271
71.25% Branches 114/160
65.9% Functions 29/44
78.04% Lines 992/1271

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 12721x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                       1x 1x 1x 1x 1x 1x 1x 1x                                                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x             1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x   67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 488x 488x 488x     488x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 488x 488x 488x 3x       3x 3x 3x 488x 488x 28x 12x 28x 16x 16x 16x 16x 16x 28x 488x 488x 425x 425x 425x 425x 488x 488x 27x 27x 27x 488x 488x 5x 5x 488x 488x   488x 457x 457x 457x 488x 457x 457x 67x 67x 67x 67x 64x 64x 64x 64x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x         67x 67x 67x 67x 67x 67x           67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 1018x 1018x 1018x 3x 3x 11x 11x 1x 1x 1015x 1015x 1018x 982x 982x 80606x 80606x 982x 982x 721x 721x 721x 721x 721x       721x 721x 721x 721x 60121x 60121x     60121x 721x 721x 721x 60121x 60121x 60141x 60141x 60000x 60000x 60141x         60000x 60000x 60141x 59400x 59400x 59400x 60141x 60121x 721x 982x 982x 982x 982x 24x 24x     24x 982x 982x 981x 982x       981x 981x 981x 33x 33x 33x 1018x 1x 1x 1x 67x 67x 67x 67x 67x 67x 250x 250x 250x 250x 67x 67x 67x 67x 67x 67x 67x 67x 67x 6x 6x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 762x 762x 67x 67x 67x 67x 67x               67x 67x 67x 67x 59x 59x 59x 28x 28x 47x 47x 1x 1x 31x 31x 59x 25x 25x 92x 92x 25x 25x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x 3x             3x 3x 3x 25x 25x 24x 25x       24x 24x 24x 6x 6x 6x 59x 1x 1x 1x 67x 67x 67x 67x 67x 67x 4x 4x 4x 4x 4x 67x 67x 67x 67x 67x 67x 67x 67x 67x 6x 6x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 49x 49x 67x 67x 67x 67x 67x               67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x                                                                                       67x 67x 67x 67x 67x               67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 1x 1x 67x 67x 257x 257x 67x 67x 67x 67x 67x 67x 3x 3x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x                       67x 67x 67x 67x 67x 67x 67x 67x 67x 67x                       67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 67x 67x 67x 67x 67x 67x 67x 254x 1x 1x 1x 1x 254x 254x 254x 254x 254x 254x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 250x 1x 1x 1x 1x 250x 250x 250x 250x 250x 250x 250x 250x     250x               67x 67x                                                                         67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 1x 1x 1x 1x 1x 1x 1x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 5x 2x 2x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 7x   7x     7x 7x   7x 1x 7x 1x 6x 5x 5x 5x 7x 7x 5x 5x 5x 8x 8x 8x 8x 1x 1x 1x 1x 7x 8x   8x   7x   7x 7x 7x 5x 5x 5x 5x     5x 5x 5x 67x 67x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 2x   2x   2x     2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 67x 67x 67x 37x 1x 1x 1x 1x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 41x 26x     26x 26x 26x 26x 41x 15x 15x 15x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 41x 41x 26x     26x     26x 26x 26x 26x     26x 41x 15x 15x 15x     15x 41x 41x 41x 37x 37x 37x 37x 67x 67x 67x 67x 67x 67x 67x 67x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 67x 67x     67x 67x 67x 67x 67x 67x 67x 67x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 67x 67x 67x 67x 67x 67x 67x 67x                   67x 67x 67x 67x 67x 67x 67x 67x 68x 68x 65x 65x 68x 65x 65x 68x     65x 65x 68x     65x 65x 65x 65x 67x  
/**
 *  The Interface class is a low-level class that accepts an
 *  ABI and provides all the necessary functionality to encode
 *  and decode paramaters to and results from methods, events
 *  and errors.
 *
 *  It also provides several convenience methods to automatically
 *  search and find matching transactions and events to parse them.
 *
 *  @_subsection api/abi:Interfaces  [interfaces]
 */
 
import { keccak256 } from "../crypto/index.js"
import { id } from "../hash/index.js"
import {
    concat, dataSlice, getBigInt, getBytes, getBytesCopy,
    hexlify, zeroPadBytes, zeroPadValue, isHexString, defineProperties,
    assertArgument, toBeHex, assert
} from "../utils/index.js";
 
import { AbiCoder } from "./abi-coder.js";
import { checkResultErrors, Result } from "./coders/abstract-coder.js";
import {
    ConstructorFragment, ErrorFragment, EventFragment, FallbackFragment,
    Fragment, FunctionFragment, ParamType
} from "./fragments.js";
import { Typed } from "./typed.js";
 
import type { BigNumberish, BytesLike, CallExceptionError, CallExceptionTransaction } from "../utils/index.js";
 
import type { JsonFragment } from "./fragments.js";
 
 
export { checkResultErrors, Result };
 
/**
 *  When using the [[Interface-parseLog]] to automatically match a Log to its event
 *  for parsing, a **LogDescription** is returned.
 */
export class LogDescription {
    /**
     *  The matching fragment for the ``topic0``.
     */
    readonly fragment!: EventFragment;
 
    /**
     *  The name of the Event.
     */
    readonly name!: string;
 
    /**
     *  The full Event signature.
     */
    readonly signature!: string;
 
    /**
     *  The topic hash for the Event.
     */
    readonly topic!: string;
 
    /**
     *  The arguments passed into the Event with ``emit``.
     */
    readonly args!: Result
 
    /**
     *  @_ignore:
     */
    constructor(fragment: EventFragment, topic: string, args: Result) {
        const name = fragment.name, signature = fragment.format();
        defineProperties<LogDescription>(this, {
            fragment, name, signature, topic, args
        });
    }
}
 
/**
 *  When using the [[Interface-parseTransaction]] to automatically match
 *  a transaction data to its function for parsing,
 *  a **TransactionDescription** is returned.
 */
export class TransactionDescription {
    /**
     *  The matching fragment from the transaction ``data``.
     */
    readonly fragment!: FunctionFragment;
 
    /**
     *  The name of the Function from the transaction ``data``.
     */
    readonly name!: string;
 
    /**
     *  The arguments passed to the Function from the transaction ``data``.
     */
    readonly args!: Result;
 
    /**
     *  The full Function signature from the transaction ``data``.
     */
    readonly signature!: string;
 
    /**
     *  The selector for the Function from the transaction ``data``.
     */
    readonly selector!: string;
 
    /**
     *  The ``value`` (in wei) from the transaction.
     */
    readonly value!: bigint;
 
    /**
     *  @_ignore:
     */
    constructor(fragment: FunctionFragment, selector: string, args: Result, value: bigint) {
        const name = fragment.name, signature = fragment.format();
        defineProperties<TransactionDescription>(this, {
            fragment, name, args, signature, selector, value
        });
    }
}
 
/**
 *  When using the [[Interface-parseError]] to automatically match an
 *  error for a call result for parsing, an **ErrorDescription** is returned.
 */
export class ErrorDescription {
    /**
     *  The matching fragment.
     */
    readonly fragment!: ErrorFragment;

    /**
     *  The name of the Error.
     */
    readonly name!: string;

    /**
     *  The arguments passed to the Error with ``revert``.
     */
    readonly args!: Result;

    /**
     *  The full Error signature.
     */
    readonly signature!: string;

    /**
     *  The selector for the Error.
     */
    readonly selector!: string;

    /**
     *  @_ignore:
     */
    constructor(fragment: ErrorFragment, selector: string, args: Result) {
        const name = fragment.name, signature = fragment.format();
        defineProperties<ErrorDescription>(this, {
            fragment, name, args, signature, selector
        });
    }
}
 
/**
 *  An **Indexed** is used as a value when a value that does not
 *  fit within a topic (i.e. not a fixed-length, 32-byte type). It
 *  is the ``keccak256`` of the value, and used for types such as
 *  arrays, tuples, bytes and strings.
 */
export class Indexed {
    /**
     *  The ``keccak256`` of the value logged.
     */
    readonly hash!: null | string;

    /**
     *  @_ignore:
     */
    readonly _isIndexed!: boolean;

    /**
     *  Returns ``true`` if %%value%% is an **Indexed**.
     *
     *  This provides a Type Guard for property access.
     */
    static isIndexed(value: any): value is Indexed {
        return !!(value && value._isIndexed);
    }

    /**
     *  @_ignore:
     */
    constructor(hash: null | string) {
        defineProperties<Indexed>(this, { hash, _isIndexed: true })
    }
}
 
type ErrorInfo = {
    signature: string,
    inputs: Array<string>,
    name: string,
    reason: (...args: Array<any>) => string;
};
 
// https://docs.soliditylang.org/en/v0.8.13/control-structures.html?highlight=panic#panic-via-assert-and-error-via-require
const PanicReasons: Record<string, string> = {
    "0": "generic panic",
    "1": "assert(false)",
    "17": "arithmetic overflow",
    "18": "division or modulo by zero",
    "33": "enum overflow",
    "34": "invalid encoded storage byte array accessed",
    "49": "out-of-bounds array access; popping on an empty array",
    "50": "out-of-bounds access of an array or bytesN",
    "65": "out of memory",
    "81": "uninitialized function",
}
 
const BuiltinErrors: Record<string, ErrorInfo> = {
    "0x08c379a0": {
        signature: "Error(string)",
        name: "Error",
        inputs: [ "string" ],
        reason: (message: string) => {
            return `reverted with reason string ${ JSON.stringify(message) }`;
        }
    },
    "0x4e487b71": {
        signature: "Panic(uint256)",
        name: "Panic",
        inputs: [ "uint256" ],
        reason: (code: bigint) => {
            let reason = "unknown panic code";
            if (code >= 0 && code <= 0xff && PanicReasons[code.toString()]) {
                reason = PanicReasons[code.toString()];
            }
            return `reverted with panic code 0x${ code.toString(16) } (${ reason })`;
        }
    }
}
 
/*
function wrapAccessError(property: string, error: Error): Error {
    const wrap = new Error(`deferred error during ABI decoding triggered accessing ${ property }`);
    (<any>wrap).error = error;
    return wrap;
}
*/
/*
function checkNames(fragment: Fragment, type: "input" | "output", params: Array<ParamType>): void {
    params.reduce((accum, param) => {
        if (param.name) {
            if (accum[param.name]) {
                logger.throwArgumentError(`duplicate ${ type } parameter ${ JSON.stringify(param.name) } in ${ fragment.format("full") }`, "fragment", fragment);
            }
            accum[param.name] = true;
        }
        return accum;
    }, <{ [ name: string ]: boolean }>{ });
}
*/
 
/**
 *  An **InterfaceAbi** may be any supported ABI format.
 *
 *  A string is expected to be a JSON string, which will be parsed
 *  using ``JSON.parse``. This means that the value **must** be a valid
 *  JSON string, with no stray commas, etc.
 *
 *  An array may contain any combination of:
 *  - Human-Readable fragments
 *  - Parsed JSON fragment
 *  - [[Fragment]] instances
 *
 *  A **Human-Readable Fragment** is a string which resembles a Solidity
 *  signature and is introduced in [this blog entry](link-ricmoo-humanreadableabi).
 *  For example, ``function balanceOf(address) view returns (uint)``.
 *
 *  A **Parsed JSON Fragment** is a JavaScript Object desribed in the
 *  [Solidity documentation](link-solc-jsonabi).
 */
export type InterfaceAbi = string | ReadonlyArray<Fragment | JsonFragment | string>;
 
/**
 *  An Interface abstracts many of the low-level details for
 *  encoding and decoding the data on the blockchain.
 *
 *  An ABI provides information on how to encode data to send to
 *  a Contract, how to decode the results and events and how to
 *  interpret revert errors.
 *
 *  The ABI can be specified by [any supported format](InterfaceAbi).
 */
export class Interface {
 
    /**
     *  All the Contract ABI members (i.e. methods, events, errors, etc).
     */
    readonly fragments!: ReadonlyArray<Fragment>;
 
    /**
     *  The Contract constructor.
     */
    readonly deploy!: ConstructorFragment;
 
    /**
     *  The Fallback method, if any.
     */
    readonly fallback!: null | FallbackFragment;
 
    /**
     *  If receiving ether is supported.
     */
    readonly receive!: boolean;
 
    #errors: Map<string, ErrorFragment>;
    #events: Map<string, EventFragment>;
    #functions: Map<string, FunctionFragment>;
//    #structs: Map<string, StructFragment>;
 
    #abiCoder: AbiCoder;
 
    /**
     *  Create a new Interface for the %%fragments%%.
     */
    constructor(fragments: InterfaceAbi) {
        let abi: ReadonlyArray<Fragment | JsonFragment | string> = [ ];
        if (typeof(fragments) === "string") {
            abi = JSON.parse(fragments);
        } else {
            abi = fragments;
        }
 
        this.#functions = new Map();
        this.#errors = new Map();
        this.#events = new Map();
//        this.#structs = new Map();
 
 
        const frags: Array<Fragment> = [ ];
        for (const a of abi) {
            try {
                frags.push(Fragment.from(a));
            } catch (error: any) {
                console.log(`[Warning] Invalid Fragment ${ JSON.stringify(a) }:`, error.message);
            }
        }
 
        defineProperties<Interface>(this, {
            fragments: Object.freeze(frags)
        });
 
        let fallback: null | FallbackFragment = null;
        let receive = false;
 
        this.#abiCoder = this.getAbiCoder();
 
        // Add all fragments by their signature
        this.fragments.forEach((fragment, index) => {
            let bucket: Map<string, Fragment>;
            switch (fragment.type) {
                case "constructor":
                    if (this.deploy) {
                        console.log("duplicate definition - constructor");
                        return;
                    }
                    //checkNames(fragment, "input", fragment.inputs);
                    defineProperties<Interface>(this, { deploy: <ConstructorFragment>fragment });
                    return;
 
                case "fallback":
                    if (fragment.inputs.length === 0) {
                        receive = true;
                    } else {
                        assertArgument(!fallback || (<FallbackFragment>fragment).payable !== fallback.payable,
                            "conflicting fallback fragments", `fragments[${ index }]`, fragment);
                        fallback = <FallbackFragment>fragment;
                        receive = fallback.payable;
                    }
                    return;
 
                case "function":
                    //checkNames(fragment, "input", fragment.inputs);
                    //checkNames(fragment, "output", (<FunctionFragment>fragment).outputs);
                    bucket = this.#functions;
                    break;
 
                case "event":
                    //checkNames(fragment, "input", fragment.inputs);
                    bucket = this.#events;
                    break;
 
                case "error":
                    bucket = this.#errors;
                    break;
 
                default:
                    return;
            }
 
            // Two identical entries; ignore it
            const signature = fragment.format();
            if (bucket.has(signature)) { return; }
 
            bucket.set(signature, fragment);
        });
 
        // If we do not have a constructor add a default
        if (!this.deploy) {
            defineProperties<Interface>(this, {
                deploy: ConstructorFragment.from("constructor()")
            });
        }
 
        defineProperties<Interface>(this, { fallback, receive });
    }
 
    /**
     *  Returns the entire Human-Readable ABI, as an array of
     *  signatures, optionally as %%minimal%% strings, which
     *  removes parameter names and unneceesary spaces.
     */
    format(minimal?: boolean): Array<string> {
        const format = (minimal ? "minimal": "full");
        const abi = this.fragments.map((f) => f.format(format));
        return abi;
    }
 
    /**
     *  Return the JSON-encoded ABI. This is the format Solidiy
     *  returns.
     */
    formatJson(): string {
        const abi = this.fragments.map((f) => f.format("json"));

        // We need to re-bundle the JSON fragments a bit
        return JSON.stringify(abi.map((j) => JSON.parse(j)));
    }
 
    /**
     *  The ABI coder that will be used to encode and decode binary
     *  data.
     */
    getAbiCoder(): AbiCoder {
        return AbiCoder.defaultAbiCoder();
    }
 
    // Find a function definition by any means necessary (unless it is ambiguous)
    #getFunction(key: string, values: null | Array<any | Typed>, forceUnique: boolean): null | FunctionFragment {
 
        // Selector
        if (isHexString(key)) {
            const selector = key.toLowerCase();
            for (const fragment of this.#functions.values()) {
                if (selector === fragment.selector) { return fragment; }
            }
            return null;
        }
 
        // It is a bare name, look up the function (will return null if ambiguous)
        if (key.indexOf("(") === -1) {
            const matching: Array<FunctionFragment> = [ ];
            for (const [ name, fragment ] of this.#functions) {
                if (name.split("("/* fix:) */)[0] === key) { matching.push(fragment); }
            }
 
            if (values) {
                const lastValue = (values.length > 0) ? values[values.length - 1]: null;
 
                let valueLength = values.length;
                let allowOptions = true;
                if (Typed.isTyped(lastValue) && lastValue.type === "overrides") {
                    allowOptions = false;
                    valueLength--;
                }
 
                // Remove all matches that don't have a compatible length. The args
                // may contain an overrides, so the match may have n or n - 1 parameters
                for (let i = matching.length - 1; i >= 0; i--) {
                    const inputs = matching[i].inputs.length;
                    if (inputs !== valueLength && (!allowOptions || inputs !== valueLength - 1)) {
                        matching.splice(i, 1);
                    }
                }
 
                // Remove all matches that don't match the Typed signature
                for (let i = matching.length - 1; i >= 0; i--) {
                    const inputs = matching[i].inputs;
                    for (let j = 0; j < values.length; j++) {
                        // Not a typed value
                        if (!Typed.isTyped(values[j])) { continue; }
 
                        // We are past the inputs
                        if (j >= inputs.length) {
                            if (values[j].type === "overrides") { continue; }
                            matching.splice(i, 1);
                            break;
                        }
 
                        // Make sure the value type matches the input type
                        if (values[j].type !== inputs[j].baseType) {
                            matching.splice(i, 1);
                            break;
                        }
                    }
                }
            }
 
            // We found a single matching signature with an overrides, but the
            // last value is something that cannot possibly be an options
            if (matching.length === 1 && values && values.length !== matching[0].inputs.length) {
                const lastArg = values[values.length - 1];
                if (lastArg == null || Array.isArray(lastArg) || typeof(lastArg) !== "object") {
                    matching.splice(0, 1);
                }
            }
 
            if (matching.length === 0) { return null; }
 
            if (matching.length > 1 && forceUnique) {
                const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
                assertArgument(false, `ambiguous function description (i.e. matches ${ matchStr })`, "key", key);
            }
 
            return matching[0];
        }
 
        // Normalize the signature and lookup the function
        const result = this.#functions.get(FunctionFragment.from(key).format());
        if (result) { return result; }
 
        return null;
    }
 
    /**
     *  Get the function name for %%key%%, which may be a function selector,
     *  function name or function signature that belongs to the ABI.
     */
    getFunctionName(key: string): string {
        const fragment = this.#getFunction(key, null, false);
        assertArgument(fragment, "no matching function", "key", key);
        return fragment.name;
    }
 
    /**
     *  Returns true if %%key%% (a function selector, function name or
     *  function signature) is present in the ABI.
     *
     *  In the case of a function name, the name may be ambiguous, so
     *  accessing the [[FunctionFragment]] may require refinement.
     */
    hasFunction(key: string): boolean {
        return !!this.#getFunction(key, null, false);
    }
 
    /**
     *  Get the [[FunctionFragment]] for %%key%%, which may be a function
     *  selector, function name or function signature that belongs to the ABI.
     *
     *  If %%values%% is provided, it will use the Typed API to handle
     *  ambiguous cases where multiple functions match by name.
     *
     *  If the %%key%% and %%values%% do not refine to a single function in
     *  the ABI, this will throw.
     */
    getFunction(key: string, values?: Array<any | Typed>): null | FunctionFragment {
        return this.#getFunction(key, values || null, true);
    }
 
    /**
     *  Iterate over all functions, calling %%callback%%, sorted by their name.
     */
    forEachFunction(callback: (func: FunctionFragment, index: number) => void): void {
        const names = Array.from(this.#functions.keys());
        names.sort((a, b) => a.localeCompare(b));
        for (let i = 0; i < names.length; i++) {
            const name = names[i];
            callback(<FunctionFragment>(this.#functions.get(name)), i);
        }
    }
 
 
    // Find an event definition by any means necessary (unless it is ambiguous)
    #getEvent(key: string, values: null | Array<null | any | Typed>, forceUnique: boolean): null | EventFragment {
 
        // EventTopic
        if (isHexString(key)) {
            const eventTopic = key.toLowerCase();
            for (const fragment of this.#events.values()) {
                if (eventTopic === fragment.topicHash) { return fragment; }
            }
            return null;
        }
 
        // It is a bare name, look up the function (will return null if ambiguous)
        if (key.indexOf("(") === -1) {
            const matching: Array<EventFragment> = [ ];
            for (const [ name, fragment ] of this.#events) {
                if (name.split("("/* fix:) */)[0] === key) { matching.push(fragment); }
            }
 
            if (values) {
                // Remove all matches that don't have a compatible length.
                for (let i = matching.length - 1; i >= 0; i--) {
                    if (matching[i].inputs.length < values.length) {
                        matching.splice(i, 1);
                    }
                }
 
                // Remove all matches that don't match the Typed signature
                for (let i = matching.length - 1; i >= 0; i--) {
                    const inputs = matching[i].inputs;
                    for (let j = 0; j < values.length; j++) {
                        // Not a typed value
                        if (!Typed.isTyped(values[j])) { continue; }

                        // Make sure the value type matches the input type
                        if (values[j].type !== inputs[j].baseType) {
                            matching.splice(i, 1);
                            break;
                        }
                    }
                }
            }
 
            if (matching.length === 0) { return null; }
 
            if (matching.length > 1 && forceUnique) {
                const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
                assertArgument(false, `ambiguous event description (i.e. matches ${ matchStr })`, "key", key);
            }
 
            return matching[0];
        }
 
        // Normalize the signature and lookup the function
        const result = this.#events.get(EventFragment.from(key).format());
        if (result) { return result; }
 
        return null;
    }
 
    /**
     *  Get the event name for %%key%%, which may be a topic hash,
     *  event name or event signature that belongs to the ABI.
     */
    getEventName(key: string): string {
        const fragment = this.#getEvent(key, null, false);
        assertArgument(fragment, "no matching event", "key", key);
 
        return fragment.name;
    }
 
    /**
     *  Returns true if %%key%% (an event topic hash, event name or
     *  event signature) is present in the ABI.
     *
     *  In the case of an event name, the name may be ambiguous, so
     *  accessing the [[EventFragment]] may require refinement.
     */
    hasEvent(key: string): boolean {
        return !!this.#getEvent(key, null, false);
    }
 
    /**
     *  Get the [[EventFragment]] for %%key%%, which may be a topic hash,
     *  event name or event signature that belongs to the ABI.
     *
     *  If %%values%% is provided, it will use the Typed API to handle
     *  ambiguous cases where multiple events match by name.
     *
     *  If the %%key%% and %%values%% do not refine to a single event in
     *  the ABI, this will throw.
     */
    getEvent(key: string, values?: Array<any | Typed>): null | EventFragment {
        return this.#getEvent(key, values || null, true)
    }
 
    /**
     *  Iterate over all events, calling %%callback%%, sorted by their name.
     */
    forEachEvent(callback: (func: EventFragment, index: number) => void): void {
        const names = Array.from(this.#events.keys());
        names.sort((a, b) => a.localeCompare(b));
        for (let i = 0; i < names.length; i++) {
            const name = names[i];
            callback(<EventFragment>(this.#events.get(name)), i);
        }
    }
 
    /**
     *  Get the [[ErrorFragment]] for %%key%%, which may be an error
     *  selector, error name or error signature that belongs to the ABI.
     *
     *  If %%values%% is provided, it will use the Typed API to handle
     *  ambiguous cases where multiple errors match by name.
     *
     *  If the %%key%% and %%values%% do not refine to a single error in
     *  the ABI, this will throw.
     */
    getError(key: string, values?: Array<any | Typed>): null | ErrorFragment {
        if (isHexString(key)) {
            const selector = key.toLowerCase();

            if (BuiltinErrors[selector]) {
                return ErrorFragment.from(BuiltinErrors[selector].signature);
            }

            for (const fragment of this.#errors.values()) {
                if (selector === fragment.selector) { return fragment; }
            }

            return null;
        }

        // It is a bare name, look up the function (will return null if ambiguous)
        if (key.indexOf("(") === -1) {
            const matching: Array<ErrorFragment> = [ ];
            for (const [ name, fragment ] of this.#errors) {
                if (name.split("("/* fix:) */)[0] === key) { matching.push(fragment); }
            }

            if (matching.length === 0) {
                if (key === "Error") { return ErrorFragment.from("error Error(string)"); }
                if (key === "Panic") { return ErrorFragment.from("error Panic(uint256)"); }
                return null;
            } else if (matching.length > 1) {
                const matchStr = matching.map((m) => JSON.stringify(m.format())).join(", ");
                assertArgument(false, `ambiguous error description (i.e. ${ matchStr })`, "name", key);
            }

            return matching[0];
        }

        // Normalize the signature and lookup the function
        key = ErrorFragment.from(key).format()
        if (key === "Error(string)") { return ErrorFragment.from("error Error(string)"); }
        if (key === "Panic(uint256)") { return ErrorFragment.from("error Panic(uint256)"); }

        const result = this.#errors.get(key);
        if (result) { return result; }

        return null;
    }
 
    /**
     *  Iterate over all errors, calling %%callback%%, sorted by their name.
     */
    forEachError(callback: (func: ErrorFragment, index: number) => void): void {
        const names = Array.from(this.#errors.keys());
        names.sort((a, b) => a.localeCompare(b));
        for (let i = 0; i < names.length; i++) {
            const name = names[i];
            callback(<ErrorFragment>(this.#errors.get(name)), i);
        }
    }
 
    // Get the 4-byte selector used by Solidity to identify a function
        /*
    getSelector(fragment: ErrorFragment | FunctionFragment): string {
        if (typeof(fragment) === "string") {
            const matches: Array<Fragment> = [ ];
 
            try { matches.push(this.getFunction(fragment)); } catch (error) { }
            try { matches.push(this.getError(<string>fragment)); } catch (_) { }
 
            if (matches.length === 0) {
                logger.throwArgumentError("unknown fragment", "key", fragment);
            } else if (matches.length > 1) {
                logger.throwArgumentError("ambiguous fragment matches function and error", "key", fragment);
            }
 
            fragment = matches[0];
        }
 
        return dataSlice(id(fragment.format()), 0, 4);
    }
        */
 
    // Get the 32-byte topic hash used by Solidity to identify an event
    /*
    getEventTopic(fragment: EventFragment): string {
        //if (typeof(fragment) === "string") { fragment = this.getEvent(eventFragment); }
        return id(fragment.format());
    }
    */
 
 
    _decodeParams(params: ReadonlyArray<ParamType>, data: BytesLike): Result {
        return this.#abiCoder.decode(params, data)
    }
 
    _encodeParams(params: ReadonlyArray<ParamType>, values: ReadonlyArray<any>): string {
        return this.#abiCoder.encode(params, values)
    }
 
    /**
     *  Encodes a ``tx.data`` object for deploying the Contract with
     *  the %%values%% as the constructor arguments.
     */
    encodeDeploy(values?: ReadonlyArray<any>): string {
        return this._encodeParams(this.deploy.inputs, values || [ ]);
    }
 
    /**
     *  Decodes the result %%data%% (e.g. from an ``eth_call``) for the
     *  specified error (see [[getError]] for valid values for
     *  %%key%%).
     *
     *  Most developers should prefer the [[parseCallResult]] method instead,
     *  which will automatically detect a ``CALL_EXCEPTION`` and throw the
     *  corresponding error.
     */
    decodeErrorResult(fragment: ErrorFragment | string, data: BytesLike): Result {
        if (typeof(fragment) === "string") {
            const f = this.getError(fragment);
            assertArgument(f, "unknown error", "fragment", fragment);
            fragment = f;
        }

        assertArgument(dataSlice(data, 0, 4) === fragment.selector,
            `data signature does not match error ${ fragment.name }.`, "data", data);

        return this._decodeParams(fragment.inputs, dataSlice(data, 4));
    }
 
    /**
     *  Encodes the transaction revert data for a call result that
     *  reverted from the the Contract with the sepcified %%error%%
     *  (see [[getError]] for valid values for %%fragment%%) with the %%values%%.
     *
     *  This is generally not used by most developers, unless trying to mock
     *  a result from a Contract.
     */
    encodeErrorResult(fragment: ErrorFragment | string, values?: ReadonlyArray<any>): string {
        if (typeof(fragment) === "string") {
            const f = this.getError(fragment);
            assertArgument(f, "unknown error", "fragment", fragment);
            fragment = f;
        }

        return concat([
            fragment.selector,
            this._encodeParams(fragment.inputs, values || [ ])
        ]);
    }
 
    /**
     *  Decodes the %%data%% from a transaction ``tx.data`` for
     *  the function specified (see [[getFunction]] for valid values
     *  for %%fragment%%).
     *
     *  Most developers should prefer the [[parseTransaction]] method
     *  instead, which will automatically detect the fragment.
     */
    decodeFunctionData(fragment: FunctionFragment | string, data: BytesLike): Result {
        if (typeof(fragment) === "string") {
            const f = this.getFunction(fragment);
            assertArgument(f, "unknown function", "fragment", fragment);
            fragment = f;
        }
 
        assertArgument(dataSlice(data, 0, 4) === fragment.selector,
            `data signature does not match function ${ fragment.name }.`, "data", data);
 
        return this._decodeParams(fragment.inputs, dataSlice(data, 4));
    }
 
    /**
     *  Encodes the ``tx.data`` for a transaction that calls the function
     *  specified (see [[getFunction]] for valid values for %%fragment%%) with
     *  the %%values%%.
     */
    encodeFunctionData(fragment: FunctionFragment | string, values?: ReadonlyArray<any>): string {
        if (typeof(fragment) === "string") {
            const f = this.getFunction(fragment);
            assertArgument(f, "unknown function", "fragment", fragment);
            fragment = f;
        }
 
        return concat([
            fragment.selector,
            this._encodeParams(fragment.inputs, values || [ ])
        ]);
    }
 
    /**
     *  Decodes the result %%data%% (e.g. from an ``eth_call``) for the
     *  specified function (see [[getFunction]] for valid values for
     *  %%key%%).
     *
     *  Most developers should prefer the [[parseCallResult]] method instead,
     *  which will automatically detect a ``CALL_EXCEPTION`` and throw the
     *  corresponding error.
     */
    decodeFunctionResult(fragment: FunctionFragment | string, data: BytesLike): Result {
        if (typeof(fragment) === "string") {
            const f = this.getFunction(fragment);
            assertArgument(f, "unknown function", "fragment", fragment);
            fragment = f;
        }
 
        let message = "invalid length for result data";
 
        const bytes = getBytesCopy(data);
        if ((bytes.length % 32) === 0) {
            try {
                return this.#abiCoder.decode(fragment.outputs, bytes);
            } catch (error) {
                message = "could not decode result data";
            }
        }

        // Call returned data with no error, but the data is junk
        assert(false, message, "BAD_DATA", {
            value: hexlify(bytes),
            info: { method: fragment.name, signature: fragment.format() }
        });
    }
 
    makeError(_data: BytesLike, tx: CallExceptionTransaction): CallExceptionError {
        const data = getBytes(_data, "data");

        const error = AbiCoder.getBuiltinCallException("call", tx, data);

        // Not a built-in error; try finding a custom error
        const customPrefix = "execution reverted (unknown custom error)";
        if (error.message.startsWith(customPrefix)) {
            const selector = hexlify(data.slice(0, 4));

            const ef = this.getError(selector);
            if (ef) {
                try {
                    const args = this.#abiCoder.decode(ef.inputs, data.slice(4));
                    error.revert = {
                        name: ef.name, signature: ef.format(), args
                    };
                    error.reason = error.revert.signature;
                    error.message = `execution reverted: ${ error.reason }`
                 } catch (e) {
                    error.message = `execution reverted (coult not decode custom error)`
                }
            }
        }

        // Add the invocation, if available
        const parsed = this.parseTransaction(tx);
        if (parsed) {
            error.invocation = {
                method: parsed.name,
                signature: parsed.signature,
                args: parsed.args
            };
        }

        return error;
    }
 
    /**
     *  Encodes the result data (e.g. from an ``eth_call``) for the
     *  specified function (see [[getFunction]] for valid values
     *  for %%fragment%%) with %%values%%.
     *
     *  This is generally not used by most developers, unless trying to mock
     *  a result from a Contract.
     */
    encodeFunctionResult(fragment: FunctionFragment | string, values?: ReadonlyArray<any>): string {
        if (typeof(fragment) === "string") {
            const f = this.getFunction(fragment);
            assertArgument(f, "unknown function", "fragment", fragment);
            fragment = f;
        }
        return hexlify(this.#abiCoder.encode(fragment.outputs, values || [ ]));
    }
/*
    spelunk(inputs: Array<ParamType>, values: ReadonlyArray<any>, processfunc: (type: string, value: any) => Promise<any>): Promise<Array<any>> {
        const promises: Array<Promise<>> = [ ];
        const process = function(type: ParamType, value: any): any {
            if (type.baseType === "array") {
                return descend(type.child
            }
            if (type. === "address") {
            }
        };
 
        const descend = function (inputs: Array<ParamType>, values: ReadonlyArray<any>) {
            if (inputs.length !== values.length) { throw new Error("length mismatch"); }
            
        };
 
        const result: Array<any> = [ ];
        values.forEach((value, index) => {
            if (value == null) {
                topics.push(null);
            } else if (param.baseType === "array" || param.baseType === "tuple") {
                logger.throwArgumentError("filtering with tuples or arrays not supported", ("contract." + param.name), value);
            } else if (Array.isArray(value)) {
                topics.push(value.map((value) => encodeTopic(param, value)));
            } else {
                topics.push(encodeTopic(param, value));
            }
        });
    }
*/
    // Create the filter for the event with search criteria (e.g. for eth_filterLog)
    encodeFilterTopics(fragment: EventFragment | string, values: ReadonlyArray<any>): Array<null | string | Array<string>> {
        if (typeof(fragment) === "string") {
            const f = this.getEvent(fragment);
            assertArgument(f, "unknown event", "eventFragment", fragment);
            fragment = f;
        }
 
        assert(values.length <= fragment.inputs.length, `too many arguments for ${ fragment.format() }`,
            "UNEXPECTED_ARGUMENT", { count: values.length, expectedCount: fragment.inputs.length })
 
        const topics: Array<null | string | Array<string>> = [];
        if (!fragment.anonymous) { topics.push(fragment.topicHash); }
 
        // @TODO: Use the coders for this; to properly support tuples, etc.
        const encodeTopic = (param: ParamType, value: any): string => {
            if (param.type === "string") {
                 return id(value);
            } else if (param.type === "bytes") {
                 return keccak256(hexlify(value));
            }
 
            if (param.type === "bool" && typeof(value) === "boolean") {
                value = (value ? "0x01": "0x00");
            } else if (param.type.match(/^u?int/)) {
                value = toBeHex(value);  // @TODO: Should this toTwos??
            } else if (param.type.match(/^bytes/)) {
                value = zeroPadBytes(value, 32);
            } else if (param.type === "address") {
                // Check addresses are valid
                this.#abiCoder.encode( [ "address" ], [ value ]);
            }
 
            return zeroPadValue(hexlify(value), 32);
        };
 
        values.forEach((value, index) => {
 
            const param = (<EventFragment>fragment).inputs[index];
 
            if (!param.indexed) {
                assertArgument(value == null,
                    "cannot filter non-indexed parameters; must be null", ("contract." + param.name), value);
                return;
            }
 
            if (value == null) {
                topics.push(null);
            } else if (param.baseType === "array" || param.baseType === "tuple") {
                assertArgument(false, "filtering with tuples or arrays not supported", ("contract." + param.name), value);
            } else if (Array.isArray(value)) {
                topics.push(value.map((value) => encodeTopic(param, value)));
            } else {
                topics.push(encodeTopic(param, value));
            }
        });
 
        // Trim off trailing nulls
        while (topics.length && topics[topics.length - 1] === null) {
            topics.pop();
        }
 
        return topics;
    }
 
    encodeEventLog(fragment: EventFragment | string, values: ReadonlyArray<any>): { data: string, topics: Array<string> } {
        if (typeof(fragment) === "string") {
            const f = this.getEvent(fragment);
            assertArgument(f, "unknown event", "eventFragment", fragment);
            fragment = f;
        }
 
        const topics: Array<string> = [ ];
 
        const dataTypes: Array<ParamType> = [ ];
        const dataValues: Array<string> = [ ];
 
        if (!fragment.anonymous) {
            topics.push(fragment.topicHash);
        }
 
        assertArgument(values.length === fragment.inputs.length,
            "event arguments/values mismatch", "values", values);
 
        fragment.inputs.forEach((param, index) => {
            const value = values[index];
            if (param.indexed) {
                if (param.type === "string") {
                    topics.push(id(value))
                } else if (param.type === "bytes") {
                    topics.push(keccak256(value))
                } else if (param.baseType === "tuple" || param.baseType === "array") {
                    // @TODO
                    throw new Error("not implemented");
                } else {
                    topics.push(this.#abiCoder.encode([ param.type] , [ value ]));
                }
            } else {
                dataTypes.push(param);
                dataValues.push(value);
            }
        });
 
        return {
            data: this.#abiCoder.encode(dataTypes , dataValues),
            topics: topics
        };
    }
 
    // Decode a filter for the event and the search criteria
    decodeEventLog(fragment: EventFragment | string, data: BytesLike, topics?: ReadonlyArray<string>): Result {
        if (typeof(fragment) === "string") {
            const f = this.getEvent(fragment);
            assertArgument(f, "unknown event", "eventFragment", fragment);
            fragment = f;
        }
 
        if (topics != null && !fragment.anonymous) {
            const eventTopic = fragment.topicHash;
            assertArgument(isHexString(topics[0], 32) && topics[0].toLowerCase() === eventTopic,
                "fragment/topic mismatch", "topics[0]", topics[0]);
            topics = topics.slice(1);
        }
 
        const indexed: Array<ParamType> = [];
        const nonIndexed: Array<ParamType> = [];
        const dynamic: Array<boolean> = [];
 
        fragment.inputs.forEach((param, index) => {
            if (param.indexed) {
                if (param.type === "string" || param.type === "bytes" || param.baseType === "tuple" || param.baseType === "array") {
                    indexed.push(ParamType.from({ type: "bytes32", name: param.name }));
                    dynamic.push(true);
                } else {
                    indexed.push(param);
                    dynamic.push(false);
                }
            } else {
                nonIndexed.push(param);
                dynamic.push(false);
            }
        });
 
        const resultIndexed = (topics != null) ? this.#abiCoder.decode(indexed, concat(topics)): null;
        const resultNonIndexed = this.#abiCoder.decode(nonIndexed, data, true);
 
        //const result: (Array<any> & { [ key: string ]: any }) = [ ];
        const values: Array<any> = [ ];
        const keys: Array<null | string> = [ ];
        let nonIndexedIndex = 0, indexedIndex = 0;
        fragment.inputs.forEach((param, index) => {
            let value: null | Indexed | Error = null;
            if (param.indexed) {
                if (resultIndexed == null) {
                    value = new Indexed(null);

                } else if (dynamic[index]) {
                    value = new Indexed(resultIndexed[indexedIndex++]);

                } else {
                    try {
                        value = resultIndexed[indexedIndex++];
                    } catch (error: any) {
                        value = error;
                    }
                }
            } else {
                try {
                    value = resultNonIndexed[nonIndexedIndex++];
                } catch (error: any) {
                    value = error;
                }
            }
 
            values.push(value);
            keys.push(param.name || null);
        });
 
        return Result.fromItems(values, keys);
    }
 
    /**
     *  Parses a transaction, finding the matching function and extracts
     *  the parameter values along with other useful function details.
     *
     *  If the matching function cannot be found, return null.
     */
    parseTransaction(tx: { data: string, value?: BigNumberish }): null | TransactionDescription {
        const data = getBytes(tx.data, "tx.data");
        const value = getBigInt((tx.value != null) ? tx.value: 0, "tx.value");
 
        const fragment = this.getFunction(hexlify(data.slice(0, 4)));
 
        if (!fragment) { return null; }
 
        const args = this.#abiCoder.decode(fragment.inputs, data.slice(4));
        return new TransactionDescription(fragment, fragment.selector, args, value);
    }
 
    parseCallResult(data: BytesLike): Result {
        throw new Error("@TODO");
    }
 
    /**
     *  Parses a receipt log, finding the matching event and extracts
     *  the parameter values along with other useful event details.
     *
     *  If the matching event cannot be found, returns null.
     */
    parseLog(log: { topics: ReadonlyArray<string>, data: string}): null | LogDescription {
        const fragment = this.getEvent(log.topics[0]);
 
        if (!fragment || fragment.anonymous) { return null; }
 
        // @TODO: If anonymous, and the only method, and the input count matches, should we parse?
        //        Probably not, because just because it is the only event in the ABI does
        //        not mean we have the full ABI; maybe just a fragment?
 
 
       return new LogDescription(fragment, fragment.topicHash, this.decodeEventLog(fragment, log.data, log.topics));
    }
 
    /**
     *  Parses a revert data, finding the matching error and extracts
     *  the parameter values along with other useful error details.
     *
     *  If the matching error cannot be found, returns null.
     */
    parseError(data: BytesLike): null | ErrorDescription {
        const hexData = hexlify(data);

        const fragment = this.getError(dataSlice(hexData, 0, 4));

        if (!fragment) { return null; }

        const args = this.#abiCoder.decode(fragment.inputs, dataSlice(hexData, 4));
        return new ErrorDescription(fragment, fragment.selector, args);
    }
 
    /**
     *  Creates a new [[Interface]] from the ABI %%value%%.
     *
     *  The %%value%% may be provided as an existing [[Interface]] object,
     *  a JSON-encoded ABI or any Human-Readable ABI format.
     */
    static from(value: InterfaceAbi | Interface): Interface {
        // Already an Interface, which is immutable
        if (value instanceof Interface) { return value; }
 
        // JSON
        if (typeof(value) === "string") { return new Interface(JSON.parse(value)); }
 
        // An Interface; possibly from another v6 instance
        if (typeof((<any>value).formatJson) === "function") {
            return new Interface((<any>value).formatJson());
        }
 
        // A legacy Interface; from an older version
        if (typeof((<any>value).format) === "function") {
            return new Interface((<any>value).format("json"));
        }
 
        // Array of fragments
        return new Interface(value);
    }
}