posting_selection.rs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. //! Posting selection for the intent layer.
  2. //!
  3. //! When a caller uses `pay` or `withdraw`, they specify an amount — not which
  4. //! postings to consume. This module picks the smallest set of postings that
  5. //! covers the requested amount, so the intent layer can build the transfer
  6. //! automatically without exposing UTXO mechanics to the caller.
  7. use kuatia_types::{AssetId, Cent, Posting, PostingId};
  8. /// Error returned when posting selection fails.
  9. #[derive(Debug, Clone, PartialEq, Eq)]
  10. pub enum SelectionError {
  11. /// Available postings do not cover the requested amount.
  12. InsufficientFunds {
  13. /// Total value of eligible postings.
  14. available: Cent,
  15. /// Amount the caller asked for.
  16. requested: Cent,
  17. },
  18. /// Summing posting values would overflow `Cent`.
  19. Overflow,
  20. }
  21. impl std::fmt::Display for SelectionError {
  22. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  23. match self {
  24. Self::InsufficientFunds {
  25. available,
  26. requested,
  27. } => {
  28. write!(
  29. f,
  30. "insufficient funds: available {available}, requested {requested}"
  31. )
  32. }
  33. Self::Overflow => write!(f, "monetary amount overflow"),
  34. }
  35. }
  36. }
  37. impl std::error::Error for SelectionError {}
  38. /// Picks postings to cover `target`, using largest-first greedy to minimise
  39. /// the number of postings consumed (and therefore the number of change postings
  40. /// created). Only active, positive postings of the right asset are considered.
  41. pub fn select_postings(
  42. available: &[Posting],
  43. asset: AssetId,
  44. target: Cent,
  45. ) -> Result<Vec<PostingId>, SelectionError> {
  46. assert!(target.is_positive(), "target must be positive");
  47. let mut candidates: Vec<&Posting> = available
  48. .iter()
  49. .filter(|p| p.is_active() && p.asset == asset && p.value.is_positive())
  50. .collect();
  51. // Largest first
  52. candidates.sort_by_key(|p| std::cmp::Reverse(p.value));
  53. let mut total_available = Cent::ZERO;
  54. for p in &candidates {
  55. total_available = total_available
  56. .checked_add(p.value)
  57. .map_err(|_| SelectionError::Overflow)?;
  58. }
  59. if total_available < target {
  60. return Err(SelectionError::InsufficientFunds {
  61. available: total_available,
  62. requested: target,
  63. });
  64. }
  65. let mut selected = Vec::new();
  66. let mut sum = Cent::ZERO;
  67. for posting in candidates {
  68. selected.push(posting.id);
  69. sum = sum
  70. .checked_add(posting.value)
  71. .map_err(|_| SelectionError::Overflow)?;
  72. if sum >= target {
  73. break;
  74. }
  75. }
  76. Ok(selected)
  77. }
  78. #[cfg(test)]
  79. mod tests {
  80. use super::*;
  81. use kuatia_types::*;
  82. fn make_posting(index: u16, value: i64) -> Posting {
  83. Posting::new(
  84. PostingId {
  85. transfer: EnvelopeId([1; 32]),
  86. index,
  87. },
  88. AccountId::new(1),
  89. AssetId::new(1),
  90. Cent::from(value),
  91. )
  92. }
  93. #[test]
  94. fn exact_match() {
  95. let postings = vec![make_posting(0, 50), make_posting(1, 50)];
  96. let result = select_postings(&postings, AssetId::new(1), Cent::from(100)).unwrap();
  97. assert_eq!(result.len(), 2);
  98. }
  99. #[test]
  100. fn largest_first() {
  101. let postings = vec![
  102. make_posting(0, 10),
  103. make_posting(1, 90),
  104. make_posting(2, 50),
  105. ];
  106. let result = select_postings(&postings, AssetId::new(1), Cent::from(80)).unwrap();
  107. // Should pick 90 first (enough on its own)
  108. assert_eq!(result.len(), 1);
  109. assert_eq!(result[0].index, 1);
  110. }
  111. #[test]
  112. fn insufficient_funds() {
  113. let postings = vec![make_posting(0, 30), make_posting(1, 20)];
  114. let err = select_postings(&postings, AssetId::new(1), Cent::from(100)).unwrap_err();
  115. assert_eq!(
  116. err,
  117. SelectionError::InsufficientFunds {
  118. available: Cent::from(50),
  119. requested: Cent::from(100)
  120. }
  121. );
  122. }
  123. #[test]
  124. fn ignores_inactive_and_wrong_asset() {
  125. let mut inactive = make_posting(0, 1000);
  126. inactive.status = PostingStatus::Inactive;
  127. let mut wrong_asset = make_posting(1, 1000);
  128. wrong_asset.asset = AssetId::new(2);
  129. let good = make_posting(2, 50);
  130. let postings = vec![inactive, wrong_asset, good];
  131. let result = select_postings(&postings, AssetId::new(1), Cent::from(50)).unwrap();
  132. assert_eq!(result.len(), 1);
  133. assert_eq!(result[0].index, 2);
  134. }
  135. #[test]
  136. fn ignores_negative_postings() {
  137. let negative = Posting::new(
  138. PostingId {
  139. transfer: EnvelopeId([1; 32]),
  140. index: 0,
  141. },
  142. AccountId::new(1),
  143. AssetId::new(1),
  144. Cent::from(-100),
  145. );
  146. let good = make_posting(1, 50);
  147. let postings = vec![negative, good];
  148. let result = select_postings(&postings, AssetId::new(1), Cent::from(50)).unwrap();
  149. assert_eq!(result.len(), 1);
  150. assert_eq!(result[0].index, 1);
  151. }
  152. }