moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Session entry point: derive the wallet from a seed, open the node
//! WebSocket, hand back a `WalletSession` ready for sync + submit.

use std::sync::Arc;

use anyhow::{anyhow, Context, Result};
use moonproof_node_client::{Config as NodeClientConfig, PolkadotNodeClient};
use url::Url;

use crate::testing::Wallet;

use super::network::NetworkConfig;

/// A connected wallet session: a [`Wallet`] derived from
/// the caller's seed plus open node endpoints.
pub struct WalletSession {
    pub network: NetworkConfig,
    pub wallet: Wallet,
    pub node: Arc<PolkadotNodeClient>,
}

impl WalletSession {
    /// Atomically swap the session onto `new_network` — opens the new
    /// node WebSocket first, then drops the old one. The seed and
    /// derived wallet are unchanged; addresses re-encode under the
    /// new network's `NetworkId` if you re-derive them.
    ///
    /// On failure, the session is left pointing at the original
    /// network with its original node still open.
    pub async fn reconnect(&mut self, new_network: NetworkConfig) -> Result<()> {
        let new_node = connect_node(&new_network).await?;
        self.node = new_node;
        self.network = new_network;
        Ok(())
    }
}

/// Derive a wallet from the caller's 64-byte BIP39 seed (sync). The
/// follow-up [`connect_node`] step opens the node WebSocket once the
/// caller is inside an async runtime.
pub fn derive_wallet(seed: &[u8], network: &NetworkConfig) -> Result<Wallet> {
    Wallet::from_seed(seed, network.network_id.clone())
        .map_err(|e| anyhow!("deriving wallet from seed: {e}"))
}

/// Open a node WebSocket against `network.node_ws`.
pub async fn connect_node(network: &NetworkConfig) -> Result<Arc<PolkadotNodeClient>> {
    let url = Url::parse(&network.node_ws).context("parsing node WebSocket URL")?;
    let node = PolkadotNodeClient::connect(NodeClientConfig::new(url))
        .await
        .with_context(|| format!("connecting to node at {}", network.node_ws))?;
    Ok(Arc::new(node))
}