use std::collections::BTreeMap;
use moonproof_ledger::coin_structure::coin::{ShieldedTokenType, TokenType};
use moonproof_ledger::ledger::structure::Transaction;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_ledger::zswap::keys::SecretKeys as ZswapSecretKeys;
use rand::{CryptoRng, Rng};
use crate::balancer::{balance, BalanceRequest, Imbalances, SmallestFirstSelector};
use crate::error::{Result, WalletError};
use crate::shielded::ledger_adapter::{build_shielded_offer, ShieldedSignedTransaction};
use crate::shielded::state::ShieldedState;
use crate::shielded::transacting::{
candidate_inputs as shielded_candidate_inputs,
token_type_from_wallet_string as shielded_token_type_from_wallet_string,
token_type_to_wallet_string as shielded_token_type_to_wallet_string, ShieldedOutputSpec,
ShieldedTransferRecipe, SHIELDED_COST_MODEL,
};
use crate::types::{Amount, TokenType as WalletTokenType};
pub fn balance_contract_call_tx<R>(
rng: &mut R,
state: ShieldedState,
secret_keys: &ZswapSecretKeys,
tx: ShieldedSignedTransaction,
network_id: &str,
) -> Result<(ShieldedSignedTransaction, ShieldedState)>
where
R: Rng + CryptoRng,
{
let raw_imbalances = tx.balance(None).map_err(|e| {
WalletError::ShieldedOffer(format!(
"Transaction::balance failed while reading shielded imbalances: {e:?}"
))
})?;
let (balancing, state) =
build_shielded_balancing_tx(rng, state, secret_keys, &raw_imbalances, network_id)?;
let Some(balancing) = balancing else {
return Ok((tx, state));
};
let tx = tx.merge(&balancing).map_err(|e| {
WalletError::ShieldedOffer(format!(
"Transaction::merge of the shielded balancing tx failed: {e:?}"
))
})?;
Ok((tx, state))
}
pub fn build_shielded_balancing_tx<R>(
rng: &mut R,
state: ShieldedState,
secret_keys: &ZswapSecretKeys,
imbalances: &BTreeMap<(TokenType, u16), i128>,
network_id: &str,
) -> Result<(Option<ShieldedSignedTransaction>, ShieldedState)>
where
R: Rng + CryptoRng,
{
let mut by_segment = group_shielded_imbalances_by_segment(imbalances);
if by_segment.is_empty() {
return Ok((None, state));
}
by_segment.sort_by_key(|(segment, _)| (*segment == 0, *segment));
let mut state = state;
let mut guaranteed = None;
let mut fallible: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
for (segment, segment_imbalances) in by_segment {
let candidate_pool = shielded_candidate_inputs(&state, secret_keys);
let our_coin_pk = crate::address::ShieldedCoinPublicKey(state.coin_public_key().0 .0);
let our_enc_pk_bytes = encode_enc_pk(&state.encryption_public_key())?;
let our_enc_pk = crate::address::ShieldedEncryptionPublicKey(our_enc_pk_bytes);
let placeholder_fee_token = WalletTokenType::new("shielded-fee-placeholder");
let recipe = balance(BalanceRequest {
coins: candidate_pool,
initial_imbalances: segment_imbalances,
target_imbalances: Imbalances::new(),
cost_model: SHIELDED_COST_MODEL,
fee_token: placeholder_fee_token,
selector: &SmallestFirstSelector,
create_output: |r| {
let value = u128::try_from(r.value.max(Amount::ZERO)).unwrap_or(0);
let tt = shielded_token_type_from_wallet_string(&r.token_type).unwrap_or(
ShieldedTokenType(moonproof_ledger::transient_crypto::hash::HashOutput(
[0u8; 32],
)),
);
let coin = moonproof_ledger::coin_structure::coin::Info::new(rng, value, tt);
ShieldedOutputSpec::new(coin, our_coin_pk.clone(), our_enc_pk.clone())
},
is_coin_equal: |a, b| a.qci.nonce == b.qci.nonce,
})?;
let transfer_recipe = ShieldedTransferRecipe {
inputs: recipe.inputs.into_iter().map(|c| c.qci).collect(),
recipient_outputs: Vec::new(),
change_outputs: recipe.outputs,
};
let materialized =
build_shielded_offer(rng, state.clone(), secret_keys, &transfer_recipe, segment)?;
let Some((offer, next_state)) = materialized else {
continue;
};
state = next_state;
if segment == 0 {
guaranteed = Some(offer);
} else {
fallible = fallible.insert(segment, offer);
}
}
if guaranteed.is_none() && fallible.size() == 0 {
return Ok((None, state));
}
let intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
let balancing: ShieldedSignedTransaction =
Transaction::new(network_id, intents, guaranteed, fallible);
Ok((Some(balancing), state))
}
fn group_shielded_imbalances_by_segment(
raw: &BTreeMap<(TokenType, u16), i128>,
) -> Vec<(u16, Imbalances)> {
let mut by_segment: BTreeMap<u16, Imbalances> = BTreeMap::new();
for ((token, segment), value) in raw {
if *value == 0 {
continue;
}
let TokenType::Shielded(stt) = token else {
continue;
};
let wallet_token = shielded_token_type_to_wallet_string(stt);
let amount = Amount::from(*value);
let imb = by_segment.entry(*segment).or_default();
let existing = imb.get(&wallet_token);
imb.set(wallet_token, existing + amount);
}
by_segment.into_iter().collect()
}
fn encode_enc_pk(
pk: &moonproof_ledger::transient_crypto::encryption::PublicKey,
) -> Result<[u8; 32]> {
use moonproof_ledger::serialize::Serializable;
let mut buf = Vec::with_capacity(32);
pk.serialize(&mut buf)
.map_err(|e| WalletError::Serialization(format!("encryption PublicKey::serialize: {e}")))?;
<[u8; 32]>::try_from(buf.as_slice()).map_err(|_| {
WalletError::Serialization(format!(
"encryption PublicKey serialized to {} bytes; expected 32",
buf.len()
))
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::abstractions::NetworkId;
use moonproof_ledger::coin_structure::coin::{Info as CoinInfo, Nonce, ShieldedTokenType};
use moonproof_ledger::coin_structure::contract::ContractAddress;
use moonproof_ledger::transient_crypto::hash::HashOutput;
use moonproof_ledger::zswap::keys::Seed as ZswapSeed;
use moonproof_ledger::zswap::Output as ZswapOutput;
use rand::rngs::StdRng;
use rand::SeedableRng;
fn keys_from_byte(b: u8) -> ZswapSecretKeys {
ZswapSecretKeys::from(ZswapSeed::from([b; 32]))
}
fn night_token() -> ShieldedTokenType {
ShieldedTokenType(HashOutput([0u8; 32]))
}
fn dummy_contract() -> ContractAddress {
ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput([0xCC; 32]))
}
fn seed_state_with_coin(keys: &ZswapSecretKeys, value: u128, nonce_byte: u8) -> ShieldedState {
let mut local = moonproof_ledger::zswap::local::State::<InMemoryDB>::new();
let info = CoinInfo {
nonce: Nonce(HashOutput([nonce_byte; 32])),
type_: night_token(),
value,
};
local = local.insert_coin(keys, info).expect("insert_coin");
ShieldedState::init(local, keys, NetworkId::Undeployed)
}
fn unbalanced_deposit_tx(rng: &mut StdRng, value: u128) -> ShieldedSignedTransaction {
let coin = CoinInfo {
nonce: Nonce(HashOutput([0x77; 32])),
type_: night_token(),
value,
};
let out =
ZswapOutput::<_, InMemoryDB>::new_contract_owned(rng, &coin, Some(0), dummy_contract())
.expect("new_contract_owned");
let offer =
moonproof_ledger::zswap::Offer::<_, InMemoryDB>::new(Vec::new(), vec![out], Vec::new())
.expect("offer with one output");
let intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
Transaction::new("local-test", intents, Some(offer), StorageHashMap::new())
}
#[test]
fn balanced_input_returns_unchanged() {
let mut rng = StdRng::seed_from_u64(0xAA);
let keys = keys_from_byte(0x11);
let state = seed_state_with_coin(&keys, 1_000, 0x55);
let intents: StorageHashMap<u16, _, InMemoryDB> = StorageHashMap::new();
let tx: ShieldedSignedTransaction =
Transaction::new("local-test", intents, None, StorageHashMap::new());
let (out_tx, _next_state) =
balance_contract_call_tx(&mut rng, state, &keys, tx, "local-test").unwrap();
match &out_tx {
Transaction::Standard(stx) => {
assert!(stx.guaranteed_coins.is_none());
assert!(stx.fallible_coins.is_empty());
}
Transaction::ClaimRewards(_) => panic!("standard tx expected"),
}
}
#[test]
fn deposit_with_exact_value_balances_with_one_input_no_change() {
let mut rng = StdRng::seed_from_u64(0xBB);
let keys = keys_from_byte(0x22);
let state = seed_state_with_coin(&keys, 1_500, 0x33);
let tx = unbalanced_deposit_tx(&mut rng, 1_500);
let (balanced_tx, next_state) =
balance_contract_call_tx(&mut rng, state, &keys, tx, "local-test").unwrap();
let stx = match &balanced_tx {
Transaction::Standard(stx) => stx,
Transaction::ClaimRewards(_) => panic!("standard tx expected"),
};
let offer = stx
.guaranteed_coins
.as_ref()
.expect("merged tx must carry a guaranteed offer");
assert_eq!(offer.inputs.len(), 1, "exactly one wallet-side input");
assert_eq!(
offer.outputs.len(),
1,
"the contract-emitted output stays in the merged offer"
);
assert_eq!(
offer.transient.len(),
0,
"no co-located coin → no transient"
);
assert_eq!(
next_state.local().pending_spends.size(),
1,
"the spent coin lives in pending_spends until tx confirmation"
);
}
#[test]
fn deposit_with_larger_coin_emits_change_output() {
let mut rng = StdRng::seed_from_u64(0xCC);
let keys = keys_from_byte(0x44);
let state = seed_state_with_coin(&keys, 5_000, 0x66);
let tx = unbalanced_deposit_tx(&mut rng, 1_000);
let (balanced_tx, _next_state) =
balance_contract_call_tx(&mut rng, state, &keys, tx, "local-test").unwrap();
let stx = match &balanced_tx {
Transaction::Standard(stx) => stx,
Transaction::ClaimRewards(_) => panic!("standard tx expected"),
};
let offer = stx
.guaranteed_coins
.as_ref()
.expect("merged tx must carry a guaranteed offer");
assert_eq!(offer.inputs.len(), 1);
assert_eq!(
offer.outputs.len(),
2,
"contract output + wallet change output"
);
}
#[test]
fn deposit_with_no_coins_errors_insufficient_funds() {
let mut rng = StdRng::seed_from_u64(0xDD);
let keys = keys_from_byte(0x55);
let state = ShieldedState::init_empty(&keys, NetworkId::Undeployed);
let tx = unbalanced_deposit_tx(&mut rng, 1_000);
let err = balance_contract_call_tx(&mut rng, state, &keys, tx, "local-test").unwrap_err();
assert!(
matches!(err, WalletError::InsufficientFunds { .. }),
"expected InsufficientFunds, got: {err:?}"
);
}
}