区块链学堂(29):Modifiers

待我称王封你为后i 2022-06-02 05:38 343阅读 0赞

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的例子

  1. pragma solidity 0.4.10;
  2. contract demo {
  3. uint public deadline;
  4. function demo() {
  5. deadline = now;
  6. deadline += 10;
  7. }
  8. modifier afterDeadline {
  9. if (now <= deadline) throw;
  10. _;
  11. }
  12. function f() afterDeadline returns (string s) {
  13. return "afterDeadline";
  14. }
  15. function g() afterDeadline returns (uint n) {
  16. n = 100;
  17. }
  18. }
  • 从上面的例子中可以看到,我们先在构造函数中,给deadline赋予一个值。在当前时间+10s
  • 然后modifier afterDeadline, 必须要当前时间过了10s,才不抛出异常
  • 然后我们可以在很多方法中使用modifier afterDeadline(). 从而使得代码非常简洁和美观。

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

  • Step 1: 首先定义一个modifier

    1. modifier onlyMinter {
    2. if (msg.sender != minter) throw;
    3. _;
    4. }
  • Step 2: 新增一个新的 function mint2()

    function changeMinter(address _to) onlyMinter {

    1. minter = _to;
    2. }

对比一下之前的function mint()

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

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

  • Step 3: 添加个function changeMinter()

    1. function changeMinter(address _to) onlyMinter {
    2. minter = _to;
    3. }
上一节代码加上Step 1-3后的完整代码如下:
  1. pragma solidity 0.4.7;
  2. contract Coin {
  3. address public minter;
  4. mapping (address => uint) public balances;
  5. event Sent(address from, address to, uint amount);
  6. function Coin() {
  7. minter = msg.sender;
  8. }
  9. function mint(address receiver, uint amount) {
  10. if (msg.sender != minter) throw;
  11. balances[receiver] += amount;
  12. }
  13. function send(address receiver, uint amount) {
  14. if (balances[msg.sender] < amount) return;
  15. balances[msg.sender] -= amount;
  16. balances[receiver] += amount;
  17. Sent(msg.sender, receiver, amount);
  18. }
  19. //对挖矿使用onlyOwner
  20. modifier onlyMinter {
  21. if (msg.sender != minter) throw;
  22. _;
  23. }
  24. function mint2(address receiver, uint amount) onlyMinter {
  25. balances[receiver] += amount;
  26. }
  27. function changeMinter(address _to) onlyMinter {
  28. minter = _to;
  29. }
  30. }

原文:http://www.ethchinese.com/?p=1122

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

stevenkcolin.jpg

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

ethchinese.jpg

发表评论

表情:
评论列表 (有 0 条评论,343人围观)

还没有评论,来说两句吧...

相关阅读