Solidity 案例详解(四)投票智能合约

该合约为原创合约,功能要求如下
在⼀定时间能进⾏投票超过时间投票截⽌,并投赞同票超过 50%则为通过。
使⽤safeMath 库,使⽤Owner 第三⽅库
拥有参与投票权的⽤户在创建合约时确定
Voter 结构 要有时间戳、投票是否同意等;
struct 结构体
Proposal 提案
提案编号、提案时间、提案内容、提案⼈、提案截⽌时间、结果等。
Voter 投票
投票时间 、态度等(也可以增加委托投票)
功能(必要功能)
vote 投票
getResult 结果
事件
Vote
Result 产⽣结果
首先我们来测试其功能
1.选择三个投票账户进行部署



2.各函数功能概述
constructor: 构造函数用于初始化合约。接收一个包含初始选民地址的数组,将这些地址添加到 eligibleVoters 映射中,表示这些地址是合适的选民。
submitProposal: 提交提案的函数。只有合适的选民才能提交提案。该函数创建一个新的提案对象,将其存储在 proposals 映射中。
vote: 进行投票的函数。只有合适的选民才能投票,且投票时间必须在提案截止时间之前。投票结果存储在 votes 映射中,并更新提案的赞成和反对数量。
getResult: 获取提案结果的函数。只有在投票截止时间之后才能调用该函数。计算赞成票的百分比,并判断提案是否通过,然后更新提案的状态并触发相应的事件。
getNextProposalId: 私有函数,用于生成下一个提案的唯一标识符。在示例中,它总是返回 1,实际应用中可能需要更复杂的逻辑
3.提交提案

4.投票



账号 1,2,3 分别投票
5.根据提案查看结果
未点击 getResult

点击 getResult

6.根据用户地址查看用户投票情况

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/2302_77339802/article/details/134370557
文章来源:CSDN 博主「发呆...」
文章原标题:《Solidity 案例详解(四)投票智能合约》
旨在传播区块链相关技术,如有侵权请与我们联系删除。
评论