Skip to content
Snippets Groups Projects
Commit 54cb378e authored by Miguel Braidot's avatar Miguel Braidot
Browse files

Crear encuesta da de alta las direcciones permitidas para votar desde el formulario

parent 1cc8df8d
No related branches found
No related tags found
No related merge requests found
...@@ -65,38 +65,42 @@ contract Ballot ...@@ -65,38 +65,42 @@ contract Ballot
bool countNonvotesAsBlanks, bool countNonvotesAsBlanks,
uint maxVotesPerVoter, uint maxVotesPerVoter,
uint maxVotesPerProposal, uint maxVotesPerProposal,
bytes32[] memory proposalNames bytes32[] memory proposalNames,
address[] memory voters
) )
public public
{ {
require( voteBefore > now ); require(voters.length > 0, "Debe registrar al menos un votante.");
require( percentOfRegisteredVotersReqToBeValid <= 100000000 ); require(voteBefore > now, "La fecha de cierre de la votación tiene que ser posterior a hoy");
require( percentOfVotesCastToWin <= 100000000 ); require(percentOfRegisteredVotersReqToBeValid <= 100000000, "El porcentaje de votantes tiene que ser menor a 100");
require(percentOfVotesCastToWin <= 100000000, "El porcentaje de votos para ganar tiene que ser menor a 100");
// chairman can not automatically vote. // chairman can not automatically vote.
// Chairman must giveRightToVote to himself if // Chairman must giveRightToVote to himself if
// he wants to vote. // he wants to vote.
ballotChairman = tx.origin; ballotChairman = tx.origin;
ballotTitle = title; ballotTitle = title;
ballotVoteStarts = voteStarts; ballotVoteStarts = voteStarts;
ballotVoteBefore = voteBefore; ballotVoteBefore = voteBefore;
ballotPercentOfRegisteredVotersReqToBeValid = percentOfRegisteredVotersReqToBeValid; ballotPercentOfRegisteredVotersReqToBeValid = percentOfRegisteredVotersReqToBeValid;
ballotPercentOfVotesCastToWin = percentOfVotesCastToWin; ballotPercentOfVotesCastToWin = percentOfVotesCastToWin;
ballotCountNonvotesAsBlanks = countNonvotesAsBlanks; ballotCountNonvotesAsBlanks = countNonvotesAsBlanks;
ballotMaxVotesPerVoter = maxVotesPerVoter; ballotMaxVotesPerVoter = maxVotesPerVoter;
ballotMaxVotesPerProposal = maxVotesPerProposal; ballotMaxVotesPerProposal = maxVotesPerProposal;
/// @dev For each of the provided proposal names, /// @dev For each of the provided proposal names,
/// @dev add it to the end of the proposalList /// @dev add it to the end of the proposalList
uint incoming = proposalNames.length; uint incoming = proposalNames.length;
uint i = 0; uint i = 0;
uint idp = 0; uint idp = 0;
proposalListLength = 0; proposalListLength = 0;
while ( i < incoming ) while ( i < incoming )
{ {
idp = proposalList.push( proposalNames[i] ); idp = proposalList.push(proposalNames[i]);
proposalListLength++; proposalListLength++;
votedProposalList[idp] = 0; votedProposalList[idp] = 0;
i++; i++;
} }
giveRightToVote(voters);
} }
/// @notice Give 'voters' the right to vote on this ballot. /// @notice Give 'voters' the right to vote on this ballot.
...@@ -105,32 +109,32 @@ contract Ballot ...@@ -105,32 +109,32 @@ contract Ballot
public public
{ {
// May only be called by chairman. // May only be called by chairman.
require( msg.sender == ballotChairman ); require(msg.sender == ballotChairman || tx.origin == ballotChairman, "Solo el creador de la votación puede agregar votantes.");
require( ballotVoteBefore > now ); require(ballotVoteBefore > now, "La votación ha finalizado, no se puede agregar votantes.");
uint len = voters.length; uint len = voters.length;
uint i = 0; uint i = 0;
while ( i < len ) while ( i < len )
{ {
address voter = voters[i]; address voter = voters[i];
uint idx = voterMap[voter]; uint idx = voterMap[voter];
/// @dev Can't add any voters more than once. /// @dev Can't add any voters more than once.
require( idx == 0 ); require(idx == 0, "No puede haber votantes duplicados");
/// @dev Not even the voter listed in [0] can vote more than once. /// @dev Not even the voter listed in [0] can vote more than once.
if ( voterList.length > 0 ) if ( voterList.length > 0 )
require( voterList[0].voter != voter ); require(voterList[0].voter != voter, "No puede haber votantes duplicados");
/// @dev If the voter's address doesn't match, it is because /// @dev If the voter's address doesn't match, it is because
/// @dev he doesn't exist (and then we always have idx=0). /// @dev he doesn't exist (and then we always have idx=0).
/// @dev So we push him onto the voterList. /// @dev So we push him onto the voterList.
idx = voterList.push( idx = voterList.push(
Voter( Voter(
{ {
voter: voter, voter: voter,
votedProposals: emptyuintlist, votedProposals: emptyuintlist,
votesLeft: ballotMaxVotesPerVoter votesLeft: ballotMaxVotesPerVoter
} }
) )
) - 1; ) - 1;
voterMap[voter] = idx; voterMap[voter] = idx;
i++; i++;
} }
} }
...@@ -140,7 +144,7 @@ contract Ballot ...@@ -140,7 +144,7 @@ contract Ballot
view view
returns( int ) returns( int )
{ {
uint idx = voterMap[voter]; uint idx = voterMap[voter];
if ( idx > 0 ) if ( idx > 0 )
return int(idx); return int(idx);
if ( voterList[0].voter == voter ) if ( voterList[0].voter == voter )
...@@ -151,15 +155,15 @@ contract Ballot ...@@ -151,15 +155,15 @@ contract Ballot
function vote( uint proposal ) function vote( uint proposal )
public public
{ {
require( proposal < proposalList.length ); require(proposal < proposalList.length, "No existe la opción de votación elegida.");
require( ballotVoteStarts <= now ); require(ballotVoteStarts <= now, "La votación no ha comenzado aún.");
require( ballotVoteBefore > now ); require(ballotVoteBefore > now, "La votacíon ha finalizado.");
int idx = getVoterIdx( msg.sender ); int idx = getVoterIdx(msg.sender);
require( idx > -1 ); require(idx > -1, "No tiene permisos para votar.");
uint uidx = uint( idx ); uint uidx = uint(idx);
require( voterList[uidx].votesLeft > 0 ); require(voterList[uidx].votesLeft > 0, "Ya ha agotado la cantidad de votos asignada.");
uint proposalCounter = 0; uint proposalCounter = 0;
uint i = voterList[uidx].votedProposals.length; uint i = voterList[uidx].votedProposals.length;
while ( i > 0 ) while ( i > 0 )
{ {
i--; i--;
...@@ -167,9 +171,9 @@ contract Ballot ...@@ -167,9 +171,9 @@ contract Ballot
proposalCounter++; proposalCounter++;
} }
require( proposalCounter < ballotMaxVotesPerProposal ); require(proposalCounter < ballotMaxVotesPerProposal, "Se ha agotado la cantidad de votos para la opción elegida.");
voterList[uidx].votesLeft--; voterList[uidx].votesLeft--;
voterList[uidx].votedProposals.push( proposal ); voterList[uidx].votedProposals.push(proposal);
votedProposalList[proposal]++; votedProposalList[proposal]++;
} }
...@@ -188,7 +192,7 @@ contract Ballot ...@@ -188,7 +192,7 @@ contract Ballot
return; return;
if ( ballotVoteStarts <= now ) if ( ballotVoteStarts <= now )
return; return;
selfdestruct( ballotChairman ); selfdestruct(ballotChairman);
} }
} }
...@@ -204,7 +208,8 @@ contract NewBallot ...@@ -204,7 +208,8 @@ contract NewBallot
bool countNonvotesAsBlanks, bool countNonvotesAsBlanks,
uint maxVotesPerVoter, uint maxVotesPerVoter,
uint maxVotesPerProposal, uint maxVotesPerProposal,
bytes32[] memory proposalNames bytes32[] memory proposalNames,
address[] memory voters
) )
public public
{ {
...@@ -219,7 +224,8 @@ contract NewBallot ...@@ -219,7 +224,8 @@ contract NewBallot
countNonvotesAsBlanks, countNonvotesAsBlanks,
maxVotesPerVoter, maxVotesPerVoter,
maxVotesPerProposal, maxVotesPerProposal,
proposalNames proposalNames,
voters
)); ));
emit contratocreado(ballot); emit contratocreado(ballot);
} }
......
...@@ -329,6 +329,10 @@ var abiBallot = [ ...@@ -329,6 +329,10 @@ var abiBallot = [
{ {
"name": "proposalNames", "name": "proposalNames",
"type": "bytes32[]" "type": "bytes32[]"
},
{
"name": "voters",
"type": "address[]"
} }
], ],
"payable": false, "payable": false,
...@@ -377,6 +381,10 @@ var abiNew = [ ...@@ -377,6 +381,10 @@ var abiNew = [
{ {
"name": "proposalNames", "name": "proposalNames",
"type": "bytes32[]" "type": "bytes32[]"
},
{
"name": "voters",
"type": "address[]"
} }
], ],
"name": "newBallot", "name": "newBallot",
......
...@@ -22,13 +22,14 @@ var netnames = { ...@@ -22,13 +22,14 @@ var netnames = {
var mainaddr = { var mainaddr = {
'5445': '0xe5bf7c3e8aa529e42fbd99428137b68db75d85f9', '5445': '0xe5bf7c3e8aa529e42fbd99428137b68db75d85f9',
'47525974938': '0xe3e08934b6fa0b68972c08e0f545cee31ed039c6', '47525974938': '0xe3e08934b6fa0b68972c08e0f545cee31ed039c6',
'5777': '0x99845b94609F0285527ee11a0C9664532ddE0428' '5777': '0xB1427B0147175ea6c6e35eA8c258b7e844ECa66A'
}; };
/// Ballot address: 0x999d06fcc0a2380e0e0038b6d186275e754dd2b4
var ballot_keccak3 = '0x27fdf9b1c0d27b6143d49147cf30b3f7f09ac1c2cb2b7115a1633e0b8551c6a9';
var contract_event; var contract_event;
// Deprecated
var ballot_keccak3 = '0x27fdf9b1c0d27b6143d49147cf30b3f7f09ac1c2cb2b7115a1633e0b8551c6a9';
window.addEventListener('load', page_loaded); window.addEventListener('load', page_loaded);
function addchild(parent, childtype, childText, attributes) { function addchild(parent, childtype, childText, attributes) {
...@@ -397,7 +398,7 @@ async function ask_for_ballot_details() { ...@@ -397,7 +398,7 @@ async function ask_for_ballot_details() {
}); });
} }
async function nueva_votacion(arguments,proposals) { async function nueva_votacion(arguments, proposals, voters) {
if (mainaddr[netid] == undefined) if (mainaddr[netid] == undefined)
return; return;
...@@ -413,14 +414,14 @@ async function nueva_votacion(arguments,proposals) { ...@@ -413,14 +414,14 @@ async function nueva_votacion(arguments,proposals) {
if (!contract) if (!contract)
return; return;
console.log(arguments,proposals); console.log(arguments, proposals, voters);
try try
{ {
contract_event = contract.contratocreado(); contract_event = contract.contratocreado();
contract_event.watch(function(error, result){ contract_event.watch(function(error, result){
if (!error){ if (!error){
console.log(result); console.log(result);
alertarSuccess('Ballot was successfuly created. Here, its address: ' + result.args.contrato); // the contract address alertarSuccess('La votación se creó correctamente, tome nota de su dirección: ' + result.args.contrato); // the contract address
}else{ }else{
alertar(error); alertar(error);
} }
...@@ -428,7 +429,7 @@ async function nueva_votacion(arguments,proposals) { ...@@ -428,7 +429,7 @@ async function nueva_votacion(arguments,proposals) {
contract.newBallot.sendTransaction( contract.newBallot.sendTransaction(
arguments[0], arguments[1], arguments[2], arguments[3], arguments[0], arguments[1], arguments[2], arguments[3],
arguments[4], arguments[5], arguments[6], arguments[7], arguments[4], arguments[5], arguments[6], arguments[7],
proposals, { gas: 2111000 }, contract_created proposals, voters, { gas: 2111000 }, contract_created
); );
} }
catch (error) catch (error)
...@@ -499,6 +500,32 @@ async function ver_votacion2(addr, code) { ...@@ -499,6 +500,32 @@ async function ver_votacion2(addr, code) {
} }
} }
function getTransactionReceiptMined(txHash, interval) {
const self = window.web3.eth;
const transactionReceiptAsync = function(resolve, reject) {
self.getTransactionReceipt(txHash, (error, receipt) => {
if (error) {
reject(error);
} else if (receipt == null) {
setTimeout(
() => transactionReceiptAsync(resolve, reject),
interval ? interval : 500);
} else {
resolve(receipt);
}
});
};
if (Array.isArray(txHash)) {
return Promise.all(txHash.map(
oneTxHash => self.getTransactionReceiptMined(oneTxHash, interval)));
} else if (typeof txHash === "string") {
return new Promise(transactionReceiptAsync);
} else {
throw new Error("Invalid Type: " + txHash);
}
};
async function votar(addr, proposal){ async function votar(addr, proposal){
await access_accounts(); await access_accounts();
return new Promise (function (resolve, reject) { return new Promise (function (resolve, reject) {
...@@ -516,13 +543,24 @@ async function votar(addr, proposal){ ...@@ -516,13 +543,24 @@ async function votar(addr, proposal){
reject("No existe un contrato en esa dirección"); reject("No existe un contrato en esa dirección");
} }
/*contract.vote.sendTransaction(proposal, { gas: 2111000 }, function (error, result) {
if (error) {
reject(error);
} else {
resolve(result);
}
});
*/
contract.vote.sendTransaction(proposal, { gas: 2111000 }, function (error, result) { contract.vote.sendTransaction(proposal, { gas: 2111000 }, function (error, result) {
if (error) { if (error) {
reject(error); reject(error);
} else { } else {
var receipt = getTransactionReceiptMined(result, 1);
resolve(result); resolve(result);
} }
}); });
}); });
...@@ -543,10 +581,8 @@ async function resultados(addr){ ...@@ -543,10 +581,8 @@ async function resultados(addr){
var results = []; var results = [];
for(var i=0;i<proposalLength;i++){ for(var i=0;i<proposalLength;i++){
results[i] = await getProposalResults(contract, i); results[i] = await getProposalResults(contract, i);
/*contract.votedProposalList.call(i, { gas: 2111000 }, function(error, rcpt){
getProposalResults(error, rcpt, totalVotes, i);
});*/
} }
console.log("Total votos:", totalVotes.toString(10));
showProposalResults(totalVotes, proposalLength, results); showProposalResults(totalVotes, proposalLength, results);
//close_alertar(); //close_alertar();
...@@ -655,9 +691,9 @@ function getProposalResults(contract, option){ ...@@ -655,9 +691,9 @@ function getProposalResults(contract, option){
}); });
} }
async function showProposalResults(totalVotes, proposalLength, results){ async function showProposalResults(_totalVotes, proposalLength, results){
for(var i = 0; i<proposalLength; i++){ for(var i = 0; i<proposalLength; i++){
var percentage = (totalVotes.toString(10) > 0) ? results[i].toString(10) / totalVotes.toString(10) * 100 : 0; var percentage = (_totalVotes.toString(10) > 0) ? results[i].toString(10) / _totalVotes.toString(10) * 100 : 0;
console.log(i, percentage); console.log(i, percentage);
$('#result_'+i).text(percentage.toFixed(2)); $('#result_'+i).text(percentage.toFixed(2));
......
...@@ -303,7 +303,7 @@ ...@@ -303,7 +303,7 @@
}); });
//console.log(arguments,proposalNames,voters); //console.log(arguments,proposalNames,voters);
nueva_votacion(arguments,proposalNames); nueva_votacion(arguments, proposalNames, voters);
} }
$("form").validate({ $("form").validate({
......
...@@ -144,10 +144,9 @@ ...@@ -144,10 +144,9 @@
$("#contract_address").text(input_address); $("#contract_address").text(input_address);
ver_votacion(input_address); ver_votacion(input_address);
//TEST //TEST showing the results bargraph
/*$("form").hide(); //$(".resultados").show();
$(".resultados").show(); //resultados(input_address);
resultados(input_address);*/
} }
function viewVotacion(){ function viewVotacion(){
...@@ -179,7 +178,9 @@ ...@@ -179,7 +178,9 @@
} }
}catch (error){ }catch (error){
alertar(error); var message = error.message.substring(error.message.indexOf('revert') + 7);
if(message.length < 1){message = error;}
alertar(message);
$("#voterow .btn").show(); $("#voterow .btn").show();
return false; return false;
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment