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
//! Build, submit, and finalize a contract deploy transaction.
//!
//! `submit_deploy_tx` = create unproven deploy tx → submit + wait for
//! finalization → persist private state + signing key on success.
//!
//! # Failure behaviour
//!
//! - **Guaranteed phase failure**: tx not included in chain, error
//!   returned, **no** local state persisted.
//! - **Fallible phase failure**: tx recorded on chain with partial
//!   success, error returned, **no** local state persisted.
//! - **`SucceedEntirely`**: private state + signing key persisted in
//!   this order:
//!   1. `set_contract_address` on the private-state provider (scopes
//!      the namespace).
//!   2. `set(private_state_id, bytes)` if `options.persistent_state`
//!      is `Some`.
//!   3. `set_signing_key(address, key)`.
//!
//! # Private-state serialization
//!
//! `PrivateStateProvider::set` takes opaque `Vec<u8>`. The caller
//! pre-serializes their private state into the
//! [`DeployOptions::persistent_state`](crate::DeployOptions::persistent_state)
//! tuple — keeps the runtime agnostic to serde-vs-bincode-vs-postcard.

use rand::{CryptoRng, Rng};

use crate::error::{ContractRuntimeError, ContractsError, Result};
use crate::providers::{PrivateStateProvider, Providers};
use crate::submit_tx::{submit_tx, SubmitTxOptions};
use crate::tx_model::{FinalizedDeployTxData, FinalizedDeployTxPublicData};
use crate::unproven_deploy_tx::{create_unproven_deploy_tx, DeployOptions};
use moonproof_runtime::ir::witnesses::Witnesses;
use moonproof_runtime::ir_executable::IrExecutable;

/// Build, submit, and finalize a contract deploy transaction. On
/// `SucceedEntirely`, the initial private state (if supplied via
/// `options.persistent_state`) and signing key are persisted. On any
/// other status, a [`ContractsError::DeployTxFailed`] is returned and
/// **no local state is persisted**.
pub async fn submit_deploy_tx<W, R, C>(
    rng: &mut R,
    executable: &IrExecutable<W>,
    providers: &C,
    options: DeployOptions,
) -> Result<FinalizedDeployTxData>
where
    W: Witnesses + 'static,
    R: Rng + CryptoRng,
    C: Providers + ?Sized,
{
    // Pull persistent_state aside before consuming `options` —
    // create_unproven_deploy_tx ignores it (it's a submit-stage
    // concern), but we need it again at the persist step.
    let persistent_state = options.persistent_state.clone();

    // (1) Build the unproven deploy tx — runs the constructor, wraps
    // the resulting ContractDeploy in a Transaction, tagged-serializes
    // into bytes the proof provider can consume.
    let unproven = create_unproven_deploy_tx(rng, executable, providers, options).await?;

    // (2) Submit + wait for finalization via the three-stage
    // submit_tx pipeline.
    let unproven_tx = unproven
        .private
        .unproven_tx
        .clone()
        .expect("create_unproven_deploy_tx populates unproven_tx");
    let submit_opts = SubmitTxOptions::for_deploy(unproven_tx);
    let finalized = submit_tx(providers, submit_opts).await?;

    // (3) On non-success, fail loudly with a structured error that
    // carries the finalized tx data for diagnostics — matches TS
    // `DeployTxFailedError(finalizedTxData)`.
    if !finalized.status.is_success() {
        return Err(ContractRuntimeError::Contracts(
            ContractsError::deploy_tx_failed(finalized),
        ));
    }

    // (4) Scope + persist. Ordering matches TS exactly — address
    // first, state second, signing key third.
    providers
        .private_state()
        .set_contract_address(&unproven.public.contract_address)
        .await?;
    if let Some((psi, bytes)) = persistent_state {
        providers.private_state().set(&psi, bytes).await?;
    }
    providers
        .private_state()
        .set_signing_key(
            &unproven.public.contract_address,
            unproven.private.signing_key.clone(),
        )
        .await?;

    // (5) Assemble the finalized deploy result — combines the
    // unproven-side private data (signing key, new coins, etc.) with
    // the finalized public data (tx id, block hash, status, etc.).
    Ok(FinalizedDeployTxData {
        public: FinalizedDeployTxPublicData {
            finalized,
            contract_address: unproven.public.contract_address,
            initial_contract_state: unproven.public.initial_contract_state,
        },
        private: unproven.private,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::counter_ir_executable;
    use crate::types::{PrivateStateId, TxStatus};
    use moonproof_ledger::base_crypto::time::Timestamp;
    use moonproof_ledger::signatures::SigningKey;
    use moonproof_runtime_ir::RuntimeValue as Value;
    use rand::SeedableRng;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::{Arc, Mutex};

    /// Recording private-state provider — captures set + `set_signing_key`
    /// invocations for assertion. Different from the
    /// `ScriptedPrivateState` in `test_helpers.rs` which only records
    /// signing-key calls.
    #[derive(Debug, Default)]
    struct RecordingPrivateState {
        contract_address_count: AtomicUsize,
        recorded_states: Mutex<Vec<(PrivateStateId, Vec<u8>)>>,
        recorded_signing_keys:
            Mutex<Vec<moonproof_ledger::coin_structure::contract::ContractAddress>>,
    }

    #[moonproof_macros::async_trait]
    impl crate::providers::PrivateStateProvider for RecordingPrivateState {
        async fn set_contract_address(
            &self,
            _address: &moonproof_ledger::coin_structure::contract::ContractAddress,
        ) -> Result<()> {
            self.contract_address_count.fetch_add(1, Ordering::Relaxed);
            Ok(())
        }
        async fn set(&self, private_state_id: &PrivateStateId, state: Vec<u8>) -> Result<()> {
            self.recorded_states
                .lock()
                .unwrap()
                .push((private_state_id.clone(), state));
            Ok(())
        }
        async fn get(&self, _: &PrivateStateId) -> Result<Option<Vec<u8>>> {
            Ok(None)
        }
        async fn remove(&self, _: &PrivateStateId) -> Result<()> {
            Ok(())
        }
        async fn clear(&self) -> Result<()> {
            Ok(())
        }
        async fn set_signing_key(
            &self,
            address: &moonproof_ledger::coin_structure::contract::ContractAddress,
            _signing_key: SigningKey,
        ) -> Result<()> {
            self.recorded_signing_keys.lock().unwrap().push(*address);
            Ok(())
        }
        async fn get_signing_key(
            &self,
            _: &moonproof_ledger::coin_structure::contract::ContractAddress,
        ) -> Result<Option<SigningKey>> {
            Ok(None)
        }
        async fn remove_signing_key(
            &self,
            _: &moonproof_ledger::coin_structure::contract::ContractAddress,
        ) -> Result<()> {
            Ok(())
        }
        async fn clear_signing_keys(&self) -> Result<()> {
            Ok(())
        }
        async fn export_private_states(
            &self,
            _options: &crate::providers::ExportPrivateStatesOptions,
        ) -> Result<crate::providers::PrivateStateExport> {
            unimplemented!()
        }
        async fn import_private_states(
            &self,
            _export: &crate::providers::PrivateStateExport,
            _options: &crate::providers::ImportPrivateStatesOptions,
        ) -> Result<crate::providers::ImportPrivateStatesResult> {
            unimplemented!()
        }
        async fn export_signing_keys(
            &self,
            _options: &crate::providers::private_state::ExportSigningKeysOptions,
        ) -> Result<crate::providers::SigningKeyExport> {
            unimplemented!()
        }
        async fn import_signing_keys(
            &self,
            _export: &crate::providers::SigningKeyExport,
            _options: &crate::providers::private_state::ImportSigningKeysOptions,
        ) -> Result<crate::providers::private_state::ImportSigningKeysResult> {
            unimplemented!()
        }
    }

    fn providers_with_status(
        status: TxStatus,
    ) -> (
        crate::providers::ErasedProviders,
        Arc<RecordingPrivateState>,
    ) {
        let ps = Arc::new(RecordingPrivateState::default());
        let bundle = crate::providers::ErasedProviders::builder()
            .private_state(ps.clone())
            .public_data(Arc::new(crate::test_helpers::ScriptedPublicData {
                state: None,
                status,
                zswap_bundle: None,
            }))
            .zk_config(Arc::new(crate::test_helpers::NoopZkConfig))
            .proof(Arc::new(crate::test_helpers::PassThroughProof))
            .wallet(Arc::new(crate::test_helpers::PassThroughWallet))
            .midnight(Arc::new(crate::test_helpers::StubMidnight))
            .build();
        (bundle, ps)
    }

    fn deploy_opts(persistent_state: Option<(PrivateStateId, Vec<u8>)>) -> DeployOptions {
        DeployOptions {
            constructor_args: Value::Null,
            initial_private_state: Value::Null,
            signing_key: Some(
                moonproof_ledger::signatures::schnorr_signing_key(&[0x55u8; 32]).unwrap(),
            ),
            additional_coin_enc_public_key_mappings: None,
            current_time: Timestamp::from_secs(0),
            network_id: "local-test".to_owned(),
            persistent_state,
            fee_balancing: None,
            register_circuits: None,
        }
    }

    /// ports: `submit-deploy-tx.test.ts::successful deployment with private state ID`
    #[tokio::test]
    async fn succeed_entirely_persists_private_state_and_signing_key() {
        let (providers, ps) = providers_with_status(TxStatus::SucceedEntirely);
        let executable = counter_ir_executable().await;

        let opts = deploy_opts(Some((PrivateStateId::new("counter"), b"seeded".to_vec())));

        let mut rng = rand::rngs::StdRng::from_seed([0u8; 32]);
        let data = submit_deploy_tx(&mut rng, &executable, &providers, opts)
            .await
            .unwrap();

        assert_eq!(data.public.finalized.status, TxStatus::SucceedEntirely);
        assert!(ps.contract_address_count.load(Ordering::Relaxed) >= 1);
        let sets = ps.recorded_states.lock().unwrap();
        assert_eq!(sets.len(), 1);
        assert_eq!(sets[0].0.as_str(), "counter");
        assert_eq!(sets[0].1, b"seeded");
        let sks = ps.recorded_signing_keys.lock().unwrap();
        assert_eq!(sks.len(), 1);
        assert_eq!(sks[0], data.public.contract_address);
    }

    /// ports: `submit-deploy-tx.test.ts::successful deployment without private state ID`
    #[tokio::test]
    async fn no_private_state_id_means_no_state_persist_but_signing_key_still_set() {
        let (providers, ps) = providers_with_status(TxStatus::SucceedEntirely);
        let executable = counter_ir_executable().await;

        let opts = deploy_opts(None);

        let mut rng = rand::rngs::StdRng::from_seed([0u8; 32]);
        submit_deploy_tx(&mut rng, &executable, &providers, opts)
            .await
            .unwrap();

        assert_eq!(ps.recorded_states.lock().unwrap().len(), 0);
        assert_eq!(ps.recorded_signing_keys.lock().unwrap().len(), 1);
    }

    /// ports: `submit-deploy-tx.test.ts::failed deployment scenarios::FailEntirely`
    #[tokio::test]
    async fn fail_entirely_surfaces_deploy_tx_failed_and_does_not_persist() {
        let (providers, ps) = providers_with_status(TxStatus::FailEntirely);
        let executable = counter_ir_executable().await;

        let opts = deploy_opts(Some((PrivateStateId::new("c"), b"never".to_vec())));

        let mut rng = rand::rngs::StdRng::from_seed([0u8; 32]);
        let err = submit_deploy_tx(&mut rng, &executable, &providers, opts)
            .await
            .unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(ContractsError::DeployTxFailed { .. }),
        );
        assert_eq!(ps.recorded_states.lock().unwrap().len(), 0);
        assert_eq!(ps.recorded_signing_keys.lock().unwrap().len(), 0);
    }

    /// ports: `submit-deploy-tx.test.ts::failed deployment scenarios::FailFallible`
    #[tokio::test]
    async fn fail_fallible_also_blocks_persist() {
        let (providers, ps) = providers_with_status(TxStatus::FailFallible);
        let executable = counter_ir_executable().await;

        let opts = deploy_opts(None);

        let mut rng = rand::rngs::StdRng::from_seed([0u8; 32]);
        let err = submit_deploy_tx(&mut rng, &executable, &providers, opts)
            .await
            .unwrap_err();
        matches!(
            err,
            ContractRuntimeError::Contracts(ContractsError::DeployTxFailed { .. }),
        );
        assert_eq!(ps.recorded_signing_keys.lock().unwrap().len(), 0);
    }
}