以太坊如何估計估算計算gas?Etherscan上transaction info中有個gas used by txn,結果跟remix給的結果以及geth中getTransactionReceipt的gasUsed給的結果都會是一致的,能夠直接用geth或是remix模擬估算gas cost。git
以前一直沒把這個問題搞清楚,因此乾脆作個試驗看一下.github
remix瀏覽器下方有個可執行的log頁面,能夠detail以及debug,很是方便。瀏覽器
有gas cost的地方有兩個地方,transaction cost以及 execution cost,這兩個有什麼不一樣呢?能夠參考一下他們的源碼.微信
簡單說一下: transaction cost指的是將交易送至ethereum blockchain所耗費的cost,是基於data size的大小,部署合約時就是基於合約內容的大小. execution cost指的是虛擬機(VM)執行所需的cost,而在部署合約時,會去執行建構子以及一些初始化的工做.app
在這裏作一個簡單的合約試驗:函數
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.oop
上面的簡單合約中,我讓test函數對第一個bytes32參數作sha3,第二個uint參數表明作幾回loop,我分別對set函數和test函數帶入10以及1000的參數,結果以下.區塊鏈
set(「0x63d7db5ce060b288ecf5390594d5969bc1a206ceeb24df31cffcc8876df5e44b」, 10) transaction cost:30628 execution 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獲得23704ui
大體上就是這樣一個過程.發現參數設定成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.
1.適合區塊鏈新手的以太坊DApp開發:
http://xc.hubwiz.com/course/5a952991adb3847553d205d1
2.用區塊鏈、星際文件系統(IPFS)、Node.js和MongoDB來構建以太坊DApp電商平臺:
http://xc.hubwiz.com/course/5abbb7acc02e6b6a59171dd6
若是想加入以太坊技術開發羣能夠加微信拉你入羣。