2018-04-06 14:52:10 +00:00
|
|
|
# Nimbus
|
|
|
|
# Copyright (c) 2018 Status Research & Development GmbH
|
|
|
|
# Licensed under either of
|
|
|
|
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
|
|
|
|
# * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
2018-01-15 18:42:40 +00:00
|
|
|
import
|
|
|
|
strformat,
|
2018-05-07 12:41:54 +00:00
|
|
|
../logging, ../errors, ../constants, stint
|
2018-01-15 18:42:40 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
GasMeter* = ref object
|
|
|
|
logger*: Logger
|
2018-02-20 17:27:43 +00:00
|
|
|
gasRefunded*: UInt256
|
|
|
|
startGas*: UInt256
|
|
|
|
gasRemaining*: UInt256
|
2018-01-15 18:42:40 +00:00
|
|
|
|
2018-02-20 17:27:43 +00:00
|
|
|
proc newGasMeter*(startGas: UInt256): GasMeter =
|
2018-01-15 18:42:40 +00:00
|
|
|
new(result)
|
|
|
|
result.startGas = startGas
|
|
|
|
result.gasRemaining = result.startGas
|
2018-02-20 17:27:43 +00:00
|
|
|
result.gasRefunded = 0.u256
|
2018-01-24 13:31:24 +00:00
|
|
|
result.logger = logging.getLogger("gas")
|
2018-01-15 18:42:40 +00:00
|
|
|
|
2018-02-20 17:27:43 +00:00
|
|
|
proc consumeGas*(gasMeter: var GasMeter; amount: UInt256; reason: string) =
|
|
|
|
#if amount < 0.u256:
|
|
|
|
# raise newException(ValidationError, "Gas consumption amount must be positive")
|
2018-01-15 18:42:40 +00:00
|
|
|
if amount > gasMeter.gasRemaining:
|
|
|
|
raise newException(OutOfGas,
|
2018-01-22 22:23:07 +00:00
|
|
|
&"Out of gas: Needed {amount} - Remaining {gasMeter.gasRemaining} - Reason: {reason}")
|
2018-01-15 18:42:40 +00:00
|
|
|
gasMeter.gasRemaining -= amount
|
|
|
|
gasMeter.logger.trace(
|
2018-01-22 22:23:07 +00:00
|
|
|
&"GAS CONSUMPTION: {gasMeter.gasRemaining + amount} - {amount} -> {gasMeter.gasRemaining} ({reason})")
|
2018-01-15 18:42:40 +00:00
|
|
|
|
2018-02-20 17:27:43 +00:00
|
|
|
proc returnGas*(gasMeter: var GasMeter; amount: UInt256) =
|
|
|
|
#if amount < 0.int256:
|
|
|
|
# raise newException(ValidationError, "Gas return amount must be positive")
|
2018-01-15 18:42:40 +00:00
|
|
|
gasMeter.gasRemaining += amount
|
|
|
|
gasMeter.logger.trace(
|
2018-01-22 22:23:07 +00:00
|
|
|
&"GAS RETURNED: {gasMeter.gasRemaining - amount} + {amount} -> {gasMeter.gasRemaining}")
|
2018-01-15 18:42:40 +00:00
|
|
|
|
2018-02-20 17:27:43 +00:00
|
|
|
proc refundGas*(gasMeter: var GasMeter; amount: UInt256) =
|
|
|
|
#if amount < 0.int256:
|
|
|
|
# raise newException(ValidationError, "Gas refund amount must be positive")
|
2018-01-15 18:42:40 +00:00
|
|
|
gasMeter.gasRefunded += amount
|
|
|
|
gasMeter.logger.trace(
|
2018-01-22 22:23:07 +00:00
|
|
|
&"GAS REFUND: {gasMeter.gasRemaining - amount} + {amount} -> {gasMeter.gasRefunded}")
|