mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-12-03 14:44:27 +01:00
14b5c389ed
* Replace logic for eth swap token in fetchQuotesAndSetQuoteState with getSwapsEthToken call (#10624) * Move swaps constants to the shared constants directory (#10614) * Fix: ETH 'token' now only appears once in the swaps to and from dropdowns. (#10650) * Swaps support for local testnet (#10658) * Swaps support for local testnet * Create util method for comparison of token addresses/symbols to default swaps token * Get chainId from txMeta in _trackSwapsMetrics of transaction controller * Add comment to document purpose of getTransactionGroupRecipientAddressFilter * Use isSwapsDefaultTokenSymbol in place of repeated defaultTokenSymbol comparisons in build-quote.js * Additional swaps network support (#10721) * Add swaps support for bnc chain * Use single default token address in shared/constants/swaps * Ensure swaps gas prices are fetched from the correct chain specific endpoint (#10744) * Ensure swaps gas prices are fetched from the correct chain specific endpoint * Just rely on fetchWithCache to cache swaps gas prices, instead of directly using storage in getSwapsPriceEstimatesLastRetrieved * Empty commit * update @metamask/etherscan-link to v2.0.0 (#10747) * Use correct block explorer name and link in swaps when on custom network (#10743) * Use correct block explorer name and link in swaps when on custom network. * Fix up custom etherscan link code in build-quote.js * Use blockExplorerUrl hostname instead of 'blockExplorerBaseUrl' * Use correct etherscan-link method for token links in build-quote * Create correct token link in build-quote for mainnet AND custom networks * Block explorer url improvements in awaiting-swap.js and build-quote.js * Use swapVerifyTokenExplanation message with substitutable block explorer for all applicable locales * Ensure that block explorer links are not shown in awaiting-swap if no url is available * Ensure that the correct default currency symbols are used for fees on the view quote screen (#10753) * Updating y18n and netmask to resolve dependency issues (#10765) netmask@1.0.6 -> 2.0.1, y18n@3.2.1 -> 3.2.2, y18n@4.0.0 -> 4.0.1 * Ensure that priceSlippage fiat amounts are always shown in view-quote.js (#10762) * Ensure that the approval fee in the swaps custom gas modal is in network specific currency (#10763) * Use network specific swaps contract address when checking swap contract token approval (#10774) * Set the BSC_CONTRACT_ADDRESS to lowercase (#10800) * Ensure correct primary currency image is displayed on home screen and token list (#10777) * [skip e2e] Update changelog for v9.3.0 (#10740) * Version v9.3.0 * [skip e2e] Update changelog for v9.3.0 (#10803) Co-authored-by: Dan J Miller <danjm.com@gmail.com> Co-authored-by: ryanml <ryanlanese@gmail.com> Co-authored-by: David Walsh <davidwalsh83@gmail.com> Co-authored-by: MetaMask Bot <metamaskbot@users.noreply.github.com>
393 lines
12 KiB
JavaScript
393 lines
12 KiB
JavaScript
import React, { useState, useEffect, useRef, useContext } from 'react';
|
|
import { useDispatch, useSelector } from 'react-redux';
|
|
import {
|
|
Switch,
|
|
Route,
|
|
useLocation,
|
|
useHistory,
|
|
Redirect,
|
|
} from 'react-router-dom';
|
|
import BigNumber from 'bignumber.js';
|
|
import { I18nContext } from '../../contexts/i18n';
|
|
import {
|
|
getSelectedAccount,
|
|
getCurrentChainId,
|
|
getIsSwapsChain,
|
|
} from '../../selectors/selectors';
|
|
import {
|
|
getQuotes,
|
|
clearSwapsState,
|
|
getTradeTxId,
|
|
getApproveTxId,
|
|
getFetchingQuotes,
|
|
setBalanceError,
|
|
setTopAssets,
|
|
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,
|
|
SWAP_FAILED_ERROR,
|
|
OFFLINE_FOR_MAINTENANCE,
|
|
} from '../../../../shared/constants/swaps';
|
|
|
|
import {
|
|
resetBackgroundSwapsState,
|
|
setSwapsTokens,
|
|
removeToken,
|
|
setBackgroundSwapRouteState,
|
|
setSwapsErrorKey,
|
|
} from '../../store/actions';
|
|
import { currentNetworkTxListSelector } from '../../selectors';
|
|
import { useNewMetricEvent } from '../../hooks/useMetricEvent';
|
|
|
|
import FeatureToggledRoute from '../../helpers/higher-order-components/feature-toggled-route';
|
|
import { TRANSACTION_STATUSES } from '../../../../shared/constants/transaction';
|
|
import {
|
|
fetchTokens,
|
|
fetchTopAssets,
|
|
getSwapsTokensReceivedFromTxMeta,
|
|
fetchAggregatorMetadata,
|
|
} from './swaps.util';
|
|
import AwaitingSwap from './awaiting-swap';
|
|
import LoadingQuote from './loading-swaps-quotes';
|
|
import BuildQuote from './build-quote';
|
|
import ViewQuote from './view-quote';
|
|
|
|
export default function Swap() {
|
|
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);
|
|
const { destinationTokenInfo = {} } = fetchParams?.metaData || {};
|
|
|
|
const [inputValue, setInputValue] = useState(fetchParams?.value || '');
|
|
const [maxSlippage, setMaxSlippage] = useState(fetchParams?.slippage || 2);
|
|
|
|
const routeState = useSelector(getBackgroundSwapRouteState);
|
|
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 fetchingQuotes = useSelector(getFetchingQuotes);
|
|
let swapsErrorKey = useSelector(getSwapsErrorKey);
|
|
const swapsEnabled = useSelector(getSwapsFeatureLiveness);
|
|
const chainId = useSelector(getCurrentChainId);
|
|
const isSwapsChain = useSelector(getIsSwapsChain);
|
|
|
|
const {
|
|
balance: ethBalance,
|
|
address: selectedAccountAddress,
|
|
} = selectedAccount;
|
|
|
|
const { destinationTokenAddedForSwap } = fetchParams || {};
|
|
|
|
const approveTxData =
|
|
approveTxId && txList.find(({ id }) => approveTxId === id);
|
|
const tradeTxData = tradeTxId && txList.find(({ id }) => tradeTxId === id);
|
|
const tokensReceived =
|
|
tradeTxData?.txReceipt &&
|
|
getSwapsTokensReceivedFromTxMeta(
|
|
destinationTokenInfo?.symbol,
|
|
tradeTxData,
|
|
destinationTokenInfo?.address,
|
|
selectedAccountAddress,
|
|
destinationTokenInfo?.decimals,
|
|
approveTxData,
|
|
chainId,
|
|
);
|
|
const tradeConfirmed = tradeTxData?.status === TRANSACTION_STATUSES.CONFIRMED;
|
|
const approveError =
|
|
approveTxData?.status === TRANSACTION_STATUSES.FAILED ||
|
|
approveTxData?.txReceipt?.status === '0x0';
|
|
const tradeError =
|
|
tradeTxData?.status === TRANSACTION_STATUSES.FAILED ||
|
|
tradeTxData?.txReceipt?.status === '0x0';
|
|
const conversionError = approveError || tradeError;
|
|
|
|
if (conversionError) {
|
|
swapsErrorKey = SWAP_FAILED_ERROR;
|
|
}
|
|
|
|
const clearTemporaryTokenRef = useRef();
|
|
useEffect(() => {
|
|
clearTemporaryTokenRef.current = () => {
|
|
if (
|
|
destinationTokenAddedForSwap &&
|
|
(!isAwaitingSwapRoute || conversionError)
|
|
) {
|
|
dispatch(removeToken(destinationTokenInfo?.address));
|
|
}
|
|
};
|
|
}, [
|
|
conversionError,
|
|
dispatch,
|
|
destinationTokenAddedForSwap,
|
|
destinationTokenInfo,
|
|
fetchParams,
|
|
isAwaitingSwapRoute,
|
|
]);
|
|
useEffect(() => {
|
|
return () => {
|
|
clearTemporaryTokenRef.current();
|
|
};
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
fetchTokens(chainId)
|
|
.then((tokens) => {
|
|
dispatch(setSwapsTokens(tokens));
|
|
})
|
|
.catch((error) => console.error(error));
|
|
|
|
fetchTopAssets(chainId).then((topAssets) => {
|
|
dispatch(setTopAssets(topAssets));
|
|
});
|
|
|
|
fetchAggregatorMetadata(chainId).then((newAggregatorMetadata) => {
|
|
dispatch(setAggregatorMetadata(newAggregatorMetadata));
|
|
});
|
|
|
|
dispatch(fetchAndSetSwapsGasPriceInfo(chainId));
|
|
|
|
return () => {
|
|
dispatch(prepareToLeaveSwaps());
|
|
};
|
|
}, [dispatch, chainId]);
|
|
|
|
const exitedSwapsEvent = useNewMetricEvent({
|
|
event: 'Exited Swaps',
|
|
category: 'swaps',
|
|
sensitiveProperties: {
|
|
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]);
|
|
|
|
if (!isSwapsChain) {
|
|
return <Redirect to={{ pathname: DEFAULT_ROUTE }} />;
|
|
}
|
|
|
|
return (
|
|
<div className="swaps">
|
|
<div className="swaps__container">
|
|
<div className="swaps__header">
|
|
<div className="swaps__title">{t('swap')}</div>
|
|
{!isAwaitingSwapRoute && (
|
|
<div
|
|
className="swaps__header-cancel"
|
|
onClick={async () => {
|
|
clearTemporaryTokenRef.current();
|
|
dispatch(clearSwapsState());
|
|
await dispatch(resetBackgroundSwapsState());
|
|
history.push(DEFAULT_ROUTE);
|
|
}}
|
|
>
|
|
{t('cancel')}
|
|
</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);
|
|
dispatch(
|
|
setBalanceError(
|
|
new BigNumber(newInputValue || 0).gt(balance || 0),
|
|
),
|
|
);
|
|
};
|
|
|
|
return (
|
|
<BuildQuote
|
|
inputValue={inputValue}
|
|
onInputChange={onInputChange}
|
|
ethBalance={ethBalance}
|
|
setMaxSlippage={setMaxSlippage}
|
|
selectedAccountAddress={selectedAccountAddress}
|
|
maxSlippage={maxSlippage}
|
|
/>
|
|
);
|
|
}}
|
|
/>
|
|
<FeatureToggledRoute
|
|
redirectRoute={SWAPS_MAINTENANCE_ROUTE}
|
|
flag={swapsEnabled}
|
|
path={VIEW_QUOTE_ROUTE}
|
|
exact
|
|
render={() => {
|
|
if (Object.values(quotes).length) {
|
|
return (
|
|
<ViewQuote numberOfQuotes={Object.values(quotes).length} />
|
|
);
|
|
} 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}
|
|
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={() => {
|
|
return aggregatorMetadata ? (
|
|
<LoadingQuote
|
|
loadingComplete={
|
|
!fetchingQuotes && Boolean(Object.values(quotes).length)
|
|
}
|
|
onDone={async () => {
|
|
await dispatch(setBackgroundSwapRouteState(''));
|
|
|
|
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 }} />
|
|
);
|
|
}}
|
|
/>
|
|
<Route
|
|
path={SWAPS_MAINTENANCE_ROUTE}
|
|
exact
|
|
render={() => {
|
|
return swapsEnabled === false ? (
|
|
<AwaitingSwap errorKey={OFFLINE_FOR_MAINTENANCE} />
|
|
) : (
|
|
<Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} />
|
|
);
|
|
}}
|
|
/>
|
|
<Route
|
|
path={AWAITING_SWAP_ROUTE}
|
|
exact
|
|
render={() => {
|
|
return routeState === 'awaiting' || tradeTxData ? (
|
|
<AwaitingSwap
|
|
swapComplete={tradeConfirmed}
|
|
txHash={tradeTxData?.hash}
|
|
tokensReceived={tokensReceived}
|
|
submittingSwap={
|
|
routeState === 'awaiting' && !(approveTxId || tradeTxId)
|
|
}
|
|
inputValue={inputValue}
|
|
maxSlippage={maxSlippage}
|
|
/>
|
|
) : (
|
|
<Redirect to={{ pathname: DEFAULT_ROUTE }} />
|
|
);
|
|
}}
|
|
/>
|
|
</Switch>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|