diff --git a/src/kernel_evm/CHANGES.md b/src/kernel_evm/CHANGES.md index 50dcb3d1e3a01f48e31844b64175dc71deb5d211..f677afcf9b6ca82fbbd9dce038b571622d666b70 100644 --- a/src/kernel_evm/CHANGES.md +++ b/src/kernel_evm/CHANGES.md @@ -14,6 +14,7 @@ - Adds a new type of message in simulation mode, to verify that a transaction is valid by checking if the nonce is neither too low nor too high. (!9679) - Simulate if a transaction has a correct chain id. (!9752) - Fees are now paid by the sender. (!9480) +- Unused gas is refunded after succesful transactions. (!9915) ### EVM Node diff --git a/src/kernel_evm/evm_execution/src/handler.rs b/src/kernel_evm/evm_execution/src/handler.rs index f5d7993c92137946e7728bc7509709ea60bb99ca..2264a5cc5bf15c1e092fbbe5635c00615fb979e9 100644 --- a/src/kernel_evm/evm_execution/src/handler.rs +++ b/src/kernel_evm/evm_execution/src/handler.rs @@ -273,6 +273,31 @@ impl<'a, Host: Runtime> EvmHandler<'a, Host> { } } + /// Repay unused gas + pub fn repay_gas( + &mut self, + caller: H160, + unused_gas: Option, + ) -> Result<(), EthereumError> { + match unused_gas { + Some(unused_gas) => { + let amount = U256::from(unused_gas) * self.block.gas_price; + + debug_msg!( + self.host, + "{:?} refunded {:?} for transaction", + caller, + amount + ); + + self.get_or_create_account(caller)? + .balance_add(self.host, amount) + .map_err(EthereumError::from) + } + None => Ok(()), + } + } + /// Execute a SputnikVM runtime with this handler fn execute( &mut self, diff --git a/src/kernel_evm/evm_execution/src/lib.rs b/src/kernel_evm/evm_execution/src/lib.rs index 5cc54c9bc0029c8d2004bf165c7a4c2234d84ca4..62463cb8bf1c14f8d528827267d37ff303fae98f 100644 --- a/src/kernel_evm/evm_execution/src/lib.rs +++ b/src/kernel_evm/evm_execution/src/lib.rs @@ -162,6 +162,11 @@ where handler.increment_nonce(caller)?; + if result.is_success { + let unused_gas = gas_limit.map(|gl| gl - result.gas_used); + handler.repay_gas(caller, unused_gas)?; + } + Ok(Some(result)) } else { // caller was unable to pay for the gas limit @@ -1624,9 +1629,13 @@ mod test { .unwrap(), None ); + + let funds_total = + 1_000_000 + all_the_gas - expected_result.unwrap().unwrap().gas_used; + assert_eq!( get_balance(&mut mock_runtime, &mut evm_account_storage, &caller), - 1_000_000.into() + funds_total.into() ); }