mod counter_offer;
mod imbalances;
use crate::error::{Result, WalletError};
use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};
pub use counter_offer::{CounterOffer, ImbalanceView, OutputRecipe};
pub use imbalances::Imbalances;
pub trait CoinSelector<T: CoinRecipe> {
fn select(
&self,
coins: &[T],
token: &TokenType,
amount_needed: Amount,
cost_model: &TransactionCostModel,
) -> Option<usize>;
}
pub struct SmallestFirstSelector;
impl<T: CoinRecipe> CoinSelector<T> for SmallestFirstSelector {
fn select(
&self,
coins: &[T],
token: &TokenType,
_amount_needed: Amount,
_cost_model: &TransactionCostModel,
) -> Option<usize> {
coins
.iter()
.enumerate()
.filter(|(_, c)| c.token_type() == token)
.min_by_key(|(_, c)| c.value())
.map(|(i, _)| i)
}
}
pub struct FewestCoinsSelector;
impl<T: CoinRecipe> CoinSelector<T> for FewestCoinsSelector {
fn select(
&self,
coins: &[T],
token: &TokenType,
amount_needed: Amount,
_cost_model: &TransactionCostModel,
) -> Option<usize> {
if amount_needed > Amount::ZERO {
if let Some((idx, _)) = coins
.iter()
.enumerate()
.filter(|(_, c)| c.token_type() == token && c.value() >= amount_needed)
.min_by_key(|(_, c)| c.value())
{
return Some(idx);
}
}
coins
.iter()
.enumerate()
.filter(|(_, c)| c.token_type() == token)
.max_by_key(|(_, c)| c.value())
.map(|(i, _)| i)
}
}
#[derive(Debug, Clone)]
pub struct BalanceRecipe<TInput, TOutput> {
pub inputs: Vec<TInput>,
pub outputs: Vec<TOutput>,
}
pub struct BalanceRequest<'a, TInput, TOutput, S, F>
where
TInput: CoinRecipe + Clone,
TOutput: CoinRecipe,
S: CoinSelector<TInput>,
F: FnMut(OutputRecipe) -> TOutput,
{
pub coins: Vec<TInput>,
pub initial_imbalances: Imbalances,
pub target_imbalances: Imbalances,
pub cost_model: TransactionCostModel,
pub fee_token: TokenType,
pub selector: &'a S,
pub create_output: F,
pub is_coin_equal: fn(&TInput, &TInput) -> bool,
}
pub fn balance<TInput, TOutput, S, F>(
request: BalanceRequest<'_, TInput, TOutput, S, F>,
) -> Result<BalanceRecipe<TInput, TOutput>>
where
TInput: CoinRecipe + Clone,
TOutput: CoinRecipe,
S: CoinSelector<TInput>,
F: FnMut(OutputRecipe) -> TOutput,
{
let BalanceRequest {
mut coins,
initial_imbalances,
target_imbalances,
cost_model,
fee_token,
selector,
mut create_output,
is_coin_equal,
} = request;
let mut counter_offer = CounterOffer::<TInput, TOutput>::new(
initial_imbalances,
target_imbalances,
cost_model,
fee_token,
);
while let Some((token, value)) = counter_offer
.find_non_native_imbalance()
.map(|v| (v.token.clone(), v.value))
{
coins = settle_token(
&token,
value,
coins,
&mut counter_offer,
selector,
&mut create_output,
is_coin_equal,
)?;
}
while let Some((token, value)) = counter_offer
.find_native_imbalance()
.map(|v| (v.token.clone(), v.value))
{
coins = settle_token(
&token,
value,
coins,
&mut counter_offer,
selector,
&mut create_output,
is_coin_equal,
)?;
}
let (inputs, outputs) = counter_offer.into_recipe();
Ok(BalanceRecipe { inputs, outputs })
}
fn settle_token<TInput, TOutput, S, F>(
token: &TokenType,
imbalance_amount: Amount,
coins: Vec<TInput>,
counter_offer: &mut CounterOffer<TInput, TOutput>,
selector: &S,
create_output: &mut F,
is_coin_equal: fn(&TInput, &TInput) -> bool,
) -> Result<Vec<TInput>>
where
TInput: CoinRecipe + Clone,
TOutput: CoinRecipe,
S: CoinSelector<TInput>,
F: FnMut(OutputRecipe) -> TOutput,
{
let target = counter_offer.target_for(token);
let cost = counter_offer.cost_model().output_fee_overhead;
let is_fee_token = token == counter_offer.fee_token();
let should_add_output = if is_fee_token {
imbalance_amount >= target + cost
} else {
imbalance_amount > target
};
if should_add_output {
counter_offer.add_output(token, imbalance_amount - target, |tok, net_value| {
(create_output)(OutputRecipe {
token_type: tok,
value: net_value,
})
});
Ok(coins)
} else {
let Some(idx) =
selector.select(&coins, token, imbalance_amount, counter_offer.cost_model())
else {
return Err(WalletError::InsufficientFunds {
token: token.to_string(),
});
};
let mut coins = coins;
let picked = coins.swap_remove(idx);
coins.retain(|c| !is_coin_equal(c, &picked));
counter_offer.add_input(picked);
Ok(coins)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::SimpleCoin;
const NATIVE: &str = "native";
const OTHER: &str = "other";
fn native() -> TokenType {
TokenType::new(NATIVE)
}
fn other() -> TokenType {
TokenType::new(OTHER)
}
fn coin(token: &str, value: impl Into<Amount>) -> SimpleCoin {
SimpleCoin::new(token, value)
}
fn default_cost_model() -> TransactionCostModel {
TransactionCostModel::new(19_314, 19_708)
}
fn balance_test(
coins: Vec<SimpleCoin>,
initial_imbalances: Imbalances,
cost_model: TransactionCostModel,
) -> Result<BalanceRecipe<SimpleCoin, SimpleCoin>> {
balance(BalanceRequest {
coins,
initial_imbalances,
target_imbalances: Imbalances::new(),
cost_model,
fee_token: native(),
selector: &SmallestFirstSelector,
create_output: |rec| SimpleCoin::new(rec.token_type, rec.value),
is_coin_equal: |a, b| a == b,
})
}
#[test]
fn nothing_to_balance() {
let recipe = balance_test(vec![], Imbalances::new(), TransactionCostModel::ZERO).unwrap();
assert_eq!(recipe.inputs, [] as [SimpleCoin; 0]);
assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
}
#[test]
fn uses_exactly_one_coin_when_value_matches_with_fee() {
let cm = default_cost_model();
let exact = coin(NATIVE, Amount::from(1_000) + cm.input_fee_overhead);
let recipe = balance_test(
vec![exact.clone()],
Imbalances::from_entry(native(), -1_000),
cm,
)
.unwrap();
assert_eq!(recipe.inputs.len(), 1);
assert_eq!(recipe.inputs[0], exact);
assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
}
#[test]
fn insufficient_funds_reports_correct_token() {
let err = balance_test(
vec![coin(NATIVE, 10)],
Imbalances::from_entry(native(), -1_000_000),
TransactionCostModel::ZERO,
)
.unwrap_err();
match err {
WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
other => panic!("wrong error: {other:?}"),
}
}
#[test]
fn no_overspend_when_exact_coin_exists() {
let cm = TransactionCostModel::ZERO;
let coins = vec![coin(NATIVE, 100), coin(NATIVE, 100)];
let recipe = balance_test(coins, Imbalances::from_entry(native(), -10), cm).unwrap();
assert_eq!(recipe.inputs.len(), 1);
assert_eq!(recipe.outputs.len(), 1);
assert_eq!(recipe.outputs[0].value, Amount::from(90));
assert_eq!(recipe.outputs[0].token_type, native());
}
#[test]
fn multi_token_balance_closes_both() {
let cm = TransactionCostModel::ZERO;
let coins = vec![
coin(OTHER, 150), coin(NATIVE, 500), ];
let initial = Imbalances::from_entries([(other(), -100), (native(), -500)]);
let recipe = balance_test(coins, initial, cm).unwrap();
assert_eq!(recipe.inputs.len(), 2);
assert!(recipe.inputs.iter().any(|c| c.token_type == other()));
assert!(recipe.inputs.iter().any(|c| c.token_type == native()));
assert_eq!(recipe.outputs.len(), 1);
assert_eq!(recipe.outputs[0].token_type, other());
assert_eq!(recipe.outputs[0].value, Amount::from(50));
}
#[test]
fn smallest_first_selector_picks_min_coin() {
let coins = vec![coin(NATIVE, 100), coin(NATIVE, 5), coin(NATIVE, 50)];
let idx = SmallestFirstSelector.select(
&coins,
&native(),
Amount::from(10),
&TransactionCostModel::ZERO,
);
assert_eq!(idx, Some(1));
}
#[test]
fn smallest_first_selector_ignores_wrong_tokens() {
let coins = vec![coin(OTHER, 1), coin(NATIVE, 100), coin(OTHER, 2)];
let idx = SmallestFirstSelector.select(
&coins,
&native(),
Amount::from(10),
&TransactionCostModel::ZERO,
);
assert_eq!(idx, Some(1));
}
#[test]
fn fee_token_output_emitted_when_excess_exceeds_overhead() {
let cm = TransactionCostModel::new(10, 20);
let coins = vec![coin(NATIVE, 200)];
let recipe = balance_test(coins, Imbalances::from_entry(native(), -100), cm).unwrap();
assert_eq!(recipe.inputs.len(), 1);
assert_eq!(recipe.outputs.len(), 1);
assert_eq!(recipe.outputs[0].value, Amount::from(70));
}
#[test]
fn excess_below_output_overhead_cannot_be_balanced() {
let cm = TransactionCostModel::new(10, 20);
let err = balance_test(
vec![coin(NATIVE, 115)],
Imbalances::from_entry(native(), -100),
cm,
)
.unwrap_err();
assert!(matches!(err, WalletError::InsufficientFunds { .. }));
}
#[test]
fn ts_does_not_overspend_coins() {
let cm = TransactionCostModel::new(19_314, 19_708);
let coins = vec![coin(NATIVE, 10_000_000), coin(NATIVE, 10_000_000)];
let recipe = balance_test(coins, Imbalances::from_entry(native(), -1_000_000), cm).unwrap();
assert_eq!(recipe.inputs.len(), 1);
assert_eq!(recipe.outputs.len(), 1);
}
#[test]
fn ts_balance_custom_token() {
let custom = TokenType::new("custom");
let cm = TransactionCostModel::new(19_314, 19_708);
let coins = vec![
coin(NATIVE, 100_000_000),
SimpleCoin::new(custom.clone(), 1),
SimpleCoin::new(custom.clone(), 2),
SimpleCoin::new(custom.clone(), 3),
];
let recipe = balance_test(coins, Imbalances::from_entry(custom, -1), cm).unwrap();
assert_eq!(recipe.inputs.len(), 2);
assert_eq!(recipe.outputs.len(), 1);
}
#[test]
fn ts_balance_multiple_token_types() {
let custom = TokenType::new("custom");
let cm = TransactionCostModel::new(19_314, 19_708);
let coins = vec![
coin(NATIVE, 10_000_000),
coin(NATIVE, 20_000_000),
coin(NATIVE, 30_000_000),
SimpleCoin::new(custom.clone(), 1),
SimpleCoin::new(custom.clone(), 2),
SimpleCoin::new(custom.clone(), 3),
];
let initial = Imbalances::from_entries([
(custom.clone(), -4),
(native(), -5_000_000),
(native(), -1_000_000),
(custom.clone(), -1),
]);
let recipe = balance_test(coins, initial, cm).unwrap();
assert_eq!(recipe.inputs.len(), 4);
assert_eq!(recipe.outputs.len(), 2);
}
#[test]
fn ts_fail_when_not_enough_for_fees() {
let cm = TransactionCostModel::new(19_314, 19_708);
let err = balance_test(
vec![coin(NATIVE, 1_000_000)],
Imbalances::from_entry(native(), -1_000_000),
cm,
)
.unwrap_err();
match err {
WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
other => panic!("wrong error: {other:?}"),
}
}
#[test]
fn ts_fail_when_change_smaller_than_output_fee() {
let cm = TransactionCostModel::new(19_314, 19_708);
let coin_val = cm.input_fee_overhead + Amount::from(5);
let deficit = -(Amount::from(5) + cm.output_fee_overhead);
let err = balance_test(
vec![coin(NATIVE, coin_val)],
Imbalances::from_entry(native(), deficit),
cm,
)
.unwrap_err();
assert!(matches!(err, WalletError::InsufficientFunds { .. }));
}
#[test]
fn ts_uses_provided_coin_selection() {
struct LargestFirst;
impl<T: CoinRecipe> CoinSelector<T> for LargestFirst {
fn select(
&self,
coins: &[T],
token: &TokenType,
_: Amount,
_: &TransactionCostModel,
) -> Option<usize> {
coins
.iter()
.enumerate()
.filter(|(_, c)| c.token_type() == token)
.max_by_key(|(_, c)| c.value())
.map(|(i, _)| i)
}
}
let cm = TransactionCostModel::ZERO;
let coins = vec![coin(NATIVE, 5), coin(NATIVE, 50), coin(NATIVE, 100)];
let recipe = balance(BalanceRequest {
coins,
initial_imbalances: Imbalances::from_entry(native(), -40),
target_imbalances: Imbalances::new(),
cost_model: cm,
fee_token: native(),
selector: &LargestFirst,
create_output: |r| SimpleCoin::new(r.token_type, r.value),
is_coin_equal: |a, b| a == b,
})
.unwrap();
assert_eq!(recipe.inputs.len(), 1);
assert_eq!(
recipe.inputs[0].value,
Amount::from(100),
"largest-first should pick 100"
);
assert_eq!(recipe.outputs.len(), 1);
assert_eq!(recipe.outputs[0].value, Amount::from(60));
}
#[test]
fn ts_reaches_target_imbalances() {
let custom = TokenType::new("custom");
let cm = TransactionCostModel::ZERO;
let recipe = balance(BalanceRequest {
coins: vec![SimpleCoin::new(custom.clone(), 7)],
initial_imbalances: Imbalances::new(),
target_imbalances: Imbalances::from_entry(custom.clone(), 7),
cost_model: cm,
fee_token: native(),
selector: &SmallestFirstSelector,
create_output: |r| SimpleCoin::new(r.token_type, r.value),
is_coin_equal: |a, b| a == b,
})
.unwrap();
assert_eq!(recipe.inputs.len(), 1);
assert_eq!(recipe.outputs, [] as [SimpleCoin; 0]);
}
#[test]
fn ts_errors_when_cannot_meet_target() {
let unobtainium = TokenType::new("unobtainium");
let cm = TransactionCostModel::ZERO;
let err = balance(BalanceRequest {
coins: vec![coin(NATIVE, 1_000_000)],
initial_imbalances: Imbalances::new(),
target_imbalances: Imbalances::from_entry(unobtainium.clone(), 1),
cost_model: cm,
fee_token: native(),
selector: &SmallestFirstSelector,
create_output: |r| SimpleCoin::new(r.token_type, r.value),
is_coin_equal: |a, b| a == b,
})
.unwrap_err();
match err {
WalletError::InsufficientFunds { token } => {
assert_eq!(token, unobtainium.as_str());
}
other => panic!("wrong error: {other:?}"),
}
}
#[test]
fn invariant_inputs_subset_of_candidate_pool() {
let cm = TransactionCostModel::ZERO;
let pool: Vec<SimpleCoin> = (1..=10).map(|v| coin(NATIVE, v * 10)).collect();
let recipe = balance_test(pool.clone(), Imbalances::from_entry(native(), -55), cm).unwrap();
for inp in &recipe.inputs {
assert!(
pool.contains(inp),
"input {inp:?} not in original candidate pool"
);
}
}
#[test]
fn invariant_non_fee_targets_met_exactly() {
let custom_a = TokenType::new("custom_a");
let custom_b = TokenType::new("custom_b");
let cm = TransactionCostModel::ZERO;
let coins = vec![
SimpleCoin::new(custom_a.clone(), 100),
SimpleCoin::new(custom_b.clone(), 50),
SimpleCoin::new(custom_b.clone(), 50),
coin(NATIVE, 1_000),
];
let target = Imbalances::from_entries([(custom_a.clone(), 30), (custom_b.clone(), 25)]);
let recipe = balance(BalanceRequest {
coins,
initial_imbalances: Imbalances::new(),
target_imbalances: target.clone(),
cost_model: cm,
fee_token: native(),
selector: &SmallestFirstSelector,
create_output: |r| SimpleCoin::new(r.token_type, r.value),
is_coin_equal: |a, b| a == b,
})
.unwrap();
let mut net = Imbalances::new();
for c in &recipe.inputs {
net.set(c.token_type.clone(), net.get(&c.token_type) + c.value);
}
for c in &recipe.outputs {
net.set(c.token_type.clone(), net.get(&c.token_type) - c.value);
}
for (token, expected) in target.iter() {
assert_eq!(net.get(token), expected, "token {token:?}: target not met");
}
}
}