Ethereum Dapp Development There is a difference from the traditional application development, is that you call the contract method is sometimes not free, need to pay gas. So, how much gas should be consumed when sending a transaction or invoking a contract method?
In Ethereum, use the Estimategas () method to estimate the gas consumption that a trade consumes. We distinguish between ordinary transfer transactions and contract method transactions, respectively, explaining how to calculate the gas consumed by the transaction. how to calculate gas consumption for ordinary transfer transactions.
For ordinary transfer transactions, use the Web3.eth.estimateGas () method to estimate gas consumption. For example:
var from = web3.eth.accounts[1]
var to = web3.eth.accounts[2]
var quantity = Web3.eth.estimateGas ({from
: From,
to:to,
value:50000000000000})
Console.log (' About to consume gas: ', quantity)
var amount = quantity * Web3.eth.gasPrice
console.log (' Transfer out of account balance approximately to be reduced: ', amount, ' (Wei) ')
How to calculate the gas consumption of the call contract method trade.
For contract method transactions, use the Estimategas () Call of the method on the contract object to calculate gas consumption. For example, for the following contract:
pragma solidity ^0.4.8;
Contract Eztest {
uint public num;
function Setnum (uint newnum) {
num = newnum;
}
}
The gas consumption of the Setnum () method can be estimated in JS. For example, the following code estimates the amount of gas that setnum (4) calls to consume:
Inst is an instance object of the Eztest contract
Inst.setNum.estimateGas (4, {from:web3.eth.accounts[1]})
Online Tutorials
Through the above introduction, I believe you have learned how to calculate the ether gas. If you are learning Ethereum dapp development, you can try the online interactive tutorial: Ethereum Dapp Practical Introductory Tutorial Ethereum to Central e-commerce Dapp application development