ergo_lib_wasm/
utils.rs

1//! Utilities
2
3use wasm_bindgen::prelude::*;
4
5use crate::error_conversion::to_js;
6
7/// helper methods to get the fee address for various networks
8#[wasm_bindgen]
9pub struct MinerAddress {}
10
11#[wasm_bindgen]
12impl MinerAddress {
13    /// Miner fee Base58 encoded P2S address on mainnet
14    pub fn mainnet_fee_address() -> String {
15        ergo_lib::wallet::miner_fee::MINERS_FEE_MAINNET_ADDRESS_STR.clone()
16    }
17    /// Miner fee Base58 encoded P2S address on testnet
18    pub fn testnet_fee_address() -> String {
19        ergo_lib::wallet::miner_fee::MINERS_FEE_TESTNET_ADDRESS_STR.clone()
20    }
21}
22
23/// Wrapper for i64 for JS/TS because JS Number can only represent 53 bits
24/// see <https://stackoverflow.com/questions/17320706/javascript-long-integer>
25#[wasm_bindgen]
26#[derive(PartialEq, Eq, Debug, Clone)]
27pub struct I64(i64);
28
29#[wasm_bindgen]
30impl I64 {
31    /// Create from a standard rust string representation
32    #[allow(clippy::should_implement_trait)]
33    pub fn from_str(string: &str) -> Result<I64, JsValue> {
34        string.parse::<i64>().map_err(to_js).map(I64)
35    }
36
37    /// String representation of the value for use from environments that don't support i64
38    pub fn to_str(&self) -> String {
39        format!("{}", self.0)
40    }
41
42    /// Get the value as JS number (64-bit float)
43    pub fn as_num(&self) -> js_sys::Number {
44        js_sys::Number::from(self.0 as f64)
45    }
46
47    /// Addition with overflow check
48    pub fn checked_add(&self, other: &I64) -> Result<I64, JsValue> {
49        match self.0.checked_add(other.0) {
50            Some(value) => Ok(I64(value)),
51            None => Err(JsValue::from_str("overflow")),
52        }
53    }
54}
55
56impl From<i64> for I64 {
57    fn from(v: i64) -> Self {
58        I64(v)
59    }
60}
61
62impl From<I64> for i64 {
63    fn from(v: I64) -> Self {
64        v.0
65    }
66}
67
68#[allow(dead_code, missing_docs)]
69pub fn set_panic_hook() {
70    // When the `console_error_panic_hook` feature is enabled, we can call the
71    // `set_panic_hook` function at least once during initialization, and then
72    // we will get better error messages if our code ever panics.
73    //
74    // For more details see
75    // https://github.com/rustwasm/console_error_panic_hook#readme
76    #[cfg(feature = "console_error_panic_hook")]
77    console_error_panic_hook::set_once();
78}