pragma solidity ^0.4.11;
contract owned {
function owned() public { owner = msg.sender; }
address owner;
// This contract only defines a modifier but does not use
// it: it will be used in derived contracts.
// The function body is inserted where the special symbol
// `_;` in the definition of a modifier appears.
// This means that if the owner calls this function, the
// function is executed and otherwise, an exception is
// thrown.
定義了一個(gè)modifier但是沒(méi)有使用肃拜,將在繼承的合約中使用
函數(shù)體將在特殊符號(hào) _ 出現(xiàn)的位置被插入
這里代表的是只有Owner調(diào)用這個(gè)方法時(shí)才會(huì)被執(zhí)行晃听,否則報(bào)錯(cuò)
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract mortal is owned {
// This contract inherits the `onlyOwner` modifier from
// `owned` and applies it to the `close` function, which
// causes that calls to `close` only have an effect if
// they are made by the stored owner.
這個(gè)合約從owned繼承了onlyOwner的modifier鲜侥,應(yīng)用在close方法上
這將造成只有Owner才能調(diào)用close方法
function close() public onlyOwner {
selfdestruct(owner);
}
}
contract priced {
// Modifiers can receive arguments:
modifiers可以接受參數(shù)
modifier costs(uint price) {
if (msg.value >= price) {
_;
}
}
}
contract Register is priced, owned {
mapping (address => bool) registeredAddresses;
uint price;
function Register(uint initialPrice) public { price = initialPrice; }
// It is important to also provide the
// `payable` keyword here, otherwise the function will
// automatically reject all Ether sent to it.
function register() public payable costs(price) {
registeredAddresses[msg.sender] = true;
}
function changePrice(uint _price) public onlyOwner {
price = _price;
}
}
contract Mutex {
bool locked;
modifier noReentrancy() {
require(!locked);
locked = true;
_;
locked = false;
}
/// This function is protected by a mutex, which means that
/// reentrant calls from within `msg.sender.call` cannot call `f` again.
/// The `return 7` statement assigns 7 to the return value but still
/// executes the statement `locked = false` in the modifier.
function f() public noReentrancy returns (uint) {
require(msg.sender.call());
return 7;
}
}
那么modifier在solidity中做的是什么工作呢涯雅?
答案就是給繼承這個(gè)modifier修飾的function加上一個(gè)特定的約束外构,比如
modifier isOwner() {
if (msg.sender != owner) {
throw;
}
_; // 繼續(xù)執(zhí)行余下的代碼體(其實(shí)就是isOwner里的實(shí)際代碼)
}
doSomething() isOwner {
// 將會(huì)檢查調(diào)用者是不是Owner
// code
}