lib

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

agreement.rs (20131B)


      1 use radroots_domain::{
      2     AgreedFixedPrice, AgreementLine, AgreementLineId, AgreementPrice, DiscountBps, EnvelopeEventId,
      3     FixedPrice, FulfillmentGroup, FulfillmentGroupId, FuturePromise, ListingOptionId, Money,
      4     MoneyError, PositiveDecimal, PriceTier, PricingError, PrivateFulfillment, PublicKey,
      5     SupplyCommitment, Terms, TermsError, TimeZoneId, UnixSeconds, VariableWeight, Window,
      6     listing::*,
      7 };
      8 
      9 pub(super) fn seller() -> PublicKey {
     10     PublicKey::from_hex("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798").unwrap()
     11 }
     12 pub(super) fn buyer() -> PublicKey {
     13     PublicKey::from_hex("c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5").unwrap()
     14 }
     15 pub(super) fn money(minor: &str) -> Money {
     16     Money::from_parts("CAD", minor, 2).unwrap()
     17 }
     18 fn source(author: PublicKey) -> ListingRevision {
     19     ListingRevision::new(
     20         ListingCoordinate::new(author, ListingId::from_bytes([1; 16])),
     21         EnvelopeEventId::from_bytes([3; 32]),
     22     )
     23 }
     24 pub(super) fn window() -> Window {
     25     Window::new(
     26         UnixSeconds::new(100).unwrap(),
     27         UnixSeconds::new(200).unwrap(),
     28         TimeZoneId::from_name("Etc/UTC").unwrap(),
     29     )
     30     .unwrap()
     31 }
     32 pub(super) fn group(id: u8) -> FulfillmentGroup {
     33     FulfillmentGroup::new(
     34         FulfillmentGroupId::from_bytes([id; 32]),
     35         PrivateFulfillment::new(
     36             FulfillmentMode::Pickup,
     37             window(),
     38             "Private destination",
     39             "Private instructions",
     40             Some("Private contact"),
     41         )
     42         .unwrap(),
     43     )
     44 }
     45 fn option() -> ListingOption {
     46     ListingOption::quote_required(
     47         ListingOptionId::from_bytes([2; 32]),
     48         "Original bunch",
     49         SaleUnit::package_unspecified("bunch").unwrap(),
     50         "1".parse().unwrap(),
     51         "1".parse().unwrap(),
     52         Supply::Estimated {
     53             amount: "0".parse().unwrap(),
     54             window: None,
     55         },
     56         LeadSeconds::new(0).unwrap(),
     57     )
     58     .unwrap()
     59 }
     60 fn agreed(minor: &str) -> AgreementPrice {
     61     AgreementPrice::Fixed(AgreedFixedPrice::new(
     62         money(minor),
     63         "1".parse().unwrap(),
     64         DiscountBps::NONE,
     65         None,
     66     ))
     67 }
     68 #[allow(clippy::too_many_arguments)]
     69 fn line_with(
     70     id: u8,
     71     source: ListingRevision,
     72     option_id: ListingOptionId,
     73     option: ListingOption,
     74     amount: &str,
     75     group: u8,
     76     label: Option<&str>,
     77     price: AgreementPrice,
     78     total: Money,
     79 ) -> Result<AgreementLine, TermsError> {
     80     AgreementLine::new(
     81         AgreementLineId::from_bytes([id; 32]),
     82         source,
     83         option_id,
     84         super::product(),
     85         option,
     86         amount.parse().unwrap(),
     87         FulfillmentGroupId::from_bytes([group; 32]),
     88         label,
     89         price,
     90         total,
     91     )
     92 }
     93 pub(super) fn line(id: u8, group: u8) -> AgreementLine {
     94     line_with(
     95         id,
     96         source(seller()),
     97         option().id(),
     98         option(),
     99         "2",
    100         group,
    101         Some("Private lot claim"),
    102         agreed("325"),
    103         money("650"),
    104     )
    105     .unwrap()
    106 }
    107 pub(super) fn terms(
    108     lines: Vec<AgreementLine>,
    109     groups: Vec<FulfillmentGroup>,
    110     fee: Money,
    111     total: Money,
    112 ) -> Result<Terms, TermsError> {
    113     Terms::new(
    114         buyer(),
    115         seller(),
    116         lines,
    117         groups,
    118         fee,
    119         total,
    120         SupplyCommitment::StockBacked,
    121     )
    122 }
    123 
    124 #[test]
    125 fn complete_negotiated_quote_terms_preserve_snapshot_and_independently_recompute_fee_and_cap() {
    126     let line = line(7, 9);
    127     assert_eq!(line.id(), AgreementLineId::from_bytes([7; 32]));
    128     assert_eq!(line.source(), source(seller()));
    129     assert_eq!(line.option_id(), option().id());
    130     assert_eq!(line.product(), &super::product());
    131     assert_eq!(line.option(), &option());
    132     assert_eq!(line.option().price(), &Price::QuoteRequired);
    133     assert_eq!(line.amount(), "2".parse::<PositiveDecimal>().unwrap());
    134     assert_eq!(
    135         line.fulfillment_group(),
    136         FulfillmentGroupId::from_bytes([9; 32])
    137     );
    138     assert_eq!(line.source_lot_label(), Some("Private lot claim"));
    139     assert_eq!(line.price(), agreed("325"));
    140     assert_eq!(line.maximum_line_total(), money("650"));
    141     let value = terms(vec![line], vec![group(9)], money("50"), money("700")).unwrap();
    142     assert_eq!(value.buyer(), buyer());
    143     assert_eq!(value.seller(), seller());
    144     assert_eq!(value.maximum_total(), money("700"));
    145     assert_eq!(value.fulfillment_charge(), money("50"));
    146     assert_eq!(value.lines().len(), 1);
    147     assert_eq!(value.fulfillment(), [group(9)]);
    148     assert_eq!(
    149         value.fulfillment()[0].id(),
    150         FulfillmentGroupId::from_bytes([9; 32])
    151     );
    152     assert_eq!(
    153         value.fulfillment()[0].terms().address(),
    154         "Private destination"
    155     );
    156     assert_eq!(value.supply(), &SupplyCommitment::StockBacked);
    157     assert_eq!(value.cancellation(), "mutual_residual_v1");
    158     assert_eq!(value.rounding(), "half_even_net_line_v1");
    159     assert_eq!(value, value.clone());
    160     assert_eq!(format!("{value:?}"), "Terms(<redacted>)");
    161     assert_eq!(
    162         format!("{:?}", value.lines()[0]),
    163         "AgreementLine(<redacted>)"
    164     );
    165     assert_eq!(
    166         format!("{:?}", value.fulfillment()[0]),
    167         "FulfillmentGroup(<redacted>)"
    168     );
    169     assert_eq!(
    170         format!("{:?}", value.supply()),
    171         "SupplyCommitment(<redacted>)"
    172     );
    173 }
    174 
    175 #[test]
    176 fn resolved_fixed_tiers_and_half_even_values_match_retained_independent_vectors_without_reselection()
    177  {
    178     let fixed = FixedPrice::new(
    179         money("325"),
    180         "1".parse().unwrap(),
    181         DiscountBps::new(1000).unwrap(),
    182         vec![PriceTier::new("2".parse().unwrap(), money("299"))],
    183     )
    184     .unwrap();
    185     let resolved = fixed.line("3.5".parse().unwrap()).unwrap();
    186     let price = AgreedFixedPrice::from_line(resolved);
    187     assert_eq!(price.rate(), money("299"));
    188     assert_eq!(price.basis(), "1".parse::<PositiveDecimal>().unwrap());
    189     assert_eq!(price.discount_bps(), DiscountBps::new(1000).unwrap());
    190     assert_eq!(price.selected_tier_from(), Some("2".parse().unwrap()));
    191     assert_eq!(price.total("3.5".parse().unwrap()).unwrap(), money("942"));
    192     assert_eq!(
    193         price.total("1".parse().unwrap()),
    194         Err(TermsError::InvalidSelectedTier)
    195     );
    196     assert_eq!(format!("{price:?}"), "AgreedFixedPrice(<redacted>)");
    197     for (rate, quantity, expected) in [
    198         ("325", "2.5", "812"),
    199         ("327", "2.5", "818"),
    200         ("0", "100", "0"),
    201     ] {
    202         let price =
    203             AgreedFixedPrice::new(money(rate), "1".parse().unwrap(), DiscountBps::NONE, None);
    204         assert_eq!(
    205             price.total(quantity.parse().unwrap()).unwrap(),
    206             money(expected)
    207         );
    208     }
    209     let full_discount = AgreedFixedPrice::new(
    210         money("325"),
    211         "1".parse().unwrap(),
    212         DiscountBps::FULL,
    213         Some("0".parse().unwrap()),
    214     );
    215     assert_eq!(
    216         full_discount.total("2".parse().unwrap()).unwrap(),
    217         money("0")
    218     );
    219     let original = ListingOption::new(
    220         option().id(),
    221         "Public fixed offering",
    222         SaleUnit::measured(MeasurementUnit::Kilogram),
    223         "0.5".parse().unwrap(),
    224         "0.5".parse().unwrap(),
    225         Price::Fixed(fixed),
    226         Supply::Unknown,
    227         LeadSeconds::new(0).unwrap(),
    228     )
    229     .unwrap();
    230     let line = line_with(
    231         1,
    232         source(seller()),
    233         original.id(),
    234         original.clone(),
    235         "3.5",
    236         1,
    237         None,
    238         AgreementPrice::Fixed(price),
    239         money("942"),
    240     )
    241     .unwrap();
    242     assert_eq!(line.option(), &original);
    243     assert_eq!(line.source_lot_label(), None);
    244     assert_eq!(
    245         terms(vec![line], vec![group(1)], money("0"), money("942"))
    246             .unwrap()
    247             .maximum_total(),
    248         money("942")
    249     );
    250 }
    251 
    252 #[test]
    253 fn variable_agreement_bounds_are_explicit_absolute_line_values_and_never_auto_scaled() {
    254     let advertised = VariableWeight::new(
    255         MeasurementUnit::Kilogram,
    256         "0.8".parse().unwrap(),
    257         "1.2".parse().unwrap(),
    258         money("325"),
    259         "1".parse().unwrap(),
    260         money("400"),
    261     )
    262     .unwrap();
    263     let original = ListingOption::new(
    264         option().id(),
    265         "Estimated bag",
    266         option().unit().clone(),
    267         "1".parse().unwrap(),
    268         "1".parse().unwrap(),
    269         Price::VariableWeight(advertised),
    270         Supply::Unknown,
    271         LeadSeconds::new(0).unwrap(),
    272     )
    273     .unwrap();
    274     let absolute = VariableWeight::new(
    275         MeasurementUnit::Kilogram,
    276         "2".parse().unwrap(),
    277         "4".parse().unwrap(),
    278         money("325"),
    279         "1".parse().unwrap(),
    280         money("1000"),
    281     )
    282     .unwrap();
    283     let line = line_with(
    284         1,
    285         source(seller()),
    286         original.id(),
    287         original.clone(),
    288         "3",
    289         1,
    290         None,
    291         AgreementPrice::VariableWeight(absolute),
    292         money("1000"),
    293     )
    294     .unwrap();
    295     assert_eq!(line.option(), &original);
    296     assert_eq!(line.price(), AgreementPrice::VariableWeight(absolute));
    297     assert_eq!(line.maximum_line_total(), money("1000"));
    298     assert_eq!(
    299         absolute
    300             .total_at(
    301                 radroots_domain::Quantity::new("3".parse().unwrap(), MeasurementUnit::Kilogram)
    302                     .unwrap()
    303             )
    304             .unwrap(),
    305         money("975")
    306     );
    307     assert_eq!(
    308         absolute.total_at(
    309             radroots_domain::Quantity::new("4".parse().unwrap(), MeasurementUnit::Kilogram)
    310                 .unwrap()
    311         ),
    312         Err(PricingError::CapExceeded)
    313     );
    314     assert_eq!(
    315         terms(vec![line], vec![group(1)], money("10"), money("1010"))
    316             .unwrap()
    317             .maximum_total(),
    318         money("1010")
    319     );
    320     assert_eq!(
    321         format!("{:?}", AgreementPrice::VariableWeight(absolute)),
    322         "AgreementPrice(<redacted>)"
    323     );
    324     assert_eq!(
    325         line_with(
    326             1,
    327             source(seller()),
    328             original.id(),
    329             original,
    330             "3",
    331             1,
    332             None,
    333             AgreementPrice::VariableWeight(absolute),
    334             money("3000")
    335         )
    336         .unwrap_err(),
    337         TermsError::TotalMismatch
    338     );
    339 }
    340 
    341 #[test]
    342 fn line_admission_refuses_snapshot_quantity_tier_text_and_claimed_total_mismatches() {
    343     assert_eq!(
    344         line_with(
    345             1,
    346             source(seller()),
    347             ListingOptionId::from_bytes([99; 32]),
    348             option(),
    349             "2",
    350             1,
    351             None,
    352             agreed("325"),
    353             money("650")
    354         )
    355         .unwrap_err(),
    356         TermsError::OptionMismatch
    357     );
    358     assert_eq!(
    359         line_with(
    360             1,
    361             source(seller()),
    362             option().id(),
    363             option(),
    364             "0.5",
    365             1,
    366             None,
    367             agreed("325"),
    368             money("0")
    369         )
    370         .unwrap_err(),
    371         TermsError::Purchase(ListingError::InvalidQuantity)
    372     );
    373     let minimum = ListingOption::quote_required(
    374         option().id(),
    375         "Even bunches",
    376         option().unit().clone(),
    377         "2".parse().unwrap(),
    378         "4".parse().unwrap(),
    379         Supply::Unknown,
    380         LeadSeconds::new(0).unwrap(),
    381     )
    382     .unwrap();
    383     for quantity in ["2", "5"] {
    384         assert_eq!(
    385             line_with(
    386                 1,
    387                 source(seller()),
    388                 minimum.id(),
    389                 minimum.clone(),
    390                 quantity,
    391                 1,
    392                 None,
    393                 agreed("0"),
    394                 money("0")
    395             )
    396             .unwrap_err(),
    397             TermsError::Purchase(ListingError::InvalidQuantity)
    398         );
    399     }
    400     for label in ["x".repeat(121), "🥕".repeat(121), "x".repeat(481)] {
    401         assert_eq!(
    402             line_with(
    403                 1,
    404                 source(seller()),
    405                 option().id(),
    406                 option(),
    407                 "2",
    408                 1,
    409                 Some(&label),
    410                 agreed("325"),
    411                 money("650")
    412             )
    413             .unwrap_err(),
    414             TermsError::InvalidText
    415         );
    416     }
    417     let label = "🥕".repeat(120);
    418     assert_eq!(
    419         line_with(
    420             1,
    421             source(seller()),
    422             option().id(),
    423             option(),
    424             "2",
    425             1,
    426             Some(&label),
    427             agreed("325"),
    428             money("650")
    429         )
    430         .unwrap()
    431         .source_lot_label(),
    432         Some(label.as_str())
    433     );
    434     assert_eq!(
    435         line_with(
    436             1,
    437             source(seller()),
    438             option().id(),
    439             option(),
    440             "2",
    441             1,
    442             Some(""),
    443             agreed("325"),
    444             money("650")
    445         )
    446         .unwrap()
    447         .source_lot_label(),
    448         Some("")
    449     );
    450     for total in [
    451         money("649"),
    452         money("651"),
    453         Money::from_parts("USD", "650", 2).unwrap(),
    454     ] {
    455         assert_eq!(
    456             line_with(
    457                 1,
    458                 source(seller()),
    459                 option().id(),
    460                 option(),
    461                 "2",
    462                 1,
    463                 None,
    464                 agreed("325"),
    465                 total
    466             )
    467             .unwrap_err(),
    468             TermsError::TotalMismatch
    469         );
    470     }
    471 }
    472 
    473 #[test]
    474 fn complete_terms_enforce_collection_identity_seller_and_group_closure_before_capture() {
    475     assert_eq!(
    476         Terms::new(
    477             seller(),
    478             seller(),
    479             vec![line(1, 1)],
    480             vec![group(1)],
    481             money("0"),
    482             money("650"),
    483             SupplyCommitment::StockBacked
    484         )
    485         .unwrap_err(),
    486         TermsError::PartiesCoincide
    487     );
    488     assert_eq!(
    489         terms(vec![], vec![group(1)], money("0"), money("0")).unwrap_err(),
    490         TermsError::InvalidLineCount
    491     );
    492     assert_eq!(
    493         terms(vec![line(1, 1); 33], vec![group(1)], money("0"), money("0")).unwrap_err(),
    494         TermsError::InvalidLineCount
    495     );
    496     assert_eq!(
    497         terms(vec![line(1, 1)], vec![], money("0"), money("650")).unwrap_err(),
    498         TermsError::InvalidFulfillmentCount
    499     );
    500     assert_eq!(
    501         terms(
    502             vec![line(1, 1)],
    503             vec![group(1); 9],
    504             money("0"),
    505             money("650")
    506         )
    507         .unwrap_err(),
    508         TermsError::InvalidFulfillmentCount
    509     );
    510     assert_eq!(
    511         terms(
    512             vec![line(1, 1); 2],
    513             vec![group(1)],
    514             money("0"),
    515             money("1300")
    516         )
    517         .unwrap_err(),
    518         TermsError::DuplicateLine
    519     );
    520     assert_eq!(
    521         terms(
    522             vec![line(1, 1)],
    523             vec![group(1); 2],
    524             money("0"),
    525             money("650")
    526         )
    527         .unwrap_err(),
    528         TermsError::DuplicateFulfillment
    529     );
    530     assert_eq!(
    531         terms(vec![line(1, 99)], vec![group(1)], money("0"), money("650")).unwrap_err(),
    532         TermsError::UnknownFulfillment
    533     );
    534     let wrong_source = line_with(
    535         1,
    536         source(buyer()),
    537         option().id(),
    538         option(),
    539         "2",
    540         1,
    541         None,
    542         agreed("325"),
    543         money("650"),
    544     )
    545     .unwrap();
    546     assert_eq!(
    547         terms(vec![wrong_source], vec![group(1)], money("0"), money("650")).unwrap_err(),
    548         TermsError::SellerMismatch
    549     );
    550     for total in [money("649"), Money::from_parts("USD", "650", 2).unwrap()] {
    551         assert_eq!(
    552             terms(vec![line(1, 1)], vec![group(1)], money("0"), total).unwrap_err(),
    553             TermsError::TotalMismatch
    554         );
    555     }
    556     assert_eq!(
    557         terms(
    558             vec![line(1, 1)],
    559             vec![group(1)],
    560             Money::from_parts("USD", "0", 2).unwrap(),
    561             money("650")
    562         )
    563         .unwrap_err(),
    564         TermsError::Pricing(PricingError::Money(MoneyError::CurrencyMismatch))
    565     );
    566 }
    567 
    568 #[test]
    569 fn maximum_collections_preserve_line_order_and_check_aggregate_money_bounds() {
    570     let mut lines = Vec::with_capacity(4096);
    571     for id in 0..32 {
    572         lines.push(line(id, (id % 8) + 1));
    573     }
    574     let mut groups = Vec::with_capacity(4096);
    575     groups.extend((1..=8).map(group));
    576     let expected = lines.clone();
    577     let value = terms(lines, groups, money("1"), money("20801")).unwrap();
    578     assert_eq!(value.lines(), expected);
    579     assert_eq!(value.fulfillment().len(), 8);
    580     let maximum = line_with(
    581         1,
    582         source(seller()),
    583         option().id(),
    584         option(),
    585         "1",
    586         1,
    587         None,
    588         agreed("999999999999999"),
    589         money("999999999999999"),
    590     )
    591     .unwrap();
    592     assert_eq!(
    593         terms(
    594             vec![maximum],
    595             vec![group(1)],
    596             money("1"),
    597             money("999999999999999")
    598         )
    599         .unwrap_err(),
    600         TermsError::Pricing(PricingError::Money(MoneyError::MinorOutOfRange))
    601     );
    602 }
    603 
    604 #[test]
    605 fn future_promise_requires_exact_bounded_risk_and_confers_no_physical_backing() {
    606     let risk = "🥕".repeat(512);
    607     let promise = FuturePromise::new(window(), &risk).unwrap();
    608     assert_eq!(promise.expected_window(), window());
    609     assert_eq!(promise.risk_disclosure(), risk);
    610     assert_eq!(promise, promise.clone());
    611     assert_eq!(format!("{promise:?}"), "FuturePromise(<redacted>)");
    612     for text in [
    613         String::new(),
    614         "x".repeat(513),
    615         "🥕".repeat(513),
    616         "x".repeat(2049),
    617     ] {
    618         assert_eq!(
    619             FuturePromise::new(window(), &text).unwrap_err(),
    620             TermsError::InvalidText
    621         );
    622     }
    623     let value = Terms::new(
    624         buyer(),
    625         seller(),
    626         vec![line(1, 1)],
    627         vec![group(1)],
    628         money("0"),
    629         money("650"),
    630         SupplyCommitment::FuturePromise(promise.clone()),
    631     )
    632     .unwrap();
    633     assert_eq!(value.supply(), &SupplyCommitment::FuturePromise(promise));
    634 }
    635 
    636 #[test]
    637 fn exact_listing_source_references_retain_full_coordinate_and_signed_revision_identity() {
    638     let reference = source(seller());
    639     assert_eq!(reference.coordinate().kind(), 30402);
    640     assert_eq!(reference.coordinate().author(), seller());
    641     assert_eq!(reference.coordinate().d(), ListingId::from_bytes([1; 16]));
    642     assert_eq!(reference.event_id(), EnvelopeEventId::from_bytes([3; 32]));
    643     assert_eq!(format!("{reference:?}"), "ListingRevision(<redacted>)");
    644     assert_eq!(
    645         format!("{:?}", reference.coordinate()),
    646         "ListingCoordinate(<redacted>)"
    647     );
    648     let published = Listing::new(
    649         reference.coordinate().d(),
    650         seller(),
    651         reference.event_id(),
    652         UnixSeconds::new(101).unwrap(),
    653         UnixSeconds::new(100).unwrap(),
    654         ListingText::new("Carrots", "Public terms", "").unwrap(),
    655         ListingTerms::new(
    656             ListingState::Active,
    657             super::product(),
    658             option().id(),
    659             vec![option()],
    660             super::fulfillment(),
    661             None,
    662             vec![],
    663         )
    664         .unwrap(),
    665     )
    666     .unwrap();
    667     assert_eq!(published.source(), reference);
    668     #[cfg(feature = "serde")]
    669     assert_eq!(
    670         serde_json::to_value(reference).unwrap(),
    671         serde_json::json!({
    672         "coordinate":{"kind":30402,"author":seller().to_string(),"d":"01".repeat(16)},
    673         "event_id":"03".repeat(32)})
    674     );
    675 }
    676 
    677 #[test]
    678 fn agreement_failures_remain_typed_bounded_and_input_free() {
    679     for error in [
    680         TermsError::PartiesCoincide,
    681         TermsError::InvalidLineCount,
    682         TermsError::InvalidFulfillmentCount,
    683         TermsError::DuplicateLine,
    684         TermsError::DuplicateFulfillment,
    685         TermsError::UnknownFulfillment,
    686         TermsError::OptionMismatch,
    687         TermsError::SellerMismatch,
    688         TermsError::InvalidText,
    689         TermsError::InvalidSelectedTier,
    690         TermsError::TotalMismatch,
    691         TermsError::Purchase(ListingError::InvalidQuantity),
    692         TermsError::Pricing(PricingError::Money(MoneyError::CurrencyMismatch)),
    693     ] {
    694         assert!(error.to_string().len() < 128);
    695         assert!(!format!("{error:?}").contains("Private"));
    696         let source = core::error::Error::source(&error);
    697         assert_eq!(
    698             source.is_some(),
    699             matches!(error, TermsError::Purchase(_) | TermsError::Pricing(_))
    700         );
    701     }
    702 }