commit 1af72be4554dbeb5be73eb2e5fcab853faf05b5f
parent 329978dbfbd7e1044a12d882c5f5ecf543f16638
Author: triesap <tyson@radroots.org>
Date: Thu, 22 Oct 2026 15:09:46 +0000
domain: calculate exact tiered net-line prices
- Validate bounded discounts and strictly ordered same-currency price tiers.
- Apply checked rational arithmetic and half-even rounding once per net line.
- Sum bounded rounded lines with explicit fulfillment charges and typed failures.
- Verify independent vectors, feature portability, public API and coverage gates.
Diffstat:
6 files changed, 901 insertions(+), 2 deletions(-)
diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt
@@ -171,10 +171,25 @@ pub radroots_domain::MoneyError::NegativeResult
pub radroots_domain::MoneyError::NonCanonicalMinor
impl core::convert::From<radroots_domain::CurrencyError> for radroots_domain::MoneyError
pub fn radroots_domain::MoneyError::from(radroots_domain::CurrencyError) -> Self
+impl core::convert::From<radroots_domain::MoneyError> for radroots_domain::PricingError
+pub fn radroots_domain::PricingError::from(radroots_domain::MoneyError) -> Self
impl core::error::Error for radroots_domain::MoneyError
pub fn radroots_domain::MoneyError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)>
impl core::fmt::Display for radroots_domain::MoneyError
pub fn radroots_domain::MoneyError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
+#[non_exhaustive] pub enum radroots_domain::PricingError
+pub radroots_domain::PricingError::ArithmeticOutOfRange
+pub radroots_domain::PricingError::InvalidDiscount
+pub radroots_domain::PricingError::InvalidLineCount
+pub radroots_domain::PricingError::InvalidTierOrder
+pub radroots_domain::PricingError::Money(radroots_domain::MoneyError)
+pub radroots_domain::PricingError::TooManyTiers
+impl core::convert::From<radroots_domain::MoneyError> for radroots_domain::PricingError
+pub fn radroots_domain::PricingError::from(radroots_domain::MoneyError) -> Self
+impl core::error::Error for radroots_domain::PricingError
+pub fn radroots_domain::PricingError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)>
+impl core::fmt::Display for radroots_domain::PricingError
+pub fn radroots_domain::PricingError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_domain::ActorRef
impl radroots_domain::ActorRef
pub const fn radroots_domain::ActorRef::grant_id(self) -> core::option::Option<radroots_domain::GrantId>
@@ -335,6 +350,14 @@ impl serde_core::ser::Serialize for radroots_domain::Decimal
pub fn radroots_domain::Decimal::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::Decimal
pub fn radroots_domain::Decimal::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error>
+pub struct radroots_domain::DiscountBps(_)
+impl radroots_domain::DiscountBps
+pub const radroots_domain::DiscountBps::FULL: Self
+pub const radroots_domain::DiscountBps::NONE: Self
+pub const fn radroots_domain::DiscountBps::get(self) -> u16
+pub const fn radroots_domain::DiscountBps::new(u16) -> core::result::Result<Self, radroots_domain::PricingError>
+impl core::fmt::Debug for radroots_domain::DiscountBps
+pub fn radroots_domain::DiscountBps::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_domain::EnvelopeEventId(_)
impl radroots_domain::EnvelopeEventId
pub const fn radroots_domain::EnvelopeEventId::as_bytes(&self) -> &[u8; 32]
@@ -373,6 +396,17 @@ pub const fn radroots_domain::ExpectedOrder::order_id(&self) -> radroots_domain:
pub const fn radroots_domain::ExpectedOrder::seller_sequence(&self) -> radroots_domain::Sequence
impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::ExpectedOrder
pub fn radroots_domain::ExpectedOrder::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error>
+pub struct radroots_domain::FixedPrice
+impl radroots_domain::FixedPrice
+pub const radroots_domain::FixedPrice::MAX_TIERS: usize
+pub const fn radroots_domain::FixedPrice::basis(&self) -> radroots_domain::PositiveDecimal
+pub const fn radroots_domain::FixedPrice::discount_bps(&self) -> radroots_domain::DiscountBps
+pub fn radroots_domain::FixedPrice::line(&self, radroots_domain::PositiveDecimal) -> core::result::Result<radroots_domain::LinePrice, radroots_domain::PricingError>
+pub fn radroots_domain::FixedPrice::new(radroots_domain::Money, radroots_domain::PositiveDecimal, radroots_domain::DiscountBps, alloc::vec::Vec<radroots_domain::PriceTier>) -> core::result::Result<Self, radroots_domain::PricingError>
+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::Generation(_)
impl radroots_domain::Generation
pub const fn radroots_domain::Generation::get(self) -> u64
@@ -406,6 +440,15 @@ pub fn radroots_domain::IssuanceWindow::capture(radroots_domain::UnixSeconds, ra
pub const fn radroots_domain::IssuanceWindow::first_issue_not_after(self) -> radroots_domain::UnixSeconds
pub fn radroots_domain::IssuanceWindow::new(radroots_domain::UnixSeconds, radroots_domain::UnixSeconds) -> core::result::Result<Self, radroots_domain::ContextError>
pub const fn radroots_domain::IssuanceWindow::prepared_at(self) -> radroots_domain::UnixSeconds
+pub struct radroots_domain::LinePrice
+impl radroots_domain::LinePrice
+pub const fn radroots_domain::LinePrice::basis(self) -> radroots_domain::PositiveDecimal
+pub const fn radroots_domain::LinePrice::discount_bps(self) -> radroots_domain::DiscountBps
+pub const fn radroots_domain::LinePrice::rate(self) -> radroots_domain::Money
+pub const fn radroots_domain::LinePrice::selected_tier_from(self) -> core::option::Option<radroots_domain::Decimal>
+pub const fn radroots_domain::LinePrice::total(self) -> radroots_domain::Money
+impl core::fmt::Debug for radroots_domain::LinePrice
+pub fn radroots_domain::LinePrice::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_domain::ListingOptionId(_)
impl radroots_domain::ListingOptionId
pub const fn radroots_domain::ListingOptionId::as_bytes(&self) -> &[u8; 32]
@@ -516,6 +559,13 @@ impl serde_core::ser::Serialize for radroots_domain::PositiveDecimal
pub fn radroots_domain::PositiveDecimal::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::PositiveDecimal
pub fn radroots_domain::PositiveDecimal::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error>
+pub struct radroots_domain::PriceTier
+impl radroots_domain::PriceTier
+pub const fn radroots_domain::PriceTier::from(self) -> radroots_domain::Decimal
+pub const fn radroots_domain::PriceTier::new(radroots_domain::Decimal, radroots_domain::Money) -> Self
+pub const fn radroots_domain::PriceTier::rate(self) -> radroots_domain::Money
+impl core::fmt::Debug for radroots_domain::PriceTier
+pub fn radroots_domain::PriceTier::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result
pub struct radroots_domain::RecordId(_)
impl radroots_domain::RecordId
pub const fn radroots_domain::RecordId::as_bytes(&self) -> &[u8; 32]
@@ -644,4 +694,7 @@ pub const radroots_domain::CHAT_MAX_BYTES: usize
pub const radroots_domain::CURRENCY_REGISTRY_ID: &str
pub const radroots_domain::CURRENCY_REGISTRY_SHA256: &str
pub const radroots_domain::FIRST_ISSUANCE_MAX_SECONDS: u64
+pub const radroots_domain::MAX_PRICED_LINES: usize
+pub const radroots_domain::PRICING_PROFILE: &str
pub const radroots_domain::SUPPORTED_CURRENCY_COUNT: usize
+pub fn radroots_domain::checked_order_total(&[radroots_domain::Money], radroots_domain::Money) -> core::result::Result<radroots_domain::Money, radroots_domain::PricingError>
diff --git a/crates/domain/README.md b/crates/domain/README.md
@@ -20,8 +20,17 @@ a guessed exponent. `MinorAmount` admits canonical integer strings up to
999999999999999. `Money` checks the explicit wire exponent against that registry
and performs checked signed 128-bit addition/subtraction within one currency.
JSON minor amounts remain strings; private monetary diagnostics are redacted.
-Pricing, rounding, complete agreement terms and command effects remain separate
-implementation requirements. Explicit zero money does not imply a price mode.
+Explicit zero money does not imply a price mode.
+
+`FixedPrice` validates at most eight strictly increasing same-currency tiers
+and one discount in basis points 0–10000. It selects the greatest applicable
+threshold, applies the discount before rounding, and rounds once per net line
+using half-even checked signed 128-bit rational arithmetic. `checked_order_total`
+sums one through 32 rounded lines and an explicit same-currency fulfillment
+charge within the money cap. The calculation uses one selected sale-unit basis
+and performs no implicit physical conversion. Complete option/terms admission,
+fixed-price listing authoring, agreement installation and command effects remain
+separate requirements; calculation values establish no authorization or stock.
Order, thread, workspace, executor and operation IDs have distinct Rust types.
Each stores 32 bytes and uses exactly 64 lowercase hexadecimal characters in
diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs
@@ -14,6 +14,7 @@ mod issuance;
pub mod listing;
mod message;
mod money;
+mod pricing;
/// The identity-owned validated participant key; no second key type is defined.
pub use radroots_identity::PublicKey;
@@ -35,3 +36,7 @@ pub use identifier::{
pub use issuance::{FIRST_ISSUANCE_MAX_SECONDS, IssuanceWindow};
pub use message::{CHAT_MAX_BYTES, ChatMessage, ChatRelation, MessageError};
pub use money::{MinorAmount, Money, MoneyError};
+pub use pricing::{
+ DiscountBps, FixedPrice, LinePrice, MAX_PRICED_LINES, PRICING_PROFILE, PriceTier, PricingError,
+ checked_order_total,
+};
diff --git a/crates/domain/src/pricing.rs b/crates/domain/src/pricing.rs
@@ -0,0 +1,305 @@
+use crate::{Decimal, MinorAmount, Money, MoneyError, PositiveDecimal};
+use alloc::{boxed::Box, vec::Vec};
+use core::fmt;
+
+/// Fixed calculation rule: discount first, half-even once per net line.
+pub const PRICING_PROFILE: &str = "half_even_net_line_v1";
+/// Largest supported number of rounded lines in one aggregate.
+pub const MAX_PRICED_LINES: usize = 32;
+
+/// Validated discount in integer basis points, without an implicit default.
+#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize))]
+#[cfg_attr(feature = "serde", serde(transparent))]
+pub struct DiscountBps(u16);
+
+impl DiscountBps {
+ /// Explicit absence of a discount.
+ pub const NONE: Self = Self(0);
+ /// Explicit full discount; the resulting price is free, not quote-required.
+ pub const FULL: Self = Self(10_000);
+
+ /// Admits exactly 0 through 10000 basis points.
+ pub const fn new(value: u16) -> Result<Self, PricingError> {
+ if value > 10_000 {
+ Err(PricingError::InvalidDiscount)
+ } else {
+ Ok(Self(value))
+ }
+ }
+
+ /// Returns the exact bounded integer basis points.
+ pub const fn get(self) -> u16 {
+ self.0
+ }
+}
+
+/// One threshold/rate pair, expressed in its enclosing price's sale-unit basis.
+#[derive(Clone, Copy, Eq, PartialEq)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize))]
+pub struct PriceTier {
+ from: Decimal,
+ rate: Money,
+}
+
+impl PriceTier {
+ /// Captures validated values; the enclosing price checks order and currency.
+ pub const fn new(from: Decimal, rate: Money) -> Self {
+ Self { from, rate }
+ }
+ /// Returns the inclusive threshold; an explicit zero threshold is valid.
+ pub const fn from(self) -> Decimal {
+ self.from
+ }
+ /// Returns the exact tier rate, without currency conversion.
+ pub const fn rate(self) -> Money {
+ self.rate
+ }
+}
+
+/// Validated fixed-price calculation inputs for one selected sale unit.
+///
+/// Amounts, basis and thresholds share that sale unit. This type performs no
+/// physical conversion, option/increment admission, agreement installation or
+/// stock operation. JSON serialization alone does not create a listing profile.
+#[derive(Clone, Eq, PartialEq)]
+#[cfg_attr(feature = "serde", derive(serde::Serialize))]
+pub struct FixedPrice {
+ rate: Money,
+ basis: PositiveDecimal,
+ discount_bps: DiscountBps,
+ tiers: Box<[PriceTier]>,
+}
+
+impl FixedPrice {
+ /// Maximum number of explicitly ordered price tiers.
+ pub const MAX_TIERS: usize = 8;
+
+ /// Checks tier count, strict threshold order and exact shared currency.
+ pub fn new(
+ rate: Money,
+ basis: PositiveDecimal,
+ discount_bps: DiscountBps,
+ tiers: Vec<PriceTier>,
+ ) -> Result<Self, PricingError> {
+ if tiers.len() > Self::MAX_TIERS {
+ return Err(PricingError::TooManyTiers);
+ }
+ let mut previous = None;
+ for tier in &tiers {
+ if tier.rate.currency() != rate.currency() {
+ return Err(MoneyError::CurrencyMismatch.into());
+ }
+ if previous.is_some_and(|value| tier.from <= value) {
+ return Err(PricingError::InvalidTierOrder);
+ }
+ previous = Some(tier.from);
+ }
+ Ok(Self {
+ rate,
+ basis,
+ discount_bps,
+ tiers: tiers.into_boxed_slice(),
+ })
+ }
+
+ /// Returns the base rate, used below the first applicable tier.
+ pub const fn rate(&self) -> Money {
+ self.rate
+ }
+ /// Returns the strictly positive common price basis.
+ pub const fn basis(&self) -> PositiveDecimal {
+ self.basis
+ }
+ /// Returns the single discount applied before line rounding.
+ pub const fn discount_bps(&self) -> DiscountBps {
+ self.discount_bps
+ }
+ /// Borrows the exact, strictly increasing tier sequence.
+ pub fn tiers(&self) -> &[PriceTier] {
+ &self.tiers
+ }
+
+ /// Resolves one tier and computes one exact discounted, half-even net line.
+ pub fn line(&self, amount: PositiveDecimal) -> Result<LinePrice, PricingError> {
+ let selected = self
+ .tiers
+ .iter()
+ .rev()
+ .find(|tier| tier.from <= amount.amount());
+ let rate = selected.map_or(self.rate, |tier| tier.rate);
+ let total = Money::new(
+ rate.currency(),
+ net_line_minor(rate.minor(), amount, self.basis, self.discount_bps)?,
+ );
+ Ok(LinePrice {
+ rate,
+ basis: self.basis,
+ discount_bps: self.discount_bps,
+ selected_tier_from: selected.map(|tier| tier.from),
+ total,
+ })
+ }
+}
+
+/// Resolved numeric calculation, without authenticated terms or installation.
+#[derive(Clone, Copy, Eq, PartialEq)]
+pub struct LinePrice {
+ rate: Money,
+ basis: PositiveDecimal,
+ discount_bps: DiscountBps,
+ selected_tier_from: Option<Decimal>,
+ total: Money,
+}
+
+impl LinePrice {
+ /// Returns the base or selected tier rate actually used.
+ pub const fn rate(self) -> Money {
+ self.rate
+ }
+ /// Returns the exact common basis used for this line.
+ pub const fn basis(self) -> PositiveDecimal {
+ self.basis
+ }
+ /// Returns the single applied discount.
+ pub const fn discount_bps(self) -> DiscountBps {
+ self.discount_bps
+ }
+ /// Returns the selected inclusive threshold, or None for the base rate.
+ pub const fn selected_tier_from(self) -> Option<Decimal> {
+ self.selected_tier_from
+ }
+ /// Returns the once-rounded minor amount within the supported money cap.
+ pub const fn total(self) -> Money {
+ self.total
+ }
+}
+
+/// Sums one through 32 already-rounded net lines and an explicit fulfillment fee.
+/// All operands must share one currency. Received totals still require the
+/// enclosing agreement's independent recomputation and admission.
+pub fn checked_order_total(
+ lines: &[Money],
+ fulfillment_charge: Money,
+) -> Result<Money, PricingError> {
+ if lines.is_empty() || lines.len() > MAX_PRICED_LINES {
+ return Err(PricingError::InvalidLineCount);
+ }
+ let mut total = fulfillment_charge;
+ for line in lines {
+ total = total.checked_add(*line)?;
+ }
+ Ok(total)
+}
+
+fn net_line_minor(
+ rate: MinorAmount,
+ amount: PositiveDecimal,
+ basis: PositiveDecimal,
+ discount: DiscountBps,
+) -> Result<MinorAmount, PricingError> {
+ let amount = amount.amount();
+ let basis = basis.amount();
+ let scale = |digits: u8| {
+ 10_i128
+ .checked_pow(u32::from(digits))
+ .ok_or(PricingError::ArithmeticOutOfRange)
+ };
+ // Validated factors bound the numerator below 10^37 and denominator below
+ // 10^22, inside signed i128. Keep every operation checked independently.
+ let basis_scale = scale(basis.scale())?;
+ let amount_scale = scale(amount.scale())?;
+ let numerator = i128::from(rate.get())
+ .checked_mul(i128::from(amount.coefficient()))
+ .and_then(|value| value.checked_mul(basis_scale))
+ .and_then(|value| value.checked_mul(i128::from(10_000 - discount.get())))
+ .ok_or(PricingError::ArithmeticOutOfRange)?;
+ let denominator = i128::from(basis.coefficient())
+ .checked_mul(amount_scale)
+ .and_then(|value| value.checked_mul(10_000))
+ .ok_or(PricingError::ArithmeticOutOfRange)?;
+ let quotient = numerator
+ .checked_div(denominator)
+ .ok_or(PricingError::ArithmeticOutOfRange)?;
+ let twice_remainder = numerator
+ .checked_rem(denominator)
+ .and_then(|value| value.checked_mul(2))
+ .ok_or(PricingError::ArithmeticOutOfRange)?;
+ let odd = quotient
+ .checked_rem(2)
+ .ok_or(PricingError::ArithmeticOutOfRange)?
+ == 1;
+ let increment = twice_remainder > denominator || (twice_remainder == denominator && odd);
+ let rounded = quotient
+ .checked_add(i128::from(increment))
+ .ok_or(PricingError::ArithmeticOutOfRange)?;
+ let rounded = u64::try_from(rounded).map_err(|_| MoneyError::MinorOutOfRange)?;
+ MinorAmount::new(rounded).map_err(Into::into)
+}
+
+/// Input-free fixed-price admission or exact-arithmetic failure.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+#[non_exhaustive]
+pub enum PricingError {
+ /// Basis points exceed the inclusive 0-10000 bound.
+ InvalidDiscount,
+ /// More than eight tiers were supplied.
+ TooManyTiers,
+ /// Thresholds are duplicate or are not strictly increasing.
+ InvalidTierOrder,
+ /// An aggregate has no lines or exceeds 32 lines.
+ InvalidLineCount,
+ /// A checked intermediate operation could not be represented.
+ ArithmeticOutOfRange,
+ /// The monetary bound or exact currency invariant was violated.
+ Money(MoneyError),
+}
+
+impl From<MoneyError> for PricingError {
+ fn from(value: MoneyError) -> Self {
+ Self::Money(value)
+ }
+}
+
+impl fmt::Display for PricingError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(match self {
+ Self::InvalidDiscount => "invalid discount basis points",
+ Self::TooManyTiers => "too many price tiers",
+ Self::InvalidTierOrder => "price thresholds must strictly increase",
+ Self::InvalidLineCount => "invalid priced line count",
+ Self::ArithmeticOutOfRange => "pricing arithmetic exceeds supported bounds",
+ Self::Money(error) => return error.fmt(f),
+ })
+ }
+}
+
+impl core::error::Error for PricingError {
+ fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
+ match self {
+ Self::Money(error) => Some(error),
+ _ => None,
+ }
+ }
+}
+
+impl fmt::Debug for DiscountBps {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("DiscountBps(<redacted>)")
+ }
+}
+impl fmt::Debug for PriceTier {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("PriceTier(<redacted>)")
+ }
+}
+impl fmt::Debug for FixedPrice {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("FixedPrice(<redacted>)")
+ }
+}
+impl fmt::Debug for LinePrice {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str("LinePrice(<redacted>)")
+ }
+}
diff --git a/crates/domain/tests/fixtures/net_line_v1.json b/crates/domain/tests/fixtures/net_line_v1.json
@@ -0,0 +1,273 @@
+{
+ "schema_version": 1,
+ "profile": "half_even_net_line_v1",
+ "provenance": {
+ "source": "Radroots synthetic fixed-price design vectors",
+ "source_sha256": "cbfe6a7ba97d1825bbaf62e82bb3a591f3d2f09f7352e2af9c433f392234a5e6",
+ "original_vectors": 10,
+ "additional_vectors": 16,
+ "expected_values": "independent Python Fraction and Decimal precision120 agreement"
+ },
+ "vectors": [
+ {
+ "id": "net-line-tie-even",
+ "rate_minor": "325",
+ "quantity": "2.5",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "812",
+ "expected_error": null,
+ "unbounded_rounded_minor": "812"
+ },
+ {
+ "id": "net-line-tie-odd",
+ "rate_minor": "327",
+ "quantity": "2.5",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "818",
+ "expected_error": null,
+ "unbounded_rounded_minor": "818"
+ },
+ {
+ "id": "half-cent-even",
+ "rate_minor": "101",
+ "quantity": "0.5",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "50",
+ "expected_error": null,
+ "unbounded_rounded_minor": "50"
+ },
+ {
+ "id": "half-cent-odd",
+ "rate_minor": "103",
+ "quantity": "0.5",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "52",
+ "expected_error": null,
+ "unbounded_rounded_minor": "52"
+ },
+ {
+ "id": "discount-before-one-round",
+ "rate_minor": "299",
+ "quantity": "3.5",
+ "basis": "1",
+ "discount_bps": 1000,
+ "expected_minor": "942",
+ "expected_error": null,
+ "unbounded_rounded_minor": "942"
+ },
+ {
+ "id": "free-is-valid",
+ "rate_minor": "0",
+ "quantity": "2",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "0",
+ "expected_error": null,
+ "unbounded_rounded_minor": "0"
+ },
+ {
+ "id": "case-price",
+ "rate_minor": "2450",
+ "quantity": "3",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "7350",
+ "expected_error": null,
+ "unbounded_rounded_minor": "7350"
+ },
+ {
+ "id": "per-100-grams",
+ "rate_minor": "175",
+ "quantity": "250",
+ "basis": "100",
+ "discount_bps": 0,
+ "expected_minor": "438",
+ "expected_error": null,
+ "unbounded_rounded_minor": "438"
+ },
+ {
+ "id": "large-exact-intermediate-beyond-js-safe",
+ "rate_minor": "999999999999999",
+ "quantity": "999999999999",
+ "basis": "999999999999",
+ "discount_bps": 0,
+ "expected_minor": "999999999999999",
+ "expected_error": null,
+ "unbounded_rounded_minor": "999999999999999"
+ },
+ {
+ "id": "full-discount",
+ "rate_minor": "999",
+ "quantity": "5",
+ "basis": "1",
+ "discount_bps": 10000,
+ "expected_minor": "0",
+ "expected_error": null,
+ "unbounded_rounded_minor": "0"
+ },
+ {
+ "id": "boundary-00",
+ "rate_minor": "1",
+ "quantity": "0.499999",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "0",
+ "expected_error": null,
+ "unbounded_rounded_minor": "0"
+ },
+ {
+ "id": "boundary-01",
+ "rate_minor": "1",
+ "quantity": "0.500001",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "1",
+ "expected_error": null,
+ "unbounded_rounded_minor": "1"
+ },
+ {
+ "id": "boundary-02",
+ "rate_minor": "1",
+ "quantity": "0.5",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "0",
+ "expected_error": null,
+ "unbounded_rounded_minor": "0"
+ },
+ {
+ "id": "boundary-03",
+ "rate_minor": "3",
+ "quantity": "0.5",
+ "basis": "1",
+ "discount_bps": 0,
+ "expected_minor": "2",
+ "expected_error": null,
+ "unbounded_rounded_minor": "2"
+ },
+ {
+ "id": "boundary-04",
+ "rate_minor": "325",
+ "quantity": "0.000001",
+ "basis": "0.000001",
+ "discount_bps": 1,
+ "expected_minor": "325",
+ "expected_error": null,
+ "unbounded_rounded_minor": "325"
+ },
+ {
+ "id": "boundary-05",
+ "rate_minor": "999999999999999",
+ "quantity": "999999999999",
+ "basis": "999999999999",
+ "discount_bps": 1,
+ "expected_minor": "999899999999999",
+ "expected_error": null,
+ "unbounded_rounded_minor": "999899999999999"
+ },
+ {
+ "id": "boundary-06",
+ "rate_minor": "999999999999999",
+ "quantity": "999999999999",
+ "basis": "0.000001",
+ "discount_bps": 0,
+ "expected_minor": null,
+ "expected_error": "minor_out_of_range",
+ "unbounded_rounded_minor": "999999999998999000000000001000000"
+ },
+ {
+ "id": "boundary-07",
+ "rate_minor": "999999999999999",
+ "quantity": "999999999999",
+ "basis": "0.000001",
+ "discount_bps": 10000,
+ "expected_minor": "0",
+ "expected_error": null,
+ "unbounded_rounded_minor": "0"
+ },
+ {
+ "id": "boundary-08",
+ "rate_minor": "999999999999999",
+ "quantity": "0.000001",
+ "basis": "999999999999",
+ "discount_bps": 0,
+ "expected_minor": "0",
+ "expected_error": null,
+ "unbounded_rounded_minor": "0"
+ },
+ {
+ "id": "boundary-09",
+ "rate_minor": "101",
+ "quantity": "1.5",
+ "basis": "0.1",
+ "discount_bps": 1000,
+ "expected_minor": "1364",
+ "expected_error": null,
+ "unbounded_rounded_minor": "1364"
+ },
+ {
+ "id": "boundary-10",
+ "rate_minor": "103",
+ "quantity": "2.5",
+ "basis": "0.1",
+ "discount_bps": 9999,
+ "expected_minor": "0",
+ "expected_error": null,
+ "unbounded_rounded_minor": "0"
+ },
+ {
+ "id": "boundary-11",
+ "rate_minor": "175",
+ "quantity": "250",
+ "basis": "100",
+ "discount_bps": 1000,
+ "expected_minor": "394",
+ "expected_error": null,
+ "unbounded_rounded_minor": "394"
+ },
+ {
+ "id": "boundary-12",
+ "rate_minor": "333",
+ "quantity": "1",
+ "basis": "3",
+ "discount_bps": 1,
+ "expected_minor": "111",
+ "expected_error": null,
+ "unbounded_rounded_minor": "111"
+ },
+ {
+ "id": "boundary-13",
+ "rate_minor": "1",
+ "quantity": "999999999999",
+ "basis": "0.000001",
+ "discount_bps": 0,
+ "expected_minor": null,
+ "expected_error": "minor_out_of_range",
+ "unbounded_rounded_minor": "999999999999000000"
+ },
+ {
+ "id": "boundary-14",
+ "rate_minor": "100",
+ "quantity": "1",
+ "basis": "0.000003",
+ "discount_bps": 0,
+ "expected_minor": "33333333",
+ "expected_error": null,
+ "unbounded_rounded_minor": "33333333"
+ },
+ {
+ "id": "boundary-15",
+ "rate_minor": "0",
+ "quantity": "999999999999",
+ "basis": "0.000001",
+ "discount_bps": 0,
+ "expected_minor": "0",
+ "expected_error": null,
+ "unbounded_rounded_minor": "0"
+ }
+ ]
+}
diff --git a/crates/domain/tests/pricing.rs b/crates/domain/tests/pricing.rs
@@ -0,0 +1,254 @@
+use radroots_domain::{
+ Decimal, DiscountBps, FixedPrice, MAX_PRICED_LINES, Money, MoneyError, PRICING_PROFILE,
+ PriceTier, PricingError, checked_order_total,
+};
+use std::error::Error;
+
+fn money(code: &str, value: &str, exponent: u8) -> Money {
+ Money::from_parts(code, value, exponent).unwrap()
+}
+fn cad(value: &str) -> Money {
+ money("CAD", value, 2)
+}
+fn price(rate: &str, basis: &str, discount: u16, tiers: Vec<PriceTier>) -> FixedPrice {
+ FixedPrice::new(
+ cad(rate),
+ basis.parse().unwrap(),
+ DiscountBps::new(discount).unwrap(),
+ tiers,
+ )
+ .unwrap()
+}
+fn tier(from: &str, rate: &str) -> PriceTier {
+ PriceTier::new(from.parse().unwrap(), cad(rate))
+}
+
+#[test]
+fn independent_fraction_decimal_and_bigint_vectors_execute_the_rust_engine() {
+ let fixture: serde_json::Value =
+ serde_json::from_str(include_str!("fixtures/net_line_v1.json")).unwrap();
+ assert_eq!(fixture["schema_version"], 1);
+ assert_eq!(fixture["profile"], PRICING_PROFILE);
+ let vectors = fixture["vectors"].as_array().unwrap();
+ assert_eq!(vectors.len(), 26);
+ for row in vectors {
+ let input = price(
+ row["rate_minor"].as_str().unwrap(),
+ row["basis"].as_str().unwrap(),
+ u16::try_from(row["discount_bps"].as_u64().unwrap()).unwrap(),
+ vec![],
+ );
+ let result = input.line(row["quantity"].as_str().unwrap().parse().unwrap());
+ if row["expected_error"].is_null() {
+ let line = result.unwrap();
+ assert_eq!(
+ line.total(),
+ cad(row["expected_minor"].as_str().unwrap()),
+ "{}",
+ row["id"]
+ );
+ assert_eq!(line.rate(), input.rate());
+ assert_eq!(line.basis(), input.basis());
+ assert_eq!(line.discount_bps(), input.discount_bps());
+ assert_eq!(line.selected_tier_from(), None);
+ } else {
+ assert_eq!(row["expected_error"], "minor_out_of_range");
+ assert_eq!(
+ result,
+ Err(PricingError::Money(MoneyError::MinorOutOfRange)),
+ "{}",
+ row["id"]
+ );
+ }
+ }
+}
+
+#[test]
+fn discounts_are_bounded_and_explicit_free_prices_are_not_quotes() {
+ for value in [0, 1, 9999, 10_000] {
+ assert_eq!(DiscountBps::new(value).unwrap().get(), value);
+ }
+ for value in [10_001, u16::MAX] {
+ assert_eq!(DiscountBps::new(value), Err(PricingError::InvalidDiscount));
+ }
+ assert_eq!(DiscountBps::NONE.get(), 0);
+ assert_eq!(DiscountBps::FULL.get(), 10_000);
+ for input in [
+ price("0", "1", 0, vec![]),
+ price("325", "1", 10_000, vec![]),
+ ] {
+ assert_eq!(input.line("1".parse().unwrap()).unwrap().total(), cad("0"));
+ }
+}
+
+#[test]
+fn one_inclusive_tier_is_selected_without_sorting_or_combining_discounts() {
+ let input = price("500", "1", 1000, vec![tier("2", "400"), tier("5", "300")]);
+ for (amount, rate, selected, total) in [
+ ("1", "500", None, "450"),
+ ("1.999999", "500", None, "900"),
+ ("2", "400", Some("2"), "720"),
+ ("4.999999", "400", Some("2"), "1800"),
+ ("5", "300", Some("5"), "1350"),
+ ("7.5", "300", Some("5"), "2025"),
+ ] {
+ let line = input.line(amount.parse().unwrap()).unwrap();
+ assert_eq!(line.rate(), cad(rate));
+ assert_eq!(
+ line.selected_tier_from(),
+ selected.map(|v| v.parse().unwrap())
+ );
+ assert_eq!(line.total(), cad(total));
+ assert_eq!(line.basis().amount(), Decimal::ONE);
+ assert_eq!(line.discount_bps().get(), 1000);
+ }
+ let explicit_zero = price("500", "1", 0, vec![tier("0", "100")]);
+ let line = explicit_zero.line("0.000001".parse().unwrap()).unwrap();
+ assert_eq!(line.selected_tier_from(), Some(Decimal::ZERO));
+ assert_eq!(line.rate(), cad("100"));
+}
+
+#[test]
+fn tier_admission_checks_numeric_order_currency_and_count_without_guessing() {
+ for tiers in [
+ vec![tier("2", "100"), tier("1", "90")],
+ vec![tier("1", "100"), tier("1", "90")],
+ vec![tier("0", "100"), tier("0", "90")],
+ ] {
+ assert_eq!(
+ FixedPrice::new(cad("200"), "1".parse().unwrap(), DiscountBps::NONE, tiers),
+ Err(PricingError::InvalidTierOrder)
+ );
+ }
+ for rate in [money("USD", "100", 2), money("JPY", "100", 0)] {
+ assert_eq!(
+ FixedPrice::new(
+ cad("200"),
+ "1".parse().unwrap(),
+ DiscountBps::NONE,
+ vec![PriceTier::new(Decimal::ONE, rate)]
+ ),
+ Err(PricingError::Money(MoneyError::CurrencyMismatch))
+ );
+ }
+ let tiers = (0..=8).map(|n| tier(&n.to_string(), "100")).collect();
+ assert_eq!(
+ FixedPrice::new(cad("200"), "1".parse().unwrap(), DiscountBps::NONE, tiers),
+ Err(PricingError::TooManyTiers)
+ );
+ assert_eq!(FixedPrice::MAX_TIERS, 8);
+ let mut tiers = Vec::with_capacity(100_000);
+ tiers.extend((0..8).map(|n| tier(&n.to_string(), "100")));
+ let input = price("200", "100", 0, tiers);
+ assert_eq!(input.tiers().len(), 8);
+ assert_eq!(input.tiers()[7].from().to_string(), "7");
+ assert_eq!(input.tiers()[7].rate(), cad("100"));
+ assert_eq!(
+ input.line("100".parse().unwrap()).unwrap().total(),
+ cad("100")
+ );
+ let across_scales = price("200", "1", 0, vec![tier("0.5", "150"), tier("2", "100")]);
+ assert_eq!(
+ across_scales.line("2".parse().unwrap()).unwrap().total(),
+ cad("200")
+ );
+}
+
+#[test]
+fn line_rounding_precedes_the_checked_aggregate_and_fulfillment_charge() {
+ let one_half = price("1", "1", 0, vec![])
+ .line("0.5".parse().unwrap())
+ .unwrap()
+ .total();
+ assert_eq!(one_half, cad("0"));
+ assert_eq!(
+ checked_order_total(&[one_half, one_half], cad("5")).unwrap(),
+ cad("5")
+ );
+ let combined = price("1", "1", 0, vec![])
+ .line("1".parse().unwrap())
+ .unwrap()
+ .total();
+ assert_eq!(combined, cad("1"));
+ assert_eq!(
+ checked_order_total(&[combined], cad("5")).unwrap(),
+ cad("6")
+ );
+ let zero = cad("0");
+ assert_eq!(
+ checked_order_total(&[], zero),
+ Err(PricingError::InvalidLineCount)
+ );
+ assert_eq!(
+ checked_order_total(&[zero; 33], zero),
+ Err(PricingError::InvalidLineCount)
+ );
+ assert_eq!(MAX_PRICED_LINES, 32);
+ assert_eq!(
+ checked_order_total(&[cad("1"); 32], cad("7")).unwrap(),
+ cad("39")
+ );
+ let maximum = cad("999999999999999");
+ assert_eq!(checked_order_total(&[maximum], zero).unwrap(), maximum);
+ assert_eq!(
+ checked_order_total(&[maximum], cad("1")),
+ Err(PricingError::Money(MoneyError::MinorOutOfRange))
+ );
+ assert_eq!(
+ checked_order_total(&[maximum, maximum], zero),
+ Err(PricingError::Money(MoneyError::MinorOutOfRange))
+ );
+ for other in [money("USD", "0", 2), money("JPY", "0", 0)] {
+ assert_eq!(
+ checked_order_total(&[zero], other),
+ Err(PricingError::Money(MoneyError::CurrencyMismatch))
+ );
+ assert_eq!(
+ checked_order_total(&[other], zero),
+ Err(PricingError::Money(MoneyError::CurrencyMismatch))
+ );
+ }
+}
+
+#[test]
+fn private_price_diagnostics_are_redacted_and_failures_are_input_free() {
+ let input = price("928174615", "1", 1234, vec![tier("3", "928174614")]);
+ let line = input.line("3".parse().unwrap()).unwrap();
+ for debug in [
+ format!("{input:?}"),
+ format!("{line:?}"),
+ format!("{:?}", input.discount_bps()),
+ format!("{:?}", input.tiers()[0]),
+ ] {
+ assert!(!debug.contains("92817461"));
+ assert!(!debug.contains("CAD"));
+ assert!(!debug.contains("1234"));
+ }
+ for error in [
+ PricingError::InvalidDiscount,
+ PricingError::TooManyTiers,
+ PricingError::InvalidTierOrder,
+ PricingError::InvalidLineCount,
+ PricingError::ArithmeticOutOfRange,
+ MoneyError::CurrencyMismatch.into(),
+ ] {
+ let text = error.to_string();
+ assert!(!text.is_empty());
+ assert!(!text.contains("92817461"));
+ assert!(!text.contains("CAD"));
+ }
+ assert!(PricingError::InvalidDiscount.source().is_none());
+ assert!(
+ PricingError::Money(MoneyError::CurrencyMismatch)
+ .source()
+ .is_some()
+ );
+}
+
+#[cfg(feature = "serde")]
+#[test]
+fn explicit_serialization_retains_exact_basis_discount_and_tier_fields() {
+ let input = price("325", "0.5", 125, vec![tier("2.5", "299")]);
+ let expected = serde_json::json!({"rate":{"currency":"CAD","minor":"325","exponent":2},"basis":"0.5","discount_bps":125,"tiers":[{"from":"2.5","rate":{"currency":"CAD","minor":"299","exponent":2}}]});
+ assert_eq!(serde_json::to_value(input).unwrap(), expected);
+}