diff options
author | Hsuan Lee <hsuan@cobinhood.com> | 2019-01-19 18:42:04 +0800 |
---|---|---|
committer | Hsuan Lee <hsuan@cobinhood.com> | 2019-01-19 18:42:04 +0800 |
commit | 7ae38906926dc09bc10670c361af0d2bf0050426 (patch) | |
tree | 5fb10ae366b987db09e4ddb4bc3ba0f75404ad08 /packages/instant/src/util | |
parent | b5fd3c72a08aaa6957917d74c333387a16edf66b (diff) | |
download | dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.gz dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.bz2 dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.lz dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.xz dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.tar.zst dexon-sol-tools-7ae38906926dc09bc10670c361af0d2bf0050426.zip |
Update dependency packages
Diffstat (limited to 'packages/instant/src/util')
21 files changed, 0 insertions, 1272 deletions
diff --git a/packages/instant/src/util/address.ts b/packages/instant/src/util/address.ts deleted file mode 100644 index b21863a8e..000000000 --- a/packages/instant/src/util/address.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { Web3Wrapper } from '@0x/web3-wrapper'; - -export const getBestAddress = async (web3Wrapper: Web3Wrapper): Promise<string | undefined> => { - const addresses = await web3Wrapper.getAvailableAddressesAsync(); - return addresses[0]; -}; diff --git a/packages/instant/src/util/analytics.ts b/packages/instant/src/util/analytics.ts deleted file mode 100644 index fa8a72a2c..000000000 --- a/packages/instant/src/util/analytics.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { BuyQuote } from '@0x/asset-buyer'; -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; - -import { GIT_SHA, HEAP_ENABLED, INSTANT_DISCHARGE_TARGET, NODE_ENV, NPM_PACKAGE_VERSION } from '../constants'; -import { - AffiliateInfo, - Asset, - BaseCurrency, - Network, - OrderProcessState, - OrderSource, - ProviderState, - QuoteFetchOrigin, - WalletSuggestion, -} from '../types'; - -import { EventProperties, heapUtil } from './heap'; - -let isDisabledViaConfig = false; -export const disableAnalytics = (shouldDisableAnalytics: boolean) => { - isDisabledViaConfig = shouldDisableAnalytics; -}; -export const evaluateIfEnabled = (fnCall: () => void) => { - if (isDisabledViaConfig) { - return; - } - if (HEAP_ENABLED) { - fnCall(); - } -}; - -enum EventNames { - InstantOpened = 'Instant - Opened', - InstantClosed = 'Instant - Closed', - AccountLocked = 'Account - Locked', - AccountReady = 'Account - Ready', - AccountUnlockRequested = 'Account - Unlock Requested', - AccountUnlockDenied = 'Account - Unlock Denied', - AccountAddressChanged = 'Account - Address Changed', - BaseCurrencyChanged = 'Base Currency - Changed', - PaymentMethodDropdownOpened = 'Payment Method - Dropdown Opened', - PaymentMethodOpenedEtherscan = 'Payment Method - Opened Etherscan', - PaymentMethodCopiedAddress = 'Payment Method - Copied Address', - BuyNotEnoughEth = 'Buy - Not Enough Eth', - BuyStarted = 'Buy - Started', - BuySignatureDenied = 'Buy - Signature Denied', - BuySimulationFailed = 'Buy - Simulation Failed', - BuyUnknownError = 'Buy - Unknown Error', - BuyTxSubmitted = 'Buy - Tx Submitted', - BuyTxSucceeded = 'Buy - Tx Succeeded', - BuyTxFailed = 'Buy - Tx Failed', - UsdPriceFetchFailed = 'USD Price - Fetch Failed', - InstallWalletClicked = 'Install Wallet - Clicked', - InstallWalletModalOpened = 'Install Wallet - Modal - Opened', - InstallWalletModalClickedExplanation = 'Install Wallet - Modal - Clicked Explanation', - InstallWalletModalClickedGet = 'Install Wallet - Modal - Clicked Get', - InstallWalletModalClosed = 'Install Wallet - Modal - Closed', - TokenSelectorOpened = 'Token Selector - Opened', - TokenSelectorClosed = 'Token Selector - Closed', - TokenSelectorChose = 'Token Selector - Chose', - TokenSelectorSearched = 'Token Selector - Searched', - TransactionViewed = 'Transaction - Viewed', - QuoteFetched = 'Quote - Fetched', - QuoteError = 'Quote - Error', -} - -const track = (eventName: EventNames, eventProperties: EventProperties = {}): void => { - evaluateIfEnabled(() => { - heapUtil.evaluateHeapCall(heap => heap.track(eventName, eventProperties)); - }); -}; -function trackingEventFnWithoutPayload(eventName: EventNames): () => void { - return () => { - track(eventName); - }; -} -// tslint:disable-next-line:no-unused-variable -function trackingEventFnWithPayload(eventName: EventNames): (eventProperties: EventProperties) => void { - return (eventProperties: EventProperties) => { - track(eventName, eventProperties); - }; -} - -const buyQuoteEventProperties = (buyQuote: BuyQuote) => { - const assetBuyAmount = buyQuote.assetBuyAmount.toString(); - const assetEthAmount = buyQuote.worstCaseQuoteInfo.assetEthAmount.toString(); - const feeEthAmount = buyQuote.worstCaseQuoteInfo.feeEthAmount.toString(); - const totalEthAmount = buyQuote.worstCaseQuoteInfo.totalEthAmount.toString(); - const feePercentage = !_.isUndefined(buyQuote.feePercentage) ? buyQuote.feePercentage.toString() : 0; - const hasFeeOrders = !_.isEmpty(buyQuote.feeOrders) ? 'true' : 'false'; - return { - assetBuyAmount, - assetEthAmount, - feeEthAmount, - totalEthAmount, - feePercentage, - hasFeeOrders, - }; -}; - -export interface AnalyticsUserOptions { - lastKnownEthAddress?: string; - lastEthBalanceInUnitAmount?: string; -} -export interface AnalyticsEventOptions { - embeddedHost?: string; - embeddedUrl?: string; - ethBalanceInUnitAmount?: string; - ethAddress?: string; - networkId?: number; - providerName?: string; - providerDisplayName?: string; - gitSha?: string; - npmVersion?: string; - instantEnvironment?: string; - orderSource?: string; - affiliateAddress?: string; - affiliateFeePercent?: number; - numberAvailableAssets?: number; - selectedAssetName?: string; - selectedAssetSymbol?: string; - selectedAssetData?: string; - selectedAssetDecimals?: number; - baseCurrency?: string; -} -export enum TokenSelectorClosedVia { - ClickedX = 'Clicked X', // tslint:disable-line:enum-naming - TokenChose = 'Token Chose', -} -export const analytics = { - addUserProperties: (properties: AnalyticsUserOptions): void => { - evaluateIfEnabled(() => { - heapUtil.evaluateHeapCall(heap => heap.addUserProperties(properties)); - }); - }, - addEventProperties: (properties: AnalyticsEventOptions): void => { - evaluateIfEnabled(() => { - heapUtil.evaluateHeapCall(heap => heap.addEventProperties(properties)); - }); - }, - generateEventProperties: ( - network: Network, - orderSource: OrderSource, - providerState: ProviderState, - window: Window, - selectedAsset?: Asset, - affiliateInfo?: AffiliateInfo, - baseCurrency?: BaseCurrency, - ): AnalyticsEventOptions => { - const affiliateAddress = affiliateInfo ? affiliateInfo.feeRecipient : 'none'; - const affiliateFeePercent = affiliateInfo ? parseFloat(affiliateInfo.feePercentage.toFixed(4)) : 0; - const orderSourceName = typeof orderSource === 'string' ? orderSource : 'provided'; - const eventOptions: AnalyticsEventOptions = { - embeddedHost: window.location.host, - embeddedUrl: window.location.href, - networkId: network, - providerName: providerState.name, - providerDisplayName: providerState.displayName, - gitSha: GIT_SHA, - npmVersion: NPM_PACKAGE_VERSION, - orderSource: orderSourceName, - affiliateAddress, - affiliateFeePercent, - selectedAssetName: selectedAsset ? selectedAsset.metaData.name : 'none', - selectedAssetData: selectedAsset ? selectedAsset.assetData : 'none', - instantEnvironment: INSTANT_DISCHARGE_TARGET || `Local ${NODE_ENV}`, - baseCurrency, - }; - return eventOptions; - }, - trackInstantOpened: trackingEventFnWithoutPayload(EventNames.InstantOpened), - trackInstantClosed: trackingEventFnWithoutPayload(EventNames.InstantClosed), - trackAccountLocked: trackingEventFnWithoutPayload(EventNames.AccountLocked), - trackAccountReady: (address: string) => trackingEventFnWithPayload(EventNames.AccountReady)({ address }), - trackAccountUnlockRequested: trackingEventFnWithoutPayload(EventNames.AccountUnlockRequested), - trackAccountUnlockDenied: trackingEventFnWithoutPayload(EventNames.AccountUnlockDenied), - trackAccountAddressChanged: (address: string) => - trackingEventFnWithPayload(EventNames.AccountAddressChanged)({ address }), - trackBaseCurrencyChanged: (currencyChangedTo: BaseCurrency) => - trackingEventFnWithPayload(EventNames.BaseCurrencyChanged)({ currencyChangedTo }), - trackPaymentMethodDropdownOpened: trackingEventFnWithoutPayload(EventNames.PaymentMethodDropdownOpened), - trackPaymentMethodOpenedEtherscan: trackingEventFnWithoutPayload(EventNames.PaymentMethodOpenedEtherscan), - trackPaymentMethodCopiedAddress: trackingEventFnWithoutPayload(EventNames.PaymentMethodCopiedAddress), - trackBuyNotEnoughEth: (buyQuote: BuyQuote) => - trackingEventFnWithPayload(EventNames.BuyNotEnoughEth)(buyQuoteEventProperties(buyQuote)), - trackBuyStarted: (buyQuote: BuyQuote) => - trackingEventFnWithPayload(EventNames.BuyStarted)(buyQuoteEventProperties(buyQuote)), - trackBuySignatureDenied: (buyQuote: BuyQuote) => - trackingEventFnWithPayload(EventNames.BuySignatureDenied)(buyQuoteEventProperties(buyQuote)), - trackBuySimulationFailed: (buyQuote: BuyQuote) => - trackingEventFnWithPayload(EventNames.BuySimulationFailed)(buyQuoteEventProperties(buyQuote)), - trackBuyUnknownError: (buyQuote: BuyQuote, errorMessage: string) => - trackingEventFnWithPayload(EventNames.BuyUnknownError)({ - ...buyQuoteEventProperties(buyQuote), - errorMessage, - }), - trackBuyTxSubmitted: (buyQuote: BuyQuote, txHash: string, startTimeUnix: number, expectedEndTimeUnix: number) => - trackingEventFnWithPayload(EventNames.BuyTxSubmitted)({ - ...buyQuoteEventProperties(buyQuote), - txHash, - expectedTxTimeMs: expectedEndTimeUnix - startTimeUnix, - }), - trackBuyTxSucceeded: (buyQuote: BuyQuote, txHash: string, startTimeUnix: number, expectedEndTimeUnix: number) => - trackingEventFnWithPayload(EventNames.BuyTxSucceeded)({ - ...buyQuoteEventProperties(buyQuote), - txHash, - expectedTxTimeMs: expectedEndTimeUnix - startTimeUnix, - actualTxTimeMs: new Date().getTime() - startTimeUnix, - }), - trackBuyTxFailed: (buyQuote: BuyQuote, txHash: string, startTimeUnix: number, expectedEndTimeUnix: number) => - trackingEventFnWithPayload(EventNames.BuyTxFailed)({ - ...buyQuoteEventProperties(buyQuote), - txHash, - expectedTxTimeMs: expectedEndTimeUnix - startTimeUnix, - actualTxTimeMs: new Date().getTime() - startTimeUnix, - }), - trackInstallWalletClicked: (walletSuggestion: WalletSuggestion) => - trackingEventFnWithPayload(EventNames.InstallWalletClicked)({ walletSuggestion }), - trackInstallWalletModalClickedExplanation: trackingEventFnWithoutPayload( - EventNames.InstallWalletModalClickedExplanation, - ), - trackInstallWalletModalClickedGet: trackingEventFnWithoutPayload(EventNames.InstallWalletModalClickedGet), - trackInstallWalletModalOpened: trackingEventFnWithoutPayload(EventNames.InstallWalletModalOpened), - trackInstallWalletModalClosed: trackingEventFnWithoutPayload(EventNames.InstallWalletModalClosed), - trackTokenSelectorOpened: trackingEventFnWithoutPayload(EventNames.TokenSelectorOpened), - trackTokenSelectorClosed: (closedVia: TokenSelectorClosedVia) => - trackingEventFnWithPayload(EventNames.TokenSelectorClosed)({ closedVia }), - trackTokenSelectorChose: (payload: { assetName: string; assetData: string }) => - trackingEventFnWithPayload(EventNames.TokenSelectorChose)(payload), - trackTokenSelectorSearched: (searchText: string) => - trackingEventFnWithPayload(EventNames.TokenSelectorSearched)({ searchText }), - trackTransactionViewed: (orderProcesState: OrderProcessState) => - trackingEventFnWithPayload(EventNames.TransactionViewed)({ orderState: orderProcesState }), - trackQuoteFetched: (buyQuote: BuyQuote, fetchOrigin: QuoteFetchOrigin) => - trackingEventFnWithPayload(EventNames.QuoteFetched)({ - ...buyQuoteEventProperties(buyQuote), - fetchOrigin, - }), - trackQuoteError: (errorMessage: string, assetBuyAmount: BigNumber, fetchOrigin: QuoteFetchOrigin) => { - trackingEventFnWithPayload(EventNames.QuoteError)({ - errorMessage, - assetBuyAmount: assetBuyAmount.toString(), - fetchOrigin, - }); - }, - trackUsdPriceFailed: trackingEventFnWithoutPayload(EventNames.UsdPriceFetchFailed), -}; diff --git a/packages/instant/src/util/assert.ts b/packages/instant/src/util/assert.ts deleted file mode 100644 index 971c1eb96..000000000 --- a/packages/instant/src/util/assert.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { assert as sharedAssert } from '@0x/assert'; -import { schemas } from '@0x/json-schemas'; -import { assetDataUtils } from '@0x/order-utils'; -import { AssetProxyId, ObjectMap, SignedOrder } from '@0x/types'; -import * as _ from 'lodash'; - -import { AffiliateInfo, AssetMetaData } from '../types'; - -export const assert = { - ...sharedAssert, - isValidOrderSource(variableName: string, orderSource: string | SignedOrder[]): void { - if (_.isString(orderSource)) { - sharedAssert.isUri(variableName, orderSource); - return; - } - sharedAssert.doesConformToSchema(variableName, orderSource, schemas.signedOrdersSchema); - }, - areValidAssetDatas(variableName: string, assetDatas: string[]): void { - _.forEach(assetDatas, (assetData, index) => assert.isHexString(`${variableName}[${index}]`, assetData)); - }, - isValidAssetMetaDataMap(variableName: string, metaDataMap: ObjectMap<AssetMetaData>): void { - _.forEach(metaDataMap, (metaData, assetData) => { - assert.isHexString(`key ${assetData} of ${variableName}`, assetData); - assert.isValidAssetMetaData(`${variableName}.${assetData}`, metaData); - const assetDataProxyId = assetDataUtils.decodeAssetProxyId(assetData); - assert.assert( - metaData.assetProxyId === assetDataProxyId, - `Expected meta data for assetData ${assetData} to have asset proxy id of ${assetDataProxyId}, but instead got ${ - metaData.assetProxyId - }`, - ); - }); - }, - isValidAssetMetaData(variableName: string, metaData: AssetMetaData): void { - assert.isHexString(`${variableName}.assetProxyId`, metaData.assetProxyId); - if (!_.isUndefined(metaData.primaryColor)) { - assert.isString(`${variableName}.primaryColor`, metaData.primaryColor); - } - if (metaData.assetProxyId === AssetProxyId.ERC20) { - assert.isNumber(`${variableName}.decimals`, metaData.decimals); - assert.isString(`${variableName}.symbol`, metaData.symbol); - } else if (metaData.assetProxyId === AssetProxyId.ERC721) { - assert.isString(`${variableName}.name`, metaData.name); - assert.isUri(`${variableName}.imageUrl`, metaData.imageUrl); - } - }, - isValidAffiliateInfo(variableName: string, affiliateInfo: AffiliateInfo): void { - assert.isETHAddressHex(`${variableName}.recipientAddress`, affiliateInfo.feeRecipient); - assert.isNumber(`${variableName}.percentage`, affiliateInfo.feePercentage); - assert.assert( - affiliateInfo.feePercentage >= 0 && affiliateInfo.feePercentage <= 0.05, - `Expected ${variableName}.percentage to be between 0 and 0.05, but is ${affiliateInfo.feePercentage}`, - ); - }, -}; diff --git a/packages/instant/src/util/asset.ts b/packages/instant/src/util/asset.ts deleted file mode 100644 index b5c97913d..000000000 --- a/packages/instant/src/util/asset.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { AssetBuyerError, InsufficientAssetLiquidityError } from '@0x/asset-buyer'; -import { AssetProxyId, ObjectMap } from '@0x/types'; -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -import { BIG_NUMBER_ZERO, DEFAULT_UNKOWN_ASSET_NAME } from '../constants'; -import { assetDataNetworkMapping } from '../data/asset_data_network_mapping'; -import { Asset, AssetMetaData, ERC20Asset, Network, ZeroExInstantError } from '../types'; - -export const assetUtils = { - createAssetsFromAssetDatas: ( - assetDatas: string[], - assetMetaDataMap: ObjectMap<AssetMetaData>, - network: Network, - ): Asset[] => { - const arrayOfAssetOrUndefined = _.map(assetDatas, assetData => - assetUtils.createAssetFromAssetDataIfExists(assetData, assetMetaDataMap, network), - ); - return _.compact(arrayOfAssetOrUndefined); - }, - createAssetFromAssetDataIfExists: ( - assetData: string, - assetMetaDataMap: ObjectMap<AssetMetaData>, - network: Network, - ): Asset | undefined => { - const metaData = assetUtils.getMetaDataIfExists(assetData, assetMetaDataMap, network); - if (_.isUndefined(metaData)) { - return; - } - return { - assetData: assetData.toLowerCase(), - metaData, - }; - }, - createAssetFromAssetDataOrThrow: ( - assetData: string, - assetMetaDataMap: ObjectMap<AssetMetaData>, - network: Network, - ): Asset => { - return { - assetData: assetData.toLowerCase(), - metaData: assetUtils.getMetaDataOrThrow(assetData, assetMetaDataMap, network), - }; - }, - getMetaDataOrThrow: (assetData: string, metaDataMap: ObjectMap<AssetMetaData>, network: Network): AssetMetaData => { - const metaDataIfExists = assetUtils.getMetaDataIfExists(assetData, metaDataMap, network); - if (_.isUndefined(metaDataIfExists)) { - throw new Error(ZeroExInstantError.AssetMetaDataNotAvailable); - } - return metaDataIfExists; - }, - getMetaDataIfExists: ( - assetData: string, - metaDataMap: ObjectMap<AssetMetaData>, - network: Network, - ): AssetMetaData | undefined => { - let mainnetAssetData: string | undefined = assetData; - if (network !== Network.Mainnet) { - const mainnetAssetDataIfExists = assetUtils.getAssociatedAssetDataIfExists( - assetData.toLowerCase(), - network, - ); - // Just so we don't fail in the case where we are on a non-mainnet network, - // but pass in a valid mainnet assetData. - mainnetAssetData = mainnetAssetDataIfExists || assetData; - } - if (_.isUndefined(mainnetAssetData)) { - return; - } - const metaData = metaDataMap[mainnetAssetData.toLowerCase()]; - if (_.isUndefined(metaData)) { - return; - } - return metaData; - }, - bestNameForAsset: (asset?: Asset, defaultName: string = DEFAULT_UNKOWN_ASSET_NAME): string => { - if (_.isUndefined(asset)) { - return defaultName; - } - const metaData = asset.metaData; - switch (metaData.assetProxyId) { - case AssetProxyId.ERC20: - return metaData.symbol.toUpperCase(); - case AssetProxyId.ERC721: - return metaData.name; - } - }, - formattedSymbolForAsset: (asset?: ERC20Asset, defaultName: string = '???'): string => { - if (_.isUndefined(asset)) { - return defaultName; - } - const symbol = asset.metaData.symbol; - if (symbol.length <= 5) { - return symbol; - } - return `${symbol.slice(0, 3)}…`; - }, - getAssociatedAssetDataIfExists: (assetData: string, network: Network): string | undefined => { - const assetDataGroupIfExists = _.find(assetDataNetworkMapping, value => value[network] === assetData); - if (_.isUndefined(assetDataGroupIfExists)) { - return; - } - return assetDataGroupIfExists[Network.Mainnet]; - }, - getERC20AssetsFromAssets: (assets: Asset[]): ERC20Asset[] => { - const erc20sOrUndefined = _.map(assets, asset => - asset.metaData.assetProxyId === AssetProxyId.ERC20 ? (asset as ERC20Asset) : undefined, - ); - return _.compact(erc20sOrUndefined); - }, - assetBuyerErrorMessage: (asset: ERC20Asset, error: Error): string | undefined => { - if (error.message === AssetBuyerError.InsufficientAssetLiquidity) { - const assetName = assetUtils.bestNameForAsset(asset, 'of this asset'); - if ( - error instanceof InsufficientAssetLiquidityError && - error.amountAvailableToFill.isGreaterThan(BIG_NUMBER_ZERO) - ) { - const unitAmountAvailableToFill = Web3Wrapper.toUnitAmount( - error.amountAvailableToFill, - asset.metaData.decimals, - ); - const roundedUnitAmountAvailableToFill = unitAmountAvailableToFill.decimalPlaces( - 2, - BigNumber.ROUND_DOWN, - ); - - if (roundedUnitAmountAvailableToFill.isGreaterThan(BIG_NUMBER_ZERO)) { - return `There are only ${roundedUnitAmountAvailableToFill} ${assetName} available to buy`; - } - } - - return `Not enough ${assetName} available`; - } else if (error.message === AssetBuyerError.InsufficientZrxLiquidity) { - return 'Not enough ZRX available'; - } else if ( - error.message === AssetBuyerError.StandardRelayerApiError || - error.message.startsWith(AssetBuyerError.AssetUnavailable) - ) { - const assetName = assetUtils.bestNameForAsset(asset, 'This asset'); - return `${assetName} is currently unavailable`; - } - - return undefined; - }, -}; diff --git a/packages/instant/src/util/asset_buyer_factory.ts b/packages/instant/src/util/asset_buyer_factory.ts deleted file mode 100644 index 5ba46223c..000000000 --- a/packages/instant/src/util/asset_buyer_factory.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { AssetBuyer, AssetBuyerOpts } from '@0x/asset-buyer'; -import { Provider } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { Network, OrderSource } from '../types'; - -export const assetBuyerFactory = { - getAssetBuyer: (provider: Provider, orderSource: OrderSource, network: Network): AssetBuyer => { - const assetBuyerOptions: Partial<AssetBuyerOpts> = { - networkId: network, - }; - const assetBuyer = _.isString(orderSource) - ? AssetBuyer.getAssetBuyerForStandardRelayerAPIUrl(provider, orderSource, assetBuyerOptions) - : AssetBuyer.getAssetBuyerForProvidedOrders(provider, orderSource, assetBuyerOptions); - return assetBuyer; - }, -}; diff --git a/packages/instant/src/util/buy_quote_updater.ts b/packages/instant/src/util/buy_quote_updater.ts deleted file mode 100644 index 37974e71c..000000000 --- a/packages/instant/src/util/buy_quote_updater.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { AssetBuyer, BuyQuote } from '@0x/asset-buyer'; -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 { SLIPPAGE_PERCENTAGE } from '../constants'; -import { Action, actions } from '../redux/actions'; -import { AffiliateInfo, ERC20Asset, QuoteFetchOrigin } from '../types'; -import { analytics } from '../util/analytics'; -import { assetUtils } from '../util/asset'; -import { errorFlasher } from '../util/error_flasher'; -import { errorReporter } from '../util/error_reporter'; - -export const buyQuoteUpdater = { - updateBuyQuoteAsync: async ( - assetBuyer: AssetBuyer, - dispatch: Dispatch<Action>, - asset: ERC20Asset, - assetUnitAmount: BigNumber, - fetchOrigin: QuoteFetchOrigin, - options: { - setPending: boolean; - dispatchErrors: boolean; - affiliateInfo?: AffiliateInfo; - }, - ): Promise<void> => { - // get a new buy quote. - const baseUnitValue = Web3Wrapper.toBaseUnitAmount(assetUnitAmount, asset.metaData.decimals); - if (options.setPending) { - // mark quote as pending - dispatch(actions.setQuoteRequestStatePending()); - } - const feePercentage = oc(options.affiliateInfo).feePercentage(); - let newBuyQuote: BuyQuote | undefined; - const slippagePercentage = SLIPPAGE_PERCENTAGE; - try { - newBuyQuote = await assetBuyer.getBuyQuoteAsync(asset.assetData, baseUnitValue, { - feePercentage, - slippagePercentage, - }); - } catch (error) { - const errorMessage = assetUtils.assetBuyerErrorMessage(asset, error); - - errorReporter.report(error); - analytics.trackQuoteError(error.message ? error.message : 'other', baseUnitValue, fetchOrigin); - - if (options.dispatchErrors) { - dispatch(actions.setQuoteRequestStateFailure()); - errorFlasher.flashNewErrorMessage(dispatch, errorMessage || 'Error fetching price, please try again'); - } - return; - } - // We have a successful new buy quote - errorFlasher.clearError(dispatch); - // invalidate the last buy quote. - dispatch(actions.updateLatestBuyQuote(newBuyQuote)); - analytics.trackQuoteFetched(newBuyQuote, fetchOrigin); - }, -}; diff --git a/packages/instant/src/util/coinbase_api.ts b/packages/instant/src/util/coinbase_api.ts deleted file mode 100644 index faac8d82d..000000000 --- a/packages/instant/src/util/coinbase_api.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { BigNumber, fetchAsync } from '@0x/utils'; - -import { COINBASE_API_BASE_URL } from '../constants'; - -export const coinbaseApi = { - getEthUsdPrice: async (): Promise<BigNumber> => { - const res = await fetchAsync(`${COINBASE_API_BASE_URL}/prices/ETH-USD/buy`); - const resJson = await res.json(); - return new BigNumber(resJson.data.amount); - }, -}; diff --git a/packages/instant/src/util/env.ts b/packages/instant/src/util/env.ts deleted file mode 100644 index 7d4f836ff..000000000 --- a/packages/instant/src/util/env.ts +++ /dev/null @@ -1,77 +0,0 @@ -import * as bowser from 'bowser'; -import { Provider } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { PROVIDER_TYPE_TO_NAME } from '../constants'; -import { Browser, OperatingSystem, ProviderType } from '../types'; - -export const envUtil = { - getBrowser(): Browser { - if (bowser.chrome) { - return Browser.Chrome; - } else if (bowser.firefox) { - return Browser.Firefox; - } else if (bowser.opera) { - return Browser.Opera; - } else if (bowser.msedge) { - return Browser.Edge; - } else if (bowser.safari) { - return Browser.Safari; - } else { - return Browser.Other; - } - }, - isMobileOperatingSystem(): boolean { - return bowser.mobile; - }, - getOperatingSystem(): OperatingSystem { - if (bowser.android) { - return OperatingSystem.Android; - } else if (bowser.ios) { - return OperatingSystem.iOS; - } else if (bowser.mac) { - return OperatingSystem.Mac; - } else if (bowser.windows) { - return OperatingSystem.Windows; - } else if (bowser.windowsphone) { - return OperatingSystem.WindowsPhone; - } else if (bowser.linux) { - return OperatingSystem.Linux; - } else { - return OperatingSystem.Other; - } - }, - getProviderType(provider: Provider): ProviderType | undefined { - const anyProvider = provider as any; - if (provider.constructor.name === 'EthereumProvider') { - return ProviderType.Mist; - } else if (anyProvider.isTrust) { - return ProviderType.TrustWallet; - } else if (anyProvider.isParity) { - return ProviderType.Parity; - } else if (anyProvider.isMetaMask) { - return ProviderType.MetaMask; - } else if (!_.isUndefined(_.get(window, 'SOFA'))) { - return ProviderType.CoinbaseWallet; - } else if (!_.isUndefined(_.get(window, '__CIPHER__'))) { - return ProviderType.Cipher; - } else if (envUtil.getBrowser() === Browser.Opera && !anyProvider.isMetaMask) { - return ProviderType.Opera; - } - return; - }, - getProviderName(provider: Provider): string { - const providerTypeIfExists = envUtil.getProviderType(provider); - if (_.isUndefined(providerTypeIfExists)) { - return provider.constructor.name; - } - return PROVIDER_TYPE_TO_NAME[providerTypeIfExists]; - }, - getProviderDisplayName(provider: Provider): string { - const providerTypeIfExists = envUtil.getProviderType(provider); - if (_.isUndefined(providerTypeIfExists)) { - return 'Wallet'; - } - return PROVIDER_TYPE_TO_NAME[providerTypeIfExists]; - }, -}; diff --git a/packages/instant/src/util/error_flasher.ts b/packages/instant/src/util/error_flasher.ts deleted file mode 100644 index 068c12fe2..000000000 --- a/packages/instant/src/util/error_flasher.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Dispatch } from 'redux'; - -import { Action, actions } from '../redux/actions'; - -class ErrorFlasher { - private _timeoutId?: number; - public flashNewErrorMessage(dispatch: Dispatch<Action>, errorMessage?: string, delayMs: number = 7000): void { - this._clearTimeout(); - // dispatch new message - dispatch(actions.setErrorMessage(errorMessage || 'Something went wrong...')); - this._timeoutId = window.setTimeout(() => { - dispatch(actions.hideError()); - }, delayMs); - } - public clearError(dispatch: Dispatch<Action>): void { - this._clearTimeout(); - dispatch(actions.hideError()); - } - private _clearTimeout(): void { - if (this._timeoutId) { - window.clearTimeout(this._timeoutId); - } - } -} - -export const errorFlasher = new ErrorFlasher(); diff --git a/packages/instant/src/util/error_reporter.ts b/packages/instant/src/util/error_reporter.ts deleted file mode 100644 index 8d7481684..000000000 --- a/packages/instant/src/util/error_reporter.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { logUtils } from '@0x/utils'; -import * as _ from 'lodash'; - -import { - GIT_SHA, - HOST_DOMAINS_EXTERNAL, - HOST_DOMAINS_LOCAL, - INSTANT_DISCHARGE_TARGET, - NODE_ENV, - ROLLBAR_CLIENT_TOKEN, - ROLLBAR_ENABLED, -} from '../constants'; - -// Import version of Rollbar designed for embedded components -// See https://docs.rollbar.com/docs/using-rollbarjs-inside-an-embedded-component -// tslint:disable-next-line:no-var-requires -const Rollbar = require('rollbar/dist/rollbar.noconflict.umd'); - -const getRollbarHostDomains = (): string[] => { - if (NODE_ENV === 'development') { - return HOST_DOMAINS_EXTERNAL.concat(HOST_DOMAINS_LOCAL); - } else { - return HOST_DOMAINS_EXTERNAL; - } -}; - -let rollbar: any; -// Configures rollbar and sets up error catching -export const setupRollbar = (): any => { - if (_.isUndefined(rollbar) && ROLLBAR_CLIENT_TOKEN && ROLLBAR_ENABLED) { - const hostDomains = getRollbarHostDomains(); - rollbar = new Rollbar({ - accessToken: ROLLBAR_CLIENT_TOKEN, - captureUncaught: true, - captureUnhandledRejections: true, - enabled: true, - itemsPerMinute: 10, - maxItems: 500, - payload: { - environment: INSTANT_DISCHARGE_TARGET || `Local ${NODE_ENV}`, - client: { - javascript: { - source_map_enabled: true, - code_version: GIT_SHA, - guess_uncaught_frames: true, - }, - }, - }, - hostWhiteList: hostDomains, - uncaughtErrorLevel: 'error', - ignoredMessages: [ - // Errors from the third-party scripts - 'Script error', - // Network errors or ad-blockers - 'TypeError: Failed to fetch', - 'Exchange has not been deployed to detected network (network/artifact mismatch)', - // Source: https://groups.google.com/a/chromium.org/forum/#!topic/chromium-discuss/7VU0_VvC7mE - "undefined is not an object (evaluating '__gCrWeb.autofill.extractForms')", - // Source: http://stackoverflow.com/questions/43399818/securityerror-from-facebook-and-cross-domain-messaging - 'SecurityError (DOM Exception 18)', - ], - }); - } -}; - -export const errorReporter = { - report(err: Error): void { - if (!rollbar) { - logUtils.log('Not reporting to rollbar because not configured', err); - return; - } - - rollbar.error(err, (rollbarErr: Error) => { - if (rollbarErr) { - logUtils.log(`Error reporting to rollbar, ignoring: ${rollbarErr}`); - } - }); - }, -}; diff --git a/packages/instant/src/util/etherscan.ts b/packages/instant/src/util/etherscan.ts deleted file mode 100644 index f9bf82827..000000000 --- a/packages/instant/src/util/etherscan.ts +++ /dev/null @@ -1,30 +0,0 @@ -import * as _ from 'lodash'; - -import { Network } from '../types'; - -const etherscanPrefix = (networkId: number): string | undefined => { - switch (networkId) { - case Network.Kovan: - return 'kovan.'; - case Network.Mainnet: - return ''; - } - return ''; -}; - -export const etherscanUtil = { - getEtherScanTxnAddressIfExists: (txHash: string, networkId: number) => { - const prefix = etherscanPrefix(networkId); - if (_.isUndefined(prefix)) { - return; - } - return `https://${prefix}etherscan.io/tx/${txHash}`; - }, - getEtherScanEthAddressIfExists: (ethAddress: string, networkId: number) => { - const prefix = etherscanPrefix(networkId); - if (_.isUndefined(prefix)) { - return; - } - return `https://${prefix}etherscan.io/address/${ethAddress}`; - }, -}; diff --git a/packages/instant/src/util/format.ts b/packages/instant/src/util/format.ts deleted file mode 100644 index 61aeb839f..000000000 --- a/packages/instant/src/util/format.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import { Web3Wrapper } from '@0x/web3-wrapper'; -import * as _ from 'lodash'; - -import { BIG_NUMBER_ZERO, ETH_DECIMALS } from '../constants'; - -export const format = { - ethBaseUnitAmount: ( - ethBaseUnitAmount?: BigNumber, - decimalPlaces: number = 4, - defaultText: React.ReactNode = '0 ETH', - ): React.ReactNode => { - if (_.isUndefined(ethBaseUnitAmount)) { - return defaultText; - } - const ethUnitAmount = Web3Wrapper.toUnitAmount(ethBaseUnitAmount, ETH_DECIMALS); - return format.ethUnitAmount(ethUnitAmount, decimalPlaces); - }, - ethUnitAmount: ( - ethUnitAmount?: BigNumber, - decimalPlaces: number = 4, - defaultText: React.ReactNode = '0 ETH', - minUnitAmountToDisplay: BigNumber = new BigNumber('0.00001'), - ): React.ReactNode => { - if (_.isUndefined(ethUnitAmount)) { - return defaultText; - } - let roundedAmount = ethUnitAmount.decimalPlaces(decimalPlaces).precision(decimalPlaces); - - if (roundedAmount.eq(BIG_NUMBER_ZERO) && ethUnitAmount.isGreaterThan(BIG_NUMBER_ZERO)) { - // Sometimes for small ETH amounts (i.e. 0.000045) the amount rounded to 4 decimalPlaces is 0 - // If that is the case, show to 1 significant digit - roundedAmount = new BigNumber(ethUnitAmount.toPrecision(1)); - } - - const displayAmount = - roundedAmount.isGreaterThan(BIG_NUMBER_ZERO) && roundedAmount.isLessThan(minUnitAmountToDisplay) - ? `< ${minUnitAmountToDisplay.toString()}` - : roundedAmount.toString(); - - return `${displayAmount} ETH`; - }, - ethBaseUnitAmountInUsd: ( - ethBaseUnitAmount?: BigNumber, - ethUsdPrice?: BigNumber, - decimalPlaces: number = 2, - defaultText: React.ReactNode = '$0.00', - minUnitAmountToDisplay: BigNumber = new BigNumber('0.00001'), - ): React.ReactNode => { - if (_.isUndefined(ethBaseUnitAmount) || _.isUndefined(ethUsdPrice)) { - return defaultText; - } - const ethUnitAmount = Web3Wrapper.toUnitAmount(ethBaseUnitAmount, ETH_DECIMALS); - return format.ethUnitAmountInUsd(ethUnitAmount, ethUsdPrice, decimalPlaces, minUnitAmountToDisplay); - }, - ethUnitAmountInUsd: ( - ethUnitAmount?: BigNumber, - ethUsdPrice?: BigNumber, - decimalPlaces: number = 2, - defaultText: React.ReactNode = '$0.00', - ): React.ReactNode => { - if (_.isUndefined(ethUnitAmount) || _.isUndefined(ethUsdPrice)) { - return defaultText; - } - const rawUsdPrice = ethUnitAmount.multipliedBy(ethUsdPrice); - const roundedUsdPrice = rawUsdPrice.toFixed(decimalPlaces); - if (roundedUsdPrice === '0.00' && rawUsdPrice.gt(BIG_NUMBER_ZERO)) { - return '<$0.01'; - } else { - return `$${roundedUsdPrice}`; - } - }, - ethAddress: (address: string): string => { - return `0x${address.slice(2, 7)}…${address.slice(-5)}`; - }, -}; diff --git a/packages/instant/src/util/gas_price_estimator.ts b/packages/instant/src/util/gas_price_estimator.ts deleted file mode 100644 index 9792b60ba..000000000 --- a/packages/instant/src/util/gas_price_estimator.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { BigNumber, fetchAsync } from '@0x/utils'; - -import { - DEFAULT_ESTIMATED_TRANSACTION_TIME_MS, - DEFAULT_GAS_PRICE, - ETH_GAS_STATION_API_BASE_URL, - GWEI_IN_WEI, -} from '../constants'; - -import { errorReporter } from './error_reporter'; - -interface EthGasStationResult { - average: number; - fastestWait: number; - fastWait: number; - fast: number; - safeLowWait: number; - blockNum: number; - avgWait: number; - block_time: number; - speed: number; - fastest: number; - safeLow: number; -} - -interface GasInfo { - gasPriceInWei: BigNumber; - estimatedTimeMs: number; -} - -const fetchFastAmountInWeiAsync = async (): Promise<GasInfo> => { - const res = await fetchAsync(`${ETH_GAS_STATION_API_BASE_URL}/json/ethgasAPI.json`); - const gasInfo = (await res.json()) as EthGasStationResult; - // Eth Gas Station result is gwei * 10 - const gasPriceInGwei = new BigNumber(gasInfo.fast / 10); - // Time is in minutes - const estimatedTimeMs = gasInfo.fastWait * 60 * 1000; // Minutes to MS - return { gasPriceInWei: gasPriceInGwei.multipliedBy(GWEI_IN_WEI), estimatedTimeMs }; -}; - -export class GasPriceEstimator { - private _lastFetched?: GasInfo; - public async getGasInfoAsync(): Promise<GasInfo> { - let fetchedAmount: GasInfo | undefined; - try { - fetchedAmount = await fetchFastAmountInWeiAsync(); - } catch (e) { - fetchedAmount = undefined; - errorReporter.report(e); - } - - if (fetchedAmount) { - this._lastFetched = fetchedAmount; - } - - return ( - fetchedAmount || - this._lastFetched || { - gasPriceInWei: DEFAULT_GAS_PRICE, - estimatedTimeMs: DEFAULT_ESTIMATED_TRANSACTION_TIME_MS, - } - ); - } -} -export const gasPriceEstimator = new GasPriceEstimator(); diff --git a/packages/instant/src/util/heap.ts b/packages/instant/src/util/heap.ts deleted file mode 100644 index 279ff3059..000000000 --- a/packages/instant/src/util/heap.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { ObjectMap } from '@0x/types'; -import { logUtils } from '@0x/utils'; -import * as _ from 'lodash'; - -import { HEAP_ANALYTICS_ID } from '../constants'; - -import { AnalyticsEventOptions, AnalyticsUserOptions } from './analytics'; -import { errorReporter } from './error_reporter'; - -export type EventProperties = ObjectMap<string | number>; - -export interface HeapAnalytics { - loaded: boolean; - appid: string; - identify(id: string, idType: string): void; - track(eventName: string, eventProperties?: EventProperties): void; - resetIdentity(): void; - addUserProperties(properties: AnalyticsUserOptions): void; - addEventProperties(properties: AnalyticsEventOptions): void; - removeEventProperty(property: string): void; - clearEventProperties(): void; -} -interface ModifiedWindow { - heap?: HeapAnalytics; - zeroExInstantLoadedHeap?: boolean; -} -const getWindow = (): ModifiedWindow => { - return window as ModifiedWindow; -}; - -const setupZeroExInstantHeap = () => { - if (_.isUndefined(HEAP_ANALYTICS_ID)) { - return; - } - - const curWindow = getWindow(); - // Set property to specify that this is zeroEx's heap - curWindow.zeroExInstantLoadedHeap = true; - - // Typescript-compatible version of https://docs.heapanalytics.com/docs/installation - /* tslint:disable */ - ((window as any).heap = (window as any).heap || []), - ((window as any).heap.load = function(e: any, t: any) { - ((window as any).heap.appid = e), ((window as any).heap.config = t = t || {}); - var r = t.forceSSL || 'https:' === (document.location as Location).protocol, - a = document.createElement('script'); - (a.type = 'text/javascript'), - (a.async = !0), - (a.src = (r ? 'https:' : 'http:') + '//cdn.heapanalytics.com/js/heap-' + e + '.js'); - var n = document.getElementsByTagName('script')[0]; - (n.parentNode as Node).insertBefore(a, n); - for ( - var o = function(e: any) { - return function() { - (window as any).heap.push([e].concat(Array.prototype.slice.call(arguments, 0))); - }; - }, - p = [ - 'addEventProperties', - 'addUserProperties', - 'clearEventProperties', - 'identify', - 'resetIdentity', - 'removeEventProperty', - 'setEventProperties', - 'track', - 'unsetEventProperty', - ], - c = 0; - c < p.length; - c++ - ) - (window as any).heap[p[c]] = o(p[c]); - }); - (window as any).heap.load(HEAP_ANALYTICS_ID); - /* tslint:enable */ - - return curWindow.heap as HeapAnalytics; -}; - -export const heapUtil = { - getHeap: (): HeapAnalytics | undefined => { - const curWindow = getWindow(); - const hasOtherExistingHeapIntegration = curWindow.heap && !curWindow.zeroExInstantLoadedHeap; - if (hasOtherExistingHeapIntegration) { - return undefined; - } - - const zeroExInstantHeapIntegration = curWindow.zeroExInstantLoadedHeap && curWindow.heap; - if (zeroExInstantHeapIntegration) { - return zeroExInstantHeapIntegration; - } - - return setupZeroExInstantHeap(); - }, - evaluateHeapCall: (heapFunctionCall: (heap: HeapAnalytics) => void): void => { - if (_.isUndefined(HEAP_ANALYTICS_ID)) { - return; - } - - const curHeap = heapUtil.getHeap(); - if (curHeap) { - try { - if (curHeap.appid !== HEAP_ANALYTICS_ID) { - // Integrator has included heap after us and reset the app id - return; - } - heapFunctionCall(curHeap); - } catch (e) { - // We never want analytics to crash our React component - logUtils.log('Analytics error', e); - errorReporter.report(e); - } - } - }, -}; diff --git a/packages/instant/src/util/heartbeater.ts b/packages/instant/src/util/heartbeater.ts deleted file mode 100644 index e700d489e..000000000 --- a/packages/instant/src/util/heartbeater.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { intervalUtils } from '@0x/utils'; -import * as _ from 'lodash'; - -type HeartbeatableFunction = () => Promise<void>; -export class Heartbeater { - private _intervalId?: NodeJS.Timer; - private readonly _performImmediatelyOnStart: boolean; - private readonly _performFunction: HeartbeatableFunction; - - public constructor(performingFunctionAsync: HeartbeatableFunction, performImmediatelyOnStart: boolean) { - this._performFunction = performingFunctionAsync; - this._performImmediatelyOnStart = performImmediatelyOnStart; - } - - public start(intervalTimeMs: number): void { - if (!_.isUndefined(this._intervalId)) { - throw new Error('Heartbeat is running, please stop before restarting'); - } - - if (this._performImmediatelyOnStart) { - // tslint:disable-next-line:no-floating-promises - this._performFunction(); - } - - // tslint:disable-next-line:no-unbound-method - this._intervalId = intervalUtils.setAsyncExcludingInterval(this._performFunction, intervalTimeMs, _.noop); - } - - public stop(): void { - if (this._intervalId) { - intervalUtils.clearInterval(this._intervalId); - } - this._intervalId = undefined; - } -} diff --git a/packages/instant/src/util/heartbeater_factory.ts b/packages/instant/src/util/heartbeater_factory.ts deleted file mode 100644 index cf29bf3ea..000000000 --- a/packages/instant/src/util/heartbeater_factory.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { asyncData } from '../redux/async_data'; -import { Store } from '../redux/store'; -import { QuoteFetchOrigin } from '../types'; - -import { Heartbeater } from './heartbeater'; - -export interface HeartbeatFactoryOptions { - store: Store; - shouldPerformImmediatelyOnStart: boolean; -} -export const generateAccountHeartbeater = (options: HeartbeatFactoryOptions): Heartbeater => { - const { store, shouldPerformImmediatelyOnStart } = options; - return new Heartbeater(async () => { - await asyncData.fetchAccountInfoAndDispatchToStore(store.getState().providerState, store.dispatch, false); - }, shouldPerformImmediatelyOnStart); -}; - -export const generateBuyQuoteHeartbeater = (options: HeartbeatFactoryOptions): Heartbeater => { - const { store, shouldPerformImmediatelyOnStart } = options; - return new Heartbeater(async () => { - await asyncData.fetchCurrentBuyQuoteAndDispatchToStore( - store.getState(), - store.dispatch, - QuoteFetchOrigin.Heartbeat, - { - updateSilently: true, - }, - ); - }, shouldPerformImmediatelyOnStart); -}; diff --git a/packages/instant/src/util/maybe_big_number.ts b/packages/instant/src/util/maybe_big_number.ts deleted file mode 100644 index f48473389..000000000 --- a/packages/instant/src/util/maybe_big_number.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { BigNumber } from '@0x/utils'; -import * as _ from 'lodash'; - -import { Maybe } from '../types'; - -export const maybeBigNumberUtil = { - // converts a string to a Maybe<BigNumber> - // if string is a NaN, considered undefined - stringToMaybeBigNumber: (stringValue: string): Maybe<BigNumber> => { - let validBigNumber: BigNumber; - try { - validBigNumber = new BigNumber(stringValue); - } catch { - return undefined; - } - - return validBigNumber.isNaN() ? undefined : validBigNumber; - }, - areMaybeBigNumbersEqual: (val1: Maybe<BigNumber>, val2: Maybe<BigNumber>): boolean => { - if (!_.isUndefined(val1) && !_.isUndefined(val2)) { - return val1.isEqualTo(val2); - } - return _.isUndefined(val1) && _.isUndefined(val2); - }, -}; diff --git a/packages/instant/src/util/provider_factory.ts b/packages/instant/src/util/provider_factory.ts deleted file mode 100644 index 603f7674d..000000000 --- a/packages/instant/src/util/provider_factory.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { EmptyWalletSubprovider, RPCSubprovider, Web3ProviderEngine } from '@0x/subproviders'; -import { Provider } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { BLOCK_POLLING_INTERVAL_MS, ETHEREUM_NODE_URL_BY_NETWORK } from '../constants'; -import { Maybe, Network } from '../types'; - -export const providerFactory = { - getInjectedProviderIfExists: (): Maybe<Provider> => { - const injectedProviderIfExists = (window as any).ethereum; - if (!_.isUndefined(injectedProviderIfExists)) { - return injectedProviderIfExists; - } - const injectedWeb3IfExists = (window as any).web3; - if (!_.isUndefined(injectedWeb3IfExists) && !_.isUndefined(injectedWeb3IfExists.currentProvider)) { - return injectedWeb3IfExists.currentProvider; - } - return undefined; - }, - getFallbackNoSigningProvider: (network: Network): Provider => { - const providerEngine = new Web3ProviderEngine({ - pollingInterval: BLOCK_POLLING_INTERVAL_MS, - }); - // Intercept calls to `eth_accounts` and always return empty - providerEngine.addProvider(new EmptyWalletSubprovider()); - // Construct an RPC subprovider, all data based requests will be sent via the RPCSubprovider - // TODO(bmillman): make this more resilient to infura failures - const rpcUrl = ETHEREUM_NODE_URL_BY_NETWORK[network]; - providerEngine.addProvider(new RPCSubprovider(rpcUrl)); - // // Start the Provider Engine - providerEngine.start(); - return providerEngine; - }, -}; diff --git a/packages/instant/src/util/provider_state_factory.ts b/packages/instant/src/util/provider_state_factory.ts deleted file mode 100644 index bd2d6dad5..000000000 --- a/packages/instant/src/util/provider_state_factory.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { Provider } from 'ethereum-types'; -import * as _ from 'lodash'; - -import { LOADING_ACCOUNT, NO_ACCOUNT } from '../constants'; -import { Maybe, Network, OrderSource, ProviderState } from '../types'; -import { envUtil } from '../util/env'; - -import { assetBuyerFactory } from './asset_buyer_factory'; -import { providerFactory } from './provider_factory'; - -export const providerStateFactory = { - getInitialProviderState: ( - orderSource: OrderSource, - network: Network, - provider?: Provider, - walletDisplayName?: string, - ): ProviderState => { - if (!_.isUndefined(provider)) { - return providerStateFactory.getInitialProviderStateFromProvider( - orderSource, - network, - provider, - walletDisplayName, - ); - } - const providerStateFromWindowIfExits = providerStateFactory.getInitialProviderStateFromWindowIfExists( - orderSource, - network, - walletDisplayName, - ); - if (providerStateFromWindowIfExits) { - return providerStateFromWindowIfExits; - } else { - return providerStateFactory.getInitialProviderStateFallback(orderSource, network, walletDisplayName); - } - }, - getInitialProviderStateFromProvider: ( - orderSource: OrderSource, - network: Network, - provider: Provider, - walletDisplayName?: string, - ): ProviderState => { - const providerState: ProviderState = { - name: envUtil.getProviderName(provider), - displayName: walletDisplayName || envUtil.getProviderDisplayName(provider), - provider, - web3Wrapper: new Web3Wrapper(provider), - assetBuyer: assetBuyerFactory.getAssetBuyer(provider, orderSource, network), - account: LOADING_ACCOUNT, - }; - return providerState; - }, - getInitialProviderStateFromWindowIfExists: ( - orderSource: OrderSource, - network: Network, - walletDisplayName?: string, - ): Maybe<ProviderState> => { - const injectedProviderIfExists = providerFactory.getInjectedProviderIfExists(); - if (!_.isUndefined(injectedProviderIfExists)) { - const providerState: ProviderState = { - name: envUtil.getProviderName(injectedProviderIfExists), - displayName: walletDisplayName || envUtil.getProviderDisplayName(injectedProviderIfExists), - provider: injectedProviderIfExists, - web3Wrapper: new Web3Wrapper(injectedProviderIfExists), - assetBuyer: assetBuyerFactory.getAssetBuyer(injectedProviderIfExists, orderSource, network), - account: LOADING_ACCOUNT, - }; - return providerState; - } else { - return undefined; - } - }, - getInitialProviderStateFallback: ( - orderSource: OrderSource, - network: Network, - walletDisplayName?: string, - ): ProviderState => { - const provider = providerFactory.getFallbackNoSigningProvider(network); - const providerState: ProviderState = { - name: 'Fallback', - displayName: walletDisplayName || envUtil.getProviderDisplayName(provider), - provider, - web3Wrapper: new Web3Wrapper(provider), - assetBuyer: assetBuyerFactory.getAssetBuyer(provider, orderSource, network), - account: NO_ACCOUNT, - }; - return providerState; - }, -}; diff --git a/packages/instant/src/util/time.ts b/packages/instant/src/util/time.ts deleted file mode 100644 index bfe69cad5..000000000 --- a/packages/instant/src/util/time.ts +++ /dev/null @@ -1,39 +0,0 @@ -const secondsToMinutesAndRemainingSeconds = (seconds: number): { minutes: number; remainingSeconds: number } => { - const minutes = Math.floor(seconds / 60); - const remainingSeconds = seconds - minutes * 60; - - return { - minutes, - remainingSeconds, - }; -}; - -const padZero = (aNumber: number): string => { - return aNumber < 10 ? `0${aNumber}` : aNumber.toString(); -}; - -export const timeUtil = { - // converts seconds to human readable version of seconds or minutes - secondsToHumanDescription: (seconds: number): string => { - const { minutes, remainingSeconds } = secondsToMinutesAndRemainingSeconds(seconds); - - if (minutes === 0) { - const suffix = seconds > 1 ? 's' : ''; - return `${seconds} second${suffix}`; - } - - const minuteSuffix = minutes > 1 ? 's' : ''; - const minuteText = `${minutes} minute${minuteSuffix}`; - - const secondsSuffix = remainingSeconds > 1 ? 's' : ''; - const secondsText = remainingSeconds === 0 ? '' : ` ${remainingSeconds} second${secondsSuffix}`; - - return `${minuteText}${secondsText}`; - }, - // converts seconds to stopwatch time (i.e. 05:30 and 00:30) - // only goes up to minutes, not hours - secondsToStopwatchTime: (seconds: number): string => { - const { minutes, remainingSeconds } = secondsToMinutesAndRemainingSeconds(seconds); - return `${padZero(minutes)}:${padZero(remainingSeconds)}`; - }, -}; diff --git a/packages/instant/src/util/util.ts b/packages/instant/src/util/util.ts deleted file mode 100644 index 29b6b1d2b..000000000 --- a/packages/instant/src/util/util.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as _ from 'lodash'; - -export const util = { - boundNoop: _.noop.bind(_), - createOpenUrlInNewWindow: (href: string) => () => window.open(href, '_blank'), -}; |