From c61fe3ce64e58e7ae427642430621b857c3a716d Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Tue, 12 Dec 2017 13:33:12 +0100 Subject: Don't unsubscribe on error. It's done automatically --- packages/website/ts/blockchain.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 76640a072..172ba6b52 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -468,8 +468,7 @@ export class Blockchain { public destroy() { clearInterval(this.zrxPollIntervalId); this.web3Wrapper.destroy(); - // tslint:disable-next-line:no-floating-promises - this.stopWatchingExchangeLogFillEventsAsync(); // fire and forget + this.stopWatchingExchangeLogFillEvents(); } private async showEtherScanLinkAndAwaitTransactionMinedAsync( txHash: string): Promise { @@ -485,7 +484,7 @@ export class Blockchain { } private async rehydrateStoreWithContractEvents() { // Ensure we are only ever listening to one set of events - await this.stopWatchingExchangeLogFillEventsAsync(); + this.stopWatchingExchangeLogFillEvents(); if (!this.doesUserAddressExist()) { return; // short-circuit @@ -517,8 +516,6 @@ export class Blockchain { // to rollbar and stop watching when one occurs // tslint:disable-next-line:no-floating-promises errorReporter.reportAsync(err); // fire and forget - // tslint:disable-next-line:no-floating-promises - this.stopWatchingExchangeLogFillEventsAsync(); // fire and forget return; } else { const decodedLog = decodedLogEvent.log; @@ -593,7 +590,7 @@ export class Blockchain { tradeHistoryStorage.setFillsLatestBlock(this.userAddress, this.networkId, blockNumberToSet); } } - private async stopWatchingExchangeLogFillEventsAsync() { + private stopWatchingExchangeLogFillEvents(): void { this.zeroEx.exchange.unsubscribeAll(); } private async getTokenRegistryTokensByAddressAsync(): Promise { -- cgit From ce242b10e2c4d35bbba3842d198b78373dd609f0 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Thu, 14 Dec 2017 17:43:42 +0100 Subject: Reuse intervalutils in website --- packages/website/ts/blockchain.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 172ba6b52..321a603ef 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -23,7 +23,7 @@ import { LedgerWalletSubprovider, RedundantRPCSubprovider, } from '@0xproject/subproviders'; -import {promisify} from '@0xproject/utils'; +import {intervalUtils, promisify} from '@0xproject/utils'; import BigNumber from 'bignumber.js'; import compareVersions = require('compare-versions'); import ethUtil = require('ethereumjs-util'); @@ -75,7 +75,7 @@ export class Blockchain { private userAddress: string; private cachedProvider: Web3.Provider; private ledgerSubprovider: LedgerWalletSubprovider; - private zrxPollIntervalId: number; + private zrxPollIntervalId: NodeJS.Timer; private static async onPageLoadAsync() { if (document.readyState === 'complete') { return; // Already loaded @@ -359,7 +359,7 @@ export class Blockchain { const [currBalance] = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, token.address); - this.zrxPollIntervalId = window.setInterval(async () => { + this.zrxPollIntervalId = intervalUtils.setAsyncExcludingInterval(async () => { const [balance] = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, token.address); if (!balance.eq(currBalance)) { this.dispatcher.replaceTokenBalanceByAddress(token.address, balance); -- cgit From 2041e9945edf6f5255185de73c0dc332270e4bbb Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Fri, 15 Dec 2017 15:19:19 +0100 Subject: Fix website unused vars --- packages/website/ts/blockchain.ts | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 321a603ef..331bafa71 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -1,7 +1,6 @@ import { BlockParam, DecodedLogEvent, - ExchangeContractErrs, ExchangeContractEventArgs, ExchangeEvents, IndexedFilterValues, @@ -14,7 +13,6 @@ import { Token as ZeroExToken, TransactionReceiptWithDecodedLogs, ZeroEx, - ZeroExError, } from '0x.js'; import { InjectedWeb3Subprovider, @@ -25,9 +23,6 @@ import { } from '@0xproject/subproviders'; import {intervalUtils, promisify} from '@0xproject/utils'; import BigNumber from 'bignumber.js'; -import compareVersions = require('compare-versions'); -import ethUtil = require('ethereumjs-util'); -import findVersions = require('find-versions'); import * as _ from 'lodash'; import * as React from 'react'; import contract = require('truffle-contract'); @@ -40,7 +35,6 @@ import { BlockchainCallErrs, BlockchainErrs, ContractInstance, - ContractResponse, EtherscanLinkSuffixes, ProviderType, Side, @@ -60,7 +54,6 @@ import FilterSubprovider = require('web3-provider-engine/subproviders/filters'); import * as MintableArtifacts from '../contracts/Mintable.json'; -const ALLOWANCE_TO_ZERO_GAS_AMOUNT = 45730; const BLOCK_NUMBER_BACK_TRACK = 50; export class Blockchain { @@ -70,8 +63,6 @@ export class Blockchain { private dispatcher: Dispatcher; private web3Wrapper?: Web3Wrapper; private exchangeAddress: string; - private tokenTransferProxy: ContractInstance; - private tokenRegistry: ContractInstance; private userAddress: string; private cachedProvider: Web3.Provider; private ledgerSubprovider: LedgerWalletSubprovider; @@ -506,8 +497,7 @@ export class Blockchain { await this.fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues); // Start a subscription for new logs - const exchangeAddress = this.getExchangeContractAddressIfExists(); - const subscriptionId = this.zeroEx.exchange.subscribe( + this.zeroEx.exchange.subscribe( ExchangeEvents.LogFill, indexFilterValues, async (err: Error, decodedLogEvent: DecodedLogEvent) => { if (err) { -- cgit From fe8f2d87c79cb25a7879c2e737dbdd64b7c40f60 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Fri, 15 Dec 2017 14:07:14 -0600 Subject: Temporary hack to alleviate issues with updating tokenRegistry with new WETH address --- packages/website/ts/blockchain.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 331bafa71..6877a301a 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -592,9 +592,22 @@ export class Blockchain { // 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 = constants.iconUrlBySymbol[t.symbol]; + // HACK: Temporarily we hijack the WETH addresses fetched from the tokenRegistry + // so that we can take our time with actually updating it. This ensures that when + // we deploy the new WETH page, everyone will re-fill their trackedTokens with the + // new canonical WETH. + // TODO: Remove this hack once we've updated the TokenRegistries + let address = t.address; + if (t.symbol === 'WETH') { + if (this.networkId === 1) { + address = '0xe495bcacaf29a0eb00fb67b86e9cd2a994dd55d8'; + } else if (this.networkId === 42) { + address = '0x739e78d6bebbdf24105a5145fa04436589d1cbd9'; + } + } const token: Token = { iconUrl, - address: t.address, + address, name: t.name, symbol: t.symbol, decimals: t.decimals, -- cgit From 51af6de6249ac8d7656052f2a7198ae4341061b6 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Sun, 17 Dec 2017 12:36:50 -0600 Subject: Update to passing etherTokenAddress into withdraw and deposit calls --- packages/website/ts/blockchain.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 6877a301a..a42b19cff 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -388,18 +388,18 @@ export class Blockchain { const balance = await this.web3Wrapper.getBalanceInEthAsync(owner); return balance; } - public async convertEthToWrappedEthTokensAsync(amount: BigNumber): Promise { + public async convertEthToWrappedEthTokensAsync(etherTokenAddress: string, amount: BigNumber): Promise { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); - const txHash = await this.zeroEx.etherToken.depositAsync(amount, this.userAddress); + const txHash = await this.zeroEx.etherToken.depositAsync(etherTokenAddress, amount, this.userAddress); await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } - public async convertWrappedEthTokensToEthAsync(amount: BigNumber): Promise { + public async convertWrappedEthTokensToEthAsync(etherTokenAddress: string, amount: BigNumber): Promise { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); - const txHash = await this.zeroEx.etherToken.withdrawAsync(amount, this.userAddress); + const txHash = await this.zeroEx.etherToken.withdrawAsync(etherTokenAddress, amount, this.userAddress); await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } public async doesContractExistAtAddressAsync(address: string) { -- cgit From b640e2cc4990e83511e1f796a06cdc890ceec396 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Sun, 17 Dec 2017 12:40:04 -0600 Subject: Update website calls to deposit/withdraw --- packages/website/ts/blockchain.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 6877a301a..a42b19cff 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -388,18 +388,18 @@ export class Blockchain { const balance = await this.web3Wrapper.getBalanceInEthAsync(owner); return balance; } - public async convertEthToWrappedEthTokensAsync(amount: BigNumber): Promise { + public async convertEthToWrappedEthTokensAsync(etherTokenAddress: string, amount: BigNumber): Promise { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); - const txHash = await this.zeroEx.etherToken.depositAsync(amount, this.userAddress); + const txHash = await this.zeroEx.etherToken.depositAsync(etherTokenAddress, amount, this.userAddress); await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } - public async convertWrappedEthTokensToEthAsync(amount: BigNumber): Promise { + public async convertWrappedEthTokensToEthAsync(etherTokenAddress: string, amount: BigNumber): Promise { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); - const txHash = await this.zeroEx.etherToken.withdrawAsync(amount, this.userAddress); + const txHash = await this.zeroEx.etherToken.withdrawAsync(etherTokenAddress, amount, this.userAddress); await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } public async doesContractExistAtAddressAsync(address: string) { -- cgit From 951fbc9b76faf6b0f9f44fd2b729bcb54cf9d565 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Sun, 17 Dec 2017 19:18:33 -0500 Subject: Temporarily pretend as if new WETH contracts are already whitelisted by tokenRegistry and put hacks behind the shouldDeprecateOldWethToken flag --- packages/website/ts/blockchain.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index a42b19cff..7a0d546b4 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -158,6 +158,12 @@ export class Blockchain { } public async isAddressInTokenRegistryAsync(tokenAddress: string): Promise { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); + // HACK: temporarily whitelist the new WETH token address `as if` they were + // already in the tokenRegistry. + if (configs.shouldDeprecateOldWethToken && + tokenAddress === configs.newWrappedEthers[this.networkId]) { + return true; + } const tokenIfExists = await this.zeroEx.tokenRegistry.getTokenIfExistsAsync(tokenAddress); return !_.isUndefined(tokenIfExists); } @@ -598,12 +604,11 @@ export class Blockchain { // new canonical WETH. // TODO: Remove this hack once we've updated the TokenRegistries let address = t.address; - if (t.symbol === 'WETH') { - if (this.networkId === 1) { - address = '0xe495bcacaf29a0eb00fb67b86e9cd2a994dd55d8'; - } else if (this.networkId === 42) { - address = '0x739e78d6bebbdf24105a5145fa04436589d1cbd9'; - } + if (configs.shouldDeprecateOldWethToken && t.symbol === 'WETH') { + const newEtherTokenAddressIfExists = configs.newWrappedEthers[this.networkId]; + if (!_.isUndefined(newEtherTokenAddressIfExists)) { + address = newEtherTokenAddressIfExists; + } } const token: Token = { iconUrl, -- cgit From 22c4ee6ef709610155191c4b0629ba0c41ce908f Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Sun, 17 Dec 2017 19:35:24 -0500 Subject: Update first two string enums to native type --- packages/website/ts/blockchain.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 6877a301a..336397f7f 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -135,11 +135,11 @@ export class Blockchain { const isConnected = !_.isUndefined(newNetworkId); if (!isConnected) { this.networkId = newNetworkId; - this.dispatcher.encounteredBlockchainError(BlockchainErrs.DISCONNECTED_FROM_ETHEREUM_NODE); + this.dispatcher.encounteredBlockchainError(BlockchainErrs.DisconnectedFromEthereumNode); this.dispatcher.updateShouldBlockchainErrDialogBeOpen(true); } else if (this.networkId !== newNetworkId) { this.networkId = newNetworkId; - this.dispatcher.encounteredBlockchainError(''); + this.dispatcher.encounteredBlockchainError(BlockchainErrs.NoError); await this.fetchTokenInformationAsync(); await this.rehydrateStoreWithContractEvents(); } @@ -712,8 +712,8 @@ export class Blockchain { _.find(allTokens, {symbol: configs.defaultTrackedTokenSymbols[0]}), _.find(allTokens, {symbol: configs.defaultTrackedTokenSymbols[1]}), ]; - this.dispatcher.updateChosenAssetTokenAddress(Side.deposit, mostPopularTradingPairTokens[0].address); - this.dispatcher.updateChosenAssetTokenAddress(Side.receive, mostPopularTradingPairTokens[1].address); + this.dispatcher.updateChosenAssetTokenAddress(Side.Deposit, mostPopularTradingPairTokens[0].address); + this.dispatcher.updateChosenAssetTokenAddress(Side.Receive, mostPopularTradingPairTokens[1].address); this.dispatcher.updateBlockchainIsLoaded(true); } private async instantiateContractIfExistsAsync(artifact: any, address?: string): Promise { -- cgit From abbad68eb838ec4611d2236a7b0036a4a4d3058e Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Sun, 17 Dec 2017 20:48:23 -0500 Subject: Replace remaining strEnums with property TS string enums --- packages/website/ts/blockchain.ts | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 336397f7f..c8ebd6b93 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -186,7 +186,7 @@ export class Blockchain { // later on in the logic. let provider; switch (providerType) { - case ProviderType.LEDGER: { + case ProviderType.Ledger: { const isU2FSupported = await utils.isU2FSupportedAsync(); if (!isU2FSupported) { throw new Error('Cannot update providerType to LEDGER without U2F support'); @@ -220,7 +220,7 @@ export class Blockchain { break; } - case ProviderType.INJECTED: { + case ProviderType.Injected: { if (_.isUndefined(this.cachedProvider)) { return; // Going from injected to injected, so we noop } @@ -241,8 +241,8 @@ export class Blockchain { await this.fetchTokenInformationAsync(); } public async setProxyAllowanceAsync(token: Token, amountInBaseUnits: BigNumber): Promise { - utils.assert(this.isValidAddress(token.address), BlockchainCallErrs.TOKEN_ADDRESS_IS_INVALID); - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); + utils.assert(this.isValidAddress(token.address), BlockchainCallErrs.TokenAddressIsInvalid); + utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); const txHash = await this.zeroEx.token.setProxyAllowanceAsync( @@ -258,7 +258,7 @@ export class Blockchain { token.address, this.userAddress, toAddress, amountInBaseUnits, ); await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); - const etherScanLinkIfExists = utils.getEtherScanLinkIfExists(txHash, this.networkId, EtherscanLinkSuffixes.tx); + const etherScanLinkIfExists = utils.getEtherScanLinkIfExists(txHash, this.networkId, EtherscanLinkSuffixes.Tx); this.dispatcher.showFlashMessage(React.createElement(TokenSendCompleted, { etherScanLinkIfExists, token, @@ -294,7 +294,7 @@ export class Blockchain { } public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber): Promise { - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); + utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); const shouldThrowOnInsufficientBalanceOrAllowance = true; @@ -346,7 +346,7 @@ export class Blockchain { return this.web3Wrapper.isAddress(lowercaseAddress); } public async pollTokenBalanceAsync(token: Token) { - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); + utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); const [currBalance] = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, token.address); @@ -375,7 +375,7 @@ export class Blockchain { return signatureData; } public async mintTestTokensAsync(token: Token) { - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); + utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); const mintableContract = await this.instantiateContractIfExistsAsync(MintableArtifacts, token.address); await mintableContract.mint(constants.MINT_AMOUNT, { @@ -390,14 +390,14 @@ export class Blockchain { } public async convertEthToWrappedEthTokensAsync(amount: BigNumber): Promise { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); + utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); const txHash = await this.zeroEx.etherToken.depositAsync(amount, this.userAddress); await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } public async convertWrappedEthTokensToEthAsync(amount: BigNumber): Promise { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); + utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); const txHash = await this.zeroEx.etherToken.withdrawAsync(amount, this.userAddress); await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); @@ -463,7 +463,7 @@ export class Blockchain { } private async showEtherScanLinkAndAwaitTransactionMinedAsync( txHash: string): Promise { - const etherScanLinkIfExists = utils.getEtherScanLinkIfExists(txHash, this.networkId, EtherscanLinkSuffixes.tx); + const etherScanLinkIfExists = utils.getEtherScanLinkIfExists(txHash, this.networkId, EtherscanLinkSuffixes.Tx); this.dispatcher.showFlashMessage(React.createElement(TransactionSubmitted, { etherScanLinkIfExists, })); @@ -491,7 +491,7 @@ export class Blockchain { } private async startListeningForExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues): Promise { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.USER_HAS_NO_ASSOCIATED_ADDRESSES); + utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); // Fetch historical logs await this.fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues); @@ -733,7 +733,7 @@ export class Blockchain { const doesContractExist = await this.doesContractExistAtAddressAsync(contractAddress); if (!doesContractExist) { utils.consoleLog(`Contract does not exist: ${artifact.contract_name} at ${contractAddress}`); - throw new Error(BlockchainCallErrs.CONTRACT_DOES_NOT_EXIST); + throw new Error(BlockchainCallErrs.ContractDoesNotExist); } } @@ -746,10 +746,10 @@ export class Blockchain { const errMsg = `${err}`; utils.consoleLog(`Notice: Error encountered: ${err} ${err.stack}`); if (_.includes(errMsg, 'not been deployed to detected network')) { - throw new Error(BlockchainCallErrs.CONTRACT_DOES_NOT_EXIST); + throw new Error(BlockchainCallErrs.ContractDoesNotExist); } else { await errorReporter.reportAsync(err); - throw new Error(BlockchainCallErrs.UNHANDLED_ERROR); + throw new Error(BlockchainCallErrs.UnhandledError); } } } -- cgit From fb0b7efc4563c7c561866ab8691361ce6919160b Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Mon, 18 Dec 2017 19:30:25 +0100 Subject: Refactor configs and constants, standardize on uppercase/snakecase, alphebetize, rename for logical grouping --- packages/website/ts/blockchain.ts | 40 +++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index c8ebd6b93..680eac0af 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -77,21 +77,21 @@ export class Blockchain { } private static getNameGivenProvider(provider: Web3.Provider): string { if (!_.isUndefined((provider as any).isMetaMask)) { - return constants.METAMASK_PROVIDER_NAME; + return constants.PROVIDER_NAME_METAMASK; } // HACK: We use the fact that Parity Signer's provider is an instance of their // internal `Web3FrameProvider` class. const isParitySigner = _.startsWith(provider.constructor.toString(), 'function Web3FrameProvider'); if (isParitySigner) { - return constants.PARITY_SIGNER_PROVIDER_NAME; + return constants.PROVIDER_NAME_PARITY_SIGNER; } - return constants.GENERIC_PROVIDER_NAME; + return constants.PROVIDER_NAME_GENERIC; } private static async getProviderAsync(injectedWeb3: Web3, networkIdIfExists: number) { const doesInjectedWeb3Exist = !_.isUndefined(injectedWeb3); - const publicNodeUrlsIfExistsForNetworkId = constants.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkIdIfExists]; + const publicNodeUrlsIfExistsForNetworkId = configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkIdIfExists]; const isPublicNodeAvailableForNetworkId = !_.isUndefined(publicNodeUrlsIfExistsForNetworkId); let provider; @@ -114,11 +114,11 @@ export class Blockchain { // injected into their browser. provider = new ProviderEngine(); provider.addProvider(new FilterSubprovider()); - const networkId = configs.isMainnetEnabled ? - constants.MAINNET_NETWORK_ID : - constants.TESTNET_NETWORK_ID; + const networkId = configs.IS_MAINNET_ENABLED ? + constants.NETWORK_ID_MAINNET : + constants.NETWORK_ID_TESTNET; provider.addProvider(new RedundantRPCSubprovider( - constants.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId], + configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId], )); provider.start(); } @@ -205,11 +205,11 @@ export class Blockchain { this.ledgerSubprovider = new LedgerSubprovider(ledgerWalletConfigs); provider.addProvider(this.ledgerSubprovider); provider.addProvider(new FilterSubprovider()); - const networkId = configs.isMainnetEnabled ? - constants.MAINNET_NETWORK_ID : - constants.TESTNET_NETWORK_ID; + const networkId = configs.IS_MAINNET_ENABLED ? + constants.NETWORK_ID_MAINNET : + constants.NETWORK_ID_TESTNET; provider.addProvider(new RedundantRPCSubprovider( - constants.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId], + configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId], )); provider.start(); this.web3Wrapper.destroy(); @@ -591,7 +591,7 @@ export class Blockchain { _.each(tokenRegistryTokens, (t: ZeroExToken, i: number) => { // 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 = constants.iconUrlBySymbol[t.symbol]; + const iconUrl = configs.ICON_URL_BY_SYMBOL[t.symbol]; // HACK: Temporarily we hijack the WETH addresses fetched from the tokenRegistry // so that we can take our time with actually updating it. This ensures that when // we deploy the new WETH page, everyone will re-fill their trackedTokens with the @@ -639,9 +639,9 @@ export class Blockchain { const provider = await Blockchain.getProviderAsync(injectedWeb3, networkIdIfExists); const networkId = !_.isUndefined(networkIdIfExists) ? networkIdIfExists : - configs.isMainnetEnabled ? - constants.MAINNET_NETWORK_ID : - constants.TESTNET_NETWORK_ID; + configs.IS_MAINNET_ENABLED ? + constants.NETWORK_ID_MAINNET : + constants.NETWORK_ID_TESTNET; const zeroExConfigs = { networkId, }; @@ -661,7 +661,7 @@ export class Blockchain { const doesInjectedWeb3Exist = !_.isUndefined(injectedWeb3); const providerName = doesInjectedWeb3Exist ? Blockchain.getNameGivenProvider(injectedWeb3.currentProvider) : - constants.PUBLIC_PROVIDER_NAME; + constants.PROVIDER_NAME_PUBLIC; this.dispatcher.updateInjectedProviderName(providerName); } private async fetchTokenInformationAsync() { @@ -686,7 +686,7 @@ export class Blockchain { let trackedTokensIfExists = trackedTokenStorage.getTrackedTokensIfExists(this.userAddress, this.networkId); const tokenRegistryTokens = _.values(tokenRegistryTokensByAddress); if (_.isUndefined(trackedTokensIfExists)) { - trackedTokensIfExists = _.map(configs.defaultTrackedTokenSymbols, symbol => { + trackedTokensIfExists = _.map(configs.DEFAULT_TRACKED_TOKEN_SYMBOLS, symbol => { const token = _.find(tokenRegistryTokens, t => t.symbol === symbol); token.isTracked = true; return token; @@ -709,8 +709,8 @@ export class Blockchain { await this.updateTokenBalancesAndAllowancesAsync(trackedTokensIfExists); const mostPopularTradingPairTokens: Token[] = [ - _.find(allTokens, {symbol: configs.defaultTrackedTokenSymbols[0]}), - _.find(allTokens, {symbol: configs.defaultTrackedTokenSymbols[1]}), + _.find(allTokens, {symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[0]}), + _.find(allTokens, {symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[1]}), ]; this.dispatcher.updateChosenAssetTokenAddress(Side.Deposit, mostPopularTradingPairTokens[0].address); this.dispatcher.updateChosenAssetTokenAddress(Side.Receive, mostPopularTradingPairTokens[1].address); -- cgit From 684542d073367ac13021262e7e69edb607629c55 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Tue, 19 Dec 2017 10:36:54 +0100 Subject: Add airtable tasks to TODO's --- packages/website/ts/blockchain.ts | 3 +++ 1 file changed, 3 insertions(+) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 7a0d546b4..0f80c47a5 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -160,6 +160,8 @@ export class Blockchain { utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); // HACK: temporarily whitelist the new WETH token address `as if` they were // already in the tokenRegistry. + // TODO: Remove this hack once we've updated the TokenRegistries + // Airtable task: https://airtable.com/tblFe0Q9JuKJPYbTn/viwsOG2Y97qdIeCIO/recv3VGmIorFzHBVz if (configs.shouldDeprecateOldWethToken && tokenAddress === configs.newWrappedEthers[this.networkId]) { return true; @@ -603,6 +605,7 @@ export class Blockchain { // we deploy the new WETH page, everyone will re-fill their trackedTokens with the // new canonical WETH. // TODO: Remove this hack once we've updated the TokenRegistries + // Airtable task: https://airtable.com/tblFe0Q9JuKJPYbTn/viwsOG2Y97qdIeCIO/recv3VGmIorFzHBVz let address = t.address; if (configs.shouldDeprecateOldWethToken && t.symbol === 'WETH') { const newEtherTokenAddressIfExists = configs.newWrappedEthers[this.networkId]; -- cgit From 1e4fdcf615502478cbec8711bf6710e093c0c279 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Mon, 18 Dec 2017 15:35:23 +0100 Subject: Rename SubscriptionOpts to BlockRange --- packages/website/ts/blockchain.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index a42b19cff..2a4aabeb2 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -1,5 +1,6 @@ import { BlockParam, + BlockRange, DecodedLogEvent, ExchangeContractEventArgs, ExchangeEvents, @@ -9,7 +10,6 @@ import { LogWithDecodedArgs, Order, SignedOrder, - SubscriptionOpts, Token as ZeroExToken, TransactionReceiptWithDecodedLogs, ZeroEx, @@ -524,12 +524,12 @@ export class Blockchain { } private async fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues) { const fromBlock = tradeHistoryStorage.getFillsLatestBlock(this.userAddress, this.networkId); - const subscriptionOpts: SubscriptionOpts = { + const blockRange: BlockRange = { fromBlock, toBlock: 'latest' as BlockParam, }; const decodedLogs = await this.zeroEx.exchange.getLogsAsync( - ExchangeEvents.LogFill, subscriptionOpts, indexFilterValues, + ExchangeEvents.LogFill, blockRange, indexFilterValues, ); for (const decodedLog of decodedLogs) { if (!this.doesLogEventInvolveUser(decodedLog)) { -- cgit From cb11aec84df346d5180c7d5874859c1c34f0bf1c Mon Sep 17 00:00:00 2001 From: Brandon Millman Date: Wed, 20 Dec 2017 00:44:08 -0500 Subject: Add new underscore-privates rule to @0xproject/tslint-config and fix lint errors --- packages/website/ts/blockchain.ts | 356 +++++++++++++++++++------------------- 1 file changed, 178 insertions(+), 178 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 481917934..3d21a5046 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -59,15 +59,15 @@ const BLOCK_NUMBER_BACK_TRACK = 50; export class Blockchain { public networkId: number; public nodeVersion: string; - private zeroEx: ZeroEx; - private dispatcher: Dispatcher; - private web3Wrapper?: Web3Wrapper; - private exchangeAddress: string; - private userAddress: string; - private cachedProvider: Web3.Provider; - private ledgerSubprovider: LedgerWalletSubprovider; - private zrxPollIntervalId: NodeJS.Timer; - private static async onPageLoadAsync() { + private _zeroEx: ZeroEx; + private _dispatcher: Dispatcher; + private _web3Wrapper?: Web3Wrapper; + private _exchangeAddress: string; + private _userAddress: string; + private _cachedProvider: Web3.Provider; + private _ledgerSubprovider: LedgerWalletSubprovider; + private _zrxPollIntervalId: NodeJS.Timer; + private static async _onPageLoadAsync() { if (document.readyState === 'complete') { return; // Already loaded } @@ -75,7 +75,7 @@ export class Blockchain { window.onload = resolve; }); } - private static getNameGivenProvider(provider: Web3.Provider): string { + private static _getNameGivenProvider(provider: Web3.Provider): string { if (!_.isUndefined((provider as any).isMetaMask)) { return constants.PROVIDER_NAME_METAMASK; } @@ -89,7 +89,7 @@ export class Blockchain { return constants.PROVIDER_NAME_GENERIC; } - private static async getProviderAsync(injectedWeb3: Web3, networkIdIfExists: number) { + private static async _getProviderAsync(injectedWeb3: Web3, networkIdIfExists: number) { const doesInjectedWeb3Exist = !_.isUndefined(injectedWeb3); const publicNodeUrlsIfExistsForNetworkId = configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkIdIfExists]; const isPublicNodeAvailableForNetworkId = !_.isUndefined(publicNodeUrlsIfExistsForNetworkId); @@ -126,29 +126,29 @@ export class Blockchain { return provider; } constructor(dispatcher: Dispatcher, isSalePage: boolean = false) { - this.dispatcher = dispatcher; - this.userAddress = ''; + this._dispatcher = dispatcher; + this._userAddress = ''; // tslint:disable-next-line:no-floating-promises - this.onPageLoadInitFireAndForgetAsync(); + this._onPageLoadInitFireAndForgetAsync(); } public async networkIdUpdatedFireAndForgetAsync(newNetworkId: number) { const isConnected = !_.isUndefined(newNetworkId); if (!isConnected) { this.networkId = newNetworkId; - this.dispatcher.encounteredBlockchainError(BlockchainErrs.DisconnectedFromEthereumNode); - this.dispatcher.updateShouldBlockchainErrDialogBeOpen(true); + 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.rehydrateStoreWithContractEvents(); + this._dispatcher.encounteredBlockchainError(BlockchainErrs.NoError); + await this._fetchTokenInformationAsync(); + await this._rehydrateStoreWithContractEvents(); } } public async userAddressUpdatedFireAndForgetAsync(newUserAddress: string) { - if (this.userAddress !== newUserAddress) { - this.userAddress = newUserAddress; - await this.fetchTokenInformationAsync(); - await this.rehydrateStoreWithContractEvents(); + if (this._userAddress !== newUserAddress) { + this._userAddress = newUserAddress; + await this._fetchTokenInformationAsync(); + await this._rehydrateStoreWithContractEvents(); } } public async nodeVersionUpdatedFireAndForgetAsync(nodeVersion: string) { @@ -157,7 +157,7 @@ export class Blockchain { } } public async isAddressInTokenRegistryAsync(tokenAddress: string): Promise { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); // HACK: temporarily whitelist the new WETH token address `as if` they were // already in the tokenRegistry. // TODO: Remove this hack once we've updated the TokenRegistries @@ -166,30 +166,30 @@ export class Blockchain { tokenAddress === configs.NEW_WRAPPED_ETHERS[this.networkId]) { return true; } - const tokenIfExists = await this.zeroEx.tokenRegistry.getTokenIfExistsAsync(tokenAddress); + const tokenIfExists = await this._zeroEx.tokenRegistry.getTokenIfExistsAsync(tokenAddress); return !_.isUndefined(tokenIfExists); } public getLedgerDerivationPathIfExists(): string { - if (_.isUndefined(this.ledgerSubprovider)) { + if (_.isUndefined(this._ledgerSubprovider)) { return undefined; } - const path = this.ledgerSubprovider.getPath(); + const path = this._ledgerSubprovider.getPath(); return path; } public updateLedgerDerivationPathIfExists(path: string) { - if (_.isUndefined(this.ledgerSubprovider)) { + if (_.isUndefined(this._ledgerSubprovider)) { return; // noop } - this.ledgerSubprovider.setPath(path); + this._ledgerSubprovider.setPath(path); } public updateLedgerDerivationIndex(pathIndex: number) { - if (_.isUndefined(this.ledgerSubprovider)) { + if (_.isUndefined(this._ledgerSubprovider)) { return; // noop } - this.ledgerSubprovider.setPathIndex(pathIndex); + this._ledgerSubprovider.setPathIndex(pathIndex); } public async providerTypeUpdatedFireAndForgetAsync(providerType: ProviderType) { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); // Should actually be Web3.Provider|ProviderEngine union type but it causes issues // later on in the logic. let provider; @@ -201,17 +201,17 @@ export class Blockchain { } // Cache injected provider so that we can switch the user back to it easily - this.cachedProvider = this.web3Wrapper.getProviderObj(); + this._cachedProvider = this._web3Wrapper.getProviderObj(); - this.dispatcher.updateUserAddress(''); // Clear old userAddress + this._dispatcher.updateUserAddress(''); // Clear old userAddress provider = new ProviderEngine(); const ledgerWalletConfigs = { networkId: this.networkId, ledgerEthereumClientFactoryAsync: ledgerEthereumBrowserClientFactoryAsync, }; - this.ledgerSubprovider = new LedgerSubprovider(ledgerWalletConfigs); - provider.addProvider(this.ledgerSubprovider); + this._ledgerSubprovider = new LedgerSubprovider(ledgerWalletConfigs); + provider.addProvider(this._ledgerSubprovider); provider.addProvider(new FilterSubprovider()); const networkId = configs.IS_MAINNET_ENABLED ? constants.NETWORK_ID_MAINNET : @@ -220,25 +220,25 @@ export class Blockchain { configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId], )); provider.start(); - this.web3Wrapper.destroy(); + this._web3Wrapper.destroy(); const shouldPollUserAddress = false; - this.web3Wrapper = new Web3Wrapper(this.dispatcher, provider, this.networkId, shouldPollUserAddress); - this.zeroEx.setProvider(provider, networkId); - await this.postInstantiationOrUpdatingProviderZeroExAsync(); + this._web3Wrapper = new Web3Wrapper(this._dispatcher, provider, this.networkId, shouldPollUserAddress); + this._zeroEx.setProvider(provider, networkId); + await this._postInstantiationOrUpdatingProviderZeroExAsync(); break; } case ProviderType.Injected: { - if (_.isUndefined(this.cachedProvider)) { + if (_.isUndefined(this._cachedProvider)) { return; // Going from injected to injected, so we noop } - provider = this.cachedProvider; + provider = this._cachedProvider; const shouldPollUserAddress = true; - this.web3Wrapper = new Web3Wrapper(this.dispatcher, provider, this.networkId, shouldPollUserAddress); - this.zeroEx.setProvider(provider, this.networkId); - await this.postInstantiationOrUpdatingProviderZeroExAsync(); - delete this.ledgerSubprovider; - delete this.cachedProvider; + this._web3Wrapper = new Web3Wrapper(this._dispatcher, provider, this.networkId, shouldPollUserAddress); + this._zeroEx.setProvider(provider, this.networkId); + await this._postInstantiationOrUpdatingProviderZeroExAsync(); + delete this._ledgerSubprovider; + delete this._cachedProvider; break; } @@ -246,28 +246,28 @@ export class Blockchain { throw utils.spawnSwitchErr('providerType', providerType); } - await this.fetchTokenInformationAsync(); + await this._fetchTokenInformationAsync(); } public async setProxyAllowanceAsync(token: Token, amountInBaseUnits: BigNumber): Promise { utils.assert(this.isValidAddress(token.address), BlockchainCallErrs.TokenAddressIsInvalid); - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); - const txHash = await this.zeroEx.token.setProxyAllowanceAsync( - token.address, this.userAddress, amountInBaseUnits, + const txHash = await this._zeroEx.token.setProxyAllowanceAsync( + token.address, this._userAddress, amountInBaseUnits, ); - await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); + await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const allowance = amountInBaseUnits; - this.dispatcher.replaceTokenAllowanceByAddress(token.address, allowance); + this._dispatcher.replaceTokenAllowanceByAddress(token.address, allowance); } public async transferAsync(token: Token, toAddress: string, amountInBaseUnits: BigNumber): Promise { - const txHash = await this.zeroEx.token.transferAsync( - token.address, this.userAddress, toAddress, amountInBaseUnits, + const txHash = await this._zeroEx.token.transferAsync( + token.address, this._userAddress, toAddress, amountInBaseUnits, ); - await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); + await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const etherScanLinkIfExists = utils.getEtherScanLinkIfExists(txHash, this.networkId, EtherscanLinkSuffixes.Tx); - this.dispatcher.showFlashMessage(React.createElement(TokenSendCompleted, { + this._dispatcher.showFlashMessage(React.createElement(TokenSendCompleted, { etherScanLinkIfExists, token, toAddress, @@ -302,16 +302,16 @@ export class Blockchain { } public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber): Promise { - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); + utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); const shouldThrowOnInsufficientBalanceOrAllowance = true; - const txHash = await this.zeroEx.exchange.fillOrderAsync( - signedOrder, fillTakerTokenAmount, shouldThrowOnInsufficientBalanceOrAllowance, this.userAddress, + const txHash = await this._zeroEx.exchange.fillOrderAsync( + signedOrder, fillTakerTokenAmount, shouldThrowOnInsufficientBalanceOrAllowance, this._userAddress, ); - const receipt = await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); + const receipt = await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const logs: Array> = receipt.logs as any; - this.zeroEx.exchange.throwLogErrorsAsErrors(logs); + this._zeroEx.exchange.throwLogErrorsAsErrors(logs); const logFill = _.find(logs, {event: 'LogFill'}); const args = logFill.args as any as LogFillContractEventArgs; const filledTakerTokenAmount = args.filledTakerTokenAmount; @@ -319,12 +319,12 @@ export class Blockchain { } public async cancelOrderAsync(signedOrder: SignedOrder, cancelTakerTokenAmount: BigNumber): Promise { - const txHash = await this.zeroEx.exchange.cancelOrderAsync( + const txHash = await this._zeroEx.exchange.cancelOrderAsync( signedOrder, cancelTakerTokenAmount, ); - const receipt = await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); + const receipt = await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const logs: Array> = receipt.logs as any; - this.zeroEx.exchange.throwLogErrorsAsErrors(logs); + this._zeroEx.exchange.throwLogErrorsAsErrors(logs); const logCancel = _.find(logs, {event: ExchangeEvents.LogCancel}); const args = logCancel.args as any as LogCancelContractEventArgs; const cancelledTakerTokenAmount = args.cancelledTakerTokenAmount; @@ -332,95 +332,95 @@ export class Blockchain { } public async getUnavailableTakerAmountAsync(orderHash: string): Promise { utils.assert(ZeroEx.isValidOrderHash(orderHash), 'Must be valid orderHash'); - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - const unavailableTakerAmount = await this.zeroEx.exchange.getUnavailableTakerAmountAsync(orderHash); + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + const unavailableTakerAmount = await this._zeroEx.exchange.getUnavailableTakerAmountAsync(orderHash); return unavailableTakerAmount; } public getExchangeContractAddressIfExists() { - return this.exchangeAddress; + return this._exchangeAddress; } public async validateFillOrderThrowIfInvalidAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber, takerAddress: string): Promise { - await this.zeroEx.exchange.validateFillOrderThrowIfInvalidAsync( + await this._zeroEx.exchange.validateFillOrderThrowIfInvalidAsync( signedOrder, fillTakerTokenAmount, takerAddress); } public async validateCancelOrderThrowIfInvalidAsync(order: Order, cancelTakerTokenAmount: BigNumber): Promise { - await this.zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(order, cancelTakerTokenAmount); + await this._zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(order, cancelTakerTokenAmount); } public isValidAddress(address: string): boolean { const lowercaseAddress = address.toLowerCase(); - return this.web3Wrapper.isAddress(lowercaseAddress); + return this._web3Wrapper.isAddress(lowercaseAddress); } public async pollTokenBalanceAsync(token: Token) { - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); + utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); - const [currBalance] = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, token.address); + const [currBalance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); - this.zrxPollIntervalId = intervalUtils.setAsyncExcludingInterval(async () => { - const [balance] = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, token.address); + this._zrxPollIntervalId = intervalUtils.setAsyncExcludingInterval(async () => { + const [balance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); if (!balance.eq(currBalance)) { - this.dispatcher.replaceTokenBalanceByAddress(token.address, balance); - clearInterval(this.zrxPollIntervalId); - delete this.zrxPollIntervalId; + this._dispatcher.replaceTokenBalanceByAddress(token.address, balance); + clearInterval(this._zrxPollIntervalId); + delete this._zrxPollIntervalId; } }, 5000); } public async signOrderHashAsync(orderHash: string): Promise { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - const makerAddress = this.userAddress; + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + const makerAddress = this._userAddress; // 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'); } - const ecSignature = await this.zeroEx.signOrderHashAsync(orderHash, makerAddress); + const ecSignature = await this._zeroEx.signOrderHashAsync(orderHash, makerAddress); const signatureData = _.extend({}, ecSignature, { hash: orderHash, }); - this.dispatcher.updateSignatureData(signatureData); + this._dispatcher.updateSignatureData(signatureData); return signatureData; } public async mintTestTokensAsync(token: Token) { - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); + utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); - const mintableContract = await this.instantiateContractIfExistsAsync(MintableArtifacts, token.address); + const mintableContract = await this._instantiateContractIfExistsAsync(MintableArtifacts, token.address); await mintableContract.mint(constants.MINT_AMOUNT, { - from: this.userAddress, + from: this._userAddress, }); const balanceDelta = constants.MINT_AMOUNT; - this.dispatcher.updateTokenBalanceByAddress(token.address, balanceDelta); + this._dispatcher.updateTokenBalanceByAddress(token.address, balanceDelta); } public async getBalanceInEthAsync(owner: string): Promise { - const balance = await this.web3Wrapper.getBalanceInEthAsync(owner); + const balance = await this._web3Wrapper.getBalanceInEthAsync(owner); return balance; } public async convertEthToWrappedEthTokensAsync(etherTokenAddress: string, amount: BigNumber): Promise { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); - const txHash = await this.zeroEx.etherToken.depositAsync(etherTokenAddress, amount, this.userAddress); - await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); + const txHash = await this._zeroEx.etherToken.depositAsync(etherTokenAddress, amount, this._userAddress); + await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } public async convertWrappedEthTokensToEthAsync(etherTokenAddress: string, amount: BigNumber): Promise { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); - const txHash = await this.zeroEx.etherToken.withdrawAsync(etherTokenAddress, amount, this.userAddress); - await this.showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); + const txHash = await this._zeroEx.etherToken.withdrawAsync(etherTokenAddress, amount, this._userAddress); + await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); } public async doesContractExistAtAddressAsync(address: string) { - const doesContractExist = await this.web3Wrapper.doesContractExistAtAddressAsync(address); + const doesContractExist = await this._web3Wrapper.doesContractExistAtAddressAsync(address); return doesContractExist; } public async getCurrentUserTokenBalanceAndAllowanceAsync(tokenAddress: string): Promise { - const tokenBalanceAndAllowance = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, tokenAddress); + const tokenBalanceAndAllowance = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, tokenAddress); return tokenBalanceAndAllowance; } public async getTokenBalanceAndAllowanceAsync(ownerAddress: string, tokenAddress: string): Promise { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); if (_.isEmpty(ownerAddress)) { const zero = new BigNumber(0); @@ -428,9 +428,9 @@ export class Blockchain { } let balance = new BigNumber(0); let allowance = new BigNumber(0); - if (this.doesUserAddressExist()) { - balance = await this.zeroEx.token.getBalanceAsync(tokenAddress, ownerAddress); - allowance = await this.zeroEx.token.getProxyAllowanceAsync(tokenAddress, ownerAddress); + if (this._doesUserAddressExist()) { + balance = await this._zeroEx.token.getBalanceAsync(tokenAddress, ownerAddress); + allowance = await this._zeroEx.token.getProxyAllowanceAsync(tokenAddress, ownerAddress); } return [balance, allowance]; } @@ -439,11 +439,11 @@ export class Blockchain { for (const token of tokens) { let balance = new BigNumber(0); let allowance = new BigNumber(0); - if (this.doesUserAddressExist()) { + if (this._doesUserAddressExist()) { [ balance, allowance, - ] = await this.getTokenBalanceAndAllowanceAsync(this.userAddress, token.address); + ] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); } const tokenState = { balance, @@ -451,61 +451,61 @@ export class Blockchain { }; tokenStateByAddress[token.address] = tokenState; } - this.dispatcher.updateTokenStateByAddress(tokenStateByAddress); + this._dispatcher.updateTokenStateByAddress(tokenStateByAddress); } public async getUserAccountsAsync() { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - const userAccountsIfExists = await this.zeroEx.getAvailableAddressesAsync(); + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + const userAccountsIfExists = await this._zeroEx.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) { - this.web3Wrapper.updatePrevUserAddress(newUserAddress); + this._web3Wrapper.updatePrevUserAddress(newUserAddress); } public destroy() { - clearInterval(this.zrxPollIntervalId); - this.web3Wrapper.destroy(); - this.stopWatchingExchangeLogFillEvents(); + clearInterval(this._zrxPollIntervalId); + this._web3Wrapper.destroy(); + this._stopWatchingExchangeLogFillEvents(); } - private async showEtherScanLinkAndAwaitTransactionMinedAsync( + private async _showEtherScanLinkAndAwaitTransactionMinedAsync( txHash: string): Promise { const etherScanLinkIfExists = utils.getEtherScanLinkIfExists(txHash, this.networkId, EtherscanLinkSuffixes.Tx); - this.dispatcher.showFlashMessage(React.createElement(TransactionSubmitted, { + this._dispatcher.showFlashMessage(React.createElement(TransactionSubmitted, { etherScanLinkIfExists, })); - const receipt = await this.zeroEx.awaitTransactionMinedAsync(txHash); + const receipt = await this._zeroEx.awaitTransactionMinedAsync(txHash); return receipt; } - private doesUserAddressExist(): boolean { - return this.userAddress !== ''; + private _doesUserAddressExist(): boolean { + return this._userAddress !== ''; } - private async rehydrateStoreWithContractEvents() { + private async _rehydrateStoreWithContractEvents() { // Ensure we are only ever listening to one set of events - this.stopWatchingExchangeLogFillEvents(); + this._stopWatchingExchangeLogFillEvents(); - if (!this.doesUserAddressExist()) { + if (!this._doesUserAddressExist()) { return; // short-circuit } - if (!_.isUndefined(this.zeroEx)) { + if (!_.isUndefined(this._zeroEx)) { // 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); + await this._startListeningForExchangeLogFillEventsAsync(filterIndexObj); } } - private async startListeningForExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues): Promise { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - utils.assert(this.doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); + private async _startListeningForExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues): Promise { + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); // Fetch historical logs - await this.fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues); + await this._fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues); // Start a subscription for new logs - this.zeroEx.exchange.subscribe( + this._zeroEx.exchange.subscribe( ExchangeEvents.LogFill, indexFilterValues, async (err: Error, decodedLogEvent: DecodedLogEvent) => { if (err) { @@ -517,40 +517,40 @@ export class Blockchain { return; } else { const decodedLog = decodedLogEvent.log; - if (!this.doesLogEventInvolveUser(decodedLog)) { + if (!this._doesLogEventInvolveUser(decodedLog)) { return; // We aren't interested in the fill event } - this.updateLatestFillsBlockIfNeeded(decodedLog.blockNumber); - const fill = await this.convertDecodedLogToFillAsync(decodedLog); + this._updateLatestFillsBlockIfNeeded(decodedLog.blockNumber); + const fill = await this._convertDecodedLogToFillAsync(decodedLog); if (decodedLogEvent.isRemoved) { - tradeHistoryStorage.removeFillFromUser(this.userAddress, this.networkId, fill); + tradeHistoryStorage.removeFillFromUser(this._userAddress, this.networkId, fill); } else { - tradeHistoryStorage.addFillToUser(this.userAddress, this.networkId, fill); + tradeHistoryStorage.addFillToUser(this._userAddress, this.networkId, fill); } } }); } - private async fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues) { - const fromBlock = tradeHistoryStorage.getFillsLatestBlock(this.userAddress, this.networkId); + private async _fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues) { + const fromBlock = tradeHistoryStorage.getFillsLatestBlock(this._userAddress, this.networkId); const blockRange: BlockRange = { fromBlock, toBlock: 'latest' as BlockParam, }; - const decodedLogs = await this.zeroEx.exchange.getLogsAsync( + const decodedLogs = await this._zeroEx.exchange.getLogsAsync( ExchangeEvents.LogFill, blockRange, indexFilterValues, ); for (const decodedLog of decodedLogs) { - if (!this.doesLogEventInvolveUser(decodedLog)) { + 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.userAddress, this.networkId, fill); + this._updateLatestFillsBlockIfNeeded(decodedLog.blockNumber); + const fill = await this._convertDecodedLogToFillAsync(decodedLog); + tradeHistoryStorage.addFillToUser(this._userAddress, this.networkId, fill); } } - private async convertDecodedLogToFillAsync(decodedLog: LogWithDecodedArgs) { + private async _convertDecodedLogToFillAsync(decodedLog: LogWithDecodedArgs) { const args = decodedLog.args; - const blockTimestamp = await this.web3Wrapper.getBlockTimestampAsync(decodedLog.blockHash); + const blockTimestamp = await this._web3Wrapper.getBlockTimestampAsync(decodedLog.blockHash); const fill = { filledTakerTokenAmount: args.filledTakerTokenAmount, filledMakerTokenAmount: args.filledMakerTokenAmount, @@ -567,13 +567,13 @@ export class Blockchain { }; return fill; } - private doesLogEventInvolveUser(decodedLog: LogWithDecodedArgs) { + private _doesLogEventInvolveUser(decodedLog: LogWithDecodedArgs) { const args = decodedLog.args; - const isUserMakerOrTaker = args.maker === this.userAddress || - args.taker === this.userAddress; + const isUserMakerOrTaker = args.maker === this._userAddress || + args.taker === this._userAddress; return isUserMakerOrTaker; } - private updateLatestFillsBlockIfNeeded(blockNumber: number) { + private _updateLatestFillsBlockIfNeeded(blockNumber: number) { const isBlockPending = _.isNull(blockNumber); if (!isBlockPending) { // Hack: I've observed the behavior where a client won't register certain fill events @@ -585,15 +585,15 @@ export class Blockchain { const blockNumberToSet = blockNumber - BLOCK_NUMBER_BACK_TRACK < 0 ? 0 : blockNumber - BLOCK_NUMBER_BACK_TRACK; - tradeHistoryStorage.setFillsLatestBlock(this.userAddress, this.networkId, blockNumberToSet); + tradeHistoryStorage.setFillsLatestBlock(this._userAddress, this.networkId, blockNumberToSet); } } - private stopWatchingExchangeLogFillEvents(): void { - this.zeroEx.exchange.unsubscribeAll(); + private _stopWatchingExchangeLogFillEvents(): void { + this._zeroEx.exchange.unsubscribeAll(); } - private async getTokenRegistryTokensByAddressAsync(): Promise { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - const tokenRegistryTokens = await this.zeroEx.tokenRegistry.getTokensAsync(); + private async _getTokenRegistryTokensByAddressAsync(): Promise { + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + const tokenRegistryTokens = await this._zeroEx.tokenRegistry.getTokensAsync(); const tokenByAddress: TokenByAddress = {}; _.each(tokenRegistryTokens, (t: ZeroExToken, i: number) => { @@ -626,8 +626,8 @@ export class Blockchain { }); return tokenByAddress; } - private async onPageLoadInitFireAndForgetAsync() { - await Blockchain.onPageLoadAsync(); // wait for page to load + private async _onPageLoadInitFireAndForgetAsync() { + await Blockchain._onPageLoadAsync(); // wait for page to load // Hack: We need to know the networkId the injectedWeb3 is connected to (if it is defined) in // order to properly instantiate the web3Wrapper. Since we must use the async call, we cannot @@ -645,7 +645,7 @@ export class Blockchain { } } - const provider = await Blockchain.getProviderAsync(injectedWeb3, networkIdIfExists); + const provider = await Blockchain._getProviderAsync(injectedWeb3, networkIdIfExists); const networkId = !_.isUndefined(networkIdIfExists) ? networkIdIfExists : configs.IS_MAINNET_ENABLED ? constants.NETWORK_ID_MAINNET : @@ -653,45 +653,45 @@ export class Blockchain { const zeroExConfigs = { networkId, }; - this.zeroEx = new ZeroEx(provider, zeroExConfigs); - this.updateProviderName(injectedWeb3); + this._zeroEx = new ZeroEx(provider, zeroExConfigs); + this._updateProviderName(injectedWeb3); const shouldPollUserAddress = true; - this.web3Wrapper = new Web3Wrapper(this.dispatcher, provider, networkId, shouldPollUserAddress); - await this.postInstantiationOrUpdatingProviderZeroExAsync(); + this._web3Wrapper = new Web3Wrapper(this._dispatcher, provider, networkId, shouldPollUserAddress); + await this._postInstantiationOrUpdatingProviderZeroExAsync(); } // This method should always be run after instantiating or updating the provider // of the ZeroEx instance. - private async postInstantiationOrUpdatingProviderZeroExAsync() { - utils.assert(!_.isUndefined(this.zeroEx), 'ZeroEx must be instantiated.'); - this.exchangeAddress = this.zeroEx.exchange.getContractAddress(); + private async _postInstantiationOrUpdatingProviderZeroExAsync() { + utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); + this._exchangeAddress = this._zeroEx.exchange.getContractAddress(); } - private updateProviderName(injectedWeb3: Web3) { + private _updateProviderName(injectedWeb3: Web3) { const doesInjectedWeb3Exist = !_.isUndefined(injectedWeb3); const providerName = doesInjectedWeb3Exist ? - Blockchain.getNameGivenProvider(injectedWeb3.currentProvider) : + Blockchain._getNameGivenProvider(injectedWeb3.currentProvider) : constants.PROVIDER_NAME_PUBLIC; - this.dispatcher.updateInjectedProviderName(providerName); + this._dispatcher.updateInjectedProviderName(providerName); } - private async fetchTokenInformationAsync() { + private async _fetchTokenInformationAsync() { utils.assert(!_.isUndefined(this.networkId), 'Cannot call fetchTokenInformationAsync if disconnected from Ethereum node'); - this.dispatcher.updateBlockchainIsLoaded(false); - this.dispatcher.clearTokenByAddress(); + this._dispatcher.updateBlockchainIsLoaded(false); + this._dispatcher.clearTokenByAddress(); - const tokenRegistryTokensByAddress = await this.getTokenRegistryTokensByAddressAsync(); + const tokenRegistryTokensByAddress = await this._getTokenRegistryTokensByAddressAsync(); // HACK: We need to fetch the userAddress here because otherwise we cannot save the // tracked tokens in localStorage under the users address nor fetch the token // balances and allowances and we need to do this in order not to trigger the blockchain // loading dialog to show up twice. First to load the contracts, and second to load the // balances and allowances. - this.userAddress = await this.web3Wrapper.getFirstAccountIfExistsAsync(); - if (!_.isEmpty(this.userAddress)) { - this.dispatcher.updateUserAddress(this.userAddress); + this._userAddress = await this._web3Wrapper.getFirstAccountIfExistsAsync(); + if (!_.isEmpty(this._userAddress)) { + this._dispatcher.updateUserAddress(this._userAddress); } - let trackedTokensIfExists = trackedTokenStorage.getTrackedTokensIfExists(this.userAddress, this.networkId); + let trackedTokensIfExists = trackedTokenStorage.getTrackedTokensIfExists(this._userAddress, this.networkId); const tokenRegistryTokens = _.values(tokenRegistryTokensByAddress); if (_.isUndefined(trackedTokensIfExists)) { trackedTokensIfExists = _.map(configs.DEFAULT_TRACKED_TOKEN_SYMBOLS, symbol => { @@ -700,7 +700,7 @@ export class Blockchain { return token; }); _.each(trackedTokensIfExists, token => { - trackedTokenStorage.addTrackedTokenToUser(this.userAddress, this.networkId, token); + trackedTokenStorage.addTrackedTokenToUser(this._userAddress, this.networkId, token); }); } else { // Properly set all tokenRegistry tokens `isTracked` to true if they are in the existing trackedTokens array @@ -711,7 +711,7 @@ export class Blockchain { }); } const allTokens = _.uniq([...tokenRegistryTokens, ...trackedTokensIfExists]); - this.dispatcher.updateTokenByAddress(allTokens); + this._dispatcher.updateTokenByAddress(allTokens); // Get balance/allowance for tracked tokens await this.updateTokenBalancesAndAllowancesAsync(trackedTokensIfExists); @@ -720,13 +720,13 @@ export class Blockchain { _.find(allTokens, {symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[0]}), _.find(allTokens, {symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[1]}), ]; - this.dispatcher.updateChosenAssetTokenAddress(Side.Deposit, mostPopularTradingPairTokens[0].address); - this.dispatcher.updateChosenAssetTokenAddress(Side.Receive, mostPopularTradingPairTokens[1].address); - this.dispatcher.updateBlockchainIsLoaded(true); + this._dispatcher.updateChosenAssetTokenAddress(Side.Deposit, mostPopularTradingPairTokens[0].address); + this._dispatcher.updateChosenAssetTokenAddress(Side.Receive, mostPopularTradingPairTokens[1].address); + this._dispatcher.updateBlockchainIsLoaded(true); } - private async instantiateContractIfExistsAsync(artifact: any, address?: string): Promise { + private async _instantiateContractIfExistsAsync(artifact: any, address?: string): Promise { const c = await contract(artifact); - const providerObj = this.web3Wrapper.getProviderObj(); + const providerObj = this._web3Wrapper.getProviderObj(); c.setProvider(providerObj); const artifactNetworkConfigs = artifact.networks[this.networkId]; -- cgit From e744e4cd989bd3ae1070c59f7baa8097f18b8b06 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Fri, 22 Dec 2017 15:05:32 +0100 Subject: Apply prettier config --- packages/website/ts/blockchain.ts | 249 ++++++++++++++++++++------------------ 1 file changed, 130 insertions(+), 119 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 3d21a5046..4ed1fe371 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -21,16 +21,16 @@ import { LedgerWalletSubprovider, RedundantRPCSubprovider, } from '@0xproject/subproviders'; -import {intervalUtils, promisify} from '@0xproject/utils'; +import { intervalUtils, promisify } from '@0xproject/utils'; import BigNumber from 'bignumber.js'; import * as _ from 'lodash'; import * as React from 'react'; import contract = require('truffle-contract'); -import {TokenSendCompleted} from 'ts/components/flash_messages/token_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 { TokenSendCompleted } from 'ts/components/flash_messages/token_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, @@ -43,11 +43,11 @@ import { TokenByAddress, TokenStateByAddress, } from 'ts/types'; -import {configs} from 'ts/utils/configs'; -import {constants} from 'ts/utils/constants'; -import {errorReporter} from 'ts/utils/error_reporter'; -import {utils} from 'ts/utils/utils'; -import {Web3Wrapper} from 'ts/web3_wrapper'; +import { configs } from 'ts/utils/configs'; +import { constants } from 'ts/utils/constants'; +import { errorReporter } from 'ts/utils/error_reporter'; +import { utils } from 'ts/utils/utils'; +import { Web3Wrapper } from 'ts/web3_wrapper'; import Web3 = require('web3'); import ProviderEngine = require('web3-provider-engine'); import FilterSubprovider = require('web3-provider-engine/subproviders/filters'); @@ -101,9 +101,7 @@ export class Blockchain { provider = new ProviderEngine(); provider.addProvider(new InjectedWeb3Subprovider(injectedWeb3)); provider.addProvider(new FilterSubprovider()); - provider.addProvider(new RedundantRPCSubprovider( - publicNodeUrlsIfExistsForNetworkId, - )); + provider.addProvider(new RedundantRPCSubprovider(publicNodeUrlsIfExistsForNetworkId)); provider.start(); } else if (doesInjectedWeb3Exist) { // Since no public node for this network, all requests go to injectedWeb3 instance @@ -114,12 +112,8 @@ export class Blockchain { // injected into their browser. provider = new ProviderEngine(); provider.addProvider(new FilterSubprovider()); - const networkId = configs.IS_MAINNET_ENABLED ? - constants.NETWORK_ID_MAINNET : - constants.NETWORK_ID_TESTNET; - provider.addProvider(new RedundantRPCSubprovider( - configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId], - )); + const networkId = configs.IS_MAINNET_ENABLED ? constants.NETWORK_ID_MAINNET : constants.NETWORK_ID_TESTNET; + provider.addProvider(new RedundantRPCSubprovider(configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId])); provider.start(); } @@ -162,8 +156,7 @@ export class Blockchain { // already in the tokenRegistry. // TODO: Remove this hack once we've updated the TokenRegistries // Airtable task: https://airtable.com/tblFe0Q9JuKJPYbTn/viwsOG2Y97qdIeCIO/recv3VGmIorFzHBVz - if (configs.SHOULD_DEPRECATE_OLD_WETH_TOKEN && - tokenAddress === configs.NEW_WRAPPED_ETHERS[this.networkId]) { + if (configs.SHOULD_DEPRECATE_OLD_WETH_TOKEN && tokenAddress === configs.NEW_WRAPPED_ETHERS[this.networkId]) { return true; } const tokenIfExists = await this._zeroEx.tokenRegistry.getTokenIfExistsAsync(tokenAddress); @@ -213,12 +206,10 @@ export class Blockchain { this._ledgerSubprovider = new LedgerSubprovider(ledgerWalletConfigs); provider.addProvider(this._ledgerSubprovider); provider.addProvider(new FilterSubprovider()); - const networkId = configs.IS_MAINNET_ENABLED ? - constants.NETWORK_ID_MAINNET : - constants.NETWORK_ID_TESTNET; - provider.addProvider(new RedundantRPCSubprovider( - configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId], - )); + const networkId = configs.IS_MAINNET_ENABLED + ? constants.NETWORK_ID_MAINNET + : constants.NETWORK_ID_TESTNET; + provider.addProvider(new RedundantRPCSubprovider(configs.PUBLIC_NODE_URLS_BY_NETWORK_ID[networkId])); provider.start(); this._web3Wrapper.destroy(); const shouldPollUserAddress = false; @@ -254,32 +245,46 @@ export class Blockchain { utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); const txHash = await this._zeroEx.token.setProxyAllowanceAsync( - token.address, this._userAddress, amountInBaseUnits, + token.address, + this._userAddress, + amountInBaseUnits, ); await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const allowance = amountInBaseUnits; this._dispatcher.replaceTokenAllowanceByAddress(token.address, allowance); } - public async transferAsync(token: Token, toAddress: string, - amountInBaseUnits: BigNumber): Promise { + public async transferAsync(token: Token, toAddress: string, amountInBaseUnits: BigNumber): Promise { const txHash = await this._zeroEx.token.transferAsync( - token.address, this._userAddress, toAddress, amountInBaseUnits, + token.address, + this._userAddress, + toAddress, + amountInBaseUnits, ); await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const etherScanLinkIfExists = utils.getEtherScanLinkIfExists(txHash, this.networkId, EtherscanLinkSuffixes.Tx); - this._dispatcher.showFlashMessage(React.createElement(TokenSendCompleted, { - etherScanLinkIfExists, - token, - toAddress, - amountInBaseUnits, - })); - } - public portalOrderToSignedOrder(maker: string, taker: string, makerTokenAddress: string, - takerTokenAddress: string, makerTokenAmount: BigNumber, - takerTokenAmount: BigNumber, makerFee: BigNumber, - takerFee: BigNumber, expirationUnixTimestampSec: BigNumber, - feeRecipient: string, - signatureData: SignatureData, salt: BigNumber): SignedOrder { + this._dispatcher.showFlashMessage( + React.createElement(TokenSendCompleted, { + etherScanLinkIfExists, + token, + toAddress, + amountInBaseUnits, + }), + ); + } + public portalOrderToSignedOrder( + maker: string, + taker: string, + makerTokenAddress: string, + takerTokenAddress: string, + makerTokenAmount: BigNumber, + takerTokenAmount: BigNumber, + makerFee: BigNumber, + takerFee: BigNumber, + expirationUnixTimestampSec: BigNumber, + feeRecipient: string, + signatureData: SignatureData, + salt: BigNumber, + ): SignedOrder { const ecSignature = signatureData; const exchangeContractAddress = this.getExchangeContractAddressIfExists(); const takerOrNullAddress = _.isEmpty(taker) ? constants.NULL_ADDRESS : taker; @@ -300,33 +305,32 @@ export class Blockchain { }; return signedOrder; } - public async fillOrderAsync(signedOrder: SignedOrder, - fillTakerTokenAmount: BigNumber): Promise { + public async fillOrderAsync(signedOrder: SignedOrder, fillTakerTokenAmount: BigNumber): Promise { utils.assert(this._doesUserAddressExist(), BlockchainCallErrs.UserHasNoAssociatedAddresses); const shouldThrowOnInsufficientBalanceOrAllowance = true; const txHash = await this._zeroEx.exchange.fillOrderAsync( - signedOrder, fillTakerTokenAmount, shouldThrowOnInsufficientBalanceOrAllowance, this._userAddress, + signedOrder, + fillTakerTokenAmount, + shouldThrowOnInsufficientBalanceOrAllowance, + this._userAddress, ); const receipt = await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const logs: Array> = receipt.logs as any; this._zeroEx.exchange.throwLogErrorsAsErrors(logs); - const logFill = _.find(logs, {event: 'LogFill'}); - const args = logFill.args as any as LogFillContractEventArgs; + const logFill = _.find(logs, { event: 'LogFill' }); + const args = (logFill.args as any) as LogFillContractEventArgs; const filledTakerTokenAmount = args.filledTakerTokenAmount; return filledTakerTokenAmount; } - public async cancelOrderAsync(signedOrder: SignedOrder, - cancelTakerTokenAmount: BigNumber): Promise { - const txHash = await this._zeroEx.exchange.cancelOrderAsync( - signedOrder, cancelTakerTokenAmount, - ); + public async cancelOrderAsync(signedOrder: SignedOrder, cancelTakerTokenAmount: BigNumber): Promise { + const txHash = await this._zeroEx.exchange.cancelOrderAsync(signedOrder, cancelTakerTokenAmount); const receipt = await this._showEtherScanLinkAndAwaitTransactionMinedAsync(txHash); const logs: Array> = receipt.logs as any; this._zeroEx.exchange.throwLogErrorsAsErrors(logs); - const logCancel = _.find(logs, {event: ExchangeEvents.LogCancel}); - const args = logCancel.args as any as LogCancelContractEventArgs; + const logCancel = _.find(logs, { event: ExchangeEvents.LogCancel }); + const args = (logCancel.args as any) as LogCancelContractEventArgs; const cancelledTakerTokenAmount = args.cancelledTakerTokenAmount; return cancelledTakerTokenAmount; } @@ -339,14 +343,21 @@ export class Blockchain { public getExchangeContractAddressIfExists() { return this._exchangeAddress; } - public async validateFillOrderThrowIfInvalidAsync(signedOrder: SignedOrder, - fillTakerTokenAmount: BigNumber, - takerAddress: string): Promise { + public async validateFillOrderThrowIfInvalidAsync( + signedOrder: SignedOrder, + fillTakerTokenAmount: BigNumber, + takerAddress: string, + ): Promise { await this._zeroEx.exchange.validateFillOrderThrowIfInvalidAsync( - signedOrder, fillTakerTokenAmount, takerAddress); + signedOrder, + fillTakerTokenAmount, + takerAddress, + ); } - public async validateCancelOrderThrowIfInvalidAsync(order: Order, - cancelTakerTokenAmount: BigNumber): Promise { + public async validateCancelOrderThrowIfInvalidAsync( + order: Order, + cancelTakerTokenAmount: BigNumber, + ): Promise { await this._zeroEx.exchange.validateCancelOrderThrowIfInvalidAsync(order, cancelTakerTokenAmount); } public isValidAddress(address: string): boolean { @@ -415,11 +426,10 @@ export class Blockchain { return doesContractExist; } public async getCurrentUserTokenBalanceAndAllowanceAsync(tokenAddress: string): Promise { - const tokenBalanceAndAllowance = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, tokenAddress); - return tokenBalanceAndAllowance; + const tokenBalanceAndAllowance = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, tokenAddress); + return tokenBalanceAndAllowance; } - public async getTokenBalanceAndAllowanceAsync(ownerAddress: string, tokenAddress: string): - Promise { + public async getTokenBalanceAndAllowanceAsync(ownerAddress: string, tokenAddress: string): Promise { utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); if (_.isEmpty(ownerAddress)) { @@ -440,10 +450,7 @@ export class Blockchain { let balance = new BigNumber(0); let allowance = new BigNumber(0); if (this._doesUserAddressExist()) { - [ - balance, - allowance, - ] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); + [balance, allowance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); } const tokenState = { balance, @@ -470,11 +477,14 @@ export class Blockchain { this._stopWatchingExchangeLogFillEvents(); } private async _showEtherScanLinkAndAwaitTransactionMinedAsync( - txHash: string): Promise { + txHash: string, + ): Promise { const etherScanLinkIfExists = utils.getEtherScanLinkIfExists(txHash, this.networkId, EtherscanLinkSuffixes.Tx); - this._dispatcher.showFlashMessage(React.createElement(TransactionSubmitted, { - etherScanLinkIfExists, - })); + this._dispatcher.showFlashMessage( + React.createElement(TransactionSubmitted, { + etherScanLinkIfExists, + }), + ); const receipt = await this._zeroEx.awaitTransactionMinedAsync(txHash); return receipt; } @@ -506,29 +516,31 @@ export class Blockchain { // Start a subscription for new logs this._zeroEx.exchange.subscribe( - ExchangeEvents.LogFill, indexFilterValues, + ExchangeEvents.LogFill, + indexFilterValues, async (err: Error, decodedLogEvent: DecodedLogEvent) => { - 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 - // tslint:disable-next-line:no-floating-promises - errorReporter.reportAsync(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._userAddress, this.networkId, fill); + 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 + // tslint:disable-next-line:no-floating-promises + errorReporter.reportAsync(err); // fire and forget + return; } else { - tradeHistoryStorage.addFillToUser(this._userAddress, this.networkId, fill); + 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._userAddress, this.networkId, fill); + } else { + tradeHistoryStorage.addFillToUser(this._userAddress, this.networkId, fill); + } } - } - }); + }, + ); } private async _fetchHistoricalExchangeLogFillEventsAsync(indexFilterValues: IndexedFilterValues) { const fromBlock = tradeHistoryStorage.getFillsLatestBlock(this._userAddress, this.networkId); @@ -537,7 +549,9 @@ export class Blockchain { toBlock: 'latest' as BlockParam, }; const decodedLogs = await this._zeroEx.exchange.getLogsAsync( - ExchangeEvents.LogFill, blockRange, indexFilterValues, + ExchangeEvents.LogFill, + blockRange, + indexFilterValues, ); for (const decodedLog of decodedLogs) { if (!this._doesLogEventInvolveUser(decodedLog)) { @@ -569,8 +583,7 @@ export class Blockchain { } private _doesLogEventInvolveUser(decodedLog: LogWithDecodedArgs) { const args = decodedLog.args; - const isUserMakerOrTaker = args.maker === this._userAddress || - args.taker === this._userAddress; + const isUserMakerOrTaker = args.maker === this._userAddress || args.taker === this._userAddress; return isUserMakerOrTaker; } private _updateLatestFillsBlockIfNeeded(blockNumber: number) { @@ -582,9 +595,8 @@ export class Blockchain { // 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; + const blockNumberToSet = + blockNumber - BLOCK_NUMBER_BACK_TRACK < 0 ? 0 : blockNumber - BLOCK_NUMBER_BACK_TRACK; tradeHistoryStorage.setFillsLatestBlock(this._userAddress, this.networkId, blockNumberToSet); } } @@ -608,10 +620,10 @@ export class Blockchain { // Airtable task: https://airtable.com/tblFe0Q9JuKJPYbTn/viwsOG2Y97qdIeCIO/recv3VGmIorFzHBVz let address = t.address; if (configs.SHOULD_DEPRECATE_OLD_WETH_TOKEN && t.symbol === 'WETH') { - const newEtherTokenAddressIfExists = configs.NEW_WRAPPED_ETHERS[this.networkId]; - if (!_.isUndefined(newEtherTokenAddressIfExists)) { - address = newEtherTokenAddressIfExists; - } + const newEtherTokenAddressIfExists = configs.NEW_WRAPPED_ETHERS[this.networkId]; + if (!_.isUndefined(newEtherTokenAddressIfExists)) { + address = newEtherTokenAddressIfExists; + } } const token: Token = { iconUrl, @@ -646,10 +658,9 @@ export class Blockchain { } const provider = await Blockchain._getProviderAsync(injectedWeb3, networkIdIfExists); - const networkId = !_.isUndefined(networkIdIfExists) ? networkIdIfExists : - configs.IS_MAINNET_ENABLED ? - constants.NETWORK_ID_MAINNET : - constants.NETWORK_ID_TESTNET; + const networkId = !_.isUndefined(networkIdIfExists) + ? networkIdIfExists + : configs.IS_MAINNET_ENABLED ? constants.NETWORK_ID_MAINNET : constants.NETWORK_ID_TESTNET; const zeroExConfigs = { networkId, }; @@ -667,14 +678,16 @@ export class Blockchain { } private _updateProviderName(injectedWeb3: Web3) { const doesInjectedWeb3Exist = !_.isUndefined(injectedWeb3); - const providerName = doesInjectedWeb3Exist ? - Blockchain._getNameGivenProvider(injectedWeb3.currentProvider) : - constants.PROVIDER_NAME_PUBLIC; + const providerName = doesInjectedWeb3Exist + ? Blockchain._getNameGivenProvider(injectedWeb3.currentProvider) + : constants.PROVIDER_NAME_PUBLIC; this._dispatcher.updateInjectedProviderName(providerName); } private async _fetchTokenInformationAsync() { - utils.assert(!_.isUndefined(this.networkId), - 'Cannot call fetchTokenInformationAsync if disconnected from Ethereum node'); + utils.assert( + !_.isUndefined(this.networkId), + 'Cannot call fetchTokenInformationAsync if disconnected from Ethereum node', + ); this._dispatcher.updateBlockchainIsLoaded(false); this._dispatcher.clearTokenByAddress(); @@ -717,8 +730,8 @@ export class Blockchain { await this.updateTokenBalancesAndAllowancesAsync(trackedTokensIfExists); const mostPopularTradingPairTokens: Token[] = [ - _.find(allTokens, {symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[0]}), - _.find(allTokens, {symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[1]}), + _.find(allTokens, { symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[0] }), + _.find(allTokens, { symbol: configs.DEFAULT_TRACKED_TOKEN_SYMBOLS[1] }), ]; this._dispatcher.updateChosenAssetTokenAddress(Side.Deposit, mostPopularTradingPairTokens[0].address); this._dispatcher.updateChosenAssetTokenAddress(Side.Receive, mostPopularTradingPairTokens[1].address); @@ -746,9 +759,7 @@ export class Blockchain { } try { - const contractInstance = _.isUndefined(address) ? - await c.deployed() : - await c.at(address); + const contractInstance = _.isUndefined(address) ? await c.deployed() : await c.at(address); return contractInstance; } catch (err) { const errMsg = `${err}`; -- cgit From 4dfa720f2dec2be0b0758633c087579a02e482bb Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Thu, 4 Jan 2018 12:38:19 +0100 Subject: Use configured version of bignumber in all packages --- packages/website/ts/blockchain.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 4ed1fe371..b209d3ba0 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -22,7 +22,7 @@ import { RedundantRPCSubprovider, } from '@0xproject/subproviders'; import { intervalUtils, promisify } from '@0xproject/utils'; -import BigNumber from 'bignumber.js'; +import { BigNumber } from '@0xproject/utils'; import * as _ from 'lodash'; import * as React from 'react'; import contract = require('truffle-contract'); -- cgit From e2ef0c5b9419fa1536a1b7e478f7950e69e8ff0e Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Thu, 4 Jan 2018 15:12:32 +0100 Subject: Fix linter errors --- packages/website/ts/blockchain.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index b209d3ba0..50cac6d29 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -21,8 +21,7 @@ import { LedgerWalletSubprovider, RedundantRPCSubprovider, } from '@0xproject/subproviders'; -import { intervalUtils, promisify } from '@0xproject/utils'; -import { BigNumber } from '@0xproject/utils'; +import { BigNumber, intervalUtils, promisify } from '@0xproject/utils'; import * as _ from 'lodash'; import * as React from 'react'; import contract = require('truffle-contract'); -- cgit From e34b0af25133629ad4c177c4d7d5050bd6ac19b8 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Wed, 10 Jan 2018 12:39:37 +0100 Subject: Fix ts error in portal after enabling more strict checks --- packages/website/ts/blockchain.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 50cac6d29..1320fbeb9 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -66,12 +66,12 @@ export class Blockchain { private _cachedProvider: Web3.Provider; private _ledgerSubprovider: LedgerWalletSubprovider; private _zrxPollIntervalId: NodeJS.Timer; - private static async _onPageLoadAsync() { + private static async _onPageLoadAsync(): Promise { if (document.readyState === 'complete') { return; // Already loaded } - return new Promise((resolve, reject) => { - window.onload = resolve; + return new Promise((resolve, reject) => { + window.onload = () => resolve(); }); } private static _getNameGivenProvider(provider: Web3.Provider): string { -- cgit From 996e9e9102dc3f7ebcd6328c59593410c397c779 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Thu, 18 Jan 2018 15:02:36 +0800 Subject: Add missing onError callbacks --- packages/website/ts/blockchain.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 1320fbeb9..e82243c83 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -375,7 +375,11 @@ export class Blockchain { clearInterval(this._zrxPollIntervalId); delete this._zrxPollIntervalId; } - }, 5000); + }, 5000, (err: Error) => { + utils.consoleLog(`Polling tokenBalance failed: ${err}`); + clearInterval(this._zrxPollIntervalId); + delete this._zrxPollIntervalId; + }); } public async signOrderHashAsync(orderHash: string): Promise { utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); -- cgit From f9c21efc3073fea4578d46a47f5a08214c592e87 Mon Sep 17 00:00:00 2001 From: Fabio Berger Date: Thu, 18 Jan 2018 19:29:54 +0800 Subject: Use intervalUtils.clearAsyncExcludingInterval instead of calling clearInterval directly for grepability --- packages/website/ts/blockchain.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index e82243c83..66f982427 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -372,12 +372,12 @@ export class Blockchain { const [balance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); if (!balance.eq(currBalance)) { this._dispatcher.replaceTokenBalanceByAddress(token.address, balance); - clearInterval(this._zrxPollIntervalId); + intervalUtils.clearAsyncExcludingInterval(this._zrxPollIntervalId); delete this._zrxPollIntervalId; } }, 5000, (err: Error) => { utils.consoleLog(`Polling tokenBalance failed: ${err}`); - clearInterval(this._zrxPollIntervalId); + intervalUtils.clearAsyncExcludingInterval(this._zrxPollIntervalId); delete this._zrxPollIntervalId; }); } @@ -475,7 +475,7 @@ export class Blockchain { this._web3Wrapper.updatePrevUserAddress(newUserAddress); } public destroy() { - clearInterval(this._zrxPollIntervalId); + intervalUtils.clearAsyncExcludingInterval(this._zrxPollIntervalId); this._web3Wrapper.destroy(); this._stopWatchingExchangeLogFillEvents(); } -- cgit From 614ea14a7fe90252d2bef8a97b3c376ae4498a17 Mon Sep 17 00:00:00 2001 From: Leonid Logvinov Date: Thu, 18 Jan 2018 16:18:25 +0100 Subject: Fix prettier --- packages/website/ts/blockchain.ts | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) (limited to 'packages/website/ts/blockchain.ts') diff --git a/packages/website/ts/blockchain.ts b/packages/website/ts/blockchain.ts index 66f982427..5530701c0 100644 --- a/packages/website/ts/blockchain.ts +++ b/packages/website/ts/blockchain.ts @@ -368,18 +368,22 @@ export class Blockchain { const [currBalance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); - this._zrxPollIntervalId = intervalUtils.setAsyncExcludingInterval(async () => { - const [balance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); - if (!balance.eq(currBalance)) { - this._dispatcher.replaceTokenBalanceByAddress(token.address, balance); + this._zrxPollIntervalId = intervalUtils.setAsyncExcludingInterval( + async () => { + const [balance] = await this.getTokenBalanceAndAllowanceAsync(this._userAddress, token.address); + if (!balance.eq(currBalance)) { + this._dispatcher.replaceTokenBalanceByAddress(token.address, balance); + intervalUtils.clearAsyncExcludingInterval(this._zrxPollIntervalId); + delete this._zrxPollIntervalId; + } + }, + 5000, + (err: Error) => { + utils.consoleLog(`Polling tokenBalance failed: ${err}`); intervalUtils.clearAsyncExcludingInterval(this._zrxPollIntervalId); delete this._zrxPollIntervalId; - } - }, 5000, (err: Error) => { - utils.consoleLog(`Polling tokenBalance failed: ${err}`); - intervalUtils.clearAsyncExcludingInterval(this._zrxPollIntervalId); - delete this._zrxPollIntervalId; - }); + }, + ); } public async signOrderHashAsync(orderHash: string): Promise { utils.assert(!_.isUndefined(this._zeroEx), 'ZeroEx must be instantiated.'); -- cgit