mirror of
https://github.com/kremalicious/metamask-extension.git
synced 2024-12-01 21:57:06 +01:00
31d5c1cf22
* Version v10.18.4 * Fix default currency symbol for `wallet_addEthereumChain` + improve warnings for data that doesn't match our validation expectations (#15201) * set more appropriate default for ticker symbol when wallet_addEthereumChain is called * throw error to dapp when site suggests network with same chainId but different ticker symbol from already added network, instead of showing error and disabled notification to user * Fix Provider Tracking Metrics (#15082) * fix filetype audit (#15334) * Remove decentralized 4byte function signature registry since it contains incorrect signatures and we can't algorithmically check for best option when 4byte.directory is down (#15300) * remove decentralized 4byte function signature registry since it is griefed and we can't algorithmically check for best option when 4byte is down * add migration * remove nock of on chain registry call in getMethodDataAsync test * remove audit exclusion (#15346) * Updates `eth-lattice-keyring` to v0.10.0 (#15261) This is mainly associated with an update in GridPlus SDK and enables better strategies for fetching calldata decoder data. `eth-lattice-keyring` changes: GridPlus/eth-lattice-keyring@v0.7.3...v0.10.0 `gridplus-sdk` changes (which includes a codebase rewrite): GridPlus/gridplus-sdk@v1.2.3...v2.2.2 * Fix 'block link explorer on custom networks' (#13870) * Created a logic for the 'Add a block explorer URL' Removed unused message Message logic rollback Modified history push operation WIP: Pushing before rebasing Applied requested changes Removed unintenionally added code * Lint fix * Metrics fixed * Stop injecting provider on docs.google.com (#15459) * Fix setting of gasPrice when on non-eip 1559 networks (#15628) * Fix setting of gasPrice when on non-eip 1559 networks * Fix unit tests * Fix logic * Update ui/ducks/send/send.test.js Co-authored-by: Mark Stacey <markjstacey@gmail.com> Co-authored-by: Mark Stacey <markjstacey@gmail.com> * [GridPlus] Bumps `eth-lattice-keyring` to v0.11.0 (#15490) * [GridPlus] Bumps `gridplus-sdk` to v2.2.4 (#15561) * remove exclusions for mismatched object jsdoc type casing (#15351) * Improve `tokenId` parsing and clean up `useAssetDetails` hook (#15304) * Fix state creation in setupSentryGetStateGlobal (#15635) * filter breadcrumbs for improved clarity while debugging sentry errors (#15639) * Update v10.18.4 changelog (#15645) * Auto generated changelog * Update 10.18.4 changelog * Run lavamoat:auto * Call metrics event for wallet type selection at the right time (#15591) * Fix Sentry in LavaMoat contexts (#15672) Our Sentry setup relies upon application state, but it wasn't able to access it in LavaMoat builds because it's running in a separate Compartment. A patch has been introduced to the LavaMoat runtime to allow the root Compartment to mutate the `rootGlobals` object, which is accessible from outside the compartment as well. This lets us expose application state to our Sentry integration. * Fix Sentry deduplication of events that were never sent (#15677) The Sentry `Dedupe` integration has been filtering out our events, even when they were never sent due to our `beforeSend` handler. It was wrongly identifying them as duplicates because it has no knowledge of `beforeSend` or whether they were actually sent or not. To resolve this, the filtering we were doing in `beforeSend` has been moved to a Sentry integration. This integration is installed ahead of the `Dedupe` integration, so `Dedupe` should never find out about any events that we filter out, and thus will never consider them as sent when they were not. * Replace `lavamoat-runtime.js` patch (#15682) A patch made in #15672 was found to be unnecessary. Instead of setting a `rootGlobals` object upon construction of the root compartment, we are now creating a `sentryHooks` object in the initial top-level compartment. I hadn't realized at the time that the root compartment would inherit all properties of the initial compartment `globalThis`. This accomplishes the same goals as #15672 except without needing a patch. * Update v10.18.4 changelog * Fix lint issues * Update yarn.lock * Update `depcheck` to latest version (#15690) `depcheck` has been updated to the latest version. This version pins `@babel/parser` to v7.16.4 because of unresolved bugs in v7.16.5 that result in `depcheck` failing to parse TypeScript files correctly. We had a Yarn resolution in place to ensure `@babel/parser@7.16.4` was being used already. That resolution is no longer needed so it has been removed. This should resove the issue the dev team has been seeing lately where `yarn` and `yarn-deduplicate` disagree about the state the lockfile should be in. * Update yarn.lock * Update LavaMoat policy * deduplicate * Update LavaMoat build policy Co-authored-by: MetaMask Bot <metamaskbot@users.noreply.github.com> Co-authored-by: Alex Donesky <adonesky@gmail.com> Co-authored-by: Brad Decker <bhdecker84@gmail.com> Co-authored-by: Alex Miller <asmiller1989@gmail.com> Co-authored-by: Filip Sekulic <filip.sekulic@consensys.net> Co-authored-by: Erik Marks <25517051+rekmarks@users.noreply.github.com> Co-authored-by: Dan J Miller <danjm.com@gmail.com> Co-authored-by: Mark Stacey <markjstacey@gmail.com> Co-authored-by: seaona <54408225+seaona@users.noreply.github.com> Co-authored-by: seaona <mariona@gmx.es> Co-authored-by: PeterYinusa <peter.yinusa@consensys.net>
313 lines
9.4 KiB
JavaScript
313 lines
9.4 KiB
JavaScript
import log from 'loglevel';
|
|
import BigNumber from 'bignumber.js';
|
|
import {
|
|
conversionUtil,
|
|
multiplyCurrencies,
|
|
} from '../../../shared/modules/conversion.utils';
|
|
import { getTokenStandardAndDetails } from '../../store/actions';
|
|
import { isEqualCaseInsensitive } from '../../../shared/modules/string-utils';
|
|
import { parseStandardTokenTransactionData } from '../../../shared/modules/transaction.utils';
|
|
import { ERC20 } from '../constants/common';
|
|
import * as util from './util';
|
|
import { formatCurrency } from './confirm-tx.util';
|
|
|
|
const DEFAULT_SYMBOL = '';
|
|
|
|
async function getSymbolFromContract(tokenAddress) {
|
|
const token = util.getContractAtAddress(tokenAddress);
|
|
try {
|
|
const result = await token.symbol();
|
|
return result[0];
|
|
} catch (error) {
|
|
log.warn(
|
|
`symbol() call for token at address ${tokenAddress} resulted in error:`,
|
|
error,
|
|
);
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
async function getDecimalsFromContract(tokenAddress) {
|
|
const token = util.getContractAtAddress(tokenAddress);
|
|
|
|
try {
|
|
const result = await token.decimals();
|
|
const decimalsBN = result[0];
|
|
return decimalsBN?.toString();
|
|
} catch (error) {
|
|
log.warn(
|
|
`decimals() call for token at address ${tokenAddress} resulted in error:`,
|
|
error,
|
|
);
|
|
return undefined;
|
|
}
|
|
}
|
|
|
|
export function getTokenMetadata(tokenAddress, tokenList) {
|
|
const casedTokenList = Object.keys(tokenList).reduce((acc, base) => {
|
|
return {
|
|
...acc,
|
|
[base.toLowerCase()]: tokenList[base],
|
|
};
|
|
}, {});
|
|
return tokenAddress && casedTokenList[tokenAddress.toLowerCase()];
|
|
}
|
|
|
|
async function getSymbol(tokenAddress, tokenList) {
|
|
let symbol = await getSymbolFromContract(tokenAddress);
|
|
|
|
if (!symbol) {
|
|
const contractMetadataInfo = getTokenMetadata(tokenAddress, tokenList);
|
|
|
|
if (contractMetadataInfo) {
|
|
symbol = contractMetadataInfo.symbol;
|
|
}
|
|
}
|
|
|
|
return symbol;
|
|
}
|
|
|
|
async function getDecimals(tokenAddress, tokenList) {
|
|
let decimals = await getDecimalsFromContract(tokenAddress);
|
|
|
|
if (!decimals || decimals === '0') {
|
|
const contractMetadataInfo = getTokenMetadata(tokenAddress, tokenList);
|
|
|
|
if (contractMetadataInfo) {
|
|
decimals = contractMetadataInfo.decimals?.toString();
|
|
}
|
|
}
|
|
|
|
return decimals;
|
|
}
|
|
|
|
export async function getSymbolAndDecimals(tokenAddress, tokenList) {
|
|
let symbol, decimals;
|
|
|
|
try {
|
|
symbol = await getSymbol(tokenAddress, tokenList);
|
|
decimals = await getDecimals(tokenAddress, tokenList);
|
|
} catch (error) {
|
|
log.warn(
|
|
`symbol() and decimal() calls for token at address ${tokenAddress} resulted in error:`,
|
|
error,
|
|
);
|
|
}
|
|
|
|
return {
|
|
symbol: symbol || DEFAULT_SYMBOL,
|
|
decimals,
|
|
};
|
|
}
|
|
|
|
export function tokenInfoGetter() {
|
|
const tokens = {};
|
|
|
|
return async (address, tokenList) => {
|
|
if (tokens[address]) {
|
|
return tokens[address];
|
|
}
|
|
|
|
tokens[address] = await getSymbolAndDecimals(address, tokenList);
|
|
|
|
return tokens[address];
|
|
};
|
|
}
|
|
|
|
export function calcTokenAmount(value, decimals) {
|
|
const multiplier = Math.pow(10, Number(decimals || 0));
|
|
return new BigNumber(String(value)).div(multiplier);
|
|
}
|
|
|
|
export function calcTokenValue(value, decimals) {
|
|
const multiplier = Math.pow(10, Number(decimals || 0));
|
|
return new BigNumber(String(value)).times(multiplier);
|
|
}
|
|
|
|
/**
|
|
* Attempts to get the address parameter of the given token transaction data
|
|
* (i.e. function call) per the Human Standard Token ABI, in the following
|
|
* order:
|
|
* - The '_to' parameter, if present
|
|
* - The first parameter, if present
|
|
*
|
|
* @param {object} tokenData - ethers Interface token data.
|
|
* @returns {string | undefined} A lowercase address string.
|
|
*/
|
|
export function getTokenAddressParam(tokenData = {}) {
|
|
const value =
|
|
tokenData?.args?._to || tokenData?.args?.to || tokenData?.args?.[0];
|
|
return value?.toString().toLowerCase();
|
|
}
|
|
|
|
/**
|
|
* Gets the '_value' parameter of the given token transaction data
|
|
* (i.e function call) per the Human Standard Token ABI, if present.
|
|
*
|
|
* @param {object} tokenData - ethers Interface token data.
|
|
* @returns {string | undefined} A decimal string value.
|
|
*/
|
|
export function getTokenValueParam(tokenData = {}) {
|
|
return tokenData?.args?._value?.toString();
|
|
}
|
|
|
|
/**
|
|
* Gets either the '_tokenId' parameter or the 'id' param of the passed token transaction data.,
|
|
* These are the parsed tokenId values returned by `parseStandardTokenTransactionData` as defined
|
|
* in the ERC721 and ERC1155 ABIs from metamask-eth-abis (https://github.com/MetaMask/metamask-eth-abis/tree/main/src/abis)
|
|
*
|
|
* @param {object} tokenData - ethers Interface token data.
|
|
* @returns {string | undefined} A decimal string value.
|
|
*/
|
|
export function getTokenIdParam(tokenData = {}) {
|
|
return (
|
|
tokenData?.args?._tokenId?.toString() ?? tokenData?.args?.id?.toString()
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Gets the '_approved' parameter of the given token transaction data
|
|
* (i.e function call) per the Human Standard Token ABI, if present.
|
|
*
|
|
* @param {object} tokenData - ethers Interface token data.
|
|
* @returns {boolean | undefined} A boolean indicating whether the function is being called to approve or revoke access.
|
|
*/
|
|
export function getTokenApprovedParam(tokenData = {}) {
|
|
return tokenData?.args?._approved;
|
|
}
|
|
|
|
/**
|
|
* Get the token balance converted to fiat and optionally formatted for display
|
|
*
|
|
* @param {number} [contractExchangeRate] - The exchange rate between the current token and the native currency
|
|
* @param {number} conversionRate - The exchange rate between the current fiat currency and the native currency
|
|
* @param {string} currentCurrency - The currency code for the user's chosen fiat currency
|
|
* @param {string} [tokenAmount] - The current token balance
|
|
* @param {string} [tokenSymbol] - The token symbol
|
|
* @param {boolean} [formatted] - Whether the return value should be formatted or not
|
|
* @param {boolean} [hideCurrencySymbol] - excludes the currency symbol in the result if true
|
|
* @returns {string|undefined} The token amount in the user's chosen fiat currency, optionally formatted and localize
|
|
*/
|
|
export function getTokenFiatAmount(
|
|
contractExchangeRate,
|
|
conversionRate,
|
|
currentCurrency,
|
|
tokenAmount,
|
|
tokenSymbol,
|
|
formatted = true,
|
|
hideCurrencySymbol = false,
|
|
) {
|
|
// If the conversionRate is 0 (i.e. unknown) or the contract exchange rate
|
|
// is currently unknown, the fiat amount cannot be calculated so it is not
|
|
// shown to the user
|
|
if (
|
|
conversionRate <= 0 ||
|
|
!contractExchangeRate ||
|
|
tokenAmount === undefined
|
|
) {
|
|
return undefined;
|
|
}
|
|
|
|
const currentTokenToFiatRate = multiplyCurrencies(
|
|
contractExchangeRate,
|
|
conversionRate,
|
|
{
|
|
multiplicandBase: 10,
|
|
multiplierBase: 10,
|
|
},
|
|
);
|
|
const currentTokenInFiat = conversionUtil(tokenAmount, {
|
|
fromNumericBase: 'dec',
|
|
fromCurrency: tokenSymbol,
|
|
toCurrency: currentCurrency.toUpperCase(),
|
|
numberOfDecimals: 2,
|
|
conversionRate: currentTokenToFiatRate,
|
|
});
|
|
let result;
|
|
if (hideCurrencySymbol) {
|
|
result = formatCurrency(currentTokenInFiat, currentCurrency);
|
|
} else if (formatted) {
|
|
result = `${formatCurrency(
|
|
currentTokenInFiat,
|
|
currentCurrency,
|
|
)} ${currentCurrency.toUpperCase()}`;
|
|
} else {
|
|
result = currentTokenInFiat;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export async function getAssetDetails(
|
|
tokenAddress,
|
|
currentUserAddress,
|
|
transactionData,
|
|
existingCollectibles,
|
|
) {
|
|
const tokenData = parseStandardTokenTransactionData(transactionData);
|
|
if (!tokenData) {
|
|
throw new Error('Unable to detect valid token data');
|
|
}
|
|
|
|
// Sometimes the tokenId value is parsed as "_value" param. Not seeing this often any more, but still occasionally:
|
|
// i.e. call approve() on BAYC contract - https://etherscan.io/token/0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d#writeContract, and tokenId shows up as _value,
|
|
// not sure why since it doesn't match the ERC721 ABI spec we use to parse these transactions - https://github.com/MetaMask/metamask-eth-abis/blob/d0474308a288f9252597b7c93a3a8deaad19e1b2/src/abis/abiERC721.ts#L62.
|
|
let tokenId =
|
|
getTokenIdParam(tokenData)?.toString() ?? getTokenValueParam(tokenData);
|
|
|
|
const toAddress = getTokenAddressParam(tokenData);
|
|
|
|
let tokenDetails;
|
|
|
|
// if a tokenId is present check if there is a collectible in state matching the address/tokenId
|
|
// and avoid unnecessary network requests to query token details we already have
|
|
if (existingCollectibles?.length && tokenId) {
|
|
const existingCollectible = existingCollectibles.find(
|
|
({ address, tokenId: _tokenId }) =>
|
|
isEqualCaseInsensitive(tokenAddress, address) && _tokenId === tokenId,
|
|
);
|
|
|
|
if (existingCollectible) {
|
|
return {
|
|
toAddress,
|
|
...existingCollectible,
|
|
};
|
|
}
|
|
}
|
|
|
|
try {
|
|
tokenDetails = await getTokenStandardAndDetails(
|
|
tokenAddress,
|
|
currentUserAddress,
|
|
tokenId,
|
|
);
|
|
} catch (error) {
|
|
log.warn(error);
|
|
// if we can't determine any token standard or details return the data we can extract purely from the parsed transaction data
|
|
return { toAddress, tokenId };
|
|
}
|
|
|
|
const tokenAmount =
|
|
tokenData &&
|
|
tokenDetails?.decimals &&
|
|
calcTokenAmount(
|
|
getTokenValueParam(tokenData),
|
|
tokenDetails?.decimals,
|
|
).toString(10);
|
|
|
|
const decimals =
|
|
tokenDetails?.decimals && Number(tokenDetails.decimals?.toString(10));
|
|
|
|
if (tokenDetails?.standard === ERC20) {
|
|
tokenId = undefined;
|
|
}
|
|
|
|
// else if not a collectible already in state or standard === ERC20 return tokenDetails and tokenId
|
|
return {
|
|
tokenAmount,
|
|
toAddress,
|
|
decimals,
|
|
tokenId,
|
|
...tokenDetails,
|
|
};
|
|
}
|