1. modifier 的作用
modifier 可以轻松的改变方法的行为,例如,可以在一个方法执行之前先检查是否满足某些条件,如果满足才继续执行。
2. 示例
(1)合约代码
contracts/Coursetro.sol
pragma solidity ^0.4.22;
contract Coursetro {
string fName;
uint age;
address owner;
event Instructor(
string name,
uint age
);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
constructor() public {
owner = msg.sender;
}
function setInstructor(string _fName, uint _age) onlyOwner public {
fName = _fName;
age = _age;
emit Instructor(_fName, _age);
}
function getInstructor() view public returns (string, uint) {
return (fName, age);
}
}
(2)测试代码
test.js
var Web3 = require("web3");
var web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider("http://localhost:7545"));
// 使用 accounts[0] 构建合约
web3.eth.defaultAccount = web3.eth.accounts[0];
var CoursetroContract = web3.eth.contract(abi);
var Coursetro = CoursetroContract.at('0x0b531928a196781f3c3b51b15e2b8d9d360317a4');
// 使用 accounts[0] 调用,没问题
console.info("accounts[0] call ...");
Coursetro.setInstructor("a", 1, (err, res) => {
if (err) {
console.error(res);
}
});
// 使用 accounts[1] 调用,会报错
console.info("accounts[1] call ...");
web3.eth.defaultAccount = web3.eth.accounts[1];
Coursetro.setInstructor("b", 2, (err, res) => {
if (err) {
console.error("oh no !!!");
}
});
(3)运行
$ node test/test.js
accounts[0] call ...
accounts[1] call ...
oh no !!!