1use serde::{Deserialize, Serialize};
7use std::collections::VecDeque;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct Wallet {
16 pub address: String,
17 pub private_key: String,
18 pub public_key: String,
19 pub balance: f64,
20 pub transaction_history: VecDeque<Transaction>,
21 pub pending_transactions: VecDeque<Transaction>, }
23
24#[derive(Debug, Clone, Serialize, Deserialize)]
30pub struct Transaction {
31 pub tx_id: String,
32 pub sender: String,
33 pub receiver: String,
34 pub amount: f64,
35 pub fee: f64, pub timestamp: u64,
37}
38
39impl Wallet {
43 pub fn new(address: String, private_key: String, public_key: String) -> Self {
44 Wallet {
45 address,
46 private_key,
47 public_key,
48 balance: 0.0,
49 transaction_history: VecDeque::new(),
50 pending_transactions: VecDeque::new(),
51 }
52 }
53
54 pub fn add_pending_transaction(&mut self, tx: Transaction) {
58 self.pending_transactions.push_back(tx);
59 }
60
61 pub fn add_transaction(&mut self, tx: Transaction) {
65 self.transaction_history.push_back(tx);
66 }
67
68 pub fn update_balance(&mut self, amount: f64) {
72 self.balance += amount;
73 }
74
75 pub fn get_balance(&self) -> f64 {
79 self.balance
80 }
81
82 pub fn get_pending_transaction_history(&self) -> &VecDeque<Transaction> {
86 &self.pending_transactions
87 }
88
89 pub fn get_transaction_history(&self) -> &VecDeque<Transaction> {
93 &self.transaction_history
94 }
95
96 pub fn transfer_txn(&mut self, tx_id: String) {
100 let mut index_to_remove = 0;
101 for txn in self.pending_transactions.clone() {
102 if txn.tx_id == tx_id {
103 self.pending_transactions.remove(index_to_remove);
104 self.add_transaction(txn);
105 break;
106 }
107 index_to_remove += 1;
108 }
109 }
110
111 pub fn load_from_file(filename: &str) -> Wallet {
115 let data = std::fs::read_to_string(filename).expect("Unable to read file");
116 serde_json::from_str(&data).expect("Unable to parse JSON")
117 }
118}