1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-04 23:14:56 +01:00
metamask-extension/ui/pages/swaps/awaiting-swap/awaiting-swap.js

338 lines
11 KiB
JavaScript
Raw Normal View History

import EventEmitter from 'events';
2021-09-15 15:13:18 +02:00
import React, { useContext, useRef, useState, useEffect } from 'react';
2021-12-07 18:33:13 +01:00
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import { useHistory } from 'react-router-dom';
2021-12-07 18:33:13 +01:00
import isEqual from 'lodash/isEqual';
import { getBlockExplorerLink } from '@metamask/etherscan-link';
import { I18nContext } from '../../../contexts/i18n';
import { MetaMetricsContext } from '../../../contexts/metametrics';
import {
EVENT,
EVENT_NAMES,
CONTEXT_PROPS,
} from '../../../../shared/constants/metametrics';
import {
getCurrentChainId,
getCurrentCurrency,
getRpcPrefsForCurrentProvider,
getUSDConversionRate,
isHardwareWallet,
getHardwareWalletType,
getFullTxData,
} from '../../../selectors';
2020-10-06 20:28:38 +02:00
import {
2020-11-03 00:41:28 +01:00
getUsedQuote,
getFetchParams,
getApproveTxParams,
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
fetchQuotesAndSetQuoteState,
navigateBackToBuildQuote,
prepareForRetryGetQuotes,
prepareToLeaveSwaps,
getSmartTransactionsOptInStatus,
getSmartTransactionsEnabled,
getCurrentSmartTransactionsEnabled,
getFromTokenInputValue,
getMaxSlippage,
} from '../../../ducks/swaps/swaps';
import Mascot from '../../../components/ui/mascot';
2020-10-06 20:28:38 +02:00
import {
QUOTES_EXPIRED_ERROR,
SWAP_FAILED_ERROR,
ERROR_FETCHING_QUOTES,
QUOTES_NOT_AVAILABLE_ERROR,
CONTRACT_DATA_DISABLED_ERROR,
2020-10-06 20:28:38 +02:00
OFFLINE_FOR_MAINTENANCE,
SWAPS_CHAINID_DEFAULT_BLOCK_EXPLORER_URL_MAP,
} from '../../../../shared/constants/swaps';
import { isSwapsDefaultTokenSymbol } from '../../../../shared/modules/swaps.utils';
import PulseLoader from '../../../components/ui/pulse-loader';
import { DEFAULT_ROUTE } from '../../../helpers/constants/routes';
import {
stopPollingForQuotes,
setDefaultHomeActiveTabName,
} from '../../../store/actions';
2020-10-06 20:28:38 +02:00
import { getRenderableNetworkFeesForQuote } from '../swaps.util';
import SwapsFooter from '../swaps-footer';
import CreateNewSwap from '../create-new-swap';
import ViewOnBlockExplorer from '../view-on-block-explorer';
import { SUPPORT_LINK } from '../../../../shared/lib/ui-utils';
import SwapFailureIcon from './swap-failure-icon';
import SwapSuccessIcon from './swap-success-icon';
import QuotesTimeoutIcon from './quotes-timeout-icon';
2020-10-06 20:28:38 +02:00
2020-11-03 00:41:28 +01:00
export default function AwaitingSwap({
2020-10-06 20:28:38 +02:00
swapComplete,
errorKey,
txHash,
tokensReceived,
submittingSwap,
txId,
2020-10-06 20:28:38 +02:00
}) {
const t = useContext(I18nContext);
const trackEvent = useContext(MetaMetricsContext);
const history = useHistory();
const dispatch = useDispatch();
const animationEventEmitter = useRef(new EventEmitter());
const { swapMetaData } =
useSelector((state) => getFullTxData(state, txId)) || {};
2021-12-07 18:33:13 +01:00
const fetchParams = useSelector(getFetchParams, isEqual);
const fromTokenInputValue = useSelector(getFromTokenInputValue);
const maxSlippage = useSelector(getMaxSlippage);
2021-12-07 18:33:13 +01:00
const usedQuote = useSelector(getUsedQuote, isEqual);
const approveTxParams = useSelector(getApproveTxParams, shallowEqual);
const swapsGasPrice = useSelector(getUsedSwapsGasPrice);
const currentCurrency = useSelector(getCurrentCurrency);
const usdConversionRate = useSelector(getUSDConversionRate);
const chainId = useSelector(getCurrentChainId);
2021-12-07 18:33:13 +01:00
const rpcPrefs = useSelector(getRpcPrefsForCurrentProvider, shallowEqual);
2022-07-31 20:26:40 +02:00
const [trackedQuotesExpiredEvent, setTrackedQuotesExpiredEvent] =
useState(false);
2020-10-06 20:28:38 +02:00
let feeinUnformattedFiat;
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
if (usedQuote && swapsGasPrice) {
const renderableNetworkFees = getRenderableNetworkFeesForQuote({
tradeGas: usedQuote.gasEstimateWithRefund || usedQuote.averageGas,
approveGas: approveTxParams?.gas || '0x0',
gasPrice: swapsGasPrice,
currentCurrency,
conversionRate: usdConversionRate,
tradeValue: usedQuote?.trade?.value,
sourceSymbol: swapMetaData?.token_from,
sourceAmount: usedQuote.sourceAmount,
chainId,
});
feeinUnformattedFiat = renderableNetworkFees.rawNetworkFees;
2020-10-06 20:28:38 +02:00
}
const hardwareWalletUsed = useSelector(isHardwareWallet);
const hardwareWalletType = useSelector(getHardwareWalletType);
const smartTransactionsOptInStatus = useSelector(
getSmartTransactionsOptInStatus,
);
const smartTransactionsEnabled = useSelector(getSmartTransactionsEnabled);
const currentSmartTransactionsEnabled = useSelector(
getCurrentSmartTransactionsEnabled,
);
2021-05-21 17:14:56 +02:00
const sensitiveProperties = {
token_from: swapMetaData?.token_from,
token_from_amount: swapMetaData?.token_from_amount,
token_to: swapMetaData?.token_to,
2021-05-21 17:14:56 +02:00
request_type: fetchParams?.balanceError ? 'Quote' : 'Order',
slippage: swapMetaData?.slippage,
custom_slippage: swapMetaData?.slippage === 2,
2021-05-21 17:14:56 +02:00
gas_fees: feeinUnformattedFiat,
is_hardware_wallet: hardwareWalletUsed,
hardware_wallet_type: hardwareWalletType,
stx_enabled: smartTransactionsEnabled,
current_stx_enabled: currentSmartTransactionsEnabled,
stx_user_opt_in: smartTransactionsOptInStatus,
2021-05-21 17:14:56 +02:00
};
2020-10-06 20:28:38 +02:00
const baseNetworkUrl =
rpcPrefs.blockExplorerUrl ??
SWAPS_CHAINID_DEFAULT_BLOCK_EXPLORER_URL_MAP[chainId] ??
null;
const blockExplorerUrl = getBlockExplorerLink(
{ hash: txHash, chainId },
{ blockExplorerUrl: baseNetworkUrl },
);
let headerText;
let statusImage;
let descriptionText;
let submitText;
let content;
2020-10-06 20:28:38 +02:00
if (errorKey === OFFLINE_FOR_MAINTENANCE) {
headerText = t('offlineForMaintenance');
descriptionText = t('metamaskSwapsOfflineDescription');
submitText = t('close');
statusImage = <SwapFailureIcon />;
2020-10-06 20:28:38 +02:00
} else if (errorKey === SWAP_FAILED_ERROR) {
headerText = t('swapFailedErrorTitle');
descriptionText = t('swapFailedErrorDescriptionWithSupportLink', [
<a
className="awaiting-swap__support-link"
key="awaiting-swap-support-link"
href={SUPPORT_LINK}
target="_blank"
rel="noopener noreferrer"
onClick={() => {
trackEvent(
{
category: EVENT.CATEGORIES.SWAPS,
event: EVENT_NAMES.SUPPORT_LINK_CLICKED,
properties: {
url: SUPPORT_LINK,
},
},
{
contextPropsIntoEventProperties: [CONTEXT_PROPS.PAGE_TITLE],
},
);
}}
>
{new URL(SUPPORT_LINK).hostname}
</a>,
]);
submitText = t('tryAgain');
statusImage = <SwapFailureIcon />;
2020-10-06 20:28:38 +02:00
content = blockExplorerUrl && (
<ViewOnBlockExplorer
2020-10-06 20:28:38 +02:00
blockExplorerUrl={blockExplorerUrl}
sensitiveTrackingProperties={sensitiveProperties}
2020-10-06 20:28:38 +02:00
/>
);
2020-10-06 20:28:38 +02:00
} else if (errorKey === QUOTES_EXPIRED_ERROR) {
headerText = t('swapQuotesExpiredErrorTitle');
descriptionText = t('swapQuotesExpiredErrorDescription');
submitText = t('tryAgain');
statusImage = <QuotesTimeoutIcon />;
2020-10-06 20:28:38 +02:00
if (!trackedQuotesExpiredEvent) {
setTrackedQuotesExpiredEvent(true);
trackEvent({
event: 'Quotes Timed Out',
category: EVENT.CATEGORIES.SWAPS,
sensitiveProperties,
});
2020-10-06 20:28:38 +02:00
}
} else if (errorKey === ERROR_FETCHING_QUOTES) {
headerText = t('swapFetchingQuotesErrorTitle');
descriptionText = t('swapFetchingQuotesErrorDescription');
submitText = t('back');
statusImage = <SwapFailureIcon />;
2020-10-06 20:28:38 +02:00
} else if (errorKey === QUOTES_NOT_AVAILABLE_ERROR) {
headerText = t('swapQuotesNotAvailableErrorTitle');
descriptionText = t('swapQuotesNotAvailableErrorDescription');
submitText = t('tryAgain');
statusImage = <SwapFailureIcon />;
} else if (errorKey === CONTRACT_DATA_DISABLED_ERROR) {
headerText = t('swapContractDataDisabledErrorTitle');
descriptionText = t('swapContractDataDisabledErrorDescription');
submitText = t('tryAgain');
statusImage = <SwapFailureIcon />;
2020-10-06 20:28:38 +02:00
} else if (!errorKey && !swapComplete) {
headerText = t('swapProcessing');
statusImage = <PulseLoader />;
submitText = t('swapsViewInActivity');
2020-11-03 00:41:28 +01:00
descriptionText = t('swapOnceTransactionHasProcess', [
<span
key="swapOnceTransactionHasProcess-1"
className="awaiting-swap__amount-and-symbol"
>
{swapMetaData?.token_to}
2020-11-03 00:41:28 +01:00
</span>,
]);
content = blockExplorerUrl && (
<ViewOnBlockExplorer
blockExplorerUrl={blockExplorerUrl}
sensitiveTrackingProperties={sensitiveProperties}
/>
);
2020-10-06 20:28:38 +02:00
} else if (!errorKey && swapComplete) {
headerText = t('swapTransactionComplete');
statusImage = <SwapSuccessIcon />;
2021-05-21 17:14:56 +02:00
submitText = t('close');
2020-11-03 00:41:28 +01:00
descriptionText = t('swapTokenAvailable', [
<span
key="swapTokenAvailable-2"
className="awaiting-swap__amount-and-symbol"
>
{`${tokensReceived || ''} ${swapMetaData?.token_to}`}
2020-11-03 00:41:28 +01:00
</span>,
]);
2020-10-06 20:28:38 +02:00
content = blockExplorerUrl && (
<ViewOnBlockExplorer
2020-10-06 20:28:38 +02:00
blockExplorerUrl={blockExplorerUrl}
sensitiveTrackingProperties={sensitiveProperties}
2020-10-06 20:28:38 +02:00
/>
);
2020-10-06 20:28:38 +02:00
}
2021-09-15 15:13:18 +02:00
useEffect(() => {
if (errorKey) {
// If there was an error, stop polling for quotes.
dispatch(stopPollingForQuotes());
}
}, [dispatch, errorKey]);
2020-10-06 20:28:38 +02:00
return (
<div className="awaiting-swap">
<div className="awaiting-swap__content">
{!(swapComplete || errorKey) && (
<Mascot
animationEventEmitter={animationEventEmitter.current}
width="90"
height="90"
/>
)}
2020-11-03 00:41:28 +01:00
<div className="awaiting-swap__status-image">{statusImage}</div>
<div className="awaiting-swap__header">{headerText}</div>
<div className="awaiting-swap__main-description">{descriptionText}</div>
2020-10-06 20:28:38 +02:00
{content}
</div>
{!errorKey && swapComplete ? (
<CreateNewSwap sensitiveTrackingProperties={sensitiveProperties} />
) : null}
2020-10-06 20:28:38 +02:00
<SwapsFooter
onSubmit={async () => {
/* istanbul ignore next */
2020-10-06 20:28:38 +02:00
if (errorKey === OFFLINE_FOR_MAINTENANCE) {
await dispatch(prepareToLeaveSwaps());
history.push(DEFAULT_ROUTE);
2020-10-06 20:28:38 +02:00
} else if (errorKey === QUOTES_EXPIRED_ERROR) {
dispatch(prepareForRetryGetQuotes());
2020-11-03 00:41:28 +01:00
await dispatch(
fetchQuotesAndSetQuoteState(
history,
fromTokenInputValue,
2020-11-03 00:41:28 +01:00
maxSlippage,
trackEvent,
2020-11-03 00:41:28 +01:00
),
);
2020-10-06 20:28:38 +02:00
} else if (errorKey) {
await dispatch(navigateBackToBuildQuote(history));
} else if (
isSwapsDefaultTokenSymbol(swapMetaData?.token_to, chainId) ||
2021-05-21 17:14:56 +02:00
swapComplete
) {
history.push(DEFAULT_ROUTE);
2020-10-06 20:28:38 +02:00
} else {
await dispatch(setDefaultHomeActiveTabName('Activity'));
history.push(DEFAULT_ROUTE);
2020-10-06 20:28:38 +02:00
}
}}
onCancel={async () => await dispatch(navigateBackToBuildQuote(history))}
submitText={submitText}
disabled={submittingSwap}
hideCancel={errorKey !== QUOTES_EXPIRED_ERROR}
/>
</div>
);
2020-10-06 20:28:38 +02:00
}
AwaitingSwap.propTypes = {
swapComplete: PropTypes.bool,
txHash: PropTypes.string,
tokensReceived: PropTypes.string,
errorKey: PropTypes.oneOf([
QUOTES_EXPIRED_ERROR,
SWAP_FAILED_ERROR,
ERROR_FETCHING_QUOTES,
QUOTES_NOT_AVAILABLE_ERROR,
OFFLINE_FOR_MAINTENANCE,
CONTRACT_DATA_DISABLED_ERROR,
2020-10-06 20:28:38 +02:00
]),
submittingSwap: PropTypes.bool,
txId: PropTypes.number,
};