Explorar o código

feat: balance by unit

thesimplekid hai 9 meses
pai
achega
f6764c7a22
Modificáronse 2 ficheiros con 55 adicións e 0 borrados
  1. 20 0
      bindings/cdk-js/src/wallet.rs
  2. 35 0
      crates/cdk/src/wallet.rs

+ 20 - 0
bindings/cdk-js/src/wallet.rs

@@ -46,6 +46,26 @@ impl JsWallet {
         Wallet::new(Arc::new(db), &seed).into()
     }
 
+    #[wasm_bindgen(js_name = unitBalance)]
+    pub async fn unit_balance(&self, unit: JsCurrencyUnit) -> Result<JsAmount> {
+        Ok(self
+            .inner
+            .unit_balance(unit.into())
+            .await
+            .map_err(into_err)?
+            .into())
+    }
+
+    #[wasm_bindgen(js_name = pendingUnitBalance)]
+    pub async fn pending_unit_balance(&self, unit: JsCurrencyUnit) -> Result<JsAmount> {
+        Ok(self
+            .inner
+            .pending_unit_balance(unit.into())
+            .await
+            .map_err(into_err)?
+            .into())
+    }
+
     #[wasm_bindgen(js_name = totalBalance)]
     pub async fn total_balance(&self) -> Result<JsValue> {
         Ok(serde_wasm_bindgen::to_value(

+ 35 - 0
crates/cdk/src/wallet.rs

@@ -136,6 +136,41 @@ impl Wallet {
         Ok(())
     }
 
+    /// Total Balance of wallet for given unit
+    #[instrument(skip(self))]
+    pub async fn unit_balance(&self, unit: CurrencyUnit) -> Result<Amount, Error> {
+        let balance = match self
+            .localstore
+            .get_proofs(None, Some(unit), Some(vec![State::Unspent]), None)
+            .await?
+        {
+            Some(proofs) => proofs.iter().map(|p| p.proof.amount).sum(),
+            None => Amount::ZERO,
+        };
+
+        Ok(balance)
+    }
+
+    /// Total pending and reserved balance of wallet for given unit
+    #[instrument(skip(self))]
+    pub async fn pending_unit_balance(&self, unit: CurrencyUnit) -> Result<Amount, Error> {
+        let balance = match self
+            .localstore
+            .get_proofs(
+                None,
+                Some(unit),
+                Some(vec![State::Pending, State::Reserved]),
+                None,
+            )
+            .await?
+        {
+            Some(proofs) => proofs.iter().map(|p| p.proof.amount).sum(),
+            None => Amount::ZERO,
+        };
+
+        Ok(balance)
+    }
+
     /// Total Balance of wallet
     #[instrument(skip(self))]
     pub async fn total_balance(&self) -> Result<HashMap<CurrencyUnit, Amount>, Error> {