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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! # Module
//! The Module interface provides helper functions to execute functions on other modules installed on the OS.

use crate::helpers::cosmwasm_std::wasm_smart_query;
use abstract_os::{
    api, app,
    manager::state::{ModuleId, OS_MODULES},
};
use cosmwasm_std::{
    wasm_execute, Addr, CosmosMsg, Deps, Empty, QueryRequest, StdError, StdResult, WasmQuery,
};
use cw2::{ContractVersion, CONTRACT};
use serde::Serialize;

use super::{Dependencies, Identification};

/// Interact with other modules on the OS.
pub trait ModuleInterface: Identification + Dependencies {
    fn modules<'a>(&'a self, deps: Deps<'a>) -> Modules<Self> {
        Modules { base: self, deps }
    }
}

impl<T> ModuleInterface for T where T: Identification + Dependencies {}

#[derive(Clone)]
pub struct Modules<'a, T: ModuleInterface> {
    base: &'a T,
    deps: Deps<'a>,
}

impl<'a, T: ModuleInterface> Modules<'a, T> {
    /// Retrieve the address of an application in this OS.
    /// This should **not** be used to execute messages on an `Api`.
    /// Use `Modules::api_request(..)` instead.
    pub fn module_address(&self, module_id: ModuleId) -> StdResult<Addr> {
        let manager_addr = self.base.manager_address(self.deps)?;
        let maybe_module_addr = OS_MODULES.query(&self.deps.querier, manager_addr, module_id)?;
        let Some(module_addr) = maybe_module_addr else {
            return Err(StdError::generic_err(format!("Module {} not enabled on OS.", module_id)));
        };
        Ok(module_addr)
    }

    /// Retrieve the version of an application in this OS.
    /// Note: this method makes use of the Cw2 query and may not coincide with the version of the
    /// module listed in VersionControl.
    pub fn module_version(&self, module_id: ModuleId) -> StdResult<ContractVersion> {
        let module_address = self.module_address(module_id)?;
        let req = QueryRequest::Wasm(WasmQuery::Raw {
            contract_addr: module_address.into(),
            key: CONTRACT.as_slice().into(),
        });
        self.deps.querier.query::<ContractVersion>(&req)
    }

    fn assert_module_dependency(&self, module_id: ModuleId) -> StdResult<()> {
        let is_dependency = Dependencies::dependencies(self.base)
            .iter()
            .map(|d| d.id)
            .any(|x| x == module_id);

        match is_dependency {
            true => Ok(()),
            false => Err(StdError::generic_err(format!(
                "Module {} is not a dependency of this contract.",
                module_id
            ))),
        }
    }

    /// Construct an app request message.
    pub fn app_request<M: Serialize>(
        &self,
        app_id: ModuleId,
        message: impl Into<app::ExecuteMsg<M, Empty>>,
    ) -> StdResult<CosmosMsg> {
        self.assert_module_dependency(app_id)?;
        let app_msg: app::ExecuteMsg<M, Empty> = message.into();
        let app_address = self.module_address(app_id)?;
        Ok(wasm_execute(app_address, &app_msg, vec![])?.into())
    }

    /// Construct an app configuation message
    pub fn app_configure(
        &self,
        app_id: ModuleId,
        message: app::BaseExecuteMsg,
    ) -> StdResult<CosmosMsg> {
        let app_msg: app::ExecuteMsg<Empty, Empty> = message.into();
        let app_address = self.module_address(app_id)?;
        Ok(wasm_execute(app_address, &app_msg, vec![])?.into())
    }

    /// Smart query an app
    pub fn app_query<Q: Serialize>(
        &self,
        app_id: ModuleId,
        message: impl Into<app::QueryMsg<Q>>,
    ) -> StdResult<QueryRequest<Empty>> {
        let app_msg: app::QueryMsg<Q> = message.into();
        let app_address = self.module_address(app_id)?;
        wasm_smart_query(app_address, &app_msg)
    }

    /// Interactions with Abstract APIs
    /// Construct an api request message.
    pub fn api_request<M: Serialize>(
        &self,
        api_id: ModuleId,
        message: impl Into<api::ExecuteMsg<M, Empty>>,
    ) -> StdResult<CosmosMsg> {
        self.assert_module_dependency(api_id)?;
        let api_msg: api::ExecuteMsg<M, Empty> = message.into();
        let api_address = self.module_address(api_id)?;
        Ok(wasm_execute(api_address, &api_msg, vec![])?.into())
    }

    /// Smart query an API
    pub fn api_query<Q: Serialize>(
        &self,
        api_id: ModuleId,
        message: impl Into<api::QueryMsg<Q>>,
    ) -> StdResult<QueryRequest<Empty>> {
        let api_msg: api::QueryMsg<Q> = message.into();
        let api_address = self.module_address(api_id)?;
        wasm_smart_query(api_address, &api_msg)
    }

    /// Construct an API configure message
    /// Note: this method is only callabable by the OS manager.
    pub fn api_configure(
        &self,
        api_id: ModuleId,
        message: api::BaseExecuteMsg,
    ) -> StdResult<CosmosMsg> {
        let api_msg: api::ExecuteMsg<Empty, Empty> = message.into();
        let api_address = self.module_address(api_id)?;
        Ok(wasm_execute(api_address, &api_msg, vec![])?.into())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use os::objects::dependency::StaticDependency;
    use std::collections::HashMap;
    use std::fmt::Debug;
    use std::marker::PhantomData;

    use crate::apis::test_common::*;

    const TEST_MODULE_ID: ModuleId = "test_module";
    /// Nonexistent module
    const FAKE_MODULE_ID: ModuleId = "fake_module";

    const TEST_MODULE_DEP: StaticDependency = StaticDependency::new(TEST_MODULE_ID, &[">1.0.0"]);

    impl Dependencies for MockModule {
        fn dependencies(&self) -> &[StaticDependency] {
            &[TEST_MODULE_DEP]
        }
    }

    const TEST_MODULE_ADDRESS: &str = "test_module_address";

    /// mock querier that has the os modules loaded
    fn mock_querier_with_existing_module() -> MockQuerier {
        let mut querier = MockQuerier::default();

        querier.update_wasm(|wasm| {
            match wasm {
                WasmQuery::Raw { contract_addr, key } => {
                    let _os_mod_key = "os_modules";
                    let string_key = String::from_utf8(key.to_vec()).unwrap();
                    let str_key = string_key.as_str();

                    let mut modules = HashMap::<Binary, Addr>::default();

                    // binary key is "os_modules<module_id>" (though with a \n or \r before)
                    let binary = Binary::from_base64("AApvc19tb2R1bGVzdGVzdF9tb2R1bGU=").unwrap();
                    modules.insert(binary, Addr::unchecked(TEST_MODULE_ADDRESS));

                    let res = match contract_addr.as_str() {
                        TEST_PROXY => match str_key {
                            "admin" => Ok(to_binary(&TEST_MANAGER).unwrap()),
                            _ => Err("unexpected key"),
                        },
                        TEST_MANAGER => {
                            if let Some(value) = modules.get(key) {
                                Ok(to_binary(&value.to_owned()).unwrap())
                            } else {
                                // Debug print out what the key was
                                // let into_binary: Binary = b"\ros_modulestest_module".into();
                                // let to_binary_res =
                                //     to_binary("os_modulestest_module".as_bytes()).unwrap();
                                // panic!(
                                //     "contract: {}, binary_key: {}, into_binary: {}, to_binary_res: {}",
                                //     contract_addr, key, into_binary, to_binary_res
                                // );
                                Ok(Binary::default())
                            }
                        }
                        _ => Err("unexpected contract"),
                    };

                    match res {
                        Ok(res) => SystemResult::Ok(ContractResult::Ok(res)),
                        Err(e) => SystemResult::Ok(ContractResult::Err(e.to_string())),
                    }
                }
                _ => panic!("Unexpected smart query"),
            }
        });

        querier
    }

    pub fn mock_dependencies_with_existing_module(
    ) -> OwnedDeps<MockStorage, MockApi, MockQuerier, Empty> {
        OwnedDeps {
            storage: MockStorage::default(),
            api: MockApi::default(),
            querier: mock_querier_with_existing_module(),
            custom_query_type: PhantomData,
        }
    }

    mod assert_module_dependency {
        use super::*;

        #[test]
        fn should_return_ok_if_dependency() {
            let deps = mock_dependencies();
            let app = MockModule::new();

            let mods = app.modules(deps.as_ref());

            let res = mods.assert_module_dependency(TEST_MODULE_ID);
            assert_that!(res).is_ok();
        }

        #[test]
        fn should_return_err_if_not_dependency() {
            let deps = mock_dependencies();
            let app = MockModule::new();

            let mods = app.modules(deps.as_ref());

            let fake_module = "lol_no_chance";
            let res = mods.assert_module_dependency(fake_module);

            assert_that!(res).is_err().matches(|e| {
                e.to_string()
                    .contains(&format!("{} is not a dependency", fake_module))
            });
        }
    }

    /// Helper to check that the method is not callable when the module is not a dependency
    fn fail_when_not_dependency_test<T: Debug>(
        modules_fn: impl FnOnce(&MockModule, Deps) -> StdResult<T>,
        fake_module: ModuleId,
    ) {
        let deps = mock_dependencies_with_existing_module();
        let app = MockModule::new();

        let _mods = app.modules(deps.as_ref());

        let res = modules_fn(&app, deps.as_ref());

        assert_that!(res).is_err().matches(|e| match e {
            StdError::GenericErr { msg, .. } => msg.contains(&fake_module.to_string()),
            _ => false,
        });
    }

    mod api_request {
        use super::*;
        use os::api::ApiRequestMsg;

        #[test]
        fn should_return_err_if_not_dependency() {
            fail_when_not_dependency_test(
                |app, deps| {
                    let mods = app.modules(deps);
                    mods.api_request(FAKE_MODULE_ID, MockModuleExecuteMsg {})
                },
                FAKE_MODULE_ID,
            );
        }

        #[test]
        fn expected_api_request() {
            let deps = mock_dependencies_with_existing_module();
            let app = MockModule::new();

            let mods = app.modules(deps.as_ref());

            let res = mods.api_request(TEST_MODULE_ID, MockModuleExecuteMsg {});

            let expected_msg: api::ExecuteMsg<_, Empty> = api::ExecuteMsg::App(ApiRequestMsg {
                proxy_address: None,
                request: MockModuleExecuteMsg {},
            });

            assert_that!(res)
                .is_ok()
                .is_equal_to(CosmosMsg::Wasm(WasmMsg::Execute {
                    contract_addr: TEST_MODULE_ADDRESS.into(),
                    msg: to_binary(&expected_msg).unwrap(),
                    funds: vec![],
                }));
        }
    }

    mod app_request {
        use super::*;

        #[test]
        fn should_return_err_if_not_dependency() {
            fail_when_not_dependency_test(
                |app, deps| {
                    let mods = app.modules(deps);
                    mods.app_request(FAKE_MODULE_ID, MockModuleExecuteMsg {})
                },
                FAKE_MODULE_ID,
            );
        }

        #[test]
        fn expected_app_request() {
            let deps = mock_dependencies_with_existing_module();
            let app = MockModule::new();

            let mods = app.modules(deps.as_ref());

            let res = mods.app_request(TEST_MODULE_ID, MockModuleExecuteMsg {});

            let expected_msg: app::ExecuteMsg<_, Empty> =
                app::ExecuteMsg::App(MockModuleExecuteMsg {});

            assert_that!(res)
                .is_ok()
                .is_equal_to(CosmosMsg::Wasm(WasmMsg::Execute {
                    contract_addr: TEST_MODULE_ADDRESS.into(),
                    msg: to_binary(&expected_msg).unwrap(),
                    funds: vec![],
                }));
        }
    }

    mod configure_api {
        use super::*;

        #[test]
        fn should_return_err_if_not_dependency() {
            fail_when_not_dependency_test(
                |app, deps| {
                    let mods = app.modules(deps);
                    mods.api_configure(FAKE_MODULE_ID, api::BaseExecuteMsg::Remove {})
                },
                FAKE_MODULE_ID,
            );
        }

        #[test]
        fn expected_configure_msg() {
            let deps = mock_dependencies_with_existing_module();
            let app = MockModule::new();

            let mods = app.modules(deps.as_ref());

            let res = mods.configure_api(TEST_MODULE_ID, api::BaseExecuteMsg::Remove {});

            let expected_msg: api::ExecuteMsg<Empty, Empty> =
                api::ExecuteMsg::Base(api::BaseExecuteMsg::Remove {});

            assert_that!(res)
                .is_ok()
                .is_equal_to(CosmosMsg::Wasm(WasmMsg::Execute {
                    contract_addr: TEST_MODULE_ADDRESS.into(),
                    msg: to_binary(&expected_msg).unwrap(),
                    funds: vec![],
                }));
        }
    }

    mod configure_app {
        use super::*;

        #[test]
        fn should_return_err_if_not_dependency() {
            fail_when_not_dependency_test(
                |app, deps| {
                    let mods = app.modules(deps);
                    mods.app_configure(
                        FAKE_MODULE_ID,
                        app::BaseExecuteMsg::UpdateConfig {
                            ans_host_address: None,
                        },
                    )
                },
                FAKE_MODULE_ID,
            );
        }

        #[test]
        fn expected_configure_msg() {
            let deps = mock_dependencies_with_existing_module();
            let app = MockModule::new();

            let mods = app.modules(deps.as_ref());

            let res = mods.configure_app(
                TEST_MODULE_ID,
                app::BaseExecuteMsg::UpdateConfig {
                    ans_host_address: Some("new_ans_addr".to_string()),
                },
            );

            let expected_msg: app::ExecuteMsg<Empty, Empty> =
                app::ExecuteMsg::Base(app::BaseExecuteMsg::UpdateConfig {
                    ans_host_address: Some("new_ans_addr".to_string()),
                });

            assert_that!(res)
                .is_ok()
                .is_equal_to(CosmosMsg::Wasm(WasmMsg::Execute {
                    contract_addr: TEST_MODULE_ADDRESS.into(),
                    msg: to_binary(&expected_msg).unwrap(),
                    funds: vec![],
                }));
        }
    }

    mod api_query {
        use super::*;
        use os::dex::{DexQueryMsg, OfferAsset};

        #[test]
        fn should_return_err_if_not_dependency() {
            fail_when_not_dependency_test(
                |app, deps| {
                    let mods = app.modules(deps);
                    mods.api_query(FAKE_MODULE_ID, Empty {})
                },
                FAKE_MODULE_ID,
            );
        }

        #[test]
        fn expected_api_query() {
            let deps = mock_dependencies_with_existing_module();
            let app = MockModule::new();

            let mods = app.modules(deps.as_ref());

            let inner_msg = DexQueryMsg::SimulateSwap {
                ask_asset: "juno".into(),
                offer_asset: OfferAsset::new("some", 69u128),
                dex: None,
            };

            let res = mods.api_query(TEST_MODULE_ID, inner_msg.clone());

            let expected_msg: api::QueryMsg<DexQueryMsg> = api::QueryMsg::App(inner_msg);

            assert_that!(res)
                .is_ok()
                .is_equal_to(QueryRequest::from(WasmQuery::Smart {
                    contract_addr: TEST_MODULE_ADDRESS.into(),
                    msg: to_binary(&expected_msg).unwrap(),
                }));
        }
    }

    mod app_query {
        use super::*;

        #[test]
        fn should_return_err_if_not_dependency() {
            fail_when_not_dependency_test(
                |app, deps| {
                    let mods = app.modules(deps);
                    mods.app_query(FAKE_MODULE_ID, Empty {})
                },
                FAKE_MODULE_ID,
            );
        }

        #[test]
        fn expected_app_query() {
            let deps = mock_dependencies_with_existing_module();
            let app = MockModule::new();

            let mods = app.modules(deps.as_ref());

            let res = mods.app_query(TEST_MODULE_ID, Empty {});

            let expected_msg: app::QueryMsg<Empty> = app::QueryMsg::App(Empty {});

            assert_that!(res)
                .is_ok()
                .is_equal_to(QueryRequest::from(WasmQuery::Smart {
                    contract_addr: TEST_MODULE_ADDRESS.into(),
                    msg: to_binary(&expected_msg).unwrap(),
                }));
        }
    }
}