Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented Default Currencies in Wallet UI (uplift to 1.34.x) #11519

Merged
merged 2 commits into from
Dec 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});

Expand Down Expand Up @@ -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); });
}
}

Expand Down Expand Up @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(() -> {
Expand Down
12 changes: 8 additions & 4 deletions components/brave_wallet/browser/asset_ratio_controller.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down Expand Up @@ -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(
Expand Down
4 changes: 3 additions & 1 deletion components/brave_wallet/browser/asset_ratio_controller.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ class AssetRatioController : public KeyedService,
const std::vector<std::string>& 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;

Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)));

Expand All @@ -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();
Expand All @@ -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)));

Expand Down Expand Up @@ -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
5 changes: 3 additions & 2 deletions components/brave_wallet/common/brave_wallet.mojom
Original file line number Diff line number Diff line change
Expand Up @@ -395,8 +395,9 @@ interface AssetRatioController {
(bool success, array<AssetPrice> values);

// Obtains the price history for a specific asset
GetPriceHistory(string asset, AssetPriceTimeframe timeframe) =>
(bool success, array<AssetTimePrice> values);
GetPriceHistory(string asset, string vs_asset,
AssetPriceTimeframe timeframe) =>
(bool success, array<AssetTimePrice> values);

// Gas estimation APIs
GetEstimatedTime(string gas_price /* decimal string in wei */) =>
Expand Down
4 changes: 3 additions & 1 deletion components/brave_wallet_ui/common/actions/wallet_actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ import {
GasEstimation1559,
ApproveERC20Params,
WalletInfoBase,
WalletInfo
WalletInfo,
DefaultCurrencies
} from '../../constants/types'

export const initialize = createAction('initialize')
Expand Down Expand Up @@ -110,3 +111,4 @@ export const autoLockMinutesChanged = createAction('autoLockMinutesChanged')
export const retryTransaction = createAction<TransactionInfo>('retryTransaction')
export const cancelTransaction = createAction<TransactionInfo>('cancelTransaction')
export const speedupTransaction = createAction<TransactionInfo>('speedupTransaction')
export const defaultCurrenciesUpdated = createAction<DefaultCurrencies>('defaultCurrenciesUpdated')
20 changes: 16 additions & 4 deletions components/brave_wallet_ui/common/async/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ import {
SetUserAssetVisiblePayloadType,
SwapParamsPayloadType,
UnlockWalletPayloadType,
// DefaultBaseCurrencyChanged,
// DefaultBaseCryptocurrencyChanged,
UpdateUnapprovedTransactionGasFieldsType,
UpdateUnapprovedTransactionSpendAllowanceType,
TransactionStatusChanged
Expand Down Expand Up @@ -156,8 +154,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
Expand Down Expand Up @@ -205,13 +208,22 @@ 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())
await store.dispatch(refreshBalances(currentNetwork))
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))
Expand Down
22 changes: 10 additions & 12 deletions components/brave_wallet_ui/common/async/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export function refreshBalances (currentNetwork: EthereumChain) {
return balanceInfo
}))
const balancesAndPrice = {
usdPrice: '',
fiatPrice: '',
balances: getBalanceReturnInfos
}
await dispatch(WalletActions.nativeAssetBalancesUpdated(balancesAndPrice))
Expand All @@ -153,13 +153,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,
Expand All @@ -168,7 +167,7 @@ export function refreshPrices () {
return balanceInfo
})
const balancesAndPrice = {
usdPrice: nativeAssetPrice,
fiatPrice: nativeAssetPrice,
balances: getBalanceReturnInfos
}

Expand All @@ -184,12 +183,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 = {
Expand All @@ -214,14 +212,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
)
}
}))
Expand Down
20 changes: 16 additions & 4 deletions components/brave_wallet_ui/common/reducers/wallet_reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ import {
WalletAccountType,
WalletState,
WalletInfoBase,
WalletInfo
WalletInfo,
DefaultCurrencies
} from '../../constants/types'
import {
ActiveOriginChanged,
Expand Down Expand Up @@ -75,7 +76,11 @@ const defaultState: WalletState = {
activeOrigin: '',
gasEstimates: undefined,
connectedAccounts: [],
isMetaMaskInstalled: false
isMetaMaskInstalled: false,
defaultCurrencies: {
fiat: '',
crypto: ''
}
}

const reducer = createReducer<WalletState>({}, defaultState)
Expand Down Expand Up @@ -165,8 +170,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()
: ''
}
})
Expand Down Expand Up @@ -434,4 +439,11 @@ reducer.on(WalletActions.refreshAccountInfo, (state: any, payload: WalletInfoBas
}
})

reducer.on(WalletActions.defaultCurrenciesUpdated, (state: any, payload: DefaultCurrencies) => {
return {
...state,
defaultCurrencies: payload
}
})

export default reducer
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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
Expand All @@ -33,6 +35,7 @@ function Buy (props: Props) {
selectedAsset,
buyAmount,
networkList,
defaultCurrencies,
onInputChange,
onSubmit,
onChangeBuyView
Expand All @@ -50,6 +53,7 @@ function Buy (props: Props) {
<StyledWrapper>
{selectedNetwork.chainId === MAINNET_CHAIN_ID ? (
<SwapInputComponent
defaultCurrencies={defaultCurrencies}
componentType='buyAmount'
onInputChange={onInputChange}
selectedAssetInputAmount={buyAmount}
Expand Down
Loading