moonproof-contracts 0.2.2

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Contract-tx dust-fee balancing.
//!
//! Unblocks live-harness submission of contract deploys and calls. The
//! moonproof submit pipeline splits `prove → balance → submit`, where
//! `balance` is a pure seal — fee coverage isn't added in `balance_tx`.
//! Instead, this module attaches the dust-balancing intent to the
//! **unproven** contract tx so that `ProofProvider::prove_tx` proves
//! the contract intent + the dust spend in one pass, `balance_tx`
//! seals the combined result, and `submit_tx` submits.
//!
//! Mirrors what the wallet facade's `build_transfer_recipe` already
//! does for transfer/swap recipes — the underlying helper
//! [`moonproof_wallet::balance_dust_fee`] is shared verbatim.
//!
//! # Who owns the dust state?
//!
//! The caller. `FeeBalancingConfig` holds the `DustState` +
//! `DustSecretKey` by value / reference; the facade-driven sync code
//! advances them via `fold_dust_events` before the caller hands them
//! to this module. After submission, the caller re-syncs via the
//! indexer — we don't try to thread the post-spend `DustState` back
//! out through the submit pipeline, because the canonical state is
//! whatever the indexer reports once the tx lands in a block.

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::dust::DustSecretKey;
use moonproof_ledger::ledger::structure::LedgerParameters;
use moonproof_wallet::{DustState, FacadeState};

use crate::error::{ContractRuntimeError, Result};

/// Parameters for injecting a dust-fee balancing intent into a
/// contract transaction before [`ProofProvider::prove_tx`].
///
/// Construct via [`FeeBalancingConfig::new`]. The struct holds the
/// `DustState` by value (cloned once at the balance site —
/// `DustState::clone` is cheap because storage is `Arc`-backed
/// internally) so callers can freely re-use their facade state.
///
/// # Fields
///
/// - `dust_state` — the current sub-wallet-owned dust state. Must be
///   populated with the latest dust events the indexer has reported
///   (typically via [`moonproof_wallet::fold_dust_events`]).
/// - `dust_secret_key` — the caller's dust secret key, used to sign
///   dust spends.
/// - `current_time` — chain-tip timestamp used as the dust spend's
///   `ctime`. Must be chain-derived — see
///   [`moonproof_wallet::fetch_chain_parameters`].
/// - `ttl` — TTL stamped on the dust-balancing intent. Typically
///   `current_time + Duration::from_secs(3_600)` to align with
///   `ttl_one_hour`.
/// - `ledger_parameters` — the parameters of the block `current_time`
///   comes from. The fee is priced against their fee prices, which move
///   per block.
#[derive(Debug, Clone)]
pub struct FeeBalancingConfig {
    pub dust_state: DustState,
    pub dust_secret_key: DustSecretKey,
    pub current_time: Timestamp,
    pub ttl: Timestamp,
    pub ledger_parameters: LedgerParameters,
}

impl FeeBalancingConfig {
    /// Construct a new config. Clones the inputs — callers that want
    /// to avoid the `DustState` clone can use struct-literal
    /// construction directly.
    #[must_use]
    pub fn new(
        dust_state: DustState,
        dust_secret_key: DustSecretKey,
        current_time: Timestamp,
        ttl: Timestamp,
        ledger_parameters: LedgerParameters,
    ) -> Self {
        Self {
            dust_state,
            dust_secret_key,
            current_time,
            ttl,
            ledger_parameters,
        }
    }

    /// The config for a wallet state the sync driver produced, which
    /// carries the tip time and ledger parameters of one block.
    #[must_use]
    pub fn from_synced(
        synced: &FacadeState,
        dust_secret_key: DustSecretKey,
        ttl: Timestamp,
    ) -> Self {
        Self::new(
            synced.dust.clone(),
            dust_secret_key,
            synced.chain_tip_ts(),
            ttl,
            synced.ledger_parameters().clone(),
        )
    }
}

/// Merge a dust-fee balancing intent into `tx`. Delegates to
/// [`moonproof_wallet::balance_dust_fee`]; the only translation layer
/// is the error mapping (`WalletError` → [`ContractRuntimeError::Wallet`]).
///
/// Returns the merged unproven transaction. The caller is responsible
/// for re-syncing their `DustState` from the indexer after submission
/// — this helper discards the post-spend state because the contract-
/// runtime layer doesn't carry facade state through its submit
/// pipeline.
pub fn apply_fee_balancing<R>(
    rng: &mut R,
    #[expect(
        clippy::needless_pass_by_value,
        reason = "exported signature; callers hand over the transaction they are replacing with the balanced one"
    )]
    tx: moonproof_wallet::UnprovenTransaction,
    config: &FeeBalancingConfig,
    network_id: &str,
) -> Result<moonproof_wallet::UnprovenTransaction>
where
    R: rand::Rng + rand::CryptoRng,
{
    let (_dust_state_after, merged) = moonproof_wallet::balance_dust_fee(
        rng,
        config.dust_state.clone(),
        &config.dust_secret_key,
        &tx,
        &moonproof_wallet::FeeContext {
            current_time: config.current_time,
            ttl: config.ttl,
            network_id,
            ledger_parameters: &config.ledger_parameters,
        },
    )
    .map_err(ContractRuntimeError::Wallet)?;
    Ok(merged)
}

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

    fn assert_send_sync<T: Send + Sync>() {}

    #[test]
    fn fee_balancing_config_is_send_sync() {
        assert_send_sync::<FeeBalancingConfig>();
    }
}