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
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of OpenEthereum.

// OpenEthereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// OpenEthereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with OpenEthereum.  If not, see <http://www.gnu.org/licenses/>.

//! `TransactionRequest` type

use ansi_term::Colour;
use ethereum_types::{H160, U256, U64};
use v1::{
    helpers,
    types::{AccessList, Bytes, TransactionCondition},
};

use std::fmt;

/// Transaction request coming from RPC
#[derive(Debug, Clone, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
#[serde(rename_all = "camelCase")]
pub struct TransactionRequest {
    /// type of transaction. Defaults to legacy type.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub transaction_type: Option<U64>,
    /// Sender
    pub from: Option<H160>,
    /// Recipient
    pub to: Option<H160>,
    /// Gas Price
    #[serde(skip_serializing_if = "Option::is_none")]
    pub gas_price: Option<U256>,
    /// Max fee per gas
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_fee_per_gas: Option<U256>,
    /// Gas
    pub gas: Option<U256>,
    /// Value of transaction in wei
    pub value: Option<U256>,
    /// Additional data sent with transaction
    pub data: Option<Bytes>,
    /// Transaction's nonce
    pub nonce: Option<U256>,
    /// Delay until this block condition.
    pub condition: Option<TransactionCondition>,
    /// Access list
    #[serde(skip_serializing_if = "Option::is_none")]
    pub access_list: Option<AccessList>,
    /// Miner bribe
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_priority_fee_per_gas: Option<U256>,
}

pub fn format_ether(i: U256) -> String {
    let mut string = format!("{}", i);
    let idx = string.len() as isize - 18;
    if idx <= 0 {
        let mut prefix = String::from("0.");
        for _ in 0..idx.abs() {
            prefix.push('0');
        }
        string = prefix + &string;
    } else {
        string.insert(idx as usize, '.');
    }
    String::from(string.trim_end_matches('0').trim_end_matches('.'))
}

impl fmt::Display for TransactionRequest {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let eth = self.value.unwrap_or_default();
        match self.to {
            Some(ref to) => write!(
                f,
                "{} ETH from {} to 0x{:?}",
                Colour::White.bold().paint(format_ether(eth)),
                Colour::White.bold().paint(
                    self.from
                        .as_ref()
                        .map(|f| format!("0x{:?}", f))
                        .unwrap_or_else(|| "?".to_string())
                ),
                to
            ),
            None => write!(
                f,
                "{} ETH from {} for contract creation",
                Colour::White.bold().paint(format_ether(eth)),
                Colour::White.bold().paint(
                    self.from
                        .as_ref()
                        .map(|f| format!("0x{:?}", f))
                        .unwrap_or_else(|| "?".to_string())
                ),
            ),
        }
    }
}

impl From<helpers::TransactionRequest> for TransactionRequest {
    fn from(r: helpers::TransactionRequest) -> Self {
        TransactionRequest {
            transaction_type: r.transaction_type,
            from: r.from.map(Into::into),
            to: r.to.map(Into::into),
            gas_price: r.gas_price.map(Into::into),
            max_fee_per_gas: r.max_fee_per_gas,
            gas: r.gas.map(Into::into),
            value: r.value.map(Into::into),
            data: r.data.map(Into::into),
            nonce: r.nonce.map(Into::into),
            condition: r.condition.map(Into::into),
            access_list: r.access_list.map(Into::into),
            max_priority_fee_per_gas: r.max_priority_fee_per_gas.map(Into::into),
        }
    }
}

impl From<helpers::FilledTransactionRequest> for TransactionRequest {
    fn from(r: helpers::FilledTransactionRequest) -> Self {
        TransactionRequest {
            transaction_type: r.transaction_type,
            from: Some(r.from),
            to: r.to,
            gas_price: r.gas_price,
            max_fee_per_gas: r.max_fee_per_gas,
            gas: Some(r.gas),
            value: Some(r.value),
            data: Some(r.data.into()),
            nonce: r.nonce,
            condition: r.condition,
            access_list: r.access_list.map(Into::into),
            max_priority_fee_per_gas: r.max_priority_fee_per_gas,
        }
    }
}

impl Into<helpers::TransactionRequest> for TransactionRequest {
    fn into(self) -> helpers::TransactionRequest {
        helpers::TransactionRequest {
            transaction_type: self.transaction_type,
            from: self.from.map(Into::into),
            to: self.to.map(Into::into),
            gas_price: self.gas_price.map(Into::into),
            max_fee_per_gas: self.max_fee_per_gas,
            gas: self.gas.map(Into::into),
            value: self.value.map(Into::into),
            data: self.data.map(Into::into),
            nonce: self.nonce.map(Into::into),
            condition: self.condition.map(Into::into),
            access_list: self.access_list.map(Into::into),
            max_priority_fee_per_gas: self.max_priority_fee_per_gas.map(Into::into),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ethereum_types::{H160, U256};
    use rustc_hex::FromHex;
    use serde_json;
    use std::str::FromStr;
    use v1::types::TransactionCondition;

    #[test]
    fn transaction_request_deserialize() {
        let s = r#"{
			"from":"0x0000000000000000000000000000000000000001",
			"to":"0x0000000000000000000000000000000000000002",
			"gasPrice":"0x1",
			"gas":"0x2",
			"value":"0x3",
			"data":"0x123456",
			"nonce":"0x4",
			"condition": { "block": 19 }
		}"#;
        let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();

        assert_eq!(
            deserialized,
            TransactionRequest {
                transaction_type: Default::default(),
                from: Some(H160::from_low_u64_be(1)),
                to: Some(H160::from_low_u64_be(2)),
                gas_price: Some(U256::from(1)),
                max_fee_per_gas: None,
                gas: Some(U256::from(2)),
                value: Some(U256::from(3)),
                data: Some(vec![0x12, 0x34, 0x56].into()),
                nonce: Some(U256::from(4)),
                condition: Some(TransactionCondition::Number(0x13)),
                access_list: None,
                max_priority_fee_per_gas: None,
            }
        );
    }

    #[test]
    fn transaction_request_deserialize_1559() {
        let s = r#"{
            "type":"0x02",
			"from":"0x0000000000000000000000000000000000000001",
			"to":"0x0000000000000000000000000000000000000002",
			"maxFeePerGas":"0x01",
			"maxPriorityFeePerGas":"0x01",
			"gas":"0x2",
			"value":"0x3",
			"data":"0x123456",
			"nonce":"0x4",
			"condition": { "block": 19 }
		}"#;
        let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();

        assert_eq!(
            deserialized,
            TransactionRequest {
                transaction_type: Some(U64::from(2)),
                from: Some(H160::from_low_u64_be(1)),
                to: Some(H160::from_low_u64_be(2)),
                gas_price: None,
                max_fee_per_gas: Some(U256::from(1)),
                gas: Some(U256::from(2)),
                value: Some(U256::from(3)),
                data: Some(vec![0x12, 0x34, 0x56].into()),
                nonce: Some(U256::from(4)),
                condition: Some(TransactionCondition::Number(0x13)),
                access_list: None,
                max_priority_fee_per_gas: Some(U256::from(1)),
            }
        );
    }

    #[test]
    fn transaction_request_deserialize2() {
        let s = r#"{
			"from": "0xb60e8dd61c5d32be8058bb8eb970870f07233155",
			"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
			"gas": "0x76c0",
			"gasPrice": "0x9184e72a000",
			"value": "0x9184e72a",
			"data": "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"
		}"#;
        let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();

        assert_eq!(deserialized, TransactionRequest {
            transaction_type: Default::default(),
			from: Some(H160::from_str("b60e8dd61c5d32be8058bb8eb970870f07233155").unwrap()),
			to: Some(H160::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
			gas_price: Some(U256::from_str("9184e72a000").unwrap()),
			max_fee_per_gas: None,
			gas: Some(U256::from_str("76c0").unwrap()),
			value: Some(U256::from_str("9184e72a").unwrap()),
			data: Some("d46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675".from_hex().unwrap().into()),
			nonce: None,
			condition: None,
			access_list: None,
			max_priority_fee_per_gas: None,
		});
    }

    #[test]
    fn transaction_request_deserialize_empty() {
        let s = r#"{"from":"0x0000000000000000000000000000000000000001"}"#;
        let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();

        assert_eq!(
            deserialized,
            TransactionRequest {
                transaction_type: Default::default(),
                from: Some(H160::from_low_u64_be(1).into()),
                to: None,
                gas_price: None,
                max_fee_per_gas: None,
                gas: None,
                value: None,
                data: None,
                nonce: None,
                condition: None,
                access_list: None,
                max_priority_fee_per_gas: None,
            }
        );
    }

    #[test]
    fn transaction_request_deserialize_test() {
        let s = r#"{
			"from":"0xb5f7502a2807cb23615c7456055e1d65b2508625",
			"to":"0x895d32f2db7d01ebb50053f9e48aacf26584fe40",
			"data":"0x8595bab1",
			"gas":"0x2fd618",
			"gasPrice":"0x0ba43b7400"
		}"#;

        let deserialized: TransactionRequest = serde_json::from_str(s).unwrap();

        assert_eq!(
            deserialized,
            TransactionRequest {
                transaction_type: Default::default(),
                from: Some(H160::from_str("b5f7502a2807cb23615c7456055e1d65b2508625").unwrap()),
                to: Some(H160::from_str("895d32f2db7d01ebb50053f9e48aacf26584fe40").unwrap()),
                gas_price: Some(U256::from_str("0ba43b7400").unwrap()),
                max_fee_per_gas: None,
                gas: Some(U256::from_str("2fd618").unwrap()),
                value: None,
                data: Some(vec![0x85, 0x95, 0xba, 0xb1].into()),
                nonce: None,
                condition: None,
                access_list: None,
                max_priority_fee_per_gas: None,
            }
        );
    }

    #[test]
    fn transaction_request_deserialize_error() {
        let s = r#"{
			"from":"0xb5f7502a2807cb23615c7456055e1d65b2508625",
			"to":"",
			"data":"0x8595bab1",
			"gas":"0x2fd618",
			"gasPrice":"0x0ba43b7400"
		}"#;

        let deserialized = serde_json::from_str::<TransactionRequest>(s);

        assert!(deserialized.is_err(), "Should be error because to is empty");
    }

    #[test]
    fn test_format_ether() {
        assert_eq!(&format_ether(U256::from(1000000000000000000u64)), "1");
        assert_eq!(&format_ether(U256::from(500000000000000000u64)), "0.5");
        assert_eq!(&format_ether(U256::from(50000000000000000u64)), "0.05");
        assert_eq!(&format_ether(U256::from(5000000000000000u64)), "0.005");
        assert_eq!(&format_ether(U256::from(2000000000000000000u64)), "2");
        assert_eq!(&format_ether(U256::from(2500000000000000000u64)), "2.5");
        assert_eq!(&format_ether(U256::from(10000000000000000000u64)), "10");
    }
}