区块链学堂(29):Modifiers

Modifiers can be used to easily change the behaviour of functions, for example to automatically check a condition prior to executing the function. They are inheritable properties of contracts and may be overridden by derived contracts. 引用自here

一个使用modifier的例子

pragma solidity 0.4.10;
contract demo {
    uint public deadline;
    function demo() {
        deadline = now;
        deadline += 10;
    }

    modifier afterDeadline {
        if (now <= deadline) throw;
        _;
    }

    function f() afterDeadline returns (string s) {
        return "afterDeadline";
    }

    function g() afterDeadline returns (uint n) {
        n = 100;
    }
}
  • 从上面的例子中可以看到,我们先在构造函数中,给deadline赋予一个值。在当前时间+10s
  • 然后modifier afterDeadline, 必须要当前时间过了10s,才不抛出异常
  • 然后我们可以在很多方法中使用modifier afterDeadline(). 从而使得代码非常简洁和美观。

另一个例子,给上一节中的代币合约中添加Modifier

  • Step 1: 首先定义一个modifier
      modifier onlyMinter {
        if (msg.sender != minter) throw;
        _;
      }
    
  • Step 2: 新增一个新的 function mint2()
    function changeMinter(address _to) onlyMinter {
      minter = _to;
    }

对比一下之前的function mint()

    function mint(address receiver, uint amount) {
        if (msg.sender != minter) throw;
        balances[receiver] += amount;
    }

很明显可以看到,通过modifier,在执行主函数之前,先进行一个条件检查。通过modifier,可以使代码变得很美。

  • Step 3: 添加个function changeMinter()
      function changeMinter(address _to) onlyMinter {
        minter = _to;
      }
    
上一节代码加上Step 1-3后的完整代码如下:
pragma solidity 0.4.7;

contract Coin {
    address public minter;
    mapping (address => uint) public balances;

    event Sent(address from, address to, uint amount);

    function Coin() {
        minter = msg.sender;
    }

    function mint(address receiver, uint amount) {
        if (msg.sender != minter) throw;
        balances[receiver] += amount;
    }

    function send(address receiver, uint amount) {
        if (balances[msg.sender] < amount) return;
        balances[msg.sender] -= amount;
        balances[receiver] += amount;
        Sent(msg.sender, receiver, amount);
    }

    //对挖矿使用onlyOwner
    modifier onlyMinter {
      if (msg.sender != minter) throw;
      _;
    }

    function mint2(address receiver, uint amount) onlyMinter {
      balances[receiver] += amount;
    }

    function changeMinter(address _to) onlyMinter {
      minter = _to;
    }
}

QQ群:559649971 (区块链学堂粉丝群)
个人微信:steven_k_colin

获取最新区块链咨询,请关注《以太中文网》微信公众号:以太中文网

 

为您推荐

发表评论

1,641条评论

  1. Pingback: My Homepage
  2. Pingback: juegos de friv
  3. Pingback: must watch
  4. Pingback: Eavestrough Cleaning
  5. Pingback: adme
  6. Pingback: sports betting
  7. Pingback: slot machines
  8. Pingback: Corporate Events
  9. Pingback: Foot Locker Coupons
  10. Pingback: iraqi Engineer
  11. Pingback: eng
  12. Pingback: GVK Bioscinces
  13. Pingback: real estate agent
  14. Pingback: daftar sbmptn online
  15. Pingback: adwords guaranteed
  16. Pingback: Free UK Chat Rooms
  17. Pingback: pendaftaran cpns 2018
  18. Pingback: freemoviesz
  19. Pingback: claw
  20. Pingback: tutorialcup
  21. Pingback: sciences
  22. Pingback: top anabolic steroids
  23. Pingback: fingering orgasm
  24. Pingback: 2018 new casinos 2018
  25. Pingback: use this link
  26. Pingback: UK Chat
  27. Pingback: briciolefavole.com
  28. Pingback: lequipe can
  29. Pingback: Free Teen Chat
  30. Pingback: PK Study
  31. Just wish to say your article is as astonishing. The
    clarity for your post is just cool and that i can think you are knowledgeable in this subject.
    Fine together with your permission allow me to clutch your feed to keep up to date with forthcoming post.
    Thank you a million and please carry on the rewarding work.

  32. Simply wish to say your article is as astounding.

    The clarity on your put up is just great and i could think you’re knowledgeable in this subject.
    Well along with your permission allow me to seize your RSS
    feed to keep up to date with forthcoming post. Thanks 1,000,000 and please continue
    the rewarding work.

  33. ТОП качество видео роликов собраны в одном месте. Никаких регистраций и прочей ерунды.
    http://ru.sex.com/user/milfs90s/top-rated

    Если есть желание, то переходи по ссылке и смотри популярные видео, клипы, приколы в самом высоком качестве.

  34. Admiring the commitment you put into your website and in depth
    information you provide. It’s awesome to come across
    a blog every once in a while that isn’t the same out of date rehashed material.
    Great read! I’ve saved your site and I’m including your RSS feeds to my Google account.

  35. Добро пожаловать развратник любого пола и возраста. Здесь ты найдешь что искал.

    Пышногрудые красавицы и похотливые малышки ждут тебя, нетерпеливо теребя свою киску в каждом ролике, в каждой категории. Бесчисленное множество мулаток, негров и славянских девушек хочет поразвлечься не меньше тебя. Они ищут своих ебарей и находят не оставляя щелку томиться в одиночестве, а мы все это тщательно отбираем, сортируем и выгружаем на сайт. Даже находясь в темной комнате. Уютное, томное оформление сайта не выдаст вас и ваших тайных желаний. Умный сайт РїРѕСЂРЅРѕ 365 скачать бесплатно адаптирован для всех устройств, что делает его ценность в глазах пользователя еще выше. Теперь даже в дороге вы не останетесь без любимых роликов, без которых так тяжело уснуть.
    На сайте, вы сами становитесь немножко модератором, так как получаете возможность просмотрами и голосами выводить ролики в раздел «Популярные». В нем находятся ролики отобранными нашими посетителями. Так же оставляйте комментарии и начинайте общение, многих точно обрадует возможность свободно выражаться под видео. Рядом находится раздел «Топовые», в нем расположены только лучшие ролики с тысячами просмотров. Они не оставят равнодушными обычного человека. В них нет четкой категории, там собраны абсолютно разные жанры наилучшего качества.
    Заходите на Porno365tube.com. каждый день и радуйте себя отборной, сочной порнухой!

  36. Hi there would you mind letting me know which webhost you’re
    working with? I’ve loaded your blog in 3 different internet browsers and
    I must say this blog loads a lot faster then most.
    Can you recommend a good internet hosting provider at a fair price?
    Thanks a lot, I appreciate it!

  37. Hi! This is my first visit to your blog! We are a group
    of volunteers and starting a new initiative in a community in the same niche.

    Your blog provided us valuable information to work on. You have done a extraordinary
    job!

  38. I was just searching for this info for a while. After 6 hours of continuous Googleing,
    at last I got it in your site. I wonder what is the lack of Google
    strategy that do not rank this type of informative sites in top of the list.
    Generally the top sites are full of garbage.

  39. s eyes because he watches you being lead faraway from him on this occasion to the gentle sway from the
    waltz. And speaking about one of the most prominent sources of
    entertainment, TV shows are the ones that stay ahead in race.
    A little patience might reward you which has a nice picture of an frog or even a dragon fly.

  40. Hi, There’s no doubt that your web site could be having web browser compatibility issues.
    Whenever I take a look at your web site in Safari, it looks fine but when opening in I.E., it
    has some overlapping issues. I merely wanted to give you
    a quick heads up! Besides that, wonderful site!

  41. Hey there outstanding website! Does running a blog like this require a lot of work?
    I have absolutely no knowledge of computer programming but
    I was hoping to start my own blog in the near future. Anyways, should you have any recommendations or tips for new blog owners please share.
    I know this is off subject nevertheless I just wanted to ask.
    Thank you!

  42. Greetings from Los angeles! I’m bored to tears at work so I decided to check
    out your site on my iphone during lunch break.
    I really like the knowledge you provide here and can’t wait to take a look when I get home.

    I’m amazed at how quick your blog loaded on my phone ..
    I’m not even using WIFI, just 3G .. Anyhow, good blog!

  43. Now that you be familiar with video editing and also the what you require you are prepared to start right onto
    your pathway of amateur filmmaker to professional director.

    ” It was President Theodore Roosevelt who had given it the name of White House in 1901. You need a special connector typically termed as a Fire wire or commonly known as as a possible IEEE 1394 high band connector.

  44. Hello! I could have sworn I’ve visited this web site before but after going through many of the posts I realized it’s new
    to me. Anyhow, I’m certainly pleased I stumbled upon it
    and I’ll be bookmarking it and checking back regularly!

  45. A motivating discussion is definitely worth comment.
    I do think that you ought to publish more about this subject matter,
    it may not be a taboo matter but generally folks don’t speak about these topics.
    To the next! Many thanks!!

  46. Undeniably imagine that that you said. Your favorite reason seemed to be at the web the easiest factor to remember of.
    I say to you, I certainly get annoyed while people consider concerns
    that they just don’t understand about. You managed to hit the
    nail upon the highest as smartly as defined out the
    whole thing with no need side-effects , people can take
    a signal. Will probably be again to get more. Thanks

  47. Pingback: james shoes exclusive
  48. Pingback: off lifestyle sneaker
  49. Pingback: nike roshe run mens
  50. Pingback: estrutura de redes
  51. Pingback: nike kd 9
  52. Pingback: nike fs lite run 4
  53. Pingback: nike kobe 5am
  54. Pingback: adidas copa
  55. Pingback: adidas x 173
  56. Pingback: vans sk8 slim leather
  57. Pingback: mexico world cup tee
  58. Pingback: nike shox outlet
  59. Pingback: nike shox
  60. Pingback: kd shoes
  61. Pingback: air jordan 11 concord
  62. Pingback: lacoste polo
  63. Pingback: ferragamo belt
  64. Pingback: nike air max
  65. Pingback: moncler gift set hat
  66. Pingback: cheap jordan shoes
  67. Pingback: kyrie irving shoes
  68. Pingback: Yeezy
  69. Pingback: jordan retro
  70. Pingback: kobe 11
  71. Pingback: baseball jerseys
  72. Pingback: golden goose sneakers
  73. Pingback: cat boots
  74. Pingback: s.oliver 48208
  75. Pingback: nike cortez women
  76. Pingback: moncler
  77. Pingback: stor h氓rklemme
  78. Pingback: yeezy boost 350 v2
  79. Pingback: nike air force
  80. Pingback: nike shoes
  81. Pingback: red sox decal
  82. Pingback: bulk knit caps
  83. Pingback: tenis chumbo asics
  84. Pingback: version er oplagt
  85. Pingback: talli keng盲t
  86. Pingback: Nike Air Max 90
  87. Pingback: foulard turquoise
  88. Pingback: white cowboy hat mens
  89. Pingback: quepe marinheiro r 30
  90. Pingback: jordan 1 banned cap
  91. Pingback: preloved adidas xplr
  92. Pingback: Nike Air Max 98 Femme
  93. Pingback: baby boys denim shirt
  94. Pingback: moncler pantalon
  95. Pingback: adidas flyers hoodie
  96. Pingback: parley x adidas ultra
  97. Pingback: womens riding boots
  98. Pingback: chuteira munique
  99. Pingback: jordan 13
  100. Pingback: air jordan 12
  101. Pingback: pre莽o chinelo rider
  102. Pingback: nike roshe run
  103. Pingback: nike shoes off
  104. Pingback: nike skyline vinted
  105. Pingback: street style regatas
  106. Pingback: koszulki vans allegro
  107. Pingback: kurs szycia dla
  108. Pingback: gucci watch
  109. Pingback: we-b-tv.com
  110. Pingback: tureckie_serialy
  111. Pingback: 00-tv.com
  112. Pingback: +1+
  113. Pingback: æóêè+2+ñåðèÿ
  114. Pingback: watch
  115. Pingback: ++++++
  116. Pingback: HD-720
  117. Pingback: 2020
  118. Pingback: Video
  119. Pingback: 1 2 3 4 5 6 7 8 9 10
  120. Pingback: wwin-tv.com
  121. Pingback: robe chic rose courte
  122. Pingback: crochet womens hat
  123. Pingback: robert meyer imdb
  124. Pingback: avon bayan 莽anta
  125. Pingback: payless nike shoes 6
  126. Pingback: vestido sereia azul
  127. Pingback: cheap biker jacket
  128. Pingback: fake og bred 4
  129. Pingback: nike shox
  130. Pingback: yeezy boost 350 v2
  131. Pingback: retro jordans
  132. Pingback: derrick rose videos
  133. Pingback: nylon swim shorts
  134. Pingback: tiny lace thong
  135. Pingback: nike foamposite
  136. Pingback: movies
  137. Pingback: nike air max 90
  138. Pingback: movies online
  139. Pingback: karan johar
  140. Pingback: Top Movies
  141. Pingback: Movies1
  142. Pingback: yeezy boost 350
  143. Pingback: 11 10 2019
  144. Pingback: jordan retro 12
  145. Pingback: n艖i ingruha 1015
  146. Pingback: yeezy boost 350
  147. Pingback: baby stud earrings
  148. Pingback: ncaa hats only 5
  149. Pingback: cheap jordans
  150. Pingback: yeezy boost 350
  151. Pingback: dobbs black big apple
  152. Pingback: nike react
  153. Pingback: anillo plata 925
  154. Pingback: smotretonline2015.ru
  155. Pingback: Serial smotret
  156. Pingback: kinokrad
  157. Pingback: kinokrad 2020
  158. Pingback: yeezy boost
  159. Pingback: duvet jackets sale
  160. Pingback: nike react
  161. Pingback: retro jordans
  162. Pingback: air max
  163. Pingback: casino
  164. Pingback: filmy-kinokrad
  165. Pingback: kinokrad-2019
  166. Pingback: filmy-2019-kinokrad
  167. Pingback: serial
  168. Pingback: bts fashion amazon
  169. Pingback: zx flux
  170. Pingback: nike air max
  171. Pingback: adidas nmd
  172. Pingback: birkin bag
  173. Pingback: jordan 11
  174. Pingback: cheap jordans
  175. Pingback: curry 4
  176. Pingback: nike lebron 15
  177. Pingback: puma mostro perf
  178. Pingback: hermes
  179. Pingback: nfl jerseys
  180. Pingback: balenciaga shoes
  181. Pingback: golden goose
  182. Pingback: poc trabec mtb helmet
  183. Pingback: nike foamposite
  184. Pingback: golden goose outlet
  185. Pingback: golden goose outlet
  186. Pingback: kinosmotretonline
  187. Pingback: yeezy boost 700
  188. Pingback: nba jerseys
  189. Pingback: balenciaga sneakers
  190. Pingback: coach outlet online
  191. Pingback: nike air max 270
  192. Pingback: nike air max
  193. Pingback: golden goose outlet
  194. Pingback: lebron james shoes
  195. Pingback: white crop tanks
  196. Pingback: longchamp bags
  197. Pingback: asics dame gt 1000 7
  198. Pingback: Tenisice Adidas hr
  199. Pingback: coach factory outlet
  200. Pingback: morgonrock i bomull
  201. Pingback: supreme
  202. Pingback: robe de fionsay
  203. Pingback: supreme clothing
  204. Pingback: menig soldat kostyme
  205. Pingback: coach outlet
  206. Pingback: supreme shirt
  207. Pingback: timberland outlet
  208. Pingback: floral dress ladies
  209. Pingback: nike lebron shoes
  210. Pingback: nike air max dames 1
  211. Pingback: nike off whtie
  212. Pingback: bl氓 papir diamant
  213. Pingback: adidas tubular
  214. Pingback: mbt shoes
  215. Pingback: womens nike gym shoes
  216. Pingback: supreme clothing
  217. Pingback: kd 12
  218. Pingback: hqcialismht.com
  219. Pingback: viagramdtrustser.com
  220. Pingback: yamaha piano clavier
  221. Pingback: rainbow vans toddler
  222. Pingback: reporter xs chain bag
  223. Pingback: pantaloncini errea
  224. Pingback: cucina gioco legno
  225. Pingback: saucony argento
  226. Pingback: skjorte agent shirt