abstract_interface/
deployment.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
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
use cosmwasm_std::{instantiate2_address, Binary, CanonicalAddr, Instantiate2AddressError};
use cw_blob::interface::{CwBlob, DeterministicInstantiation};
#[cfg(feature = "daemon")]
use cw_orch::daemon::DeployedChains;

use cw_orch::{mock::MockBase, prelude::*};

use crate::{
    get_ibc_contracts, get_native_contracts, AbstractIbc, AbstractInterfaceError, AccountI,
    AnsHost, ModuleFactory, Registry,
};
use abstract_std::{native_addrs, ACCOUNT, ANS_HOST, MODULE_FACTORY, REGISTRY};

const CW_BLOB: &str = "cw:blob";

#[derive(Clone)]
pub struct Abstract<Chain: CwEnv> {
    pub ans_host: AnsHost<Chain>,
    pub registry: Registry<Chain>,
    pub module_factory: ModuleFactory<Chain>,
    pub ibc: AbstractIbc<Chain>,
    pub(crate) account: AccountI<Chain>,
    pub(crate) blob: CwBlob<Chain>,
}

impl<Chain: CwEnv> Deploy<Chain> for Abstract<Chain> {
    // We don't have a custom error type
    type Error = AbstractInterfaceError;
    type DeployData = Chain::Sender;

    fn store_on(chain: Chain) -> Result<Self, AbstractInterfaceError> {
        let blob = CwBlob::new(CW_BLOB, chain.clone());

        let ans_host = AnsHost::new(ANS_HOST, chain.clone());
        let registry = Registry::new(REGISTRY, chain.clone());
        let module_factory = ModuleFactory::new(MODULE_FACTORY, chain.clone());
        let account = AccountI::new(ACCOUNT, chain.clone());

        let ibc_infra = AbstractIbc::new(&chain);

        blob.upload_if_needed()?;
        ans_host.upload()?;
        registry.upload()?;
        module_factory.upload()?;
        account.upload()?;
        ibc_infra.upload()?;

        let deployment = Abstract {
            ans_host,
            registry,
            module_factory,
            account,
            ibc: ibc_infra,
            blob,
        };

        Ok(deployment)
    }

    /// Deploys abstract using provided [`TxHandler::Sender`].
    /// After deployment sender of abstract contracts is a sender of provided `chain`
    fn deploy_on(
        mut chain: Chain,
        deploy_data: Self::DeployData,
    ) -> Result<Self, AbstractInterfaceError> {
        let original_sender = chain.sender().clone();
        chain.set_sender(deploy_data);

        // Ensure we have expected sender address
        let sender_addr = chain.sender_addr();
        let hrp = sender_addr.as_str().split_once("1").unwrap().0;
        assert_eq!(
            sender_addr.as_str(),
            native_addrs::creator_address(hrp)?,
            "Only predetermined abstract admin can deploy abstract contracts, see `native_addrs.rs`"
        );

        let admin = sender_addr.to_string();
        // upload
        let mut deployment = Self::store_on(chain.clone())?;
        let blob_code_id = deployment.blob.code_id()?;

        let creator_account_id: cosmrs::AccountId = admin.as_str().parse().unwrap();
        let canon_creator = CanonicalAddr::from(creator_account_id.to_bytes());

        let expected_addr = |salt: &[u8]| -> Result<CanonicalAddr, Instantiate2AddressError> {
            instantiate2_address(&cw_blob::CHECKSUM, &canon_creator, salt)
        };

        deployment.ans_host.deterministic_instantiate(
            &abstract_std::ans_host::MigrateMsg::Instantiate(
                abstract_std::ans_host::InstantiateMsg {
                    admin: admin.to_string(),
                },
            ),
            blob_code_id,
            expected_addr(native_addrs::ANS_HOST_SALT)?,
            Binary::from(native_addrs::ANS_HOST_SALT),
        )?;

        deployment.registry.deterministic_instantiate(
            &abstract_std::registry::MigrateMsg::Instantiate(
                abstract_std::registry::InstantiateMsg {
                    admin: admin.to_string(),
                    #[cfg(feature = "integration")]
                    security_disabled: Some(true),
                    #[cfg(not(feature = "integration"))]
                    security_disabled: Some(false),
                    namespace_registration_fee: None,
                },
            ),
            blob_code_id,
            expected_addr(native_addrs::REGISTRY_SALT)?,
            Binary::from(native_addrs::REGISTRY_SALT),
        )?;
        deployment.module_factory.deterministic_instantiate(
            &abstract_std::module_factory::MigrateMsg::Instantiate(
                abstract_std::module_factory::InstantiateMsg {
                    admin: admin.to_string(),
                },
            ),
            blob_code_id,
            expected_addr(native_addrs::MODULE_FACTORY_SALT)?,
            Binary::from(native_addrs::MODULE_FACTORY_SALT),
        )?;

        // We also instantiate ibc contracts
        deployment.ibc.client.deterministic_instantiate(
            &abstract_std::ibc_client::MigrateMsg::Instantiate(
                abstract_std::ibc_client::InstantiateMsg {},
            ),
            blob_code_id,
            expected_addr(native_addrs::IBC_CLIENT_SALT)?,
            Binary::from(native_addrs::IBC_CLIENT_SALT),
        )?;
        deployment.ibc.host.deterministic_instantiate(
            &abstract_std::ibc_host::MigrateMsg::Instantiate(
                abstract_std::ibc_host::InstantiateMsg {},
            ),
            blob_code_id,
            expected_addr(native_addrs::IBC_HOST_SALT)?,
            Binary::from(native_addrs::IBC_HOST_SALT),
        )?;
        deployment.ibc.register(&deployment.registry)?;

        deployment.registry.register_base(&deployment.account)?;
        deployment
            .registry
            .register_natives(deployment.contracts())?;
        deployment.registry.approve_any_abstract_modules()?;

        // Create the first abstract account in integration environments
        #[cfg(feature = "integration")]
        use abstract_std::objects::gov_type::GovernanceDetails;
        #[cfg(feature = "integration")]
        AccountI::create_default_account(
            &deployment,
            GovernanceDetails::Monarchy {
                monarch: chain.sender_addr().to_string(),
            },
        )?;

        // Return original sender
        deployment.update_sender(&original_sender);
        Ok(deployment)
    }

    fn get_contracts_mut(&mut self) -> Vec<Box<&mut dyn ContractInstance<Chain>>> {
        vec![
            Box::new(&mut self.ans_host),
            Box::new(&mut self.registry),
            Box::new(&mut self.module_factory),
            Box::new(&mut self.account),
            Box::new(&mut self.ibc.client),
            Box::new(&mut self.ibc.host),
        ]
    }

    fn load_from(chain: Chain) -> Result<Self, Self::Error> {
        #[allow(unused_mut)]
        let mut abstr = Self::new(chain);
        #[cfg(feature = "daemon")]
        {
            // We register all the contracts default state
            let state = crate::AbstractDaemonState::default().state();

            abstr.set_contracts_state(Some(state));
        }
        // Check if abstract deployed, for successful load
        if let Err(CwOrchError::AddrNotInStore(_)) = abstr.registry.address() {
            return Err(AbstractInterfaceError::NotDeployed {});
        } else if abstr.registry.item_query(cw2::CONTRACT).is_err() {
            return Err(AbstractInterfaceError::NotDeployed {});
        }
        Ok(abstr)
    }
}

#[cfg(feature = "daemon")]
impl<Chain: CwEnv> DeployedChains<Chain> for Abstract<Chain> {
    fn deployed_state_file_path() -> Option<String> {
        let crate_path = env!("CARGO_MANIFEST_DIR");

        Some(
            std::path::PathBuf::from(crate_path)
                .join("state.json")
                .display()
                .to_string(),
        )
    }
}

impl<Chain: CwEnv> Abstract<Chain> {
    pub fn new(chain: Chain) -> Self {
        let (ans_host, registry, module_factory) = get_native_contracts(chain.clone());
        let (ibc_client, ibc_host) = get_ibc_contracts(chain.clone());
        let account = AccountI::new(ACCOUNT, chain.clone());
        Self {
            account,
            ans_host,
            registry,
            module_factory,
            ibc: AbstractIbc {
                client: ibc_client,
                host: ibc_host,
            },
            blob: CwBlob::new(CW_BLOB, chain),
        }
    }

    pub fn instantiate(&mut self, admin: String) -> Result<(), AbstractInterfaceError> {
        let admin = Addr::unchecked(admin);

        self.ans_host.instantiate(
            &abstract_std::ans_host::InstantiateMsg {
                admin: admin.to_string(),
            },
            Some(&admin),
            &[],
        )?;

        self.registry.instantiate(
            &abstract_std::registry::InstantiateMsg {
                admin: admin.to_string(),
                #[cfg(feature = "integration")]
                security_disabled: Some(true),
                #[cfg(not(feature = "integration"))]
                security_disabled: Some(false),
                namespace_registration_fee: None,
            },
            Some(&admin),
            &[],
        )?;

        self.module_factory.instantiate(
            &abstract_std::module_factory::InstantiateMsg {
                admin: admin.to_string(),
            },
            Some(&admin),
            &[],
        )?;

        // We also instantiate ibc contracts
        self.ibc.instantiate(&admin)?;
        self.ibc.register(&self.registry)?;

        Ok(())
    }

    pub fn contracts(&self) -> Vec<(&cw_orch::contract::Contract<Chain>, String)> {
        vec![
            (
                self.ans_host.as_instance(),
                ans_host::contract::CONTRACT_VERSION.to_string(),
            ),
            (
                self.registry.as_instance(),
                registry::contract::CONTRACT_VERSION.to_string(),
            ),
            (
                self.module_factory.as_instance(),
                module_factory::contract::CONTRACT_VERSION.to_string(),
            ),
            (
                self.ibc.client.as_instance(),
                ibc_client::contract::CONTRACT_VERSION.to_string(),
            ),
            (
                self.ibc.host.as_instance(),
                ibc_host::contract::CONTRACT_VERSION.to_string(),
            ),
        ]
    }

    pub fn update_sender(&mut self, sender: &Chain::Sender) {
        let Self {
            ans_host,
            registry,
            module_factory,
            ibc,
            account,
            blob: _,
        } = self;
        ans_host.set_sender(sender);
        registry.set_sender(sender);
        module_factory.set_sender(sender);
        account.set_sender(sender);
        ibc.client.set_sender(sender);
        ibc.host.set_sender(sender);
    }

    pub fn call_as(&self, sender: &<Chain as TxHandler>::Sender) -> Self {
        Self {
            ans_host: self.ans_host.clone().call_as(sender),
            registry: self.registry.clone().call_as(sender),
            module_factory: self.module_factory.clone().call_as(sender),
            ibc: self.ibc.call_as(sender),
            account: self.account.call_as(sender),
            blob: self.blob.clone(),
        }
    }
}

// Sender addr means it's mock or CloneTest(which is also mock)
impl<Chain: CwEnv<Sender = Addr>> Abstract<Chain> {
    pub fn deploy_on_mock(chain: Chain) -> Result<Self, AbstractInterfaceError> {
        let admin = Self::mock_admin(&chain);
        Self::deploy_on(chain, admin)
    }

    pub fn mock_admin(chain: &Chain) -> <MockBase as TxHandler>::Sender {
        // Getting prefix
        let sender_addr: cosmrs::AccountId = chain.sender().as_str().parse().unwrap();
        let prefix = sender_addr.prefix();
        // Building mock_admin
        let mock_admin = native_addrs::creator_address(prefix).unwrap();
        Addr::unchecked(mock_admin)
    }
}

#[cfg(test)]
mod test {
    #![allow(clippy::needless_borrows_for_generic_args)]

    use cosmwasm_std::Api;
    use cw_orch::anyhow;

    use super::*;

    #[coverage_helper::test]
    fn deploy2() -> anyhow::Result<()> {
        let prefix = "mock";
        let mut chain = MockBech32::new(prefix);
        let sender = native_addrs::creator_address(prefix)?;
        chain.set_sender(Addr::unchecked(sender));

        let abstr = Abstract::deploy_on(chain.clone(), chain.sender().clone())?;
        let app = chain.app.borrow();
        let api = app.api();

        // ANS
        let ans_addr = api.addr_canonicalize(&abstr.ans_host.addr_str()?)?;
        assert_eq!(ans_addr, native_addrs::ans_address(prefix, api)?);

        // REGISTRY
        let registry = api.addr_canonicalize(&abstr.registry.addr_str()?)?;
        assert_eq!(registry, native_addrs::registry_address(prefix, api)?);

        // MODULE_FACTORY
        let module_factory = api.addr_canonicalize(&abstr.module_factory.addr_str()?)?;
        assert_eq!(
            module_factory,
            native_addrs::module_factory_address(prefix, api)?
        );

        // IBC_CLIENT
        let ibc_client = api.addr_canonicalize(&abstr.ibc.client.addr_str()?)?;
        assert_eq!(ibc_client, native_addrs::ibc_client_address(prefix, api)?);

        // IBC_HOST
        let ibc_host = api.addr_canonicalize(&abstr.ibc.host.addr_str()?)?;
        assert_eq!(ibc_host, native_addrs::ibc_host_address(prefix, api)?);

        Ok(())
    }
}