wallet_adapter/wallet_ser_der/standard_features/
standard_fn.rs

1use core::hash::Hash;
2
3use web_sys::js_sys::Function;
4
5use crate::{Reflection, SemverVersion, WalletError, WalletResult};
6
7/// A struct containing the [semver version](SemverVersion)
8/// and [callback function](Function) within the `standard:` namespace as
9/// defined by the wallet standard
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
11pub struct StandardFunction {
12    pub(crate) version: SemverVersion,
13    pub(crate) callback: Function,
14}
15
16impl StandardFunction {
17    /// Parse the [semver version](SemverVersion) and the [callback function](Function)
18    /// given a [web_sys::wasm_bindgen::JsValue], a [key](str) and a [namespace](str) . The namespace is either
19    /// `standard:` or `solana:` as defined by the wallet standard
20    pub(crate) fn new(
21        reflection: &Reflection,
22        version: SemverVersion,
23        key: &str,
24        namespace: &str,
25    ) -> WalletResult<Self> {
26        let incase_of_error = Err(WalletError::InternalError(format!(
27            "Namespace[`{namespace}: {key} -> {key}]: Reflect `{key}` in JsValue `{:?}` did not yield a JS Function", reflection.get_inner()
28        )));
29
30        let fn_value = reflection
31            .reflect_inner(key)
32            .or(Err(WalletError::MissingConnectFunction))?;
33        let get_fn = Reflection::new(fn_value)?
34            .into_function()
35            .or(incase_of_error)?;
36
37        Ok(Self {
38            version,
39            callback: get_fn,
40        })
41    }
42}
43
44#[allow(clippy::non_canonical_partial_ord_impl)]
45impl PartialOrd for StandardFunction {
46    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
47        Some(self.version.cmp(&other.version))
48    }
49}
50
51impl Ord for StandardFunction {
52    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
53        self.version.cmp(&other.version)
54    }
55}
56
57impl Hash for StandardFunction {
58    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
59        self.version.hash(state);
60    }
61}