Skip to content

Commit

Permalink
feat(interpreter): add helpers for spending all gas (bluealloy#1360)
Browse files Browse the repository at this point in the history
  • Loading branch information
DaniPopes authored Apr 29, 2024
1 parent 215a4c4 commit f59ce8c
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 12 deletions.
19 changes: 19 additions & 0 deletions crates/interpreter/src/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,18 @@ impl Gas {
}
}

/// Creates a new `Gas` struct with the given gas limit, but without any gas remaining.
#[inline]
pub const fn new_spent(limit: u64) -> Self {
Self {
limit,
remaining: 0,
remaining_nomem: 0,
memory: 0,
refunded: 0,
}
}

/// Returns the gas limit.
#[inline]
pub const fn limit(&self) -> u64 {
Expand Down Expand Up @@ -79,6 +91,13 @@ impl Gas {
self.remaining += returned;
}

/// Spends all remaining gas.
#[inline]
pub fn spend_all(&mut self) {
self.remaining = 0;
self.remaining_nomem = 0;
}

/// Records a refund value.
///
/// `refund` can be negative but `self.refunded` should always be positive
Expand Down
3 changes: 1 addition & 2 deletions crates/revm/src/handler/mainnet/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ pub fn frame_return_with_refund_flag<SPEC: Spec>(
let refunded = gas.refunded();

// Spend the gas limit. Gas is reimbursed when the tx returns successfully.
*gas = Gas::new(env.tx.gas_limit);
gas.record_cost(env.tx.gas_limit);
*gas = Gas::new_spent(env.tx.gas_limit);

match instruction_result {
return_ok!() => {
Expand Down
10 changes: 2 additions & 8 deletions crates/revm/src/inspector/gas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,7 @@ impl<DB: Database> Inspector<DB> for GasInspector {
mut outcome: CallOutcome,
) -> CallOutcome {
if outcome.result.result.is_error() {
outcome
.result
.gas
.record_cost(outcome.result.gas.remaining());
outcome.result.gas.spend_all();
self.gas_remaining = 0;
}
outcome
Expand All @@ -76,10 +73,7 @@ impl<DB: Database> Inspector<DB> for GasInspector {
mut outcome: CreateOutcome,
) -> CreateOutcome {
if outcome.result.result.is_error() {
outcome
.result
.gas
.record_cost(outcome.result.gas.remaining());
outcome.result.gas.spend_all();
self.gas_remaining = 0;
}
outcome
Expand Down
3 changes: 1 addition & 2 deletions crates/revm/src/optimism/handler_register.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ pub fn last_frame_return<SPEC: Spec, EXT, DB: Database>(
let remaining = gas.remaining();
let refunded = gas.refunded();
// Spend the gas limit. Gas is reimbursed when the tx returns successfully.
*gas = Gas::new(tx_gas_limit);
gas.record_cost(tx_gas_limit);
*gas = Gas::new_spent(tx_gas_limit);

match instruction_result {
return_ok!() => {
Expand Down

0 comments on commit f59ce8c

Please sign in to comment.