abstract_interface/
deployers.rs

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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
use abstract_std::{
    account::ModuleInstallConfig,
    objects::{
        dependency::StaticDependency,
        module::{ModuleInfo, ModuleVersion},
        AccountId,
    },
};
use cosmwasm_std::to_json_binary;
use cw_orch::{
    environment::Environment,
    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;
    /// Create the unique contract ID for a module installed on an Account.
    fn installed_module_contract_id(account_id: &AccountId) -> String {
        format!("{}-{}", Self::module_id(), account_id)
    }
    /// Dependencies of the module
    fn dependencies<'a>() -> &'a [StaticDependency];
}

/// 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_std::adapter::InstantiateMsg<CustomInitMsg>>
    + Uploadable
    + Sized
    + RegisteredModule
{
    /// Deploys the adapter. If the adapter is already deployed, it will return an error.
    /// Use [`DeployStrategy::Try`]  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.environment().to_owned())?;

        abstr
            .registry
            .assert_dependencies_deployed(Self::dependencies())?;

        // check for existing version, if not force strategy
        let vc_has_module = || {
            abstr
                .registry
                .registered_or_pending_module(
                    ModuleInfo::from_id(&self.id(), ModuleVersion::from(version.to_string()))
                        .unwrap(),
                )
                .and_then(|module| module.reference.unwrap_adapter().map_err(Into::into))
        };

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

        self.upload_if_needed()?;
        let init_msg = abstract_std::adapter::InstantiateMsg {
            module: custom_init_msg,
            base: abstract_std::adapter::BaseInstantiateMsg {},
        };
        self.instantiate(&init_msg, None, &[])?;

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

        Ok(())
    }
}

/// Trait for deploying APPs
pub trait AppDeployer<Chain: CwEnv>:
    Sized + Uploadable + ContractInstance<Chain> + RegisteredModule
{
    /// Deploys the app. If the app is already deployed, it will return an error.
    /// Use [`DeployStrategy::Try`]  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.environment().to_owned())?;

        abstr
            .registry
            .assert_dependencies_deployed(Self::dependencies())?;

        // check for existing version
        let vc_has_module = || {
            abstr
                .registry
                .registered_or_pending_module(
                    ModuleInfo::from_id(&self.id(), ModuleVersion::from(version.to_string()))
                        .unwrap(),
                )
                .and_then(|module| module.reference.unwrap_app().map_err(Into::into))
        };

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

        self.upload_if_needed()?;
        abstr
            .registry
            .register_apps(vec![(self.as_instance(), version.to_string())])?;

        Ok(())
    }
}

/// Trait for deploying Standalones
pub trait StandaloneDeployer<Chain: CwEnv>:
    Sized + Uploadable + ContractInstance<Chain> + RegisteredModule
{
    /// Deploys the app. If the app is already deployed, it will return an error.
    /// Use [`DeployStrategy::Try`] 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.environment().to_owned())?;

        abstr
            .registry
            .assert_dependencies_deployed(Self::dependencies())?;

        // check for existing version
        let vc_has_module = || {
            abstr
                .registry
                .registered_or_pending_module(
                    ModuleInfo::from_id(&self.id(), ModuleVersion::from(version.to_string()))
                        .unwrap(),
                )
                .and_then(|module| module.reference.unwrap_standalone().map_err(Into::into))
        };

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

        self.upload_if_needed()?;
        abstr
            .registry
            .register_standalones(vec![(self.as_instance(), version.to_string())])?;

        Ok(())
    }
}

/// Trait for deploying Services
pub trait ServiceDeployer<Chain: CwEnv>:
    Sized + Uploadable + ContractInstance<Chain> + CwOrchInstantiate<Chain>
{
    /// Deploys the module. If the module is already deployed, it will return an error.
    /// Use [`DeployStrategy::Try`] if you want to deploy the module only if it is not already deployed.
    fn deploy(
        &self,
        version: Version,
        custom_init_msg: &<Self as InstantiableContract>::InstantiateMsg,
        strategy: DeployStrategy,
    ) -> Result<(), crate::AbstractInterfaceError> {
        // retrieve the deployment
        let abstr = Abstract::<Chain>::load_from(self.environment().to_owned())?;

        // check for existing version
        let vc_has_module = || {
            abstr
                .registry
                .registered_or_pending_module(
                    ModuleInfo::from_id(&self.id(), ModuleVersion::from(version.to_string()))
                        .unwrap(),
                )
                .and_then(|module| module.reference.unwrap_standalone().map_err(Into::into))
        };

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

        self.upload_if_needed()?;
        self.instantiate(custom_init_msg, None, &[])?;
        abstr
            .registry
            .register_services(vec![(self.as_instance(), version.to_string())])?;

        Ok(())
    }
}