Skip to content

Commit

Permalink
Merge pull request #11324 from brave/separate-balances-and-prices-cal…
Browse files Browse the repository at this point in the history
…ls-1.33.x

Separated Balances and Prices Calls (uplift to 1.33.x)
  • Loading branch information
kjozwiak authored Dec 1, 2021
2 parents 8247e14 + a3e5632 commit a2d13a4
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 33 deletions.
13 changes: 8 additions & 5 deletions components/brave_wallet_ui/common/async/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ import {
refreshTokenPriceHistory,
refreshSitePermissions,
refreshTransactionHistory,
refreshBalancesAndPrices
refreshBalances,
refreshPrices
} from './lib'
import { Store } from './types'
import InteractionNotifier from './interactionNotifier'
Expand All @@ -64,7 +65,8 @@ function getWalletState (store: Store): WalletState {

async function refreshBalancesPricesAndHistory (store: Store) {
const state = getWalletState(store)
await store.dispatch(refreshBalancesAndPrices(state.selectedNetwork))
await store.dispatch(refreshBalances(state.selectedNetwork))
await store.dispatch(refreshPrices())
await store.dispatch(refreshTokenPriceHistory(state.selectedPortfolioTimeline))
}

Expand Down Expand Up @@ -106,8 +108,8 @@ async function updateAccountInfo (store: Store) {

handler.on(WalletActions.refreshBalancesAndPrices.getType(), async (store: Store) => {
const state = getWalletState(store)

await store.dispatch(refreshBalancesAndPrices(state.selectedNetwork))
await store.dispatch(refreshBalances(state.selectedNetwork))
await store.dispatch(refreshPrices())
})

handler.on(WalletActions.initialize.getType(), async (store) => {
Expand Down Expand Up @@ -207,7 +209,8 @@ handler.on(WalletActions.initialized.getType(), async (store: Store, payload: Wa
// Fetch Balances and Prices
if (!state.isWalletLocked && state.isWalletCreated) {
const currentNetwork = await store.dispatch(refreshNetworkInfo())
await store.dispatch(refreshBalancesAndPrices(currentNetwork))
await store.dispatch(refreshBalances(currentNetwork))
await store.dispatch(refreshPrices())
await store.dispatch(refreshTokenPriceHistory(state.selectedPortfolioTimeline))
}
// This can be 0 when the wallet is locked
Expand Down
72 changes: 55 additions & 17 deletions components/brave_wallet_ui/common/async/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,12 @@ export async function findHardwareAccountInfo (address: string) {
return null
}

export function refreshBalancesAndPrices (currentNetwork: EthereumChain) {
export function refreshBalances (currentNetwork: EthereumChain) {
return async (dispatch: Dispatch, getState: () => State) => {
const apiProxy = getAPIProxy()
const { wallet: { accounts, selectedPortfolioTimeline } } = getState()
const { wallet: { accounts } } = getState()

const { braveWalletService, assetRatioController, ethJsonRpcController } = apiProxy
const { braveWalletService, ethJsonRpcController } = apiProxy

const visibleTokensInfo = await braveWalletService.getUserAssets(currentNetwork.chainId)

Expand All @@ -122,13 +122,50 @@ export function refreshBalancesAndPrices (currentNetwork: EthereumChain) {
const visibleTokens: ERCToken[] = visibleTokensInfo.tokens.length === 0 ? [nativeAsset] : visibleTokensInfo.tokens
await dispatch(WalletActions.setVisibleTokensInfo(visibleTokens))

// Update ETH Balances
const getNativeAssetPrice = await assetRatioController.getPrice([nativeAsset.symbol.toLowerCase()], ['usd'], selectedPortfolioTimeline)
const nativeAssetPrice = getNativeAssetPrice.success ? getNativeAssetPrice.values.find((i) => i.toAsset === 'usd')?.price ?? '0' : '0'
const getBalanceReturnInfos = await Promise.all(accounts.map(async (account) => {
const balanceInfo = await ethJsonRpcController.getBalance(account.address)
return balanceInfo
}))
const balancesAndPrice = {
usdPrice: '',
balances: getBalanceReturnInfos
}
await dispatch(WalletActions.nativeAssetBalancesUpdated(balancesAndPrice))

const getERCTokenBalanceReturnInfos = await Promise.all(accounts.map(async (account) => {
return Promise.all(visibleTokens.map(async (token) => {
if (token.isErc721) {
return ethJsonRpcController.getERC721TokenBalance(token.contractAddress, token.tokenId ?? '', account.address)
}
return ethJsonRpcController.getERC20TokenBalance(token.contractAddress, account.address)
}))
}))

const tokenBalancesAndPrices = {
balances: getERCTokenBalanceReturnInfos,
prices: { success: true, values: [] }
}
await dispatch(WalletActions.tokenBalancesUpdated(tokenBalancesAndPrices))
}
}

export function refreshPrices () {
return async (dispatch: Dispatch, getState: () => State) => {
const apiProxy = getAPIProxy()
const { wallet: { accounts, selectedPortfolioTimeline, selectedNetwork, userVisibleTokensInfo } } = getState()

const { assetRatioController } = apiProxy

// 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 getBalanceReturnInfos = accounts.map((account) => {
const balanceInfo = {
success: true,
balance: account.balance
}
return balanceInfo
})
const balancesAndPrice = {
usdPrice: nativeAssetPrice,
balances: getBalanceReturnInfos
Expand All @@ -137,29 +174,30 @@ export function refreshBalancesAndPrices (currentNetwork: EthereumChain) {
await dispatch(WalletActions.nativeAssetBalancesUpdated(balancesAndPrice))

// Update Token Balances
if (!visibleTokens) {
if (!userVisibleTokensInfo) {
return
}

const getTokenPrices = await Promise.all(visibleTokens.map(async (token) => {
const getTokenPrices = await Promise.all(userVisibleTokensInfo.map(async (token) => {
const emptyPrice = {
assetTimeframeChange: '0',
assetTimeframeChange: '',
fromAsset: token.symbol,
price: '0',
price: '',
toAsset: 'usd'
}
const price = await assetRatioController.getPrice([token.symbol.toLowerCase()], ['usd'], selectedPortfolioTimeline)
return price.success ? price.values[0] : emptyPrice
}))

const getERCTokenBalanceReturnInfos = await Promise.all(accounts.map(async (account) => {
return Promise.all(visibleTokens.map(async (token) => {
if (token.isErc721) {
return ethJsonRpcController.getERC721TokenBalance(token.contractAddress, token.tokenId ?? '', account.address)
const getERCTokenBalanceReturnInfos = accounts.map((account) => {
return account.tokens.map((token) => {
const balanceInfo = {
success: true,
balance: token.assetBalance
}
return ethJsonRpcController.getERC20TokenBalance(token.contractAddress, account.address)
}))
}))
return balanceInfo
})
})

const tokenBalancesAndPrices = {
balances: getERCTokenBalanceReturnInfos,
Expand Down
20 changes: 12 additions & 8 deletions components/brave_wallet_ui/common/reducers/wallet_reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,11 @@ 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 = formatFiatBalance(payload.balances[index].balance, state.selectedNetwork.decimals, payload.usdPrice).toString()
accounts[index].fiatBalance = payload.usdPrice !== ''
? formatFiatBalance(payload.balances[index].balance, state.selectedNetwork.decimals, payload.usdPrice).toString()
: ''
}
})

return {
...state,
accounts
Expand All @@ -187,26 +188,29 @@ reducer.on(WalletActions.tokenBalancesUpdated, (state: any, payload: GetERC20Tok
const prices = payload.prices
const findTokenPrice = (symbol: string) => {
if (prices.success) {
return prices.values.find((value) => value.fromAsset === symbol.toLowerCase())?.price ?? '0'
return prices.values.find((value) => value.fromAsset === symbol.toLowerCase())?.price ?? ''
} else {
return '0'
return ''
}
}
let accounts: WalletAccountType[] = [...state.accounts]
accounts.forEach((account, accountIndex) => {
payload.balances[accountIndex].forEach((info, tokenIndex) => {
let assetBalance = '0'
let fiatBalance = '0'
let assetBalance = ''
let fiatBalance = ''

if (userVisibleTokensInfo[tokenIndex].contractAddress === '') {
assetBalance = account.balance
fiatBalance = account.fiatBalance
} else if (info.success && userVisibleTokensInfo[tokenIndex].isErc721) {
assetBalance = info.balance
fiatBalance = '0' // TODO: support estimated market value.
fiatBalance = '' // TODO: support estimated market value.
} else if (info.success) {
const tokenPrice = findTokenPrice(userVisibleTokensInfo[tokenIndex].symbol)
assetBalance = info.balance
fiatBalance = formatFiatBalance(info.balance, userVisibleTokensInfo[tokenIndex].decimals, findTokenPrice(userVisibleTokensInfo[tokenIndex].symbol))
fiatBalance = tokenPrice !== ''
? formatFiatBalance(info.balance, userVisibleTokensInfo[tokenIndex].decimals, findTokenPrice(userVisibleTokensInfo[tokenIndex].symbol))
: ''
} else if (account.tokens[tokenIndex]) {
assetBalance = account.tokens[tokenIndex].assetBalance
fiatBalance = account.tokens[tokenIndex].fiatBalance
Expand Down
7 changes: 4 additions & 3 deletions components/brave_wallet_ui/page/container.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ function Container (props: Props) {
const amounts = accounts.map((account) => {
let fiatBalance
const found = account.tokens.find((token) => token.asset.contractAddress === asset.contractAddress)
if (found) {
if (found && found.fiatBalance !== '') {
fiatBalance = Number(found.fiatBalance)
}
return fiatBalance
Expand All @@ -316,8 +316,9 @@ function Container (props: Props) {

// This will scrape all of the user's accounts and combine the fiat value for every asset
const fullPortfolioBalance = React.useMemo(() => {
const amountList = userAssetList.map((item) => {
return item.asset.visible ? fullAssetFiatBalance(item.asset) !== '' ? fullAssetFiatBalance(item.asset) : undefined : 0
const filteredList = userAssetList.filter((token) => token.asset.visible && !token.asset.isErc721)
const amountList = filteredList.map((item) => {
return fullAssetFiatBalance(item.asset) !== '' ? fullAssetFiatBalance(item.asset) : undefined
})
if (amountList.length === 0) {
return ''
Expand Down

0 comments on commit a2d13a4

Please sign in to comment.