iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 6
1
影片教學

Smart Contract 實戰教學系列 第 6

Function Modifiers

  • 分享至 

  • xImage
  •  

當我們有需求是多個 function 在執行前需要做檢查或者預先處理的時候,除了每次都在開頭複製一份一樣的程式碼以外,我們還有另外一種選擇 - Function Modifiers

昨天的合約:

	function setName(string _name) public returns (string) {
	    /* Only owner has the permission to modify its name. */
		if (msg.sender == owner) {
			name = _name;
		} else {
			revert("Permission denied.");
		}
		return name;
	}

抽出 funciton modifiter 之後,是不是看起來更直覺了呢?:

    modifier onlyOwner() {
        require(msg.sender == owner, "Permission denied.");
        _;
    }
	function setName(string _name) public onlyOwner returns (string) {
	    /* Only owner has the permission to modify its name. */
		name = _name;
		return name;
	}

最後的範例,有 parameters 的 modifier 用法:

pragma solidity ^0.4.25;

contract StateVariables {
	string name;
	uint public rename_counter;
	address owner;

	constructor() public {
		/* Initailize default state. */
		name = "unknown";
		owner = msg.sender;
		rename_counter = 0;
	}

	modifier checkOwner(address _addr) {
		require(_addr == owner, "Address is not the owner.");
		rename_counter += 1;
		_;
	}

	function setName(string _name) public checkOwner(msg.sender) returns (string) {
		name = _name;
		return name;
	}

	function getName() public view returns (string) {
		return name;
	}
}

本日影片:
https://youtu.be/v1OEwKM1-Zg

Smart Contract 實戰教學播放清單:
https://www.youtube.com/playlist?list=PLHmOMPRfmOxSJcrlwyandWYiuP9ZAMYoF


上一篇
State Variables
下一篇
Assert, Require, Revert
系列文
Smart Contract 實戰教學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言