Skip to main content

miden_client/
builder.rs

1use alloc::boxed::Box;
2use alloc::sync::Arc;
3
4use miden_protocol::assembly::{DefaultSourceManager, SourceManagerSync};
5use miden_protocol::block::BlockNumber;
6use miden_protocol::crypto::rand::RpoRandomCoin;
7use miden_protocol::{Felt, MAX_TX_EXECUTION_CYCLES, MIN_TX_EXECUTION_CYCLES};
8use miden_tx::{ExecutionOptions, LocalTransactionProver};
9use rand::Rng;
10
11#[cfg(any(feature = "tonic", feature = "std"))]
12use crate::alloc::string::ToString;
13#[cfg(feature = "std")]
14use crate::keystore::FilesystemKeyStore;
15use crate::keystore::Keystore;
16use crate::note_transport::NoteTransportClient;
17use crate::rpc::{Endpoint, NodeRpcClient};
18use crate::store::{Store, StoreError};
19use crate::transaction::TransactionProver;
20use crate::{Client, ClientError, ClientRng, ClientRngBox, DebugMode, grpc_support};
21
22// CONSTANTS
23// ================================================================================================
24
25/// The default number of blocks after which pending transactions are considered stale and
26/// discarded.
27const TX_DISCARD_DELTA: u32 = 20;
28
29pub use grpc_support::*;
30
31// STORE BUILDER
32// ================================================================================================
33
34/// Allows the [`ClientBuilder`] to accept either an already built store instance or a factory for
35/// deferring the store instantiation.
36pub enum StoreBuilder {
37    Store(Arc<dyn Store>),
38    Factory(Box<dyn StoreFactory>),
39}
40
41/// Trait for building a store instance.
42#[async_trait::async_trait]
43pub trait StoreFactory {
44    /// Returns a new store instance.
45    async fn build(&self) -> Result<Arc<dyn Store>, StoreError>;
46}
47
48// CLIENT BUILDER
49// ================================================================================================
50
51/// A builder for constructing a Miden client.
52///
53/// This builder allows you to configure the various components required by the client, such as the
54/// RPC endpoint, store, RNG, and authenticator. It is generic over the authenticator type.
55///
56/// ## Network-Aware Constructors
57///
58/// Use one of the network-specific constructors to get sensible defaults for a specific network:
59/// - [`for_testnet()`](Self::for_testnet) - Pre-configured for Miden testnet
60/// - [`for_devnet()`](Self::for_devnet) - Pre-configured for Miden devnet
61/// - [`for_localhost()`](Self::for_localhost) - Pre-configured for local development
62///
63/// The builder provides defaults for:
64/// - **RPC endpoint**: Automatically configured based on the network
65/// - **Transaction prover**: Remote for testnet/devnet, local for localhost
66/// - **RNG**: Random seed-based prover randomness
67///
68/// ## Components
69///
70/// The client requires several components to function:
71///
72/// - **RPC client** ([`NodeRpcClient`]): Provides connectivity to the Miden node for submitting
73///   transactions, syncing state, and fetching account/note data. Configure via
74///   [`rpc()`](Self::rpc) or [`grpc_client()`](Self::grpc_client).
75///
76/// - **Store** ([`Store`]): Provides persistence for accounts, notes, and transaction history.
77///   Configure via [`store()`](Self::store).
78///
79/// - **RNG** ([`FeltRng`](miden_protocol::crypto::rand::FeltRng)): Provides randomness for
80///   generating keys, serial numbers, and other cryptographic operations. If not provided, a random
81///   seed-based RNG is created automatically. Configure via [`rng()`](Self::rng).
82///
83/// - **Authenticator** ([`TransactionAuthenticator`](miden_tx::auth::TransactionAuthenticator)):
84///   Handles transaction signing when signatures are requested from within the VM. Configure via
85///   [`authenticator()`](Self::authenticator).
86///
87/// - **Transaction prover** ([`TransactionProver`]): Generates proofs for transactions. Defaults to
88///   a local prover if not specified. Configure via [`prover()`](Self::prover).
89///
90/// - **Note transport** ([`NoteTransportClient`]): Optional component for exchanging private notes
91///   through the Miden note transport network. Configure via
92///   [`note_transport()`](Self::note_transport).
93///
94/// - **Debug mode**: Enables debug mode for transaction execution. Configure via
95///   [`in_debug_mode()`](Self::in_debug_mode).
96///
97/// - **Transaction discard delta**: Number of blocks after which pending transactions are
98///   considered stale and discarded. Configure via [`tx_discard_delta()`](Self::tx_discard_delta).
99///
100/// - **Max block number delta**: Maximum number of blocks the client can be behind the network for
101///   transactions and account proofs to be considered valid. Configure via
102///   [`max_block_number_delta()`](Self::max_block_number_delta).
103pub struct ClientBuilder<AUTH> {
104    /// An optional custom RPC client. If provided, this takes precedence over `rpc_endpoint`.
105    rpc_api: Option<Arc<dyn NodeRpcClient>>,
106    /// An optional store provided by the user.
107    pub store: Option<StoreBuilder>,
108    /// An optional RNG provided by the user.
109    rng: Option<ClientRngBox>,
110    /// The authenticator provided by the user.
111    authenticator: Option<Arc<AUTH>>,
112    /// A flag to enable debug mode.
113    in_debug_mode: DebugMode,
114    /// Number of blocks after which pending transactions are considered stale and discarded.
115    /// If `None`, there is no limit and transactions will be kept indefinitely.
116    tx_discard_delta: Option<u32>,
117    /// Maximum number of blocks the client can be behind the network for transactions and account
118    /// proofs to be considered valid.
119    max_block_number_delta: Option<u32>,
120    /// An optional custom note transport client.
121    note_transport_api: Option<Arc<dyn NoteTransportClient>>,
122    /// Configuration for lazy note transport initialization (used by network constructors).
123    #[allow(unused)]
124    note_transport_config: Option<NoteTransportConfig>,
125    /// An optional custom transaction prover.
126    tx_prover: Option<Arc<dyn TransactionProver + Send + Sync>>,
127    /// The endpoint used by the builder for network configuration.
128    endpoint: Option<Endpoint>,
129}
130
131impl<AUTH> Default for ClientBuilder<AUTH> {
132    fn default() -> Self {
133        Self {
134            rpc_api: None,
135            store: None,
136            rng: None,
137            authenticator: None,
138            in_debug_mode: DebugMode::Disabled,
139            tx_discard_delta: Some(TX_DISCARD_DELTA),
140            max_block_number_delta: None,
141            note_transport_api: None,
142            note_transport_config: None,
143            tx_prover: None,
144            endpoint: None,
145        }
146    }
147}
148
149/// Network-specific constructors for [`ClientBuilder`].
150///
151/// These constructors automatically configure the builder for a specific network,
152/// including RPC endpoint, transaction prover, and note transport (where applicable).
153#[cfg(feature = "tonic")]
154impl<AUTH> ClientBuilder<AUTH>
155where
156    AUTH: BuilderAuthenticator,
157{
158    /// Creates a `ClientBuilder` pre-configured for Miden testnet.
159    ///
160    /// This automatically configures:
161    /// - **RPC**: `https://rpc.testnet.miden.io`
162    /// - **Prover**: Remote prover at `https://tx-prover.testnet.miden.io`
163    /// - **Note transport**: `https://transport.miden.io`
164    ///
165    /// You still need to provide:
166    /// - A store (via `.store()`)
167    /// - An authenticator (via `.authenticator()`)
168    ///
169    /// All defaults can be overridden by calling the corresponding builder methods
170    /// after `for_testnet()`.
171    ///
172    /// # Example
173    ///
174    /// ```ignore
175    /// let client = ClientBuilder::for_testnet()
176    ///     .store(store)
177    ///     .authenticator(Arc::new(keystore))
178    ///     .build()
179    ///     .await?;
180    /// ```
181    #[must_use]
182    pub fn for_testnet() -> Self {
183        let endpoint = Endpoint::testnet();
184        Self {
185            rpc_api: Some(Arc::new(crate::rpc::GrpcClient::new(&endpoint, 10_000))),
186            tx_prover: Some(Arc::new(RemoteTransactionProver::new(
187                TESTNET_PROVER_ENDPOINT.to_string(),
188            ))),
189            note_transport_config: Some(NoteTransportConfig {
190                endpoint: crate::note_transport::NOTE_TRANSPORT_DEFAULT_ENDPOINT.to_string(),
191                timeout_ms: NOTE_TRANSPORT_DEFAULT_TIMEOUT_MS,
192            }),
193            endpoint: Some(endpoint),
194            ..Self::default()
195        }
196    }
197
198    /// Creates a `ClientBuilder` pre-configured for Miden devnet.
199    ///
200    /// This automatically configures:
201    /// - **RPC**: `https://rpc.devnet.miden.io`
202    /// - **Prover**: Remote prover at `https://tx-prover.devnet.miden.io`
203    ///
204    /// Note transport is not configured by default for devnet.
205    ///
206    /// You still need to provide:
207    /// - A store (via `.store()`)
208    /// - An authenticator (via `.authenticator()`)
209    ///
210    /// All defaults can be overridden by calling the corresponding builder methods
211    /// after `for_devnet()`.
212    ///
213    /// # Example
214    ///
215    /// ```ignore
216    /// let client = ClientBuilder::for_devnet()
217    ///     .store(store)
218    ///     .authenticator(Arc::new(keystore))
219    ///     .build()
220    ///     .await?;
221    /// ```
222    #[must_use]
223    pub fn for_devnet() -> Self {
224        let endpoint = Endpoint::devnet();
225        Self {
226            rpc_api: Some(Arc::new(crate::rpc::GrpcClient::new(&endpoint, 10_000))),
227            tx_prover: Some(Arc::new(RemoteTransactionProver::new(
228                DEVNET_PROVER_ENDPOINT.to_string(),
229            ))),
230            endpoint: Some(endpoint),
231            ..Self::default()
232        }
233    }
234
235    /// Creates a `ClientBuilder` pre-configured for localhost.
236    ///
237    /// This automatically configures:
238    /// - **RPC**: `http://localhost:57291`
239    /// - **Prover**: Local (default)
240    ///
241    /// Note transport is not configured by default for localhost.
242    ///
243    /// You still need to provide:
244    /// - A store (via `.store()`)
245    /// - An authenticator (via `.authenticator()`)
246    ///
247    /// All defaults can be overridden by calling the corresponding builder methods
248    /// after `for_localhost()`.
249    ///
250    /// # Example
251    ///
252    /// ```ignore
253    /// let client = ClientBuilder::for_localhost()
254    ///     .store(store)
255    ///     .authenticator(Arc::new(keystore))
256    ///     .build()
257    ///     .await?;
258    /// ```
259    #[must_use]
260    pub fn for_localhost() -> Self {
261        let endpoint = Endpoint::localhost();
262        Self {
263            rpc_api: Some(Arc::new(crate::rpc::GrpcClient::new(&endpoint, 10_000))),
264            endpoint: Some(endpoint),
265            ..Self::default()
266        }
267    }
268}
269
270impl<AUTH> ClientBuilder<AUTH>
271where
272    AUTH: BuilderAuthenticator,
273{
274    /// Create a new `ClientBuilder` with default settings.
275    #[must_use]
276    pub fn new() -> Self {
277        Self::default()
278    }
279
280    /// Enable or disable debug mode.
281    #[must_use]
282    pub fn in_debug_mode(mut self, debug: DebugMode) -> Self {
283        self.in_debug_mode = debug;
284        self
285    }
286
287    /// Sets a custom RPC client directly.
288    #[must_use]
289    pub fn rpc(mut self, client: Arc<dyn NodeRpcClient>) -> Self {
290        self.rpc_api = Some(client);
291        self
292    }
293
294    /// Sets a gRPC client from the endpoint and optional timeout.
295    #[must_use]
296    #[cfg(feature = "tonic")]
297    pub fn grpc_client(mut self, endpoint: &crate::rpc::Endpoint, timeout_ms: Option<u64>) -> Self {
298        self.rpc_api =
299            Some(Arc::new(crate::rpc::GrpcClient::new(endpoint, timeout_ms.unwrap_or(10_000))));
300        self
301    }
302
303    /// Provide a store to be used by the client.
304    #[must_use]
305    pub fn store(mut self, store: Arc<dyn Store>) -> Self {
306        self.store = Some(StoreBuilder::Store(store));
307        self
308    }
309
310    /// Optionally provide a custom RNG.
311    #[must_use]
312    pub fn rng(mut self, rng: ClientRngBox) -> Self {
313        self.rng = Some(rng);
314        self
315    }
316
317    /// Optionally provide a custom authenticator instance.
318    #[must_use]
319    pub fn authenticator(mut self, authenticator: Arc<AUTH>) -> Self {
320        self.authenticator = Some(authenticator);
321        self
322    }
323
324    /// Optionally set a maximum number of blocks that the client can be behind the network.
325    /// By default, there's no maximum.
326    #[must_use]
327    pub fn max_block_number_delta(mut self, delta: u32) -> Self {
328        self.max_block_number_delta = Some(delta);
329        self
330    }
331
332    /// Sets the number of blocks after which pending transactions are considered stale and
333    /// discarded.
334    ///
335    /// If a transaction has not been included in a block within this many blocks after submission,
336    /// it will be discarded. If `None`, transactions will be kept indefinitely.
337    ///
338    /// By default, the delta is set to `TX_DISCARD_DELTA` (20 blocks).
339    #[must_use]
340    pub fn tx_discard_delta(mut self, delta: Option<u32>) -> Self {
341        self.tx_discard_delta = delta;
342        self
343    }
344
345    /// Sets the number of blocks after which pending transactions are considered stale and
346    /// discarded.
347    ///
348    /// This is an alias for [`tx_discard_delta`](Self::tx_discard_delta).
349    #[deprecated(since = "0.10.0", note = "Use `tx_discard_delta` instead")]
350    #[must_use]
351    pub fn tx_graceful_blocks(mut self, delta: Option<u32>) -> Self {
352        self.tx_discard_delta = delta;
353        self
354    }
355
356    /// Sets a custom note transport client directly.
357    #[must_use]
358    pub fn note_transport(mut self, client: Arc<dyn NoteTransportClient>) -> Self {
359        self.note_transport_api = Some(client);
360        self
361    }
362
363    /// Sets a custom transaction prover.
364    #[must_use]
365    pub fn prover(mut self, prover: Arc<dyn TransactionProver + Send + Sync>) -> Self {
366        self.tx_prover = Some(prover);
367        self
368    }
369
370    /// Returns the endpoint configured for this builder, if any.
371    ///
372    /// This is set automatically when using network-specific constructors like
373    /// [`for_testnet()`](Self::for_testnet), [`for_devnet()`](Self::for_devnet),
374    /// or [`for_localhost()`](Self::for_localhost).
375    #[must_use]
376    pub fn endpoint(&self) -> Option<&Endpoint> {
377        self.endpoint.as_ref()
378    }
379
380    /// Build and return the `Client`.
381    ///
382    /// # Errors
383    ///
384    /// - Returns an error if no RPC client was provided.
385    /// - Returns an error if the store cannot be instantiated.
386    #[allow(clippy::unused_async, unused_mut)]
387    pub async fn build(mut self) -> Result<Client<AUTH>, ClientError> {
388        // Determine the RPC client to use.
389        let rpc_api: Arc<dyn NodeRpcClient> = if let Some(client) = self.rpc_api {
390            client
391        } else {
392            return Err(ClientError::ClientInitializationError(
393                "RPC client is required. Call `.rpc(...)` or `.grpc_client(...)`.".into(),
394            ));
395        };
396
397        // Ensure a store was provided.
398        let store = if let Some(store_builder) = self.store {
399            match store_builder {
400                StoreBuilder::Store(store) => store,
401                StoreBuilder::Factory(factory) => factory.build().await?,
402            }
403        } else {
404            return Err(ClientError::ClientInitializationError(
405                "Store must be specified. Call `.store(...)`.".into(),
406            ));
407        };
408
409        // Use the provided RNG, or create a default one.
410        let rng = if let Some(user_rng) = self.rng {
411            user_rng
412        } else {
413            let mut seed_rng = rand::rng();
414            let coin_seed: [u64; 4] = seed_rng.random();
415            Box::new(RpoRandomCoin::new(coin_seed.map(Felt::new).into()))
416        };
417
418        // Set default prover if not provided
419        let tx_prover: Arc<dyn TransactionProver + Send + Sync> =
420            self.tx_prover.unwrap_or_else(|| Arc::new(LocalTransactionProver::default()));
421
422        // Initialize genesis commitment in RPC client
423        if let Some((genesis, _)) = store.get_block_header_by_num(BlockNumber::GENESIS).await? {
424            rpc_api.set_genesis_commitment(genesis.commitment()).await?;
425        }
426
427        // Set the RPC client with persisted limits if available.
428        // If not present, they will be fetched from the node during sync_state.
429        if let Some(limits) = store.get_rpc_limits().await? {
430            rpc_api.set_rpc_limits(limits).await;
431        }
432
433        // Initialize note transport: prefer explicit client, fall back to config (tonic only)
434        #[cfg(feature = "tonic")]
435        if self.note_transport_api.is_none()
436            && let Some(config) = self.note_transport_config
437        {
438            #[cfg(not(target_arch = "wasm32"))]
439            let transport = crate::note_transport::grpc::GrpcNoteTransportClient::connect(
440                config.endpoint,
441                config.timeout_ms,
442            )
443            .await
444            .map_err(|e| {
445                ClientError::ClientInitializationError(format!(
446                    "Failed to connect to note transport: {e}"
447                ))
448            })?;
449
450            #[cfg(target_arch = "wasm32")]
451            let transport =
452                crate::note_transport::grpc::GrpcNoteTransportClient::new(config.endpoint);
453
454            self.note_transport_api = Some(Arc::new(transport) as Arc<dyn NoteTransportClient>);
455        }
456
457        // Create source manager for MASM source information
458        let source_manager: Arc<dyn SourceManagerSync> = Arc::new(DefaultSourceManager::default());
459
460        // Construct and return the Client
461        Ok(Client {
462            store,
463            rng: ClientRng::new(rng),
464            rpc_api,
465            tx_prover,
466            authenticator: self.authenticator,
467            source_manager,
468            exec_options: ExecutionOptions::new(
469                Some(MAX_TX_EXECUTION_CYCLES),
470                MIN_TX_EXECUTION_CYCLES,
471                false,
472                self.in_debug_mode.into(),
473            )
474            .expect("Default executor's options should always be valid"),
475            tx_discard_delta: self.tx_discard_delta,
476            max_block_number_delta: self.max_block_number_delta,
477            note_transport_api: self.note_transport_api.clone(),
478        })
479    }
480}
481
482// FILESYSTEM KEYSTORE CONVENIENCE METHOD
483// ================================================================================================
484
485/// Marker trait to capture the bounds the builder requires for the authenticator type
486/// parameter.
487#[cfg(feature = "std")]
488pub trait BuilderAuthenticator: Keystore + From<FilesystemKeyStore> + 'static {}
489#[cfg(feature = "std")]
490impl<T> BuilderAuthenticator for T where T: Keystore + From<FilesystemKeyStore> + 'static {}
491
492#[cfg(not(feature = "std"))]
493pub trait BuilderAuthenticator: Keystore + 'static {}
494#[cfg(not(feature = "std"))]
495impl<T> BuilderAuthenticator for T where T: Keystore + 'static {}
496
497/// Convenience method for [`ClientBuilder`] when using [`FilesystemKeyStore`] as the authenticator.
498#[cfg(feature = "std")]
499impl ClientBuilder<FilesystemKeyStore> {
500    /// Creates a [`FilesystemKeyStore`] from the given path and sets it as the authenticator.
501    ///
502    /// This is a convenience method that creates the keystore and configures it as the
503    /// authenticator in a single call. The keystore provides transaction signing capabilities
504    /// using keys stored on the filesystem.
505    ///
506    /// # Errors
507    ///
508    /// Returns an error if the keystore cannot be created from the given path.
509    ///
510    /// # Example
511    ///
512    /// ```ignore
513    /// let client = ClientBuilder::new()
514    ///     .rpc(rpc_client)
515    ///     .store(store)
516    ///     .filesystem_keystore("path/to/keys")?
517    ///     .build()
518    ///     .await?;
519    /// ```
520    pub fn filesystem_keystore(
521        self,
522        keystore_path: impl Into<std::path::PathBuf>,
523    ) -> Result<Self, ClientError> {
524        let keystore = FilesystemKeyStore::new(keystore_path.into())
525            .map_err(|e| ClientError::ClientInitializationError(e.to_string()))?;
526        Ok(self.authenticator(Arc::new(keystore)))
527    }
528}