blockchain/
transaction.rs

1use chrono::Utc;
2use serde::{Deserialize, Serialize};
3use uuid::Uuid;
4
5use crate::Chain;
6
7/// Exchange of assets between two parties.
8#[derive(Clone, Debug, Serialize, Deserialize)]
9pub struct Transaction {
10    /// Identifier of the transaction.
11    pub id: Uuid,
12
13    /// Transaction hash.
14    pub hash: String,
15
16    /// Transaction sender wallet address.
17    pub from: String,
18
19    /// Transaction receiver wallet address.
20    pub to: String,
21
22    /// Transaction fee.
23    pub fee: f64,
24
25    /// Transaction amount.
26    pub amount: f64,
27
28    /// Transaction timestamp.
29    pub timestamp: i64,
30}
31
32impl Transaction {
33    /// Create a new transaction.
34    ///
35    /// # Arguments
36    ///
37    /// - `from`: The transaction sender address.
38    /// - `to`: The transaction receiver address.
39    /// - `fee`: The transaction fee.
40    /// - `amount`: The transaction amount.
41    ///
42    /// # Returns
43    ///
44    /// A new transaction with the given hash, sender, receiver, fee, amount, and timestamp.
45    pub fn new(from: String, to: String, fee: f64, amount: f64) -> Self {
46        let timestamp = Utc::now().timestamp();
47
48        // Create a hash of the transaction
49        let hash = Chain::hash(&(&from, &to, amount, timestamp));
50
51        // Create a new transaction
52        Transaction {
53            id: Uuid::new_v4(),
54            hash,
55            from,
56            to,
57            fee,
58            amount,
59            timestamp,
60        }
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn test_new_transaction() {
70        let from = "0x 1234".to_string();
71        let to = "0x 5678".to_string();
72        let fee = 0.1;
73        let amount = 100.0;
74        let transaction = Transaction::new(from.to_owned(), to.to_owned(), fee, amount);
75
76        assert_eq!(transaction.from, from);
77        assert_eq!(transaction.to, to);
78        assert_eq!(transaction.fee, fee);
79        assert_eq!(transaction.amount, amount);
80    }
81}