Reject zero and invalid exchange rates for every provider

Merged
GF
2mo ago
+336-26

A provider occasionally answers a single-rate lookup with a zero rate. ExchangeRate.find_or_fetch_rate stored it (the model only checked presence), and every conversion that picked it up turned the balance into zero: net worth dropped the account and the balance chart fell to 0 for that day. The bulk import path already skipped such rows, but only because TwelveData filtered them itself.

Validity is now enforced independently of the provider:

  • Provider::ExchangeRateConcept prepends a validation to every provider that includes it, including ones added later. A single lookup with an unusable rate becomes a failed response; unusable rows are dropped from a series, so the importer carries the previous rate forward. Both are recorded as a DebugLogEntry.
  • ExchangeRate validates that a rate is finite and positive.
  • A check constraint rejects zero, negative and NaN rates for writes that skip validations, like the importer's upsert_all. The migration deletes existing invalid rows; the next sync refetches those dates.
  • The importer skips inverse rates that round to zero at 12 decimals instead of storing them.

A rate of exactly 1 stays valid: pegged currencies convert at parity.

Two tests stored a zero rate to cover downstream guards. The transfer matching one is removed since that state can no longer exist; the trade one now supplies the rate through the preload.

Refs we-promise/sure#1187

Summary by CodeRabbit

  • Bug Fixes
    • Zero, negative, non-numeric, and infinite exchange rates are rejected. Invalid provider rates are excluded from results, and invalid inverse rates are not stored.
    • Database safeguards also reject invalid rates submitted through bulk operations.
    • Existing stored rates that fail the new requirements are removed during migration.
  • Documentation
    • Added guidance on how invalid exchange rates are handled.