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
use std::fmt::Debug;

use semver::Version;
use serde::Serialize;

use abstract_os::{
    api::BaseInstantiateMsg,
    middleware,
    objects::{
        module::{ModuleInfo, ModuleVersion},
        module_reference::ModuleReference,
    },
    registry,
    version_control::*,
};

use crate::AbstractOS;
use boot_core::{
    state::StateInterface, BootError, Contract, Daemon, IndexResponse, TxHandler, TxResponse,
};

pub type VersionControl<Chain> =
    AbstractOS<Chain, ExecuteMsg, InstantiateMsg, QueryMsg, MigrateMsg>;

impl<Chain: TxHandler + Clone> VersionControl<Chain>
where
    TxResponse<Chain>: IndexResponse,
{
    pub fn new(name: &str, chain: &Chain) -> Self {
        Self(
            Contract::new(name, chain).with_wasm_path("version_control"), // .with_mock(Box::new(
                                                                          //     ContractWrapper::new_with_empty(
                                                                          //         ::contract::execute,
                                                                          //         ::contract::instantiate,
                                                                          //         ::contract::query,
                                                                          //     ),
                                                                          // ))
        )
    }
    pub fn upload_and_register_module<
        R: Serialize + Debug,
        S: Serialize + Debug,
        T: Serialize + Debug,
        V: Serialize + Debug,
    >(
        &self,
        module: &mut Contract<Chain, R, S, T, V>,
        new_version: &Version,
    ) -> Result<(), BootError> {
        module.upload()?;
        self.execute(
            &ExecuteMsg::AddModules {
                modules: vec![(
                    ModuleInfo::from_id(
                        &module.id,
                        ModuleVersion::Version(new_version.to_string()),
                    )?,
                    ModuleReference::App(module.code_id()?),
                )],
            },
            None,
        )?;
        Ok(())
    }

    pub fn upload_and_register_api<
        R: Serialize + Debug,
        T: Serialize + Debug,
        V: Serialize + Debug,
    >(
        &self,
        api: &mut Contract<Chain, R, middleware::InstantiateMsg<BaseInstantiateMsg>, T, V>,
        api_init_msg: &middleware::InstantiateMsg<BaseInstantiateMsg>,
        new_version: &Version,
    ) -> Result<(), BootError> {
        api.upload()?;
        api.instantiate(api_init_msg, None, None)?;
        self.execute(
            &ExecuteMsg::AddModules {
                modules: vec![(
                    ModuleInfo::from_id(&api.id, ModuleVersion::Version(new_version.to_string()))?,
                    ModuleReference::Extension(api.address()?),
                )],
            },
            None,
        )?;
        Ok(())
    }

    pub fn add_code_ids(&self, version: Version) -> anyhow::Result<()> {
        let code_ids = self.chain().state().get_all_code_ids()?;
        let _addresses = self.chain().state().get_all_addresses()?;
        let mut modules = vec![];
        for app in registry::CORE {
            let code_id = code_ids.get(*app).unwrap();
            modules.push((
                ModuleInfo::from_id(app, ModuleVersion::Version(version.to_string()))?,
                ModuleReference::App(*code_id),
            ))
        }
        // for app in registry::APPS {
        //     let code_id = code_ids.get(app.clone()).unwrap();
        //     modules.push((ModuleInfo::from_id(app, ModuleVersion::Version(version.to_string()))?,ModuleReference::App(code_id.clone())))
        // }
        // for api in registry::API_CONTRACTS {
        //     let address = addresses.get(api.clone()).unwrap();
        //     modules.push((ModuleInfo::from_id(&api, ModuleVersion::Version(version.to_string()))?,ModuleReference::Extension(address.clone())))
        // }
        self.execute(&ExecuteMsg::AddModules { modules }, None)?;
        Ok(())
    }

    pub fn get_os_core(&self, os_id: u32) -> Result<Core, BootError> {
        let resp: OsCoreResponse = self.query(&QueryMsg::OsCore { os_id })?;
        Ok(resp.os_core)
    }
}

impl VersionControl<Daemon> {
    // pub fn update_code_ids(&self, new_version: Version) -> anyhow::Result<()> {
    //     let code_ids = self.chain().state().get_all_code_ids()?;
    //     for (contract_id, code_id) in code_ids {
    //         if NATIVE_CONTRACTS.contains(&contract_id.as_str()) {
    //             continue;
    //         }

    //         // Get latest code id
    //         let resp: Result<QueryCodeIdResponse, BootError> = self.query(&QueryMsg::CodeId {
    //             module: ModuleInfo {
    //                 name: contract_id.clone(),
    //                 version: None,
    //             },
    //         });
    //         log::debug!("{:?}", resp);
    //         if new_version.pre.is_empty() {
    //             match resp {
    //                 Ok(resp) => {
    //                     let registered_code_id = resp.code_id.u64();
    //                     // If equal, continue
    //                     if registered_code_id == code_id {
    //                         continue;
    //                     } else {
    //                         let latest_version = resp.info.version;
    //                         version = latest_version.parse().unwrap();
    //                         // bump patch
    //                         version.patch += 1;
    //                     }
    //                 }
    //                 Err(_) => (),
    //             };
    //         }

    //         self.execute(
    //             &ExecuteMsg::AddCodeId {
    //                 module: contract_id.to_string(),
    //                 version: version.to_string(),
    //                 code_id,
    //             },
    //             None,
    //         )?;
    //     }
    //     Ok(())
    // }

    // pub fn update_apis(&self) -> anyhow::Result<()> {
    //     for contract_name in chain_state.keys() {
    //         if !API_CONTRACTS.contains(&contract_name.as_str()) {
    //             continue;
    //         }

    //         // Get local addr
    //         let address: String = chain_state[contract_name].as_str().unwrap().into();

    //         // Get latest addr
    //         let resp: Result<QueryApiAddressResponse, BootError> =
    //             self.query(&QueryMsg::ApiAddress {
    //                 module: ModuleInfo {
    //                     name: contract_name.clone(),
    //                     version: None,
    //                 },
    //             });
    //         log::debug!("{:?}", resp);
    //         let mut version = self.deployment_version.clone();
    //         match resp {
    //             Ok(resp) => {
    //                 let registered_addr = resp.address.to_string();

    //                 // If equal, continue
    //                 if registered_addr == address {
    //                     continue;
    //                 } else {
    //                     let latest_version = resp.info.version;
    //                     version = latest_version.parse().unwrap();
    //                     // bump patch
    //                     version.patch += 1;
    //                 }
    //             }
    //             Err(_) => (),
    //         };

    //         self.execute(
    //             &ExecuteMsg::AddApi {
    //                 module: contract_name.to_string(),
    //                 version: version.to_string(),
    //                 address,
    //             },
    //             None,
    //         )?;
    //     }
    //     Ok(())
    // }
}