Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get gas amount web3py?

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.

like image 575
randoTrack Avatar asked Oct 13 '25 04:10

randoTrack


2 Answers

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(tx)
tx.update({'gas': gas})
like image 166
Branko B Avatar answered Oct 14 '25 17:10

Branko B


  • 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})
    
like image 30
Yilmaz Avatar answered Oct 14 '25 17:10

Yilmaz