foldEntryUsd function

FoldUsd foldEntryUsd({
  1. required int signedAmountMicros,
  2. required String currency,
  3. required String usdRate,
})

Converts signedAmountMicros (signed micros of currency's major unit) to signed micros of USD via usdRate.

Throws a StateError if currency is USD and usdRate is not exactly 1 (USD must be the identity). Throws a FormatException if usdRate is not a non-negative plain decimal string. Returns FoldUsdOverflow if the converted value would not fit a signed 64-bit integer.

Implementation

FoldUsd foldEntryUsd({
  required int signedAmountMicros,
  required String currency,
  required String usdRate,
}) {
  final (:num, :den) = _parseDecimalRate(usdRate);
  final micros = BigInt.from(signedAmountMicros);

  if (currency == 'USD') {
    // USD is the identity: the rate must be exactly 1 (num == den). A non-1
    // USD rate is a data/programming error, not a recoverable hold.
    if (num != den) {
      throw StateError('USD must convert at rate 1, got "$usdRate".');
    }
    if (micros.abs() > _int64Max) {
      return const FoldUsdOverflow();
    }
    return FoldUsdValue(signedAmountMicros);
  }

  // Magnitude only — the sign is re-applied after rounding so a negative
  // amount is the exact negation of its positive twin (half-even is
  // sign-symmetric).
  final magnitude = _roundHalfEvenDiv(micros.abs() * num, den);
  final signed = signedAmountMicros < 0 ? -magnitude : magnitude;

  if (signed.abs() > _int64Max) {
    return const FoldUsdOverflow();
  }
  return FoldUsdValue(signed.toInt());
}