lib

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

commit 4bc20bca66de47cebdea9d1967795bda31eac9e7
parent 60e7c6342fe4f420c12c77bacf711cbe79240fd7
Author: triesap <tyson@radroots.org>
Date:   Thu, 22 Oct 2026 21:27:36 +0000

domain: Validate complete bilateral agreement values

- Retain exact source snapshots and distinct line and fulfillment identities.
- Recompute agreed fixed and absolute variable terms without changing public prices.
- Bound private groups and risk claims with redacted validated construction.
- Verify contracts, additive API, portable features, focused tests and coverage.

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/README.md | 41+++++++++++++++++++++++++++++++++++++++++
Acrates/domain/src/agreement.rs | 445+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/identifier.rs | 8++++++++
Mcrates/domain/src/lib.rs | 12+++++++++---
Mcrates/domain/src/listing.rs | 2++
Acrates/domain/src/listing/reference.rs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/src/listing/view.rs | 6+++++-
Mcrates/domain/tests/identifier.rs | 2++
Mcrates/domain/tests/listing.rs | 3+++
Acrates/domain/tests/support/agreement.rs | 688+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 1405 insertions(+), 4 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -57,10 +57,21 @@ pub const fn radroots_domain::listing::Listing::id(&self) -> radroots_domain::li pub fn radroots_domain::listing::Listing::new(radroots_domain::listing::ListingId, radroots_identity::key::PublicKey, radroots_domain::EnvelopeEventId, radroots_domain::UnixSeconds, radroots_domain::UnixSeconds, radroots_domain::listing::ListingText, radroots_domain::listing::ListingTerms) -> core::result::Result<Self, radroots_domain::listing::ListingError> pub const fn radroots_domain::listing::Listing::published_at(&self) -> radroots_domain::UnixSeconds pub const fn radroots_domain::listing::Listing::revision(&self) -> radroots_domain::EnvelopeEventId +pub const fn radroots_domain::listing::Listing::source(&self) -> radroots_domain::listing::ListingRevision pub const fn radroots_domain::listing::Listing::terms(&self) -> &radroots_domain::listing::ListingTerms pub const fn radroots_domain::listing::Listing::text(&self) -> &radroots_domain::listing::ListingText impl core::fmt::Debug for radroots_domain::listing::Listing pub fn radroots_domain::listing::Listing::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::listing::ListingCoordinate +impl radroots_domain::listing::ListingCoordinate +pub const fn radroots_domain::listing::ListingCoordinate::author(self) -> radroots_identity::key::PublicKey +pub const fn radroots_domain::listing::ListingCoordinate::d(self) -> radroots_domain::listing::ListingId +pub const fn radroots_domain::listing::ListingCoordinate::kind(self) -> u16 +pub const fn radroots_domain::listing::ListingCoordinate::new(radroots_identity::key::PublicKey, radroots_domain::listing::ListingId) -> Self +impl core::fmt::Debug for radroots_domain::listing::ListingCoordinate +pub fn radroots_domain::listing::ListingCoordinate::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl serde_core::ser::Serialize for radroots_domain::listing::ListingCoordinate +pub fn radroots_domain::listing::ListingCoordinate::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> pub struct radroots_domain::listing::ListingId(_) impl radroots_domain::listing::ListingId pub const fn radroots_domain::listing::ListingId::as_bytes(&self) -> &[u8; 16] @@ -89,6 +100,13 @@ pub const fn radroots_domain::listing::ListingOption::unit(&self) -> &radroots_d pub fn radroots_domain::listing::ListingOption::validate_amount(&self, radroots_domain::PositiveDecimal) -> core::result::Result<(), radroots_domain::listing::ListingError> impl core::fmt::Debug for radroots_domain::listing::ListingOption pub fn radroots_domain::listing::ListingOption::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::listing::ListingRevision +impl radroots_domain::listing::ListingRevision +pub const fn radroots_domain::listing::ListingRevision::coordinate(self) -> radroots_domain::listing::ListingCoordinate +pub const fn radroots_domain::listing::ListingRevision::event_id(self) -> radroots_domain::EnvelopeEventId +pub const fn radroots_domain::listing::ListingRevision::new(radroots_domain::listing::ListingCoordinate, radroots_domain::EnvelopeEventId) -> Self +impl core::fmt::Debug for radroots_domain::listing::ListingRevision +pub fn radroots_domain::listing::ListingRevision::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::listing::ListingTerms impl radroots_domain::listing::ListingTerms pub const radroots_domain::listing::ListingTerms::MAX_MEDIA: usize @@ -144,6 +162,11 @@ pub fn radroots_domain::listing::SaleUnit::fmt(&self, &mut core::fmt::Formatter< pub radroots_domain::ActorRole::Buyer pub radroots_domain::ActorRole::Coordinator pub radroots_domain::ActorRole::Seller +#[non_exhaustive] pub enum radroots_domain::AgreementPrice +pub radroots_domain::AgreementPrice::Fixed(radroots_domain::AgreedFixedPrice) +pub radroots_domain::AgreementPrice::VariableWeight(radroots_domain::VariableWeight) +impl core::fmt::Debug for radroots_domain::AgreementPrice +pub fn radroots_domain::AgreementPrice::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_domain::AmountError pub radroots_domain::AmountError::CoefficientOutOfRange pub radroots_domain::AmountError::InvalidFormat @@ -256,6 +279,28 @@ impl core::error::Error for radroots_domain::QuantityError pub fn radroots_domain::QuantityError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)> impl core::fmt::Display for radroots_domain::QuantityError pub fn radroots_domain::QuantityError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::SupplyCommitment +pub radroots_domain::SupplyCommitment::FuturePromise(radroots_domain::FuturePromise) +pub radroots_domain::SupplyCommitment::StockBacked +impl core::fmt::Debug for radroots_domain::SupplyCommitment +pub fn radroots_domain::SupplyCommitment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +#[non_exhaustive] pub enum radroots_domain::TermsError +pub radroots_domain::TermsError::DuplicateFulfillment +pub radroots_domain::TermsError::DuplicateLine +pub radroots_domain::TermsError::InvalidFulfillmentCount +pub radroots_domain::TermsError::InvalidLineCount +pub radroots_domain::TermsError::InvalidSelectedTier +pub radroots_domain::TermsError::InvalidText +pub radroots_domain::TermsError::OptionMismatch +pub radroots_domain::TermsError::Pricing(radroots_domain::PricingError) +pub radroots_domain::TermsError::Purchase(radroots_domain::listing::ListingError) +pub radroots_domain::TermsError::SellerMismatch +pub radroots_domain::TermsError::TotalMismatch +pub radroots_domain::TermsError::UnknownFulfillment +impl core::error::Error for radroots_domain::TermsError +pub fn radroots_domain::TermsError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)> +impl core::fmt::Display for radroots_domain::TermsError +pub fn radroots_domain::TermsError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result #[non_exhaustive] pub enum radroots_domain::TimeError pub radroots_domain::TimeError::InvalidTimeZone pub radroots_domain::TimeError::InvalidWindow @@ -272,6 +317,46 @@ pub const fn radroots_domain::ActorRef::participant(self) -> radroots_identity:: pub const fn radroots_domain::ActorRef::role(self) -> radroots_domain::ActorRole impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ActorRef pub fn radroots_domain::ActorRef::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::AgreedFixedPrice +impl radroots_domain::AgreedFixedPrice +pub const fn radroots_domain::AgreedFixedPrice::basis(self) -> radroots_domain::PositiveDecimal +pub const fn radroots_domain::AgreedFixedPrice::discount_bps(self) -> radroots_domain::DiscountBps +pub const fn radroots_domain::AgreedFixedPrice::from_line(radroots_domain::LinePrice) -> Self +pub const fn radroots_domain::AgreedFixedPrice::new(radroots_domain::Money, radroots_domain::PositiveDecimal, radroots_domain::DiscountBps, core::option::Option<radroots_domain::Decimal>) -> Self +pub const fn radroots_domain::AgreedFixedPrice::rate(self) -> radroots_domain::Money +pub const fn radroots_domain::AgreedFixedPrice::selected_tier_from(self) -> core::option::Option<radroots_domain::Decimal> +pub fn radroots_domain::AgreedFixedPrice::total(self, radroots_domain::PositiveDecimal) -> core::result::Result<radroots_domain::Money, radroots_domain::TermsError> +impl core::fmt::Debug for radroots_domain::AgreedFixedPrice +pub fn radroots_domain::AgreedFixedPrice::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::AgreementLine +impl radroots_domain::AgreementLine +pub const fn radroots_domain::AgreementLine::amount(&self) -> radroots_domain::PositiveDecimal +pub const fn radroots_domain::AgreementLine::fulfillment_group(&self) -> radroots_domain::FulfillmentGroupId +pub const fn radroots_domain::AgreementLine::id(&self) -> radroots_domain::AgreementLineId +pub const fn radroots_domain::AgreementLine::maximum_line_total(&self) -> radroots_domain::Money +pub fn radroots_domain::AgreementLine::new(radroots_domain::AgreementLineId, radroots_domain::listing::ListingRevision, radroots_domain::ListingOptionId, radroots_domain::listing::Product, radroots_domain::listing::ListingOption, radroots_domain::PositiveDecimal, radroots_domain::FulfillmentGroupId, core::option::Option<&str>, radroots_domain::AgreementPrice, radroots_domain::Money) -> core::result::Result<Self, radroots_domain::TermsError> +pub const fn radroots_domain::AgreementLine::option(&self) -> &radroots_domain::listing::ListingOption +pub const fn radroots_domain::AgreementLine::option_id(&self) -> radroots_domain::ListingOptionId +pub const fn radroots_domain::AgreementLine::price(&self) -> radroots_domain::AgreementPrice +pub const fn radroots_domain::AgreementLine::product(&self) -> &radroots_domain::listing::Product +pub const fn radroots_domain::AgreementLine::source(&self) -> radroots_domain::listing::ListingRevision +pub fn radroots_domain::AgreementLine::source_lot_label(&self) -> core::option::Option<&str> +impl core::fmt::Debug for radroots_domain::AgreementLine +pub fn radroots_domain::AgreementLine::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::AgreementLineId(_) +impl radroots_domain::AgreementLineId +pub const fn radroots_domain::AgreementLineId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::AgreementLineId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::AgreementLineId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::AgreementLineId +pub fn radroots_domain::AgreementLineId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::AgreementLineId +pub type radroots_domain::AgreementLineId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::AgreementLineId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::AgreementLineId +pub fn radroots_domain::AgreementLineId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::AgreementLineId +pub fn radroots_domain::AgreementLineId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::Approval impl radroots_domain::Approval pub const fn radroots_domain::Approval::expires_at(&self) -> radroots_domain::UnixSeconds @@ -480,6 +565,34 @@ pub const fn radroots_domain::FixedPrice::rate(&self) -> radroots_domain::Money pub fn radroots_domain::FixedPrice::tiers(&self) -> &[radroots_domain::PriceTier] impl core::fmt::Debug for radroots_domain::FixedPrice pub fn radroots_domain::FixedPrice::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::FulfillmentGroup +impl radroots_domain::FulfillmentGroup +pub const fn radroots_domain::FulfillmentGroup::id(&self) -> radroots_domain::FulfillmentGroupId +pub const fn radroots_domain::FulfillmentGroup::new(radroots_domain::FulfillmentGroupId, radroots_domain::PrivateFulfillment) -> Self +pub const fn radroots_domain::FulfillmentGroup::terms(&self) -> &radroots_domain::PrivateFulfillment +impl core::fmt::Debug for radroots_domain::FulfillmentGroup +pub fn radroots_domain::FulfillmentGroup::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +pub struct radroots_domain::FulfillmentGroupId(_) +impl radroots_domain::FulfillmentGroupId +pub const fn radroots_domain::FulfillmentGroupId::as_bytes(&self) -> &[u8; 32] +pub const fn radroots_domain::FulfillmentGroupId::from_bytes([u8; 32]) -> Self +pub const fn radroots_domain::FulfillmentGroupId::into_bytes(self) -> [u8; 32] +impl core::fmt::Display for radroots_domain::FulfillmentGroupId +pub fn radroots_domain::FulfillmentGroupId::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::str::traits::FromStr for radroots_domain::FulfillmentGroupId +pub type radroots_domain::FulfillmentGroupId::Err = radroots_domain::IdentifierError +pub fn radroots_domain::FulfillmentGroupId::from_str(&str) -> core::result::Result<Self, Self::Err> +impl serde_core::ser::Serialize for radroots_domain::FulfillmentGroupId +pub fn radroots_domain::FulfillmentGroupId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> +impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::FulfillmentGroupId +pub fn radroots_domain::FulfillmentGroupId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::FuturePromise +impl radroots_domain::FuturePromise +pub const fn radroots_domain::FuturePromise::expected_window(&self) -> radroots_domain::Window +pub fn radroots_domain::FuturePromise::new(radroots_domain::Window, &str) -> core::result::Result<Self, radroots_domain::TermsError> +pub fn radroots_domain::FuturePromise::risk_disclosure(&self) -> &str +impl core::fmt::Debug for radroots_domain::FuturePromise +pub fn radroots_domain::FuturePromise::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::Generation(_) impl radroots_domain::Generation pub const fn radroots_domain::Generation::get(self) -> u64 @@ -728,6 +841,21 @@ impl serde_core::ser::Serialize for radroots_domain::SourceId pub fn radroots_domain::SourceId::serialize<S: serde_core::ser::Serializer>(&self, S) -> core::result::Result<<S as serde_core::ser::Serializer>::Ok, <S as serde_core::ser::Serializer>::Error> impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::SourceId pub fn radroots_domain::SourceId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> +pub struct radroots_domain::Terms +impl radroots_domain::Terms +pub const radroots_domain::Terms::MAX_FULFILLMENT_GROUPS: usize +pub const fn radroots_domain::Terms::buyer(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_domain::Terms::cancellation(&self) -> &'static str +pub fn radroots_domain::Terms::fulfillment(&self) -> &[radroots_domain::FulfillmentGroup] +pub const fn radroots_domain::Terms::fulfillment_charge(&self) -> radroots_domain::Money +pub fn radroots_domain::Terms::lines(&self) -> &[radroots_domain::AgreementLine] +pub const fn radroots_domain::Terms::maximum_total(&self) -> radroots_domain::Money +pub fn radroots_domain::Terms::new(radroots_identity::key::PublicKey, radroots_identity::key::PublicKey, alloc::vec::Vec<radroots_domain::AgreementLine>, alloc::vec::Vec<radroots_domain::FulfillmentGroup>, radroots_domain::Money, radroots_domain::Money, radroots_domain::SupplyCommitment) -> core::result::Result<Self, radroots_domain::TermsError> +pub const fn radroots_domain::Terms::rounding(&self) -> &'static str +pub const fn radroots_domain::Terms::seller(&self) -> radroots_identity::key::PublicKey +pub const fn radroots_domain::Terms::supply(&self) -> &radroots_domain::SupplyCommitment +impl core::fmt::Debug for radroots_domain::Terms +pub fn radroots_domain::Terms::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::ThreadId(_) impl radroots_domain::ThreadId pub const fn radroots_domain::ThreadId::as_bytes(&self) -> &[u8; 32] diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -87,6 +87,47 @@ Private fulfillment data retains a required window, explicit pickup/delivery mode and bounded zeroizing address/instructions/contact. It has no public wire serialization and grants no agreement, destination or delivery authority. +`Terms` retains complete immutable bilateral values: one through32 uniquely +identified lines, one through8 uniquely identified private fulfillment groups, +explicit participants, original listing revision/product/option snapshots, +selected positive purchase amounts, fulfillment fee, aggregate cap and supply +commitment. Every line names a declared group and a source coordinate for the +named seller. Coordinate/revision bytes and snapshots remain unverified claims +until independent authenticated source admission. + +`AgreementPrice` admits resolved fixed or absolute variable measurement terms; +quote-required has no agreed-price representation. `AgreedFixedPrice` retains +the selected rate/threshold, basis and discount independently of the unchanged +public option. It uses the shared half-even primitive and refuses a selected +threshold above the purchased amount. Lines validate original purchase rules +and recompute the declared fixed total or explicit variable cap. `Terms` sums +those checked maxima and the explicit fee in one currency within the money cap. +Variable line bounds are explicit absolute values; construction performs no +per-sale-unit scaling. Future promises retain a required expected window and +bounded nonempty risk disclosure, with no physical hold. Cancellation and +rounding identities are fixed by the supported value contract. + +Private terms, line/group data and supply promises expose borrowed accessors +and redacted diagnostics, with no automatic serialization/deserialization. +Their constructors grant no participant consent, installed agreement, signer +permission or stock effect. Private wire/hash admission remains separate. + +Line and group identities cannot be substituted: + +```compile_fail +use radroots_domain::{AgreementLineId, FulfillmentGroupId}; +let group = FulfillmentGroupId::from_bytes([0; 32]); +let _: AgreementLineId = group; +``` + +Private terms have no automatic public wire encoder: + +```compile_fail +fn encode(terms: &radroots_domain::Terms) { + let _ = serde_json::to_string(terms); +} +``` + Namespaces remain separate across native calls: ```compile_fail diff --git a/crates/domain/src/agreement.rs b/crates/domain/src/agreement.rs @@ -0,0 +1,445 @@ +use crate::{ + AgreementLineId, Decimal, DiscountBps, FulfillmentGroupId, LinePrice, ListingOptionId, + MAX_PRICED_LINES, Money, PRICING_PROFILE, PositiveDecimal, PricingError, PrivateFulfillment, + PublicKey, VariableWeight, Window, checked_order_total, + listing::{ListingError, ListingOption, ListingRevision, Product}, + pricing::net_line_minor, +}; +use alloc::{boxed::Box, string::String, vec::Vec}; +use core::fmt; +use zeroize::Zeroizing; + +/// One resolved fixed agreement rate, independent of its public option snapshot. +/// Selected-tier provenance is retained; no tier is selected again or invented. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct AgreedFixedPrice { + rate: Money, + basis: PositiveDecimal, + discount_bps: DiscountBps, + selected_tier_from: Option<Decimal>, +} +impl AgreedFixedPrice { + /// Captures validated numeric values. A line additionally checks that any + /// declared selected threshold does not exceed its purchased amount. + pub const fn new( + rate: Money, + basis: PositiveDecimal, + discount_bps: DiscountBps, + selected_tier_from: Option<Decimal>, + ) -> Self { + Self { + rate, + basis, + discount_bps, + selected_tier_from, + } + } + /// Retains the exact selected inputs of a qualified fixed-price calculation. + pub const fn from_line(value: LinePrice) -> Self { + Self::new( + value.rate(), + value.basis(), + value.discount_bps(), + value.selected_tier_from(), + ) + } + /// Returns the explicitly negotiated or resolved rate. + pub const fn rate(self) -> Money { + self.rate + } + /// Returns the positive basis in this line's selected sale unit. + pub const fn basis(self) -> PositiveDecimal { + self.basis + } + /// Returns the single discount, applied before rounding. + pub const fn discount_bps(self) -> DiscountBps { + self.discount_bps + } + /// Returns retained selected-tier provenance, including explicit None. + pub const fn selected_tier_from(self) -> Option<Decimal> { + self.selected_tier_from + } + /// Recomputes one net line with the shared checked half-even primitive. + pub fn total(self, amount: PositiveDecimal) -> Result<Money, TermsError> { + if self + .selected_tier_from + .is_some_and(|threshold| threshold > amount.amount()) + { + return Err(TermsError::InvalidSelectedTier); + } + Ok(Money::new( + self.rate.currency(), + net_line_minor(self.rate.minor(), amount, self.basis, self.discount_bps) + .map_err(TermsError::Pricing)?, + )) + } +} + +/// Complete agreed price: quote-required has no representation here. +/// Variable measurement bounds/cap are absolute for this entire line. +#[derive(Clone, Copy, Eq, PartialEq)] +#[non_exhaustive] +pub enum AgreementPrice { + /// Exact selected fixed inputs; no future tier reselection occurs. + Fixed(AgreedFixedPrice), + /// Explicit complete line bounds, unit, rate, basis and monetary cap. + VariableWeight(VariableWeight), +} +impl AgreementPrice { + fn maximum_total(self, amount: PositiveDecimal) -> Result<Money, TermsError> { + match self { + Self::Fixed(value) => value.total(amount), + Self::VariableWeight(value) => Ok(value.maximum_total()), + } + } +} + +/// Complete immutable line data. Its source and snapshot are claims pending +/// independent authenticated source admission; construction grants no consent. +#[derive(Clone, Eq, PartialEq)] +pub struct AgreementLine { + id: AgreementLineId, + source: ListingRevision, + product: Product, + option: ListingOption, + amount: PositiveDecimal, + fulfillment_group: FulfillmentGroupId, + source_lot_label: Option<Zeroizing<String>>, + price: AgreementPrice, + maximum_line_total: Money, +} +impl AgreementLine { + /// Validates the explicit option identity, purchase rules and independently + /// recomputed fixed total or variable cap. Negotiated prices need not equal + /// the original public price. No stock mapping or physical conversion occurs. + #[allow(clippy::too_many_arguments)] + pub fn new( + id: AgreementLineId, + source: ListingRevision, + option_id: ListingOptionId, + product: Product, + option: ListingOption, + amount: PositiveDecimal, + fulfillment_group: FulfillmentGroupId, + source_lot_label: Option<&str>, + price: AgreementPrice, + maximum_line_total: Money, + ) -> Result<Self, TermsError> { + if option_id != option.id() { + return Err(TermsError::OptionMismatch); + } + option + .validate_amount(amount) + .map_err(TermsError::Purchase)?; + if let Some(label) = source_lot_label { + text(label, 120, false)?; + } + if price.maximum_total(amount)? != maximum_line_total { + return Err(TermsError::TotalMismatch); + } + Ok(Self { + id, + source, + product, + option, + amount, + fulfillment_group, + source_lot_label: source_lot_label.map(|label| Zeroizing::new(label.into())), + price, + maximum_line_total, + }) + } + /// Returns the stable line identity, without lineage authentication. + pub const fn id(&self) -> AgreementLineId { + self.id + } + /// Returns the exact immutable source revision claim. + pub const fn source(&self) -> ListingRevision { + self.source + } + /// Returns the option identity, kept equal to the retained option snapshot. + pub const fn option_id(&self) -> ListingOptionId { + self.option.id() + } + /// Borrows the exact public product snapshot; no current-head lookup occurs. + pub const fn product(&self) -> &Product { + &self.product + } + /// Borrows the unchanged original sale option, including its public price. + pub const fn option(&self) -> &ListingOption { + &self.option + } + /// Returns the positive validated sale amount. + pub const fn amount(&self) -> PositiveDecimal { + self.amount + } + /// Returns the group identity checked by complete enclosing terms. + pub const fn fulfillment_group(&self) -> FulfillmentGroupId { + self.fulfillment_group + } + /// Explicitly borrows the optional private descriptive lot claim. + pub fn source_lot_label(&self) -> Option<&str> { + self.source_lot_label.as_ref().map(|v| v.as_str()) + } + /// Returns the complete agreed price, without changing its public provenance. + pub const fn price(&self) -> AgreementPrice { + self.price + } + /// Returns the independently checked fixed total or explicit variable cap. + pub const fn maximum_line_total(&self) -> Money { + self.maximum_line_total + } +} + +/// One stable private fulfillment identity and its complete validated data. +#[derive(Clone, Eq, PartialEq)] +pub struct FulfillmentGroup { + id: FulfillmentGroupId, + terms: PrivateFulfillment, +} +impl FulfillmentGroup { + /// Captures validated values; enclosing terms check uniqueness and links. + pub const fn new(id: FulfillmentGroupId, terms: PrivateFulfillment) -> Self { + Self { id, terms } + } + /// Returns the exact group identity. + pub const fn id(&self) -> FulfillmentGroupId { + self.id + } + /// Explicitly borrows private fulfillment data. + pub const fn terms(&self) -> &PrivateFulfillment { + &self.terms + } +} + +/// Explicit non-stock-backed expectation and risk claim, without scheduling. +#[derive(Clone, Eq, PartialEq)] +pub struct FuturePromise { + expected_window: Window, + risk_disclosure: Zeroizing<String>, +} +impl FuturePromise { + /// Requires an explicit bounded nonempty risk disclosure before copying. + pub fn new(expected_window: Window, risk_disclosure: &str) -> Result<Self, TermsError> { + text(risk_disclosure, 512, true)?; + Ok(Self { + expected_window, + risk_disclosure: Zeroizing::new(risk_disclosure.into()), + }) + } + /// Returns the exact expected window without current-time judgment. + pub const fn expected_window(&self) -> Window { + self.expected_window + } + /// Explicitly borrows the exact private risk text. + pub fn risk_disclosure(&self) -> &str { + &self.risk_disclosure + } +} + +/// Declared commitment mode, without a physical hold or installed promise. +#[derive(Clone, Eq, PartialEq)] +#[non_exhaustive] +pub enum SupplyCommitment { + /// Requires the executor's separately verified stock-backed installation. + StockBacked, + /// Explicit expectation and risk, never physical stock backing. + FuturePromise(FuturePromise), +} + +/// Complete validated bilateral data, not participant consent, authenticated +/// source evidence, an installed agreement or a physical stock reservation. +/// Private wire/hash encoding remains owned by the admitting protocol. +#[derive(Clone, Eq, PartialEq)] +pub struct Terms { + buyer: PublicKey, + seller: PublicKey, + lines: Box<[AgreementLine]>, + fulfillment: Box<[FulfillmentGroup]>, + fulfillment_charge: Money, + maximum_total: Money, + supply: SupplyCommitment, +} +impl Terms { + /// Greatest supported number of private fulfillment groups. + pub const MAX_FULFILLMENT_GROUPS: usize = 8; + /// Bounds collections before capture; checks distinct IDs, complete group + /// links, source seller identities and recomputed same-currency line totals. + /// No live lookup, signing, authorization or stock effect occurs. + pub fn new( + buyer: PublicKey, + seller: PublicKey, + lines: Vec<AgreementLine>, + fulfillment: Vec<FulfillmentGroup>, + fulfillment_charge: Money, + maximum_total: Money, + supply: SupplyCommitment, + ) -> Result<Self, TermsError> { + if lines.is_empty() || lines.len() > MAX_PRICED_LINES { + return Err(TermsError::InvalidLineCount); + } + if fulfillment.is_empty() || fulfillment.len() > Self::MAX_FULFILLMENT_GROUPS { + return Err(TermsError::InvalidFulfillmentCount); + } + for (index, group) in fulfillment.iter().enumerate() { + if fulfillment[..index] + .iter() + .any(|prior| prior.id == group.id) + { + return Err(TermsError::DuplicateFulfillment); + } + } + for (index, line) in lines.iter().enumerate() { + if lines[..index].iter().any(|prior| prior.id == line.id) { + return Err(TermsError::DuplicateLine); + } + if line.source.coordinate().author() != seller { + return Err(TermsError::SellerMismatch); + } + if !fulfillment + .iter() + .any(|group| group.id == line.fulfillment_group) + { + return Err(TermsError::UnknownFulfillment); + } + } + let totals: Vec<_> = lines + .iter() + .map(AgreementLine::maximum_line_total) + .collect(); + let recomputed = + checked_order_total(&totals, fulfillment_charge).map_err(TermsError::Pricing)?; + if recomputed != maximum_total { + return Err(TermsError::TotalMismatch); + } + Ok(Self { + buyer, + seller, + lines: lines.into_boxed_slice(), + fulfillment: fulfillment.into_boxed_slice(), + fulfillment_charge, + maximum_total, + supply, + }) + } + /// Returns the named buyer without authenticating its consent or signer. + pub const fn buyer(&self) -> PublicKey { + self.buyer + } + /// Returns the named seller, matching all source coordinate authors. + pub const fn seller(&self) -> PublicKey { + self.seller + } + /// Borrows the complete immutable ordered line set. + pub fn lines(&self) -> &[AgreementLine] { + &self.lines + } + /// Explicitly borrows the bounded private fulfillment groups. + pub fn fulfillment(&self) -> &[FulfillmentGroup] { + &self.fulfillment + } + /// Returns the explicit same-currency fulfillment fee, including valid zero. + pub const fn fulfillment_charge(&self) -> Money { + self.fulfillment_charge + } + /// Returns the independently recomputed aggregate maximum. + pub const fn maximum_total(&self) -> Money { + self.maximum_total + } + /// Borrows the explicit commitment declaration; no hold is minted. + pub const fn supply(&self) -> &SupplyCommitment { + &self.supply + } + /// Returns the fixed supported residual-cancellation contract identity. + pub const fn cancellation(&self) -> &'static str { + "mutual_residual_v1" + } + /// Returns the fixed supported net-line rounding contract identity. + pub const fn rounding(&self) -> &'static str { + PRICING_PROFILE + } +} + +fn text(value: &str, maximum: usize, nonempty: bool) -> Result<(), TermsError> { + if (nonempty && value.is_empty()) + || value.len() > maximum * 4 + || value.chars().count() > maximum + { + return Err(TermsError::InvalidText); + } + Ok(()) +} + +/// Input-free bilateral-value admission failure; no private data is retained. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum TermsError { + /// The complete agreement requires one through32 lines. + InvalidLineCount, + /// The complete agreement requires one through8 private groups. + InvalidFulfillmentCount, + /// A line identity repeats within one complete line set. + DuplicateLine, + /// A private fulfillment identity repeats. + DuplicateFulfillment, + /// A line references no declared private group. + UnknownFulfillment, + /// An explicit option ID differs from the retained original snapshot. + OptionMismatch, + /// A listing coordinate author differs from the named seller. + SellerMismatch, + /// Required risk text is empty or private text exceeds its bound. + InvalidText, + /// A selected threshold exceeds the purchased sale amount. + InvalidSelectedTier, + /// A declared line or order total differs from exact recomputation. + TotalMismatch, + /// The original option's selected-amount rules were not met. + Purchase(ListingError), + /// Checked arithmetic, currency or supported aggregate bounds failed. + Pricing(PricingError), +} +impl fmt::Display for TermsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::InvalidLineCount => "invalid agreement line count", + Self::InvalidFulfillmentCount => "invalid private fulfillment count", + Self::DuplicateLine => "duplicate agreement line", + Self::DuplicateFulfillment => "duplicate private fulfillment group", + Self::UnknownFulfillment => "unknown private fulfillment group", + Self::OptionMismatch => "agreement option identity mismatch", + Self::SellerMismatch => "agreement source seller mismatch", + Self::InvalidText => "invalid private agreement text", + Self::InvalidSelectedTier => "invalid selected agreement tier", + Self::TotalMismatch => "agreement total differs from recomputation", + Self::Purchase(error) => return error.fmt(f), + Self::Pricing(error) => return error.fmt(f), + }) + } +} +impl core::error::Error for TermsError { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + Self::Purchase(error) => Some(error), + Self::Pricing(error) => Some(error), + _ => None, + } + } +} + +macro_rules! redacted { + ($($name:ident),+)=> { $(impl fmt::Debug for $name { + fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { + f.write_str(concat!(stringify!($name),"(<redacted>)")) + } + })+ }; +} +redacted!( + AgreedFixedPrice, + AgreementPrice, + AgreementLine, + FulfillmentGroup, + FuturePromise, + SupplyCommitment, + Terms +); diff --git a/crates/domain/src/identifier.rs b/crates/domain/src/identifier.rs @@ -116,6 +116,14 @@ identifier!( ListingOptionId, "An exact 256-bit public sale-option identifier." ); +identifier!( + AgreementLineId, + "An exact 256-bit line identity within an agreement lineage." +); +identifier!( + FulfillmentGroupId, + "An exact 256-bit private fulfillment-group identity." +); identifier!(ThreadId, "An exact 256-bit private thread identifier."); identifier!( WorkspaceId, diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs @@ -5,6 +5,7 @@ extern crate alloc; +mod agreement; mod amount; mod context; mod currency; @@ -23,6 +24,10 @@ mod variable_price; /// The identity-owned validated participant key; no second key type is defined. pub use radroots_identity::PublicKey; +pub use agreement::{ + AgreedFixedPrice, AgreementLine, AgreementPrice, FulfillmentGroup, FuturePromise, + SupplyCommitment, Terms, TermsError, +}; pub use amount::{AmountError, Decimal, PositiveDecimal}; pub use context::{ ActorRef, ActorRole, Approval, AuthorityRef, CheckpointRef, CommandContextData, ContextError, @@ -34,9 +39,10 @@ pub use currency::{ }; pub use fulfillment::{FulfillmentError, PrivateFulfillment}; pub use identifier::{ - ApprovalIntentDigest, CheckpointDigest, CommandDigest, EnvelopeEventId, ExecutorId, GrantId, - IdentifierError, ListingOptionId, MessageId, OperationId, OrderId, RecordId, RouteDigest, - SigningAttemptId, SourceId, ThreadId, TransactionId, WorkspaceId, + AgreementLineId, ApprovalIntentDigest, CheckpointDigest, CommandDigest, EnvelopeEventId, + ExecutorId, FulfillmentGroupId, GrantId, IdentifierError, ListingOptionId, MessageId, + OperationId, OrderId, RecordId, RouteDigest, SigningAttemptId, SourceId, ThreadId, + TransactionId, WorkspaceId, }; pub use issuance::{FIRST_ISSUANCE_MAX_SECONDS, IssuanceWindow}; pub use message::{CHAT_MAX_BYTES, ChatMessage, ChatRelation, MessageError}; diff --git a/crates/domain/src/listing.rs b/crates/domain/src/listing.rs @@ -10,6 +10,8 @@ use core::{fmt, str::FromStr}; mod view; pub use view::{Listing, ListingText}; +mod reference; +pub use reference::{ListingCoordinate, ListingRevision}; mod price; pub use price::Price; mod media; diff --git a/crates/domain/src/listing/reference.rs b/crates/domain/src/listing/reference.rs @@ -0,0 +1,74 @@ +use super::ListingId; +use crate::{EnvelopeEventId, PublicKey}; +use core::fmt; + +/// Exact public listing coordinate, without an authenticated observation claim. +#[derive(Clone, Copy, Eq, PartialEq)] +pub struct ListingCoordinate { + author: PublicKey, + d: ListingId, +} +impl ListingCoordinate { + /// Captures validated identity parts; the kind is always NIP-99 kind30402. + pub const fn new(author: PublicKey, d: ListingId) -> Self { + Self { author, d } + } + /// Returns the fixed listing kind, never a caller-supplied alternative. + pub const fn kind(self) -> u16 { + 30402 + } + /// Returns the participant named by the coordinate, without author proof. + pub const fn author(self) -> PublicKey { + self.author + } + /// Returns the exact stable 128-bit discriminator. + pub const fn d(self) -> ListingId { + self.d + } +} +impl fmt::Debug for ListingCoordinate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ListingCoordinate(<redacted>)") + } +} +#[cfg(feature = "serde")] +impl serde::Serialize for ListingCoordinate { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + use serde::ser::SerializeStruct; + let mut out = serializer.serialize_struct("ListingCoordinate", 3)?; + out.serialize_field("kind", &self.kind())?; + out.serialize_field("author", &self.author)?; + out.serialize_field("d", &self.d)?; + out.end() + } +} + +/// Exact revision identity and coordinate; bytes alone authenticate no source. +#[derive(Clone, Copy, Eq, PartialEq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize))] +pub struct ListingRevision { + coordinate: ListingCoordinate, + event_id: EnvelopeEventId, +} +impl ListingRevision { + /// Captures structural data; source authentication/admission remains separate. + pub const fn new(coordinate: ListingCoordinate, event_id: EnvelopeEventId) -> Self { + Self { + coordinate, + event_id, + } + } + /// Returns the complete stable coordinate. + pub const fn coordinate(self) -> ListingCoordinate { + self.coordinate + } + /// Returns the exact signed-artifact identity claimed as the source. + pub const fn event_id(self) -> EnvelopeEventId { + self.event_id + } +} +impl fmt::Debug for ListingRevision { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ListingRevision(<redacted>)") + } +} diff --git a/crates/domain/src/listing/view.rs b/crates/domain/src/listing/view.rs @@ -1,5 +1,5 @@ //! Immutable public values. Construction authenticates no source or installation. -use super::{ListingError, ListingId, ListingTerms, text}; +use super::{ListingCoordinate, ListingError, ListingId, ListingRevision, ListingTerms, text}; use crate::{EnvelopeEventId, PublicKey, UnixSeconds}; use alloc::string::String; use core::fmt; @@ -96,6 +96,10 @@ impl Listing { pub const fn revision(&self) -> EnvelopeEventId { self.revision } + /// Returns the exact structural source reference, without new source proof. + pub const fn source(&self) -> ListingRevision { + ListingRevision::new(ListingCoordinate::new(self.author, self.id), self.revision) + } /// Original signed event time, not local installation or current time. pub const fn created_at(&self) -> UnixSeconds { self.created_at diff --git a/crates/domain/tests/identifier.rs b/crates/domain/tests/identifier.rs @@ -29,6 +29,8 @@ fn captured_context_identities_preserve_full_width_and_canonical_encoding() { }}; } check!(radroots_domain::SigningAttemptId); + check!(radroots_domain::AgreementLineId); + check!(radroots_domain::FulfillmentGroupId); check!(radroots_domain::GrantId); check!(radroots_domain::RecordId); check!(radroots_domain::SourceId); diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs @@ -6,6 +6,9 @@ mod media; #[path = "support/listing_time.rs"] mod time; +#[path = "support/agreement.rs"] +mod agreement; + #[test] fn public_text_has_shared_unicode_bounds_and_revision_data_rejects_inverted_time() { use radroots_domain::{EnvelopeEventId, PublicKey, UnixSeconds}; diff --git a/crates/domain/tests/support/agreement.rs b/crates/domain/tests/support/agreement.rs @@ -0,0 +1,688 @@ +use radroots_domain::{ + AgreedFixedPrice, AgreementLine, AgreementLineId, AgreementPrice, DiscountBps, EnvelopeEventId, + FixedPrice, FulfillmentGroup, FulfillmentGroupId, FuturePromise, ListingOptionId, Money, + MoneyError, PositiveDecimal, PriceTier, PricingError, PrivateFulfillment, PublicKey, + SupplyCommitment, Terms, TermsError, TimeZoneId, UnixSeconds, VariableWeight, Window, + listing::*, +}; + +fn seller() -> PublicKey { + PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap() +} +fn buyer() -> PublicKey { + PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5").unwrap() +} +fn money(minor: &str) -> Money { + Money::from_parts("CAD", minor, 2).unwrap() +} +fn source(author: PublicKey) -> ListingRevision { + ListingRevision::new( + ListingCoordinate::new(author, ListingId::from_bytes([1; 16])), + EnvelopeEventId::from_bytes([3; 32]), + ) +} +fn window() -> Window { + Window::new( + UnixSeconds::new(100).unwrap(), + UnixSeconds::new(200).unwrap(), + TimeZoneId::from_name("Etc/UTC").unwrap(), + ) + .unwrap() +} +fn group(id: u8) -> FulfillmentGroup { + FulfillmentGroup::new( + FulfillmentGroupId::from_bytes([id; 32]), + PrivateFulfillment::new( + FulfillmentMode::Pickup, + window(), + "Private destination", + "Private instructions", + Some("Private contact"), + ) + .unwrap(), + ) +} +fn option() -> ListingOption { + ListingOption::quote_required( + ListingOptionId::from_bytes([2; 32]), + "Original bunch", + SaleUnit::package_unspecified("bunch").unwrap(), + "1".parse().unwrap(), + "1".parse().unwrap(), + Supply::Estimated { + amount: "0".parse().unwrap(), + window: None, + }, + LeadSeconds::new(0).unwrap(), + ) + .unwrap() +} +fn agreed(minor: &str) -> AgreementPrice { + AgreementPrice::Fixed(AgreedFixedPrice::new( + money(minor), + "1".parse().unwrap(), + DiscountBps::NONE, + None, + )) +} +#[allow(clippy::too_many_arguments)] +fn line_with( + id: u8, + source: ListingRevision, + option_id: ListingOptionId, + option: ListingOption, + amount: &str, + group: u8, + label: Option<&str>, + price: AgreementPrice, + total: Money, +) -> Result<AgreementLine, TermsError> { + AgreementLine::new( + AgreementLineId::from_bytes([id; 32]), + source, + option_id, + super::product(), + option, + amount.parse().unwrap(), + FulfillmentGroupId::from_bytes([group; 32]), + label, + price, + total, + ) +} +fn line(id: u8, group: u8) -> AgreementLine { + line_with( + id, + source(seller()), + option().id(), + option(), + "2", + group, + Some("Private lot claim"), + agreed("325"), + money("650"), + ) + .unwrap() +} +fn terms( + lines: Vec<AgreementLine>, + groups: Vec<FulfillmentGroup>, + fee: Money, + total: Money, +) -> Result<Terms, TermsError> { + Terms::new( + buyer(), + seller(), + lines, + groups, + fee, + total, + SupplyCommitment::StockBacked, + ) +} + +#[test] +fn complete_negotiated_quote_terms_preserve_snapshot_and_independently_recompute_fee_and_cap() { + let line = line(7, 9); + assert_eq!(line.id(), AgreementLineId::from_bytes([7; 32])); + assert_eq!(line.source(), source(seller())); + assert_eq!(line.option_id(), option().id()); + assert_eq!(line.product(), &super::product()); + assert_eq!(line.option(), &option()); + assert_eq!(line.option().price(), &Price::QuoteRequired); + assert_eq!(line.amount(), "2".parse::<PositiveDecimal>().unwrap()); + assert_eq!( + line.fulfillment_group(), + FulfillmentGroupId::from_bytes([9; 32]) + ); + assert_eq!(line.source_lot_label(), Some("Private lot claim")); + assert_eq!(line.price(), agreed("325")); + assert_eq!(line.maximum_line_total(), money("650")); + let value = terms(vec![line], vec![group(9)], money("50"), money("700")).unwrap(); + assert_eq!(value.buyer(), buyer()); + assert_eq!(value.seller(), seller()); + assert_eq!(value.maximum_total(), money("700")); + assert_eq!(value.fulfillment_charge(), money("50")); + assert_eq!(value.lines().len(), 1); + assert_eq!(value.fulfillment(), [group(9)]); + assert_eq!( + value.fulfillment()[0].id(), + FulfillmentGroupId::from_bytes([9; 32]) + ); + assert_eq!( + value.fulfillment()[0].terms().address(), + "Private destination" + ); + assert_eq!(value.supply(), &SupplyCommitment::StockBacked); + assert_eq!(value.cancellation(), "mutual_residual_v1"); + assert_eq!(value.rounding(), "half_even_net_line_v1"); + assert_eq!(value, value.clone()); + assert_eq!(format!("{value:?}"), "Terms(<redacted>)"); + assert_eq!( + format!("{:?}", value.lines()[0]), + "AgreementLine(<redacted>)" + ); + assert_eq!( + format!("{:?}", value.fulfillment()[0]), + "FulfillmentGroup(<redacted>)" + ); + assert_eq!( + format!("{:?}", value.supply()), + "SupplyCommitment(<redacted>)" + ); +} + +#[test] +fn resolved_fixed_tiers_and_half_even_values_match_retained_independent_vectors_without_reselection() + { + let fixed = FixedPrice::new( + money("325"), + "1".parse().unwrap(), + DiscountBps::new(1000).unwrap(), + vec![PriceTier::new("2".parse().unwrap(), money("299"))], + ) + .unwrap(); + let resolved = fixed.line("3.5".parse().unwrap()).unwrap(); + let price = AgreedFixedPrice::from_line(resolved); + assert_eq!(price.rate(), money("299")); + assert_eq!(price.basis(), "1".parse::<PositiveDecimal>().unwrap()); + assert_eq!(price.discount_bps(), DiscountBps::new(1000).unwrap()); + assert_eq!(price.selected_tier_from(), Some("2".parse().unwrap())); + assert_eq!(price.total("3.5".parse().unwrap()).unwrap(), money("942")); + assert_eq!( + price.total("1".parse().unwrap()), + Err(TermsError::InvalidSelectedTier) + ); + assert_eq!(format!("{price:?}"), "AgreedFixedPrice(<redacted>)"); + for (rate, quantity, expected) in [ + ("325", "2.5", "812"), + ("327", "2.5", "818"), + ("0", "100", "0"), + ] { + let price = + AgreedFixedPrice::new(money(rate), "1".parse().unwrap(), DiscountBps::NONE, None); + assert_eq!( + price.total(quantity.parse().unwrap()).unwrap(), + money(expected) + ); + } + let full_discount = AgreedFixedPrice::new( + money("325"), + "1".parse().unwrap(), + DiscountBps::FULL, + Some("0".parse().unwrap()), + ); + assert_eq!( + full_discount.total("2".parse().unwrap()).unwrap(), + money("0") + ); + let original = ListingOption::new( + option().id(), + "Public fixed offering", + SaleUnit::measured(MeasurementUnit::Kilogram), + "0.5".parse().unwrap(), + "0.5".parse().unwrap(), + Price::Fixed(fixed), + Supply::Unknown, + LeadSeconds::new(0).unwrap(), + ) + .unwrap(); + let line = line_with( + 1, + source(seller()), + original.id(), + original.clone(), + "3.5", + 1, + None, + AgreementPrice::Fixed(price), + money("942"), + ) + .unwrap(); + assert_eq!(line.option(), &original); + assert_eq!(line.source_lot_label(), None); + assert_eq!( + terms(vec![line], vec![group(1)], money("0"), money("942")) + .unwrap() + .maximum_total(), + money("942") + ); +} + +#[test] +fn variable_agreement_bounds_are_explicit_absolute_line_values_and_never_auto_scaled() { + let advertised = VariableWeight::new( + MeasurementUnit::Kilogram, + "0.8".parse().unwrap(), + "1.2".parse().unwrap(), + money("325"), + "1".parse().unwrap(), + money("400"), + ) + .unwrap(); + let original = ListingOption::new( + option().id(), + "Estimated bag", + option().unit().clone(), + "1".parse().unwrap(), + "1".parse().unwrap(), + Price::VariableWeight(advertised), + Supply::Unknown, + LeadSeconds::new(0).unwrap(), + ) + .unwrap(); + let absolute = VariableWeight::new( + MeasurementUnit::Kilogram, + "2".parse().unwrap(), + "4".parse().unwrap(), + money("325"), + "1".parse().unwrap(), + money("1000"), + ) + .unwrap(); + let line = line_with( + 1, + source(seller()), + original.id(), + original.clone(), + "3", + 1, + None, + AgreementPrice::VariableWeight(absolute), + money("1000"), + ) + .unwrap(); + assert_eq!(line.option(), &original); + assert_eq!(line.price(), AgreementPrice::VariableWeight(absolute)); + assert_eq!(line.maximum_line_total(), money("1000")); + assert_eq!( + absolute + .total_at( + radroots_domain::Quantity::new("3".parse().unwrap(), MeasurementUnit::Kilogram) + .unwrap() + ) + .unwrap(), + money("975") + ); + assert_eq!( + absolute.total_at( + radroots_domain::Quantity::new("4".parse().unwrap(), MeasurementUnit::Kilogram) + .unwrap() + ), + Err(PricingError::CapExceeded) + ); + assert_eq!( + terms(vec![line], vec![group(1)], money("10"), money("1010")) + .unwrap() + .maximum_total(), + money("1010") + ); + assert_eq!( + format!("{:?}", AgreementPrice::VariableWeight(absolute)), + "AgreementPrice(<redacted>)" + ); + assert_eq!( + line_with( + 1, + source(seller()), + original.id(), + original, + "3", + 1, + None, + AgreementPrice::VariableWeight(absolute), + money("3000") + ) + .unwrap_err(), + TermsError::TotalMismatch + ); +} + +#[test] +fn line_admission_refuses_snapshot_quantity_tier_text_and_claimed_total_mismatches() { + assert_eq!( + line_with( + 1, + source(seller()), + ListingOptionId::from_bytes([99; 32]), + option(), + "2", + 1, + None, + agreed("325"), + money("650") + ) + .unwrap_err(), + TermsError::OptionMismatch + ); + assert_eq!( + line_with( + 1, + source(seller()), + option().id(), + option(), + "0.5", + 1, + None, + agreed("325"), + money("0") + ) + .unwrap_err(), + TermsError::Purchase(ListingError::InvalidQuantity) + ); + let minimum = ListingOption::quote_required( + option().id(), + "Even bunches", + option().unit().clone(), + "2".parse().unwrap(), + "4".parse().unwrap(), + Supply::Unknown, + LeadSeconds::new(0).unwrap(), + ) + .unwrap(); + for quantity in ["2", "5"] { + assert_eq!( + line_with( + 1, + source(seller()), + minimum.id(), + minimum.clone(), + quantity, + 1, + None, + agreed("0"), + money("0") + ) + .unwrap_err(), + TermsError::Purchase(ListingError::InvalidQuantity) + ); + } + for label in ["x".repeat(121), "🥕".repeat(121), "x".repeat(481)] { + assert_eq!( + line_with( + 1, + source(seller()), + option().id(), + option(), + "2", + 1, + Some(&label), + agreed("325"), + money("650") + ) + .unwrap_err(), + TermsError::InvalidText + ); + } + let label = "🥕".repeat(120); + assert_eq!( + line_with( + 1, + source(seller()), + option().id(), + option(), + "2", + 1, + Some(&label), + agreed("325"), + money("650") + ) + .unwrap() + .source_lot_label(), + Some(label.as_str()) + ); + assert_eq!( + line_with( + 1, + source(seller()), + option().id(), + option(), + "2", + 1, + Some(""), + agreed("325"), + money("650") + ) + .unwrap() + .source_lot_label(), + Some("") + ); + for total in [ + money("649"), + money("651"), + Money::from_parts("USD", "650", 2).unwrap(), + ] { + assert_eq!( + line_with( + 1, + source(seller()), + option().id(), + option(), + "2", + 1, + None, + agreed("325"), + total + ) + .unwrap_err(), + TermsError::TotalMismatch + ); + } +} + +#[test] +fn complete_terms_enforce_collection_identity_seller_and_group_closure_before_capture() { + assert_eq!( + terms(vec![], vec![group(1)], money("0"), money("0")).unwrap_err(), + TermsError::InvalidLineCount + ); + assert_eq!( + terms(vec![line(1, 1); 33], vec![group(1)], money("0"), money("0")).unwrap_err(), + TermsError::InvalidLineCount + ); + assert_eq!( + terms(vec![line(1, 1)], vec![], money("0"), money("650")).unwrap_err(), + TermsError::InvalidFulfillmentCount + ); + assert_eq!( + terms( + vec![line(1, 1)], + vec![group(1); 9], + money("0"), + money("650") + ) + .unwrap_err(), + TermsError::InvalidFulfillmentCount + ); + assert_eq!( + terms( + vec![line(1, 1); 2], + vec![group(1)], + money("0"), + money("1300") + ) + .unwrap_err(), + TermsError::DuplicateLine + ); + assert_eq!( + terms( + vec![line(1, 1)], + vec![group(1); 2], + money("0"), + money("650") + ) + .unwrap_err(), + TermsError::DuplicateFulfillment + ); + assert_eq!( + terms(vec![line(1, 99)], vec![group(1)], money("0"), money("650")).unwrap_err(), + TermsError::UnknownFulfillment + ); + let wrong_source = line_with( + 1, + source(buyer()), + option().id(), + option(), + "2", + 1, + None, + agreed("325"), + money("650"), + ) + .unwrap(); + assert_eq!( + terms(vec![wrong_source], vec![group(1)], money("0"), money("650")).unwrap_err(), + TermsError::SellerMismatch + ); + for total in [money("649"), Money::from_parts("USD", "650", 2).unwrap()] { + assert_eq!( + terms(vec![line(1, 1)], vec![group(1)], money("0"), total).unwrap_err(), + TermsError::TotalMismatch + ); + } + assert_eq!( + terms( + vec![line(1, 1)], + vec![group(1)], + Money::from_parts("USD", "0", 2).unwrap(), + money("650") + ) + .unwrap_err(), + TermsError::Pricing(PricingError::Money(MoneyError::CurrencyMismatch)) + ); +} + +#[test] +fn maximum_collections_preserve_line_order_and_check_aggregate_money_bounds() { + let mut lines = Vec::with_capacity(4096); + for id in 0..32 { + lines.push(line(id, (id % 8) + 1)); + } + let mut groups = Vec::with_capacity(4096); + groups.extend((1..=8).map(group)); + let expected = lines.clone(); + let value = terms(lines, groups, money("1"), money("20801")).unwrap(); + assert_eq!(value.lines(), expected); + assert_eq!(value.fulfillment().len(), 8); + let maximum = line_with( + 1, + source(seller()), + option().id(), + option(), + "1", + 1, + None, + agreed("999999999999999"), + money("999999999999999"), + ) + .unwrap(); + assert_eq!( + terms( + vec![maximum], + vec![group(1)], + money("1"), + money("999999999999999") + ) + .unwrap_err(), + TermsError::Pricing(PricingError::Money(MoneyError::MinorOutOfRange)) + ); +} + +#[test] +fn future_promise_requires_exact_bounded_risk_and_confers_no_physical_backing() { + let risk = "🥕".repeat(512); + let promise = FuturePromise::new(window(), &risk).unwrap(); + assert_eq!(promise.expected_window(), window()); + assert_eq!(promise.risk_disclosure(), risk); + assert_eq!(promise, promise.clone()); + assert_eq!(format!("{promise:?}"), "FuturePromise(<redacted>)"); + for text in [ + String::new(), + "x".repeat(513), + "🥕".repeat(513), + "x".repeat(2049), + ] { + assert_eq!( + FuturePromise::new(window(), &text).unwrap_err(), + TermsError::InvalidText + ); + } + let value = Terms::new( + buyer(), + seller(), + vec![line(1, 1)], + vec![group(1)], + money("0"), + money("650"), + SupplyCommitment::FuturePromise(promise.clone()), + ) + .unwrap(); + assert_eq!(value.supply(), &SupplyCommitment::FuturePromise(promise)); +} + +#[test] +fn exact_listing_source_references_retain_full_coordinate_and_signed_revision_identity() { + let reference = source(seller()); + assert_eq!(reference.coordinate().kind(), 30402); + assert_eq!(reference.coordinate().author(), seller()); + assert_eq!(reference.coordinate().d(), ListingId::from_bytes([1; 16])); + assert_eq!(reference.event_id(), EnvelopeEventId::from_bytes([3; 32])); + assert_eq!(format!("{reference:?}"), "ListingRevision(<redacted>)"); + assert_eq!( + format!("{:?}", reference.coordinate()), + "ListingCoordinate(<redacted>)" + ); + let published = Listing::new( + reference.coordinate().d(), + seller(), + reference.event_id(), + UnixSeconds::new(101).unwrap(), + UnixSeconds::new(100).unwrap(), + ListingText::new("Carrots", "Public terms", "").unwrap(), + ListingTerms::new( + ListingState::Active, + super::product(), + option().id(), + vec![option()], + super::fulfillment(), + None, + vec![], + ) + .unwrap(), + ) + .unwrap(); + assert_eq!(published.source(), reference); + #[cfg(feature = "serde")] + assert_eq!( + serde_json::to_value(reference).unwrap(), + serde_json::json!({ + "coordinate":{"kind":30402,"author":seller().to_string(),"d":"01".repeat(16)}, + "event_id":"03".repeat(32)}) + ); +} + +#[test] +fn agreement_failures_remain_typed_bounded_and_input_free() { + for error in [ + TermsError::InvalidLineCount, + TermsError::InvalidFulfillmentCount, + TermsError::DuplicateLine, + TermsError::DuplicateFulfillment, + TermsError::UnknownFulfillment, + TermsError::OptionMismatch, + TermsError::SellerMismatch, + TermsError::InvalidText, + TermsError::InvalidSelectedTier, + TermsError::TotalMismatch, + TermsError::Purchase(ListingError::InvalidQuantity), + TermsError::Pricing(PricingError::Money(MoneyError::CurrencyMismatch)), + ] { + assert!(error.to_string().len() < 128); + assert!(!format!("{error:?}").contains("Private")); + let source = core::error::Error::source(&error); + assert_eq!( + source.is_some(), + matches!(error, TermsError::Purchase(_) | TermsError::Pricing(_)) + ); + } +}