1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-22 19:26:13 +02:00
metamask-extension/ui/pages/confirm-approve/confirm-approve.js

294 lines
9.7 KiB
JavaScript
Raw Normal View History

import React, { useEffect, useRef, useState, useCallback } from 'react';
import PropTypes from 'prop-types';
import { useDispatch, useSelector } from 'react-redux';
import ConfirmTransactionBase from '../confirm-transaction-base';
import { EDIT_GAS_MODES } from '../../../shared/constants/gas';
import {
showModal,
updateCustomNonce,
getNextNonce,
} from '../../store/actions';
import { calcTokenAmount } from '../../helpers/utils/token-util';
import { readAddressAsContract } from '../../../shared/modules/contract-utils';
import { GasFeeContextProvider } from '../../contexts/gasFee';
import { TransactionModalContextProvider } from '../../contexts/transaction-modal';
import {
getNativeCurrency,
isAddressLedger,
} from '../../ducks/metamask/metamask';
import {
2020-11-03 00:41:28 +01:00
getCurrentCurrency,
Permission System 2.0 (#12243) # Permission System 2.0 ## Background This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions). The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack. We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp. While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps. Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`. With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0. Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works. The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod. ## Changes in Detail First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files. - The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers). - The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers). - The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation. - Migration number 68 has been added to account for the new state changes. - The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`. Reviewers should focus their attention on the following files: - `app/scripts/` - `metamask-controller.js` - This is where most of the integration work for the new `PermissionController` occurs. Some functions that were internal to the original controller were moved here. - `controllers/permissions/` - `selectors.js` - These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details. - `specifications.js` - The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation. See the `PermissionController` readme for details. - `migrations/068.js` - The new state should be cross-referenced with the controllers that manage it. The accompanying tests should also be thoroughly reviewed. Some files may appear new but have just moved and/or been renamed: - `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js` - This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`. - `test/mocks/permissions.js` - A truncated version of `test/mocks/permission-controller.js`. Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
getSubjectMetadata,
getUseNonceField,
getCustomNonceValue,
getNextSuggestedNonce,
getCurrentChainId,
getRpcPrefsForCurrentProvider,
getIsMultiLayerFeeNetwork,
checkNetworkAndAccountSupports1559,
getEIP1559V2Enabled,
} from '../../selectors';
import { useApproveTransaction } from '../../hooks/useApproveTransaction';
import AdvancedGasFeePopover from '../../components/app/advanced-gas-fee-popover';
import EditGasFeePopover from '../../components/app/edit-gas-fee-popover';
import EditGasPopover from '../../components/app/edit-gas-popover/edit-gas-popover.component';
import Loading from '../../components/ui/loading-screen';
import { ERC20, ERC1155, ERC721 } from '../../helpers/constants/common';
import { getCustomTxParamsData } from './confirm-approve.util';
import ConfirmApproveContent from './confirm-approve-content';
const isAddressLedgerByFromAddress = (address) => (state) => {
return isAddressLedger(state, address);
Connect Ledger via WebHID (#12411) * Connect ledger via webhid if that option is available * Explicitly setting preference for webhid * Use ledgerTransportType enum instead of booleans for ledger live and webhid preferences * Use single setLEdgerTransport preference methods and property * Temp * Lint fix * Unit test fix * Remove async keyword from setLedgerTransportPreference function definition in preferences controller * Fix ledgelive setting toggle logic * Migrate useLedgerLive preference property to ledgerTransportType * Use shared constants for ledger transport type enums * Use constant for ledger usb vendor id * Use correct property to check if ledgerLive preference is set when deciding whether to ask for webhid connection * Update eth-ledger-bridge-keyring to v0.9.0 * Only show ledger live transaction helper messages if using ledger live * Only show ledger live part of tutorial if ledger live setting is on * Fix ledger related prop type errors * Explicitly use u2f enum instead of empty string as a transport type; default transport type to webhid if available; use constants for u2f and webhid * Cleanup * Wrap ledger webhid device request in try/catch * Clean up * Lint fix * Ensure user can easily connect their ledger wallet when they need to. * Fix locales * Fix/improve locales changes * Remove unused isFirefox property from confirm-transaction-base.container.js * Disable transaction and message signing confirmation if ledger webhid requires connection * Ensure translation keys for ledger connection options in settings dropdown can be properly detected by verify-locales * Drop .component from ledger-instruction-field file name * Move renderLedgerLiveStep to module scope * Remove ledgerLive from function and message names in ledger-instruction-field * Wrap ledger connection logic in ledger-instruction-field in try catch * Clean up signature-request.component.js * Check whether the signing address, and not the selected address, is a ledger account in singature-request.container * Ensure ledger instructions and webhid connection button are shown on signature-request-original signatures * Improve webhid selection handling in select-ledger-transport-type onChange handler * Move metamask redux focused ledger selectors to metamask duck * Lint fix * Use async await in checkWebHidStatusRef.current * Remove unnecessary use of ref in ledger-instruction-field.js * Lint fix * Remove unnecessary try/catch in ledger-instruction-field.js * Check if from address, not selected address, is from a ledger account in confirm-approve * Move findKeyringForAddress to metamask duck * Fix typo in function name * Ensure isEqualCaseInsensitive handles possible differences in address casing * Fix Learn More link size in advanced settings tab * Update app/scripts/migrations/066.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> * Update ui/pages/settings/advanced-tab/advanced-tab.component.test.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> * Add jsdoc comments for new selectors * Use jest.spyOn for mocking navigator in ledger webhid migration tests * Use LEDGER_TRANSPORT_TYPES values to set proptype of ledgerTransportType * Use LEDGER_TRANSPORT_TYPES values to set proptype of ledgerTransportType * Fix font size of link in ledger connection description in advanced settings * Fix return type in setLedgerTransportPreference comment * Clean up connectHardware code for webhid connection in actions.js * Update app/scripts/migrations/066.test.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> * Update ui/ducks/metamask/metamask.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> * Add migration test for when useLedgerLive is true in a browser that supports webhid * Lint fix * Fix inline-link size Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-10-21 21:17:03 +02:00
};
export default function ConfirmApprove({
assetStandard,
assetName,
userBalance,
tokenSymbol,
decimals,
tokenImage,
tokenAmount,
tokenId,
userAddress,
toAddress,
tokenAddress,
transaction,
ethTransactionTotal,
fiatTransactionTotal,
hexTransactionTotal,
}) {
const dispatch = useDispatch();
const { txParams: { data: transactionData } = {} } = transaction;
const currentCurrency = useSelector(getCurrentCurrency);
const nativeCurrency = useSelector(getNativeCurrency);
Permission System 2.0 (#12243) # Permission System 2.0 ## Background This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions). The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack. We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp. While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps. Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`. With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0. Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works. The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod. ## Changes in Detail First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files. - The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers). - The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers). - The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation. - Migration number 68 has been added to account for the new state changes. - The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`. Reviewers should focus their attention on the following files: - `app/scripts/` - `metamask-controller.js` - This is where most of the integration work for the new `PermissionController` occurs. Some functions that were internal to the original controller were moved here. - `controllers/permissions/` - `selectors.js` - These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details. - `specifications.js` - The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation. See the `PermissionController` readme for details. - `migrations/068.js` - The new state should be cross-referenced with the controllers that manage it. The accompanying tests should also be thoroughly reviewed. Some files may appear new but have just moved and/or been renamed: - `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js` - This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`. - `test/mocks/permissions.js` - A truncated version of `test/mocks/permission-controller.js`. Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
const subjectMetadata = useSelector(getSubjectMetadata);
const useNonceField = useSelector(getUseNonceField);
const nextNonce = useSelector(getNextSuggestedNonce);
const customNonceValue = useSelector(getCustomNonceValue);
const chainId = useSelector(getCurrentChainId);
const rpcPrefs = useSelector(getRpcPrefsForCurrentProvider);
const isMultiLayerFeeNetwork = useSelector(getIsMultiLayerFeeNetwork);
const networkAndAccountSupports1559 = useSelector(
checkNetworkAndAccountSupports1559,
);
const fromAddressIsLedger = useSelector(
isAddressLedgerByFromAddress(userAddress),
);
const [customPermissionAmount, setCustomPermissionAmount] = useState('');
const [submitWarning, setSubmitWarning] = useState('');
const [isContract, setIsContract] = useState(false);
const eip1559V2Enabled = useSelector(getEIP1559V2Enabled);
const supportsEIP1559V2 = eip1559V2Enabled && networkAndAccountSupports1559;
const previousTokenAmount = useRef(tokenAmount);
const {
approveTransaction,
showCustomizeGasPopover,
closeCustomizeGasPopover,
} = useApproveTransaction();
2020-11-03 00:41:28 +01:00
useEffect(() => {
if (customPermissionAmount && previousTokenAmount.current !== tokenAmount) {
setCustomPermissionAmount(tokenAmount);
2020-11-03 00:41:28 +01:00
}
previousTokenAmount.current = tokenAmount;
}, [customPermissionAmount, tokenAmount]);
const prevNonce = useRef(nextNonce);
const prevCustomNonce = useRef(customNonceValue);
useEffect(() => {
if (
prevNonce.current !== nextNonce ||
prevCustomNonce.current !== customNonceValue
) {
if (nextNonce !== null && customNonceValue > nextNonce) {
setSubmitWarning(
`Nonce is higher than suggested nonce of ${nextNonce}`,
);
} else {
setSubmitWarning('');
}
}
prevCustomNonce.current = customNonceValue;
prevNonce.current = nextNonce;
}, [customNonceValue, nextNonce]);
const checkIfContract = useCallback(async () => {
const { isContractAddress } = await readAddressAsContract(
global.eth,
toAddress,
);
setIsContract(isContractAddress);
}, [setIsContract, toAddress]);
useEffect(() => {
checkIfContract();
}, [checkIfContract]);
const { origin } = transaction;
const formattedOrigin = origin || '';
Permission System 2.0 (#12243) # Permission System 2.0 ## Background This PR migrates the extension permission system to [the new `PermissionController`](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions). The original permission system, based on [`rpc-cap`](https://github.com/MetaMask/rpc-cap), introduced [`ZCAP-LD`](https://w3c-ccg.github.io/zcap-ld/)-like permissions to our JSON-RPC stack. We used it to [implement](https://github.com/MetaMask/metamask-extension/pull/7004) what we called "LoginPerSite" in [version 7.7.0](https://github.com/MetaMask/metamask-extension/releases/tag/v7.7.0) of the extension, which enabled the user to choose which accounts, if any, should be exposed to each dapp. While that was a worthwhile feature in and of itself, we wanted a permission _system_ in order to enable everything we are going to with Snaps. Unfortunately, the original permission system was difficult to use, and necessitated the creation of the original `PermissionsController` (note the "s"), which was more or less a wrapper for `rpc-cap`. With this PR, we shake off the yoke of the original permission system, in favor of the modular, self-contained, ergonomic, and more mature permission system 2.0. Note that [the `PermissionController` readme](https://github.com/MetaMask/snaps-skunkworks/tree/main/packages/controllers/src/permissions/README.md) explains how the new permission system works. The `PermissionController` and `SubjectMetadataController` are currently shipped via `@metamask/snap-controllers`. This is a temporary state of affairs, and we'll move them to `@metamask/controllers` once they've landed in prod. ## Changes in Detail First, the changes in this PR are not as big as they seem. Roughly half of the additions in this PR are fixtures in the test for the new migration (number 68), and a significant portion of the remaining ~2500 lines are due to find-and-replace changes in other test fixtures and UI files. - The extension `PermissionsController` has been deleted, and completely replaced with the new `PermissionController` from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers). - The original `PermissionsController` "domain metadata" functionality is now managed by the new `SubjectMetadataController`, also from [`@metamask/snap-controllers`](https://www.npmjs.com/package/@metamask/snap-controllers). - The permission activity and history log controller has been renamed `PermissionLogController` and has its own top-level state key, but is otherwise functionally equivalent to the existing implementation. - Migration number 68 has been added to account for the new state changes. - The tests in `app/scripts/controllers/permissions` have been migrated from `mocha` to `jest`. Reviewers should focus their attention on the following files: - `app/scripts/` - `metamask-controller.js` - This is where most of the integration work for the new `PermissionController` occurs. Some functions that were internal to the original controller were moved here. - `controllers/permissions/` - `selectors.js` - These selectors are for `ControllerMessenger` selector subscriptions. The actual subscriptions occur in `metamask-controller.js`. See the `ControllerMessenger` implementation for details. - `specifications.js` - The caveat and permission specifications are required by the new `PermissionController`, and are used to specify the `eth_accounts` permission and its JSON-RPC method implementation. See the `PermissionController` readme for details. - `migrations/068.js` - The new state should be cross-referenced with the controllers that manage it. The accompanying tests should also be thoroughly reviewed. Some files may appear new but have just moved and/or been renamed: - `app/scripts/lib/rpc-method-middleware/handlers/request-accounts.js` - This was previously implemented in `controllers/permissions/permissionsMethodMiddleware.js`. - `test/mocks/permissions.js` - A truncated version of `test/mocks/permission-controller.js`. Co-authored-by: Mark Stacey <markjstacey@gmail.com>
2021-12-07 04:16:49 +01:00
const { iconUrl: siteImage = '' } = subjectMetadata[origin] || {};
let tokensText;
if (assetStandard === ERC20) {
tokensText = `${Number(tokenAmount)} ${tokenSymbol}`;
} else if (assetStandard === ERC721 || assetStandard === ERC1155) {
tokensText = assetName;
}
const tokenBalance = userBalance
? calcTokenAmount(userBalance, decimals).toString(10)
: '';
const customData = customPermissionAmount
? getCustomTxParamsData(transactionData, {
customPermissionAmount,
decimals,
})
: null;
return tokenSymbol === undefined && assetName === undefined ? (
<Loading />
) : (
<GasFeeContextProvider transaction={transaction}>
<ConfirmTransactionBase
toAddress={toAddress}
identiconAddress={toAddress}
showAccountInHeader
title={tokensText}
contentComponent={
<TransactionModalContextProvider>
<ConfirmApproveContent
decimals={decimals}
siteImage={siteImage}
setCustomAmount={setCustomPermissionAmount}
customTokenAmount={String(customPermissionAmount)}
tokenAmount={tokenAmount}
origin={formattedOrigin}
tokenSymbol={tokenSymbol}
tokenImage={tokenImage}
tokenBalance={tokenBalance}
tokenId={tokenId}
assetName={assetName}
assetStandard={assetStandard}
tokenAddress={tokenAddress}
showCustomizeGasModal={approveTransaction}
showEditApprovalPermissionModal={({
/* eslint-disable no-shadow */
customTokenAmount,
decimals,
origin,
setCustomAmount,
tokenAmount,
tokenBalance,
tokenSymbol,
/* eslint-enable no-shadow */
}) =>
dispatch(
showModal({
name: 'EDIT_APPROVAL_PERMISSION',
customTokenAmount,
decimals,
origin,
setCustomAmount,
tokenAmount,
tokenBalance,
tokenSymbol,
tokenId,
assetStandard,
}),
)
}
data={customData || transactionData}
toAddress={toAddress}
currentCurrency={currentCurrency}
nativeCurrency={nativeCurrency}
ethTransactionTotal={ethTransactionTotal}
fiatTransactionTotal={fiatTransactionTotal}
hexTransactionTotal={hexTransactionTotal}
useNonceField={useNonceField}
nextNonce={nextNonce}
customNonceValue={customNonceValue}
updateCustomNonce={(value) => {
dispatch(updateCustomNonce(value));
}}
getNextNonce={() => dispatch(getNextNonce())}
showCustomizeNonceModal={({
/* eslint-disable no-shadow */
useNonceField,
nextNonce,
customNonceValue,
updateCustomNonce,
getNextNonce,
/* eslint-disable no-shadow */
}) =>
dispatch(
showModal({
name: 'CUSTOMIZE_NONCE',
useNonceField,
nextNonce,
customNonceValue,
updateCustomNonce,
getNextNonce,
}),
)
}
warning={submitWarning}
txData={transaction}
fromAddressIsLedger={fromAddressIsLedger}
chainId={chainId}
rpcPrefs={rpcPrefs}
isContract={isContract}
isMultiLayerFeeNetwork={isMultiLayerFeeNetwork}
supportsEIP1559V2={supportsEIP1559V2}
/>
{showCustomizeGasPopover && !supportsEIP1559V2 && (
<EditGasPopover
onClose={closeCustomizeGasPopover}
mode={EDIT_GAS_MODES.MODIFY_IN_PLACE}
transaction={transaction}
/>
)}
2021-12-12 00:26:28 +01:00
{supportsEIP1559V2 && (
<>
<EditGasFeePopover />
<AdvancedGasFeePopover />
</>
)}
</TransactionModalContextProvider>
}
hideSenderToRecipient
customTxParamsData={customData}
/>
</GasFeeContextProvider>
);
}
ConfirmApprove.propTypes = {
assetStandard: PropTypes.string,
assetName: PropTypes.string,
tokenAddress: PropTypes.string,
userBalance: PropTypes.string,
tokenSymbol: PropTypes.string,
decimals: PropTypes.string,
tokenImage: PropTypes.string,
tokenAmount: PropTypes.string,
tokenId: PropTypes.string,
userAddress: PropTypes.string,
toAddress: PropTypes.string,
transaction: PropTypes.shape({
origin: PropTypes.string,
txParams: PropTypes.shape({
data: PropTypes.string,
to: PropTypes.string,
from: PropTypes.string,
}),
}),
ethTransactionTotal: PropTypes.string,
fiatTransactionTotal: PropTypes.string,
hexTransactionTotal: PropTypes.string,
};