pessimistic_proof_core/
local_balance_tree.rs

1use agglayer_primitives::{Digest, FromU256, U256};
2use agglayer_tries::proof::SmtMerkleProof;
3use serde::{Deserialize, Serialize};
4use serde_with::serde_as;
5use unified_bridge::TokenInfo;
6
7use crate::ProofError;
8
9/// The key is [`TokenInfo`] which can be packed into 192 bits (32 for network
10/// id and 160 for token address).
11pub const LOCAL_BALANCE_TREE_DEPTH: usize = 192;
12
13/// A commitment to the set of per-network local balance trees maintained by the
14/// local network
15#[serde_as]
16#[derive(Clone, Debug, Serialize, Deserialize)]
17pub struct LocalBalanceTree {
18    /// The Merkle Root of the local balance tree
19    #[serde_as(as = "_")]
20    pub root: Digest,
21}
22
23pub type LocalBalancePath = SmtMerkleProof<LOCAL_BALANCE_TREE_DEPTH>;
24
25impl LocalBalanceTree {
26    pub fn verify_and_update(
27        &mut self,
28        key: TokenInfo,
29        path_to_update: &LocalBalancePath,
30        old_balance: U256,
31        new_balance: U256,
32    ) -> Result<(), ProofError> {
33        self.root = path_to_update
34            .verify_and_update(
35                key,
36                Digest::from_u256(old_balance),
37                Digest::from_u256(new_balance),
38                self.root,
39            )
40            .ok_or(ProofError::InvalidBalancePath)?;
41
42        Ok(())
43    }
44}