Solidity Tutorial – View, Pure and Payable

solidity-tutorial-view-pure-constant

1.View 

This is generally the replacement for constant. It indicates that the function will not alter the storage state in any way

function viewState() public view returns(string) {
        //read the contract storage 
        return state;
    }

2.Pure 

This is even more restrictive, indicating that it won’t even read the storage state.

function pureComputation(uint para1 , uint para2) public pure returns(uint result) {
        // do whatever with para1 and para2 and assign to result as below
        result = para1 + para2;
        return  result;
    }

3.Payable

Payable functions can accept ether from callers. If sender does not provide ether, call may fail. Payable functions can only accept ether

function payMoney() public payable{
        amount += msg.value;
    }

4.Self-defined Modifier

A modifier can be used to change function behavior. For example: modifier could be used to check the condition before the execution of a function. A modifier can be inherited and can be overridden by derived contract.

//create a modifier that the msg.sender must be the owner
    modifier onlyOwner() {
        require(msg.sender == Owner, 'Not owner');
        _;
    }    

 //the owner can withdraw from the contract because payable was added to the state variable above
    function withdraw (uint _amount) public onlyOwner {
        Owner.transfer(_amount); 
    }

Note:

Constant is depricated solc 0.4.17, In Remix, you’ll get a warning when you use the old constant modifier
Using pure and view functions allows these functions to consume zero gas, because they are not modifying state.

Leave a Reply

Your email address will not be published. Required fields are marked *