solidity
solidity copied to clipboard
Error: cannot estimate gas; transaction may fail or may require manual gas limit
Description
I frequently get errors like the following:
Error: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ]
(reason="VM Exception while processing transaction: reverted with reason string ''", method="estimateGas", transaction=
{"from":"0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC","gasPrice":
{"type":"BigNumber","hex":"0x00"},"to":"0x663F3ad617193148711d28f5334eE4Ed07016602","value":
{"type":"BigNumber","hex":"0x65"},"data":"0x3e58c58c00000000000000000000000071c95911e9a5d330f4d621842ec243ee1343292e",
"accessList":null}, error={"stackTrace":[{"type":4,"sourceReference":
{"function":"send","contract":"SendFunction","sourceName":"contracts/test/SendFunction.sol","sourceContent":
"// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\n\ncontract SendFunction {\n
function send(address to) external payable {\n (bool success, bytes memory data) = to.call{value: msg.value}(\"x\");\n
if (!success) {\n revert(string(data));\n }\n }\n}\n","line":9,"range":[244,264]},"message":{"value":
{"type":"Buffer","data":
[8,195,121,160,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0]},"_selector":"08c379a0"},"isInvalidOpcodeError":false}],"data":"0x08c379a000000000000000000000000000000000
000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000"},
code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.6.8)
at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:261:28)
at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:273:20)
at checkError (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:78:20)
at EthersProviderWrapper.<anonymous> (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:603:20)
at step (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:48:23)
at Object.throw (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:29:53)
at rejected (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:21:65)
This only happens occasionally (I'll include a testcase below), and it's always hard to fix. The only solution is to set {gasLimit: 3e7}
in each contract function call.
One thing that can trigger this problem is when the contract size approaches the maximum possible size. (Hopefully the testcase triggers this as a standalone program -- other contracts in my build environment raise the total size close to the limit.)
Environment
- Compiler version: 0.8.14
- Target EVM version (as per compiler settings): unknown
- Framework/IDE (e.g. Truffle or Remix): Hardhat
- EVM execution environment / backend / blockchain client: Hardhat network
- Operating system: Linux
Steps to Reproduce
Contracts.sol
:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.14;
contract HasReceiveFunction {
uint256 public receivedETH;
receive() external payable {
receivedETH += msg.value;
}
}
contract SendFunction {
function send(address to) external payable {
(bool success,) = to.call{value: msg.value}("");
if (!success) {
revert("Failed to send ETH");
}
}
}
index.js
:
const { expect } = require("chai");
const { ethers } = require("hardhat");
const SendFunction = require("../artifacts/contracts/Contracts.sol/SendFunction.json");
const HasReceiveFunction = require("../artifacts/contracts/Contracts.sol/HasReceiveFunction.json");
async function deployContract(wallet, contract, constructorArgs) {
const contractInstance = await ethers.ContractFactory.fromSolidity(contract, wallet).deploy(...constructorArgs);
await contractInstance.deployed();
return contractInstance;
}
describe("TestSendReceiveFunction", () => {
let wallet;
beforeEach(async () => {
wallet = await ethers.getSigners();
});
it("send ETH", async () => {
const send = await deployContract(wallet[2], SendFunction, []);
const hasReceive = await deployContract(wallet[1], HasReceiveFunction, []);
await send.send(hasReceive.address, {value: 101, gasLimit: 3e7});
expect(await hasReceive.receivedETH({gasLimit:3e7})).to.equal(101);
});
)};
To trigger the error, you need to do two things:
- Remove the
gasLimit: 3e7
args. - Change
(bool success,) = to.call{value: msg.value}("");
into(bool success,) = to.call{value: msg.value}("x");
-- this should revert thecall
, becausereceive
functions require thatmsg.data.length == 0
. It's when this call tries to revert that the "cannot estimate gas" error seems to be triggered.
Hi. Did you fix this error? I have the same shit :/
I checked the Solidity documentation, and sometimes this is triggered simply by a transaction reverting. I don't know why some transactions reverting trigger this and some don't.
Add allowUnlimitedContractSize: true
to your hardhat.config.ts under defaultNetworks.networks both "hardhat" and "localhost".
At least it worked for me.
Have you fixed it yet? Having the same issue using ether js and walletconnect provider. But works with injected
Am doing: signer.estimateGas.method(parameter)
Edit: My bad, it was my mistake on contract. I was facing the issue for doing unhandled rejections. The reason was the transaction actually reverting every time for lack of allowance which I didn't handled in contract. Thus, the estimateGas method was reverting every time as the contract call fails.
From my side the solution would be for this by debugging the contract if somehow it reverts the call by any unhandled rejection
Add
allowUnlimitedContractSize: true
to your hardhat.config.ts under defaultNetworks.networks both "hardhat" and "localhost". At least it worked for me.
but what about in remix ide???
Add
allowUnlimitedContractSize: true
to your hardhat.config.ts under defaultNetworks.networks both "hardhat" and "localhost". At least it worked for me.
worked for me, Gracias man, you just saved my day!
I had the same issue but solved it myself
I forgot to add the following line of code in my contract
receive() external payable {}
I had the same issue but solved it myself
I forgot to add the following line of code in my contract
receive() external payable {}
Niceeee, well done man
in my case, there is a line of code in the constructor that revert the transaction
require(block.timestamp < _poolStartTime, "late");
Check your code for any revert boyz
where and how can i run this code please
Hi I got this error in my code. I just forgot to add "utf8" in fs.readFileSync()
const binary = fs.readFileSync(
"./SimpleStorage_sol_SimpleStorage.bin",
"utf8"
);
and this fixes my error.
And I mean that maybe your code (@lukehutch) has some bugs like that.
This issue has been marked as stale due to inactivity for the last 90 days. It will be automatically closed in 7 days.
Am having same issue. Any idea on how to solve it? My contract is deployed successfully, all other functions works fine, but when the buy function is called, Metamask will throw an error saying We are unable to estimate gas prize, and it will give outrageous amount for gas fee. It gives me 0.8BNB for gas fee, what could be wrong
Am having same issue. Any idea on how to solve it? My contract is deployed successfully, all other functions works fine, but when the buy function is called, Metamask will throw an error saying We are unable to estimate gas prize, and it will give outrageous amount for gas fee. It gives me 0.8BNB for gas fee, what could be wrong
Can you share the code of buy function?
Same problem.
I solved it in this way.
-
Create a new directory totally empty: /blabla/createsmartaccount_dir.
-
Create these 2 files inside it.
/blabla/createsmartaccount_dir/index.js
/blabla/createsmartaccount_dir/package.json
- Run the commands
npm install
node ./index.js
#/blabla/createsmartaccount_dir/index.js
const { ethers } = require( 'ethers')
const { EthersAdapter } = require( '@safe-global/protocol-kit')
const Safe = require( '@safe-global/protocol-kit')
const { SafeFactory } = require( '@safe-global/protocol-kit')
const { SafeAccountConfig } = require( '@safe-global/protocol-kit')
const { ContractNetworksConfig } = require( '@safe-global/protocol-kit')
const execute = async () => {
const RPC_URL='https://rpc2.sepolia.org'
const provider = new ethers.providers.JsonRpcProvider(RPC_URL)
// Initialize signers
//metamask wallet and privatekey
//0x967c1CF5d91f3738c969c76EB4bDddA6da4183c1
const signerWallet =
new ethers.Wallet("ca46xxxxxxxxxxxxxxx", provider)
const ethAdapter = new EthersAdapter({ethers, signerOrProvider: signerWallet})
const chainId = await ethAdapter.getChainId()
console.log(`ChainId: ${chainId}`)
const safeVersion = '1.3.0'
const isL1SafeMasterCopy = false
const safeFactory = await SafeFactory.create({ ethAdapter: ethAdapter })
const safeAccountConfig = {
threshold: 1, // Have to be >= 1 && <= totalOwners
owners: ["0x967xxxxxxxxxxxxxxxxxxxxxxxxxxxx"],
eth_estimateGas:30000,
}
console.log("Start Deploying Safe");
//This Safe is tied to owner 1 because the factory was initialized with an
//adapter that had owner 1 as the signer.
const safeSdkOwner1 = await safeFactory.deploySafe({ safeAccountConfig })
const safeAddress = safeSdkOwner1.getAddress()
console.log(`Safe deployed at: ${safeAddress}`)
}
execute();
#/blabla/createsmartaccount_dir/package.json
{
"dependencies": {
"@safe-global/api-kit": "^1.0.1",
"@safe-global/protocol-kit": "^0.1.1",
"@safe-global/safe-core-sdk-types": "^1.10.1",
"dotenv": "^16.0.3",
"ethers": "5.7.2"
}
}
https://ethereum.stackexchange.com/questions/150579/periodic-failure-when-attempting-to-create-gnosis-safe-via-safe-global-protocol/150771#150771
My solve was to upgrade everything I could in my project relating to hardhat and ganache.
yarn add ganache
yarn add hardhat
yarn add hardhat-contract-sizer
yarn add hardhat-gas-reporter
yarn add solidity-coverage
yarn add @nomicfoundation/hardhat-ethers
Out of nowhere some conflict between my packages was causing my configuration to no longer function as it used to.
hardhat: {
throwOnTransactionFailures: true,
throwOnCallFailures: true,
allowUnlimitedContractSize: true,
timeout: 1800000
},
Add
allowUnlimitedContractSize: true
to your hardhat.config.ts under defaultNetworks.networks both "hardhat" and "localhost". At least it worked for me.
Sometimes its working and sometimes not
still facing error https://stackoverflow.com/questions/76795642/error-missing-revert-data-action-estimategas?noredirect=1#comment135417356_76795642
This issue has been marked as stale due to inactivity for the last 90 days. It will be automatically closed in 7 days.
Hi everyone! This issue has been automatically closed due to inactivity. If you think this issue is still relevant in the latest Solidity version and you have something to contribute, feel free to reopen. However, unless the issue is a concrete proposal that can be implemented, we recommend starting a language discussion on the forum instead.
Have you tried specifically setting a higher gas limit?
// if you are using ethers.js
....
const contractFactory = new ethers.ContractFactory(abi, binary, wallet);
const overrides = {
gasPrice: 10000000000, // Can set this >= to the number read from Ganache window
gasLimit: 6721975, // Use the same gasLimit as read from Ganache window (or a bit higher if still having issue)
};
const contract = await contractFactory.deploy(overrides);
Let me know if that helps!
There are some things you can do to deal with We were not able to estimate gas. there might be an error in the contract and this transaction may fail issue.
we were not able to estimate gas. there might be an error in the contract and this transaction may fail.
1- Contract review: Review the smart contract code to make sure there are no errors or issues that could cause gas estimation problems. Look for any complicated operations or loops that cause excessive gas consumption.
Also, check the account you use is the same account you set up the contract with because you have a restricted converter and you start the manager in the manufacturer.
There are a couple of approaches to troubleshoot your contract like attempt adding a candidate through Etherscan. If the issue persists, consider deploying the contract on another testnet or estimate the gas required for this function.
2- Gas Limit: Make sure you set the proper gas limit for the transaction. If the gas limit is too low, the transaction may fail due to running out of gas before completion.
3- Gas Price: Make sure the gas price you are willing to pay is appropriate for the current network conditions. If gas prices are too low, miners may prioritize other projects over yours.
4- Consult with Developers: If you’re not the developer of the contract, consider consulting with the team or individual who developed it for assistance in resolving the problem of why We were not able to estimate gas. there might be an error in the contract and this transaction may fail.
-
cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (reason="execution reverted: TO2", method="estimateGas", transaction={"from":"0x65D738955217C4341873e677e2F570e3782bcc91","to":"0xd2A20682CcB8210974B8D860Dea55816fe48D98d","value":{"type":"BigNumber","hex":"0x2386f26fc10000"},"data":"0xec8ac4d800000000000000000000000065d738955217c4341873e677e2f570e3782bcc91","accessList":null}, error={"code":-32603,"message":"Internal JSON-RPC error.","data":{"code":3,"message":"execution reverted: TO2","data":"0x08c379a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000003544f320000000000000000000000000000000000000000000000000000000000"}}, code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.7.2)
please how to fix this kind of error I created it on bep20 network on remix.eth.org
Description
I frequently get errors like the following:
Error: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (reason="VM Exception while processing transaction: reverted with reason string ''", method="estimateGas", transaction= {"from":"0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC","gasPrice": {"type":"BigNumber","hex":"0x00"},"to":"0x663F3ad617193148711d28f5334eE4Ed07016602","value": {"type":"BigNumber","hex":"0x65"},"data":"0x3e58c58c00000000000000000000000071c95911e9a5d330f4d621842ec243ee1343292e", "accessList":null}, error={"stackTrace":[{"type":4,"sourceReference": {"function":"send","contract":"SendFunction","sourceName":"contracts/test/SendFunction.sol","sourceContent": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.14;\n\ncontract SendFunction {\n function send(address to) external payable {\n (bool success, bytes memory data) = to.call{value: msg.value}(\"x\");\n if (!success) {\n revert(string(data));\n }\n }\n}\n","line":9,"range":[244,264]},"message":{"value": {"type":"Buffer","data": [8,195,121,160,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0]},"_selector":"08c379a0"},"isInvalidOpcodeError":false}],"data":"0x08c379a000000000000000000000000000000000 000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000"}, code=UNPREDICTABLE_GAS_LIMIT, version=providers/5.6.8) at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:261:28) at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:273:20) at checkError (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:78:20) at EthersProviderWrapper.<anonymous> (node_modules/@ethersproject/providers/src.ts/json-rpc-provider.ts:603:20) at step (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:48:23) at Object.throw (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:29:53) at rejected (node_modules/@ethersproject/providers/lib/json-rpc-provider.js:21:65)
This only happens occasionally (I'll include a testcase below), and it's always hard to fix. The only solution is to set
{gasLimit: 3e7}
in each contract function call.One thing that can trigger this problem is when the contract size approaches the maximum possible size. (Hopefully the testcase triggers this as a standalone program -- other contracts in my build environment raise the total size close to the limit.)
Environment
- Compiler version: 0.8.14
- Target EVM version (as per compiler settings): unknown
- Framework/IDE (e.g. Truffle or Remix): Hardhat
- EVM execution environment / backend / blockchain client: Hardhat network
- Operating system: Linux
Steps to Reproduce
Contracts.sol
:// SPDX-License-Identifier: MIT pragma solidity ^0.8.14; contract HasReceiveFunction { uint256 public receivedETH; receive() external payable { receivedETH += msg.value; } } contract SendFunction { function send(address to) external payable { (bool success,) = to.call{value: msg.value}(""); if (!success) { revert("Failed to send ETH"); } } }
index.js
:const { expect } = require("chai"); const { ethers } = require("hardhat"); const SendFunction = require("../artifacts/contracts/Contracts.sol/SendFunction.json"); const HasReceiveFunction = require("../artifacts/contracts/Contracts.sol/HasReceiveFunction.json"); async function deployContract(wallet, contract, constructorArgs) { const contractInstance = await ethers.ContractFactory.fromSolidity(contract, wallet).deploy(...constructorArgs); await contractInstance.deployed(); return contractInstance; } describe("TestSendReceiveFunction", () => { let wallet; beforeEach(async () => { wallet = await ethers.getSigners(); }); it("send ETH", async () => { const send = await deployContract(wallet[2], SendFunction, []); const hasReceive = await deployContract(wallet[1], HasReceiveFunction, []); await send.send(hasReceive.address, {value: 101, gasLimit: 3e7}); expect(await hasReceive.receivedETH({gasLimit:3e7})).to.equal(101); }); )};
To trigger the error, you need to do two things:
- Remove the
gasLimit: 3e7
args.- Change
(bool success,) = to.call{value: msg.value}("");
into(bool success,) = to.call{value: msg.value}("x");
-- this should revert thecall
, becausereceive
functions require thatmsg.data.length == 0
. It's when this call tries to revert that the "cannot estimate gas" error seems to be triggered.
This is the exact error I'm having