Published on

solidity 纯计算函数(pure)不消耗gas

Authors

go ethereum - If view or pure function doesn't cost any gas, would they be abused/free ride? - Ethereum Stack Exchange

自己外部调用,不消耗gas,只消耗相关节点的计算资源。如果用合约调用则会消耗gas

Storage | Address 0x4bf093e8995abca206ad223cf65ffcec17ceb571 | BscScan 自己部署的实例合约,核心代码为for循环,可以通过count参数传入,当循环过多时会出现 “Error: Returned error: out of gas”。 每个节点应该有gas limit上限,超过这个值就会报错。

SourceCode

/**
 *Submitted for verification at testnet.bscscan.com on 2023-05-09
*/

pragma solidity >=0.7.0 <0.9.0;

/**
 * @title Storage
 * @dev Store & retrieve value in a variable
 * @custom:dev-run-script ./scripts/deploy_with_ethers.ts
 */
contract Storage {

    uint256 number;

    /**
     * @dev Store value in variable
     * @param num value to store
     */
    function store(uint256 num) public {
        number = num;
    }

    /**
     * @dev Return value 
     * @return value of 'number'
     */
    function retrieve() public view returns (uint256){
        return number;
    }

    function add(uint256 a, uint256 b, uint count) public pure returns (uint256){
         for (uint i = 0; i < count; i++) {
             a+b;
         }
        return a+b;
    }
}