abstract-client 0.26.1

A client oriented package for the Abstract Framework.
Documentation
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
//! # Represents Abstract Client
//!
//! [`AbstractClient`] allows you to do everything you might need to work with the Abstract
//! or to be more precise
//!
//! - Create or interact with Account
//! - Install or interact with a module (including apps and adapters)
//! - Publish modules
//! - Do integration tests with Abstract
//!
//! Example of publishing mock app
//!
//! ```
//! # use abstract_client::AbstractClientError;
//! use abstract_app::mock::mock_app_dependency::interface::MockAppI;
//! use cw_orch::prelude::*;
//! use abstract_client::{AbstractClient, Publisher, Namespace};
//! use abstract_testing::prelude::*;
//!
//! let chain = MockBech32::new("mock");
//! let client = AbstractClient::builder(chain.clone()).build()?;
//!
//! let namespace = Namespace::new("tester")?;
//! let publisher: Publisher<MockBech32> = client
//!     .account_builder()
//!     .namespace(namespace)
//!     .build()?
//!     .publisher()?;
//!
//! publisher.publish_app::<MockAppI<MockBech32>>()?;
//! # Ok::<(), AbstractClientError>(())
//! ```

use abstract_interface::{
    Abstract, AccountI, AnsHost, IbcClient, ModuleFactory, RegisteredModule, Registry,
};
use abstract_std::objects::{
    module::{ModuleInfo, ModuleStatus, ModuleVersion},
    module_reference::ModuleReference,
    namespace::Namespace,
    salt::generate_instantiate_salt,
    AccountId,
};
use cosmwasm_std::{BlockInfo, Uint128};
use cw_orch::{contract::Contract, environment::Environment as _, prelude::*};
use rand::Rng;

use crate::{
    account::{Account, AccountBuilder},
    source::AccountSource,
    AbstractClientError, Environment, Publisher, Service,
};

/// Client to interact with Abstract accounts and modules
#[derive(Clone)]
pub struct AbstractClient<Chain: CwEnv> {
    pub(crate) abstr: Abstract<Chain>,
}

/// The result type for the Abstract Client.
pub type AbstractClientResult<T> = Result<T, AbstractClientError>;

impl<Chain: CwEnv> AbstractClient<Chain> {
    /// Get [`AbstractClient`] from a chosen environment. [`Abstract`] should
    /// already be deployed to this environment.
    ///
    /// ```
    /// use abstract_client::AbstractClient;
    /// # use abstract_client::{Environment, AbstractClientError};
    /// # use cw_orch::prelude::*;
    /// # let chain = MockBech32::new("mock");
    /// # let client = AbstractClient::builder(chain.clone()).build().unwrap(); // Deploy mock abstract
    ///
    /// let client = AbstractClient::new(chain)?;
    /// # Ok::<(), AbstractClientError>(())
    /// ```
    pub fn new(chain: Chain) -> AbstractClientResult<Self> {
        let abstr = Abstract::load_from(chain)?;
        Ok(Self { abstr })
    }

    /// Registry contract API
    ///
    /// The Registry contract is a database contract that stores all module-related information.
    /// ```
    /// # use abstract_client::AbstractClientError;
    /// # let chain = cw_orch::prelude::MockBech32::new("mock");
    /// # let client = abstract_client::AbstractClient::builder(chain.clone()).build().unwrap();
    /// use abstract_std::objects::{module_reference::ModuleReference, module::ModuleInfo};
    /// // For getting registry address
    /// use cw_orch::prelude::*;
    ///
    /// let registry = client.registry();
    /// let vc_module = registry.module(ModuleInfo::from_id_latest("abstract:registry")?)?;
    /// assert_eq!(vc_module.reference, ModuleReference::Native(registry.address()?));
    /// # Ok::<(), AbstractClientError>(())
    /// ```
    pub fn registry(&self) -> &Registry<Chain> {
        &self.abstr.registry
    }

    /// Abstract Name Service contract API
    ///
    /// The Abstract Name Service contract is a database contract that stores all asset-related information.
    /// ```
    /// # use abstract_client::AbstractClientError;
    /// # use abstract_testing::prelude::*;
    /// use abstract_client::{AbstractClient, ClientResolve};
    /// use cw_asset::AssetInfo;
    /// use abstract_app::objects::AssetEntry;
    /// // For getting registry address
    /// use cw_orch::prelude::*;
    ///
    /// let denom = "test_denom";
    /// let entry = "denom";
    /// # let chain = MockBech32::new("mock");
    /// # let client = AbstractClient::builder(chain.clone())
    /// #     .asset(entry, cw_asset::AssetInfoBase::Native(denom.to_owned()))
    /// #     .build()?;
    ///
    /// let name_service = client.name_service();
    /// let asset_entry = AssetEntry::new(entry);
    /// let asset = asset_entry.resolve(name_service)?;
    /// assert_eq!(asset, AssetInfo::Native(denom.to_owned()));
    /// # Ok::<(), AbstractClientError>(())
    /// ```
    pub fn name_service(&self) -> &AnsHost<Chain> {
        &self.abstr.ans_host
    }

    /// Abstract Module Factory contract API
    pub fn module_factory(&self) -> &ModuleFactory<Chain> {
        &self.abstr.module_factory
    }

    /// Abstract Ibc Client contract API
    ///
    /// The Abstract Ibc Client contract allows users to create and use Interchain Abstract Accounts
    pub fn ibc_client(&self) -> &IbcClient<Chain> {
        &self.abstr.ibc.client
    }

    /// Service contract API
    pub fn service<M: RegisteredModule + From<Contract<Chain>>>(
        &self,
    ) -> AbstractClientResult<Service<Chain, M>> {
        Service::new(self.registry())
    }

    /// Return current block info see [`BlockInfo`].
    pub fn block_info(&self) -> AbstractClientResult<BlockInfo> {
        self.environment()
            .block_info()
            .map_err(|e| AbstractClientError::CwOrch(e.into()))
    }

    /// Fetches an existing Abstract [`Publisher`] from chain
    pub fn fetch_publisher(&self, namespace: Namespace) -> AbstractClientResult<Publisher<Chain>> {
        let account = self.fetch_account(namespace)?;
        account.publisher()
    }

    /// Builder for creating a new Abstract [`Account`].
    pub fn account_builder(&self) -> AccountBuilder<Chain> {
        AccountBuilder::new(&self.abstr)
    }

    /// Builder for creating a new Abstract [`Account`].
    pub fn sub_account_builder<'a>(
        &'a self,
        account: &'a Account<Chain>,
    ) -> AbstractClientResult<AccountBuilder<'a, Chain>> {
        let mut builder = AccountBuilder::new(&self.abstr);
        builder.sub_account(account);
        builder.name("Sub Account");
        Ok(builder)
    }

    /// Fetch an [`Account`] from a given source.
    ///
    /// This method is used to retrieve an account from a given source. It will **not** create a new account if the source is invalid.
    ///
    /// Sources that can be used are:
    /// - [`Namespace`]: Will retrieve the account from the namespace if it is already claimed.
    /// - [`AccountId`]: Will retrieve the account from the account id.
    /// - App [`Addr`]: Will retrieve the account from an app that is installed on it.
    pub fn fetch_account<T: Into<AccountSource>>(
        &self,
        source: T,
    ) -> AbstractClientResult<Account<Chain>> {
        let source = source.into();
        let chain = self.abstr.registry.environment();

        match source {
            AccountSource::Namespace(namespace) => {
                // if namespace, check if we need to claim or not.
                // Check if namespace already claimed
                let account_from_namespace_result: Option<Account<Chain>> =
                    Account::maybe_from_namespace(&self.abstr, namespace.clone())?;

                // Only return if the account can be retrieved without errors.
                if let Some(account_from_namespace) = account_from_namespace_result {
                    Ok(account_from_namespace)
                } else {
                    Err(AbstractClientError::NamespaceNotClaimed {
                        namespace: namespace.to_string(),
                    })
                }
            }
            AccountSource::AccountId(account_id) => {
                let abstract_account = AccountI::load_from(&self.abstr, account_id.clone())?;
                Ok(Account::new(abstract_account))
            }
            AccountSource::App(app) => {
                // Query app for account address and get AccountId from it.
                let app_config: abstract_std::app::AppConfigResponse = chain
                    .query(
                        &abstract_std::app::QueryMsg::<Empty>::Base(
                            abstract_std::app::BaseQueryMsg::BaseConfig {},
                        ),
                        &app,
                    )
                    .map_err(Into::into)?;

                let account_config: abstract_std::account::ConfigResponse = chain
                    .query(
                        &abstract_std::account::QueryMsg::Config {},
                        &app_config.account,
                    )
                    .map_err(Into::into)?;
                // This function verifies the account-id is valid and returns an error if not.
                let abstract_account = AccountI::load_from(&self.abstr, account_config.account_id)?;
                Ok(Account::new(abstract_account))
            }
        }
    }

    /// Fetches an existing Abstract [`Account`] from chain
    /// If the Namespace is not claimed, creates an account with the provided account builder
    pub fn fetch_or_build_account<T: Into<AccountSource>, F>(
        &self,
        source: T,
        build_fn: F,
    ) -> AbstractClientResult<Account<Chain>>
    where
        F: for<'a, 'b> FnOnce(
            &'a mut AccountBuilder<'b, Chain>,
        ) -> &'a mut AccountBuilder<'b, Chain>,
    {
        match self.fetch_account(source) {
            Ok(account) => Ok(account),
            Err(_) => {
                let mut account_builder = self.account_builder();
                build_fn(&mut account_builder).build()
            }
        }
    }

    /// Address of the sender
    pub fn sender(&self) -> Addr {
        self.environment().sender_addr()
    }

    /// Fetch an [`Account`] from a given source.
    ///
    /// This method is used to retrieve an account from a given source. It will **not** create a new account if the source is invalid.
    ///
    /// Sources that can be used are:
    /// - [`Namespace`]: Will retrieve the account from the namespace if it is already claimed.
    /// - [`AccountId`]: Will retrieve the account from the account id.
    /// - App [`Addr`]: Will retrieve the account from an app that is installed on it.
    #[deprecated(since = "0.24.2", note = "use fetch_account instead")]
    pub fn account_from<T: Into<AccountSource>>(
        &self,
        source: T,
    ) -> AbstractClientResult<Account<Chain>> {
        self.fetch_account(source)
    }

    /// Retrieve denom balance for provided address
    pub fn query_balance(
        &self,
        address: &Addr,
        denom: impl Into<String>,
    ) -> AbstractClientResult<Uint128> {
        let coins = self
            .environment()
            .bank_querier()
            .balance(address, Some(denom.into()))
            .map_err(Into::into)?;
        // There will always be a single element in this case.
        Ok(coins[0].amount)
    }

    /// Retrieve balances of all denoms for provided address
    pub fn query_balances(&self, address: &Addr) -> AbstractClientResult<Vec<Coin>> {
        self.environment()
            .bank_querier()
            .balance(address, None)
            .map_err(Into::into)
            .map_err(Into::into)
    }

    /// Waits for a specified number of blocks.
    pub fn wait_blocks(&self, amount: u64) -> AbstractClientResult<()> {
        self.environment()
            .wait_blocks(amount)
            .map_err(Into::into)
            .map_err(Into::into)
    }

    /// Waits for a specified number of blocks.
    pub fn wait_seconds(&self, secs: u64) -> AbstractClientResult<()> {
        self.environment()
            .wait_seconds(secs)
            .map_err(Into::into)
            .map_err(Into::into)
    }

    /// Waits for next block.
    pub fn next_block(&self) -> AbstractClientResult<()> {
        self.environment()
            .next_block()
            .map_err(Into::into)
            .map_err(Into::into)
    }

    /// Get random local account id sequence(unclaimed) in 2147483648..u32::MAX range
    pub fn random_account_id(&self) -> AbstractClientResult<u32> {
        let mut rng = rand::thread_rng();
        loop {
            let random_sequence = rng.gen_range(2147483648..u32::MAX);
            let potential_account_id = AccountId::local(random_sequence);
            if self.abstr.registry.account(potential_account_id).is_err() {
                return Ok(random_sequence);
            };
        }
    }

    /// Get address of instantiate2 module
    /// If used for upcoming account this supposed to be used in pair with [`AbstractClient::next_local_account_id`]
    pub fn module_instantiate2_address<M: RegisteredModule>(
        &self,
        account_id: &AccountId,
    ) -> AbstractClientResult<Addr> {
        self.module_instantiate2_address_raw(
            account_id,
            ModuleInfo::from_id(
                M::module_id(),
                ModuleVersion::Version(M::module_version().to_owned()),
            )?,
        )
    }

    /// Get address of instantiate2 module
    /// Raw version of [`AbstractClient::module_instantiate2_address`]
    /// If used for upcoming account this supposed to be used in pair with [`AbstractClient::next_local_account_id`]
    pub fn module_instantiate2_address_raw(
        &self,
        account_id: &AccountId,
        module_info: ModuleInfo,
    ) -> AbstractClientResult<Addr> {
        let salt = generate_instantiate_salt(account_id);
        let wasm_querier = self.environment().wasm_querier();
        let module = self.registry().module(module_info)?;
        let (code_id, creator) = match module.reference {
            // If Account - signer is creator
            ModuleReference::Account(id) => (id, self.environment().sender_addr()),
            // Else module factory is creator
            ModuleReference::App(id) | ModuleReference::Standalone(id) => {
                (id, self.abstr.module_factory.address()?)
            }
            _ => {
                return Err(AbstractClientError::Abstract(
                    abstract_std::AbstractError::Assert(
                        "module reference not account, app or standalone".to_owned(),
                    ),
                ))
            }
        };

        let addr = wasm_querier
            .instantiate2_addr(code_id, &creator, salt)
            .map_err(Into::into)?;
        Ok(Addr::unchecked(addr))
    }

    /// Retrieves the status of a specified module.
    ///
    /// This function checks the status of a module within the registry contract.
    /// and returns appropriate `Some(ModuleStatus)`. If the module is not deployed, it returns `None`.
    pub fn module_status(&self, module: ModuleInfo) -> AbstractClientResult<Option<ModuleStatus>> {
        self.registry().module_status(module).map_err(Into::into)
    }

    /// Clones the Abstract Client with a different sender.
    pub fn call_as(&self, sender: &<Chain as TxHandler>::Sender) -> Self {
        Self {
            abstr: self.abstr.call_as(sender),
        }
    }

    #[cfg(feature = "interchain")]
    /// Connect this abstract client to the remote abstract client
    /// If [`cw_orch_polytone::Polytone`] is deployed between 2 chains, it will NOT redeploy it (good for actual chains)
    /// If Polytone is not deployed, deploys it between the 2 chains (good for integration testing)
    pub fn connect_to(
        &self,
        remote_abstr: &AbstractClient<Chain>,
        ibc: &impl cw_orch_interchain::prelude::InterchainEnv<Chain>,
    ) -> AbstractClientResult<()>
    where
        Chain: cw_orch_interchain::prelude::IbcQueryHandler,
    {
        self.abstr.connect_to(&remote_abstr.abstr, ibc)?;

        Ok(())
    }
}