1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-30 08:09:15 +01:00
metamask-extension/ui/components/app/transaction-list-item/transaction-list-item.component.js

309 lines
9.3 KiB
JavaScript
Raw Normal View History

import React, { useMemo, useState, useCallback, useContext } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { useHistory } from 'react-router-dom';
import { useSelector } from 'react-redux';
import ListItem from '../../ui/list-item';
import { useTransactionDisplayData } from '../../../hooks/useTransactionDisplayData';
import { useI18nContext } from '../../../hooks/useI18nContext';
import TransactionListItemDetails from '../transaction-list-item-details';
import { CONFIRM_TRANSACTION_ROUTE } from '../../../helpers/constants/routes';
import { useShouldShowSpeedUp } from '../../../hooks/useShouldShowSpeedUp';
import TransactionStatusLabel from '../transaction-status-label/transaction-status-label';
import TransactionIcon from '../transaction-icon';
import { MetaMetricsEventCategory } from '../../../../shared/constants/metametrics';
import {
TransactionGroupCategory,
TransactionStatus,
} from '../../../../shared/constants/transaction';
import { EditGasModes } from '../../../../shared/constants/gas';
import {
GasFeeContextProvider,
useGasFeeContext,
} from '../../../contexts/gasFee';
import {
TransactionModalContextProvider,
useTransactionModalContext,
} from '../../../contexts/transaction-modal';
import { checkNetworkAndAccountSupports1559 } from '../../../selectors';
import { isLegacyTransaction } from '../../../helpers/utils/transactions.util';
import Button from '../../ui/button';
import AdvancedGasFeePopover from '../advanced-gas-fee-popover';
import CancelButton from '../cancel-button';
import CancelSpeedupPopover from '../cancel-speedup-popover';
import EditGasFeePopover from '../edit-gas-fee-popover';
import EditGasPopover from '../edit-gas-popover';
import { MetaMetricsContext } from '../../../contexts/metametrics';
import SiteOrigin from '../../ui/site-origin';
function TransactionListItemInner({
2020-11-03 00:41:28 +01:00
transactionGroup,
setEditGasMode,
2020-11-03 00:41:28 +01:00
isEarliestNonce = false,
}) {
const t = useI18nContext();
const history = useHistory();
const { hasCancelled } = transactionGroup;
const [showDetails, setShowDetails] = useState(false);
2022-07-31 20:26:40 +02:00
const [showCancelEditGasPopover, setShowCancelEditGasPopover] =
useState(false);
const [showRetryEditGasPopover, setShowRetryEditGasPopover] = useState(false);
const { supportsEIP1559 } = useGasFeeContext();
const { openModal } = useTransactionModalContext();
2020-11-03 00:41:28 +01:00
const {
initialTransaction: { id },
primaryTransaction: { err, status },
} = transactionGroup;
const trackEvent = useContext(MetaMetricsContext);
const retryTransaction = useCallback(
async (event) => {
event.stopPropagation();
trackEvent({
event: 'Clicked "Speed Up"',
category: MetaMetricsEventCategory.Navigation,
properties: {
action: 'Activity Log',
legacy_event: true,
},
});
if (supportsEIP1559) {
setEditGasMode(EditGasModes.speedUp);
openModal('cancelSpeedUpTransaction');
} else {
setShowRetryEditGasPopover(true);
}
},
[openModal, setEditGasMode, trackEvent, supportsEIP1559],
);
const cancelTransaction = useCallback(
(event) => {
event.stopPropagation();
trackEvent({
event: 'Clicked "Cancel"',
category: MetaMetricsEventCategory.Navigation,
properties: {
action: 'Activity Log',
legacy_event: true,
},
});
if (supportsEIP1559) {
setEditGasMode(EditGasModes.cancel);
openModal('cancelSpeedUpTransaction');
} else {
setShowCancelEditGasPopover(true);
}
},
[trackEvent, openModal, setEditGasMode, supportsEIP1559],
);
2020-11-03 00:41:28 +01:00
const shouldShowSpeedUp = useShouldShowSpeedUp(
transactionGroup,
isEarliestNonce,
);
const {
title,
subtitle,
subtitleContainsOrigin,
date,
category,
primaryCurrency,
recipientAddress,
secondaryCurrency,
displayedStatusKey,
isPending,
senderAddress,
} = useTransactionDisplayData(transactionGroup);
const isSignatureReq = category === TransactionGroupCategory.signatureRequest;
const isApproval = category === TransactionGroupCategory.approval;
const isUnapproved = status === TransactionStatus.unapproved;
const isSwap = category === TransactionGroupCategory.swap;
const className = classnames('transaction-list-item', {
2020-11-03 00:41:28 +01:00
'transaction-list-item--unconfirmed':
isPending ||
[
TransactionStatus.failed,
TransactionStatus.dropped,
TransactionStatus.rejected,
].includes(displayedStatusKey),
});
const toggleShowDetails = useCallback(() => {
if (isUnapproved) {
history.push(`${CONFIRM_TRANSACTION_ROUTE}/${id}`);
return;
}
setShowDetails((prev) => !prev);
}, [isUnapproved, history, id]);
const speedUpButton = useMemo(() => {
if (!shouldShowSpeedUp || !isPending || isUnapproved) {
return null;
}
return (
<Button
type="primary"
onClick={hasCancelled ? cancelTransaction : retryTransaction}
style={hasCancelled ? { width: 'auto' } : null}
>
{hasCancelled ? t('speedUpCancellation') : t('speedUp')}
</Button>
);
}, [
shouldShowSpeedUp,
isUnapproved,
t,
isPending,
hasCancelled,
retryTransaction,
cancelTransaction,
]);
const showCancelButton = !hasCancelled && isPending && !isUnapproved;
return (
<>
<ListItem
onClick={toggleShowDetails}
className={className}
title={title}
2020-11-03 00:41:28 +01:00
icon={
<TransactionIcon category={category} status={displayedStatusKey} />
}
subtitle={
<h3>
<TransactionStatusLabel
isPending={isPending}
isEarliestNonce={isEarliestNonce}
error={err}
date={date}
status={displayedStatusKey}
/>
{subtitleContainsOrigin ? (
<SiteOrigin siteOrigin={subtitle} />
) : (
<span className="transaction-list-item__address" title={subtitle}>
{subtitle}
</span>
)}
</h3>
2020-11-03 00:41:28 +01:00
}
rightContent={
!isSignatureReq &&
!isApproval && (
<>
<h2
title={primaryCurrency}
className="transaction-list-item__primary-currency"
>
{primaryCurrency}
</h2>
<h3 className="transaction-list-item__secondary-currency">
{secondaryCurrency}
</h3>
</>
)
}
>
<div className="transaction-list-item__pending-actions">
{speedUpButton}
{showCancelButton && (
<CancelButton
transaction={transactionGroup.primaryTransaction}
cancelTransaction={cancelTransaction}
/>
)}
</div>
</ListItem>
{showDetails && (
<TransactionListItemDetails
title={title}
onClose={toggleShowDetails}
transactionGroup={transactionGroup}
primaryCurrency={primaryCurrency}
senderAddress={senderAddress}
recipientAddress={recipientAddress}
onRetry={retryTransaction}
showRetry={status === TransactionStatus.failed && !isSwap}
showSpeedUp={shouldShowSpeedUp}
isEarliestNonce={isEarliestNonce}
onCancel={cancelTransaction}
showCancel={isPending && !hasCancelled}
Feature: Transaction Insights (#12881) * integration for tx decoding confirmation and history view * upgrading @truffle/decoder to latest release 5.1.0 * Update acorn and colors patches * feat: remove redundant styling * feat: basic integration for nickname components * feat: wiring functionality of adding new nickname * feat: wire functionality of showing nickname modal * feat: link the nickname popover with add/update popover * feat: moving forward with address nicknames integration * feat: fixing a bug related to passing chainId in addressBook * feat: populating memo prop in addressbook entry * feat: add explorer link * feat: bug fixing update nickname component * feat: fix proptypes * feat: adding tooltip for copying nickname address * featL fix styling for tx-details page * feat: optimize code for error handling * feat: limiting transaction decoding to tx with data * feat: remove tree UI component * feat: adding request to check for tx decoding supported networks * feat: showing data hex component * feat: fix react warnings * feat: remove extra margin in tx decoding * Remove unused package @truffle/source-map-utils * Ensure messages get translated * feat: link tx-decoding addresses with nicknames * Omit value for boolean attributes * Fix props reading in CopyRawData * fix: fixing issue with transaltion * Fix lint errors in TransactionDecoding - Remove unused import - Reorder imports - Address conflict between caught `error` and error state flag by renaming state flag to `hasError` - Fix requestUrl identifier casing and use of template string - Ensure `useEffect` gets passed the deps it needs - Add scope braces around case statement where it's needed - Omit literal `true` for boolean jsx attribute - Refactor nested ternary as `if` statements * fix: revert fetchWithCache modifications * Fix linting for TransactionListItemDetails - Remove unused import - Fix import spacing - Remove unused prop dereference - Fix string interpolation for translated From/To * Moving to popover pattern * fix: sass color variable * Omit value for boolean attribute * Remove changes from modal.js * fix: refactor nickname popovers * Ensure const gets declared before it's used * Fix linting for ConfirmTransactionBase - Remove unused prop chainId - Stop destructuring an unused field * fix: refactor usage of nicknames popovers in send-content-container * fix: remove extra prop updateAccountNicknameModal * fix: refactor code for address.component * fix: remove extra tooltip * Ensure NicknamePopovers always returns component * Fix linting for NicknamePopover component - Fix useCallback deps - Switch ternary to logical-or * Fix linting for SenderToRecipient ... by fixing import order * Remove unused addressCopied state * Delete empty file * fix: remove sender-to-recipient.container * fix: refactor usage of nickname popovers in confirm-page-container * fix: bug related to state variable * Stylelint fix * Lint fix * Change "Total Amount" to "Total" * Lint fix locales * Update address-book.spec.js * e2e test update * Update e2e tests * Fix issue where absence of function params in data hex tab would result in rendering a string * Fix border radius, and width and height in small notification windows, of the update-nickname-popover * Remove fake await * Clean up * Clean up Co-authored-by: Alaa Hadad <alaahd@Alaas-MacBook-M1-Pro-14-inch.local> Co-authored-by: Dan Miller <danjm.com@gmail.com> Co-authored-by: g. nicholas d'andrea <gnidan@trufflesuite.com>
2021-12-01 18:22:08 +01:00
transactionStatus={() => (
<TransactionStatusLabel
Feature: Transaction Insights (#12881) * integration for tx decoding confirmation and history view * upgrading @truffle/decoder to latest release 5.1.0 * Update acorn and colors patches * feat: remove redundant styling * feat: basic integration for nickname components * feat: wiring functionality of adding new nickname * feat: wire functionality of showing nickname modal * feat: link the nickname popover with add/update popover * feat: moving forward with address nicknames integration * feat: fixing a bug related to passing chainId in addressBook * feat: populating memo prop in addressbook entry * feat: add explorer link * feat: bug fixing update nickname component * feat: fix proptypes * feat: adding tooltip for copying nickname address * featL fix styling for tx-details page * feat: optimize code for error handling * feat: limiting transaction decoding to tx with data * feat: remove tree UI component * feat: adding request to check for tx decoding supported networks * feat: showing data hex component * feat: fix react warnings * feat: remove extra margin in tx decoding * Remove unused package @truffle/source-map-utils * Ensure messages get translated * feat: link tx-decoding addresses with nicknames * Omit value for boolean attributes * Fix props reading in CopyRawData * fix: fixing issue with transaltion * Fix lint errors in TransactionDecoding - Remove unused import - Reorder imports - Address conflict between caught `error` and error state flag by renaming state flag to `hasError` - Fix requestUrl identifier casing and use of template string - Ensure `useEffect` gets passed the deps it needs - Add scope braces around case statement where it's needed - Omit literal `true` for boolean jsx attribute - Refactor nested ternary as `if` statements * fix: revert fetchWithCache modifications * Fix linting for TransactionListItemDetails - Remove unused import - Fix import spacing - Remove unused prop dereference - Fix string interpolation for translated From/To * Moving to popover pattern * fix: sass color variable * Omit value for boolean attribute * Remove changes from modal.js * fix: refactor nickname popovers * Ensure const gets declared before it's used * Fix linting for ConfirmTransactionBase - Remove unused prop chainId - Stop destructuring an unused field * fix: refactor usage of nicknames popovers in send-content-container * fix: remove extra prop updateAccountNicknameModal * fix: refactor code for address.component * fix: remove extra tooltip * Ensure NicknamePopovers always returns component * Fix linting for NicknamePopover component - Fix useCallback deps - Switch ternary to logical-or * Fix linting for SenderToRecipient ... by fixing import order * Remove unused addressCopied state * Delete empty file * fix: remove sender-to-recipient.container * fix: refactor usage of nickname popovers in confirm-page-container * fix: bug related to state variable * Stylelint fix * Lint fix * Change "Total Amount" to "Total" * Lint fix locales * Update address-book.spec.js * e2e test update * Update e2e tests * Fix issue where absence of function params in data hex tab would result in rendering a string * Fix border radius, and width and height in small notification windows, of the update-nickname-popover * Remove fake await * Clean up * Clean up Co-authored-by: Alaa Hadad <alaahd@Alaas-MacBook-M1-Pro-14-inch.local> Co-authored-by: Dan Miller <danjm.com@gmail.com> Co-authored-by: g. nicholas d'andrea <gnidan@trufflesuite.com>
2021-12-01 18:22:08 +01:00
isPending={isPending}
isEarliestNonce={isEarliestNonce}
error={err}
date={date}
status={displayedStatusKey}
statusOnly
/>
)}
/>
)}
{!supportsEIP1559 && showRetryEditGasPopover && (
<EditGasPopover
onClose={() => setShowRetryEditGasPopover(false)}
mode={EditGasModes.speedUp}
transaction={transactionGroup.primaryTransaction}
/>
)}
{!supportsEIP1559 && showCancelEditGasPopover && (
<EditGasPopover
onClose={() => setShowCancelEditGasPopover(false)}
mode={EditGasModes.cancel}
transaction={transactionGroup.primaryTransaction}
/>
)}
</>
);
}
TransactionListItemInner.propTypes = {
transactionGroup: PropTypes.object.isRequired,
isEarliestNonce: PropTypes.bool,
setEditGasMode: PropTypes.func,
};
const TransactionListItem = (props) => {
const { transactionGroup } = props;
const [editGasMode, setEditGasMode] = useState();
const transaction = transactionGroup.primaryTransaction;
const supportsEIP1559 =
useSelector(checkNetworkAndAccountSupports1559) &&
!isLegacyTransaction(transaction?.txParams);
return (
<GasFeeContextProvider
transaction={transactionGroup.primaryTransaction}
editGasMode={editGasMode}
>
<TransactionModalContextProvider>
<TransactionListItemInner {...props} setEditGasMode={setEditGasMode} />
{supportsEIP1559 && (
<>
<CancelSpeedupPopover />
<EditGasFeePopover />
<AdvancedGasFeePopover />
</>
)}
</TransactionModalContextProvider>
</GasFeeContextProvider>
);
};
TransactionListItem.propTypes = {
transactionGroup: PropTypes.object.isRequired,
};
export default TransactionListItem;