Skip to content

Commit

Permalink
refactor: rewrite shannonToCKBFormatter with formatUnit (#3129)
Browse files Browse the repository at this point in the history
Co-authored-by: Chen Yu <[email protected]>
  • Loading branch information
twhy and Keith-CY authored Apr 19, 2024
1 parent 3981ba6 commit 820e073
Show file tree
Hide file tree
Showing 10 changed files with 20 additions and 44 deletions.
2 changes: 1 addition & 1 deletion packages/neuron-ui/src/components/AddressBook/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ const AddressBook = ({ onClose }: { onClose?: () => void }) => {
return `${HIDE_BALANCE} CKB`
}
return (
<CopyZone content={shannonToCKBFormatter(balance, false, '')} className={styles.copyBalance}>
<CopyZone content={shannonToCKBFormatter(balance, false, false)} className={styles.copyBalance}>
<span className="textOverflow">{`${shannonToCKBFormatter(balance)} CKB`}</span>
</CopyZone>
)
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-ui/src/components/Balance/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const Balance = ({ balance, connectionStatus, syncStatus }: BalanceProps) => {
return (
<>
<span>{`${t('overview.balance')}:`}</span>
<CopyZone content={shannonToCKBFormatter(balance, false, '')} name={t('overview.copy-balance')}>
<CopyZone content={shannonToCKBFormatter(balance, false, false)} name={t('overview.copy-balance')}>
<span className={styles.balanceValue}>{shannonToCKBFormatter(balance)}</span>
</CopyZone>
<BalanceSyncIcon connectionStatus={connectionStatus} syncStatus={syncStatus} />
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-ui/src/components/DepositDialog/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export const useGenerateDaoDepositTx = ({
payload: res,
})
if (isDepositAll) {
setMaxDepositValue(shannonToCKBFormatter(res?.outputs[0]?.capacity ?? '0', false, ''))
setMaxDepositValue(shannonToCKBFormatter(res?.outputs[0]?.capacity ?? '0', false, false))
if (!isBalanceReserved) {
setErrorMessage(t('messages.remain-ckb-for-withdraw'))
}
Expand Down Expand Up @@ -181,7 +181,7 @@ export const useDepositValue = (balance: string, showDepositDialog: boolean) =>
const amount = shannonToCKBFormatter(
((BigInt(percent) * BigInt(balance)) / BigInt(PERCENT_100)).toString(),
false,
''
false
)
setDepositValue(padFractionDigitsIfDecimal(amount, 8))
},
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-ui/src/components/NervosDAO/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ const NervosDAO = () => {
</>
) : (
<CopyZone
content={shannonToCKBFormatter(`${free}`, false, '')}
content={shannonToCKBFormatter(`${free}`, false, false)}
name={t('nervos-dao.copy-balance')}
className={styles.balance}
>
Expand All @@ -303,7 +303,7 @@ const NervosDAO = () => {
<div className={styles.value}>
{onlineAndSynced && !isPrivacyMode ? (
<CopyZone
content={shannonToCKBFormatter(`${locked}`, false, '')}
content={shannonToCKBFormatter(`${locked}`, false, false)}
name={t('nervos-dao.copy-balance')}
className={styles.balance}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ const TabsVariantWithTxTypes = ({
{isIncomeShow ? (
<div className={clsx(styles.fieldValue, styles.fullRow, styles.income)}>
<CopyZone
content={shannonToCKBFormatter(transaction.value, false, '')}
content={shannonToCKBFormatter(transaction.value, false, false)}
className={styles.incomeCopy}
maskRadius={8}
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ export const DAORecord = ({
) : (
<CopyZone
className={clsx(styles.amount, styles.withCopy)}
content={shannonToCKBFormatter(capacity, false, '')}
content={shannonToCKBFormatter(capacity, false, false)}
>
{`${shannonToCKBFormatter(capacity)} CKB`}
</CopyZone>
Expand Down
4 changes: 2 additions & 2 deletions packages/neuron-ui/src/components/Overview/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ const Overview = () => {
)}
</span>
{showBalance ? (
<CopyZone content={shannonToCKBFormatter(balance, false, '')} className={styles.copyBalance}>
<CopyZone content={shannonToCKBFormatter(balance, false, false)} className={styles.copyBalance}>
<span className={styles.balanceValue}>{shannonToCKBFormatter(balance)}</span>
</CopyZone>
) : (
Expand All @@ -191,7 +191,7 @@ const Overview = () => {
<Lock />
<span className={styles.lockedTitle}>{t('overview.locked-balance')}&nbsp;:</span>
{showBalance ? (
<CopyZone content={shannonToCKBFormatter(balance, false, '')}>
<CopyZone content={shannonToCKBFormatter(balance, false, false)}>
<span className={styles.lockedBalance}>{shannonToCKBFormatter(lockedBalance)}</span>
</CopyZone>
) : (
Expand Down
2 changes: 1 addition & 1 deletion packages/neuron-ui/src/components/Send/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ const updateTransactionWith =
if (type === 'all') {
const fmtItems = items.map((item, i) => ({
...item,
amount: shannonToCKBFormatter(res.result.outputs[i].capacity, false, ''),
amount: shannonToCKBFormatter(res.result.outputs[i].capacity, false, false),
}))
const totalAmount = outputsToTotalAmount(fmtItems)
setTotalAmount(totalAmount)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ export const useSendInfo = ({
...v.slice(0, v.length - 1),
{
...v[v.length - 1],
amount: shannonToCKBFormatter(res.outputs[res.outputs.length - 1].capacity, false, ''),
amount: shannonToCKBFormatter(res.outputs[res.outputs.length - 1].capacity, false, false),
disabled: true,
},
])
Expand Down
40 changes: 8 additions & 32 deletions packages/neuron-ui/src/utils/formatters.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { formatUnit } from '@ckb-lumos/bi'
import { molecule } from '@ckb-lumos/codec'
import { blockchain } from '@ckb-lumos/base'
import { formatUnit, ckbDecimals } from '@ckb-lumos/bi'
import { TFunction } from 'i18next'
import { FailureFromController } from 'services/remote/remoteApiWrapper'
import { CapacityUnit } from './enums'
Expand Down Expand Up @@ -104,40 +104,16 @@ export const CKBToShannonFormatter = (amount: string = '0', unit: CapacityUnit =
}
}

export const shannonToCKBFormatter = (shannon: string, showPositiveSign?: boolean, delimiter: string = ',') => {
export const shannonToCKBFormatter = (shannon: string, showPositiveSign?: boolean, showCommaSeparator = true) => {
if (Number.isNaN(+shannon)) {
console.warn(`Shannon is not a valid number`)
console.warn(`Invalid shannon value: ${shannon}`)
return shannon
}
if (shannon === null) {
return '0'
}
let sign = ''
if (shannon.startsWith('-')) {
sign = '-'
} else if (showPositiveSign) {
sign = '+'
}
const unsignedShannon = shannon.replace(/^-?0*/, '')
let unsignedCKB = ''
if (unsignedShannon.length <= 8) {
unsignedCKB = `0.${unsignedShannon.padStart(8, '0')}`.replace(/\.?0+$/, '')
} else {
const decimal = `.${unsignedShannon.slice(-8)}`.replace(/\.?0+$/, '')
const int = unsignedShannon.slice(0, -8).replace(/\^0+/, '')
unsignedCKB = `${(
int
.split('')
.reverse()
.join('')
.match(/\d{1,3}/g) || ['0']
)
.join(delimiter)
.split('')
.reverse()
.join('')}${decimal}`
}
return +unsignedCKB === 0 ? '0' : `${sign}${unsignedCKB}`
return new Intl.NumberFormat('en-US', {
useGrouping: showCommaSeparator,
signDisplay: showPositiveSign && +shannon > 0 ? 'always' : 'auto',
maximumFractionDigits: ckbDecimals,
}).format(formatUnit(BigInt(shannon ?? '0'), 'ckb') as any)
}

export const localNumberFormatter = (num: string | number | bigint = 0) => {
Expand Down

2 comments on commit 820e073

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packaging for test is done in 8751949925

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Packaging for test is done in 8751951367

Please sign in to comment.