abstract_interface/
account.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
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
//! # Functionality we want to implement on an `Account`
//!
//! ## Queries
//! - module address
//! - module asserts
//! - account balance
//! - account asserts
//! ## Actions
//! - get
//! - install module
//! - uninstall module
//! - upgrade module

use crate::{get_account_contract, Abstract, AbstractInterfaceError, AdapterDeployer, Registry};
pub use abstract_std::account::{ExecuteMsgFns as AccountExecFns, QueryMsgFns as AccountQueryFns};
use abstract_std::{
    account::{AccountModuleInfo, ModuleInstallConfig, *},
    adapter::{self, AdapterBaseMsg},
    ibc_host::{HelperAction, HostAction},
    module_factory::SimulateInstallModulesResponse,
    objects::{
        gov_type::GovernanceDetails,
        module::{ModuleInfo, ModuleStatus, ModuleVersion},
        salt::generate_instantiate_salt,
        AccountId, TruncatedChainId,
    },
    registry::{state::LOCAL_ACCOUNT_SEQUENCE, ExecuteMsgFns, ModuleFilter, QueryMsgFns},
    ABSTRACT_EVENT_TYPE, ACCOUNT, IBC_CLIENT,
};
use cosmwasm_std::{from_json, to_json_binary};
use cosmwasm_std::{Binary, Empty};
use cw2::{ContractVersion, CONTRACT};
use cw_orch::{environment::Environment, interface, prelude::*};
use semver::{Version, VersionReq};
use serde::Serialize;
use std::{collections::HashSet, fmt::Debug};

/// A helper struct that contains fields from [`abstract_std::account::state::AccountInfo`]
#[derive(Default)]
pub struct AccountDetails {
    pub name: String,
    pub description: Option<String>,
    pub link: Option<String>,
    pub namespace: Option<String>,
    pub install_modules: Vec<ModuleInstallConfig>,
    pub account_id: Option<u32>,
}

#[interface(InstantiateMsg, ExecuteMsg, QueryMsg, MigrateMsg)]
pub struct AccountI<Chain>;

impl<Chain: CwEnv> AccountI<Chain> {
    pub fn load_from(
        abstract_deployment: &Abstract<Chain>,
        account_id: AccountId,
    ) -> Result<Self, AbstractInterfaceError> {
        get_account_contract(&abstract_deployment.registry, account_id)
    }

    pub(crate) fn new_from_id(account_id: &AccountId, chain: Chain) -> Self {
        let account_id = format!("{ACCOUNT}-{account_id}");
        Self::new(account_id, chain)
    }

    /// Create account, `b"abstract_account"` used as a salt
    pub fn create(
        abstract_deployment: &Abstract<Chain>,
        details: AccountDetails,
        governance_details: GovernanceDetails<String>,
        funds: &[cosmwasm_std::Coin],
    ) -> Result<Self, AbstractInterfaceError> {
        let chain = abstract_deployment.registry.environment().clone();

        // Generate salt from account id(or)
        let salt = generate_instantiate_salt(&AccountId::local(details.account_id.unwrap_or(
            chain.wasm_querier().item_query(
                &abstract_deployment.registry.address()?,
                LOCAL_ACCOUNT_SEQUENCE,
            )?,
        )));
        let code_id = abstract_deployment.account.code_id().unwrap();

        let account_addr = chain
            .wasm_querier()
            .instantiate2_addr(code_id, &chain.sender_addr(), salt.clone())
            .map_err(Into::into)?;
        let account_addr = Addr::unchecked(account_addr);

        chain
            .instantiate2(
                code_id,
                &InstantiateMsg::<Empty> {
                    account_id: details.account_id.map(AccountId::local),
                    owner: governance_details,
                    namespace: details.namespace,
                    install_modules: details.install_modules,
                    name: Some(details.name),
                    description: details.description,
                    link: details.link,
                    authenticator: None,
                },
                Some("Abstract Account"),
                Some(&account_addr),
                funds,
                salt,
            )
            .map_err(Into::into)?;

        let account_id = chain
            .wasm_querier()
            .item_query(&account_addr, state::ACCOUNT_ID)?;
        let contract_id = format!("{ACCOUNT}-{account_id}");

        let account = Self::new(contract_id, chain);
        account.set_address(&account_addr);
        Ok(account)
    }

    pub fn create_default_account(
        abstract_deployment: &Abstract<Chain>,
        governance_details: GovernanceDetails<String>,
    ) -> Result<Self, AbstractInterfaceError> {
        let details = AccountDetails {
            name: "Default Abstract Account".into(),
            ..Default::default()
        };
        Self::create(abstract_deployment, details, governance_details, &[])
    }
}

// Module related operations
impl<Chain: CwEnv> AccountI<Chain> {
    pub fn upgrade_module<M: Serialize>(
        &self,
        module_id: &str,
        migrate_msg: &M,
    ) -> Result<(), crate::AbstractInterfaceError> {
        self.upgrade(vec![(
            ModuleInfo::from_id(module_id, ModuleVersion::Latest)?,
            Some(to_json_binary(migrate_msg).unwrap()),
        )])?;
        Ok(())
    }

    pub fn replace_api(
        &self,
        module_id: &str,
        funds: &[Coin],
    ) -> Result<(), crate::AbstractInterfaceError> {
        // this should check if installed?
        self.uninstall_module(module_id.to_string())?;

        self.install_module::<Empty>(module_id, None, funds)?;
        Ok(())
    }
    pub fn install_module<TInitMsg: Serialize>(
        &self,
        module_id: &str,
        init_msg: Option<&TInitMsg>,
        funds: &[Coin],
    ) -> Result<Chain::Response, crate::AbstractInterfaceError> {
        self.install_module_version(module_id, ModuleVersion::Latest, init_msg, funds)
    }

    pub fn install_modules_auto(
        &self,
        modules: Vec<ModuleInstallConfig>,
    ) -> Result<Chain::Response, crate::AbstractInterfaceError> {
        let config = self.config()?;
        let module_infos = modules.iter().map(|m| m.module.clone()).collect();
        let sim_response: SimulateInstallModulesResponse = self
            .environment()
            .query(
                &abstract_std::module_factory::QueryMsg::SimulateInstallModules {
                    modules: module_infos,
                },
                &config.module_factory_address,
            )
            .map_err(Into::into)?;
        self.install_modules(modules, sim_response.total_required_funds.as_ref())
            .map_err(Into::into)
    }

    pub fn install_module_version<M: Serialize>(
        &self,
        module_id: &str,
        version: ModuleVersion,
        init_msg: Option<&M>,
        funds: &[Coin],
    ) -> Result<Chain::Response, crate::AbstractInterfaceError> {
        self.install_modules(
            vec![ModuleInstallConfig::new(
                ModuleInfo::from_id(module_id, version)?,
                init_msg.map(to_json_binary).transpose().unwrap(),
            )],
            funds,
        )
        .map_err(Into::into)
    }
    /// Assert that the Account has the expected modules with the provided **expected_module_addrs** installed.
    /// Returns the `Vec<AccountModuleInfo>` from the account
    pub fn expect_modules(
        &self,
        module_addrs: Vec<String>,
    ) -> Result<Vec<AccountModuleInfo>, crate::AbstractInterfaceError> {
        let abstract_std::account::ModuleInfosResponse {
            module_infos: account_modules,
        } = self.module_infos(None, None)?;

        let expected_module_addrs = module_addrs
            .into_iter()
            .map(Addr::unchecked)
            .collect::<HashSet<_>>();

        let actual_module_addrs = account_modules
            .iter()
            .map(|module_info| module_info.address.clone())
            .collect::<HashSet<_>>();

        // assert that these modules are installed
        assert_eq!(expected_module_addrs, actual_module_addrs);

        Ok(account_modules)
    }

    pub fn is_module_installed(
        &self,
        module_id: &str,
    ) -> Result<bool, crate::AbstractInterfaceError> {
        let module = self.module_info(module_id)?;
        Ok(module.is_some())
    }

    /// Checks that the account's whitelist includes the expected module addresses.
    pub fn expect_whitelist(
        &self,
        expected_whitelisted_addrs: Vec<Addr>,
    ) -> Result<(), crate::AbstractInterfaceError> {
        let expected_whitelisted_addrs = expected_whitelisted_addrs
            .into_iter()
            .collect::<HashSet<_>>();

        // check account config
        let abstract_std::account::ConfigResponse {
            whitelisted_addresses: whitelist,
            ..
        } = self.config()?;

        let actual_whitelist = HashSet::from_iter(whitelist);
        assert_eq!(actual_whitelist, expected_whitelisted_addrs);

        Ok(())
    }

    /// Installs an adapter from an adapter object
    pub fn install_adapter<CustomInitMsg: Serialize, T: AdapterDeployer<Chain, CustomInitMsg>>(
        &self,
        module: &T,
        funds: &[Coin],
    ) -> Result<Addr, crate::AbstractInterfaceError> {
        self.install_module_parse_addr::<Empty, _>(module, None, funds)
    }

    /// Installs an app from an app object
    pub fn install_app<CustomInitMsg: Serialize, T: ContractInstance<Chain>>(
        &self,
        module: &T,
        custom_init_msg: &CustomInitMsg,
        funds: &[Coin],
    ) -> Result<Addr, crate::AbstractInterfaceError> {
        // retrieve the deployment
        self.install_module_parse_addr(module, Some(&custom_init_msg), funds)
    }

    /// Installs an standalone from an standalone object
    pub fn install_standalone<CustomInitMsg: Serialize, T: ContractInstance<Chain>>(
        &self,
        standalone: &T,
        custom_init_msg: &CustomInitMsg,
        funds: &[Coin],
    ) -> Result<Addr, crate::AbstractInterfaceError> {
        // retrieve the deployment
        self.install_module_parse_addr(standalone, Some(&custom_init_msg), funds)
    }

    fn install_module_parse_addr<InitMsg: Serialize, T: ContractInstance<Chain>>(
        &self,
        module: &T,
        init_msg: Option<&InitMsg>,
        funds: &[Coin],
    ) -> Result<Addr, crate::AbstractInterfaceError> {
        let resp = self.install_module(&module.id(), init_msg, funds)?;
        let module_address = resp.event_attr_value(ABSTRACT_EVENT_TYPE, "new_modules")?;
        let module_address = Addr::unchecked(module_address);

        module.set_address(&module_address);
        Ok(module_address)
    }

    pub fn execute_on_module(
        &self,
        module: &str,
        msg: impl Serialize,
        funds: Vec<Coin>,
    ) -> Result<<Chain as cw_orch::prelude::TxHandler>::Response, crate::AbstractInterfaceError>
    {
        <AccountI<Chain> as AccountExecFns<Chain, abstract_std::account::ExecuteMsg>>::execute_on_module(
            self,
            to_json_binary(&msg).unwrap(),
            funds,
            module,
            &[],
        )
        .map_err(Into::into)
    }

    pub fn update_adapter_authorized_addresses(
        &self,
        module_id: &str,
        to_add: Vec<String>,
        to_remove: Vec<String>,
    ) -> Result<(), crate::AbstractInterfaceError> {
        self.admin_execute_on_module(
            module_id,
            to_json_binary(&adapter::ExecuteMsg::<Empty>::Base(
                adapter::BaseExecuteMsg {
                    msg: AdapterBaseMsg::UpdateAuthorizedAddresses { to_add, to_remove },
                    account_address: None,
                },
            ))?,
        )?;

        Ok(())
    }

    /// Return the module info installed on the account
    pub fn module_info(
        &self,
        module_id: &str,
    ) -> Result<Option<AccountModuleInfo>, crate::AbstractInterfaceError> {
        let module_infos = self.module_infos(None, None)?.module_infos;
        let found = module_infos
            .into_iter()
            .find(|module_info| module_info.id == module_id);
        Ok(found)
    }

    /// Get the address of a module
    /// Will err when not installed.
    pub fn module_address(
        &self,
        module_id: impl Into<String>,
    ) -> Result<Addr, crate::AbstractInterfaceError> {
        Ok(self.module_addresses(vec![module_id.into()])?.modules[0]
            .1
            .clone())
    }
}

// Remote accounts related operations
impl<Chain: CwEnv> AccountI<Chain> {
    /// Helper to create remote accounts
    pub fn register_remote_account(
        &self,
        host_chain: TruncatedChainId,
    ) -> Result<<Chain as cw_orch::prelude::TxHandler>::Response, crate::AbstractInterfaceError>
    {
        self.create_remote_account(
            AccountDetails {
                name: "No specified name".to_string(),
                description: None,
                link: None,
                namespace: None,
                install_modules: vec![ModuleInstallConfig::new(
                    ModuleInfo::from_id_latest(IBC_CLIENT)?,
                    None,
                )],
                account_id: None,
            },
            host_chain,
        )
    }

    pub fn create_remote_account(
        &self,
        account_details: AccountDetails,
        host_chain: TruncatedChainId,
    ) -> Result<<Chain as cw_orch::prelude::TxHandler>::Response, crate::AbstractInterfaceError>
    {
        let AccountDetails {
            namespace,
            install_modules,
            // Unused fields
            name: _,
            description: _,
            link: _,
            account_id: _,
        } = account_details;

        self.execute_on_module(
            IBC_CLIENT,
            &abstract_std::ibc_client::ExecuteMsg::Register {
                host_chain,
                namespace,
                install_modules,
            },
            vec![],
        )
        .map_err(Into::into)
    }

    pub fn set_ibc_status(
        &self,
        enabled: bool,
    ) -> Result<Chain::Response, crate::AbstractInterfaceError> {
        let response = if enabled {
            self.install_module::<Empty>(IBC_CLIENT, None, &[])?
        } else {
            self.uninstall_module(IBC_CLIENT.to_string())?
        };

        Ok(response)
    }

    pub fn execute_on_remote(
        &self,
        host_chain: TruncatedChainId,
        msg: ExecuteMsg,
    ) -> Result<<Chain as cw_orch::prelude::TxHandler>::Response, crate::AbstractInterfaceError>
    {
        self.execute_on_module(
            IBC_CLIENT,
            abstract_std::ibc_client::ExecuteMsg::RemoteAction {
                host_chain,
                action: HostAction::Dispatch {
                    account_msgs: vec![msg],
                },
            },
            vec![],
        )
        .map_err(Into::into)
    }

    /// Execute action on remote module.
    /// Funds attached from remote account to the module
    pub fn execute_on_remote_module(
        &self,
        host_chain: TruncatedChainId,
        module_id: &str,
        msg: Binary,
        funds: Vec<Coin>,
    ) -> Result<<Chain as cw_orch::prelude::TxHandler>::Response, crate::AbstractInterfaceError>
    {
        self.execute_on_module(
            IBC_CLIENT,
            &(abstract_std::ibc_client::ExecuteMsg::RemoteAction {
                host_chain,
                action: HostAction::Dispatch {
                    account_msgs: vec![ExecuteMsg::ExecuteOnModule {
                        module_id: module_id.to_string(),
                        exec_msg: msg,
                        funds,
                    }],
                },
            }),
            vec![],
        )
        .map_err(Into::into)
    }

    pub fn send_all_funds_back(
        &self,
        host_chain: TruncatedChainId,
    ) -> Result<<Chain as cw_orch::prelude::TxHandler>::Response, crate::AbstractInterfaceError>
    {
        self.execute_on_module(
            IBC_CLIENT,
            &abstract_std::ibc_client::ExecuteMsg::RemoteAction {
                host_chain,
                action: HostAction::Helpers(HelperAction::SendAllBack),
            },
            vec![],
        )
        .map_err(Into::into)
    }
}

impl<Chain: CwEnv> AccountI<Chain> {
    /// Register the account core contracts in the registry
    pub fn register(
        &self,
        registry: &Registry<Chain>,
    ) -> Result<(), crate::AbstractInterfaceError> {
        registry.register_base(self)
    }

    /// Gets the account ID of the
    pub fn id(&self) -> Result<AccountId, crate::AbstractInterfaceError> {
        Ok(self.config()?.account_id)
    }

    pub fn create_and_return_sub_account(
        &self,
        account_details: AccountDetails,
        funds: &[Coin],
    ) -> Result<AccountI<Chain>, crate::AbstractInterfaceError> {
        let AccountDetails {
            name,
            description,
            link,
            namespace,
            install_modules,
            account_id,
        } = account_details;

        let result = self.create_sub_account(
            install_modules,
            account_id,
            description,
            link,
            Some(name),
            namespace,
            funds,
        )?;

        Self::from_tx_response(self.environment(), result)
    }

    // Parse account from events
    // It's restricted to parse 1 account at a time
    pub(crate) fn from_tx_response(
        chain: &Chain,
        result: <Chain as TxHandler>::Response,
    ) -> Result<AccountI<Chain>, crate::AbstractInterfaceError> {
        // Parse data from events
        let acc_id = &result.event_attr_value(ABSTRACT_EVENT_TYPE, "account_id")?;
        let id: AccountId = acc_id.parse()?;
        let account = Self::new_from_id(&id, chain.clone());

        // set addresses
        let account_address = result.event_attr_value(ABSTRACT_EVENT_TYPE, "account_address")?;
        account.set_address(&Addr::unchecked(account_address));

        Ok(account)
    }

    pub fn upload_and_register_if_needed(
        &self,
        registry: &Registry<Chain>,
    ) -> Result<bool, AbstractInterfaceError> {
        let migrated = if self.upload_if_needed()?.is_some() {
            registry.register_account(
                self.as_instance(),
                ::account::contract::CONTRACT_VERSION.to_string(),
            )?;
            true
        } else {
            false
        };

        Ok(migrated)
    }

    /// Attempts to upgrade the Account
    /// returns `true` if any migrations were performed.
    pub fn upgrade_account(
        &self,
        abstract_deployment: &Abstract<Chain>,
    ) -> Result<bool, AbstractInterfaceError> {
        let mut one_migration_was_successful = false;

        // upgrade sub accounts first
        {
            let mut sub_account_ids = vec![];
            let mut start_after = None;
            loop {
                let sub_account_ids_page = self.sub_account_ids(None, start_after)?.sub_accounts;

                start_after = sub_account_ids_page.last().cloned();
                if sub_account_ids_page.is_empty() {
                    break;
                }
                sub_account_ids.extend(sub_account_ids_page);
            }
            for sub_account_id in sub_account_ids {
                let abstract_account =
                    AccountI::load_from(abstract_deployment, AccountId::local(sub_account_id))?;
                if abstract_account.upgrade_account(abstract_deployment)? {
                    one_migration_was_successful = true;
                }
            }
        }

        // We upgrade the account to the latest version through all the versions
        loop {
            if self.upgrade_next_module_version(ACCOUNT)?.is_none() {
                break;
            }
            one_migration_was_successful = true;
        }

        Ok(one_migration_was_successful)
    }

    /// Attempt to upgrade a module to its next version.
    /// Will return `Ok(None)` if the module is on its latest version already.
    fn upgrade_next_module_version(
        &self,
        module_id: &str,
    ) -> Result<Option<Chain::Response>, AbstractInterfaceError> {
        let chain = self.environment().clone();

        // We start by getting the current module version
        let current_cw2_module_version: ContractVersion = if module_id == ACCOUNT {
            let current_account_version = chain
                .wasm_querier()
                .raw_query(&self.address()?, CONTRACT.as_slice().to_vec())
                .unwrap();
            from_json(current_account_version)?
        } else {
            self.module_versions(vec![module_id.to_string()])?.versions[0].clone()
        };
        let current_module_version = Version::parse(&current_cw2_module_version.version)?;

        let module = ModuleInfo::from_id(module_id, current_module_version.to_string().into())?;

        // We query all the module versions above the current one
        let abstr = Abstract::load_from(chain.clone())?;
        let all_next_module_versions = abstr
            .registry
            .module_list(
                Some(ModuleFilter {
                    namespace: Some(module.namespace.to_string()),
                    name: Some(module.name.clone()),
                    version: None,
                    status: Some(ModuleStatus::Registered),
                }),
                None,
                Some(module.clone()),
            )?
            .modules
            .into_iter()
            .map(|module| {
                let version: Version = module.module.info.version.clone().try_into().unwrap();
                version
            })
            .collect::<Vec<_>>();

        // Two cases now.
        // 1. If there exists a higher non-compatible version, we want to update to the next breaking version
        // 2. If there are only compatible versions we want to update the highest compatible version

        // Set current version as version requirement (`^x.y.z`)
        let requirement = VersionReq::parse(current_module_version.to_string().as_str())?;

        // Find out the lowest next major version
        let non_compatible_versions = all_next_module_versions
            .iter()
            .filter(|version| !requirement.matches(version))
            .collect::<Vec<_>>();

        let maybe_min_non_compatible_version = non_compatible_versions.iter().min().cloned();

        let selected_version = if let Some(min_non_compatible_version) =
            maybe_min_non_compatible_version
        {
            // Case 1
            // There is a next breaking version, we want to get the highest minor version associated with it
            let requirement = VersionReq::parse(min_non_compatible_version.to_string().as_str())?;

            non_compatible_versions
                .into_iter()
                .filter(|version| requirement.matches(version))
                .max()
                .unwrap()
                .clone()
        } else {
            // Case 2
            let possible_version = all_next_module_versions
                .into_iter()
                .filter(|version| version != &current_module_version)
                .max();

            // No version upgrade required
            if possible_version.is_none() {
                return Ok(None);
            }
            possible_version.unwrap()
        };

        // Actual upgrade to the next version
        Some(self.upgrade(vec![(
            ModuleInfo::from_id(
                module_id,
                ModuleVersion::Version(selected_version.to_string()),
            )?,
            Some(to_json_binary(&Empty {})?),
        )]))
        .transpose()
        .map_err(Into::into)
    }

    pub fn claim_namespace(
        &self,
        namespace: impl Into<String>,
    ) -> Result<Chain::Response, AbstractInterfaceError> {
        let abstr = Abstract::load_from(self.environment().clone())?;
        abstr
            .registry
            .claim_namespace(self.id()?, namespace.into())
            .map_err(Into::into)
    }

    pub fn update_whitelist(
        &self,
        to_add: Vec<String>,
        to_remove: Vec<String>,
    ) -> Result<(), AbstractInterfaceError> {
        self.update_internal_config(InternalConfigAction::UpdateWhitelist { to_add, to_remove })?;
        Ok(())
    }
}

impl<Chain: CwEnv> Uploadable for AccountI<Chain> {
    fn wrapper() -> <Mock as TxHandler>::ContractSource {
        Box::new(
            ContractWrapper::new_with_empty(
                ::account::contract::execute,
                ::account::contract::instantiate,
                ::account::contract::query,
            )
            .with_migrate(::account::contract::migrate)
            .with_reply(::account::contract::reply),
        )
    }
    fn wasm(chain: &ChainInfoOwned) -> WasmPath {
        artifacts_dir_from_workspace!()
            .find_wasm_path_with_build_postfix(
                "account",
                cw_orch::build::BuildPostfix::ChainName(chain),
            )
            .unwrap()
    }
}

impl<Chain: CwEnv> std::fmt::Display for AccountI<Chain> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Account: {:?} ({:?})",
            self.id(),
            self.addr_str()
                .or_else(|_| Result::<_, CwOrchError>::Ok(String::from("unknown"))),
        )
    }
}

impl<Chain: CwEnv> Debug for AccountI<Chain> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Account: {:?}", self.id())
    }
}