lwk_wasm 0.11.0

Liquid Wallet Kit - WASM
Documentation
use crate::{Error, Network, Pset, Transaction, Txid, Update, Wollet};
use lwk_wollet::{age, clients::asyncr};
use wasm_bindgen::prelude::*;

/// Wrapper of [`asyncr::EsploraClient`]
#[wasm_bindgen]
pub struct EsploraClient {
    inner: asyncr::EsploraClient,
}

impl AsRef<asyncr::EsploraClient> for EsploraClient {
    fn as_ref(&self) -> &asyncr::EsploraClient {
        &self.inner
    }
}

#[wasm_bindgen]
impl EsploraClient {
    /// Creates a client, wrapper of [`asyncr::EsploraClient`]
    #[wasm_bindgen(constructor)]
    pub fn new(
        network: &Network,
        url: &str,
        waterfalls: bool,
        concurrency: usize,
        utxo_only: bool,
    ) -> Result<Self, Error> {
        let inner = asyncr::EsploraClientBuilder::new(url, network.into())
            .waterfalls(waterfalls)
            .concurrency(concurrency)
            .utxo_only(utxo_only)
            .build()
            .map_err(|e| Error::Generic(e.to_string()))?;
        Ok(Self { inner })
    }

    #[wasm_bindgen(js_name = fullScan)]
    pub async fn full_scan(&mut self, wollet: &Wollet) -> Result<Option<Update>, Error> {
        let update: Option<lwk_wollet::Update> = self.inner.full_scan(wollet.as_ref()).await?;
        Ok(update.map(Into::into))
    }

    /// Scan the blockchain for the scripts generated by a watch-only wallet up to a specified derivation index
    #[wasm_bindgen(js_name = fullScanToIndex)]
    pub async fn full_scan_to_index(
        &mut self,
        wollet: &Wollet,
        index: u32,
    ) -> Result<Option<Update>, Error> {
        let update: Option<lwk_wollet::Update> = self
            .inner
            .full_scan_to_index(wollet.as_ref(), index)
            .await?;
        Ok(update.map(Into::into))
    }

    #[wasm_bindgen(js_name = broadcastTx)]
    pub async fn broadcast_tx(&mut self, tx: &Transaction) -> Result<Txid, Error> {
        let txid = self.inner.broadcast(tx.as_ref()).await?;
        Ok(txid.into())
    }

    pub async fn broadcast(&mut self, pset: &Pset) -> Result<Txid, Error> {
        let tx = pset.extract_tx()?;
        self.broadcast_tx(&tx).await
    }

    pub async fn set_waterfalls_server_recipient(&mut self, recipient: &str) -> Result<(), Error> {
        let recipient: age::x25519::Recipient = recipient
            .parse()
            .map_err(|e: &str| Error::Generic(e.to_string()))?;
        self.inner.set_waterfalls_server_recipient(recipient);
        Ok(())
    }
}

#[cfg(all(test, target_arch = "wasm32"))]
mod tests {

    use wasm_bindgen_test::*;

    wasm_bindgen_test_configure!(run_in_browser);

    #[wasm_bindgen_test]
    async fn test_sleep() {
        lwk_wollet::clients::asyncr::async_sleep(1).await;
    }
}