deal with the pow error during stake adjustment

This commit is contained in:
Jędrzej Stuczyński
2023-11-24 09:40:17 +00:00
parent 4c8fa74dfe
commit d92c8c4149
2 changed files with 12 additions and 14 deletions
@@ -3,6 +3,7 @@
use cosmwasm_schema::cw_serde;
use cosmwasm_std::Decimal;
use cosmwasm_std::OverflowError;
use cosmwasm_std::Uint128;
use serde::de::Error;
use serde::{Deserialize, Deserializer};
@@ -72,19 +73,8 @@ impl Percent {
truncate_decimal(hundred * self.0).u128() as u8
}
pub fn pow(&self, exp: u32) -> Self {
match self.0.checked_pow(exp) {
Ok(res) => Percent(res),
Err(_overflow) => {
// since the percent is meant to always be less than 1, this should NEVER hapen, however,
// when the inevitable happens because of some misuse, just saturate the result
if self.0 < Decimal::one() {
Percent::zero()
} else {
Percent(Decimal::MAX)
}
}
}
pub fn checked_pow(&self, exp: u32) -> Result<Self, OverflowError> {
self.0.checked_pow(exp).map(Percent)
}
}
@@ -24,7 +24,15 @@ struct MixnodeWithStakeAndPerformance {
impl MixnodeWithStakeAndPerformance {
fn to_selection_weight(&self) -> f64 {
let scaled_stake = self.total_stake * self.performance.pow(20);
let scaled_performance = match self.performance.checked_pow(20) {
Ok(perf) => perf,
Err(overflow) => {
warn!("the node's performance ({}) has overflow while scaling it by the factor of 20: {overflow}. Setting it to 0 instead.", self.performance);
return 0.;
}
};
let scaled_stake = self.total_stake * scaled_performance;
stake_to_f64(scaled_stake)
}
}