[Ethereum] How to use estimateGas() in web3 py

pythonweb3.py

Before I run a function transaction, I want to know how much it will cost so I am trying to run estimateGas() like the docs say but I can't seem to get it to work.

appropriate_gas_amount = 300000
transaction = contract.functions.getName(
    account,
).buildTransaction({
    'gas' : appropriate_gas_amount,
    'nonce' : w3.eth.get_transaction_count(wallet_address)
})
print("transaction", transaction)

signed_tx = w3.eth.account.sign_transaction(transaction, key)
print("signed_tx", signed_tx)

gas_estimate = w3.eth.estimateGas(signed_tx)
print("gas_estimate", gas_estimate)

I keep getting

AttributeError: 'SignedTransaction' object has no attribute 'items'

For the line gas_estimate = w3.eth.estimateGas(signed_tx)

Unsure if this is an infura issue but am I wrong in how I am trying to accomplish this?

Best Answer

You have to estimate on the built tx, not the signed. For your code that would be the transaction variable.

Related Topic