-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
492 lines (423 loc) · 17.1 KB
/
script.js
File metadata and controls
492 lines (423 loc) · 17.1 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
class NanoSol {
constructor() {
// La conexión se inicializará solo si window.solana está disponible.
// Si no está, se hará más tarde.
this.connection = null;
this.wallet = null;
this.publicKey = null;
this.transactions = [];
}
// Nuevo método para inicializar la conexión, que requiere solanaWeb3
initializeConnection() {
if (!this.connection && typeof solanaWeb3 !== 'undefined') {
try {
this.connection = new solanaWeb3.Connection(
'https://api.mainnet-beta.solana.com',
'confirmed'
);
console.log('NanoSol: Conexión a Solana Web3 inicializada.');
} catch (e) {
console.error('NanoSol: Error al inicializar solanaWeb3.Connection:', e);
}
}
}
init() {
console.log('NanoSol: Inicializando aplicación...');
this.initializeConnection(); // Intentar inicializar la conexión al principio
this.setupEventListeners();
this.checkWalletConnection();
console.log('NanoSol: Event listeners y chequeo de conexión configurados.');
}
setupEventListeners() {
// Wallet connection
const connectWalletBtn = document.getElementById('connectWallet');
if (connectWalletBtn) {
connectWalletBtn.addEventListener('click', () => {
this.connectWallet();
});
} else {
console.warn("Elemento 'connectWallet' no encontrado. Verifica index.html.");
}
// Copy address
const copyAddressBtn = document.getElementById('copyAddress');
if (copyAddressBtn) {
copyAddressBtn.addEventListener('click', () => {
this.copyAddress();
});
} else {
console.warn("Elemento 'copyAddress' no encontrado. Verifica index.html.");
}
// Send payment
const sendPaymentBtn = document.getElementById('sendPayment');
if (sendPaymentBtn) {
sendPaymentBtn.addEventListener('click', (event) => { // Añadir event para prevenir default
event.preventDefault(); // Evitar el envío de formulario si está dentro de uno
this.sendPayment();
});
} else {
console.warn("Elemento 'sendPayment' no encontrado. Verifica index.html.");
}
// Generate QR code
const generateQRBtn = document.getElementById('generateQR');
if (generateQRBtn) {
generateQRBtn.addEventListener('click', () => {
this.generateQRCode();
});
} else {
console.warn("Elemento 'generateQR' no encontrado. Verifica index.html.");
}
// Quick amount buttons
document.querySelectorAll('.amount-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
const amount = e.target.dataset.amount;
this.generateQRCode(amount);
});
});
// Form validation
const recipientAddressInput = document.getElementById('recipientAddress');
if (recipientAddressInput) {
recipientAddressInput.addEventListener('input', () => {
this.validateForm();
});
} else {
console.warn("Elemento 'recipientAddress' no encontrado. Verifica index.html.");
}
const amountInput = document.getElementById('amount');
if (amountInput) {
amountInput.addEventListener('input', () => {
this.validateForm();
});
} else {
console.warn("Elemento 'amount' no encontrado. Verifica index.html.");
}
// Close notification
const closeNotificationBtn = document.getElementById('closeNotification');
if (closeNotificationBtn) {
closeNotificationBtn.addEventListener('click', () => {
this.hideNotification();
});
} else {
console.warn("Elemento 'closeNotification' no encontrado. Verifica index.html.");
}
}
async checkWalletConnection() {
console.log('NanoSol: Chequeando conexión de billetera...');
if (window.solana && window.solana.isPhantom) {
try {
const response = await window.solana.connect({ onlyIfTrusted: true });
this.handleWalletConnect(response.publicKey);
console.log('NanoSol: Billetera conectada automáticamente (trusted).');
} catch (error) {
console.log('NanoSol: Billetera no conectada o no trusted.');
// No notificar error si onlyIfTrusted falla, es un comportamiento esperado.
}
} else {
console.log('NanoSol: Phantom Wallet no detectada al inicio (esperando).');
// No deshabilitamos el botón, permitimos que el usuario intente conectarse.
}
}
async connectWallet() {
console.log('NanoSol: Intentando conectar billetera...');
if (!window.solana || !window.solana.isPhantom) {
this.showNotification('Por favor, instala la extensión Phantom Wallet.', 'error');
console.error('Phantom Wallet no instalada o no detectada.');
return;
}
try {
this.showLoading(true);
const response = await window.solana.connect();
this.handleWalletConnect(response.publicKey);
this.showNotification('Billetera conectada con éxito!', 'success');
console.log('NanoSol: Conexión de billetera exitosa.');
} catch (error) {
console.error('NanoSol: Falló la conexión de la billetera:', error);
this.showNotification(`Falló la conexión: ${error.message || error}`, 'error');
} finally {
this.showLoading(false);
}
}
async handleWalletConnect(publicKey) {
this.publicKey = publicKey;
this.wallet = window.solana;
const connectWalletBtn = document.getElementById('connectWallet');
if (connectWalletBtn) {
connectWalletBtn.textContent = 'Conectado';
connectWalletBtn.disabled = true;
}
const walletInfoDiv = document.getElementById('walletInfo');
if (walletInfoDiv) {
walletInfoDiv.classList.remove('hidden');
}
const address = publicKey.toString();
const walletAddressSpan = document.getElementById('walletAddress');
if (walletAddressSpan) {
walletAddressSpan.textContent =
`${address.slice(0, 8)}...${address.slice(-8)}`;
}
// Asegurarse de que la conexión esté inicializada antes de usarla
this.initializeConnection();
if (this.connection) {
await this.updateBalance();
} else {
console.error('NanoSol: No se pudo actualizar el balance: la conexión a Solana no está lista.');
this.showNotification('Error: Conexión a Solana no establecida.', 'error');
}
this.validateForm();
console.log('NanoSol: UI de billetera actualizada.');
}
async updateBalance() {
if (!this.publicKey || !this.connection) {
console.log('NanoSol: No hay clave pública o conexión para actualizar el balance.');
return;
}
try {
const balance = await this.connection.getBalance(this.publicKey);
const solBalance = balance / solanaWeb3.LAMPORTS_PER_SOL;
const solBalanceSpan = document.getElementById('solBalance');
if (solBalanceSpan) {
solBalanceSpan.textContent = solBalance.toFixed(4);
}
console.log(`NanoSol: Balance actualizado: ${solBalance.toFixed(4)} SOL`);
} catch (error) {
console.error('NanoSol: Falló la obtención del balance:', error);
this.showNotification('Falló la obtención del balance.', 'error');
}
}
validateForm() {
const addressInput = document.getElementById('recipientAddress');
const amountInput = document.getElementById('amount');
const sendBtn = document.getElementById('sendPayment');
if (!addressInput || !amountInput || !sendBtn) {
console.warn("NanoSol: Elementos del formulario no encontrados para validación.");
return;
}
const address = addressInput.value.trim();
const amount = parseFloat(amountInput.value);
const isValidAddress = this.isValidSolanaAddress(address);
const isValidAmount = amount > 0 && !isNaN(amount);
const isWalletConnected = this.publicKey !== null;
sendBtn.disabled = !(isValidAddress && isValidAmount && isWalletConnected);
}
isValidSolanaAddress(address) {
try {
new solanaWeb3.PublicKey(address);
return true;
} catch {
return false;
}
}
async sendPayment() {
const recipientAddress = document.getElementById('recipientAddress').value.trim();
const amount = parseFloat(document.getElementById('amount').value);
const memo = document.getElementById('memo').value.trim();
const tokenType = document.getElementById('tokenType').value; // Usado pero no implementado para SPL tokens
if (!this.publicKey || !this.wallet || !this.connection) {
this.showNotification('Por favor, conecta tu billetera y asegura la conexión a Solana.', 'error');
console.warn('NanoSol: Intento de envío de pago sin billetera conectada o conexión a Solana.');
return;
}
try {
this.showLoading(true);
const recipientPublicKey = new solanaWeb3.PublicKey(recipientAddress);
const lamports = amount * solanaWeb3.LAMPORTS_PER_SOL;
const transaction = new solanaWeb3.Transaction();
transaction.add(
solanaWeb3.SystemProgram.transfer({
fromPubkey: this.publicKey,
toPubkey: recipientPublicKey,
lamports: lamports,
})
);
if (memo) {
transaction.add(
new solanaWeb3.TransactionInstruction({
keys: [{ pubkey: this.publicKey, isSigner: true, isWritable: false }],
data: Buffer.from(memo, 'utf-8'),
programId: new solanaWeb3.PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'),
})
);
}
const { blockhash } = await this.connection.getLatestBlockhash();
transaction.recentBlockhash = blockhash;
transaction.feePayer = this.publicKey;
const signedTransaction = await this.wallet.signTransaction(transaction);
const signature = await this.connection.sendRawTransaction(signedTransaction.serialize());
console.log('NanoSol: Transacción enviada, firma:', signature);
this.showNotification('Transacción enviada! Confirmando...', 'info');
await this.connection.confirmTransaction(signature);
this.addTransaction({
signature,
type: 'sent',
amount,
address: recipientAddress,
memo,
status: 'success',
timestamp: new Date()
});
document.getElementById('recipientAddress').value = '';
document.getElementById('amount').value = '';
document.getElementById('memo').value = '';
await this.updateBalance();
this.showNotification(`Enviado ${amount} SOL con éxito!`, 'success');
} catch (error) {
console.error('NanoSol: Transacción fallida:', error);
this.showNotification(`Transacción fallida: ${error.message || error}`, 'error');
} finally {
this.showLoading(false);
this.validateForm();
}
}
async generateQRCode(amount = null) {
if (!this.publicKey) {
this.showNotification('Por favor, conecta tu billetera primero.', 'error');
return;
}
const requestAmount = amount || document.getElementById('amount').value || '0.001';
const address = this.publicKey.toString();
const solanaPayUrl = `solana:${address}?amount=${requestAmount}&label=NanoSol%20Payment`;
try {
const canvas = document.getElementById('qrCode');
if (canvas) {
await QRCode.toCanvas(canvas, solanaPayUrl, {
width: 200,
margin: 2,
color: {
dark: '#4c1d95',
light: '#ffffff'
}
});
this.showNotification(`Código QR generado para ${requestAmount} SOL`, 'success');
console.log(`NanoSol: QR generado para ${requestAmount} SOL`);
} else {
console.warn("Elemento 'qrCode' (canvas) no encontrado. Verifica index.html.");
this.showNotification('Falló la generación del código QR: elemento QR faltante.', 'error');
}
} catch (error) {
console.error('NanoSol: Falló la generación del código QR:', error);
this.showNotification('Falló la generación del código QR.', 'error');
}
}
copyAddress() {
if (!this.publicKey) return;
const address = this.publicKey.toString();
navigator.clipboard.writeText(address).then(() => {
this.showNotification('Dirección copiada al portapapeles!', 'success');
console.log('NanoSol: Dirección copiada.');
}).catch(() => {
this.showNotification('Falló al copiar la dirección.', 'error');
console.error('NanoSol: Falló al copiar la dirección.');
});
}
addTransaction(transaction) {
this.transactions.unshift(transaction);
this.updateTransactionHistory();
}
updateTransactionHistory() {
const container = document.getElementById('transactionList');
if (!container) {
console.warn("Elemento 'transactionList' no encontrado. Verifica index.html.");
return;
}
if (this.transactions.length === 0) {
container.innerHTML = '<p class="no-transactions">No hay transacciones aún</p>';
return;
}
container.innerHTML = this.transactions.map(tx => `
<div class="transaction-item">
<div class="transaction-info">
<div class="transaction-amount">
${tx.type === 'sent' ? '-' : '+'}${tx.amount} SOL
</div>
<div class="transaction-address">
${tx.type === 'sent' ? 'Para: ' : 'De: '}${tx.address.slice(0, 8)}...${tx.address.slice(-8)}
</div>
${tx.memo ? `<div class="transaction-memo">${tx.memo}</div>` : ''}
</div>
<div class="transaction-status status-${tx.status}">
${tx.status}
</div>
</div>
`).join('');
}
showNotification(message, type = 'info') {
const notification = document.getElementById('notification');
const text = document.getElementById('notificationText');
if (!notification || !text) {
console.warn("NanoSol: Elementos de notificación no encontrados.");
return;
}
text.textContent = message;
notification.className = `notification ${type}`;
notification.classList.remove('hidden');
setTimeout(() => {
this.hideNotification();
}, 5000);
}
hideNotification() {
const notification = document.getElementById('notification');
if (notification) {
notification.classList.add('hidden');
}
}
showLoading(show) {
const overlay = document.getElementById('loadingOverlay');
if (overlay) {
if (show) {
overlay.classList.remove('hidden');
} else {
overlay.classList.add('hidden');
}
}
}
}
// =========================================================================
// Inicialización de la aplicación: Estrategia más robusta para Phantom Wallet
// =========================================================================
let nanoSolApp; // Declaramos la instancia fuera para que sea accesible globalmente si es necesario
// Función para inicializar NanoSol una vez que window.solana esté disponible
function tryInitializeNanoSol() {
if (window.solana && window.solana.isPhantom) {
console.log('Phantom Wallet detectada. Inicializando NanoSol...');
if (!nanoSolApp) { // Solo inicializar si no se ha hecho ya
nanoSolApp = new NanoSol();
nanoSolApp.init();
// Configurar listeners de Phantom una vez que la instancia de NanoSol exista
window.solana.on('connect', (publicKey) => {
console.log('Evento Phantom: Billetera conectada:', publicKey.toString());
if (!nanoSolApp.publicKey || nanoSolApp.publicKey.toString() !== publicKey.toString()) {
nanoSolApp.handleWalletConnect(publicKey);
nanoSolApp.showNotification('Billetera reconectada!', 'success');
}
});
window.solana.on('disconnect', () => {
console.log('Evento Phantom: Billetera desconectada. Recargando página...');
location.reload(); // Recargar para limpiar el estado
});
}
} else {
console.log('Esperando por Phantom Wallet...');
}
}
// 1. Intentar inicializar inmediatamente al cargar el DOM (antes que 'load')
// Esto captura casos donde Phantom es muy rápido.
document.addEventListener('DOMContentLoaded', tryInitializeNanoSol);
// 2. Intentar inicializar después de que todos los recursos de la página hayan cargado
// Esto da más tiempo a las extensiones.
window.addEventListener('load', () => {
tryInitializeNanoSol(); // Intentar de nuevo
// Si después de 'load' Phantom aún no se detecta, puedes dar un mensaje al usuario.
// Pero evita deshabilitar el botón, ya que el usuario puede instalar Phantom después
// y luego intentar conectar.
if (!window.solana || !window.solana.isPhantom) {
console.warn('Phantom Wallet aún no detectada después del evento "load". El usuario necesitará instalarla o recargar.');
// Podrías mostrar un mensaje persistente en la UI para el usuario aquí.
}
});
// Opcional: Un pequeño retraso adicional si 'load' no es suficiente.
// No siempre es necesario, pero puede ayudar en ciertos entornos.
setTimeout(() => {
if (!nanoSolApp && window.solana && window.solana.isPhantom) {
console.log('Phantom Wallet detectada después de un pequeño retraso. Inicializando NanoSol.');
tryInitializeNanoSol();
}
}, 1000); // Intenta de nuevo 1 segundo después del evento 'load'