I am using a alchemy node to calculate the gas limit of a smart contract once the state of the contract has changed to what I am looking for. I monitor this change by calling a read method on the contract every couple of seconds and checking its value. However, the estimateGas function seems to be getting called too early and returning the gas limit of the contract where the state is still the same as the old version.
For example: Contract state 1 gas limit is 100 Contract state 2 gas limit is 200
I check the state of the contract every few seconds, once it is state 2 I expect to get gas limit 200, but I am getting 100 even though the contract has already changed.
My guess is that I need to estimate the gas on the latest block, but I don't know how and I can't find a way to change this. I know for example the getBlock function has the option to specify 'latest' and I'm not sure how to do this using estimateGas.
Here is the code I use to do the estimation:
const gasLimit = await contract.methods['someFunction'](1).estimateGas({from: address, value: val, data: data});