Skip to content

Commit 1874fc9

Browse files
committed
Return Result type instead of Option
Result allows for a more descriptive error messaging.
1 parent 77b6beb commit 1874fc9

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

units/src/amount/tests.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -1467,8 +1467,8 @@ fn math_op_errors() {
14671467
fn to_effective_value() {
14681468
let amt = "1 cBTC".parse::<Amount>().unwrap();
14691469
let fee_rate = FeeRate::from_sat_per_kwu(10);
1470-
let effective_value =
1471-
amt.to_effective_value(fee_rate, Weight::from_wu(272)).unwrap();
1470+
let effective_value = amt.to_effective_value(
1471+
fee_rate, Weight::from_wu(272)).unwrap();
14721472

14731473
// 10 sat/kwu * 272 wu = 4 sats (rounding up)
14741474
let expected_fee = "3 sats".parse::<SignedAmount>().unwrap();
@@ -1478,7 +1478,7 @@ fn to_effective_value() {
14781478

14791479
#[test]
14801480
#[cfg(feature = "alloc")]
1481-
fn effective_value_fee_rate_does_not_overflow() {
1482-
let eff_value =Amount::ZERO.to_effective_value(FeeRate::MAX, Weight::from_wu(272));
1483-
assert!(eff_value.is_none());
1481+
fn to_effective_value_error() {
1482+
let eff_val = Amount::ZERO.to_effective_value(FeeRate::MAX, Weight::from_wu(272));
1483+
assert_eq!(eff_val, Err(OutOfRangeError::too_big(false)));
14841484
}

units/src/amount/unsigned.rs

+14-4
Original file line numberDiff line numberDiff line change
@@ -248,13 +248,23 @@ impl Amount {
248248
///
249249
/// * `fee_rate` - the fee rate of the transaction being created.
250250
/// * `weight` - the predicted input weight.
251+
///
252+
/// # Errors
253+
///
254+
/// If fee_rate multiplied by weight exceeds SignedAmount::MAX
251255
pub fn to_effective_value(
252256
&self,
253257
fee_rate: FeeRate,
254-
weight: Weight,
255-
) -> Option<SignedAmount> {
256-
let signed_input_fee = fee_rate.to_fee(weight)?.to_signed();
257-
self.to_signed().checked_sub(signed_input_fee)
258+
weight: Weight
259+
) -> Result<SignedAmount, OutOfRangeError> {
260+
let signed_input_fee = fee_rate.to_fee(weight).ok_or(
261+
OutOfRangeError { is_signed: false, is_greater_than_max: true }
262+
)?.to_signed();
263+
264+
// it's not possible to overflow when subtracted by the smallest given:
265+
// Amount::MIN - SignedAmount::MAX = SignedAmount::MIN
266+
let eff_val = (self.to_signed() - signed_input_fee).unwrap(); //unwrap ok
267+
Ok(eff_val)
258268
}
259269

260270
/// Converts this [`Amount`] in floating-point notation in the given [`Denomination`].

0 commit comments

Comments
 (0)