-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (47 loc) · 2.58 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
(function () {
var web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
// this is the same ABI JSON string generated by the `deploy.js` script
var abi = '[{"constant":false,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"totalVotesFor","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"validCandidate","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"votesReceived","outputs":[{"name":"","type":"uint8"}],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"candidateList","outputs":[{"name":"","type":"bytes32"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"voteForCandidate","outputs":[],"payable":false,"type":"function"},{"inputs":[{"name":"candidateNames","type":"bytes32[]"}],"payable":false,"type":"constructor"}]';
var VotingContract = web3.eth.contract(JSON.parse(abi));
// use the address that was provided when creating the Voting contract on testrpc
var contractInstance = VotingContract.at('0xc7a159c79420a3ff70283a276d72f634ff89625b');
var candidates = ['2B', '9S', 'A2'];
// define totalVotesFor callback
var createTotalVotesForCallback = function (candidate) {
return function (err, numVotes) {
if (err) {
alert(err);
return;
}
var n = candidates.indexOf(candidate) + 1;
document.getElementById('candidate-' + n).innerHTML = numVotes.toString();
};
};
// get all candidate votes function
var updateVotes = function() {
candidates.forEach(function(candidate) {
contractInstance.totalVotesFor.call(candidate, createTotalVotesForCallback(candidate));
});
};
var voteForm = document.getElementById('vote');
var candidateInput = document.getElementById('candidate');
voteForm.addEventListener('submit', function (e) {
e.preventDefault();
var candidate = candidateInput.value;
if (candidate === '' || candidates.indexOf(candidate) < 0) {
alert('invalid candidate:', candidate)
return
}
contractInstance.voteForCandidate(candidate, {from: web3.eth.accounts[0]}, function (err) {
if (err) {
alert(err);
return;
}
contractInstance.totalVotesFor.call(candidate, createTotalVotesForCallback(candidate));
});
})
// get initial value of votes
updateVotes();
// update votes every 30 seconds
setInterval(updateVotes, 30000);
})();