ethereum / solidity

Solidity, the Smart Contract Programming Language
https://soliditylang.org
GNU General Public License v3.0
23.27k stars 5.76k forks source link

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

Closed lukehutch closed 11 months ago

lukehutch commented 2 years ago

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

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 commented 2 years ago

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

lukehutch commented 2 years ago

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 commented 2 years ago

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

yourchocomate commented 2 years ago

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 commented 2 years ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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

JoniBrite commented 1 year ago

where and how can i run this code please

MMPgenave commented 1 year ago

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[bot] commented 1 year ago

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

Okpedan commented 1 year ago

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 commented 1 year ago

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?

kenny1323 commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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

1337-ishaan commented 1 year ago

still facing error https://stackoverflow.com/questions/76795642/error-missing-revert-data-action-estimategas?noredirect=1#comment135417356_76795642

github-actions[bot] commented 12 months ago

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[bot] commented 11 months ago

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.

rodonguyen commented 11 months ago

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 commented 8 months ago

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.

henry4848 commented 7 months ago
  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 commented 7 months ago

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

acmicpc0614 commented 1 month ago

I've got same error. How to fix it? Error is like this. "Error: Error: 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: ERC20: transfer amount exceeds allowance", method="estimateGas", transaction={"from":"0x0f252d465D12c03E42C206a21cE4A9Fe4E81e75F","to":"0x6350038196Bd8cDC12aEFd990c34DCb5E9876cba","data":"0x79c888940000000000000000000000000000000000000000000000000000000000000002","accessList":null}, error={"code":-32603,"message":"Internal JSON-RPC error.","data":{"code":3,"message":"execution reverted: ERC20: transfer amount exceeds allowance""