qidao123.com技术社区-IT企服评测·应用市场

 找回密码
 立即注册

Solidity学习-投票合约示例

[复制链接]
发表于 2025-6-29 15:51:38 | 显示全部楼层 |阅读模式
以下的合约有一些复杂,但展示了很多Solidity的语言特性。它实现了一个投票合约。 当然,电子投票的重要题目是如何将投票权分配给正确的人员以及如何防止被操纵。 我们不会在这里办理所有的题目,但至少我们会展示如何举行委托投票,同时,计票又是 自动和完全透明的 。
我们的想法是为每个(投票)表决创建一份合约,为每个选项提供简称。 然后作为合约的创造者——即主席,将给予每个独立的地点以投票权。
地点背面的人可以选择本身投票,或者委托给他们信任的人来投票。
在投票时间结束时,winningProposal() 将返回获得最多投票的提案。
代码如下:
  1. // SPDX-License-Identifier: GPL-3.0
  2. pragma solidity >=0.7.0 <0.9.0;
  3. /// @title 委托投票
  4. contract Ballot {
  5.    
  6.   
  7.     // 定义投票者
  8.     struct Voter {
  9.         uint weight; // 计票的权重
  10.         bool voted;  // 若为真,代表该人已投票
  11.         address delegate; // 被委托人
  12.         uint vote;   // 投票提案的索引
  13.     }
  14.     // 定义被投票者
  15.     struct Proposal {
  16.         bytes32 name;   // 简称(最长32个字节)
  17.         uint voteCount; // 得票数
  18.     }
  19.     address public chairperson;
  20.    // 这声明了一个状态变量,为每个可能的地址存储一个 `Voter`。
  21.     mapping(address => Voter) public voters;
  22.      // 一个 `Proposal` 结构类型的动态数组
  23.     Proposal[] public proposals;
  24.     /// 为 `proposalNames` 中的每个提案,创建一个新的(投票)表决
  25.     constructor(bytes32[] memory proposalNames) {
  26.         chairperson = msg.sender;
  27.         voters[chairperson].weight = 1;
  28.         //对于提供的每个提案名称,
  29.         //创建一个新的 Proposal 对象并把它添加到数组的末尾。
  30.         for (uint i = 0; i < proposalNames.length; i++) {
  31.             // `Proposal({...})` 创建一个临时 Proposal 对象,
  32.             // `proposals.push(...)` 将其添加到 `proposals` 的末尾
  33.             proposals.push(Proposal({
  34.                 name: proposalNames[i],
  35.                 voteCount: 0
  36.             }));
  37.         }
  38.     }
  39.     // 授权 `voter` 对这个(投票)表决进行投票
  40.     // 只有 `chairperson` 可以调用该函数。
  41.     function giveRightToVote(address voter) external {
  42.         // 若 `require` 的第一个参数的计算结果为 `false`,
  43.         // 则终止执行,撤销所有对状态和以太币余额的改动。
  44.         // 在旧版的 EVM 中这曾经会消耗所有 gas,但现在不会了。
  45.         // 使用 require 来检查函数是否被正确地调用,是一个好习惯。
  46.         // 你也可以在 require 的第二个参数中提供一个对错误情况的解释。
  47.         require(
  48.             msg.sender == chairperson,
  49.             "Only chairperson can give right to vote."
  50.         );
  51.         //判断是否已经投过票了
  52.         require(
  53.             !voters[voter].voted,
  54.             "The voter already voted."
  55.         );
  56.         require(voters[voter].weight == 0);
  57.         voters[voter].weight = 1;
  58.     }
  59. /// 把你的投票委托到投票者 `to`。
  60.     function delegate(address to) external {
  61.         // 传引用
  62.         Voter storage sender = voters[msg.sender];
  63.         require(sender.weight != 0, "You have no right to vote");
  64.         require(!sender.voted, "You already voted.");
  65.         require(to != msg.sender, "Self-delegation is disallowed.");
  66.         // 委托是可以传递的,只要被委托者 `to` 也设置了委托。
  67.         // 一般来说,这种循环委托是危险的。因为,如果传递的链条太长,
  68.         // 则可能需消耗的gas要多于区块中剩余的(大于区块设置的gasLimit),
  69.         // 这种情况下,委托不会被执行。
  70.         // 而在另一些情况下,如果形成闭环,则会让合约完全卡住。
  71.         while (voters[to].delegate != address(0)) {
  72.             to = voters[to].delegate;
  73.             // 不允许闭环委托
  74.             require(to != msg.sender, "Found loop in delegation.");
  75.         }
  76.         // `sender` 是一个引用, 相当于对 `voters[msg.sender].voted` 进行修改
  77.         Voter storage delegate_ = voters[to];
  78.         // Voters cannot delegate to accounts that cannot vote.
  79.         require(delegate_.weight >= 1);
  80.         // Since `sender` is a reference, this
  81.         // modifies `voters[msg.sender]`.
  82.         sender.voted = true;
  83.         sender.delegate = to;
  84.         if (delegate_.voted) {
  85.             // 若被委托者已经投过票了,直接增加得票数
  86.             proposals[delegate_.vote].voteCount += sender.weight;
  87.         } else {
  88.             // 若被委托者还没投票,增加委托者的权重
  89.             delegate_.weight += sender.weight;
  90.         }
  91.     }
  92. /// 把你的票(包括委托给你的票),
  93.     /// 投给提案 `proposals[proposal].name`.
  94.     function vote(uint proposal) external {
  95.         Voter storage sender = voters[msg.sender];
  96.         require(!sender.voted, "Already voted.");
  97.         sender.voted = true;
  98.         sender.vote = proposal;
  99.         // 如果 `proposal` 超过了数组的范围,则会自动抛出异常,并恢复所有的改动
  100.         proposals[proposal].voteCount += sender.weight;
  101.     }
  102.   /// @dev 结合之前所有的投票,计算出最终胜出的提案
  103.     function winningProposal() public view returns (uint winningProposal_)
  104.     {
  105.         uint winningVoteCount = 0;
  106.         for (uint p = 0; p < proposals.length; p++) {
  107.             if (proposals[p].voteCount > winningVoteCount) {
  108.                 winningVoteCount = proposals[p].voteCount;
  109.                 winningProposal_ = p;
  110.             }
  111.         }
  112.     }  
  113.    
  114.      // 计算获胜的提案
  115.     // function winningProposal() public view returns (uint winningProposal) {
  116.     //     uint winningVoteCount = 0;
  117.     //     for (uint p = 0; p < proposals.length; p++) {
  118.     //         if (proposals[p].voteCount > winningVoteCount) {
  119.     //             winningVoteCount = proposals[p].voteCount;
  120.     //             winningProposal = p;
  121.     //         }
  122.     //     }
  123.     // }
  124.    
  125.      // 调用 winningProposal() 函数以获取提案数组中获胜者的索引,并以此返回获胜者的名称
  126.      //winnerName 函数调用 winningProposal() 函数,并使用其返回值来访问 proposals 数组。
  127.     function winnerName() public view returns (bytes32 winnerName_)
  128.     {
  129.         winnerName_ = proposals[winningProposal()].name;
  130.     }
  131. }
复制代码
测试

在你的合约中,构造函数需要一个参数 proposalNames,它是一个 bytes32 数组。因此,你需要在部署时提供这个参数。
在“Deploy & Run Transactions”面板中,找到“Deploy”按钮下方的输入框并输入提案名称列表。
例如,你可以输入以下内容:
  1. ["0x50726f706f73616c310000000000000000000000000000000000000000000000", "0x50726f706f73616c320000000000000000000000000000000000000000000000"]
复制代码

部署成功:

查看生成的账户:
在 Deploy & Run Transactions 面板中,你会看到一个 ACCOUNT 下拉菜单。这个菜单中列出了所有生成的账户地点及其余额。你可以从中选择一个地点举行测试。
选择和复制账户地点:
点击 ACCOUNT 下拉菜单,选择一个账户。
复制选中的账户地点。


  • 授权投票权 (giveRightToVote)
    在 giveRightToVote 的输入框中输入授权投票者的地点。
示例:

2. 委托投票 (delegate)
在 delegate 的输入框中输入被委托人的地点(可以是同一个账户或其他账户)

   这里测试发现输入的都会这个提示,这个待验证处理
  

  • 投票 (vote)
    在 vote 的输入框中输入提案索引。

4. 查看主席 (chairperson)
点击 chairperson 按钮查看合约的主席地点。

5. 查看提案信息 (proposals)
在 proposals 的输入框中输入提案索引。

点击 proposals 按钮查看提案的名称和票数。


6. 查看投票者信息 (voters)
在 voters 的输入框中输入投票者的地点。

7. 得胜提案名称 (winnerName)
点击 winnerName 按钮查看当前得胜提案的名称。

8. 计算得胜提案 (winningProposal)
点击 winningProposal 按钮查看当前得胜提案的索引。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|qidao123.com技术社区-IT企服评测▪应用市场 ( 浙ICP备20004199|浙ICP备20004199号 )|网站地图

GMT+8, 2025-8-13 11:07 , Processed in 0.087600 second(s), 32 queries .

Powered by Discuz! X3.5 Licensed

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表