This repository has been archived by the owner on Dec 12, 2024. It is now read-only.
forked from alexvandesande/stake-voice
-
Notifications
You must be signed in to change notification settings - Fork 184
/
scripts.js
315 lines (257 loc) · 12.2 KB
/
scripts.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Set some initial variables
var ethervote, ethervoteContract, proposalHash, totalVotes, proposal, totalPro, totalAgainst;
var voteMap = {};
var contractAddress = '0x8a57d2708d1f228dac2f7934f5311cd2a0a1cda4';
var contractAddressTestnet = '0x4ad62d4aaec13098832b1be635fc01581d97325c'; // Rinkeby
// Ropsten: 0x47ab800a75990b0bd5bb4a54cfbec777972c973c
var startingBlock = 4000000; // on mainnet
var contractABI = [{"constant":false,"inputs":[{"name":"proposalHash","type":"bytes32"},{"name":"pro","type":"bool"}],"name":"vote","outputs":[],"type":"function"},{"anonymous":false,"inputs":[{"indexed":true,"name":"proposalHash","type":"bytes32"},{"indexed":false,"name":"pro","type":"bool"},{"indexed":false,"name":"addr","type":"address"}],"name":"LogVote","type":"event"}];
var history = [];
function init() {
// Get parameters and set up the basic structure
proposal = decodeURI(getParameterByName('proposal'));
document.getElementById('proposal').textContent = proposal;
// Add event listeners
document.getElementById('see-results').addEventListener('click', function(){
document.getElementById("results").style.opacity = "1";
document.getElementById("see-results").style.opacity = "0";
} , false);
document.getElementById('vote-support').addEventListener('click', function(){ vote(true);}, false);
document.getElementById('vote-against').addEventListener('click', function(){ vote(false);}, false);
var newProposalInput = document.getElementById('new-proposal');
newProposalInput.addEventListener('keypress', function() {
document.getElementById("new-proposal-link").style.display = "block";
});
newProposalInput.addEventListener('blur', newProposal);
// Checks Web3 support
if(typeof web3 !== 'undefined' && typeof Web3 !== 'undefined') {
// If there's a web3 library loaded, then make your own web3
web3 = new Web3(web3.currentProvider);
} else if (typeof Web3 !== 'undefined') {
// If there isn't then set a provider
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
} else if(typeof web3 == 'undefined') {
// If there is neither then this isn't an ethereum browser
document.getElementById("results").style.display = "none";
document.getElementById("see-results").style.display = "none";
document.getElementById("vote-support").style.display = "none";
document.getElementById("vote-against").style.display = "none";
document.getElementById("subtitle").style.display = "none";
document.getElementById("proposal").textContent = "Give Stakers a Voice";
var message = document.getElementById("message");
message.style.display = "block";
return;
}
// Check if there are available accounts
web3.eth.getAccounts(function(e,accounts){
// show the floating baloon
if (e || !accounts || accounts.length == 0) {
document.getElementById("add-account").style.display = "block";
}
});
// Get the proposal
proposalHash = web3.sha3(proposal);
document.body.style.background = "#" + proposalHash.substr(2,6);
if (typeof proposal == 'undefined' || proposal == 'null' || proposal == '') {
// No Proposals are set
document.getElementById("results").style.display = "none";
document.getElementById("see-results").style.display = "none";
document.getElementById("vote-support").style.display = "none";
document.getElementById("vote-against").style.display = "none";
document.getElementById("subtitle").style.display = "none";
document.getElementById("proposal").textContent = "Give Stakers a Voice";
var message = document.getElementById("message");
message.style.display = "block";
message.textContent = "This tool will enable anyone to create any statement that ethereum token holders can voice their support or opposition to. Statements are not binding and represent only the opinion of those who support it.";
} else {
// If proposal is valid, start watching the chain
web3.eth.filter('latest').watch(function(e, res){
console.log('web3.filter', e, res)
if(!e) {
console.log('Block arrived ', res);
document.getElementById('status').textContent = 'Calculating votes...';
calculateVotes();
}
});
}
// Load the contract
web3.eth.getCode(contractAddress, function(e, r) {
if (!e) {
// if bytecode is small, then try switching networks
if (r.length < 3) {
contractAddress = contractAddressTestnet;
startingBlock = 500000;
}
web3.eth.getCode(contractAddress, function(e, r) {
if (!e) {
}})
// Load the contract
ethervoteContract = web3.eth.contract(contractABI);
ethervote = ethervoteContract.at(contractAddress);
// Watch Votes
if (proposal && proposal.length > 0 && proposal != 'null')
watchVotes();
}
})
// Build Mist Menu
// Add proposal to history
if (typeof(Storage) !== "undefined" && typeof(mist) !== "undefined") {
// Code for localStorage/sessionStorage.
var propHistory = localStorage.propHistory ? localStorage.propHistory.split(',') : [];
if (proposal && proposal.length > 0 && propHistory.indexOf(proposal)<0)
propHistory.unshift(proposal);
propHistory = propHistory.slice(0, 10);
localStorage.setItem('propHistory', propHistory.join(','));
// mist.menu.clear();
mist.menu.add( 'main' ,{
position: 0,
name: 'Main Page',
selected: typeof proposal == 'undefined' || proposal == 'null'
}, function(){
window.location.search = '';
});
var n = 1;
for (item of propHistory) {
if (item.length > 0 && item != 'null') {
mist.menu.add( item ,{
name: item,
position: n++,
selected: item == proposal
}, function(){
window.location.search = '?proposal=' + encodeURI(this.name);
});
}
}
}
}
function watchVotes() {
// Set the texts and variables
document.getElementById('status').textContent = 'Calculating votes...';
setTimeout(function(){
// If the app doesn't respond after a timeout it probably has no votes
document.getElementById('status').textContent = "";
}, 3000);
// LogVote is an event on the contract. Read all since block 1 million
var logVotes = ethervote.LogVote({proposalHash: proposalHash}, {fromBlock: startingBlock});
// Wait for the events to be loaded
logVotes.watch(function(error, res){
console.log('logVotes Watch', error, res);
// Each vote will execute this function
if (!error) {
web3.eth.getBalance(res.args.addr, function(err, balanceInWei){
// Get the current balance of a voter
var bal = Number(web3.fromWei(balanceInWei, "finney"));
voteMap[res.args.addr] = {balance: bal, support: res.args.pro};
// Check if the current owner has already voted and show that on the interface
web3.eth.getAccounts(function(e,accounts){
if (!e && accounts && accounts[0] == res.args.addr) {
if (res.args.pro) {
document.getElementById('vote-support').classList.add("pressed");
document.getElementById('vote-against').classList.remove("pressed");
} else {
document.getElementById('vote-support').classList.remove("pressed");
document.getElementById('vote-against').classList.add("pressed");
}
}
});
calculateVotes();
})
}
})
}
function convertToString(vote, total){
// how many 0's are we dealing with
var magnitude = Math.floor(Math.log10(total));
// Select the right unit
if (magnitude <= 3) {
return Math.round(vote*10)/10 + " finney";
} else if (magnitude < 6) {
return Math.round(vote/10)/100 + " ether";
} else if (magnitude < 9) {
return Math.round(vote/10000)/100 + "k ether";
} else {
return Math.round(vote/10000000)/100 + " million ether";
}
}
function calculateVotes() {
for (var a in voteMap) {
// call the function asynchronously
web3.eth.getBalance(a, function(e,r) {
voteMap[a].balance = Number(web3.fromWei(r, 'finney'));
updateTotals()
});
};
// End the calculation
document.getElementById("message").style.display = "none";
setTimeout(function(){
// If the app doesn't respond after a timeout it probably has no votes
document.getElementById('status').textContent = "";
if (!(totalVotes > 0)){
document.getElementById("results").style.display = "none";
var message = document.getElementById("message");
message.textContent = "No votes yet. Vote now!";
message.style.display = "block";
}
}, 2000);
}
function updateTotals() {
totalPro = 0;
totalAgainst = 0;
totalVotes = 0;
for (var acc in voteMap) {
if (voteMap[acc].support)
totalPro += parseFloat(voteMap[acc].balance);
else
totalAgainst += parseFloat(voteMap[acc].balance);
}
totalVotes = totalPro + totalAgainst;
// Show a colored bar with the result
document.getElementById("results").style.display = "block";
var proResult = document.getElementById('support');
proResult.textContent = convertToString(totalPro, totalVotes);
proResult.style.width = Math.round(totalPro*100/totalVotes) + "%";
var againstResult = document.getElementById('opposition');
againstResult.textContent = convertToString(totalAgainst, totalVotes);
againstResult.style.width = Math.round(totalAgainst*100/totalVotes) + "%";
if (totalVotes>0)
mist.menu.update( proposal ,{ badge: Math.round(totalPro*100/totalVotes) + "%" });
}
function vote(support) {
web3.eth.getAccounts(function(e,accounts){
// Check if there are accounts available
if (!e && accounts && accounts.length > 0) {
// Create a dialog requesting the transaction
ethervote.vote(proposalHash, support, {from: accounts[0]}, function(err, res) {
console.log('voted!', err, res);
})
document.getElementById('status').textContent = 'Waiting for new block...';
} else {
mist.requestAccount(function(e, account) {
if(!e) {
// Create a dialog requesting the transaction
ethervote.vote(proposalHash, support, {from: account.toLowerCase()}, function(err, res) {
console.log('voted!', err, res);
})
document.getElementById('status').textContent = 'Waiting for new block...';
}
});
}
})
document.getElementById("results").style.opacity = "1";
document.getElementById("see-results").style.opacity = "0";
}
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function newProposal() {
// When typing a new proposal, generate new dinamic urls
var newProposal = document.getElementById('new-proposal');
var newProposalLink = document.getElementById('new-proposal-link');
newProposalLink.href = '?proposal=' + encodeURI(newProposal.value);
}