以太坊智能合约开发(五):Solidity成绩录入智能合约实验
1 编写智能合约
每个学生分别部署合约Student.sol ,保证只有自己可以修改姓名。老师部署合约StudentScore.sol,用于录入学生成绩,查询学生信息。查询学生信息时,需要调用学生部署的合约Student.sol。 student.sol合约,用于学生对自己信息进行管理。
pragma solidity ^0.4.0;
contract Student{
string studentID;
string studentName;
address owner;
}
- 声明构造函数,在构造函数中将owner设置为调用者的address:
constructor(string _studentID, string _stdentName) public{
studentID = _studentID;
studentName = _stdentName;
owner = msg.sender;
}
- 声明函数修饰器,可以将其加在函数中,在函数执行前进行判断,来检查调用者是否为学生本人,只有本人才能调用该函数:
modifier onlyOwner(){
require(msg.sender == owner,"only owner can call this function");
_;
}
- get和set方法,其中set方法加入了函数修饰器:
function getStudentIDandName() public constant returns(string,string) {
return (studentID,studentName);
}
function setStudentIDandName(string _studentID,string _studentName) public onlyOwner {
studentID = _studentID;
studentName = _studentName;
}
Teacher.sol合约,用于录入、查询学生成绩
pragma solidity ^0.4.11;
import "./Student.sol";
- 学生的相关成绩作为状态变量,totalScore为全班总成绩,studentCount全班学生数量,owner部署合约的账户地址。同时声明映射studentAddrMap,studentScoreMap,将学生ID分别映射为学生地址和学生成绩。事件studentNotExistsEvent用于存储学生ID号
contract StudentScore{
uint totalScore;
uint studentCount;
address owner;
mapping(string => address) studentAddrMap;
mapping(string => uint) studentScoreMap;
event studentNotExistsEvent(string studentID);
}
- 声明自定义修饰符onlyOwner,只有老师地址才能执行这些函数。
modifier onlyOwner(){
require(msg.sender == owner,"only owner can call this function");
_;
}
- 函数addStudentScore,modifyScoreByStudentId分别用于老师添加或修改学生成绩:
function addStudentScore(string studentID, address student, uint score) public onlyOwner {
studentAddrMap[studentID] = student;
studentScoreMap[studentID] = score;
totalScore += score;
studentCount ++;
}
function modifyScoreByStudentId(string studentID, uint score) public onlyOwner{
if(!studentExists(studentID)) {
studentNotExistsEvent(studentID);
return;
}
totalScore -= studentScoreMap[studentID];
studentScoreMap[studentID] = score;
totalScore += score;
}
- 函数getAvgScore用于查询全班学生平均成绩,函数studentExists用于判断学生ID是否存在,函数getScoreByStudentID用于学生查询自己的成绩。
function getAvgScore() public view returns(uint){
return totalScore / studentCount;
}
function studentExists(string studentID) public view returns(bool){
address student = Student(studentAddrMap[studentID]);
if(student == 0x00){
return false;
}else{
return true;
}
}
function getScoreByStudentID(string studentID) public constant returns(string, string, uint){
if(!studentExists(studentID)) {
studentNotExistsEvent(studentID);
return;
}
Student student = Student(studentAddrMap[studentID]);
var studentName = student.getStudentName();
uint score = studentScoreMap[studentID];
return(studentID, studentName, score);
}
|