Code has been added to clipboard!

Solidity Function Modifiers Example

Example
pragma solidity ^0.4.11;

contract isOwned {
    function isOwned() { owner = msg.sender; }
    address owner;

    // The contract here will only define a modifier but will not 
    // use it - derived contracts are going to utilize it.
    // The body of the function is inserted where the special 
    // symbol "_;" in the modifier's definition appears.
    // That means that when the owner will call this function, 
    // the function will get executed and otherwise, an exception 
    // will be thrown.
    modifier ownerOnly {
        require(msg.sender == owner);
        _;
    }
}

contract mortal is isOwned {
    // The contract "mortal" will inherit the modifier "ownerOnly" 
    // from the contract "isOwned" and apply it to the function "close"
    // that will cause calls to "close" only affect if
    // the stored owner makes them.
    function close() ownerOnly {
        selfdestruct(owner);
    }
}

contract priced {
    // Modifiers may also receive arguments of their own:
    modifier itCosts(uint price) {
        if (msg.value >= price) {
            _;
        }
    }
}

contract Registration is priced, isOwned {
    mapping (address => bool) addressesRegistered;
    uint price;

    function Registration(uint initialPrice) { price = initialPrice; }

    // The keyword "payable" is crucial here, else the function 
    // will automatically reject all Ether that gets 
    // sent to it.
    function Registration() payable itCosts(price) {
        addressesRegistered[msg.sender] = true;
    }

    function priceChange(uint _price) ownerOnly {
        price = _price;
    }
}

contract Mutex {
    bool isLocked;
    modifier noReentrance() {
        require(!isLocked);
        isLocked = true;
        _;
        isLocked = false;
    }

    /// The function here is protected by mutex, meaning that
    /// reentrant will call from inside msg.sender.call, being unable to call func again.
    /// The statement `return 7` will assign 7 to the value being returned but still
    /// execute the statement `isLocked = false` inside the modifier.
    function func() noReentrance returns (uint) {
        require(msg.sender.call());
        return 7;
    }
}