use indexmap::IndexMap;
use crate::types::TokenType;
use crate::unshielded::state::{UnshieldedState, UtxoWithMeta};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BalanceSummary {
pub available: u128,
pub pending: u128,
}
impl BalanceSummary {
#[inline]
#[must_use]
pub fn total(self) -> u128 {
self.available.saturating_add(self.pending)
}
}
#[must_use]
pub fn sum_by_token<'a>(
utxos: impl IntoIterator<Item = &'a UtxoWithMeta>,
token: &TokenType,
) -> u128 {
utxos
.into_iter()
.filter(|u| u.utxo.token_type == *token)
.fold(0u128, |acc, u| acc.saturating_add(u.utxo.value))
}
pub fn filter_by_token<'a>(
utxos: impl IntoIterator<Item = &'a UtxoWithMeta>,
token: &'a TokenType,
) -> impl Iterator<Item = &'a UtxoWithMeta> {
utxos
.into_iter()
.filter(move |u| u.utxo.token_type == *token)
}
impl UnshieldedState {
#[must_use]
pub fn available_balance(&self, token: &TokenType) -> u128 {
sum_by_token(self.available(), token)
}
#[must_use]
pub fn pending_balance(&self, token: &TokenType) -> u128 {
sum_by_token(self.pending(), token)
}
#[must_use]
pub fn balance_for(&self, token: &TokenType) -> BalanceSummary {
BalanceSummary {
available: self.available_balance(token),
pending: self.pending_balance(token),
}
}
#[must_use]
pub fn balances(&self) -> IndexMap<TokenType, BalanceSummary> {
let mut out: IndexMap<TokenType, BalanceSummary> = IndexMap::new();
for u in self.available() {
out.entry(u.utxo.token_type.clone()).or_default().available = out
.get(&u.utxo.token_type)
.map_or(0u128, |s| s.available)
.saturating_add(u.utxo.value);
}
for u in self.pending() {
out.entry(u.utxo.token_type.clone()).or_default().pending = out
.get(&u.utxo.token_type)
.map_or(0u128, |s| s.pending)
.saturating_add(u.utxo.value);
}
out
}
pub fn available_of_token<'a>(
&'a self,
token: &'a TokenType,
) -> impl Iterator<Item = &'a UtxoWithMeta> {
filter_by_token(self.available(), token)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::unshielded::state::{
UnshieldedUpdate, UnshieldedUtxo, UtxoId, UtxoMeta, UtxoWithMeta,
};
fn tok(s: &str) -> TokenType {
TokenType::new(s)
}
fn utxo(token: &str, value: u128, byte: u8) -> UtxoWithMeta {
UtxoWithMeta::new(
UnshieldedUtxo::new(
UtxoId::new([byte; 32], u32::from(byte)),
value,
tok(token),
[byte; 32],
),
UtxoMeta::new(0, false),
)
}
#[allow(clippy::needless_pass_by_value)] fn seed_state(available: Vec<UtxoWithMeta>, pending: Vec<UtxoWithMeta>) -> UnshieldedState {
let mut s = UnshieldedState::empty();
if !available.is_empty() {
s = s
.apply_update(&UnshieldedUpdate::success(available.clone(), vec![]))
.unwrap();
}
for p in &pending {
s = s
.apply_update(&UnshieldedUpdate::success(vec![p.clone()], vec![]))
.unwrap();
s = s.spend(p).unwrap();
}
s
}
#[test]
fn empty_state_has_zero_balance() {
let s = UnshieldedState::empty();
assert_eq!(s.available_balance(&tok("native")), 0);
assert_eq!(s.pending_balance(&tok("native")), 0);
}
#[test]
fn sums_available_by_token() {
let s = seed_state(
vec![
utxo("native", 100, 1),
utxo("native", 250, 2),
utxo("custom", 50, 3),
],
vec![],
);
assert_eq!(s.available_balance(&tok("native")), 350);
assert_eq!(s.available_balance(&tok("custom")), 50);
assert_eq!(s.available_balance(&tok("unknown")), 0);
}
#[test]
fn sums_pending_separately_from_available() {
let s = seed_state(
vec![utxo("native", 100, 1)],
vec![utxo("native", 10, 2), utxo("native", 20, 3)],
);
assert_eq!(s.available_balance(&tok("native")), 100);
assert_eq!(s.pending_balance(&tok("native")), 30);
}
#[test]
fn balance_for_pairs_available_and_pending() {
let s = seed_state(vec![utxo("native", 100, 1)], vec![utxo("native", 25, 2)]);
let summary = s.balance_for(&tok("native"));
assert_eq!(summary.available, 100);
assert_eq!(summary.pending, 25);
assert_eq!(summary.total(), 125);
}
#[test]
fn balances_map_covers_all_tokens_deterministically() {
let s = seed_state(
vec![
utxo("native", 100, 1),
utxo("custom", 50, 2),
utxo("native", 200, 3),
],
vec![utxo("third", 7, 4)],
);
let all = s.balances();
assert_eq!(all.get(&tok("native")).unwrap().available, 300);
assert_eq!(all.get(&tok("native")).unwrap().pending, 0);
assert_eq!(all.get(&tok("custom")).unwrap().available, 50);
assert_eq!(all.get(&tok("third")).unwrap().pending, 7);
}
#[test]
fn available_of_token_respects_insertion_order() {
let s = seed_state(
vec![
utxo("native", 100, 1),
utxo("custom", 50, 2),
utxo("native", 200, 3),
utxo("custom", 25, 4),
],
vec![],
);
let native = tok("native");
let natives: Vec<_> = s.available_of_token(&native).collect();
assert_eq!(natives.len(), 2);
assert_eq!(natives[0].utxo.value, 100);
assert_eq!(natives[1].utxo.value, 200);
}
#[test]
fn balance_total_saturates_on_overflow() {
let s = BalanceSummary {
available: u128::MAX,
pending: 1,
};
assert_eq!(s.total(), u128::MAX);
}
}