aboutsummaryrefslogtreecommitdiffstats
path: root/packages/website/ts/blockchain.ts
blob: 37f746f7caa813dc559a976896fe94b83c8fec88 (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
import {
    BlockRange,
    ContractWrappers,
    DecodedLogEvent,
    ExchangeCancelEventArgs,
    ExchangeEventArgs,
    ExchangeEvents,
    ExchangeFillEventArgs,
    IndexedFilterValues,
} from '@0x/contract-wrappers';
import { assetDataUtils, orderHashUtils, signatureUtils } from '@0x/order-utils';
import { EtherscanLinkSuffixes, utils as sharedUtils } from '@0x/react-shared';
import {
    ledgerEthereumBrowserClientFactoryAsync,
    LedgerSubprovider,
    MetamaskSubprovider,
    RedundantSubprovider,
    RPCSubprovider,
    SignerSubprovider,
    Web3ProviderEngine,
} from '@0x/subproviders';
import { SignedOrder, Token as ZeroExToken } from '@0x/types';
import { BigNumber, intervalUtils, logUtils } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import { BlockParam, LogWithDecodedArgs, Provider, TransactionReceiptWithDecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
import * as moment from 'moment';
import * as React from 'react';
import contract from 'truffle-contract';
import { BlockchainWatcher } from 'ts/blockchain_watcher';
import { AssetSendCompleted } from 'ts/components/flash_messages/asset_send_completed';
import { TransactionSubmitted } from 'ts/components/flash_messages/transaction_submitted';
import { trackedTokenStorage } from 'ts/local_storage/tracked_token_storage';
import { tradeHistoryStorage } from 'ts/local_storage/trade_history_storage';
import { Dispatcher } from 'ts/redux/dispatcher';
import {
    BlockchainCallErrs,
    BlockchainErrs,
    ContractInstance,
    Fill,
    InjectedProvider,
    InjectedProviderObservable,
    InjectedProviderUpdate,
    Providers,
    ProviderType,
    Side,
    SideToAssetToken,
    Token,
    TokenByAddress,
} from 'ts/types';
import { backendClient } from 'ts/utils/backend_client';
import { configs } from 'ts/utils/configs';
import { constants } from 'ts/utils/constants';
import { errorReporter } from 'ts/utils/error_reporter';
import { fakeTokenRegistry } from 'ts/utils/fake_token_registry';
import { tokenAddressOverrides } from 'ts/utils/token_address_overrides';
import { utils } from 'ts/utils/utils';
import FilterSubprovider from 'web3-provider-engine/subproviders/filters';

import MintableArtifacts from '../contracts/Mintable.json';

const BLOCK_NUMBER_BACK_TRACK = 50;
const GWEI_IN_WEI = 1000000000;

const providerToName: { [provider: string]: string } = {
    [Providers.Metamask]: constants.PROVIDER_NAME_METAMASK,
    [Providers.Parity]: constants.PROVIDER_NAME_PARITY_SIGNER,
    [Providers.Mist]: constants.PROVIDER_NAME_MIST,
    [Providers.CoinbaseWallet]: constants.PROVIDER_NAME_COINBASE_WALLET,
    [Providers.Cipher]: constants.PROVIDER_NAME_CIPHER,
};

export class Blockchain {
    public networkId: number;
    public nodeVersion: string;
    private _contractWrappers: ContractWrappers;
    private readonly _dispatcher: Dispatcher;
    private _web3Wrapper?: Web3Wrapper;
    private _blockchainWatcher?: BlockchainWatcher;
    private _injectedProviderObservable?: InjectedProviderObservable;
    private readonly _injectedProviderUpdateHandler: (update: InjectedProviderUpdate) => Promise<void>;
    private _userAddressIfExists: string;
    private _ledgerSubprovider: LedgerSubprovider;
    private _defaultGasPrice: BigNumber;
    private _watchGasPriceIntervalId: NodeJS.Timer;
    private _injectedProviderIfExists?: InjectedProvider;
    private static _getNameGivenProvider(provider: Provider): string {
        const providerType = utils.getProviderType(provider);
        const providerNameIfExists = providerToName[providerType];
        if (_.isUndefined(providerNameIfExists)) {
            return constants.PROVIDER_NAME_GENERIC;
        }
        return providerNameIfExists;
    }
    private static async _getProviderAsync(
        injectedProviderIfExists?: InjectedProvider,
        networkIdIfExists?: number,
        shouldUserLedgerProvider: boolean = false,
    ): Promise<[Provider, LedgerSubprovider | undefined]> {
        const doesInjectedProviderExist = !_.isUndefined(injectedProviderIfExists);
        const isNetworkIdAvailable = !_.isUndefined(networkIdIfExists);
        const publicNodeUrlsIfExistsForNetworkId = configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkIdIfExists];
        const isPublicNodeAvailableForNetworkId = !_.isUndefined(publicNodeUrlsIfExistsForNetworkId);

        if (shouldUserLedgerProvider && isNetworkIdAvailable) {
            const isU2FSupported = await utils.isU2FSupportedAsync();
            if (!isU2FSupported) {
                throw new Error('Cannot update providerType to LEDGER without U2F support');
            }
            const provider = new Web3ProviderEngine();
            const ledgerWalletConfigs = {
                networkId: networkIdIfExists,
                ledgerEthereumClientFactoryAsync: ledgerEthereumBrowserClientFactoryAsync,
            };
            const ledgerSubprovider = new LedgerSubprovider(ledgerWalletConfigs);
            provider.addProvider(ledgerSubprovider);
            provider.addProvider(new FilterSubprovider());
            const rpcSubproviders = _.map(configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkIdIfExists], publicNodeUrl => {
                return new RPCSubprovider(publicNodeUrl);
            });
            provider.addProvider(new RedundantSubprovider(rpcSubproviders));
            provider.start();
            return [provider, ledgerSubprovider];
        } else if (doesInjectedProviderExist && isPublicNodeAvailableForNetworkId) {
            // We catch all requests involving a users account and send it to the injectedWeb3
            // instance. All other requests go to the public hosted node.
            const provider = new Web3ProviderEngine();
            const providerName = this._getNameGivenProvider(injectedProviderIfExists);
            // Wrap Metamask in a compatability wrapper MetamaskSubprovider (to handle inconsistencies)
            const signerSubprovider =
                providerName === constants.PROVIDER_NAME_METAMASK
                    ? new MetamaskSubprovider(injectedProviderIfExists)
                    : new SignerSubprovider(injectedProviderIfExists);
            provider.addProvider(signerSubprovider);
            provider.addProvider(new FilterSubprovider());
            const rpcSubproviders = _.map(publicNodeUrlsIfExistsForNetworkId, publicNodeUrl => {
                return new RPCSubprovider(publicNodeUrl);
            });
            provider.addProvider(new RedundantSubprovider(rpcSubproviders));
            provider.start();
            return [provider, undefined];
        } else if (doesInjectedProviderExist) {
            // Since no public node for this network, all requests go to injectedWeb3 instance
            return [injectedProviderIfExists, undefined];
        } else {
            // If no injectedWeb3 instance, all requests fallback to our public hosted mainnet/testnet node
            // We do this so that users can still browse the 0x Portal DApp even if they do not have web3
            // injected into their browser.
            const provider = new Web3ProviderEngine();
            provider.addProvider(new FilterSubprovider());
            const networkId = constants.NETWORK_ID_MAINNET;
            const rpcSubproviders = _.map(configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId], publicNodeUrl => {
                return new RPCSubprovider(publicNodeUrl);
            });
            provider.addProvider(new RedundantSubprovider(rpcSubproviders));
            provider.start();
            return [provider, undefined];
        }
    }
    constructor(dispatcher: Dispatcher) {
        this._dispatcher = dispatcher;
        const defaultGasPrice = GWEI_IN_WEI * 40;
        this._defaultGasPrice = new BigNumber(defaultGasPrice);
        // We need a unique reference to this function so we can use it to unsubcribe.
        this._injectedProviderUpdateHandler = this._handleInjectedProviderUpdateAsync.bind(this);
        // tslint:disable-next-line:no-floating-promises
        this._onPageLoadInitFireAndForgetAsync();
    }
    public async networkIdUpdatedFireAndForgetAsync(newNetworkId: number): Promise<void> {
        const isConnected = !_.isUndefined(newNetworkId);
        if (!isConnected) {
            this.networkId = newNetworkId;
            this._dispatcher.encounteredBlockchainError(BlockchainErrs.DisconnectedFromEthereumNode);
            this._dispatcher.updateShouldBlockchainErrDialogBeOpen(true);
        } else if (this.networkId !== newNetworkId) {
            this.networkId = newNetworkId;
            this._dispatcher.encounteredBlockchainError(BlockchainErrs.NoError);
            await this.fetchTokenInformationAsync();
            await this._rehydrateStoreWithContractEventsAsync();
        }
    }
    public async userAddressUpdatedFireAndForgetAsync(newUserAddress: string): Promise<void> {
        if (this._userAddressIfExists !== newUserAddress) {
            this._userAddressIfExists = newUserAddress;
            await this.fetchTokenInformationAsync();
            await this._rehydrateStoreWithContractEventsAsync();
        }
    }
    public async nodeVersionUpdatedFireAndForgetAsync(nodeVersion: string): Promise<void> {
        if (this.nodeVersion !== nodeVersion) {
            this.nodeVersion = nodeVersion;
        }
    }
    public async isAddressInTokenRegistryAsync(tokenAddress: string): Promise<boolean> {
        const tokens = fakeTokenRegistry[this.networkId];
        const tokenIfExists = _.find(tokens, { address: tokenAddress });

        // HACK: Override token addresses on testnets
        const tokenSymbolToAddressOverrides = tokenAddressOverrides[this.networkId];
        let isTokenAddressInOverrides = false;
        if (!_.isUndefined(tokenSymbolToAddressOverrides)) {
            isTokenAddressInOverrides = _.values(tokenSymbolToAddressOverrides).includes(tokenAddress);
        }
        return !_.isUndefined(tokenIfExists) || isTokenAddressInOverrides;
    }
    public getLedgerDerivationPathIfExists(): string {
        if (_.isUndefined(this._ledgerSubprovider)) {
            return undefined;
        }
        const path = this._ledgerSubprovider.getPath();
        return path;
    }
    public updateLedgerDerivationPathIfExists(path: string): void {
        if (_.isUndefined(this._ledgerSubprovider)) {
            return; // noop
        }
        this._ledgerSubprovider.setPath(path);
    }
    public async updateProviderToLedgerAsync(networkId: number): Promise<void> {
        const shouldPollUserAddress = false;
        const shouldUserLedgerProvider = true;
        await this._resetOrInitializeAsync(networkId, shouldPollUserAddress, shouldUserLedgerProvider);
    }
    public async updateProviderToInjectedAsync(): Promise<void> {
        const shouldPollUserAddress = true;
        const shouldUserLedgerProvider = false;
        this._dispatcher.updateBlockchainIsLoaded(false);
        // We don't want to be out of sync with the network the injected provider declares.
        const networkId = await this._getInjectedProviderNetworkIdIfExistsAsync();
        await this._resetOrInitializeAsync(networkId, shouldPollUserAddress, shouldUserLedgerProvider);
    }
    public async setProxyAllowanceAsync(token: Token, amountInBaseUnits: BigNumber): Promise<void> {
        utils.assert(this.isValidAddress(token.address), BlockchainCallErrs.TokenAddressIsInvalid);
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);
        utils.assert(!_.isUndefined(this._contractWrappers), 'Contract Wrappers must be instantiated.');

        this._showFlashMessageIfLedger();
        const txHash = await this._contractWrappers.erc20Token.setProxyAllowanceAsync(
            token.address,
            this._userAddressIfExists,
            amountInBaseUnits,
            {
                gasPrice: this._defaultGasPrice,
            },
        );
        await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
    }
    public async sendAsync(toAddress: string, amountInBaseUnits: BigNumber): Promise<void> {
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);
        const transaction = {
            from: this._userAddressIfExists,
            to: toAddress,
            value: amountInBaseUnits,
            gasPrice: this._defaultGasPrice,
        };
        this._showFlashMessageIfLedger();
        const txHash = await this._web3Wrapper.sendTransactionAsync(transaction);
        await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
        const etherScanLinkIfExists = sharedUtils.getEtherScanLinkIfExists(
            txHash,
            this.networkId,
            EtherscanLinkSuffixes.Tx,
        );
        this._dispatcher.showFlashMessage(
            React.createElement(AssetSendCompleted, {
                etherScanLinkIfExists,
                toAddress,
                amountInBaseUnits,
                decimals: constants.DECIMAL_PLACES_ETH,
                symbol: constants.ETHER_SYMBOL,
            }),
        );
    }
    public async transferAsync(token: Token, toAddress: string, amountInBaseUnits: BigNumber): Promise<void> {
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        this._showFlashMessageIfLedger();
        const txHash = await this._contractWrappers.erc20Token.transferAsync(
            token.address,
            this._userAddressIfExists,
            toAddress,
            amountInBaseUnits,
            {
                gasPrice: this._defaultGasPrice,
            },
        );
        await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
        const etherScanLinkIfExists = sharedUtils.getEtherScanLinkIfExists(
            txHash,
            this.networkId,
            EtherscanLinkSuffixes.Tx,
        );
        this._dispatcher.showFlashMessage(
            React.createElement(AssetSendCompleted, {
                etherScanLinkIfExists,
                toAddress,
                amountInBaseUnits,
                decimals: token.decimals,
                symbol: token.symbol,
            }),
        );
    }
    public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber): Promise<BigNumber> {
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);
        this._showFlashMessageIfLedger();
        const txHash = await this._contractWrappers.exchange.fillOrderAsync(
            signedOrder,
            fillTakerTokenAmount,
            this._userAddressIfExists,
            {
                gasPrice: this._defaultGasPrice,
            },
        );
        const receipt = await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
        const logs: Array<LogWithDecodedArgs<ExchangeEventArgs>> = receipt.logs as any;
        const logFill = _.find(logs, { event: ExchangeEvents.Fill });
        const args = (logFill.args as any) as ExchangeFillEventArgs;
        const takerAssetFilledAmount = args.takerAssetFilledAmount;
        return takerAssetFilledAmount;
    }
    public async cancelOrderAsync(signedOrder: SignedOrder): Promise<string> {
        this._showFlashMessageIfLedger();
        const txHash = await this._contractWrappers.exchange.cancelOrderAsync(signedOrder, {
            gasPrice: this._defaultGasPrice,
        });
        const receipt = await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
        const logs: Array<LogWithDecodedArgs<ExchangeEventArgs>> = receipt.logs as any;
        const logCancel = _.find(logs, { event: ExchangeEvents.Cancel });
        const args = (logCancel.args as any) as ExchangeCancelEventArgs;
        const cancelledOrderHash = args.orderHash;
        return cancelledOrderHash;
    }
    public async getUnavailableTakerAmountAsync(orderHash: string): Promise<BigNumber> {
        utils.assert(orderHashUtils.isValidOrderHash(orderHash), 'Must be valid orderHash');
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');
        const unavailableTakerAmount = await this._contractWrappers.exchange.getFilledTakerAssetAmountAsync(orderHash);
        return unavailableTakerAmount;
    }
    public getExchangeContractAddressIfExists(): string | undefined {
        return this._contractWrappers.exchange.address;
    }
    public async validateFillOrderThrowIfInvalidAsync(
        signedOrder: SignedOrder,
        fillTakerTokenAmount: BigNumber,
        takerAddress: string,
    ): Promise<void> {
        await this._contractWrappers.exchange.validateFillOrderThrowIfInvalidAsync(
            signedOrder,
            fillTakerTokenAmount,
            takerAddress,
        );
    }
    public isValidAddress(address: string): boolean {
        const lowercaseAddress = address.toLowerCase();
        return Web3Wrapper.isAddress(lowercaseAddress);
    }
    public async isValidSignatureAsync(data: string, signature: string, signerAddress: string): Promise<boolean> {
        const result = await signatureUtils.isValidSignatureAsync(
            this._contractWrappers.getProvider(),
            data,
            signature,
            signerAddress,
        );
        return result;
    }
    public async pollTokenBalanceAsync(token: Token): Promise<BigNumber> {
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        const [currBalance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddressIfExists, token.address);

        const newTokenBalancePromise = new Promise((resolve: (balance: BigNumber) => void, reject) => {
            const tokenPollInterval = intervalUtils.setAsyncExcludingInterval(
                async () => {
                    const [balance] = await this.getTokenBalanceAndAllowanceAsync(
                        this._userAddressIfExists,
                        token.address,
                    );
                    if (!balance.eq(currBalance)) {
                        intervalUtils.clearAsyncExcludingInterval(tokenPollInterval);
                        resolve(balance);
                    }
                },
                5000,
                (err: Error) => {
                    logUtils.log(`Polling tokenBalance failed: ${err}`);
                    intervalUtils.clearAsyncExcludingInterval(tokenPollInterval);
                    reject(err);
                },
            );
        });

        return newTokenBalancePromise;
    }
    public async signOrderHashAsync(orderHash: string): Promise<string> {
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');
        const makerAddress = this._userAddressIfExists;
        // If makerAddress is undefined, this means they have a web3 instance injected into their browser
        // but no account addresses associated with it.
        if (_.isUndefined(makerAddress)) {
            throw new Error('Tried to send a sign request but user has no associated addresses');
        }
        this._showFlashMessageIfLedger();
        const provider = this._contractWrappers.getProvider();
        const ecSignatureString = await signatureUtils.ecSignHashAsync(provider, orderHash, makerAddress);
        this._dispatcher.updateSignature(ecSignatureString);
        return ecSignatureString;
    }
    public async mintTestTokensAsync(token: Token): Promise<void> {
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        const mintableContract = await this._instantiateContractIfExistsAsync(MintableArtifacts, token.address);
        this._showFlashMessageIfLedger();
        await mintableContract.mint(constants.MINT_AMOUNT, {
            from: this._userAddressIfExists,
            gasPrice: this._defaultGasPrice,
        });
    }
    public async getBalanceInWeiAsync(owner: string): Promise<BigNumber> {
        const balanceInWei = await this._web3Wrapper.getBalanceInWeiAsync(owner);
        return balanceInWei;
    }
    public async convertEthToWrappedEthTokensAsync(etherTokenAddress: string, amount: BigNumber): Promise<void> {
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        this._showFlashMessageIfLedger();
        const txHash = await this._contractWrappers.etherToken.depositAsync(
            etherTokenAddress,
            amount,
            this._userAddressIfExists,
            {
                gasPrice: this._defaultGasPrice,
            },
        );
        await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
    }
    public async convertWrappedEthTokensToEthAsync(etherTokenAddress: string, amount: BigNumber): Promise<void> {
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        this._showFlashMessageIfLedger();
        const txHash = await this._contractWrappers.etherToken.withdrawAsync(
            etherTokenAddress,
            amount,
            this._userAddressIfExists,
            {
                gasPrice: this._defaultGasPrice,
            },
        );
        await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash);
    }
    public async doesContractExistAtAddressAsync(address: string): Promise<boolean> {
        const doesContractExist = await this._web3Wrapper.doesContractExistAtAddressAsync(address);
        return doesContractExist;
    }
    public async getCurrentUserTokenBalanceAndAllowanceAsync(tokenAddress: string): Promise<BigNumber[]> {
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        const tokenBalanceAndAllowance = await this.getTokenBalanceAndAllowanceAsync(
            this._userAddressIfExists,
            tokenAddress,
        );
        return tokenBalanceAndAllowance;
    }
    public async getTokenBalanceAndAllowanceAsync(
        ownerAddressIfExists: string,
        tokenAddress: string,
    ): Promise<[BigNumber, BigNumber]> {
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');

        if (_.isUndefined(ownerAddressIfExists)) {
            const zero = new BigNumber(0);
            return [zero, zero];
        }
        let balance = new BigNumber(0);
        let allowance = new BigNumber(0);
        if (this._doesUserAddressExist()) {
            [balance, allowance] = await Promise.all([
                this._contractWrappers.erc20Token.getBalanceAsync(tokenAddress, ownerAddressIfExists),
                this._contractWrappers.erc20Token.getProxyAllowanceAsync(tokenAddress, ownerAddressIfExists),
            ]);
        }
        return [balance, allowance];
    }
    public async getUserAccountsAsync(): Promise<string[]> {
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');
        const provider = this._contractWrappers.getProvider();
        const web3Wrapper = new Web3Wrapper(provider);
        const userAccountsIfExists = await web3Wrapper.getAvailableAddressesAsync();
        return userAccountsIfExists;
    }
    // HACK: When a user is using a Ledger, we simply dispatch the selected userAddress, which
    // by-passes the web3Wrapper logic for updating the prevUserAddress. We therefore need to
    // manually update it. This should only be called by the LedgerConfigDialog.
    public updateWeb3WrapperPrevUserAddress(newUserAddress: string): void {
        this._blockchainWatcher.updatePrevUserAddress(newUserAddress);
    }
    public destroy(): void {
        this._blockchainWatcher.destroy();
        if (this._injectedProviderObservable) {
            this._injectedProviderObservable.unsubscribe(this._injectedProviderUpdateHandler);
        }
        this._stopWatchingExchangeLogFillEvents();
        this._stopWatchingGasPrice();
    }
    public async fetchTokenInformationAsync(): Promise<void> {
        utils.assert(
            !_.isUndefined(this.networkId),
            'Cannot call fetchTokenInformationAsync if disconnected from Ethereum node',
        );

        this._dispatcher.updateBlockchainIsLoaded(false);

        const tokenRegistryTokensByAddress = await this._getTokenRegistryTokensByAddressAsync();

        const trackedTokensByAddress = _.isUndefined(this._userAddressIfExists)
            ? {}
            : trackedTokenStorage.getTrackedTokensByAddress(this._userAddressIfExists, this.networkId);
        const tokenRegistryTokens = _.values(tokenRegistryTokensByAddress);
        const tokenRegistryTokenSymbols = _.map(tokenRegistryTokens, t => t.symbol);
        const defaultTrackedTokensInRegistry = _.intersection(
            tokenRegistryTokenSymbols,
            configs.DEFAULT_TRACKED_TOKEN_SYMBOLS,
        );
        const currentTimestamp = moment().unix();
        if (defaultTrackedTokensInRegistry.length !== configs.DEFAULT_TRACKED_TOKEN_SYMBOLS.length) {
            this._dispatcher.updateShouldBlockchainErrDialogBeOpen(true);
            this._dispatcher.encounteredBlockchainError(BlockchainErrs.DefaultTokensNotInTokenRegistry);
            const err = new Error(
                `Default tracked tokens (${JSON.stringify(
                    configs.DEFAULT_TRACKED_TOKEN_SYMBOLS,
                )}) not found in tokenRegistry: ${JSON.stringify(tokenRegistryTokens)}`,
            );
            errorReporter.report(err);
            return;
        }
        if (_.isEmpty(trackedTokensByAddress)) {
            _.each(configs.DEFAULT_TRACKED_TOKEN_SYMBOLS, symbol => {
                const token = _.find(tokenRegistryTokens, t => t.symbol === symbol);
                token.trackedTimestamp = currentTimestamp;
                trackedTokensByAddress[token.address] = token;
            });
            if (!_.isUndefined(this._userAddressIfExists)) {
                _.each(trackedTokensByAddress, (token: Token) => {
                    trackedTokenStorage.addTrackedTokenToUser(this._userAddressIfExists, this.networkId, token);
                });
            }
        } else {
            // Properly set all tokenRegistry tokens `trackedTimestamp` if they are in the existing trackedTokens array
            _.each(trackedTokensByAddress, (trackedToken: Token, address: string) => {
                if (!_.isUndefined(tokenRegistryTokensByAddress[address])) {
                    tokenRegistryTokensByAddress[address].trackedTimestamp = trackedToken.trackedTimestamp;
                }
            });
        }
        const allTokensByAddress = {
            ...tokenRegistryTokensByAddress,
            ...trackedTokensByAddress,
        };
        const allTokens = _.values(allTokensByAddress);
        const mostPopularTradingPairTokens: Token[] = [
            _.find(allTokens, { symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[0] }),
            _.find(allTokens, { symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[1] }),
        ];
        const sideToAssetToken: SideToAssetToken = {
            [Side.Deposit]: {
                address: mostPopularTradingPairTokens[0].address,
            },
            [Side.Receive]: {
                address: mostPopularTradingPairTokens[1].address,
            },
        };
        this._dispatcher.batchDispatch(allTokensByAddress, this.networkId, this._userAddressIfExists, sideToAssetToken);

        this._dispatcher.updateBlockchainIsLoaded(true);
    }
    private async _getInjectedProviderIfExistsAsync(): Promise<InjectedProvider | undefined> {
        if (!_.isUndefined(this._injectedProviderIfExists)) {
            return this._injectedProviderIfExists;
        }
        let injectedProviderIfExists = (window as any).ethereum;
        if (!_.isUndefined(injectedProviderIfExists)) {
            if (!_.isUndefined(injectedProviderIfExists.enable)) {
                try {
                    await injectedProviderIfExists.enable();
                } catch (err) {
                    errorReporter.report(err);
                }
            }
        } else {
            const injectedWeb3IfExists = (window as any).web3;
            if (!_.isUndefined(injectedWeb3IfExists) && !_.isUndefined(injectedWeb3IfExists.currentProvider)) {
                injectedProviderIfExists = injectedWeb3IfExists.currentProvider;
            } else {
                return undefined;
            }
        }
        this._injectedProviderIfExists = injectedProviderIfExists;
        return injectedProviderIfExists;
    }
    private async _getInjectedProviderNetworkIdIfExistsAsync(): Promise<number | undefined> {
        // If the user has an injectedWeb3 instance that is disconnected from a backing
        // Ethereum node, this call will throw. We need to handle this case gracefully
        const injectedProviderIfExists = await this._getInjectedProviderIfExistsAsync();
        let networkIdIfExists: number;
        if (!_.isUndefined(injectedProviderIfExists)) {
            try {
                const injectedWeb3Wrapper = new Web3Wrapper(injectedProviderIfExists);
                networkIdIfExists = await injectedWeb3Wrapper.getNetworkIdAsync();
            } catch (err) {
                // Ignore error and proceed with networkId undefined
            }
        }
        return networkIdIfExists;
    }
    private async _showEtherScanLinkAndAwaitTransactionMinedAsync(
        txHash: string,
    ): Promise<TransactionReceiptWithDecodedLogs> {
        const etherScanLinkIfExists = sharedUtils.getEtherScanLinkIfExists(
            txHash,
            this.networkId,
            EtherscanLinkSuffixes.Tx,
        );
        this._dispatcher.showFlashMessage(
            React.createElement(TransactionSubmitted, {
                etherScanLinkIfExists,
            }),
        );
        const provider = this._contractWrappers.getProvider();
        const web3Wrapper = new Web3Wrapper(provider);
        const exchangeAbi = this._contractWrappers.exchange.abi;
        web3Wrapper.abiDecoder.addABI(exchangeAbi);
        const receipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash);
        return receipt;
    }
    private _doesUserAddressExist(): boolean {
        return !_.isUndefined(this._userAddressIfExists);
    }
    private async _handleInjectedProviderUpdateAsync(update: InjectedProviderUpdate): Promise<void> {
        if (update.networkVersion === 'loading' || !_.isUndefined(this._ledgerSubprovider)) {
            return;
        }
        const updatedNetworkId = _.parseInt(update.networkVersion);
        if (this.networkId === updatedNetworkId) {
            return;
        }
        const shouldPollUserAddress = true;
        const shouldUserLedgerProvider = false;
        await this._resetOrInitializeAsync(updatedNetworkId, shouldPollUserAddress, shouldUserLedgerProvider);
    }
    private async _rehydrateStoreWithContractEventsAsync(): Promise<void> {
        // Ensure we are only ever listening to one set of events
        this._stopWatchingExchangeLogFillEvents();

        if (!this._doesUserAddressExist()) {
            return; // short-circuit
        }

        if (!_.isUndefined(this._contractWrappers)) {
            // Since we do not have an index on the `taker` address and want to show
            // transactions where an account is either the `maker` or `taker`, we loop
            // through all fill events, and filter/cache them client-side.
            const filterIndexObj = {};
            await this._startListeningForExchangeLogFillEventsAsync(filterIndexObj);
        }
    }
    private async _startListeningForExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues): Promise<void> {
        utils.assert(!_.isUndefined(this._contractWrappers), 'ContractWrappers must be instantiated.');
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        // Fetch historical logs
        await this._fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues);

        // Start a subscription for new logs
        this._contractWrappers.exchange.subscribe(
            ExchangeEvents.Fill,
            indexFilterValues,
            async (err: Error, decodedLogEvent: DecodedLogEvent<ExchangeFillEventArgs>) => {
                if (err) {
                    // Note: it's not entirely clear from the documentation which
                    // errors will be thrown by `watch`. For now, let's log the error
                    // to rollbar and stop watching when one occurs
                    errorReporter.report(err); // fire and forget
                    return;
                } else {
                    const decodedLog = decodedLogEvent.log;
                    if (!this._doesLogEventInvolveUser(decodedLog)) {
                        return; // We aren't interested in the fill event
                    }
                    this._updateLatestFillsBlockIfNeeded(decodedLog.blockNumber);
                    const fill = await this._convertDecodedLogToFillAsync(decodedLog);
                    if (decodedLogEvent.isRemoved) {
                        tradeHistoryStorage.removeFillFromUser(this._userAddressIfExists, this.networkId, fill);
                    } else {
                        tradeHistoryStorage.addFillToUser(this._userAddressIfExists, this.networkId, fill);
                    }
                }
            },
        );
    }
    private async _fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues): Promise<void> {
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        const fromBlock = tradeHistoryStorage.getFillsLatestBlock(this._userAddressIfExists, this.networkId);
        const blockRange: BlockRange = {
            fromBlock,
            toBlock: 'latest' as BlockParam,
        };
        const decodedLogs = await this._contractWrappers.exchange.getLogsAsync<ExchangeFillEventArgs>(
            ExchangeEvents.Fill,
            blockRange,
            indexFilterValues,
        );
        for (const decodedLog of decodedLogs) {
            if (!this._doesLogEventInvolveUser(decodedLog)) {
                continue; // We aren't interested in the fill event
            }
            this._updateLatestFillsBlockIfNeeded(decodedLog.blockNumber);
            const fill = await this._convertDecodedLogToFillAsync(decodedLog);
            tradeHistoryStorage.addFillToUser(this._userAddressIfExists, this.networkId, fill);
        }
    }
    private async _convertDecodedLogToFillAsync(decodedLog: LogWithDecodedArgs<ExchangeFillEventArgs>): Promise<Fill> {
        const args = decodedLog.args;
        const blockTimestamp = await this._web3Wrapper.getBlockTimestampAsync(decodedLog.blockHash);
        const makerToken = assetDataUtils.decodeERC20AssetData(args.makerAssetData).tokenAddress;
        const takerToken = assetDataUtils.decodeERC20AssetData(args.takerAssetData).tokenAddress;
        const fill = {
            filledTakerTokenAmount: args.takerAssetFilledAmount,
            filledMakerTokenAmount: args.makerAssetFilledAmount,
            logIndex: decodedLog.logIndex,
            maker: args.makerAddress,
            orderHash: args.orderHash,
            taker: args.takerAddress,
            makerToken,
            takerToken,
            paidMakerFee: args.makerFeePaid,
            paidTakerFee: args.takerFeePaid,
            transactionHash: decodedLog.transactionHash,
            blockTimestamp,
        };
        return fill;
    }
    private _doesLogEventInvolveUser(decodedLog: LogWithDecodedArgs<ExchangeFillEventArgs>): boolean {
        const args = decodedLog.args;
        const isUserMakerOrTaker = args.maker === this._userAddressIfExists || args.taker === this._userAddressIfExists;
        return isUserMakerOrTaker;
    }
    private _updateLatestFillsBlockIfNeeded(blockNumber: number): void {
        utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses);

        const isBlockPending = _.isNull(blockNumber);
        if (!isBlockPending) {
            // Hack: I've observed the behavior where a client won't register certain fill events
            // and lowering the cache blockNumber fixes the issue. As a quick fix for now, simply
            // set the cached blockNumber 50 below the one returned. This way, upon refreshing, a user
            // would still attempt to re-fetch events from the previous 50 blocks, but won't need to
            // re-fetch all events in all blocks.
            // TODO: Debug if this is a race condition, and apply a more precise fix
            const blockNumberToSet =
                blockNumber - BLOCK_NUMBER_BACK_TRACK < 0 ? 0 : blockNumber - BLOCK_NUMBER_BACK_TRACK;
            tradeHistoryStorage.setFillsLatestBlock(this._userAddressIfExists, this.networkId, blockNumberToSet);
        }
    }
    private _stopWatchingExchangeLogFillEvents(): void {
        this._contractWrappers.exchange.unsubscribeAll();
    }
    private async _getTokenRegistryTokensByAddressAsync(): Promise<TokenByAddress> {
        let tokenRegistryTokens;
        if (this.networkId === constants.NETWORK_ID_MAINNET) {
            tokenRegistryTokens = await backendClient.getTokenInfosAsync();
        } else {
            tokenRegistryTokens = fakeTokenRegistry[this.networkId];
            const tokenSymbolToAddressOverrides = tokenAddressOverrides[this.networkId];
            if (!_.isUndefined(tokenAddressOverrides)) {
                // HACK: Override token addresses on testnets
                tokenRegistryTokens = _.map(tokenRegistryTokens, (token: ZeroExToken) => {
                    const overrideIfExists = tokenSymbolToAddressOverrides[token.symbol];
                    if (!_.isUndefined(overrideIfExists)) {
                        return {
                            ...token,
                            address: overrideIfExists,
                        };
                    }
                    return token;
                });
            }
        }
        const tokenByAddress: TokenByAddress = {};
        _.each(tokenRegistryTokens, (t: ZeroExToken) => {
            // HACK: For now we have a hard-coded list of iconUrls for the dummyTokens
            // TODO: Refactor this out and pull the iconUrl directly from the TokenRegistry
            const iconUrl = utils.getTokenIconUrl(t.symbol);
            const token: Token = {
                iconUrl,
                address: t.address,
                name: t.name,
                symbol: t.symbol,
                decimals: t.decimals,
                trackedTimestamp: undefined,
                isRegistered: true,
            };
            tokenByAddress[token.address] = token;
        });
        return tokenByAddress;
    }
    private async _onPageLoadInitFireAndForgetAsync(): Promise<void> {
        await utils.onPageLoadPromise; // wait for page to load
        const networkIdIfExists = await this._getInjectedProviderNetworkIdIfExistsAsync();
        this.networkId = !_.isUndefined(networkIdIfExists) ? networkIdIfExists : constants.NETWORK_ID_MAINNET;
        const injectedProviderIfExists = await this._getInjectedProviderIfExistsAsync();
        if (!_.isUndefined(injectedProviderIfExists)) {
            const injectedProviderObservable = injectedProviderIfExists.publicConfigStore;
            if (!_.isUndefined(injectedProviderObservable) && _.isUndefined(this._injectedProviderObservable)) {
                this._injectedProviderObservable = injectedProviderObservable;
                this._injectedProviderObservable.subscribe(this._injectedProviderUpdateHandler);
            }
        }
        this._updateProviderName(injectedProviderIfExists);
        const shouldPollUserAddress = true;
        const shouldUseLedgerProvider = false;
        this._startWatchingGasPrice();
        await this._resetOrInitializeAsync(this.networkId, shouldPollUserAddress, shouldUseLedgerProvider);
    }
    private _startWatchingGasPrice(): void {
        if (!_.isUndefined(this._watchGasPriceIntervalId)) {
            return; // we are already watching
        }
        const oneMinuteInMs = 60000;
        // tslint:disable-next-line:no-floating-promises
        this._updateDefaultGasPriceAsync();
        this._watchGasPriceIntervalId = intervalUtils.setAsyncExcludingInterval(
            this._updateDefaultGasPriceAsync.bind(this),
            oneMinuteInMs,
            (err: Error) => {
                logUtils.log(`Watching gas price failed: ${err.stack}`);
                this._stopWatchingGasPrice();
            },
        );
    }
    private _stopWatchingGasPrice(): void {
        if (!_.isUndefined(this._watchGasPriceIntervalId)) {
            intervalUtils.clearAsyncExcludingInterval(this._watchGasPriceIntervalId);
        }
    }
    private async _resetOrInitializeAsync(
        networkId: number,
        shouldPollUserAddress: boolean = false,
        shouldUserLedgerProvider: boolean = false,
    ): Promise<void> {
        if (!shouldUserLedgerProvider) {
            this._dispatcher.updateBlockchainIsLoaded(false);
        }
        this._dispatcher.updateUserWeiBalance(undefined);
        this.networkId = networkId;
        const injectedProviderIfExists = await this._getInjectedProviderIfExistsAsync();
        const [provider, ledgerSubproviderIfExists] = await Blockchain._getProviderAsync(
            injectedProviderIfExists,
            networkId,
            shouldUserLedgerProvider,
        );
        this._web3Wrapper = new Web3Wrapper(provider);
        this.networkId = await this._web3Wrapper.getNetworkIdAsync();
        if (!_.isUndefined(this._contractWrappers)) {
            this._contractWrappers.unsubscribeAll();
        }
        const contractWrappersConfig = {
            networkId,
        };
        this._contractWrappers = new ContractWrappers(provider, contractWrappersConfig);
        if (!_.isUndefined(this._blockchainWatcher)) {
            this._blockchainWatcher.destroy();
        }
        this._blockchainWatcher = new BlockchainWatcher(this._dispatcher, this._web3Wrapper, shouldPollUserAddress);
        if (shouldUserLedgerProvider && !_.isUndefined(ledgerSubproviderIfExists)) {
            delete this._userAddressIfExists;
            this._ledgerSubprovider = ledgerSubproviderIfExists;
            this._dispatcher.updateUserAddress(undefined);
            this._dispatcher.updateProviderType(ProviderType.Ledger);
        } else {
            delete this._ledgerSubprovider;
            const userAddresses = await this._web3Wrapper.getAvailableAddressesAsync();
            this._userAddressIfExists = userAddresses[0];
            this._dispatcher.updateUserAddress(this._userAddressIfExists);
            if (!_.isUndefined(injectedProviderIfExists)) {
                this._dispatcher.updateProviderType(ProviderType.Injected);
            }
            await this.fetchTokenInformationAsync();
        }
        await this._blockchainWatcher.startEmittingUserBalanceStateAsync();
        this._dispatcher.updateNetworkId(networkId);
        await this._rehydrateStoreWithContractEventsAsync();
    }
    private _updateProviderName(injectedProviderIfExists?: InjectedProvider): void {
        const doesInjectedProviderExist = !_.isUndefined(injectedProviderIfExists);
        const providerName = doesInjectedProviderExist
            ? Blockchain._getNameGivenProvider(injectedProviderIfExists)
            : constants.PROVIDER_NAME_PUBLIC;
        this._dispatcher.updateInjectedProviderName(providerName);
    }
    private async _instantiateContractIfExistsAsync(artifact: any, address?: string): Promise<ContractInstance> {
        const c = await contract(artifact);
        const providerObj = this._web3Wrapper.getProvider();
        c.setProvider(providerObj);

        const artifactNetworkConfigs = artifact.networks[this.networkId];
        let contractAddress;
        if (!_.isUndefined(address)) {
            contractAddress = address;
        } else if (!_.isUndefined(artifactNetworkConfigs)) {
            contractAddress = artifactNetworkConfigs.address;
        }

        if (!_.isUndefined(contractAddress)) {
            const doesContractExist = await this.doesContractExistAtAddressAsync(contractAddress);
            if (!doesContractExist) {
                logUtils.log(`Contract does not exist: ${artifact.contract_name} at ${contractAddress}`);
                throw new Error(BlockchainCallErrs.ContractDoesNotExist);
            }
        }

        try {
            const contractInstance = _.isUndefined(address) ? await c.deployed() : await c.at(address);
            return contractInstance;
        } catch (err) {
            const errMsg = `${err}`;
            logUtils.log(`Notice: Error encountered: ${err} ${err.stack}`);
            if (_.includes(errMsg, 'not been deployed to detected network')) {
                throw new Error(BlockchainCallErrs.ContractDoesNotExist);
            } else {
                errorReporter.report(err);
                throw new Error(BlockchainCallErrs.UnhandledError);
            }
        }
    }
    private _showFlashMessageIfLedger(): void {
        if (!_.isUndefined(this._ledgerSubprovider)) {
            this._dispatcher.showFlashMessage('Confirm the transaction on your Ledger Nano S');
        }
    }
    private async _updateDefaultGasPriceAsync(): Promise<void> {
        try {
            const gasInfo = await backendClient.getGasInfoAsync();
            const gasPriceInGwei = new BigNumber(gasInfo.fast / 10);
            const gasPriceInWei = gasPriceInGwei.mul(1000000000);
            this._defaultGasPrice = gasPriceInWei;
        } catch (err) {
            return;
        }
    }
} // tslint:disable:max-file-line-count