Skip to content

Commit

Permalink
refactor: rewrite sudtValueToAmount with formatUnit in neuron-wallet (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
twhy authored Apr 12, 2024
1 parent 3d3e767 commit de1df5d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 29 deletions.
37 changes: 8 additions & 29 deletions packages/neuron-wallet/src/utils/sudt-value-to-amount.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,11 @@
const sudtValueToAmount = (value: string | null | undefined = '0', decimal: string | null | undefined = '') => {
if (value === null || value === '0') {
return '+0'
}

if (decimal === null || decimal === undefined || Number.isNaN(+value)) {
return '--'
}

let sign = '+'
if (value.startsWith('-')) {
sign = '-'
}

const unsignedValue = value.replace(/^-?0*/, '')

const dec = +decimal
if (dec === 0) {
return +unsignedValue ? `${sign}${unsignedValue}` : '+0'
}
let unsignedSUDTValue = ''
if (unsignedValue.length <= dec) {
unsignedSUDTValue = `0.${unsignedValue.padStart(dec, '0')}`.replace(/\.?0+$/, '')
} else {
const decimalFraction = `.${unsignedValue.slice(-dec)}`.replace(/\.?0+$/, '')
const int = unsignedValue.slice(0, -dec).replace(/\^0+/, '')
unsignedSUDTValue = `${int}${decimalFraction}`
}
return `${sign}${unsignedSUDTValue}`
import { formatUnit } from '@ckb-lumos/bi'

const sudtValueToAmount = (value: string | null = '0', decimal: string | null = '') => {
return value === null || value === '0'
? '+0'
: decimal === null || Number.isNaN(+value) || Number.isNaN(+decimal)
? '--'
: `${+value >= 0 ? '+' : ''}${formatUnit(BigInt(value), +decimal)}`
}

export default sudtValueToAmount
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,21 @@
"decimal": "12",
"expected": "+0"
},
"null value and null decimal": {
"value": null,
"decimal": null,
"expected": "+0"
},
"zero value": {
"value": "0",
"decimal": "1",
"expected": "+0"
},
"zero value and null decimal": {
"value": "0",
"decimal": null,
"expected": "+0"
},
"negative value": {
"value": "-1",
"decimal": "1",
Expand Down

2 comments on commit de1df5d

@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 8660067732

@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 8660069418

Please sign in to comment.