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
use abstract_sdk::os::ibc_host::{
    BaseExecuteMsg, ExecuteMsg, HostAction, InternalAction, PacketMsg,
};
use abstract_sdk::Execution;

use abstract_sdk::base::{ExecuteEndpoint, Handler};
use cosmwasm_std::{
    from_binary, from_slice, DepsMut, Env, IbcPacketReceiveMsg, IbcReceiveResponse, MessageInfo,
    Response, StdError,
};
use schemars::JsonSchema;
use serde::{de::DeserializeOwned, Serialize};

use crate::{
    error::HostError,
    host_commands::{receive_query, receive_register, receive_who_am_i},
    state::{Host, ACCOUNTS, CLIENT_PROXY, CLOSED_CHANNELS, PROCESSING_PACKET},
};

/// The host contract base implementation.
impl<
        Error: From<cosmwasm_std::StdError> + From<HostError>,
        CustomExecMsg: Serialize + DeserializeOwned + JsonSchema,
        CustomInitMsg,
        CustomQueryMsg,
        CustomMigrateMsg,
        ReceiveMsg: Serialize + JsonSchema,
    > ExecuteEndpoint
    for Host<Error, CustomExecMsg, CustomInitMsg, CustomQueryMsg, CustomMigrateMsg, ReceiveMsg>
{
    type ExecuteMsg = ExecuteMsg<CustomExecMsg, ReceiveMsg>;

    fn execute(
        self,
        deps: DepsMut,
        env: Env,
        info: MessageInfo,
        msg: Self::ExecuteMsg,
    ) -> Result<Response, Self::Error> {
        match msg {
            ExecuteMsg::App(request) => self.execute_handler()?(deps, env, info, self, request),
            ExecuteMsg::Base(exec_msg) => self
                .base_execute(deps, env, info, exec_msg)
                .map_err(From::from),
            _ => Err(StdError::generic_err("Unsupported Host execute message variant").into()),
        }
    }
}

/// The host contract base implementation.
impl<
        Error: From<cosmwasm_std::StdError> + From<HostError>,
        CustomExecMsg: DeserializeOwned,
        CustomInitMsg,
        CustomQueryMsg,
        CustomMigrateMsg,
        ReceiveMsg,
    > Host<Error, CustomExecMsg, CustomInitMsg, CustomQueryMsg, CustomMigrateMsg, ReceiveMsg>
{
    /// Takes ibc request, matches and executes
    /// This fn is the only way to get an Host instance.
    pub fn handle_packet<RequestError: From<cosmwasm_std::StdError> + From<HostError>>(
        mut self,
        deps: DepsMut,
        env: Env,
        packet: IbcPacketReceiveMsg,
        packet_handler: impl FnOnce(
            DepsMut,
            Env,
            Self,
            CustomExecMsg,
        ) -> Result<IbcReceiveResponse, RequestError>,
    ) -> Result<IbcReceiveResponse, RequestError> {
        let packet = packet.packet;
        // which local channel did this packet come on
        let channel = packet.dest.channel_id;
        let PacketMsg {
            client_chain,
            os_id,
            action,
            ..
        } = from_slice(&packet.data)?;
        // fill the local proxy address
        self.proxy_address = ACCOUNTS.may_load(deps.storage, (&channel, os_id))?;
        match action {
            HostAction::Internal(InternalAction::Register { os_proxy_address }) => {
                receive_register(deps, env, self, channel, os_id, os_proxy_address)
            }
            HostAction::Internal(InternalAction::WhoAmI) => {
                let this_chain = self.base_state.load(deps.storage)?.chain;
                receive_who_am_i(this_chain)
            }
            HostAction::Dispatch { msgs, .. } => self.receive_dispatch(deps, msgs),
            HostAction::Query { msgs, .. } => receive_query(deps.as_ref(), msgs),
            HostAction::Balances {} => self.receive_balances(deps),
            HostAction::SendAllBack {} => {
                // address of the proxy on the client chain
                let client_proxy_address = CLIENT_PROXY.load(deps.storage, (&channel, os_id))?;
                self.receive_send_all_back(deps, env, client_proxy_address, client_chain)
            }
            HostAction::App { msg } => {
                PROCESSING_PACKET.save(deps.storage, &(from_slice(&packet.data)?, channel))?;
                return packet_handler(deps, env, self, from_binary(&msg)?);
            }
        }
        .map_err(Into::into)
    }

    pub fn base_execute(
        mut self,
        deps: DepsMut,
        _env: Env,
        info: MessageInfo,
        message: BaseExecuteMsg,
    ) -> Result<Response, HostError> {
        match message {
            BaseExecuteMsg::UpdateAdmin { admin } => {
                let new_admin = deps.api.addr_validate(&admin)?;
                self.admin
                    .execute_update_admin(deps, info, Some(new_admin))
                    .map_err(Into::into)
            }
            BaseExecuteMsg::UpdateConfig {
                ans_host_address,
                cw1_code_id,
            } => self.update_config(deps, info, ans_host_address, cw1_code_id),
            BaseExecuteMsg::RecoverAccount {
                closed_channel,
                os_id,
                msgs,
            } => {
                let closed_channels = CLOSED_CHANNELS.load(deps.storage)?;
                if !closed_channels.contains(&closed_channel) {
                    return Err(HostError::ChannelNotClosed {});
                }
                self.admin.assert_admin(deps.as_ref(), &info.sender)?;
                self.proxy_address = ACCOUNTS.may_load(deps.storage, (&closed_channel, os_id))?;
                ACCOUNTS.remove(deps.storage, (&closed_channel, os_id));
                // Execute provided msgs on proxy.
                self.executor(deps.as_ref())
                    .execute_with_response(msgs, "recover_account")
                    .map_err(Into::into)
            }
        }
    }

    fn update_config(
        &self,
        deps: DepsMut,
        info: MessageInfo,
        ans_host_address: Option<String>,
        cw1_code_id: Option<u64>,
    ) -> Result<Response, HostError> {
        let mut state = self.state(deps.storage)?;

        self.admin.assert_admin(deps.as_ref(), &info.sender)?;

        if let Some(ans_host_address) = ans_host_address {
            // validate address format
            state.ans_host.address = deps.api.addr_validate(&ans_host_address)?;
        }
        if let Some(cw1_code_id) = cw1_code_id {
            // validate address format
            state.cw1_code_id = cw1_code_id;
        }
        self.base_state.save(deps.storage, &state)?;
        Ok(Response::new())
    }
}