Skip to content

Commit

Permalink
refactor(backend): merge_db_account_data
Browse files Browse the repository at this point in the history
chore: lints
  • Loading branch information
Karrq committed Aug 5, 2024
1 parent 42e2aa4 commit eb21bc2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 21 deletions.
2 changes: 0 additions & 2 deletions crates/cheatcodes/src/inspector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,6 @@ impl Cheatcodes {
for address in data.db.persistent_accounts().into_iter().chain([data.env.tx.caller]) {
info!(?address, "importing to evm state");

let zk_address = address.to_h160();
let balance_key = get_balance_key(address);
let nonce_key = get_nonce_key(address);

Expand Down Expand Up @@ -559,7 +558,6 @@ impl Cheatcodes {

let account = journaled_account(data, address).expect("failed to load account");
let info = &account.info;
let zk_address = address.to_h160();

let balance_key = get_balance_key(address);
l2_eth_storage.insert(balance_key, EvmStorageSlot::new(info.balance));
Expand Down
43 changes: 24 additions & 19 deletions crates/evm/core/src/backend/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1947,26 +1947,31 @@ fn merge_db_account_data<ExtDB: DatabaseRef>(
active: &CacheDB<ExtDB>,
fork_db: &mut ForkDB,
) {

let mut acc = if let Some(acc) = active.accounts.get(&addr).cloned() {
acc
} else {
// Account does not exist
return;
};

if let Some(code) = active.contracts.get(&acc.info.code_hash).cloned() {
fork_db.contracts.insert(acc.info.code_hash, code);
}

if let Some(fork_account) = fork_db.accounts.get_mut(&addr) {
// This will merge the fork's tracked storage with active storage and update values
fork_account.storage.extend(std::mem::take(&mut acc.storage));
// swap them so we can insert the account as whole in the next step
std::mem::swap(&mut fork_account.storage, &mut acc.storage);
let Some(acc) = active.accounts.get(&addr) else { return };

// port contract cache over
if let Some(code) = active.contracts.get(&acc.info.code_hash) {
trace!("merging contract cache");
fork_db.contracts.insert(acc.info.code_hash, code.clone());
}

// port account storage over
use std::collections::hash_map::Entry;
match fork_db.accounts.entry(addr) {
Entry::Vacant(vacant) => {
trace!("target account not present - inserting from active");
// if the fork_db doesn't have the target account
// insert the entire thing
vacant.insert(acc.clone());
}
Entry::Occupied(mut occupied) => {
trace!("target account present - merging storage slots");
// if the fork_db does have the system,
// extend the existing storage (overriding)
let fork_account = occupied.get_mut();
fork_account.storage.extend(&acc.storage);
}
}

fork_db.accounts.insert(addr, acc);
}

/// Clones the zk account data from the `active` db into the `ForkDB`
Expand Down

0 comments on commit eb21bc2

Please sign in to comment.