1
0
Fork 0
mirror of https://github.com/maybe-finance/maybe.git synced 2025-08-02 20:15:22 +02:00

Implement Synth as an exchange rate provider (#574)

* Implement Synth as an exchange rate provider

* Add assertions to provider interface test

* Assert the correct provider error is raised

* Remove unnecessary parens
This commit is contained in:
Jose Farias 2024-03-27 09:16:00 -06:00 committed by GitHub
parent a1b25f1c5b
commit 7ae25dd6df
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 310 additions and 34 deletions

View file

@ -1,42 +1,22 @@
class ExchangeRate < ApplicationRecord
include Provided
validates :base_currency, :converted_currency, presence: true
class << self
def convert(from, to, amount)
rate = ExchangeRate.find_by(base_currency: from, converted_currency: to, date: Date.current)
return nil if rate.nil?
amount * rate.rate
def find_rate(from:, to:, date:)
find_by \
base_currency: Money::Currency.new(from).iso_code,
converted_currency: Money::Currency.new(to).iso_code,
date: date
end
def get_rate(from, to, date)
_from = Money::Currency.new(from)
_to = Money::Currency.new(to)
find_by! base_currency: _from.iso_code, converted_currency: _to.iso_code, date: date
rescue
logger.warn "Exchange rate not found for #{_from.iso_code} to #{_to.iso_code} on #{date}"
nil
def find_rate_or_fetch(from:, to:, date:)
find_rate(from:, to:, date:) || fetch_rate_from_provider(from:, to:, date:).tap(&:save!)
end
def get_rate_series(from, to, date_range)
where(base_currency: from, converted_currency: to, date: date_range).order(:date)
end
# TODO: Replace with generic provider
# See https://github.com/maybe-finance/maybe/pull/556
def fetch_rate_from_provider(from, to, date)
response = Faraday.get("https://api.synthfinance.com/rates/historical") do |req|
req.headers["Authorization"] = "Bearer #{ENV["SYNTH_API_KEY"]}"
req.params["date"] = date.to_s
req.params["from"] = from
req.params["to"] = to
end
if response.success?
rates = JSON.parse(response.body)
rates.dig("data", "rates", to)
else
nil
end
end
end
end