Skip to content

chore(wallet): Don't Fetch Prices for 0 Balances #11731

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

Merged
merged 1 commit into from
Jan 4, 2022
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
43 changes: 29 additions & 14 deletions components/brave_wallet_ui/common/async/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
} from '../../constants/types'
import * as WalletActions from '../actions/wallet_actions'
import { GetNetworkInfo } from '../../utils/network-utils'
import { GetTokenParam } from '../../utils/api-utils'
import { GetTokenParam, GetFlattenedAccountBalances } from '../../utils/api-utils'
import getAPIProxy from './bridge'
import { Dispatch, State } from './types'
import LedgerBridgeKeyring from '../../common/hardware/ledgerjs/eth_ledger_bridge_keyring'
Expand Down Expand Up @@ -203,20 +203,26 @@ export function refreshPrices () {
return
}

const getTokenPrices = await Promise.all(userVisibleTokensInfo.map(async (token) => {
const getTokenPrices = await Promise.all(GetFlattenedAccountBalances(accounts).map(async (token) => {
const emptyPrice = {
assetTimeframeChange: '',
fromAsset: token.symbol,
fromAsset: token.token.symbol,
toAsset: defaultFiatCurrency,
price: '',
toAsset: defaultFiatCurrency
assetTimeframeChange: ''
}
const price = await assetRatioController.getPrice([GetTokenParam(selectedNetwork, token)], [defaultFiatCurrency], selectedPortfolioTimeline)

// If a tokens balance is 0 we do not make an unnecessary api call for the price of that token
const price = token.balance > 0 && token.token.isErc20
? await assetRatioController.getPrice([GetTokenParam(selectedNetwork, token.token)], [defaultFiatCurrency], selectedPortfolioTimeline)
: { values: [{ ...emptyPrice, price: '0' }], success: true }

const tokenPrice = {
...price.values[0],
fromAsset: token.symbol.toLowerCase()
fromAsset: token.token.symbol.toLowerCase()
}
return price.success ? tokenPrice : emptyPrice
}))

const getERCTokenBalanceReturnInfos = accounts.map((account) => {
return account.tokens.map((token) => {
const balanceInfo = {
Expand All @@ -243,18 +249,27 @@ export function refreshTokenPriceHistory (selectedPortfolioTimeline: BraveWallet
const { assetRatioController } = apiProxy

const { wallet: { accounts, defaultCurrencies, selectedNetwork } } = getState()
const result = await Promise.all(accounts.map(async (account) => {
return Promise.all(account.tokens.filter((t) => !t.asset.isErc721).map(async (token) => {

// If a tokens balance is 0 we do not make an unnecessary api call for price history of that token
const priceHistory = await Promise.all(GetFlattenedAccountBalances(accounts).filter((t) => !t.token.isErc721 && t.balance > 0).map(async (token) => {
return {
contractAddress: token.token.contractAddress,
history: await assetRatioController.getPriceHistory(
GetTokenParam(selectedNetwork, token.token), defaultCurrencies.fiat.toLowerCase(), selectedPortfolioTimeline
)
}
}))

const priceHistoryWithBalances = accounts.map((account) => {
return (account.tokens.filter((t) => !t.asset.isErc721).map((token) => {
return {
token: token,
history: await assetRatioController.getPriceHistory(
GetTokenParam(selectedNetwork, token.asset), defaultCurrencies.fiat.toLowerCase(), selectedPortfolioTimeline
)
history: priceHistory.find((t) => token.asset.contractAddress === t.contractAddress)?.history ?? { success: true, values: [] }
}
}))
}))
})

dispatch(WalletActions.portfolioPriceHistoryUpdated(result))
dispatch(WalletActions.portfolioPriceHistoryUpdated(priceHistoryWithBalances))
}
}

Expand Down
5 changes: 5 additions & 0 deletions components/brave_wallet_ui/constants/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,11 @@ export interface GetERC20TokenBalanceAndPriceReturnInfo {
prices: GetPriceReturnInfo
}

export interface GetFlattenedAccountBalancesReturnInfo {
token: BraveWallet.ERCToken
balance: number
}

export interface PortfolioTokenHistoryAndInfo {
history: GetPriceHistoryReturnObjectInfo
token: AccountAssetOptionType
Expand Down
34 changes: 33 additions & 1 deletion components/brave_wallet_ui/utils/api-utils.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { GetTokenParam } from './api-utils'
import { GetTokenParam, GetFlattenedAccountBalances } from './api-utils'
import { mockNetworks } from '../stories/mock-data/mock-networks'
import { AccountAssetOptions } from '../options/asset-options'
import { mockAccount } from '../common/constants/mocks'

describe('Check token param', () => {
test('Value should return contract address', () => {
Expand All @@ -10,3 +11,34 @@ describe('Check token param', () => {
expect(GetTokenParam(mockNetworks[1], AccountAssetOptions[1].asset)).toEqual('bat')
})
})

const mockAccounts = [
{
...mockAccount,
tokens: [{ ...AccountAssetOptions[0], assetBalance: '0x350082652bcfb2e' }, AccountAssetOptions[1]]
},
{
...mockAccount,
tokens: [{ ...AccountAssetOptions[0], assetBalance: '0x11e40b7737cd000' }, AccountAssetOptions[1]]
}
]

const expectedResult = [
{
balance: 0.31930000000000003,
token: AccountAssetOptions[0].asset
},
{
balance: 0,
token: AccountAssetOptions[1].asset
}
]

describe('Check Flattened Account Balances', () => {
test('Value should return an Empty Array', () => {
expect(GetFlattenedAccountBalances([])).toEqual([])
})
test('Value should return a Flattened Account Balance List', () => {
expect(GetFlattenedAccountBalances(mockAccounts)).toEqual(expectedResult)
})
})
16 changes: 15 additions & 1 deletion components/brave_wallet_ui/utils/api-utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { BraveWallet } from '../constants/types'
import { BraveWallet, WalletAccountType, GetFlattenedAccountBalancesReturnInfo } from '../constants/types'
import { formatBalance } from './format-balances'
import { ETH } from '../options/asset-options'

export const GetTokenParam = (selectedNetwork: BraveWallet.EthereumChain, token: BraveWallet.ERCToken): string => {
Expand All @@ -12,3 +13,16 @@ export const GetTokenParam = (selectedNetwork: BraveWallet.EthereumChain, token:
? token.symbol.toLowerCase()
: token.contractAddress
}

// This will get the sum balance for each token between all accounts
export const GetFlattenedAccountBalances = (accounts: WalletAccountType[]): GetFlattenedAccountBalancesReturnInfo[] => {
if (accounts.length === 0) {
return []
}
return accounts[0].tokens.map((token, index) => {
return {
token: token.asset,
balance: accounts.map(t => Number(formatBalance(t.tokens[index].assetBalance, token.asset.decimals)) || 0).reduce((sum, x) => sum + x, 0)
}
})
}