aboutsummaryrefslogtreecommitdiffstats
path: root/packages/order-utils/test/abi_encoder_test.ts
blob: 6f723036b559512a3a936d208b34860795657f91 (plain) (blame)
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
import * as chai from 'chai';
import 'mocha';
import ethUtil = require('ethereumjs-util');

var _ = require('lodash');

// import { assert } from '@0x/order-utils/src/assert';

import { chaiSetup } from './utils/chai_setup';

import { MethodAbi, DataItem } from 'ethereum-types';

import { BigNumber } from '@0x/utils';
import { assert } from '@0x/order-utils/src/assert';

const simpleAbi = {
    constant: false,
    inputs: [
        {
            name: 'greg',
            type: 'uint256',
        },
        {
            name: 'gregStr',
            type: 'string',
        },
    ],
    name: 'simpleFunction',
    outputs: [],
    payable: false,
    stateMutability: 'nonpayable',
    type: 'function',
} as MethodAbi;

const fillOrderAbi = {
    constant: false,
    inputs: [
        {
            components: [
                {
                    name: 'makerAddress',
                    type: 'address',
                },
                {
                    name: 'takerAddress',
                    type: 'address',
                },
                {
                    name: 'feeRecipientAddress',
                    type: 'address',
                },
                {
                    name: 'senderAddress',
                    type: 'address',
                },
                {
                    name: 'makerAssetAmount',
                    type: 'uint256',
                },
                {
                    name: 'takerAssetAmount',
                    type: 'uint256',
                },
                {
                    name: 'makerFee',
                    type: 'uint256',
                },
                {
                    name: 'takerFee',
                    type: 'uint256',
                },
                {
                    name: 'expirationTimeSeconds',
                    type: 'uint256',
                },
                {
                    name: 'salt',
                    type: 'uint256',
                },
                {
                    name: 'makerAssetData',
                    type: 'bytes',
                },
                {
                    name: 'takerAssetData',
                    type: 'bytes',
                },
            ],
            name: 'order',
            type: 'tuple',
        },
        {
            name: 'takerAssetFillAmount',
            type: 'uint256',
        },
        {
            name: 'salt',
            type: 'uint256',
        },
        {
            name: 'orderSignature',
            type: 'bytes',
        },
        {
            name: 'takerSignature',
            type: 'bytes',
        },
    ],
    name: 'fillOrder',
    outputs: [],
    payable: false,
    stateMutability: 'nonpayable',
    type: 'function',
} as MethodAbi;

chaiSetup.configure();
const expect = chai.expect;

namespace AbiEncoder {
    class Word {
        private value: string;

        constructor(value?: string) {
            if (value === undefined) {
                this.value = '';
            } else {
                this.value = value;
            }
        }

        public set(value: string) {
            if (value.length !== 64) {
                throw `Tried to create word that is not 32 bytes: ${value}`;
            }

            this.value = value;
        }

        public get(): string {
            return this.value;
        }

        public getAsHex(): string {
            return `0x${this.value}`;
        }
    }

    enum CalldataSection {
        NONE,
        PARAMS,
        DATA,
    }

    class Memblock {
        private dataType: DataType;
        private location: { calldataSection: CalldataSection; sectionOffset: BigNumber; offset: BigNumber };

        constructor(dataType: DataType) {
            this.dataType = dataType;
            this.location = {
                calldataSection: CalldataSection.NONE,
                sectionOffset: new BigNumber(0),
                offset: new BigNumber(0),
            };
        }

        public getSize(): BigNumber {
            return new BigNumber(ethUtil.toBuffer(this.dataType.getHexValue()).byteLength);
        }

        public assignLocation(calldataSection: CalldataSection, sectionOffset: BigNumber, offset: BigNumber) {
            this.location.calldataSection = calldataSection;
            this.location.sectionOffset = sectionOffset;
            this.location.offset = offset;
        }

        public get(): string {
            return ethUtil.stripHexPrefix(this.dataType.getHexValue());
        }

        public getOffset(): BigNumber {
            return this.location.offset;
        }

        public getAbsoluteOffset(): BigNumber {
            return this.location.sectionOffset.plus(this.location.offset);
        }

        public getSection(): CalldataSection {
            return this.location.calldataSection;
        }
    }

    interface BindList {
        [key: string]: Memblock;
    }

    class Calldata {
        private selector: string;
        private params: Memblock[];
        private data: Memblock[];
        private dataOffset: BigNumber;
        private currentDataOffset: BigNumber;
        private currentParamOffset: BigNumber;
        private bindList: BindList;

        constructor(selector: string, nParams: number) {
            this.selector = selector;
            console.log(this.selector);
            this.params = [];
            this.data = [];
            const evmWordSize = 32;
            this.dataOffset = new BigNumber(nParams).times(evmWordSize);
            this.currentDataOffset = new BigNumber(0);
            this.currentParamOffset = new BigNumber(0);
            this.bindList = {};
        }

        public bind(dataType: DataType, section: CalldataSection) {
            if (dataType.getId() in this.bindList) {
                throw `Rebind on ${dataType.getId()}`;
            }
            const memblock = new Memblock(dataType);
            switch (section) {
                case CalldataSection.PARAMS:
                    this.params.push(memblock);
                    memblock.assignLocation(section, new BigNumber(0), this.currentParamOffset);
                    this.currentParamOffset = this.currentParamOffset.plus(memblock.getSize());
                    break;

                case CalldataSection.DATA:
                    this.data.push(memblock);
                    memblock.assignLocation(section, this.dataOffset, this.currentDataOffset);
                    this.currentDataOffset = this.currentDataOffset.plus(memblock.getSize());
                    break;

                default:
                    throw `Unrecognized calldata section: ${section}`;
            }

            this.bindList[dataType.getId()] = memblock;
            dataType.rbind(memblock);
        }

        public getHexValue(): string {
            let hexValue = `${this.selector}`;
            _.each(this.params, (memblock: Memblock) => {
                hexValue += memblock.get();
            });
            _.each(this.data, (memblock: Memblock) => {
                hexValue += memblock.get();
            });

            return hexValue;
        }
    }

    export abstract class DataType {
        private dataItem: DataItem;
        private hexValue: string;
        protected memblock: Memblock | undefined;
        protected children: DataType[];

        constructor(dataItem: DataItem) {
            this.dataItem = dataItem;
            this.hexValue = '0x';
            this.memblock = undefined;
            this.children = [];
        }

        protected assignHexValue(hexValue: string) {
            this.hexValue = hexValue;
        }

        public getHexValue(): string {
            return this.hexValue;
        }

        public getDataItem(): DataItem {
            return this.dataItem;
        }

        public rbind(memblock: Memblock) {
            this.memblock = memblock;
        }

        public bind(calldata: Calldata, section: CalldataSection) {
            if (this.memblock === undefined) {
                calldata.bind(this, section);
            }
            _.each(this.children, (child: DataType) => {
                child.bind(calldata, CalldataSection.DATA);
            });
        }

        public getId(): string {
            return this.dataItem.name;
        }

        public getOffset(): BigNumber {
            if (this.memblock === undefined) return new BigNumber(0);
            return this.memblock.getOffset();
        }

        public getAbsoluteOffset(): BigNumber {
            if (this.memblock === undefined) return new BigNumber(0);
            return this.memblock.getAbsoluteOffset();
        }

        public abstract assignValue(value: any): void;
        public abstract getSignature(): string;
    }

    export abstract class StaticDataType extends DataType {
        constructor(dataItem: DataItem) {
            super(dataItem);
        }
    }

    export abstract class DynamicDataType extends DataType {
        constructor(dataItem: DataItem) {
            super(dataItem);
        }
    }

    export class Address extends StaticDataType {
        constructor(dataItem: DataItem) {
            super(dataItem);
            expect(Address.matchGrammar(dataItem.type)).to.be.true();
        }

        public assignValue(value: string) {
            const evmWordWidth = 32;
            const hexValue = ethUtil.bufferToHex(ethUtil.setLengthLeft(ethUtil.toBuffer(value), evmWordWidth));
            this.assignHexValue(hexValue);
        }

        public getSignature(): string {
            return `address`;
        }

        public static matchGrammar(type: string): boolean {
            return type === 'address';
        }
    }

    export class Bool extends StaticDataType {
        constructor(dataItem: DataItem) {
            super(dataItem);
            expect(Bool.matchGrammar(dataItem.type)).to.be.true();
        }

        public assignValue(value: boolean) {
            const evmWordWidth = 32;
            const encodedValue = value === true ? '0x1' : '0x0';
            const hexValue = ethUtil.bufferToHex(ethUtil.setLengthLeft(ethUtil.toBuffer(encodedValue), evmWordWidth));
            this.assignHexValue(hexValue);
        }

        public getSignature(): string {
            return 'bool';
        }

        public static matchGrammar(type: string): boolean {
            return type === 'bool';
        }
    }

    abstract class Number extends StaticDataType {
        static MAX_WIDTH: number = 256;
        static DEFAULT_WIDTH: number = Number.MAX_WIDTH;
        width: number = Number.DEFAULT_WIDTH;

        constructor(dataItem: DataItem, matcher: RegExp) {
            super(dataItem);
            const matches = matcher.exec(dataItem.type);
            expect(matches).to.be.not.null();
            if (matches !== null && matches.length === 2 && matches[1] !== undefined) {
                this.width = parseInt(matches[1]);
            } else {
                this.width = 256;
            }
        }

        public assignValue(value: BigNumber) {
            if (value.greaterThan(this.getMaxValue())) {
                throw `tried to assign value of ${value}, which exceeds max value of ${this.getMaxValue()}`;
            } else if (value.lessThan(this.getMinValue())) {
                throw `tried to assign value of ${value}, which exceeds min value of ${this.getMinValue()}`;
            }

            const hexBase = 16;
            const evmWordWidth = 32;
            let valueBuf: Buffer;
            if (value.greaterThanOrEqualTo(0)) {
                valueBuf = ethUtil.setLengthLeft(ethUtil.toBuffer(`0x${value.toString(hexBase)}`), evmWordWidth);
            } else {
                // BigNumber can't write a negative hex value, so we use twos-complement conversion to do it ourselves.
                // Step 1/3: Convert value to positive binary string
                const binBase = 2;
                const valueBin = value.times(-1).toString(binBase);

                // Step 2/3: Invert binary value
                const bitsInEvmWord = 256;
                let invertedValueBin = '1'.repeat(bitsInEvmWord - valueBin.length);
                _.each(valueBin, (bit: string) => {
                    invertedValueBin += bit === '1' ? '0' : '1';
                });
                const invertedValue = new BigNumber(invertedValueBin, binBase);

                // Step 3/3: Add 1 to inverted value
                // The result is the two's-complement represent of the input value.
                const negativeValue = invertedValue.plus(1);

                // Convert the negated value to a hex string
                valueBuf = ethUtil.setLengthLeft(
                    ethUtil.toBuffer(`0x${negativeValue.toString(hexBase)}`),
                    evmWordWidth,
                );
            }

            const encodedValue = ethUtil.bufferToHex(valueBuf);
            this.assignHexValue(encodedValue);
        }

        public abstract getMaxValue(): BigNumber;
        public abstract getMinValue(): BigNumber;
    }

    export class Int extends Number {
        static matcher = RegExp(
            '^int(8|16|24|32|40|48|56|64|72|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256){0,1}$',
        );

        constructor(dataItem: DataItem) {
            super(dataItem, Int.matcher);
        }

        public getMaxValue(): BigNumber {
            return new BigNumber(2).toPower(this.width - 1).sub(1);
        }

        public getMinValue(): BigNumber {
            return new BigNumber(2).toPower(this.width - 1).times(-1);
        }

        public getSignature(): string {
            return `int${this.width}`;
        }

        public static matchGrammar(type: string): boolean {
            return this.matcher.test(type);
        }
    }

    export class UInt extends Number {
        static matcher = RegExp(
            '^uint(8|16|24|32|40|48|56|64|72|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256){0,1}$',
        );

        constructor(dataItem: DataItem) {
            super(dataItem, UInt.matcher);
        }

        public getMaxValue(): BigNumber {
            return new BigNumber(2).toPower(this.width).sub(1);
        }

        public getMinValue(): BigNumber {
            return new BigNumber(0);
        }

        public getSignature(): string {
            return `uint${this.width}`;
        }

        public static matchGrammar(type: string): boolean {
            return this.matcher.test(type);
        }
    }

    export class Byte extends StaticDataType {
        static matcher = RegExp(
            '^(byte|bytes(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))$',
        );

        static DEFAULT_WIDTH = 1;
        width: number = Byte.DEFAULT_WIDTH;

        constructor(dataItem: DataItem) {
            super(dataItem);
            const matches = Byte.matcher.exec(dataItem.type);
            expect(matches).to.be.not.null();
            if (matches !== null && matches.length === 3 && matches[2] !== undefined) {
                this.width = parseInt(matches[2]);
            } else {
                this.width = Byte.DEFAULT_WIDTH;
            }
        }

        public assignValue(value: string | Buffer) {
            // Convert value into a buffer and do bounds checking
            const valueBuf = ethUtil.toBuffer(value);
            if (valueBuf.byteLength > this.width) {
                throw new Error(
                    `Tried to assign ${value} (${
                        valueBuf.byteLength
                    } bytes), which exceeds max bytes that can be stored in a ${this.getSignature()}`,
                );
            } else if (value.length % 2 !== 0) {
                throw new Error(`Tried to assign ${value}, which is contains a half-byte. Use full bytes only.`);
            }

            // Store value as hex
            const evmWordWidth = 32;
            const paddedValue = ethUtil.setLengthRight(valueBuf, evmWordWidth);
            const hexValue = ethUtil.bufferToHex(paddedValue);
            this.assignHexValue(hexValue);
        }

        public getSignature(): string {
            // Note that `byte` reduces to `bytes1`
            return `bytes${this.width}`;
        }

        public static matchGrammar(type: string): boolean {
            return this.matcher.test(type);
        }
    }

    export class Tuple extends DynamicDataType {
        constructor(dataItem: DataItem) {
            super(dataItem);
            expect(Tuple.matchGrammar(dataItem.type)).to.be.true();
        }

        public assignValue(value: string) {
            //const hexValue = ethUtil.bufferToHex(new Buffer(value));
            //this.assignHexValue(hexValue);
        }

        public getSignature(): string {
            throw 1;
        }

        public encodeToCalldata(calldata: Calldata): void {
            throw 2;
        }

        public static matchGrammar(type: string): boolean {
            return type === 'tuple';
        }
    }

    export class Bytes extends StaticDataType {
        static UNDEFINED_LENGTH = new BigNumber(-1);
        length: BigNumber = SolArray.UNDEFINED_LENGTH;

        constructor(dataItem: DataItem) {
            super(dataItem);
            expect(Bytes.matchGrammar(dataItem.type)).to.be.true();
        }

        public assignValue(value: string) {
            //const hexValue = ethUtil.bufferToHex(new Buffer(value));
            //this.assignHexValue(hexValue);
        }

        public getSignature(): string {
            throw 1;
        }

        public encodeToCalldata(calldata: Calldata): void {
            throw 2;
        }

        public static matchGrammar(type: string): boolean {
            return type === 'bytes';
        }
    }

    export class SolArray extends DynamicDataType {
        static matcher = RegExp('^.+\\[([0-9]d*)\\]$');
        static UNDEFINED_LENGTH = new BigNumber(-1);
        length: BigNumber = SolArray.UNDEFINED_LENGTH;

        constructor(dataItem: DataItem) {
            super(dataItem);
            const matches = SolArray.matcher.exec(dataItem.type);
            expect(matches).to.be.not.null();
            if (matches !== null && matches.length === 1) {
                this.length = new BigNumber(matches[1], 10);
            }
        }

        public assignValue(value: string) {
            //const hexValue = ethUtil.bufferToHex(new Buffer(value));
            //this.assignHexValue(hexValue);
        }

        public encodeToCalldata(calldata: Calldata): void {
            throw 2;
        }

        public static matchGrammar(type: string): boolean {
            return this.matcher.test(type);
        }

        public getSignature(): string {
            throw 1;
        }
    }

    export class SolString extends DynamicDataType {
        constructor(dataItem: DataItem) {
            super(dataItem);
            expect(SolString.matchGrammar(dataItem.type)).to.be.true();
        }

        public assignValue(value: string) {
            const wordsForValue = Math.ceil(value.length / 32);
            const paddedBytesForValue = wordsForValue * 32;
            const valueBuf = ethUtil.setLengthRight(ethUtil.toBuffer(value), paddedBytesForValue);
            const lengthBuf = ethUtil.setLengthLeft(ethUtil.toBuffer(value.length), 32);
            const encodedValueBuf = Buffer.concat([lengthBuf, valueBuf]);
            const encodedValue = ethUtil.bufferToHex(encodedValueBuf);

            this.assignHexValue(encodedValue);
        }

        public getSignature(): string {
            return 'string';
        }

        public encodeToCalldata(calldata: Calldata): void {}

        public static matchGrammar(type: string): boolean {
            return type === 'string';
        }
    }

    /* TODO
    class Fixed extends StaticDataType {}

    class UFixed extends StaticDataType {}*/

    export class Pointer extends StaticDataType {
        destDataType: DynamicDataType;

        constructor(destDataType: DynamicDataType) {
            const destDataItem = destDataType.getDataItem();
            const dataItem = { name: `ptr<${destDataItem.name}>`, type: `ptr<${destDataItem.type}>` } as DataItem;
            super(dataItem);
            this.destDataType = destDataType;
            this.children.push(destDataType);
        }

        /*
        public assignValue(destDataType: DynamicDataType) {
            this.destDataType = destDataType;
        }*/

        public assignValue(value: any) {
            this.destDataType.assignValue(value);
        }

        public getHexValue(): string {
            let offset = new BigNumber(0);
            if (this.memblock !== undefined) {
                switch (this.memblock.getSection()) {
                    case CalldataSection.PARAMS:
                        offset = this.destDataType.getAbsoluteOffset();
                        break;
                    case CalldataSection.DATA:
                        offset = this.destDataType.getOffset();
                        break;
                }
            }

            const hexBase = 16;
            const evmWordWidth = 32;
            const valueBuf = ethUtil.setLengthLeft(ethUtil.toBuffer(`0x${offset.toString(hexBase)}`), evmWordWidth);
            const encodedValue = ethUtil.bufferToHex(valueBuf);
            return encodedValue;
        }

        public getSignature(): string {
            return this.destDataType.getSignature();
        }

        public encodeToCalldata(calldata: Calldata): void {
            throw 2;
        }
    }

    export class DataTypeFactory {
        public static mapDataItemToDataType(dataItem: DataItem): DataType {
            console.log(`Type: ${dataItem.type}`);

            if (SolArray.matchGrammar(dataItem.type)) return new SolArray(dataItem);
            if (Address.matchGrammar(dataItem.type)) return new Address(dataItem);
            if (Bool.matchGrammar(dataItem.type)) return new Bool(dataItem);
            if (Int.matchGrammar(dataItem.type)) return new Int(dataItem);
            if (UInt.matchGrammar(dataItem.type)) return new UInt(dataItem);
            if (Byte.matchGrammar(dataItem.type)) return new Byte(dataItem);
            if (Tuple.matchGrammar(dataItem.type)) return new Tuple(dataItem);
            if (SolArray.matchGrammar(dataItem.type)) return new SolArray(dataItem);
            if (Bytes.matchGrammar(dataItem.type)) return new Bytes(dataItem);
            if (SolString.matchGrammar(dataItem.type)) return new SolString(dataItem);
            //if (Fixed.matchGrammar(dataItem.type)) return Fixed(dataItem);
            //if (UFixed.matchGrammar(dataItem.type)) return UFixed(dataItem);

            throw new Error(`Unrecognized data type: '${dataItem.type}'`);
        }

        public static create(dataItem: DataItem): DataType {
            const dataType = DataTypeFactory.mapDataItemToDataType(dataItem);
            if (dataType instanceof StaticDataType) {
                return dataType;
            } else if (dataType instanceof DynamicDataType) {
                const pointer = new Pointer(dataType);
                return pointer;
            }

            throw new Error(`Unrecognized instance type: '${dataType}'`);
        }
    }

    export class Method {
        name: string;
        params: DataType[];
        signature: string;
        selector: string;

        constructor(abi: MethodAbi) {
            // super();
            this.name = abi.name;
            this.params = [];

            _.each(abi.inputs, (input: DataItem) => {
                this.params.push(DataTypeFactory.create(input));
            });

            // Compute signature
            this.signature = `${this.name}(`;
            _.each(this.params, (param: DataType, i: number) => {
                this.signature += param.getSignature();
                if (i < this.params.length - 1) {
                    this.signature += ',';
                }
            });
            this.signature += ')';

            // Compute selector
            this.selector = ethUtil.bufferToHex(ethUtil.toBuffer(ethUtil.sha3(this.signature).slice(0, 4)));

            console.log(`--SIGNATURE--\n${this.signature}\n---------\n`);
            console.log(`--SELECTOR--\n${this.selector}\n---------\n`);
        }

        encode(args: any[]): string {
            const calldata = new Calldata(this.selector, this.params.length);
            const params = this.params;
            _.each(params, (param: DataType, i: number) => {
                param.assignValue(args[i]);
                param.bind(calldata, CalldataSection.PARAMS);
            });

            console.log(calldata);

            return calldata.getHexValue();

            //return calldata.getRaw();
        }

        /*
        encodeOptimized(args: any[]): string {
            const calldata = new Memory();
            // Assign values
            optimizableParams : StaticDataType = [];
            _.each(this.params, function(args: any[], i: number, param: DataType) {
                param.assignValue(args[i]);
                if (param instanceof DynamicDataType) {

                }
            });

            // Find non-parameter leaves


            return '';
        } */

        /*
        decode(rawCalldata: string): any[] {
            const calldata = new Calldata(this.name, this.params.length);
            calldata.assignRaw(rawCalldata);
            let args: any[];
            let params = this.params;
            _.each(params, function(args: any[], i: number, param: DataType) {
                param.decodeFromCalldata(calldata);
                args.push(param.getValue());
            });

            return args;
        }*/
    }
}

describe.only('ABI Encoder', () => {
    describe.only('Just a Greg, Eh', () => {
        it('Yessir', async () => {
            const method = new AbiEncoder.Method(simpleAbi);
            const calldata = method.encode([new BigNumber(5), 'five']);
            console.log(calldata);
            expect(true).to.be.true();
        });
    });

    describe('Address', () => {
        const testAddressDataItem = { name: 'testAddress', type: 'address' };
        it('Valid Address', async () => {
            const addressDataType = new AbiEncoder.Address(testAddressDataItem);
            addressDataType.assignValue('0xe41d2489571d322189246dafa5ebde1f4699f498');
            const expectedAbiEncodedAddress = '0x000000000000000000000000e41d2489571d322189246dafa5ebde1f4699f498';

            console.log(addressDataType.getHexValue());
            console.log(expectedAbiEncodedAddress);
            expect(addressDataType.getHexValue()).to.be.equal(expectedAbiEncodedAddress);
        });
    });

    describe('Bool', () => {
        const testBoolDataItem = { name: 'testBool', type: 'bool' };
        it('True', async () => {
            const boolDataType = new AbiEncoder.Bool(testBoolDataItem);
            boolDataType.assignValue(true);
            const expectedAbiEncodedBool = '0x0000000000000000000000000000000000000000000000000000000000000001';
            expect(boolDataType.getHexValue()).to.be.equal(expectedAbiEncodedBool);
        });

        it('False', async () => {
            const boolDataType = new AbiEncoder.Bool(testBoolDataItem);
            boolDataType.assignValue(false);
            const expectedAbiEncodedBool = '0x0000000000000000000000000000000000000000000000000000000000000000';
            expect(boolDataType.getHexValue()).to.be.equal(expectedAbiEncodedBool);
        });
    });

    describe('Integer', () => {
        const testIntDataItem = { name: 'testInt', type: 'int' };
        it('Positive - Base case', async () => {
            const intDataType = new AbiEncoder.Int(testIntDataItem);
            intDataType.assignValue(new BigNumber(1));
            const expectedAbiEncodedInt = '0x0000000000000000000000000000000000000000000000000000000000000001';
            expect(intDataType.getHexValue()).to.be.equal(expectedAbiEncodedInt);
        });

        it('Positive', async () => {
            const intDataType = new AbiEncoder.Int(testIntDataItem);
            intDataType.assignValue(new BigNumber(437829473));
            const expectedAbiEncodedInt = '0x000000000000000000000000000000000000000000000000000000001a18bf61';
            expect(intDataType.getHexValue()).to.be.equal(expectedAbiEncodedInt);
        });

        it('Negative - Base case', async () => {
            const intDataType = new AbiEncoder.Int(testIntDataItem);
            intDataType.assignValue(new BigNumber(-1));
            const expectedAbiEncodedInt = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff';
            expect(intDataType.getHexValue()).to.be.equal(expectedAbiEncodedInt);
        });

        it('Negative', async () => {
            const intDataType = new AbiEncoder.Int(testIntDataItem);
            intDataType.assignValue(new BigNumber(-437829473));
            const expectedAbiEncodedInt = '0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffe5e7409f';
            expect(intDataType.getHexValue()).to.be.equal(expectedAbiEncodedInt);
        });

        // TODO: Add bounds tests + tests for different widths
    });

    describe('Unsigned Integer', () => {
        const testIntDataItem = { name: 'testUInt', type: 'uint' };
        it('Lower Bound', async () => {
            const uintDataType = new AbiEncoder.UInt(testIntDataItem);
            uintDataType.assignValue(new BigNumber(0));
            const expectedAbiEncodedUInt = '0x0000000000000000000000000000000000000000000000000000000000000000';
            expect(uintDataType.getHexValue()).to.be.equal(expectedAbiEncodedUInt);
        });

        it('Base Case', async () => {
            const uintDataType = new AbiEncoder.UInt(testIntDataItem);
            uintDataType.assignValue(new BigNumber(1));
            const expectedAbiEncodedUInt = '0x0000000000000000000000000000000000000000000000000000000000000001';
            expect(uintDataType.getHexValue()).to.be.equal(expectedAbiEncodedUInt);
        });

        it('Random value', async () => {
            const uintDataType = new AbiEncoder.UInt(testIntDataItem);
            uintDataType.assignValue(new BigNumber(437829473));
            const expectedAbiEncodedUInt = '0x000000000000000000000000000000000000000000000000000000001a18bf61';
            expect(uintDataType.getHexValue()).to.be.equal(expectedAbiEncodedUInt);
        });

        // TODO: Add bounds tests + tests for different widths
    });

    describe.only('Static Bytes', () => {
        it('Byte (padded)', async () => {
            const testByteDataItem = { name: 'testStaticBytes', type: 'byte' };
            const byteDataType = new AbiEncoder.Byte(testByteDataItem);
            byteDataType.assignValue('0x05');
            const expectedAbiEncodedByte = '0x0500000000000000000000000000000000000000000000000000000000000000';
            expect(byteDataType.getHexValue()).to.be.equal(expectedAbiEncodedByte);
        });

        it.skip('Byte (no padding)', async () => {
            const testByteDataItem = { name: 'testStaticBytes', type: 'byte' };
            const byteDataType = new AbiEncoder.Byte(testByteDataItem);

            // @TODO: This does not catch the Error
            expect(byteDataType.assignValue('0x5')).to.throw();
        });

        it('Bytes1', async () => {
            const testByteDataItem = { name: 'testStaticBytes', type: 'bytes1' };
            const byteDataType = new AbiEncoder.Byte(testByteDataItem);
            byteDataType.assignValue('0x05');
            const expectedAbiEncodedByte = '0x0500000000000000000000000000000000000000000000000000000000000000';
            expect(byteDataType.getHexValue()).to.be.equal(expectedAbiEncodedByte);
        });

        it('Bytes32 (padded)', async () => {
            const testByteDataItem = { name: 'testStaticBytes', type: 'bytes32' };
            const byteDataType = new AbiEncoder.Byte(testByteDataItem);
            byteDataType.assignValue('0x0001020304050607080911121314151617181920212223242526272829303132');
            const expectedAbiEncodedByte = '0x0001020304050607080911121314151617181920212223242526272829303132';
            expect(byteDataType.getHexValue()).to.be.equal(expectedAbiEncodedByte);
        });

        it('Bytes32 (unpadded)', async () => {
            const testByteDataItem = { name: 'testStaticBytes', type: 'bytes32' };
            const byteDataType = new AbiEncoder.Byte(testByteDataItem);
            byteDataType.assignValue('0x1a18bf61');
            const expectedAbiEncodedByte = '0x1a18bf6100000000000000000000000000000000000000000000000000000000';
            expect(byteDataType.getHexValue()).to.be.equal(expectedAbiEncodedByte);
        });

        it.skip('Bytes32 - Too long', async () => {
            const testByteDataItem = { name: 'testStaticBytes', type: 'bytes32' };
            const byteDataType = new AbiEncoder.Byte(testByteDataItem);

            // @TODO: This does not catch the Error
            expect(
                byteDataType.assignValue('0x000102030405060708091112131415161718192021222324252627282930313233'),
            ).to.throw(
                `Tried to assign 0x000102030405060708091112131415161718192021222324252627282930313233 (33 bytes), which exceeds max bytes that can be stored in a bytes32`,
            );
        });
    });

    describe('String', () => {
        const testStringDataItem = { name: 'testString', type: 'string' };
        it('Less than 32 bytes', async () => {
            const stringDataType = new AbiEncoder.SolString(testStringDataItem);
            stringDataType.assignValue('five');
            const expectedAbiEncodedString =
                '0x00000000000000000000000000000000000000000000000000000000000000046669766500000000000000000000000000000000000000000000000000000000';

            console.log(stringDataType.getHexValue());
            console.log(expectedAbiEncodedString);
            expect(stringDataType.getHexValue()).to.be.equal(expectedAbiEncodedString);
        });

        it('Greater than 32 bytes', async () => {
            const stringDataType = new AbiEncoder.SolString(testStringDataItem);
            const testValue = 'a'.repeat(40);
            stringDataType.assignValue(testValue);
            const expectedAbiEncodedString =
                '0x000000000000000000000000000000000000000000000000000000000000002861616161616161616161616161616161616161616161616161616161616161616161616161616161000000000000000000000000000000000000000000000000';
            expect(stringDataType.getHexValue()).to.be.equal(expectedAbiEncodedString);
        });
    });
});