replacement.rs (9119B)
1 //! Net amendment claims. Negative changes cannot finance preparatory holds. 2 use super::{ 3 AllocationClaim, AllocationPlanError, OptionPoolMapping, PoolHoldProposal, PoolSnapshot, 4 StockAllocation, StockTicks, 5 }; 6 use crate::{Decimal, Quantity, SupplyCommitment, Terms}; 7 use alloc::{collections::BTreeMap, vec::Vec}; 8 use core::fmt; 9 10 /// Resolves complete replacement draws against retained original line/pool 11 /// quantities. Automatic allocation keeps an existing single pool, even when 12 /// a listing mapping now names another pool. An unchanged multi-pool draw is 13 /// retained exactly; changing its split requires explicit complete allocation. 14 /// Mappings for existing lines must come from the retained preparation, with 15 /// consumed quantities and original provenance separately checked by execution. 16 pub fn resolve_replacement_allocations( 17 terms: &Terms, 18 mappings: &[OptionPoolMapping], 19 pools: &[PoolSnapshot], 20 explicit: Option<&[AllocationClaim]>, 21 current: &[StockAllocation], 22 ) -> Result<Vec<StockAllocation>, AllocationPlanError> { 23 plan_replacement_allocations(current, current, pools)?; 24 let observed = if matches!(terms.supply(), SupplyCommitment::FuturePromise(_)) { 25 &[][..] 26 } else { 27 pools 28 }; 29 let desired = super::resolve_allocations(terms, mappings, observed, explicit)?; 30 if current.len() > 64 { 31 return Err(AllocationPlanError::Capacity); 32 } 33 if explicit.is_some() { 34 return Ok(desired); 35 } 36 let pools: BTreeMap<_, _> = pools.iter().map(|pool| (pool.id(), *pool)).collect(); 37 let mut result = Vec::new(); 38 for target in desired { 39 let originals: Vec<_> = current 40 .iter() 41 .filter(|old| old.line_id() == target.line_id()) 42 .copied() 43 .collect(); 44 let target_pool = pools 45 .get(&target.pool_id()) 46 .ok_or(AllocationPlanError::StaleState)?; 47 let quantity = Quantity::new( 48 Decimal::from_parts(target.ticks().get(), target_pool.unit().scale()) 49 .map_err(|_| AllocationPlanError::Capacity)?, 50 target_pool.unit().unit(), 51 ) 52 .map_err(|_| AllocationPlanError::InvalidInput)?; 53 match originals.as_slice() { 54 [] => result.push(target), 55 [original] => { 56 let original_pool = pools 57 .get(&original.pool_id()) 58 .ok_or(AllocationPlanError::StaleState)?; 59 let converted = quantity 60 .convert(original_pool.unit().unit()) 61 .map_err(|_| AllocationPlanError::InvalidInput)?; 62 result.push(StockAllocation::new( 63 target.line_id(), 64 original.pool_id(), 65 original_pool 66 .unit() 67 .ticks_for(converted) 68 .map_err(|_| AllocationPlanError::InvalidInput)?, 69 )?); 70 } 71 _ => { 72 let mut quantity = Quantity::new( 73 Decimal::from_parts(0, 0).map_err(|_| AllocationPlanError::InvalidInput)?, 74 target_pool.unit().unit(), 75 ) 76 .map_err(|_| AllocationPlanError::InvalidInput)?; 77 for original in &originals { 78 let original_pool = pools 79 .get(&original.pool_id()) 80 .ok_or(AllocationPlanError::StaleState)?; 81 let converted = Quantity::new( 82 Decimal::from_parts(original.ticks().get(), original_pool.unit().scale()) 83 .map_err(|_| AllocationPlanError::Capacity)?, 84 original_pool.unit().unit(), 85 ) 86 .and_then(|value| value.convert(target_pool.unit().unit())) 87 .map_err(|_| AllocationPlanError::InvalidInput)?; 88 quantity = quantity 89 .checked_add(converted) 90 .map_err(|_| AllocationPlanError::Capacity)?; 91 } 92 if target_pool 93 .unit() 94 .ticks_for(quantity) 95 .map_err(|_| AllocationPlanError::InvalidInput)? 96 != target.ticks() 97 { 98 return Err(AllocationPlanError::Unsupported); 99 } 100 result.extend(originals); 101 } 102 } 103 } 104 if result.len() > 64 { 105 return Err(AllocationPlanError::Capacity); 106 } 107 result.sort_by_key(|value| (value.pool_id(), value.line_id())); 108 Ok(result) 109 } 110 111 /// Checked net changes over claimed current and desired residual draws. 112 /// Original provenance, retained mappings, already consumed quantities and 113 /// deficit/backing composition must be authenticated by the executor. This 114 /// value neither acquires positives nor releases negatives or heals deficits. 115 pub struct ReplacementAllocationPlan { 116 additional: Vec<StockAllocation>, 117 releases: Vec<StockAllocation>, 118 holds: Vec<PoolHoldProposal>, 119 } 120 impl ReplacementAllocationPlan { 121 /// Positive residual differences to acquire before replacement issuance. 122 pub fn additional_allocations(&self) -> &[StockAllocation] { 123 &self.additional 124 } 125 /// Negative residual differences to resolve against original allocations 126 /// only when the mutually authorized replacement actually installs. 127 pub fn pending_releases(&self) -> &[StockAllocation] { 128 &self.releases 129 } 130 /// Atomic available-to-preparatory proposals, without spending any pending 131 /// negative delta. Current pool/permission checks still belong to the store. 132 pub fn preparatory_holds(&self) -> &[PoolHoldProposal] { 133 &self.holds 134 } 135 } 136 impl fmt::Debug for ReplacementAllocationPlan { 137 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 138 f.write_str("ReplacementAllocationPlan(<private proposal>)") 139 } 140 } 141 142 /// Compares complete aggregate current and desired residual line/pool draws. 143 /// Inputs contain at most64 unique positive pairs each and96 distinct versioned 144 /// pools. They are already normalized to each pool's fixed ticks; resolving 145 /// full new terms and subtracting consumed quantities happens before this call. 146 /// Current includes deficits as outstanding obligations: unchanged quantities 147 /// never receive replacement backing implicitly. All positive pool holds must 148 /// succeed together; negative deltas remain data and never alter these holds. 149 pub fn plan_replacement_allocations( 150 current: &[StockAllocation], 151 desired: &[StockAllocation], 152 pools: &[PoolSnapshot], 153 ) -> Result<ReplacementAllocationPlan, AllocationPlanError> { 154 if current.len() > 64 || desired.len() > 64 || pools.len() > 96 { 155 return Err(AllocationPlanError::Capacity); 156 } 157 let mut observed = BTreeMap::new(); 158 for pool in pools { 159 if pool.version().get() == 0 || observed.insert(pool.id(), *pool).is_some() { 160 return Err(AllocationPlanError::InvalidInput); 161 } 162 } 163 let mut before = BTreeMap::new(); 164 let mut after = BTreeMap::new(); 165 for (values, target) in [(current, &mut before), (desired, &mut after)] { 166 for value in values { 167 if !observed.contains_key(&value.pool_id()) { 168 return Err(AllocationPlanError::StaleState); 169 } 170 if target 171 .insert((value.pool_id(), value.line_id()), value.ticks()) 172 .is_some() 173 { 174 return Err(AllocationPlanError::InvalidInput); 175 } 176 } 177 } 178 let mut keys: Vec<_> = before.keys().chain(after.keys()).copied().collect(); 179 keys.sort(); 180 keys.dedup(); 181 let mut additional = Vec::new(); 182 let mut releases = Vec::new(); 183 let mut quantities = BTreeMap::new(); 184 for (pool, line) in keys { 185 let old = before 186 .get(&(pool, line)) 187 .copied() 188 .unwrap_or(StockTicks::ZERO); 189 let new = after 190 .get(&(pool, line)) 191 .copied() 192 .unwrap_or(StockTicks::ZERO); 193 if new > old { 194 let quantity = new 195 .checked_sub(old) 196 .map_err(|_| AllocationPlanError::InvalidInput)?; 197 additional.push(StockAllocation::new(line, pool, quantity)?); 198 let total = quantities.entry(pool).or_insert(StockTicks::ZERO); 199 *total = total 200 .checked_add(quantity) 201 .map_err(|_| AllocationPlanError::Capacity)?; 202 } else if old > new { 203 releases.push(StockAllocation::new( 204 line, 205 pool, 206 old.checked_sub(new) 207 .map_err(|_| AllocationPlanError::InvalidInput)?, 208 )?); 209 } 210 } 211 let mut holds = Vec::with_capacity(quantities.len()); 212 for (pool, quantity) in quantities { 213 holds.push(PoolHoldProposal::new(observed[&pool], quantity)?); 214 } 215 Ok(ReplacementAllocationPlan { 216 additional, 217 releases, 218 holds, 219 }) 220 }