Skip to content

Commit

Permalink
docs: document non-zero amounts in State::increment_balances (#760)
Browse files Browse the repository at this point in the history
* feat: document non-zero amounts in State::increment_balances

* handle zero balance increment

---------

Co-authored-by: rakita <dragan0rakita@gmail.com>
  • Loading branch information
Rjected and rakita committed Oct 2, 2023
1 parent af4146a commit 4e78fbe
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
16 changes: 9 additions & 7 deletions crates/revm/src/db/states/cache_account.rs
Expand Up @@ -293,13 +293,15 @@ impl CacheAccount {
/// Increment balance by `balance` amount. Assume that balance will not
/// overflow or be zero.
///
/// Note: to skip some edge cases we assume that additional balance is never zero.
/// And as increment is always related to block fee/reward and withdrawals this is correct.
pub fn increment_balance(&mut self, balance: u128) -> TransitionAccount {
self.account_info_change(|info| {
info.balance += U256::from(balance);
})
.1
/// Note: only if balance is zero we would return None as no transition would be made.
pub fn increment_balance(&mut self, balance: u128) -> Option<TransitionAccount> {
if balance == 0 {
return None;
}
let (_, transition) = self.account_info_change(|info| {
info.balance = info.balance.saturating_add(U256::from(balance));
});
Some(transition)
}

fn account_info_change<T, F: FnOnce(&mut AccountInfo) -> T>(
Expand Down
14 changes: 13 additions & 1 deletion crates/revm/src/db/states/state.rs
Expand Up @@ -82,15 +82,27 @@ impl<DB: Database> State<DB> {
/// If account is not found inside cache state it will be loaded from database.
///
/// Update will create transitions for all accounts that are updated.
///
/// Like [CacheAccount::increment_balance], this assumes that incremented balances are not
/// zero, and will not overflow once incremented. If using this to implement withdrawals, zero
/// balances must be filtered out before calling this function.
pub fn increment_balances(
&mut self,
balances: impl IntoIterator<Item = (Address, u128)>,
) -> Result<(), DB::Error> {
// make transition and update cache state
let mut transitions = Vec::new();
for (address, balance) in balances {
if balance == 0 {
continue;
}
let original_account = self.load_cache_account(address)?;
transitions.push((address, original_account.increment_balance(balance)))
transitions.push((
address,
original_account
.increment_balance(balance)
.expect("Balance is not zero"),
))
}
// append transition
if let Some(s) = self.transition_state.as_mut() {
Expand Down

0 comments on commit 4e78fbe

Please sign in to comment.