1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-18 07:23:21 +01:00
metamask-extension/ui/app/helpers/utils/token-util.js

245 lines
6.6 KiB
JavaScript
Raw Normal View History

import log from 'loglevel';
import BigNumber from 'bignumber.js';
import contractMap from '@metamask/contract-metadata';
import * as util from './util';
import { conversionUtil, multiplyCurrencies } from './conversion-util';
import { formatCurrency } from './confirm-tx.util';
const casedContractMap = Object.keys(contractMap).reduce((acc, base) => {
return {
...acc,
[base.toLowerCase()]: contractMap[base],
};
}, {});
const DEFAULT_SYMBOL = '';
const DEFAULT_DECIMALS = '0';
2020-11-03 00:41:28 +01:00
async function getSymbolFromContract(tokenAddress) {
const token = util.getContractAtAddress(tokenAddress);
try {
const result = await token.symbol();
return result[0];
} catch (error) {
2020-11-03 00:41:28 +01:00
log.warn(
`symbol() call for token at address ${tokenAddress} resulted in error:`,
error,
);
return undefined;
}
}
2020-11-03 00:41:28 +01:00
async function getDecimalsFromContract(tokenAddress) {
const token = util.getContractAtAddress(tokenAddress);
try {
const result = await token.decimals();
const decimalsBN = result[0];
return decimalsBN?.toString();
} catch (error) {
2020-11-03 00:41:28 +01:00
log.warn(
`decimals() call for token at address ${tokenAddress} resulted in error:`,
error,
);
return undefined;
}
}
2020-11-03 00:41:28 +01:00
function getContractMetadata(tokenAddress) {
return tokenAddress && casedContractMap[tokenAddress.toLowerCase()];
}
2020-11-03 00:41:28 +01:00
async function getSymbol(tokenAddress) {
let symbol = await getSymbolFromContract(tokenAddress);
if (!symbol) {
const contractMetadataInfo = getContractMetadata(tokenAddress);
if (contractMetadataInfo) {
symbol = contractMetadataInfo.symbol;
}
}
return symbol;
}
2020-11-03 00:41:28 +01:00
async function getDecimals(tokenAddress) {
let decimals = await getDecimalsFromContract(tokenAddress);
if (!decimals || decimals === '0') {
const contractMetadataInfo = getContractMetadata(tokenAddress);
if (contractMetadataInfo) {
decimals = contractMetadataInfo.decimals;
}
}
return decimals;
}
2020-11-03 00:41:28 +01:00
export async function fetchSymbolAndDecimals(tokenAddress) {
let symbol, decimals;
try {
symbol = await getSymbol(tokenAddress);
decimals = await getDecimals(tokenAddress);
} catch (error) {
2020-11-03 00:41:28 +01:00
log.warn(
`symbol() and decimal() calls for token at address ${tokenAddress} resulted in error:`,
error,
);
}
return {
symbol: symbol || DEFAULT_SYMBOL,
decimals: decimals || DEFAULT_DECIMALS,
};
}
2020-11-03 00:41:28 +01:00
export async function getSymbolAndDecimals(tokenAddress, existingTokens = []) {
const existingToken = existingTokens.find(
({ address }) => tokenAddress === address,
);
if (existingToken) {
return {
symbol: existingToken.symbol,
decimals: existingToken.decimals,
};
}
2018-07-03 00:49:33 +02:00
let symbol, decimals;
try {
symbol = await getSymbol(tokenAddress);
decimals = await getDecimals(tokenAddress);
} catch (error) {
2020-11-03 00:41:28 +01:00
log.warn(
`symbol() and decimal() calls for token at address ${tokenAddress} resulted in error:`,
error,
);
}
return {
symbol: symbol || DEFAULT_SYMBOL,
decimals: decimals || DEFAULT_DECIMALS,
};
}
2020-11-03 00:41:28 +01:00
export function tokenInfoGetter() {
const tokens = {};
return async (address) => {
if (tokens[address]) {
return tokens[address];
}
tokens[address] = await getSymbolAndDecimals(address);
return tokens[address];
};
}
2020-11-03 00:41:28 +01:00
export function calcTokenAmount(value, decimals) {
const multiplier = Math.pow(10, Number(decimals || 0));
return new BigNumber(String(value)).div(multiplier);
}
2018-10-09 02:05:57 +02:00
2020-11-03 00:41:28 +01:00
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.
*/
2020-11-03 00:41:28 +01:00
export function getTokenAddressParam(tokenData = {}) {
const value = tokenData?.args?._to || tokenData?.args?.[0];
return value?.toString().toLowerCase();
2018-10-09 02:05:57 +02:00
}
/**
* 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.
*/
2020-11-03 00:41:28 +01:00
export function getTokenValueParam(tokenData = {}) {
return tokenData?.args?._value?.toString();
}
2020-11-03 00:41:28 +01:00
export function getTokenValue(tokenParams = []) {
const valueData = tokenParams.find((param) => param.name === '_value');
return valueData && valueData.value;
2020-10-06 20:28:38 +02:00
}
/**
2020-10-06 20:28:38 +02:00
* 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
2020-10-06 20:28:38 +02:00
* @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
*/
2020-11-03 00:41:28 +01:00
export function getTokenFiatAmount(
contractExchangeRate,
conversionRate,
currentCurrency,
tokenAmount,
tokenSymbol,
2020-10-06 20:28:38 +02:00
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
2020-11-03 00:41:28 +01:00
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;
2020-10-06 20:28:38 +02:00
if (hideCurrencySymbol) {
result = formatCurrency(currentTokenInFiat, currentCurrency);
2020-10-06 20:28:38 +02:00
} else if (formatted) {
2020-11-03 00:41:28 +01:00
result = `${formatCurrency(
currentTokenInFiat,
currentCurrency,
)} ${currentCurrency.toUpperCase()}`;
2020-10-06 20:28:38 +02:00
} else {
result = currentTokenInFiat;
2020-10-06 20:28:38 +02:00
}
return result;
}