-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
705 lines (616 loc) · 23 KB
/
main.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
var web3 = new Web3(Web3.givenProvider);
var contractInstance;
var network;
var pause;
var adduser, addowner;
var ownerIn=false;
//ADDRESS of deployment on ropsten : 0xbf1b63292a9893a78dBB7b209e048987D5E5fEb9
//old 0x25B1F3366af2Ff2E81E2B7E4D7D1de17bFB77e4f
//ADD THE ADDRESS OF PROXY HERE IF Changed :
var addContract = "0xbf1b63292a9893a78dBB7b209e048987D5E5fEb9";
//////////////////////////PROCESS TO CANCEL Tx//////////////////////
//if there's a spending Tx on ropsten => deployment stucked
//put higher fees >10%
// web3.eth.sendTransaction({
// from: add,//ATTENTION "0x...." & lowercase
// to: add,
// value: 0,
// gasPrice: "0x...",//amount 33gwei =>wei
// gasLimit: "0x...",
// gas: "0x...",
// nonce: "0x.."//nonce of tx to cancel
// }, function(error, hash){
// console.log("transaction : hash "+ hash);
// console.error;
// });
$(document).ready(function() {
//get the network
web3.eth.net.getNetworkType().then(function(res){
display("#network", res, "fetch");
});
//get the user access autorisation & creat instance to interact with
window.ethereum.enable().then(function(accounts){
adduser = accounts[0];
console.log("User address : " + adduser);
contractInstance = new web3.eth.Contract(abi, addContract, {from: adduser});
console.log("Contract address : " + contractInstance.address);
fetchAndDisplay();
listenToGeneralEvents();
});
//-----------------Triggered if metamask account changes
window.ethereum.on('accountsChanged', function (accounts) {
//MEMO pas sure que la manip soit approriée mais sinon msg erreur add from non valide
window.ethereum.enable().then(function(accounts){
adduser = accounts[0];
console.log("User address changed to : " + adduser);
contractInstance = new web3.eth.Contract(abi, addContract, {from: adduser});
console.log("Contract address : " + contractInstance.address);
fetchAndDisplay();
listenToGeneralEvents();
});
})
//-----------------Page events
$("#bet_btn").click(flip);
$("#claim_btn").click(claimRewards);
$("#name_btn").click(setName);
$("#owner_btn").click(ownerAccess);
$("#pause_btn").click(setPause);
$("#unpause_btn").click(setUnpause);
$("#min_btn").click(updateMinimumBet);
$("#max_btn").click(updateMaximumBet);
$("#mult_btn").click(updateJackpotFactor);
$("#msg_btn").click(setMsgToChain);
$("#deposit_btn").click(deposit);
$("#emergencywithdraw_btn").click(emergencyWithdrawAll);
$("#emergencyclaim_btn").click(emergencyClaimAllRewards);
$("#owner_btn").click(ownerAccess);
});
//------------------ getters => display
function fetchAndDisplay(){
ownerAccessManager();
fetchAndDisplayUserBalance();
fetchAndDisplayPendingBet();
fetchAndDisplayBalance();
fetchAndDisplayReward();
fetchAndDisplayPauseState();
contractInstance.methods.getMsgToChain().call().then(function(res){
display("#msg_output", res, "pending");
});
contractInstance.methods.getSettings().call().then(function(res){
display("#min_span", res.min, "fetch");
});
contractInstance.methods.getSettings().call().then(function(res){
display("#max_span",res.max, "fetch");
});
contractInstance.methods.getSettings().call().then(function(res){
display("#reward_factor",res.fact, "fetch");
console.log("fetch : FACTOR : " + res);
});
contractInstance.methods.getName(adduser).call().then(function(res){
display("#name_output", ((res != "") ? res : adduser), "fetch");
});
}
//MEMO not test yet
function fetchAndDisplayPendingBet(){
contractInstance.methods.getUserPendingBetState(adduser).call().then(function(res){
if(res) {
pendingFlip();
}
});
}
function fetchAndDisplayUserBalance(){
web3.eth.getBalance(adduser).then(function(res){
display("#balance_user", res, "fetch")});
}
function fetchAndDisplayBalance(){
contractInstance.methods.getContractBalance().call().then(function(res){
display("#balance_output", res, "fetch");
});
}
function fetchAndDisplayReward(){
contractInstance.methods.getTotalReward().call({from : adduser}).then(function(res){
display("#reward_output", res, "fetch");
});
}
function fetchAndDisplayPauseState(){
//call appel methode via l enoeud sans transaction (renvoi erroe, resultat)
contractInstance.methods.getPauseState().call().then(function(res){
pauseStateManager(res);
});
}
//------------------ states manager
function ownerAccessManager(){
contractInstance.methods.getOwnerAdd().call().then(function(res){
addowner = res.toLowerCase();
console.log("Owner address : " + addowner);
if (addowner == adduser) {
console.log("addowner == adduser" + (addowner == adduser));
$("#owner_btn").removeAttr("disabled");//, "disabled");
} else {
$("#owner_btn").attr("disabled", "disabled");
}
});
}
function pauseStateManager(state){
if (state) {
$("#unpause_btn").removeClass("disabled");//.removeAttr("disabled");
$("#pause_btn").addClass("disabled");//.attr("disabled", "disabled");
} else {
$("#unpause_btn").addClass("disabled");//.attr("disabled", "disabled");
$("#pause_btn").removeClass("disabled");////.removeAttr("disabled");
}
}
function settingEventManager(error, event) {
if(!error) {
switch(event.returnValues._param) {
case "minimumBet" :
display("#min_span", event.returnValues._value, "set");
break;
case "maximumBet" :
display("#max_span", event.returnValues._value, "set");
break;
case "jackpotFator" :
display("#reward_factor", event.returnValues._value, "set");
break;
case "pause" :
pauseStateManager(event.returnValues._value);
break;
}
} else {
console.log(error);
}
}
//To do : add a param in event to get the new value and don't have to call via fetch
//centralize funding events management here
function fundingEventManager(error, event) {
if(!error) {
switch(event.returnValues._param) {
case "deposit" :
fetchAndDisplayBalance();
console.log(event);
break;
case "emergencyWithdrawAll" :
fetchAndDisplayBalance();
fetchAndDisplayReward();
console.log(event);
break;
case "emergencyClaimAllRewards" :
fetchAndDisplayBalance();
fetchAndDisplayReward();
console.log(event);
break;
case "claimRewards" :
console.log(event);
break;
case "withdrawReward" :
console.log(event);
break;
case "withdraw" :
console.log(event);
break;
}
} else {
console.log(error);
}
}
//------------------ main display
//src : reset => "" via val / fetching and pending : display text
function display(id, res, src) {
if (src != "reset") {
switch (id) {
case "#min_span" :
$("#min_span").text(web3.utils.fromWei(res.toString(),"ether") + " ");
break;
case "#max_span" :
$("#max_span").text(" " + web3.utils.fromWei(res.toString(),"ether"));
break;
case "#reward_factor" :
$("#reward_factor").text(res - 1);
break;
case "#balance_output" :
$("#balance_output").text(web3.utils.fromWei(res.toString(),"ether") + " eth");
break;
case "#reward_output" :
$("#reward_output").text(web3.utils.fromWei(res.toString(),"ether"));
break;
case "#balance_user" :
$("#balance_user").text(web3.utils.fromWei(res.toString(),"ether"));
break;
case "#msg_output" :
$("#msg_output").text(" " + res);
break;
default:
$(id).text(res);
}
} else {
$(id).val(res);
}
console.log(src + " " + id + " to " + res);
}
//------------------ display dismissible box
function appendAlert(id, txt, success) {
var element = "";
var elementAlerte1 = "<div class=\"alert alert-";
var elementAlerte2 = " alert-dismissible\">" +
"<a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">" +
"×</a><strong>";
var elementType1 = success ? "success" : "warning";
var elementType2 = success ? "Success!" : "Warning!" + "</strong>";
element = elementAlerte1 + elementType1 + elementAlerte2 + elementType2 + txt + "</div>";
$(id).append(element);
console.log(element);
}
//------------------ general events listeners
function listenToGeneralEvents(){
contractInstance.events.evtSettingsUpdated(function(error, event){
settingEventManager(error, event);
});
contractInstance.events.evtPauseSet(function(error, event){
settingEventManager(error, event);
});
contractInstance.events.evtFundingOperation(function(error, event){
fundingEventManager(error, event);
});
contractInstance.events.evtMsgToChain(function(error, event){
display("#msg_output", event.returnValues._msg, "pending");
});
}
//------------------ user functions
function ownerAccess() {
if (!ownerIn) {
$("#image").hide(()=>{ownerIn = true;});
} else {
$("#image").show(()=>{ownerIn = false;});
}
}
function flip(){
var success;
var evtBetResult = 0;
var evtBetClosed = 0;
var betInput = $("#bet_input").val();
var userConfig = {
from : adduser,
value: web3.utils.toWei(betInput,"ether")
}
//---------------SCENARIO
//---------------user actives flip button =>
//--------disable the button as only one bet is allow
$("#bet_btn").attr("disabled", "disabled");
//--------display an animation to wait the end of the process
$("#bet_btn").html("<span id='bet_spin' " +
"class='spinner-border spinner-border-sm'></span>Processing...");
//---------indication of step : bet taken, waiting for Tx
display("#evt_output", "Waiting for your transaction...", "pending");
contractInstance.methods.flip().send(userConfig)
.on("transactionHash", function(hash){
console.log("flip hash : " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("flip conf : " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("flip rcpt : " + receipt);
})
.on('error', function(error){
//---------------error occured with Tx => stop the scenario
$("#bet_btn").removeAttr("disabled", "enabled");
$("#bet_btn").html("Flip the coin");
//-------------display for 3 sec a msg for Tx error
display("#evt_output", "Something went wrong, no bet taken", "pending");
setTimeout(function(){
display("#evt_output", "", "pending");
}, 3000);
console.error;
})
//---------------listen to the events and filter the user
//---------indication of step : Tx received, bet initialized
contractInstance.events.evtBetOpened(function(error, event){
if(event.returnValues._user.toLowerCase() == adduser){
display("#evt_output", event.returnValues._msg, "pending");
}
})
//---------indication of step : Query to oracle, waiting the answer
contractInstance.events.evtBetQuery(function(error, event){
if(event.returnValues._user.toLowerCase() == adduser){
display("#evt_output", event.returnValues._msg, "pending");
}
});
//---------indication of step : result received, evalutaion
contractInstance.events.evtBetResume(function(error, event){
if(event.returnValues._user.toLowerCase() == adduser){
display("#evt_output", event.returnValues._msg, "pending");
}
});
//---------indication of step : bet won or lost
contractInstance.events.evtBetResult(function(error, event){
if(event.returnValues._user.toLowerCase() == adduser){
var resultOfBet = (event.returnValues._isWon) ?
" Hip hip hooray! YOU WON! Your reward increased... will you succeed in emptying the contract? " :
" Bet lost! Sorry, it's even money... try again! Take one more chance! ";
display("#evt_output", resultOfBet, "pending");
evtBetResult += 1;
if (evtBetResult == 1) {
appendAlert("#colUser", resultOfBet , event.returnValues._isWon);
}
}
});
//---------------contract send event : bet closed for this user=>
//--------enable the button and reset the button state
contractInstance.events.evtBetClosed(function(error, event){
if(event.returnValues._user.toLowerCase() == adduser){
$("#bet_btn").removeAttr("disabled", "enabled");
$("#bet_btn").html("Flip the coin");
//---------indication of step : reset the information field
setTimeout(function(){
display("#evt_output", "", "pending");
}, 3000);
//display("#evt_output", "", "pending");
//---------indication of step : bet closed or aborted
evtBetClosed += 1;
success = !(event.returnValues._status == "Aborted, refund in progress...");
if (evtBetClosed == 1) {
appendAlert("#colUser", event.returnValues._status ,success);
}
fetchAndDisplayBalance();
fetchAndDisplayReward();
}
});
display("#bet_input", "", "reset");
}
//MEMO not test yet
function pendingFlip(){
//---------------SCENARIO
//---------------there's a pending flip =>
//--------disable the button as only one bet is allow
$("#bet_btn").attr("disabled", "disabled");
//--------display an animation to wait the end of the process
$("#bet_btn").html("<span id='bet_spin' " +
"class='spinner-border spinner-border-sm'></span>Processing...");
//---------indication of step : bet taken, waiting for Tx
display("#evt_output", "You have a pending bet...", "pending");
//---------indication of step : bet won or lost
contractInstance.events.evtBetResult(function(error, event){
if(event.returnValues._user.toLowerCase() == adduser){
var resultOfBet = (event.returnValues._isWon) ?
" Hip hip hooray! YOU WON ! Your reward increased... " :
" Bet lost! Sorry, it's even money... try again! Take one more chance! ";
display("#evt_output", resultOfBet, "pending");
evtBetResult += 1;
if (evtBetResult == 1) {
appendAlert("#mainContainer", resultOfBet , event.returnValues._isWon);
}
}
});
//---------------contract send event : bet closed for this user=>
//--------enable the button and reset the button state
contractInstance.events.evtBetClosed(function(error, event){
if(event.returnValues._user.toLowerCase() == adduser){
$("#bet_btn").removeAttr("disabled", "enabled");
$("#bet_btn").html("Flip the coin");
//---------indication of step : reset the information field
display("#evt_output", "", "pending");
//---------indication of step : bet closed or aborted
evtBetClosed += 1;
success = !(event.returnValues._status == "Aborted, refund in progress...");
if (evtBetClosed == 1) {
appendAlert("#colUser", event.returnValues._status ,success);
}
fetchAndDisplayBalance();
fetchAndDisplayReward();
}
});
}
function setName(){
var input = $("#name_input").val();
contractInstance.methods.setName(input).send()
.on("transactionHash", function(hash){
console.log("setName hash : " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("setName conf : " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("setName rcpt : " + receipt);
appendAlert("#colUser"," New name set : " + input, true);
})
.on('error', console.error);
//MEMO essai de ne pas avoir 3 fois la boite modale en filtrant le bloc ecouté
//ça ne change rien
//var latestBlock = web3.eth.blockNumber; //get the latest blocknumber
//contractInstance.events.evtNameSet({fromBlock: latestBlock}, function(error, event){
//----waiting the event of the new name set to display it
contractInstance.events.evtNameSet(function(error, event){
if (event.returnValues._user.toLowerCase() == adduser) {
display("#name_output", event.returnValues._name, "set");
//appendAlert("#colUser"," New name set : " + input, true); //pb : duplicate action 3 times
display("#name_input", "", "reset");
}
})
//.on('error', console.error);
}
function claimRewards(){
contractInstance.methods.claimRewards().send()
.on("transactionHash", function(hash){
console.log("claim hash " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("claim conf " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("claim rcpt " + receipt);
appendAlert("#colUser", " You claimed your reward! ", true);
fetchAndDisplayBalance();
fetchAndDisplayReward();
})
.on('error', console.error);
}
//-------------------owner functions
function updateMinimumBet(){
var input = $("#min_input").val();
var value = web3.utils.toWei(input,"ether");
contractInstance.methods.updateMinimumBet(value).send()
.on("transactionHash", function(hash){
console.log("updateMin hash : " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("updateMin conf : " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("updateMin rcpt : " + receipt);
//----inform the owner
appendAlert("#colOwner"," New minimum set : " + value, true);
})
.on("error",function(error){
console.error;
})
display("#min_input", "", "reset");
}
function updateMaximumBet(){
var input = $("#max_input").val();
var value = web3.utils.toWei(input,"ether");
contractInstance.methods.updateMaximumBet(value).send()
.on("transactionHash", function(hash){
console.log("updateMax hash : " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("updateMax conf : " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("updateMax rcpt : " + receipt);
//----inform the owner
appendAlert("#colOwner"," New maximum set : " + value, true);
})
.on("error",function(error){
console.error;
})
display("#max_input", "", "reset");
}
function updateJackpotFactor(){
var input = $("#mult_input").val();
var value = parseInt(input);
contractInstance.methods.updateJackpotFactor(value).send()
.on("transactionHash", function(hash){
console.log("updateFact hash : " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("updateFact conf : " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("updateFact rcpt : " + receipt);
//----inform the owner
appendAlert("#colOwner"," New factor set : " + input, true);
})
.on("error",function(error){
console.error;
})
display("#mult_input", "", "reset");
}
function deposit(){
var depositInput = $("#deposit_input").val();
var depositValue = {
value: web3.utils.toWei(depositInput,"ether")
}
contractInstance.methods.deposit().send(depositValue)
.on("transactionHash", function(hash){
console.log("deposit hash " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("deposit conf " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("deposit rcpt " + receipt);
//----inform the owner
appendAlert("#colOwner"," New deposit : " + web3.utils.fromWei(depositInput,"ether"), + " eth", true);
fetchAndDisplayBalance();
})
.on("error",function(error){
console.error;
})
}
function emergencyWithdrawAll(){
contractInstance.methods.emergencyWithdrawAll().send()
.on("transactionHash", function(hash){
console.log("emwithAll hash " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("emwithAll conf " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("emwithAll rcpt " + receipt);
//----inform the owner
appendAlert("#colOwner", " Emregency withdraw! ", true);
fetchAndDisplayBalance();
fetchAndDisplayReward();
})
.on("error",function(error){
console.error;
})
}
function emergencyClaimAllRewards(){
contractInstance.methods.emergencyClaimAllRewards().send()
.on("transactionHash", function(hash){
console.log("emclaimAll hash " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("emclaimAll conf " +confirmationNr);
})
.on("receipt", function(receipt){
console.log("emclaimAll rcpt " +receipt);
//----inform the owner
appendAlert("#colOwner", " Emregency claim! ", true);
fetchAndDisplayBalance();
fetchAndDisplayReward();
})
.on("error",function(error){
console.error;
})
}
function setPause(){
contractInstance.methods.pause().send()
.on("transactionHash", function(hash){
console.log("pause hash " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("pause conf " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("pause rcpt " + receipt);
//----inform the owner
appendAlert("#colOwner", " Contract paused! ", true);
})
.on("error",function(error){
console.error;
});
}
function setUnpause(){
contractInstance.methods.unPause().send()
.on("transactionHash", function(hash){
console.log("unpause hash " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("unpause conf " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("unpause rcpt " + receipt);
//----inform the owner
appendAlert("#colOwner", " Contract unpaused! ", true);
})
.on("error",function(error){
console.error;
});
}
function setMsgToChain(){
var input = $("#msg_input").val();
contractInstance.methods.setMsgToChain(input).send()
.on("transactionHash", function(hash){
console.log("setMsgToChain hash : " + hash);
})
.on("confirmation", function(confirmationNr){
console.log("setMsgToChain conf : " + confirmationNr);
})
.on("receipt", function(receipt){
console.log("setMsgToChain rcpt : " + receipt);
appendAlert("#colUser"," New name set : " + input, true);
})
.on('error', console.error);
}