权限控制 / 学习智能合约#13

权限控制 / 学习智能合约#13

owner.jpg

现实中有很多不同的权限,比如说你可以花自己的钱,别人的钱你就花不了,这说明你没有别人的权限。在智能合约中也可以同样定义权限以得到不同的控制级别。

在智能合约中可以设置所有者、管理员,对它们赋予不同的权限,控制不同的操作。本质上就是设置函数修改器,只有符合条件的人员才能调用函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
pragma solidity >=0.4.24 <0.7.0;

contract AccessControl {
address public owner; //所有者
address[] admins; //管理员列表
uint public x;

constructor() public {
owner = msg.sender;
}

function isAdmin() public view returns(bool){
//遍历管理员列表以判断是不是管理员
for(uint i = 0; i < admins.length; i ++){
if(msg.sender == admins[i]){
return true;
}
}
return false;
}

modifier onlyOwner() {
require(msg.sender == owner);
_;
}


modifier onlyAdmins() {
require(isAdmin());
_;
}


function addAdmin(address a) public onlyOwner{
//只有所有者才能添加管理员
admins.push(a);
}

function set(uint a) public onlyAdmins{
//只有管理员才能调用此函数
x = a;
}
}

如上代码所示,就是把名单先存起来,设计出函数修改器(类似于python的装饰器)以实现不同的权限。


This page is synchronized from the post: ‘权限控制 / 学习智能合约#13’

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×