Skip to content

Commit

Permalink
Merge pull request #17367 from brave/use-contract-address-in-spot-prices
Browse files Browse the repository at this point in the history
fix(wallet): Use Contract Address and ChainId in Spot Prices
  • Loading branch information
Douglashdaniel authored Feb 25, 2023
2 parents 30b403d + 6546214 commit f9b5674
Show file tree
Hide file tree
Showing 25 changed files with 230 additions and 82 deletions.
12 changes: 9 additions & 3 deletions components/brave_wallet_ui/common/async/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,9 @@ export function refreshPrices () {
fromAsset: network.symbol.toLowerCase(),
toAsset: defaultFiatCurrency,
price: nativeAssetPrice,
assetTimeframeChange: ''
assetTimeframeChange: '',
contractAddress: '',
chainId: network.chainId
}
}))

Expand All @@ -687,7 +689,9 @@ export function refreshPrices () {
fromAsset: token.token.symbol,
toAsset: defaultFiatCurrency,
price: '',
assetTimeframeChange: ''
assetTimeframeChange: '',
contractAddress: token.token.contractAddress,
chainId: token.token.chainId
}

// If a tokens balance is 0 we do not make an unnecessary api call for the price of that token
Expand All @@ -705,7 +709,9 @@ export function refreshPrices () {

const tokenPrice = {
...price.values[0],
fromAsset: token.token.symbol.toLowerCase()
fromAsset: token.token.symbol.toLowerCase(),
contractAddress: token.token.contractAddress,
chainId: token.token.chainId
}

return price.success ? tokenPrice : emptyPrice
Expand Down
17 changes: 12 additions & 5 deletions components/brave_wallet_ui/common/constants/mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import {
AppsListType,
BraveWallet,
SerializableTransactionInfo,
WalletAccountType
WalletAccountType,
AssetPriceWithContractAndChainId
} from '../../constants/types'

// mocks
Expand Down Expand Up @@ -189,24 +190,30 @@ export const mockFilecoinAccount: WalletAccountType = {
keyringId: BraveWallet.FILECOIN_TESTNET_KEYRING_ID
}

export const mockAssetPrices: BraveWallet.AssetPrice[] = [
export const mockAssetPrices: AssetPriceWithContractAndChainId[] = [
{
fromAsset: 'ETH',
price: '4000',
toAsset: 'mockValue',
assetTimeframeChange: 'mockValue'
assetTimeframeChange: 'mockValue',
contractAddress: '0x1',
chainId: 'ETH'
},
{
fromAsset: 'DOG',
price: '100',
toAsset: 'mockValue',
assetTimeframeChange: 'mockValue'
assetTimeframeChange: 'mockValue',
contractAddress: '0xdog',
chainId: '0x1'
},
{
fromAsset: mockBasicAttentionToken.symbol,
price: '0.88',
toAsset: 'mockValue',
assetTimeframeChange: 'mockValue'
assetTimeframeChange: 'mockValue',
contractAddress: '0x0D8775F648430679A709E98d2b0Cb6250d2887EF',
chainId: '0x1'
}
]

Expand Down
4 changes: 2 additions & 2 deletions components/brave_wallet_ui/common/hooks/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ export function useAssets () {
const aBalance = getBalance(selectedAccount, a)
const bBalance = getBalance(selectedAccount, b)

const bFiatBalance = computeFiatAmount(bBalance, b.symbol, b.decimals)
const aFiatBalance = computeFiatAmount(aBalance, a.symbol, a.decimals)
const bFiatBalance = computeFiatAmount(bBalance, b.symbol, b.decimals, b.contractAddress, b.chainId)
const aFiatBalance = computeFiatAmount(aBalance, a.symbol, a.decimals, a.contractAddress, a.chainId)

return bFiatBalance.toNumber() - aFiatBalance.toNumber()
})
Expand Down
10 changes: 5 additions & 5 deletions components/brave_wallet_ui/common/hooks/pricing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,26 +12,26 @@ import usePricing from './pricing'
describe('usePricing hook', () => {
it('should return asset price of DOG token', () => {
const { result } = renderHook(() => usePricing(mockAssetPrices))
expect(result.current.findAssetPrice('DOG')).toEqual('100')
expect(result.current.findAssetPrice('DOG', '0xdog', '0x1')).toEqual('100')
})

it('should return empty asset price of unknown token', () => {
const { result } = renderHook(() => usePricing(mockAssetPrices))
expect(result.current.findAssetPrice('CAT')).toEqual('')
expect(result.current.findAssetPrice('CAT', '0xcat', '0x1')).toEqual('')
})

it('should compute fiat amount for DOG token', () => {
const { result } = renderHook(() => usePricing(mockAssetPrices))
expect(result.current.computeFiatAmount('7', 'DOG', 1).formatAsFiat()).toEqual('70.00')
expect(result.current.computeFiatAmount('7', 'DOG', 1, '0xdog', '0x1').formatAsFiat()).toEqual('70.00')
})

it('should return empty fiat value for unknown token', () => {
const { result } = renderHook(() => usePricing(mockAssetPrices))
expect(result.current.computeFiatAmount('7', 'CAT', 0).formatAsFiat()).toEqual('')
expect(result.current.computeFiatAmount('7', 'CAT', 0, '0xcat', '0x1').formatAsFiat()).toEqual('')
})

it('should return empty fiat value for empty amount', () => {
const { result } = renderHook(() => usePricing(mockAssetPrices))
expect(result.current.computeFiatAmount('', 'DOG', 0).formatAsFiat()).toEqual('')
expect(result.current.computeFiatAmount('', 'DOG', 0, '0xdog', '0x1').formatAsFiat()).toEqual('')
})
})
28 changes: 20 additions & 8 deletions components/brave_wallet_ui/common/hooks/pricing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,32 @@
import * as React from 'react'

// types
import { BraveWallet } from '../../constants/types'
import { AssetPriceWithContractAndChainId } from '../../constants/types'

// utils
import Amount from '../../utils/amount'
import { findAssetPrice, computeFiatAmount } from '../../utils/pricing-utils'

export default function usePricing (spotPrices: BraveWallet.AssetPrice[]) {
const _findAssetPrice = React.useCallback((symbol: string) => {
return findAssetPrice(spotPrices, symbol)
}, [spotPrices])
export default function usePricing (spotPrices: AssetPriceWithContractAndChainId[]) {
const _findAssetPrice = React.useCallback(
(
symbol: string,
contractAddress: string,
chainId: string
) => {
return findAssetPrice(spotPrices, symbol, contractAddress, chainId)
}, [spotPrices])

const _computeFiatAmount = React.useCallback((value: string, symbol: string, decimals: number): Amount => {
return computeFiatAmount(spotPrices, { decimals, symbol, value })
}, [spotPrices])
const _computeFiatAmount = React.useCallback(
(
value: string,
symbol: string,
decimals: number,
contractAddress: string,
chainId: string
): Amount => {
return computeFiatAmount(spotPrices, { decimals, symbol, value, contractAddress, chainId })
}, [spotPrices])

return {
computeFiatAmount: _computeFiatAmount,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,38 @@ export const SellAssetModal = (props: Props) => {
{
decimals: selectedAsset?.decimals ?? '',
symbol: selectedAsset?.symbol ?? '',
value: sellAssetBalance
contractAddress: selectedAsset?.contractAddress ?? '',
value: sellAssetBalance,
chainId: selectedAsset?.chainId ?? ''
})
}, [spotPrices, sellAssetBalance, selectedAsset?.symbol, selectedAsset?.decimals])
}, [
spotPrices,
sellAssetBalance,
selectedAsset?.symbol,
selectedAsset?.decimals,
selectedAsset?.contractAddress,
selectedAsset.chainId
])

const estimatedAssetAmount = React.useMemo(() => {
if (sellAmount !== '') {
return `~${computeFiatAmountToAssetValue(sellAmount, spotPrices, selectedAsset?.symbol ?? '')
return `~${computeFiatAmountToAssetValue(
sellAmount,
spotPrices,
selectedAsset?.symbol ?? '',
selectedAsset?.contractAddress ?? '',
selectedAsset?.chainId ?? ''
)
.formatAsAsset(6, selectedAsset.symbol)}`
}
return `0.00 ${selectedAsset?.symbol}`
}, [sellAmount, spotPrices, selectedAsset.symbol])
}, [
sellAmount,
spotPrices,
selectedAsset?.symbol,
selectedAsset?.contractAddress,
selectedAsset?.chainId
])

const formattedFiatBalance = React.useMemo(() => {
return fiatBalance ? new Amount(fiatBalance.format(2)).formatAsFiat(defaultCurrencies.fiat) : undefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { create } from 'ethereum-blockies'
import { useHistory } from 'react-router'

// Types
import { BraveWallet, DefaultCurrencies, WalletRoutes } from '../../../constants/types'
import { BraveWallet, DefaultCurrencies, WalletRoutes, AssetPriceWithContractAndChainId } from '../../../constants/types'

// Hooks
import { useExplorer, usePricing } from '../../../common/hooks'
Expand Down Expand Up @@ -42,9 +42,11 @@ import {
import { SellButtonRow, SellButton } from '../../shared/style'

interface Props {
spotPrices: BraveWallet.AssetPrice[]
spotPrices: AssetPriceWithContractAndChainId[]
address: string
defaultCurrencies: DefaultCurrencies
assetContractAddress: string
assetChainId: string
assetBalance: string
assetTicker: string
assetDecimals: number
Expand All @@ -58,6 +60,8 @@ interface Props {

export const PortfolioAccountItem = (props: Props) => {
const {
assetContractAddress,
assetChainId,
assetBalance,
address,
assetTicker,
Expand Down Expand Up @@ -94,8 +98,8 @@ export const PortfolioAccountItem = (props: Props) => {
}, [assetBalance, assetDecimals])

const fiatBalance: Amount = React.useMemo(() => {
return computeFiatAmount(assetBalance, assetTicker, assetDecimals)
}, [computeFiatAmount, assetDecimals, assetBalance, assetTicker])
return computeFiatAmount(assetBalance, assetTicker, assetDecimals, assetContractAddress, assetChainId)
}, [computeFiatAmount, assetDecimals, assetBalance, assetTicker, assetContractAddress, assetChainId])

const isAssetsBalanceZero = React.useMemo(() => {
return new Amount(assetBalance).isZero()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,14 @@ export const PortfolioAssetItem = ({
.formatAsAsset(6, token.symbol)

const fiatBalance = React.useMemo(() => {
return computeFiatAmount(spotPrices, { decimals: token.decimals, symbol: token.symbol, value: assetBalance })
}, [spotPrices, assetBalance, token.symbol, token.decimals])
return computeFiatAmount(spotPrices, {
decimals: token.decimals,
symbol: token.symbol,
value: assetBalance,
contractAddress: token.contractAddress,
chainId: token.chainId
})
}, [spotPrices, assetBalance, token.symbol, token.decimals, token.chainId])

const formattedFiatBalance = React.useMemo(() => {
return fiatBalance.formatAsFiat(defaultCurrencies.fiat)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ export const AccountsAndTransactionsList = ({
spotPrices={transactionSpotPrices}
defaultCurrencies={defaultCurrencies}
key={account.address}
assetContractAddress={selectedAsset.contractAddress}
assetChainId={selectedAsset.chainId}
assetTicker={selectedAsset.symbol}
assetDecimals={selectedAsset.decimals}
name={account.name}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ export const TokenLists = ({
return [...fungibleTokens].sort(function (a, b) {
const aBalance = a.assetBalance
const bBalance = b.assetBalance
const bFiatBalance = computeFiatAmount(bBalance, b.asset.symbol, b.asset.decimals)
const aFiatBalance = computeFiatAmount(aBalance, a.asset.symbol, a.asset.decimals)
const bFiatBalance = computeFiatAmount(bBalance, b.asset.symbol, b.asset.decimals, b.asset.contractAddress, b.asset.chainId)
const aFiatBalance = computeFiatAmount(aBalance, a.asset.symbol, a.asset.decimals, a.asset.contractAddress, a.asset.chainId)
return assetFilterItemInfo.id === 'highToLow'
? bFiatBalance.toNumber() - aFiatBalance.toNumber()
: aFiatBalance.toNumber() - bFiatBalance.toNumber()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,13 @@ export const PortfolioAsset = (props: Props) => {

const visibleAssetFiatBalances = visibleAssetOptions
.map((item) => {
return computeFiatAmount(item.assetBalance, item.asset.symbol, item.asset.decimals)
return computeFiatAmount(
item.assetBalance,
item.asset.symbol,
item.asset.decimals,
item.asset.contractAddress,
item.asset.chainId
)
})

const grandTotal = visibleAssetFiatBalances.reduce(function (a, b) {
Expand Down Expand Up @@ -347,7 +353,9 @@ export const PortfolioAsset = (props: Props) => {
? computeFiatAmount(
fullAssetBalances.assetBalance,
fullAssetBalances.asset.symbol,
fullAssetBalances.asset.decimals
fullAssetBalances.asset.decimals,
fullAssetBalances.asset.contractAddress,
fullAssetBalances.asset.chainId
)
: Amount.empty(),
[fullAssetBalances]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,9 @@ export const PortfolioOverview = () => {
{
value: item.assetBalance,
decimals: item.asset.decimals,
symbol: item.asset.symbol
symbol: item.asset.symbol,
contractAddress: item.asset.contractAddress,
chainId: item.asset.chainId
}
)
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export function EditPendingTransactionGas (props: Props) {
<EditGas
transactionInfo={transactionInfo}
onCancel={onCancel}
networkSpotPrice={findAssetPrice(transactionsNetwork.symbol)}
networkSpotPrice={findAssetPrice(transactionsNetwork.symbol, '', transactionsNetwork.chainId)}
selectedNetwork={transactionsNetwork}
baseFeePerGas={baseFeePerGas}
suggestedMaxPriorityFeeChoices={suggestedMaxPriorityFeeChoices}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,11 @@ export const ConnectedPanel = (props: Props) => {
}

return computeFiatAmount(
selectedAccount.nativeBalanceRegistry[selectedNetwork.chainId], selectedNetwork.symbol, selectedNetwork.decimals
selectedAccount.nativeBalanceRegistry[selectedNetwork.chainId],
selectedNetwork.symbol,
selectedNetwork.decimals,
'',
selectedNetwork.chainId
)
}, [computeFiatAmount, selectedNetwork, selectedAccount])

Expand Down
13 changes: 9 additions & 4 deletions components/brave_wallet_ui/constants/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,11 @@ export interface TokenRegistry {
[chainID: string]: BraveWallet.BlockchainToken[]
}

export interface AssetPriceWithContractAndChainId extends BraveWallet.AssetPrice {
contractAddress: string
chainId: string
}

export interface WalletState {
hasInitialized: boolean
isFilecoinEnabled: boolean
Expand All @@ -244,7 +249,7 @@ export interface WalletState {
selectedPortfolioTimeline: BraveWallet.AssetPriceTimeframe
networkList: BraveWallet.NetworkInfo[]
hiddenNetworkList: BraveWallet.NetworkInfo[]
transactionSpotPrices: BraveWallet.AssetPrice[]
transactionSpotPrices: AssetPriceWithContractAndChainId[]
addUserAssetError: boolean
defaultEthereumWallet: BraveWallet.DefaultWallet
defaultSolanaWallet: BraveWallet.DefaultWallet
Expand Down Expand Up @@ -302,8 +307,8 @@ export interface PageState {
enablingAutoPin: boolean
isAutoPinEnabled: boolean
pinStatusOverview: BraveWallet.TokenPinOverview | undefined
selectedAssetFiatPrice: BraveWallet.AssetPrice | undefined
selectedAssetCryptoPrice: BraveWallet.AssetPrice | undefined
selectedAssetFiatPrice: AssetPriceWithContractAndChainId | undefined
selectedAssetCryptoPrice: AssetPriceWithContractAndChainId | undefined
selectedAssetPriceHistory: GetPriceHistoryReturnInfo[]
portfolioPriceHistory: PriceDataObjectType[]
mnemonic?: string
Expand Down Expand Up @@ -364,7 +369,7 @@ export type SwapValidationErrorType =

export interface GetPriceReturnInfo {
success: boolean
values: BraveWallet.AssetPrice[]
values: AssetPriceWithContractAndChainId[]
}

export interface GetPriceHistoryReturnInfo {
Expand Down
Loading

0 comments on commit f9b5674

Please sign in to comment.