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
use crate::error::Error::UnsupportedOperation;
use crate::error::{Error, Result};
use crate::model::{Address, Amount, AssetId, ByteString, Function, StateChanges};
use crate::util::JsonDeserializer;
use serde_json::Value;
use std::borrow::Borrow;
use std::fmt;

const TYPE: u8 = 18;

#[derive(Clone, Eq, PartialEq, Debug)]
pub struct EthereumTransactionInfo {
    bytes: HexString,
    payload: Payload,
}

impl EthereumTransactionInfo {
    pub fn new(bytes: HexString, payload: Payload) -> Self {
        Self { bytes, payload }
    }

    pub fn bytes(&self) -> HexString {
        self.bytes.clone()
    }

    pub fn payload(&self) -> Payload {
        self.payload.clone()
    }

    pub fn tx_type() -> u8 {
        TYPE
    }
}

impl TryFrom<&Value> for EthereumTransactionInfo {
    type Error = Error;

    fn try_from(value: &Value) -> Result<Self> {
        let payload = value["payload"].borrow().try_into()?;
        let bytes = HexString::new(hex::decode(
            &JsonDeserializer::safe_to_string_from_field(value, "bytes")?[2..],
        )?);
        Ok(EthereumTransactionInfo { bytes, payload })
    }
}

#[derive(Clone, Eq, PartialEq, Debug)]
pub struct EthereumTransaction {
    bytes: HexString,
}

impl EthereumTransaction {
    pub fn new(bytes: HexString) -> Self {
        Self { bytes }
    }

    pub fn bytes(&self) -> HexString {
        self.bytes.clone()
    }

    pub fn tx_type() -> u8 {
        TYPE
    }
}

impl TryFrom<&Value> for EthereumTransaction {
    type Error = Error;

    fn try_from(value: &Value) -> Result<Self> {
        let bytes = HexString::new(hex::decode(
            &JsonDeserializer::safe_to_string_from_field(value, "bytes")?[2..],
        )?);
        Ok(EthereumTransaction { bytes })
    }
}

#[derive(Clone, Eq, PartialEq, Debug)]
//todo fix it
#[allow(clippy::large_enum_variant)]
pub enum Payload {
    Invoke(InvokePayload),
    Transfer(TransferPayload),
}

impl TryFrom<&Value> for Payload {
    type Error = Error;

    fn try_from(value: &Value) -> Result<Self> {
        match JsonDeserializer::safe_to_string_from_field(value, "type")?.as_str() {
            "invocation" => {
                let invoke: InvokePayload = value.try_into()?;
                Ok(Payload::Invoke(invoke))
            }
            "transfer" => {
                let transfer: TransferPayload = value.try_into()?;
                Ok(Payload::Transfer(transfer))
            }
            _ => Err(UnsupportedOperation("unknown payload type".to_owned())),
        }
    }
}

#[derive(Clone, Eq, PartialEq, Debug)]
pub struct TransferPayload {
    recipient: Address,
    amount: Amount,
}

impl TransferPayload {
    pub fn new(recipient: Address, amount: Amount) -> Self {
        Self { recipient, amount }
    }

    pub fn recipient(&self) -> Address {
        self.recipient.clone()
    }

    pub fn amount(&self) -> Amount {
        self.amount.clone()
    }
}

impl TryFrom<&Value> for TransferPayload {
    type Error = Error;

    fn try_from(value: &Value) -> Result<Self> {
        let recipient = JsonDeserializer::safe_to_string_from_field(value, "recipient")?;
        let asset = match value["asset"].as_str() {
            Some(asset_id) => Some(AssetId::from_string(asset_id)?),
            None => None,
        };
        let amount = JsonDeserializer::safe_to_int_from_field(value, "amount")?;

        Ok(TransferPayload {
            recipient: Address::from_string(&recipient)?,
            amount: Amount::new(amount as u64, asset),
        })
    }
}

#[derive(Clone, Eq, PartialEq, Debug)]
pub struct InvokePayload {
    dapp: Address,
    function: Function,
    payments: Vec<Amount>,
    state_changes: StateChanges,
}

impl InvokePayload {
    pub fn new(
        dapp: Address,
        function: Function,
        payments: Vec<Amount>,
        state_changes: StateChanges,
    ) -> Self {
        Self {
            dapp,
            function,
            payments,
            state_changes,
        }
    }

    pub fn dapp(&self) -> Address {
        self.dapp.clone()
    }

    pub fn function(&self) -> Function {
        self.function.clone()
    }

    pub fn payments(&self) -> Vec<Amount> {
        self.payments.clone()
    }

    pub fn state_changes(&self) -> StateChanges {
        self.state_changes.clone()
    }
}

impl TryFrom<&Value> for InvokePayload {
    type Error = Error;

    fn try_from(value: &Value) -> Result<Self> {
        let dapp = JsonDeserializer::safe_to_string_from_field(value, "dApp")?;
        let function: Function = value.try_into()?;
        let payments = map_payment(value)?;
        let state_changes: StateChanges = value["stateChanges"].borrow().try_into()?;

        Ok(InvokePayload {
            dapp: Address::from_string(&dapp)?,
            function,
            payments,
            state_changes,
        })
    }
}

#[derive(Clone, Eq, PartialEq, Hash)]
pub struct HexString {
    bytes: Vec<u8>,
}

impl fmt::Debug for HexString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "HexString {{ {} }}", self.encoded())
    }
}

impl HexString {
    pub fn new(bytes: Vec<u8>) -> Self {
        Self { bytes }
    }

    pub fn encoded(&self) -> String {
        hex::encode(self.bytes.clone())
    }

    pub fn bytes(&self) -> Vec<u8> {
        self.bytes.clone()
    }
}

impl ByteString for HexString {
    fn bytes(&self) -> Vec<u8> {
        self.bytes.clone()
    }

    fn encoded(&self) -> String {
        hex::encode(self.bytes.clone())
    }

    fn encoded_with_prefix(&self) -> String {
        format!("0x{}", self.encoded())
    }
}

//todo rm duplicate
fn map_payment(value: &Value) -> Result<Vec<Amount>> {
    JsonDeserializer::safe_to_array_from_field(value, "payment")?
        .iter()
        .map(|payment| {
            let value = JsonDeserializer::safe_to_int_from_field(payment, "amount")?;
            let asset_id = match payment["assetId"].as_str() {
                Some(asset) => Some(AssetId::from_string(asset)?),
                None => None,
            };
            Ok(Amount::new(value as u64, asset_id))
        })
        .collect::<Result<Vec<Amount>>>()
}

#[cfg(test)]
mod tests {
    use crate::model::data_entry::DataEntry;
    use crate::model::{Arg, ByteString, EthereumTransactionInfo, Payload};
    use serde_json::Value;
    use std::borrow::Borrow;
    use std::fs;

    const INVOKE_BYTES: &str = "0xf9011186017cac99be168502540be4008307a120940ea8e14f313237aac31995f9c19a7e0f78c1cc2b80b8a409abf90e00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000e74657374206d6574616d61736b32000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000081c9a0dcc682194d46cd3a763b352ca77a4317e9d89f10e5213379b55563cbc03619f3a02a2f26c580ab9f3d83db801bf7d556dd50d37cd69b19df8ee4a3488a6c5140c8";

    #[test]
    fn test_json_to_eth_invoke_transaction() {
        let data = fs::read_to_string("./tests/resources/ethereum_transaction_invoke_rs.json")
            .expect("Unable to read file");
        let json: Value = serde_json::from_str(&data).expect("failed to generate json from str");

        let eth_invoke_from_json: EthereumTransactionInfo = json.borrow().try_into().unwrap();

        assert_eq!(
            INVOKE_BYTES[2..],
            hex::encode(eth_invoke_from_json.bytes().bytes())
        );

        let invoke = match eth_invoke_from_json.payload() {
            Payload::Invoke(invoke) => invoke,
            Payload::Transfer(_) => panic!("expected invoke but was transfer"),
        };

        assert_eq!(
            "3MRuzZVauiiX2DGwNyP8Tv7idDGUy1VG5bJ",
            invoke.dapp().encoded()
        );
        assert_eq!("saveString", invoke.function().name());

        match &invoke.function().args()[0] {
            Arg::String(value) => {
                assert_eq!("test metamask2", value)
            }
            _ => panic!("expected string arg"),
        }

        assert_eq!(1, invoke.payments().len());
        let payment = &invoke.payments()[0];
        assert_eq!(26434954086, payment.value());
        assert_eq!(
            "97zHFp1C3cB7qfvx8Xv5f2rWp9nUSG5UnAamfPcW6txf",
            payment.asset_id().expect("should not be empty").encoded()
        );

        match &invoke.state_changes().data()[0] {
            DataEntry::StringEntry { key, value } => {
                assert_eq!("str_1043725", key);
                assert_eq!("test metamask2", value);
            }
            _ => panic!("expected string entry"),
        }
    }

    #[test]
    fn test_json_to_eth_transfer_transaction() {
        let data = fs::read_to_string("./tests/resources/ethereum_transaction_transfer_rs.json")
            .expect("Unable to read file");
        let json: Value = serde_json::from_str(&data).expect("failed to generate json from str");

        let eth_invoke_from_json: EthereumTransactionInfo = json.borrow().try_into().unwrap();

        let transfer = match eth_invoke_from_json.payload() {
            Payload::Transfer(transfer) => transfer,
            Payload::Invoke(_) => panic!("expected transfer but was invoke"),
        };

        assert_eq!(
            "3MVeY7NhZciZLsnwb4E47moXVd9y4gKw8S7",
            transfer.recipient().encoded()
        );
        assert_eq!(10000000, transfer.amount().value());
        assert_eq!(None, transfer.amount().asset_id());
    }
}