From 76a2d70b2866c9a9e2e24c1d71a9630a57559737 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 28 Feb 2025 12:17:57 +1100 Subject: [PATCH] Make mul weight by fee return NumOpResult Now that we have the `NumOpResult` 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. --- units/src/amount/mod.rs | 1 + units/src/amount/result.rs | 5 ++--- units/src/fee.rs | 13 ++++++------- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/units/src/amount/mod.rs b/units/src/amount/mod.rs index 7fb8bc535..940b9a5a8 100644 --- a/units/src/amount/mod.rs +++ b/units/src/amount/mod.rs @@ -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. /// diff --git a/units/src/amount/result.rs b/units/src/amount/result.rs index ae1c6e12d..4b78d0080 100644 --- a/units/src/amount/result.rs +++ b/units/src/amount/result.rs @@ -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> for NumOpResult { +pub(crate) trait OptionExt { fn valid_or_error(self) -> NumOpResult; } diff --git a/units/src/fee.rs b/units/src/fee.rs index 1bb3b9b66..39dff63b0 100644 --- a/units/src/fee.rs +++ b/units/src/fee.rs @@ -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 for Weight { - type Output = Amount; + type Output = NumOpResult; - 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 for FeeRate { - type Output = Amount; + type Output = NumOpResult; - 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 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]