1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
use miden_objects::accounts::AccountId;
use wasm_bindgen::prelude::*;

use crate::{models::accounts::SerializedAccountStub, WebClient};

#[wasm_bindgen]
impl WebClient {
    pub async fn get_accounts(&mut self) -> Result<JsValue, JsValue> {
        if let Some(client) = self.get_mut_inner() {
            let account_tuples = client.get_account_stubs().await.unwrap();
            let accounts: Vec<SerializedAccountStub> = account_tuples
                .into_iter()
                .map(|(account, _)| {
                    SerializedAccountStub::new(
                        account.id().to_string(),
                        account.nonce().to_string(),
                        account.vault_root().to_string(),
                        account.storage_root().to_string(),
                        account.code_commitment().to_string(),
                    )
                })
                .collect();

            let accounts_as_js_value =
                serde_wasm_bindgen::to_value(&accounts).unwrap_or_else(|_| {
                    wasm_bindgen::throw_val(JsValue::from_str("Serialization error"))
                });

            Ok(accounts_as_js_value)
        } else {
            Err(JsValue::from_str("Client not initialized"))
        }
    }

    pub async fn get_account(&mut self, account_id: String) -> Result<JsValue, JsValue> {
        if let Some(client) = self.get_mut_inner() {
            let native_account_id = AccountId::from_hex(&account_id).unwrap();

            let result = client.get_account(native_account_id).await.unwrap();

            serde_wasm_bindgen::to_value(&result.0.id().to_string())
                .map_err(|e| JsValue::from_str(&e.to_string()))
        } else {
            Err(JsValue::from_str("Client not initialized"))
        }
    }

    pub async fn fetch_and_cache_account_auth_by_pub_key(
        &mut self,
        account_id: String,
    ) -> Result<JsValue, JsValue> {
        if let Some(client) = self.get_mut_inner() {
            let _ = client
                .store()
                .fetch_and_cache_account_auth_by_pub_key(account_id)
                .await
                .unwrap();

            Ok(JsValue::from_str("Okay, it worked"))
        } else {
            Err(JsValue::from_str("Client not initialized"))
        }
    }
}