Is there a way to find the total gas that will be used by the transaction before a tx actually takes place?
Does the gas used depend on the amount of tx size in kb?
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityIs there a way to find the total gas that will be used by the transaction before a tx actually takes place?
Does the gas used depend on the amount of tx size in kb?
At least Metamask has some functionality to estimate the gas usage, but it's not perfect. More info about that: What is the general cause for out-of-gas with MetaMask?
The amount of gas required depends on what you are trying to do. There is no "kb" size of transactions as such - the gas requirements are calculated differently. If you are just sending some Ether around, 21000 is default and it's fine. If you are creating a contract, it takes a lot more gas. Some ideas about contract gas requirements: How to minimize gas consumption during contract creation
Yes, there is a way to estimate the gas consumption using web3. For transactions involving contract functions execution you can use this:
myContract.methods.myMethod([param1[, param2[, ...]]]).estimateGas(options[, callback])
, see here for more information.
For simple ether transactions you can use:
web3.eth.estimateGas({from: address, to: address, value: web3.toWei(1, "ether")})
See this discussion for more information