use super::{
Address, AddressBalance, CollectionLimit, FeeEstimate, FeeTarget, History, HistoryRange,
NetworkIdentity, TokenFilter, Transaction, TransactionStatus, Txid, UnspentOutputs,
};
use crate::{
domain::{Source, Timestamp},
error::{Error, ValidationError},
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Operation {
AddressBalance {
address: Address,
token_filter: TokenFilter,
},
AddressHistory {
address: Address,
range: HistoryRange,
},
FeeEstimate {
target: FeeTarget,
},
TransactionStatus {
txid: Txid,
},
Transaction {
txid: Txid,
limit: CollectionLimit,
},
UnspentOutputs {
address: Address,
token_filter: TokenFilter,
limit: CollectionLimit,
},
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ProtocolMetadata {
pub software: super::SourceText,
pub version: super::SourceText,
pub cash_tokens: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "ContextFields")]
pub struct Context {
schema_version: u16,
network: NetworkIdentity,
operation: Operation,
source: Source,
retrieved_at: Timestamp,
protocol_metadata: Option<ProtocolMetadata>,
}
impl Context {
pub fn new(
network: NetworkIdentity,
operation: Operation,
source: Source,
retrieved_at: Timestamp,
) -> Result<Self, Error> {
let address = match &operation {
Operation::AddressBalance { address, .. }
| Operation::AddressHistory { address, .. }
| Operation::UnspentOutputs { address, .. } => Some(address),
_ => None,
};
if address.is_some_and(|v| v.namespace() != network.namespace()) {
return Err(ValidationError::NetworkMismatch.into());
}
Ok(Self {
schema_version: 1,
network,
operation,
source,
retrieved_at,
protocol_metadata: None,
})
}
#[must_use]
pub const fn schema_version(&self) -> u16 {
self.schema_version
}
#[must_use]
pub const fn network(&self) -> &NetworkIdentity {
&self.network
}
#[must_use]
pub const fn operation(&self) -> &Operation {
&self.operation
}
#[must_use]
pub const fn source(&self) -> &Source {
&self.source
}
#[must_use]
pub const fn retrieved_at(&self) -> Timestamp {
self.retrieved_at
}
#[must_use]
pub fn with_protocol_metadata(mut self, value: ProtocolMetadata) -> Self {
self.protocol_metadata = Some(value);
self
}
#[must_use]
pub const fn protocol_metadata(&self) -> Option<&ProtocolMetadata> {
self.protocol_metadata.as_ref()
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ContextFields {
schema_version: u16,
network: NetworkIdentity,
operation: Operation,
source: Source,
retrieved_at: Timestamp,
protocol_metadata: Option<ProtocolMetadata>,
}
impl TryFrom<ContextFields> for Context {
type Error = Error;
fn try_from(v: ContextFields) -> Result<Self, Error> {
if v.schema_version != 1 {
return Err(ValidationError::UnsupportedSchemaVersion.into());
}
let mut result = Self::new(v.network, v.operation, v.source, v.retrieved_at)?;
result.protocol_metadata = v.protocol_metadata;
Ok(result)
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "ObservationFields<T>", bound(deserialize = "T: ReadValue"))]
pub struct Observation<T: ReadValue> {
context: Context,
value: T,
}
impl<T: ReadValue> Observation<T> {
pub fn new(context: Context, value: T) -> Result<Self, Error> {
if !value.matches(&context) {
return Err(ValidationError::ObservationOperationMismatch.into());
}
Ok(Self { context, value })
}
#[must_use]
pub const fn context(&self) -> &Context {
&self.context
}
#[must_use]
pub const fn value(&self) -> &T {
&self.value
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields, bound(deserialize = "T: ReadValue"))]
struct ObservationFields<T: ReadValue> {
context: Context,
value: T,
}
impl<T: ReadValue> TryFrom<ObservationFields<T>> for Observation<T> {
type Error = Error;
fn try_from(v: ObservationFields<T>) -> Result<Self, Error> {
Self::new(v.context, v.value)
}
}
mod sealed {
pub trait Sealed {}
}
#[doc(hidden)]
pub trait ReadValue: sealed::Sealed + for<'de> Deserialize<'de> {
fn matches(&self, context: &Context) -> bool;
}
impl sealed::Sealed for AddressBalance {}
impl ReadValue for AddressBalance {
fn matches(&self, c: &Context) -> bool {
matches!(c.operation(),Operation::AddressBalance{address,token_filter} if address==&self.address&&*token_filter==self.token_filter)
}
}
impl sealed::Sealed for History {}
impl ReadValue for History {
fn matches(&self, c: &Context) -> bool {
matches!(c.operation(),Operation::AddressHistory{address,range} if address==self.address()&&*range==self.range())
}
}
impl sealed::Sealed for FeeEstimate {}
impl ReadValue for FeeEstimate {
fn matches(&self, c: &Context) -> bool {
matches!(c.operation(),Operation::FeeEstimate{target} if *target==self.target())
}
}
impl sealed::Sealed for TransactionStatus {}
impl ReadValue for TransactionStatus {
fn matches(&self, c: &Context) -> bool {
matches!(c.operation(),Operation::TransactionStatus{txid} if *txid==self.txid())
}
}
impl sealed::Sealed for Transaction {}
impl ReadValue for Transaction {
fn matches(&self, c: &Context) -> bool {
matches!(c.operation(),Operation::Transaction{txid,limit} if *txid==self.txid()&&*limit==self.limit())
&& c.network().namespace() == self.data().namespace
}
}
impl sealed::Sealed for UnspentOutputs {}
impl ReadValue for UnspentOutputs {
fn matches(&self, c: &Context) -> bool {
matches!(c.operation(),Operation::UnspentOutputs{address,token_filter,limit} if address==self.address()&&*token_filter==self.token_filter()&&*limit==self.limit())
}
}