use serde::{Deserialize, Deserializer, Serialize};
use crate::{
domain::{Source, Timestamp},
error::{Error, ValidationError},
};
use super::{
AccountBalance, FeeEstimate, Hash, HistoryPage, Network, SubmissionResult, Transaction,
TransactionStatus, TrustLinePage,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "LedgerFields")]
pub struct Ledger {
index: u32,
hash: Option<Hash>,
validated: bool,
}
impl Ledger {
pub const fn new(index: u32, hash: Option<Hash>, validated: bool) -> Result<Self, Error> {
if index == 0 {
return Err(Error::Validation(ValidationError::InvalidXrplRecord));
}
Ok(Self {
index,
hash,
validated,
})
}
#[must_use]
pub const fn index(self) -> u32 {
self.index
}
#[must_use]
pub const fn hash(self) -> Option<Hash> {
self.hash
}
#[must_use]
pub const fn validated(self) -> bool {
self.validated
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct LedgerFields {
index: u32,
#[serde(deserialize_with = "crate::domain::deserialize_optional")]
hash: Option<Hash>,
validated: bool,
}
impl TryFrom<LedgerFields> for Ledger {
type Error = Error;
fn try_from(v: LedgerFields) -> Result<Self, Error> {
Self::new(v.index, v.hash, v.validated)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Operation {
AccountBalance,
TrustLines,
FeeEstimate,
Transaction,
TransactionStatus,
AccountHistory,
Submission,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Context {
operation: Operation,
network: Network,
#[serde(deserialize_with = "crate::domain::deserialize_optional")]
ledger: Option<Ledger>,
source: Source,
retrieved_at: Timestamp,
}
impl Context {
#[must_use]
pub const fn new(
operation: Operation,
network: Network,
ledger: Option<Ledger>,
source: Source,
retrieved_at: Timestamp,
) -> Self {
Self {
operation,
network,
ledger,
source,
retrieved_at,
}
}
#[must_use]
pub const fn operation(&self) -> Operation {
self.operation
}
#[must_use]
pub const fn network(&self) -> &Network {
&self.network
}
#[must_use]
pub const fn ledger(&self) -> Option<Ledger> {
self.ledger
}
#[must_use]
pub const fn source(&self) -> &Source {
&self.source
}
#[must_use]
pub const fn retrieved_at(&self) -> Timestamp {
self.retrieved_at
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct Observation<T> {
schema_version: u16,
context: Context,
value: T,
}
impl<T> Observation<T> {
#[must_use]
pub const fn schema_version(&self) -> u16 {
self.schema_version
}
#[must_use]
pub const fn context(&self) -> &Context {
&self.context
}
#[must_use]
pub const fn value(&self) -> &T {
&self.value
}
fn new(value: T, context: Context, expected: Operation) -> Result<Self, Error> {
if context.operation() != expected {
return Err(ValidationError::ObservationOperationMismatch.into());
}
Ok(Self {
schema_version: 1,
context,
value,
})
}
}
impl Observation<AccountBalance> {
pub fn account_balance(value: AccountBalance, context: Context) -> Result<Self, Error> {
if !context
.ledger()
.is_some_and(|ledger| ledger.validated() && ledger.hash().is_some())
{
return Err(ValidationError::InvalidXrplRecord.into());
}
Self::new(value, context, Operation::AccountBalance)
}
}
impl Observation<TrustLinePage> {
pub fn trust_lines(value: TrustLinePage, context: Context) -> Result<Self, Error> {
if !context
.ledger()
.is_some_and(|ledger| ledger.validated() && ledger.hash().is_some())
|| value
.request()
.ledger_hash()
.is_some_and(|hash| context.ledger().and_then(Ledger::hash) != Some(hash))
{
return Err(ValidationError::InvalidXrplRecord.into());
}
Self::new(value, context, Operation::TrustLines)
}
}
impl Observation<FeeEstimate> {
pub fn fee_estimate(value: FeeEstimate, context: Context) -> Result<Self, Error> {
if !context
.ledger()
.is_some_and(|ledger| !ledger.validated() && ledger.hash().is_none())
{
return Err(ValidationError::InvalidXrplRecord.into());
}
Self::new(value, context, Operation::FeeEstimate)
}
}
impl Observation<Transaction> {
pub fn transaction(value: Transaction, context: Context) -> Result<Self, Error> {
if value.ledger() != context.ledger() {
return Err(ValidationError::InvalidXrplRecord.into());
}
Self::new(value, context, Operation::Transaction)
}
}
impl Observation<TransactionStatus> {
pub fn transaction_status(value: TransactionStatus, context: Context) -> Result<Self, Error> {
if value.ledger() != context.ledger() {
return Err(ValidationError::InvalidXrplRecord.into());
}
Self::new(value, context, Operation::TransactionStatus)
}
}
impl Observation<HistoryPage> {
pub fn account_history(value: HistoryPage, context: Context) -> Result<Self, Error> {
if context.ledger().is_some() {
return Err(ValidationError::InvalidXrplRecord.into());
}
Self::new(value, context, Operation::AccountHistory)
}
}
impl Observation<SubmissionResult> {
pub fn submission(value: SubmissionResult, context: Context) -> Result<Self, Error> {
if context.ledger().is_some() {
return Err(ValidationError::InvalidXrplRecord.into());
}
Self::new(value, context, Operation::Submission)
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Fields<T> {
schema_version: u16,
context: Context,
value: T,
}
macro_rules! observation_deserialize {
($value:ty, $constructor:ident) => {
impl<'de> Deserialize<'de> for Observation<$value> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = Fields::<$value>::deserialize(d)?;
if v.schema_version != 1 {
return Err(serde::de::Error::custom(
ValidationError::UnsupportedSchemaVersion,
));
}
Self::$constructor(v.value, v.context).map_err(serde::de::Error::custom)
}
}
};
}
observation_deserialize!(AccountBalance, account_balance);
observation_deserialize!(TrustLinePage, trust_lines);
observation_deserialize!(FeeEstimate, fee_estimate);
observation_deserialize!(Transaction, transaction);
observation_deserialize!(TransactionStatus, transaction_status);
observation_deserialize!(HistoryPage, account_history);
observation_deserialize!(SubmissionResult, submission);