Solidity의 modifier 와 payable

Kai Park
5 min readJun 28, 2017

Solidity를 공부 할 때 제가 참고하는 것은 크게 공식 DocumentState of the DAPPs, ICO들의 소스 입니다.

공식문서는 Solidity의 기본부터 심화까지 모든 것을 담고 있고, State of the dapps 의 경우 현재 진행되고 있는 거의 모든 dapp들을 볼수 있고, 해당 소스도 참고하면서 공부도 해볼수 있습니다.

ICO 들의 소스의 경우 ERC20 토큰의 제일 충분한 예시입니다.

그리고 해당 소스들을 보면 특이한 점들이 있습니다.

pragma solidity 0.4.11;import "TokenFactory.sol"contract CrowdSaleSample {    TokenFactory public token;
mapping (address => uint256) balances;
address public owner;
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function FLToken(){
owner = msg.sender;
}
function() payable {
if (now > endBlock) throw;
token.distribute(msg.sender);
}
function distribute(address depositor) onlyOwner {
balances[depositor] += 100;
}

매우 간단한 소스이고, function 이라는 것은 어느 언어에서든지 있는 개념입니다.

하지만 modifier 라는 것은 조금 생소했고, function 뒤에 리턴값이 아닌 것이 위치해있습니다.

그래서 Document 에서 해당 사항을 찾아봤습니다.

Function ModifiersModifiers can be used to easily change the behaviour of functions. 
For example, they can automatically check a condition prior to executing the function.
Modifiers are inheritable properties of contracts and may be overridden by derived contracts.
-> modifier 는 function의 실행(행동)을 쉽게 변경가능하도록하며, function 실행의 조건을 체크 할수 있다

위에 예제에서 modifier 는 한번은 정의, 그리고 또 한번은 function 뒤에 두번 적혀있습니다.

간단하게 본다면 distribute function 을 실행하기 전에 onlyOwner 라는 것을 미리 체크를 해보다는 겁니다.

modifier onlyOwner {
// msg.sender(실행하려는 Address)와 owner(Contract 를 생성한 Address) 같아야 합니다.
require(msg.sender == owner);
_;
}

Rails 에서는 BeforeFilter 라는 개념이 있습니다.

저는 이것과 비슷한 개념이라고 이해를 했습니다.

함수를 실행하기 전에 미리 필터링을 시켜준다는 개념(?)(저만의 정의입니다.)

그러면 다양하게 적용을 할수 있을 겁니다.

modifier  startCheck {
require(block.number >= startBlock);
_;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier crowdEndingCheck {
require(!isCrwoldEnding);
_;
}

등등등 중복적으로 실행이 필요하지만 간단하다면 modifier 로 정의해서 사용해보면 될겁니다.

그리고 payable

Reddit 공식 문서에서 보면 payable 에 대한 설명이 나옵니다.

// Reddit 
functions reject ether by default and require the new "payable" modifier if they want to accept it
// Solidity Document
It is important to also provide the
"payable" keyword here, otherwise the function will
automatically reject all Ether sent to it.

Default 로 모든 function 에서는 이더 전송에 관한 모든 것을 Reject 시키며, payable(아마도 내장 modifier 인 것 같네요) 가 붙지 않으면 모든 전송을 자동으로 Reject 시킨다.

이더 전송에 관련된 function 이라면 무조건 붙여야지만 전송이 가능하도록 해놓은 거 같네요.

modifier 와 payable..

둘 다 생소했지만 Solidity에서는 매우 필요한 요소 인듯 싶네요.

잘못된 부분은 댓글로 남겨주시면 수정하도록 하겠습니다.

Donation

기부는 사랑입니다.

  • Ƀ BTC : 16MdVNJgvGYbVuaC6KrjGNy2RCrNsaPaZz
  • Ξ ETH : 0x5debb97a6Cc1Fdf686a3C6aA804a623a21deD73c

개발자에게 Starize 도 사랑입니다.

--

--