Tengo un contrato inteligente copiado simple para las elecciones, donde un votante vota solo una vez por un candidato y luego se le niega votar más veces.
Pero, ¿sería posible permitir que el votante vote hasta 3 veces y enviar un voto a un candidato diferente cada vez? Lo que significa que cuando envía más de un voto a un candidato, se le negará. ¿Cómo se haría?
El código
contract Election {
struct Candidate {
string name;
uint voteCount;
}
struct Voter {
uint voteIndex;
bool voted;
uint weight;
}
address public owner;
string public name;
mapping(address => Voter) public voters;
Candidate[] public candidates;
uint public auctionEnd;
event ElectionResult(string name, uint voteCount);
function Election(string _name, uint durationMinutes, string candidate1, string candidate2, string candidate3, string candidate4, string candidate5) public{
owner = msg.sender;
name = _name;
auctionEnd = now + (durationMinutes * 1 minutes);
candidates.push(Candidate(candidate1, 0));
candidates.push(Candidate(candidate2, 0));
candidates.push(Candidate(candidate3, 0));
candidates.push(Candidate(candidate4, 0));
candidates.push(Candidate(candidate5, 0));
}
function authorize(address voter) public {
require(msg.sender == owner);
require(!voters[voter].voted);
voters[voter].weight = 1;
}
function vote(uint voteIndex) public {
require(now < auctionEnd);
require(!voters[msg.sender].voted);
voters[msg.sender].voted = true;
voters[msg.sender].voteIndex = voteIndex;
candidates[voteIndex].voteCount += voters[msg.sender].weight;
}
function end() public {
require(msg.sender == owner);
require(now >= auctionEnd);
for(uint i=0; i < candidates.length; i++) {
ElectionResult(candidates[i].name, candidates[i].voteCount);
}
}
}
Estoy de acuerdo con @Nulik en que se trata más generalmente de programación. Quiere cambiar las reglas. Básicamente, en lugar de verificar si el votante alguna vez votó, desea cambiar cuántas veces votó.
Este
struct Voter {
uint voteIndex;
bool voted; // <= ever voted
uint weight;
}
A esto:
struct Voter {
uint voteIndex;
uint voted; // <== count of votes cast
uint weight;
}
Este
require(!voters[voter].voted);
A esto
require(voters[voter].voted < 3);
Este
voters[msg.sender].voted = true;
A esto
voters[msg.sender].voted += 1;
Esto de ninguna manera se ha probado a fondo y no hay garantía. Puede ser un comienzo solo con fines educativos.
Espero eso ayude.
Nulik