odra_cli/
utils.rs

1use odra::{
2    contract_def::HasIdent,
3    host::{Deployer, HostEnv, InstallConfig},
4    prelude::Addressable,
5    OdraContract
6};
7
8use crate::{ContractProvider, DeployedContractsContainer};
9
10/// Logs a message to the console.
11pub fn log<T: ToString>(msg: T) {
12    prettycli::info(&msg.to_string());
13}
14
15/// Trait that extends the functionality of OdraContract to include deployment capabilities.
16pub trait DeployerExt: Sized {
17    /// Contract that implements OdraContract and Deployer for Self
18    type Contract: OdraContract + 'static + Deployer<Self::Contract>;
19
20    /// Load an existing contract instance from container or deploy a new one.
21    fn load_or_deploy(
22        env: &HostEnv,
23        args: <<Self as DeployerExt>::Contract as OdraContract>::InitArgs,
24        container: &mut DeployedContractsContainer,
25        gas: u64
26    ) -> Result<<<Self as DeployerExt>::Contract as OdraContract>::HostRef, crate::deploy::Error>
27    {
28        if let Ok(contract) = container.contract_ref::<Self::Contract>(env) {
29            prettycli::info(&format!(
30                "Using existing contract {} at address {:?}",
31                <Self::Contract as OdraContract>::HostRef::ident(),
32                contract.address()
33            ));
34            Ok(contract)
35        } else {
36            env.set_gas(gas);
37            let contract = Self::Contract::try_deploy(env, args)?;
38            container.add_contract(&contract)?;
39            Ok(contract)
40        }
41    }
42
43    /// Load an existing contract instance from container or deploy a new one with a custom configuration.
44    fn load_or_deploy_with_cfg(
45        env: &HostEnv,
46        args: <<Self as DeployerExt>::Contract as OdraContract>::InitArgs,
47        cfg: InstallConfig,
48        container: &mut DeployedContractsContainer,
49        gas: u64
50    ) -> Result<<<Self as DeployerExt>::Contract as OdraContract>::HostRef, crate::deploy::Error>
51    {
52        if let Ok(contract) = container.contract_ref::<Self::Contract>(env) {
53            prettycli::info(&format!(
54                "Using existing contract {} at address {:?}",
55                <Self::Contract as OdraContract>::HostRef::ident(),
56                contract.address()
57            ));
58            Ok(contract)
59        } else {
60            env.set_gas(gas);
61            let contract = Self::Contract::try_deploy_with_cfg(env, args, cfg)?;
62            container.add_contract(&contract)?;
63            Ok(contract)
64        }
65    }
66}
67
68impl<T: OdraContract + Deployer<T> + 'static> DeployerExt for T {
69    type Contract = T;
70}