use std::sync::Arc;
use anyhow::Context;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use mithril_common::entities::SupportedEra;
use crate::MithrilResult;
pub struct MithrilEraClient {
era_fetcher: Arc<dyn EraFetcher>,
}
impl MithrilEraClient {
pub fn new(era_fetcher: Arc<dyn EraFetcher>) -> Self {
Self { era_fetcher }
}
pub async fn fetch_current(&self) -> MithrilResult<FetchedEra> {
self.era_fetcher.fetch_current_era().await
}
}
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct FetchedEra {
pub era: String,
}
impl FetchedEra {
pub fn to_supported_era(&self) -> MithrilResult<SupportedEra> {
self.era
.parse::<SupportedEra>()
.with_context(|| format!("Unknown supported era: {}", self.era))
}
}
#[cfg_attr(target_family = "wasm", async_trait(?Send))]
#[cfg_attr(not(target_family = "wasm"), async_trait)]
pub trait EraFetcher: Send + Sync {
async fn fetch_current_era(&self) -> MithrilResult<FetchedEra>;
}
#[cfg(test)]
mod tests {
use mithril_common::entities::SupportedEra;
use super::*;
#[test]
fn to_supported_era_should_return_enum_variant_for_known_era() {
let fetched_era = FetchedEra {
era: SupportedEra::Pythagoras.to_string(),
};
let supported_era = fetched_era.to_supported_era().unwrap();
assert_eq!(SupportedEra::Pythagoras, supported_era);
}
#[test]
fn to_supported_era_returns_error_for_unsupported_era() {
let fetched_era = FetchedEra {
era: "unsupported_era".to_string(),
};
fetched_era
.to_supported_era()
.expect_err("Expected an error when converting an unsupported era to 'SupportedEra'");
}
}