使用ethereum browser計算gas cost

Brian Po-han Chen
Taipei Ethereum Meetup
5 min readOct 23, 2017

因為CW大大覺得remix團隊一直有在更新,所以建議我使用remix來做估算gas cost,之前腦子裡一直有個疑問沒有釐清楚,所以乾脆做個小實驗來驗證一下.

remix瀏覽器下方有個執行的log頁面,可以detail以及debug,非常方便呢

有gas cost的地方有兩處,transaction cost以及 execution cost,這兩個有什麼不同呢?可以參考一下他們的source code

簡單說明一下:
transaction cost指的是說將交易送至ethereum blockchain所耗費的cost,基於data size的大小,部署合約時就是基於合約內容大小.
execution cost指的是說虛擬機(VM)執行所需的cost,而在部署合約時,會去執行建構子以及一些初始化的工作.

這邊做了一個簡單的合約實驗

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的參數,結果如下.

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得到23704

大致上就是這樣.發現參數設定成1000時,也會造成transaction cost的提高.(不負責任猜測加上ps的計算:transaction cost中是有包含execution cost,一並計算在最後要付給miner的fee,因為每個相減結果都差不多)

(補充)
CW大大請我補充geth的estimateGas的狀況,之所以estimateGas會不太精準是因為一些不確定性的operator實作會不一樣,譬如說,在一個contract中,若是blockhash的尾數是奇數,他就去執行會耗大量gas的合約,反之則去執行hello world合約,所以他的gas cost很大的機會是一半一半.

所以永遠要記得設定一個合理的gas limit來防止自己遭受惡意攻擊.

參考自:https://ethereum.stackexchange.com/questions/266/what-are-the-limitations-to-estimategas-and-when-would-its-estimate-be-considera

(補充2)
跟咏宸大大討論了gas cost的問題,他建議我可以參考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.

--

--