咱们可以使用web3.js框架的estimateGas函数得到一个以太坊智能合约的Gas估计值 ,经过执行一个消息调用或交易,该消息调用或交易直接在节点的VM中执行,并未在区块链中确认,函数会返回估算使用的gas量。git
函数调用:github
web3.eth.estimateGas(callObject [, callback])
复制代码
参数:web
在 web3.eth.sendTransaction 中, 参数大都是可选的。浏览器
返回值: 数字:模拟呼叫/交易的须要使用的gas值。bash
一个简单示例:微信
var result = web3.eth.estimateGas({
to: "0xc4abd0339eb8d57087278718986382264244252f",
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
});
console.log(result); // "0x0000000000000000000000000000000000000000000000000000000000000015"
复制代码
用web3js库中可能遇到estimateGas方法出错的问题。大多数状况下获得的错误是这个:“所需的gas超过容许值或老是交易失败”。网络
首先要检查的下交易是否有效。例如,若是正在估计将必定数量的通证发送到另外一个地址的gasAmount,那么最主要的检查两件事:app
评估发送通证的所需gas量的代码片断:框架
tokenContract.methods.transfer(recipientAddress,numtokens)
.estimateGas({from:tokenHolderAddress},function(gasAmount){
console.log(gasAmount);
});
复制代码
官网在这里https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethestimategas.异步
也能够在你的浏览器地址栏输入https://ethereum.github.io/browser-solidity,而后直接copy你的合约就能够得到估计值。
这个代码中默认的一个示例是提案投票的代码以下:
pragma solidity ^0.4.0;
contract Ballot {
struct Voter {
uint weight;
bool voted;
uint8 vote;
address delegate;
}
struct Proposal {
uint voteCount;
}
address chairperson;
mapping(address => Voter) voters;
Proposal[] proposals;
/// Create a new ballot with $(_numProposals) different proposals. //为不一样的提案建立一个新的投票合约
function Ballot(uint8 _numProposals) public {
chairperson = msg.sender;
voters[chairperson].weight = 1;
proposals.length = _numProposals;
}
/// Give $(toVoter) the right to vote on this ballot.//授予投票权
/// May only be called by $(chairperson). //只能被主席调用
function giveRightToVote(address toVoter) public {
if (msg.sender != chairperson || voters[toVoter].voted) return;
voters[toVoter].weight = 1;
}
/// Delegate your vote to the voter $(to).//委托你的投票权
function delegate(address to) public {
Voter storage sender = voters[msg.sender]; // assigns reference 指定参数
if (sender.voted) return;
while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender)
to = voters[to].delegate;
if (to == msg.sender) return;
sender.voted = true;
sender.delegate = to;
Voter storage delegateTo = voters[to];
if (delegateTo.voted)
proposals[delegateTo.vote].voteCount += sender.weight;
else
delegateTo.weight += sender.weight;
}
/// Give a single vote to proposal $(toProposal). //对某个提案投一票
function vote(uint8 toProposal) public {
Voter storage sender = voters[msg.sender];
if (sender.voted || toProposal >= proposals.length) return;
sender.voted = true;
sender.vote = toProposal;
proposals[toProposal].voteCount += sender.weight;
}
function winningProposal() public constant returns (uint8 _winningProposal) {
uint256 winningVoteCount = 0;
for (uint8 prop = 0; prop < proposals.length; prop++)
if (proposals[prop].voteCount > winningVoteCount) {
winningVoteCount = proposals[prop].voteCount;
_winningProposal = prop;
}
}
}
复制代码
能够run下试试。
安利一个适合区块链新手的以太坊DApp开发教程:以太坊DApp开发实战入门
若是想加入以太坊技术开发群聊交流技术能够加微信.