import { formatUnits } from "viem" import { normalizePrecision } from "./numbers" /** * Formats a number as a currency * @param value The value to format * @param options The options to pass to the formatter * @returns The formatted currency */ export function formatCurrency( value: number, options: Omit, ): string { const formatter = new Intl.NumberFormat("en-US", { style: "currency", minimumFractionDigits: 2, maximumFractionDigits: 2, ...options, }) return formatter.format(value) } /** * Formats a number as a USD currency * @param value The value to format * @returns The formatted currency */ export function formatUsd(value: number | string): string { return formatCurrency(Number(value), { currency: "USD" }) } /** * Converts an asset amount to USD based on a conversion rate and decimals * @param assetAmount - The amount of the asset in its smallest unit (e.g., satoshis for BTC) * @param conversionRate - The conversion rate from the asset to USD in fixed-point format * @param decimals - The number of decimals for the asset * @returns - The value in USD as a number */ export function convertToUsd( assetAmount: bigint, assetDecimals: number, conversionRate: bigint, conversionRateDecimals: number, ) { const value = normalizePrecision( assetAmount * conversionRate, assetDecimals + conversionRateDecimals, conversionRateDecimals, ) const formatted = formatUnits(value, conversionRateDecimals) return { value, formatted, } }