UNPKG

@cranberry-money/shared-utils

Version:

Shared utility functions for Blueberry platform

65 lines 2.56 kB
import { getChainShortCode } from '@cranberry-money/shared-constants'; export function formatCurrency(value, options = {}) { if (value === undefined || value === null || isNaN(value)) return '—'; const { currency = 'AUD', locale = 'en-AU', decimals = 2, minimumFractionDigits = decimals, maximumFractionDigits = decimals, } = options; return new Intl.NumberFormat(locale, { style: 'currency', currency, minimumFractionDigits, maximumFractionDigits, }).format(value); } export function formatCryptoBalance(balance, symbol, decimals = 8) { const balanceNum = typeof balance === 'string' ? parseFloat(balance) : balance; if (balanceNum === 0) return `0 ${symbol}`; const formatted = balanceNum.toFixed(decimals).replace(/\.?0+$/, ''); return `${formatted} ${symbol}`; } export function getBlockchainShortName(chainName) { return getChainShortCode(chainName); } export function formatPercentage(value, decimals = 2) { if (value === undefined || value === null || isNaN(value)) return '—'; return `${value.toFixed(decimals)}%`; } /** * Convert raw token amount to human-readable display format. * Handles blockchain amounts that are stored as integers with implied decimals. * * @param rawAmount - Raw amount from blockchain (e.g., 4430 for 44.30 with 2 decimals) * @param decimals - Token decimals (e.g., 2 for aAUD, 18 for ETH) * @returns Formatted string (e.g., "44.30") * * @example * formatTokenAmount(4430, 2) // "44.30" * formatTokenAmount("1000000000000000000", 18) // "1.000000000000000000" */ export function formatTokenAmount(rawAmount, decimals) { const raw = typeof rawAmount === 'string' ? parseInt(rawAmount, 10) : rawAmount; if (isNaN(raw) || decimals === 0) return raw.toString(); const divisor = Math.pow(10, decimals); return (raw / divisor).toFixed(decimals); } /** * Convert human-readable amount to raw token units for blockchain operations. * * @param displayAmount - Human-readable amount (e.g., "10.50") * @param decimals - Token decimals (e.g., 2 for aAUD) * @returns Raw amount for blockchain (e.g., 1050) * * @example * parseTokenAmount("10.50", 2) // 1050 * parseTokenAmount("1.5", 18) // 1500000000000000000 */ export function parseTokenAmount(displayAmount, decimals) { const parsed = parseFloat(displayAmount); if (isNaN(parsed)) return 0; const multiplier = Math.pow(10, decimals); return Math.round(parsed * multiplier); } //# sourceMappingURL=formatting.js.map