Skip to content

Latest commit

 

History

History
121 lines (83 loc) · 4.37 KB

gas_price.rst

File metadata and controls

121 lines (83 loc) · 4.37 KB

Gas Price API

Warning

Gas price strategy is only supported for legacy transactions. The London fork introduced maxFeePerGas and maxPriorityFeePerGas transaction parameters which should be used over gasPrice whenever possible.

For Ethereum (legacy) transactions, gas price is a delicate property. For this reason, Web3 includes an API for configuring it.

The Gas Price API allows you to define Web3's behaviour for populating the gas price. This is done using a "Gas Price Strategy" - a method which takes the Web3 object and a transaction dictionary and returns a gas price (denominated in wei).

Retrieving gas price

To retrieve the gas price using the selected strategy simply call ~web3.eth.Eth.generate_gas_price

>>> web3.eth.generate_gas_price()
20000000000

Creating a gas price strategy

A gas price strategy is implemented as a python method with the following signature:

def gas_price_strategy(web3, transaction_params=None):
...

The method must return a positive integer representing the gas price in wei.

To demonstrate, here is a rudimentary example of a gas price strategy that returns a higher gas price when the value of the transaction is higher than 1 Ether.

from web3 import Web3

def value_based_gas_price_strategy(web3, transaction_params):
    if transaction_params['value'] > Web3.to_wei(1, 'ether'):
        return Web3.to_wei(20, 'gwei')
    else:
        return Web3.to_wei(5, 'gwei')

Selecting the gas price strategy

The gas price strategy can be set by calling ~web3.eth.Eth.set_gas_price_strategy.

from web3 import Web3

def value_based_gas_price_strategy(web3, transaction_params):
    ...

w3 = Web3(...)
w3.eth.set_gas_price_strategy(value_based_gas_price_strategy)

Available gas price strategies