|
1 | | -import { clsx, type ClassValue } from "clsx" |
2 | | -import { twMerge } from "tailwind-merge" |
| 1 | +import { clsx, type ClassValue } from 'clsx' |
| 2 | +import { twMerge } from 'tailwind-merge' |
3 | 3 |
|
4 | 4 | export function cn(...inputs: ClassValue[]) { |
5 | 5 | return twMerge(clsx(inputs)) |
6 | 6 | } |
| 7 | + |
| 8 | +export const NEAR_NOMINATION_EXP = 24 |
| 9 | + |
| 10 | +// Pre-calculate offsets used for rounding to different number of digits |
| 11 | +const ROUNDING_OFFSETS: bigint[] = [] |
| 12 | +const BN10 = 10n |
| 13 | +for (let i = 0, offset = 5n; i < NEAR_NOMINATION_EXP; i++, offset = offset * BN10) { |
| 14 | + ROUNDING_OFFSETS[i] = offset |
| 15 | +} |
| 16 | + |
| 17 | +function trimTrailingZeroes(value: string): string { |
| 18 | + return value.replace(/\.?0*$/, '') |
| 19 | +} |
| 20 | + |
| 21 | +function formatWithCommas(value: string): string { |
| 22 | + const pattern = /(-?\d+)(\d{3})/ |
| 23 | + while (pattern.test(value)) { |
| 24 | + value = value.replace(pattern, '$1,$2') |
| 25 | + } |
| 26 | + return value |
| 27 | +} |
| 28 | + |
| 29 | +export function formatNearAmount( |
| 30 | + balance: string, |
| 31 | + fracDigits: number = NEAR_NOMINATION_EXP |
| 32 | +): string { |
| 33 | + let balanceBN = BigInt(balance) |
| 34 | + if (fracDigits !== NEAR_NOMINATION_EXP) { |
| 35 | + // Adjust balance for rounding at given number of digits |
| 36 | + const roundingExp = NEAR_NOMINATION_EXP - fracDigits - 1 |
| 37 | + if (roundingExp > 0) { |
| 38 | + balanceBN += ROUNDING_OFFSETS[roundingExp] |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + balance = balanceBN.toString() |
| 43 | + const wholeStr = balance.substring(0, balance.length - NEAR_NOMINATION_EXP) || '0' |
| 44 | + const fractionStr = balance |
| 45 | + .substring(balance.length - NEAR_NOMINATION_EXP) |
| 46 | + .padStart(NEAR_NOMINATION_EXP, '0') |
| 47 | + .substring(0, fracDigits) |
| 48 | + |
| 49 | + return trimTrailingZeroes(`${formatWithCommas(wholeStr)}.${fractionStr}`) |
| 50 | +} |
0 commit comments