lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

mapping.rs (7512B)


      1 //! Exact private option-to-pool claims; no store, stock hold or source authority.
      2 use super::{PoolUnit, StockError, StockTicks};
      3 use crate::{
      4     ListingOptionId, PoolId, PositiveDecimal, Quantity, QuantityError, Sequence,
      5     listing::ListingCoordinate,
      6 };
      7 use core::fmt;
      8 
      9 /// The entire listing coordinate and stable option identity of a private mapping.
     10 #[derive(Clone, Copy, Eq, PartialEq)]
     11 pub struct OptionMappingKey {
     12     listing: ListingCoordinate,
     13     option: ListingOptionId,
     14 }
     15 impl OptionMappingKey {
     16     /// Captures identity metadata without authenticating an owner or listing.
     17     pub const fn new(listing: ListingCoordinate, option: ListingOptionId) -> Self {
     18         Self { listing, option }
     19     }
     20     /// Returns the complete claimed listing coordinate.
     21     pub const fn listing(self) -> ListingCoordinate {
     22         self.listing
     23     }
     24     /// Returns the stable option identity within that listing.
     25     pub const fn option_id(self) -> ListingOptionId {
     26         self.option
     27     }
     28 }
     29 impl fmt::Debug for OptionMappingKey {
     30     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     31         f.write_str("OptionMappingKey(<private metadata>)")
     32     }
     33 }
     34 
     35 /// A validated private conversion claim at one positive mapping version.
     36 /// This establishes neither an observed listing nor physical backing. The
     37 /// executor checks current ownership, pool identity and versions separately.
     38 #[derive(Clone, Copy, Eq, PartialEq)]
     39 pub struct OptionPoolMapping {
     40     key: OptionMappingKey,
     41     pool: PoolId,
     42     unit: PoolUnit,
     43     per_sale_unit: Quantity,
     44     per_sale_ticks: StockTicks,
     45     version: Sequence,
     46 }
     47 impl OptionPoolMapping {
     48     /// Resolves an explicit positive per-sale draw into the fixed pool precision.
     49     /// Only exact g/kg or mL/L conversion is performed. Package labels, estimated
     50     /// contents and mass/volume assumptions never supply a conversion here.
     51     pub fn new(
     52         key: OptionMappingKey,
     53         pool: PoolId,
     54         unit: PoolUnit,
     55         per_sale_unit: Quantity,
     56         version: Sequence,
     57     ) -> Result<Self, MappingError> {
     58         if version.get() == 0 {
     59             return Err(MappingError::InvalidVersion);
     60         }
     61         if per_sale_unit.amount().is_zero() {
     62             return Err(MappingError::ZeroDraw);
     63         }
     64         let normalized = per_sale_unit.convert(unit.unit())?;
     65         let per_sale_ticks = unit.ticks_for(normalized)?;
     66         if per_sale_ticks == StockTicks::ZERO {
     67             return Err(MappingError::ZeroDraw);
     68         }
     69         Ok(Self {
     70             key,
     71             pool,
     72             unit,
     73             per_sale_unit,
     74             per_sale_ticks,
     75             version,
     76         })
     77     }
     78     /// Returns the exact private option key.
     79     pub const fn key(self) -> OptionMappingKey {
     80         self.key
     81     }
     82     /// Returns the claimed pool identity.
     83     pub const fn pool_id(self) -> PoolId {
     84         self.pool
     85     }
     86     /// Returns the fixed unit/precision used to validate this mapping.
     87     pub const fn pool_unit(self) -> PoolUnit {
     88         self.unit
     89     }
     90     /// Retains the original explicit quantity, including its declared SI unit.
     91     pub const fn per_sale_unit(self) -> Quantity {
     92         self.per_sale_unit
     93     }
     94     /// Returns the exact integral pool ticks for one declared sale unit.
     95     pub const fn per_sale_ticks(self) -> StockTicks {
     96         self.per_sale_ticks
     97     }
     98     /// Returns a positive mapping version, without authenticating freshness.
     99     pub const fn version(self) -> Sequence {
    100         self.version
    101     }
    102     /// Multiplies a validated positive sale amount without rounding pool ticks.
    103     /// The caller must independently enforce the selected option's sale basis,
    104     /// including integral package purchases. This function reserves no stock.
    105     pub fn draw_for_sales(self, sales: PositiveDecimal) -> Result<StockTicks, MappingError> {
    106         let amount = sales.amount();
    107         let numerator = u128::from(self.per_sale_ticks.get())
    108             .checked_mul(u128::from(amount.coefficient()))
    109             .ok_or(StockError::OutOfRange)?;
    110         let denominator = 10_u128.pow(u32::from(amount.scale()));
    111         if !numerator.is_multiple_of(denominator) {
    112             return Err(StockError::PrecisionLoss.into());
    113         }
    114         let ticks = u64::try_from(numerator / denominator).map_err(|_| StockError::OutOfRange)?;
    115         StockTicks::new(ticks).map_err(MappingError::from)
    116     }
    117 }
    118 impl fmt::Debug for OptionPoolMapping {
    119     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    120         f.write_str("OptionPoolMapping(<private metadata>)")
    121     }
    122 }
    123 
    124 /// Input-free exact mapping validation failure.
    125 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    126 #[non_exhaustive]
    127 pub enum MappingError {
    128     /// A stored mapping version must be positive; version0 denotes absence.
    129     InvalidVersion,
    130     /// One sale unit cannot consume an explicit zero amount.
    131     ZeroDraw,
    132     /// Explicit quantity conversion is incompatible or inexact.
    133     Quantity(QuantityError),
    134     /// Exact ticks or multiplication exceed the physical value contract.
    135     Stock(StockError),
    136 }
    137 impl From<QuantityError> for MappingError {
    138     fn from(value: QuantityError) -> Self {
    139         Self::Quantity(value)
    140     }
    141 }
    142 impl From<StockError> for MappingError {
    143     fn from(value: StockError) -> Self {
    144         Self::Stock(value)
    145     }
    146 }
    147 impl fmt::Display for MappingError {
    148     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    149         match self {
    150             Self::InvalidVersion => f.write_str("mapping version must be positive"),
    151             Self::ZeroDraw => f.write_str("mapping draw must be positive"),
    152             Self::Quantity(error) => error.fmt(f),
    153             Self::Stock(error) => error.fmt(f),
    154         }
    155     }
    156 }
    157 impl core::error::Error for MappingError {}
    158 
    159 #[cfg(feature = "serde")]
    160 mod serialization {
    161     use super::*;
    162     use serde::{Deserialize, Serialize};
    163     #[derive(Serialize, Deserialize)]
    164     #[serde(deny_unknown_fields)]
    165     struct Wire {
    166         listing: ListingCoordinate,
    167         option_id: ListingOptionId,
    168         pool_id: PoolId,
    169         pool_unit: PoolUnit,
    170         per_sale_unit: Quantity,
    171         per_sale_ticks: StockTicks,
    172         version: Sequence,
    173     }
    174     impl Serialize for OptionPoolMapping {
    175         fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
    176             Wire {
    177                 listing: self.key.listing,
    178                 option_id: self.key.option,
    179                 pool_id: self.pool,
    180                 pool_unit: self.unit,
    181                 per_sale_unit: self.per_sale_unit,
    182                 per_sale_ticks: self.per_sale_ticks,
    183                 version: self.version,
    184             }
    185             .serialize(serializer)
    186         }
    187     }
    188     impl<'de> Deserialize<'de> for OptionPoolMapping {
    189         fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
    190             let wire: Wire = super::super::serialization::object(deserializer)?;
    191             let value = Self::new(
    192                 OptionMappingKey::new(wire.listing, wire.option_id),
    193                 wire.pool_id,
    194                 wire.pool_unit,
    195                 wire.per_sale_unit,
    196                 wire.version,
    197             )
    198             .map_err(serde::de::Error::custom)?;
    199             if value.per_sale_ticks() != wire.per_sale_ticks {
    200                 return Err(serde::de::Error::custom(
    201                     "mapping tick conversion does not match its declared quantity",
    202                 ));
    203             }
    204             Ok(value)
    205         }
    206     }
    207 }