1mod counter_offer;
21mod imbalances;
22
23use crate::error::{Result, WalletError};
24use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};
25
26pub use counter_offer::{CounterOffer, ImbalanceView, OutputRecipe};
27pub use imbalances::Imbalances;
28
29pub trait CoinSelector<T: CoinRecipe> {
36 fn select(
37 &self,
38 coins: &[T],
39 token: &TokenType,
40 amount_needed: Amount,
41 cost_model: &TransactionCostModel,
42 ) -> Option<usize>;
43}
44
45pub struct SmallestFirstSelector;
53
54impl<T: CoinRecipe> CoinSelector<T> for SmallestFirstSelector {
55 fn select(
56 &self,
57 coins: &[T],
58 token: &TokenType,
59 _amount_needed: Amount,
60 _cost_model: &TransactionCostModel,
61 ) -> Option<usize> {
62 coins
63 .iter()
64 .enumerate()
65 .filter(|(_, c)| c.token_type() == token)
66 .min_by_key(|(_, c)| c.value())
67 .map(|(i, _)| i)
68 }
69}
70
71pub struct FewestCoinsSelector;
80
81impl<T: CoinRecipe> CoinSelector<T> for FewestCoinsSelector {
82 fn select(
83 &self,
84 coins: &[T],
85 token: &TokenType,
86 amount_needed: Amount,
87 _cost_model: &TransactionCostModel,
88 ) -> Option<usize> {
89 if amount_needed > Amount::ZERO {
90 if let Some((idx, _)) = coins
91 .iter()
92 .enumerate()
93 .filter(|(_, c)| c.token_type() == token && c.value() >= amount_needed)
94 .min_by_key(|(_, c)| c.value())
95 {
96 return Some(idx);
97 }
98 }
99 coins
100 .iter()
101 .enumerate()
102 .filter(|(_, c)| c.token_type() == token)
103 .max_by_key(|(_, c)| c.value())
104 .map(|(i, _)| i)
105 }
106}
107
108#[derive(Debug, Clone)]
112pub struct BalanceRecipe<TInput, TOutput> {
113 pub inputs: Vec<TInput>,
114 pub outputs: Vec<TOutput>,
115}
116
117pub struct BalanceRequest<'a, TInput, TOutput, S, F>
120where
121 TInput: CoinRecipe + Clone,
122 TOutput: CoinRecipe,
123 S: CoinSelector<TInput>,
124 F: FnMut(OutputRecipe) -> TOutput,
125{
126 pub coins: Vec<TInput>,
129 pub initial_imbalances: Imbalances,
131 pub target_imbalances: Imbalances,
133 pub cost_model: TransactionCostModel,
135 pub fee_token: TokenType,
137 pub selector: &'a S,
139 pub create_output: F,
141 pub is_coin_equal: fn(&TInput, &TInput) -> bool,
144}
145
146pub fn balance<TInput, TOutput, S, F>(
149 request: BalanceRequest<'_, TInput, TOutput, S, F>,
150) -> Result<BalanceRecipe<TInput, TOutput>>
151where
152 TInput: CoinRecipe + Clone,
153 TOutput: CoinRecipe,
154 S: CoinSelector<TInput>,
155 F: FnMut(OutputRecipe) -> TOutput,
156{
157 let BalanceRequest {
158 mut coins,
159 initial_imbalances,
160 target_imbalances,
161 cost_model,
162 fee_token,
163 selector,
164 mut create_output,
165 is_coin_equal,
166 } = request;
167
168 let mut counter_offer = CounterOffer::<TInput, TOutput>::new(
169 initial_imbalances,
170 target_imbalances,
171 cost_model,
172 fee_token,
173 );
174
175 while let Some((token, value)) = counter_offer
178 .find_non_native_imbalance()
179 .map(|v| (v.token.clone(), v.value))
180 {
181 coins = settle_token(
182 &token,
183 value,
184 coins,
185 &mut counter_offer,
186 selector,
187 &mut create_output,
188 is_coin_equal,
189 )?;
190 }
191
192 while let Some((token, value)) = counter_offer
194 .find_native_imbalance()
195 .map(|v| (v.token.clone(), v.value))
196 {
197 coins = settle_token(
198 &token,
199 value,
200 coins,
201 &mut counter_offer,
202 selector,
203 &mut create_output,
204 is_coin_equal,
205 )?;
206 }
207
208 let (inputs, outputs) = counter_offer.into_recipe();
209 Ok(BalanceRecipe { inputs, outputs })
210}
211
212fn settle_token<TInput, TOutput, S, F>(
215 token: &TokenType,
216 imbalance_amount: Amount,
217 coins: Vec<TInput>,
218 counter_offer: &mut CounterOffer<TInput, TOutput>,
219 selector: &S,
220 create_output: &mut F,
221 is_coin_equal: fn(&TInput, &TInput) -> bool,
222) -> Result<Vec<TInput>>
223where
224 TInput: CoinRecipe + Clone,
225 TOutput: CoinRecipe,
226 S: CoinSelector<TInput>,
227 F: FnMut(OutputRecipe) -> TOutput,
228{
229 let target = counter_offer.target_for(token);
230 let cost = counter_offer.cost_model().output_fee_overhead;
231 let is_fee_token = token == counter_offer.fee_token();
232
233 let should_add_output = if is_fee_token {
234 imbalance_amount >= target + cost
235 } else {
236 imbalance_amount > target
237 };
238
239 if should_add_output {
240 counter_offer.add_output(token, imbalance_amount - target, |tok, net_value| {
241 (create_output)(OutputRecipe {
242 token_type: tok,
243 value: net_value,
244 })
245 });
246 Ok(coins)
247 } else {
248 let Some(idx) =
249 selector.select(&coins, token, imbalance_amount, counter_offer.cost_model())
250 else {
251 return Err(WalletError::InsufficientFunds {
252 token: token.to_string(),
253 });
254 };
255
256 let mut coins = coins;
257 let picked = coins.swap_remove(idx);
258 coins.retain(|c| !is_coin_equal(c, &picked));
261 counter_offer.add_input(picked);
262 Ok(coins)
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269 use crate::types::SimpleCoin;
270
271 const NATIVE: &str = "native";
272 const OTHER: &str = "other";
273
274 fn native() -> TokenType {
275 TokenType::new(NATIVE)
276 }
277 fn other() -> TokenType {
278 TokenType::new(OTHER)
279 }
280
281 fn coin(token: &str, value: impl Into<Amount>) -> SimpleCoin {
282 SimpleCoin::new(token, value)
283 }
284
285 fn default_cost_model() -> TransactionCostModel {
286 TransactionCostModel::new(19_314, 19_708)
287 }
288
289 fn balance_test(
290 coins: Vec<SimpleCoin>,
291 initial_imbalances: Imbalances,
292 cost_model: TransactionCostModel,
293 ) -> Result<BalanceRecipe<SimpleCoin, SimpleCoin>> {
294 balance(BalanceRequest {
295 coins,
296 initial_imbalances,
297 target_imbalances: Imbalances::new(),
298 cost_model,
299 fee_token: native(),
300 selector: &SmallestFirstSelector,
301 create_output: |rec| SimpleCoin::new(rec.token_type, rec.value),
302 is_coin_equal: |a, b| a == b,
303 })
304 }
305
306 #[test]
307 fn nothing_to_balance() {
308 let recipe = balance_test(vec![], Imbalances::new(), TransactionCostModel::ZERO).unwrap();
309 assert_eq!(recipe.inputs, [] as [SimpleCoin; 0]);
310 assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
311 }
312
313 #[test]
314 fn uses_exactly_one_coin_when_value_matches_with_fee() {
315 let cm = default_cost_model();
316 let exact = coin(NATIVE, Amount::from(1_000) + cm.input_fee_overhead);
317 let recipe = balance_test(
318 vec![exact.clone()],
319 Imbalances::from_entry(native(), -1_000),
320 cm,
321 )
322 .unwrap();
323 assert_eq!(recipe.inputs.len(), 1);
324 assert_eq!(recipe.inputs[0], exact);
325 assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
326 }
327
328 #[test]
329 fn insufficient_funds_reports_correct_token() {
330 let err = balance_test(
331 vec![coin(NATIVE, 10)],
332 Imbalances::from_entry(native(), -1_000_000),
333 TransactionCostModel::ZERO,
334 )
335 .unwrap_err();
336 match err {
337 WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
338 other => panic!("wrong error: {other:?}"),
339 }
340 }
341
342 #[test]
343 fn no_overspend_when_exact_coin_exists() {
344 let cm = TransactionCostModel::ZERO;
347 let coins = vec![coin(NATIVE, 100), coin(NATIVE, 100)];
348 let recipe = balance_test(coins, Imbalances::from_entry(native(), -10), cm).unwrap();
349 assert_eq!(recipe.inputs.len(), 1);
350 assert_eq!(recipe.outputs.len(), 1);
351 assert_eq!(recipe.outputs[0].value, Amount::from(90));
352 assert_eq!(recipe.outputs[0].token_type, native());
353 }
354
355 #[test]
356 fn multi_token_balance_closes_both() {
357 let cm = TransactionCostModel::ZERO;
359 let coins = vec![
360 coin(OTHER, 150), coin(NATIVE, 500), ];
363 let initial = Imbalances::from_entries([(other(), -100), (native(), -500)]);
364 let recipe = balance_test(coins, initial, cm).unwrap();
365
366 assert_eq!(recipe.inputs.len(), 2);
367 assert!(recipe.inputs.iter().any(|c| c.token_type == other()));
368 assert!(recipe.inputs.iter().any(|c| c.token_type == native()));
369 assert_eq!(recipe.outputs.len(), 1);
371 assert_eq!(recipe.outputs[0].token_type, other());
372 assert_eq!(recipe.outputs[0].value, Amount::from(50));
373 }
374
375 #[test]
376 fn smallest_first_selector_picks_min_coin() {
377 let coins = vec![coin(NATIVE, 100), coin(NATIVE, 5), coin(NATIVE, 50)];
378 let idx = SmallestFirstSelector.select(
379 &coins,
380 &native(),
381 Amount::from(10),
382 &TransactionCostModel::ZERO,
383 );
384 assert_eq!(idx, Some(1));
385 }
386
387 #[test]
388 fn smallest_first_selector_ignores_wrong_tokens() {
389 let coins = vec![coin(OTHER, 1), coin(NATIVE, 100), coin(OTHER, 2)];
390 let idx = SmallestFirstSelector.select(
391 &coins,
392 &native(),
393 Amount::from(10),
394 &TransactionCostModel::ZERO,
395 );
396 assert_eq!(idx, Some(1));
397 }
398
399 #[test]
400 fn fee_token_output_emitted_when_excess_exceeds_overhead() {
401 let cm = TransactionCostModel::new(10, 20);
405 let coins = vec![coin(NATIVE, 200)];
406 let recipe = balance_test(coins, Imbalances::from_entry(native(), -100), cm).unwrap();
407 assert_eq!(recipe.inputs.len(), 1);
408 assert_eq!(recipe.outputs.len(), 1);
409 assert_eq!(recipe.outputs[0].value, Amount::from(70));
410 }
411
412 #[test]
413 fn excess_below_output_overhead_cannot_be_balanced() {
414 let cm = TransactionCostModel::new(10, 20);
419 let err = balance_test(
422 vec![coin(NATIVE, 115)],
423 Imbalances::from_entry(native(), -100),
424 cm,
425 )
426 .unwrap_err();
427 assert!(matches!(err, WalletError::InsufficientFunds { .. }));
428 }
429
430 #[test]
435 fn ts_does_not_overspend_coins() {
436 let cm = TransactionCostModel::new(19_314, 19_708);
437 let coins = vec![coin(NATIVE, 10_000_000), coin(NATIVE, 10_000_000)];
438 let recipe = balance_test(coins, Imbalances::from_entry(native(), -1_000_000), cm).unwrap();
439 assert_eq!(recipe.inputs.len(), 1);
440 assert_eq!(recipe.outputs.len(), 1);
441 }
442
443 #[test]
446 fn ts_balance_custom_token() {
447 let custom = TokenType::new("custom");
448 let cm = TransactionCostModel::new(19_314, 19_708);
449 let coins = vec![
452 coin(NATIVE, 100_000_000),
453 SimpleCoin::new(custom.clone(), 1),
454 SimpleCoin::new(custom.clone(), 2),
455 SimpleCoin::new(custom.clone(), 3),
456 ];
457 let recipe = balance_test(coins, Imbalances::from_entry(custom, -1), cm).unwrap();
458 assert_eq!(recipe.inputs.len(), 2);
459 assert_eq!(recipe.outputs.len(), 1);
460 }
461
462 #[test]
465 fn ts_balance_multiple_token_types() {
466 let custom = TokenType::new("custom");
467 let cm = TransactionCostModel::new(19_314, 19_708);
468 let coins = vec![
469 coin(NATIVE, 10_000_000),
470 coin(NATIVE, 20_000_000),
471 coin(NATIVE, 30_000_000),
472 SimpleCoin::new(custom.clone(), 1),
473 SimpleCoin::new(custom.clone(), 2),
474 SimpleCoin::new(custom.clone(), 3),
475 ];
476 let initial = Imbalances::from_entries([
478 (custom.clone(), -4),
479 (native(), -5_000_000),
480 (native(), -1_000_000),
481 (custom.clone(), -1),
482 ]);
483 let recipe = balance_test(coins, initial, cm).unwrap();
484 assert_eq!(recipe.inputs.len(), 4);
485 assert_eq!(recipe.outputs.len(), 2);
486 }
487
488 #[test]
492 fn ts_fail_when_not_enough_for_fees() {
493 let cm = TransactionCostModel::new(19_314, 19_708);
494 let err = balance_test(
495 vec![coin(NATIVE, 1_000_000)],
496 Imbalances::from_entry(native(), -1_000_000),
497 cm,
498 )
499 .unwrap_err();
500 match err {
501 WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
502 other => panic!("wrong error: {other:?}"),
503 }
504 }
505
506 #[test]
510 fn ts_fail_when_change_smaller_than_output_fee() {
511 let cm = TransactionCostModel::new(19_314, 19_708);
512 let coin_val = cm.input_fee_overhead + Amount::from(5);
516 let deficit = -(Amount::from(5) + cm.output_fee_overhead);
517 let err = balance_test(
518 vec![coin(NATIVE, coin_val)],
519 Imbalances::from_entry(native(), deficit),
520 cm,
521 )
522 .unwrap_err();
523 assert!(matches!(err, WalletError::InsufficientFunds { .. }));
524 }
525
526 #[test]
529 fn ts_uses_provided_coin_selection() {
530 struct LargestFirst;
533 impl<T: CoinRecipe> CoinSelector<T> for LargestFirst {
534 fn select(
535 &self,
536 coins: &[T],
537 token: &TokenType,
538 _: Amount,
539 _: &TransactionCostModel,
540 ) -> Option<usize> {
541 coins
542 .iter()
543 .enumerate()
544 .filter(|(_, c)| c.token_type() == token)
545 .max_by_key(|(_, c)| c.value())
546 .map(|(i, _)| i)
547 }
548 }
549
550 let cm = TransactionCostModel::ZERO;
551 let coins = vec![coin(NATIVE, 5), coin(NATIVE, 50), coin(NATIVE, 100)];
552 let recipe = balance(BalanceRequest {
553 coins,
554 initial_imbalances: Imbalances::from_entry(native(), -40),
555 target_imbalances: Imbalances::new(),
556 cost_model: cm,
557 fee_token: native(),
558 selector: &LargestFirst,
559 create_output: |r| SimpleCoin::new(r.token_type, r.value),
560 is_coin_equal: |a, b| a == b,
561 })
562 .unwrap();
563 assert_eq!(recipe.inputs.len(), 1);
564 assert_eq!(
565 recipe.inputs[0].value,
566 Amount::from(100),
567 "largest-first should pick 100"
568 );
569 assert_eq!(recipe.outputs.len(), 1);
570 assert_eq!(recipe.outputs[0].value, Amount::from(60));
571 }
572
573 #[test]
577 fn ts_reaches_target_imbalances() {
578 let custom = TokenType::new("custom");
579 let cm = TransactionCostModel::ZERO;
580 let recipe = balance(BalanceRequest {
583 coins: vec![SimpleCoin::new(custom.clone(), 7)],
584 initial_imbalances: Imbalances::new(),
585 target_imbalances: Imbalances::from_entry(custom.clone(), 7),
586 cost_model: cm,
587 fee_token: native(),
588 selector: &SmallestFirstSelector,
589 create_output: |r| SimpleCoin::new(r.token_type, r.value),
590 is_coin_equal: |a, b| a == b,
591 })
592 .unwrap();
593 assert_eq!(recipe.inputs.len(), 1);
595 assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
596 }
597
598 #[test]
602 fn ts_errors_when_cannot_meet_target() {
603 let unobtainium = TokenType::new("unobtainium");
604 let cm = TransactionCostModel::ZERO;
605 let err = balance(BalanceRequest {
606 coins: vec![coin(NATIVE, 1_000_000)],
607 initial_imbalances: Imbalances::new(),
608 target_imbalances: Imbalances::from_entry(unobtainium.clone(), 1),
609 cost_model: cm,
610 fee_token: native(),
611 selector: &SmallestFirstSelector,
612 create_output: |r| SimpleCoin::new(r.token_type, r.value),
613 is_coin_equal: |a, b| a == b,
614 })
615 .unwrap_err();
616 match err {
617 WalletError::InsufficientFunds { token } => {
618 assert_eq!(token, unobtainium.as_str());
619 }
620 other => panic!("wrong error: {other:?}"),
621 }
622 }
623
624 #[test]
627 fn invariant_inputs_subset_of_candidate_pool() {
628 let cm = TransactionCostModel::ZERO;
629 let pool: Vec<SimpleCoin> = (1..=10).map(|v| coin(NATIVE, v * 10)).collect();
630 let recipe = balance_test(pool.clone(), Imbalances::from_entry(native(), -55), cm).unwrap();
631 for inp in &recipe.inputs {
632 assert!(
633 pool.contains(inp),
634 "input {inp:?} not in original candidate pool"
635 );
636 }
637 }
638
639 #[test]
642 fn invariant_non_fee_targets_met_exactly() {
643 let custom_a = TokenType::new("custom_a");
644 let custom_b = TokenType::new("custom_b");
645 let cm = TransactionCostModel::ZERO;
646 let coins = vec![
647 SimpleCoin::new(custom_a.clone(), 100),
648 SimpleCoin::new(custom_b.clone(), 50),
649 SimpleCoin::new(custom_b.clone(), 50),
650 coin(NATIVE, 1_000),
651 ];
652 let target = Imbalances::from_entries([(custom_a.clone(), 30), (custom_b.clone(), 25)]);
653 let recipe = balance(BalanceRequest {
654 coins,
655 initial_imbalances: Imbalances::new(),
656 target_imbalances: target.clone(),
657 cost_model: cm,
658 fee_token: native(),
659 selector: &SmallestFirstSelector,
660 create_output: |r| SimpleCoin::new(r.token_type, r.value),
661 is_coin_equal: |a, b| a == b,
662 })
663 .unwrap();
664
665 let mut net = Imbalances::new();
668 for c in &recipe.inputs {
669 net.set(c.token_type.clone(), net.get(&c.token_type) + c.value);
670 }
671 for c in &recipe.outputs {
672 net.set(c.token_type.clone(), net.get(&c.token_type) - c.value);
673 }
674 for (token, expected) in target.iter() {
675 assert_eq!(net.get(token), expected, "token {token:?}: target not met");
676 }
677 }
678}