Skip to main content

moonproof_contracts/providers/
contract_module.rs

1//! Rust port of midnight-js 5's `contractModuleProvider`: the code a
2//! cross-contract call runs for each callee address, with the ZK
3//! artifacts its proofs need.
4
5use std::collections::HashMap;
6use std::sync::Arc;
7
8use moonproof_ledger::coin_structure::contract::ContractAddress;
9use moonproof_macros::async_trait;
10use moonproof_runtime_ir::ir::MoonIr;
11
12use crate::error::Result;
13use crate::providers::zk_config::ZkConfigProvider;
14
15/// A compiled contract: its runtime IR and its ZK artifacts.
16#[derive(Debug, Clone)]
17pub struct ContractModule {
18    pub ir: Arc<MoonIr>,
19    pub zk_config: Arc<dyn ZkConfigProvider>,
20}
21
22/// Binds callee addresses to the code deployed there.
23///
24/// A binding is checked before it is used: the module must implement
25/// the contract type the caller declares, and its verifier keys must be
26/// the ones deployed at the address.
27#[async_trait]
28pub trait ContractModuleProvider: Send + Sync + std::fmt::Debug {
29    /// The module for `address`, or `Ok(None)` when this provider binds
30    /// nothing there.
31    async fn resolve(&self, address: &ContractAddress) -> Result<Option<ContractModule>>;
32}
33
34#[async_trait]
35impl<T: ContractModuleProvider + ?Sized> ContractModuleProvider for Arc<T> {
36    async fn resolve(&self, address: &ContractAddress) -> Result<Option<ContractModule>> {
37        (**self).resolve(address).await
38    }
39}
40
41/// A fixed address-to-module map.
42#[derive(Debug, Clone, Default)]
43pub struct ContractModuleRegistry {
44    modules: HashMap<ContractAddress, ContractModule>,
45}
46
47impl ContractModuleRegistry {
48    #[must_use]
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    #[must_use]
54    pub fn with(mut self, address: ContractAddress, module: ContractModule) -> Self {
55        self.insert(address, module);
56        self
57    }
58
59    pub fn insert(&mut self, address: ContractAddress, module: ContractModule) {
60        self.modules.insert(address, module);
61    }
62}
63
64#[async_trait]
65impl ContractModuleProvider for ContractModuleRegistry {
66    async fn resolve(&self, address: &ContractAddress) -> Result<Option<ContractModule>> {
67        Ok(self.modules.get(address).cloned())
68    }
69}