moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Preview helpers — build a transfer/swap/registration recipe against
//! a **clone** of the facade state and return an estimated cost summary
//! without committing the in-memory state mutations the recipe would
//! otherwise produce.
//!
//! Mirrors midnight-wallet's preview surface (planned port of TS
//! `previewTransfer` / `previewSwap`). Wallet UIs use this to show the
//! caller the dust fee + dust-input count *before* asking for a
//! signature.
//!
//! ## Caveat
//!
//! Fee estimation goes through [`super::transfer::estimate_unproven_fee`]
//! which uses `INITIAL_PARAMETERS`. For a chain-accurate number, fetch
//! live parameters via
//! [`super::submission::fetch_chain_parameters`] and call
//! `tx.fees_with_margin(&params, FEE_BLOCKS_MARGIN)` directly. The
//! offline preview is correct to within the parameter drift between
//! genesis and the latest block — large enough for UX previews, not
//! for hard cost contracts.

use rand::{CryptoRng, Rng};

use crate::error::Result;
use crate::facade::registration::{
    build_deregistration_recipe, build_registration_recipe, RegistrationParams,
    SignedRegistrationRecipe,
};
use crate::facade::state::FacadeState;
use crate::facade::swap::{build_init_swap_recipe, SwapOptions, SwapSigningKeys};
use crate::facade::transfer::{
    build_transfer_recipe, estimate_unproven_fee, CombinedTokenTransfer, TransferOptions,
    TransferSigningKeys, UnprovenTransaction, UnprovenTransactionRecipe,
};
use crate::unshielded::UtxoWithMeta;
use moonproof_ledger::ledger::dust::DustPublicKey;

// ---------------------------------------------------------------------------
// Preview shapes
// ---------------------------------------------------------------------------

/// Cost summary attached to every preview. Returned alongside the
/// underlying recipe so the caller can either discard the preview or
/// commit by handing the recipe to
/// [`crate::facade::submission::finalize_recipe`].
#[derive(Debug, Clone)]
pub struct PreviewCost {
    /// Approximate dust fee (in specks) the recipe will pay. Computed
    /// against [`moonproof_ledger::ledger::structure::INITIAL_PARAMETERS`] —
    /// callers that need the chain-accurate number should re-estimate
    /// against fresh parameters fetched via
    /// [`crate::facade::submission::fetch_chain_parameters`].
    pub estimated_dust_fee: u128,
}

/// Preview of a [`build_transfer_recipe`] call. Holds both the cost
/// summary and the prepared recipe; the caller decides whether to
/// drop it or sign + submit.
#[derive(Debug, Clone)]
pub struct TransferPreview {
    pub cost: PreviewCost,
    pub recipe: UnprovenTransactionRecipe,
    pub shielded_outputs: Vec<crate::facade::transfer::ShieldedTokenTransfer>,
    pub unshielded_outputs: Vec<crate::facade::transfer::UnshieldedTokenTransfer>,
}

/// Preview of a [`build_init_swap_recipe`] call.
#[derive(Debug, Clone)]
pub struct SwapPreview {
    pub cost: PreviewCost,
    pub recipe: UnprovenTransactionRecipe,
}

/// Preview of a [`build_registration_recipe`] / [`build_deregistration_recipe`]
/// call. Registration recipes carry pre-signed intents, so the recipe
/// type differs from transfer/swap.
#[derive(Debug, Clone)]
pub struct RegistrationPreview {
    pub cost: PreviewCost,
    pub recipe: SignedRegistrationRecipe,
    pub night_utxo_count: usize,
}

// ---------------------------------------------------------------------------
// Preview functions
// ---------------------------------------------------------------------------

/// Run [`build_transfer_recipe`] against a clone of `state` and return
/// the recipe + cost summary without mutating the caller's state.
///
/// ## Errors
///
/// Surfaces every error [`build_transfer_recipe`] would raise.
pub fn preview_transfer<R>(
    rng: &mut R,
    state: &FacadeState,
    outputs: &[CombinedTokenTransfer],
    keys: &TransferSigningKeys<'_>,
    options: &TransferOptions,
) -> Result<TransferPreview>
where
    R: Rng + CryptoRng,
{
    let (recipe, _new_state) = build_transfer_recipe(rng, state.clone(), outputs, keys, options)?;
    let estimated_dust_fee = estimate_unproven_fee(&recipe.transaction, state.ledger_parameters());
    let (shielded_outputs, unshielded_outputs) = split_outputs(outputs);
    Ok(TransferPreview {
        cost: PreviewCost { estimated_dust_fee },
        recipe,
        shielded_outputs,
        unshielded_outputs,
    })
}

/// Run [`build_init_swap_recipe`] against a clone of `state` and return
/// the recipe + cost summary without mutating the caller's state.
///
/// `shielded_leg` / `unshielded_leg` are the same arguments
/// [`build_init_swap_recipe`] takes — pre-built unproven transactions
/// for either side of the swap. At least one must be `Some`.
pub fn preview_swap<R>(
    rng: &mut R,
    state: &FacadeState,
    shielded_leg: Option<UnprovenTransaction>,
    unshielded_leg: Option<UnprovenTransaction>,
    keys: &SwapSigningKeys<'_>,
    options: &SwapOptions,
) -> Result<SwapPreview>
where
    R: Rng + CryptoRng,
{
    let (recipe, _new_state) = build_init_swap_recipe(
        rng,
        state.clone(),
        shielded_leg,
        unshielded_leg,
        keys,
        options,
    )?;
    let estimated_dust_fee = estimate_unproven_fee(&recipe.transaction, state.ledger_parameters());
    Ok(SwapPreview {
        cost: PreviewCost { estimated_dust_fee },
        recipe,
    })
}

/// Run [`build_registration_recipe`] against a clone of `state` and
/// return the recipe + cost summary. Use [`preview_deregistration`] for
/// the deregistration variant.
pub fn preview_registration<R>(
    rng: &mut R,
    state: &FacadeState,
    night_utxos: &[UtxoWithMeta],
    dust_receiver: DustPublicKey,
    params: &RegistrationParams<'_>,
) -> Result<RegistrationPreview>
where
    R: Rng + CryptoRng,
{
    let (recipe, _new_state) =
        build_registration_recipe(rng, state.clone(), night_utxos, dust_receiver, params)?;
    let estimated_dust_fee =
        estimate_unproven_fee(&recipe.recipe.transaction, state.ledger_parameters());
    Ok(RegistrationPreview {
        cost: PreviewCost { estimated_dust_fee },
        recipe,
        night_utxo_count: night_utxos.len(),
    })
}

/// Run [`build_deregistration_recipe`] against a clone of `state` and
/// return the recipe + cost summary.
pub fn preview_deregistration<R>(
    rng: &mut R,
    state: &FacadeState,
    night_utxos: &[UtxoWithMeta],
    params: &RegistrationParams<'_>,
) -> Result<RegistrationPreview>
where
    R: Rng + CryptoRng,
{
    let (recipe, _new_state) =
        build_deregistration_recipe(rng, state.clone(), night_utxos, params)?;
    let estimated_dust_fee =
        estimate_unproven_fee(&recipe.recipe.transaction, state.ledger_parameters());
    Ok(RegistrationPreview {
        cost: PreviewCost { estimated_dust_fee },
        recipe,
        night_utxo_count: night_utxos.len(),
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn split_outputs(
    outputs: &[CombinedTokenTransfer],
) -> (
    Vec<crate::facade::transfer::ShieldedTokenTransfer>,
    Vec<crate::facade::transfer::UnshieldedTokenTransfer>,
) {
    let mut shielded = Vec::new();
    let mut unshielded = Vec::new();
    for o in outputs {
        match o {
            CombinedTokenTransfer::Shielded(v) => shielded.extend(v.iter().cloned()),
            CombinedTokenTransfer::Unshielded(v) => unshielded.extend(v.iter().cloned()),
        }
    }
    (shielded, unshielded)
}