tetcore_runtime/
accounts.rs1use crate::RuntimeError;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use tetcore_primitives::{account::AccountData, Address, Hash32};
5
6pub struct AccountsModule {
7 accounts: HashMap<Address, AccountData>,
8}
9
10impl AccountsModule {
11 pub fn new() -> Self {
12 Self {
13 accounts: HashMap::new(),
14 }
15 }
16
17 pub fn create_account(&mut self, address: Address, balance: u128) {
18 self.accounts.insert(address, AccountData::new(balance));
19 }
20
21 pub fn get_account(&self, address: &Address) -> Option<&AccountData> {
22 self.accounts.get(address)
23 }
24
25 pub fn get_account_mut(&mut self, address: &Address) -> Option<&mut AccountData> {
26 self.accounts.get_mut(address)
27 }
28
29 pub fn account_exists(&self, address: &Address) -> bool {
30 self.accounts.contains_key(address)
31 }
32
33 pub fn transfer(
34 &mut self,
35 from: &Address,
36 to: &Address,
37 amount: u128,
38 ) -> Result<(), RuntimeError> {
39 let from_account = self
40 .accounts
41 .get_mut(from)
42 .ok_or(RuntimeError::InvalidState)?;
43
44 if from_account.balance < amount {
45 return Err(RuntimeError::InvalidState);
46 }
47
48 from_account.balance -= amount;
49
50 let to_account = self
51 .accounts
52 .entry(*to)
53 .or_insert_with(|| AccountData::new(0));
54 to_account.balance += amount;
55
56 Ok(())
57 }
58
59 pub fn increment_nonce(&mut self, address: &Address) -> Result<(), RuntimeError> {
60 let account = self
61 .accounts
62 .get_mut(address)
63 .ok_or(RuntimeError::InvalidState)?;
64 account.nonce += 1;
65 Ok(())
66 }
67
68 pub fn set_contract_code(
69 &mut self,
70 address: &Address,
71 code_hash: Hash32,
72 ) -> Result<(), RuntimeError> {
73 let account = self
74 .accounts
75 .get_mut(address)
76 .ok_or(RuntimeError::InvalidState)?;
77 account.contract_code_ref = Some(code_hash);
78 Ok(())
79 }
80
81 pub fn set_contract_storage_root(
82 &mut self,
83 address: &Address,
84 storage_root: Hash32,
85 ) -> Result<(), RuntimeError> {
86 let account = self
87 .accounts
88 .get_mut(address)
89 .ok_or(RuntimeError::InvalidState)?;
90 account.contract_storage_root = Some(storage_root);
91 Ok(())
92 }
93
94 pub fn all_accounts(&self) -> &HashMap<Address, AccountData> {
95 &self.accounts
96 }
97}
98
99impl Default for AccountsModule {
100 fn default() -> Self {
101 Self::new()
102 }
103}