diff --git a/webln-js/src/balance.rs b/webln-js/src/balance.rs new file mode 100644 index 0000000..40bdf88 --- /dev/null +++ b/webln-js/src/balance.rs @@ -0,0 +1,29 @@ +// Copyright (c) 2024 Yuki Kishimoto +// Distributed under the MIT software license + +use alloc::string::String; + +use wasm_bindgen::prelude::*; +use webln::BalanceResponse; + +#[wasm_bindgen(js_name = BalanceResponse)] +pub struct JsBalanceResponse { + inner: BalanceResponse, +} + +impl From for JsBalanceResponse { + fn from(inner: BalanceResponse) -> Self { + Self { inner } + } +} + +#[wasm_bindgen(js_class = BalanceResponse)] +impl JsBalanceResponse { + pub fn balance(&self) -> f64 { + self.inner.balance + } + + pub fn currency(&self) -> Option { + self.inner.currency.clone() + } +} diff --git a/webln-js/src/lib.rs b/webln-js/src/lib.rs index 16b6e78..aefe104 100644 --- a/webln-js/src/lib.rs +++ b/webln-js/src/lib.rs @@ -14,6 +14,7 @@ use core::ops::Deref; use wasm_bindgen::prelude::*; use webln::WebLN; +pub mod balance; pub mod error; pub mod get_info; pub mod keysend; @@ -21,6 +22,7 @@ pub mod request_invoice; pub mod send_payment; pub mod sign_message; +use self::balance::JsBalanceResponse; use self::error::{into_err, Result}; use self::get_info::JsGetInfoResponse; use self::keysend::JsKeysendArgs; @@ -127,4 +129,10 @@ impl JsWebLN { .map_err(into_err)? .into()) } + + /// Fetch the balance of the current account. + #[wasm_bindgen(js_name = getBalance)] + pub async fn get_balance(&self) -> Result { + Ok(self.inner.get_balance().await.map_err(into_err)?.into()) + } } diff --git a/webln/src/lib.rs b/webln/src/lib.rs index 9175caf..0333a0d 100644 --- a/webln/src/lib.rs +++ b/webln/src/lib.rs @@ -321,6 +321,15 @@ pub struct SignMessageResponse { pub signature: String, } +/// Balance Response +#[derive(Debug, Clone, PartialEq, PartialOrd)] +pub struct BalanceResponse { + /// Balance + pub balance: f64, + /// Currency + pub currency: Option, +} + /// WebLN instance #[derive(Debug, Clone)] pub struct WebLN { @@ -539,4 +548,24 @@ impl WebLN { signature, }) } + + /// Fetch the balance of the current account. + pub async fn get_balance(&self) -> Result { + let func: Function = self.get_func(&self.webln_obj, GET_BALANCE)?; + let promise: Promise = Promise::resolve(&func.call0(&self.webln_obj)?); + let result: JsValue = JsFuture::from(promise).await?; + let balance_response_obj: Object = + result.dyn_into().map_err(|_| Error::SomethingGoneWrong)?; + + // Extract data + let balance: f64 = self + .get_value_by_key(&balance_response_obj, "balance")? + .as_f64() + .ok_or_else(|| Error::TypeMismatch(String::from("expected a number [balance]")))?; + let currency: Option = self + .get_value_by_key(&balance_response_obj, "currency")? + .as_string(); + + Ok(BalanceResponse { balance, currency }) + } }