Skip to content

Commit

Permalink
Use BigNumber for number formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
csillag committed Apr 27, 2023
1 parent 57be353 commit 6273034
Show file tree
Hide file tree
Showing 12 changed files with 86 additions and 49 deletions.
3 changes: 2 additions & 1 deletion src/app/components/Account/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { TextSkeleton } from '../../components/Skeleton'
import { type RuntimeAccount } from '../../../oasis-indexer/api'
import { TokenPills } from './TokenPills'
import { AccountLink } from './AccountLink'
import { formatNumber } from '../../utils/numberFormatter'

export const StyledAvatarContainer = styled('dt')(({ theme }) => ({
'&&': {
Expand Down Expand Up @@ -95,7 +96,7 @@ export const Account: FC<AccountProps> = ({ account, isLoading, roseFiatValue, s
)}

<dt>{t('common.transactions')}</dt>
<dd>{account.stats.num_txns}</dd>
<dd>{formatNumber(account.stats.num_txns)}</dd>

<dt>{t('account.evmTokens')}</dt>
<dd>
Expand Down
3 changes: 2 additions & 1 deletion src/app/components/Blocks/BlockLink.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import Link from '@mui/material/Link'
import { Layer } from '../../../oasis-indexer/api'
import { RouteUtils } from '../../utils/route-utils'
import { TrimLinkLabel } from '../TrimLinkLabel'
import { formatNumber } from '../../utils/numberFormatter'

export const BlockLink: FC<{ layer: Layer; height: number }> = ({ layer, height }) => (
<Typography variant="mono">
<Link component={RouterLink} to={RouteUtils.getBlockRoute(height, layer)}>
{height.toLocaleString()}
{formatNumber(height)}
</Link>
</Typography>
)
Expand Down
18 changes: 7 additions & 11 deletions src/app/components/Blocks/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Table, TableCellAlign, TableColProps } from '../../components/Table'
import { paraTimesConfig } from '../../../config'
import { TablePaginationProps } from '../Table/TablePagination'
import { BlockHashLink, BlockLink } from './BlockLink'
import { formatNumber } from '../../utils/numberFormatter'

export type TableRuntimeBlock = RuntimeBlock & {
markAsNew?: boolean
Expand Down Expand Up @@ -66,7 +67,7 @@ export const Blocks = (props: BlocksProps) => {
},
{
align: TableCellAlign.Right,
content: block.num_transactions,
content: formatNumber(block.num_transactions),
key: 'txs',
},
...(verbose
Expand All @@ -80,22 +81,17 @@ export const Blocks = (props: BlocksProps) => {
{
align: TableCellAlign.Right,
content: t('common.bytes', {
value: block.size,
formatParams: {
value: {
style: 'unit',
unit: 'byte',
unitDisplay: 'long',
} satisfies Intl.NumberFormatOptions,
},
value: formatNumber(block.size, {
unit: 'byte',
}),
}),
key: 'size',
},
...(verbose
? [
{
align: TableCellAlign.Right,
content: block.gas_used.toLocaleString(),
content: formatNumber(block.gas_used),
key: 'gasUsed',
},
]
Expand All @@ -104,7 +100,7 @@ export const Blocks = (props: BlocksProps) => {
? [
{
align: TableCellAlign.Right,
content: blockGasLimit.toLocaleString(),
content: formatNumber(blockGasLimit),
key: 'gasLimit',
},
]
Expand Down
16 changes: 6 additions & 10 deletions src/app/pages/BlockDetailPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { transactionsContainerId } from './TransactionsCard'
import { useLayerParam } from '../../hooks/useLayerParam'
import { BlockLink, BlockHashLink } from '../../components/Blocks/BlockLink'
import { RouteUtils } from '../../utils/route-utils'
import { formatNumber } from '../../utils/numberFormatter'

export const BlockDetailPage: FC = () => {
const { t } = useTranslation()
Expand Down Expand Up @@ -101,14 +102,9 @@ export const BlockDetailView: FC<{
<dt>{t('common.size')}</dt>
<dd>
{t('common.bytes', {
value: block.size,
formatParams: {
value: {
style: 'unit',
unit: 'byte',
unitDisplay: 'long',
} satisfies Intl.NumberFormatOptions,
},
value: formatNumber(block.size, {
unit: 'byte',
}),
})}
</dd>

Expand All @@ -122,7 +118,7 @@ export const BlockDetailView: FC<{
<dt>{t('common.gasUsed')}</dt>
<dd>
{t('block.gasUsed', {
value: block.gas_used,
value: formatNumber(block.gas_used),
percentage: block.gas_used / blockGasLimit,
formatParams: {
percentage: {
Expand All @@ -134,7 +130,7 @@ export const BlockDetailView: FC<{
</dd>

<dt>{t('common.gasLimit')}</dt>
<dd>{blockGasLimit.toLocaleString()}</dd>
<dd>{formatNumber(blockGasLimit)}</dd>
</StyledDescriptionList>
)
}
9 changes: 6 additions & 3 deletions src/app/pages/DashboardPage/ActiveAccounts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
sumBucketsByStartDuration,
} from '../../utils/chart-utils'
import { useLayerParam } from '../../hooks/useLayerParam'
import { formatNumber } from '../../utils/numberFormatter'

export const getActiveAccountsWindows = (duration: ChartDuration, windows: Windows[]) => {
switch (duration) {
Expand Down Expand Up @@ -80,8 +81,10 @@ export const ActiveAccounts: FC<ActiveAccountsProps> = ({ chartDuration }) => {
getActiveAccountsWindows(chartDuration, activeAccountsQuery.data?.data?.windows)
const totalNumberLabel =
dailyChart && windows?.length
? windows[0].active_accounts.toLocaleString()
: windows?.reduce((acc, curr) => acc + curr.active_accounts, 0).toLocaleString()
? formatNumber(windows[0].active_accounts)
: windows
? formatNumber(windows.reduce((acc, curr) => acc + curr.active_accounts, 0))
: undefined

return (
<SnapshotCard title={t('activeAccounts.title')} label={totalNumberLabel}>
Expand All @@ -93,7 +96,7 @@ export const ActiveAccounts: FC<ActiveAccountsProps> = ({ chartDuration }) => {
formatters={{
data: (value: number) =>
t('activeAccounts.tooltip', {
value,
value: formatNumber(value),
}),
label: (value: string) =>
t('common.formattedDateTime', {
Expand Down
3 changes: 2 additions & 1 deletion src/app/pages/DashboardPage/Nodes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { COLORS } from '../../../styles/theme/colors'
import { Layer, useGetRuntimeStatus } from '../../../oasis-indexer/api'
import { useLayerParam } from '../../hooks/useLayerParam'
import { AppErrors } from '../../../types/errors'
import { formatNumber } from '../../utils/numberFormatter'

export const Nodes: FC = () => {
const { t } = useTranslation()
Expand All @@ -25,7 +26,7 @@ export const Nodes: FC = () => {
<>
<OfflineBoltIcon fontSize="large" sx={{ color: COLORS.eucalyptus, mr: 3 }} />
<Typography component="span" sx={{ fontSize: '48px', fontWeight: 700, color: COLORS.brandDark }}>
{t('nodes.value', { value: activeNodes })}
{formatNumber(activeNodes)}
</Typography>
</>
)}
Expand Down
10 changes: 4 additions & 6 deletions src/app/pages/DashboardPage/TotalTransactions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { DurationPills } from './DurationPills'
import { CardHeaderWithResponsiveActions } from './CardHeaderWithResponsiveActions'
import { ChartDuration, cumulativeSum } from '../../utils/chart-utils'
import { useLayerParam } from '../../hooks/useLayerParam'
import { formatNumber } from '../../utils/numberFormatter'

export const TotalTransactions: FC = () => {
const { t } = useTranslation()
Expand Down Expand Up @@ -47,12 +48,9 @@ export const TotalTransactions: FC = () => {
formatters={{
data: (value: number) =>
t('totalTransactions.tooltip', {
value,
formatParams: {
value: {
maximumFractionDigits: 2,
} satisfies Intl.NumberFormatOptions,
},
value: formatNumber(value, {
maximumFractionDigits: 2,
})!,
}),
label: (value: string) =>
t('common.formattedDateTime', {
Expand Down
12 changes: 5 additions & 7 deletions src/app/pages/DashboardPage/TransactionsChartCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { SnapshotCard } from './SnapshotCard'
import { PercentageGain } from '../../components/PercentageGain'
import startOfHour from 'date-fns/startOfHour'
import { useLayerParam } from '../../hooks/useLayerParam'
import { formatNumber } from '../../utils/numberFormatter'

interface TransactionsChartCardProps {
chartDuration: ChartDuration
Expand Down Expand Up @@ -67,7 +68,7 @@ const TransactionsChartCardCmp: FC<TransactionsChartCardProps> = ({ chartDuratio
/>
)
}
label={totalTransactions.toLocaleString()}
label={formatNumber(totalTransactions)}
>
{lineChartData && (
<LineChart
Expand All @@ -77,12 +78,9 @@ const TransactionsChartCardCmp: FC<TransactionsChartCardProps> = ({ chartDuratio
formatters={{
data: (value: number) =>
t('transactionsTpsChart.tooltip', {
value,
formatParams: {
value: {
maximumFractionDigits: 2,
} satisfies Intl.NumberFormatOptions,
},
value: formatNumber(value, {
maximumFractionDigits: 2,
}),
}),
label: (value: string) =>
t('common.formattedDateTime', {
Expand Down
3 changes: 2 additions & 1 deletion src/app/pages/DashboardPage/TransactionsStats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { DurationPills } from './DurationPills'
import { CardHeaderWithResponsiveActions } from './CardHeaderWithResponsiveActions'
import { ChartDuration } from '../../utils/chart-utils'
import { useLayerParam } from '../../hooks/useLayerParam'
import { formatNumber } from '../../utils/numberFormatter'

export const TransactionsStats: FC = () => {
const { t } = useTranslation()
Expand Down Expand Up @@ -55,7 +56,7 @@ export const TransactionsStats: FC = () => {
data={buckets.slice().reverse()}
dataKey="tx_volume"
formatters={{
data: (value: number) => t('transactionStats.tooltip', { value: value.toLocaleString() }),
data: (value: number) => t('transactionStats.tooltip', { value: formatNumber(value) }),
label: (value: string) =>
t('common.formattedDateTime', {
timestamp: new Date(value),
Expand Down
3 changes: 2 additions & 1 deletion src/app/pages/TransactionDetailPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { useLayerParam } from '../../hooks/useLayerParam'
import { BlockLink } from '../../components/Blocks/BlockLink'
import { TransactionLink } from '../../components/Transactions/TransactionLink'
import { TransactionLogs } from '../../components/Transactions/Logs'
import { formatNumber } from '../../utils/numberFormatter'

type TransactionSelectionResult = {
wantedTransaction?: RuntimeTransaction
Expand Down Expand Up @@ -204,7 +205,7 @@ export const TransactionDetailView: FC<{
<dd>{t('common.valueInRose', { value: transaction.fee })}</dd>

<dt>{t('common.gasLimit')}</dt>
<dd>{transaction.gas_limit.toLocaleString()}</dd>
<dd>{formatNumber(transaction.gas_limit)}</dd>
</StyledDescriptionList>
)}
</>
Expand Down
42 changes: 42 additions & 0 deletions src/app/utils/numberFormatter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { BigNumber } from 'bignumber.js'

export type NumberFormattingParameters = Partial<BigNumber.Format> & {
// Additional features which are not natively supported by BigNumber

decimalPlaces?: number
maximumFractionDigits?: number
roundingMode?: BigNumber.RoundingMode
unit?: string
}

export const formatNumber = (
inputNumber: number | string | BigNumber.Instance | undefined,
format: NumberFormattingParameters = {},
): string | undefined => {
if (inputNumber === undefined) return
const { decimalPlaces, maximumFractionDigits, roundingMode, unit, ...formatting } = format
let number =
typeof inputNumber === 'number'
? BigNumber(inputNumber.toString(2), 2) // This is required to keep all precision
: BigNumber(inputNumber)
if (maximumFractionDigits !== undefined) {
number = BigNumber(number.toFixed(maximumFractionDigits, roundingMode))
}
const wantedFormat = { ...BigNumber.config().FORMAT, ...formatting }
const numberString =
decimalPlaces === undefined
? number.toFormat(wantedFormat)
: roundingMode === undefined
? number.toFormat(decimalPlaces, wantedFormat)
: number.toFormat(decimalPlaces, roundingMode, wantedFormat)
if (unit) {
const formattedUnit = number
.toNumber()
.toLocaleString(undefined, { style: 'unit', unit, unitDisplay: 'long' })
.split(' ')
.at(-1)
return `${numberString} ${formattedUnit}`
} else {
return numberString
}
}
13 changes: 6 additions & 7 deletions src/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
},
"activeAccounts": {
"title": "Active Accounts",
"tooltip": "{{value, number}} accounts"
"tooltip": "{{value}} accounts"
},
"blocks": {
"latest": "Latest Blocks"
},
"block": {
"gasUsed": "{{value, number}} | {{percentage, number}}"
"gasUsed": "{{value}} | {{percentage, number}}"
},
"buildInternal": "Please note this is an internal launch meant to gather your feedback. Please share your feedback with screenshots through this from: ",
"buildPreview": "Please note this is an experimental build of Oasis Explorer and that data that is shown might be incorrect.",
Expand All @@ -34,7 +34,7 @@
"active": "Active",
"balance": "Balance",
"block": "Block",
"bytes": "{{value, number}}",
"bytes": "{{value}}",
"change": "Change",
"data": "Data",
"emerald": "Emerald",
Expand Down Expand Up @@ -79,8 +79,7 @@
"paraTimeOnline": "ParaTime Online"
},
"nodes": {
"title": "Active nodes",
"value": "{{value, number}}"
"title": "Active nodes"
},
"errors": {
"code": "error code",
Expand Down Expand Up @@ -152,7 +151,7 @@
},
"totalTransactions": {
"header": "Total Transactions",
"tooltip": "{{value, number}} total transactions"
"tooltip": "{{value}} total transactions"
},
"transactions": {
"latest": "Latest Transactions",
Expand Down Expand Up @@ -186,7 +185,7 @@
"tooltip": "{{value}} tx/day"
},
"transactionsTpsChart": {
"tooltip": "{{value, number}} TPS"
"tooltip": "{{value}} TPS"
},
"select": {
"placeholder": "Select"
Expand Down

0 comments on commit 6273034

Please sign in to comment.