fix: assert that Monero address pool sums to one

This commit is contained in:
Binarybaron 2025-06-25 19:42:55 +02:00
parent a48652328c
commit e73a418cd2
6 changed files with 26 additions and 7 deletions

View file

@ -1990,8 +1990,7 @@ mod tests {
// We check all but the last amount since the last one gets the remainder
let mut percentages_respected = true;
for i in 0..percentages.len() - 1 {
let expected_amount =
((balance.as_pico() as f64) * percentages[i]).floor() as u64;
let expected_amount = ((balance.as_pico() as f64) * percentages[i]).floor() as u64;
if amounts[i].as_pico() != expected_amount {
percentages_respected = false;
break;

View file

@ -55,7 +55,7 @@ export default function XmrRedeemInMempoolPage(
color: theme.palette.text.primary,
})}
>
{pool.label} ({pool.percentage}%)
{pool.label} ({pool.percentage * 100}%)
</Typography>
</Box>
<Typography

View file

@ -133,7 +133,7 @@ export default function HistoryRowExpanded({
color: theme.palette.text.primary,
})}
>
{pool.label} ({pool.percentage}%)
{pool.label} ({pool.percentage * 100}%)
</Typography>
<Typography
variant="caption"

View file

@ -186,12 +186,12 @@ export async function buyXmr(
address_pool.push(
{
address: monero_receive_address,
percentage: 100 - donation_percentage * 100,
percentage: 1 - donation_percentage,
label: "Your wallet",
},
{
address: donation_address,
percentage: donation_percentage * 100,
percentage: donation_percentage,
label: "Tip to the developers",
},
);

View file

@ -598,6 +598,7 @@ pub async fn buy_xmr(
} = buy_xmr;
monero_receive_pool.assert_network(context.config.env_config.monero_network)?;
monero_receive_pool.assert_sum_to_one()?;
let bitcoin_wallet = Arc::clone(
context

View file

@ -343,6 +343,23 @@ impl MoneroAddressPool {
Ok(())
}
/// Assert that the sum of the percentages in the address pool is 1 (allowing for a small tolerance)
pub fn assert_sum_to_one(&self) -> Result<()> {
let sum = self
.0
.iter()
.map(|address| address.percentage())
.sum::<Decimal>();
const TOLERANCE: f64 = 1e-6;
if (sum - Decimal::ONE).abs() > Decimal::from_f64(TOLERANCE).unwrap() {
bail!("Address pool percentages do not sum to 1");
}
Ok(())
}
}
impl From<::monero::Address> for MoneroAddressPool {
@ -907,7 +924,9 @@ mod tests {
assert!(LabeledMoneroAddress::new(address, Decimal::ZERO, "test".to_string()).is_ok());
assert!(LabeledMoneroAddress::new(address, Decimal::ONE, "test".to_string()).is_ok());
assert!(LabeledMoneroAddress::new(address, Decimal::new(5, 1), "test".to_string()).is_ok()); // 0.5
assert!(LabeledMoneroAddress::new(address, Decimal::new(9925, 4), "test".to_string()).is_ok()); // 0.9925
assert!(
LabeledMoneroAddress::new(address, Decimal::new(9925, 4), "test".to_string()).is_ok()
); // 0.9925
// Invalid percentages should fail
assert!(