listing.rs (22050B)
1 //! Public offer values without protocol effects or private inventory backing. 2 //! Exact economics remain separate from execution and physical backing. 3 4 use crate::{ 5 AuthorityRef, ContentMeasure, Decimal, LinePrice, ListingOptionId, PositiveDecimal, 6 PricingError, PublicKey, Sequence, Window, 7 }; 8 use alloc::{boxed::Box, string::String, vec::Vec}; 9 use core::{fmt, str::FromStr}; 10 11 mod view; 12 pub use view::{Listing, ListingText}; 13 mod reference; 14 pub use reference::{ListingCoordinate, ListingRevision}; 15 mod price; 16 pub use price::Price; 17 mod media; 18 pub use media::Media; 19 20 /// A fixed, input-free public-offer value failure. 21 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 22 #[non_exhaustive] 23 pub enum ListingError { 24 /// An identifier has the wrong width or noncanonical hexadecimal. 25 InvalidIdentifier, 26 /// A descriptive field is empty where required or exceeds its bound. 27 InvalidText, 28 /// An amount violates its increment, minimum or count unit. 29 InvalidQuantity, 30 /// Choices are missing, excessive, duplicated or lack the selected default. 31 InvalidOptions, 32 /// Fulfillment modes are empty, duplicated or excessive. 33 InvalidFulfillment, 34 /// A duration exceeds the cross-host exact integer bound. 35 InvalidDuration, 36 /// Declared publication time follows the signed revision time. 37 InvalidTime, 38 /// The requested calculation requires a fixed-price option. 39 NotFixedPrice, 40 /// Exact price calculation cannot be represented within the approved bounds. 41 Pricing(PricingError), 42 /// A media digest is not exactly64 lowercase hexadecimal digits. 43 InvalidMediaDigest, 44 /// More than eight public object references were supplied. 45 TooManyMedia, 46 } 47 impl fmt::Display for ListingError { 48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 49 f.write_str(match self { 50 Self::InvalidIdentifier => "invalid listing identifier", 51 Self::InvalidText => "invalid listing text", 52 Self::InvalidQuantity => "invalid listing quantity", 53 Self::InvalidOptions => "invalid listing options", 54 Self::InvalidFulfillment => "invalid public fulfillment", 55 Self::InvalidDuration => "invalid listing duration", 56 Self::InvalidTime => "invalid listing time", 57 Self::NotFixedPrice => "listing option has no fixed price", 58 Self::Pricing(error) => return error.fmt(f), 59 Self::InvalidMediaDigest => "invalid media digest", 60 Self::TooManyMedia => "too many public media references", 61 }) 62 } 63 } 64 impl core::error::Error for ListingError { 65 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { 66 match self { 67 Self::Pricing(error) => Some(error), 68 _ => None, 69 } 70 } 71 } 72 73 /// Stable128-bit coordinate discriminator. Generation requires host entropy; 74 /// parsing this descriptor never proves novelty, ownership or publication. 75 #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] 76 pub struct ListingId([u8; 16]); 77 impl ListingId { 78 /// Captures exact bytes supplied by the execution owner's entropy boundary. 79 pub const fn from_bytes(bytes: [u8; 16]) -> Self { 80 Self(bytes) 81 } 82 /// Borrows the original bytes. 83 pub const fn as_bytes(&self) -> &[u8; 16] { 84 &self.0 85 } 86 } 87 impl FromStr for ListingId { 88 type Err = ListingError; 89 fn from_str(value: &str) -> Result<Self, Self::Err> { 90 if value.len() != 32 { 91 return Err(ListingError::InvalidIdentifier); 92 } 93 let digit = |b| match b { 94 b'0'..=b'9' => Ok(b - b'0'), 95 b'a'..=b'f' => Ok(b - b'a' + 10), 96 _ => Err(ListingError::InvalidIdentifier), 97 }; 98 let mut bytes = [0; 16]; 99 let (pairs, _) = value.as_bytes().as_chunks::<2>(); 100 for (out, &[a, b]) in bytes.iter_mut().zip(pairs) { 101 *out = digit(a)? * 16 + digit(b)?; 102 } 103 Ok(Self(bytes)) 104 } 105 } 106 impl fmt::Display for ListingId { 107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 108 for byte in self.0 { 109 write!(f, "{byte:02x}")?; 110 } 111 Ok(()) 112 } 113 } 114 #[cfg(feature = "serde")] 115 impl serde::Serialize for ListingId { 116 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> { 117 s.collect_str(self) 118 } 119 } 120 #[cfg(feature = "serde")] 121 impl<'de> serde::Deserialize<'de> for ListingId { 122 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> { 123 struct Visitor; 124 impl serde::de::Visitor<'_> for Visitor { 125 type Value = ListingId; 126 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 127 f.write_str("32 lowercase hexadecimal characters") 128 } 129 fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { 130 value.parse().map_err(E::custom) 131 } 132 } 133 d.deserialize_str(Visitor) 134 } 135 } 136 137 /// Exact lead time, serialized as a canonical decimal string. 138 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 139 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] 140 #[cfg_attr(feature = "serde", serde(transparent))] 141 pub struct LeadSeconds(Sequence); 142 impl LeadSeconds { 143 /// Checks the shared integer range; zero means no advertised lead time. 144 pub fn new(value: u64) -> Result<Self, ListingError> { 145 Sequence::new(value) 146 .map(Self) 147 .map_err(|_| ListingError::InvalidDuration) 148 } 149 /// Returns the exact duration without conversion to a timestamp. 150 pub const fn get(self) -> u64 { 151 self.0.get() 152 } 153 } 154 155 /// Required public listing state; inactive states retain their coordinate. 156 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 157 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 158 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] 159 pub enum ListingState { 160 /// Available for new inquiries subject to current action readiness. 161 Active, 162 /// Temporarily unavailable, without a sold or completion claim. 163 Paused, 164 /// Withdrawn from new business, without cancelling existing obligations. 165 Withdrawn, 166 } 167 168 /// Explicit measurement identity; equal numbers do not imply conversion. 169 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 170 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 171 pub enum MeasurementUnit { 172 /// Grams. 173 #[cfg_attr(feature = "serde", serde(rename = "g"))] 174 Gram, 175 /// Kilograms. 176 #[cfg_attr(feature = "serde", serde(rename = "kg"))] 177 Kilogram, 178 /// Millilitres. 179 #[cfg_attr(feature = "serde", serde(rename = "mL"))] 180 Millilitre, 181 /// Litres. 182 #[cfg_attr(feature = "serde", serde(rename = "L"))] 183 Litre, 184 /// Integral individual units. 185 #[cfg_attr(feature = "serde", serde(rename = "each"))] 186 Each, 187 } 188 impl MeasurementUnit { 189 /// Exact public protocol symbol, without an implicit unit conversion. 190 pub const fn symbol(self) -> &'static str { 191 match self { 192 Self::Gram => "g", 193 Self::Kilogram => "kg", 194 Self::Millilitre => "mL", 195 Self::Litre => "L", 196 Self::Each => "each", 197 } 198 } 199 } 200 201 #[cfg(feature = "serde")] 202 impl<'de> serde::Deserialize<'de> for MeasurementUnit { 203 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 204 struct Visitor; 205 impl serde::de::Visitor<'_> for Visitor { 206 type Value = MeasurementUnit; 207 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 208 f.write_str("one exact measurement unit symbol") 209 } 210 fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<MeasurementUnit, E> { 211 match value { 212 "g" => Ok(MeasurementUnit::Gram), 213 "kg" => Ok(MeasurementUnit::Kilogram), 214 "mL" => Ok(MeasurementUnit::Millilitre), 215 "L" => Ok(MeasurementUnit::Litre), 216 "each" => Ok(MeasurementUnit::Each), 217 _ => Err(E::custom("invalid measurement unit")), 218 } 219 } 220 } 221 deserializer.deserialize_str(Visitor) 222 } 223 } 224 225 #[derive(Clone, Eq, PartialEq)] 226 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 227 #[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] 228 enum UnitKind { 229 Measured { 230 unit: MeasurementUnit, 231 }, 232 Package { 233 label: String, 234 contents: ContentMeasure, 235 }, 236 } 237 238 /// Validated sale unit. An unspecified package implies no mass/volume mapping. 239 #[derive(Clone, Eq, PartialEq)] 240 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 241 #[cfg_attr(feature = "serde", serde(transparent))] 242 pub struct SaleUnit(UnitKind); 243 impl SaleUnit { 244 /// Selects an explicit measurement unit. 245 pub const fn measured(unit: MeasurementUnit) -> Self { 246 Self(UnitKind::Measured { unit }) 247 } 248 /// Selects a labelled package without inventing its physical contents. 249 pub fn package_unspecified(label: &str) -> Result<Self, ListingError> { 250 Self::package(label, ContentMeasure::Unspecified) 251 } 252 /// Captures declared contents without inferring physical conversion or stock. 253 pub fn package(label: &str, contents: ContentMeasure) -> Result<Self, ListingError> { 254 text(label, 80, false)?; 255 Ok(Self(UnitKind::Package { 256 label: label.into(), 257 contents, 258 })) 259 } 260 /// Returns package metadata; a measured sale unit has no package contents. 261 pub const fn contents(&self) -> Option<ContentMeasure> { 262 match self.0 { 263 UnitKind::Package { contents, .. } => Some(contents), 264 UnitKind::Measured { .. } => None, 265 } 266 } 267 /// Borrows the explicit display label/symbol used by public projections. 268 pub fn label(&self) -> &str { 269 match &self.0 { 270 UnitKind::Measured { unit } => unit.symbol(), 271 UnitKind::Package { label, .. } => label, 272 } 273 } 274 /// Whether sale quantities must be integral counts. 275 pub const fn integral(&self) -> bool { 276 matches!( 277 self.0, 278 UnitKind::Package { .. } 279 | UnitKind::Measured { 280 unit: MeasurementUnit::Each 281 } 282 ) 283 } 284 } 285 impl fmt::Debug for SaleUnit { 286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 287 f.write_str("SaleUnit(<redacted>)") 288 } 289 } 290 291 /// An advertised estimate/claim, never an authoritative stock balance. 292 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 293 #[non_exhaustive] 294 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 295 #[cfg_attr(feature = "serde", serde(tag = "type", rename_all = "snake_case"))] 296 pub enum Supply { 297 /// No quantity is advertised. 298 Unknown, 299 /// The seller advertises this nonnegative quantity in the sale unit. 300 Available { 301 /// Public advertised quantity, without backing authority. 302 amount: Decimal, 303 }, 304 /// An estimate and optional declared expected window, without reservation. 305 Estimated { 306 /// Exact nonnegative estimate in the selected sale unit. 307 amount: Decimal, 308 /// Explicit absent or validated absolute expected window. 309 window: Option<Window>, 310 }, 311 } 312 313 /// Validated public product description; producer data grants no agency rights. 314 #[derive(Clone, Eq, PartialEq)] 315 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 316 pub struct Product { 317 name: String, 318 description: String, 319 producer: Option<PublicKey>, 320 origin_summary: Option<String>, 321 } 322 impl Product { 323 /// Captures explicitly public descriptive fields without hierarchy lookup. 324 pub fn new( 325 name: &str, 326 description: &str, 327 producer: Option<PublicKey>, 328 origin_summary: Option<&str>, 329 ) -> Result<Self, ListingError> { 330 text(name, 160, false)?; 331 text(description, 4096, true)?; 332 if let Some(origin) = origin_summary { 333 text(origin, 160, true)?; 334 } 335 Ok(Self { 336 name: name.into(), 337 description: description.into(), 338 producer, 339 origin_summary: origin_summary.map(String::from), 340 }) 341 } 342 /// Borrows the validated public product name. 343 pub fn name(&self) -> &str { 344 &self.name 345 } 346 } 347 impl fmt::Debug for Product { 348 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 349 f.write_str("Product(<redacted>)") 350 } 351 } 352 353 /// A validated buyer-selectable sale choice, with no private pool/lot IDs. 354 #[derive(Clone, Eq, PartialEq)] 355 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 356 pub struct ListingOption { 357 id: ListingOptionId, 358 label: String, 359 unit: SaleUnit, 360 increment: PositiveDecimal, 361 minimum: PositiveDecimal, 362 price: Price, 363 supply: Supply, 364 lead_seconds: LeadSeconds, 365 } 366 impl ListingOption { 367 /// Captures quote-required terms. Minimum is an exact multiple of increment; 368 /// count/package units and their advertised available supply are integral. 369 pub fn quote_required( 370 id: ListingOptionId, 371 label: &str, 372 unit: SaleUnit, 373 increment: PositiveDecimal, 374 minimum: PositiveDecimal, 375 supply: Supply, 376 lead_seconds: LeadSeconds, 377 ) -> Result<Self, ListingError> { 378 Self::new( 379 id, 380 label, 381 unit, 382 increment, 383 minimum, 384 Price::QuoteRequired, 385 supply, 386 lead_seconds, 387 ) 388 } 389 /// Captures complete explicit price and purchase rules without stock effects. 390 #[allow(clippy::too_many_arguments)] 391 pub fn new( 392 id: ListingOptionId, 393 label: &str, 394 unit: SaleUnit, 395 increment: PositiveDecimal, 396 minimum: PositiveDecimal, 397 price: Price, 398 supply: Supply, 399 lead_seconds: LeadSeconds, 400 ) -> Result<Self, ListingError> { 401 text(label, 120, false)?; 402 let inc = increment.amount(); 403 let min = minimum.amount(); 404 if !exact_multiple(min, inc) 405 || (unit.integral() 406 && (inc.scale() != 0 407 || min.scale() != 0 408 || matches!(supply, Supply::Available { amount } | Supply::Estimated { amount,.. } if amount.scale() != 0))) 409 { 410 return Err(ListingError::InvalidQuantity); 411 } 412 Ok(Self { 413 id, 414 label: label.into(), 415 unit, 416 increment, 417 minimum, 418 price, 419 supply, 420 lead_seconds, 421 }) 422 } 423 /// Returns the stable sale-choice identity. 424 pub const fn id(&self) -> ListingOptionId { 425 self.id 426 } 427 /// Borrows the exact sale unit. 428 pub const fn unit(&self) -> &SaleUnit { 429 &self.unit 430 } 431 /// Returns the exact positive purchase increment. 432 pub const fn increment(&self) -> PositiveDecimal { 433 self.increment 434 } 435 /// Returns the exact positive advertised minimum. 436 pub const fn minimum(&self) -> PositiveDecimal { 437 self.minimum 438 } 439 /// Returns the advertised supply claim without freshness or stock authority. 440 pub const fn supply(&self) -> Supply { 441 self.supply 442 } 443 /// Checks minimum, increment and integral count rules without claiming stock. 444 /// Advertised supply is an estimate, not an implicit quantity ceiling. 445 pub fn validate_amount(&self, amount: PositiveDecimal) -> Result<(), ListingError> { 446 let amount = amount.amount(); 447 if amount < self.minimum.amount() 448 || !exact_multiple(amount, self.increment.amount()) 449 || (self.unit.integral() && amount.scale() != 0) 450 { 451 return Err(ListingError::InvalidQuantity); 452 } 453 Ok(()) 454 } 455 /// Borrows the complete validated mode without inventing a quoted amount. 456 pub const fn price(&self) -> &Price { 457 &self.price 458 } 459 /// Admits purchase rules before selecting a tier and pricing one fixed line. 460 pub fn fixed_line(&self, amount: PositiveDecimal) -> Result<LinePrice, ListingError> { 461 self.validate_amount(amount)?; 462 match &self.price { 463 Price::Fixed(value) => value.line(amount).map_err(ListingError::Pricing), 464 Price::QuoteRequired | Price::VariableWeight(_) => Err(ListingError::NotFixedPrice), 465 } 466 } 467 /// Borrows the public default-choice description. 468 pub fn label(&self) -> &str { 469 &self.label 470 } 471 } 472 impl fmt::Debug for ListingOption { 473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 474 f.write_str("ListingOption(<redacted>)") 475 } 476 } 477 478 fn exact_multiple(value: Decimal, increment: Decimal) -> bool { 479 let scale = value.scale().max(increment.scale()); 480 let align = |amount: Decimal| { 481 i128::from(amount.coefficient()) 482 .checked_mul(10_i128.checked_pow(u32::from(scale - amount.scale()))?) 483 }; 484 align(value).and_then(|value| value.checked_rem(align(increment)?)) == Some(0) 485 } 486 487 /// Public fulfillment mode, without exact private destination or time window. 488 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 489 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 490 #[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))] 491 pub enum FulfillmentMode { 492 /// Collection by the buyer. 493 Pickup, 494 /// Delivery, subject to separately agreed private terms. 495 Delivery, 496 } 497 498 /// Bounded coarse public fulfillment; this is not an installed agreement. 499 #[derive(Clone, Eq, PartialEq)] 500 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 501 pub struct PublicFulfillment { 502 modes: Box<[FulfillmentMode]>, 503 area: String, 504 lead_seconds: LeadSeconds, 505 } 506 impl PublicFulfillment { 507 /// Captures one or two distinct modes and an explicitly public coarse area. 508 pub fn new( 509 modes: Vec<FulfillmentMode>, 510 area: &str, 511 lead_seconds: LeadSeconds, 512 ) -> Result<Self, ListingError> { 513 if modes.is_empty() || modes.len() > 2 || (modes.len() == 2 && modes[0] == modes[1]) { 514 return Err(ListingError::InvalidFulfillment); 515 } 516 text(area, 160, true)?; 517 Ok(Self { 518 modes: modes.into_boxed_slice(), 519 area: area.into(), 520 lead_seconds, 521 }) 522 } 523 /// Borrows the public coarse area; it grants no endpoint or address trust. 524 pub fn area(&self) -> &str { 525 &self.area 526 } 527 } 528 impl fmt::Debug for PublicFulfillment { 529 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 530 f.write_str("PublicFulfillment(<redacted>)") 531 } 532 } 533 534 /// Immutable public-offer terms, with complete explicit sale-option prices. 535 /// These are data, without workspace authority, signing or private backing. 536 #[derive(Clone, Eq, PartialEq)] 537 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 538 pub struct ListingTerms { 539 state: ListingState, 540 product: Product, 541 default_option: ListingOptionId, 542 options: Box<[ListingOption]>, 543 fulfillment: PublicFulfillment, 544 authority: Option<AuthorityRef>, 545 media: Box<[Media]>, 546 #[cfg_attr(feature = "serde", serde(skip))] 547 default_index: usize, 548 } 549 impl ListingTerms { 550 /// Largest number of public object references in one complete profile. 551 pub const MAX_MEDIA: usize = 8; 552 /// Checks bounded unique choices and exact default membership before capture. 553 pub fn new( 554 state: ListingState, 555 product: Product, 556 default_option: ListingOptionId, 557 options: Vec<ListingOption>, 558 fulfillment: PublicFulfillment, 559 authority: Option<AuthorityRef>, 560 media: Vec<Media>, 561 ) -> Result<Self, ListingError> { 562 if media.len() > Self::MAX_MEDIA { 563 return Err(ListingError::TooManyMedia); 564 } 565 if options.is_empty() 566 || options.len() > 16 567 || options 568 .iter() 569 .enumerate() 570 .any(|(i, o)| options[..i].iter().any(|p| p.id == o.id)) 571 { 572 return Err(ListingError::InvalidOptions); 573 } 574 let default_index = options 575 .iter() 576 .position(|o| o.id == default_option) 577 .ok_or(ListingError::InvalidOptions)?; 578 Ok(Self { 579 state, 580 product, 581 default_option, 582 options: options.into_boxed_slice(), 583 fulfillment, 584 authority, 585 media: media.into_boxed_slice(), 586 default_index, 587 }) 588 } 589 /// Returns the advertised state, without determining action readiness. 590 pub const fn state(&self) -> ListingState { 591 self.state 592 } 593 /// Borrows the exact public product snapshot without any live source proof. 594 pub const fn product(&self) -> &Product { 595 &self.product 596 } 597 /// Borrows the bounded, unique public choices. 598 pub fn options(&self) -> &[ListingOption] { 599 &self.options 600 } 601 /// Borrows the previously validated default choice without a fallback. 602 pub fn default_option(&self) -> &ListingOption { 603 // Private immutable fields and the validating constructor ensure exact 604 // membership. Returning a reference introduces no reconstructed choice. 605 &self.options[self.default_index] 606 } 607 /// Borrows the coarse public fulfillment data. 608 pub const fn fulfillment(&self) -> &PublicFulfillment { 609 &self.fulfillment 610 } 611 /// Borrows bounded declared references without fetching or verifying files. 612 pub fn media(&self) -> &[Media] { 613 &self.media 614 } 615 } 616 impl fmt::Debug for ListingTerms { 617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 618 f.write_str("ListingTerms(<redacted>)") 619 } 620 } 621 622 fn text(value: &str, maximum: usize, allow_empty: bool) -> Result<(), ListingError> { 623 if (!allow_empty && value.is_empty()) 624 || value.len() > maximum.saturating_mul(4) 625 || value.chars().count() > maximum 626 { 627 return Err(ListingError::InvalidText); 628 } 629 Ok(()) 630 }