1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use abstract_core::{
    manager::ModuleInstallConfig,
    objects::module::{ModuleInfo, ModuleVersion},
};
use cosmwasm_std::to_json_binary;
use cw_orch::prelude::{CwOrchError::StdErr, *};
use semver::Version;
use serde::Serialize;

use crate::Abstract;

/// Trait to access module information tied directly to the type.
pub trait RegisteredModule {
    /// The init message for the module.
    type InitMsg: Serialize;
    /// The id of the module.
    fn module_id<'a>() -> &'a str;
    /// The version of the module.
    fn module_version<'a>() -> &'a str;
}

/// Trait to access module dependency information tied directly to the type.
pub trait DependencyCreation {
    /// Type that exposes the dependencies's configurations if that's required.
    type DependenciesConfig;

    /// Function that returns the [`ModuleInstallConfig`] for each dependent module.
    #[allow(unused_variables)]
    fn dependency_install_configs(
        configuration: Self::DependenciesConfig,
    ) -> Result<Vec<ModuleInstallConfig>, crate::AbstractInterfaceError> {
        Ok(vec![])
    }
}

/// Trait to make it easier to construct [`ModuleInfo`] and [`ModuleInstallConfig`] for a
/// [`RegisteredModule`].
pub trait InstallConfig: RegisteredModule {
    /// Constructs the [`ModuleInfo`] by using information from [`RegisteredModule`].
    fn module_info() -> Result<ModuleInfo, crate::AbstractInterfaceError> {
        ModuleInfo::from_id(Self::module_id(), Self::module_version().into()).map_err(Into::into)
    }

    /// Constructs the [`ModuleInstallConfig`] for an App Interface
    fn install_config(
        init_msg: &Self::InitMsg,
    ) -> Result<ModuleInstallConfig, crate::AbstractInterfaceError> {
        Ok(ModuleInstallConfig::new(
            Self::module_info()?,
            Some(to_json_binary(init_msg)?),
        ))
    }
}

// Blanket implemention.
impl<T> InstallConfig for T where T: RegisteredModule {}

/// Strategy for deploying
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeployStrategy {
    /// Error if already present
    Error,
    /// Ignore if already present
    Try,
    /// Force deployment
    Force,
}

/// Trait for deploying Adapters
pub trait AdapterDeployer<Chain: CwEnv, CustomInitMsg: Serialize>: ContractInstance<Chain>
    + CwOrchInstantiate<Chain, InstantiateMsg = abstract_core::adapter::InstantiateMsg<CustomInitMsg>>
    + Uploadable
    + Sized
{
    /// Deploys the adapter. If the adapter is already deployed, it will return an error.
    /// Use `maybe_deploy` if you want to deploy the adapter only if it is not already deployed.
    fn deploy(
        &self,
        version: Version,
        custom_init_msg: CustomInitMsg,
        strategy: DeployStrategy,
    ) -> Result<(), crate::AbstractInterfaceError> {
        // retrieve the deployment
        let abstr = Abstract::load_from(self.get_chain().to_owned())?;

        // check for existing version, if not force strategy
        let version_check = || {
            abstr
                .version_control
                .get_adapter_addr(&self.id(), ModuleVersion::from(version.to_string()))
        };

        match strategy {
            DeployStrategy::Error => {
                if version_check().is_ok() {
                    return Err(StdErr(format!(
                        "Adapter {} already exists with version {}",
                        self.id(),
                        version
                    ))
                    .into());
                }
            }
            DeployStrategy::Try => {
                if version_check().is_ok() {
                    return Ok(());
                }
            }
            DeployStrategy::Force => {}
        }

        if self.upload_if_needed()?.is_some() {
            let init_msg = abstract_core::adapter::InstantiateMsg {
                module: custom_init_msg,
                base: abstract_core::adapter::BaseInstantiateMsg {
                    ans_host_address: abstr.ans_host.address()?.into(),
                    version_control_address: abstr.version_control.address()?.into(),
                },
            };
            self.instantiate(&init_msg, None, None)?;

            abstr
                .version_control
                .register_adapters(vec![(self.as_instance(), version.to_string())])?;
        }
        Ok(())
    }
}

/// Trait for deploying APPs
pub trait AppDeployer<Chain: CwEnv>: Sized + Uploadable + ContractInstance<Chain> {
    /// Deploys the app. If the app is already deployed, it will return an error.
    /// Use `maybe_deploy` if you want to deploy the app only if it is not already deployed.
    fn deploy(
        &self,
        version: Version,
        strategy: DeployStrategy,
    ) -> Result<(), crate::AbstractInterfaceError> {
        // retrieve the deployment
        let abstr = Abstract::<Chain>::load_from(self.get_chain().to_owned())?;

        // check for existing version
        let version_check = || {
            abstr
                .version_control
                .get_app_code(&self.id(), ModuleVersion::from(version.to_string()))
        };

        match strategy {
            DeployStrategy::Error => {
                if version_check().is_ok() {
                    return Err(StdErr(format!(
                        "App {} already exists with version {}",
                        self.id(),
                        version
                    ))
                    .into());
                }
            }
            DeployStrategy::Try => {
                if version_check().is_ok() {
                    return Ok(());
                }
            }
            _ => {}
        }

        if self.upload_if_needed()?.is_some() {
            abstr
                .version_control
                .register_apps(vec![(self.as_instance(), version.to_string())])?;
        }

        Ok(())
    }
}