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
use crate::erc20::Erc20Token;
use alloy::primitives::{Address, AddressError, U256};
use alloy_sol_types::SolValue;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{HexBinary, Uint128};

/// Marks either `String` or valid EVM `Address`.
///
/// String is used in unverified types, such as messages and query responses.
/// Addr is used in verified types, which are to be stored in blockchain state.
///
/// This trait is intended to be used as a generic in type definitions.
pub trait EvmAddressLike {}

impl EvmAddressLike for String {}

impl EvmAddressLike for HexBinary {}

impl EvmAddressLike for Address {}

/// A message to be sent to the EVM
#[cw_serde]
#[non_exhaustive]
pub enum EvmMsg<T: EvmAddressLike> {
    /// Call a contract with the given data
    Call {
        /// The address of the contract to call, must pass checksum validation
        to: T,
        /// The calldata to send to the contract
        data: HexBinary,
        /// Native ETH used in the tx
        #[serde(skip_serializing_if = "Option::is_none")]
        value: Option<Uint128>,
        /// Don't revert entire batch when this transaction fails
        #[serde(skip_serializing_if = "Option::is_none")]
        allow_failure: Option<bool>,
    },
    /// Delegate a call to an external contract. This is dangerous and should be used with caution.
    DelegateCall {
        /// The address of the contract to call, must pass checksum validation
        to: T,
        /// The calldata to send to the contract
        data: HexBinary,
        /// Native ETH used in the tx
        #[serde(skip_serializing_if = "Option::is_none")]
        value: Option<Uint128>,
        /// Don't revert entire batch when this transaction fails
        #[serde(skip_serializing_if = "Option::is_none")]
        allow_failure: Option<bool>,
    },
}

impl<T> EvmMsg<T>
where
    T: EvmAddressLike,
{
    pub fn call(to: T, data: impl Into<HexBinary>) -> Self {
        EvmMsg::Call {
            to,
            data: data.into(),
            value: None,
            allow_failure: None,
        }
    }

    pub fn call_with_value(to: T, data: impl Into<HexBinary>, value: Uint128) -> Self {
        EvmMsg::Call {
            to,
            data: data.into(),
            value: Some(value),
            allow_failure: None,
        }
    }

    pub fn delegate_call(to: T, data: impl Into<HexBinary>) -> Self {
        EvmMsg::DelegateCall {
            to,
            data: data.into(),
            value: None,
            allow_failure: None,
        }
    }
}

impl EvmMsg<String> {
    /// Check the validity of the addresses
    pub fn check(self) -> Result<EvmMsg<Address>, AddressError> {
        match self {
            EvmMsg::Call {
                to,
                data,
                value,
                allow_failure,
            } => {
                let to: Address = Address::parse_checksummed(to, None)?;
                Ok(EvmMsg::Call {
                    to,
                    data,
                    value,
                    allow_failure,
                })
            }
            EvmMsg::DelegateCall {
                to,
                data,
                value,
                allow_failure,
            } => {
                let to: Address = Address::parse_checksummed(to, None)?;
                Ok(EvmMsg::DelegateCall {
                    to,
                    data,
                    value,
                    allow_failure,
                })
            }
        }
    }
}

impl EvmMsg<Address> {
    pub fn encode(self) -> Vec<u8> {
        match self {
            EvmMsg::Call {
                to,
                data,
                allow_failure,
                value,
            } => {
                let data = data.to_vec();
                let call = abi_types::CallMessage {
                    to,
                    data: data.to_vec().into(),
                    allowFailure: allow_failure.unwrap_or(false),
                    value: value.map(|v| U256::from(v.u128())).unwrap_or_default(),
                }
                .abi_encode();
                abi_types::EvmMsg {
                    msgType: abi_types::EvmMsgType::Call,
                    message: call.into(),
                }
                .abi_encode()
            }
            EvmMsg::DelegateCall {
                to,
                data,
                allow_failure,
                value,
            } => {
                let data = data.to_vec();
                let call = abi_types::CallMessage {
                    to,
                    data: data.to_vec().into(),
                    allowFailure: allow_failure.unwrap_or(false),
                    value: value.map(|v| U256::from(v.u128())).unwrap_or_default(),
                }
                .abi_encode();
                abi_types::EvmMsg {
                    msgType: abi_types::EvmMsgType::DelegateCall,
                    message: call.into(),
                }
                .abi_encode()
            }
        }
    }

    #[allow(dead_code)]
    fn unchecked(self) -> EvmMsg<String> {
        match self {
            EvmMsg::Call {
                to,
                data,
                allow_failure,
                value,
            } => EvmMsg::Call {
                to: to.to_string(),
                data,
                allow_failure,
                value,
            },
            EvmMsg::DelegateCall {
                to,
                data,
                allow_failure,
                value,
            } => EvmMsg::DelegateCall {
                to: to.to_string(),
                data,
                allow_failure,
                value,
            },
        }
    }
}

pub(crate) mod abi_types {
    use alloy_sol_types::sol;

    // Copied directly from solidity/src/Requests.sol
    sol! {
    // Reflect the CW Packet
    struct Packet {
        string sender;
        Msg msg;
    }

    // Message called on the voice
    struct Msg {
        MsgType msgType;
        // Requests on the voice (Exec / Query)
        bytes[] data;
    }

    // Type of voice message
    enum MsgType {
        Execute
    //    Query
    }

    // Message called on the proxy contract
    // Reflect EvmMsg<Address>
    struct EvmMsg {
        EvmMsgType msgType;
        bytes message;
    }

    // Type of message called on proxy contract
    enum EvmMsgType {
        Call,
        DelegateCall,
    }

    // Data to execute by proxy
    struct CallMessage {
        address to;
        bool allowFailure;
        uint256 value;
        bytes data;
    }


    struct ExecuteResult {
        bool success;
        bytes data;
    }

    struct ExecuteResponsePacket {
        address executedBy;
        ExecuteResult[] result;
    }


    struct Token {
        address denom;
        uint128 amount;
    }

    }
}

impl From<abi_types::Token> for Erc20Token<String> {
    fn from(token: abi_types::Token) -> Self {
        Erc20Token {
            address: token.denom.to_string(),
            amount: token.amount.into(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod call_message {
        use crate::ibc::{Msg, Packet};

        use super::*;

        #[test]
        fn unchecked_encoding() {
            let msg = abi_types::CallMessage {
                to: "0x785B548D3d7064F77A26e479AC7847DBCE0c1B46"
                    .parse()
                    .unwrap(),
                data: HexBinary::from_hex("b49004e9").unwrap().to_vec().into(),
                allowFailure: false,
                value: U256::from(0),
            };

            let encoded = msg.abi_encode();
            let actual = HexBinary::from(encoded);

            let expected = HexBinary::from_hex("0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000785b548d3d7064f77a26e479ac7847dbce0c1b460000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000004b49004e900000000000000000000000000000000000000000000000000000000").unwrap();

            assert_eq!(actual, expected);
        }

        #[test]
        fn checked_encoding() {
            let msg = EvmMsg::call(
                "0x785B548D3d7064F77A26e479AC7847DBCE0c1B46".to_string(),
                HexBinary::from_hex("b49004e9").unwrap(),
            )
            .check()
            .unwrap();

            let encoded = msg.encode();
            let actual = HexBinary::from(encoded);

            let expected = HexBinary::from_hex("0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000785b548d3d7064f77a26e479ac7847dbce0c1b460000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000004b49004e900000000000000000000000000000000000000000000000000000000").unwrap();

            assert_eq!(actual, expected);
        }

        const TEST_SENDER: &str =
            "union1tw2y3uk7fwcjeh208gdwaqd3utkuzmnp2fyvqve00jg8vtyhuhfqsender";

        #[test]
        fn packet_encoding() {
            let evm_msg = EvmMsg::call(
                "0x785B548D3d7064F77A26e479AC7847DBCE0c1B46".to_string(),
                HexBinary::from_hex("b49004e9").unwrap(),
            );

            let msg = Msg::Execute {
                msgs: vec![evm_msg],
            };
            let request: Packet = Packet {
                msg,
                sender: TEST_SENDER.to_string(),
            };
            let encoded = request.encode().unwrap();
            let actual = HexBinary::from(encoded);

            let expected = HexBinary::from_hex("0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000040756e696f6e317477327933756b376677636a65683230386764776171643375746b757a6d6e703266797671766530306a6738767479687568667173656e6465720000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000785b548d3d7064f77a26e479ac7847dbce0c1b460000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000004b49004e900000000000000000000000000000000000000000000000000000000").unwrap();

            assert_eq!(actual, expected);
        }
    }

    #[test]
    fn test_address() {
        EvmMsg::call(
            "0x785B548D3d7064F77A26e479AC7847DBCE0c1B46".to_string(),
            HexBinary::from_hex("b49004e9").unwrap(),
        );
    }
}