2

I can get the gas price, but how do I even get the gas amount? I feel like this is something that is not covered properly in the docs. In order for me to send a transaction(contract call), I need to build it but when I build it I need to give it the gas price and the amount of gas. How can I give it the amount of gas if I have no idea how to estimate the amount of gas?

For example this is my code of an approve contract call.

    tx = contract.functions.approve(spender,max_amount).buildTransaction({
        'nonce': nonce,
        'from':self.account,
        'gasPrice': web3.toWei('20', 'gwei'),
        'gas': ?
        })
    signed_tx = web3.eth.account.signTransaction(tx, self.pkey)

I can give it some arbitrary number, but this is not a real solution. In every example I see online, some arbitrary gas amount is thrown in, with no explanation of how they got it.

TylerH
  • 20,799
  • 66
  • 75
  • 101
randoTrack
  • 83
  • 1
  • 3
  • 6

3 Answers3

3

You can use web3.eth.estimate_gas on the unsigned transaction and then update the transaction with appropriate gas amount and sign

tx = contract.functions.approve(spender,max_amount).buildTransaction({
   'nonce': nonce,
   'from':self.account,
   'gasPrice': web3.toWei('20', 'gwei'),
   'gas': '0'
   })

gas = web3.eth.estimate_gas(temp)
tx.update({'gas': gas})
Branko B
  • 94
  • 4
1
  • get the gas price : w3.eth.gas_price
transaction = SimpleStorage.constructor().buildTransaction(
    {
        "chainId": chain_id,
        "gasPrice": w3.eth.gas_price,
        "from": my_address,
        "nonce": nonce,
    }
)
  • get the estimate gas

    estimate = web3.eth.estimateGas({
      'to':   'to_ddress_here', 
      'from': 'from_address_here', 
      'value': 145})
    
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
1

From the web3py docs:

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.

Try building your transaction like this, setting only those fields. Web3 will calculate the best gas price using those constraints.

tx = contract.functions.approve(spender, max_amount).buildTransaction({
    'from': self.account,
    'maxFeePerGas': web3.toWei('2', 'gwei'),
    'maxPriorityFeePerGas': web3.toWei('1', 'gwei'),
    'nonce': nonce
})