Repository navigation
Expand file tree
/
Copy pathlottery-participate.html
More file actions
757 lines (732 loc) · 34.4 KB
/
Copy pathlottery-participate.html
File metadata and controls
757 lines (732 loc) · 34.4 KB
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Join a Circles Lottery</title>
<link rel="icon" href="https://aboutcircles.com/favicon.ico" />
<script src="https://unpkg.com/ethers@5.7.2/dist/ethers.umd.min.js"></script>
<style>
body {
font-family: 'Inter', Arial, sans-serif;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
min-height: 100vh;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
}
.container {
background: white;
border-radius: 16px;
box-shadow: 0 4px 24px rgba(0,0,0,0.08);
margin-top: 40px;
padding: 32px 24px 24px 24px;
max-width: 420px;
width: 100%;
position: relative;
text-align: center;
}
.logo {
width: 60px;
margin-bottom: 12px;
}
h1 {
color: #4A90E2;
font-size: 2rem;
margin-bottom: 8px;
letter-spacing: -1px;
}
.subtitle {
color: #666;
font-size: 1.1rem;
margin-bottom: 24px;
}
.input-group {
margin-bottom: 18px;
text-align: left;
}
.input-group label {
font-weight: 600;
color: #191568;
margin-bottom: 4px;
display: block;
}
.input-group input {
width: 100%;
padding: 10px;
border: 1px solid #d0d7de;
border-radius: 6px;
font-size: 1rem;
margin-bottom: 2px;
box-sizing: border-box;
}
.button {
background: linear-gradient(90deg, #4A90E2 0%, #50E3C2 100%);
color: white;
border: none;
border-radius: 6px;
padding: 12px 28px;
font-size: 1.1rem;
font-weight: 600;
cursor: pointer;
margin: 12px 0 0 0;
transition: background 0.2s;
box-shadow: 0 2px 8px rgba(80,227,194,0.08);
}
.button:disabled {
background: #b2bec3;
cursor: not-allowed;
}
.lottery-details {
margin: 24px 0 12px 0;
text-align: left;
background: #f7fafc;
border-radius: 8px;
padding: 18px 16px;
box-shadow: 0 1px 4px rgba(74,144,226,0.04);
}
.lottery-details h2 {
margin: 0 0 8px 0;
color: #4A90E2;
font-size: 1.2rem;
}
.lottery-details p {
margin: 4px 0;
color: #191568;
font-size: 1rem;
}
.status {
font-weight: bold;
text-transform: uppercase;
letter-spacing: 1px;
font-size: 0.95em;
margin-bottom: 6px;
}
.status.active { color: #27ae60; }
.status.ended { color: #e67e22; }
.status.drawn { color: #2980b9; }
.status.cancelled { color: #e74c3c; }
.status.unfunded { color: #636e72; }
.participants-list {
margin: 8px 0 0 0;
padding-left: 18px;
color: #555;
font-size: 0.98em;
}
.spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #4A90E2;
border-radius: 50%;
width: 36px;
height: 36px;
animation: spin 1s linear infinite;
margin: 32px auto 0 auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.error {
color: #e74c3c;
background: #ffeaea;
border-radius: 6px;
padding: 10px;
margin: 12px 0;
font-size: 1rem;
}
.success {
color: #27ae60;
background: #eafaf1;
border-radius: 6px;
padding: 10px;
margin: 12px 0;
font-size: 1rem;
}
@media (max-width: 600px) {
.container {
padding: 16px 4px 18px 4px;
margin-top: 12px;
}
.lottery-details {
padding: 10px 4px;
}
}
</style>
</head>
<body>
<div class="container">
<img src="https://i.imgur.com/UaqSXxq.jpeg" class="logo" alt="Circles Logo" />
<h1>Join a Circles Lottery</h1>
<div class="subtitle">Try your luck and win prizes with Circles!</div>
<div id="error" class="error" style="display:none;"></div>
<div id="success" class="success" style="display:none;"></div>
<div id="advancedSection" style="display:none;margin-bottom:12px;">
<div class="input-group" style="margin-bottom:8px;">
<label for="activeLotterySelect" style="font-weight:600;font-size:1.1em;">Active Lotteries</label>
<select id="activeLotterySelect" style="padding:4px 8px;border-radius:6px;border:1px solid #d0d7de;background:#f7fafc;font-size:0.98em;width:100%;margin-bottom:8px;"></select>
</div>
<div class="input-group" style="margin-bottom:8px;">
<label for="otherLotterySelect" style="font-weight:600;font-size:1.1em;">Past Lotteries</label>
<select id="otherLotterySelect" style="padding:4px 8px;border-radius:6px;border:1px solid #d0d7de;background:#f7fafc;font-size:0.98em;width:100%;margin-bottom:8px;"></select>
</div>
<div class="input-group" style="margin-bottom:8px;">
<label for="lotteryAddress" style="font-size:0.95em;">Or Enter Lottery Address</label>
<input type="text" id="lotteryAddress" placeholder="0x..." style="font-size:0.98em;" />
</div>
<button class="button" id="loadLotteryBtn" style="font-size:0.98em;padding:8px 18px;">Load Lottery</button>
<div style="margin-top:16px;text-align:center;">
<a href="lottery.html" style="color:#4A90E2;font-weight:bold;font-size:1.05em;text-decoration:none;">Start your own lottery</a>
</div>
</div>
<button id="showAdvancedBtn" style="background:none;border:none;color:#4A90E2;font-size:0.95em;cursor:pointer;margin-bottom:8px;display:block;">Switch/Advanced...</button>
<div id="lotterySection" style="display:none;">
<div class="spinner" id="loadingSpinner" style="display:none;"></div>
<div class="lottery-details" id="lotteryDetails"></div>
</div>
</div>
<div id="participantNotification" style="display:none;position:fixed;top:32px;left:50%;transform:translateX(-50%);z-index:1000;background:linear-gradient(90deg,#4A90E2 0%,#50E3C2 100%);color:white;font-weight:bold;font-size:1.15em;padding:14px 32px;border-radius:32px;box-shadow:0 2px 12px rgba(80,227,194,0.18);transition:opacity 0.5s;"></div>
<script>
// Wait for ethers to be loaded
window.addEventListener('load', function() {
if (typeof ethers === 'undefined') {
showError('Failed to load ethers.js library. Please refresh the page.');
return;
}
});
// --- Config ---
const GNOSIS_RPC = "https://rpc.gnosis.gateway.fm";
const CIRCLES_PROFILE_RPC = "https://rpc.aboutcircles.com/profiles/search?address=";
const FACTORY_ADDRESS = '0x4B14679899A7AF92D947386Cb45D686C748BcA55';
const FACTORY_ABI = ["function allDeployments() view returns (address[])"];
const LOTTERY_ABI = [
"function lotteryName() view returns (string)",
"function startTime() view returns (uint256)",
"function endTime() view returns (uint256)",
"function ticketPrice() view returns (uint256)",
"function prizeAmount() view returns (uint256)",
"function isCancelled() view returns (bool)",
"function isDrawn() view returns (bool)",
"function winner() view returns (address)",
"function getParticipantCount() view returns (uint256)",
"function getTotalTicketsSold() view returns (uint256)",
"function prizeToken() view returns (address)",
"function owner() view returns (address)",
"function requireTrustedBy() view returns (address)",
"function trustedAddress() view returns (address)",
"function acceptedId() view returns (uint256)",
"function participants(uint256) view returns (address)",
"function hasBought(address) view returns (bool)",
"function claimRemainder() external"
];
const ERC20_ABI = [
"function decimals() view returns (uint8)",
"function name() view returns (string)",
"function symbol() view returns (string)",
"function balanceOf(address) view returns (uint256)"
];
const provider = new ethers.providers.JsonRpcProvider(GNOSIS_RPC);
const factory = new ethers.Contract(FACTORY_ADDRESS, FACTORY_ABI, provider);
let lottery;
let allLotteries = [];
let ticketPrice, ticketPriceHuman, ticketTokenSymbol, ticketTokenDecimals, isDrawn, isCancelled, endTime, startTime, winner, participants, hasBought, prizeAmount, prizeToken, prizeTokenSymbol, prizeTokenDecimals;
let myAddress = null;
let currentLotteryAddress = null;
let ticketBoughtListener = null;
let lastParticipantCount = 0;
const profileCache = {};
// --- URL param helper ---
function getParam(name) {
const url = new URL(window.location.href);
return url.searchParams.get(name);
}
function setParam(name, value) {
const url = new URL(window.location.href);
url.searchParams.set(name, value);
window.history.replaceState({}, '', url);
}
// --- UI helpers ---
function showError(msg) {
const errorDiv = document.getElementById('error');
if (errorDiv) {
errorDiv.textContent = msg;
errorDiv.style.display = 'block';
}
const successDiv = document.getElementById('success');
if (successDiv) successDiv.style.display = 'none';
}
function showSuccess(msg) {
const successDiv = document.getElementById('success');
if (successDiv) {
successDiv.textContent = msg;
successDiv.style.display = 'block';
}
const errorDiv = document.getElementById('error');
if (errorDiv) errorDiv.style.display = 'none';
}
function clearMessages() {
const errorDiv = document.getElementById('error');
if (errorDiv) errorDiv.style.display = 'none';
const successDiv = document.getElementById('success');
if (successDiv) successDiv.style.display = 'none';
}
function showSpinner(show) {
const spinner = document.getElementById('loadingSpinner');
if (spinner) spinner.style.display = show ? 'block' : 'none';
}
// --- Load lotteries from factory ---
async function loadLotteriesList() {
try {
allLotteries = await factory.allDeployments();
const activeLotterySelect = document.getElementById('activeLotterySelect');
const otherLotterySelect = document.getElementById('otherLotterySelect');
const now = Math.floor(Date.now() / 1000);
const activeOptions = [];
const otherOptions = [];
await Promise.all(allLotteries.map(async (addr) => {
let name = addr;
try {
const l = new ethers.Contract(addr, LOTTERY_ABI, provider);
name = await l.lotteryName();
const [isDrawn, isCancelled, endTime] = await Promise.all([
l.isDrawn(),
l.isCancelled(),
l.endTime()
]);
const option = document.createElement('option');
option.value = addr;
option.textContent = `${name} (${addr.slice(0, 6)}...${addr.slice(-4)})`;
if (!isDrawn && !isCancelled && endTime.toNumber() > now) {
activeOptions.push(option);
} else {
otherOptions.push(option);
}
} catch {}
}));
activeOptions.sort((a, b) => a.textContent.localeCompare(b.textContent));
otherOptions.sort((a, b) => a.textContent.localeCompare(b.textContent));
activeLotterySelect.innerHTML = '';
otherLotterySelect.innerHTML = '';
activeOptions.forEach(opt => activeLotterySelect.appendChild(opt));
otherOptions.forEach(opt => otherLotterySelect.appendChild(opt));
// By default, select the latest
if (allLotteries.length > 0) {
activeLotterySelect.value = allLotteries[allLotteries.length - 1];
otherLotterySelect.value = allLotteries[allLotteries.length - 1];
setLotteryAddress(activeLotterySelect.value);
setLotteryAddress(otherLotterySelect.value);
}
} catch (e) {
showError('Could not load lotteries from factory.');
}
}
document.getElementById('activeLotterySelect').addEventListener('change', function() {
setLotteryAddress(this.value);
loadLotteryByAddress(this.value);
});
document.getElementById('otherLotterySelect').addEventListener('change', function() {
setLotteryAddress(this.value);
loadLotteryByAddress(this.value);
});
function setLotteryAddress(addr) {
const addrInput = document.getElementById('lotteryAddress');
if (addrInput) addrInput.value = addr;
}
function getLotteryAddress() {
const addrInput = document.getElementById('lotteryAddress');
return addrInput ? addrInput.value.trim() : '';
}
async function loadLotteryByAddress(addr) {
clearMessages();
if (!/^0x[a-fA-F0-9]{40}$/.test(addr)) {
showError('Please enter a valid lottery address.');
return;
}
setParam('address', addr);
const lotterySection = document.getElementById('lotterySection');
if (lotterySection) lotterySection.style.display = 'none';
const lotteryDetails = document.getElementById('lotteryDetails');
if (lotteryDetails) lotteryDetails.innerHTML = '';
showSpinner(true);
lottery = new ethers.Contract(addr, LOTTERY_ABI, provider);
// Remove previous event listener if switching lotteries
if (ticketBoughtListener && currentLotteryAddress) {
try {
provider.off({ address: currentLotteryAddress, topics: [ethers.utils.id('TicketBought(address,uint256)')] }, ticketBoughtListener);
} catch {}
}
currentLotteryAddress = addr;
ticketBoughtListener = async (log) => {
if (log.address.toLowerCase() === currentLotteryAddress.toLowerCase()) {
await loadLotteryDetails(true);
}
};
// Listen for TicketBought events
provider.on({ address: addr, topics: [ethers.utils.id('TicketBought(address,uint256)')] }, ticketBoughtListener);
try {
await loadLotteryDetails();
if (lotterySection) lotterySection.style.display = 'block';
} catch (e) {
showError('Could not load lottery: ' + (e.message || e));
}
showSpinner(false);
}
document.getElementById('loadLotteryBtn').onclick = async function() {
const addr = getLotteryAddress();
await loadLotteryByAddress(addr);
};
document.getElementById('showAdvancedBtn').onclick = function() {
const adv = document.getElementById('advancedSection');
if (adv) adv.style.display = adv.style.display === 'none' ? 'block' : 'none';
};
// --- On page load: load lotteries and show latest ---
window.addEventListener('DOMContentLoaded', async () => {
await loadLotteriesList();
const select = document.getElementById('activeLotterySelect');
const addr = getParam('address');
if (addr && /^0x[a-fA-F0-9]{40}$/.test(addr)) {
setLotteryAddress(addr);
if (select) select.value = addr;
await loadLotteryByAddress(addr);
} else if (select && select.value) {
await loadLotteryByAddress(select.value);
}
// Hide advanced by default
const adv = document.getElementById('advancedSection');
if (adv) adv.style.display = 'none';
});
async function getProfilesBatch(addresses) {
if (!addresses || addresses.length === 0) return {};
try {
// Convert all addresses to lowercase before sending
const lowerAddresses = addresses.map(a => a.toLowerCase());
console.log('Querying profiles for addresses:', lowerAddresses);
const response = await fetch("https://rpc.aboutcircles.com/profiles/search/addresses", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ addresses: lowerAddresses, fetchComplete: true })
});
if (!response.ok) {
console.log('Profile fetch failed:', response.status);
return {};
}
const data = await response.json();
console.log('Profile data returned:', data);
// Use data.results if present, otherwise fallback to data as array
const profiles = Array.isArray(data) ? data : data.results;
const map = {};
for (const profile of profiles) {
if (profile.address) map[profile.address.toLowerCase()] = profile;
}
return map;
} catch (e) {
console.log('Profile fetch error:', e);
return {};
}
}
function getAvatarUrl(profile) {
if (!profile) {
console.log('No profile, using default avatar');
return 'https://ui-avatars.com/api/?name=Circles';
}
// Prefer avatar, fallback to previewImageUrl
const avatar = profile.avatar || profile.previewImageUrl;
if (!avatar) {
console.log('No avatar or previewImageUrl in profile, using default avatar for', profile.address);
return 'https://ui-avatars.com/api/?name=Circles';
}
if (avatar.startsWith('ipfs://')) {
const url = 'https://ipfs.io/ipfs/' + avatar.replace('ipfs://', '');
console.log('Using IPFS avatar:', url);
return url;
}
if (avatar.startsWith('data:image/')) {
console.log('Using base64 avatar');
return avatar;
}
console.log('Using direct avatar:', avatar);
return avatar;
}
const notificationDiv = document.createElement('div');
notificationDiv.id = 'participantNotification';
notificationDiv.style.position = 'fixed';
notificationDiv.style.top = '32px';
notificationDiv.style.left = '50%';
notificationDiv.style.transform = 'translateX(-50%)';
notificationDiv.style.zIndex = '1000';
notificationDiv.style.display = 'none';
notificationDiv.style.background = 'linear-gradient(90deg,#4A90E2 0%,#50E3C2 100%)';
notificationDiv.style.color = 'white';
notificationDiv.style.fontWeight = 'bold';
notificationDiv.style.fontSize = '1.15em';
notificationDiv.style.padding = '14px 32px';
notificationDiv.style.borderRadius = '32px';
notificationDiv.style.boxShadow = '0 2px 12px rgba(80,227,194,0.18)';
notificationDiv.style.transition = 'opacity 0.5s';
document.body.appendChild(notificationDiv);
function showParticipantNotification(name) {
notificationDiv.innerHTML = `🎉 New participant joined${name ? ': <b>' + name + '</b>' : '!'}`;
notificationDiv.style.display = 'block';
notificationDiv.style.opacity = '1';
setTimeout(() => {
notificationDiv.style.opacity = '0';
setTimeout(() => {
notificationDiv.style.display = 'none';
}, 500);
}, 2000);
}
async function loadLotteryDetails(isEvent = false) {
showSpinner(true);
const [name, start, end, price, isCanc, isDr, win, partCount, totalTickets, pToken, pAmount] = await Promise.all([
lottery.lotteryName(),
lottery.startTime(),
lottery.endTime(),
lottery.ticketPrice(),
lottery.isCancelled(),
lottery.isDrawn(),
lottery.winner(),
lottery.getParticipantCount(),
lottery.getTotalTicketsSold(),
lottery.prizeToken(),
lottery.prizeAmount()
]);
startTime = start.toNumber();
endTime = end.toNumber();
ticketPrice = price;
isCancelled = isCanc;
isDrawn = isDr;
winner = win;
prizeToken = pToken;
prizeAmount = pAmount;
// Get token info
const tokenContract = new ethers.Contract(prizeToken, ERC20_ABI, provider);
const [decimals, symbol, currentBalance] = await Promise.all([
tokenContract.decimals(),
tokenContract.symbol(),
tokenContract.balanceOf(lottery.address)
]);
prizeTokenDecimals = decimals;
prizeTokenSymbol = symbol;
ticketTokenDecimals = 18;
ticketTokenSymbol = 'CRC';
ticketPriceHuman = ethers.utils.formatEther(ticketPrice);
// Render main details immediately with a placeholder for participants
renderLotteryDetails(
name, startTime, endTime, ticketPriceHuman, prizeAmount, prizeTokenSymbol, isCancelled, isDrawn, winner, null, null, [], [], [], totalTickets, currentBalance.gte(prizeAmount), currentBalance
);
// Show placeholder for participants
const partDiv = document.querySelector('.participants-list');
if (partDiv) partDiv.innerHTML = `<b>Participants:</b><ul style='list-style:none;padding-left:0;margin-top:8px;'><li>Loading participants...</li></ul>`;
// Only render and fetch participants if partCount > 0
if (partCount > 0) {
// Now load participant addresses in parallel
let participants = [];
try {
const participantPromises = [];
for (let i = 0; i < partCount; i++) {
participantPromises.push(lottery.participants(i));
}
participants = await Promise.all(participantPromises);
console.log('Fetched participants:', participants);
} catch (e) {
console.error('Error fetching participants:', e);
}
// Render participants as addresses only
const partDiv = document.querySelector('.participants-list');
if (partDiv) partDiv.innerHTML = `<b>Participants:</b><ul style='list-style:none;padding-left:0;margin-top:8px;'>` + participants.map(p => `<li>${p}</li>`).join('') + `</ul>`;
// Fetch profiles in background and update
const allAddresses = [...participants];
if (winner && winner !== ethers.constants.AddressZero && !allAddresses.includes(winner)) allAddresses.push(winner);
const profilesMap = await getProfilesBatchCached(allAddresses);
const participantNames = participants.map(addr => profilesMap[addr.toLowerCase()]?.name || null);
const participantAvatars = participants.map(addr => getAvatarUrl(profilesMap[addr.toLowerCase()]));
let winnerName = winner && winner !== ethers.constants.AddressZero ? (profilesMap[winner.toLowerCase()]?.name || null) : null;
let winnerAvatar = winner && winner !== ethers.constants.AddressZero ? getAvatarUrl(profilesMap[winner.toLowerCase()]) : null;
if (!winnerAvatar) winnerAvatar = 'https://ui-avatars.com/api/?name=Circles';
// Re-render full lottery details with all data
renderLotteryDetails(
name, startTime, endTime, ticketPriceHuman, prizeAmount, prizeTokenSymbol, isCancelled, isDrawn, winner, winnerName, winnerAvatar, participants, participantNames, participantAvatars, totalTickets, currentBalance.gte(prizeAmount), currentBalance
);
} else {
// No participants, clear the section
const partDiv = document.querySelector('.participants-list');
if (partDiv) partDiv.innerHTML = '';
}
// Detect new participant (only on event, not on page load)
if (isEvent && partCount > lastParticipantCount) {
// Show notification with the latest participant's name
const newIndex = partCount - 1;
const newAddr = participants[newIndex];
const newName = participantNames[newIndex] || null;
showParticipantNotification(newName);
}
lastParticipantCount = partCount;
console.log('Participant count from contract:', partCount);
showSpinner(false);
}
function timeAgoOrIn(timestamp) {
const now = Math.floor(Date.now() / 1000);
const diff = timestamp - now;
const absDiff = Math.abs(diff);
if (absDiff < 60) return diff > 0 ? `in ${absDiff} seconds` : `${absDiff} seconds ago`;
if (absDiff < 3600) return diff > 0 ? `in ${Math.floor(absDiff/60)} minutes` : `${Math.floor(absDiff/60)} minutes ago`;
if (absDiff < 86400) return diff > 0 ? `in ${Math.floor(absDiff/3600)} hours` : `${Math.floor(absDiff/3600)} hours ago`;
return diff > 0 ? `in ${Math.floor(absDiff/86400)} days` : `${Math.floor(absDiff/86400)} days ago`;
}
function renderLotteryDetails(name, start, end, price, prize, prizeSymbol, cancelled, drawn, winner, winnerName, winnerAvatar, participants, participantNames, participantAvatars, totalTickets, isFunded, currentBalance) {
const now = Math.floor(Date.now() / 1000);
let status = 'ACTIVE';
if (cancelled) status = 'CANCELLED';
else if (drawn) status = 'DRAWN';
else if (now > end) status = 'ENDED';
const statusClass = status.toLowerCase();
let html = `<h2 style='color:#4A90E2;'>${name}</h2>`;
html += `<div class=\"status ${statusClass}\">${status}</div>`;
html += `<div style='margin-bottom:10px;'>`;
html += `<b>Start:</b> ${timeAgoOrIn(start)}<br/>`;
html += `<b>End:</b> ${timeAgoOrIn(end)}<br/>`;
html += `</div>`;
html += `<p><b>Ticket Price:</b> <span style='color:#27ae60;'>${price} CRC</span></p>`;
html += `<p><b>Prize:</b> <span style='color:#f39c12;'>${ethers.utils.formatUnits(prize, prizeTokenDecimals)} ${prizeSymbol}</span></p>`;
html += `<p><b>Total Tickets Sold:</b> ${totalTickets}</p>`;
if (status === 'ACTIVE' && now < end) {
html += `<div id='countdown-timer' style='margin:12px 0 8px 0; font-size:1.12em; color:#2980b9;'><b>Loading time left...</b></div>`;
}
if (status === 'ACTIVE' && !isFunded) {
html += `<div style='margin:16px 0 8px 0; font-size:1.08em; color:#e67e22;'><b>⚠️ This lottery is not yet funded.<br>Prize will be available once funded.<br>Current balance: ${ethers.utils.formatUnits(currentBalance, prizeTokenDecimals)} ${prizeSymbol}</b></div>`;
}
// Engaging call-to-action
if (status === 'ACTIVE' && isFunded) {
const gnosisUrl = `https://app.gnosis.io/transfer/${lottery.address}/crc/${ticketPriceHuman}`;
const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(lottery.address)}`;
html += `<div style='margin:20px 0 8px 0; padding:18px 12px; background:#eafaf1; border-radius:10px; text-align:center;'>
<div style='font-size:1.15em; color:#2980b9; margin-bottom:10px;'><b>Want to win <span style='color:#f39c12;'>${ethers.utils.formatUnits(prize, prizeTokenDecimals)} ${prizeSymbol}</span>?</b></div>
<a href='${gnosisUrl}' target='_blank' style='display:inline-block;margin:10px 0 12px 0;padding:12px 28px;background:linear-gradient(90deg,#4A90E2 0%,#50E3C2 100%);color:white;font-weight:bold;font-size:1.1em;border-radius:6px;text-decoration:none;box-shadow:0 2px 8px rgba(80,227,194,0.08);'>
Buy Ticket via Gnosis
</a>
<div style='margin:14px 0 0 0;'>
<img src='${qrUrl}' alt='QR code' style='display:block;margin:0 auto 6px auto;border-radius:8px;border:1.5px solid #27ae60;background:#fff;' />
<div style='font-size:0.98em;color:#555;'>Or scan & send <b style='color:#27ae60;'>${price} CRC</b> to this lottery address from your mobile wallet:</div>
<div style='font-family:monospace;font-size:0.93em;color:#888;word-break:break-all;margin-top:2px;'>${lottery.address}</div>
</div>
</div>`;
} else if (status === 'ACTIVE' && !isFunded) {
html += `<div style='margin:16px 0 8px 0; font-size:1.08em; color:#888;'><b>Waiting for funding... You can't join until the prize is funded.</b></div>`;
} else if (status === 'DRAWN') {
html += `<div style='margin:16px 0 8px 0; font-size:1.2em; color:#27ae60; text-align:center;'><b>🎉 The lottery is over! Congratulations to our winner:</b></div>`;
} else if (status === 'ENDED' && !drawn && !cancelled && participants && participants.length > 0) {
const gnosisUrl = `https://app.gnosis.io/transfer/${lottery.address}/crc/${ticketPriceHuman}`;
const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(lottery.address)}`;
html += `<div style='margin:20px 0 8px 0; padding:18px 12px; background:#eafaf1; border-radius:10px; text-align:center;'>
<div style='font-size:1.15em; color:#e67e22; margin-bottom:10px;'><b>This lottery is over, but the winner has not been drawn yet.</b></div>
<div style='font-size:1.08em; color:#2980b9; margin-bottom:10px;'><b>Send ${ticketPriceHuman} CRC to trigger the drawing.</b></div>
<a href='${gnosisUrl}' target='_blank' style='display:inline-block;margin:10px 0 12px 0;padding:12px 28px;background:linear-gradient(90deg,#4A90E2 0%,#50E3C2 100%);color:white;font-weight:bold;font-size:1.1em;border-radius:6px;text-decoration:none;box-shadow:0 2px 8px rgba(80,227,194,0.08);'>
Trigger Drawing via Gnosis
</a>
<div style='margin:14px 0 0 0;'>
<img src='${qrUrl}' alt='QR code' style='display:block;margin:0 auto 6px auto;border-radius:8px;border:1.5px solid #27ae60;background:#fff;' />
<div style='font-size:0.98em;color:#555;'>Or scan & send <b style='color:#27ae60;'>${ticketPriceHuman} CRC</b> to this lottery address from your mobile wallet:</div>
<div style='font-family:monospace;font-size:0.93em;color:#888;word-break:break-all;margin-top:2px;'>${lottery.address}</div>
</div>
</div>`;
} else if (status === 'ENDED' || status === 'CANCELLED') {
html += `<div style='margin:16px 0 8px 0; font-size:1.08em; color:#888;'><b>This lottery is over. Come back soon for the next one!</b></div>`;
}
// Winner section
if (drawn && winner && winner !== ethers.constants.AddressZero) {
// Laurel wreath SVG
const laurel = `<svg width='80' height='80' viewBox='0 0 80 80' style='position:absolute;left:0;top:0;pointer-events:none;'><g><ellipse cx='40' cy='40' rx='36' ry='36' fill='none' stroke='#27ae60' stroke-width='4' stroke-dasharray='8 8' /></g></svg>`;
const winnerProfileUrl = winner && winner !== ethers.constants.AddressZero ? `https://app.gnosis.io/${winner}` : null;
if (winnerProfileUrl) {
html += `<div style='display:flex;flex-direction:column;align-items:center;justify-content:center;margin:18px 0 18px 0;position:relative;'>
<a href='${winnerProfileUrl}' target='_blank' style='text-decoration:none;'>
<div style='position:relative;width:80px;height:80px;'>
${laurel}
<img src='${winnerAvatar}' alt='avatar' style='width:64px;height:64px;border-radius:50%;object-fit:cover;border:3px solid #27ae60;position:absolute;left:8px;top:8px;background:#fff;' />
</div>
<div style='margin-top:10px;font-size:1.2em;font-weight:bold;color:#27ae60;text-align:center;'>${winnerName ? winnerName : winner.slice(0, 6) + '...' + winner.slice(-4)}</div>
</a>
</div>`;
} else {
html += `<div style='display:flex;flex-direction:column;align-items:center;justify-content:center;margin:18px 0 18px 0;position:relative;'>
<div style='position:relative;width:80px;height:80px;'>
${laurel}
<img src='${winnerAvatar}' alt='avatar' style='width:64px;height:64px;border-radius:50%;object-fit:cover;border:3px solid #27ae60;position:absolute;left:8px;top:8px;background:#fff;' />
</div>
<div style='margin-top:10px;font-size:1.2em;font-weight:bold;color:#27ae60;text-align:center;'>${winnerName ? winnerName : 'Winner'}</div>
</div>`;
}
}
// Participants
if (participants && participants.length > 0) {
html += `<div class="participants-list" style='margin-top:18px;'><b>Participants:</b><ul style='list-style:none;padding-left:0;margin-top:8px;'>` + participants.map((p, i) => {
const displayName = participantNames && participantNames[i] ? participantNames[i] : (p.slice(0, 6) + '...' + p.slice(-4));
const avatar = participantAvatars && participantAvatars[i] ? participantAvatars[i] : 'https://ui-avatars.com/api/?name=Circles';
return `<li style='display:flex;align-items:center;gap:8px;margin-bottom:6px;'><img src='${avatar}' alt='avatar' style='width:28px;height:28px;border-radius:50%;object-fit:cover;border:1.5px solid #ccc;'/><a href='https://app.gnosis.io/${p}' target='_blank' style='text-decoration:none;color:#4A90E2;'>@${displayName}</a></li>`;
}).join('') + `</ul></div>`;
}
const lotteryDetails = document.getElementById('lotteryDetails');
if (lotteryDetails) lotteryDetails.innerHTML = html;
// Hide buy button (no wallet interaction in this version)
const buyBtn = document.getElementById('buyTicketBtn');
if (buyBtn) buyBtn.style.display = 'none';
// After setting lotteryDetails.innerHTML = html;
// Add this code to start the countdown if active
if (status === 'ACTIVE' && now < end) {
const timerDiv = document.getElementById('countdown-timer');
function updateCountdown() {
const nowSec = Math.floor(Date.now() / 1000);
let diff = end - nowSec;
if (diff < 0) diff = 0;
const m = Math.floor(diff / 60);
const s = diff % 60;
timerDiv.innerHTML = `<b>${m}m ${s < 10 ? '0' : ''}${s}s until drawing</b>`;
if (diff > 0) setTimeout(updateCountdown, 1000);
else timerDiv.innerHTML = `<b>Lottery ended!</b>`;
}
updateCountdown();
}
// For the End label, if status is ACTIVE, show 'in X minutes' instead of a date:
let endLabel = '';
if (status === 'ACTIVE' && now < end) {
const diff = end - now;
if (diff < 60) endLabel = `in ${diff} seconds`;
else if (diff < 3600) endLabel = `in ${Math.floor(diff/60)} minutes`;
else if (diff < 86400) endLabel = `in ${Math.floor(diff/3600)} hours`;
else endLabel = `in ${Math.floor(diff/86400)} days`;
} else {
endLabel = new Date(end * 1000).toLocaleString();
}
// Replace the End line:
html += `<b>End:</b> ${endLabel}<br/>`;
}
// Add a cached version of getProfilesBatch
async function getProfilesBatchCached(addresses) {
if (!addresses || addresses.length === 0) return {};
const uncached = addresses.filter(a => !profileCache[a.toLowerCase()]);
let newProfiles = {};
if (uncached.length > 0) {
newProfiles = await getProfilesBatch(uncached);
Object.assign(profileCache, newProfiles);
}
// Merge cached and new
const result = {};
addresses.forEach(a => {
const key = a.toLowerCase();
if (profileCache[key]) result[key] = profileCache[key];
});
return result;
}
window.addEventListener('beforeunload', () => {
// Clean up event listeners on page unload
if (ticketBoughtListener && currentLotteryAddress) {
try {
provider.off({ address: currentLotteryAddress, topics: [ethers.utils.id('TicketBought(address,uint256)')] }, ticketBoughtListener);
} catch {}
}
});
</script>
</body>
</html>