A deeper understanding of how Estimategas calculates the gas volume consumed by the smart contract in Web3.js

Source: Internet
Author: User

We can use the Estimategas function of the web3.js framework to obtain a gas estimate for an Ethereum smart contract by executing a message call or transaction that executes directly in the VM of the node, not confirmed in the blockchain, and returns the estimated gas amount used.

Function call:

Web3.eth.estimateGas (CallObject [, callback])

Parameters:

In Web3.eth.sendTransaction, the parameters are mostly optional.

1. Object-The transaction object to be sent:

    • from: String -The account address used to transfer. The Web3.eth.defaultAccount property is used by default.
    • to: String -(optional) destination address, not defined for the transaction that created the contract.
    • value: Number|String|BigNumber -(optional) The value of the transfer for the transaction is in Wei, and if the contract is created, it is also the fund.
    • gas: Number|String|BigNumber -(optional, default: Pending) The amount of gas used to trade (unused gas has been refunded).
    • gasPrice: Number|String|BigNumber -(optional, default: Pending) The gas price for this transaction is in Wei, which defaults to the average network gas price.
    • data: String -(optional) either the byte string that contains the message's associated data, or creates the initialization code for the contract transaction.
    • nonce: Number -(optional) An integer of a random number. This allows you to overwrite your own pending transactions that use the same random number.

2.Function-(optional) If the callback is passed, the HTTP request becomes asynchronous. Detailed description here for this note.

return Value:

Number: The gas value used to simulate call/trade.

A simple example:
var result = Web3.eth.estimateGas ({    "  0xc4abd0339eb8d57087278718986382264244252f",      "  0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"// "0x0000000000000000000000000000000000000000000000000000000000000015"

You may encounter problems with the Estimategas method in the Web3js library. In most cases the error is this: "The required gas exceeds the allowable value or is always a trade failure".

The first thing to check is whether the next trade is valid. For example, if you are estimating the gasamount of sending a certain number of passes to another address, then the most important thing to check is two things:

1. Whether there is enough ether in the sending address.
2. Whether there is sufficient pass/token in the sending address.
These seem to be obvious to check, but it is still possible to make such a low-level mistake, that the method estimates that gas is only used to calculate the estimated value, actually not. If the actual condition of the parameter setting is not correct, it throws an error directly when running the method without actually executing any code .

Code snippet to evaluate the amount of gas required to send a pass:

TokenContract.methods.transfer (Recipientaddress,numtokens). Estimategas ({ from : Tokenholderaddress},function (Gasamount) {console.log (gasamount);} );

The official website is here Https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethestimategas.

You can also enter https://ethereum.github.io/browser-solidity in your browser's address bar, and then copy your contract directly to get the estimated value.

One of the default examples in this code is that the code for a proposal vote is as follows:

pragma solidity ^0.4.0; contract Ballot {structVoter {UINTweight; BOOLvoted;        Uint8 vote; AddressDelegate; }    structProposal {UINTVotecount;    } address Chairperson; Mapping (Address=voter) voters;    Proposal[] proposals; ///create a new ballot with $ (_numproposals) different proposals.//Creating a voting contract for different proposalsFunction ballot (uint8 _numproposals) Public{Chairperson=Msg.sender; Voters[chairperson].weight=1; Proposals.length=_numproposals; }    ///Give $ (tovoter) the right to vote in this ballot.//grant voting rights///May is called by $ (Chairperson).//can only be called by the Presidentfunction Giverighttovote (address tovoter) Public {        if(Msg.sender! = Chairperson | | voters[tovoter].voted)return; Voters[tovoter].weight=1; }    ///Delegate your vote to the voter $ (to).//Entrust you with the right to votefunctionDelegate(Address to) Public{Voter Storage sender= Voters[msg.sender];//assigns reference specifying parameters        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; ElseDelegateto.weight+=Sender.weight; }    ///Give A single vote to proposal $ (toproposal).//vote on a proposalFunction 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 () Publicconstant 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; }    }}

You can try it under run.

A deeper understanding of how Estimategas calculates the gas volume consumed by the smart contract in Web3.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.