1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-10-23 03:36:18 +02:00
metamask-extension/ui/pages/import-token/import-token.component.js

543 lines
15 KiB
JavaScript
Raw Normal View History

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getTokenTrackerLink } from '@metamask/etherscan-link';
import contractMap from '@metamask/contract-metadata';
import ZENDESK_URLS from '../../helpers/constants/zendesk-url';
import {
checkExistingAddresses,
getURLHostName,
} from '../../helpers/utils/util';
import { tokenInfoGetter } from '../../helpers/utils/token-util';
import {
ADD_COLLECTIBLE_ROUTE,
CONFIRM_IMPORT_TOKEN_ROUTE,
EXPERIMENTAL_ROUTE,
} from '../../helpers/constants/routes';
import TextField from '../../components/ui/text-field';
import PageContainer from '../../components/ui/page-container';
import { Tabs, Tab } from '../../components/ui/tabs';
import { addHexPrefix } from '../../../app/scripts/lib/util';
import { isValidHexAddress } from '../../../shared/modules/hexstring-utils';
import ActionableMessage from '../../components/ui/actionable-message/actionable-message';
import Typography from '../../components/ui/typography';
import { TYPOGRAPHY, FONT_WEIGHT } from '../../helpers/constants/design-system';
import Button from '../../components/ui/button';
import TokenSearch from './token-search';
import TokenList from './token-list';
const emptyAddr = '0x0000000000000000000000000000000000000000';
2018-05-20 08:04:19 +02:00
const MIN_DECIMAL_VALUE = 0;
const MAX_DECIMAL_VALUE = 36;
class ImportToken extends Component {
2018-05-20 08:04:19 +02:00
static contextTypes = {
t: PropTypes.func,
};
2018-05-20 08:04:19 +02:00
static propTypes = {
history: PropTypes.object,
setPendingTokens: PropTypes.func,
pendingTokens: PropTypes.object,
clearPendingTokens: PropTypes.func,
tokens: PropTypes.array,
identities: PropTypes.object,
showSearchTab: PropTypes.bool.isRequired,
mostRecentOverviewPage: PropTypes.string.isRequired,
chainId: PropTypes.string,
rpcPrefs: PropTypes.object,
tokenList: PropTypes.object,
useTokenDetection: PropTypes.bool,
getTokenStandardAndDetails: PropTypes.func,
selectedAddress: PropTypes.string,
};
static defaultProps = {
tokenList: {},
};
2018-05-20 08:04:19 +02:00
state = {
customAddress: '',
customSymbol: '',
customDecimals: 0,
searchResults: [],
selectedTokens: {},
tokenSelectorError: null,
customAddressError: null,
customSymbolError: null,
customDecimalsError: null,
collectibleAddressError: null,
forceEditSymbol: false,
symbolAutoFilled: false,
decimalAutoFilled: false,
mainnetTokenWarning: null,
};
2018-05-20 08:04:19 +02:00
2020-11-03 00:41:28 +01:00
componentDidMount() {
this.tokenInfoGetter = tokenInfoGetter();
const { pendingTokens = {} } = this.props;
const pendingTokenKeys = Object.keys(pendingTokens);
2018-05-20 08:04:19 +02:00
if (pendingTokenKeys.length > 0) {
let selectedTokens = {};
let customToken = {};
2018-05-20 08:04:19 +02:00
2020-02-15 21:34:12 +01:00
pendingTokenKeys.forEach((tokenAddress) => {
const token = pendingTokens[tokenAddress];
const { isCustom } = token;
2018-05-20 08:04:19 +02:00
if (isCustom) {
customToken = { ...token };
2018-05-20 08:04:19 +02:00
} else {
selectedTokens = { ...selectedTokens, [tokenAddress]: { ...token } };
2018-05-20 08:04:19 +02:00
}
});
2018-05-20 08:04:19 +02:00
const {
address: customAddress = '',
symbol: customSymbol = '',
decimals: customDecimals = 0,
} = customToken;
2018-05-20 08:04:19 +02:00
2020-11-03 00:41:28 +01:00
this.setState({
selectedTokens,
customAddress,
customSymbol,
customDecimals,
});
2018-05-20 08:04:19 +02:00
}
}
2020-11-03 00:41:28 +01:00
handleToggleToken(token) {
const { address } = token;
const { selectedTokens = {} } = this.state;
const selectedTokensCopy = { ...selectedTokens };
2018-05-20 08:04:19 +02:00
if (address in selectedTokensCopy) {
delete selectedTokensCopy[address];
2018-05-20 08:04:19 +02:00
} else {
selectedTokensCopy[address] = token;
2018-05-20 08:04:19 +02:00
}
this.setState({
selectedTokens: selectedTokensCopy,
tokenSelectorError: null,
});
2018-05-20 08:04:19 +02:00
}
2020-11-03 00:41:28 +01:00
hasError() {
2018-05-20 08:04:19 +02:00
const {
tokenSelectorError,
customAddressError,
customSymbolError,
customDecimalsError,
collectibleAddressError,
} = this.state;
2018-05-20 08:04:19 +02:00
2020-11-03 00:41:28 +01:00
return (
tokenSelectorError ||
customAddressError ||
customSymbolError ||
customDecimalsError ||
collectibleAddressError
);
2018-05-20 08:04:19 +02:00
}
2020-11-03 00:41:28 +01:00
hasSelected() {
const { customAddress = '', selectedTokens = {} } = this.state;
return customAddress || Object.keys(selectedTokens).length > 0;
2018-05-20 08:04:19 +02:00
}
2020-11-03 00:41:28 +01:00
handleNext() {
2018-05-20 08:04:19 +02:00
if (this.hasError()) {
return;
2018-05-20 08:04:19 +02:00
}
if (!this.hasSelected()) {
this.setState({ tokenSelectorError: this.context.t('mustSelectOne') });
return;
2018-05-20 08:04:19 +02:00
}
const { setPendingTokens, history, tokenList } = this.props;
const tokenAddressList = Object.keys(tokenList).map((address) =>
address.toLowerCase(),
);
2018-05-20 08:04:19 +02:00
const {
customAddress: address,
customSymbol: symbol,
customDecimals: decimals,
selectedTokens,
} = this.state;
2018-05-20 08:04:19 +02:00
const customToken = {
address,
symbol,
decimals,
};
2018-05-20 08:04:19 +02:00
setPendingTokens({ customToken, selectedTokens, tokenAddressList });
history.push(CONFIRM_IMPORT_TOKEN_ROUTE);
2018-05-20 08:04:19 +02:00
}
2020-11-03 00:41:28 +01:00
async attemptToAutoFillTokenParams(address) {
const { tokenList } = this.props;
const { symbol = '', decimals } = await this.tokenInfoGetter(
address,
tokenList,
);
2018-05-20 23:08:45 +02:00
const symbolAutoFilled = Boolean(symbol);
const decimalAutoFilled = Boolean(decimals);
this.setState({ symbolAutoFilled, decimalAutoFilled });
this.handleCustomSymbolChange(symbol || '');
this.handleCustomDecimalsChange(decimals);
2018-05-20 08:04:19 +02:00
}
async handleCustomAddressChange(value) {
const customAddress = value.trim();
2018-05-20 08:04:19 +02:00
this.setState({
customAddress,
customAddressError: null,
collectibleAddressError: null,
2018-05-20 08:04:19 +02:00
tokenSelectorError: null,
symbolAutoFilled: false,
decimalAutoFilled: false,
mainnetTokenWarning: null,
});
2018-05-20 08:04:19 +02:00
const addressIsValid = isValidHexAddress(customAddress, {
allowNonPrefixed: false,
});
const standardAddress = addHexPrefix(customAddress).toLowerCase();
2018-05-20 08:04:19 +02:00
const isMainnetToken = Object.keys(contractMap).some(
(key) => key.toLowerCase() === customAddress.toLowerCase(),
);
const isMainnetNetwork = this.props.chainId === '0x1';
let standard;
if (addressIsValid && process.env.COLLECTIBLES_V1) {
try {
({ standard } = await this.props.getTokenStandardAndDetails(
standardAddress,
this.props.selectedAddress,
));
} catch (error) {
// ignore
}
}
const addressIsEmpty =
customAddress.length === 0 || customAddress === emptyAddr;
2018-05-20 08:04:19 +02:00
switch (true) {
case !addressIsValid && !addressIsEmpty:
2018-05-20 08:04:19 +02:00
this.setState({
customAddressError: this.context.t('invalidAddress'),
customSymbol: '',
customDecimals: 0,
customSymbolError: null,
customDecimalsError: null,
});
2018-05-20 08:04:19 +02:00
break;
case process.env.COLLECTIBLES_V1 &&
(standard === 'ERC1155' || standard === 'ERC721'):
this.setState({
collectibleAddressError: this.context.t('collectibleAddressError', [
<a
className="import-token__collectible-address-error-link"
onClick={() =>
this.props.history.push({
pathname: ADD_COLLECTIBLE_ROUTE,
state: {
addressEnteredOnImportTokensPage: this.state.customAddress,
},
})
}
key="collectibleAddressError"
>
{this.context.t('importNFTPage')}
</a>,
]),
});
break;
case isMainnetToken && !isMainnetNetwork:
this.setState({
mainnetTokenWarning: this.context.t('mainnetToken'),
customSymbol: '',
customDecimals: 0,
customSymbolError: null,
customDecimalsError: null,
});
break;
2018-05-20 08:04:19 +02:00
case Boolean(this.props.identities[standardAddress]):
this.setState({
customAddressError: this.context.t('personalAddressDetected'),
});
2018-05-20 08:04:19 +02:00
break;
2018-05-20 08:04:19 +02:00
case checkExistingAddresses(customAddress, this.props.tokens):
this.setState({
customAddressError: this.context.t('tokenAlreadyAdded'),
});
2018-05-20 08:04:19 +02:00
break;
2018-05-20 08:04:19 +02:00
default:
if (!addressIsEmpty) {
this.attemptToAutoFillTokenParams(customAddress);
2018-05-20 08:04:19 +02:00
}
}
}
2020-11-03 00:41:28 +01:00
handleCustomSymbolChange(value) {
const customSymbol = value.trim();
const symbolLength = customSymbol.length;
let customSymbolError = null;
2018-05-20 08:04:19 +02:00
2018-11-22 19:39:59 +01:00
if (symbolLength <= 0 || symbolLength >= 12) {
customSymbolError = this.context.t('symbolBetweenZeroTwelve');
2018-05-20 08:04:19 +02:00
}
this.setState({ customSymbol, customSymbolError });
2018-05-20 08:04:19 +02:00
}
2020-11-03 00:41:28 +01:00
handleCustomDecimalsChange(value) {
let customDecimals;
let customDecimalsError = null;
2018-05-20 08:04:19 +02:00
if (value) {
customDecimals = Number(value.trim());
customDecimalsError =
value < MIN_DECIMAL_VALUE || value > MAX_DECIMAL_VALUE
? this.context.t('decimalsMustZerotoTen')
: null;
} else {
customDecimals = '';
customDecimalsError = this.context.t('tokenDecimalFetchFailed');
2018-05-20 08:04:19 +02:00
}
this.setState({ customDecimals, customDecimalsError });
2018-05-20 08:04:19 +02:00
}
2020-11-03 00:41:28 +01:00
renderCustomTokenForm() {
2018-05-20 08:04:19 +02:00
const {
customAddress,
customSymbol,
customDecimals,
customAddressError,
customSymbolError,
customDecimalsError,
forceEditSymbol,
symbolAutoFilled,
decimalAutoFilled,
mainnetTokenWarning,
collectibleAddressError,
} = this.state;
2018-05-20 08:04:19 +02:00
const { chainId, rpcPrefs } = this.props;
const blockExplorerTokenLink = getTokenTrackerLink(
customAddress,
chainId,
null,
null,
{ blockExplorerUrl: rpcPrefs?.blockExplorerUrl ?? null },
);
const blockExplorerLabel = rpcPrefs?.blockExplorerUrl
? getURLHostName(blockExplorerTokenLink)
: this.context.t('etherscan');
2018-05-20 08:04:19 +02:00
return (
<div className="import-token__custom-token-form">
<ActionableMessage
message={this.context.t('fakeTokenWarning', [
<Button
type="link"
key="import-token-fake-token-warning"
className="import-token__link"
rel="noopener noreferrer"
target="_blank"
href={ZENDESK_URLS.TOKEN_SAFETY_PRACTICES}
>
{this.context.t('learnScamRisk')}
</Button>,
])}
type="warning"
withRightButton
useIcon
iconFillColor="#f8c000"
/>
2018-05-20 08:04:19 +02:00
<TextField
id="custom-address"
label={this.context.t('tokenContractAddress')}
2018-05-20 08:04:19 +02:00
type="text"
value={customAddress}
2020-02-15 21:34:12 +01:00
onChange={(e) => this.handleCustomAddressChange(e.target.value)}
error={
customAddressError || mainnetTokenWarning || collectibleAddressError
}
2018-05-20 08:04:19 +02:00
fullWidth
autoFocus
2018-05-20 08:04:19 +02:00
margin="normal"
/>
<TextField
id="custom-symbol"
2020-11-03 00:41:28 +01:00
label={
<div className="import-token__custom-symbol__label-wrapper">
<span className="import-token__custom-symbol__label">
{this.context.t('tokenSymbol')}
</span>
{symbolAutoFilled && !forceEditSymbol && (
<div
className="import-token__custom-symbol__edit"
onClick={() => this.setState({ forceEditSymbol: true })}
>
{this.context.t('edit')}
</div>
)}
</div>
2020-11-03 00:41:28 +01:00
}
2018-05-20 08:04:19 +02:00
type="text"
value={customSymbol}
2020-02-15 21:34:12 +01:00
onChange={(e) => this.handleCustomSymbolChange(e.target.value)}
2018-05-20 08:04:19 +02:00
error={customSymbolError}
fullWidth
margin="normal"
disabled={symbolAutoFilled && !forceEditSymbol}
2018-05-20 08:04:19 +02:00
/>
<TextField
id="custom-decimals"
2018-06-06 20:38:57 +02:00
label={this.context.t('decimal')}
2018-05-20 08:04:19 +02:00
type="number"
value={customDecimals}
2020-02-15 21:34:12 +01:00
onChange={(e) => this.handleCustomDecimalsChange(e.target.value)}
error={customDecimals ? customDecimalsError : null}
2018-05-20 08:04:19 +02:00
fullWidth
margin="normal"
disabled={decimalAutoFilled}
min={MIN_DECIMAL_VALUE}
max={MAX_DECIMAL_VALUE}
2018-05-20 08:04:19 +02:00
/>
{customDecimals === '' && (
<ActionableMessage
message={
<>
<Typography
variant={TYPOGRAPHY.H7}
fontWeight={FONT_WEIGHT.BOLD}
>
{this.context.t('tokenDecimalFetchFailed')}
</Typography>
<Typography
variant={TYPOGRAPHY.H7}
fontWeight={FONT_WEIGHT.NORMAL}
>
{this.context.t('verifyThisTokenDecimalOn', [
<Button
type="link"
key="import-token-verify-token-decimal"
className="import-token__link"
rel="noopener noreferrer"
target="_blank"
href={blockExplorerTokenLink}
>
{blockExplorerLabel}
</Button>,
])}
</Typography>
</>
}
type="warning"
withRightButton
className="import-token__decimal-warning"
/>
)}
2018-05-20 08:04:19 +02:00
</div>
);
2018-05-20 08:04:19 +02:00
}
2020-11-03 00:41:28 +01:00
renderSearchToken() {
const { tokenList, history, useTokenDetection } = this.props;
const { tokenSelectorError, selectedTokens, searchResults } = this.state;
2018-05-20 08:04:19 +02:00
return (
<div className="import-token__search-token">
{!useTokenDetection && (
<ActionableMessage
message={this.context.t('tokenDetectionAnnouncement', [
<Button
type="link"
key="token-detection-announcement"
className="import-token__link"
onClick={() => history.push(EXPERIMENTAL_ROUTE)}
>
{this.context.t('enableFromSettings')}
</Button>,
])}
withRightButton
useIcon
iconFillColor="#037DD6"
className="import-token__token-detection-announcement"
/>
)}
2018-05-20 08:04:19 +02:00
<TokenSearch
2020-11-03 00:41:28 +01:00
onSearch={({ results = [] }) =>
this.setState({ searchResults: results })
}
2018-05-20 08:04:19 +02:00
error={tokenSelectorError}
tokenList={tokenList}
2018-05-20 08:04:19 +02:00
/>
<div className="import-token__token-list">
2018-05-20 08:04:19 +02:00
<TokenList
results={searchResults}
selectedTokens={selectedTokens}
2020-02-15 21:34:12 +01:00
onToggleToken={(token) => this.handleToggleToken(token)}
2018-05-20 08:04:19 +02:00
/>
</div>
</div>
);
2018-05-20 08:04:19 +02:00
}
2020-11-03 00:41:28 +01:00
renderTabs() {
const { showSearchTab } = this.props;
const tabs = [];
if (showSearchTab) {
tabs.push(
<Tab name={this.context.t('search')} key="search-tab">
{this.renderSearchToken()}
</Tab>,
);
}
tabs.push(
<Tab name={this.context.t('customToken')} key="custom-tab">
{this.renderCustomTokenForm()}
</Tab>,
);
return <Tabs>{tabs}</Tabs>;
2018-07-19 02:47:01 +02:00
}
2020-11-03 00:41:28 +01:00
render() {
const { history, clearPendingTokens, mostRecentOverviewPage } = this.props;
2018-05-20 08:04:19 +02:00
return (
2018-07-19 02:47:01 +02:00
<PageContainer
title={this.context.t('importTokensCamelCase')}
2018-07-19 02:47:01 +02:00
tabsComponent={this.renderTabs()}
onSubmit={() => this.handleNext()}
hideCancel
disabled={Boolean(this.hasError()) || !this.hasSelected()}
onClose={() => {
clearPendingTokens();
history.push(mostRecentOverviewPage);
2018-07-19 02:47:01 +02:00
}}
/>
);
2018-05-20 08:04:19 +02:00
}
}
export default ImportToken;