lib

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

agreement.rs (16480B)


      1 use crate::{
      2     AgreementLineId, Decimal, DiscountBps, FulfillmentGroupId, LinePrice, ListingOptionId,
      3     MAX_PRICED_LINES, Money, PRICING_PROFILE, PositiveDecimal, PricingError, PrivateFulfillment,
      4     PublicKey, VariableWeight, Window, checked_order_total,
      5     listing::{ListingError, ListingOption, ListingRevision, Product},
      6     pricing::net_line_minor,
      7 };
      8 use alloc::{boxed::Box, string::String, vec::Vec};
      9 use core::fmt;
     10 use zeroize::Zeroizing;
     11 
     12 /// One resolved fixed agreement rate, independent of its public option snapshot.
     13 /// Selected-tier provenance is retained; no tier is selected again or invented.
     14 #[derive(Clone, Copy, Eq, PartialEq)]
     15 pub struct AgreedFixedPrice {
     16     rate: Money,
     17     basis: PositiveDecimal,
     18     discount_bps: DiscountBps,
     19     selected_tier_from: Option<Decimal>,
     20 }
     21 impl AgreedFixedPrice {
     22     /// Captures validated numeric values. A line additionally checks that any
     23     /// declared selected threshold does not exceed its purchased amount.
     24     pub const fn new(
     25         rate: Money,
     26         basis: PositiveDecimal,
     27         discount_bps: DiscountBps,
     28         selected_tier_from: Option<Decimal>,
     29     ) -> Self {
     30         Self {
     31             rate,
     32             basis,
     33             discount_bps,
     34             selected_tier_from,
     35         }
     36     }
     37     /// Retains the exact selected inputs of a qualified fixed-price calculation.
     38     pub const fn from_line(value: LinePrice) -> Self {
     39         Self::new(
     40             value.rate(),
     41             value.basis(),
     42             value.discount_bps(),
     43             value.selected_tier_from(),
     44         )
     45     }
     46     /// Returns the explicitly negotiated or resolved rate.
     47     pub const fn rate(self) -> Money {
     48         self.rate
     49     }
     50     /// Returns the positive basis in this line's selected sale unit.
     51     pub const fn basis(self) -> PositiveDecimal {
     52         self.basis
     53     }
     54     /// Returns the single discount, applied before rounding.
     55     pub const fn discount_bps(self) -> DiscountBps {
     56         self.discount_bps
     57     }
     58     /// Returns retained selected-tier provenance, including explicit None.
     59     pub const fn selected_tier_from(self) -> Option<Decimal> {
     60         self.selected_tier_from
     61     }
     62     /// Recomputes one net line with the shared checked half-even primitive.
     63     pub fn total(self, amount: PositiveDecimal) -> Result<Money, TermsError> {
     64         if self
     65             .selected_tier_from
     66             .is_some_and(|threshold| threshold > amount.amount())
     67         {
     68             return Err(TermsError::InvalidSelectedTier);
     69         }
     70         Ok(Money::new(
     71             self.rate.currency(),
     72             net_line_minor(self.rate.minor(), amount, self.basis, self.discount_bps)
     73                 .map_err(TermsError::Pricing)?,
     74         ))
     75     }
     76 }
     77 
     78 /// Complete agreed price: quote-required has no representation here.
     79 /// Variable measurement bounds/cap are absolute for this entire line.
     80 #[derive(Clone, Copy, Eq, PartialEq)]
     81 #[non_exhaustive]
     82 pub enum AgreementPrice {
     83     /// Exact selected fixed inputs; no future tier reselection occurs.
     84     Fixed(AgreedFixedPrice),
     85     /// Explicit complete line bounds, unit, rate, basis and monetary cap.
     86     VariableWeight(VariableWeight),
     87 }
     88 impl AgreementPrice {
     89     fn maximum_total(self, amount: PositiveDecimal) -> Result<Money, TermsError> {
     90         match self {
     91             Self::Fixed(value) => value.total(amount),
     92             Self::VariableWeight(value) => Ok(value.maximum_total()),
     93         }
     94     }
     95 }
     96 
     97 /// Complete immutable line data. Its source and snapshot are claims pending
     98 /// independent authenticated source admission; construction grants no consent.
     99 #[derive(Clone, Eq, PartialEq)]
    100 pub struct AgreementLine {
    101     id: AgreementLineId,
    102     source: ListingRevision,
    103     product: Product,
    104     option: ListingOption,
    105     amount: PositiveDecimal,
    106     fulfillment_group: FulfillmentGroupId,
    107     source_lot_label: Option<Zeroizing<String>>,
    108     price: AgreementPrice,
    109     maximum_line_total: Money,
    110 }
    111 impl AgreementLine {
    112     /// Validates the explicit option identity, purchase rules and independently
    113     /// recomputed fixed total or variable cap. Negotiated prices need not equal
    114     /// the original public price. No stock mapping or physical conversion occurs.
    115     #[allow(clippy::too_many_arguments)]
    116     pub fn new(
    117         id: AgreementLineId,
    118         source: ListingRevision,
    119         option_id: ListingOptionId,
    120         product: Product,
    121         option: ListingOption,
    122         amount: PositiveDecimal,
    123         fulfillment_group: FulfillmentGroupId,
    124         source_lot_label: Option<&str>,
    125         price: AgreementPrice,
    126         maximum_line_total: Money,
    127     ) -> Result<Self, TermsError> {
    128         if option_id != option.id() {
    129             return Err(TermsError::OptionMismatch);
    130         }
    131         option
    132             .validate_amount(amount)
    133             .map_err(TermsError::Purchase)?;
    134         if let Some(label) = source_lot_label {
    135             text(label, 120, false)?;
    136         }
    137         if price.maximum_total(amount)? != maximum_line_total {
    138             return Err(TermsError::TotalMismatch);
    139         }
    140         Ok(Self {
    141             id,
    142             source,
    143             product,
    144             option,
    145             amount,
    146             fulfillment_group,
    147             source_lot_label: source_lot_label.map(|label| Zeroizing::new(label.into())),
    148             price,
    149             maximum_line_total,
    150         })
    151     }
    152     /// Returns the stable line identity, without lineage authentication.
    153     pub const fn id(&self) -> AgreementLineId {
    154         self.id
    155     }
    156     /// Returns the exact immutable source revision claim.
    157     pub const fn source(&self) -> ListingRevision {
    158         self.source
    159     }
    160     /// Returns the option identity, kept equal to the retained option snapshot.
    161     pub const fn option_id(&self) -> ListingOptionId {
    162         self.option.id()
    163     }
    164     /// Borrows the exact public product snapshot; no current-head lookup occurs.
    165     pub const fn product(&self) -> &Product {
    166         &self.product
    167     }
    168     /// Borrows the unchanged original sale option, including its public price.
    169     pub const fn option(&self) -> &ListingOption {
    170         &self.option
    171     }
    172     /// Returns the positive validated sale amount.
    173     pub const fn amount(&self) -> PositiveDecimal {
    174         self.amount
    175     }
    176     /// Returns the group identity checked by complete enclosing terms.
    177     pub const fn fulfillment_group(&self) -> FulfillmentGroupId {
    178         self.fulfillment_group
    179     }
    180     /// Explicitly borrows the optional private descriptive lot claim.
    181     pub fn source_lot_label(&self) -> Option<&str> {
    182         self.source_lot_label.as_ref().map(|v| v.as_str())
    183     }
    184     /// Returns the complete agreed price, without changing its public provenance.
    185     pub const fn price(&self) -> AgreementPrice {
    186         self.price
    187     }
    188     /// Returns the independently checked fixed total or explicit variable cap.
    189     pub const fn maximum_line_total(&self) -> Money {
    190         self.maximum_line_total
    191     }
    192 }
    193 
    194 /// One stable private fulfillment identity and its complete validated data.
    195 #[derive(Clone, Eq, PartialEq)]
    196 pub struct FulfillmentGroup {
    197     id: FulfillmentGroupId,
    198     terms: PrivateFulfillment,
    199 }
    200 impl FulfillmentGroup {
    201     /// Captures validated values; enclosing terms check uniqueness and links.
    202     pub const fn new(id: FulfillmentGroupId, terms: PrivateFulfillment) -> Self {
    203         Self { id, terms }
    204     }
    205     /// Returns the exact group identity.
    206     pub const fn id(&self) -> FulfillmentGroupId {
    207         self.id
    208     }
    209     /// Explicitly borrows private fulfillment data.
    210     pub const fn terms(&self) -> &PrivateFulfillment {
    211         &self.terms
    212     }
    213 }
    214 
    215 /// Explicit non-stock-backed expectation and risk claim, without scheduling.
    216 #[derive(Clone, Eq, PartialEq)]
    217 pub struct FuturePromise {
    218     expected_window: Window,
    219     risk_disclosure: Zeroizing<String>,
    220 }
    221 impl FuturePromise {
    222     /// Requires an explicit bounded nonempty risk disclosure before copying.
    223     pub fn new(expected_window: Window, risk_disclosure: &str) -> Result<Self, TermsError> {
    224         text(risk_disclosure, 512, true)?;
    225         Ok(Self {
    226             expected_window,
    227             risk_disclosure: Zeroizing::new(risk_disclosure.into()),
    228         })
    229     }
    230     /// Returns the exact expected window without current-time judgment.
    231     pub const fn expected_window(&self) -> Window {
    232         self.expected_window
    233     }
    234     /// Explicitly borrows the exact private risk text.
    235     pub fn risk_disclosure(&self) -> &str {
    236         &self.risk_disclosure
    237     }
    238 }
    239 
    240 /// Declared commitment mode, without a physical hold or installed promise.
    241 #[derive(Clone, Eq, PartialEq)]
    242 #[non_exhaustive]
    243 pub enum SupplyCommitment {
    244     /// Requires the executor's separately verified stock-backed installation.
    245     StockBacked,
    246     /// Explicit expectation and risk, never physical stock backing.
    247     FuturePromise(FuturePromise),
    248 }
    249 
    250 /// Complete validated bilateral data, not participant consent, authenticated
    251 /// source evidence, an installed agreement or a physical stock reservation.
    252 /// Private wire/hash encoding remains owned by the admitting protocol.
    253 #[derive(Clone, Eq, PartialEq)]
    254 pub struct Terms {
    255     buyer: PublicKey,
    256     seller: PublicKey,
    257     lines: Box<[AgreementLine]>,
    258     fulfillment: Box<[FulfillmentGroup]>,
    259     fulfillment_charge: Money,
    260     maximum_total: Money,
    261     supply: SupplyCommitment,
    262 }
    263 impl Terms {
    264     /// Greatest supported number of private fulfillment groups.
    265     pub const MAX_FULFILLMENT_GROUPS: usize = 8;
    266     /// Bounds collections before capture; checks distinct IDs, complete group
    267     /// links, source seller identities and recomputed same-currency line totals.
    268     /// No live lookup, signing, authorization or stock effect occurs.
    269     pub fn new(
    270         buyer: PublicKey,
    271         seller: PublicKey,
    272         lines: Vec<AgreementLine>,
    273         fulfillment: Vec<FulfillmentGroup>,
    274         fulfillment_charge: Money,
    275         maximum_total: Money,
    276         supply: SupplyCommitment,
    277     ) -> Result<Self, TermsError> {
    278         if buyer == seller {
    279             return Err(TermsError::PartiesCoincide);
    280         }
    281         if lines.is_empty() || lines.len() > MAX_PRICED_LINES {
    282             return Err(TermsError::InvalidLineCount);
    283         }
    284         if fulfillment.is_empty() || fulfillment.len() > Self::MAX_FULFILLMENT_GROUPS {
    285             return Err(TermsError::InvalidFulfillmentCount);
    286         }
    287         for (index, group) in fulfillment.iter().enumerate() {
    288             if fulfillment[..index]
    289                 .iter()
    290                 .any(|prior| prior.id == group.id)
    291             {
    292                 return Err(TermsError::DuplicateFulfillment);
    293             }
    294         }
    295         for (index, line) in lines.iter().enumerate() {
    296             if lines[..index].iter().any(|prior| prior.id == line.id) {
    297                 return Err(TermsError::DuplicateLine);
    298             }
    299             if line.source.coordinate().author() != seller {
    300                 return Err(TermsError::SellerMismatch);
    301             }
    302             if !fulfillment
    303                 .iter()
    304                 .any(|group| group.id == line.fulfillment_group)
    305             {
    306                 return Err(TermsError::UnknownFulfillment);
    307             }
    308         }
    309         let totals: Vec<_> = lines
    310             .iter()
    311             .map(AgreementLine::maximum_line_total)
    312             .collect();
    313         let recomputed =
    314             checked_order_total(&totals, fulfillment_charge).map_err(TermsError::Pricing)?;
    315         if recomputed != maximum_total {
    316             return Err(TermsError::TotalMismatch);
    317         }
    318         Ok(Self {
    319             buyer,
    320             seller,
    321             lines: lines.into_boxed_slice(),
    322             fulfillment: fulfillment.into_boxed_slice(),
    323             fulfillment_charge,
    324             maximum_total,
    325             supply,
    326         })
    327     }
    328     /// Returns the named buyer without authenticating its consent or signer.
    329     pub const fn buyer(&self) -> PublicKey {
    330         self.buyer
    331     }
    332     /// Returns the named seller, matching all source coordinate authors.
    333     pub const fn seller(&self) -> PublicKey {
    334         self.seller
    335     }
    336     /// Borrows the complete immutable ordered line set.
    337     pub fn lines(&self) -> &[AgreementLine] {
    338         &self.lines
    339     }
    340     /// Explicitly borrows the bounded private fulfillment groups.
    341     pub fn fulfillment(&self) -> &[FulfillmentGroup] {
    342         &self.fulfillment
    343     }
    344     /// Returns the explicit same-currency fulfillment fee, including valid zero.
    345     pub const fn fulfillment_charge(&self) -> Money {
    346         self.fulfillment_charge
    347     }
    348     /// Returns the independently recomputed aggregate maximum.
    349     pub const fn maximum_total(&self) -> Money {
    350         self.maximum_total
    351     }
    352     /// Borrows the explicit commitment declaration; no hold is minted.
    353     pub const fn supply(&self) -> &SupplyCommitment {
    354         &self.supply
    355     }
    356     /// Returns the fixed supported residual-cancellation contract identity.
    357     pub const fn cancellation(&self) -> &'static str {
    358         "mutual_residual_v1"
    359     }
    360     /// Returns the fixed supported net-line rounding contract identity.
    361     pub const fn rounding(&self) -> &'static str {
    362         PRICING_PROFILE
    363     }
    364 }
    365 
    366 fn text(value: &str, maximum: usize, nonempty: bool) -> Result<(), TermsError> {
    367     if (nonempty && value.is_empty())
    368         || value.len() > maximum * 4
    369         || value.chars().count() > maximum
    370     {
    371         return Err(TermsError::InvalidText);
    372     }
    373     Ok(())
    374 }
    375 
    376 /// Input-free bilateral-value admission failure; no private data is retained.
    377 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    378 #[non_exhaustive]
    379 pub enum TermsError {
    380     /// Buyer and seller name the same participant in bilateral terms.
    381     PartiesCoincide,
    382     /// The complete agreement requires one through32 lines.
    383     InvalidLineCount,
    384     /// The complete agreement requires one through8 private groups.
    385     InvalidFulfillmentCount,
    386     /// A line identity repeats within one complete line set.
    387     DuplicateLine,
    388     /// A private fulfillment identity repeats.
    389     DuplicateFulfillment,
    390     /// A line references no declared private group.
    391     UnknownFulfillment,
    392     /// An explicit option ID differs from the retained original snapshot.
    393     OptionMismatch,
    394     /// A listing coordinate author differs from the named seller.
    395     SellerMismatch,
    396     /// Required risk text is empty or private text exceeds its bound.
    397     InvalidText,
    398     /// A selected threshold exceeds the purchased sale amount.
    399     InvalidSelectedTier,
    400     /// A declared line or order total differs from exact recomputation.
    401     TotalMismatch,
    402     /// The original option's selected-amount rules were not met.
    403     Purchase(ListingError),
    404     /// Checked arithmetic, currency or supported aggregate bounds failed.
    405     Pricing(PricingError),
    406 }
    407 impl fmt::Display for TermsError {
    408     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    409         f.write_str(match self {
    410             Self::PartiesCoincide => "bilateral participants must be distinct",
    411             Self::InvalidLineCount => "invalid agreement line count",
    412             Self::InvalidFulfillmentCount => "invalid private fulfillment count",
    413             Self::DuplicateLine => "duplicate agreement line",
    414             Self::DuplicateFulfillment => "duplicate private fulfillment group",
    415             Self::UnknownFulfillment => "unknown private fulfillment group",
    416             Self::OptionMismatch => "agreement option identity mismatch",
    417             Self::SellerMismatch => "agreement source seller mismatch",
    418             Self::InvalidText => "invalid private agreement text",
    419             Self::InvalidSelectedTier => "invalid selected agreement tier",
    420             Self::TotalMismatch => "agreement total differs from recomputation",
    421             Self::Purchase(error) => return error.fmt(f),
    422             Self::Pricing(error) => return error.fmt(f),
    423         })
    424     }
    425 }
    426 impl core::error::Error for TermsError {
    427     fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    428         match self {
    429             Self::Purchase(error) => Some(error),
    430             Self::Pricing(error) => Some(error),
    431             _ => None,
    432         }
    433     }
    434 }
    435 
    436 macro_rules! redacted {
    437     ($($name:ident),+)=> { $(impl fmt::Debug for $name {
    438         fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result {
    439             f.write_str(concat!(stringify!($name),"(<redacted>)"))
    440         }
    441     })+ };
    442 }
    443 redacted!(
    444     AgreedFixedPrice,
    445     AgreementPrice,
    446     AgreementLine,
    447     FulfillmentGroup,
    448     FuturePromise,
    449     SupplyCommitment,
    450     Terms
    451 );