We can use the estimateGas function of the Web3.js framework to obtain a Gas estimate for an Ethereum smart contract by performing a message call or transaction that is executed directly in the VM of the node and not validated in the blockchain. The function returns the estimated amount of Gas used.
Function call:
web3.eth.estimateGas(callObject [, callback])
Copy the code
Parameters:
In web3.eth. SendTransaction, the parameters are mostly optional.
- Object – The transaction Object to be sent:
- From: String – Address of the account used for transmission. The web3.eth. DefaultAccount attribute is used by default.
- To: String – (Optional) Destination address, undefined for the transaction that created the contract.
- Value: Number | String | BigNumber – (optional) for the value of transactions to Wei for the unit, if the contract is created, and funds.
- Gas: Number | String | BigNumber – (optional, default: pending) used in transaction volume of gas (unused gas has returned).
- GasPrice: Number | String | BigNumber – (optional, default: pending) the deal gas prices to wei, the default is the average price of gas network.
- Data: String – (Optional) Either A byte String containing the data associated with the message, or the initialization code that creates the contract transaction.
- Nonce: Number – (Optional) Integer of a random Number. This allows you to override your own pending transactions that use the same random number.
- Function – (optional) The HTTP request becomes asynchronous if a callback is passed. Details are here in this note.
Return value: Digital: The gas value to be used for the analog call/transaction.
A simple example:
var result = web3.eth.estimateGas({
to: "0xc4abd0339eb8d57087278718986382264244252f",
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
});
console.log(result); // "0x0000000000000000000000000000000000000000000000000000000000000015"
Copy the code
The estimateGas method may fail in web3JS libraries. Most of the time the error you get is this: “Gas required exceeds the allowable value or the transaction always fails”.
First check whether the underlying transaction is valid. For example, if gasAmount is estimating to send a certain number of tokens to another address, the two main things to check are:
- Whether there is enough Ethernet in the sending address.
- Whether there are enough tokens/tokens in the sending address. This may seem like an obvious thing to check, but it’s still possible to make the silly mistake of thinking that the method estimates Gas only to compute estimates, which it isn’t. If the actual condition of the parameter is not correct, it simply throws an error when running the method without actually executing any code.
Code snippet for evaluating the amount of gas required to send a token:
TokenContract. The methods. Transfer (recipientAddress, numtokens). EstimateGas ({the from: tokenHolderAddress}.function(gasAmount) {console.log (gasAmount); });Copy the code
Website https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethestimategas here.
Can enter https://ethereum.github.io/browser-solidity in your browser address bar, and then copy your contract directly can obtain estimates.
A default example in this code is the code for proposal voting as follows:
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 proposalsfunctionBallot(uint8 _numProposals) public { chairperson = msg.sender; voters[chairperson].weight = 1; proposals.length = _numProposals; } /// Give $(toVoter) the right to vote on this ballot.// Grant voting rights /// May only be called by $(Chairperson). // May only be called by chairmanfunction giveRightToVote(address toVoter) public {
if(msg.sender ! = chairperson || voters[toVoter].voted)return; voters[toVoter].weight = 1; } // Delegate your vote to the voter $(to)functiondelegate(address to) public { Voter storage sender = voters[msg.sender]; // Assert reference specifies parametersif (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;
elsedelegateTo.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; }}}Copy the code
You can run it.
Amway a suitable blockchain novice Ethereum DApp development tutorial: Ethereum DApp development combat introduction
If you want to join ethereum technology development group chat communication technology can add wechat.