31 lines
807 B
TypeScript
31 lines
807 B
TypeScript
|
|
const WEI_DECIMALS = 18n
|
||
|
|
|
||
|
|
export function formatWeiAsEth(value: string, fractionDigits = 4): string {
|
||
|
|
try {
|
||
|
|
const normalizedDigits = Math.max(0, Math.min(18, fractionDigits))
|
||
|
|
const wei = BigInt(value)
|
||
|
|
const divisor = 10n ** WEI_DECIMALS
|
||
|
|
const whole = wei / divisor
|
||
|
|
const fraction = wei % divisor
|
||
|
|
|
||
|
|
if (normalizedDigits === 0) {
|
||
|
|
return `${whole.toString()} ETH`
|
||
|
|
}
|
||
|
|
|
||
|
|
const scale = 10n ** (WEI_DECIMALS - BigInt(normalizedDigits))
|
||
|
|
const truncatedFraction = fraction / scale
|
||
|
|
const paddedFraction = truncatedFraction
|
||
|
|
.toString()
|
||
|
|
.padStart(normalizedDigits, '0')
|
||
|
|
.replace(/0+$/, '')
|
||
|
|
|
||
|
|
if (!paddedFraction) {
|
||
|
|
return `${whole.toString()} ETH`
|
||
|
|
}
|
||
|
|
|
||
|
|
return `${whole.toString()}.${paddedFraction} ETH`
|
||
|
|
} catch {
|
||
|
|
return '0 ETH'
|
||
|
|
}
|
||
|
|
}
|