lwk_wasm/
balance.rs

1use std::collections::BTreeMap;
2
3use serde::Serialize;
4use serde_wasm_bindgen::Serializer;
5use wasm_bindgen::prelude::*;
6
7use crate::Error;
8
9/// A signed balance of assets, to represent a balance with negative values such
10/// as the results of a transaction from the perspective of a wallet.
11#[wasm_bindgen]
12#[derive(PartialEq, Eq, Debug, Clone)]
13pub struct Balance {
14    inner: lwk_common::SignedBalance,
15}
16
17impl From<lwk_common::SignedBalance> for Balance {
18    fn from(inner: lwk_common::SignedBalance) -> Self {
19        Self { inner }
20    }
21}
22
23impl From<lwk_common::Balance> for Balance {
24    fn from(balance: lwk_common::Balance) -> Self {
25        // Convert Balance to SignedBalance by mapping positive values
26        let signed_map: std::collections::BTreeMap<lwk_wollet::elements::AssetId, i64> = balance
27            .iter()
28            .map(|(asset_id, amount)| (*asset_id, *amount as i64))
29            .collect();
30        Self {
31            inner: lwk_common::SignedBalance::from(signed_map),
32        }
33    }
34}
35
36#[wasm_bindgen]
37impl Balance {
38    /// Convert the balance to a JsValue for serialization
39    ///
40    /// Note: the amounts are strings since `JSON.stringify` cannot handle `BigInt`s.
41    /// Use `entries()` to get the raw data.
42    #[wasm_bindgen(js_name = toJSON)]
43    pub fn to_json(&self) -> Result<JsValue, Error> {
44        let serializer = Serializer::new().serialize_maps_as_objects(true);
45
46        Ok(self
47            .inner
48            .as_ref()
49            .iter()
50            .map(|(k, v)| (k.to_string(), v.to_string()))
51            .collect::<BTreeMap<String, String>>()
52            .serialize(&serializer)?)
53    }
54
55    /// Returns the balance as an array of [key, value] pairs.
56    #[wasm_bindgen]
57    pub fn entries(&self) -> Result<JsValue, Error> {
58        let serializer = Serializer::new().serialize_large_number_types_as_bigints(true);
59
60        Ok(self.inner.serialize(&serializer)?)
61    }
62
63    /// Return the string representation of the balance.
64    #[wasm_bindgen(js_name = toString)]
65    pub fn to_string_js(&self) -> String {
66        serde_json::to_string(&self.inner).expect("contain simple types")
67    }
68}