CHALLENGER : BNB 체인 해커톤
solidity modifier | Ownable 이해하기
EDDO
2022. 12. 6. 01:05
# modifier란?
한국말로 그냥 번역하자면 "변경자"인데, 뭘 변경한다는 건지 잘 모르겠다.
사용하는 예시를 보면 보통 함수의 실행 전에 조건을 체크하는 용도로 사용되고 있는 것 같다.
예를 들어, onlyOwner 를 살펴보자.
onlyOwner modifier 를 활용하여, 함수를 실행하기 전에 함수를 실행하는 사람이 소유자인지 확인을 할 수 있다.
OpenZeppline에서 Ownable을 구현해 놓은 라이브러리가 있는데, 아래와 같이 onlyOwner가 modifier로 구현된 것을 알 수 있다.
코드를 살펴보면 아래와 같다.
abstract contract Ownable is Context {
address private _owner;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
...
}
modifier onlyOwner() 를 보면 _checkOwner() 함수를 실행하고 _ (언더바) 를 실행한다.
_ (언더바) 가 modifier를 사용한 함수의 실행 위치가 된다.
예를 들어 아래와 같이 onlyOwner를 사용하게 되면, _checkOwner() 함수가 실행되고나서 setWhitelist 함수가 실행되게 된다.
contract mintNFT{
function setWhitelist(address _whitelist, uint _amount) public onlyOwner{
whitelist[_whitelist] = _amount;
}
...
}
반응형