Solidity

為什麼視圖/純函式需要gas?

  • December 9, 2017
pragma solidity ^0.4.11;

contract Test {
   function toBytes(address a) public pure returns (bytes b) {
       assembly {
           let m := mload(0x40)
           mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
           mstore(0x40, add(m, 52))
           b := m
      }
   }

   function toBytes(uint _num) public pure returns (bytes _ret) {
       assembly {
           _ret := mload(0x10)
           mstore(_ret, 0x20)
           mstore(add(_ret, 0x20), _num)
       }
   }

   function test(uint num1, uint num2) public view returns (bytes) {
       bytes memory a1 = toBytes(msg.sender);
       bytes memory a2 = toBytes(num1);
       bytes memory a3 = toBytes(num2);
       bytes memory ret = new bytes(a1.length + a2.length + a3.length);
       uint x = 0;

       for (uint i = 0; i < a1.length; i++) {
           ret[x++] = a1[i];
       }

       for (i = 0; i < a2.length; i++) {
           ret[x++] = a2[i];
       }

       for (i = 0; i < a3.length; i++) {
           ret[x++] = a3[i];
       }

       return ret;
   }
}

我嘗試了 Remix 中的程式碼,但它總是給我一個錯誤:

call to browser/test.sol:Test.test errored: VM error: out of gas.
out of gas  The transaction ran out of gas. Please increase the Gas Limit.
       Debug the transaction to get more information.

,即使我將氣體限制修改為非常大的值。

我認為視圖/純函式不會影響區塊鏈,因此它們不是由礦工執行的。因此,它們不消耗氣體。

我錯了嗎?如果我錯了,如何使程式碼有利於執行?

非常感謝!

是的,pure/view 函式與事務綁定到相同的氣體約束。他們需要氣體來執行。唯一的區別是不支付gas費用。

引用自:https://ethereum.stackexchange.com/questions/32913