-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
675 lines (566 loc) · 21.7 KB
/
app.js
File metadata and controls
675 lines (566 loc) · 21.7 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
// App State
let state = {
session: null,
connected: false,
account: null,
activeBids: [],
myBids: [],
currentBidData: null
};
// Constants
const TELOS_RPC = 'https://mainnet.telos.net/v1';
const BACKUP_RPC = 'https://rpc.telos.net/v1';
const EOSIO_CONTRACT = 'eosio';
// Initialize App
document.addEventListener('DOMContentLoaded', async () => {
initializeUI();
await loadActiveBids();
setInterval(updateTimers, 1000);
setInterval(refreshActiveBids, 30000); // Refresh every 30 seconds
});
// UI Initialization
function initializeUI() {
// Tab switching
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', () => switchTab(btn.dataset.tab));
});
// Wallet connection
document.getElementById('connectWallet').addEventListener('click', connectWallet);
// Search functionality
document.getElementById('searchBtn').addEventListener('click', searchName);
document.getElementById('nameSearch').addEventListener('keypress', (e) => {
if (e.key === 'Enter') searchName();
});
// Bid history search
document.getElementById('historySearchBtn').addEventListener('click', searchBidHistory);
document.getElementById('historySearch').addEventListener('keypress', (e) => {
if (e.key === 'Enter') searchBidHistory();
});
// Refresh bids
document.getElementById('refreshBids').addEventListener('click', refreshActiveBids);
// Modal controls
document.querySelector('.modal-close').addEventListener('click', closeBidModal);
document.getElementById('overlay').addEventListener('click', closeBidModal);
document.getElementById('submitBid').addEventListener('click', submitBid);
// Modal bid amount input
document.getElementById('bidAmount').addEventListener('input', validateBidAmount);
}
// Wallet Connection (Anchor Link)
let anchorLink = null;
function initAnchorLink() {
const AnchorLink = TelosWallet.AnchorLink;
const AnchorLinkBrowserTransport = TelosWallet.AnchorLinkBrowserTransport;
const transport = new AnchorLinkBrowserTransport();
anchorLink = new AnchorLink({
transport,
chains: [{
chainId: '4667b205c6838ef70ff7988f6e8257e8be0e1284a2f59699054a018f743b1d11',
nodeUrl: 'https://mainnet.telos.net'
}]
});
}
async function connectWallet() {
try {
showStatus('Connecting to wallet...', 'info');
if (!anchorLink) initAnchorLink();
const identity = await anchorLink.login('telosnames');
state.session = identity.session;
state.connected = true;
state.account = String(identity.session.auth.actor);
updateWalletUI();
await loadMyBids();
showStatus('Wallet connected successfully!', 'success');
} catch (error) {
console.error('Wallet connection failed:', error);
if (error.message && error.message.includes('cancel')) {
showStatus('Wallet connection cancelled', 'info');
} else {
showStatus('Failed to connect wallet. Please try again.', 'error');
}
}
}
async function disconnectWallet() {
if (anchorLink && state.session) {
await anchorLink.removeSession('telosnames', state.session.auth);
}
state.session = null;
state.connected = false;
state.account = null;
state.myBids = [];
updateWalletUI();
renderMyBids();
showStatus('Wallet disconnected', 'info');
}
function updateWalletUI() {
const connectBtn = document.getElementById('connectWallet');
const walletText = document.getElementById('walletText');
if (state.connected && state.account) {
walletText.textContent = `${state.account}`;
connectBtn.onclick = disconnectWallet;
connectBtn.classList.add('connected');
} else {
walletText.textContent = 'Connect Wallet';
connectBtn.onclick = connectWallet;
connectBtn.classList.remove('connected');
}
}
// Tab Management
function switchTab(tabName) {
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.tab === tabName);
});
// Update content sections
document.querySelectorAll('.tab-content').forEach(content => {
content.classList.toggle('active', content.id === tabName);
});
// Load data if needed
if (tabName === 'mybids' && state.connected) {
loadMyBids();
}
}
// Data Fetching
async function fetchFromRPC(endpoint, body) {
const rpcs = [TELOS_RPC, BACKUP_RPC];
for (const rpc of rpcs) {
try {
const response = await fetch(`${rpc}/${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!response.ok) continue;
return await response.json();
} catch (error) {
console.warn(`RPC ${rpc} failed:`, error);
}
}
throw new Error('All RPC endpoints failed');
}
async function loadActiveBids() {
try {
let allRows = [];
let more = true;
let lowerBound = '';
while (more) {
const result = await fetchFromRPC('chain/get_table_rows', {
json: true,
code: EOSIO_CONTRACT,
scope: EOSIO_CONTRACT,
table: 'namebids',
limit: 500,
lower_bound: lowerBound
});
const rows = result.rows || [];
if (rows.length === 0) break;
// Avoid duplicates when paginating
if (lowerBound && rows.length > 0 && rows[0].newname === lowerBound) {
rows.shift();
}
allRows = allRows.concat(rows);
more = result.more;
if (rows.length > 0) {
lowerBound = rows[rows.length - 1].newname;
}
}
state.activeBids = allRows;
renderActiveBids();
} catch (error) {
console.error('Failed to load active bids:', error);
showStatus('Failed to load bids. Please try again.', 'error');
renderError('activeBids', 'Failed to load active bids');
}
}
async function loadMyBids() {
if (!state.connected) return;
try {
// Filter active bids for current user
state.myBids = state.activeBids.filter(bid =>
bid.high_bidder === state.account
);
renderMyBids();
} catch (error) {
console.error('Failed to load my bids:', error);
renderError('myBidsList', 'Failed to load your bids');
}
}
async function refreshActiveBids() {
document.getElementById('refreshBids').disabled = true;
await loadActiveBids();
if (state.connected) {
await loadMyBids();
}
document.getElementById('refreshBids').disabled = false;
}
// Name Search
async function searchName() {
const nameInput = document.getElementById('nameSearch');
const name = nameInput.value.trim().toLowerCase();
const resultDiv = document.getElementById('searchResult');
if (!name || name.length > 11) {
showStatus('Name must be 1-11 characters', 'error');
return;
}
try {
resultDiv.innerHTML = '<div class="loading">Searching...</div>';
resultDiv.classList.add('show');
// Check if account exists
let accountExists = false;
try {
const acctResult = await fetchFromRPC('chain/get_account', { account_name: name });
// If the response has account_name and no error, account exists
accountExists = !!(acctResult && acctResult.account_name && !acctResult.error);
} catch {
// Account doesn't exist
}
// Check if there's an active bid
const bidData = state.activeBids.find(bid => bid.newname === name);
let resultHTML = '';
if (accountExists) {
resultHTML = `
<div class="text-warning">
<strong>${name}</strong> - Account already exists
</div>
`;
} else if (bidData) {
const timeLeft = getTimeRemaining(bidData.last_bid_time);
resultHTML = `
<div class="bid-card">
<div class="bid-name">${bidData.newname}</div>
<div class="bid-amount">Current bid: ${formatBidAmount(bidData.high_bid)}</div>
<div class="bid-time">Time left: ${timeLeft}</div>
<div class="bid-actions">
<button class="btn btn-primary" onclick="openBidModal('${bidData.newname}')">
Place Bid
</button>
</div>
</div>
`;
} else {
resultHTML = `
<div class="text-success">
<strong>${name}</strong> - Available for bidding!
<button class="btn btn-primary" onclick="openBidModal('${name}')" style="margin-left: 1rem;">
Start Bidding
</button>
</div>
`;
}
resultDiv.innerHTML = resultHTML;
} catch (error) {
console.error('Search failed:', error);
resultDiv.innerHTML = '<div class="text-error">Search failed. Please try again.</div>';
}
}
// Bid History
async function searchBidHistory() {
const nameInput = document.getElementById('historySearch');
const name = nameInput.value.trim().toLowerCase();
const historyDiv = document.getElementById('bidHistory');
if (!name) {
showStatus('Please enter a name', 'error');
return;
}
try {
historyDiv.innerHTML = '<div class="loading">Loading bid history...</div>';
// For now, show current bid data if available
// In a full implementation, you'd query historical data
const currentBid = state.activeBids.find(bid => bid.newname === name);
let historyHTML = '';
if (currentBid) {
historyHTML = `
<div class="history-item">
<div class="history-header">
<span class="history-name">${currentBid.newname}</span>
<span>${formatBidAmount(currentBid.high_bid)}</span>
</div>
<div class="history-details">
Bidder: ${currentBid.high_bidder}<br>
Last bid: ${new Date(currentBid.last_bid_time + 'Z').toLocaleString()}
</div>
</div>
`;
} else {
historyHTML = '<div class="empty-state">No bid history found for this name</div>';
}
historyDiv.innerHTML = historyHTML;
} catch (error) {
console.error('History search failed:', error);
historyDiv.innerHTML = '<div class="text-error">Failed to load bid history</div>';
}
}
// Bidding
function openBidModal(name) {
if (!state.connected) {
showStatus('Please connect your wallet first', 'error');
return;
}
const modal = document.getElementById('bidModal');
const overlay = document.getElementById('overlay');
const nameDisplay = document.getElementById('modalNameDisplay');
nameDisplay.textContent = name;
// Find current bid data
const bidData = state.activeBids.find(bid => bid.newname === name);
state.currentBidData = bidData;
updateBidModalInfo(bidData);
modal.classList.add('show');
overlay.classList.add('show');
// Focus bid input
document.getElementById('bidAmount').focus();
}
function updateBidModalInfo(bidData) {
const currentBidEl = document.getElementById('currentBid');
const minimumBidEl = document.getElementById('minimumBid');
const timeRemainingEl = document.getElementById('timeRemaining');
const bidAmountInput = document.getElementById('bidAmount');
if (bidData) {
const currentBid = Math.abs(bidData.high_bid) / 10000;
const minimumBid = Math.ceil(currentBid * 1.1 * 10000) / 10000; // 10% higher, rounded
currentBidEl.textContent = formatBidAmount(bidData.high_bid);
minimumBidEl.textContent = `${minimumBid.toFixed(4)} TLOS`;
timeRemainingEl.textContent = getTimeRemaining(bidData.last_bid_time);
bidAmountInput.min = minimumBid;
bidAmountInput.value = minimumBid.toFixed(4);
} else {
// New bid
currentBidEl.textContent = 'None';
minimumBidEl.textContent = '10.0000 TLOS';
timeRemainingEl.textContent = '24 hours (after first bid)';
bidAmountInput.min = 10;
bidAmountInput.value = '10.0000';
}
}
function validateBidAmount() {
const input = document.getElementById('bidAmount');
const submitBtn = document.getElementById('submitBid');
const value = parseFloat(input.value);
const minValue = parseFloat(input.min);
if (value >= minValue) {
submitBtn.disabled = false;
input.style.borderColor = '';
} else {
submitBtn.disabled = true;
input.style.borderColor = 'var(--error)';
}
}
async function submitBid() {
if (!state.session) {
showStatus('Wallet not connected', 'error');
return;
}
const nameDisplay = document.getElementById('modalNameDisplay');
const bidAmountInput = document.getElementById('bidAmount');
const submitBtn = document.getElementById('submitBid');
const name = nameDisplay.textContent;
const amount = parseFloat(bidAmountInput.value);
if (!amount || amount < parseFloat(bidAmountInput.min)) {
showStatus('Invalid bid amount', 'error');
return;
}
try {
submitBtn.disabled = true;
submitBtn.textContent = 'Placing Bid...';
const actions = [{
account: EOSIO_CONTRACT,
name: 'bidname',
authorization: [{
actor: state.account,
permission: 'active'
}],
data: {
bidder: state.account,
newname: name,
bid: `${amount.toFixed(4)} TLOS`
}
}];
const result = await state.session.transact({ actions }, { broadcast: true });
showStatus('Bid placed successfully!', 'success');
closeBidModal();
// Refresh data after short delay
setTimeout(() => {
refreshActiveBids();
}, 2000);
} catch (error) {
console.error('Bid failed:', error);
showStatus(error.message || 'Failed to place bid', 'error');
} finally {
submitBtn.disabled = false;
submitBtn.textContent = 'Place Bid';
}
}
function closeBidModal() {
const modal = document.getElementById('bidModal');
const overlay = document.getElementById('overlay');
modal.classList.remove('show');
overlay.classList.remove('show');
state.currentBidData = null;
// Reset form
document.getElementById('bidAmount').value = '';
document.getElementById('submitBid').disabled = false;
}
// Rendering Functions
function formatBidAmount(highBid) {
// high_bid is an integer in units of 0.0001 TLOS
// Negative means auction was claimed/ended
const raw = typeof highBid === 'number' ? highBid : parseInt(highBid);
const amount = Math.abs(raw) / 10000;
return `${amount.toFixed(4)} TLOS`;
}
function isBidClaimed(highBid) {
const raw = typeof highBid === 'number' ? highBid : parseInt(highBid);
return raw < 0;
}
function renderActiveBids() {
const container = document.getElementById('activeBids');
if (!state.activeBids.length) {
container.innerHTML = '<div class="empty-state">No active bids found</div>';
return;
}
// Sort: active auctions first, then by bid amount descending
const sorted = [...state.activeBids].sort((a, b) => {
const aClaimed = isBidClaimed(a.high_bid);
const bClaimed = isBidClaimed(b.high_bid);
if (aClaimed !== bClaimed) return aClaimed ? 1 : -1;
return Math.abs(b.high_bid) - Math.abs(a.high_bid);
});
const html = sorted.map(bid => {
const timeLeft = getTimeRemaining(bid.last_bid_time);
const claimed = isBidClaimed(bid.high_bid);
const isMyBid = state.connected && bid.high_bidder === state.account;
const statusClass = claimed ? 'claimed' : '';
return `
<div class="bid-card ${isMyBid ? 'my-bid' : ''} ${statusClass}">
<div class="bid-name">${bid.newname}</div>
<div class="bid-amount">${formatBidAmount(bid.high_bid)}</div>
<div class="bid-time">${claimed ? 'Claimed' : `Time left: ${timeLeft}`}</div>
<div class="bid-time text-muted">Bidder: ${bid.high_bidder || 'unknown'}</div>
<div class="bid-actions">
${state.connected && !claimed ? `
<button class="btn btn-primary" onclick="openBidModal('${bid.newname}')">
${isMyBid ? 'Increase Bid' : 'Place Bid'}
</button>
` : ''}
</div>
</div>
`;
}).join('');
container.innerHTML = html;
}
function renderMyBids() {
const container = document.getElementById('myBidsList');
if (!state.connected) {
container.innerHTML = '<div class="empty-state">Connect your wallet to see your bids</div>';
return;
}
if (!state.myBids.length) {
container.innerHTML = '<div class="empty-state">You have no active bids</div>';
return;
}
const html = state.myBids.map(bid => {
const timeLeft = getTimeRemaining(bid.last_bid_time);
const isWinning = timeLeft === 'Auction ended';
return `
<div class="bid-card my-bid">
<div class="bid-name">${bid.newname}</div>
<div class="bid-amount">${formatBidAmount(bid.high_bid)}</div>
<div class="bid-time ${isWinning ? 'text-success' : ''}">
${isWinning ? 'Won!' : `Time left: ${timeLeft}`}
</div>
<div class="bid-actions">
${!isWinning ? `
<button class="btn btn-primary" onclick="openBidModal('${bid.newname}')">
Increase Bid
</button>
` : ''}
</div>
</div>
`;
}).join('');
container.innerHTML = html;
}
function renderError(containerId, message) {
const container = document.getElementById(containerId);
container.innerHTML = `<div class="error-state">${message}</div>`;
}
// Utility Functions
function formatTLOS(amount) {
if (typeof amount === 'string') return amount;
return `${amount.toFixed(4)} TLOS`;
}
function getTimeRemaining(lastBidTime) {
const bidTime = new Date(lastBidTime + 'Z');
const endTime = new Date(bidTime.getTime() + 24 * 60 * 60 * 1000); // 24 hours
const now = new Date();
const remaining = endTime.getTime() - now.getTime();
if (remaining <= 0) {
return 'Auction ended';
}
const hours = Math.floor(remaining / (1000 * 60 * 60));
const minutes = Math.floor((remaining % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((remaining % (1000 * 60)) / 1000);
if (hours > 0) {
return `${hours}h ${minutes}m`;
} else if (minutes > 0) {
return `${minutes}m ${seconds}s`;
} else {
return `${seconds}s`;
}
}
function updateTimers() {
// Update time remaining displays
document.querySelectorAll('.bid-time').forEach(el => {
if (el.textContent.includes('Time left:')) {
const bidCard = el.closest('.bid-card');
const nameEl = bidCard.querySelector('.bid-name');
if (nameEl) {
const name = nameEl.textContent;
const bidData = state.activeBids.find(bid => bid.newname === name);
if (bidData) {
const timeLeft = getTimeRemaining(bidData.last_bid_time);
el.textContent = `Time left: ${timeLeft}`;
if (timeLeft === 'Auction ended') {
el.classList.add('text-warning');
}
}
}
}
});
// Update modal if open
if (state.currentBidData) {
const timeRemainingEl = document.getElementById('timeRemaining');
if (timeRemainingEl) {
timeRemainingEl.textContent = getTimeRemaining(state.currentBidData.last_bid_time);
}
}
}
function showStatus(message, type = 'info') {
const container = document.getElementById('statusContainer');
const statusEl = document.createElement('div');
statusEl.className = `status-message status-${type}`;
statusEl.textContent = message;
container.appendChild(statusEl);
// Auto remove after 5 seconds
setTimeout(() => {
if (statusEl.parentNode) {
statusEl.parentNode.removeChild(statusEl);
}
}, 5000);
// Make it clickable to dismiss
statusEl.addEventListener('click', () => {
if (statusEl.parentNode) {
statusEl.parentNode.removeChild(statusEl);
}
});
}
// Add CSS for my-bid styling
const style = document.createElement('style');
style.textContent = `
.my-bid {
border-color: var(--telos-cyan) !important;
background: linear-gradient(135deg, var(--bg-secondary), rgba(0, 242, 254, 0.05)) !important;
}
.connected {
background: var(--gradient-secondary) !important;
}
`;
document.head.appendChild(style);