如何估算太坊交易的gas消耗量

在以太坊中,使用estimateGas()方法来估算一个交易要消耗的gas消耗量。我们区分普通转账交易和合约方法交易进行说明。

普通转账交易

对于普通转账交易而言,使用web3.eth.estimateGas()方法进行估计。例如:

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('大约要消耗gas:',quantity)
var amount = quantity * web3.eth.gasPrice
console.log('转出方的账户余额大约要减少:',amount,'(wei)')

合约方法交易

对于合约方法交易而言,使用合约对象上该方法的estimateGas()调用进行估计。例如,对于下面的合约:

pragma solidity ^0.4.8;
contract EzTest {
    uint public num;
    function setNum(uint newNum) {
        num = newNum;
    }
}

可以在js中估算setNum()方法的gas消耗量。例如,下面的代码对setNum(4)调用要消耗的gas量进行估算:

//inst 是EzTest合约的实例对象
inst.setNum.estimateGas(4, {from: web3.eth.accounts[1]})

在线教程

如果你正在尝试学习以太坊DApp开发,可以尝试一下汇智网的在线互动教程:

猜你喜欢

转载自my.oschina.net/u/3794778/blog/1799323