abstract-adapter 0.24.1-beta.2

base adapter contract implementation
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
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
use abstract_sdk::{
    base::{ExecuteEndpoint, Handler, IbcCallbackEndpoint, ModuleIbcEndpoint},
    features::ModuleIdentification,
    AbstractResponse, AccountVerification,
};
use abstract_std::{
    account::state::ACCOUNT_MODULES,
    adapter::{AdapterBaseMsg, AdapterExecuteMsg, AdapterRequestMsg, BaseExecuteMsg, ExecuteMsg},
    objects::ownership::nested_admin::query_top_level_owner_addr,
};
use cosmwasm_std::{Addr, Deps, DepsMut, Env, MessageInfo, QuerierWrapper, Response, StdResult};
use schemars::JsonSchema;
use serde::Serialize;

use crate::{
    error::AdapterError,
    state::{AdapterContract, ContractError, MAXIMUM_AUTHORIZED_ADDRESSES},
    AdapterResult,
};

impl<
        Error: ContractError,
        CustomInitMsg,
        CustomExecMsg: Serialize + JsonSchema + AdapterExecuteMsg,
        CustomQueryMsg,
        SudoMsg,
    > ExecuteEndpoint
    for AdapterContract<Error, CustomInitMsg, CustomExecMsg, CustomQueryMsg, SudoMsg>
{
    type ExecuteMsg = ExecuteMsg<CustomExecMsg>;

    fn execute(
        mut self,
        deps: DepsMut,
        env: Env,
        info: MessageInfo,
        msg: Self::ExecuteMsg,
    ) -> Result<Response, Error> {
        match msg {
            ExecuteMsg::Module(request) => self.handle_app_msg(deps, env, info, request),
            ExecuteMsg::Base(exec_msg) => self
                .base_execute(deps, env, info, exec_msg)
                .map_err(From::from),
            ExecuteMsg::IbcCallback(msg) => self.ibc_callback(deps, env, info, msg),
            ExecuteMsg::ModuleIbc(msg) => self.module_ibc(deps, env, info, msg),
        }
    }
}

fn is_top_level_owner(querier: &QuerierWrapper, account: Addr, sender: &Addr) -> StdResult<bool> {
    let owner = query_top_level_owner_addr(querier, account)?;
    Ok(owner == sender)
}

/// The api-contract base implementation.
impl<Error: ContractError, CustomInitMsg, CustomExecMsg, CustomQueryMsg, SudoMsg>
    AdapterContract<Error, CustomInitMsg, CustomExecMsg, CustomQueryMsg, SudoMsg>
{
    fn base_execute(
        &mut self,
        deps: DepsMut,
        env: Env,
        info: MessageInfo,
        message: BaseExecuteMsg,
    ) -> AdapterResult {
        let BaseExecuteMsg {
            account_address,
            msg,
        } = message;
        let account_registry = self.account_registry(deps.as_ref(), &env)?;
        let account = account_registry
            .assert_is_account_admin(&env, &info.sender)
            .map_err(|_| AdapterError::UnauthorizedAdapterRequest {
                adapter: self.module_id().to_string(),
                sender: info.sender.to_string(),
            })
            .or_else(|e| {
                // If the sender is not an account or doesn't have the admin functionality enabled, the sender must be a top-level account owner
                match account_address {
                    Some(requested_account) => {
                        let account_address = deps.api.addr_validate(&requested_account)?;
                        let account = account_registry.assert_is_account(&account_address)?;
                        if is_top_level_owner(&deps.querier, account.addr().clone(), &info.sender)
                            .unwrap_or(false)
                        {
                            Ok(account)
                        } else {
                            Err(AdapterError::UnauthorizedAdapterRequest {
                                adapter: self.module_id().to_string(),
                                sender: info.sender.to_string(),
                            })
                        }
                    }
                    // If not provided the sender must be the direct owner AND have admin execution rights
                    None => Err(e),
                }
            })?;

        self.target_account = Some(account);
        match msg {
            AdapterBaseMsg::UpdateAuthorizedAddresses { to_add, to_remove } => {
                self.update_authorized_addresses(deps, info, to_add, to_remove)
            }
        }
    }

    /// Handle a custom execution message sent to this api.
    /// Two success scenarios are possible:
    /// 1. The sender is an authorized address of the given account address and has provided the account address in the message.
    /// 2. The sender is a account of the given account address.
    fn handle_app_msg(
        mut self,
        deps: DepsMut,
        env: Env,
        info: MessageInfo,
        request: AdapterRequestMsg<CustomExecMsg>,
    ) -> Result<Response, Error> {
        let sender = &info.sender;
        let unauthorized_sender = || AdapterError::UnauthorizedAddressAdapterRequest {
            adapter: self.module_id().to_string(),
            sender: sender.to_string(),
        };

        let account_registry = self.account_registry(deps.as_ref(), &env)?;

        let account = match request.account_address {
            // The sender must either be an authorized address or account.
            Some(requested_account) => {
                let account_address = deps.api.addr_validate(&requested_account)?;
                let requested_core = account_registry.assert_is_account(&account_address)?;

                if requested_core.addr() == sender {
                    // If the caller is the account of the indicated account_address, it's authorized to do the operation
                    // This covers the case where the account field of the request is indicated where it doesn't need to be
                    requested_core
                } else {
                    // If not, we load the authorized addresses for the given account address.
                    let authorized = self
                        .authorized_addresses
                        .load(deps.storage, account_address)
                        .unwrap_or_default();
                    if authorized.contains(sender)
                        || is_top_level_owner(&deps.querier, requested_core.addr().clone(), sender)
                            .unwrap_or(false)
                    {
                        // If the sender is an authorized address,
                        // or top level account return the account.
                        requested_core
                    } else {
                        // If not, we error, this call is not permitted
                        return Err(unauthorized_sender().into());
                    }
                }
            }
            None => account_registry
                .assert_is_account(sender)
                .map_err(|_| unauthorized_sender())?,
        };
        self.target_account = Some(account);
        self.execute_handler()?(deps, env, info, self, request.request)
    }

    /// Update authorized addresses from the adapter.
    fn update_authorized_addresses(
        &self,
        deps: DepsMut,
        info: MessageInfo,
        to_add: Vec<String>,
        to_remove: Vec<String>,
    ) -> AdapterResult {
        let account = self.target_account.as_ref().unwrap();
        let account_addr = account.addr().clone();

        let mut authorized_addrs = self
            .authorized_addresses
            .may_load(deps.storage, account_addr.clone())?
            .unwrap_or_default();

        // Handle the addition of authorized addresses
        for authorized in to_add {
            // authorized here can either be a contract address or a module id
            let authorized_addr = get_addr_from_module_id_or_addr(
                deps.as_ref(),
                info.sender.clone(),
                authorized.clone(),
            )?;

            if authorized_addrs.contains(&authorized_addr) {
                return Err(AdapterError::AuthorizedAddressOrModuleIdAlreadyPresent {
                    addr_or_module_id: authorized,
                });
            } else {
                authorized_addrs.push(authorized_addr);
            }
        }

        // Handling the removal of authorized addresses
        for deauthorized in to_remove {
            let deauthorized_addr = get_addr_from_module_id_or_addr(
                deps.as_ref(),
                info.sender.clone(),
                deauthorized.clone(),
            )?;
            if !authorized_addrs.contains(&deauthorized_addr) {
                return Err(AdapterError::AuthorizedAddressOrModuleIdNotPresent {
                    addr_or_module_id: deauthorized,
                });
            } else {
                authorized_addrs.retain(|addr| deauthorized_addr.ne(addr));
            }
        }

        if authorized_addrs.len() > MAXIMUM_AUTHORIZED_ADDRESSES as usize {
            return Err(AdapterError::TooManyAuthorizedAddresses {
                max: MAXIMUM_AUTHORIZED_ADDRESSES,
            });
        }

        self.authorized_addresses
            .save(deps.storage, account_addr.clone(), &authorized_addrs)?;
        Ok(self.custom_response(
            "update_authorized_addresses",
            vec![("account", account_addr.as_str())],
        ))
    }
}

/// This function is a helper to get a contract address from a module ir or from an address.
/// This is a temporary fix until we change or get rid of the UpdateAuthorizedAddresses API
fn get_addr_from_module_id_or_addr(
    deps: Deps,
    account: Addr,
    addr_or_module_id: String,
) -> Result<Addr, AdapterError> {
    // authorized here can either be a contract address or a module id
    if let Ok(Some(addr)) = ACCOUNT_MODULES.query(&deps.querier, account, &addr_or_module_id) {
        // In case we receive a module id
        Ok(addr)
    } else if let Ok(addr) = deps.api.addr_validate(addr_or_module_id.as_str()) {
        // In case we receive an address
        Ok(addr)
    } else {
        Err(AdapterError::AuthorizedAddressOrModuleIdNotValid { addr_or_module_id })
    }
}

#[cfg(test)]
mod tests {
    use abstract_std::adapter;
    use abstract_testing::prelude::*;
    use cosmwasm_std::{testing::*, Addr, Storage};

    use super::*;
    use crate::mock::{mock_init, AdapterMockResult, MockError, MockExecMsg, MOCK_ADAPTER};

    fn execute_as(
        deps: &mut MockDeps,
        sender: &Addr,
        msg: ExecuteMsg<MockExecMsg>,
    ) -> Result<Response, MockError> {
        let env = mock_env_validated(deps.api);
        MOCK_ADAPTER.execute(deps.as_mut(), env, message_info(sender, &[]), msg)
    }

    fn base_execute_as(
        deps: &mut MockDeps,
        sender: &Addr,
        msg: BaseExecuteMsg,
    ) -> Result<Response, MockError> {
        execute_as(deps, sender, adapter::ExecuteMsg::Base(msg))
    }

    mod update_authorized_addresses {
        use super::*;
        use crate::mock::TEST_AUTHORIZED_ADDR;

        fn load_test_account_authorized_addresses(
            storage: &dyn Storage,
            account_addr: &Addr,
        ) -> Vec<Addr> {
            MOCK_ADAPTER
                .authorized_addresses
                .load(storage, account_addr.clone())
                .unwrap()
        }

        #[coverage_helper::test]
        fn authorize_address() -> AdapterMockResult {
            let mut deps = mock_dependencies();
            let account = test_account(deps.api);
            deps.querier = abstract_mock_querier_builder(deps.api)
                .account(&account, TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&account)
                .build();

            mock_init(&mut deps)?;

            let msg = BaseExecuteMsg {
                msg: AdapterBaseMsg::UpdateAuthorizedAddresses {
                    to_add: vec![deps.api.addr_make(TEST_AUTHORIZED_ADDR).to_string()],
                    to_remove: vec![],
                },
                account_address: None,
            };

            base_execute_as(&mut deps, account.addr(), msg)?;

            let api = MOCK_ADAPTER;
            assert!(!api.authorized_addresses.is_empty(&deps.storage));

            let test_account_authorized_addrs =
                load_test_account_authorized_addresses(&deps.storage, account.addr());

            assert_eq!(test_account_authorized_addrs.len(), 1);
            assert!(
                test_account_authorized_addrs.contains(&deps.api.addr_make(TEST_AUTHORIZED_ADDR))
            );
            Ok(())
        }

        #[coverage_helper::test]
        fn revoke_address_authorization() -> AdapterMockResult {
            let mut deps = mock_dependencies();
            let account = test_account(deps.api);
            deps.querier = abstract_mock_querier_builder(deps.api)
                .account(&account, TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&account)
                .build();

            mock_init(&mut deps)?;

            let _api = MOCK_ADAPTER;
            let msg = BaseExecuteMsg {
                account_address: None,
                msg: AdapterBaseMsg::UpdateAuthorizedAddresses {
                    to_add: vec![deps.api.addr_make(TEST_AUTHORIZED_ADDR).to_string()],
                    to_remove: vec![],
                },
            };

            base_execute_as(&mut deps, account.addr(), msg)?;

            let authorized_addrs =
                load_test_account_authorized_addresses(&deps.storage, account.addr());
            assert_eq!(authorized_addrs.len(), 1);

            let msg = BaseExecuteMsg {
                account_address: None,
                msg: AdapterBaseMsg::UpdateAuthorizedAddresses {
                    to_add: vec![],
                    to_remove: vec![deps.api.addr_make(TEST_AUTHORIZED_ADDR).to_string()],
                },
            };

            base_execute_as(&mut deps, account.addr(), msg)?;
            let authorized_addrs =
                load_test_account_authorized_addresses(&deps.storage, account.addr());
            assert!(authorized_addrs.is_empty());
            Ok(())
        }

        #[coverage_helper::test]
        fn add_existing_authorized_address() -> AdapterMockResult {
            let mut deps = mock_dependencies();
            let account = test_account(deps.api);
            deps.querier = abstract_mock_querier_builder(deps.api)
                .account(&account, TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&account)
                .build();

            mock_init(&mut deps)?;

            let msg = BaseExecuteMsg {
                account_address: None,
                msg: AdapterBaseMsg::UpdateAuthorizedAddresses {
                    to_add: vec![deps.api.addr_make(TEST_AUTHORIZED_ADDR).to_string()],
                    to_remove: vec![],
                },
            };

            base_execute_as(&mut deps, account.addr(), msg)?;

            let msg = BaseExecuteMsg {
                account_address: None,
                msg: AdapterBaseMsg::UpdateAuthorizedAddresses {
                    to_add: vec![deps.api.addr_make(TEST_AUTHORIZED_ADDR).to_string()],
                    to_remove: vec![],
                },
            };

            let res = base_execute_as(&mut deps, account.addr(), msg);

            assert!(matches!(
                res,
                Err(MockError::Adapter(
                    AdapterError::AuthorizedAddressOrModuleIdAlreadyPresent {
                        addr_or_module_id: _test_authorized_address_string
                    }
                ))
            ));

            Ok(())
        }

        #[coverage_helper::test]
        fn add_module_id_authorized_address() -> AdapterMockResult {
            let mut deps = mock_dependencies();
            let account = test_account(deps.api);
            deps.querier = abstract_mock_querier_builder(deps.api)
                .account(&account, TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&account)
                .build();
            let abstr = AbstractMockAddrs::new(deps.api);

            mock_init(&mut deps)?;

            let _api = MOCK_ADAPTER;
            let msg = BaseExecuteMsg {
                account_address: None,
                msg: AdapterBaseMsg::UpdateAuthorizedAddresses {
                    to_add: vec![TEST_MODULE_ID.into()],
                    to_remove: vec![],
                },
            };

            base_execute_as(&mut deps, account.addr(), msg)?;

            let authorized_addrs =
                load_test_account_authorized_addresses(&deps.storage, account.addr());
            assert_eq!(authorized_addrs.len(), 1);
            assert_eq!(
                authorized_addrs[0].to_string(),
                abstr.module_address.to_string()
            );

            Ok(())
        }

        #[coverage_helper::test]
        fn remove_authorized_address_dne() -> AdapterMockResult {
            let mut deps = mock_dependencies();
            let account = test_account(deps.api);
            deps.querier = abstract_mock_querier_builder(deps.api)
                .account(&account, TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&account)
                .build();

            mock_init(&mut deps)?;
            let test_authorized_address_string =
                deps.api.addr_make(TEST_AUTHORIZED_ADDR).to_string();

            let _api = MOCK_ADAPTER;
            let msg = BaseExecuteMsg {
                account_address: None,
                msg: AdapterBaseMsg::UpdateAuthorizedAddresses {
                    to_add: vec![],
                    to_remove: vec![test_authorized_address_string.clone()],
                },
            };

            let res = base_execute_as(&mut deps, account.addr(), msg);

            assert_eq!(
                res,
                Err(MockError::Adapter(
                    AdapterError::AuthorizedAddressOrModuleIdNotPresent {
                        addr_or_module_id: test_authorized_address_string
                    }
                ))
            );
            Ok(())
        }
    }

    mod execute_app {
        use super::*;

        use crate::mock::TEST_AUTHORIZED_ADDR;
        use abstract_std::{
            objects::{account::AccountTrace, AccountId},
            registry::Account,
        };
        use cosmwasm_std::OwnedDeps;

        /// This sets up the test with the following:
        /// TEST_ACCOUNT has a single authorized address, test_authorized_address
        ///
        /// Note that the querier needs to mock the Account base, as the account will
        /// query the Account base to get the list of authorized addresses.
        fn setup_with_authorized_addresses(
            deps: &mut OwnedDeps<MockStorage, MockApi, MockQuerier>,
            authorized: Vec<&str>,
        ) {
            mock_init(deps).unwrap();

            let msg = BaseExecuteMsg {
                account_address: None,
                msg: AdapterBaseMsg::UpdateAuthorizedAddresses {
                    to_add: authorized
                        .into_iter()
                        .map(|addr| deps.api.addr_make(addr).to_string())
                        .collect(),
                    to_remove: vec![],
                },
            };

            let account = test_account(deps.api);
            base_execute_as(deps, account.addr(), msg).unwrap();
        }

        #[coverage_helper::test]
        fn unauthorized_addresses_are_unauthorized() {
            let mut deps = mock_dependencies();
            deps.querier = MockQuerierBuilder::new(deps.api)
                .account(&test_account(deps.api), TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&test_account(deps.api))
                .build();

            setup_with_authorized_addresses(&mut deps, vec![]);

            let msg = ExecuteMsg::Module(AdapterRequestMsg {
                account_address: None,
                request: MockExecMsg {},
            });

            let unauthorized = deps.api.addr_make("someoone");
            let res = execute_as(&mut deps, &unauthorized, msg);

            assert_unauthorized(res);
        }

        fn assert_unauthorized(res: Result<Response, MockError>) {
            assert!(matches!(
                res,
                Err(MockError::Adapter(
                    AdapterError::UnauthorizedAddressAdapterRequest {
                        sender: _unauthorized,
                        ..
                    }
                ))
            ));
        }

        #[coverage_helper::test]
        fn executing_as_account_account_is_allowed() {
            let mut deps = mock_dependencies();
            let account = test_account(deps.api);
            deps.querier = MockQuerierBuilder::new(deps.api)
                .account(&account, TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&account)
                .build();

            setup_with_authorized_addresses(&mut deps, vec![]);

            let msg = ExecuteMsg::Module(AdapterRequestMsg {
                account_address: None,
                request: MockExecMsg {},
            });

            let res = execute_as(&mut deps, account.addr(), msg);

            assert!(res.is_ok());
        }

        #[coverage_helper::test]
        fn executing_as_authorized_address_not_allowed_without_account() {
            let mut deps = mock_dependencies();
            deps.querier = MockQuerierBuilder::new(deps.api)
                .account(&test_account(deps.api), TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&test_account(deps.api))
                .build();

            setup_with_authorized_addresses(&mut deps, vec![TEST_AUTHORIZED_ADDR]);

            let msg = ExecuteMsg::Module(AdapterRequestMsg {
                account_address: None,
                request: MockExecMsg {},
            });

            let authorized = deps.api.addr_make(TEST_AUTHORIZED_ADDR);
            let res = execute_as(&mut deps, &authorized, msg);

            assert_unauthorized(res);
        }

        #[coverage_helper::test]
        fn executing_as_authorized_address_is_allowed_via_account() {
            let mut deps = mock_dependencies();
            let account = test_account(deps.api);
            deps.querier = MockQuerierBuilder::new(deps.api)
                .account(&account, TEST_ACCOUNT_ID)
                .set_account_admin_call_to(&account)
                .build();

            setup_with_authorized_addresses(&mut deps, vec![TEST_AUTHORIZED_ADDR]);

            let msg = ExecuteMsg::Module(AdapterRequestMsg {
                account_address: Some(account.addr().to_string()),
                request: MockExecMsg {},
            });

            let authorized = deps.api.addr_make(TEST_AUTHORIZED_ADDR);
            let res = execute_as(&mut deps, &authorized, msg);

            assert!(res.is_ok());
        }

        #[coverage_helper::test]
        fn executing_as_authorized_address_on_diff_account_should_err() {
            let mut deps = mock_dependencies();
            let account = test_account(deps.api);
            let another_account = Account::new(deps.api.addr_make("some_other_account"));
            deps.querier = MockQuerierBuilder::new(deps.api)
                .account(&account, TEST_ACCOUNT_ID)
                .account(
                    &another_account,
                    AccountId::new(69420u32, AccountTrace::Local).unwrap(),
                )
                .set_account_admin_call_to(&account)
                .build();

            setup_with_authorized_addresses(&mut deps, vec![TEST_AUTHORIZED_ADDR]);

            let msg = ExecuteMsg::Module(AdapterRequestMsg {
                account_address: Some(another_account.addr().to_string()),
                request: MockExecMsg {},
            });

            let authorized = deps.api.addr_make(TEST_AUTHORIZED_ADDR);
            let res = execute_as(&mut deps, &authorized, msg);

            assert_unauthorized(res);
        }
    }
}