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
use abstract_std::{
    base::ExecuteMsg as MiddlewareExecMsg,
    ibc::{ModuleIbcInfo, ModuleIbcMsg},
    ibc_client::InstalledModuleIdentification,
    ibc_host::{
        state::{ActionAfterCreationCache, CONFIG, TEMP_ACTION_AFTER_CREATION},
        HelperAction, HostAction, InternalAction,
    },
    objects::{
        account::AccountTrace, module::ModuleInfo, module_reference::ModuleReference, AccountId,
        TruncatedChainId,
    },
};
use cosmwasm_std::{
    to_json_vec, wasm_execute, Binary, ContractResult, Deps, DepsMut, Empty, Env, QueryRequest,
    Response, StdError, SystemResult, WasmQuery,
};

use crate::{
    account_commands::{self, receive_dispatch, receive_register, receive_send_all_back},
    contract::HostResult,
    HostError,
};

/// Handle actions that are passed to the IBC host contract
/// This function is not permissioned and access control needs to be handled outside of it
/// Usually the `client_chain` argument needs to be derived from the message sender
pub fn handle_host_action(
    deps: DepsMut,
    env: Env,
    client_chain: TruncatedChainId,
    proxy_address: String,
    received_account_id: AccountId,
    host_action: HostAction,
) -> HostResult {
    // Push the client chain to the account trace
    let account_id = {
        let mut account_id = received_account_id.clone();
        account_id.push_chain(client_chain.clone());
        account_id
    };

    // get the local account information
    match host_action {
        HostAction::Internal(InternalAction::Register {
            description,
            link,
            name,
            base_asset,
            namespace,
            install_modules,
        }) => receive_register(
            deps,
            env,
            account_id,
            name,
            description,
            link,
            base_asset,
            namespace,
            install_modules,
            false,
        ),

        action => {
            // If this account already exists, we can propagate the action
            if let Ok(account) = account_commands::get_account(deps.as_ref(), &account_id) {
                match action {
                    HostAction::Dispatch { manager_msgs } => {
                        receive_dispatch(deps, account, manager_msgs)
                    }
                    HostAction::Helpers(helper_action) => match helper_action {
                        HelperAction::SendAllBack => {
                            receive_send_all_back(deps, env, account, proxy_address, client_chain)
                        }
                        _ => unimplemented!(""),
                    },
                    HostAction::Internal(InternalAction::Register { .. }) => {
                        unreachable!("This action is handled above")
                    }
                    _ => unimplemented!(""),
                }
            } else {
                // If no account is created already, we create one and execute the action on reply
                // The account metadata are not set with this call
                // One will have to change them at a later point if they decide to
                let name = format!(
                    "Remote Abstract Account for {}/{}",
                    client_chain.as_str(),
                    account_id
                );

                // We save the action they wanted to dispatch for the reply triggered by the receive_register function
                TEMP_ACTION_AFTER_CREATION.save(
                    deps.storage,
                    &ActionAfterCreationCache {
                        action,
                        client_proxy_address: proxy_address,
                        account_id: received_account_id,
                        chain_name: client_chain,
                    },
                )?;
                receive_register(
                    deps,
                    env,
                    account_id,
                    name,
                    None,
                    None,
                    None,
                    None,
                    vec![],
                    true,
                )
            }
        }
    }
    .map_err(Into::into)
}

/// Handle actions that are passed to the IBC host contract and originate from a registered module
pub fn handle_module_execute(
    deps: DepsMut,
    env: Env,
    src_chain: TruncatedChainId,
    source_module: InstalledModuleIdentification,
    target_module: ModuleInfo,
    msg: Binary,
) -> HostResult {
    // We resolve the target module
    let vc = CONFIG.load(deps.storage)?.version_control;

    let target_module = InstalledModuleIdentification {
        module_info: target_module,
        // Account can only call modules that are installed on its ICAA.
        // If the calling module is account-specific then we map the calling account-id to the destination.
        account_id: source_module
            .account_id
            .map(|a| client_to_host_module_account_id(&env, src_chain.clone(), a)),
    };

    let target_module_resolved = target_module.addr(deps.as_ref(), vc)?;

    match target_module_resolved.reference {
        ModuleReference::AccountBase(_) | ModuleReference::Native(_) => {
            return Err(HostError::WrongModuleAction(
                "Can't send module-to-module message to an account or a native module".to_string(),
            ))
        }
        _ => {}
    }

    let response = Response::new().add_attribute("action", "module-ibc-call");
    // We pass the message on to the module
    let msg = wasm_execute(
        target_module_resolved.address,
        &MiddlewareExecMsg::ModuleIbc::<Empty, Empty>(ModuleIbcMsg {
            src_module_info: ModuleIbcInfo {
                chain: src_chain,
                module: source_module.module_info,
            },
            msg,
        }),
        vec![],
    )?;

    Ok(response.add_message(msg))
}

/// Handle actions that are passed to the IBC host contract and originate from a registered module
pub fn handle_host_module_query(
    deps: Deps,
    target_module: InstalledModuleIdentification,
    msg: Binary,
) -> HostResult<Binary> {
    // We resolve the target module
    let vc = CONFIG.load(deps.storage)?.version_control;

    let target_module_resolved = target_module.addr(deps, vc)?;

    let query = QueryRequest::<Empty>::from(WasmQuery::Smart {
        contract_addr: target_module_resolved.address.into_string(),
        msg,
    });
    let bin = match deps.querier.raw_query(&to_json_vec(&query)?) {
        SystemResult::Err(system_err) => Err(StdError::generic_err(format!(
            "Querier system error: {system_err}"
        ))),
        SystemResult::Ok(ContractResult::Err(contract_err)) => Err(StdError::generic_err(format!(
            "Querier contract error: {contract_err}"
        ))),
        SystemResult::Ok(ContractResult::Ok(value)) => Ok(value),
    }?;
    Ok(bin)
}

/// We need to figure what trace module is implying here
pub fn client_to_host_module_account_id(
    env: &Env,
    remote_chain: TruncatedChainId,
    mut account_id: AccountId,
) -> AccountId {
    let account_trace = account_id.trace_mut();
    match account_trace {
        AccountTrace::Local => account_trace.push_chain(remote_chain),
        AccountTrace::Remote(trace) => {
            let current_chain_name = TruncatedChainId::from_chain_id(&env.block.chain_id);
            // If current chain_name == last trace in account_id it means we got response back from remote chain
            if current_chain_name.eq(trace.last().unwrap()) {
                trace.pop();
                if trace.is_empty() {
                    *account_trace = AccountTrace::Local;
                }
            } else {
                trace.push(remote_chain);
            }
        }
    };
    account_id
}