Skip to main content

off_grid_primitives/account/
option.rs

1use blake3::Hasher;
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4
5use super::AccountBalances;
6
7#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
8pub struct OptionsAccount {
9    /// Account ID
10    #[serde(with = "serde_bytes")]
11    pub id: Vec<u8>,
12    /// Balances of the account with asset id as key and balance as value
13    pub balances: HashMap<Vec<u8>, u64>,
14    /// state hash of the account
15    pub state_hash: Vec<u8>,
16}
17
18impl AccountBalances for OptionsAccount {
19    fn balances(&self) -> &HashMap<Vec<u8>, u64> {
20        &self.balances
21    }
22}
23
24impl OptionsAccount {
25    pub fn update_state_hash(&mut self) {
26        self.state_hash = self.hash_state();
27    }
28
29    pub fn hash_state(&self) -> Vec<u8> {
30        let mut hasher = Hasher::new();
31        for (asset, amount) in self.balances.iter() {
32            hasher.update(asset);
33            hasher.update(&amount.to_le_bytes());
34        }
35        hasher.finalize().as_bytes().to_vec()
36    }
37}