moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
//! Port of
//! `@midnight-ntwrk/midnight-js-contracts/src/get-unshielded-balances.ts`.
//!
//! Thin wrapper around
//! [`PublicDataProvider::query_unshielded_balances`] that surfaces a
//! missing-balances condition as a clear error rather than the
//! provider's `Option::None`.

use moonproof_ledger::coin_structure::contract::ContractAddress;

use crate::error::{ContractRuntimeError, Result};
use crate::providers::PublicDataProvider;
use crate::types::UnshieldedBalances;
use moonproof_runtime::state::contract_address_to_hex;

/// Fetch the unshielded balances for `contract_address`. Port of TS
/// `getUnshieldedBalances`.
///
/// # Errors
///
/// - [`ContractRuntimeError::NotFound`] when the provider returns
///   `None` — mirrors TS `assertDefined(..., "No unshielded balances
///   found at contract address '...'")`.
/// - Any error propagated from the public-data provider.
pub async fn get_unshielded_balances(
    public_data: &dyn PublicDataProvider,
    contract_address: &ContractAddress,
) -> Result<UnshieldedBalances> {
    public_data
        .query_unshielded_balances(contract_address, None)
        .await?
        .ok_or_else(|| {
            ContractRuntimeError::NotFound(format!(
                "No unshielded balances found at contract address {}",
                contract_address_to_hex(contract_address),
            ))
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::providers::public_data::{PublicDataStream, ZSwapAndContractState};
    use crate::types::{
        ContractStateQueryAt, ContractStateStreamStart, FinalizedTxData, TransactionId,
        UnshieldedBalance,
    };
    use async_trait::async_trait;
    use moonproof_ledger::onchain_runtime::state::ContractState;
    use moonproof_ledger::storage::db::InMemoryDB;

    #[derive(Debug)]
    struct ScriptedProvider(Option<UnshieldedBalances>);

    #[async_trait]
    impl PublicDataProvider for ScriptedProvider {
        async fn query_contract_state(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<ContractState<InMemoryDB>>> {
            unimplemented!()
        }
        async fn query_zswap_and_contract_state(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<ZSwapAndContractState>> {
            unimplemented!()
        }
        async fn query_deploy_contract_state(
            &self,
            _address: &ContractAddress,
        ) -> Result<Option<ContractState<InMemoryDB>>> {
            unimplemented!()
        }
        async fn query_unshielded_balances(
            &self,
            _address: &ContractAddress,
            _at: Option<ContractStateQueryAt>,
        ) -> Result<Option<UnshieldedBalances>> {
            Ok(self.0.clone())
        }
        async fn watch_for_deploy_tx_data(
            &self,
            _address: &ContractAddress,
        ) -> Result<FinalizedTxData> {
            unimplemented!()
        }
        async fn watch_for_tx_data(&self, _tx_id: &TransactionId) -> Result<FinalizedTxData> {
            unimplemented!()
        }
        async fn watch_for_contract_state(
            &self,
            _address: &ContractAddress,
        ) -> Result<ContractState<InMemoryDB>> {
            unimplemented!()
        }
        async fn watch_for_unshielded_balances(
            &self,
            _address: &ContractAddress,
        ) -> Result<UnshieldedBalances> {
            unimplemented!()
        }
        async fn contract_state_stream(
            &self,
            _address: &ContractAddress,
            _start: ContractStateStreamStart,
        ) -> Result<PublicDataStream<ContractState<InMemoryDB>>> {
            unimplemented!()
        }
        async fn unshielded_balances_stream(
            &self,
            _address: &ContractAddress,
            _start: ContractStateStreamStart,
        ) -> Result<PublicDataStream<UnshieldedBalances>> {
            unimplemented!()
        }
    }

    fn dummy_address() -> ContractAddress {
        ContractAddress(moonproof_ledger::base_crypto::hash::HashOutput(
            [0x01u8; 32],
        ))
    }

    /// ports: `get-unshielded-balances.test.ts::should return unshielded balances when data exists`
    #[tokio::test]
    async fn returns_balances_when_provider_has_them() {
        let provider = ScriptedProvider(Some(vec![UnshieldedBalance {
            balance: 123,
            token_type: [0u8; 32],
        }]));
        let balances = get_unshielded_balances(&provider, &dummy_address())
            .await
            .unwrap();
        assert_eq!(balances.len(), 1);
        assert_eq!(balances[0].balance, 123);
    }

    /// ports: `get-unshielded-balances.test.ts::should throw error when no unshielded balances found`
    #[tokio::test]
    async fn errors_when_provider_returns_none() {
        let provider = ScriptedProvider(None);
        let err = get_unshielded_balances(&provider, &dummy_address())
            .await
            .unwrap_err();
        matches!(err, ContractRuntimeError::NotFound(_));
        let msg = format!("{err}");
        assert!(msg.contains("No unshielded balances"), "{msg}");
        // The TS variant interpolates the contract address into the
        // error message: `assertDefined(... 'No unshielded balances
        // found at contract address \'<addr>\'')`. We do the same so
        // diagnostic logs name the offending address.
        assert!(
            msg.contains(&moonproof_runtime::state::contract_address_to_hex(
                &dummy_address()
            )),
            "{msg}",
        );
    }

    /// ports: `get-unshielded-balances.test.ts::should return empty array when balances exist but are empty`
    ///
    /// Empty-balance contracts are still considered "found" — the
    /// provider returns `Some(Vec::new())`, not `None`. This guards
    /// against accidentally surfacing empty arrays as
    /// [`ContractRuntimeError::NotFound`].
    #[tokio::test]
    async fn returns_empty_vec_when_provider_has_empty_balances() {
        let provider = ScriptedProvider(Some(Vec::new()));
        let balances = get_unshielded_balances(&provider, &dummy_address())
            .await
            .unwrap();
        assert_eq!(balances, [] as [UnshieldedBalance; 0]);
    }

    // The TS test "should validate contract address" exercises a
    // hex-decoding step that runs before the provider call. The Rust
    // surface accepts a typed `ContractAddress` directly — there is
    // no string parsing at this layer, so the corresponding negative
    // test would have to be placed at the call site that does the hex
    // decode. The behaviour itself is exercised in
    // `moonproof_runtime::state::tests::address_hex_roundtrip_is_byte_stable`.
}