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.
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})
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})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With