lib

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

commit 3699beea978b6772aefdd0bbb7cd8a69cd0e08eb
parent 0b0a3cb91c41b0d72d42182f368d85e021bba877
Author: triesap <tyson@radroots.org>
Date:   Thu, 22 Oct 2026 17:23:02 +0000

listing: Admit and publish exact monetary sale options

- Connect fixed and per-sale-unit variable prices to validated purchase rules.
- Preserve declared package contents and require object-shaped listing inputs.
- Project the fixed default rate with explicit basis and shared event budgets.
- Prove native signing, installation, delivery and replay through actual reopen.

Diffstat:
Mcontracts/api_baselines/radroots_domain.txt | 13++++++++++++-
Mcrates/domain/README.md | 20+++++++++++++-------
Mcrates/domain/src/listing.rs | 99++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
Acrates/domain/src/listing/price.rs | 48++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/domain/tests/listing.rs | 2+-
Acrates/domain/tests/offering_prices.rs | 197+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/protocol/README.md | 12+++++++++++-
Mcrates/protocol/src/listing.rs | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mcrates/protocol/src/listing/input.rs | 171++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcrates/protocol/tests/public_command.rs | 287++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Acrates/radroots/tests/support/receipt_listing_economics.rs | 128+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcrates/radroots/tests/support/receipt_workflow_listing.rs | 2++
12 files changed, 981 insertions(+), 72 deletions(-)

diff --git a/contracts/api_baselines/radroots_domain.txt b/contracts/api_baselines/radroots_domain.txt @@ -12,7 +12,10 @@ pub radroots_domain::listing::ListingError::InvalidOptions pub radroots_domain::listing::ListingError::InvalidQuantity pub radroots_domain::listing::ListingError::InvalidText pub radroots_domain::listing::ListingError::InvalidTime +pub radroots_domain::listing::ListingError::NotFixedPrice +pub radroots_domain::listing::ListingError::Pricing(radroots_domain::PricingError) impl core::error::Error for radroots_domain::listing::ListingError +pub fn radroots_domain::listing::ListingError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)> impl core::fmt::Display for radroots_domain::listing::ListingError pub fn radroots_domain::listing::ListingError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub enum radroots_domain::listing::ListingState @@ -28,7 +31,11 @@ pub radroots_domain::listing::MeasurementUnit::Millilitre impl radroots_domain::listing::MeasurementUnit pub const fn radroots_domain::listing::MeasurementUnit::symbol(self) -> &'static str #[non_exhaustive] pub enum radroots_domain::listing::Price +pub radroots_domain::listing::Price::Fixed(radroots_domain::FixedPrice) pub radroots_domain::listing::Price::QuoteRequired +pub radroots_domain::listing::Price::VariableWeight(radroots_domain::VariableWeight) +impl serde_core::ser::Serialize for radroots_domain::listing::Price +pub fn radroots_domain::listing::Price::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> #[non_exhaustive] pub enum radroots_domain::listing::Supply pub radroots_domain::listing::Supply::Available pub radroots_domain::listing::Supply::Available::amount: radroots_domain::Decimal @@ -64,11 +71,13 @@ impl<'de> serde_core::de::Deserialize<'de> for radroots_domain::listing::Listing pub fn radroots_domain::listing::ListingId::deserialize<D: serde_core::de::Deserializer<'de>>(D) -> core::result::Result<Self, <D as serde_core::de::Deserializer>::Error> pub struct radroots_domain::listing::ListingOption impl radroots_domain::listing::ListingOption +pub fn radroots_domain::listing::ListingOption::fixed_line(&self, radroots_domain::PositiveDecimal) -> core::result::Result<radroots_domain::LinePrice, radroots_domain::listing::ListingError> pub const fn radroots_domain::listing::ListingOption::id(&self) -> radroots_domain::ListingOptionId pub const fn radroots_domain::listing::ListingOption::increment(&self) -> radroots_domain::PositiveDecimal pub fn radroots_domain::listing::ListingOption::label(&self) -> &str pub const fn radroots_domain::listing::ListingOption::minimum(&self) -> radroots_domain::PositiveDecimal -pub const fn radroots_domain::listing::ListingOption::price(&self) -> radroots_domain::listing::Price +pub fn radroots_domain::listing::ListingOption::new(radroots_domain::ListingOptionId, &str, radroots_domain::listing::SaleUnit, radroots_domain::PositiveDecimal, radroots_domain::PositiveDecimal, radroots_domain::listing::Price, radroots_domain::listing::Supply, radroots_domain::listing::LeadSeconds) -> core::result::Result<Self, radroots_domain::listing::ListingError> +pub const fn radroots_domain::listing::ListingOption::price(&self) -> &radroots_domain::listing::Price pub fn radroots_domain::listing::ListingOption::quote_required(radroots_domain::ListingOptionId, &str, radroots_domain::listing::SaleUnit, radroots_domain::PositiveDecimal, radroots_domain::PositiveDecimal, radroots_domain::listing::Supply, radroots_domain::listing::LeadSeconds) -> core::result::Result<Self, radroots_domain::listing::ListingError> pub const fn radroots_domain::listing::ListingOption::unit(&self) -> &radroots_domain::listing::SaleUnit pub fn radroots_domain::listing::ListingOption::validate_amount(&self, radroots_domain::PositiveDecimal) -> core::result::Result<(), radroots_domain::listing::ListingError> @@ -105,9 +114,11 @@ impl core::fmt::Debug for radroots_domain::listing::PublicFulfillment pub fn radroots_domain::listing::PublicFulfillment::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct radroots_domain::listing::SaleUnit(_) impl radroots_domain::listing::SaleUnit +pub const fn radroots_domain::listing::SaleUnit::contents(&self) -> core::option::Option<radroots_domain::ContentMeasure> pub const fn radroots_domain::listing::SaleUnit::integral(&self) -> bool pub fn radroots_domain::listing::SaleUnit::label(&self) -> &str pub const fn radroots_domain::listing::SaleUnit::measured(radroots_domain::listing::MeasurementUnit) -> Self +pub fn radroots_domain::listing::SaleUnit::package(&str, radroots_domain::ContentMeasure) -> core::result::Result<Self, radroots_domain::listing::ListingError> pub fn radroots_domain::listing::SaleUnit::package_unspecified(&str) -> core::result::Result<Self, radroots_domain::listing::ListingError> impl core::fmt::Debug for radroots_domain::listing::SaleUnit pub fn radroots_domain::listing::SaleUnit::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result diff --git a/crates/domain/README.md b/crates/domain/README.md @@ -1,7 +1,7 @@ # Radroots domain Independently implemented exact values for the shared SDK successor. This -pre-release package provides validated values and public quote-required offer +pre-release package provides validated values and public sale-option offer terms. It does not execute commands, install agreements or establish stock. `Decimal` has a nonnegative coefficient up to 999999999999 and scale 0–6. @@ -28,18 +28,20 @@ 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. +and performs no implicit physical conversion. Sale options validate purchase +rules before using this engine. Complete bilateral terms, agreement installation +and command effects remain separate requirements; calculations establish no +authorization or stock. `Quantity` uses the existing measurement identity and exact decimal bounds. Conversions between g/kg and mL/L are explicit and reject precision loss; -arithmetic requires matching units. `each` counts remain integral. Standalone +arithmetic requires matching units. `each` counts remain integral. `ContentMeasure` descriptors distinguish fixed, estimated and unspecified contents; estimates do not provide fixed conversions or stock backing. Existing sale options validate selected amounts against their minimum, increment and integral package/count rules. Advertised supply establishes no quantity ceiling -or actual availability. Complete listing/term integration remains separate. +or actual availability. Sale-unit packages retain all three content modes; +complete bilateral-term integration remains separate. `VariableWeight` retains a positive inclusive measurement range, exact rate and basis, and an explicit same-currency maximum total. Its minimum is feasible @@ -59,7 +61,11 @@ belongs to the execution owner's qualified CSPRNG boundary. and deduplicate options, retain an exact selected default, and validate positive increments/minimums without floating conversion. Package and `each` quantities remain integral; measured units imply no conversion. Quote-required prices -contain no invented zero amount or currency. Optional opaque authority and +contain no invented zero amount or currency. Fixed options retain their complete +rate/basis, discount and tiers; `fixed_line` validates the selected purchase +amount before calculating it. Variable option bounds and caps describe one +sale unit and require complete absolute agreement terms before installation. +Optional opaque authority and producer metadata establish no permission or endpoint trust. These immutable terms serialize public data explicitly and redact ordinary diagnostics. diff --git a/crates/domain/src/listing.rs b/crates/domain/src/listing.rs @@ -1,12 +1,17 @@ //! Public offer values without protocol effects or private inventory backing. -//! Quote-required choices are supported independently of monetary registries. +//! Exact economics remain separate from execution and physical backing. -use crate::{AuthorityRef, Decimal, ListingOptionId, PositiveDecimal, PublicKey, Sequence}; +use crate::{ + AuthorityRef, ContentMeasure, Decimal, LinePrice, ListingOptionId, PositiveDecimal, + PricingError, PublicKey, Sequence, +}; use alloc::{boxed::Box, string::String, vec::Vec}; use core::{fmt, str::FromStr}; mod view; pub use view::{Listing, ListingText}; +mod price; +pub use price::Price; /// A fixed, input-free public-offer value failure. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -26,6 +31,10 @@ pub enum ListingError { InvalidDuration, /// Declared publication time follows the signed revision time. InvalidTime, + /// The requested calculation requires a fixed-price option. + NotFixedPrice, + /// Exact price calculation cannot be represented within the approved bounds. + Pricing(PricingError), } impl fmt::Display for ListingError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -37,10 +46,19 @@ impl fmt::Display for ListingError { Self::InvalidFulfillment => "invalid public fulfillment", Self::InvalidDuration => "invalid listing duration", Self::InvalidTime => "invalid listing time", + Self::NotFixedPrice => "listing option has no fixed price", + Self::Pricing(error) => return error.fmt(f), }) } } -impl core::error::Error for ListingError {} +impl core::error::Error for ListingError { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + match self { + Self::Pricing(error) => Some(error), + _ => None, + } + } +} /// Stable128-bit coordinate discriminator. Generation requires host entropy; /// parsing this descriptor never proves novelty, ownership or publication. @@ -179,15 +197,9 @@ enum UnitKind { }, Package { label: String, - contents: UnspecifiedContents, + contents: ContentMeasure, }, } -#[derive(Clone, Eq, PartialEq)] -#[cfg_attr(feature = "serde", derive(serde::Serialize))] -#[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] -enum UnspecifiedContents { - Unspecified, -} /// Validated sale unit. An unspecified package implies no mass/volume mapping. #[derive(Clone, Eq, PartialEq)] @@ -201,12 +213,23 @@ impl SaleUnit { } /// Selects a labelled package without inventing its physical contents. pub fn package_unspecified(label: &str) -> Result<Self, ListingError> { + Self::package(label, ContentMeasure::Unspecified) + } + /// Captures declared contents without inferring physical conversion or stock. + pub fn package(label: &str, contents: ContentMeasure) -> Result<Self, ListingError> { text(label, 80, false)?; Ok(Self(UnitKind::Package { label: label.into(), - contents: UnspecifiedContents::Unspecified, + contents, })) } + /// Returns package metadata; a measured sale unit has no package contents. + pub const fn contents(&self) -> Option<ContentMeasure> { + match self.0 { + UnitKind::Package { contents, .. } => Some(contents), + UnitKind::Measured { .. } => None, + } + } /// Borrows the explicit display label/symbol used by public projections. pub fn label(&self) -> &str { match &self.0 { @@ -246,17 +269,6 @@ pub enum Supply { }, } -/// Supported quote-required price. Monetary modes require their validated -/// registry and exact economics before they can be represented here. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[non_exhaustive] -#[cfg_attr(feature = "serde", derive(serde::Serialize))] -#[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] -pub enum Price { - /// No zero-price, rate, currency, discount or hold is inferred. - QuoteRequired, -} - /// Validated public product description; producer data grants no agency rights. #[derive(Clone, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] @@ -297,7 +309,7 @@ impl fmt::Debug for Product { } } -/// A validated buyer-selectable quote choice, with no private pool/lot IDs. +/// A validated buyer-selectable sale choice, with no private pool/lot IDs. #[derive(Clone, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] pub struct ListingOption { @@ -322,6 +334,29 @@ impl ListingOption { supply: Supply, lead_seconds: LeadSeconds, ) -> Result<Self, ListingError> { + Self::new( + id, + label, + unit, + increment, + minimum, + Price::QuoteRequired, + supply, + lead_seconds, + ) + } + /// Captures complete explicit price and purchase rules without stock effects. + #[allow(clippy::too_many_arguments)] + pub fn new( + id: ListingOptionId, + label: &str, + unit: SaleUnit, + increment: PositiveDecimal, + minimum: PositiveDecimal, + price: Price, + supply: Supply, + lead_seconds: LeadSeconds, + ) -> Result<Self, ListingError> { text(label, 120, false)?; let inc = increment.amount(); let min = minimum.amount(); @@ -339,7 +374,7 @@ impl ListingOption { unit, increment, minimum, - price: Price::QuoteRequired, + price, supply, lead_seconds, }) @@ -372,9 +407,17 @@ impl ListingOption { } Ok(()) } - /// Returns the validated price mode, without inventing a quoted amount. - pub const fn price(&self) -> Price { - self.price + /// Borrows the complete validated mode without inventing a quoted amount. + pub const fn price(&self) -> &Price { + &self.price + } + /// Admits purchase rules before selecting a tier and pricing one fixed line. + pub fn fixed_line(&self, amount: PositiveDecimal) -> Result<LinePrice, ListingError> { + self.validate_amount(amount)?; + match &self.price { + Price::Fixed(value) => value.line(amount).map_err(ListingError::Pricing), + Price::QuoteRequired | Price::VariableWeight(_) => Err(ListingError::NotFixedPrice), + } } /// Borrows the public default-choice description. pub fn label(&self) -> &str { @@ -443,7 +486,7 @@ impl fmt::Debug for PublicFulfillment { } } -/// Immutable public-offer terms for the supported quote-required producer. +/// Immutable public-offer terms, with complete explicit sale-option prices. /// These are data, without workspace authority, signing or private backing. #[derive(Clone, Eq, PartialEq)] #[cfg_attr(feature = "serde", derive(serde::Serialize))] diff --git a/crates/domain/src/listing/price.rs b/crates/domain/src/listing/price.rs @@ -0,0 +1,48 @@ +use crate::{FixedPrice, VariableWeight}; + +/// Public sale-option economics. Variable bounds and cap describe one sale unit; +/// an agreement must explicitly resolve its complete absolute line terms. +#[derive(Clone, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub enum Price { + /// Complete fixed rate, basis, single discount and ordered tiers. + Fixed(FixedPrice), + /// An explicit request for a quote, without an invented zero or currency. + QuoteRequired, + /// Complete per-sale-unit measurement bounds, exact rate and monetary cap. + VariableWeight(VariableWeight), +} + +#[cfg(feature = "serde")] +impl serde::Serialize for Price { + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { + use serde::ser::SerializeStruct; + match self { + Self::Fixed(value) => { + let mut out = serializer.serialize_struct("Price", 5)?; + out.serialize_field("type", "fixed")?; + out.serialize_field("rate", &value.rate())?; + out.serialize_field("basis", &value.basis())?; + out.serialize_field("discount_bps", &value.discount_bps())?; + out.serialize_field("tiers", value.tiers())?; + out.end() + } + Self::QuoteRequired => { + let mut out = serializer.serialize_struct("Price", 1)?; + out.serialize_field("type", "quote_required")?; + out.end() + } + Self::VariableWeight(value) => { + let mut out = serializer.serialize_struct("Price", 7)?; + out.serialize_field("type", "variable_weight")?; + out.serialize_field("measurement_unit", &value.measurement_unit())?; + out.serialize_field("minimum_per_sale_unit", &value.minimum())?; + out.serialize_field("maximum_per_sale_unit", &value.maximum())?; + out.serialize_field("rate", &value.rate())?; + out.serialize_field("basis", &value.basis())?; + out.serialize_field("maximum_per_sale_unit_total", &value.maximum_total())?; + out.end() + } + } + } +} diff --git a/crates/domain/tests/listing.rs b/crates/domain/tests/listing.rs @@ -229,7 +229,7 @@ fn exact_increments_and_units_never_invent_fractional_packages_or_conversion() { let value = option(1, SaleUnit::measured(unit), "0.25", "0.5", "1.5").unwrap(); assert_eq!(value.unit().label(), unit.symbol()); assert!(!value.unit().integral()); - assert_eq!(value.price(), Price::QuoteRequired); + assert_eq!(value.price(), &Price::QuoteRequired); assert!(option(1, SaleUnit::measured(unit), "0.25", "0.3", "1.5").is_err()); } for unit in [ diff --git a/crates/domain/tests/offering_prices.rs b/crates/domain/tests/offering_prices.rs @@ -0,0 +1,197 @@ +use radroots_domain::{ + ContentMeasure, DiscountBps, FixedPrice, ListingOptionId, Money, PriceTier, Quantity, + VariableWeight, listing::*, +}; + +fn money(minor: &str) -> Money { + Money::from_parts("CAD", minor, 2).unwrap() +} +fn option(price: Price, unit: SaleUnit) -> ListingOption { + ListingOption::new( + ListingOptionId::from_bytes([1; 32]), + "Carrot bunch", + unit, + "1".parse().unwrap(), + "2".parse().unwrap(), + price, + Supply::Available { + amount: "0".parse().unwrap(), + }, + LeadSeconds::new(0).unwrap(), + ) + .unwrap() +} +fn fixed() -> FixedPrice { + FixedPrice::new( + money("325"), + "1".parse().unwrap(), + DiscountBps::new(1000).unwrap(), + vec![PriceTier::new("3".parse().unwrap(), money("299"))], + ) + .unwrap() +} +fn variable() -> VariableWeight { + VariableWeight::new( + MeasurementUnit::Kilogram, + "0.8".parse().unwrap(), + "1.2".parse().unwrap(), + money("325"), + "1".parse().unwrap(), + money("400"), + ) + .unwrap() +} + +#[test] +fn fixed_options_admit_purchase_rules_before_resolving_tiers_and_rounding() { + let value = option( + Price::Fixed(fixed()), + SaleUnit::package_unspecified("bunch").unwrap(), + ); + assert_eq!( + value.fixed_line("2".parse().unwrap()).unwrap().total(), + money("585") + ); + let selected = value.fixed_line("3".parse().unwrap()).unwrap(); + assert_eq!(selected.rate(), money("299")); + assert_eq!(selected.selected_tier_from().unwrap().to_string(), "3"); + assert_eq!(selected.total(), money("807")); + for amount in ["1", "2.5"] { + assert_eq!( + value.fixed_line(amount.parse().unwrap()), + Err(ListingError::InvalidQuantity) + ); + } + // Explicit advertised zero is not a purchase ceiling or physical claim. + assert_eq!( + value.fixed_line("10".parse().unwrap()).unwrap().total(), + money("2691") + ); + let free = option( + Price::Fixed( + FixedPrice::new(money("0"), "1".parse().unwrap(), DiscountBps::NONE, vec![]).unwrap(), + ), + SaleUnit::measured(MeasurementUnit::Each), + ); + assert_eq!( + free.fixed_line("2".parse().unwrap()).unwrap().total(), + money("0") + ); +} + +#[test] +fn quote_and_per_sale_unit_variable_modes_never_invent_fixed_line_totals() { + for price in [Price::QuoteRequired, Price::VariableWeight(variable())] { + let value = option(price, SaleUnit::package_unspecified("bag").unwrap()); + assert_eq!( + value.fixed_line("2".parse().unwrap()), + Err(ListingError::NotFixedPrice) + ); + assert_eq!( + value.fixed_line("1".parse().unwrap()), + Err(ListingError::InvalidQuantity) + ); + } + let value = variable(); + assert_eq!( + value + .total_at(Quantity::new("1.2".parse().unwrap(), MeasurementUnit::Kilogram).unwrap()) + .unwrap(), + money("390") + ); + // Selecting two bags does not silently double a per-sale-unit value here. + assert_eq!(value.maximum().to_string(), "1.2"); + assert_eq!(value.maximum_total(), money("400")); +} + +#[test] +fn package_content_modes_preserve_counts_and_do_not_turn_estimates_into_conversions() { + let quantity = Quantity::new("0.5".parse().unwrap(), MeasurementUnit::Kilogram).unwrap(); + for contents in [ + ContentMeasure::Fixed { quantity }, + ContentMeasure::Estimated { quantity }, + ContentMeasure::Unspecified, + ] { + let unit = SaleUnit::package("bag", contents).unwrap(); + assert_eq!(unit.contents(), Some(contents)); + assert!(unit.integral()); + assert_eq!(unit.label(), "bag"); + assert!(!format!("{unit:?}").contains("bag")); + let value = option(Price::Fixed(fixed()), unit); + assert!(value.validate_amount("2".parse().unwrap()).is_ok()); + assert_eq!( + value.validate_amount("2.5".parse().unwrap()), + Err(ListingError::InvalidQuantity) + ); + assert_eq!( + contents.fixed_quantity(), + match contents { + ContentMeasure::Fixed { quantity } => Some(quantity), + _ => None, + } + ); + } + assert_eq!( + SaleUnit::measured(MeasurementUnit::Kilogram).contents(), + None + ); + assert!(SaleUnit::package("", ContentMeasure::Unspecified).is_err()); + assert!(SaleUnit::package(&"x".repeat(81), ContentMeasure::Unspecified).is_err()); +} + +#[test] +fn failed_fixed_calculations_remain_typed_and_redacted() { + use std::error::Error; + let value = option( + Price::Fixed( + FixedPrice::new( + money("999999999999999"), + "0.000001".parse().unwrap(), + DiscountBps::NONE, + vec![], + ) + .unwrap(), + ), + SaleUnit::package_unspecified("private label").unwrap(), + ); + let error = value.fixed_line("2".parse().unwrap()).unwrap_err(); + assert!(matches!(error, ListingError::Pricing(_))); + assert!(error.source().is_some()); + assert!(ListingError::NotFixedPrice.source().is_none()); + assert!(!format!("{value:?} {error}").contains("999999999999999")); + assert!(!format!("{:?}", value.price()).contains("999999999999999")); +} + +#[cfg(feature = "serde")] +#[test] +fn all_price_and_package_modes_serialize_the_exact_closed_public_shapes() { + use serde_json::json; + let fixed = serde_json::to_value(Price::Fixed(fixed())).unwrap(); + assert_eq!( + fixed, + json!({"type":"fixed","rate":{"currency":"CAD","minor":"325","exponent":2}, + "basis":"1","discount_bps":1000,"tiers":[{"from":"3","rate":{"currency":"CAD","minor":"299","exponent":2}}]}) + ); + assert_eq!( + serde_json::to_value(Price::QuoteRequired).unwrap(), + json!({"type":"quote_required"}) + ); + assert_eq!( + serde_json::to_value(Price::VariableWeight(variable())).unwrap(), + json!({"type":"variable_weight","measurement_unit":"kg","minimum_per_sale_unit":"0.8", + "maximum_per_sale_unit":"1.2","rate":{"currency":"CAD","minor":"325","exponent":2}, + "basis":"1","maximum_per_sale_unit_total":{"currency":"CAD","minor":"400","exponent":2}}) + ); + let quantity = Quantity::new("0.5".parse().unwrap(), MeasurementUnit::Kilogram).unwrap(); + for (name, contents) in [ + ("fixed", ContentMeasure::Fixed { quantity }), + ("estimated", ContentMeasure::Estimated { quantity }), + ] { + let unit = SaleUnit::package("bag", contents).unwrap(); + assert_eq!( + serde_json::to_value(unit).unwrap(), + json!({"type":"package","label":"bag", + "contents":{"type":name,"quantity":{"amount":"0.5","unit":"kg"}}}) + ); + } +} diff --git a/crates/protocol/README.md b/crates/protocol/README.md @@ -34,7 +34,7 @@ numbers embedded in wire and schema contracts. | `nip01` (`nip01` feature) | exact bounded canonical preimages, IDs and complete-event sizes | | `intent` (`intent` feature) | exact v1 signing commitment data without execution authority | | `chat` (`chat` feature) | bounded kind-14/13 data, complete immutable signing-plan codec and observed DM route descriptors | -| `listing` (`listing` feature) | typed quote-required input and bounded kind-30402/profile-v1 preimages without command or publication authority | +| `listing` (`listing` feature) | closed sale-option inputs and bounded kind-30402/profile-v1 preimages without execution or publication authority | Versioned DTOs live below an explicit generation module. The command codec implements its fixed v1 profile without exposing automatic serialization of @@ -43,6 +43,16 @@ The crate root does not reexport individual DTOs, so consumers must name the contract version they use. +Public listing inputs retain fixed, quote-required or per-sale-unit variable +prices, with fixed/estimated/unspecified package metadata. Object fields reject +positional arrays, and the closed typed decoder rejects duplicate, missing and +unknown fields. Media and estimated supply/windows remain unsupported. +Only the fixed default contributes a three-field NIP-99 base-rate `price` tag; +the monetary summary identifies its basis, unit, discount and tier conditions. +Variable bounds/caps stay explicit in the profile and summary. No recurring +frequency field is used for units. Complete signed events retain the64KiB cap, +with at most nine tags and19 fields shared by signer and storage admission. + ## Features | Feature | Default | Effect | diff --git a/crates/protocol/src/listing.rs b/crates/protocol/src/listing.rs @@ -1,5 +1,5 @@ -//! Known public listing producer. Full monetary/media admission is separate; -//! unsupported features are never reduced to an invented quote or zero price. +//! Closed public listing producer with exact default-option price projections. +//! Unsupported media is never silently stripped or reduced to an empty value. use crate::nip01::{self, EventFields, WireError}; use alloc::{ @@ -10,7 +10,7 @@ use alloc::{ }; use core::fmt; use radroots_domain::{ - PublicKey, UnixSeconds, + Money, PublicKey, UnixSeconds, listing::{ListingId, ListingState, ListingTerms, ListingText, Price}, }; use serde::Serialize; @@ -27,10 +27,10 @@ pub use plan::PublicSigningPlan; pub const LISTING_KIND: u32 = 30402; /// Complete public event cap, including NIP-01 key, ID and signature framing. pub const LISTING_EVENT_MAX_BYTES: usize = 65_536; -/// The closed public profile emits at most eight ordered two-field tags. -pub const LISTING_TAG_MAX_COUNT: usize = 8; +/// At most eight ordinary two-field tags and one fixed-price three-field tag. +pub const LISTING_TAG_MAX_COUNT: usize = 9; /// Both key and value count toward the closed public profile's field budget. -pub const LISTING_TAG_TOTAL_ELEMENT_MAX_COUNT: usize = 16; +pub const LISTING_TAG_TOTAL_ELEMENT_MAX_COUNT: usize = 19; /// Explicit immutable public-offer input; no IDs, time or authority are inferred. #[derive(Clone, Serialize)] @@ -43,8 +43,8 @@ pub struct PublishInput { terms: ListingTerms, } impl PublishInput { - /// Captures bounded text and validated quote-required terms. The human - /// summary describes the selected default unit/basis. No price is inferred. + /// Captures bounded text and validated sale terms. Monetary event summaries + /// name the selected default's explicit rate/basis and pricing conditions. pub fn new( id: ListingId, title: &str, @@ -95,10 +95,6 @@ fn profile_value(terms: &ListingTerms) -> Result<Value, WireError> { "authority" | "default_option" | "fulfillment" | "options" | "product" | "state" ) }) - || terms - .options() - .iter() - .any(|option| !matches!(option.price(), Price::QuoteRequired)) { return Err(WireError::InvalidInput); } @@ -147,9 +143,40 @@ impl ListingEvent { ListingState::Paused => Some("Paused: unavailable"), ListingState::Withdrawn => Some("Withdrawn: unavailable"), }; + let default = input.terms.default_option(); + let description = match default.price() { + Price::Fixed(value) => format!( + "[Default: {}; base {} {} per {} {}; discount {} bps; {} tiers] {}", + default.label(), + money_amount(value.rate()), + value.rate().currency().code(), + value.basis(), + default.unit().label(), + value.discount_bps().get(), + value.tiers().len(), + input.text.summary(), + ), + Price::VariableWeight(value) => format!( + "[Default: {} {}; {}..{} {} per sale unit; {} {} per {} {}; cap {} {}] {}", + default.label(), + default.unit().label(), + value.minimum(), + value.maximum(), + value.measurement_unit().symbol(), + money_amount(value.rate()), + value.rate().currency().code(), + value.basis(), + value.measurement_unit().symbol(), + money_amount(value.maximum_total()), + value.maximum_total().currency().code(), + input.text.summary(), + ), + Price::QuoteRequired => input.text.summary().into(), + _ => return Err(WireError::InvalidInput), + }; let summary = match inactive { - Some(label) => format!("[{label}] {}", input.text.summary()), - None => input.text.summary().into(), + Some(label) => format!("[{label}] {description}"), + None => description, }; let content = match inactive { Some(label) => format!("[{label}]\n\n{}", input.text.description_markdown()), @@ -169,6 +196,13 @@ impl ListingEvent { if inactive.is_none() { tags.push(vec!["status".into(), "active".into()]); } + if let Price::Fixed(value) = default.price() { + tags.push(vec![ + "price".into(), + money_amount(value.rate()), + value.rate().currency().code().into(), + ]); + } tags.push(vec!["radroots:listing".into(), profile]); let fields = EventFields { author, @@ -202,6 +236,18 @@ impl ListingEvent { &self.id } } + +fn money_amount(value: Money) -> String { + let exponent = value.currency().exponent(); + let minor = value.minor().get(); + if exponent == 0 { + return minor.to_string(); + } + let divisor = 10_u64.pow(u32::from(exponent)); + let whole = minor / divisor; + let fraction = minor % divisor; + format!("{whole}.{fraction:0width$}", width = usize::from(exponent)) +} impl fmt::Debug for ListingEvent { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("ListingEvent(<redacted>)") diff --git a/crates/protocol/src/listing/input.rs b/crates/protocol/src/listing/input.rs @@ -4,7 +4,8 @@ use super::PublishInput; use crate::command::{CommandError, check_frame, required_nullable}; use alloc::{string::String, vec::Vec}; use radroots_domain::{ - AuthorityRef, Decimal, ListingOptionId, PositiveDecimal, PublicKey, UnixSeconds, listing::*, + AuthorityRef, ContentMeasure, Decimal, DiscountBps, FixedPrice, ListingOptionId, Money, + PositiveDecimal, PriceTier, PublicKey, Quantity, UnixSeconds, VariableWeight, listing::*, }; use serde::Deserialize; @@ -58,7 +59,7 @@ struct OptionInput { unit: Unit, increment: PositiveDecimal, minimum: PositiveDecimal, - price: Quote, + price: RawPrice, supply: RawSupply, lead_seconds: LeadSeconds, } @@ -81,15 +82,95 @@ enum Measure { #[serde(rename = "each")] Each, } +impl Measure { + fn domain(self) -> MeasurementUnit { + match self { + Self::Gram => MeasurementUnit::Gram, + Self::Kilogram => MeasurementUnit::Kilogram, + Self::Millilitre => MeasurementUnit::Millilitre, + Self::Litre => MeasurementUnit::Litre, + Self::Each => MeasurementUnit::Each, + } + } +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawQuantity { + amount: Decimal, + unit: Measure, +} +impl RawQuantity { + fn domain(self) -> Result<Quantity, CommandError> { + invalid(Quantity::new(self.amount, self.unit.domain())) + } +} #[derive(Deserialize)] #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] enum Contents { + Fixed { quantity: RawQuantity }, + Estimated { quantity: RawQuantity }, Unspecified, } #[derive(Deserialize)] #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] -enum Quote { +enum RawPrice { + Fixed { + rate: Money, + basis: PositiveDecimal, + discount_bps: u16, + tiers: Vec<RawTier>, + }, QuoteRequired, + VariableWeight { + measurement_unit: Measure, + minimum_per_sale_unit: PositiveDecimal, + maximum_per_sale_unit: PositiveDecimal, + rate: Money, + basis: PositiveDecimal, + maximum_per_sale_unit_total: Money, + }, +} +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct RawTier { + from: Decimal, + rate: Money, +} +impl RawPrice { + fn domain(self) -> Result<Price, CommandError> { + match self { + Self::QuoteRequired => Ok(Price::QuoteRequired), + Self::Fixed { + rate, + basis, + discount_bps, + tiers, + } => Ok(Price::Fixed(invalid(FixedPrice::new( + rate, + basis, + invalid(DiscountBps::new(discount_bps))?, + tiers + .into_iter() + .map(|tier| PriceTier::new(tier.from, tier.rate)) + .collect(), + ))?)), + Self::VariableWeight { + measurement_unit, + minimum_per_sale_unit, + maximum_per_sale_unit, + rate, + basis, + maximum_per_sale_unit_total, + } => Ok(Price::VariableWeight(invalid(VariableWeight::new( + measurement_unit.domain(), + minimum_per_sale_unit, + maximum_per_sale_unit, + rate, + basis, + maximum_per_sale_unit_total, + ))?)), + } + } } #[derive(Deserialize)] #[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)] @@ -111,7 +192,7 @@ enum Mode { Delivery, } -fn invalid<T>(value: Result<T, ListingError>) -> Result<T, CommandError> { +fn invalid<T, E>(value: Result<T, E>) -> Result<T, CommandError> { value.map_err(|_| CommandError::InvalidInput) } impl Input { @@ -131,26 +212,28 @@ impl Input { } let mut options = Vec::with_capacity(profile.options.len()); for option in profile.options { - let Quote::QuoteRequired = option.price; let unit = match option.unit { - Unit::Measured { unit } => SaleUnit::measured(match unit { - Measure::Gram => MeasurementUnit::Gram, - Measure::Kilogram => MeasurementUnit::Kilogram, - Measure::Millilitre => MeasurementUnit::Millilitre, - Measure::Litre => MeasurementUnit::Litre, - Measure::Each => MeasurementUnit::Each, - }), + Unit::Measured { unit } => SaleUnit::measured(unit.domain()), Unit::Package { label, contents } => { - let Contents::Unspecified = contents; - invalid(SaleUnit::package_unspecified(&label))? + let contents = match contents { + Contents::Fixed { quantity } => ContentMeasure::Fixed { + quantity: quantity.domain()?, + }, + Contents::Estimated { quantity } => ContentMeasure::Estimated { + quantity: quantity.domain()?, + }, + Contents::Unspecified => ContentMeasure::Unspecified, + }; + invalid(SaleUnit::package(&label, contents))? } }; - options.push(invalid(ListingOption::quote_required( + options.push(invalid(ListingOption::new( option.id, &option.label, unit, option.increment, option.minimum, + option.price.domain()?, match option.supply { RawSupply::Unknown => Supply::Unknown, RawSupply::Available { amount } => Supply::Available { amount }, @@ -195,7 +278,7 @@ impl Input { } } impl PublishInput { - /// Admits bounded closed quote-required input. Known unsupported features + /// Admits bounded closed sale-option input. Known unsupported features /// return an explicit refusal; they are never silently stripped or coerced. pub fn parse(raw: &[u8]) -> Result<Self, CommandError> { check_frame(raw)?; @@ -204,6 +287,7 @@ impl PublishInput { // required nulls and all nested domain constructors. let value: serde_json::Value = serde_json::from_slice(raw).map_err(|_| CommandError::InvalidInput)?; + object_shapes(&value)?; if let Some(profile) = value.get("profile") { if profile .get("profile") @@ -221,7 +305,9 @@ impl PublishInput { if option .pointer("/price/type") .and_then(serde_json::Value::as_str) - .is_some_and(|v| v != "quote_required") + .is_some_and(|v| { + !matches!(v, "quote_required" | "fixed" | "variable_weight") + }) || option .pointer("/supply/type") .and_then(serde_json::Value::as_str) @@ -229,7 +315,7 @@ impl PublishInput { || option .pointer("/unit/contents/type") .and_then(serde_json::Value::as_str) - .is_some_and(|v| v != "unspecified") + .is_some_and(|v| !matches!(v, "unspecified" | "fixed" | "estimated")) { return Err(CommandError::UnsupportedProfile); } @@ -240,3 +326,52 @@ impl PublishInput { input.validate() } } + +// Serde's derived struct decoder also accepts positional sequences. The wire +// profile requires JSON objects; this bounded structural pass never supplies +// acceptance without the independent duplicate/unknown-field-aware parser. +fn object(value: &serde_json::Value) -> Result<(), CommandError> { + if value.is_object() { + Ok(()) + } else { + Err(CommandError::InvalidInput) + } +} +fn object_shapes(value: &serde_json::Value) -> Result<(), CommandError> { + object(value)?; + let profile = &value["profile"]; + object(profile)?; + object(&profile["product"])?; + object(&profile["fulfillment"])?; + if !profile["authority"].is_null() { + object(&profile["authority"])?; + } + let options = profile["options"] + .as_array() + .ok_or(CommandError::InvalidInput)?; + if options.is_empty() || options.len() > 16 { + return Err(CommandError::LimitExceeded); + } + for option in options { + object(option)?; + object(&option["unit"])?; + object(&option["price"])?; + object(&option["supply"])?; + if let Some(contents) = option["unit"].get("contents") { + object(contents)?; + if let Some(quantity) = contents.get("quantity") { + object(quantity)?; + } + } + if let Some(tiers) = option["price"].get("tiers") { + let tiers = tiers.as_array().ok_or(CommandError::InvalidInput)?; + if tiers.len() > FixedPrice::MAX_TIERS { + return Err(CommandError::LimitExceeded); + } + for tier in tiers { + object(tier)?; + } + } + } + Ok(()) +} diff --git a/crates/protocol/tests/public_command.rs b/crates/protocol/tests/public_command.rs @@ -35,6 +35,289 @@ fn input() -> Value { } #[test] +fn listing_objects_reject_positional_arrays_at_every_struct_boundary() { + let mut accepted = Vec::new(); + for (pointer, fields) in [ + ( + "", + &[ + "id", + "title", + "summary", + "description_markdown", + "published_at", + "profile", + ][..], + ), + ( + "/profile", + &[ + "profile", + "version", + "state", + "product", + "default_option", + "options", + "fulfillment", + "authority", + "media", + ][..], + ), + ( + "/profile/product", + &["name", "description", "producer", "origin_summary"][..], + ), + ( + "/profile/options/0", + &[ + "id", + "label", + "unit", + "increment", + "minimum", + "price", + "supply", + "lead_seconds", + ][..], + ), + ( + "/profile/fulfillment", + &["modes", "area", "lead_seconds"][..], + ), + ] { + let mut value = input(); + let object = value.pointer(pointer).unwrap(); + let array = Value::Array(fields.iter().map(|key| object[*key].clone()).collect()); + *value.pointer_mut(pointer).unwrap() = array; + if PublishInput::parse(&serde_json::to_vec(&value).unwrap()).is_ok() { + accepted.push(pointer); + } + } + assert!( + accepted.is_empty(), + "object-only fields accepted arrays: {accepted:?}" + ); +} + +fn fixed_price(code: &str, minor: &str, exponent: u8) -> Value { + json!({"type":"fixed","rate":{"currency":code,"minor":minor,"exponent":exponent}, + "basis":"2","discount_bps":1000,"tiers":[]}) +} + +#[test] +fn fixed_default_projection_preserves_basis_currency_and_full_command_plan_replay() { + use radroots_protocol::{ + listing::{ListingEvent, PublicSigningPlan}, + plan::SigningReplay, + }; + for (code, minor, exponent, amount) in [ + ("JPY", "101", 0, "101"), + ("CAD", "101", 2, "1.01"), + ("KWD", "101", 3, "0.101"), + ("CLF", "101", 4, "0.0101"), + ("CAD", "0", 2, "0.00"), + ] { + let mut wire = input(); + wire["profile"]["options"][0]["price"] = fixed_price(code, minor, exponent); + wire["summary"] = json!("Carrot offering"); + wire["profile"]["options"][0]["unit"]["contents"] = + json!({"type":"fixed","quantity":{"amount":"0.5","unit":"kg"}}); + let mut cheaper = wire["profile"]["options"][0].clone(); + cheaper["id"] = json!("03".repeat(32)); + cheaper["price"]["rate"]["minor"] = json!("0"); + wire["profile"]["options"] + .as_array_mut() + .unwrap() + .push(cheaper); + let parsed = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + assert_eq!(serde_json::to_value(&parsed).unwrap(), wire); + let event = ListingEvent::new(&parsed, key(), UnixSeconds::new(101).unwrap()).unwrap(); + let fields = event.fields(); + let prices: Vec<_> = fields.tags.iter().filter(|tag| tag[0] == "price").collect(); + assert_eq!(prices.len(), 1); + assert_eq!(prices[0].as_slice(), ["price", amount, code]); + assert_eq!(fields.tags.len(), 9); + assert_eq!(fields.tags.iter().map(Vec::len).sum::<usize>(), 19); + let summary = &fields.tags.iter().find(|tag| tag[0] == "summary").unwrap()[1]; + assert!(summary.contains("per 2 bunch")); + assert!(summary.contains("discount 1000 bps")); + assert!(summary.contains("One bunch")); + let public = CapturedListingCommand::capture(context(), parsed).unwrap(); + let captured = CapturedListingCommand::parse(public.protected_wire()).unwrap(); + assert_eq!(captured.digest(), public.digest()); + assert_eq!(captured.protected_wire(), public.protected_wire()); + let plan = PublicSigningPlan::capture( + &public, + UnixSeconds::new(101).unwrap(), + &["wss://listing.fixture.example".into()], + SigningReplay::LocalReplaySafe, + ) + .unwrap(); + let restored = PublicSigningPlan::parse(&captured, plan.protected_wire()).unwrap(); + assert_eq!(restored.event().event_id(), event.event_id()); + assert_eq!(restored.protected_wire(), plan.protected_wire()); + } +} + +#[test] +fn variable_per_sale_unit_profile_preserves_all_bounds_and_estimated_contents_without_fixed_price() +{ + use radroots_protocol::listing::ListingEvent; + let mut wire = input(); + wire["profile"]["options"][0]["price"] = json!({"type":"variable_weight","measurement_unit":"kg", + "minimum_per_sale_unit":"0.8","maximum_per_sale_unit":"1.2","rate":{"currency":"CAD","minor":"325","exponent":2}, + "basis":"1","maximum_per_sale_unit_total":{"currency":"CAD","minor":"400","exponent":2}}); + wire["profile"]["options"][0]["unit"]["contents"] = + json!({"type":"estimated","quantity":{"amount":"1","unit":"kg"}}); + let parsed = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + assert_eq!(serde_json::to_value(&parsed).unwrap(), wire); + let event = ListingEvent::new(&parsed, key(), UnixSeconds::new(101).unwrap()).unwrap(); + assert!(!event.fields().tags.iter().any(|tag| tag[0] == "price")); + let summary = &event + .fields() + .tags + .iter() + .find(|tag| tag[0] == "summary") + .unwrap()[1]; + assert!(summary.contains("0.8..1.2 kg per sale unit")); + assert!(summary.contains("cap 4.00 CAD")); + assert!(summary.contains("per 1 kg")); + assert!( + parsed + .terms() + .default_option() + .unit() + .contents() + .unwrap() + .fixed_quantity() + .is_none() + ); + let public = CapturedListingCommand::capture(context(), parsed).unwrap(); + assert_eq!( + CapturedListingCommand::parse(public.protected_wire()) + .unwrap() + .digest(), + public.digest() + ); +} + +#[test] +fn monetary_profile_admission_rejects_incomplete_inconsistent_duplicate_and_array_values() { + let mut original = input(); + original["profile"]["options"][0]["price"] = fixed_price("CAD", "325", 2); + for (pointer, invalid) in [ + ( + "/profile/options/0/price", + json!({"type":"fixed","rate":{"currency":"CAD","minor":"325","exponent":2}}), + ), + ("/profile/options/0/price/basis", json!("0")), + ("/profile/options/0/price/discount_bps", json!(10001)), + ("/profile/options/0/price/rate/exponent", json!(3)), + ("/profile/options/0/price/rate/minor", json!(325)), + ("/profile/options/0/price/rate", json!(["CAD", "325", 2])), + ( + "/profile/options/0/price/tiers", + json!([["1",{"currency":"CAD","minor":"300","exponent":2}]]), + ), + ( + "/profile/options/0/price/tiers", + json!([{"from":"1","rate":{"currency":"USD","minor":"300","exponent":2}}]), + ), + ( + "/profile/options/0/unit/contents", + json!({"type":"fixed","quantity":["1","kg"]}), + ), + ( + "/profile/options/0/unit/contents", + json!({"type":"fixed","quantity":{"amount":"0.5","unit":"each"}}), + ), + ] { + let mut wire = original.clone(); + *wire.pointer_mut(pointer).unwrap() = invalid; + assert!( + PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).is_err(), + "{pointer}" + ); + } + let raw = serde_json::to_string(&original).unwrap(); + for (needle, duplicate) in [ + ("\"basis\":\"2\"", "\"basis\":\"2\",\"basis\":\"2\""), + ("\"minor\":\"325\"", "\"minor\":\"325\",\"minor\":\"325\""), + ] { + let changed = raw.replacen(needle, duplicate, 1); + assert_ne!(changed, raw); + assert!(PublishInput::parse(changed.as_bytes()).is_err()); + } + let mut extra = original.clone(); + extra["profile"]["options"][0]["price"]["unapproved"] = json!(true); + assert!(PublishInput::parse(&serde_json::to_vec(&extra).unwrap()).is_err()); +} + +#[test] +fn variable_wire_terms_refuse_inverted_ranges_infeasible_caps_and_currency_changes() { + let mut original = input(); + original["profile"]["options"][0]["price"] = json!({"type":"variable_weight","measurement_unit":"kg", + "minimum_per_sale_unit":"0.8","maximum_per_sale_unit":"1.2","rate":{"currency":"CAD","minor":"325","exponent":2}, + "basis":"1","maximum_per_sale_unit_total":{"currency":"CAD","minor":"400","exponent":2}}); + for (pointer, bad) in [ + ( + "/profile/options/0/price/minimum_per_sale_unit", + json!("1.3"), + ), + ("/profile/options/0/price/maximum_per_sale_unit", json!("0")), + ("/profile/options/0/price/basis", json!("0")), + ("/profile/options/0/price/measurement_unit", json!("each")), + ( + "/profile/options/0/price/maximum_per_sale_unit_total/minor", + json!("259"), + ), + ( + "/profile/options/0/price/maximum_per_sale_unit_total/currency", + json!("USD"), + ), + ] { + let mut wire = original.clone(); + *wire.pointer_mut(pointer).unwrap() = bad; + assert_eq!( + PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap_err(), + CommandError::InvalidInput + ); + } + let mut extra = original; + extra["profile"]["options"][0]["price"]["discount_bps"] = json!(0); + assert!(PublishInput::parse(&serde_json::to_vec(&extra).unwrap()).is_err()); +} + +#[test] +fn monetary_listing_limits_include_projection_profile_and_complete_signed_framing() { + use radroots_protocol::{ + listing::{LISTING_EVENT_MAX_BYTES, ListingEvent}, + nip01::{self, WireError}, + }; + let mut wire = input(); + wire["description_markdown"] = json!(""); + wire["profile"]["options"][0]["price"] = fixed_price("CAD", "325", 2); + let make = |wire: &Value| PublishInput::parse(&serde_json::to_vec(wire).unwrap()).unwrap(); + let base = ListingEvent::new(&make(&wire), key(), UnixSeconds::new(101).unwrap()).unwrap(); + let free = LISTING_EVENT_MAX_BYTES + - nip01::signed_json_len(&base.fields(), LISTING_EVENT_MAX_BYTES).unwrap(); + let body = "\u{0001}".repeat(free / 6) + &"a".repeat(free % 6); + assert!(body.chars().count() <= 16_384); + wire["description_markdown"] = json!(body); + let exact = ListingEvent::new(&make(&wire), key(), UnixSeconds::new(101).unwrap()).unwrap(); + assert_eq!( + nip01::signed_json_len(&exact.fields(), LISTING_EVENT_MAX_BYTES).unwrap(), + LISTING_EVENT_MAX_BYTES + ); + let larger = wire["description_markdown"].as_str().unwrap().to_owned() + "a"; + wire["description_markdown"] = json!(larger); + assert!(matches!( + ListingEvent::new(&make(&wire), key(), UnixSeconds::new(101).unwrap()), + Err(WireError::LimitExceeded) + )); +} + +#[test] fn both_families_round_trip_without_rehashing_or_fabricating_chat_data() { let chat = CapturedChatCommand::inquire( context(), @@ -162,7 +445,7 @@ fn unsupported_full_profile_features_are_refused_without_silent_quote_or_media_f ), ( "/profile/options/0/price", - json!({"type":"fixed","rate":{"currency":"CAD","minor":"325","exponent":2}}), + json!({"type":"future_price","rate":{"currency":"CAD","minor":"325","exponent":2}}), ), ( "/profile/options/0/supply", @@ -170,7 +453,7 @@ fn unsupported_full_profile_features_are_refused_without_silent_quote_or_media_f ), ( "/profile/options/0/unit/contents", - json!({"type":"fixed","quantity":{"amount":"1","unit":"kg"}}), + json!({"type":"future_contents","quantity":{"amount":"1","unit":"kg"}}), ), ] { let mut value = input(); diff --git a/crates/radroots/tests/support/receipt_listing_economics.rs b/crates/radroots/tests/support/receipt_listing_economics.rs @@ -0,0 +1,128 @@ +use super::*; + +#[tokio::test] +async fn monetary_listings_sign_install_deliver_and_reopen_without_repricing_or_new_issuance() { + let mut relay = Relay::new().await; + let ready = Ready::new(&relay, StartMode::Online, PublicSigner::new(), true).await; + let mut expected = Vec::new(); + for (id, price, contents, expected_price) in [ + ( + 240, + json!({"type":"fixed","rate":{"currency":"CAD","minor":"325","exponent":2}, + "basis":"2","discount_bps":1000,"tiers":[{"from":"10","rate":{"currency":"CAD","minor":"299","exponent":2}}]}), + json!({"type":"fixed","quantity":{"amount":"0.5","unit":"kg"}}), + Some("3.25"), + ), + ( + 241, + json!({"type":"variable_weight","measurement_unit":"kg","minimum_per_sale_unit":"0.8", + "maximum_per_sale_unit":"1.2","rate":{"currency":"CAD","minor":"325","exponent":2}, + "basis":"1","maximum_per_sale_unit_total":{"currency":"CAD","minor":"400","exponent":2}}), + json!({"type":"estimated","quantity":{"amount":"1","unit":"kg"}}), + None, + ), + ] { + let mut wire = serde_json::to_value(input(id)).unwrap(); + wire["summary"] = json!("Native carrot offering"); + wire["profile"]["options"][0]["price"] = price; + wire["profile"]["options"][0]["unit"]["contents"] = contents; + let captured = PublishInput::parse(&serde_json::to_vec(&wire).unwrap()).unwrap(); + let deadline = now() + 120; + let receipt = ready + .client + .listings() + .publish(ready.context(id, deadline), captured.clone()) + .await + .unwrap(); + assert_eq!( + receipt.business_installation(), + BusinessInstallation::Installed + ); + assert_eq!(receipt.issuance(), Issuance::Obtained); + assert_eq!(receipt.delivery(), Delivery::Observed); + let listing = receipt.business_result().unwrap().clone(); + assert_eq!(listing.terms(), captured.terms()); + let raw = tokio::time::timeout(Duration::from_secs(5), relay.events.recv()) + .await + .unwrap() + .unwrap(); + let independent = nostr::Event::from_json(&raw).unwrap(); + independent.verify().unwrap(); + assert_eq!(independent.kind.as_u16(), 30402); + assert_eq!(independent.id.as_bytes(), listing.revision().as_bytes()); + let prices: Vec<_> = independent + .tags + .iter() + .filter(|tag| tag.as_slice()[0] == "price") + .collect(); + match expected_price { + Some(amount) => { + assert_eq!(prices.len(), 1); + assert_eq!(prices[0].as_slice(), ["price", amount, "CAD"]); + assert_eq!(independent.tags.len(), 9); + } + None => assert!(prices.is_empty()), + } + let profile_tag = independent + .tags + .iter() + .find(|tag| tag.as_slice()[0] == "radroots:listing") + .unwrap(); + let actual: serde_json::Value = serde_json::from_str(&profile_tag.as_slice()[1]).unwrap(); + assert_eq!(actual, wire["profile"]); + let replay = ready + .client + .listings() + .publish(ready.context(id, deadline), captured) + .await + .unwrap(); + assert_eq!( + replay.operation_checkpoint(), + receipt.operation_checkpoint() + ); + expected.push(( + id, + listing, + receipt.command_digest(), + receipt.operation_checkpoint(), + )); + } + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 2); + assert_eq!(ready.signer.private_calls.load(Ordering::SeqCst), 0); + assert_eq!(relay.count.load(Ordering::SeqCst), 2); + ready.client.close().await.unwrap(); + let store = ready.fixture.reopen(ready.input.clone()).await; + let (client, scope) = open( + &ready.fixture, + &store, + &relay, + "cache-monetary-reopen", + ready.signer.clone(), + (&ready.input, &ready.proof), + StartMode::Online, + ) + .await; + for (id, listing, digest, checkpoint) in expected { + let retained = client + .operations(&scope) + .get(OperationId::from_bytes([id; 32])) + .await + .unwrap() + .unwrap(); + assert_eq!( + retained.business_result().unwrap().as_listing().unwrap(), + &listing + ); + assert_eq!(retained.operation_checkpoint(), checkpoint); + let resumed = client + .operations(&scope) + .resume(OperationId::from_bytes([id; 32]), Some(digest)) + .await + .unwrap(); + assert_eq!(resumed.operation_checkpoint(), checkpoint); + } + assert_eq!(ready.signer.calls.load(Ordering::SeqCst), 2); + assert_eq!(relay.count.load(Ordering::SeqCst), 2); + client.close().await.unwrap(); + stop(relay).await; +} diff --git a/crates/radroots/tests/support/receipt_workflow_listing.rs b/crates/radroots/tests/support/receipt_workflow_listing.rs @@ -1,4 +1,6 @@ //! Ordinary public commands with a signing-only provider and measured relay reads. +#[path = "receipt_listing_economics.rs"] +mod economics; #[path = "receipt_public_snapshots.rs"] mod snapshots;