以太坊智能合约gas如何估计?

以太坊如何估计估算计算gas?Etherscan上transaction info中有个gas used by txn,结果跟remix给的结果以及geth中getTransactionReceipt的gasUsed给的结果都会是一致的,能够直接用geth或是remix模拟估算gas cost。浏览器

以前一直没把这个问题搞清楚,因此干脆作个试验看一下.bash

remix浏览器下方有个可执行的log页面,能够detail以及debug,很是方便。微信

有gas cost的地方有两个地方,transaction cost以及 execution cost,這两个有什么不一样呢?能够參考一下他们的源码。app

简单说一下: transaction cost指的是将交易送至ethereum blockchain所耗费的cost,是基于data size的大小,部署合约时就是基于合约內容的大小. execution cost指的是虚拟机(VM)执行所需的cost,而在部署合约时,会去执行建構子以及一些初始化的工做.函数

在这里作一个简单的合约试验:oop

contract Test {

bytes32 public tmp;

function test(

bytes32 input,

uint num

)

constant returns (bytes32){

bytes32 result = input;

for(uint i = 0; i < num; i++) {

result = sha3(result);

}

}

function set(bytes32 input, uint num) {

tmp = test(input, num);

} }
复制代码

若是直接呼叫constant function的话,由于是由自己节点去计算不会更改到区块链上的值,是不会消耗gas的,可是若是是由一个通常合约(非constant function call)去呼叫一个constant function的話,由于让矿工来计算constant function,因此会消耗gas.区块链

上面的简单合约中,我让test函数对第一个bytes32参数作sha3,第二个uint参数表明作几回loop,我分別对set函数和test函数带入10以及1000的参数,結果以下.ui

set(“0x63d7db5ce060b288ecf5390594d5969bc1a206ceeb24df31cffcc8876df5e44b”, 10)

transaction cost:30628execution

cost:6988 
复制代码
set(“0x63d7db5ce060b288ecf5390594d5969bc1a206ceeb24df31cffcc8876df5e44b”, 1000)

transaction cost:196022

execution cost:172318
复制代码
test(“0x63d7db5ce060b288ecf5390594d5969bc1a206ceeb24df31cffcc8876df5e44b”, 10)

transaction cost:25663 (cost only applies when called by a contract)

execution cost:2023 (cost only applies when called by a contract) 

复制代码
test(“0x63d7db5ce060b288ecf5390594d5969bc1a206ceeb24df31cffcc8876df5e44b”, 1000)

transaction cost:191057(cost only applies when called by a contract)

execution cost:167353(cost only applies when called by a contract)
复制代码

ps:用transaction cost减去execution cost的话1, 3获得23640,2, 4获得23704spa

大体上就是这样一个过程.发现参数设定成1000时,也会形成transaction cost的提升.(初步猜测加上ps的计算:transaction cost中是已经包含了execution cost,一并计算在最后要支付给miner的fee,由于每一个相减结果都差很少)debug

另外geth的estimateGas的之因此会不太准确是由于一些不肯定性的operator操做会不一样,好比说,在一个contract中,如果blockhash的尾数是奇数,他就去执行会消耗大量gas的合约,反之则去执行hello world合约,因此他的gas cost很大的状况下是一半一半.

因此永远要记得设定一个合理的gas limit来防止本身遭受恶意攻击.

另外建议能够参考traceTransaction指令,能够看每一個opcode的gas cost. 为了要确认矿工处理transaction的状况,在ropsten testnet上作个简单的试验.首先在ropsten faucet上拿一点儿ether来玩,而后在metamask上送出交易,由于ropsten是模拟pow的环境,因此我相信应该会是正确的数字.

重要的话再说一次结论:Etherscan上transaction info中有个gas used by txn,结果跟remix给的结果以及geth中getTransactionReceipt的gasUsed给的结果都会是一致的,之后能够直接用geth或是remix模拟估算gas cost.

参考资料:以太坊DApp开发实战入门

能够加微信拉以太坊技术群聊。

相关文章
相关标签/搜索