diff options
Diffstat (limited to 'packages/instant')
-rw-r--r-- | packages/instant/src/components/zero_ex_instant_provider.tsx | 25 | ||||
-rw-r--r-- | packages/instant/src/constants.ts | 2 | ||||
-rw-r--r-- | packages/instant/src/containers/selected_erc20_asset_amount_input.ts | 2 | ||||
-rw-r--r-- | packages/instant/src/redux/async_data.ts | 4 | ||||
-rw-r--r-- | packages/instant/src/util/buy_quote_fetcher.ts | 75 | ||||
-rw-r--r-- | packages/instant/src/util/heartbeater.ts | 42 | ||||
-rw-r--r-- | packages/instant/src/util/heartbeater_factory.ts | 17 |
7 files changed, 162 insertions, 5 deletions
diff --git a/packages/instant/src/components/zero_ex_instant_provider.tsx b/packages/instant/src/components/zero_ex_instant_provider.tsx index cceb44377..34257d25f 100644 --- a/packages/instant/src/components/zero_ex_instant_provider.tsx +++ b/packages/instant/src/components/zero_ex_instant_provider.tsx @@ -5,6 +5,7 @@ import * as _ from 'lodash'; import * as React from 'react'; import { Provider as ReduxProvider } from 'react-redux'; +import { ACCOUNT_UPDATE_INTERVAL_TIME_MS, BUY_QUOTE_UPDATE_INTERVAL_TIME_MS } from '../constants'; import { SelectedAssetThemeProvider } from '../containers/selected_asset_theme_provider'; import { asyncData } from '../redux/async_data'; import { DEFAULT_STATE, DefaultState, State } from '../redux/reducer'; @@ -14,6 +15,8 @@ import { AffiliateInfo, AssetMetaData, Network, OrderSource } from '../types'; import { assetUtils } from '../util/asset'; import { errorFlasher } from '../util/error_flasher'; import { gasPriceEstimator } from '../util/gas_price_estimator'; +import { Heartbeater } from '../util/heartbeater'; +import { generateAccountHeartbeater, generateBuyQuoteHeartbeater } from '../util/heartbeater_factory'; import { providerStateFactory } from '../util/provider_state_factory'; fonts.include(); @@ -37,6 +40,9 @@ export interface ZeroExInstantProviderOptionalProps { export class ZeroExInstantProvider extends React.Component<ZeroExInstantProviderProps> { private readonly _store: Store; + private _accountUpdateHeartbeat?: Heartbeater; + private _buyQuoteHeartbeat?: Heartbeater; + // TODO(fragosti): Write tests for this beast once we inject a provider. private static _mergeDefaultStateWithProps( props: ZeroExInstantProviderProps, @@ -93,9 +99,14 @@ export class ZeroExInstantProvider extends React.Component<ZeroExInstantProvider asyncData.fetchAvailableAssetDatasAndDispatchToStore(this._store); } // tslint:disable-next-line:no-floating-promises - asyncData.fetchAccountInfoAndDispatchToStore(this._store); - // tslint:disable-next-line:no-floating-promises - asyncData.fetchCurrentBuyQuoteAndDispatchToStore(this._store); + // asyncData.fetchAccountInfoAndDispatchToStore(this._store); + + this._accountUpdateHeartbeat = generateAccountHeartbeater(this._store); + this._accountUpdateHeartbeat.start(ACCOUNT_UPDATE_INTERVAL_TIME_MS); + + this._buyQuoteHeartbeat = generateBuyQuoteHeartbeater(this._store); + this._buyQuoteHeartbeat.start(BUY_QUOTE_UPDATE_INTERVAL_TIME_MS); + // warm up the gas price estimator cache just in case we can't // grab the gas price estimate when submitting the transaction // tslint:disable-next-line:no-floating-promises @@ -103,6 +114,14 @@ export class ZeroExInstantProvider extends React.Component<ZeroExInstantProvider // tslint:disable-next-line:no-floating-promises this._flashErrorIfWrongNetwork(); } + public componentWillUnmount(): void { + if (this._accountUpdateHeartbeat) { + this._accountUpdateHeartbeat.stop(); + } + if (this._buyQuoteHeartbeat) { + this._buyQuoteHeartbeat.stop(); + } + } public render(): React.ReactNode { return ( <ReduxProvider store={this._store}> diff --git a/packages/instant/src/constants.ts b/packages/instant/src/constants.ts index b5c4f96e4..37320e21d 100644 --- a/packages/instant/src/constants.ts +++ b/packages/instant/src/constants.ts @@ -11,6 +11,8 @@ export const WEB_3_WRAPPER_TRANSACTION_FAILED_ERROR_MSG_PREFIX = 'Transaction fa export const GWEI_IN_WEI = new BigNumber(1000000000); export const ONE_SECOND_MS = 1000; export const ONE_MINUTE_MS = ONE_SECOND_MS * 60; +export const ACCOUNT_UPDATE_INTERVAL_TIME_MS = ONE_SECOND_MS * 15; +export const BUY_QUOTE_UPDATE_INTERVAL_TIME_MS = ONE_SECOND_MS * 15; export const DEFAULT_GAS_PRICE = GWEI_IN_WEI.mul(6); export const DEFAULT_ESTIMATED_TRANSACTION_TIME_MS = ONE_MINUTE_MS * 2; export const ETH_GAS_STATION_API_BASE_URL = 'https://ethgasstation.info'; diff --git a/packages/instant/src/containers/selected_erc20_asset_amount_input.ts b/packages/instant/src/containers/selected_erc20_asset_amount_input.ts index c550aef04..74713327c 100644 --- a/packages/instant/src/containers/selected_erc20_asset_amount_input.ts +++ b/packages/instant/src/containers/selected_erc20_asset_amount_input.ts @@ -11,6 +11,7 @@ import { Action, actions } from '../redux/actions'; import { State } from '../redux/reducer'; import { ColorOption } from '../style/theme'; import { AffiliateInfo, ERC20Asset, OrderProcessState } from '../types'; +import { updateBuyQuoteOrFlashErrorAsync } from '../util/buy_quote_fetcher'; import { buyQuoteUpdater } from '../util/buy_quote_updater'; export interface SelectedERC20AssetAmountInputProps { @@ -67,6 +68,7 @@ const mapStateToProps = (state: State, _ownProps: SelectedERC20AssetAmountInputP }; }; +// TODO: change to set pending to true const debouncedUpdateBuyQuoteAsync = _.debounce(buyQuoteUpdater.updateBuyQuoteAsync.bind(buyQuoteUpdater), 200, { trailing: true, }); diff --git a/packages/instant/src/redux/async_data.ts b/packages/instant/src/redux/async_data.ts index a8f632009..a50f24cba 100644 --- a/packages/instant/src/redux/async_data.ts +++ b/packages/instant/src/redux/async_data.ts @@ -36,10 +36,10 @@ export const asyncData = { store.dispatch(actions.setAvailableAssets([])); } }, - fetchAccountInfoAndDispatchToStore: async (store: Store) => { + fetchAccountInfoAndDispatchToStore: async (store: Store, options = { setLoading: true }) => { const { providerState } = store.getState(); const web3Wrapper = providerState.web3Wrapper; - if (providerState.account.state !== AccountState.Loading) { + if (options.setLoading && providerState.account.state !== AccountState.Loading) { store.dispatch(actions.setAccountStateLoading()); } let availableAddresses: string[]; diff --git a/packages/instant/src/util/buy_quote_fetcher.ts b/packages/instant/src/util/buy_quote_fetcher.ts new file mode 100644 index 000000000..22ce835e8 --- /dev/null +++ b/packages/instant/src/util/buy_quote_fetcher.ts @@ -0,0 +1,75 @@ +// TODO: rename file and export object +// TODO: delete this + +import { AssetBuyer, AssetBuyerError, BuyQuote } from '@0x/asset-buyer'; +import { AssetProxyId } from '@0x/types'; +import { BigNumber } from '@0x/utils'; +import { Web3Wrapper } from '@0x/web3-wrapper'; +import * as _ from 'lodash'; +import { Dispatch } from 'redux'; +import { oc } from 'ts-optchain'; + +import { Action, actions } from '../redux/actions'; +import { State } from '../redux/reducer'; +import { AffiliateInfo, ERC20Asset } from '../types'; +import { assetUtils } from '../util/asset'; + +import { errorFlasher } from './error_flasher'; + +export const updateBuyQuoteOrFlashErrorAsync = async ( + assetBuyer: AssetBuyer, + asset: ERC20Asset, + assetAmount: BigNumber, + dispatch: Dispatch<Action>, + affiliateInfo?: AffiliateInfo, +) => { + // get a new buy quote. + const baseUnitValue = Web3Wrapper.toBaseUnitAmount(assetAmount, asset.metaData.decimals); + + const feePercentage = oc(affiliateInfo).feePercentage(); + let newBuyQuote: BuyQuote | undefined; + try { + newBuyQuote = await assetBuyer.getBuyQuoteAsync(asset.assetData, baseUnitValue, { feePercentage }); + } catch (error) { + dispatch(actions.setQuoteRequestStateFailure()); + let errorMessage; + if (error.message === AssetBuyerError.InsufficientAssetLiquidity) { + const assetName = assetUtils.bestNameForAsset(asset, 'of this asset'); + errorMessage = `Not enough ${assetName} available`; + } else if (error.message === AssetBuyerError.InsufficientZrxLiquidity) { + errorMessage = 'Not enough ZRX available'; + } else if ( + error.message === AssetBuyerError.StandardRelayerApiError || + error.message.startsWith(AssetBuyerError.AssetUnavailable) + ) { + const assetName = assetUtils.bestNameForAsset(asset, 'This asset'); + errorMessage = `${assetName} is currently unavailable`; + } + if (!_.isUndefined(errorMessage)) { + errorFlasher.flashNewErrorMessage(dispatch, errorMessage); + } else { + throw error; + } + return; + } + // We have a successful new buy quote + errorFlasher.clearError(dispatch); + // invalidate the last buy quote. + dispatch(actions.updateLatestBuyQuote(newBuyQuote)); +}; + +export const updateBuyQuoteOrFlashErrorAsyncForState = async (state: State, dispatch: Dispatch<Action>) => { + const { selectedAsset, selectedAssetAmount, affiliateInfo } = state; + const assetBuyer = state.providerState.assetBuyer; + + if (selectedAsset && selectedAssetAmount && selectedAsset.metaData.assetProxyId === AssetProxyId.ERC20) { + // TODO: maybe dont do in the case of an error showing + updateBuyQuoteOrFlashErrorAsync( + assetBuyer, + selectedAsset as ERC20Asset, // TODO: better way to do this? + selectedAssetAmount, + dispatch, + affiliateInfo, + ); + } +}; diff --git a/packages/instant/src/util/heartbeater.ts b/packages/instant/src/util/heartbeater.ts new file mode 100644 index 000000000..bb4e99383 --- /dev/null +++ b/packages/instant/src/util/heartbeater.ts @@ -0,0 +1,42 @@ +import * as _ from 'lodash'; + +type HeartbeatableFunction = () => Promise<void>; +export class Heartbeater { + private _intervalId?: number; + private _hasPendingRequest: boolean; + private _performFunction: HeartbeatableFunction; + + public constructor(_performingFunctionAsync: HeartbeatableFunction) { + this._performFunction = _performingFunctionAsync; + this._hasPendingRequest = false; + } + + public start(intervalTimeMs: number): void { + if (!_.isUndefined(this._intervalId)) { + throw new Error('Heartbeat is running, please stop before restarting'); + } + this._trackAndPerformAsync(); + this._intervalId = window.setInterval(this._trackAndPerformAsync.bind(this), intervalTimeMs); + } + + public stop(): void { + if (this._intervalId) { + window.clearInterval(this._intervalId); + } + this._intervalId = undefined; + this._hasPendingRequest = false; + } + + private async _trackAndPerformAsync(): Promise<void> { + if (this._hasPendingRequest) { + return; + } + + this._hasPendingRequest = true; + try { + await this._performFunction(); + } finally { + this._hasPendingRequest = false; + } + } +} diff --git a/packages/instant/src/util/heartbeater_factory.ts b/packages/instant/src/util/heartbeater_factory.ts new file mode 100644 index 000000000..9fac9cf4c --- /dev/null +++ b/packages/instant/src/util/heartbeater_factory.ts @@ -0,0 +1,17 @@ +import { asyncData } from '../redux/async_data'; +import { Store } from '../redux/store'; + +import { updateBuyQuoteOrFlashErrorAsyncForState } from './buy_quote_fetcher'; +import { Heartbeater } from './heartbeater'; + +export const generateAccountHeartbeater = (store: Store): Heartbeater => { + return new Heartbeater(async () => { + await asyncData.fetchAccountInfoAndDispatchToStore(store, { setLoading: false }); + }); +}; + +export const generateBuyQuoteHeartbeater = (store: Store): Heartbeater => { + return new Heartbeater(async () => { + await updateBuyQuoteOrFlashErrorAsyncForState(store.getState(), store.dispatch); + }); +}; |