miden-client-web 0.15.0

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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
// All `#[js_export]` methods must accept arguments by value (not by reference) because
// wasm_bindgen and napi-rs require owned parameters for JS interop. Suppress the lint
// crate-wide rather than annotating every individual function.
#![allow(clippy::needless_pass_by_value)]

extern crate alloc;

#[cfg(all(feature = "browser", feature = "nodejs"))]
compile_error!("Features `browser` and `nodejs` are mutually exclusive. Enable only one.");

#[cfg(not(any(feature = "browser", feature = "nodejs")))]
compile_error!("Either `browser` or `nodejs` feature must be enabled.");

use alloc::sync::Arc;
use core::error::Error;
use core::fmt::Write;

#[cfg(feature = "browser")]
use idxdb_store::IdxdbStore;
use js_export_macro::js_export;
#[cfg(feature = "browser")]
use js_sys::{Function, Reflect};
use miden_client::builder::{ClientBuilder, DEFAULT_GRPC_TIMEOUT_MS};
use miden_client::crypto::RandomCoin;
#[cfg(feature = "nodejs")]
use miden_client::keystore::FilesystemKeyStore;
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;
#[cfg(feature = "nodejs")]
use napi_derive::napi;
#[cfg(feature = "nodejs")]
use platform::maybe_wrap_send;
use platform::{AsyncCell, ClientAuth, JsErr, from_str_err};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
#[cfg(feature = "browser")]
use tracing::Level;
#[cfg(feature = "browser")]
use tracing_subscriber::layer::SubscriberExt;
#[cfg(feature = "browser")]
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(crate) mod platform;
pub mod rpc_client;
pub mod settings;
pub mod sync;
pub mod tags;
pub mod transactions;
pub mod utils;

#[cfg(feature = "browser")]
pub mod keystore_api;
#[cfg(feature = "browser")]
mod web_keystore;
#[cfg(feature = "browser")]
mod web_keystore_callbacks;
#[cfg(feature = "browser")]
mod web_keystore_db;
#[cfg(feature = "browser")]
pub use web_keystore::WebKeyStore;

// The multi-threaded build is meaningful only for the browser WASM target —
// wasm-bindgen-rayon bootstraps its thread pool over Web Workers, which do
// not exist under the napi Node.js binding (Node-side parallelism comes from
// the native tokio/rayon stack instead).
#[cfg(all(feature = "mt-threads", feature = "nodejs"))]
compile_error!("feature \"mt-threads\" is browser-only and cannot be combined with \"nodejs\"");

// 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", feature = "browser"))]
#[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", feature = "browser"))]
#[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()
}

/// MT diagnostics: report which rayon threads execute a tiny par_iter when
/// dispatched from a plain synchronous wasm export. `outer` is the calling
/// thread's pool index (-1 = external), `inside` the distinct pool indexes
/// that ran chunks.
#[cfg(all(feature = "mt-threads", feature = "testing", feature = "browser"))]
#[wasm_bindgen(js_name = "mtProbeSync")]
pub fn mt_probe_sync() -> String {
    mt_probe_body()
}

/// Same probe, but exported as an async fn so it runs inside a
/// wasm-bindgen-futures task — mirroring the context `proveTransaction`
/// executes in. Divergence between the two reveals whether the futures
/// context breaks rayon dispatch.
#[cfg(all(feature = "mt-threads", feature = "testing", feature = "browser"))]
#[wasm_bindgen(js_name = "mtProbeAsync")]
pub async fn mt_probe_async() -> String {
    mt_probe_body()
}

#[cfg(all(feature = "mt-threads", feature = "testing", feature = "browser"))]
fn mt_probe_body() -> String {
    use rayon::prelude::*;
    let outer = rayon::current_thread_index().map_or(-1, |i| i as i32);
    let inside: std::collections::BTreeSet<i32> = (0..100_000)
        .into_par_iter()
        .map(|i| {
            // Enough per-item work that rayon actually splits.
            let _ = core::hint::black_box((i as f64).sqrt().sin());
            rayon::current_thread_index().map_or(-1, |i| i as i32)
        })
        .collect();
    format!("outer={outer} inside={inside:?}")
}

/// 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(all(feature = "testing", feature = "browser"))]
#[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()
}

#[cfg(feature = "browser")]
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.
#[cfg(feature = "browser")]
#[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)),
        );
    }
}

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

// SAFETY: napi-rs with `tokio_rt` uses a multi-threaded tokio runtime, so async napi
// functions run on worker threads. This is sound because the concrete types behind
// trait objects (`SqliteStore`, `GrpcClient`, `FilesystemKeyStore`) are all Send + Sync
// — only the `dyn Trait` bounds lack Send. All mutable state is behind `AsyncCell`
// (tokio::sync::Mutex), which serializes access.
#[cfg(feature = "nodejs")]
unsafe impl Send for WebClient {}
#[cfg(feature = "nodejs")]
unsafe impl Sync for WebClient {}

// Prevent deadpool's Drop from panicking on Node.js process exit.
// When napi's Tokio runtime shuts down, the SQLite connection pool tries to
// spawn_blocking during Drop, but the runtime is already gone. This causes a
// panic-in-panic (SIGABRT).
//
// We only leak when the runtime is already gone (process shutdown). During
// normal operation, the regular Drop chain runs so resources are released.
#[cfg(feature = "nodejs")]
impl Drop for WebClient {
    fn drop(&mut self) {
        if tokio::runtime::Handle::try_current().is_err() {
            let inner = std::mem::replace(&mut self.inner, AsyncCell::new(None));
            std::mem::forget(inner);
        }
    }
}

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

// Common methods shared between browser and Node.js
#[js_export]
impl WebClient {
    #[js_export(constructor)]
    pub fn new() -> Self {
        #[cfg(feature = "browser")]
        console_error_panic_hook::set_once();

        WebClient {
            inner: AsyncCell::new(None),
            mock_rpc_api: AsyncCell::new(None),
            mock_note_transport_api: AsyncCell::new(None),
        }
    }

    /// Returns the identifier of the underlying store (e.g. `IndexedDB` database name, file path).
    #[js_export(js_name = "storeIdentifier")]
    pub async fn store_identifier(&self) -> Result<String, JsErr> {
        let guard = self.inner.lock().await;
        let client = guard.as_ref().ok_or_else(|| from_str_err("Client not initialized"))?;
        Ok(client.store_identifier().to_string())
    }

    #[js_export(js_name = "createCodeBuilder")]
    pub async fn create_code_builder(&self) -> Result<CodeBuilder, JsErr> {
        let guard = self.inner.lock().await;
        let client = guard.as_ref().ok_or_else(|| {
            from_str_err("client was not initialized before instancing CodeBuilder")
        })?;
        Ok(CodeBuilder::from_source_manager(client.code_builder().source_manager().clone()))
    }
}

// Internal helpers
impl WebClient {
    pub(crate) async fn get_mut_inner(
        &self,
    ) -> impl core::ops::DerefMut<Target = Option<Client<ClientAuth>>> + '_ {
        self.inner.lock().await
    }

    pub(crate) async fn get_keystore(&self) -> Result<Arc<ClientAuth>, JsErr> {
        let guard = self.inner.lock().await;
        guard
            .as_ref()
            .and_then(|c| c.authenticator())
            .cloned()
            .ok_or_else(|| from_str_err("Client not initialized"))
    }
}

// Browser-specific client creation
#[cfg(feature = "browser")]
#[wasm_bindgen]
impl WebClient {
    /// 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 guard = self.inner.borrow();
        let ks = guard
            .as_ref()
            .and_then(|c| c.authenticator())
            .cloned()
            .ok_or_else(|| JsValue::from_str("Client not initialized"))?;
        Ok(keystore_api::WebKeystoreApi::new(ks))
    }

    /// 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 {
        let guard = self.inner.borrow();
        match guard.as_ref().and_then(|c| c.authenticator()) {
            Some(keystore) => keystore.last_sign_error(),
            None => JsValue::NULL,
        }
    }

    /// 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.
    /// * `debug_mode`: Optional flag to enable debug mode for transaction execution. When enabled,
    ///   the transaction executor records additional information useful for debugging. Defaults to
    ///   disabled.
    #[wasm_bindgen(js_name = "createClient")]
    pub async fn create_client(
        &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 rng = create_rng(seed)?;
        let store: Arc<dyn Store> = Arc::new(
            IdxdbStore::new(store_name.clone())
                .await
                .map_err(|_| JsValue::from_str("Failed to initialize IdxdbStore"))?,
        );
        let keystore = 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)
            .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.
    /// * `debug_mode`: Optional flag to enable debug mode for transaction execution. Defaults to
    ///   disabled.
    #[wasm_bindgen(js_name = "createClientWithExternalKeystore")]
    #[allow(clippy::too_many_arguments)]
    pub async fn create_client_with_external_keystore(
        &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 rng = create_rng(seed)?;
        let store: Arc<dyn Store> = Arc::new(
            IdxdbStore::new(store_name.clone())
                .await
                .map_err(|_| JsValue::from_str("Failed to initialize IdxdbStore"))?,
        );
        let keystore =
            WebKeyStore::new_with_callbacks(rng, store_name, get_key_cb, insert_key_cb, sign_cb);

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

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

    async fn setup_client(
        &self,
        rpc_client: Arc<dyn NodeRpcClient>,
        store: Arc<dyn Store>,
        keystore: WebKeyStore<RandomCoin>,
        rng: RandomCoin,
        note_transport_client: Option<Arc<dyn NoteTransportClient>>,
        debug_mode: Option<bool>,
    ) -> Result<(), JsValue> {
        let mut builder = ClientBuilder::new()
            .rpc(rpc_client)
            .rng(Box::new(rng))
            .store(store)
            .authenticator(Arc::new(keystore))
            .in_debug_mode(if debug_mode.unwrap_or(false) {
                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"))?;

        client
            .ensure_genesis_in_place()
            .await
            .map_err(|err| js_error_with_context(err, "Failed to ensure genesis in place"))?;

        *self.inner.lock().await = Some(client);

        Ok(())
    }
}

// Node.js-specific client creation
#[cfg(feature = "nodejs")]
#[napi]
impl WebClient {
    /// 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.
    /// * `db_path`: Path to the SQLite database file.
    /// * `keystore_path`: Path to the directory for storing keys.
    /// * `debug_mode`: Optional flag to enable debug mode for transaction execution. Defaults to
    ///   disabled.
    #[napi(js_name = "createClient")]
    pub async fn create_client(
        &self,
        node_url: Option<String>,
        node_note_transport_url: Option<String>,
        seed: Option<Vec<u8>>,
        db_path: String,
        keystore_path: String,
        debug_mode: Option<bool>,
    ) -> Result<String, JsErr> {
        let endpoint = node_url.map_or(Ok(Endpoint::testnet()), |url| {
            Endpoint::try_from(url.as_str()).map_err(|_| from_str_err("Invalid node URL"))
        })?;

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

        let note_transport_client = if let Some(url) = node_note_transport_url {
            let client = GrpcNoteTransportClient::new(url, DEFAULT_GRPC_TIMEOUT_MS);
            Some(Arc::new(client) as Arc<dyn NoteTransportClient>)
        } else {
            None
        };

        let rng = create_rng(seed)?;

        let store: Arc<dyn Store> = Arc::new(
            miden_client_sqlite_store::SqliteStore::new(db_path.into())
                .await
                .map_err(|e| from_str_err(&format!("Failed to initialize SqliteStore: {e}")))?,
        );

        let keystore = FilesystemKeyStore::new(keystore_path.into())
            .map_err(|e| from_str_err(&format!("Failed to initialize keystore: {e}")))?;

        self.setup_client(rpc_client, store, keystore, rng, note_transport_client, debug_mode)
            .await?;

        Ok("Client created successfully".to_string())
    }

    async fn setup_client(
        &self,
        rpc_client: Arc<dyn NodeRpcClient>,
        store: Arc<dyn Store>,
        keystore: FilesystemKeyStore,
        rng: RandomCoin,
        note_transport_client: Option<Arc<dyn NoteTransportClient>>,
        debug_mode: Option<bool>,
    ) -> Result<(), JsErr> {
        let client = maybe_wrap_send(async move {
            let mut builder = ClientBuilder::new()
                .rpc(rpc_client)
                .rng(Box::new(rng))
                .store(store)
                .authenticator(Arc::new(keystore))
                .in_debug_mode(if debug_mode.unwrap_or(false) {
                    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"))?;

            client
                .ensure_genesis_in_place()
                .await
                .map_err(|err| js_error_with_context(err, "Failed to ensure genesis in place"))?;

            Ok::<_, JsErr>(client)
        })
        .await?;

        *self.inner.lock().await = Some(client);

        Ok(())
    }
}

pub(crate) fn create_rng(seed: Option<Vec<u8>>) -> Result<RandomCoin, JsErr> {
    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(from_str_err("Seed must be exactly 32 bytes"));
            }
        },
        None => StdRng::from_os_rng(),
    };
    let coin_seed: [u64; 4] = rng.random();
    // `coin_seed` is freshly drawn `u64`s; the probability of hitting the modulus is
    // vanishing and `new_unchecked` matches the upstream Rust client's usage.
    Ok(RandomCoin::new(coin_seed.map(Felt::new_unchecked).into()))
}

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

pub(crate) fn js_error_with_context<T>(err: T, context: &str) -> JsErr
where
    T: Error + 'static,
{
    let error_message = build_error_chain(context, &err);
    let help = hint_from_error(&err);

    #[cfg(feature = "browser")]
    {
        let js_error: JsValue = JsError::new(&error_message).into();
        if let Some(help) = help {
            let _ = Reflect::set(&js_error, &JsValue::from_str("help"), &JsValue::from_str(&help));
        }
        // Stable, machine-readable code for the ClientError variants JS callers
        // branch on, so they don't have to match the (changeable) message text.
        // The worker shim's serializeError already forwards `code`.
        if let Some(code) = code_from_error(&err) {
            let _ = Reflect::set(&js_error, &JsValue::from_str("code"), &JsValue::from_str(code));
        }
        js_error
    }

    #[cfg(feature = "nodejs")]
    {
        let message = match help {
            Some(help) => format!("{error_message} [help: {help}]"),
            None => error_message,
        };
        napi::Error::from_reason(message)
    }
}

/// Walks the error chain and builds a `context: err1: err2: ...` message.
fn build_error_chain(context: &str, err: &(dyn Error + 'static)) -> String {
    let mut msg = context.to_string();
    let mut source = Some(err);
    while let Some(e) = source {
        write!(msg, ": {e}").expect("writing to string should always succeed");
        source = e.source();
    }
    msg
}

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)
}

/// Maps the typed [`ClientError`] variants that JS callers need to distinguish
/// to stable string codes (exposed as the `code` property on the thrown JS
/// error). Only the variants consumers branch on are mapped; everything else
/// returns `None`.
#[cfg(feature = "browser")]
fn code_from_error(err: &(dyn Error + 'static)) -> Option<&'static str> {
    if let Some(client_error) = err.downcast_ref::<ClientError>() {
        return match client_error {
            ClientError::AccountNotFoundOnChain(_) => Some("ACCOUNT_NOT_FOUND_ON_CHAIN"),
            ClientError::AccountAlreadyTracked(_) => Some("ACCOUNT_ALREADY_TRACKED"),
            _ => None,
        };
    }

    err.source().and_then(code_from_error)
}