-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlottery.html
More file actions
838 lines (770 loc) · 34.6 KB
/
lottery.html
File metadata and controls
838 lines (770 loc) · 34.6 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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Circles Lottery</title>
<script src="https://unpkg.com/ethers@5.7.2/dist/ethers.umd.min.js"></script>
<script src="https://unpkg.com/@circles-sdk/sdk@latest/dist/umd/index.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
.error {
color: red;
padding: 10px;
margin: 10px 0;
background-color: #ffe6e6;
border-radius: 4px;
}
.lottery-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
gap: 20px;
margin-top: 20px;
}
.lottery-card {
background: white;
border: 1px solid #ddd;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.lottery-card.active {
border-left: 4px solid #4CAF50;
}
.lottery-card.ended {
border-left: 4px solid #FFA500;
}
.lottery-card.cancelled {
border-left: 4px solid #f44336;
}
.lottery-card.completed {
border-left: 4px solid #2196F3;
}
.lottery-card.unfunded {
border-left: 4px solid #9E9E9E;
}
button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
margin: 5px;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
button.cancel {
background-color: #f44336;
}
.status {
font-weight: bold;
margin-bottom: 10px;
}
.status.active { color: #4CAF50; }
.status.ended { color: #FFA500; }
.status.cancelled { color: #f44336; }
.status.completed { color: #2196F3; }
.status.unfunded { color: #9E9E9E; }
#walletButtons {
margin: 20px 0;
}
#walletButtons button {
margin-right: 10px;
}
.form-container {
background: white;
padding: 20px;
border-radius: 8px;
margin: 20px 0;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.form-group input {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
.form-group input[type="checkbox"] {
width: auto;
}
.tabs {
display: flex;
margin-bottom: 20px;
}
.tab {
padding: 10px 20px;
cursor: pointer;
border: 1px solid #ddd;
background: #f5f5f5;
}
.tab.active {
background: white;
border-bottom: none;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
</style>
</head>
<body>
<h1>Circles Lottery</h1>
<div id="error" class="error" style="display: none;"></div>
<div id="walletButtons">
<button onclick="connectWallet('metamask')">Connect MetaMask</button>
<button onclick="connectWallet('rabby')">Connect Rabby</button>
</div>
<div id="appContent" style="display: none;">
<div class="tabs">
<div class="tab active" onclick="showTab('default')">Test Lottery</div>
<div class="tab" onclick="showTab('custom')">Set up Lottery</div>
</div>
<div id="defaultTab" class="tab-content active">
<button id="createLottery" onclick="createDefaultLottery()">Create Test Lottery</button>
</div>
<div id="customTab" class="tab-content">
<div class="form-container">
<div class="form-group">
<label for="lotteryName">Lottery Name:</label>
<input type="text" id="lotteryName" placeholder="Enter lottery name">
</div>
<div class="form-group">
<label for="trustedAddress">Accepted CRC: <span title="What CRC needs to be used to buy a lottery ticket? This can be a group CRC or a personal CRC. As long as participants have a trust path to this CRC, they can buy a ticket. The sponsor will receive these CRC.">(i)</span></label>
<select id="trustedAddressSelect" onchange="handleTrustedAddressChange()"></select>
<input type="text" id="trustedAddress" placeholder="Enter accepted CRC address" style="display: none;">
<div style="color:#666;font-size:0.95em;margin-top:2px;">This is the CRC that must be used to buy a ticket. It can be a group or personal CRC. The sponsor will receive these CRC.</div>
</div>
<div class="form-group">
<label for="startTime">Start Time (leave empty for now):</label>
<input type="datetime-local" id="startTime">
</div>
<div class="form-group">
<label for="endTime">End Time:</label>
<select id="endTimeSelect" onchange="handleEndTimeChange()">
<option value="900">15 minutes</option>
<option value="3600">1 hour</option>
<option value="86400">24 hours</option>
<option value="259200">3 days</option>
<option value="604800">7 days</option>
<option value="custom">Custom...</option>
</select>
<input type="datetime-local" id="endTimeCustom" style="display:none; margin-top:8px;" />
</div>
<div class="form-group">
<label for="ticketPrice">Ticket Price (in CRC):</label>
<input type="number" id="ticketPrice" step="0.1" min="0.1" value="10">
</div>
<div class="form-group">
<label for="requireTrustedBy">Require Trust From (optional):</label>
<input type="text" id="requireTrustedBy" placeholder="Enter address or leave empty">
</div>
<div style="color:#666;font-size:0.95em;margin-top:2px;">If set, only users who are trusted by this address (group or person) can participate in the lottery.</div>
<div class="form-group">
<label for="prizeToken">Prize Token Address: <span title="Prize will be sent to the winner's Circles account. Gnosis currently only supports USDC, EURe, and GBPe.">(i)</span></label>
<select id="prizeTokenSelect" onchange="handlePrizeTokenChange()">
<option value="0x420CA0f9B9b604cE0fd9C18EF134C705e5Fa3430">EURe (0x420CA0f9B9b604cE0fd9C18EF134C705e5Fa3430)</option>
<option value="0x2a22f9c3b484c3629090FeED35F17Ff8F88f76F0">USDC (0x2a22f9c3b484c3629090FeED35F17Ff8F88f76F0)</option>
<option value="0x9c58bacc331c9aa871afd802db6379a98e80cedb">GNO (0x9c58bacc331c9aa871afd802db6379a98e80cedb)</option>
<option value="custom">Other (custom address)</option>
</select>
<input type="text" id="prizeToken" value="0x2a22f9c3b484c3629090FeED35F17Ff8F88f76F0" oninput="updatePrizeTokenInfo()" style="display:none;">
<div id="prizeTokenInfo" style="margin-top:4px; color:#666; font-size:0.95em;"></div>
<div style="color:#666;font-size:0.95em;margin-top:2px;">Prize will be sent to the winner's Circles account. Gnosis currently only supports USDC, EURe, and GBPe.</div>
</div>
<div class="form-group">
<label for="prizeAmount">Prize Amount: <span title="Number of tokens that get paid out. Someone must fund the new contract with this amount to activate the lottery.">(i)</span></label>
<input type="number" id="prizeAmount" step="any" min="0" value="1">
<span id="prizeAmountUnit"></span>
<div style="color:#666;font-size:0.95em;margin-top:2px;">Number of tokens to be paid out. The contract must be funded with this amount to activate the lottery.</div>
</div>
<div class="form-group">
<label for="sponsor">Sponsor Address (optional): <span title="Account that will receive CRC (e.g., your Circles account).">(i)</span></label>
<input type="text" id="sponsor" placeholder="Enter sponsor address or leave empty">
<div style="color:#666;font-size:0.95em;margin-top:2px;">Account that will receive CRC (e.g., your Circles account).</div>
</div>
<button onclick="createCustomLottery()">Create Custom Lottery</button>
</div>
</div>
<h2>Active Lotteries</h2>
<div id="lotteries" class="lottery-grid"></div>
</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;
}
});
const FACTORY_ADDRESS = '0x4B14679899A7AF92D947386Cb45D686C748BcA55';
const FACTORY_ABI = [
"function allDeployments() view returns (address[])",
"function createLotteryDefault() returns (address)",
"function transferLotteryOwnership(address lottery, address newOwner) external",
"function createLottery(string _lotteryName, address _trustedAddress, uint256 _startTime, uint256 _endTime, uint256 _ticketPrice, address _requireTrustedBy, address _prizeToken, uint256 _prizeAmount, address _sponsor) returns (address)"
];
// Remove the static TRUSTED_ADDRESSES and instead load dynamically
// Example endpoint (adjust if needed):
const GROUPS_URL = 'https://raw.githubusercontent.com/CirclesUBI/circles-group-config/main/groups.json';
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 drawWinner()",
"function cancelLottery()",
"function prizeToken() view returns (address)",
"function owner() view returns (address)",
"function transferOwnership(address) external",
"function requireTrustedBy() view returns (address)",
"function trustedAddress() view returns (address)",
"function acceptedId() view returns (uint256)",
"function participants(uint256) view returns (address)",
"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)"
];
let provider, signer, factory, myAddress;
async function connectWallet(walletType) {
try {
if (typeof ethers === 'undefined') {
showError('ethers.js library not loaded. Please refresh the page.');
return;
}
let ethereum;
if (walletType === 'metamask') {
if (!window.ethereum) {
showError('MetaMask is not installed');
return;
}
ethereum = window.ethereum;
} else if (walletType === 'rabby') {
if (!window.rabby) {
showError('Rabby is not installed');
return;
}
ethereum = window.rabby;
}
provider = new ethers.providers.Web3Provider(ethereum);
await provider.send("eth_requestAccounts", []);
signer = provider.getSigner();
factory = new ethers.Contract(FACTORY_ADDRESS, FACTORY_ABI, signer);
myAddress = await signer.getAddress();
// Show app content and hide wallet buttons
document.getElementById('walletButtons').style.display = 'none';
document.getElementById('appContent').style.display = 'block';
// Load lotteries
loadLotteries();
// Prefill the sponsor input with the connected account when wallet is connected
document.getElementById('sponsor').value = myAddress;
} catch (err) {
showError('Failed to connect wallet: ' + err.message);
}
}
function showError(message) {
const errorDiv = document.getElementById('error');
errorDiv.textContent = message;
errorDiv.style.display = 'block';
}
async function loadLotteries() {
try {
const lotteries = await factory.allDeployments();
const lotteryGrid = document.getElementById('lotteries');
lotteryGrid.innerHTML = '';
for (const address of lotteries) {
const lottery = new ethers.Contract(address, LOTTERY_ABI, signer);
// Get all lottery details
const [
name,
startTime,
endTime,
ticketPrice,
requireTrustedBy,
prizeToken,
prizeAmount,
isCancelled,
isDrawn,
totalTicketsSold,
participantCount,
owner,
trustedAddress,
acceptedId,
winner
] = await Promise.all([
lottery.lotteryName(),
lottery.startTime(),
lottery.endTime(),
lottery.ticketPrice(),
lottery.requireTrustedBy(),
lottery.prizeToken(),
lottery.prizeAmount(),
lottery.isCancelled(),
lottery.isDrawn(),
lottery.getTotalTicketsSold(),
lottery.getParticipantCount(),
lottery.owner(),
lottery.trustedAddress(),
lottery.acceptedId(),
lottery.winner()
]);
// Get token details
const tokenContract = new ethers.Contract(prizeToken, ERC20_ABI, signer);
const [tokenDecimals, tokenSymbol] = await Promise.all([
tokenContract.decimals(),
tokenContract.symbol()
]);
// Get current balance
const currentBalance = await tokenContract.balanceOf(address);
const isFunded = currentBalance.gte(prizeAmount);
// Create lottery card
const card = document.createElement('div');
card.className = `lottery-card ${!isFunded ? 'unfunded' : ''}`;
// Format times
const startDate = new Date(startTime.toNumber() * 1000);
const endDate = new Date(endTime.toNumber() * 1000);
const now = Math.floor(Date.now() / 1000);
// Determine status
let status = 'ACTIVE';
if (isCancelled) status = 'CANCELLED';
else if (isDrawn) status = 'DRAWN';
else if (now > endTime) status = 'ENDED';
else if (!isFunded) status = 'UNFUNDED';
else if (now < startTime) status = 'PENDING';
// Countdown logic
let endCountdownHtml = '';
if (status === 'ACTIVE') {
const secondsLeft = endTime - now;
function formatCountdown(secs) {
const d = Math.floor(secs / 86400);
const h = Math.floor((secs % 86400) / 3600);
const m = Math.floor((secs % 3600) / 60);
const s = secs % 60;
return `${d > 0 ? d + 'd ' : ''}${h > 0 ? h + 'h ' : ''}${m > 0 ? m + 'm ' : ''}${s}s`;
}
endCountdownHtml = `<span id="countdown-${address}">${formatCountdown(secondsLeft)} left</span>`;
setTimeout(function updateCountdown() {
const el = document.getElementById(`countdown-${address}`);
if (!el) return;
const left = Math.max(0, endTime - Math.floor(Date.now() / 1000));
el.textContent = left > 0 ? formatCountdown(left) + ' left' : 'ENDED';
if (left > 0) setTimeout(updateCountdown, 1000);
}, 1000);
} else {
endCountdownHtml = endDate.toLocaleString();
}
const gnosisUrl = `https://app.gnosis.io/transfer/${address}`;
card.innerHTML = `
<h3><a href="lottery-participate.html?address=${address}" style="color:#4A90E2;text-decoration:underline;">${name}</a></h3>
<p>Status: <span class="status ${status.toLowerCase()}">${status}</span></p>
<p>Owner: ${owner}</p>
<p>Accepted CRC: ${trustedAddress}</p>
<p>Accepted Token ID: ${acceptedId}</p>
<p>Start: ${startDate.toLocaleString()}</p>
<p>End: ${endCountdownHtml}</p>
<p>Ticket Price: ${ethers.utils.formatEther(ticketPrice)} CRC</p>
<p>Prize: ${ethers.utils.formatUnits(prizeAmount, tokenDecimals)} ${tokenSymbol}</p>
<p>Current Balance: ${ethers.utils.formatUnits(currentBalance, tokenDecimals)} ${tokenSymbol}</p>
${status === 'UNFUNDED' ? `<div style='margin:12px 0 8px 0; font-size:1.08em; color:#e67e22;'><b>⚠️ This lottery is not yet funded.<br>To fund, send ${ethers.utils.formatUnits(prizeAmount, tokenDecimals)} ${tokenSymbol} to <span style='font-family:monospace;'>${address}</span> (lottery address).</b></div>` : ''}
<p>Total Tickets Sold: ${totalTicketsSold}</p>
${isDrawn ? `<p><b>Winner:</b> <span id="winner-${address}">${winner}</span></p>` : ''}
${requireTrustedBy !== ethers.constants.AddressZero ? `<p>Requires Trust From: ${requireTrustedBy}</p>` : ''}
<p>Gnosis Link: <a href='${gnosisUrl}' target='_blank' style='color:#4A90E2;font-weight:bold;'>Fund Lottery from Gnosis</a></p>
<div class="button-container">
${status === 'ENDED' && !isDrawn && participantCount > 0 ? `
<button onclick="drawWinner('${address}')">Draw Winner</button>
` : ''}
${status === 'ENDED' && !isDrawn && participantCount === 0 ? `
<button onclick="cancelLottery('${address}')">Cancel Lottery</button>
` : ''}
${(status === 'ENDED' || status === 'DRAWN' || status === 'CANCELLED') && myAddress && owner.toLowerCase() === myAddress.toLowerCase() && currentBalance.gt(0) ? `
<button onclick="claimRemainder('${address}')">Claim Remainder</button>
` : ''}
</div>
<div id="participants-${address}" style="margin-top:10px;"></div>
`;
lotteryGrid.appendChild(card);
// List participants (with Circles profile name if available)
(async () => {
try {
const count = Number(participantCount);
if (count > 0) {
let participants = [];
for (let i = 0; i < count; i++) {
try {
const addr = await lottery.participants(i);
participants.push(addr);
} catch (e) { break; }
}
// Fetch profile names in parallel
const names = await Promise.all(participants.map(addr => getProfileName(addr)));
document.getElementById(`participants-${address}`).innerHTML =
`<b>Participants:</b><ul style='margin:4px 0 0 16px;'>${participants.map((p, i) => `<li><a href='https://app.gnosis.io/${p}' target='_blank' style='text-decoration:none;color:#4A90E2;'>@${names[i] ? names[i] : p.slice(0, 6) + '...' + p.slice(-4)}</a> (${p})</li>`).join('')}</ul>`;
}
} catch {}
})();
// Show winner name if drawn
if (isDrawn && winner && winner !== ethers.constants.AddressZero) {
getProfileName(winner).then(name => {
const el = document.getElementById(`winner-${address}`);
if (el) el.textContent = name ? `${name} (${winner})` : winner;
});
}
}
} catch (error) {
console.error('Error loading lotteries:', error);
showError('Failed to load lotteries: ' + error.message);
}
}
async function createDefaultLottery() {
try {
const button = document.getElementById('createLottery');
button.disabled = true;
const tx = await factory.createLotteryDefault();
await tx.wait();
await loadLotteries();
} catch (err) {
showError('Failed to create lottery: ' + err.message);
} finally {
document.getElementById('createLottery').disabled = false;
}
}
async function drawWinner(address) {
try {
const lottery = new ethers.Contract(address, LOTTERY_ABI, signer);
const tx = await lottery.drawWinner();
await tx.wait();
await loadLotteries();
} catch (err) {
showError('Failed to draw winner: ' + err.message);
}
}
async function cancelLottery(address) {
try {
const lottery = new ethers.Contract(address, LOTTERY_ABI, signer);
const tx = await lottery.cancelLottery();
await tx.wait();
await loadLotteries();
} catch (err) {
showError('Failed to cancel lottery: ' + err.message);
}
}
async function withdrawFunds(address) {
try {
const lottery = new ethers.Contract(address, LOTTERY_ABI, signer);
const tx = await lottery.withdrawFunds();
await tx.wait();
await loadLotteries();
} catch (err) {
showError('Failed to withdraw funds: ' + err.message);
}
}
async function transferOwnership(address) {
try {
const myAddress = await signer.getAddress();
const tx = await factory.transferLotteryOwnership(address, myAddress);
await tx.wait();
await loadLotteries();
} catch (err) {
showError('Failed to transfer ownership: ' + err.message);
}
}
function showTab(tabName) {
// Hide all tabs
document.querySelectorAll('.tab-content').forEach(tab => {
tab.classList.remove('active');
});
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.remove('active');
});
// Show selected tab
document.getElementById(tabName + 'Tab').classList.add('active');
document.querySelector(`.tab[onclick="showTab('${tabName}')"]`).classList.add('active');
}
function handleTrustedAddressChange() {
const select = document.getElementById('trustedAddressSelect');
const input = document.getElementById('trustedAddress');
if (select.value === 'custom') {
input.style.display = 'block';
input.value = '';
input.required = true;
} else {
input.style.display = 'none';
input.value = select.value;
input.required = false;
}
}
function handleEndTimeChange() {
const select = document.getElementById('endTimeSelect');
const customInput = document.getElementById('endTimeCustom');
if (select.value === 'custom') {
customInput.style.display = 'block';
customInput.required = true;
} else {
customInput.style.display = 'none';
customInput.required = false;
}
}
let prizeTokenDecimals = 18;
let prizeTokenSymbol = '';
async function updatePrizeTokenInfo() {
const address = document.getElementById('prizeToken').value;
const infoDiv = document.getElementById('prizeTokenInfo');
const unitSpan = document.getElementById('prizeAmountUnit');
if (!ethers.utils.isAddress(address)) {
infoDiv.textContent = '';
unitSpan.textContent = '';
prizeTokenDecimals = 18;
prizeTokenSymbol = '';
return;
}
try {
const provider = new ethers.providers.Web3Provider(window.ethereum || window.rabby || window.web3?.currentProvider);
const erc20 = new ethers.Contract(address, ["function name() view returns (string)", "function symbol() view returns (string)", "function decimals() view returns (uint8)"], provider);
const [name, symbol, decimals] = await Promise.all([
erc20.name(),
erc20.symbol(),
erc20.decimals()
]);
infoDiv.textContent = `Token: ${name} (${symbol}), Decimals: ${decimals}`;
unitSpan.textContent = symbol ? symbol : '';
prizeTokenDecimals = decimals;
prizeTokenSymbol = symbol;
} catch (e) {
infoDiv.textContent = 'Could not fetch token info';
unitSpan.textContent = '';
prizeTokenDecimals = 18;
prizeTokenSymbol = '';
}
}
// Call on load for default value
setTimeout(updatePrizeTokenInfo, 100);
async function createCustomLottery() {
try {
const name = document.getElementById('lotteryName').value;
const trustedAddressSelect = document.getElementById('trustedAddressSelect');
const trustedAddress = trustedAddressSelect.value === 'custom'
? document.getElementById('trustedAddress').value
: trustedAddressSelect.value;
const startTimeInput = document.getElementById('startTime').value;
const endTimeSelect = document.getElementById('endTimeSelect');
const endTimeCustom = document.getElementById('endTimeCustom').value;
const ticketPrice = document.getElementById('ticketPrice').value;
const requireTrustedBy = document.getElementById('requireTrustedBy').value;
const prizeToken = document.getElementById('prizeToken').value;
const prizeAmountHuman = document.getElementById('prizeAmount').value;
const sponsor = document.getElementById('sponsor').value;
// Validate inputs
if (!name) throw new Error('Lottery name is required');
if (!trustedAddress) throw new Error('Trusted address is required');
if (!ticketPrice || ticketPrice <= 0) throw new Error('Ticket price must be greater than 0');
if (!prizeToken) throw new Error('Prize token address is required');
if (!prizeAmountHuman || prizeAmountHuman <= 0) throw new Error('Prize amount must be greater than 0');
// Convert times to timestamps
const startTime = startTimeInput ? Math.floor(new Date(startTimeInput).getTime() / 1000) : Math.floor(Date.now() / 1000);
let endTime;
if (endTimeSelect.value === 'custom') {
if (!endTimeCustom) throw new Error('Custom end time is required');
endTime = Math.floor(new Date(endTimeCustom).getTime() / 1000);
} else {
endTime = startTime + parseInt(endTimeSelect.value, 10);
}
// Convert human amount to token units
const prizeAmount = ethers.utils.parseUnits(prizeAmountHuman.toString(), prizeTokenDecimals);
// Create lottery
const ticketPriceWei = ethers.utils.parseEther(ticketPrice.toString());
const tx = await factory.createLottery(
name,
trustedAddress,
startTime,
endTime,
ticketPriceWei,
requireTrustedBy || ethers.constants.AddressZero,
prizeToken,
prizeAmount,
sponsor || ethers.constants.AddressZero
);
await tx.wait();
await loadLotteries();
// Reset form
document.getElementById('lotteryName').value = '';
document.getElementById('trustedAddressSelect').value = 'custom';
document.getElementById('startTime').value = '';
document.getElementById('endTimeSelect').value = '900';
document.getElementById('endTimeCustom').value = '';
document.getElementById('ticketPrice').value = '10';
document.getElementById('requireTrustedBy').value = '';
document.getElementById('prizeToken').value = '0x2a22f9c3b484c3629090FeED35F17Ff8F88f76F0';
document.getElementById('prizeAmount').value = '1';
document.getElementById('sponsor').value = '';
showTab('default');
} catch (err) {
showError('Failed to create lottery: ' + err.message);
}
}
// Remove previous group loading logic and use the RPC approach from lbpStarter.html
const CIRCLES_RPC = "https://rpc.aboutcircles.com/";
async function fetchGroupAddresses() {
const requestBody = {
jsonrpc: "2.0",
id: 1,
method: "circles_query",
params: [
{
Namespace: "V_CrcV2",
Table: "TrustRelations",
Columns: [],
Filter: [
{
Type: "FilterPredicate",
FilterType: "Equals",
Column: "truster",
Value: "0x0afd8899bca011bb95611409f09c8efbf6b169cf",
},
],
},
],
};
try {
const response = await fetch(CIRCLES_RPC, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(requestBody),
});
const data = await response.json();
if (data.result && data.result.rows) {
// Extract unique trustee addresses from the rows (trustee is at index 5)
const addresses = Array.from(new Set(data.result.rows.map(row => row[5])));
return addresses;
}
} catch (e) { /* ignore */ }
return [];
}
// Helper: get group token name (static ERC20 name)
async function getGroupTokenName(address) {
if (!ethers.utils.isAddress(address)) return null;
const LIFT_ADDRESS = '0x5F99a795dD2743C36D63511f0D4bc667e6d3cDB5';
const liftAbi = ["function erc20Circles(uint8 circlesType, address avatar) view returns (address)"];
const erc20Abi = ["function name() view returns (string)"];
try {
const provider = new ethers.providers.Web3Provider(window.ethereum || window.rabby || window.web3?.currentProvider);
const lift = new ethers.Contract(LIFT_ADDRESS, liftAbi, provider);
const erc20 = await lift.erc20Circles(0, address);
if (erc20 && erc20 !== ethers.constants.AddressZero) {
const token = new ethers.Contract(erc20, erc20Abi, provider);
const name = await token.name();
if (name && name.length > 0) return name;
}
} catch (e) {}
return null;
}
document.addEventListener('DOMContentLoaded', async function() {
const select = document.getElementById('trustedAddressSelect');
if (select) {
select.innerHTML = '';
const addresses = await fetchGroupAddresses();
// Fetch token names in parallel
const namePromises = addresses.map(addr => getGroupTokenName(addr));
const names = await Promise.all(namePromises);
addresses.forEach((addr, i) => {
const option = document.createElement('option');
option.value = addr;
option.textContent = names[i] && names[i].length > 0 ? `${names[i]} (${addr})` : addr;
select.appendChild(option);
});
// Always add Custom Address at the end
const customOption = document.createElement('option');
customOption.value = 'custom';
customOption.textContent = 'Custom Address';
select.appendChild(customOption);
// After populating the trustedAddressSelect options, set its value to the CRC Backer address (lowercase):
const CRC_BACKER_ADDRESS = '0x1aca75e38263c79d9d4f10df0635cc6fcfe6f026';
const backerOption = Array.from(select.options).find(opt => opt.value.toLowerCase() === CRC_BACKER_ADDRESS);
if (backerOption) select.value = CRC_BACKER_ADDRESS;
}
});
async function claimRemainder(address) {
try {
const lottery = new ethers.Contract(address, LOTTERY_ABI, signer);
const tx = await lottery.claimRemainder();
await tx.wait();
await loadLotteries();
} catch (err) {
showError('Failed to claim remainder: ' + err.message);
}
}
// Helper: get Circles profile name for an address using simple RPC request
async function getProfileName(address) {
if (!address || address === ethers.constants.AddressZero) return null;
try {
const queryAddress = address.toLowerCase();
const url = `https://rpc.aboutcircles.com/profiles/search?address=${queryAddress}`;
const response = await fetch(url);
if (!response.ok) return null;
const data = await response.json();
if (Array.isArray(data)) {
const profile = data.find(entry => entry.address.toLowerCase() === queryAddress);
return profile?.name || null;
}
return null;
} catch (e) {
return null;
}
}
// Helper: resolve avatar URL (handle ipfs:// and fallback)
function resolveAvatarUrl(avatar) {
if (!avatar) return 'https://ui-avatars.com/api/?name=Circles'; // fallback image
if (avatar.startsWith('ipfs://')) {
return 'https://ipfs.io/ipfs/' + avatar.replace('ipfs://', '');
}
return avatar;
}
function handlePrizeTokenChange() {
const select = document.getElementById('prizeTokenSelect');
const input = document.getElementById('prizeToken');
if (select.value === 'custom') {
input.style.display = 'block';
input.value = '';
input.required = true;
} else {
input.style.display = 'none';
input.value = select.value;
input.required = false;
updatePrizeTokenInfo();
}
}
document.getElementById('prizeTokenSelect').addEventListener('change', handlePrizeTokenChange);
// On page load, set the default value
handlePrizeTokenChange();
</script>
</body>
</html>