[Ethereum] the right way to calculate gas price and limit for contract deployment

contract-deploymentcontract-developmentmetamaskout-of-gasremix

I have tried several times and reached up to a gasPrice of 65 Gwei and a gasLimit of 500,000 which is $7.6 and still the deployment fails with error "Out of gas".

After spending tens of USD without getting the fees back – how can I calculate how much gas will be enough for deploying my contract?

Best Answer

If you are using Remix and MetaMask (ass your tags imply), then it should be calculated for you automatically (they use the eth_estimateGas RPC call under the hood). If that is the case, you should not manually enter a gasLimit of 500,000 and instead use their estimated gas.

As a note, any gas that is unused in the transaction is returned to you. For example, if your contract costs 1,000,000 gas to deploy and you use gasLimit = 5,000,000, then your contract will be deployed and you will only have spent 1,000,000 gas.