Web3JS – Estimating Gas Error: Gas Required Exceeds Allowance Solutions

web3.pyweb3js

I would like to estimate the amount of gas required for a transaction before actually sending it with web3. For some reason I always get a gas exceeded error. I've double-checked my solidity code and there are no errors failing during this function call. Does anyone know why estimateGas() does not work for my use case?

My Code:

from web3 import Web3, HTTPProvider

web3 = Web3(HTTPProvider('https://mainnet.infura.io/v3/{LONG_INFURA_PROJECT_ID}'))

abi = [ ... long abi ...]
MyContract = web3.eth.contract(address="[contract_address]", abi=abi)

# this line fails...
# note: contractMethod is the name of the contract function I'm trying to call
estimated_gas = MyContract.functions.contractMethod("some_param").estimateGas()

Once I try to execute the line where estimateGas() is called, I get the following error:

{'code': -32000, 'message': 'gas required exceeds allowance (124572510) or always failing transaction'}

Best Answer

The issue was that I need to pass a transaction to the estimateGas() function. In addition, I needed to delete the data and to fields from the transaction dictionary (if they exist).

Final Working Code:

from web3 import Web3, HTTPProvider

web3 = Web3(HTTPProvider('https://mainnet.infura.io/v3/{LONG_INFURA_PROJECT_ID}'))

# grab contract instance using web3
abi = [ ... long abi ...]
MyContract = web3.eth.contract(address="[contract_address]", abi=abi)

# get nonce to use for transaction
nonce = web3.eth.getTransactionCount("<YOUR_ACCOUNT_ADDRESS>")

# create the transaction
transaction = Controller.functions \
            .doHardWork(*params) \
            .buildTransaction({
                'gas': 2000000,
                'gasPrice': web3.toWei(100),
                'from': "<YOUR_ACCOUNT_ADDRESS>",
                'nonce': nonce
            }) 

# delete the data and to fields from the transaction
del transaction['data']
del transaction['to']

# calculate gas
estimated_gas = MyContract.functions.contractMethod("some_param").estimateGas()