Skip to content

Commit

Permalink
Implemented Default Currencies in Wallet UI
Browse files Browse the repository at this point in the history
  • Loading branch information
Douglashdaniel committed Dec 7, 2021
1 parent 7842e77 commit b474ffc
Show file tree
Hide file tree
Showing 28 changed files with 297 additions and 102 deletions.
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 @@ -159,8 +157,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 @@ -208,13 +211,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(), 'usd', 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
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import {
SlippagePresetObjectType,
ExpirationPresetObjectType,
SwapValidationErrorType,
AmountPresetTypes
AmountPresetTypes,
DefaultCurrencies
} from '../../../constants/types'
import { CurrencySymbols } from '../../../utils/currency-symbols'
import { AmountPresetOptions } from '../../../options/amount-preset-options'
import { SlippagePresetOptions } from '../../../options/slippage-preset-options'
import { ExpirationPresetOptions } from '../../../options/expiration-preset-options'
Expand Down Expand Up @@ -64,6 +66,7 @@ export interface Props {
orderExpiration?: ExpirationPresetObjectType
validationError?: SwapValidationErrorType
customSlippageTolerance?: string
defaultCurrencies?: DefaultCurrencies
onCustomSlippageToleranceChange?: (value: string) => void
onInputChange?: (value: string, name: string) => void
onSelectPresetAmount?: (percent: number) => void
Expand Down Expand Up @@ -91,6 +94,7 @@ function SwapInputComponent (props: Props) {
orderExpiration,
validationError,
customSlippageTolerance,
defaultCurrencies,
onCustomSlippageToleranceChange,
onInputChange,
onPaste,
Expand Down Expand Up @@ -241,7 +245,7 @@ function SwapInputComponent (props: Props) {
}
<Row componentType={componentType}>
{componentType === 'buyAmount' &&
<AssetTicker>$</AssetTicker>
<AssetTicker>{CurrencySymbols[defaultCurrencies?.fiat ?? 'USD']}</AssetTicker>
}
{!selectedAsset?.asset.isErc721 &&
<Input
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import {
UserAccountType,
AccountAssetOptionType,
BuySendSwapViewTypes,
EthereumChain
EthereumChain,
DefaultCurrencies
} from '../../../constants/types'
import {
AccountsAssetsNetworks,
Expand All @@ -19,6 +20,7 @@ export interface Props {
assetOptions: AccountAssetOptionType[]
buyAmount: string
showHeader?: boolean
defaultCurrencies: DefaultCurrencies
onSubmit: (asset: AccountAssetOptionType) => void
onSelectNetwork: (network: EthereumChain) => void
onSelectAccount: (account: UserAccountType) => void
Expand All @@ -34,6 +36,7 @@ function BuyTab (props: Props) {
buyAmount,
showHeader,
assetOptions,
defaultCurrencies,
onSubmit,
onSelectNetwork,
onSelectAccount,
Expand Down Expand Up @@ -85,6 +88,7 @@ function BuyTab (props: Props) {
/>
}
<Buy
defaultCurrencies={defaultCurrencies}
buyAmount={buyAmount}
selectedAsset={selectedAsset}
selectedNetwork={selectedNetwork}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import { create } from 'ethereum-blockies'
import { Tooltip } from '../../shared'
import { getLocale } from '../../../../common/locale'
import { EthereumChain } from '../../../constants/types'
import { EthereumChain, DefaultCurrencies } from '../../../constants/types'
import { TransactionPopup } from '../'
// Styled Components
import {
Expand All @@ -28,6 +28,7 @@ import {
import { TransactionPopupItem } from '../transaction-popup'

export interface Props {
defaultCurrencies: DefaultCurrencies
address: string
fiatBalance: string
assetBalance: string
Expand All @@ -37,7 +38,15 @@ export interface Props {
}

const PortfolioAccountItem = (props: Props) => {
const { address, name, assetBalance, fiatBalance, assetTicker, selectedNetwork } = props
const {
address,
name,
assetBalance,
fiatBalance,
assetTicker,
selectedNetwork,
defaultCurrencies
} = props
const [showAccountPopup, setShowAccountPopup] = React.useState<boolean>(false)
const onCopyToClipboard = async () => {
await copyToClipboard(address)
Expand Down Expand Up @@ -80,7 +89,7 @@ const PortfolioAccountItem = (props: Props) => {
</NameAndIcon>
<RightSide>
<BalanceColumn>
<FiatBalanceText>{formatFiatAmountWithCommasAndDecimals(fiatBalance)}</FiatBalanceText>
<FiatBalanceText>{formatFiatAmountWithCommasAndDecimals(fiatBalance, defaultCurrencies.fiat)}</FiatBalanceText>
<AssetBalanceText>{formatTokenAmountWithCommasAndDecimals(assetBalance, assetTicker)}</AssetBalanceText>
</BalanceColumn>
<MoreButton onClick={onShowTransactionPopup}>
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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 })
Expand All @@ -47,7 +54,7 @@ const PortfolioAssetItem = (props: Props) => {
</NameAndIcon>
<BalanceColumn>
{!token.isErc721 &&
<FiatBalanceText>{formatFiatAmountWithCommasAndDecimals(fiatBalance)}</FiatBalanceText>
<FiatBalanceText>{formatFiatAmountWithCommasAndDecimals(fiatBalance, defaultCurrencies.fiat)}</FiatBalanceText>
}
<AssetBalanceText>{formatedAssetBalance}</AssetBalanceText>
</BalanceColumn>
Expand Down
Loading

0 comments on commit b474ffc

Please sign in to comment.