Merge rust-bitcoin/rust-bitcoin#4614: Add fee rate constructors that take `Amount` as arg

6ed3fd6234 Add fee rate constructors that take Amount as arg (Tobin C. Harding)
c1a760bf60 units: Use singular in rustdoc (Tobin C. Harding)

Pull request description:

  Some users may find it more ergonomic to pass in an `Amount` when constructing fee rates. Also the strong type adds some semantic meaning as well as imposes the `Amount::MAX` limit.

  Add an equivalent constructor for each of the existing ones that uses an argument of type `Amount` instead of `u64` sats.

  (This was pulled out of #4610.)

  Close: #4734

ACKs for top commit:
  apoelstra:
    ACK 6ed3fd6234a6d9e44d2cf187108cc22955471d27; successfully ran local tests

Tree-SHA512: 92609457ba181370e1484c08028cec9158d6e1fb2ee984e4e8caeacc5c9828bc70febeb4fd3601d9a2fee57c65d5cee0af0ef95ea15e2387d5fd886879c2afb1
This commit is contained in:
merge-script 2025-06-12 21:27:32 +00:00
commit aab9c2dfca
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 32 additions and 1 deletions

View File

@ -11,6 +11,10 @@ use core::ops;
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
use NumOpResult as R;
use crate::{Amount,MathOp, NumOpError as E, NumOpResult};
mod encapsulate {
/// Fee rate.
///
@ -62,7 +66,16 @@ impl FeeRate {
}
}
/// Constructs a new [`FeeRate`] from satoshis per virtual bytes,
/// Constructs a new [`FeeRate`] from amount per 1000 weight units.
pub const fn from_per_kwu(rate: Amount) -> NumOpResult<Self> {
// No `map()` in const context.
match rate.checked_mul(4_000) {
Some(per_mvb) => R::Valid(FeeRate::from_sat_per_mvb(per_mvb.to_sat())),
None => R::Error(E::while_doing(MathOp::Mul)),
}
}
/// Constructs a new [`FeeRate`] from satoshis per virtual byte,
/// returning `None` if overflow occurred.
pub const fn from_sat_per_vb(sat_vb: u64) -> Option<Self> {
// No `map()` in const context.
@ -72,6 +85,15 @@ impl FeeRate {
}
}
/// Constructs a new [`FeeRate`] from amount per virtual byte.
pub const fn from_per_vb(rate: Amount) -> NumOpResult<Self> {
// No `map()` in const context.
match rate.checked_mul(1_000_000) {
Some(per_mvb) => R::Valid(FeeRate::from_sat_per_mvb(per_mvb.to_sat())),
None => R::Error(E::while_doing(MathOp::Mul)),
}
}
/// Constructs a new [`FeeRate`] from satoshis per virtual bytes.
pub const fn from_sat_per_vb_u32(sat_vb: u32) -> Self {
let sat_vb = sat_vb as u64; // No `Into` in const context.
@ -88,6 +110,15 @@ impl FeeRate {
}
}
/// Constructs a new [`FeeRate`] from satoshis per kilo virtual bytes (1,000 vbytes).
pub const fn from_per_kvb(rate: Amount) -> NumOpResult<Self> {
// No `map()` in const context.
match rate.checked_mul(1_000) {
Some(per_mvb) => R::Valid(FeeRate::from_sat_per_mvb(per_mvb.to_sat())),
None => R::Error(E::while_doing(MathOp::Mul)),
}
}
/// Converts to sat/kwu rounding down.
pub const fn to_sat_per_kwu_floor(self) -> u64 { self.to_sat_per_mvb() / 4_000 }