Make mul weight by fee return NumOpResult

Now that we have the `NumOpResult<Amount>` type that is used to show a
math calculation returned a valid amount we can use it when multiplying
weight and fee rates thus removing panics.
This commit is contained in:
Tobin C. Harding 2025-02-28 12:17:57 +11:00
parent f9eb307953
commit 76a2d70b28
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
3 changed files with 9 additions and 10 deletions

View File

@ -39,6 +39,7 @@ pub use self::{
signed::SignedAmount,
unsigned::Amount,
};
pub(crate) use self::result::OptionExt;
/// A set of denominations in which amounts can be expressed.
///

View File

@ -1,7 +1,6 @@
// SPDX-License-Identifier: CC0-1.0
//! Provides a monodic numeric result type that is used to return the result of
//! doing mathematical operations (`core::ops`) on amount types.
//! Provides a monodic type used when mathematical operations (`core::ops`) return an amount type.
use core::{fmt, ops};
@ -378,7 +377,7 @@ impl<'a> core::iter::Sum<&'a NumOpResult<SignedAmount>> for NumOpResult<SignedAm
}
}
pub(in crate::amount) trait OptionExt<T> {
pub(crate) trait OptionExt<T> {
fn valid_or_error(self) -> NumOpResult<T>;
}

View File

@ -13,6 +13,7 @@
use core::ops;
use crate::amount::{NumOpResult, OptionExt};
use crate::{Amount, FeeRate, Weight};
impl Amount {
@ -160,17 +161,15 @@ impl FeeRate {
/// Computes the ceiling so that the fee computation is conservative.
impl ops::Mul<FeeRate> for Weight {
type Output = Amount;
type Output = NumOpResult<Amount>;
fn mul(self, rhs: FeeRate) -> Self::Output {
Amount::from_sat((rhs.to_sat_per_kwu() * self.to_wu() + 999) / 1000)
}
fn mul(self, rhs: FeeRate) -> Self::Output { rhs.checked_mul_by_weight(self).valid_or_error() }
}
impl ops::Mul<Weight> for FeeRate {
type Output = Amount;
type Output = NumOpResult<Amount>;
fn mul(self, rhs: Weight) -> Self::Output { rhs * self }
fn mul(self, rhs: Weight) -> Self::Output { self.checked_mul_by_weight(rhs).valid_or_error() }
}
impl ops::Div<Weight> for Amount {
@ -265,7 +264,7 @@ mod tests {
let three = Weight::from_vb(3).unwrap();
let six = Amount::from_sat_unchecked(6);
assert_eq!(two * three, six);
assert_eq!(two * three, six.into());
}
#[test]