委托投票相的功能模块相对比较简单,只用写一个函数就可以完成。
需要实现的功能要求如下,
1>委托者未投票
2>不能委托给自己
3>不能循环投票
委托者在委托投票之前,需要先判断下,要求委托者未投票,
require(!sender.voted, "You already voted.");
不能委托给自己也比较容易实现,只要做下判断即可,
require(to != msg.sender, "Self-delegation is disallowed.");
不能循环投票的实现,就稍微有点烧脑,
while (voters[to].delegate != address(0))
{
to = voters[to].delegate;
require(to != msg.sender, "Found loop in delegation.");
}
整体代码如下图,
编译没有出错。
部署后测试下,
委托投票正常。
需要注意的是,存储这里分为两种变量,一种storage,另一种memory。前一种是存储在区块链上,后一种是临时存储,打个比方,你可以简单理解为,前一个storage存储在硬盘,后一种是临时变量存储在内存。