Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error: cannot estimate gas; transaction may fail or may require manual gas limit #13159

Closed
lukehutch opened this issue Jun 16, 2022 · 24 comments
Closed
Labels
closed due inactivity The issue/PR was automatically closed due to inactivity. needs investigation stale The issue/PR was marked as stale because it has been open for too long.

Comments

@lukehutch
Copy link
Contributor

lukehutch commented Jun 16, 2022

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:

  1. Remove the gasLimit: 3e7 args.
  2. Change (bool success,) = to.call{value: msg.value}(""); into (bool success,) = to.call{value: msg.value}("x"); -- this should revert the call, because receive functions require that msg.data.length == 0. It's when this call tries to revert that the "cannot estimate gas" error seems to be triggered.
@SlamOff
Copy link

SlamOff commented Jun 29, 2022

Hi. Did you fix this error? I have the same shit :/

@lukehutch
Copy link
Contributor Author

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.

@Felix-Monteiro
Copy link

Add allowUnlimitedContractSize: true to your hardhat.config.ts under defaultNetworks.networks both "hardhat" and "localhost".
At least it worked for me.

@yourchocomate
Copy link

yourchocomate commented Sep 16, 2022

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

@janaka45
Copy link

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???

@mandatedisrael
Copy link

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!

@vmmuthu31
Copy link

I had the same issue but solved it myself

I forgot to add the following line of code in my contract

receive() external payable {}

@mandatedisrael
Copy link

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

@mirzasetiyono
Copy link

mirzasetiyono commented Dec 4, 2022

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

@cameel cameel added this to Triage in Solidity via automation Dec 30, 2022
@JoniBrite
Copy link

where and how can i run this code please

@MMPgenave
Copy link

MMPgenave commented Jan 5, 2023

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.

@github-actions
Copy link

github-actions bot commented Apr 5, 2023

This issue has been marked as stale due to inactivity for the last 90 days.
It will be automatically closed in 7 days.

@github-actions github-actions bot added the stale The issue/PR was marked as stale because it has been open for too long. label Apr 5, 2023
@Okpedan
Copy link

Okpedan commented Apr 8, 2023

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

@yourchocomate
Copy link

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?

@github-actions github-actions bot removed the stale The issue/PR was marked as stale because it has been open for too long. label Apr 9, 2023
@cameel cameel removed this from Triage in Solidity Apr 27, 2023
@kenny1323
Copy link

Same problem.

I solved it in this way.

  1. Create a new directory totally empty: /blabla/createsmartaccount_dir.

  2. Create these 2 files inside it.

/blabla/createsmartaccount_dir/index.js

/blabla/createsmartaccount_dir/package.json

  1. 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

@johnnyshankman
Copy link

johnnyshankman commented May 30, 2023

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
},

@DhaanishTts
Copy link

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

Copy link

github-actions bot commented Nov 1, 2023

This issue has been marked as stale due to inactivity for the last 90 days.
It will be automatically closed in 7 days.

@github-actions github-actions bot added the stale The issue/PR was marked as stale because it has been open for too long. label Nov 1, 2023
Copy link

github-actions bot commented Nov 8, 2023

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.

@github-actions github-actions bot added the closed due inactivity The issue/PR was automatically closed due to inactivity. label Nov 8, 2023
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Nov 8, 2023
@rodonguyen
Copy link

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!

@fundlan

This comment was marked as off-topic.

@henry4848
Copy link

  1. 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

@henry4848
Copy link

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:

  1. Remove the gasLimit: 3e7 args.
  2. Change (bool success,) = to.call{value: msg.value}(""); into (bool success,) = to.call{value: msg.value}("x"); -- this should revert the call, because receive functions require that msg.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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed due inactivity The issue/PR was automatically closed due to inactivity. needs investigation stale The issue/PR was marked as stale because it has been open for too long.
Projects
None yet
Development

No branches or pull requests