Spaces:
Running
Running
File size: 12,481 Bytes
83820df |
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 |
// CryptoSphere - Cryptocurrency Tracker JavaScript
class CryptosphereTracker {
constructor() {
this.web3 = null;
this.provider = null;
this.connectedAccount = null;
this.cryptoData = [];
this.portfolioData = [];
this.currentPage = 1;
this.itemsPerPage = 12;
this.init();
}
async init() {
await this.registerServiceWorker();
this.setupEventListeners();
await this.loadCryptoData();
this.updateMarketStats();
this.setupRealTimeUpdates();
}
// Web3 Wallet Integration
async connectWallet() {
try {
if (window.ethereum) {
this.provider = window.ethereum;
this.web3 = new Web3(this.provider);
// Request account access
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
this.connectedAccount = accounts[0];
this.updateWalletStatus();
await this.loadPortfolioData();
// Listen for account changes
window.ethereum.on('accountsChanged', (accounts) => {
this.connectedAccount = accounts[0] || null;
this.updateWalletStatus();
});
} else {
throw new Error('No Ethereum wallet detected. Please install MetaMask.');
}
} catch (error) {
this.showNotification(error.message, 'error');
}
}
// Real-time Crypto Data from CoinGecko API
async fetchCryptoData(page = 1) {
const vsCurrency = 'usd';
const perPage = this.itemsPerPage;
try {
const response = await fetch(
`https://api.coingecko.com/api/v3/coins/markets?vs_currency=${vsCurrency}&order=market_cap_desc&per_page=${perPage}&page=${page}&sparkline=true&price_change_percentage=24h`
);
if (!response.ok) {
throw new Error('Failed to fetch crypto data');
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching crypto data:', error);
return this.getMockCryptoData(page);
}
}
// Mock data for demonstration
getMockCryptoData(page) {
const mockData = [];
const startIndex = (page - 1) * this.itemsPerPage;
const topCryptos = [
{ id: 'bitcoin', symbol: 'btc', name: 'Bitcoin' },
{ id: 'ethereum', symbol: 'eth', name: 'Ethereum' },
{ id: 'binancecoin', symbol: 'bnb', name: 'BNB' },
{ id: 'ripple', symbol: 'xrp', name: 'XRP' },
{ id: 'cardano', symbol: 'ada', name: 'Cardano' },
{ id: 'solana', symbol: 'sol', name: 'Solana' },
{ id: 'polkadot', symbol: 'dot', name: 'Polkadot' }
];
for (let i = 0; i < this.itemsPerPage; i++) {
const crypto = topCryptos[i % topCryptos.length];
const price = Math.random() * 50000 + 1000;
const change24h = (Math.random() - 0.5) * 20;
mockData.push({
id: crypto.id,
symbol: crypto.symbol,
name: crypto.name,
current_price: price,
price_change_percentage_24h: change24h,
market_cap: price * (Math.random() * 1000000),
total_volume: price * (Math.random() * 100000),
price_change_24h: change24h * price / 100,
image: `http://static.photos/finance/200x200/${startIndex + i + 1}`,
sparkline_in_7d: { price: Array(7).fill(0).map(() => price + (Math.random() - 0.5) * 1000
});
}
return mockData;
}
// Load and display crypto data
async loadCryptoData() {
const data = await this.fetchCryptoData(this.currentPage);
this.cryptoData = [...this.cryptoData, ...data];
this.renderCryptoData(data);
}
renderCryptoData(data) {
const grid = document.getElementById('crypto-grid');
data.forEach(crypto => {
const cryptoCard = document.createElement('crypto-card');
cryptoCard.setAttribute('data-crypto', JSON.stringify(crypto));
grid.appendChild(cryptoCard);
});
}
// Update global market statistics
updateMarketStats() {
// Simulate real-time market data updates
setInterval(() => {
const marketCap = (2.1 + Math.random() * 0.1).toFixed(1);
const volume = (78.4 + Math.random() * 5).toFixed(1);
const dominance = (52.3 + (Math.random() - 0.5)).toFixed(1);
document.getElementById('global-market-cap').textContent = `$${marketCap}T`;
document.getElementById('total-volume').textContent = `$${volume}B`;
document.getElementById('btc-dominance').textContent = `${dominance}%`;
}, 3000);
}
// Real-time price updates via WebSocket
setupRealTimeUpdates() {
// This would connect to a WebSocket service for real-time updates
// For demo purposes, we'll simulate with intervals
setInterval(() => {
this.updateLivePrices();
}, 5000);
}
updateLivePrices() {
const cards = document.querySelectorAll('crypto-card');
cards.forEach(card => {
const cryptoData = JSON.parse(card.getAttribute('data-crypto')));
// Simulate price changes
const change = (Math.random() - 0.5) * 2;
const newPrice = cryptoData.current_price * (1 + change / 100);
cryptoData.current_price = newPrice;
cryptoData.price_change_percentage_24h = change;
// Update the card
card.setAttribute('data-crypto', JSON.stringify(cryptoData));
});
}
// Load portfolio data from connected wallet
async loadPortfolioData() {
if (!this.connectedAccount) return;
try {
// In a real implementation, you would query the blockchain
// for the wallet's token holdings and their current values
// Mock portfolio data
this.portfolioData = [
{
id: 'bitcoin',
symbol: 'btc',
name: 'Bitcoin',
amount: Math.random() * 0.5,
value: Math.random() * 15000,
change24h: (Math.random() - 0.5) * 10
},
{
id: 'ethereum',
symbol: 'eth',
name: 'Ethereum',
amount: Math.random() * 10,
value: Math.random() * 20000
}
];
this.renderPortfolio();
} catch (error) {
console.error('Error loading portfolio:', error);
}
}
renderPortfolio() {
const container = document.getElementById('portfolio-container');
if (this.portfolioData.length === 0) {
container.innerHTML = `
<div class="text-center text-gray-400">
<i data-feather="alert-circle" class="w-16 h-16 mx-auto mb-4"></i>
<p>No crypto assets detected in your wallet</p>
`;
} else {
let totalValue = 0;
let totalChange = 0;
const portfolioHTML = this.portfolioData.map(asset => {
totalValue += asset.value;
totalChange += asset.change24h || 0;
return `
<div class="asset ${asset.change24h >= 0 ? 'portfolio-up' : 'portfolio-down'} p-4 mb-4 rounded-xl">
<div class="flex justify-between items-center">
<div class="flex items-center gap-3">
<img src="${asset.image || 'http://static.photos/finance/200x200'}" class="w-10 h-10 rounded-full">
<div>
<div class="font-semibold">${asset.name} (${asset.symbol.toUpperCase()})</div>
<div class="text-right">
<div class="font-bold">$${asset.value.toFixed(2)}</div>
<div class="text-sm ${asset.change24h >= 0 ? 'price-up' : 'price-down'}">
${asset.change24h >= 0 ? '+' : ''}${asset.change24h?.toFixed(2) || '0.00'}%</div>
</div>
</div>
</div>
`;
}).join('');
container.innerHTML = `
<h3 class="text-2xl font-bold text-white mb-6">Your Portfolio</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
${portfolioHTML}
</div>
<div class="mt-6 pt-6 border-t border-gray-600">
<div class="flex justify-between text-xl">
<span>Total Value:</span>
<span class="font-bold text-primary">$${totalValue.toFixed(2)}</div>
`;
}
}
feather.replace();
}
// Event listeners setup
setupEventListeners() {
// Connect wallet button
const connectBtn = document.getElementById('connect-wallet');
if (connectBtn) {
connectBtn.addEventListener('click', () => this.connectWallet());
}
// Load more cryptocurrencies
const loadMoreBtn = document.getElementById('load-more');
if (loadMoreBtn) {
loadMoreBtn.addEventListener('click', () => {
this.currentPage++;
this.loadCryptoData();
});
}
}
// Notification system
showNotification(message, type = 'info') {
const notification = document.createElement('div');
notification.className = `crypto-card p-4 mb-4 ${type === 'error' ? 'border-l-4 border-red-500' : 'border-l-4 border-primary'} crypto-notification`;
notification.innerHTML = `
<div class="flex items-center gap-3">
<i data-feather="${type === 'error' ? 'alert-triangle' : 'check-circle'}`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
notification.remove();
}, 5000);
feather.replace();
}
// Update wallet connection status
updateWalletStatus() {
const connectBtn = document.getElementById('connect-wallet');
if (this.connectedAccount) {
const shortAddress = `${this.connectedAccount.slice(0, 6)}...${this.connectedAccount.slice(-4)}`;
if (connectBtn) {
if (this.connectedAccount) {
connectBtn.innerHTML = `
<i data-feather="user-check" class="inline mr-2"></i>
${this.connectedAccount.slice(0, 6)}...${this.connectedAccount.slice(-4)}`;
} else {
connectBtn.innerHTML = `
<i data-feather="wallet" class="inline mr-2"></i>
${this.connectedAccount.slice(0, 6)}...${this.connectedAccount.slice(-4)}`;
}
}
// PWA Service Worker Registration
async registerServiceWorker() {
if ('serviceWorker' in navigator) {
try {
await navigator.serviceWorker.register('/crypto-sw.js');
console.log('Crypto Service Worker registered successfully');
} catch (error) {
console.error('Crypto Service Worker registration failed:', error);
}
}
}
}
// Initialize the crypto tracker when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
new CryptosphereTracker();
});
// Export for use in other modules
window.CryptosphereTracker = CryptosphereTracker; |