miden-client-web 0.14.9

Web Client library that facilitates interaction with the Miden network
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
extern crate alloc;
use alloc::sync::Arc;
use core::error::Error;
use core::fmt::Write;

use idxdb_store::IdxdbStore;
use js_sys::{Function, Reflect};
use miden_client::builder::{ClientBuilder, DEFAULT_GRPC_TIMEOUT_MS};
use miden_client::crypto::RandomCoin;
use miden_client::note_transport::NoteTransportClient;
use miden_client::note_transport::grpc::GrpcNoteTransportClient;
use miden_client::rpc::{Endpoint, GrpcClient, NodeRpcClient};
use miden_client::store::Store;
use miden_client::testing::mock::MockRpcApi;
use miden_client::testing::note_transport::MockNoteTransportApi;
use miden_client::{Client, ClientError, DebugMode, ErrorHint, Felt};
use models::code_builder::CodeBuilder;
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use wasm_bindgen::prelude::*;

pub mod account;
pub mod export;
pub mod helpers;
pub mod import;
#[macro_use]
pub(crate) mod miden_array;
pub mod mock;
pub mod models;
pub mod new_account;
pub mod new_transactions;
pub mod note_transport;
pub mod notes;
pub mod rpc_client;
pub mod settings;
pub mod sync;
pub mod tags;
pub mod transactions;
pub mod utils;

pub mod keystore_api;
mod web_keystore;
mod web_keystore_callbacks;
mod web_keystore_db;
use tracing::Level;
use tracing_subscriber::layer::SubscriberExt;
pub use web_keystore::WebKeyStore;

// Re-export wasm-bindgen-rayon's `init_thread_pool` ONLY in the multi-threaded
// build. JS callers MUST `await initThreadPool(navigator.hardwareConcurrency)`
// once on the main thread (or inside the worker that owns the WebClient)
// before any transaction proving runs. Without this call the rayon global
// thread pool spawns zero threads on wasm32 and every `par_iter(...)` falls
// through to a sequential loop — i.e. you've shipped multi-threaded WASM
// that runs single-threaded. In the single-threaded build (no `mt-threads`
// feature), wasm-bindgen-rayon isn't a dependency, the prover paths use
// p3-maybe-rayon's sequential fallback, and `initThreadPool` doesn't exist
// to call.
#[cfg(feature = "mt-threads")]
pub use wasm_bindgen_rayon::init_thread_pool;

// MT bring-up diagnostics — gated behind `testing` so they don't ship in
// production WASM bundles. Useful during initial wiring of a new MT host
// or when investigating "why is my MT prove not faster" regressions; not
// needed at runtime by normal consumers. Enable with
// `--features mt-threads,testing` to surface them on the wasm-bindgen API.

/// How many rayon worker threads are visible from THIS WASM instance's view of
/// the global rayon pool. Diagnostic only — the value should equal whatever
/// `initThreadPool(n)` was called with. If it's 1, rayon is in single-threaded
/// fallback (workers never spawned, or spawned in a different WASM instance).
#[cfg(all(feature = "mt-threads", feature = "testing"))]
#[wasm_bindgen(js_name = "rayonThreadCount")]
pub fn rayon_thread_count() -> usize {
    rayon::current_num_threads()
}

/// Synthetic parallel benchmark: sums 0..n via `par_iter()` on the global
/// rayon pool. Returns elapsed micros. If the pool is actually multi-threaded,
/// large `n` should scale ~linearly with thread count. Diagnostic for
/// confirming whether rayon is dispatching work at all.
//
// `cast_precision_loss` is intentional: this is a synthetic FP-mix workload
// to defeat constant-folding and exercise rayon's dispatch — we don't care
// about precision, only about CPU work being divided across threads.
#[cfg(all(feature = "mt-threads", feature = "testing"))]
#[wasm_bindgen(js_name = "parallelSumBench")]
#[allow(clippy::cast_precision_loss)]
pub fn parallel_sum_bench(n: u64) -> u64 {
    use rayon::prelude::*;
    // Don't actually need timing on the Rust side — caller times it. We
    // return the sum to defeat the optimizer. Use an FP-mix workload so
    // it's not trivially constant-folded.
    let s: f64 = (0..n)
        .into_par_iter()
        .map(|i| ((i as f64).sqrt() * 1.0001).sin().abs())
        .sum();
    s.to_bits()
}

/// Single-threaded version of `parallel_sum_bench` for direct comparison.
/// Same workload, plain `iter()` — bypasses rayon entirely. Needs to live
/// on the WASM side rather than be reimplemented in JS so the workload is
/// bit-for-bit identical to `parallel_sum_bench` (same libm, same FP
/// determinism, same constant-folding resistance).
#[cfg(feature = "testing")]
#[wasm_bindgen(js_name = "sequentialSumBench")]
#[allow(clippy::cast_precision_loss)]
pub fn sequential_sum_bench(n: u64) -> u64 {
    let s: f64 = (0..n)
        .map(|i| ((i as f64).sqrt() * 1.0001).sin().abs())
        .sum();
    s.to_bits()
}

/// Client authenticator type. Gate with `#[cfg]` to support other keystores, e.g.
/// `FilesystemKeyStore` for Node.js.
pub(crate) type ClientAuth = WebKeyStore<RandomCoin>;

const BASE_STORE_NAME: &str = "MidenClientDB";

/// Initializes the `tracing` subscriber that routes Rust log output to the
/// browser console via `console.log` / `console.warn` / `console.error`.
///
/// `log_level` must be one of `"error"`, `"warn"`, `"info"`, `"debug"`,
/// `"trace"`, `"off"`, or `"none"` (no logging). Unknown values are treated
/// as "off".
///
/// This is a **per-thread global** — call it once on the main thread and, if
/// you use a Web Worker, once inside the worker. Subsequent calls on the same
/// thread are harmless no-ops.
#[wasm_bindgen(js_name = "setupLogging")]
pub fn setup_logging(log_level: &str) {
    let level = match log_level.to_lowercase().as_str() {
        "error" => Some(Level::ERROR),
        "warn" => Some(Level::WARN),
        "info" => Some(Level::INFO),
        "debug" => Some(Level::DEBUG),
        "trace" => Some(Level::TRACE),
        _ => None,
    };

    if let Some(level) = level {
        let config = tracing_wasm::WASMLayerConfigBuilder::new()
            .set_max_level(level)
            .build();
        // `set_as_global_default_with_config` panics on double-init, so replicate
        // its logic with `set_global_default` which returns a `Result` instead.
        let _ = tracing::subscriber::set_global_default(
            tracing_subscriber::registry().with(tracing_wasm::WASMLayer::new(config)),
        );
    }
}

#[wasm_bindgen]
pub struct WebClient {
    inner: Option<Client<ClientAuth>>,
    mock_rpc_api: Option<Arc<MockRpcApi>>,
    mock_note_transport_api: Option<Arc<MockNoteTransportApi>>,
}

impl Default for WebClient {
    fn default() -> Self {
        Self::new()
    }
}

#[wasm_bindgen]
impl WebClient {
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self {
        console_error_panic_hook::set_once();
        WebClient {
            inner: None,
            mock_rpc_api: None,
            mock_note_transport_api: None,
        }
    }

    /// Returns the identifier of the underlying store (e.g. `IndexedDB` database name, file path).
    #[wasm_bindgen(js_name = "storeIdentifier")]
    pub fn store_identifier(&self) -> Result<String, JsValue> {
        Ok(self.get_inner()?.store_identifier().to_string())
    }

    /// Returns the raw JS value that the most recent sign-callback invocation
    /// threw, or `null` if the last sign call succeeded (or no call has
    /// happened yet).
    ///
    /// Combined with the serialized-call discipline enforced at the JS
    /// `WebClient` wrapper, this lets a caller that caught a failed
    /// `executeTransaction` / `submitNewTransaction` recover the original
    /// JS error the signing callback threw — preserving any structured
    /// metadata (e.g. a `reason: 'locked'` property) that the kernel-level
    /// `auth::request` diagnostic would otherwise have erased.
    ///
    /// # Usage (TS)
    /// ```ts
    /// try {
    ///   await client.submitNewTransaction(acc, req);
    /// } catch (e) {
    ///   const authErr = client.lastAuthError();
    ///   if (authErr && authErr.reason === 'locked') {
    ///     // wait for unlock, then retry
    ///   }
    /// }
    /// ```
    #[wasm_bindgen(js_name = "lastAuthError")]
    pub fn last_auth_error(&self) -> JsValue {
        match self.inner_keystore() {
            Ok(keystore) => keystore.last_sign_error(),
            Err(_) => JsValue::NULL,
        }
    }

    pub(crate) fn get_inner(&self) -> Result<&Client<ClientAuth>, JsValue> {
        self.inner
            .as_ref()
            .ok_or_else(|| JsValue::from_str("Client not initialized"))
    }

    pub(crate) fn get_mut_inner(&mut self) -> Option<&mut Client<ClientAuth>> {
        self.inner.as_mut()
    }

    pub(crate) fn inner_keystore(&self) -> Result<&Arc<ClientAuth>, JsValue> {
        self.inner
            .as_ref()
            .and_then(|c| c.authenticator())
            .ok_or_else(|| JsValue::from_str("Client not initialized"))
    }

    /// Returns a `WebKeystoreApi` handle for managing secret keys.
    ///
    /// The returned object can be used from JavaScript as `client.keystore`.
    #[wasm_bindgen(getter)]
    pub fn keystore(&self) -> Result<keystore_api::WebKeystoreApi, JsValue> {
        let ks = self.inner_keystore()?.clone();
        Ok(keystore_api::WebKeystoreApi::new(ks))
    }

    /// Creates a new `WebClient` instance with the specified configuration.
    ///
    /// # Arguments
    /// * `node_url`: The URL of the node RPC endpoint. If `None`, defaults to the testnet endpoint.
    /// * `node_note_transport_url`: Optional URL of the note transport service.
    /// * `seed`: Optional seed for account initialization.
    /// * `store_name`: Optional name for the web store. If `None`, the store name defaults to
    ///   `MidenClientDB_{network_id}`, where `network_id` is derived from the `node_url`.
    ///   Explicitly setting this allows for creating multiple isolated clients.
    #[wasm_bindgen(js_name = "createClient")]
    pub async fn create_client(
        &mut self,
        node_url: Option<String>,
        node_note_transport_url: Option<String>,
        seed: Option<Vec<u8>>,
        store_name: Option<String>,
        debug_mode: Option<bool>,
    ) -> Result<JsValue, JsValue> {
        let endpoint = node_url.map_or(Ok(Endpoint::testnet()), |url| {
            Endpoint::try_from(url.as_str()).map_err(|_| JsValue::from_str("Invalid node URL"))
        })?;

        let web_rpc_client = Arc::new(GrpcClient::new(&endpoint, DEFAULT_GRPC_TIMEOUT_MS));

        let note_transport_client = node_note_transport_url.map(|url| {
            Arc::new(GrpcNoteTransportClient::new(url, DEFAULT_GRPC_TIMEOUT_MS))
                as Arc<dyn NoteTransportClient>
        });

        let store_name =
            store_name.unwrap_or(format!("{}_{}", BASE_STORE_NAME, endpoint.to_network_id()));

        let store = Arc::new(
            IdxdbStore::new(store_name.clone())
                .await
                .map_err(|_| JsValue::from_str("Failed to initialize IdxdbStore"))?,
        );

        let rng = create_rng(seed)?;
        let keystore = Arc::new(WebKeyStore::new_with_callbacks(
            rng,
            store_name.clone(),
            None,
            None,
            None,
        ));

        self.setup_client(
            web_rpc_client,
            store,
            keystore,
            rng,
            note_transport_client,
            debug_mode.unwrap_or(false),
        )
        .await?;

        Ok(JsValue::from_str("Client created successfully"))
    }

    /// Creates a new `WebClient` instance with external keystore callbacks.
    ///
    /// # Arguments
    /// * `node_url`: The URL of the node RPC endpoint. If `None`, defaults to the testnet endpoint.
    /// * `node_note_transport_url`: Optional URL of the note transport service.
    /// * `seed`: Optional seed for account initialization.
    /// * `store_name`: Optional name for the web store. If `None`, the store name defaults to
    ///   `MidenClientDB_{network_id}`, where `network_id` is derived from the `node_url`.
    ///   Explicitly setting this allows for creating multiple isolated clients.
    /// * `get_key_cb`: Callback to retrieve the secret key bytes for a given public key.
    /// * `insert_key_cb`: Callback to persist a secret key.
    /// * `sign_cb`: Callback to produce serialized signature bytes for the provided inputs.
    #[wasm_bindgen(js_name = "createClientWithExternalKeystore")]
    #[allow(clippy::too_many_arguments)]
    pub async fn create_client_with_external_keystore(
        &mut self,
        node_url: Option<String>,
        node_note_transport_url: Option<String>,
        seed: Option<Vec<u8>>,
        store_name: Option<String>,
        get_key_cb: Option<Function>,
        insert_key_cb: Option<Function>,
        sign_cb: Option<Function>,
        debug_mode: Option<bool>,
    ) -> Result<JsValue, JsValue> {
        let endpoint = node_url.map_or(Ok(Endpoint::testnet()), |url| {
            Endpoint::try_from(url.as_str()).map_err(|_| JsValue::from_str("Invalid node URL"))
        })?;

        let web_rpc_client = Arc::new(GrpcClient::new(&endpoint, DEFAULT_GRPC_TIMEOUT_MS));

        let note_transport_client = node_note_transport_url.map(|url| {
            Arc::new(GrpcNoteTransportClient::new(url, DEFAULT_GRPC_TIMEOUT_MS))
                as Arc<dyn NoteTransportClient>
        });

        let store_name =
            store_name.unwrap_or(format!("{}_{}", BASE_STORE_NAME, endpoint.to_network_id()));

        let store = Arc::new(
            IdxdbStore::new(store_name.clone())
                .await
                .map_err(|_| JsValue::from_str("Failed to initialize IdxdbStore"))?,
        );

        let rng = create_rng(seed)?;
        let keystore = Arc::new(WebKeyStore::new_with_callbacks(
            rng,
            store_name.clone(),
            get_key_cb,
            insert_key_cb,
            sign_cb,
        ));

        self.setup_client(
            web_rpc_client,
            store,
            keystore,
            rng,
            note_transport_client,
            debug_mode.unwrap_or(false),
        )
        .await?;

        Ok(JsValue::from_str("Client created successfully"))
    }

    /// Shared client setup. Platform-specific callers create the store and keystore,
    /// then pass them here for the common `ClientBuilder` logic.
    async fn setup_client(
        &mut self,
        rpc_client: Arc<dyn NodeRpcClient>,
        store: Arc<dyn Store>,
        keystore: Arc<ClientAuth>,
        rng: RandomCoin,
        note_transport_client: Option<Arc<dyn NoteTransportClient>>,
        debug_mode: bool,
    ) -> Result<(), JsValue> {
        let mut builder = ClientBuilder::new()
            .rpc(rpc_client)
            .rng(Box::new(rng))
            .store(store)
            .authenticator(keystore)
            .in_debug_mode(if debug_mode {
                DebugMode::Enabled
            } else {
                DebugMode::Disabled
            });

        if let Some(transport) = note_transport_client {
            builder = builder.note_transport(transport);
        }

        let mut client = builder
            .build()
            .await
            .map_err(|err| js_error_with_context(err, "Failed to create client"))?;

        // Ensure genesis block is fetched and stored in IndexedDB.
        // This is important for web workers that create their own client instances -
        // they will read the genesis from the shared IndexedDB and automatically
        // set the genesis commitment on their RPC client.
        client
            .ensure_genesis_in_place()
            .await
            .map_err(|err| js_error_with_context(err, "Failed to ensure genesis in place"))?;

        self.inner = Some(client);

        Ok(())
    }

    #[wasm_bindgen(js_name = "createCodeBuilder")]
    pub fn create_code_builder(&self) -> Result<CodeBuilder, JsValue> {
        let Some(client) = &self.inner else {
            return Err("client was not initialized before instancing CodeBuilder".into());
        };
        Ok(CodeBuilder::from_source_manager(
            client.code_builder().source_manager().clone(),
        ))
    }
}

// HELPERS
// ================================================================================================

pub(crate) fn create_rng(seed: Option<Vec<u8>>) -> Result<RandomCoin, JsValue> {
    let mut rng = match seed {
        Some(seed_bytes) => {
            if seed_bytes.len() == 32 {
                let mut seed_array = [0u8; 32];
                seed_array.copy_from_slice(&seed_bytes);
                StdRng::from_seed(seed_array)
            } else {
                return Err(JsValue::from_str("Seed must be exactly 32 bytes"));
            }
        }
        None => StdRng::from_os_rng(),
    };
    let coin_seed: [u64; 4] = rng.random();
    Ok(RandomCoin::new(coin_seed.map(Felt::new).into()))
}

// ERROR HANDLING HELPERS
// ================================================================================================

fn js_error_with_context<T>(err: T, context: &str) -> JsValue
where
    T: Error + 'static,
{
    let mut error_string = context.to_string();
    let mut source = Some(&err as &dyn Error);
    while let Some(err) = source {
        write!(error_string, ": {err}").expect("writing to string should always succeed");
        source = err.source();
    }

    let help = hint_from_error(&err);
    let js_error: JsValue = JsError::new(&error_string).into();

    if let Some(help) = help {
        let _ = Reflect::set(
            &js_error,
            &JsValue::from_str("help"),
            &JsValue::from_str(&help),
        );
    }

    js_error
}

fn hint_from_error(err: &(dyn Error + 'static)) -> Option<String> {
    if let Some(client_error) = err.downcast_ref::<ClientError>() {
        return Option::<ErrorHint>::from(client_error).map(ErrorHint::into_help_message);
    }

    err.source().and_then(hint_from_error)
}