-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzero.html
More file actions
744 lines (641 loc) · 33.1 KB
/
zero.html
File metadata and controls
744 lines (641 loc) · 33.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
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
<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Interactive Script Console (Non-Blocking TX)</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ethers/6.7.0/ethers.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.2/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;900&display=swap" rel="stylesheet">
<!-- Font Awesome for Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* Custom Styles for aesthetics and responsiveness */
:root {
--bg-primary-light: #f4f1eb; /* Warm Beige */
--bg-secondary-light: #ffffff;
--text-main-light: #212529;
--brand-color: #3b82f6; /* Blue 500 */
--danger-color: #ef4444; /* Red 500 */
}
body {
font-family: 'Inter', sans-serif;
background-color: var(--bg-primary-light);
color: var(--text-main-light);
min-height: 100vh;
}
.card {
background-color: var(--bg-secondary-light);
border-radius: 1rem;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
.btn-primary {
background-color: var(--brand-color);
transition: background-color 0.15s;
}
.btn-primary:hover {
background-color: #2563eb; /* Blue 600 */
}
.btn-secondary {
background-color: #f3f4f6;
color: #374151;
transition: background-color 0.15s;
}
.btn-secondary:hover {
background-color: #e5e7eb;
}
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
/* Style for the console output */
#console-output {
max-height: 300px;
overflow-y: auto;
white-space: pre-wrap;
word-wrap: break-word;
}
/* Modal backdrop for QR Code */
.modal {
background-color: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(5px);
}
.explorer-link {
color: #3b82f6;
text-decoration: underline;
cursor: pointer;
}
</style>
</head>
<body class="p-4 sm:p-8 flex flex-col items-center">
<div class="max-w-4xl w-full">
<header class="text-center mb-8">
<h1 class="text-4xl font-extrabold text-gray-800">EVM Transaction Console</h1>
<p class="text-gray-600 mt-2">Connect, send, and analyze Ethereum transactions. **Manual and Auto-Send can run concurrently.**</p>
</header>
<!-- Connection and Status Card -->
<div class="card p-6 mb-8">
<h2 class="text-2xl font-bold mb-4 border-b pb-2 text-gray-700">Wallet Status</h2>
<div id="status-display" class="space-y-3">
<p><strong>Status:</strong> <span id="connection-status" class="text-red-500">Disconnected</span></p>
<!-- Added Chain ID Display -->
<p><strong>Network:</strong> <span id="network-display">N/A</span></p>
<p><strong>Chain ID:</strong> <span id="chain-id-display">N/A</span></p>
<p><strong>Address:</strong> <span id="address-display" class="font-mono text-sm break-all">Connect Wallet First</span></p>
<p><strong>Balance:</strong> <span id="balance-display">N/A</span></p>
</div>
<button id="connect-wallet-btn" class="w-full mt-4 btn-primary text-white py-3 px-4 rounded-xl font-semibold shadow-md hover:shadow-lg">
Connect Wallet (MetaMask / EIP-1193)
</button>
</div>
<!-- Transaction Card -->
<div class="card p-6 mb-8">
<h2 class="text-2xl font-bold mb-4 border-b pb-2 text-gray-700">Send Transaction (Manual)</h2>
<div class="space-y-4">
<div>
<label for="recipient-input" class="block text-sm font-medium text-gray-700">Recipient Address</label>
<input type="text" id="recipient-input" placeholder="0x..." class="mt-1 block w-full border border-gray-300 rounded-xl shadow-sm p-3 focus:ring-blue-500 focus:border-blue-500 font-mono">
</div>
<!-- New Recipient Buttons -->
<div class="flex space-x-2">
<button id="self-send-btn" class="flex-1 btn-secondary text-gray-700 py-2 px-3 rounded-xl font-medium shadow-sm hover:shadow-md transition">
<i class="fas fa-undo mr-1"></i> Self-Send
</button>
<button id="dead-address-btn" class="flex-1 bg-red-100 text-red-700 py-2 px-3 rounded-xl font-medium shadow-sm hover:bg-red-200 transition">
<i class="fas fa-trash-alt mr-1"></i> Send to Burn Address
</button>
</div>
<div>
<label for="amount-input" class="block text-sm font-medium text-gray-700">Amount (ETH/Token) - Min $0$</label>
<input type="number" id="amount-input" value="0.000" min="0" step="0.000000000000000001" placeholder="0.000" class="mt-1 block w-full border border-gray-300 rounded-xl shadow-sm p-3 focus:ring-blue-500 focus:border-blue-500">
</div>
<div>
<label for="data-input" class="block text-sm font-medium text-gray-700">Transaction Data (Optional Hex)</label>
<input type="text" id="data-input" placeholder="0x..." class="mt-1 block w-full border border-gray-300 rounded-xl shadow-sm p-3 focus:ring-blue-500 focus:border-blue-500 font-mono">
</div>
<button id="send-transaction-btn" class="w-full btn-primary text-white py-3 px-4 rounded-xl font-semibold shadow-md hover:shadow-lg disabled:bg-gray-400" disabled>
<i class="fas fa-paper-plane mr-2"></i> Send Transaction
</button>
</div>
</div>
<!-- Automated Transaction Sender Card -->
<div class="card p-6 mb-8">
<h2 class="text-2xl font-bold mb-4 border-b pb-2 text-gray-700">Automated Transaction Sender</h2>
<p class="text-gray-600 mb-4">Repeatedly sends the transaction defined above with a random delay between attempts. Transactions are **sent but confirmations are monitored in the background** to prevent blocking the loop.</p>
<div class="space-y-4">
<!-- Delay Inputs -->
<div class="flex space-x-4">
<div class="flex-1">
<label for="min-delay-input" class="block text-sm font-medium text-gray-700">Min Delay (seconds)</label>
<input type="number" id="min-delay-input" value="10" min="1" class="mt-1 block w-full border border-gray-300 rounded-xl shadow-sm p-3 focus:ring-blue-500 focus:border-blue-500">
</div>
<div class="flex-1">
<label for="max-delay-input" class="block text-sm font-medium text-gray-700">Max Delay (seconds)</label>
<input type="number" id="max-delay-input" value="20" min="1" class="mt-1 block w-full border border-gray-300 rounded-xl shadow-sm p-3 focus:ring-blue-500 focus:border-blue-500">
</div>
</div>
<button id="toggle-auto-send-btn" class="w-full bg-green-500 text-white py-3 px-4 rounded-xl font-semibold shadow-md hover:bg-green-600 disabled:bg-gray-400" disabled>
<i class="fas fa-play mr-2"></i> Start Auto-Send Loop
</button>
</div>
</div>
<!-- End Automated Transaction Sender Card -->
<!-- Console Output Card -->
<div class="card p-6 mb-8">
<h2 class="text-2xl font-bold mb-4 border-b pb-2 text-gray-700">Console Output</h2>
<div id="console-output" class="bg-gray-800 text-green-400 p-4 rounded-lg text-sm">
Awaiting wallet connection...
</div>
</div>
<!-- Donation Section -->
<div class="card p-6 text-center mb-8">
<h2 class="text-xl font-bold text-gray-700 mb-4">Support This Tool</h2>
<p class="text-gray-600 mb-4">You can support the development of this tool by sending a small amount to the address below.</p>
<button id="show-qr-btn" class="bg-yellow-500 text-white py-2 px-4 rounded-xl font-semibold shadow-md hover:bg-yellow-600 transition">
Show Donation QR
</button>
</div>
</div>
<!-- QR Code Modal -->
<div id="qr-modal" class="modal fixed inset-0 flex items-center justify-center z-50 hidden p-4">
<div class="bg-white p-8 rounded-xl shadow-2xl max-w-sm w-full relative">
<button id="close-qr-modal-btn" class="absolute top-3 right-3 text-gray-500 hover:text-gray-800">
<i class="fas fa-times text-xl"></i>
</button>
<h3 class="text-xl font-bold text-center mb-4">Donation Address</h3>
<div id="qr-code-container" class="flex justify-center mb-4"></div>
<p id="qr-address-display" class="font-mono text-center break-all text-sm mb-4"></p>
<button id="copy-address-btn" class="w-full btn-primary text-white py-2 rounded-xl font-semibold flex items-center justify-center space-x-2">
<i id="copy-icon" class="fas fa-copy"></i>
<i id="check-icon" class="fas fa-check text-green-400 hidden"></i>
<span>Copy Address</span>
</button>
</div>
</div>
<script>
// --- Global Variables & Initialization ---
let provider = null;
let signer = null;
let userAddress = null;
let userBalance = 0n; // Use BigInt for balance
let chainId = null;
const donationAddressStr = "0xdAC34f55a10A0A9b82F9e4d588526553A577717E"; // Placeholder address
const deadAddress = "0x0000000000000000000000000000000000000000"; // The standard burn address
// Auto-Send Variables
let autoSendTimeoutId = null;
let isAutoSending = false;
// DOM elements
const connectWalletBtn = document.getElementById('connect-wallet-btn');
const sendTransactionBtn = document.getElementById('send-transaction-btn');
const statusDisplay = document.getElementById('connection-status');
const networkDisplay = document.getElementById('network-display');
const chainIdDisplay = document.getElementById('chain-id-display');
const addressDisplay = document.getElementById('address-display');
const balanceDisplay = document.getElementById('balance-display');
const recipientInput = document.getElementById('recipient-input');
const amountInput = document.getElementById('amount-input');
const dataInput = document.getElementById('data-input');
const consoleOutput = document.getElementById('console-output');
// New Recipient Buttons
const selfSendBtn = document.getElementById('self-send-btn');
const deadAddressBtn = document.getElementById('dead-address-btn');
// New Auto-Send DOM elements
const minDelayInput = document.getElementById('min-delay-input');
const maxDelayInput = document.getElementById('max-delay-input');
const toggleAutoSendBtn = document.getElementById('toggle-auto-send-btn');
// QR Modal elements
const qrModal = document.getElementById('qr-modal');
const qrCodeContainer = document.getElementById('qr-code-container');
const qrAddressDisplay = document.getElementById('qr-address-display');
const copyBtn = document.getElementById('copy-address-btn');
const copyIcon = document.getElementById('copy-icon');
const checkIcon = document.getElementById('check-icon');
const showQrBtn = document.getElementById('show-qr-btn');
const closeQrModalBtn = document.getElementById('close-qr-modal-btn');
// Map common chain IDs to their block explorers (using BigInt keys for ethers v6)
const chainExplorers = {
1n: 'https://etherscan.io/tx/', // Ethereum Mainnet
5n: 'https://goerli.etherscan.io/tx/', // Goerli (Legacy)
11155111n: 'https://sepolia.etherscan.io/tx/', // Sepolia
137n: 'https://polygonscan.com/tx/', // Polygon Mainnet
80001n: 'https://mumbai.polygonscan.com/tx/', // Polygon Mumbai (Legacy)
42161n: 'https://arbiscan.io/tx/', // Arbitrum One
10n: 'https://optimistic.etherscan.io/tx/', // Optimism
56n: 'https://bscscan.com/tx/', // BNB Smart Chain
43114n: 'https://snowtrace.io/tx/', // Avalanche C-Chain
250n: 'https://ftmscan.com/tx/', // Fantom Opera
};
/**
* Gets the appropriate block explorer URL for the current chain.
* @param {bigint} currentChainId The current chain ID.
* @param {string} txHash The transaction hash.
* @returns {string} The full transaction explorer URL.
*/
function getExplorerUrl(currentChainId, txHash) {
const baseUrl = chainExplorers[currentChainId] || `https://etherscan.io/tx/`;
return `${baseUrl}${txHash}`;
}
// --- Utility Functions ---
/**
* Appends a message to the console output.
* @param {string} message The message to display.
* @param {string} type The type of message (log, error, success, warn, info, pending).
*/
function log(message, type = 'log') {
const time = new Date().toLocaleTimeString();
let color = 'text-green-400';
if (type === 'error') color = 'text-red-400';
if (type === 'warn') color = 'text-yellow-400';
if (type === 'info') color = 'text-blue-400';
if (type === 'pending') color = 'text-purple-400';
const element = document.createElement('span');
element.className = color + ' block';
if (message.startsWith('Explorer Link: ')) {
const url = message.substring('Explorer Link: '.length);
const prefix = `[${time}] [INFO] Explorer Link: `;
const prefixSpan = document.createElement('span');
prefixSpan.textContent = prefix;
const linkAnchor = document.createElement('a');
linkAnchor.href = url;
linkAnchor.target = '_blank';
linkAnchor.textContent = url;
linkAnchor.className = 'explorer-link';
element.appendChild(prefixSpan);
element.appendChild(linkAnchor);
} else {
element.textContent = `[${time}] [${type.toUpperCase()}] ${message}`;
}
consoleOutput.appendChild(element);
consoleOutput.scrollTop = consoleOutput.scrollHeight;
}
/**
* Copies text to the clipboard.
* @param {string} text The text to copy.
*/
function copyToClipboard(text) {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand('copy');
log('Address copied to clipboard.', 'info');
} catch (err) {
log('Failed to copy text.', 'error');
}
document.body.removeChild(textarea);
}
/**
* Updates the wallet status in the UI.
*/
function updateStatus() {
if (userAddress) {
statusDisplay.textContent = 'Connected';
statusDisplay.className = 'text-green-500 font-semibold';
addressDisplay.textContent = userAddress;
balanceDisplay.textContent = userBalance ? `${ethers.formatEther(userBalance)} ETH` : '0 ETH';
chainIdDisplay.textContent = chainId !== null ? chainId.toString() : 'N/A';
// UX Tweak: Manual send is ALWAYS available if connected
sendTransactionBtn.disabled = false;
toggleAutoSendBtn.disabled = false;
} else {
statusDisplay.textContent = 'Disconnected';
statusDisplay.className = 'text-red-500';
networkDisplay.textContent = 'N/A';
chainIdDisplay.textContent = 'N/A';
addressDisplay.textContent = 'Connect Wallet First';
balanceDisplay.textContent = 'N/A';
sendTransactionBtn.disabled = true;
toggleAutoSendBtn.disabled = true;
stopAutoSend(); // Ensure loop is stopped on disconnect
}
}
// --- Auto-Send Logic ---
/**
* Generates a random delay in milliseconds between min and max seconds.
* @param {number} minS Minimum delay in seconds.
* @param {number} maxS Maximum delay in seconds.
* @returns {number} Random delay in milliseconds.
*/
function getRandomDelay(minS, maxS) {
const minMs = minS * 1000;
const maxMs = maxS * 1000;
return Math.floor(Math.random() * (maxMs - minMs + 1)) + minMs;
}
/**
* Stops the auto-send loop.
*/
function stopAutoSend() {
if (!isAutoSending) return;
clearTimeout(autoSendTimeoutId);
autoSendTimeoutId = null;
isAutoSending = false;
// Update UI
toggleAutoSendBtn.textContent = 'Start Auto-Send Loop';
toggleAutoSendBtn.classList.remove('bg-red-500', 'hover:bg-red-600');
toggleAutoSendBtn.classList.add('bg-green-500', 'hover:bg-green-600');
updateStatus();
log('Auto-Send Loop Stopped.', 'warn');
}
/**
* The core logic for the automated send loop.
*/
async function autoSendLoop() {
if (!isAutoSending || !signer) {
stopAutoSend();
return;
}
const minDelay = parseInt(minDelayInput.value, 10);
const maxDelay = parseInt(maxDelayInput.value, 10);
const recipient = recipientInput.value.trim();
const amountStr = amountInput.value.trim() || '0';
const data = dataInput.value.trim() || '0x';
if (!recipient || isNaN(parseFloat(amountStr)) || parseFloat(amountStr) < 0 || minDelay <= 0 || maxDelay <= 0 || minDelay > maxDelay) {
log('Invalid transaction or delay settings for auto-send. Stopping loop.', 'error');
stopAutoSend();
return;
}
log(`Auto-Send: Attempting transaction...`, 'info');
// Use the core send function, skipping confirmation wait (non-blocking)
const txResponse = await coreSendTransaction(recipient, amountStr, data, true);
if (txResponse) {
// If broadcast was successful, schedule the next iteration based on the timer
const delayMs = getRandomDelay(minDelay, maxDelay);
log(`Auto-Send: TX ${txResponse.hash.slice(0, 10)}... sent. Next scheduled in ${delayMs / 1000}s.`, 'pending');
// The coreSendTransaction call already initiates monitorConfirmation(txResponse.hash) without awaiting it.
autoSendTimeoutId = setTimeout(autoSendLoop, delayMs);
} else {
// If send failed (e.g., user rejected, insufficient funds), wait before retrying or stopping
log('Auto-Send: Transaction failed to broadcast. Retrying in 5s.', 'error');
autoSendTimeoutId = setTimeout(autoSendLoop, 5000);
}
}
/**
* Toggles the auto-send state.
*/
function toggleAutoSend() {
if (isAutoSending) {
stopAutoSend();
} else {
startAutoSend();
}
}
/**
* Starts the auto-send loop.
*/
function startAutoSend() {
if (!signer) {
log('Please connect your wallet first.', 'warn');
return;
}
const minDelay = parseInt(minDelayInput.value, 10);
const maxDelay = parseInt(maxDelayInput.value, 10);
if (minDelay <= 0 || maxDelay <= 0 || minDelay > maxDelay) {
log('Invalid delay settings. Min must be $\\leq$ Max and both must be $\\geq 1$ second.', 'error');
return;
}
isAutoSending = true;
// Update UI
toggleAutoSendBtn.textContent = 'Stop Auto-Send Loop';
toggleAutoSendBtn.classList.remove('bg-green-500', 'hover:bg-green-600');
toggleAutoSendBtn.classList.add('bg-red-500', 'hover:bg-red-600');
updateStatus();
log('Auto-Send Loop Started. Manual sends are still available!', 'success');
// Start the first iteration immediately
autoSendLoop();
}
// --- Core Application Logic ---
/**
* Fetches and updates the user's balance and network info.
*/
async function fetchAccountData() {
if (!provider || !userAddress) return;
try {
// Get Balance
const balance = await provider.getBalance(userAddress);
userBalance = balance;
// Get Network & Chain ID
const network = await provider.getNetwork();
networkDisplay.textContent = network.name || 'Unknown Network';
chainId = network.chainId;
chainIdDisplay.textContent = chainId !== null ? chainId.toString() : 'N/A';
updateStatus();
log(`Account data refreshed. Balance: ${ethers.formatEther(userBalance)} ETH. Chain ID: ${chainId}`, 'info');
} catch (error) {
log(`Error fetching account data: ${error.message}`, 'error');
}
}
/**
* Connects the wallet using window.ethereum (MetaMask/EIP-1193).
*/
async function connectWallet() {
if (typeof window.ethereum === 'undefined') {
log('MetaMask or other EIP-1193 compatible wallet not found.', 'error');
return;
}
try {
const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
userAddress = accounts[0];
provider = new ethers.BrowserProvider(window.ethereum);
signer = await provider.getSigner();
log('Wallet connected successfully.', 'success');
await fetchAccountData();
// Auto-refresh balance every 15 seconds
setInterval(fetchAccountData, 15000);
// Event listeners for account/chain changes
window.ethereum.on('accountsChanged', (accounts) => {
userAddress = accounts.length > 0 ? accounts[0] : null;
if (userAddress) {
signer = provider.getSigner();
fetchAccountData();
} else {
provider = null;
signer = null;
updateStatus();
log('Wallet disconnected.', 'warn');
}
});
window.ethereum.on('chainChanged', () => {
log('Network changed. Re-fetching data...', 'warn');
fetchAccountData();
});
} catch (error) {
log(`Connection failed: ${error.message}`, 'error');
userAddress = null;
updateStatus();
}
}
/**
* Waits for the transaction confirmation and logs the result.
* This function is non-blocking to the main send logic.
* @param {string} txHash The transaction hash to monitor.
*/
async function monitorConfirmation(txHash) {
try {
log(`Waiting for confirmation of TX ${txHash.slice(0, 10)}...`, 'pending');
// This will throw if the transaction is replaced or times out
const txReceipt = await provider.waitForTransaction(txHash);
if (txReceipt && txReceipt.status === 1n) {
log(`Confirmation SUCCESS: TX ${txHash.slice(0, 10)}... confirmed successfully. ✅`, 'success');
log(`Explorer Link: ${getExplorerUrl(chainId, txHash)}`, 'info');
await fetchAccountData();
} else if (txReceipt && txReceipt.status === 0n) {
log(`Confirmation FAILED: TX ${txHash.slice(0, 10)}... reverted ❌`, 'error');
log(`Explorer Link: ${getExplorerUrl(chainId, txHash)}`, 'info');
} else {
log(`Confirmation UNKNOWN: TX ${txHash.slice(0, 10)}... unknown status 🤔`, 'warn');
}
} catch (error) {
// Handle explicit errors during waiting (e.g., node disconnection, timeout, replacement)
log(`Error while monitoring TX ${txHash.slice(0, 10)}...: ${error.message}`, 'error');
}
}
/**
* Signs and sends the transaction, but can optionally skip waiting for confirmation.
* @param {string} recipient The recipient address.
* @param {string} amountStr The amount string (e.g., '0.001').
* @param {string} data The transaction data (e.g., '0x').
* @param {boolean} skipConfirm If true, returns immediately after broadcasting.
* @returns {Promise<ethers.TransactionResponse | null>} The transaction response if sent, null otherwise.
*/
async function coreSendTransaction(recipient, amountStr, data, skipConfirm = false) {
if (!signer) {
log('No connected signer. Connect your wallet first.', 'error');
return null;
}
try {
// Ensure amount is parsed correctly, defaulting to 0
const txValue = ethers.parseEther(amountStr || "0");
const txData = data && data !== '' ? data : "0x";
const txRequest = {
to: recipient,
value: txValue,
data: txData,
};
log('Estimating gas limits and costs...', 'info');
let gasLimit;
try {
gasLimit = await provider.estimateGas(txRequest);
} catch (gasError) {
gasLimit = 21000n; // Fallback to base ETH transfer limit (21,000 Wei)
log(`Gas estimation failed (${gasError.message}). Using default ${gasLimit.toString()}.`, 'warn');
}
txRequest.gasLimit = gasLimit;
log('Sending transaction to wallet for approval...', 'warn');
// This line waits for the user to approve the transaction, then returns the broadcasted response.
const txResponse = await signer.sendTransaction(txRequest);
log(`Transaction broadcasted: ${txResponse.hash}`, 'success'); // Change to success since it's confirmed broadcasted
log(`Explorer Link: ${getExplorerUrl(chainId, txResponse.hash)}`, 'info');
// If not skipping confirmation (i.e., manual send), WAIT for the non-blocking monitor to finish.
if (!skipConfirm) {
await monitorConfirmation(txResponse.hash);
} else {
// If skipping confirmation (auto-send), FIRE AND FORGET the monitor.
monitorConfirmation(txResponse.hash);
}
return txResponse;
} catch (error) {
let errorMessage = error.message;
if (error.code === 'INSUFFICIENT_FUNDS') {
errorMessage = 'Insufficient funds to cover the transaction fees (gas).';
} else if (error.code === 'ACTION_REJECTED' || error.message.includes('user rejected')) {
errorMessage = 'Transaction rejected by the user in the wallet.';
} else if (error.message.includes('invalid address')) {
errorMessage = 'Invalid recipient address.';
}
log(`Transaction failed to broadcast: ${errorMessage}`, 'error');
return null;
}
}
/**
* Wrapper for single-click transaction sending (calls core function).
*/
async function handleSingleSend() {
const recipient = recipientInput.value.trim();
const amountStr = amountInput.value.trim() || '0';
const data = dataInput.value.trim() || '0x';
// 1. Basic Input Validation
if (!recipient) {
log('Recipient address is required.', 'error');
return;
}
if (isNaN(parseFloat(amountStr)) || parseFloat(amountStr) < 0) {
log('Invalid amount entered. Amount must be $0$ or greater.', 'error');
return;
}
sendTransactionBtn.disabled = true;
sendTransactionBtn.textContent = 'Awaiting Wallet Approval (Blocking)...';
// Pass 'false' so it awaits confirmation
await coreSendTransaction(recipient, amountStr, data, false);
// Reset button state
sendTransactionBtn.textContent = 'Send Transaction';
sendTransactionBtn.disabled = false;
}
// --- Event Listeners and Initial Setup ---
connectWalletBtn.addEventListener('click', connectWallet);
sendTransactionBtn.addEventListener('click', handleSingleSend);
toggleAutoSendBtn.addEventListener('click', toggleAutoSend);
// New Self-Send Button
selfSendBtn.addEventListener('click', () => {
if (userAddress) {
recipientInput.value = userAddress;
log('Recipient set to connected wallet address (Self-Send).', 'info');
} else {
log('Please connect your wallet first to use Self-Send.', 'error');
}
});
// New Dead Address Button
deadAddressBtn.addEventListener('click', () => {
recipientInput.value = deadAddress;
log('Recipient set to the burn address (0x0...).', 'warn');
});
// --- QR Code Modal Logic ---
document.addEventListener('DOMContentLoaded', () => {
// Initialize QR Code for the donation address
if (typeof QRCode !== 'undefined') {
new QRCode(qrCodeContainer, {
text: donationAddressStr,
width: 200,
height: 200,
colorDark : "#2d3748",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
});
qrAddressDisplay.textContent = donationAddressStr;
} else {
console.error("QRCode library is not loaded.")
qrCodeContainer.innerHTML = "QR Code library failed to load. Please check your connection.";
}
copyBtn.addEventListener('click', () => {
copyToClipboard(donationAddressStr);
copyIcon.classList.add('hidden');
checkIcon.classList.remove('hidden');
setTimeout(() => {
copyIcon.classList.remove('hidden');
checkIcon.classList.add('hidden');
}, 2000);
});
showQrBtn.addEventListener('click', () => {
qrModal.classList.remove('hidden');
});
const closeQrModal = () => {
qrModal.classList.add('hidden');
}
closeQrModalBtn.addEventListener('click', closeQrModal);
window.addEventListener('click', (event) => {
if (event.target === qrModal) {
closeQrModal();
}
});
});
</script>
</body>
</html>