1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
use std::{
    cell::{Ref, RefCell},
    collections::HashMap,
    fmt,
    rc::Rc,
};

use elrond_wasm::types::heap::Address;

use crate::{
    address_hex,
    world_mock::{AccountData, BlockchainMock},
};

use super::TxCacheSource;

pub struct TxCache {
    source_ref: Rc<dyn TxCacheSource>,
    pub(super) accounts: RefCell<HashMap<Address, AccountData>>,
}

impl fmt::Debug for TxCache {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TxCache")
            .field("accounts", &self.accounts)
            .finish()
    }
}

impl TxCache {
    pub fn new(source_ref: Rc<dyn TxCacheSource>) -> Self {
        TxCache {
            source_ref,
            accounts: RefCell::new(HashMap::new()),
        }
    }

    pub fn blockchain_ref(&self) -> &BlockchainMock {
        self.source_ref.blockchain_ref()
    }

    fn load_account_if_necessary(&self, address: &Address) {
        let mut accounts_mut = self.accounts.borrow_mut();
        if !accounts_mut.contains_key(address) {
            if let Some(blockchain_account) = self.source_ref.load_account(address) {
                accounts_mut.insert(address.clone(), blockchain_account);
            }
        }
    }

    pub fn with_account<R, F>(&self, address: &Address, f: F) -> R
    where
        F: FnOnce(&AccountData) -> R,
    {
        self.load_account_if_necessary(address);
        let accounts = self.accounts.borrow();
        let account = accounts
            .get(address)
            .unwrap_or_else(|| panic!("Account {} not found", address_hex(address)));
        f(account)
    }

    pub fn with_account_mut<R, F>(&self, address: &Address, f: F) -> R
    where
        F: FnOnce(&mut AccountData) -> R,
    {
        self.load_account_if_necessary(address);
        let mut accounts = self.accounts.borrow_mut();
        let account = accounts
            .get_mut(address)
            .unwrap_or_else(|| panic!("Account {} not found", address_hex(address)));
        f(account)
    }

    pub fn insert_account(&self, account_data: AccountData) {
        self.accounts
            .borrow_mut()
            .insert(account_data.address.clone(), account_data);
    }

    pub fn increase_acount_nonce(&self, address: &Address) {
        self.with_account_mut(address, |account| {
            account.nonce += 1;
        });
    }

    pub fn get_all_accounts(&self) -> Ref<HashMap<Address, AccountData>> {
        self.accounts.borrow()
    }

    /// Assumes the nonce has already been increased.
    pub fn get_new_address(&self, creator_address: &Address) -> Address {
        let current_nonce = self.with_account(creator_address, |account| account.nonce);
        self.blockchain_ref()
            .get_new_address(creator_address.clone(), current_nonce - 1)
            .unwrap_or_else(|| {
                panic!("Missing new address. Only explicit new deploy addresses supported")
            })
    }

    pub fn into_blockchain_updates(self) -> BlockchainUpdate {
        BlockchainUpdate {
            accounts: self.accounts.into_inner(),
        }
    }

    pub fn commit_updates(&self, updates: BlockchainUpdate) {
        self.accounts
            .borrow_mut()
            .extend(updates.accounts.into_iter());
    }
}

pub struct BlockchainUpdate {
    accounts: HashMap<Address, AccountData>,
}

impl BlockchainUpdate {
    pub fn empty() -> Self {
        BlockchainUpdate {
            accounts: HashMap::new(),
        }
    }

    pub fn apply(self, blockchain: &mut BlockchainMock) {
        blockchain.update_accounts(self.accounts);
    }
}