use crate::balancer::{balance, BalanceRequest, FewestCoinsSelector, Imbalances};
use crate::error::{Result, WalletError};
use crate::types::{Amount, CoinRecipe, TokenType, TransactionCostModel};
use crate::unshielded::state::{UnshieldedState, UtxoWithMeta};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnshieldedTransfer {
pub amount: u128,
pub token_type: TokenType,
pub recipient: [u8; 32],
}
impl UnshieldedTransfer {
#[inline]
#[must_use]
pub fn new(amount: u128, token_type: TokenType, recipient: [u8; 32]) -> Self {
Self {
amount,
token_type,
recipient,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnshieldedOutputSpec {
pub value: u128,
pub token_type: TokenType,
pub owner: [u8; 32],
}
impl UnshieldedOutputSpec {
#[inline]
#[must_use]
pub fn new(value: u128, token_type: TokenType, owner: [u8; 32]) -> Self {
Self {
value,
token_type,
owner,
}
}
}
impl CoinRecipe for UnshieldedOutputSpec {
#[inline]
fn token_type(&self) -> &TokenType {
&self.token_type
}
#[inline]
fn value(&self) -> Amount {
Amount::from(self.value)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransferRecipe {
pub inputs: Vec<UtxoWithMeta>,
pub recipient_outputs: Vec<UnshieldedOutputSpec>,
pub change_outputs: Vec<UnshieldedOutputSpec>,
}
impl TransferRecipe {
#[must_use]
pub fn all_outputs(&self) -> Vec<&UnshieldedOutputSpec> {
let mut out = Vec::with_capacity(self.recipient_outputs.len() + self.change_outputs.len());
for o in &self.recipient_outputs {
out.push(o);
}
for o in &self.change_outputs {
out.push(o);
}
out
}
#[inline]
#[must_use]
pub fn total_output_count(&self) -> usize {
self.recipient_outputs.len() + self.change_outputs.len()
}
}
fn initial_imbalances(
transfers: &[UnshieldedTransfer],
fee_token: &TokenType,
cost_model: &TransactionCostModel,
) -> Result<Imbalances> {
let mut initial = Imbalances::new();
for t in transfers {
let amount = Amount::from(t.amount);
let cur = initial.get(&t.token_type);
initial.set(
t.token_type.clone(),
cur.checked_sub(amount).ok_or(WalletError::AmountOverflow)?,
);
if t.token_type != *fee_token {
let cur_fee = initial.get(fee_token);
initial.set(
fee_token.clone(),
cur_fee
.checked_sub(cost_model.output_fee_overhead)
.ok_or(WalletError::AmountOverflow)?,
);
}
}
Ok(initial)
}
pub fn build_transfer_recipe(
state: &UnshieldedState,
sender_address: [u8; 32],
transfers: &[UnshieldedTransfer],
fee_token: TokenType,
cost_model: TransactionCostModel,
) -> Result<TransferRecipe> {
let recipient_outputs: Vec<UnshieldedOutputSpec> = transfers
.iter()
.map(|t| UnshieldedOutputSpec::new(t.amount, t.token_type.clone(), t.recipient))
.collect();
let initial = initial_imbalances(transfers, &fee_token, &cost_model)?;
let coins: Vec<UtxoWithMeta> = state.available().cloned().collect();
let change_owner = sender_address;
let br = balance(BalanceRequest {
coins,
initial_imbalances: initial,
target_imbalances: Imbalances::new(),
cost_model,
fee_token,
selector: &FewestCoinsSelector,
create_output: move |r| {
let v = u128::try_from(r.value.max(Amount::ZERO)).unwrap_or(0);
UnshieldedOutputSpec::new(v, r.token_type, change_owner)
},
is_coin_equal: |a, b| a.id() == b.id(),
})?;
Ok(TransferRecipe {
inputs: br.inputs,
recipient_outputs,
change_outputs: br.outputs,
})
}
pub fn build_init_swap_recipe(
state: &UnshieldedState,
sender_address: [u8; 32],
desired_inputs: &[(TokenType, u128)],
desired_outputs: &[UnshieldedTransfer],
fee_token: TokenType,
cost_model: TransactionCostModel,
) -> Result<TransferRecipe> {
use crate::balancer::OutputRecipe;
if desired_inputs.is_empty() && desired_outputs.is_empty() {
return Err(WalletError::SigningFailed(
"initSwap requires at least one input or output".to_owned(),
));
}
for (_, amount) in desired_inputs {
if *amount == 0 {
return Err(WalletError::SigningFailed(
"initSwap input amount must be positive".to_owned(),
));
}
}
for t in desired_outputs {
if t.amount == 0 {
return Err(WalletError::SigningFailed(
"initSwap output amount must be positive".to_owned(),
));
}
}
let recipient_outputs: Vec<UnshieldedOutputSpec> = desired_outputs
.iter()
.map(|t| UnshieldedOutputSpec::new(t.amount, t.token_type.clone(), t.recipient))
.collect();
let target = Imbalances::from_entries(
desired_inputs
.iter()
.map(|(t, v)| (t.clone(), Amount::from(*v))),
);
let coins: Vec<UtxoWithMeta> = state.available().cloned().collect();
let change_owner = sender_address;
let br = balance(BalanceRequest {
coins,
initial_imbalances: Imbalances::new(),
target_imbalances: target,
cost_model,
fee_token,
selector: &FewestCoinsSelector,
create_output: move |r: OutputRecipe| {
let v = u128::try_from(r.value.max(Amount::ZERO)).unwrap_or(0);
UnshieldedOutputSpec::new(v, r.token_type, change_owner)
},
is_coin_equal: |a, b| a.id() == b.id(),
})?;
Ok(TransferRecipe {
inputs: br.inputs,
recipient_outputs,
change_outputs: br.outputs,
})
}
pub fn build_balancing_recipe(
state: &UnshieldedState,
owner: [u8; 32],
imbalances: Imbalances,
) -> Result<TransferRecipe> {
let coins: Vec<UtxoWithMeta> = state.available().cloned().collect();
let br = balance(BalanceRequest {
coins,
initial_imbalances: imbalances,
target_imbalances: Imbalances::new(),
cost_model: TransactionCostModel::ZERO,
fee_token: TokenType::new("native"),
selector: &FewestCoinsSelector,
create_output: move |r| {
let v = u128::try_from(r.value.max(Amount::ZERO)).unwrap_or(0);
UnshieldedOutputSpec::new(v, r.token_type, owner)
},
is_coin_equal: |a, b| a.id() == b.id(),
})?;
Ok(TransferRecipe {
inputs: br.inputs,
recipient_outputs: Vec::new(),
change_outputs: br.outputs,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::unshielded::state::{UnshieldedUpdate, UnshieldedUtxo, UtxoId, UtxoMeta};
const NATIVE: &str = "native";
const CUSTOM: &str = "custom";
const SENDER: [u8; 32] = [0xAA; 32];
const RECIPIENT: [u8; 32] = [0xBB; 32];
fn tok(s: &str) -> TokenType {
TokenType::new(s)
}
fn utxo(intent_byte: u8, output_no: u32, value: u128, tt: &str) -> UtxoWithMeta {
UtxoWithMeta::new(
UnshieldedUtxo::new(
UtxoId::new([intent_byte; 32], output_no),
value,
tok(tt),
SENDER,
),
UtxoMeta::new(0, false),
)
}
fn seed(utxos: Vec<UtxoWithMeta>) -> UnshieldedState {
UnshieldedState::empty()
.apply_update(&UnshieldedUpdate::success(utxos, vec![]))
.unwrap()
}
fn cm() -> TransactionCostModel {
TransactionCostModel::new(1_000, 2_000)
}
#[test]
fn single_transfer_emits_recipient_output_and_pulls_inputs() {
let state = seed(vec![utxo(0x01, 0, 100_000, NATIVE)]);
let transfers = vec![UnshieldedTransfer::new(500, tok(NATIVE), RECIPIENT)];
let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
assert_eq!(r.inputs.len(), 1);
assert_eq!(r.recipient_outputs.len(), 1);
assert_eq!(r.recipient_outputs[0].value, 500);
assert_eq!(r.recipient_outputs[0].owner, RECIPIENT);
assert_eq!(r.change_outputs.len(), 1);
assert_eq!(r.change_outputs[0].owner, SENDER);
}
#[test]
fn non_fee_token_transfer_uses_two_inputs_one_for_fees() {
let state = seed(vec![
utxo(0x01, 0, 500, CUSTOM),
utxo(0x02, 0, 100_000, NATIVE),
]);
let transfers = vec![UnshieldedTransfer::new(500, tok(CUSTOM), RECIPIENT)];
let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
assert_eq!(r.inputs.len(), 2);
let input_tokens: Vec<_> = r.inputs.iter().map(|u| u.utxo.token_type.clone()).collect();
assert!(input_tokens.contains(&tok(CUSTOM)));
assert!(input_tokens.contains(&tok(NATIVE)));
assert_eq!(r.recipient_outputs.len(), 1);
assert_eq!(r.recipient_outputs[0].value, 500);
assert_eq!(r.recipient_outputs[0].token_type, tok(CUSTOM));
assert_eq!(r.recipient_outputs[0].owner, RECIPIENT);
assert_ne!(r.change_outputs, [] as [UnshieldedOutputSpec; 0]);
for c in &r.change_outputs {
assert_eq!(c.owner, SENDER);
}
}
#[test]
fn multi_token_transfer_emits_one_recipient_output_per_transfer() {
let state = seed(vec![
utxo(0x01, 0, 500, CUSTOM),
utxo(0x02, 0, 100_000, NATIVE),
]);
let transfers = vec![
UnshieldedTransfer::new(500, tok(CUSTOM), RECIPIENT),
UnshieldedTransfer::new(1_234, tok(NATIVE), [0xCC; 32]),
];
let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
assert_eq!(r.recipient_outputs.len(), 2);
assert_eq!(r.recipient_outputs[0].value, 500);
assert_eq!(r.recipient_outputs[0].token_type, tok(CUSTOM));
assert_eq!(r.recipient_outputs[0].owner, RECIPIENT);
assert_eq!(r.recipient_outputs[1].value, 1_234);
assert_eq!(r.recipient_outputs[1].token_type, tok(NATIVE));
assert_eq!(r.recipient_outputs[1].owner, [0xCC; 32]);
}
#[test]
fn insufficient_fee_token_errors_with_correct_token() {
let state = seed(vec![utxo(0x01, 0, 500, CUSTOM)]);
let transfers = vec![UnshieldedTransfer::new(500, tok(CUSTOM), RECIPIENT)];
let err = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap_err();
match err {
WalletError::InsufficientFunds { token } => assert_eq!(token, NATIVE),
other => panic!("unexpected error: {other:?}"),
}
}
#[test]
fn insufficient_target_token_errors() {
let state = seed(vec![utxo(0x01, 0, 100_000, NATIVE)]);
let transfers = vec![UnshieldedTransfer::new(1, tok(CUSTOM), RECIPIENT)];
let err = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap_err();
match err {
WalletError::InsufficientFunds { token } => assert_eq!(token, CUSTOM),
other => panic!("unexpected error: {other:?}"),
}
}
#[test]
fn empty_transfer_list_produces_empty_recipe() {
let state = seed(vec![utxo(0x01, 0, 100_000, NATIVE)]);
let r = build_transfer_recipe(&state, SENDER, &[], tok(NATIVE), cm()).unwrap();
assert_eq!(r.inputs, [] as [UtxoWithMeta; 0]);
assert_eq!(r.recipient_outputs, [] as [UnshieldedOutputSpec; 0]);
assert_eq!(r.change_outputs, [] as [UnshieldedOutputSpec; 0]);
}
#[test]
fn inputs_are_subset_of_wallet_available() {
let state = seed(vec![
utxo(0x01, 0, 1_000, NATIVE),
utxo(0x02, 0, 2_000, NATIVE),
utxo(0x03, 0, 50_000, NATIVE),
]);
let transfers = vec![UnshieldedTransfer::new(500, tok(NATIVE), RECIPIENT)];
let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
for inp in &r.inputs {
assert!(state.has_available(&inp.id()));
}
}
#[test]
fn change_outputs_always_go_to_sender() {
let state = seed(vec![utxo(0x01, 0, 1_000_000, NATIVE)]);
let transfers = vec![UnshieldedTransfer::new(123, tok(NATIVE), RECIPIENT)];
let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
for c in &r.change_outputs {
assert_eq!(c.owner, SENDER, "change must always route back to sender");
}
}
#[test]
fn all_outputs_iter_returns_recipient_outputs_first_then_change() {
let state = seed(vec![utxo(0x01, 0, 1_000_000, NATIVE)]);
let transfers = vec![UnshieldedTransfer::new(123, tok(NATIVE), RECIPIENT)];
let r = build_transfer_recipe(&state, SENDER, &transfers, tok(NATIVE), cm()).unwrap();
let all = r.all_outputs();
assert_eq!(all.len(), r.total_output_count());
assert_eq!(
all.len(),
r.recipient_outputs.len() + r.change_outputs.len()
);
for (i, ro) in r.recipient_outputs.iter().enumerate() {
assert_eq!(all[i], ro);
}
}
#[test]
fn initial_imbalances_handles_fee_token_transfer() {
let cm = TransactionCostModel::new(100, 200);
let transfers = vec![UnshieldedTransfer::new(1_000, tok(NATIVE), RECIPIENT)];
let got = initial_imbalances(&transfers, &tok(NATIVE), &cm).unwrap();
assert_eq!(got.get(&tok(NATIVE)), Amount::from(-1_000));
}
#[test]
fn initial_imbalances_handles_non_fee_token_transfer() {
let cm = TransactionCostModel::new(100, 200);
let transfers = vec![UnshieldedTransfer::new(1_000, tok(CUSTOM), RECIPIENT)];
let got = initial_imbalances(&transfers, &tok(NATIVE), &cm).unwrap();
assert_eq!(got.get(&tok(CUSTOM)), Amount::from(-1_000));
assert_eq!(got.get(&tok(NATIVE)), Amount::from(-200));
}
#[test]
fn initial_imbalances_accumulates_across_transfers() {
let cm = TransactionCostModel::new(100, 200);
let transfers = vec![
UnshieldedTransfer::new(500, tok(CUSTOM), RECIPIENT),
UnshieldedTransfer::new(700, tok(CUSTOM), RECIPIENT),
UnshieldedTransfer::new(300, tok(NATIVE), RECIPIENT),
];
let got = initial_imbalances(&transfers, &tok(NATIVE), &cm).unwrap();
assert_eq!(got.get(&tok(CUSTOM)), Amount::from(-1_200));
assert_eq!(got.get(&tok(NATIVE)), Amount::from(-300 - 200 - 200));
}
#[test]
fn initial_imbalances_lifts_full_u128_range() {
let cm = TransactionCostModel::new(100, 200);
let transfers = vec![UnshieldedTransfer::new(u128::MAX, tok(CUSTOM), RECIPIENT)];
let got = initial_imbalances(&transfers, &tok(NATIVE), &cm).unwrap();
assert_eq!(got.get(&tok(CUSTOM)), -Amount::from(u128::MAX));
assert_eq!(got.get(&tok(NATIVE)), Amount::from(-200));
}
#[test]
fn init_swap_pulls_input_for_target_imbalance() {
let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
let r = build_init_swap_recipe(
&state,
SENDER,
&[(tok(NATIVE), 30)],
&[],
tok(NATIVE),
TransactionCostModel::ZERO,
)
.unwrap();
assert_eq!(r.inputs.len(), 1);
let total_change: u128 = r.change_outputs.iter().map(|c| c.value).sum();
assert_eq!(total_change, 70);
assert_eq!(r.recipient_outputs, [] as [UnshieldedOutputSpec; 0]);
}
#[test]
fn init_swap_with_outputs_routes_recipients_too() {
let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
let r = build_init_swap_recipe(
&state,
SENDER,
&[(tok(NATIVE), 20)],
&[UnshieldedTransfer::new(10, tok(NATIVE), RECIPIENT)],
tok(NATIVE),
TransactionCostModel::ZERO,
)
.unwrap();
assert_eq!(r.inputs.len(), 1);
assert_eq!(r.recipient_outputs.len(), 1);
assert_eq!(r.recipient_outputs[0].value, 10);
assert_eq!(r.recipient_outputs[0].owner, RECIPIENT);
let change: u128 = r.change_outputs.iter().map(|c| c.value).sum();
assert_eq!(change, 80); }
#[test]
fn init_swap_with_only_outputs_spends_nothing() {
let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
let r = build_init_swap_recipe(
&state,
SENDER,
&[],
&[UnshieldedTransfer::new(10, tok(NATIVE), RECIPIENT)],
tok(NATIVE),
TransactionCostModel::ZERO,
)
.unwrap();
assert_eq!(r.inputs, [] as [UtxoWithMeta; 0]);
assert_eq!(r.change_outputs, [] as [UnshieldedOutputSpec; 0]);
assert_eq!(r.recipient_outputs.len(), 1);
}
#[test]
fn init_swap_rejects_zero_amounts() {
let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
let err = build_init_swap_recipe(
&state,
SENDER,
&[(tok(NATIVE), 0)],
&[],
tok(NATIVE),
TransactionCostModel::ZERO,
)
.unwrap_err();
assert!(matches!(err, WalletError::SigningFailed(_)));
}
#[test]
fn init_swap_rejects_empty_request() {
let state = seed(vec![utxo(0x01, 0, 100, NATIVE)]);
let err = build_init_swap_recipe(
&state,
SENDER,
&[],
&[],
tok(NATIVE),
TransactionCostModel::ZERO,
)
.unwrap_err();
assert!(matches!(err, WalletError::SigningFailed(_)));
}
}