import { ceilDiv, parseDecimalToUnits } from './amounts'; /** Rates are stored as integer units: fiat per 1 whole token, scaled by 1e6. */ export const RATE_DECIMALS = 6; /** * Convert a fiat amount (decimal string) into crypto base units at the given rate. * Rounds UP by one base unit at most, so the merchant never receives less fiat * value than invoiced. No floating point anywhere. */ export function pegCryptoAmount(fiatAmount: string, rateUnits: bigint, tokenDecimals = 6): bigint { if (rateUnits <= 0n) throw new Error('rate must be positive'); const fiatUnits = parseDecimalToUnits(fiatAmount, RATE_DECIMALS); if (fiatUnits <= 0n) throw new Error('fiat amount must be positive'); return ceilDiv(fiatUnits * 10n ** BigInt(tokenDecimals), rateUnits); }