1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-12-12 12:47:14 +01:00
metamask-extension/ui/app/hooks/useTokenFiatAmount.js
Erik Marks 76a2a9bb8b
@metamask/eslint config@5.0.0 (#10358)
* @metamask/eslint-config@5.0.0
* Update eslintrc and prettierrc
* yarn lint:fix
2021-02-04 10:15:23 -08:00

65 lines
2.2 KiB
JavaScript

import { useMemo } from 'react';
import { useSelector } from 'react-redux';
import {
getTokenExchangeRates,
getConversionRate,
getCurrentCurrency,
getShouldShowFiat,
} from '../selectors';
import { getTokenFiatAmount } from '../helpers/utils/token-util';
/**
* Get the token balance converted to fiat and formatted for display
*
* @param {string} [tokenAddress] - The token address
* @param {string} [tokenAmount] - The token balance
* @param {string} [tokenSymbol] - The token symbol
* @param {Object} [overrides] - A configuration object that allows the caller to explicitly pass an exchange rate or
* ensure fiat is shown even if the property is not set in state.
* @param {number} [overrides.exchangeRate] - An exhchange rate to use instead of the one selected from state
* @param {boolean} [overrides.showFiat] - If truthy, ensures the fiat value is shown even if the showFiat value from state is falsey
* @param {boolean} hideCurrencySymbol Indicates whether the returned formatted amount should include the trailing currency symbol
* @return {string} - The formatted token amount in the user's chosen fiat currency
*/
export function useTokenFiatAmount(
tokenAddress,
tokenAmount,
tokenSymbol,
overrides = {},
hideCurrencySymbol,
) {
const contractExchangeRates = useSelector(getTokenExchangeRates);
const conversionRate = useSelector(getConversionRate);
const currentCurrency = useSelector(getCurrentCurrency);
const userPrefersShownFiat = useSelector(getShouldShowFiat);
const showFiat = overrides.showFiat ?? userPrefersShownFiat;
const tokenExchangeRate =
overrides.exchangeRate ?? contractExchangeRates[tokenAddress];
const formattedFiat = useMemo(
() =>
getTokenFiatAmount(
tokenExchangeRate,
conversionRate,
currentCurrency,
tokenAmount,
tokenSymbol,
true,
hideCurrencySymbol,
),
[
tokenExchangeRate,
conversionRate,
currentCurrency,
tokenAmount,
tokenSymbol,
hideCurrencySymbol,
],
);
if (!showFiat || currentCurrency.toUpperCase() === tokenSymbol) {
return undefined;
}
return formattedFiat;
}