moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Fluent constructor for [`WalletSession`] (and optionally an
//! initial synced [`FacadeState`]).
//!
//! Mirror of `midnight-wallet/packages/runtime/src/WalletBuilder.ts`,
//! collapsed to the moonproof shape:
//!
//! 1. pick a network (preset or full [`NetworkConfig`]),
//! 2. supply a seed (raw bytes, hex, mnemonic, prebuilt [`HDWallet`],
//!    or the genesis test seed),
//! 3. (optionally) auto-sync against the indexer to land an initial
//!    [`FacadeState`].
//!
//! Today, dApp / cli / bridge code does these three steps inline:
//! - `chain::resolve_network(...)` (cli) or
//!   `session::preset_by_name(...)` + manual override (bridge),
//! - `derive_wallet(seed, &network)` →
//!   `WalletSession { network, wallet, node }`,
//! - `sync_wallet_fresh(&session)` for bootstrap.
//!
//! This builder consolidates the chain into one expression, with
//! compile-time enforcement that both `network` and `seed` were
//! provided before [`WalletSessionBuilder::build`].
//!
//! ## Example — bootstrap a session + initial state in one line:
//!
//! ```ignore
//! use moonproof_wallet::session::WalletSessionBuilder;
//!
//! let (session, state) = WalletSessionBuilder::new()
//!     .network_preset("localdev")?
//!     .mnemonic("abandon abandon ... art", "")
//!     .build_and_sync()
//!     .await?;
//! ```
//!
//! ## Example — production code wiring the builder behind a CLI flag:
//!
//! ```ignore
//! let session = WalletSessionBuilder::new()
//!     .network(network_config)
//!     .seed(seed_bytes)
//!     .build()
//!     .await?;
//! ```

use anyhow::{anyhow, Result};

use crate::facade::FacadeState;
use crate::hd::HDWallet;

use super::connect::{connect_node, derive_wallet, WalletSession};
use super::network::NetworkConfig;
use super::presets::preset_by_name;
use super::sync::sync_wallet_fresh;

/// Source of the wallet's master seed. Variants are mutually
/// exclusive — the most recently set wins. Not `Debug`/`Clone`
/// because [`HDWallet`] holds private key material that shouldn't be
/// trivially duplicated; the builder consumes the variant on
/// `build()`.
enum SeedSource {
    /// Raw 16..=64 byte master seed.
    Bytes(Vec<u8>),
    /// Hex-encoded master seed (with or without `0x` prefix).
    Hex(String),
    /// BIP39 mnemonic phrase + optional passphrase.
    Mnemonic { phrase: String, passphrase: String },
    /// Pre-built [`HDWallet`] — for callers that already derived the
    /// HD root through their own path.
    Hd(HDWallet),
    /// Deterministic genesis test seed (NEVER use for real funds).
    /// Mirrors [`crate::testing::Wallet::genesis`].
    GenesisTest,
}

/// Fluent builder for a [`WalletSession`]. Required: network + seed.
/// Build with [`build`](Self::build) for offline construction (no
/// indexer touch) or [`build_and_sync`](Self::build_and_sync) to
/// also drain history into a [`FacadeState`].
#[derive(Default)]
pub struct WalletSessionBuilder {
    network: Option<NetworkConfig>,
    seed: Option<SeedSource>,
}

impl WalletSessionBuilder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    // --- Network -------------------------------------------------------

    /// Use the supplied [`NetworkConfig`] verbatim. Caller-built
    /// configs win over preset lookups.
    #[must_use]
    pub fn network(mut self, network: NetworkConfig) -> Self {
        self.network = Some(network);
        self
    }

    /// Resolve a preset by name (e.g. `"localdev"`, `"testnet"`).
    /// Errors if the name doesn't match any built-in preset.
    pub fn network_preset(mut self, name: &str) -> Result<Self> {
        let preset = preset_by_name(name)
            .ok_or_else(|| anyhow!("unknown network preset `{name}`"))?
            .authenticated_from_env()?;
        self.network = Some(preset);
        Ok(self)
    }

    // --- Seed ----------------------------------------------------------

    /// Use raw seed bytes (16..=64 per BIP32). Master seed, NOT a
    /// BIP39 mnemonic-seed.
    #[must_use]
    pub fn seed(mut self, bytes: impl Into<Vec<u8>>) -> Self {
        self.seed = Some(SeedSource::Bytes(bytes.into()));
        self
    }

    /// Use a hex-encoded master seed. `0x` prefix optional.
    #[must_use]
    pub fn hex_seed(mut self, hex: impl Into<String>) -> Self {
        self.seed = Some(SeedSource::Hex(hex.into()));
        self
    }

    /// Use a BIP39 mnemonic phrase + passphrase. Pass `""` for
    /// `passphrase` if no extra entropy is wanted.
    #[must_use]
    pub fn mnemonic(mut self, phrase: impl Into<String>, passphrase: impl Into<String>) -> Self {
        self.seed = Some(SeedSource::Mnemonic {
            phrase: phrase.into(),
            passphrase: passphrase.into(),
        });
        self
    }

    /// Use a pre-built [`HDWallet`] root. The builder will derive the
    /// wallet's three role secrets at account 0 / index 0 from this
    /// root.
    #[must_use]
    pub fn hd_wallet(mut self, hd: HDWallet) -> Self {
        self.seed = Some(SeedSource::Hd(hd));
        self
    }

    /// Use the deterministic genesis test seed. **Never** use for
    /// real funds — the genesis seed is `0x00..01`, publicly known.
    #[must_use]
    pub fn genesis_test_wallet(mut self) -> Self {
        self.seed = Some(SeedSource::GenesisTest);
        self
    }

    // --- Terminal ------------------------------------------------------

    /// Construct a [`WalletSession`] without touching the indexer.
    /// Errors if `network` or `seed` was not supplied.
    pub async fn build(self) -> Result<WalletSession> {
        let network = self
            .network
            .ok_or_else(|| anyhow!("WalletSessionBuilder: network not set"))?;
        let seed = self
            .seed
            .ok_or_else(|| anyhow!("WalletSessionBuilder: seed not set"))?;
        let wallet = match seed {
            SeedSource::Bytes(bytes) => derive_wallet(&bytes, &network)?,
            SeedSource::Hex(hex) => {
                let bytes = moonproof_utils::parse_hex(&hex)
                    .map_err(|e| anyhow!("hex_seed: invalid hex: {e}"))?;
                derive_wallet(&bytes, &network)?
            }
            SeedSource::Mnemonic { phrase, passphrase } => {
                let hd = HDWallet::from_mnemonic(&phrase, &passphrase)
                    .map_err(|e| anyhow!("from_mnemonic: {e}"))?;
                crate::testing::Wallet::from_hd_wallet(&hd, network.network_id.clone())
                    .map_err(|e| anyhow!("derive from mnemonic HD: {e}"))?
            }
            SeedSource::Hd(hd) => {
                crate::testing::Wallet::from_hd_wallet(&hd, network.network_id.clone())
                    .map_err(|e| anyhow!("derive from HD wallet: {e}"))?
            }
            SeedSource::GenesisTest => crate::testing::Wallet::genesis(network.network_id.clone())
                .map_err(|e| anyhow!("derive genesis test wallet: {e}"))?,
        };
        let node = connect_node(&network).await?;
        Ok(WalletSession {
            network,
            wallet,
            node,
        })
    }

    /// Like [`build`] but also runs [`sync_wallet_fresh`] to load the
    /// initial [`FacadeState`]. The returned tuple is ready to feed
    /// into [`crate::runtime::WalletRuntime::new`] for perpetual
    /// operation:
    ///
    /// ```ignore
    /// let (session, initial) = WalletSessionBuilder::new()
    ///     .network_preset("localdev")?
    ///     .mnemonic(phrase, "")
    ///     .build_and_sync()
    ///     .await?;
    /// let runtime = WalletRuntime::new(initial);
    /// ```
    pub async fn build_and_sync(self) -> Result<(WalletSession, FacadeState)> {
        let session = self.build().await?;
        let state = sync_wallet_fresh(&session).await?;
        Ok((session, state))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test(flavor = "current_thread")]
    async fn build_errors_without_network() {
        let result = WalletSessionBuilder::new().seed([1u8; 32]).build().await;
        let msg = match result {
            Ok(_) => panic!("build should have errored without network"),
            Err(e) => format!("{e}"),
        };
        assert!(msg.contains("network"));
    }

    #[tokio::test(flavor = "current_thread")]
    async fn build_errors_without_seed() {
        let preset = preset_by_name("localdev").expect("localdev preset present");
        let result = WalletSessionBuilder::new().network(preset).build().await;
        let msg = match result {
            Ok(_) => panic!("build should have errored without seed"),
            Err(e) => format!("{e}"),
        };
        assert!(msg.contains("seed"));
    }

    #[test]
    fn network_preset_errors_on_unknown_name() {
        let result = WalletSessionBuilder::new().network_preset("ghost-net");
        let msg = match result {
            Ok(_) => panic!("expected unknown-preset error"),
            Err(e) => format!("{e}"),
        };
        assert!(msg.contains("ghost-net"));
    }

    #[test]
    fn fluent_chain_compiles() {
        let _b = WalletSessionBuilder::new()
            .network_preset("localdev")
            .unwrap()
            .mnemonic("abandon abandon abandon", "");
    }

    #[test]
    fn most_recent_seed_call_wins() {
        // Set hex_seed then override via genesis_test_wallet — last
        // wins. Compile-time check + behavioural assertion that the
        // SeedSource enum carries the latest value.
        let b = WalletSessionBuilder::new()
            .hex_seed("0xab")
            .genesis_test_wallet();
        assert!(matches!(b.seed, Some(SeedSource::GenesisTest)));
    }
}