allocation.rs (13595B)
1 //! Portable complete stock-allocation proposals. These are unauthenticated 2 //! values; only a qualified executor can acquire actual stock in a transaction. 3 use super::{OptionMappingKey, OptionPoolMapping, PoolSnapshot, StockTicks}; 4 use crate::{AgreementLineId, AgreementPrice, PoolId, Quantity, Sequence, SupplyCommitment, Terms}; 5 use alloc::{collections::BTreeMap, vec, vec::Vec}; 6 use core::fmt; 7 8 /// A positive seller allocation claim before current pool/version validation. 9 #[derive(Clone, Copy, Eq, PartialEq)] 10 pub struct AllocationClaim { 11 line: AgreementLineId, 12 pool: PoolId, 13 quantity: Quantity, 14 expected: Sequence, 15 } 16 impl AllocationClaim { 17 /// Captures data only; no participant, mapping or stock is authenticated. 18 pub fn new( 19 line: AgreementLineId, 20 pool: PoolId, 21 quantity: Quantity, 22 expected: Sequence, 23 ) -> Result<Self, AllocationPlanError> { 24 if quantity.amount().is_zero() || expected.get() == 0 { 25 return Err(AllocationPlanError::InvalidInput); 26 } 27 Ok(Self { 28 line, 29 pool, 30 quantity, 31 expected, 32 }) 33 } 34 /// Exact claimed agreement line. 35 pub const fn line_id(self) -> AgreementLineId { 36 self.line 37 } 38 /// Exact claimed private pool. 39 pub const fn pool_id(self) -> PoolId { 40 self.pool 41 } 42 /// Explicit positive quantity with its declared unit. 43 pub const fn quantity(self) -> Quantity { 44 self.quantity 45 } 46 /// Positive expected current pool version. 47 pub const fn expected_pool_version(self) -> Sequence { 48 self.expected 49 } 50 } 51 /// Exact positive proposed line/pool draw, without a store hold or consent. 52 #[derive(Clone, Copy, Eq, PartialEq)] 53 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 54 pub struct StockAllocation { 55 line: AgreementLineId, 56 pool: PoolId, 57 ticks: StockTicks, 58 } 59 impl StockAllocation { 60 /// Captures only a positive proposed draw. Execution is always separate. 61 pub fn new( 62 line: AgreementLineId, 63 pool: PoolId, 64 ticks: StockTicks, 65 ) -> Result<Self, AllocationPlanError> { 66 if ticks == StockTicks::ZERO { 67 return Err(AllocationPlanError::InvalidInput); 68 } 69 Ok(Self { line, pool, ticks }) 70 } 71 /// Exact proposed line identity. 72 pub const fn line_id(self) -> AgreementLineId { 73 self.line 74 } 75 /// Exact proposed private pool identity. 76 pub const fn pool_id(self) -> PoolId { 77 self.pool 78 } 79 /// Exact positive pool ticks to acquire. 80 pub const fn ticks(self) -> StockTicks { 81 self.ticks 82 } 83 } 84 /// Conservation-checked before/after data; construction never acquires stock. 85 #[derive(Clone, Copy, Eq, PartialEq)] 86 #[cfg_attr(feature = "serde", derive(serde::Serialize))] 87 pub struct PoolHoldProposal { 88 before: PoolSnapshot, 89 after: PoolSnapshot, 90 quantity: StockTicks, 91 } 92 impl PoolHoldProposal { 93 /// Proposes available-to-preparatory transfer and one positive version step. 94 pub fn new(before: PoolSnapshot, quantity: StockTicks) -> Result<Self, AllocationPlanError> { 95 if before.version().get() == 0 || quantity == StockTicks::ZERO { 96 return Err(AllocationPlanError::InvalidInput); 97 } 98 let balances = before 99 .balances() 100 .hold_available(quantity) 101 .map_err(|_| AllocationPlanError::StaleState)?; 102 let version = Sequence::new( 103 before 104 .version() 105 .get() 106 .checked_add(1) 107 .ok_or(AllocationPlanError::Capacity)?, 108 ) 109 .map_err(|_| AllocationPlanError::Capacity)?; 110 Ok(Self { 111 before, 112 after: PoolSnapshot::new(before.id(), before.unit(), balances, version), 113 quantity, 114 }) 115 } 116 /// Exact observed data claim before the proposed transfer. 117 pub const fn before(self) -> PoolSnapshot { 118 self.before 119 } 120 /// Exact proposed after-image, not a confirmed database state. 121 pub const fn after(self) -> PoolSnapshot { 122 self.after 123 } 124 /// Positive quantity proposed for preparatory backing. 125 pub const fn quantity(self) -> StockTicks { 126 self.quantity 127 } 128 } 129 /// Input-free complete-allocation failure; no source or private values retained. 130 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 131 #[non_exhaustive] 132 pub enum AllocationPlanError { 133 /// Missing, ambiguous, incompatible, inexact or incomplete allocation data. 134 InvalidInput, 135 /// A supplied current version/unit or available quantity cannot support it. 136 StaleState, 137 /// A future supply or price profile is not supported. 138 Unsupported, 139 /// Exact quantity, aggregate, collection or version capacity is exceeded. 140 Capacity, 141 } 142 impl fmt::Display for AllocationPlanError { 143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 144 f.write_str(match self { 145 Self::InvalidInput => "invalid complete allocation", 146 Self::StaleState => "allocation state differs", 147 Self::Unsupported => "unsupported allocation profile", 148 Self::Capacity => "allocation capacity exceeded", 149 }) 150 } 151 } 152 impl core::error::Error for AllocationPlanError {} 153 macro_rules! redacted { ($($name:ident),+) => { $(impl fmt::Debug for $name { fn fmt(&self,f:&mut fmt::Formatter<'_>)->fmt::Result { f.write_str(concat!(stringify!($name),"(<private proposal>)")) } })+ }; } 154 redacted!(AllocationClaim, StockAllocation, PoolHoldProposal); 155 156 #[cfg(feature = "serde")] 157 mod serialization { 158 use super::*; 159 use serde::Deserialize; 160 impl<'de> Deserialize<'de> for StockAllocation { 161 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 162 #[derive(Deserialize)] 163 #[serde(deny_unknown_fields)] 164 struct Wire { 165 line: AgreementLineId, 166 pool: PoolId, 167 ticks: StockTicks, 168 } 169 let wire: Wire = super::super::serialization::object(deserializer)?; 170 Self::new(wire.line, wire.pool, wire.ticks).map_err(serde::de::Error::custom) 171 } 172 } 173 impl<'de> Deserialize<'de> for PoolHoldProposal { 174 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { 175 #[derive(Deserialize)] 176 #[serde(deny_unknown_fields)] 177 struct Wire { 178 before: PoolSnapshot, 179 after: PoolSnapshot, 180 quantity: StockTicks, 181 } 182 let wire: Wire = super::super::serialization::object(deserializer)?; 183 let value = Self::new(wire.before, wire.quantity).map_err(serde::de::Error::custom)?; 184 if value.after != wire.after { 185 return Err(serde::de::Error::custom("pool hold proposal differs")); 186 } 187 Ok(value) 188 } 189 } 190 } 191 192 /// Resolves complete deterministic allocation data with checked exact units and 193 /// versioned before/after proposals. `None` selects current mappings; `Some` 194 /// requires one through64 distinct positive line/pool claims with complete line 195 /// coverage. At most96 distinct pool observations are accepted. Only explicit 196 /// future-promise terms allow no physical draws. This function performs no IO, 197 /// authenticates no source/grant/version and acquires no stock. 198 pub fn plan_allocations( 199 terms: &Terms, 200 mappings: &[OptionPoolMapping], 201 pools: &[PoolSnapshot], 202 explicit: Option<&[AllocationClaim]>, 203 ) -> Result<(Vec<StockAllocation>, Vec<PoolHoldProposal>), AllocationPlanError> { 204 let result = resolve_allocations(terms, mappings, pools, explicit)?; 205 let available: BTreeMap<_, _> = pools.iter().map(|pool| (pool.id(), *pool)).collect(); 206 let mut totals = BTreeMap::new(); 207 for allocation in &result { 208 let total = totals.entry(allocation.pool).or_insert(StockTicks::ZERO); 209 *total = total 210 .checked_add(allocation.ticks) 211 .map_err(|_| AllocationPlanError::Capacity)?; 212 } 213 let mut effects = Vec::new(); 214 for (id, quantity) in totals { 215 effects.push(PoolHoldProposal::new(available[&id], quantity)?); 216 } 217 Ok((result, effects)) 218 } 219 220 /// Resolves complete line/pool quantities using the supplied exact mappings, 221 /// units and versions, without requiring or proposing new available stock. 222 /// An amendment executor supplies retained mappings for existing draws. It 223 /// must separately compare current residual/original allocations and acquire 224 /// positive deltas; successful resolution alone grants no physical backing. 225 pub fn resolve_allocations( 226 terms: &Terms, 227 mappings: &[OptionPoolMapping], 228 pools: &[PoolSnapshot], 229 explicit: Option<&[AllocationClaim]>, 230 ) -> Result<Vec<StockAllocation>, AllocationPlanError> { 231 match terms.supply() { 232 SupplyCommitment::FuturePromise(_) => { 233 if explicit.is_some() || !mappings.is_empty() || !pools.is_empty() { 234 return Err(AllocationPlanError::InvalidInput); 235 } 236 return Ok(vec![]); 237 } 238 SupplyCommitment::StockBacked => {} 239 } 240 if mappings.len() != terms.lines().len() || pools.len() > 96 { 241 return Err(AllocationPlanError::InvalidInput); 242 } 243 if let Some(choices) = explicit { 244 if choices.is_empty() || choices.len() > 64 { 245 return Err(AllocationPlanError::InvalidInput); 246 } 247 for (index, choice) in choices.iter().enumerate() { 248 if choices[..index] 249 .iter() 250 .any(|prior| prior.line == choice.line && prior.pool == choice.pool) 251 { 252 return Err(AllocationPlanError::InvalidInput); 253 } 254 } 255 } 256 let mut available = BTreeMap::new(); 257 for pool in pools { 258 if pool.version().get() == 0 || available.insert(pool.id(), *pool).is_some() { 259 return Err(AllocationPlanError::InvalidInput); 260 } 261 } 262 let mut result = Vec::new(); 263 for (line, mapping) in terms.lines().iter().zip(mappings) { 264 if mapping.key() != OptionMappingKey::new(line.source().coordinate(), line.option_id()) 265 || available 266 .get(&mapping.pool_id()) 267 .is_none_or(|pool| pool.unit() != mapping.pool_unit()) 268 { 269 return Err(AllocationPlanError::StaleState); 270 } 271 let required = match line.price() { 272 AgreementPrice::Fixed(_) => mapping 273 .draw_for_sales(line.amount()) 274 .map_err(|_| AllocationPlanError::InvalidInput)?, 275 AgreementPrice::VariableWeight(weight) => { 276 // Bounds describe this entire line. Never multiply by package 277 // count or infer a mass/volume conversion from its label. 278 let quantity = Quantity::new(weight.maximum().amount(), weight.measurement_unit()) 279 .and_then(|value| value.convert(mapping.pool_unit().unit())) 280 .map_err(|_| AllocationPlanError::InvalidInput)?; 281 mapping 282 .pool_unit() 283 .ticks_for(quantity) 284 .map_err(|_| AllocationPlanError::InvalidInput)? 285 } 286 }; 287 if required == StockTicks::ZERO { 288 return Err(AllocationPlanError::InvalidInput); 289 } 290 if let Some(explicit) = explicit { 291 let mut covered = StockTicks::ZERO; 292 for choice in explicit.iter().filter(|value| value.line_id() == line.id()) { 293 let pool = available 294 .get(&choice.pool_id()) 295 .ok_or(AllocationPlanError::StaleState)?; 296 if pool.version() != choice.expected_pool_version() { 297 return Err(AllocationPlanError::StaleState); 298 } 299 let normalized = choice 300 .quantity() 301 .convert(mapping.pool_unit().unit()) 302 .map_err(|_| AllocationPlanError::InvalidInput)?; 303 covered = covered 304 .checked_add( 305 mapping 306 .pool_unit() 307 .ticks_for(normalized) 308 .map_err(|_| AllocationPlanError::InvalidInput)?, 309 ) 310 .map_err(|_| AllocationPlanError::Capacity)?; 311 let quantity = choice 312 .quantity() 313 .convert(pool.unit().unit()) 314 .map_err(|_| AllocationPlanError::InvalidInput)?; 315 let ticks = pool 316 .unit() 317 .ticks_for(quantity) 318 .map_err(|_| AllocationPlanError::InvalidInput)?; 319 result.push(StockAllocation { 320 line: line.id(), 321 pool: pool.id(), 322 ticks, 323 }); 324 } 325 if covered != required { 326 return Err(AllocationPlanError::InvalidInput); 327 } 328 } else { 329 result.push(StockAllocation { 330 line: line.id(), 331 pool: mapping.pool_id(), 332 ticks: required, 333 }); 334 } 335 } 336 if let Some(explicit) = explicit 337 && result.len() != explicit.len() 338 { 339 return Err(AllocationPlanError::InvalidInput); 340 } 341 if result.is_empty() || result.len() > 64 { 342 return Err(AllocationPlanError::InvalidInput); 343 } 344 result.sort_by_key(|value| (value.pool, value.line)); 345 Ok(result) 346 }