use std::fmt;
use serde::{Deserialize, Deserializer, Serialize};
use crate::error::Error;
pub trait Preparation: Clone + Eq {
type Network: Eq;
type Intent: Eq;
type UnsignedPayload: Eq;
fn network(&self) -> &Self::Network;
fn intent(&self) -> &Self::Intent;
fn unsigned_payload(&self) -> &Self::UnsignedPayload;
fn validate(&self) -> Result<(), Error>;
}
#[derive(Clone, Eq, PartialEq, Serialize)]
pub struct PreparedRequest<P: Preparation> {
preparation: P,
}
impl<P: Preparation> PreparedRequest<P> {
pub fn new(preparation: P) -> Result<Self, Error> {
preparation.validate()?;
Ok(Self { preparation })
}
#[must_use]
pub const fn preparation(&self) -> &P {
&self.preparation
}
#[must_use]
pub const fn review(&self) -> Review<'_, P> {
Review { request: self }
}
pub(super) fn matches(&self, other: &Self) -> bool {
self.preparation == other.preparation
&& self.preparation.network() == other.preparation.network()
&& self.preparation.intent() == other.preparation.intent()
&& self.preparation.unsigned_payload() == other.preparation.unsigned_payload()
}
}
impl<P: Preparation> fmt::Debug for PreparedRequest<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PreparedRequest").finish_non_exhaustive()
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Fields<P> {
preparation: P,
}
impl<'de, P: Preparation + Deserialize<'de>> Deserialize<'de> for PreparedRequest<P> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let fields = Fields::<P>::deserialize(d)?;
Self::new(fields.preparation).map_err(serde::de::Error::custom)
}
}
pub struct Review<'a, P: Preparation> {
request: &'a PreparedRequest<P>,
}
impl<P: Preparation> Review<'_, P> {
#[must_use]
pub fn network(&self) -> &P::Network {
self.request.preparation.network()
}
#[must_use]
pub fn intent(&self) -> &P::Intent {
self.request.preparation.intent()
}
#[must_use]
pub fn unsigned_payload(&self) -> &P::UnsignedPayload {
self.request.preparation.unsigned_payload()
}
}
impl<P: Preparation> fmt::Debug for Review<'_, P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Review").finish_non_exhaustive()
}
}