use brk_error::Result;
use brk_traversable::Traversable;
use brk_types::{Cents, CentsSigned, Dollars, Version};
use schemars::JsonSchema;
use vecdb::{Database, ReadableCloneableVec, Rw, StorageMode, UnaryTransform};
use crate::{
indexes,
internal::{
CentsSignedToDollars, CentsUnsignedToDollars, LazyPerBlock, NumericValue, PerBlock,
},
};
pub trait CentsType: NumericValue + JsonSchema {
type ToDollars: UnaryTransform<Self, Dollars>;
}
impl CentsType for Cents {
type ToDollars = CentsUnsignedToDollars;
}
impl CentsType for CentsSigned {
type ToDollars = CentsSignedToDollars;
}
#[derive(Traversable)]
pub struct FiatPerBlock<C: CentsType, M: StorageMode = Rw> {
pub usd: LazyPerBlock<Dollars, C>,
pub cents: PerBlock<C, M>,
}
impl<C: CentsType> FiatPerBlock<C> {
pub(crate) fn forced_import(
db: &Database,
name: &str,
version: Version,
indexes: &indexes::Vecs,
) -> Result<Self> {
let cents = PerBlock::forced_import(db, &format!("{name}_cents"), version, indexes)?;
let usd = LazyPerBlock::from_computed::<C::ToDollars>(
name,
version,
cents.height.read_only_boxed_clone(),
¢s,
);
Ok(Self { usd, cents })
}
}