aboutsummaryrefslogtreecommitdiffstats
path: root/packages/order-watcher/test/order_watcher_test.ts
blob: 41dc884d5145bfdc8ede7667cfbabe0d2d2cf613 (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
// tslint:disable:no-unnecessary-type-assertion
import { ContractWrappers } from '@0x/contract-wrappers';
import { tokenUtils } from '@0x/contract-wrappers/lib/test/utils/token_utils';
import { BlockchainLifecycle, callbackErrorReporter } from '@0x/dev-utils';
import { FillScenarios } from '@0x/fill-scenarios';
import { assetDataUtils, orderHashUtils } from '@0x/order-utils';
import {
    DoneCallback,
    ExchangeContractErrs,
    OrderState,
    OrderStateInvalid,
    OrderStateValid,
    SignedOrder,
} from '@0x/types';
import { BigNumber } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import * as chai from 'chai';
import * as _ from 'lodash';
import 'mocha';

import {
    DependentOrderHashesTracker,
    OrderHashesByERC20ByMakerAddress,
} from '../src/order_watcher/dependent_order_hashes_tracker';
import { OrderWatcher } from '../src/order_watcher/order_watcher';
import { OrderWatcherError } from '../src/types';

import { chaiSetup } from './utils/chai_setup';
import { constants } from './utils/constants';
import { migrateOnceAsync } from './utils/migrate';
import { provider, web3Wrapper } from './utils/web3_wrapper';

const TIMEOUT_MS = 150;

chaiSetup.configure();
const expect = chai.expect;
const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper);

describe('OrderWatcher', () => {
    let contractWrappers: ContractWrappers;
    let fillScenarios: FillScenarios;
    let userAddresses: string[];
    let zrxTokenAddress: string;
    let makerAssetData: string;
    let takerAssetData: string;
    let makerTokenAddress: string;
    let takerTokenAddress: string;
    let makerAddress: string;
    let takerAddress: string;
    let coinbase: string;
    let feeRecipient: string;
    let signedOrder: SignedOrder;
    let orderWatcher: OrderWatcher;
    const decimals = constants.ZRX_DECIMALS;
    const fillableAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(5), decimals);
    before(async () => {
        const contractAddresses = await migrateOnceAsync();
        await blockchainLifecycle.startAsync();
        const networkId = constants.TESTRPC_NETWORK_ID;
        const config = {
            networkId,
            contractAddresses,
        };
        contractWrappers = new ContractWrappers(provider, config);
        userAddresses = await web3Wrapper.getAvailableAddressesAsync();
        zrxTokenAddress = contractAddresses.zrxToken;
        fillScenarios = new FillScenarios(
            provider,
            userAddresses,
            zrxTokenAddress,
            contractAddresses.exchange,
            contractAddresses.erc20Proxy,
            contractAddresses.erc721Proxy,
        );
        [coinbase, makerAddress, takerAddress, feeRecipient] = userAddresses;
        [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses();
        [makerAssetData, takerAssetData] = [
            assetDataUtils.encodeERC20AssetData(makerTokenAddress),
            assetDataUtils.encodeERC20AssetData(takerTokenAddress),
        ];
        const orderWatcherConfig = {};
        orderWatcher = new OrderWatcher(provider, networkId, contractAddresses, orderWatcherConfig);
    });
    after(async () => {
        await blockchainLifecycle.revertAsync();
    });
    beforeEach(async () => {
        await blockchainLifecycle.startAsync();
    });
    afterEach(async () => {
        await blockchainLifecycle.revertAsync();
    });
    describe('#removeOrder', async () => {
        it('should successfully remove existing order', async () => {
            signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerAssetData,
                takerAssetData,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
            await orderWatcher.addOrderAsync(signedOrder);
            expect((orderWatcher as any)._orderByOrderHash).to.include({
                [orderHash]: signedOrder,
            });
            const dependentOrderHashesTracker = (orderWatcher as any)
                ._dependentOrderHashesTracker as DependentOrderHashesTracker;
            let orderHashesByERC20ByMakerAddress: OrderHashesByERC20ByMakerAddress = (dependentOrderHashesTracker as any)
                ._orderHashesByERC20ByMakerAddress;
            expect(orderHashesByERC20ByMakerAddress[signedOrder.makerAddress][makerTokenAddress]).to.have.keys(
                orderHash,
            );
            orderWatcher.removeOrder(orderHash);
            expect((orderWatcher as any)._orderByOrderHash).to.not.include({
                [orderHash]: signedOrder,
            });
            orderHashesByERC20ByMakerAddress = (dependentOrderHashesTracker as any)._orderHashesByERC20ByMakerAddress;
            expect(orderHashesByERC20ByMakerAddress[signedOrder.makerAddress]).to.be.undefined();
        });
        it('should no-op when removing a non-existing order', async () => {
            signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerAssetData,
                takerAssetData,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
            const nonExistentOrderHash = `0x${orderHash
                .substr(2)
                .split('')
                .reverse()
                .join('')}`;
            orderWatcher.removeOrder(nonExistentOrderHash);
        });
    });
    describe('#subscribe', async () => {
        afterEach(async () => {
            orderWatcher.unsubscribe();
        });
        it('should fail when trying to subscribe twice', async () => {
            orderWatcher.subscribe(_.noop.bind(_));
            expect(() => orderWatcher.subscribe(_.noop.bind(_))).to.throw(OrderWatcherError.SubscriptionAlreadyPresent);
        });
    });
    describe('#getStats', async () => {
        it('orderCount should increment and decrement with order additions and removals', async () => {
            signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                makerAssetData,
                takerAssetData,
                makerAddress,
                takerAddress,
                fillableAmount,
            );
            const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
            expect(orderWatcher.getStats().orderCount).to.be.eq(0);
            await orderWatcher.addOrderAsync(signedOrder);
            expect(orderWatcher.getStats().orderCount).to.be.eq(1);
            orderWatcher.removeOrder(orderHash);
            expect(orderWatcher.getStats().orderCount).to.be.eq(0);
        });
    });
    describe('tests with cleanup', async () => {
        afterEach(async () => {
            orderWatcher.unsubscribe();
            const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
            orderWatcher.removeOrder(orderHash);
        });
        it('should emit orderStateInvalid when makerAddress allowance set to 0 for watched order', (done: DoneCallback) => {
            (async () => {
                signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                    makerAssetData,
                    takerAssetData,
                    makerAddress,
                    takerAddress,
                    fillableAmount,
                );
                const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                await orderWatcher.addOrderAsync(signedOrder);
                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                    expect(orderState.isValid).to.be.false();
                    const invalidOrderState = orderState as OrderStateInvalid;
                    expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                    expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
                });
                orderWatcher.subscribe(callback);
                await contractWrappers.erc20Token.setProxyAllowanceAsync(
                    makerTokenAddress,
                    makerAddress,
                    new BigNumber(0),
                );
            })().catch(done);
        });
        it('should not emit an orderState event when irrelevant Transfer event received', (done: DoneCallback) => {
            (async () => {
                signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                    makerAssetData,
                    takerAssetData,
                    makerAddress,
                    takerAddress,
                    fillableAmount,
                );
                await orderWatcher.addOrderAsync(signedOrder);
                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((_orderState: OrderState) => {
                    throw new Error('OrderState callback fired for irrelevant order');
                });
                orderWatcher.subscribe(callback);
                const notTheMaker = userAddresses[0];
                const anyRecipient = takerAddress;
                const transferAmount = new BigNumber(2);
                await contractWrappers.erc20Token.transferAsync(
                    makerTokenAddress,
                    notTheMaker,
                    anyRecipient,
                    transferAmount,
                );
                setTimeout(() => {
                    done();
                }, TIMEOUT_MS);
            })().catch(done);
        });
        it('should emit orderStateInvalid when makerAddress moves balance backing watched order', (done: DoneCallback) => {
            (async () => {
                signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                    makerAssetData,
                    takerAssetData,
                    makerAddress,
                    takerAddress,
                    fillableAmount,
                );
                const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                await orderWatcher.addOrderAsync(signedOrder);
                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                    expect(orderState.isValid).to.be.false();
                    const invalidOrderState = orderState as OrderStateInvalid;
                    expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                    expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerBalance);
                });
                orderWatcher.subscribe(callback);
                const anyRecipient = takerAddress;
                const makerBalance = await contractWrappers.erc20Token.getBalanceAsync(makerTokenAddress, makerAddress);
                await contractWrappers.erc20Token.transferAsync(
                    makerTokenAddress,
                    makerAddress,
                    anyRecipient,
                    makerBalance,
                );
            })().catch(done);
        });
        it('should emit orderStateInvalid when watched order fully filled', (done: DoneCallback) => {
            (async () => {
                signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                    makerAssetData,
                    takerAssetData,
                    makerAddress,
                    takerAddress,
                    fillableAmount,
                );
                const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                await orderWatcher.addOrderAsync(signedOrder);

                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                    expect(orderState.isValid).to.be.false();
                    const invalidOrderState = orderState as OrderStateInvalid;
                    expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                    expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderRemainingFillAmountZero);
                });
                orderWatcher.subscribe(callback);

                await contractWrappers.exchange.fillOrderAsync(signedOrder, fillableAmount, takerAddress);
            })().catch(done);
        });
        it('should include transactionHash in emitted orderStateInvalid when watched order fully filled', (done: DoneCallback) => {
            (async () => {
                signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                    makerAssetData,
                    takerAssetData,
                    makerAddress,
                    takerAddress,
                    fillableAmount,
                );
                await orderWatcher.addOrderAsync(signedOrder);

                let transactionHash: string;
                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                    expect(orderState.isValid).to.be.false();
                    const invalidOrderState = orderState as OrderStateInvalid;
                    expect(invalidOrderState.transactionHash).to.be.equal(transactionHash);
                });
                orderWatcher.subscribe(callback);

                transactionHash = await contractWrappers.exchange.fillOrderAsync(
                    signedOrder,
                    fillableAmount,
                    takerAddress,
                );
            })().catch(done);
        });
        it('should emit orderStateValid when watched order partially filled', (done: DoneCallback) => {
            (async () => {
                signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                    makerAssetData,
                    takerAssetData,
                    makerAddress,
                    takerAddress,
                    fillableAmount,
                );

                const makerBalance = await contractWrappers.erc20Token.getBalanceAsync(makerTokenAddress, makerAddress);
                const fillAmountInBaseUnits = new BigNumber(2);
                const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                await orderWatcher.addOrderAsync(signedOrder);

                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                    expect(orderState.isValid).to.be.true();
                    const validOrderState = orderState as OrderStateValid;
                    expect(validOrderState.orderHash).to.be.equal(orderHash);
                    const orderRelevantState = validOrderState.orderRelevantState;
                    const remainingMakerBalance = makerBalance.sub(fillAmountInBaseUnits);
                    const remainingFillable = fillableAmount.minus(fillAmountInBaseUnits);
                    expect(orderRelevantState.remainingFillableMakerAssetAmount).to.be.bignumber.equal(
                        remainingFillable,
                    );
                    expect(orderRelevantState.remainingFillableTakerAssetAmount).to.be.bignumber.equal(
                        remainingFillable,
                    );
                    expect(orderRelevantState.makerBalance).to.be.bignumber.equal(remainingMakerBalance);
                });
                orderWatcher.subscribe(callback);
                await contractWrappers.exchange.fillOrderAsync(signedOrder, fillAmountInBaseUnits, takerAddress);
            })().catch(done);
        });
        it('should trigger the callback when orders backing ZRX allowance changes', (done: DoneCallback) => {
            (async () => {
                const makerFee = Web3Wrapper.toBaseUnitAmount(new BigNumber(2), decimals);
                const takerFee = Web3Wrapper.toBaseUnitAmount(new BigNumber(0), decimals);
                signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
                    makerAssetData,
                    takerAssetData,
                    makerFee,
                    takerFee,
                    makerAddress,
                    takerAddress,
                    fillableAmount,
                    takerAddress,
                );
                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)();
                await orderWatcher.addOrderAsync(signedOrder);
                orderWatcher.subscribe(callback);
                await contractWrappers.erc20Token.setProxyAllowanceAsync(
                    zrxTokenAddress,
                    makerAddress,
                    new BigNumber(0),
                );
            })().catch(done);
        });
        describe('remainingFillable(M|T)akerTokenAmount', () => {
            it('should calculate correct remaining fillable', (done: DoneCallback) => {
                (async () => {
                    const takerFillableAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(10), decimals);
                    const makerFillableAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(20), decimals);
                    signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
                        makerAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        makerFillableAmount,
                        takerFillableAmount,
                    );
                    const fillAmountInBaseUnits = Web3Wrapper.toBaseUnitAmount(new BigNumber(2), decimals);
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.true();
                        const validOrderState = orderState as OrderStateValid;
                        expect(validOrderState.orderHash).to.be.equal(orderHash);
                        const orderRelevantState = validOrderState.orderRelevantState;
                        expect(orderRelevantState.remainingFillableMakerAssetAmount).to.be.bignumber.equal(
                            Web3Wrapper.toBaseUnitAmount(new BigNumber(16), decimals),
                        );
                        expect(orderRelevantState.remainingFillableTakerAssetAmount).to.be.bignumber.equal(
                            Web3Wrapper.toBaseUnitAmount(new BigNumber(8), decimals),
                        );
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.exchange.fillOrderAsync(signedOrder, fillAmountInBaseUnits, takerAddress);
                })().catch(done);
            });
            it('should equal approved amount when approved amount is lowest', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableAmount,
                    );

                    const changedMakerApprovalAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(3), decimals);
                    await orderWatcher.addOrderAsync(signedOrder);

                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        const validOrderState = orderState as OrderStateValid;
                        const orderRelevantState = validOrderState.orderRelevantState;
                        expect(orderRelevantState.remainingFillableMakerAssetAmount).to.be.bignumber.equal(
                            changedMakerApprovalAmount,
                        );
                        expect(orderRelevantState.remainingFillableTakerAssetAmount).to.be.bignumber.equal(
                            changedMakerApprovalAmount,
                        );
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc20Token.setProxyAllowanceAsync(
                        makerTokenAddress,
                        makerAddress,
                        changedMakerApprovalAmount,
                    );
                })().catch(done);
            });
            it('should equal balance amount when balance amount is lowest', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableAmount,
                    );

                    const makerBalance = await contractWrappers.erc20Token.getBalanceAsync(
                        makerTokenAddress,
                        makerAddress,
                    );

                    const remainingAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(1), decimals);
                    const transferAmount = makerBalance.sub(remainingAmount);
                    await orderWatcher.addOrderAsync(signedOrder);

                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.true();
                        const validOrderState = orderState as OrderStateValid;
                        const orderRelevantState = validOrderState.orderRelevantState;
                        expect(orderRelevantState.remainingFillableMakerAssetAmount).to.be.bignumber.equal(
                            remainingAmount,
                        );
                        expect(orderRelevantState.remainingFillableTakerAssetAmount).to.be.bignumber.equal(
                            remainingAmount,
                        );
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc20Token.transferAsync(
                        makerTokenAddress,
                        makerAddress,
                        constants.NULL_ADDRESS,
                        transferAmount,
                    );
                })().catch(done);
            });
            it('should equal ratio amount when fee balance is lowered', (done: DoneCallback) => {
                (async () => {
                    const takerFee = Web3Wrapper.toBaseUnitAmount(new BigNumber(0), decimals);
                    const makerFee = Web3Wrapper.toBaseUnitAmount(new BigNumber(5), decimals);
                    signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
                        makerAssetData,
                        takerAssetData,
                        makerFee,
                        takerFee,
                        makerAddress,
                        takerAddress,
                        fillableAmount,
                        feeRecipient,
                    );

                    const remainingFeeAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(3), decimals);

                    const remainingTokenAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(4), decimals);
                    const transferTokenAmount = makerFee.sub(remainingTokenAmount);
                    await orderWatcher.addOrderAsync(signedOrder);

                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        const validOrderState = orderState as OrderStateValid;
                        const orderRelevantState = validOrderState.orderRelevantState;
                        expect(orderRelevantState.remainingFillableMakerAssetAmount).to.be.bignumber.equal(
                            remainingFeeAmount,
                        );
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc20Token.setProxyAllowanceAsync(
                        zrxTokenAddress,
                        makerAddress,
                        remainingFeeAmount,
                    );
                    await contractWrappers.erc20Token.transferAsync(
                        makerTokenAddress,
                        makerAddress,
                        constants.NULL_ADDRESS,
                        transferTokenAmount,
                    );
                })().catch(done);
            });
            it('should calculate full amount when all available and non-divisible', (done: DoneCallback) => {
                (async () => {
                    const takerFee = Web3Wrapper.toBaseUnitAmount(new BigNumber(0), decimals);
                    const makerFee = Web3Wrapper.toBaseUnitAmount(new BigNumber(2), decimals);
                    signedOrder = await fillScenarios.createFillableSignedOrderWithFeesAsync(
                        makerAssetData,
                        takerAssetData,
                        makerFee,
                        takerFee,
                        makerAddress,
                        takerAddress,
                        fillableAmount,
                        feeRecipient,
                    );

                    await orderWatcher.addOrderAsync(signedOrder);

                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        const validOrderState = orderState as OrderStateValid;
                        const orderRelevantState = validOrderState.orderRelevantState;
                        expect(orderRelevantState.remainingFillableMakerAssetAmount).to.be.bignumber.equal(
                            fillableAmount,
                        );
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc20Token.setProxyAllowanceAsync(
                        makerTokenAddress,
                        makerAddress,
                        Web3Wrapper.toBaseUnitAmount(new BigNumber(100), decimals),
                    );
                })().catch(done);
            });
        });
        it('should emit orderStateInvalid when watched order cancelled', (done: DoneCallback) => {
            (async () => {
                signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                    makerAssetData,
                    takerAssetData,
                    makerAddress,
                    takerAddress,
                    fillableAmount,
                );
                const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                await orderWatcher.addOrderAsync(signedOrder);

                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                    expect(orderState.isValid).to.be.false();
                    const invalidOrderState = orderState as OrderStateInvalid;
                    expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                    expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderCancelled);
                });
                orderWatcher.subscribe(callback);
                await contractWrappers.exchange.cancelOrderAsync(signedOrder);
            })().catch(done);
        });
        it('should emit orderStateInvalid when within rounding error range after a partial fill', (done: DoneCallback) => {
            (async () => {
                const fillAmountInBaseUnits = new BigNumber(2);
                const makerAssetAmount = new BigNumber(1001);
                const takerAssetAmount = new BigNumber(3);
                signedOrder = await fillScenarios.createAsymmetricFillableSignedOrderAsync(
                    makerAssetData,
                    takerAssetData,
                    makerAddress,
                    takerAddress,
                    makerAssetAmount,
                    takerAssetAmount,
                );
                const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                await orderWatcher.addOrderAsync(signedOrder);
                const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                    expect(orderState.isValid).to.be.false();
                    const invalidOrderState = orderState as OrderStateInvalid;
                    expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                    expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderFillRoundingError);
                });
                orderWatcher.subscribe(callback);
                await contractWrappers.exchange.fillOrderAsync(signedOrder, fillAmountInBaseUnits, takerAddress);
            })().catch(done);
        });
        describe('erc721', () => {
            let makerErc721AssetData: string;
            let makerErc721TokenAddress: string;
            const tokenId = new BigNumber(42);
            [makerErc721TokenAddress] = tokenUtils.getDummyERC721TokenAddresses();
            makerErc721AssetData = assetDataUtils.encodeERC721AssetData(makerErc721TokenAddress, tokenId);
            const fillableErc721Amount = new BigNumber(1);
            it('should emit orderStateInvalid when maker allowance set to 0 for watched order', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerErc721AssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableErc721Amount,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc721Token.setApprovalAsync(
                        makerErc721TokenAddress,
                        constants.NULL_ADDRESS,
                        tokenId,
                    );
                })().catch(done);
            });
            it('should emit orderStateInvalid when maker allowance for all set to 0 for watched order', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerErc721AssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableErc721Amount,
                    );
                    await contractWrappers.erc721Token.setApprovalAsync(
                        makerErc721TokenAddress,
                        constants.NULL_ADDRESS,
                        tokenId,
                    );
                    let isApproved = true;
                    await contractWrappers.erc721Token.setProxyApprovalForAllAsync(
                        makerErc721TokenAddress,
                        makerAddress,
                        isApproved,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
                    });
                    orderWatcher.subscribe(callback);
                    isApproved = false;
                    await contractWrappers.erc721Token.setProxyApprovalForAllAsync(
                        makerErc721TokenAddress,
                        makerAddress,
                        isApproved,
                    );
                })().catch(done);
            });
            it('should emit orderStateInvalid when maker moves NFT backing watched order', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerErc721AssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableErc721Amount,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerBalance);
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc721Token.transferFromAsync(
                        makerErc721TokenAddress,
                        coinbase,
                        makerAddress,
                        tokenId,
                    );
                })().catch(done);
            });
        });
        describe('multiAsset', async () => {
            const tokenId = new BigNumber(42);
            const [makerErc721TokenAddress] = tokenUtils.getDummyERC721TokenAddresses();
            const makerErc721AssetData = assetDataUtils.encodeERC721AssetData(makerErc721TokenAddress, tokenId);
            const fillableErc721Amount = new BigNumber(1);
            const [makerErc20TokenAddress] = tokenUtils.getDummyERC20TokenAddresses();
            const makerErc20AssetData = assetDataUtils.encodeERC20AssetData(makerErc20TokenAddress);
            const fillableErc20Amount = new BigNumber(2);
            const multiAssetAmounts = [fillableErc721Amount, fillableErc20Amount];
            const nestedAssetData = [makerErc721AssetData, makerErc20AssetData];
            const makerMultiAssetData = assetDataUtils.encodeMultiAssetData(multiAssetAmounts, nestedAssetData);
            it('should emit orderStateInvalid when maker allowance of ERC721 token set to 0 for watched order', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerMultiAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableErc721Amount,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc721Token.setApprovalAsync(
                        makerErc721TokenAddress,
                        constants.NULL_ADDRESS,
                        tokenId,
                    );
                })().catch(done);
            });
            it('should emit orderStateInvalid when maker allowance for all of ERC721 token set to 0 for watched order', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerMultiAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableErc721Amount,
                    );
                    await contractWrappers.erc721Token.setApprovalAsync(
                        makerErc721TokenAddress,
                        constants.NULL_ADDRESS,
                        tokenId,
                    );
                    let isApproved = true;
                    await contractWrappers.erc721Token.setProxyApprovalForAllAsync(
                        makerErc721TokenAddress,
                        makerAddress,
                        isApproved,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
                    });
                    orderWatcher.subscribe(callback);
                    isApproved = false;
                    await contractWrappers.erc721Token.setProxyApprovalForAllAsync(
                        makerErc721TokenAddress,
                        makerAddress,
                        isApproved,
                    );
                })().catch(done);
            });
            it('should emit orderStateInvalid when maker moves ERC721 backing watched order', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerMultiAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableErc721Amount,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerBalance);
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc721Token.transferFromAsync(
                        makerErc721TokenAddress,
                        coinbase,
                        makerAddress,
                        tokenId,
                    );
                })().catch(done);
            });
            it('should emit orderStateInvalid when maker allowance of ERC20 token set to 0 for watched order', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerMultiAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableErc721Amount,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerAllowance);
                    });
                    orderWatcher.subscribe(callback);
                    await contractWrappers.erc20Token.setProxyAllowanceAsync(
                        makerErc20TokenAddress,
                        makerAddress,
                        new BigNumber(0),
                    );
                })().catch(done);
            });
            it('should not emit an orderState event when irrelevant ERC20 Transfer event received', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerMultiAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableAmount,
                    );
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((_orderState: OrderState) => {
                        throw new Error('OrderState callback fired for irrelevant order');
                    });
                    orderWatcher.subscribe(callback);
                    const notTheMaker = userAddresses[0];
                    const anyRecipient = takerAddress;
                    const transferAmount = new BigNumber(2);
                    await contractWrappers.erc20Token.transferAsync(
                        makerTokenAddress,
                        notTheMaker,
                        anyRecipient,
                        transferAmount,
                    );
                    setTimeout(() => {
                        done();
                    }, TIMEOUT_MS);
                })().catch(done);
            });
            it('should emit orderStateInvalid when makerAddress moves ERC20 balance backing watched order', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerMultiAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableAmount,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);
                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.InsufficientMakerBalance);
                    });
                    orderWatcher.subscribe(callback);
                    const anyRecipient = takerAddress;
                    const makerBalance = await contractWrappers.erc20Token.getBalanceAsync(
                        makerTokenAddress,
                        makerAddress,
                    );
                    await contractWrappers.erc20Token.transferAsync(
                        makerTokenAddress,
                        makerAddress,
                        anyRecipient,
                        makerBalance,
                    );
                })().catch(done);
            });
            // TODO(abandeali1): The following test will fail until the MAP has been deployed and activated.
            it.skip('should emit orderStateInvalid when watched order fully filled', (done: DoneCallback) => {
                (async () => {
                    signedOrder = await fillScenarios.createFillableSignedOrderAsync(
                        makerMultiAssetData,
                        takerAssetData,
                        makerAddress,
                        takerAddress,
                        fillableAmount,
                    );
                    const orderHash = orderHashUtils.getOrderHashHex(signedOrder);
                    await orderWatcher.addOrderAsync(signedOrder);

                    const callback = callbackErrorReporter.reportNodeCallbackErrors(done)((orderState: OrderState) => {
                        expect(orderState.isValid).to.be.false();
                        const invalidOrderState = orderState as OrderStateInvalid;
                        expect(invalidOrderState.orderHash).to.be.equal(orderHash);
                        expect(invalidOrderState.error).to.be.equal(ExchangeContractErrs.OrderRemainingFillAmountZero);
                    });
                    orderWatcher.subscribe(callback);

                    await contractWrappers.exchange.fillOrderAsync(signedOrder, fillableAmount, takerAddress);
                })().catch(done);
            });
        });
    });
}); // tslint:disable:max-file-line-count