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
use cosmwasm_schema::QueryResponses;
use cosmwasm_std::{Addr, Binary, Coin, Deps, Empty, QueryRequest, StdError};
use polytone::callbacks::CallbackMessage;

use self::state::IbcInfrastructure;
use crate::{
    ibc::CallbackInfo,
    ibc_host::HostAction,
    manager::{self, ModuleInstallConfig},
    objects::{
        account::AccountId, chain_name::ChainName, module::ModuleInfo,
        module_reference::ModuleReference, version_control::VersionControlContract, AssetEntry,
    },
    AbstractError,
};

pub mod state {

    use cosmwasm_std::Addr;
    use cw_storage_plus::{Item, Map};

    use crate::objects::{
        account::{AccountSequence, AccountTrace},
        ans_host::AnsHost,
        chain_name::ChainName,
        version_control::VersionControlContract,
    };

    #[cosmwasm_schema::cw_serde]
    pub struct Config {
        pub version_control: VersionControlContract,
        pub ans_host: AnsHost,
    }

    /// Information about the deployed infrastructure we're connected to.
    #[cosmwasm_schema::cw_serde]
    pub struct IbcInfrastructure {
        /// Address of the polytone note deployed on the local chain. This contract will forward the messages for us.
        pub polytone_note: Addr,
        /// The address of the abstract host deployed on the remote chain. This address will be called with our packet.
        pub remote_abstract_host: String,
        // The remote polytone proxy address which will be called by the polytone host.
        pub remote_proxy: Option<String>,
    }

    // Saves the local note deployed contract and the remote abstract host connected
    // This allows sending cross-chain messages
    pub const IBC_INFRA: Map<&ChainName, IbcInfrastructure> = Map::new("ibci");
    pub const REVERSE_POLYTONE_NOTE: Map<&Addr, ChainName> = Map::new("revpn");

    pub const CONFIG: Item<Config> = Item::new("config");
    /// (account_trace, account_sequence, chain_name) -> remote proxy account address. We use a
    /// triple instead of including AccountId since nested tuples do not behave as expected due to
    /// a bug that will be fixed in a future release.
    pub const ACCOUNTS: Map<(&AccountTrace, AccountSequence, &ChainName), String> =
        Map::new("accs");

    // For callbacks tests
    pub const ACKS: Item<Vec<String>> = Item::new("tmpc");
}

/// This needs no info. Owner of the contract is whoever signed the InstantiateMsg.
#[cosmwasm_schema::cw_serde]
pub struct InstantiateMsg {
    pub ans_host_address: String,
    pub version_control_address: String,
}

#[cosmwasm_schema::cw_serde]
pub struct MigrateMsg {}

#[cosmwasm_schema::cw_serde]
#[derive(cw_orch::ExecuteFns)]
pub enum ExecuteMsg {
    /// Update the ownership.
    UpdateOwnership(cw_ownable::Action),
    // Registers the polytone note on the local chain as well as the host on the remote chain to send messages through
    // This allows for monitoring which chain are connected to the contract remotely
    RegisterInfrastructure {
        /// Chain to register the infrastructure for ("juno", "osmosis", etc.)
        chain: String,
        /// Polytone note (locally deployed)
        note: String,
        /// Address of the abstract host deployed on the remote chain
        host: String,
    },
    /// Changes the config
    UpdateConfig {
        ans_host: Option<String>,
        version_control: Option<String>,
    },
    /// Only callable by Account proxy
    /// Will attempt to forward the specified funds to the corresponding
    /// address on the remote chain.
    SendFunds {
        host_chain: String,
        funds: Vec<Coin>,
    },
    /// Register an Account on a remote chain over IBC
    /// This action creates a proxy for them on the remote chain.
    Register {
        host_chain: String,
        base_asset: Option<AssetEntry>,
        namespace: Option<String>,
        install_modules: Vec<ModuleInstallConfig>,
    },
    ModuleIbcAction {
        host_chain: String,
        target_module: ModuleInfo,
        msg: Binary,
        callback_info: Option<CallbackInfo>,
    },
    IbcQuery {
        host_chain: String,
        query: QueryRequest<Empty>,
        callback_info: CallbackInfo,
    },
    RemoteAction {
        // host chain to be executed on
        // Example: "osmosis"
        host_chain: String,
        // execute the custom host function
        action: HostAction,
    },
    RemoveHost {
        host_chain: String,
    },
    /// Callback from the Polytone implementation
    /// This is NOT ONLY triggered when a contract execution is successful
    Callback(CallbackMessage),
}

/// This enum is used for sending callbacks to the note contract of the IBC client
#[cosmwasm_schema::cw_serde]
pub enum IbcClientCallback {
    ModuleRemoteAction {
        sender_address: String,
        callback_info: CallbackInfo,
        initiator_msg: Binary,
    },
    ModuleRemoteQuery {
        sender_address: String,
        callback_info: CallbackInfo,
        query: QueryRequest<Empty>,
    },
    CreateAccount {
        account_id: AccountId,
    },
    WhoAmI {},
}

/// This is used for identifying calling modules
/// For adapters, we don't need the account id because it's independent of an account
/// For apps and standalone, the account id is used to identify the calling module
#[cosmwasm_schema::cw_serde]
pub struct InstalledModuleIdentification {
    pub module_info: ModuleInfo,
    pub account_id: Option<AccountId>,
}

#[cosmwasm_schema::cw_serde]
pub struct ModuleAddr {
    pub reference: ModuleReference,
    pub address: Addr,
}

impl InstalledModuleIdentification {
    pub fn addr(
        &self,
        deps: Deps,
        vc: VersionControlContract,
    ) -> Result<ModuleAddr, AbstractError> {
        let target_module_resolved = vc.query_module(self.module_info.clone(), &deps.querier)?;

        let no_account_id_error =
            StdError::generic_err("Account id not specified in installed module definition");

        let target_addr = match &target_module_resolved.reference {
            ModuleReference::AccountBase(code_id) => {
                let target_account_id = self.account_id.clone().ok_or(no_account_id_error)?;
                let account_base = vc.account_base(&target_account_id, &deps.querier)?;

                if deps
                    .querier
                    .query_wasm_contract_info(&account_base.proxy)?
                    .code_id
                    == *code_id
                {
                    account_base.proxy
                } else if deps
                    .querier
                    .query_wasm_contract_info(&account_base.manager)?
                    .code_id
                    == *code_id
                {
                    account_base.manager
                } else {
                    Err(StdError::generic_err(
                        "Account base contract doesn't correspond to any of the proxy or manager",
                    ))?
                }
            }
            ModuleReference::Native(addr) => addr.clone(),
            ModuleReference::Adapter(addr) => addr.clone(),
            ModuleReference::App(_) | ModuleReference::Standalone(_) => {
                let target_account_id = self.account_id.clone().ok_or(no_account_id_error)?;
                let account_base = vc.account_base(&target_account_id, &deps.querier)?;

                let module_info: manager::ModuleAddressesResponse = deps.querier.query_wasm_smart(
                    account_base.manager,
                    &manager::QueryMsg::ModuleAddresses {
                        ids: vec![self.module_info.id()],
                    },
                )?;
                module_info
                    .modules
                    .first()
                    .ok_or(AbstractError::AppNotInstalled(self.module_info.to_string()))?
                    .1
                    .clone()
            }
        };
        Ok(ModuleAddr {
            reference: target_module_resolved.reference,
            address: target_addr,
        })
    }
}

#[cosmwasm_schema::cw_serde]
#[derive(QueryResponses, cw_orch::QueryFns)]
pub enum QueryMsg {
    /// Queries the ownership of the ibc client contract
    /// Returns [`cw_ownable::Ownership<Addr>`]
    #[returns(cw_ownable::Ownership<Addr> )]
    Ownership {},

    /// Returns config
    /// Returns [`ConfigResponse`]
    #[returns(ConfigResponse)]
    Config {},

    /// Returns the host information associated with a specific chain-name (e.g. osmosis, juno)
    /// Returns [`HostResponse`]
    #[returns(HostResponse)]
    Host { chain_name: String },

    // Shows all open channels (incl. remote info)
    /// Returns [`ListAccountsResponse`]
    #[returns(ListAccountsResponse)]
    ListAccounts {
        start: Option<(AccountId, String)>,
        limit: Option<u32>,
    },

    // Get channel info for one chain
    /// Returns [`AccountResponse`]
    #[returns(AccountResponse)]
    Account {
        chain: String,
        account_id: AccountId,
    },
    // get the hosts
    /// Returns [`ListRemoteHostsResponse`]
    #[returns(ListRemoteHostsResponse)]
    ListRemoteHosts {},

    // get the IBC execution proxies
    /// Returns [`ListRemoteProxiesResponse`]
    #[returns(ListRemoteProxiesResponse)]
    ListRemoteProxies {},

    // get the IBC execution proxies based on the account id passed
    /// Returns [`ListRemoteProxiesResponse`]
    #[returns(ListRemoteProxiesResponse)]
    ListRemoteProxiesByAccountId { account_id: AccountId },

    // get the IBC counterparts connected to this abstract client
    /// Returns [`ListIbcInfrastructureResponse`]
    #[returns(ListIbcInfrastructureResponse)]
    ListIbcInfrastructures {},
}

#[cosmwasm_schema::cw_serde]
pub struct ConfigResponse {
    pub ans_host: String,
    pub version_control_address: String,
}

#[cosmwasm_schema::cw_serde]
pub struct ListAccountsResponse {
    pub accounts: Vec<(AccountId, ChainName, String)>,
}

#[cosmwasm_schema::cw_serde]
pub struct ListRemoteHostsResponse {
    pub hosts: Vec<(ChainName, String)>,
}

#[cosmwasm_schema::cw_serde]
pub struct ListRemoteProxiesResponse {
    pub proxies: Vec<(ChainName, Option<String>)>,
}

#[cosmwasm_schema::cw_serde]
pub struct ListIbcInfrastructureResponse {
    pub counterparts: Vec<(ChainName, IbcInfrastructure)>,
}

#[cosmwasm_schema::cw_serde]
pub struct HostResponse {
    pub remote_host: String,
    pub remote_polytone_proxy: Option<String>,
}

#[cosmwasm_schema::cw_serde]
pub struct AccountResponse {
    pub remote_proxy_addr: String,
}

#[cosmwasm_schema::cw_serde]
pub struct RemoteProxyResponse {
    /// last block balance was updated (0 is never)
    pub channel_id: String,
    /// address of the remote proxy
    pub proxy_address: String,
}

#[cfg(test)]
mod tests {
    use cosmwasm_std::{to_json_binary, CosmosMsg, Empty};
    use speculoos::prelude::*;

    use crate::app::ExecuteMsg;
    use crate::ibc::{CallbackResult, IbcResponseMsg};

    // ... (other test functions)

    #[test]
    fn test_response_msg_to_callback_msg() {
        let receiver = "receiver".to_string();
        let callback_id = "15".to_string();
        let callback_msg = to_json_binary("15").unwrap();

        let result = CallbackResult::FatalError("ibc execution error".to_string());

        let response_msg = IbcResponseMsg {
            id: callback_id,
            msg: Some(callback_msg),
            result,
        };

        let actual: CosmosMsg<Empty> = response_msg
            .clone()
            .into_cosmos_msg(receiver.clone())
            .unwrap();

        assert_that!(actual).is_equal_to(CosmosMsg::Wasm(cosmwasm_std::WasmMsg::Execute {
            contract_addr: receiver,
            // we can't test the message because the fields in it are private
            msg: to_json_binary(&ExecuteMsg::<Empty, Empty>::IbcCallback(response_msg)).unwrap(),
            funds: vec![],
        }))
    }
}