Skip to content

Commit

Permalink
CU-86dt6hj38 - NEON3 - Settings - Implement currency selection
Browse files Browse the repository at this point in the history
  • Loading branch information
yumiuehara committed May 6, 2024
1 parent 531ab3c commit 8603418
Show file tree
Hide file tree
Showing 23 changed files with 183 additions and 67 deletions.
9 changes: 6 additions & 3 deletions src/renderer/src/@types/i18next-resources.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -402,13 +402,13 @@ interface Resources {
inputAmount: {
title: 'Amount you want to send'
enterTokenAmount: 'Enter token amount:'
fiatValue: 'Fiat value (USD estimated)'
fiatValue: 'Fiat value ({{currencyType}} estimated)'
balanceAfterTransaction: 'Balance after transaction'
insufficientBalanceAvailable: 'Insufficient balance available'
max: 'Max'
or: 'OR'
inputPlaceholder: '0,000.00'
enterUsdAmount: 'Enter a USD amount:'
enterAmount: 'Enter a {{currencyType}} amount:'
roundDown: 'Round down'
selectAmountSend: 'Select amount to send'
tokenValue: 'Token value'
Expand Down Expand Up @@ -731,7 +731,7 @@ interface Resources {
sourceAccount: 'Source account'
inputAmount: 'Input amount...'
amount: 'Amount'
fiatValue: 'Fiat value (USD estimated)'
fiatValue: 'Fiat value ({{currencyType}} estimated)'
recipientAddress: 'Recipient address'
contacts: 'Contacts'
addressInputHint: 'Enter recipient address...'
Expand Down Expand Up @@ -903,6 +903,9 @@ interface Resources {
subtitle: 'Your NEON 3 password has been successfully changed!'
}
}
settingsCurrency: {
title: 'Currency'
}
}
receive: {
title: 'Receive Tokens'
Expand Down
6 changes: 6 additions & 0 deletions src/renderer/src/@types/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,17 @@ export interface IWalletState {
}
export type TSecurityType = 'none' | 'password'

export type TAvailableCurrency = 'USD' | 'BRL' | 'EUR' | 'GBP' | 'CNY'
export type TCurrency = {
symbol: string
label: TAvailableCurrency
}
export interface ISettingsState {
encryptedPassword?: string
isFirstTime: boolean
securityType: TSecurityType
networkType: TNetworkType
currency: TCurrency
}

export type TContactAddress = { address: string; blockchain: TBlockchainServiceKey }
Expand Down
21 changes: 16 additions & 5 deletions src/renderer/src/components/BalanceChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { UseMultipleBalanceAndExchangeResult } from '@renderer/@types/query'
import { BalanceConvertedToExchange, BalanceHelper } from '@renderer/helpers/BalanceHelper'
import { FilterHelper } from '@renderer/helpers/FilterHelper'
import { NumberHelper } from '@renderer/helpers/NumberHelper'
import { UtilsHelper } from '@renderer/helpers/UtilsHelper'
import { useCurrencySelector } from '@renderer/hooks/useSettingsSelector'

import { Loader } from './Loader'

Expand All @@ -20,6 +21,7 @@ type TBar = {

export const BalanceChart = ({ balanceExchange }: TProps) => {
const { t } = useTranslation('components', { keyPrefix: 'balanceChart' })
const { currency } = useCurrencySelector()

const totalTokensBalances = useMemo(
() => BalanceHelper.calculateTotalBalances(balanceExchange.balance.data, balanceExchange.exchange.data),
Expand All @@ -33,7 +35,9 @@ export const BalanceChart = ({ balanceExchange }: TProps) => {
balanceExchange.exchange.data
)
if (!totalTokensBalances || totalTokensBalances <= 0 || !convertedBalances)
return [{ color: '#676767', name: t('noAssets'), value: FilterHelper.currency(0), widthPercent: 100 }]
return [
{ color: '#676767', name: t('noAssets'), value: NumberHelper.currency(0, currency.label), widthPercent: 100 },
]

const filteredBalances = convertedBalances
.filter(balance => balance.convertedAmount > 0)
Expand All @@ -56,7 +60,7 @@ export const BalanceChart = ({ balanceExchange }: TProps) => {
const widthPercent = (balance.convertedAmount * 100) / totalTokensBalances
return {
name: balance.token.name,
value: FilterHelper.currency(balance.convertedAmount),
value: NumberHelper.currency(balance.convertedAmount, currency.label),
color,
widthPercent,
}
Expand All @@ -69,13 +73,20 @@ export const BalanceChart = ({ balanceExchange }: TProps) => {
const othersAmount = filteredBalances.slice(4).reduce((acc, balance) => acc + balance.convertedAmount, 0)
const otherBar: TBar = {
color: '#47BEFF',
value: FilterHelper.currency(othersAmount),
value: NumberHelper.currency(othersAmount, currency.label),
name: t('othersTokens'),
widthPercent: (othersAmount * 100) / totalTokensBalances,
}

return [...firstFourBars, otherBar]
}, [balanceExchange.balance.data, balanceExchange.exchange.data, balanceExchange.isLoading, t, totalTokensBalances])
}, [
balanceExchange.balance.data,
balanceExchange.exchange.data,
balanceExchange.isLoading,
currency.label,
t,
totalTokensBalances,
])

if (bars === undefined) {
return <Loader />
Expand Down
13 changes: 8 additions & 5 deletions src/renderer/src/components/TokensTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { forwardRef, useImperativeHandle, useMemo, useRef, useState } from 'reac
import { Balance, TokenBalance, UseMultipleBalanceAndExchangeResult } from '@renderer/@types/query'
import { BlockchainIcon } from '@renderer/components/BlockchainIcon'
import { BalanceHelper } from '@renderer/helpers/BalanceHelper'
import { FilterHelper } from '@renderer/helpers/FilterHelper'
import { NumberHelper } from '@renderer/helpers/NumberHelper'
import { StyleHelper } from '@renderer/helpers/StyleHelper'
import { useCurrencySelector } from '@renderer/hooks/useSettingsSelector'
import { getI18next } from '@renderer/libs/i18next'
import {
createColumnHelper,
Expand Down Expand Up @@ -37,6 +38,8 @@ const columnHelper = createColumnHelper<TTokenBalanceWithExchange>()

export const TokensTable = forwardRef<HTMLDivElement, TProps>(
({ balanceExchange, showSimplified, className, onTokenSelected, selectedToken, containerClassName }, ref) => {
const { currency } = useCurrencySelector()

const filteredTokenBalance = useMemo(() => {
const groupedTokens = new Map<string, TTokenBalanceWithExchange>()

Expand Down Expand Up @@ -103,11 +106,11 @@ export const TokensTable = forwardRef<HTMLDivElement, TProps>(
header: t('components:tokensTable.holdings'),
}),
columnHelper.accessor('exchangeRatio', {
cell: info => FilterHelper.currency(info.getValue()),
cell: info => NumberHelper.currency(info.getValue(), currency.label),
header: t('components:tokensTable.price'),
}),
columnHelper.accessor('convertedAmount', {
cell: info => FilterHelper.currency(info.getValue()),
cell: info => NumberHelper.currency(info.getValue(), currency.label),
header: t('components:tokensTable.value'),
}),
]
Expand Down Expand Up @@ -135,11 +138,11 @@ export const TokensTable = forwardRef<HTMLDivElement, TProps>(
header: t('components:tokensTable.holdings'),
}),
columnHelper.accessor('exchangeRatio', {
cell: info => FilterHelper.currency(info.getValue()),
cell: info => NumberHelper.currency(info.getValue(), currency.label),
header: t('components:tokensTable.price'),
}),
],
[showSimplified]
[currency.label, showSimplified]
)

const table = useReactTable({
Expand Down
9 changes: 9 additions & 0 deletions src/renderer/src/constants/currency.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { TCurrency } from '@renderer/@types/store'

export const availableCurrencies: TCurrency[] = [
{ symbol: 'U$', label: 'USD' },
{ symbol: '€', label: 'EUR' },
{ symbol: '£', label: 'GBP' },
{ symbol: 'R$', label: 'BRL' },
{ symbol: '¥', label: 'CNY' },
]
4 changes: 2 additions & 2 deletions src/renderer/src/helpers/NumberHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@ export class NumberHelper {
return decimals?.length ?? 0
}

static currency(input: string | number, minimumFractionDigits = 2, maximumFractionDigits = 2) {
static currency(input: string | number, currencyName: string, minimumFractionDigits = 2, maximumFractionDigits = 2) {
const num = Number(input)

try {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
currency: currencyName,
minimumFractionDigits,
maximumFractionDigits,
})
Expand Down
7 changes: 4 additions & 3 deletions src/renderer/src/hooks/useExchange.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,19 @@ import { bsAggregator } from '@renderer/libs/blockchainService'
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import lodash from 'lodash'

import { useNetworkTypeSelector } from './useSettingsSelector'
import { useCurrencySelector, useNetworkTypeSelector } from './useSettingsSelector'

type ExchangeInfoByKey = Record<string, TokenPricesResponse[]>

export function useExchange(
queryOptions?: Omit<UseQueryOptions<MultiExchange, unknown, MultiExchange, string[]>, 'queryKey' | 'queryFn'>
): UseExchangeResult {
const { networkType } = useNetworkTypeSelector()
const { currency } = useCurrencySelector()
const fetchExchanges = useCallback(async (): Promise<MultiExchange> => {
const promises = Object.values(bsAggregator.blockchainServicesByName).map(
async (service): Promise<ExchangeInfoByKey> => ({
[service.blockchainName]: await service.exchangeDataService.getTokenPrices('USD'),
[service.blockchainName]: await service.exchangeDataService.getTokenPrices(currency.label as any),
})
)

Expand All @@ -26,7 +27,7 @@ export function useExchange(
.map(exchange => exchange.value)

return lodash.merge({}, ...exchangesFiltered)
}, [])
}, [currency.label])

const [isRefetchingByUser, setIsRefetchingByUser] = useState(false)

Expand Down
8 changes: 8 additions & 0 deletions src/renderer/src/hooks/useSettingsSelector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,11 @@ export const useNetworkTypeSelector = () => {
networkTypeRef: ref,
}
}

export const useCurrencySelector = () => {
const { ref, value } = useAppSelector(state => state.settings.currency)
return {
currency: value,
currencyRef: ref,
}
}
6 changes: 3 additions & 3 deletions src/renderer/src/locales/en/modals.json
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,13 @@
"inputAmount": {
"title": "Amount you want to send",
"enterTokenAmount": "Enter token amount:",
"fiatValue": "Fiat value (USD estimated)",
"fiatValue": "Fiat value ({{currencyType}} estimated)",
"balanceAfterTransaction": "Balance after transaction",
"insufficientBalanceAvailable": "Insufficient balance available",
"max": "Max",
"or": "OR",
"inputPlaceholder": "0,000.00",
"enterUsdAmount": "Enter a USD amount:",
"enterAmount": "Enter a {{currencyType}} amount:",
"roundDown": "Round down",
"selectAmountSend": "Select amount to send",
"tokenValue": "Token value"
Expand Down Expand Up @@ -444,4 +444,4 @@
}
}
}
}
}
21 changes: 7 additions & 14 deletions src/renderer/src/locales/en/pages.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,7 @@
},
"welcomeSecuritySetup": {
"title": "Securing your new wallet",
"steps": [
"Create Password",
"Confirm Password",
"Complete"
],
"steps": ["Create Password", "Confirm Password", "Complete"],
"step1": {
"formTitle": "Please create a password to secure your wallet",
"passwordPlaceholder": "Create a password...",
Expand All @@ -43,13 +39,7 @@
},
"welcomeImportWallet": {
"title": "Import a wallet",
"steps": [
"Create Password",
"Confirm Password",
"Enter address or key",
"Import",
"Complete"
],
"steps": ["Create Password", "Confirm Password", "Enter address or key", "Import", "Complete"],
"step3": {
"formTitle": "Enter an address, encrypted key, private key or mnemonic",
"inputPlaceholder": "Enter an address, key or mnemonic...",
Expand Down Expand Up @@ -110,7 +100,7 @@
"sourceAccount": "Source account",
"inputAmount": "Input amount...",
"amount": "Amount",
"fiatValue": "Fiat value (USD estimated)",
"fiatValue": "Fiat value ({{currencyType}} estimated)",
"recipientAddress": "Recipient address",
"contacts": "Contacts",
"addressInputHint": "Enter recipient address...",
Expand Down Expand Up @@ -281,6 +271,9 @@
"step3": {
"subtitle": "Your NEON 3 password has been successfully changed!"
}
},
"settingsCurrency": {
"title": "Currency"
}
},
"receive": {
Expand All @@ -298,4 +291,4 @@
"selectReceivingAccount": "Select receiving account"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Input } from '@renderer/components/Input'
import { NumberHelper } from '@renderer/helpers/NumberHelper'
import { StringHelper } from '@renderer/helpers/StringHelper'
import { StyleHelper } from '@renderer/helpers/StyleHelper'
import { useCurrencySelector } from '@renderer/hooks/useSettingsSelector'

type TProps = {
value: string
Expand All @@ -16,6 +17,7 @@ type TProps = {

export const FiatAmountInput = ({ onChange, value, exchangeRatio, tokenBalance, error }: TProps) => {
const { t } = useTranslation('modals', { keyPrefix: 'inputAmount' })
const { currency } = useCurrencySelector()

const valueNumber = NumberHelper.number(value)
const estimatedToken = valueNumber > 0 && exchangeRatio > 0 ? valueNumber / exchangeRatio : 0
Expand All @@ -27,7 +29,7 @@ export const FiatAmountInput = ({ onChange, value, exchangeRatio, tokenBalance,
})}
>
<label className="text-gray-100" htmlFor="fiatAmount">
{t('enterUsdAmount')}
{t('enterAmount', { currencyType: currency.label })}
</label>

<Input
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Button } from '@renderer/components/Button'
import { Input } from '@renderer/components/Input'
import { NumberHelper } from '@renderer/helpers/NumberHelper'
import { StyleHelper } from '@renderer/helpers/StyleHelper'
import { useCurrencySelector } from '@renderer/hooks/useSettingsSelector'

type TProps = {
value: string
Expand All @@ -15,6 +16,7 @@ type TProps = {

export const TokenAmountInput = ({ onChange, onMaxClick, value, exchangeRatio, error }: TProps) => {
const { t } = useTranslation('modals', { keyPrefix: 'inputAmount' })
const { currency } = useCurrencySelector()

const estimatedFiat = NumberHelper.number(value) * exchangeRatio

Expand Down Expand Up @@ -52,8 +54,10 @@ export const TokenAmountInput = ({ onChange, onMaxClick, value, exchangeRatio, e
'opacity-50': exchangeRatio === 0,
})}
>
<span className="text-gray-300 whitespace-nowrap">{t('fiatValue')}</span>
<span className="text-gray-100 whitespace-nowrap truncate">{NumberHelper.currency(estimatedFiat)}</span>
<span className="text-gray-300 whitespace-nowrap">{t('fiatValue', { currencyType: currency.label })}</span>
<span className="text-gray-100 whitespace-nowrap truncate">
{NumberHelper.currency(estimatedFiat, currency.label)}
</span>
</div>
</div>
)
Expand Down
11 changes: 7 additions & 4 deletions src/renderer/src/routes/pages/Portfolio/Activity/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,26 @@ import { useTranslation } from 'react-i18next'
import { Separator } from '@renderer/components/Separator'
import { TransactionsTable } from '@renderer/components/TransactionsTable'
import { BalanceHelper } from '@renderer/helpers/BalanceHelper'
import { FilterHelper } from '@renderer/helpers/FilterHelper'
import { NumberHelper } from '@renderer/helpers/NumberHelper'
import { useAccountsSelector } from '@renderer/hooks/useAccountSelector'
import { useBalancesAndExchange } from '@renderer/hooks/useBalancesAndExchange'
import { useCurrencySelector } from '@renderer/hooks/useSettingsSelector'
import { useWalletsSelector } from '@renderer/hooks/useWalletSelector'

export const PortfolioActivityPage = () => {
const { t } = useTranslation('pages', { keyPrefix: 'portfolio.portfolioActivity' })
const { accounts } = useAccountsSelector()
const { wallets } = useWalletsSelector()
const { currency } = useCurrencySelector()
const balanceExchange = useBalancesAndExchange(accounts)

const formattedTotalTokensBalances = useMemo(
() =>
FilterHelper.currency(
BalanceHelper.calculateTotalBalances(balanceExchange.balance.data, balanceExchange.exchange.data)
NumberHelper.currency(
BalanceHelper.calculateTotalBalances(balanceExchange.balance.data, balanceExchange.exchange.data) || 0,
currency.label
),
[balanceExchange.balance.data, balanceExchange.exchange.data]
[balanceExchange.balance.data, balanceExchange.exchange.data, currency.label]
)

return (
Expand Down
Loading

0 comments on commit 8603418

Please sign in to comment.