Skip to content

Commit

Permalink
primitives: improvements to Sats API
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Sep 20, 2023
1 parent 6b2e0da commit 64477b5
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions primitives/src/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,10 @@ pub struct TxIn {
pub witness: Witness,
}

#[derive(Wrapper, WrapperMut, Copy, Clone, Eq, PartialEq, Hash, Debug, From)]
#[derive(Wrapper, WrapperMut, Copy, Clone, Eq, PartialEq, Hash, Debug, From, Default)]
#[wrapper(Add, Sub, Mul, Div, FromStr)]
#[wrapper_mut(MathAssign)]
#[derive(StrictType, StrictDumb, StrictEncode, StrictDecode)]
#[derive(StrictType, StrictEncode, StrictDecode)]
#[strict_type(lib = LIB_NAME_BITCOIN)]
#[cfg_attr(
feature = "serde",
Expand All @@ -237,6 +237,10 @@ impl Sats {
pub const BTC: Self = Sats(1_000_000_00);

pub const fn from_btc(btc: u32) -> Self { Self(btc as u64 * Self::BTC.0) }
pub fn from_sats(sats: impl Into<u64>) -> Self { Self(sats.into()) }

pub const fn is_zero(&self) -> bool { self.0 == 0 }
pub const fn is_non_zero(&self) -> bool { self.0 != 0 }

pub const fn btc_round(&self) -> u64 {
if self.0 == 0 {
Expand All @@ -263,6 +267,10 @@ impl Sats {

pub const fn sats(&self) -> u64 { self.0 }

pub fn sats_i64(&self) -> i64 {
i64::try_from(self.0).expect("amount of sats exceeds total bitcoin supply")
}

pub const fn sats_rem(&self) -> u64 { self.0 % Self::BTC.0 }

pub fn checked_add(&self, other: impl Into<Self>) -> Option<Self> {
Expand Down Expand Up @@ -304,6 +312,10 @@ impl Sats {
}
}

impl PartialEq<u64> for Sats {
fn eq(&self, other: &u64) -> bool { self.0.eq(other) }
}

impl Sum for Sats {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Sats::ZERO, |sum, value| sum.saturating_add(value))
Expand Down

0 comments on commit 64477b5

Please sign in to comment.