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

use anyhow::{anyhow, bail};
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{
    to_json_binary, Addr, IbcChannel, IbcEndpoint, IbcMsg, IbcOrder, IbcTimeout, IbcTimeoutBlock,
    Timestamp,
};
use ibc_proto::ibc::{apps::transfer::v2::FungibleTokenPacketData, core::client::v1::Height};

use crate::{
    error::AppResult,
    ibc_module::{IbcPacketType, OutgoingPacket},
    IbcApplication,
};

#[derive(Clone)]
#[non_exhaustive]
pub struct IbcChannelWrapper {
    pub local: IbcChannelCreator,
    pub remote: IbcChannelCreator,
    pub status: IbcChannelStatus,
    pub sequence: Rc<RefCell<u64>>,
}

impl IbcChannelWrapper {
    pub fn new(
        local: IbcChannelCreator,
        remote: IbcChannelCreator,
        sequence: Rc<RefCell<u64>>,
    ) -> Self {
        Self {
            local,
            remote,
            status: IbcChannelStatus::Created,
            sequence,
        }
    }
}

#[derive(Default, Clone)]
pub struct Channels {
    channels: BTreeMap<u64, IbcChannelWrapper>,
}

impl Channels {
    pub fn get(&self, id: impl Channelable) -> AppResult<&IbcChannelWrapper> {
        self.channels
            .get(&id.as_channel_number()?)
            .ok_or(anyhow!("channel not found"))
    }

    pub fn get_mut(&mut self, id: impl Channelable) -> AppResult<&mut IbcChannelWrapper> {
        self.channels
            .get_mut(&id.as_channel_number()?)
            .ok_or(anyhow!("channel not found"))
    }

    pub fn next_key(&self) -> u64 {
        self.channels
            .last_key_value()
            .map(|(k, _)| k + 1)
            .unwrap_or(0)
    }

    pub fn insert(&mut self, key: impl Channelable, channel: IbcChannelWrapper) -> AppResult<()> {
        let key = key.as_channel_number()?;
        self.channels.insert(key, channel);
        Ok(())
    }
}

pub trait Channelable {
    fn as_channel_string(&self) -> String;
    fn as_channel_number(&self) -> AppResult<u64>;
}

impl Channelable for u64 {
    fn as_channel_string(&self) -> String {
        format!("channel-{}", self)
    }

    fn as_channel_number(&self) -> AppResult<u64> {
        Ok(*self)
    }
}

impl Channelable for String {
    fn as_channel_string(&self) -> String {
        self.clone()
    }

    fn as_channel_number(&self) -> AppResult<u64> {
        self.strip_prefix("channel-")
            .ok_or(anyhow!("invalid `channel-id`"))
            .and_then(|s| {
                s.parse::<u64>()
                    .map_err(|_| anyhow!("invalid `channel-id`"))
            })
    }
}

impl Channelable for &str {
    fn as_channel_string(&self) -> String {
        self.to_string()
    }

    fn as_channel_number(&self) -> AppResult<u64> {
        self.strip_prefix("channel-")
            .ok_or(anyhow!("invalid `channel-id`"))
            .and_then(|s| {
                s.parse::<u64>()
                    .map_err(|_| anyhow!("invalid `channel-id`"))
            })
    }
}

#[cw_serde]
pub enum IbcChannelStatus {
    Created,
    Opening,
    Connected,
    Closed,
}

impl IbcChannelStatus {
    #[allow(clippy::wrong_self_convention)]
    pub fn to_next_status(&mut self) -> AppResult<()> {
        match self {
            IbcChannelStatus::Created => *self = IbcChannelStatus::Opening,
            IbcChannelStatus::Opening => *self = IbcChannelStatus::Connected,
            _ => bail!("invalid status for next: {:?}", self),
        }

        Ok(())
    }
}

/// Define the `port` type of a ibc-channel
#[cw_serde]
pub enum IbcPort {
    /// `smart-contract` port address. The contract has to implement the `ibc entry_points`.
    Contract(Addr),
    /// [`IbcApplication`](crate::ibc_application::IbcApplication) port name.
    Module(String),
}

impl IbcPort {
    pub(crate) fn port_name(&self) -> String {
        match self {
            IbcPort::Contract(addr) => addr.to_string(),
            IbcPort::Module(name) => name.clone(),
        }
    }

    /// Create a a [`IbcPort`] from [`IbcApplication`]
    pub fn from_application(ibc_application: impl IbcApplication) -> Self {
        Self::Module(ibc_application.port_name())
    }
}

///
#[cw_serde]
#[non_exhaustive]
pub struct IbcChannelCreator {
    /// Channel `port`
    pub port: IbcPort,
    /// Channel packet `order`
    pub order: IbcOrder,
    /// Channel packet `version`
    pub version: String,
    /// Channel `connection_id`
    pub connection_id: String,
    /// Chain name. This value has to be equal to [`IperApp::chain_id`](crate::iper_app::IperApp)
    pub chain_id: String,
    channel_id: Option<u64>,
}

impl IbcChannelCreator {
    /// Constructor function
    pub fn new(
        port: IbcPort,
        order: IbcOrder,
        version: impl Into<String>,
        connection_id: impl Into<String>,
        chain_id: impl Into<String>,
    ) -> Self {
        Self {
            port,
            order,
            version: version.into(),
            connection_id: connection_id.into(),
            chain_id: chain_id.into(),
            channel_id: None,
        }
    }

    pub(crate) fn channel_id(&self) -> AppResult<u64> {
        self.channel_id.ok_or(anyhow!("channel-id not set"))
    }

    pub(crate) fn set_channel_id(&mut self, channe_id: u64) {
        self.channel_id = Some(channe_id);
    }

    pub(crate) fn as_endpoint(&self) -> AppResult<IbcEndpoint> {
        Ok(IbcEndpoint {
            port_id: self.port.port_name(),
            channel_id: self
                .channel_id
                .ok_or(anyhow!("channel-id not set"))?
                .as_channel_string(),
        })
    }
}

pub trait IbcChannelExt {
    fn new_from_creators(
        local: &IbcChannelCreator,
        remote: &IbcChannelCreator,
    ) -> AppResult<IbcChannel>;
}

impl IbcChannelExt for IbcChannel {
    fn new_from_creators(
        local: &IbcChannelCreator,
        remote: &IbcChannelCreator,
    ) -> AppResult<IbcChannel> {
        Ok(IbcChannel::new(
            local.as_endpoint()?,
            remote.as_endpoint()?,
            local.order.clone(),
            local.version.clone(),
            local.connection_id.clone(),
        ))
    }
}

pub trait IbcMsgExt {
    fn get_src_channel(&self) -> String;
    fn into_packet(
        self,
        sender: &Addr,
        channel_wrapper: &IbcChannelWrapper,
    ) -> AppResult<IbcPacketType>;
}

impl IbcMsgExt for IbcMsg {
    fn get_src_channel(&self) -> String {
        match self {
            IbcMsg::Transfer { channel_id, .. } => channel_id.clone(),
            IbcMsg::SendPacket { channel_id, .. } => channel_id.clone(),
            IbcMsg::CloseChannel { channel_id } => channel_id.clone(),
            _ => todo!(),
        }
    }

    fn into_packet(
        self,
        sender: &Addr,
        channel_wrapper: &IbcChannelWrapper,
    ) -> AppResult<IbcPacketType> {
        let src = channel_wrapper.local.as_endpoint()?;
        let dest = channel_wrapper.remote.as_endpoint()?;

        match self {
            IbcMsg::Transfer {
                to_address,
                amount,
                timeout,
                memo,
                ..
            } => Ok(IbcPacketType::OutgoingPacket(OutgoingPacket {
                data: to_json_binary(&FungibleTokenPacketData {
                    denom: amount.denom,
                    amount: amount.amount.to_string(),
                    sender: sender.to_string(),
                    receiver: to_address,
                    memo: memo.unwrap_or_default(),
                })?,
                src,
                dest,
                timeout,
            })),
            IbcMsg::SendPacket { data, timeout, .. } => {
                Ok(IbcPacketType::OutgoingPacket(OutgoingPacket {
                    data,
                    src,
                    dest,
                    timeout,
                }))
            }
            IbcMsg::CloseChannel { channel_id } => Ok(IbcPacketType::CloseChannel { channel_id }),
            _ => unimplemented!(),
        }
    }
}

pub fn create_ibc_timeout(nanos: u64, height: Option<Height>) -> IbcTimeout {
    match (nanos, height) {
        (0, None) => unimplemented!(),
        (0, Some(height)) => IbcTimeout::with_block(IbcTimeoutBlock {
            revision: height.revision_number,
            height: height.revision_height,
        }),
        (seconds, None) => IbcTimeout::with_timestamp(Timestamp::from_nanos(seconds)),

        (seconds, Some(height)) => IbcTimeout::with_both(
            IbcTimeoutBlock {
                revision: height.revision_number,
                height: height.revision_height,
            },
            Timestamp::from_nanos(seconds),
        ),
    }
}