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
use std::{cell::RefCell, collections::BTreeMap, rc::Rc, u64};

use crate::{
    ibc::IbcChannelWrapper,
    ibc_application::{IbcApplication, PacketReceiveFailing, PacketReceiveOk},
    iper_app::InfallibleResult,
    router::{RouterWrapper, UseRouter, UseRouterResponse},
};

use anyhow::{anyhow, bail};

use cosmwasm_schema::cw_serde;
use cosmwasm_std::{
    from_json, Addr, Api, Binary, BlockInfo, CustomMsg, CustomQuery, Empty, IbcAcknowledgement,
    IbcChannelConnectMsg, IbcChannelOpenMsg, IbcEndpoint, IbcMsg, IbcPacketAckMsg,
    IbcPacketReceiveMsg, IbcQuery, IbcTimeout, Querier, Storage,
};
use cw_multi_test::{AppResponse, CosmosRouter, Ibc, Module};
use cw_storage_plus::Item;
use serde::de::DeserializeOwned;

use crate::{
    error::AppResult,
    ibc::{IbcMsgExt, IbcPort},
    iper_app::SharedChannels,
    router_closure,
};

pub(crate) const PENDING_PACKETS: Item<BTreeMap<u64, IbcPacketType>> = Item::new("pending_packets");

/// The [`IperIbcModule`] is the default struct used in an [`IperApp`](crate::iper_app::IperApp) as an `IBC module` and contains all [`IbcApplication`].
///
/// This structure implements the [`Module`] and [`Ibc`] `traits` from `cw-multi-test`.
///
/// When an [`IbcMsg`] needs to be handled, if the `src channel-id` matches a `port` of a saved [`IbcApplication`] within the
/// [`IperIbcModule`], the [`IbcApplication::handle_outgoing_packet`] function is called.
///
/// [`IbcApplication`] instances must be added to the [`IperIbcModule`] during the creation of the [`App`](cw_multi_test::App)
/// via the [`AppBuilder`](cw_multi_test::AppBuilder). This is achieved using the [`AppBuilderIperExt::with_ibc_app`](crate::iper_app_builder::AppBuilderIperExt) function.
///
/// It is essential that the `IBC module` in the [`AppBuilder`](cw_multi_test::AppBuilder) is set to [`IperIbcModule`] for this integration
/// to function correctly.

#[derive(Default)]
pub struct IperIbcModule {
    pub(crate) applications: BTreeMap<String, Rc<RefCell<dyn IbcApplication>>>,
    pub(crate) channels: SharedChannels,
}

impl IperIbcModule {
    fn load_application(
        &self,
        name: impl Into<String> + Clone,
    ) -> AppResult<&Rc<RefCell<dyn IbcApplication>>> {
        self.applications
            .get(&name.clone().into())
            .ok_or(anyhow!("application not found: {}", name.into()))
    }

    pub(crate) fn open_channel<ExecC, QueryC>(
        &self,
        api: &dyn Api,
        storage: &mut dyn Storage,
        router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
        block: &BlockInfo,
        application: &str,
        msg: IbcChannelOpenMsg,
    ) -> AppResult<AppResponse>
    where
        ExecC: CustomMsg + DeserializeOwned + 'static,
        QueryC: CustomQuery + DeserializeOwned + 'static,
    {
        let rc_storage = Rc::new(RefCell::new(storage));

        self.load_application(application)?.borrow().open_channel(
            api,
            block,
            &RouterWrapper::new(&router_closure!(router, api, rc_storage, block)),
            rc_storage.clone(),
            msg,
        )
    }

    pub(crate) fn channel_connect<ExecC, QueryC>(
        &self,
        api: &dyn Api,
        storage: &mut dyn Storage,
        router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
        block: &BlockInfo,
        application: &str,
        msg: IbcChannelConnectMsg,
    ) -> AppResult<AppResponse>
    where
        ExecC: CustomMsg + DeserializeOwned + 'static,
        QueryC: CustomQuery + DeserializeOwned + 'static,
    {
        let rc_storage = Rc::new(RefCell::new(storage));

        self.load_application(application)?
            .borrow()
            .channel_connect(
                api,
                block,
                &RouterWrapper::new(&router_closure!(router, api, rc_storage, block)),
                rc_storage.clone(),
                msg,
            )
    }

    pub(crate) fn packet_receive<ExecC, QueryC>(
        &self,
        api: &dyn Api,
        storage: &mut dyn Storage,
        router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
        block: &BlockInfo,
        application: &str,
        packet: IbcPacketReceiveMsg,
    ) -> InfallibleResult<PacketReceiveOk, PacketReceiveFailing>
    where
        ExecC: CustomMsg + DeserializeOwned + 'static,
        QueryC: CustomQuery + DeserializeOwned + 'static,
    {
        let rc_storage = Rc::new(RefCell::new(storage));

        self.load_application(application)
            .unwrap()
            .borrow()
            .packet_receive(
                api,
                block,
                &RouterWrapper::new(&router_closure!(router, api, rc_storage, block)),
                rc_storage.clone(),
                packet.clone(),
            )
    }

    pub(crate) fn packet_ack<ExecC, QueryC>(
        &self,
        api: &dyn Api,
        storage: &mut dyn Storage,
        router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
        block: &BlockInfo,
        application: &str,
        msg: AckPacket,
    ) -> AppResult<AppResponse>
    where
        ExecC: CustomMsg + DeserializeOwned + 'static,
        QueryC: CustomQuery + DeserializeOwned + 'static,
    {
        let rc_storage = Rc::new(RefCell::new(storage));

        self.load_application(application)?.borrow().packet_ack(
            api,
            block,
            &RouterWrapper::new(&router_closure!(router, api, rc_storage, block)),
            rc_storage.clone(),
            msg,
        )
    }

    pub(crate) fn packet_timeout<ExecC, QueryC>(
        &self,
        api: &dyn Api,
        storage: &mut dyn Storage,
        router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
        block: &BlockInfo,
        application: &str,
        msg: TimeoutPacket,
    ) -> AppResult<AppResponse>
    where
        ExecC: CustomMsg + DeserializeOwned + 'static,
        QueryC: CustomQuery + DeserializeOwned + 'static,
    {
        let rc_storage = Rc::new(RefCell::new(storage));

        self.load_application(application)?.borrow().packet_timeout(
            api,
            block,
            &RouterWrapper::new(&router_closure!(router, api, rc_storage, block)),
            rc_storage.clone(),
            msg,
        )
    }
}

impl Module for IperIbcModule {
    type ExecT = IbcMsg;
    type QueryT = IbcQuery;
    type SudoT = Empty;

    fn execute<ExecC, QueryC>(
        &self,
        api: &dyn Api,
        storage: &mut dyn Storage,
        router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
        block: &BlockInfo,
        sender: Addr,
        msg: Self::ExecT,
    ) -> AppResult<AppResponse>
    where
        ExecC: CustomMsg + DeserializeOwned + 'static,
        QueryC: CustomQuery + DeserializeOwned + 'static,
    {
        let channel = self.channels.borrow().get(msg.get_src_channel())?.clone();
        let rc_storage = Rc::new(RefCell::new(storage));

        if let IbcPort::Module(name) = &channel.local.port {
            self.load_application(name)?
                .borrow()
                .handle_outgoing_packet(
                    api,
                    block,
                    sender,
                    &RouterWrapper::new(&router_closure!(router, api, rc_storage, block)),
                    rc_storage.clone(),
                    msg.clone(),
                    channel,
                )
        } else {
            emit_packet_boxed(msg.into_packet(&sender, &channel)?, &rc_storage)?;
            Ok(AppResponse::default())
        }
    }

    fn query(
        &self,
        _api: &dyn Api,
        _storage: &dyn Storage,
        _querier: &dyn Querier,
        _block: &BlockInfo,
        _request: Self::QueryT,
    ) -> AppResult<Binary> {
        todo!()
    }

    fn sudo<ExecC, QueryC>(
        &self,
        _api: &dyn Api,
        _storage: &mut dyn Storage,
        _router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
        _block: &BlockInfo,
        _msg: Self::SudoT,
    ) -> AppResult<AppResponse>
    where
        ExecC: CustomMsg + DeserializeOwned + 'static,
        QueryC: CustomQuery + DeserializeOwned + 'static,
    {
        todo!()
    }
}

impl Ibc for IperIbcModule {}

#[cw_serde]
pub enum IbcPacketType {
    AckPacket(AckPacket),
    OutgoingPacket(OutgoingPacket),
    OutgoinPacketRaw(OutgoingPacketRaw),
    CloseChannel { channel_id: String },
    Timeout(TimeoutPacket),
}

impl IbcPacketType {
    pub fn get_channel_to_deliver(&self) -> AppResult<String> {
        match self {
            IbcPacketType::AckPacket(packet) => Ok(packet.get_src_channel()),
            IbcPacketType::OutgoingPacket(packet) => Ok(packet.get_dest_channel()),
            IbcPacketType::CloseChannel { .. } => {
                bail!("Unexpected error: Channel to deliver can't set for CloseChannel")
            }
            IbcPacketType::OutgoinPacketRaw(..) => {
                bail!("Unexpected error: Channel to deliver can't set for CloseChannel")
            }
            IbcPacketType::Timeout(packet) => {
                Ok(packet.original_packet.packet.src.channel_id.clone())
            }
        }
    }

    pub fn get_local_channel_id(&self) -> String {
        match self {
            IbcPacketType::AckPacket(packet) => {
                packet.original_packet.packet.dest.channel_id.clone()
            }
            IbcPacketType::OutgoingPacket(packet) => packet.src.channel_id.clone(),
            IbcPacketType::CloseChannel { channel_id } => channel_id.clone(),
            IbcPacketType::OutgoinPacketRaw(packet) => packet.src_channel.clone(),
            IbcPacketType::Timeout(packet) => packet.original_packet.packet.dest.channel_id.clone(),
        }
    }
}

#[cw_serde]
pub struct OutgoingPacket {
    pub data: Binary,
    pub src: IbcEndpoint,
    pub dest: IbcEndpoint,
    pub timeout: IbcTimeout,
}

#[cw_serde]
pub struct OutgoingPacketRaw {
    pub data: Binary,
    pub src_port: String,
    pub src_channel: String,
    pub timeout: IbcTimeout,
}

impl OutgoingPacketRaw {
    pub fn into_full_packet(self, channel: &IbcChannelWrapper) -> AppResult<OutgoingPacket> {
        Ok(OutgoingPacket {
            data: self.data,
            src: channel.local.as_endpoint()?,
            dest: channel.remote.as_endpoint()?,
            timeout: self.timeout,
        })
    }
}

#[cw_serde]
pub struct AckPacket {
    pub ack: Binary,
    pub original_packet: IbcPacketReceiveMsg,
    pub success: bool,
    pub relayer: Option<Addr>,
}

#[cw_serde]
pub struct TimeoutPacket {
    pub original_packet: IbcPacketReceiveMsg,
    pub relayer: Option<Addr>,
}

impl AckPacket {
    pub fn get_src_channel(&self) -> String {
        self.original_packet.packet.src.channel_id.clone()
    }

    pub fn into_msg(self, relayer: Addr) -> IbcPacketAckMsg {
        IbcPacketAckMsg::new(
            IbcAcknowledgement::new(self.ack),
            self.original_packet.packet,
            relayer,
        )
    }
}

#[cw_serde]
pub(crate) struct AckResponse {
    pub ack: Option<Binary>,
    pub success: bool,
}

impl OutgoingPacket {
    pub fn get_dest_channel(&self) -> String {
        self.dest.channel_id.clone()
    }

    pub fn get_src_channel(&self) -> String {
        self.src.channel_id.clone()
    }
}

pub(crate) fn emit_packet_boxed(
    packet: IbcPacketType,
    rc_storage: &Rc<RefCell<&mut dyn Storage>>,
) -> AppResult<()> {
    let mut packets = PENDING_PACKETS
        .load(*rc_storage.borrow())
        .unwrap_or_default();
    let new_key = packets.last_key_value().map(|(k, _)| *k).unwrap_or(0) + 1;
    packets.insert(new_key, packet);
    PENDING_PACKETS.save(*rc_storage.borrow_mut(), &packets)?;
    Ok(())
}

pub(crate) fn emit_packet(packet: IbcPacketType, storage: &mut dyn Storage) -> AppResult<()> {
    let mut packets = PENDING_PACKETS.load(storage).unwrap_or_default();
    let new_key = packets.last_key_value().map(|(k, _)| *k).unwrap_or(0) + 1;
    packets.insert(new_key, packet);
    PENDING_PACKETS.save(storage, &packets)?;
    Ok(())
}