Skip to content

Commit

Permalink
Refactor exchange rate caching
Browse files Browse the repository at this point in the history
  • Loading branch information
gcomte committed Dec 4, 2024
1 parent 4f527d6 commit 1894f2c
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ tabled = "0.16.0"
thiserror = "2.0.3"
thousands = "0.2.0"
typetag = "0.2"
lazy_static = "1.5.0"

[dev-dependencies]
assert_cmd = "2.0.16"
21 changes: 15 additions & 6 deletions src/currency/fiat.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::sync::Mutex;
use lazy_static::lazy_static;
use crate::fiat_rates::blockchain_info_consumer;
use serde::{Deserialize, Serialize};
use strum_macros::{Display, EnumString};
Expand All @@ -6,11 +8,14 @@ use crate::currency::Currency;
use crate::fiat_rates::exchange_rate_provider::ExchangeRateProvider;

// Static to have an easy way of caching the exchange rates.
static mut EXCHANGE_RATE_PROVIDER: ExchangeRateProvider<blockchain_info_consumer::ApiConsumer> =
ExchangeRateProvider {
data_source: blockchain_info_consumer::ApiConsumer,
data: None,
};
lazy_static! {
static ref EXCHANGE_RATE_PROVIDER: Mutex<ExchangeRateProvider<blockchain_info_consumer::ApiConsumer>> =
Mutex::new(ExchangeRateProvider {
data_source: blockchain_info_consumer::ApiConsumer,
data: None,
});
}


#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, EnumString, Display)]
#[strum(ascii_case_insensitive, serialize_all = "UPPERCASE")]
Expand Down Expand Up @@ -47,7 +52,11 @@ pub enum Fiat {
#[typetag::serde]
impl Currency for Fiat {
fn btc_value(&self) -> f64 {
unsafe { EXCHANGE_RATE_PROVIDER.btc_value(self) }
EXCHANGE_RATE_PROVIDER
.lock()
.expect("Failed to lock EXCHANGE_RATE_PROVIDER")
.btc_value(self)

}

fn decimal_places(&self) -> u8 {
Expand Down

0 comments on commit 1894f2c

Please sign in to comment.