1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-23 11:46:13 +02:00
metamask-extension/ui/app/pages/swaps/index.js

420 lines
13 KiB
JavaScript
Raw Normal View History

2020-10-06 20:28:38 +02:00
import React, { useState, useEffect, useRef, useContext } from 'react'
import { useDispatch, useSelector } from 'react-redux'
2020-11-03 00:41:28 +01:00
import {
Switch,
Route,
useLocation,
useHistory,
Redirect,
} from 'react-router-dom'
2020-10-06 20:28:38 +02:00
import BigNumber from 'bignumber.js'
import { I18nContext } from '../../contexts/i18n'
2020-11-03 00:41:28 +01:00
import {
getSelectedAccount,
getCurrentNetworkId,
} from '../../selectors/selectors'
2020-10-06 20:28:38 +02:00
import {
getFromToken,
getQuotes,
clearSwapsState,
getTradeTxId,
getApproveTxId,
getFetchingQuotes,
setBalanceError,
setTopAssets,
Switch gas price estimation in swaps to metaswap-api /gasPrices (#9599) Adds swaps-gas-customization-modal and utilize in swaps Remove swaps specific code from gas-modal-page-container/ Remove slow estimate data from swaps-gas-customization-modal.container Use average as lower safe price limit in swaps-gas-customization-modal Lint fix Fix up unit tests Update ui/app/ducks/swaps/swaps.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> Remove stale properties from gas-modal-page-container.component.js Replace use of isCustomPrice safe with isCustomSwapsGasPriceSafe, in swaps-gas-customization-modal Remove use of averageIsSafe in isCustomPriceSafe function Stop calling resetCustomGasState in swaps Refactor 'setter' type actions and creators to 'event based', for swaps slice custom gas logic Replace use of advanced-tab-content.component with advanceGasInputs in swaps gas customization component Add validation for the gasPrices endpoint swaps custom gas price should be considered safe if >= to average Update renderDataSummary unit test Lint fix Remove customOnHideOpts for swapsGasCustomizationModal in modal.js Better handling for swaps gas price loading and failure states Improve semantics: isCustomSwapsGasPriceSafe renamed to isCustomSwapsGasPriceUnSafe Mutate state directly in swaps gas slice reducer Remove unused params More reliable tracking of speed setting for Gas Fees Changed metrics event Lint fix Throw error when fetchSwapsGasPrices response is invalid add disableSave and customTotalSupplement to swaps-gas-customization container return Update ui/app/ducks/swaps/swaps.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> Improve error handling in fetchMetaSwapsGasPriceEstimates Remove metricsEvent from swaps-gas-customization-modal context Base check of gas speed type in swaps-gas-customization-modal on gasEstimateType Improve naming of variable and functions use to set customPriceIsSafe prop of AdvancedGasInputs in swaps-gas-customization-modal Simplify sinon spy/stub code in gas-price-button-group-component.test.js Remove unnecessary getSwapsFallbackGasPrice call in swaps-gas-customization-modal Remove use of getSwapsTradeTxParams and clean up related gas price logic in swaps Improve validator of SWAP_GAS_PRICE_VALIDATOR Ensure default tradeValue
2020-11-04 17:14:08 +01:00
getUsedSwapsGasPrice,
2020-10-06 20:28:38 +02:00
getFetchParams,
setAggregatorMetadata,
getAggregatorMetadata,
getBackgroundSwapRouteState,
getSwapsErrorKey,
getSwapsFeatureLiveness,
prepareToLeaveSwaps,
fetchAndSetSwapsGasPriceInfo,
} from '../../ducks/swaps/swaps'
import {
AWAITING_SWAP_ROUTE,
BUILD_QUOTE_ROUTE,
VIEW_QUOTE_ROUTE,
LOADING_QUOTES_ROUTE,
SWAPS_ERROR_ROUTE,
DEFAULT_ROUTE,
SWAPS_MAINTENANCE_ROUTE,
} from '../../helpers/constants/routes'
import {
ERROR_FETCHING_QUOTES,
QUOTES_NOT_AVAILABLE_ERROR,
ETH_SWAPS_TOKEN_OBJECT,
SWAP_FAILED_ERROR,
OFFLINE_FOR_MAINTENANCE,
} from '../../helpers/constants/swaps'
2020-11-03 00:41:28 +01:00
import {
resetBackgroundSwapsState,
setSwapsTokens,
removeToken,
setBackgroundSwapRouteState,
setSwapsErrorKey,
} from '../../store/actions'
import {
currentNetworkTxListSelector,
getRpcPrefsForCurrentProvider,
} from '../../selectors'
2020-10-06 20:28:38 +02:00
import { useNewMetricEvent } from '../../hooks/useMetricEvent'
import { getValueFromWeiHex } from '../../helpers/utils/conversions.util'
import FeatureToggledRoute from '../../helpers/higher-order-components/feature-toggled-route'
import { TRANSACTION_STATUSES } from '../../../../shared/constants/transaction'
2020-11-03 00:41:28 +01:00
import {
fetchTokens,
fetchTopAssets,
getSwapsTokensReceivedFromTxMeta,
fetchAggregatorMetadata,
} from './swaps.util'
2020-10-06 20:28:38 +02:00
import AwaitingSwap from './awaiting-swap'
import LoadingQuote from './loading-swaps-quotes'
import BuildQuote from './build-quote'
import ViewQuote from './view-quote'
2020-11-03 00:41:28 +01:00
export default function Swap() {
2020-10-06 20:28:38 +02:00
const t = useContext(I18nContext)
const history = useHistory()
const dispatch = useDispatch()
const { pathname } = useLocation()
const isAwaitingSwapRoute = pathname === AWAITING_SWAP_ROUTE
const isSwapsErrorRoute = pathname === SWAPS_ERROR_ROUTE
const isLoadingQuotesRoute = pathname === LOADING_QUOTES_ROUTE
const fetchParams = useSelector(getFetchParams)
2020-11-03 00:41:28 +01:00
const { sourceTokenInfo = {}, destinationTokenInfo = {} } =
fetchParams?.metaData || {}
2020-10-06 20:28:38 +02:00
const [inputValue, setInputValue] = useState(fetchParams?.value || '')
const [maxSlippage, setMaxSlippage] = useState(fetchParams?.slippage || 2)
const routeState = useSelector(getBackgroundSwapRouteState)
Switch gas price estimation in swaps to metaswap-api /gasPrices (#9599) Adds swaps-gas-customization-modal and utilize in swaps Remove swaps specific code from gas-modal-page-container/ Remove slow estimate data from swaps-gas-customization-modal.container Use average as lower safe price limit in swaps-gas-customization-modal Lint fix Fix up unit tests Update ui/app/ducks/swaps/swaps.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> Remove stale properties from gas-modal-page-container.component.js Replace use of isCustomPrice safe with isCustomSwapsGasPriceSafe, in swaps-gas-customization-modal Remove use of averageIsSafe in isCustomPriceSafe function Stop calling resetCustomGasState in swaps Refactor 'setter' type actions and creators to 'event based', for swaps slice custom gas logic Replace use of advanced-tab-content.component with advanceGasInputs in swaps gas customization component Add validation for the gasPrices endpoint swaps custom gas price should be considered safe if >= to average Update renderDataSummary unit test Lint fix Remove customOnHideOpts for swapsGasCustomizationModal in modal.js Better handling for swaps gas price loading and failure states Improve semantics: isCustomSwapsGasPriceSafe renamed to isCustomSwapsGasPriceUnSafe Mutate state directly in swaps gas slice reducer Remove unused params More reliable tracking of speed setting for Gas Fees Changed metrics event Lint fix Throw error when fetchSwapsGasPrices response is invalid add disableSave and customTotalSupplement to swaps-gas-customization container return Update ui/app/ducks/swaps/swaps.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> Improve error handling in fetchMetaSwapsGasPriceEstimates Remove metricsEvent from swaps-gas-customization-modal context Base check of gas speed type in swaps-gas-customization-modal on gasEstimateType Improve naming of variable and functions use to set customPriceIsSafe prop of AdvancedGasInputs in swaps-gas-customization-modal Simplify sinon spy/stub code in gas-price-button-group-component.test.js Remove unnecessary getSwapsFallbackGasPrice call in swaps-gas-customization-modal Remove use of getSwapsTradeTxParams and clean up related gas price logic in swaps Improve validator of SWAP_GAS_PRICE_VALIDATOR Ensure default tradeValue
2020-11-04 17:14:08 +01:00
const usedGasPrice = useSelector(getUsedSwapsGasPrice)
2020-10-06 20:28:38 +02:00
const selectedAccount = useSelector(getSelectedAccount)
const quotes = useSelector(getQuotes)
const txList = useSelector(currentNetworkTxListSelector)
const tradeTxId = useSelector(getTradeTxId)
const approveTxId = useSelector(getApproveTxId)
const aggregatorMetadata = useSelector(getAggregatorMetadata)
const networkId = useSelector(getCurrentNetworkId)
const rpcPrefs = useSelector(getRpcPrefsForCurrentProvider)
const fetchingQuotes = useSelector(getFetchingQuotes)
let swapsErrorKey = useSelector(getSwapsErrorKey)
const swapsEnabled = useSelector(getSwapsFeatureLiveness)
2020-11-03 00:41:28 +01:00
const {
balance: ethBalance,
address: selectedAccountAddress,
} = selectedAccount
const fetchParamsFromToken =
sourceTokenInfo?.symbol === 'ETH'
? {
...ETH_SWAPS_TOKEN_OBJECT,
string: getValueFromWeiHex({
value: ethBalance,
numberOfDecimals: 4,
toDenomination: 'ETH',
}),
balance: ethBalance,
}
: sourceTokenInfo
const selectedFromToken =
useSelector(getFromToken) || fetchParamsFromToken || {}
2020-10-06 20:28:38 +02:00
const { destinationTokenAddedForSwap } = fetchParams || {}
2020-11-03 00:41:28 +01:00
const approveTxData =
approveTxId && txList.find(({ id }) => approveTxId === id)
2020-10-06 20:28:38 +02:00
const tradeTxData = tradeTxId && txList.find(({ id }) => tradeTxId === id)
2020-11-03 00:41:28 +01:00
const tokensReceived =
tradeTxData?.txReceipt &&
getSwapsTokensReceivedFromTxMeta(
destinationTokenInfo?.symbol,
tradeTxData,
destinationTokenInfo?.address,
selectedAccountAddress,
destinationTokenInfo?.decimals,
approveTxData,
)
const tradeConfirmed = tradeTxData?.status === TRANSACTION_STATUSES.CONFIRMED
2020-11-03 00:41:28 +01:00
const approveError =
approveTxData?.status === TRANSACTION_STATUSES.FAILED ||
2020-11-03 00:41:28 +01:00
approveTxData?.txReceipt?.status === '0x0'
const tradeError =
tradeTxData?.status === TRANSACTION_STATUSES.FAILED ||
tradeTxData?.txReceipt?.status === '0x0'
2020-10-06 20:28:38 +02:00
const conversionError = approveError || tradeError
if (conversionError) {
swapsErrorKey = SWAP_FAILED_ERROR
}
const clearTemporaryTokenRef = useRef()
2020-11-03 00:41:28 +01:00
useEffect(() => {
clearTemporaryTokenRef.current = () => {
if (
destinationTokenAddedForSwap &&
(!isAwaitingSwapRoute || conversionError)
) {
dispatch(removeToken(destinationTokenInfo?.address))
2020-10-06 20:28:38 +02:00
}
2020-11-03 00:41:28 +01:00
}
}, [
conversionError,
dispatch,
destinationTokenAddedForSwap,
destinationTokenInfo,
fetchParams,
isAwaitingSwapRoute,
])
2020-10-06 20:28:38 +02:00
useEffect(() => {
return () => {
clearTemporaryTokenRef.current()
}
}, [])
useEffect(() => {
fetchTokens()
.then((tokens) => {
dispatch(setSwapsTokens(tokens))
})
.catch((error) => console.error(error))
2020-11-03 00:41:28 +01:00
fetchTopAssets().then((topAssets) => {
dispatch(setTopAssets(topAssets))
})
2020-10-06 20:28:38 +02:00
2020-11-03 00:41:28 +01:00
fetchAggregatorMetadata().then((newAggregatorMetadata) => {
dispatch(setAggregatorMetadata(newAggregatorMetadata))
})
2020-10-06 20:28:38 +02:00
dispatch(fetchAndSetSwapsGasPriceInfo())
return () => {
dispatch(prepareToLeaveSwaps())
}
}, [dispatch])
const exitedSwapsEvent = useNewMetricEvent({
event: 'Exited Swaps',
category: 'swaps',
sensitiveProperties: {
2020-10-06 20:28:38 +02:00
token_from: fetchParams?.sourceTokenInfo?.symbol,
token_from_amount: fetchParams?.value,
request_type: fetchParams?.balanceError,
token_to: fetchParams?.destinationTokenInfo?.symbol,
slippage: fetchParams?.slippage,
custom_slippage: fetchParams?.slippage !== 2,
current_screen: pathname.match(/\/swaps\/(.+)/u)[1],
},
})
const exitEventRef = useRef()
useEffect(() => {
exitEventRef.current = () => {
exitedSwapsEvent()
}
})
useEffect(() => {
return () => {
exitEventRef.current()
}
}, [])
useEffect(() => {
if (swapsErrorKey && !isSwapsErrorRoute) {
history.push(SWAPS_ERROR_ROUTE)
}
}, [history, swapsErrorKey, isSwapsErrorRoute])
const beforeUnloadEventAddedRef = useRef()
useEffect(() => {
const fn = () => {
clearTemporaryTokenRef.current()
if (isLoadingQuotesRoute) {
dispatch(prepareToLeaveSwaps())
}
return null
}
if (isLoadingQuotesRoute && !beforeUnloadEventAddedRef.current) {
beforeUnloadEventAddedRef.current = true
window.addEventListener('beforeunload', fn)
}
return () => window.removeEventListener('beforeunload', fn)
}, [dispatch, isLoadingQuotesRoute])
return (
<div className="swaps">
<div className="swaps__container">
<div className="swaps__header">
2020-11-03 00:41:28 +01:00
<div className="swaps__title">{t('swap')}</div>
2020-10-06 20:28:38 +02:00
{!isAwaitingSwapRoute && (
<div
className="swaps__header-cancel"
onClick={async () => {
clearTemporaryTokenRef.current()
dispatch(clearSwapsState())
await dispatch(resetBackgroundSwapsState())
history.push(DEFAULT_ROUTE)
}}
>
2020-11-03 00:41:28 +01:00
{t('cancel')}
2020-10-06 20:28:38 +02:00
</div>
)}
</div>
<div className="swaps__content">
<Switch>
<FeatureToggledRoute
redirectRoute={SWAPS_MAINTENANCE_ROUTE}
flag={swapsEnabled}
path={BUILD_QUOTE_ROUTE}
exact
render={() => {
if (tradeTxData && !conversionError) {
return <Redirect to={{ pathname: AWAITING_SWAP_ROUTE }} />
} else if (tradeTxData) {
return <Redirect to={{ pathname: SWAPS_ERROR_ROUTE }} />
} else if (routeState === 'loading' && aggregatorMetadata) {
return <Redirect to={{ pathname: LOADING_QUOTES_ROUTE }} />
}
const onInputChange = (newInputValue, balance) => {
setInputValue(newInputValue)
2020-11-03 00:41:28 +01:00
dispatch(
setBalanceError(
new BigNumber(newInputValue || 0).gt(balance || 0),
),
)
2020-10-06 20:28:38 +02:00
}
return (
<BuildQuote
inputValue={inputValue}
selectedFromToken={selectedFromToken}
onInputChange={onInputChange}
ethBalance={ethBalance}
setMaxSlippage={setMaxSlippage}
selectedAccountAddress={selectedAccountAddress}
maxSlippage={Number(maxSlippage)}
2020-10-06 20:28:38 +02:00
/>
)
}}
/>
<FeatureToggledRoute
redirectRoute={SWAPS_MAINTENANCE_ROUTE}
flag={swapsEnabled}
path={VIEW_QUOTE_ROUTE}
exact
render={() => {
if (Object.values(quotes).length) {
return (
2020-11-03 00:41:28 +01:00
<ViewQuote numberOfQuotes={Object.values(quotes).length} />
2020-10-06 20:28:38 +02:00
)
} else if (fetchParams) {
return <Redirect to={{ pathname: SWAPS_ERROR_ROUTE }} />
}
return <Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} />
}}
/>
<Route
path={SWAPS_ERROR_ROUTE}
exact
render={() => {
if (swapsErrorKey) {
return (
<AwaitingSwap
swapComplete={false}
errorKey={swapsErrorKey}
txHash={tradeTxData?.hash}
networkId={networkId}
rpcPrefs={rpcPrefs}
inputValue={inputValue}
maxSlippage={maxSlippage}
submittedTime={tradeTxData?.submittedTime}
/>
)
}
return <Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} />
}}
/>
<FeatureToggledRoute
redirectRoute={SWAPS_MAINTENANCE_ROUTE}
flag={swapsEnabled}
path={LOADING_QUOTES_ROUTE}
exact
render={() => {
2020-11-03 00:41:28 +01:00
return aggregatorMetadata ? (
<LoadingQuote
loadingComplete={
!fetchingQuotes && Boolean(Object.values(quotes).length)
}
onDone={async () => {
await dispatch(setBackgroundSwapRouteState(''))
2020-10-06 20:28:38 +02:00
2020-11-03 00:41:28 +01:00
if (
swapsErrorKey === ERROR_FETCHING_QUOTES ||
swapsErrorKey === QUOTES_NOT_AVAILABLE_ERROR
) {
dispatch(setSwapsErrorKey(QUOTES_NOT_AVAILABLE_ERROR))
history.push(SWAPS_ERROR_ROUTE)
} else {
history.push(VIEW_QUOTE_ROUTE)
}
}}
aggregatorMetadata={aggregatorMetadata}
/>
) : (
<Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} />
)
2020-10-06 20:28:38 +02:00
}}
/>
<Route
path={SWAPS_MAINTENANCE_ROUTE}
exact
render={() => {
return swapsEnabled === false ? (
<AwaitingSwap
errorKey={OFFLINE_FOR_MAINTENANCE}
networkId={networkId}
rpcPrefs={rpcPrefs}
/>
2020-11-03 00:41:28 +01:00
) : (
<Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} />
)
2020-10-06 20:28:38 +02:00
}}
/>
<Route
path={AWAITING_SWAP_ROUTE}
exact
render={() => {
2020-11-03 00:41:28 +01:00
return routeState === 'awaiting' || tradeTxData ? (
<AwaitingSwap
swapComplete={tradeConfirmed}
networkId={networkId}
txHash={tradeTxData?.hash}
tokensReceived={tokensReceived}
tradeTxData={tradeTxData}
usedGasPrice={usedGasPrice}
submittingSwap={
routeState === 'awaiting' && !(approveTxId || tradeTxId)
}
rpcPrefs={rpcPrefs}
inputValue={inputValue}
maxSlippage={maxSlippage}
/>
) : (
<Redirect to={{ pathname: DEFAULT_ROUTE }} />
)
2020-10-06 20:28:38 +02:00
}}
/>
</Switch>
</div>
</div>
</div>
)
}