diff --git a/android/java/org/chromium/chrome/browser/crypto_wallet/activities/AssetDetailActivity.java b/android/java/org/chromium/chrome/browser/crypto_wallet/activities/AssetDetailActivity.java index 6ea5a0294bd6..6b7a57ba8567 100644 --- a/android/java/org/chromium/chrome/browser/crypto_wallet/activities/AssetDetailActivity.java +++ b/android/java/org/chromium/chrome/browser/crypto_wallet/activities/AssetDetailActivity.java @@ -163,7 +163,7 @@ public void onClick(View v) { .setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0); RadioButton button = findViewById(checkedId); int timeframeType = Utils.getTimeframeFromRadioButtonId(checkedId); - getPriceHistory(mAssetSymbol, timeframeType); + getPriceHistory(mAssetSymbol, "usd", timeframeType); checkedTimeframeType = checkedId; }); @@ -196,10 +196,10 @@ public boolean onTouch(View v, MotionEvent event) { onInitialLayoutInflationComplete(); } - private void getPriceHistory(String asset, int timeframe) { + private void getPriceHistory(String asset, String vsAsset, int timeframe) { if (mAssetRatioController != null) { - mAssetRatioController.getPriceHistory( - asset, timeframe, (result, priceHistory) -> { chartES.setData(priceHistory); }); + mAssetRatioController.getPriceHistory(asset, vsAsset, timeframe, + (result, priceHistory) -> { chartES.setData(priceHistory); }); } } @@ -290,7 +290,7 @@ public void finishNativeInitialization() { InitKeyringController(); InitEthTxController(); InitEthJsonRpcController(); - getPriceHistory(mAssetSymbol, AssetPriceTimeframe.ONE_DAY); + getPriceHistory(mAssetSymbol, "usd", AssetPriceTimeframe.ONE_DAY); getPrice(mAssetSymbol, "btc", AssetPriceTimeframe.LIVE); setUpAccountList(); } diff --git a/android/java/org/chromium/chrome/browser/crypto_wallet/util/PortfolioHelper.java b/android/java/org/chromium/chrome/browser/crypto_wallet/util/PortfolioHelper.java index d9030c3d1b23..2ab6fe985fb2 100644 --- a/android/java/org/chromium/chrome/browser/crypto_wallet/util/PortfolioHelper.java +++ b/android/java/org/chromium/chrome/browser/crypto_wallet/util/PortfolioHelper.java @@ -259,7 +259,7 @@ public void calculateFiatHistory(Runnable runWhenDone) { pricesHistoryContexts.add(priceHistoryContext); mAssetRatioController.getPriceHistory(userAsset.symbol.toLowerCase(Locale.getDefault()), - mFiatHistoryTimeframe, priceHistoryContext); + "usd", mFiatHistoryTimeframe, priceHistoryContext); } historyMultiResponse.setWhenAllCompletedAction(() -> { diff --git a/components/brave_wallet/browser/asset_ratio_controller.cc b/components/brave_wallet/browser/asset_ratio_controller.cc index 191c21d38f93..5a3c7a7d0b10 100644 --- a/components/brave_wallet/browser/asset_ratio_controller.cc +++ b/components/brave_wallet/browser/asset_ratio_controller.cc @@ -135,12 +135,13 @@ GURL AssetRatioController::GetPriceURL( // static GURL AssetRatioController::GetPriceHistoryURL( const std::string& asset, + const std::string& vs_asset, brave_wallet::mojom::AssetPriceTimeframe timeframe) { std::string spec = base::StringPrintf( - "%sv2/history/coingecko/%s/usd/%s", + "%sv2/history/coingecko/%s/%s/%s", base_url_for_test_.is_empty() ? kAssetRatioBaseURL : base_url_for_test_.spec().c_str(), - asset.c_str(), TimeFrameKeyToString(timeframe).c_str()); + asset.c_str(), vs_asset.c_str(), TimeFrameKeyToString(timeframe).c_str()); return GURL(spec); } @@ -181,14 +182,17 @@ void AssetRatioController::OnGetPrice( void AssetRatioController::GetPriceHistory( const std::string& asset, + const std::string& vs_asset, brave_wallet::mojom::AssetPriceTimeframe timeframe, GetPriceHistoryCallback callback) { std::string asset_lower = base::ToLowerASCII(asset); + std::string vs_asset_lower = base::ToLowerASCII(vs_asset); auto internal_callback = base::BindOnce(&AssetRatioController::OnGetPriceHistory, weak_ptr_factory_.GetWeakPtr(), std::move(callback)); - api_request_helper_.Request("GET", GetPriceHistoryURL(asset_lower, timeframe), - "", "", true, std::move(internal_callback)); + api_request_helper_.Request( + "GET", GetPriceHistoryURL(asset_lower, vs_asset_lower, timeframe), "", "", + true, std::move(internal_callback)); } void AssetRatioController::OnGetPriceHistory( diff --git a/components/brave_wallet/browser/asset_ratio_controller.h b/components/brave_wallet/browser/asset_ratio_controller.h index 0a53545a10a0..febc8c78bb85 100644 --- a/components/brave_wallet/browser/asset_ratio_controller.h +++ b/components/brave_wallet/browser/asset_ratio_controller.h @@ -46,8 +46,9 @@ class AssetRatioController : public KeyedService, const std::vector& to_assets, brave_wallet::mojom::AssetPriceTimeframe timeframe, GetPriceCallback callback) override; - // The asset param is a string like: "bat" + // The asset and vs_asset params are strings like: "bat" void GetPriceHistory(const std::string& asset, + const std::string& vs_asset, brave_wallet::mojom::AssetPriceTimeframe timeframe, GetPriceHistoryCallback callback) override; @@ -56,6 +57,7 @@ class AssetRatioController : public KeyedService, brave_wallet::mojom::AssetPriceTimeframe timeframe); static GURL GetPriceHistoryURL( const std::string& asset, + const std::string& vs_asset, brave_wallet::mojom::AssetPriceTimeframe timeframe); void GetEstimatedTime(const std::string& gas_price, diff --git a/components/brave_wallet/browser/asset_ratio_controller_unittest.cc b/components/brave_wallet/browser/asset_ratio_controller_unittest.cc index fe9f425e09d3..64627fc7f3f2 100644 --- a/components/brave_wallet/browser/asset_ratio_controller_unittest.cc +++ b/components/brave_wallet/browser/asset_ratio_controller_unittest.cc @@ -245,7 +245,7 @@ TEST_F(AssetRatioControllerUnitTest, GetPriceHistory) { bool callback_run = false; asset_ratio_controller_->GetPriceHistory( - "bat", brave_wallet::mojom::AssetPriceTimeframe::OneDay, + "bat", "usd", brave_wallet::mojom::AssetPriceTimeframe::OneDay, base::BindOnce(&OnGetPriceHistory, &callback_run, true, std::move(expected_price_history_response))); @@ -260,7 +260,7 @@ TEST_F(AssetRatioControllerUnitTest, GetPriceHistoryError) { expected_price_history_response; bool callback_run = false; asset_ratio_controller_->GetPriceHistory( - "bat", brave_wallet::mojom::AssetPriceTimeframe::OneDay, + "bat", "usd", brave_wallet::mojom::AssetPriceTimeframe::OneDay, base::BindOnce(&OnGetPriceHistory, &callback_run, false, std::move(expected_price_history_response))); base::RunLoop().RunUntilIdle(); @@ -274,7 +274,7 @@ TEST_F(AssetRatioControllerUnitTest, GetPriceHistoryUnexpectedResponse) { bool callback_run = false; asset_ratio_controller_->GetPriceHistory( - "bat", brave_wallet::mojom::AssetPriceTimeframe::OneDay, + "bat", "usd", brave_wallet::mojom::AssetPriceTimeframe::OneDay, base::BindOnce(&OnGetPriceHistory, &callback_run, false, std::move(expected_price_history_response))); @@ -385,4 +385,39 @@ TEST_F(AssetRatioControllerUnitTest, GetGasOracleServerError) { EXPECT_TRUE(callback_run); } +TEST_F(AssetRatioControllerUnitTest, GetPriceHistoryURL) { + // Basic test + EXPECT_EQ("/v2/history/coingecko/bat/usd/1d", + AssetRatioController::GetPriceHistoryURL( + "bat", "usd", brave_wallet::mojom::AssetPriceTimeframe::OneDay) + .path()); + // Test the remaining timeframes + EXPECT_EQ("/v2/history/coingecko/eth/cad/live", + AssetRatioController::GetPriceHistoryURL( + "eth", "cad", brave_wallet::mojom::AssetPriceTimeframe::Live) + .path()); + EXPECT_EQ("/v2/history/coingecko/eth/cad/1w", + AssetRatioController::GetPriceHistoryURL( + "eth", "cad", brave_wallet::mojom::AssetPriceTimeframe::OneWeek) + .path()); + EXPECT_EQ( + "/v2/history/coingecko/eth/cad/1m", + AssetRatioController::GetPriceHistoryURL( + "eth", "cad", brave_wallet::mojom::AssetPriceTimeframe::OneMonth) + .path()); + EXPECT_EQ( + "/v2/history/coingecko/eth/cad/3m", + AssetRatioController::GetPriceHistoryURL( + "eth", "cad", brave_wallet::mojom::AssetPriceTimeframe::ThreeMonths) + .path()); + EXPECT_EQ("/v2/history/coingecko/eth/cad/1y", + AssetRatioController::GetPriceHistoryURL( + "eth", "cad", brave_wallet::mojom::AssetPriceTimeframe::OneYear) + .path()); + EXPECT_EQ("/v2/history/coingecko/eth/cad/all", + AssetRatioController::GetPriceHistoryURL( + "eth", "cad", brave_wallet::mojom::AssetPriceTimeframe::All) + .path()); +} + } // namespace brave_wallet diff --git a/components/brave_wallet/common/brave_wallet.mojom b/components/brave_wallet/common/brave_wallet.mojom index 1e3f9a453e63..eb691c9e8e45 100644 --- a/components/brave_wallet/common/brave_wallet.mojom +++ b/components/brave_wallet/common/brave_wallet.mojom @@ -276,8 +276,11 @@ interface KeyringController { interface AssetRatioController { GetPrice(array from_assets, array to_assets, AssetPriceTimeframe timeframe) => (bool success, array values); - GetPriceHistory(string asset, AssetPriceTimeframe timeframe) => - (bool success, array values); + + // Obtains the price history for a specific asset + GetPriceHistory(string asset, string vs_asset, + AssetPriceTimeframe timeframe) => + (bool success, array values); // Gas estimation APIs GetEstimatedTime(string gas_price /* decimal string in wei */) => diff --git a/components/brave_wallet_ui/common/actions/wallet_actions.ts b/components/brave_wallet_ui/common/actions/wallet_actions.ts index 9199df705bfc..527a046df450 100644 --- a/components/brave_wallet_ui/common/actions/wallet_actions.ts +++ b/components/brave_wallet_ui/common/actions/wallet_actions.ts @@ -43,7 +43,8 @@ import { GasEstimation1559, ApproveERC20Params, WalletInfoBase, - WalletInfo + WalletInfo, + DefaultCurrencies } from '../../constants/types' export const initialize = createAction('initialize') @@ -110,3 +111,4 @@ export const autoLockMinutesChanged = createAction('autoLockMinutesChanged') export const retryTransaction = createAction('retryTransaction') export const cancelTransaction = createAction('cancelTransaction') export const speedupTransaction = createAction('speedupTransaction') +export const defaultCurrenciesUpdated = createAction('defaultCurrenciesUpdated') diff --git a/components/brave_wallet_ui/common/async/handlers.ts b/components/brave_wallet_ui/common/async/handlers.ts index 85536c719695..4781b72b4820 100644 --- a/components/brave_wallet_ui/common/async/handlers.ts +++ b/components/brave_wallet_ui/common/async/handlers.ts @@ -16,8 +16,6 @@ import { SetUserAssetVisiblePayloadType, SwapParamsPayloadType, UnlockWalletPayloadType, - // DefaultBaseCurrencyChanged, - // DefaultBaseCryptocurrencyChanged, UpdateUnapprovedTransactionGasFieldsType, UpdateUnapprovedTransactionSpendAllowanceType, TransactionStatusChanged @@ -157,8 +155,13 @@ handler.on(WalletActions.defaultWalletChanged.getType(), async (store) => { await refreshWalletInfo(store) }) -// handler.on(WalletActions.defaultBaseCurrencyChanged.getType(), async (store, payload: DefaultBaseCurrencyChanged) => {}) -// handler.on(WalletActions.defaultBaseCryptocurrencyChanged.getType(), async (store, payload: DefaultBaseCryptocurrencyChanged) => {}) +handler.on(WalletActions.defaultBaseCurrencyChanged.getType(), async (store) => { + await refreshWalletInfo(store) +}) + +handler.on(WalletActions.defaultBaseCryptocurrencyChanged.getType(), async (store) => { + await refreshWalletInfo(store) +}) handler.on(WalletActions.lockWallet.getType(), async (store) => { const keyringController = getAPIProxy().keyringController @@ -206,6 +209,14 @@ handler.on(WalletActions.initialized.getType(), async (store: Store, payload: Wa interactionNotifier.beginWatchingForInteraction(50000, state.isWalletLocked, async () => { keyringController.notifyUserInteraction() }) + const braveWalletService = getAPIProxy().braveWalletService + const defaultFiat = await braveWalletService.getDefaultBaseCurrency() + const defualtCrypo = await braveWalletService.getDefaultBaseCryptocurrency() + const defaultCurrencies = { + fiat: defaultFiat.currency, + crypto: defualtCrypo.cryptocurrency + } + store.dispatch(WalletActions.defaultCurrenciesUpdated(defaultCurrencies)) // Fetch Balances and Prices if (!state.isWalletLocked && state.isWalletCreated) { const currentNetwork = await store.dispatch(refreshNetworkInfo()) @@ -213,6 +224,7 @@ handler.on(WalletActions.initialized.getType(), async (store: Store, payload: Wa await store.dispatch(refreshPrices()) await store.dispatch(refreshTokenPriceHistory(state.selectedPortfolioTimeline)) } + // This can be 0 when the wallet is locked if (payload.selectedAccount) { await store.dispatch(refreshTransactionHistory(payload.selectedAccount)) diff --git a/components/brave_wallet_ui/common/async/lib.ts b/components/brave_wallet_ui/common/async/lib.ts index 2f76580afb52..602836274443 100644 --- a/components/brave_wallet_ui/common/async/lib.ts +++ b/components/brave_wallet_ui/common/async/lib.ts @@ -127,7 +127,7 @@ export function refreshBalances (currentNetwork: EthereumChain) { return balanceInfo })) const balancesAndPrice = { - usdPrice: '', + fiatPrice: '', balances: getBalanceReturnInfos } await dispatch(WalletActions.nativeAssetBalancesUpdated(balancesAndPrice)) @@ -152,13 +152,12 @@ export function refreshBalances (currentNetwork: EthereumChain) { export function refreshPrices () { return async (dispatch: Dispatch, getState: () => State) => { const apiProxy = getAPIProxy() - const { wallet: { accounts, selectedPortfolioTimeline, selectedNetwork, userVisibleTokensInfo } } = getState() - + const { wallet: { accounts, selectedPortfolioTimeline, selectedNetwork, userVisibleTokensInfo, defaultCurrencies } } = getState() const { assetRatioController } = apiProxy - + const defaultFiatCurrency = defaultCurrencies.fiat.toLowerCase() // Update ETH Balances - const getNativeAssetPrice = await assetRatioController.getPrice([selectedNetwork.symbol.toLowerCase()], ['usd'], selectedPortfolioTimeline) - const nativeAssetPrice = getNativeAssetPrice.success ? getNativeAssetPrice.values.find((i) => i.toAsset === 'usd')?.price ?? '' : '' + const getNativeAssetPrice = await assetRatioController.getPrice([selectedNetwork.symbol.toLowerCase()], [defaultFiatCurrency], selectedPortfolioTimeline) + const nativeAssetPrice = getNativeAssetPrice.success ? getNativeAssetPrice.values.find((i) => i.toAsset === defaultFiatCurrency)?.price ?? '' : '' const getBalanceReturnInfos = accounts.map((account) => { const balanceInfo = { success: true, @@ -167,7 +166,7 @@ export function refreshPrices () { return balanceInfo }) const balancesAndPrice = { - usdPrice: nativeAssetPrice, + fiatPrice: nativeAssetPrice, balances: getBalanceReturnInfos } @@ -183,12 +182,11 @@ export function refreshPrices () { assetTimeframeChange: '', fromAsset: token.symbol, price: '', - toAsset: 'usd' + toAsset: defaultFiatCurrency } - const price = await assetRatioController.getPrice([token.symbol.toLowerCase()], ['usd'], selectedPortfolioTimeline) + const price = await assetRatioController.getPrice([token.symbol.toLowerCase()], [defaultFiatCurrency], selectedPortfolioTimeline) return price.success ? price.values[0] : emptyPrice })) - const getERCTokenBalanceReturnInfos = accounts.map((account) => { return account.tokens.map((token) => { const balanceInfo = { @@ -213,14 +211,14 @@ export function refreshTokenPriceHistory (selectedPortfolioTimeline: AssetPriceT const apiProxy = getAPIProxy() const { assetRatioController } = apiProxy - const { wallet: { accounts } } = getState() + const { wallet: { accounts, defaultCurrencies } } = getState() const result = await Promise.all(accounts.map(async (account) => { return Promise.all(account.tokens.filter((t) => !t.asset.isErc721).map(async (token) => { return { token: token, history: await assetRatioController.getPriceHistory( - token.asset.symbol.toLowerCase(), selectedPortfolioTimeline + token.asset.symbol.toLowerCase(), defaultCurrencies.fiat.toLowerCase(), selectedPortfolioTimeline ) } })) diff --git a/components/brave_wallet_ui/common/reducers/wallet_reducer.ts b/components/brave_wallet_ui/common/reducers/wallet_reducer.ts index 3133086b7de5..f5a20e6451af 100644 --- a/components/brave_wallet_ui/common/reducers/wallet_reducer.ts +++ b/components/brave_wallet_ui/common/reducers/wallet_reducer.ts @@ -25,7 +25,8 @@ import { WalletAccountType, WalletState, WalletInfoBase, - WalletInfo + WalletInfo, + DefaultCurrencies } from '../../constants/types' import { ActiveOriginChanged, @@ -76,7 +77,11 @@ const defaultState: WalletState = { activeOrigin: '', gasEstimates: undefined, connectedAccounts: [], - isMetaMaskInstalled: false + isMetaMaskInstalled: false, + defaultCurrencies: { + fiat: '', + crypto: '' + } } const reducer = createReducer({}, defaultState) @@ -166,8 +171,8 @@ reducer.on(WalletActions.nativeAssetBalancesUpdated, (state: any, payload: GetNa accounts.forEach((account, index) => { if (payload.balances[index].success) { accounts[index].balance = payload.balances[index].balance - accounts[index].fiatBalance = payload.usdPrice !== '' - ? formatFiatBalance(payload.balances[index].balance, state.selectedNetwork.decimals, payload.usdPrice).toString() + accounts[index].fiatBalance = payload.fiatPrice !== '' + ? formatFiatBalance(payload.balances[index].balance, state.selectedNetwork.decimals, payload.fiatPrice).toString() : '' } }) @@ -435,4 +440,11 @@ reducer.on(WalletActions.refreshAccountInfo, (state: any, payload: WalletInfoBas } }) +reducer.on(WalletActions.defaultCurrenciesUpdated, (state: any, payload: DefaultCurrencies) => { + return { + ...state, + defaultCurrencies: payload + } +}) + export default reducer diff --git a/components/brave_wallet_ui/components/buy-send-swap/buy/index.tsx b/components/brave_wallet_ui/components/buy-send-swap/buy/index.tsx index 8b29919beaf9..3cb7048f5664 100644 --- a/components/brave_wallet_ui/components/buy-send-swap/buy/index.tsx +++ b/components/brave_wallet_ui/components/buy-send-swap/buy/index.tsx @@ -4,7 +4,8 @@ import { BuySendSwapViewTypes, EthereumChain, ToOrFromType, - MAINNET_CHAIN_ID + MAINNET_CHAIN_ID, + DefaultCurrencies } from '../../../constants/types' import { NavButton } from '../../extension' import SwapInputComponent from '../swap-input-component' @@ -22,6 +23,7 @@ export interface Props { selectedNetwork: EthereumChain buyAmount: string networkList: EthereumChain[] + defaultCurrencies: DefaultCurrencies onSubmit: () => void onInputChange: (value: string, name: string) => void onChangeBuyView: (view: BuySendSwapViewTypes, option?: ToOrFromType) => void @@ -33,6 +35,7 @@ function Buy (props: Props) { selectedAsset, buyAmount, networkList, + defaultCurrencies, onInputChange, onSubmit, onChangeBuyView @@ -50,6 +53,7 @@ function Buy (props: Props) { {selectedNetwork.chainId === MAINNET_CHAIN_ID ? ( void onInputChange?: (value: string, name: string) => void onSelectPresetAmount?: (percent: number) => void @@ -89,6 +92,7 @@ function SwapInputComponent (props: Props) { orderExpiration, validationError, customSlippageTolerance, + defaultCurrencies, onCustomSlippageToleranceChange, onInputChange, onPaste, @@ -239,7 +243,7 @@ function SwapInputComponent (props: Props) { } {componentType === 'buyAmount' && - $ + {CurrencySymbols[defaultCurrencies?.fiat ?? 'USD']} } {!selectedAsset?.asset.isErc721 && void onSelectNetwork: (network: EthereumChain) => void onSelectAccount: (account: UserAccountType) => void @@ -34,6 +36,7 @@ function BuyTab (props: Props) { buyAmount, showHeader, assetOptions, + defaultCurrencies, onSubmit, onSelectNetwork, onSelectAccount, @@ -85,6 +88,7 @@ function BuyTab (props: Props) { /> } { - const { address, name, assetBalance, fiatBalance, assetTicker, selectedNetwork } = props + const { + address, + name, + assetBalance, + fiatBalance, + assetTicker, + selectedNetwork, + defaultCurrencies + } = props const [showAccountPopup, setShowAccountPopup] = React.useState(false) const onCopyToClipboard = async () => { await copyToClipboard(address) @@ -80,7 +89,7 @@ const PortfolioAccountItem = (props: Props) => { - {formatFiatAmountWithCommasAndDecimals(fiatBalance)} + {formatFiatAmountWithCommasAndDecimals(fiatBalance, defaultCurrencies.fiat)} {formatTokenAmountWithCommasAndDecimals(assetBalance, assetTicker)} diff --git a/components/brave_wallet_ui/components/desktop/portfolio-asset-item/index.tsx b/components/brave_wallet_ui/components/desktop/portfolio-asset-item/index.tsx index 4a6865569984..74283771f701 100644 --- a/components/brave_wallet_ui/components/desktop/portfolio-asset-item/index.tsx +++ b/components/brave_wallet_ui/components/desktop/portfolio-asset-item/index.tsx @@ -1,7 +1,7 @@ import * as React from 'react' // Options -import { ERCToken } from '../../../constants/types' +import { ERCToken, DefaultCurrencies } from '../../../constants/types' import { hexToNumber } from '../../../utils/format-balances' // Styled Components @@ -25,10 +25,17 @@ export interface Props { assetBalance: string fiatBalance: string token: ERCToken + defaultCurrencies: DefaultCurrencies } const PortfolioAssetItem = (props: Props) => { - const { assetBalance, fiatBalance, action, token } = props + const { + assetBalance, + fiatBalance, + action, + token, + defaultCurrencies + } = props const AssetIconWithPlaceholder = React.useMemo(() => { return withPlaceholderIcon(AssetIcon, { size: 'big', marginLeft: 0, marginRight: 8 }) @@ -47,7 +54,7 @@ const PortfolioAssetItem = (props: Props) => { {!token.isErc721 && - {formatFiatAmountWithCommasAndDecimals(fiatBalance)} + {formatFiatAmountWithCommasAndDecimals(fiatBalance, defaultCurrencies.fiat)} } {formatedAssetBalance} diff --git a/components/brave_wallet_ui/components/desktop/portfolio-transaction-item/index.tsx b/components/brave_wallet_ui/components/desktop/portfolio-transaction-item/index.tsx index a41fca64f206..12163b53dfde 100644 --- a/components/brave_wallet_ui/components/desktop/portfolio-transaction-item/index.tsx +++ b/components/brave_wallet_ui/components/desktop/portfolio-transaction-item/index.tsx @@ -9,12 +9,14 @@ import { TransactionInfo, TransactionStatus, TransactionType, - WalletAccountType + WalletAccountType, + DefaultCurrencies } from '../../../constants/types' // Utils import { toProperCase } from '../../../utils/string-utils' import { mojoTimeDeltaToJSDate, formatDateAsRelative } from '../../../utils/datetime-utils' +import { formatFiatAmountWithCommasAndDecimals } from '../../../utils/format-prices' // Hooks import { useTransactionParser } from '../../../common/hooks' @@ -57,6 +59,7 @@ export interface Props { visibleTokens: ERCToken[] transactionSpotPrices: AssetPrice[] displayAccountName: boolean + defaultCurrencies: DefaultCurrencies onSelectAccount: (account: WalletAccountType) => void onSelectAsset: (asset: ERCToken) => void onRetryTransaction: (transaction: TransactionInfo) => void @@ -73,6 +76,7 @@ const PortfolioTransactionItem = (props: Props) => { transactionSpotPrices, displayAccountName, accounts, + defaultCurrencies, onSelectAccount, onSelectAsset, onRetryTransaction, @@ -309,15 +313,15 @@ const PortfolioTransactionItem = (props: Props) => { - {/*We need to return a Transaction Time Stamp to calculate Fiat value here*/}${transactionDetails.fiatValue} + {/* We need to return a Transaction Time Stamp to calculate Fiat value here */}{formatFiatAmountWithCommasAndDecimals(transactionDetails.fiatValue, defaultCurrencies.fiat)} {transactionDetails.nativeCurrencyTotal} {selectedNetwork.symbol} - Transaction fee + {getLocale('braveWalletAllowSpendTransactionFee')} {transactionDetails.gasFee} {selectedNetwork.symbol} - ${transactionDetails.gasFeeFiat} + {formatFiatAmountWithCommasAndDecimals(transactionDetails.gasFeeFiat, defaultCurrencies.fiat)} } > diff --git a/components/brave_wallet_ui/components/desktop/views/accounts/index.tsx b/components/brave_wallet_ui/components/desktop/views/accounts/index.tsx index c80549560751..39e57d05064e 100644 --- a/components/brave_wallet_ui/components/desktop/views/accounts/index.tsx +++ b/components/brave_wallet_ui/components/desktop/views/accounts/index.tsx @@ -8,7 +8,8 @@ import { EthereumChain, ERCToken, AssetPrice, - TransactionInfo + TransactionInfo, + DefaultCurrencies } from '../../../../constants/types' import { reduceAddress } from '../../../../utils/reduce-address' import { copyToClipboard } from '../../../../utils/copy-to-clipboard' @@ -64,6 +65,7 @@ export interface Props { userVisibleTokensInfo: ERCToken[] transactionSpotPrices: AssetPrice[] selectedAccount: WalletAccountType | undefined + defaultCurrencies: DefaultCurrencies onViewPrivateKey: (address: string, isDefault: boolean) => void onDoneViewingPrivateKey: () => void toggleNav: () => void @@ -88,6 +90,7 @@ function Accounts (props: Props) { transactionSpotPrices, userVisibleTokensInfo, selectedAccount, + defaultCurrencies, goBack, onSelectAccount, onSelectAsset, @@ -271,6 +274,7 @@ function Accounts (props: Props) { {selectedAccount.tokens.filter((token) => !token.asset.isErc721).map((item) => {erc271Tokens?.map((item) => {transactionList.map((transaction) => void onRemoveUserAsset: (token: ERCToken) => void onOpenWalletSettings: () => void + defaultCurrencies: DefaultCurrencies addUserAssetError: boolean hasImportError: boolean transactionSpotPrices: AssetPrice[] @@ -67,8 +69,8 @@ export interface Props { selectedPortfolioTimeline: AssetPriceTimeframe portfolioPriceHistory: PriceDataObjectType[] selectedAssetPriceHistory: PriceDataObjectType[] - selectedUSDAssetPrice: AssetPrice | undefined - selectedBTCAssetPrice: AssetPrice | undefined + selectedAssetFiatPrice: AssetPrice | undefined + selectedAssetCryptoPrice: AssetPrice | undefined selectedAsset: ERCToken | undefined portfolioBalance: string transactions: AccountTransactions @@ -110,6 +112,7 @@ const CryptoView = (props: Props) => { onOpenWalletSettings, onShowAddModal, onHideAddModal, + defaultCurrencies, defaultWallet, addUserAssetError, hasImportError, @@ -129,8 +132,8 @@ const CryptoView = (props: Props) => { selectedAsset, portfolioBalance, transactions, - selectedUSDAssetPrice, - selectedBTCAssetPrice, + selectedAssetFiatPrice, + selectedAssetCryptoPrice, isLoading, showAddModal, isFetchingPortfolioPriceHistory, @@ -235,8 +238,8 @@ const CryptoView = (props: Props) => { onLockWallet={onLockWallet} /> {(defaultWallet !== DefaultWallet.BraveWallet && - (defaultWallet !== DefaultWallet.BraveWalletPreferExtension || (defaultWallet === DefaultWallet.BraveWalletPreferExtension && isMetaMaskInstalled))) && - showDefaultWalletBanner && + (defaultWallet !== DefaultWallet.BraveWalletPreferExtension || (defaultWallet === DefaultWallet.BraveWalletPreferExtension && isMetaMaskInstalled))) && + showDefaultWalletBanner && { { portfolioBalance={portfolioBalance} portfolioPriceHistory={portfolioPriceHistory} transactions={transactions} - selectedUSDAssetPrice={selectedUSDAssetPrice} - selectedBTCAssetPrice={selectedBTCAssetPrice} + selectedAssetFiatPrice={selectedAssetFiatPrice} + selectedAssetCryptoPrice={selectedAssetCryptoPrice} userAssetList={userAssetList} isLoading={isLoading} selectedNetwork={selectedNetwork} @@ -295,6 +299,7 @@ const CryptoView = (props: Props) => { void onSetUserAssetVisible: (token: ERCToken, isVisible: boolean) => void onRemoveUserAsset: (token: ERCToken) => void + defaultCurrencies: DefaultCurrencies addUserAssetError: boolean selectedNetwork: EthereumChain networkList: EthereumChain[] @@ -90,8 +93,8 @@ export interface Props { selectedTimeline: AssetPriceTimeframe selectedPortfolioTimeline: AssetPriceTimeframe selectedAsset: ERCToken | undefined - selectedUSDAssetPrice: AssetPrice | undefined - selectedBTCAssetPrice: AssetPrice | undefined + selectedAssetFiatPrice: AssetPrice | undefined + selectedAssetCryptoPrice: AssetPrice | undefined selectedAssetPriceHistory: PriceDataObjectType[] portfolioPriceHistory: PriceDataObjectType[] portfolioBalance: string @@ -118,14 +121,15 @@ const Portfolio = (props: Props) => { onAddUserAsset, onSetUserAssetVisible, onRemoveUserAsset, + defaultCurrencies, addUserAssetError, userVisibleTokensInfo, selectedNetwork, fullAssetList, portfolioPriceHistory, selectedAssetPriceHistory, - selectedUSDAssetPrice, - selectedBTCAssetPrice, + selectedAssetFiatPrice, + selectedAssetCryptoPrice, selectedTimeline, selectedPortfolioTimeline, accounts, @@ -301,7 +305,7 @@ const Portfolio = (props: Props) => { {!selectedAsset ? ( <> - {fullPortfolioFiatBalance !== '' ? '$' : ''}{hoverBalance || fullPortfolioFiatBalance} + {fullPortfolioFiatBalance !== '' ? CurrencySymbols[defaultCurrencies.fiat] : ''}{hoverBalance || fullPortfolioFiatBalance} ) : ( @@ -311,17 +315,17 @@ const Portfolio = (props: Props) => { {selectedAsset.name} {getLocale('braveWalletPrice')} ({selectedAsset.symbol}) - ${hoverPrice ? hoverPrice : selectedUSDAssetPrice ? formatWithCommasAndDecimals(selectedUSDAssetPrice.price) : 0.00} - - - {selectedUSDAssetPrice ? Number(selectedUSDAssetPrice.assetTimeframeChange).toFixed(2) : 0.00}% + {CurrencySymbols[defaultCurrencies.fiat]}{hoverPrice || (selectedAssetFiatPrice ? formatWithCommasAndDecimals(selectedAssetFiatPrice.price) : 0.00)} + + + {selectedAssetFiatPrice ? Number(selectedAssetFiatPrice.assetTimeframeChange).toFixed(2) : 0.00}% - {selectedBTCAssetPrice ? selectedBTCAssetPrice.price : ''} BTC + {selectedAssetCryptoPrice ? selectedAssetCryptoPrice.price : ''} {defaultCurrencies.crypto} )} { <> {getLocale('braveWalletAccounts')} - {formatFiatAmountWithCommasAndDecimals(fullAssetBalances?.fiatBalance ?? '')} {formatedFullAssetBalance} + {formatFiatAmountWithCommasAndDecimals(fullAssetBalances?.fiatBalance ?? '', defaultCurrencies.fiat)} {formatedFullAssetBalance} {accounts.map((account) => { <> {selectedAssetTransactions.map((transaction: TransactionInfo) => { {filteredAssetList.filter((asset) => !asset.asset.isErc721).map((item) => { {erc271Tokens.map((item) => void onConfirm: () => void onReject: () => void @@ -106,6 +108,7 @@ function ConfirmTransactionPanel (props: Props) { transactionsQueueLength, transactionQueueNumber, fullTokenList, + defaultCurrencies, onQueueNextTransction, onConfirm, onReject, @@ -314,7 +317,7 @@ function ConfirmTransactionPanel (props: Props) { {transactionInfo.txType !== TransactionType.ERC721TransferFrom && transactionInfo.txType !== TransactionType.ERC721SafeTransferFrom && - ${formatWithCommasAndDecimals(transactionDetails.fiatValue)} + {formatFiatAmountWithCommasAndDecimals(transactionDetails.fiatValue, defaultCurrencies.fiat)} } )} @@ -345,7 +348,7 @@ function ConfirmTransactionPanel (props: Props) { hasError={transactionDetails.insufficientFundsError} > {transactionDetails.insufficientFundsError ? `${getLocale('braveWalletSwapInsufficientBalance')} ` : ''} - ${formatWithCommasAndDecimals(transactionDetails.gasFeeFiat)} + {formatFiatAmountWithCommasAndDecimals(transactionDetails.gasFeeFiat, defaultCurrencies.fiat)} @@ -373,7 +376,7 @@ function ConfirmTransactionPanel (props: Props) { {getLocale('braveWalletAllowSpendEditButton')} {formatWithCommasAndDecimals(transactionDetails.gasFee)} {selectedNetwork.symbol} - ${formatWithCommasAndDecimals(transactionDetails.gasFeeFiat)} + {formatFiatAmountWithCommasAndDecimals(transactionDetails.gasFeeFiat, defaultCurrencies.fiat)} @@ -394,7 +397,7 @@ function ConfirmTransactionPanel (props: Props) { {transactionDetails.insufficientFundsError ? `${getLocale('braveWalletSwapInsufficientBalance')} ` : ''} - ${formatWithCommasAndDecimals(transactionDetails.fiatTotal)} + {formatFiatAmountWithCommasAndDecimals(transactionDetails.fiatTotal, defaultCurrencies.fiat)} diff --git a/components/brave_wallet_ui/components/extension/connected-panel/index.tsx b/components/brave_wallet_ui/components/extension/connected-panel/index.tsx index ef57cbfbee94..9a5acb74963f 100644 --- a/components/brave_wallet_ui/components/extension/connected-panel/index.tsx +++ b/components/brave_wallet_ui/components/extension/connected-panel/index.tsx @@ -41,7 +41,8 @@ import { EthereumChain, BuySupportedChains, SwapSupportedChains, - WalletOrigin + WalletOrigin, + DefaultCurrencies } from '../../../constants/types' import { create, background } from 'ethereum-blockies' import { getLocale } from '../../../../common/locale' @@ -51,13 +52,23 @@ export interface Props { selectedNetwork: EthereumChain isConnected: boolean activeOrigin: string + defaultCurrencies: DefaultCurrencies navAction: (path: PanelTypes) => void onLockWallet: () => void onOpenSettings: () => void } const ConnectedPanel = (props: Props) => { - const { onLockWallet, onOpenSettings, isConnected, navAction, selectedAccount, selectedNetwork, activeOrigin } = props + const { + onLockWallet, + onOpenSettings, + isConnected, + navAction, + selectedAccount, + selectedNetwork, + activeOrigin, + defaultCurrencies + } = props const [showMore, setShowMore] = React.useState(false) const navigate = (path: PanelTypes) => () => { @@ -154,7 +165,7 @@ const ConnectedPanel = (props: Props) => { {formatedAssetBalanceWithDecimals} - {formatFiatAmountWithCommasAndDecimals(selectedAccount.fiatBalance)} + {formatFiatAmountWithCommasAndDecimals(selectedAccount.fiatBalance, defaultCurrencies.fiat)} {hideMainComponents && void onSubmitBuy: (asset: AccountAssetOptionType) => void onSubmitSend: () => void @@ -104,6 +106,7 @@ function BuySendSwap (props: Props) { isFetchingSwapQuote, isSwapSubmitDisabled, customSlippageTolerance, + defaultCurrencies, onCustomSlippageToleranceChange, onSubmitBuy, onSubmitSend, @@ -222,6 +225,7 @@ function BuySendSwap (props: Props) { } {selectedTab === 'buy' && { const { + defaultCurrencies, hasImportError, userVisibleTokensInfo, transactionSpotPrices, @@ -97,8 +100,8 @@ const CryptoStoryView = (props: Props) => { selectedAsset, portfolioBalance, transactions, - selectedUSDAssetPrice, - selectedBTCAssetPrice, + selectedAssetFiatPrice, + selectedAssetCryptoPrice, isLoading, showAddModal, isFetchingPortfolioPriceHistory, @@ -262,6 +265,7 @@ const CryptoStoryView = (props: Props) => { } {selectedTab === 'portfolio' && { portfolioBalance={portfolioBalance} portfolioPriceHistory={portfolioPriceHistory} transactions={transactions} - selectedUSDAssetPrice={selectedUSDAssetPrice} - selectedBTCAssetPrice={selectedBTCAssetPrice} + selectedAssetFiatPrice={selectedAssetFiatPrice} + selectedAssetCryptoPrice={selectedAssetCryptoPrice} userAssetList={userAssetList} isLoading={isLoading} selectedNetwork={selectedNetwork} @@ -298,6 +302,7 @@ const CryptoStoryView = (props: Props) => { } {selectedTab === 'accounts' && {/* ) : ( { const transactionInfo: TransactionInfo = { @@ -171,6 +176,7 @@ export const _ConfirmTransaction = () => { return ( { <> {selectedPanel === 'main' ? ( { } {selectedPanel === 'buy' && { describe('Check Formating with Commas and Decimals for Fiat', () => { test('Value was empty, should return an empty string', () => { const value = '' - expect(formatFiatAmountWithCommasAndDecimals(value)).toEqual('') + expect(formatFiatAmountWithCommasAndDecimals(value, 'USD')).toEqual('') }) - test('Value is 0 should return $0.00', () => { + test('USD Value is 0 should return $0.00', () => { const value = '0' - expect(formatFiatAmountWithCommasAndDecimals(value)).toEqual('$0.00') + expect(formatFiatAmountWithCommasAndDecimals(value, 'USD')).toEqual('$0.00') + }) + + test('RUB Value is 0 should return $0.00', () => { + const value = '0' + expect(formatFiatAmountWithCommasAndDecimals(value, 'RUB')).toEqual('₽0.00') }) }) diff --git a/components/brave_wallet_ui/utils/format-prices.ts b/components/brave_wallet_ui/utils/format-prices.ts index 589350a0c19b..0b2f7c5cf15c 100644 --- a/components/brave_wallet_ui/utils/format-prices.ts +++ b/components/brave_wallet_ui/utils/format-prices.ts @@ -1,3 +1,4 @@ +import { CurrencySymbols } from './currency-symbols' const addCommas = (value: string) => { const parts = value.split('.') return ( @@ -31,15 +32,18 @@ export const formatWithCommasAndDecimals = (value: string) => { return addCommas(valueToNumber.toFixed(added)) } -export const formatFiatAmountWithCommasAndDecimals = (value: string): string => { +export const formatFiatAmountWithCommasAndDecimals = (value: string, defaultCurrency: string): string => { if (!value) { return '' } + + const currencySymbol = CurrencySymbols[defaultCurrency] + // Check to make sure a formated value is returned before showing the fiat symbol if (!formatWithCommasAndDecimals(value)) { return '' } - return '$' + formatWithCommasAndDecimals(value) + return currencySymbol + formatWithCommasAndDecimals(value) } export const formatTokenAmountWithCommasAndDecimals = (value: string, symbol: string): string => {