offerpk3 commited on
Commit
56b3cbf
·
verified ·
1 Parent(s): f1a439e

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +604 -529
index.html CHANGED
@@ -4,43 +4,47 @@
4
  <head>
5
  <meta charset="UTF-8">
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
- <title>Dogechain Super DApp</title>
 
 
 
8
  <script src="https://cdn.tailwindcss.com"></script>
9
- <script src="https://cdn.ethers.io/lib/ethers-5.7.2.umd.min.js"></script>
10
  <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
11
  <style>
 
 
12
  .tab-button.active {
13
- background-color: #fbbf24; /* Tailwind amber-400 */
14
- color: #1f2937; /* Tailwind gray-800 */
15
  border-bottom-color: transparent;
16
  }
17
  .tab-button {
18
  transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
19
  padding: 0.75rem 1.5rem;
20
  margin-bottom: -1px; /* Overlap border */
21
- border: 1px solid #4b5563; /* Tailwind gray-600 */
22
  border-bottom: 1px solid #4b5563;
 
 
 
23
  }
24
- .tab-button:not(.active):hover {
25
- background-color: #374151; /* Tailwind gray-700 */
26
- }
27
  .tab-content { display: none; }
28
  .tab-content.active { display: block; }
29
 
30
- /* Spinner for loading states */
31
  .spinner {
32
  border: 4px solid rgba(255, 255, 255, 0.3);
33
  border-radius: 50%;
34
- border-top-color: #fbbf24; /* amber-400 */
35
  width: 20px;
36
  height: 20px;
37
  animation: spin 1s linear infinite;
38
  display: inline-block;
 
39
  margin-right: 8px;
40
  }
41
- @keyframes spin {
42
- to { transform: rotate(360deg); }
43
- }
44
  input[type="text"], input[type="number"], textarea, select {
45
  background-color: #374151; /* gray-700 */
46
  border: 1px solid #4b5563; /* gray-600 */
@@ -51,46 +55,101 @@
51
  }
52
  input:focus, textarea:focus, select:focus {
53
  outline: none;
54
- border-color: #fbbf24; /* amber-400 */
55
- box-shadow: 0 0 0 2px rgba(251, 191, 36, 0.5);
56
  }
57
  button {
58
  padding: 0.5rem 1rem;
59
  border-radius: 0.375rem; /* rounded-md */
60
  font-weight: 600; /* semibold */
61
- transition: background-color 0.2s ease;
 
 
 
62
  }
 
63
  .btn-primary {
64
- background-color: #fbbf24; /* amber-400 */
65
  color: #1f2937; /* gray-800 */
66
  }
67
- .btn-primary:hover {
68
- background-color: #f59e0b; /* amber-500 */
69
- }
70
  .btn-secondary {
71
  background-color: #4b5563; /* gray-600 */
72
  color: #f3f4f6; /* gray-100 */
73
  }
74
- .btn-secondary:hover {
75
- background-color: #6b7280; /* gray-500 */
 
 
76
  }
 
 
 
77
  .table-auto th, .table-auto td {
78
  border: 1px solid #4b5563; /* gray-600 */
79
  padding: 0.5rem;
80
  text-align: left;
81
  }
82
- .table-auto th {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
  background-color: #374151; /* gray-700 */
 
 
 
 
 
84
  }
85
- .word-break-all { word-break: break-all; }
86
  </style>
87
- <script type="importmap">
 
88
  {
89
  "imports": {
 
90
  "react": "https://esm.sh/react@^19.1.0",
91
  "react-dom/": "https://esm.sh/react-dom@^19.1.0/",
92
- "react/": "https://esm.sh/react@^19.1.0/",
93
- "ethers": "https://esm.sh/ethers@^6.14.4"
94
  }
95
  }
96
  </script>
@@ -99,16 +158,17 @@
99
  <div class="container mx-auto max-w-6xl">
100
  <header class="mb-6 text-center">
101
  <h1 class="text-3xl sm:text-4xl font-bold text-yellow-400">Dogechain Super DApp 🐕⛓️</h1>
102
- <div class="mt-3">
103
- <button id="connectWalletBtn" class="btn-primary px-5 py-2">
104
- Connect Wallet
105
- </button>
106
  </div>
107
- <div id="walletInfo" class="mt-3 text-sm hidden space-y-1">
108
  <p><strong>Status:</strong> <span id="walletStatus" class="text-green-400">Connected</span></p>
 
109
  <p><strong>Account:</strong> <span id="connectedAccount" class="text-amber-300 word-break-all"></span></p>
110
  <p><strong>Network:</strong> <span id="connectedNetwork" class="text-amber-300"></span></p>
111
- <p><strong>Balance:</strong> <span id="accountBalance" class="text-amber-300"></span> DOGE</p>
112
  </div>
113
  </header>
114
 
@@ -123,8 +183,7 @@
123
  <li><button class="tab-button" data-tab="contractInteract">Contract Interaction</button></li>
124
  </ul>
125
  </nav>
126
-
127
- <!-- Tab Content Area -->
128
  <main id="tabContentContainer">
129
  <!-- TXID Tools Tab -->
130
  <div id="txidTools" class="tab-content active space-y-6">
@@ -150,13 +209,13 @@
150
  <label for="signatureToVerify" class="block text-sm mb-1">Signature:</label>
151
  <textarea id="signatureToVerify" rows="3" class="mb-2" placeholder="Enter signature"></textarea>
152
  <button id="verifySignatureBtn" class="btn-primary">Verify Signature</button>
153
- <p class="mt-2 text-sm">Recovered Address: <span id="recoveredAddress" class="font-mono text-amber-300"></span></p>
154
  <p id="verificationStatus" class="mt-1 text-sm"></p>
155
  </section>
156
 
157
  <section class="bg-gray-800 p-4 rounded-lg shadow">
158
  <h2 class="text-xl font-semibold text-yellow-400 mb-3">4. TXID + Signature History</h2>
159
- <button id="clearHistoryBtn" class="btn-secondary text-sm mb-3">Clear History</button>
160
  <div class="overflow-x-auto">
161
  <table class="w-full table-auto text-sm">
162
  <thead>
@@ -186,7 +245,7 @@
186
  </section>
187
 
188
  <section id="drc20MetadataSection" class="bg-gray-800 p-4 rounded-lg shadow hidden">
189
- <h2 class="text-xl font-semibold text-yellow-400 mb-3">5. Token Metadata</h2>
190
  <div id="drc20MetadataDisplay" class="space-y-1 text-sm">
191
  <p><strong>Name:</strong> <span id="tokenMetaName">N/A</span></p>
192
  <p><strong>Symbol:</strong> <span id="tokenMetaSymbol">N/A</span></p>
@@ -196,7 +255,7 @@
196
  </section>
197
 
198
  <section id="drc20HoldersSection" class="bg-gray-800 p-4 rounded-lg shadow hidden">
199
- <h2 class="text-xl font-semibold text-yellow-400 mb-3">6. Token Holder Scanner</h2>
200
  <div class="flex justify-between items-center mb-2">
201
  <label for="whaleFilterCheckbox" class="text-sm flex items-center">
202
  <input type="checkbox" id="whaleFilterCheckbox" class="mr-2 h-4 w-4 rounded text-amber-400 focus:ring-amber-500 bg-gray-700 border-gray-600"> Show only "Whales" (10,000+ tokens)
@@ -220,12 +279,13 @@
220
  </section>
221
 
222
  <section id="drc20ChartSection" class="bg-gray-800 p-4 rounded-lg shadow hidden">
223
- <h2 class="text-xl font-semibold text-yellow-400 mb-3">7. Token Distribution Chart (Top Holders)</h2>
224
  <canvas id="tokenDistributionChart" class="max-h-96"></canvas>
225
  </section>
226
 
227
  <section id="drc20TransfersSection" class="bg-gray-800 p-4 rounded-lg shadow hidden">
228
- <h2 class="text-xl font-semibold text-yellow-400 mb-3">8. Recent Token Transfers</h2>
 
229
  <div class="overflow-x-auto max-h-96">
230
  <table class="w-full table-auto text-sm">
231
  <thead>
@@ -265,107 +325,157 @@
265
  </div>
266
  </div>
267
  </main>
 
 
268
  <footer class="mt-12 text-center text-gray-500 text-xs pb-8">
269
- <p>&copy; ${new Date().getFullYear()} Dogechain Super DApp. For educational and utility purposes.</p>
270
- <p>Always verify information and be cautious. Interacting with smart contracts carries risk.</p>
271
  </footer>
272
  </div>
273
 
274
- <script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  document.addEventListener('DOMContentLoaded', () => {
276
- // Ethers.js provider and signer
277
- let provider;
278
- let signer;
279
- let currentAccount;
280
- let currentNetwork;
281
- let tokenDistributionChartInstance = null;
 
 
282
  let activeTokenAddress = null; // For DRC-20 Inspector
283
  let currentHoldersPage = 1;
284
- const DOGECHAIN_MAINNET_CHAIN_ID = '0x7d0'; // 2000
285
- const DOGECHAIN_TESTNET_CHAIN_ID = '0x238'; // 568
 
 
 
286
  const DOGECHAIN_EXPLORER_API_BASE = 'https://explorer.dogechain.dog/api';
287
- const TXID_HISTORY_KEY = 'dogechainDappTxidHistory';
288
 
289
- // UI Elements
290
- const connectWalletBtn = document.getElementById('connectWalletBtn');
291
- const walletInfoDiv = document.getElementById('walletInfo');
292
- const walletStatusSpan = document.getElementById('walletStatus');
293
- const connectedAccountSpan = document.getElementById('connectedAccount');
294
- const connectedNetworkSpan = document.getElementById('connectedNetwork');
295
- const accountBalanceSpan = document.getElementById('accountBalance');
296
- const globalMessageDiv = document.getElementById('globalMessage');
 
 
 
 
 
 
 
 
 
 
 
297
 
298
  // Tab Elements
299
  const tabButtons = document.querySelectorAll('.tab-button');
300
  const tabContents = document.querySelectorAll('.tab-content');
301
 
302
  // TXID Tools Elements
303
- const generateTxidBtn = document.getElementById('generateTxidBtn');
304
- const generatedTxidInput = document.getElementById('generatedTxid');
305
- const txidToSignInput = document.getElementById('txidToSign');
306
- const signTxidBtn = document.getElementById('signTxidBtn');
307
- const txidSignatureTextarea = document.getElementById('txidSignature');
308
- const messageToVerifyInput = document.getElementById('messageToVerify');
309
- const signatureToVerifyTextarea = document.getElementById('signatureToVerify');
310
- const verifySignatureBtn = document.getElementById('verifySignatureBtn');
311
- const recoveredAddressSpan = document.getElementById('recoveredAddress');
312
- const verificationStatusP = document.getElementById('verificationStatus');
313
- const clearHistoryBtn = document.getElementById('clearHistoryBtn');
314
- const txidHistoryTableBody = document.getElementById('txidHistoryTableBody');
315
 
316
  // DRC-20 Inspector Elements
317
- const drc20TokenAddressInput = document.getElementById('drc20TokenAddress');
318
- const fetchTokenDataBtn = document.getElementById('fetchTokenDataBtn');
319
- const drc20MetadataSection = document.getElementById('drc20MetadataSection');
320
- const tokenMetaNameSpan = document.getElementById('tokenMetaName');
321
- const tokenMetaSymbolSpan = document.getElementById('tokenMetaSymbol');
322
- const tokenMetaDecimalsSpan = document.getElementById('tokenMetaDecimals');
323
- const tokenMetaTotalSupplySpan = document.getElementById('tokenMetaTotalSupply');
324
- const drc20HoldersSection = document.getElementById('drc20HoldersSection');
325
- const tokenHoldersTableBody = document.getElementById('tokenHoldersTableBody');
326
- const holdersPaginationControlsDiv = document.getElementById('holdersPaginationControls');
327
- const whaleFilterCheckbox = document.getElementById('whaleFilterCheckbox');
328
- const drc20ChartSection = document.getElementById('drc20ChartSection');
329
- const tokenDistributionChartCanvas = document.getElementById('tokenDistributionChart');
330
- const drc20TransfersSection = document.getElementById('drc20TransfersSection');
331
- const tokenTransfersTableBody = document.getElementById('tokenTransfersTableBody');
 
332
 
333
  // Contract Interaction Elements
334
- const contractAddressInput = document.getElementById('contractAddressInput');
335
- const contractAbiInput = document.getElementById('contractAbiInput');
336
- const loadContractBtn = document.getElementById('loadContractBtn');
337
- const contractFunctionsSection = document.getElementById('contractFunctionsSection');
338
- const readFunctionsContainer = document.getElementById('readFunctionsContainer');
339
- const writeFunctionsContainer = document.getElementById('writeFunctionsContainer');
340
- const functionResultDisplay = document.getElementById('functionResultDisplay');
341
- const functionResultOutput = document.getElementById('functionResultOutput');
 
 
 
 
 
342
 
343
  // --- Helper Functions ---
344
- function showMessage(message, type = 'info', duration = 5000) {
345
  globalMessageDiv.textContent = message;
346
  globalMessageDiv.className = 'my-4 p-3 rounded-md text-white break-words text-sm shadow-lg'; // Reset classes
347
- if (type === 'error') globalMessageDiv.classList.add('bg-red-600');
348
- else if (type === 'success') globalMessageDiv.classList.add('bg-green-600');
349
- else globalMessageDiv.classList.add('bg-blue-600');
350
  globalMessageDiv.classList.remove('hidden');
351
  setTimeout(() => {
352
- globalMessageDiv.classList.add('hidden');
 
 
353
  }, duration);
354
  }
355
 
356
  function showLoadingSpinner(button, show = true, originalText = "Submit") {
 
357
  if (show) {
358
  button.disabled = true;
 
359
  button.innerHTML = `<span class="spinner"></span>Processing...`;
360
  } else {
361
  button.disabled = false;
362
- button.innerHTML = originalText;
363
  }
364
  }
365
-
366
  async function checkDogechainTxStatus(txHash) {
 
367
  try {
368
  const response = await fetch(`${DOGECHAIN_EXPLORER_API_BASE}?module=transaction&action=gettxreceiptstatus&txhash=${txHash}`);
 
369
  const data = await response.json();
370
  if (data.status === "1" && data.result && data.result.status === "1") {
371
  return '<span class="text-green-400">Success</span>';
@@ -380,177 +490,270 @@
380
  }
381
  }
382
 
383
- // --- Wallet Connection ---
384
- async function connectWallet() {
385
- if (typeof window.ethers === 'undefined' || typeof window.ethereum === 'undefined') {
386
- showMessage("MetaMask (or an Ethereum compatible wallet) is not installed. Please install it.", 'error');
387
- return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
  }
 
 
 
 
389
  try {
390
- provider = new ethers.providers.Web3Provider(window.ethereum);
391
- await provider.send("eth_requestAccounts", []);
392
- signer = provider.getSigner();
 
 
 
 
 
 
393
  currentAccount = await signer.getAddress();
394
- const network = await provider.getNetwork();
395
- currentNetwork = network;
396
 
397
- updateWalletUI(currentAccount, network);
398
- showMessage('Wallet connected successfully!', 'success');
399
- if (network.chainId !== DOGECHAIN_MAINNET_CHAIN_ID && network.chainId !== DOGECHAIN_TESTNET_CHAIN_ID) {
400
- showMessage('Warning: You are not connected to Dogechain Mainnet or Testnet. Please switch network in MetaMask.', 'error', 10000);
401
- }
402
 
403
- // Handle account and network changes
404
- window.ethereum.on('accountsChanged', (accounts) => {
405
- if (accounts.length === 0) {
406
- disconnectWallet();
407
- } else {
408
- currentAccount = accounts[0];
409
- signer = provider.getSigner(); // Re-get signer for new account
410
- updateWalletUI(currentAccount, currentNetwork); // Network hasn't changed here
411
- showMessage('Account switched successfully.', 'info');
412
- }
413
- });
414
- window.ethereum.on('chainChanged', async (_chainId) => {
415
- const newNetwork = await provider.getNetwork(); // Re-fetch to get up-to-date network info
416
- currentNetwork = newNetwork;
417
- updateWalletUI(currentAccount, newNetwork);
418
- showMessage(`Network switched to: ${newNetwork.name} (ID: ${newNetwork.chainId})`, 'info');
419
- if (newNetwork.chainId !== DOGECHAIN_MAINNET_CHAIN_ID && newNetwork.chainId !== DOGECHAIN_TESTNET_CHAIN_ID) {
420
- showMessage('Warning: You are not connected to Dogechain Mainnet or Testnet.', 'error', 10000);
421
- }
422
- });
423
 
424
  } catch (error) {
425
- console.error("Error connecting wallet:", error);
426
- showMessage(`Error connecting wallet: ${error.message}`, 'error');
427
- disconnectWallet(); // Ensure UI is in disconnected state
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  }
429
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
 
431
- function disconnectWallet() {
432
  provider = null;
433
  signer = null;
434
  currentAccount = null;
435
  currentNetwork = null;
 
 
436
  walletInfoDiv.classList.add('hidden');
437
  connectWalletBtn.textContent = 'Connect Wallet';
438
  connectWalletBtn.disabled = false;
439
- walletStatusSpan.textContent = 'Not Connected';
440
- walletStatusSpan.className = 'text-red-400';
 
 
 
 
 
 
 
 
 
 
 
 
441
  showMessage("Wallet disconnected.", "info");
442
  }
443
 
444
- async function updateWalletUI(account, network) {
 
 
 
 
445
  connectedAccountSpan.textContent = account;
446
- connectedNetworkSpan.textContent = `${network.name} (ID: ${network.chainId})`;
447
  walletStatusSpan.textContent = 'Connected';
448
  walletStatusSpan.className = 'text-green-400';
449
  walletInfoDiv.classList.remove('hidden');
450
- connectWalletBtn.textContent = 'Wallet Connected';
451
- connectWalletBtn.disabled = true; // Or change to "Disconnect" behavior
452
 
453
  try {
454
- const balance = await provider.getBalance(account);
455
- accountBalanceSpan.textContent = ethers.utils.formatEther(balance).substring(0, 8);
456
  } catch (error) {
457
  console.error("Error fetching balance:", error);
458
  accountBalanceSpan.textContent = "Error";
459
  }
460
  }
461
- connectWalletBtn.addEventListener('click', connectWallet);
462
-
463
 
464
  // --- Tab Management ---
465
  tabButtons.forEach(button => {
466
  button.addEventListener('click', () => {
 
467
  tabButtons.forEach(btn => btn.classList.remove('active'));
468
  tabContents.forEach(content => content.classList.remove('active'));
 
469
  button.classList.add('active');
470
- document.getElementById(button.dataset.tab).classList.add('active');
 
 
 
 
471
  });
472
  });
473
 
474
  // --- TXID Tools Module ---
475
  generateTxidBtn.addEventListener('click', () => {
476
- const randomBytes = ethers.utils.randomBytes(32);
477
- const txid = ethers.utils.hexlify(randomBytes);
478
  generatedTxidInput.value = txid;
479
- txidToSignInput.value = txid; // Auto-fill signer input
480
- showMessage('TXID generated and auto-filled for signing.', 'success');
 
481
  });
482
 
483
  signTxidBtn.addEventListener('click', async () => {
484
- if (!signer) {
485
- showMessage('Please connect your wallet first.', 'error');
486
- return;
487
- }
488
  const message = txidToSignInput.value;
489
- if (!message || !ethers.utils.isHexString(message, 32)) { // Check if it's a 32-byte hex string
490
- showMessage('Please enter a valid 64-character hexadecimal TXID to sign (e.g., 0x...).', 'error');
491
- return;
492
  }
 
 
493
  try {
494
- showLoadingSpinner(signTxidBtn, true, "Sign TXID with Wallet");
495
- const signature = await signer.signMessage(message);
496
  txidSignatureTextarea.value = signature;
497
- // Auto-fill verifier inputs
498
- messageToVerifyInput.value = message;
499
  signatureToVerifyTextarea.value = signature;
500
- showMessage('Message signed successfully! Signature and details auto-filled for verification.', 'success');
501
- saveTxidToHistory(message, signature);
502
  } catch (error) {
503
- console.error("Error signing message:", error);
504
- showMessage(`Error signing message: ${error.message}`, 'error');
505
  } finally {
506
- showLoadingSpinner(signTxidBtn, false, "Sign TXID with Wallet");
507
  }
508
  });
509
 
510
  verifySignatureBtn.addEventListener('click', () => {
511
  const message = messageToVerifyInput.value;
512
  const signature = signatureToVerifyTextarea.value;
513
- if (!message || !signature) {
514
- showMessage('Please enter both message (TXID) and signature to verify.', 'error');
515
- return;
516
- }
517
  try {
518
- const recovered = ethers.utils.verifyMessage(message, signature);
519
  recoveredAddressSpan.textContent = recovered;
 
520
  if (currentAccount && recovered.toLowerCase() === currentAccount.toLowerCase()) {
521
- verificationStatusP.textContent = 'Successfully verified! Signature matches connected wallet.';
522
- verificationStatusP.className = 'mt-1 text-sm text-green-400';
523
  } else if (currentAccount) {
524
- verificationStatusP.textContent = 'Signature is valid, but does not match connected wallet.';
525
- verificationStatusP.className = 'mt-1 text-sm text-yellow-400';
526
  } else {
527
- verificationStatusP.textContent = 'Signature is valid.';
528
- verificationStatusP.className = 'mt-1 text-sm text-green-400';
529
  }
530
  } catch (error) {
531
- console.error("Error verifying signature:", error);
532
  recoveredAddressSpan.textContent = 'Error';
533
  verificationStatusP.textContent = `Verification failed: ${error.message}`;
534
  verificationStatusP.className = 'mt-1 text-sm text-red-400';
535
  }
536
  });
537
-
538
  function saveTxidToHistory(message, signature, verifiedSigner = null) {
539
  let history = JSON.parse(localStorage.getItem(TXID_HISTORY_KEY)) || [];
 
540
  const newEntry = {
541
- message,
542
- signature,
543
  timestamp: new Date().toISOString(),
544
- verifiedSigner, // Can be updated later if verified against a known account
545
- dogechainTxStatus: ethers.utils.isHexString(message, 32) ? 'Checking...' : 'N/A (Not TX Hash)'
546
  };
547
- history.unshift(newEntry); // Add to the beginning
548
- if (history.length > 50) history.pop(); // Limit history size
549
  localStorage.setItem(TXID_HISTORY_KEY, JSON.stringify(history));
550
  renderTxidHistory();
551
  }
552
 
553
  async function renderTxidHistory() {
 
554
  txidHistoryTableBody.innerHTML = '';
555
  let history = JSON.parse(localStorage.getItem(TXID_HISTORY_KEY)) || [];
556
  if (history.length === 0) {
@@ -563,21 +766,24 @@
563
  <td class="word-break-all text-xs">${item.message}</td>
564
  <td class="word-break-all text-xs">${item.signature}</td>
565
  <td class="text-xs">${new Date(item.timestamp).toLocaleString()}</td>
566
- <td class="word-break-all text-xs">${item.verifiedSigner || 'Not verified here'}</td>
567
  <td class="text-xs status-cell" data-txhash="${item.message}">${item.dogechainTxStatus || 'N/A'}</td>
568
  `;
569
- // If status is 'Checking...', fetch actual status (only for valid TX hashes)
570
- if (item.dogechainTxStatus === 'Checking...' && ethers.utils.isHexString(item.message, 32)) {
571
  const statusCell = row.querySelector('.status-cell');
572
  checkDogechainTxStatus(item.message).then(statusHtml => {
573
- statusCell.innerHTML = statusHtml;
574
- // Optionally update localStorage too, but might be too much I/O
 
 
 
 
575
  });
576
  }
577
  }
578
  }
579
  clearHistoryBtn.addEventListener('click', () => {
580
- if (confirm('Are you sure you want to clear all TXID history? This cannot be undone.')) {
581
  localStorage.removeItem(TXID_HISTORY_KEY);
582
  renderTxidHistory();
583
  showMessage('TXID history cleared.', 'success');
@@ -586,468 +792,337 @@
586
 
587
  // --- DRC-20 Inspector Module ---
588
  fetchTokenDataBtn.addEventListener('click', async () => {
589
- activeTokenAddress = drc20TokenAddressInput.value.trim();
590
- if (!ethers.utils.isAddress(activeTokenAddress)) {
591
- showMessage("Invalid DRC-20 Token Address.", "error");
592
- return;
593
- }
594
- showMessage(`Fetching data for ${activeTokenAddress}...`, "info", 2000);
595
 
596
- // Reset sections
597
  drc20MetadataSection.classList.add('hidden');
598
  drc20HoldersSection.classList.add('hidden');
599
  drc20ChartSection.classList.add('hidden');
600
  drc20TransfersSection.classList.add('hidden');
601
- tokenHoldersTableBody.innerHTML = '';
602
- tokenTransfersTableBody.innerHTML = '';
603
  if (tokenDistributionChartInstance) tokenDistributionChartInstance.destroy();
604
 
605
  await fetchTokenMetadata(activeTokenAddress);
606
- await fetchTokenHolders(activeTokenAddress, 1); // Start with page 1
607
- await fetchTokenTransfers(activeTokenAddress);
 
 
 
 
608
  });
609
 
610
  whaleFilterCheckbox.addEventListener('change', () => {
611
- if (activeTokenAddress) fetchTokenHolders(activeTokenAddress, 1); // Re-fetch from page 1 with filter
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
612
  });
613
 
614
  async function fetchTokenMetadata(tokenAddress) {
615
- if (!provider) { showMessage("Connect wallet to fetch metadata via contract calls.", "error"); return; }
 
 
 
 
 
 
 
 
 
616
  try {
617
- const tokenContract = new ethers.Contract(tokenAddress, [
618
- "function name() view returns (string)",
619
- "function symbol() view returns (string)",
620
- "function decimals() view returns (uint8)",
621
- "function totalSupply() view returns (uint256)"
622
- ], provider);
623
-
624
- const [name, symbol, decimals, totalSupply] = await Promise.all([
625
- tokenContract.name(),
626
- tokenContract.symbol(),
627
- tokenContract.decimals(),
628
- tokenContract.totalSupply()
629
  ]);
630
-
631
  tokenMetaNameSpan.textContent = name;
632
  tokenMetaSymbolSpan.textContent = symbol;
633
  tokenMetaDecimalsSpan.textContent = decimals.toString();
634
- tokenMetaTotalSupplySpan.textContent = ethers.utils.formatUnits(totalSupply, decimals);
635
  drc20MetadataSection.classList.remove('hidden');
 
636
  } catch (error) {
637
- console.error("Error fetching token metadata:", error);
638
- showMessage("Failed to fetch token metadata. Ensure address is a valid DRC-20 contract and you're on the correct network.", "error");
639
- tokenMetaNameSpan.textContent = "Error";
640
- tokenMetaSymbolSpan.textContent = "Error";
641
- tokenMetaDecimalsSpan.textContent = "Error";
642
- tokenMetaTotalSupplySpan.textContent = "Error";
 
643
  }
644
  }
645
 
646
  async function fetchTokenHolders(tokenAddress, page, offset = 10) {
 
647
  currentHoldersPage = page;
648
  const isWhaleFilterActive = whaleFilterCheckbox.checked;
 
649
  try {
650
- // The Dogechain explorer API for token holders is usually:
651
- // ?module=token&action=tokenholders&contractaddress={contractAddress}&page={page}&offset={offset}
652
- // However, the exact API structure and availability can vary. This is a common pattern.
653
- // For this example, I'll simulate fetching and then client-side filtering if needed,
654
- // as direct whale filtering might not be an API param.
655
- // A more robust solution would be to use an API that supports rich queries if available.
656
- // This specific explorer might not have a direct 'tokenholders' action.
657
- // Let's assume we are getting a list of transfers and deriving holders.
658
- // A better approach is often to use a dedicated indexing service or a more capable API.
659
- // Given the limitations, for this example, the "Token Holder Scanner" might be limited or illustrative.
660
- // For a true holder list, you need an API endpoint like Etherscan's `action=tokenholderlist`.
661
- // Dogechain explorer `action=tokentx` lists transfers.
662
- // We'll use the API for transfers and try to approximate. This is not ideal for true holder scanning.
663
-
664
- // Using a placeholder: Dogechain explorer API for token holders might be like:
665
- // `${DOGECHAIN_EXPLORER_API_BASE}?module=token&action=tokenholderlist&contractaddress=${tokenAddress}&page=${page}&offset=${offset}`
666
- // This endpoint does not seem to exist on explorer.dogechain.dog.
667
- // So, for demonstration, holder scanning will be illustrative.
668
- // A real implementation would require a different API or backend service.
669
-
670
- // For now, let's try to get a list of recent transactions and count unique addresses as a proxy,
671
- // which is NOT a true holder list but demonstrates API interaction.
672
- const response = await fetch(`${DOGECHAIN_EXPLORER_API_BASE}?module=account&action=tokentx&contractaddress=${tokenAddress}&address=${tokenAddress}&page=${page}&offset=100&sort=desc`);
673
  const data = await response.json();
674
 
675
- if (data.status === "1" && data.result) {
676
- let holders = {};
677
- let decimals = parseInt(tokenMetaDecimalsSpan.textContent) || 18; // Use fetched decimals
 
 
 
 
678
 
679
- // This is a simplified way to estimate balances from transfers and is not accurate for full holder list.
680
- // A proper holder list requires an API that provides current balances per holder.
681
  data.result.forEach(tx => {
682
- if (tx.to && ethers.utils.isAddress(tx.to)) {
683
- holders[tx.to.toLowerCase()] = (holders[tx.to.toLowerCase()] || 0) + parseFloat(ethers.utils.formatUnits(tx.value, decimals));
684
- }
685
- if (tx.from && ethers.utils.isAddress(tx.from)) {
686
- holders[tx.from.toLowerCase()] = (holders[tx.from.toLowerCase()] || 0) - parseFloat(ethers.utils.formatUnits(tx.value, decimals));
687
  }
688
  });
689
 
690
- let aggregatedHolders = Object.entries(holders)
691
- .map(([address, balance]) => ({ address, balance }))
692
- .filter(h => h.balance > 0.000001); // Filter out dust or negative from this crude calc
693
 
694
  if (isWhaleFilterActive) {
695
- aggregatedHolders = aggregatedHolders.filter(h => h.balance >= 10000);
 
696
  }
697
 
698
- aggregatedHolders.sort((a, b) => b.balance - a.balance);
 
 
 
 
699
 
700
- // Paginate client-side (since API for holders is missing)
701
  const paginatedHolders = aggregatedHolders.slice((page - 1) * offset, page * offset);
702
-
703
-
704
  tokenHoldersTableBody.innerHTML = '';
705
  if (paginatedHolders.length === 0) {
706
- tokenHoldersTableBody.innerHTML = '<tr><td colspan="3" class="text-center py-3 text-gray-400">No holders found or end of list. (Note: This is an estimation based on recent transfers).</td></tr>';
707
  } else {
708
- const totalSupplyNum = parseFloat(tokenMetaTotalSupplySpan.textContent.replace(/,/g, '')) || 1;
 
 
 
 
709
  paginatedHolders.forEach(holder => {
710
- const percentage = totalSupplyNum > 0 ? ((holder.balance / totalSupplyNum) * 100).toFixed(4) : "0.0000";
 
711
  const row = tokenHoldersTableBody.insertRow();
712
- row.innerHTML = `
713
- <td class="word-break-all text-xs">${holder.address}</td>
714
- <td class="text-xs">${holder.balance.toFixed(4)}</td>
715
- <td class="text-xs">${percentage}%</td>
716
- `;
717
  });
718
  }
719
  drc20HoldersSection.classList.remove('hidden');
720
  renderHoldersPagination(page, aggregatedHolders.length, offset);
721
-
722
- // Update chart with top holders from the *full* aggregated list (not just paginated)
723
  renderTokenDistributionChart(aggregatedHolders.slice(0,10), decimals);
724
-
725
-
726
  } else {
727
- showMessage("Could not fetch token holder data (or no transactions found for proxy). " + (data.message || ""), "error");
728
- tokenHoldersTableBody.innerHTML = '<tr><td colspan="3" class="text-center py-3 text-gray-400">Error fetching data.</td></tr>';
729
  }
730
  } catch (error) {
731
- console.error("Error fetching token holders:", error);
732
- showMessage("Error fetching token holders. " + error.message, "error");
733
- tokenHoldersTableBody.innerHTML = '<tr><td colspan="3" class="text-center py-3 text-gray-400">Error fetching data.</td></tr>';
734
  }
735
  }
736
 
737
  function renderHoldersPagination(currentPage, totalItems, itemsPerPage) {
 
738
  holdersPaginationControlsDiv.innerHTML = '';
739
  const totalPages = Math.ceil(totalItems / itemsPerPage);
740
  if (totalPages <= 1) return;
741
-
742
- const prevButton = document.createElement('button');
743
- prevButton.textContent = 'Previous';
744
- prevButton.className = 'btn-secondary text-xs mr-1 disabled:opacity-50';
745
- prevButton.disabled = currentPage === 1;
746
- prevButton.addEventListener('click', () => fetchTokenHolders(activeTokenAddress, currentPage - 1));
747
- holdersPaginationControlsDiv.appendChild(prevButton);
748
-
749
- const pageInfo = document.createElement('span');
750
- pageInfo.textContent = ` Page ${currentPage} of ${totalPages} `;
751
- pageInfo.className = 'text-xs align-middle';
752
  holdersPaginationControlsDiv.appendChild(pageInfo);
753
-
754
- const nextButton = document.createElement('button');
755
- nextButton.textContent = 'Next';
756
- nextButton.className = 'btn-secondary text-xs ml-1 disabled:opacity-50';
757
- nextButton.disabled = currentPage === totalPages;
758
- nextButton.addEventListener('click', () => fetchTokenHolders(activeTokenAddress, currentPage + 1));
759
- holdersPaginationControlsDiv.appendChild(nextButton);
760
  }
761
 
762
- function renderTokenDistributionChart(topHolders, decimals) { // topHolders: [{address, balance}]
763
- if (tokenDistributionChartInstance) {
764
- tokenDistributionChartInstance.destroy();
765
- }
766
- if (!topHolders || topHolders.length === 0) {
767
- drc20ChartSection.classList.add('hidden');
768
- return;
769
- }
770
-
771
  const labels = topHolders.map(h => `${h.address.substring(0,6)}...${h.address.substring(h.address.length - 4)}`);
772
- const data = topHolders.map(h => parseFloat(h.balance)); // Balance is already formatted
773
-
774
  const chartData = {
775
  labels: labels,
776
- datasets: [{
777
- label: 'Token Distribution',
778
- data: data,
779
- backgroundColor: [
780
- '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF',
781
- '#FF9F40', '#C9CBCF', '#7BC225', '#F263A2', '#A136EB'
782
- ],
783
- hoverOffset: 4
784
- }]
785
  };
786
- tokenDistributionChartInstance = new Chart(tokenDistributionChartCanvas, {
787
- type: 'pie',
788
- data: chartData,
789
- options: {
790
- responsive: true,
791
- maintainAspectRatio: false,
792
- plugins: {
793
- legend: {
794
- position: 'top',
795
- labels: { color: '#f3f4f6' }
796
- },
797
- tooltip: {
798
- callbacks: {
799
- label: function(context) {
800
- let label = context.dataset.label || '';
801
- if (label) {
802
- label += ': ';
803
- }
804
- if (context.parsed !== null) {
805
- label += context.parsed.toFixed(2) + ' tokens';
806
- }
807
- return label;
808
- }
809
- }
810
- }
811
- }
812
- }
813
- });
814
  drc20ChartSection.classList.remove('hidden');
815
  }
816
-
817
- let transferPollInterval;
818
  async function fetchTokenTransfers(tokenAddress, limit = 20) {
819
- if (transferPollInterval) clearInterval(transferPollInterval); // Clear previous poll
820
-
821
  const loadTransfers = async () => {
822
  try {
823
- const response = await fetch(`${DOGECHAIN_EXPLORER_API_BASE}?module=account&action=tokentx&contractaddress=${tokenAddress}&address=${tokenAddress}&page=1&offset=${limit}&sort=desc`);
 
824
  const data = await response.json();
825
- if (data.status === "1" && data.result) {
826
  tokenTransfersTableBody.innerHTML = '';
827
- const decimals = parseInt(tokenMetaDecimalsSpan.textContent) || 18;
 
 
 
 
828
  data.result.forEach(tx => {
829
  const row = tokenTransfersTableBody.insertRow();
830
- row.innerHTML = `
831
- <td class="word-break-all text-xs"><a href="https://explorer.dogechain.dog/tx/${tx.hash}" target="_blank" class="text-amber-300 hover:underline">${tx.hash.substring(0,10)}...</a></td>
832
- <td class="word-break-all text-xs">${tx.from.substring(0,10)}...</td>
833
- <td class="word-break-all text-xs">${tx.to.substring(0,10)}...</td>
834
- <td class="text-xs">${parseFloat(ethers.utils.formatUnits(tx.value, decimals)).toFixed(4)}</td>
835
- <td class="text-xs">${new Date(tx.timeStamp * 1000).toLocaleString()}</td>
836
- `;
837
  });
838
- drc20TransfersSection.classList.remove('hidden');
839
- } else {
840
- tokenTransfersTableBody.innerHTML = '<tr><td colspan="5" class="text-center py-3 text-gray-400">No transfers found or API error.</td></tr>';
841
- }
842
  } catch (error) {
843
- console.error("Error fetching token transfers:", error);
844
- tokenTransfersTableBody.innerHTML = '<tr><td colspan="5" class="text-center py-3 text-gray-400">Error fetching transfers.</td></tr>';
 
845
  }
846
  };
847
-
848
- await loadTransfers(); // Initial load
849
- transferPollInterval = setInterval(loadTransfers, 30000); // Poll every 30 seconds
850
  }
851
 
852
-
853
  // --- Contract Interaction Module ---
854
- let currentContractInstance;
855
  loadContractBtn.addEventListener('click', () => {
856
  const address = contractAddressInput.value.trim();
857
  const abiString = contractAbiInput.value.trim();
858
-
859
- if (!ethers.utils.isAddress(address)) {
860
- showMessage("Invalid Contract Address.", "error");
861
- return;
862
- }
863
  let abi;
864
- try {
865
- abi = JSON.parse(abiString);
866
- if (!Array.isArray(abi)) throw new Error("ABI must be a JSON array.");
867
- } catch (error) {
868
- showMessage("Invalid ABI format. Must be a valid JSON array.", "error");
869
- console.error("ABI Parse Error:", error);
870
- return;
871
- }
872
-
873
- if (!provider) {
874
- showMessage("Please connect your wallet first.", "error");
875
- return;
876
- }
877
 
878
  currentContractInstance = new ethers.Contract(address, abi, signer || provider);
879
  renderContractFunctions(abi);
880
  contractFunctionsSection.classList.remove('hidden');
881
  functionResultDisplay.classList.add('hidden');
882
- showMessage("Contract loaded. Functions listed below.", "success");
883
  });
884
 
885
  function renderContractFunctions(abi) {
886
- readFunctionsContainer.innerHTML = '';
887
- writeFunctionsContainer.innerHTML = '';
888
-
889
  abi.forEach(item => {
890
  if (item.type === 'function') {
891
- const container = (item.stateMutability === 'view' || item.stateMutability === 'pure') ? readFunctionsContainer : writeFunctionsContainer;
892
-
893
- const funcDiv = document.createElement('div');
894
- funcDiv.className = 'p-3 bg-gray-700 rounded mb-3';
895
-
896
- let inputsHtml = item.inputs.map((input, index) => `
897
- <label for="${item.name}_${index}" class="block text-xs mt-2 mb-1">${input.name || 'input_' + index} (${input.type})</label>
898
- <input type="${input.type.includes('uint') || input.type.includes('int') ? 'number' : 'text'}"
899
- id="${item.name}_${index}"
900
- class="text-sm w-full"
901
- placeholder="${input.type}">
902
- `).join('');
903
-
904
- if (item.stateMutability !== 'view' && item.stateMutability !== 'pure' && item.payable) {
905
- inputsHtml += `
906
- <label for="${item.name}_value" class="block text-xs mt-2 mb-1">Value (DOGE to send):</label>
907
- <input type="number" id="${item.name}_value" class="text-sm w-full" placeholder="0.0">`;
908
- }
909
-
910
- const buttonText = (item.stateMutability === 'view' || item.stateMutability === 'pure') ? 'Query' : 'Execute';
911
-
912
- funcDiv.innerHTML = `
913
- <h5 class="font-semibold text-amber-300">${item.name}</h5>
914
- ${inputsHtml}
915
- <button data-function="${item.name}" data-payable="${item.payable || false}" data-inputs='${JSON.stringify(item.inputs)}' class="btn-secondary text-sm mt-3 contract-call-btn">${buttonText}</button>
916
- `;
917
  container.appendChild(funcDiv);
918
  }
919
  });
920
-
921
- document.querySelectorAll('.contract-call-btn').forEach(button => {
922
- button.addEventListener('click', handleContractCall);
923
- });
924
  }
925
 
926
  async function handleContractCall(event) {
927
- if (!currentContractInstance || !signer) { // Signer needed for write, provider for read
928
- showMessage("Contract or wallet not ready.", "error");
929
- return;
930
- }
931
  const button = event.target;
932
  const functionName = button.dataset.function;
933
  const isPayable = button.dataset.payable === 'true';
 
934
  const inputsMeta = JSON.parse(button.dataset.inputs);
 
 
 
 
935
 
936
  const args = [];
937
- for (let i = 0; i < inputsMeta.length; i++) {
938
- const inputElement = document.getElementById(`${functionName}_${i}`);
939
- let value = inputElement.value;
940
- // Handle boolean
941
- if (inputsMeta[i].type === 'bool') {
942
- value = (value.toLowerCase() === 'true' || value === '1');
943
- }
944
- // Handle arrays (simple comma separated string for now, could be improved with JSON input)
945
- else if (inputsMeta[i].type.endsWith('[]')) {
946
- try {
947
- value = JSON.parse(value); // Try parsing as JSON array
948
- if (!Array.isArray(value)) throw new Error();
949
- } catch (e) {
950
- // Fallback to comma-separated if not valid JSON array
951
- value = value.split(',').map(s => s.trim()).filter(s => s !== '');
952
- // Convert numbers in array if original type was uint[] or int[]
953
- if (inputsMeta[i].type.startsWith('uint') || inputsMeta[i].type.startsWith('int')) {
954
- value = value.map(v => ethers.BigNumber.from(v));
955
- }
956
- }
957
- }
958
- // Handle BigNumber for uint/int types
959
- else if (inputsMeta[i].type.startsWith('uint') || inputsMeta[i].type.startsWith('int')) {
960
- if (value === '') {
961
- showMessage(`Input for ${inputsMeta[i].name} cannot be empty.`, "error");
962
- return;
963
- }
964
- try {
965
- value = ethers.BigNumber.from(value);
966
- } catch (e) {
967
- showMessage(`Invalid number format for ${inputsMeta[i].name}: ${value}`, "error");
968
- return;
969
- }
970
  }
971
- args.push(value);
972
- }
973
 
974
- let options = {};
975
- if (isPayable) {
976
- const valueElement = document.getElementById(`${functionName}_value`);
977
- if (valueElement && valueElement.value) {
978
- try {
979
- options.value = ethers.utils.parseEther(valueElement.value);
980
- } catch (e) {
981
- showMessage("Invalid DOGE value to send.", "error"); return;
982
- }
983
- }
984
- }
985
 
986
- functionResultDisplay.classList.remove('hidden');
987
- functionResultOutput.textContent = 'Processing...';
988
- showLoadingSpinner(button, true, button.textContent);
989
 
990
  try {
991
- const func = currentContractInstance.functions[functionName];
992
- if (!func) {
993
- throw new Error(`Function ${functionName} not found on contract instance.`);
994
- }
995
-
996
  let result;
997
- // Distinguish read from write (write functions need a signer and return a transaction)
998
- const isReadCall = currentContractInstance.interface.getFunction(functionName).stateMutability === 'view' ||
999
- currentContractInstance.interface.getFunction(functionName).stateMutability === 'pure';
1000
-
1001
- if (isReadCall) {
1002
- if (Object.keys(options).length > 0) { // options like {value} not for read calls
1003
- result = await func(...args);
1004
- } else {
1005
- result = await func(...args);
1006
- }
1007
  functionResultOutput.textContent = `Result: ${formatContractResult(result)}`;
1008
  showMessage("Query successful.", "success");
1009
- } else { // Write call
1010
- if (!signer) {
1011
- throw new Error("Wallet Signer is required for write operations.");
1012
- }
1013
- // For write functions, connect contract to signer
1014
  const contractWithSigner = currentContractInstance.connect(signer);
1015
- const tx = await contractWithSigner[functionName](...args, options);
1016
- functionResultOutput.textContent = `Transaction Sent! Hash: ${tx.hash}\nWaiting for confirmation...`;
1017
- showMessage(`Transaction ${tx.hash} sent.`, "info", 10000);
1018
- const receipt = await tx.wait();
1019
- functionResultOutput.textContent = `Transaction Confirmed!\nHash: ${receipt.transactionHash}\nBlock: ${receipt.blockNumber}\nStatus: ${receipt.status === 1 ? 'Success' : 'Failed'}`;
1020
- showMessage(`Transaction ${receipt.transactionHash} confirmed!`, "success");
1021
- if (ethers.utils.isHexString(receipt.transactionHash, 32)) { // If it's a valid hash
1022
- saveTxidToHistory(receipt.transactionHash, "N/A (Contract TX)", currentAccount); // Save to history
1023
- }
1024
  }
1025
  } catch (error) {
1026
- console.error(`Error calling ${functionName}:`, error);
1027
- functionResultOutput.textContent = `Error: ${error.message || error.toString()}`;
1028
- showMessage(`Error calling ${functionName}: ${error.data?.message || error.message}`, "error", 10000);
1029
- } finally {
1030
- showLoadingSpinner(button, false, button.textContent.replace("Processing...", "").trim());
1031
- }
 
1032
  }
1033
 
1034
  function formatContractResult(result) {
 
1035
  if (result === null || result === undefined) return "null/undefined";
1036
- if (ethers.BigNumber.isBigNumber(result)) return result.toString();
1037
- if (Array.isArray(result)) return `[${result.map(formatContractResult).join(', ')}]`;
1038
- if (typeof result === 'object') {
1039
- try { return JSON.stringify(result, null, 2); }
1040
- catch (e) { return result.toString(); }
 
 
 
 
 
1041
  }
 
1042
  return result.toString();
1043
  }
1044
 
1045
  // --- Initialization ---
1046
- renderTxidHistory(); // Load history on page load
1047
- // Attempt to auto-connect if previously connected or permissions granted (optional)
1048
- // This might require more sophisticated state management or specific EIP-6963 handling
1049
  });
1050
  </script>
 
1051
  </body>
1052
  </html>
1053
-
 
4
  <head>
5
  <meta charset="UTF-8">
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
+ <title>Dogechain Super DApp - Multi-Wallet</title>
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
+ <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap" rel="stylesheet">
11
  <script src="https://cdn.tailwindcss.com"></script>
 
12
  <script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
13
  <style>
14
+ :root { --primary-color: #fbbf24; /* amber-400 */ }
15
+ body { font-family: 'Inter', sans-serif; }
16
  .tab-button.active {
17
+ background-color: var(--primary-color);
18
+ color: #1f2937; /* gray-800 */
19
  border-bottom-color: transparent;
20
  }
21
  .tab-button {
22
  transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out;
23
  padding: 0.75rem 1.5rem;
24
  margin-bottom: -1px; /* Overlap border */
25
+ border: 1px solid #4b5563; /* gray-600 */
26
  border-bottom: 1px solid #4b5563;
27
+ white-space: nowrap;
28
+ border-top-left-radius: 0.375rem; /* rounded-t-md */
29
+ border-top-right-radius: 0.375rem; /* rounded-t-md */
30
  }
31
+ .tab-button:not(.active):hover { background-color: #374151; /* gray-700 */ }
 
 
32
  .tab-content { display: none; }
33
  .tab-content.active { display: block; }
34
 
 
35
  .spinner {
36
  border: 4px solid rgba(255, 255, 255, 0.3);
37
  border-radius: 50%;
38
+ border-top-color: var(--primary-color);
39
  width: 20px;
40
  height: 20px;
41
  animation: spin 1s linear infinite;
42
  display: inline-block;
43
+ vertical-align: middle;
44
  margin-right: 8px;
45
  }
46
+ @keyframes spin { to { transform: rotate(360deg); } }
47
+
 
48
  input[type="text"], input[type="number"], textarea, select {
49
  background-color: #374151; /* gray-700 */
50
  border: 1px solid #4b5563; /* gray-600 */
 
55
  }
56
  input:focus, textarea:focus, select:focus {
57
  outline: none;
58
+ border-color: var(--primary-color);
59
+ box-shadow: 0 0 0 2px rgba(251,191,36,0.5);
60
  }
61
  button {
62
  padding: 0.5rem 1rem;
63
  border-radius: 0.375rem; /* rounded-md */
64
  font-weight: 600; /* semibold */
65
+ transition: all 0.2s;
66
+ display: inline-flex;
67
+ align-items: center;
68
+ justify-content: center;
69
  }
70
+ button:disabled { opacity: 0.6; cursor: not-allowed; }
71
  .btn-primary {
72
+ background-color: var(--primary-color);
73
  color: #1f2937; /* gray-800 */
74
  }
75
+ .btn-primary:hover:not(:disabled) { background-color: #f59e0b; /* amber-500 */ }
 
 
76
  .btn-secondary {
77
  background-color: #4b5563; /* gray-600 */
78
  color: #f3f4f6; /* gray-100 */
79
  }
80
+ .btn-secondary:hover:not(:disabled) { background-color: #6b7280; /* gray-500 */ }
81
+ .btn-danger {
82
+ background-color: #dc2626; /* red-600 */
83
+ color: #f3f4f6; /* gray-100 */
84
  }
85
+ .btn-danger:hover:not(:disabled) { background-color: #b91c1c; /* red-700 */ }
86
+
87
+
88
  .table-auto th, .table-auto td {
89
  border: 1px solid #4b5563; /* gray-600 */
90
  padding: 0.5rem;
91
  text-align: left;
92
  }
93
+ .table-auto th { background-color: #374151; /* gray-700 */ }
94
+ .word-break-all { word-break: break-all; }
95
+
96
+ /* Styles for Modals */
97
+ .modal-overlay {
98
+ position: fixed;
99
+ top: 0;
100
+ left: 0;
101
+ width: 100%;
102
+ height: 100%;
103
+ background-color: rgba(0, 0, 0, 0.7);
104
+ display: flex;
105
+ justify-content: center;
106
+ align-items: center;
107
+ z-index: 1000;
108
+ backdrop-filter: blur(4px);
109
+ }
110
+ .modal-content {
111
+ position: relative;
112
+ background-color: #1f2937; /* gray-800 */
113
+ padding: 1.5rem;
114
+ border-radius: 0.5rem;
115
+ box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05);
116
+ width: 100%;
117
+ max-width: 24rem; /* sm */
118
+ text-align: center;
119
+ border: 1px solid #4b5563; /* gray-600 */
120
+ }
121
+ .modal-close-btn {
122
+ position: absolute;
123
+ top: 0.5rem;
124
+ right: 0.75rem;
125
+ background: none;
126
+ border: none;
127
+ font-size: 1.5rem;
128
+ line-height: 1;
129
+ color: #9ca3af; /* gray-400 */
130
+ cursor: pointer;
131
+ padding: 0.25rem;
132
+ }
133
+ .modal-close-btn:hover { color: #f3f4f6; /* gray-100 */ }
134
+ .wallet-choice-btn {
135
+ text-align: left;
136
  background-color: #374151; /* gray-700 */
137
+ color: #f3f4f6; /* gray-100 */
138
+ border: 1px solid #4b5563; /* gray-600 */
139
+ padding: 1rem;
140
+ font-size: 1rem;
141
+ width: 100%;
142
  }
143
+ .wallet-choice-btn:hover:not(:disabled) { border-color: var(--primary-color); background-color: #4b5563; }
144
  </style>
145
+ <!-- Import Map for ethers v6 -->
146
+ <script type="importmap">
147
  {
148
  "imports": {
149
+ "ethers": "https://esm.sh/ethers@6",
150
  "react": "https://esm.sh/react@^19.1.0",
151
  "react-dom/": "https://esm.sh/react-dom@^19.1.0/",
152
+ "react/": "https://esm.sh/react@^19.1.0/"
 
153
  }
154
  }
155
  </script>
 
158
  <div class="container mx-auto max-w-6xl">
159
  <header class="mb-6 text-center">
160
  <h1 class="text-3xl sm:text-4xl font-bold text-yellow-400">Dogechain Super DApp 🐕⛓️</h1>
161
+ <p class="text-gray-400 mt-1">Multi-Wallet Support</p>
162
+ <div class="mt-4">
163
+ <button id="connectWalletBtn" class="btn-primary px-5 py-2">Connect Wallet</button>
164
+ <button id="disconnectWalletBtn" class="btn-secondary px-5 py-2 hidden ml-2">Disconnect</button>
165
  </div>
166
+ <div id="walletInfo" class="mt-3 text-sm hidden space-y-1 bg-gray-800 p-3 rounded-md">
167
  <p><strong>Status:</strong> <span id="walletStatus" class="text-green-400">Connected</span></p>
168
+ <p><strong>Connected via:</strong> <span id="connectedWalletName" class="text-gray-300"></span></p>
169
  <p><strong>Account:</strong> <span id="connectedAccount" class="text-amber-300 word-break-all"></span></p>
170
  <p><strong>Network:</strong> <span id="connectedNetwork" class="text-amber-300"></span></p>
171
+ <p><strong>Native Balance:</strong> <span id="accountBalance" class="text-amber-300"></span> DOGE</p>
172
  </div>
173
  </header>
174
 
 
183
  <li><button class="tab-button" data-tab="contractInteract">Contract Interaction</button></li>
184
  </ul>
185
  </nav>
186
+
 
187
  <main id="tabContentContainer">
188
  <!-- TXID Tools Tab -->
189
  <div id="txidTools" class="tab-content active space-y-6">
 
209
  <label for="signatureToVerify" class="block text-sm mb-1">Signature:</label>
210
  <textarea id="signatureToVerify" rows="3" class="mb-2" placeholder="Enter signature"></textarea>
211
  <button id="verifySignatureBtn" class="btn-primary">Verify Signature</button>
212
+ <p class="mt-2 text-sm">Recovered Address: <span id="recoveredAddress" class="font-mono text-amber-300 word-break-all"></span></p>
213
  <p id="verificationStatus" class="mt-1 text-sm"></p>
214
  </section>
215
 
216
  <section class="bg-gray-800 p-4 rounded-lg shadow">
217
  <h2 class="text-xl font-semibold text-yellow-400 mb-3">4. TXID + Signature History</h2>
218
+ <button id="clearHistoryBtn" class="btn-danger text-sm mb-3">Clear History</button>
219
  <div class="overflow-x-auto">
220
  <table class="w-full table-auto text-sm">
221
  <thead>
 
245
  </section>
246
 
247
  <section id="drc20MetadataSection" class="bg-gray-800 p-4 rounded-lg shadow hidden">
248
+ <h2 class="text-xl font-semibold text-yellow-400 mb-3">Token Metadata</h2>
249
  <div id="drc20MetadataDisplay" class="space-y-1 text-sm">
250
  <p><strong>Name:</strong> <span id="tokenMetaName">N/A</span></p>
251
  <p><strong>Symbol:</strong> <span id="tokenMetaSymbol">N/A</span></p>
 
255
  </section>
256
 
257
  <section id="drc20HoldersSection" class="bg-gray-800 p-4 rounded-lg shadow hidden">
258
+ <h2 class="text-xl font-semibold text-yellow-400 mb-3">Token Holder Scanner</h2>
259
  <div class="flex justify-between items-center mb-2">
260
  <label for="whaleFilterCheckbox" class="text-sm flex items-center">
261
  <input type="checkbox" id="whaleFilterCheckbox" class="mr-2 h-4 w-4 rounded text-amber-400 focus:ring-amber-500 bg-gray-700 border-gray-600"> Show only "Whales" (10,000+ tokens)
 
279
  </section>
280
 
281
  <section id="drc20ChartSection" class="bg-gray-800 p-4 rounded-lg shadow hidden">
282
+ <h2 class="text-xl font-semibold text-yellow-400 mb-3">Token Distribution Chart (Top Holders)</h2>
283
  <canvas id="tokenDistributionChart" class="max-h-96"></canvas>
284
  </section>
285
 
286
  <section id="drc20TransfersSection" class="bg-gray-800 p-4 rounded-lg shadow hidden">
287
+ <h2 class="text-xl font-semibold text-yellow-400 mb-3">Recent Token Transfers</h2>
288
+ <button id="toggleLiveUpdatesBtn" class="btn-secondary text-sm mb-2">Enable Live Updates</button>
289
  <div class="overflow-x-auto max-h-96">
290
  <table class="w-full table-auto text-sm">
291
  <thead>
 
325
  </div>
326
  </div>
327
  </main>
328
+
329
+
330
  <footer class="mt-12 text-center text-gray-500 text-xs pb-8">
331
+ <p id="footerYear"></p>
332
+ <p>Always verify information and be cautious. Interacting with smart contracts carries inherent risk.</p>
333
  </footer>
334
  </div>
335
 
336
+ <!-- Multi-Wallet Choice Modal -->
337
+ <div id="walletChoiceModal" class="modal-overlay hidden">
338
+ <div class="modal-content">
339
+ <button id="walletChoiceModalCloseBtn" class="modal-close-btn">×</button>
340
+ <h3 class="text-lg font-bold text-gray-100 mb-4">Connect a Wallet</h3>
341
+ <div class="flex flex-col space-y-3">
342
+ <button id="connectMyDogeBtn" class="wallet-choice-btn">
343
+ <img src="https://mydoge.com/assets/img/logo_blue.svg" alt="MyDoge Logo" class="w-8 h-8 mr-4 inline-block align-middle">
344
+ MyDoge Wallet
345
+ </button>
346
+ <button id="connectMetaMaskBtn" class="wallet-choice-btn">
347
+ <img src="https://upload.wikimedia.org/wikipedia/commons/3/36/MetaMask_Fox.svg" alt="MetaMask Logo" class="w-8 h-8 mr-4 inline-block align-middle">
348
+ MetaMask / Other EIP-1193
349
+ </button>
350
+ </div>
351
+ <button id="walletChoiceCancelBtn" class="btn-secondary w-full py-2.5 mt-6">Cancel</button>
352
+ </div>
353
+ </div>
354
+
355
+ <script type="module">
356
+ import { ethers } from 'ethers';
357
+
358
  document.addEventListener('DOMContentLoaded', () => {
359
+ // --- State Variables ---
360
+ let provider; // ethers.BrowserProvider
361
+ let signer; // ethers.Signer
362
+ let currentAccount = null; // string | null
363
+ let currentNetwork = null; // ethers.Network | null
364
+ let currentWalletType = null; // 'mydoge' | 'metamask' | null
365
+ let tokenDistributionChartInstance = null; // Chart.js instance
366
+ let transferPollInterval; // For live transfer updates
367
  let activeTokenAddress = null; // For DRC-20 Inspector
368
  let currentHoldersPage = 1;
369
+ let isLiveUpdatesEnabled = false;
370
+
371
+ // --- Constants ---
372
+ const DOGECHAIN_MAINNET_CHAIN_ID = 2000n; // Use BigInt for chain IDs with ethers v6
373
+ const DOGECHAIN_TESTNET_CHAIN_ID = 568n; // Example Testnet ID
374
  const DOGECHAIN_EXPLORER_API_BASE = 'https://explorer.dogechain.dog/api';
375
+ const TXID_HISTORY_KEY = 'dogechainSuperDapp_TxidHistory_v4_multiwallet';
376
 
377
+ // --- UI Element Selectors ---
378
+ const getEl = (id) => document.getElementById(id);
379
+
380
+ const connectWalletBtn = getEl('connectWalletBtn');
381
+ const disconnectWalletBtn = getEl('disconnectWalletBtn');
382
+ const walletInfoDiv = getEl('walletInfo');
383
+ const walletStatusSpan = getEl('walletStatus');
384
+ const connectedWalletNameSpan = getEl('connectedWalletName');
385
+ const connectedAccountSpan = getEl('connectedAccount');
386
+ const connectedNetworkSpan = getEl('connectedNetwork');
387
+ const accountBalanceSpan = getEl('accountBalance');
388
+ const globalMessageDiv = getEl('globalMessage');
389
+
390
+ // Wallet Choice Modal
391
+ const walletChoiceModal = getEl('walletChoiceModal');
392
+ const connectMyDogeBtn = getEl('connectMyDogeBtn');
393
+ const connectMetaMaskBtn = getEl('connectMetaMaskBtn');
394
+ const walletChoiceCancelBtn = getEl('walletChoiceCancelBtn');
395
+ const walletChoiceModalCloseBtn = getEl('walletChoiceModalCloseBtn');
396
 
397
  // Tab Elements
398
  const tabButtons = document.querySelectorAll('.tab-button');
399
  const tabContents = document.querySelectorAll('.tab-content');
400
 
401
  // TXID Tools Elements
402
+ const generateTxidBtn = getEl('generateTxidBtn');
403
+ const generatedTxidInput = getEl('generatedTxid');
404
+ const txidToSignInput = getEl('txidToSign');
405
+ const signTxidBtn = getEl('signTxidBtn');
406
+ const txidSignatureTextarea = getEl('txidSignature');
407
+ const messageToVerifyInput = getEl('messageToVerify');
408
+ const signatureToVerifyTextarea = getEl('signatureToVerify');
409
+ const verifySignatureBtn = getEl('verifySignatureBtn');
410
+ const recoveredAddressSpan = getEl('recoveredAddress');
411
+ const verificationStatusP = getEl('verificationStatus');
412
+ const clearHistoryBtn = getEl('clearHistoryBtn');
413
+ const txidHistoryTableBody = getEl('txidHistoryTableBody');
414
 
415
  // DRC-20 Inspector Elements
416
+ const drc20TokenAddressInput = getEl('drc20TokenAddress');
417
+ const fetchTokenDataBtn = getEl('fetchTokenDataBtn');
418
+ const drc20MetadataSection = getEl('drc20MetadataSection');
419
+ const tokenMetaNameSpan = getEl('tokenMetaName');
420
+ const tokenMetaSymbolSpan = getEl('tokenMetaSymbol');
421
+ const tokenMetaDecimalsSpan = getEl('tokenMetaDecimals');
422
+ const tokenMetaTotalSupplySpan = getEl('tokenMetaTotalSupply');
423
+ const drc20HoldersSection = getEl('drc20HoldersSection');
424
+ const tokenHoldersTableBody = getEl('tokenHoldersTableBody');
425
+ const holdersPaginationControlsDiv = getEl('holdersPaginationControls');
426
+ const whaleFilterCheckbox = getEl('whaleFilterCheckbox');
427
+ const drc20ChartSection = getEl('drc20ChartSection');
428
+ const tokenDistributionChartCanvas = getEl('tokenDistributionChart');
429
+ const drc20TransfersSection = getEl('drc20TransfersSection');
430
+ const tokenTransfersTableBody = getEl('tokenTransfersTableBody');
431
+ const toggleLiveUpdatesBtn = getEl('toggleLiveUpdatesBtn');
432
 
433
  // Contract Interaction Elements
434
+ const contractAddressInput = getEl('contractAddressInput');
435
+ const contractAbiInput = getEl('contractAbiInput');
436
+ const loadContractBtn = getEl('loadContractBtn');
437
+ const contractFunctionsSection = getEl('contractFunctionsSection');
438
+ const readFunctionsContainer = getEl('readFunctionsContainer');
439
+ const writeFunctionsContainer = getEl('writeFunctionsContainer');
440
+ const functionResultDisplay = getEl('functionResultDisplay');
441
+ const functionResultOutput = getEl('functionResultOutput');
442
+ let currentContractInstance; // Stores the ethers.Contract instance
443
+
444
+ // Footer year
445
+ getEl('footerYear').textContent = `© ${new Date().getFullYear()} Dogechain Super DApp. For educational purposes.`;
446
+
447
 
448
  // --- Helper Functions ---
449
+ function showMessage(message, type = 'info', duration = 6000) {
450
  globalMessageDiv.textContent = message;
451
  globalMessageDiv.className = 'my-4 p-3 rounded-md text-white break-words text-sm shadow-lg'; // Reset classes
452
+ const typeClasses = { error: 'bg-red-600', success: 'bg-green-600', info: 'bg-blue-600' };
453
+ globalMessageDiv.classList.add(typeClasses[type] || 'bg-blue-600');
 
454
  globalMessageDiv.classList.remove('hidden');
455
  setTimeout(() => {
456
+ if (globalMessageDiv.textContent === message) {
457
+ globalMessageDiv.classList.add('hidden');
458
+ }
459
  }, duration);
460
  }
461
 
462
  function showLoadingSpinner(button, show = true, originalText = "Submit") {
463
+ if (!button) return;
464
  if (show) {
465
  button.disabled = true;
466
+ button.dataset.originalText = button.innerHTML;
467
  button.innerHTML = `<span class="spinner"></span>Processing...`;
468
  } else {
469
  button.disabled = false;
470
+ button.innerHTML = button.dataset.originalText || originalText;
471
  }
472
  }
473
+
474
  async function checkDogechainTxStatus(txHash) {
475
+ // ... (implementation is the same as previous full Vanilla JS version)
476
  try {
477
  const response = await fetch(`${DOGECHAIN_EXPLORER_API_BASE}?module=transaction&action=gettxreceiptstatus&txhash=${txHash}`);
478
+ if (!response.ok) throw new Error(`API request failed with status ${response.status}`);
479
  const data = await response.json();
480
  if (data.status === "1" && data.result && data.result.status === "1") {
481
  return '<span class="text-green-400">Success</span>';
 
490
  }
491
  }
492
 
493
+
494
+ // --- UNIFIED WALLET CONNECTION LOGIC ---
495
+ connectWalletBtn.addEventListener('click', () => {
496
+ walletChoiceModal.classList.remove('hidden');
497
+ });
498
+
499
+ walletChoiceCancelBtn.addEventListener('click', () => {
500
+ walletChoiceModal.classList.add('hidden');
501
+ });
502
+ walletChoiceModalCloseBtn.addEventListener('click', () => {
503
+ walletChoiceModal.classList.add('hidden');
504
+ });
505
+
506
+ connectMyDogeBtn.addEventListener('click', () => handleWalletConnectionAttempt('mydoge'));
507
+ connectMetaMaskBtn.addEventListener('click', () => handleWalletConnectionAttempt('metamask'));
508
+
509
+ disconnectWalletBtn.addEventListener('click', () => {
510
+ handleDisconnect();
511
+ });
512
+
513
+ async function handleWalletConnectionAttempt(walletTypeToConnect) {
514
+ currentWalletType = walletTypeToConnect; // Store the type for re-connection attempts
515
+ let walletProviderInstance;
516
+ let walletDisplayName;
517
+
518
+ if (walletTypeToConnect === 'mydoge') {
519
+ if (!window.myDogeEthereum) { // MyDoge specific provider check
520
+ showMessage("MyDoge Wallet extension not found. Please install it.", 'error');
521
+ return;
522
+ }
523
+ walletProviderInstance = window.myDogeEthereum;
524
+ walletDisplayName = "MyDoge Wallet";
525
+ } else { // 'metamask' or other EIP-1193 standard wallets
526
+ if (!window.ethereum) {
527
+ showMessage("MetaMask or a compatible EIP-1193 wallet not found.", 'error');
528
+ return;
529
+ }
530
+ walletProviderInstance = window.ethereum;
531
+ // Determine name more specifically if possible
532
+ if (window.ethereum.isMetaMask) walletDisplayName = "MetaMask";
533
+ else if (window.ethereum.isMyDoge) { // Should not happen if MyDoge button was clicked, but good fallback
534
+ walletDisplayName = "MyDoge Wallet (via window.ethereum)";
535
+ }
536
+ else walletDisplayName = "EIP-1193 Wallet";
537
  }
538
+
539
+ walletChoiceModal.classList.add('hidden');
540
+ showLoadingSpinner(connectWalletBtn, true, "Connect Wallet");
541
+
542
  try {
543
+ provider = new ethers.BrowserProvider(walletProviderInstance, 'any');
544
+
545
+ // Request accounts - this triggers the wallet prompt
546
+ const accounts = await provider.send("eth_requestAccounts", []);
547
+ if (!accounts || accounts.length === 0) {
548
+ throw new Error("No accounts selected or connection rejected by user.");
549
+ }
550
+
551
+ signer = await provider.getSigner(); // Get signer for the selected account
552
  currentAccount = await signer.getAddress();
553
+ currentNetwork = await provider.getNetwork();
 
554
 
555
+ updateWalletUI(currentAccount, currentNetwork, walletDisplayName);
556
+ setupWalletListeners(walletProviderInstance); // Pass the specific provider instance
557
+ showMessage(`${walletDisplayName} connected successfully!`, 'success');
 
 
558
 
559
+ // Recommend switching if not on Dogechain Mainnet (adjust as needed for testnet focus)
560
+ if (currentNetwork.chainId !== DOGECHAIN_MAINNET_CHAIN_ID) {
561
+ // Could add logic here to prompt for switch to DOGECHAIN_TESTNET_CHAIN_ID if this dApp is for testnet
562
+ showMessage(`Warning: You are currently on ${currentNetwork.name}. This DApp is primarily tested on Dogechain Mainnet (ID: ${DOGECHAIN_MAINNET_CHAIN_ID}).`, 'error', 10000);
563
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
564
 
565
  } catch (error) {
566
+ console.error(`Error connecting ${walletDisplayName}:`, error);
567
+ showMessage(`Connection failed: ${error.message || 'User rejected the request.'}`, 'error');
568
+ handleDisconnect(); // Ensure UI resets
569
+ } finally {
570
+ showLoadingSpinner(connectWalletBtn, false, "Connect Wallet");
571
+ }
572
+ }
573
+
574
+ function setupWalletListeners(activeProvider) {
575
+ if (activeProvider && typeof activeProvider.on === 'function' && typeof activeProvider.removeListener === 'function') {
576
+ // Clear previous listeners from this specific provider to avoid duplicates
577
+ activeProvider.removeListener('accountsChanged', handleAccountsChanged);
578
+ activeProvider.removeListener('chainChanged', handleChainChanged);
579
+
580
+ activeProvider.on('accountsChanged', handleAccountsChanged);
581
+ activeProvider.on('chainChanged', handleChainChanged);
582
+ }
583
+ }
584
+
585
+ async function handleAccountsChanged(accounts) {
586
+ if (accounts.length === 0) {
587
+ showMessage("Wallet disconnected or locked.", "info");
588
+ handleDisconnect();
589
+ } else if (accounts[0].toLowerCase() !== currentAccount?.toLowerCase()) {
590
+ showMessage(`Account switched in ${currentWalletType === 'mydoge' ? 'MyDoge Wallet' : 'wallet'}. Re-initializing...`, "info");
591
+ // Attempt to re-establish connection state with the new account using the stored wallet type
592
+ if (currentWalletType) {
593
+ await handleWalletConnectionAttempt(currentWalletType);
594
+ } else { // Should not happen if currentWalletType is set on connect
595
+ handleDisconnect();
596
+ }
597
  }
598
  }
599
+
600
+ function handleChainChanged(_chainId) {
601
+ showMessage(`Network changed in wallet. Reloading DApp to reflect new network state...`, "info");
602
+ setTimeout(() => window.location.reload(), 1500);
603
+ }
604
+
605
+ function handleDisconnect() {
606
+ // Remove listeners from the specific provider if it's known and supports removeListener
607
+ let activeProvider = null;
608
+ if (currentWalletType === 'mydoge' && window.myDogeEthereum) activeProvider = window.myDogeEthereum;
609
+ else if (window.ethereum) activeProvider = window.ethereum;
610
+
611
+ if (activeProvider && typeof activeProvider.removeListener === 'function') {
612
+ activeProvider.removeListener('accountsChanged', handleAccountsChanged);
613
+ activeProvider.removeListener('chainChanged', handleChainChanged);
614
+ }
615
 
 
616
  provider = null;
617
  signer = null;
618
  currentAccount = null;
619
  currentNetwork = null;
620
+ currentWalletType = null; // Reset wallet type
621
+
622
  walletInfoDiv.classList.add('hidden');
623
  connectWalletBtn.textContent = 'Connect Wallet';
624
  connectWalletBtn.disabled = false;
625
+ connectWalletBtn.classList.remove('hidden');
626
+ disconnectWalletBtn.classList.add('hidden');
627
+
628
+ if (walletStatusSpan) walletStatusSpan.textContent = 'Not Connected';
629
+ if (walletStatusSpan) walletStatusSpan.className = 'text-red-400';
630
+ if (accountBalanceSpan) accountBalanceSpan.textContent = '0.00';
631
+ if (connectedWalletNameSpan) connectedWalletNameSpan.textContent = 'N/A';
632
+
633
+ if (transferPollInterval) clearInterval(transferPollInterval);
634
+ isLiveUpdatesEnabled = false;
635
+ if (toggleLiveUpdatesBtn) {
636
+ toggleLiveUpdatesBtn.textContent = "Enable Live Updates";
637
+ toggleLiveUpdatesBtn.classList.remove('btn-danger');
638
+ }
639
  showMessage("Wallet disconnected.", "info");
640
  }
641
 
642
+ async function updateWalletUI(account, network, walletName) {
643
+ if (!account || !network || !provider) {
644
+ handleDisconnect(); return;
645
+ }
646
+ connectedWalletNameSpan.textContent = walletName;
647
  connectedAccountSpan.textContent = account;
648
+ connectedNetworkSpan.textContent = `${network.name} (ID: ${network.chainId.toString()})`;
649
  walletStatusSpan.textContent = 'Connected';
650
  walletStatusSpan.className = 'text-green-400';
651
  walletInfoDiv.classList.remove('hidden');
652
+ connectWalletBtn.classList.add('hidden');
653
+ disconnectWalletBtn.classList.remove('hidden');
654
 
655
  try {
656
+ const balanceWei = await provider.getBalance(account);
657
+ accountBalanceSpan.textContent = parseFloat(ethers.formatEther(balanceWei)).toFixed(4);
658
  } catch (error) {
659
  console.error("Error fetching balance:", error);
660
  accountBalanceSpan.textContent = "Error";
661
  }
662
  }
 
 
663
 
664
  // --- Tab Management ---
665
  tabButtons.forEach(button => {
666
  button.addEventListener('click', () => {
667
+ const activeTab = button.dataset.tab;
668
  tabButtons.forEach(btn => btn.classList.remove('active'));
669
  tabContents.forEach(content => content.classList.remove('active'));
670
+
671
  button.classList.add('active');
672
+ getEl(activeTab).classList.add('active');
673
+
674
+ if (activeTab === 'drc20Inspector' && tokenDistributionChartInstance) {
675
+ setTimeout(() => tokenDistributionChartInstance.resize(), 0);
676
+ }
677
  });
678
  });
679
 
680
  // --- TXID Tools Module ---
681
  generateTxidBtn.addEventListener('click', () => {
682
+ const randomBytes = ethers.randomBytes(32);
683
+ const txid = ethers.hexlify(randomBytes);
684
  generatedTxidInput.value = txid;
685
+ txidToSignInput.value = txid;
686
+ messageToVerifyInput.value = txid;
687
+ showMessage('TXID generated and auto-filled.', 'success');
688
  });
689
 
690
  signTxidBtn.addEventListener('click', async () => {
691
+ if (!signer) { showMessage('Connect wallet first.', 'error'); return; }
 
 
 
692
  const message = txidToSignInput.value;
693
+ if (!message || !ethers.isHexString(message, 32)) {
694
+ showMessage('Enter a valid 64-character 0x-prefixed TXID.', 'error'); return;
 
695
  }
696
+ const originalText = signTxidBtn.textContent;
697
+ showLoadingSpinner(signTxidBtn, true, originalText);
698
  try {
699
+ const signature = await signer.signMessage(ethers.getBytes(message)); // Ethers v6 signs bytes
 
700
  txidSignatureTextarea.value = signature;
 
 
701
  signatureToVerifyTextarea.value = signature;
702
+ showMessage('Message signed!', 'success');
703
+ saveTxidToHistory(message, signature, currentAccount);
704
  } catch (error) {
705
+ console.error("Sign error:", error);
706
+ showMessage(`Sign error: ${error.message}`, 'error');
707
  } finally {
708
+ showLoadingSpinner(signTxidBtn, false, originalText);
709
  }
710
  });
711
 
712
  verifySignatureBtn.addEventListener('click', () => {
713
  const message = messageToVerifyInput.value;
714
  const signature = signatureToVerifyTextarea.value;
715
+ if (!message || !signature) { showMessage('Message and signature required.', 'error'); return; }
716
+ if (!ethers.isHexString(message, 32)) { showMessage('Original message (TXID) must be 0x-prefixed 64-char hex.', 'error'); return; }
717
+ if (!ethers.isHexString(signature)) { showMessage('Signature must be 0x-prefixed hex.', 'error'); return; }
718
+
719
  try {
720
+ const recovered = ethers.verifyMessage(ethers.getBytes(message), signature);
721
  recoveredAddressSpan.textContent = recovered;
722
+ verificationStatusP.className = 'mt-1 text-sm';
723
  if (currentAccount && recovered.toLowerCase() === currentAccount.toLowerCase()) {
724
+ verificationStatusP.textContent = 'OK! Signature matches connected wallet.';
725
+ verificationStatusP.classList.add('text-green-400');
726
  } else if (currentAccount) {
727
+ verificationStatusP.textContent = 'Valid signature, but not from connected wallet.';
728
+ verificationStatusP.classList.add('text-yellow-400');
729
  } else {
730
+ verificationStatusP.textContent = 'Valid signature.';
731
+ verificationStatusP.classList.add('text-green-400');
732
  }
733
  } catch (error) {
734
+ console.error("Verify error:", error);
735
  recoveredAddressSpan.textContent = 'Error';
736
  verificationStatusP.textContent = `Verification failed: ${error.message}`;
737
  verificationStatusP.className = 'mt-1 text-sm text-red-400';
738
  }
739
  });
740
+
741
  function saveTxidToHistory(message, signature, verifiedSigner = null) {
742
  let history = JSON.parse(localStorage.getItem(TXID_HISTORY_KEY)) || [];
743
+ const isTxHash = ethers.isHexString(message, 32);
744
  const newEntry = {
745
+ message, signature, verifiedSigner,
 
746
  timestamp: new Date().toISOString(),
747
+ dogechainTxStatus: isTxHash ? 'Checking...' : 'N/A (Not TX Hash)'
 
748
  };
749
+ history.unshift(newEntry);
750
+ if (history.length > 50) history.pop();
751
  localStorage.setItem(TXID_HISTORY_KEY, JSON.stringify(history));
752
  renderTxidHistory();
753
  }
754
 
755
  async function renderTxidHistory() {
756
+ // ... (implementation is the same as previous full Vanilla JS version, check statusCell logic)
757
  txidHistoryTableBody.innerHTML = '';
758
  let history = JSON.parse(localStorage.getItem(TXID_HISTORY_KEY)) || [];
759
  if (history.length === 0) {
 
766
  <td class="word-break-all text-xs">${item.message}</td>
767
  <td class="word-break-all text-xs">${item.signature}</td>
768
  <td class="text-xs">${new Date(item.timestamp).toLocaleString()}</td>
769
+ <td class="word-break-all text-xs">${item.verifiedSigner || 'N/A'}</td>
770
  <td class="text-xs status-cell" data-txhash="${item.message}">${item.dogechainTxStatus || 'N/A'}</td>
771
  `;
772
+ if (item.dogechainTxStatus === 'Checking...' && ethers.isHexString(item.message, 32)) {
 
773
  const statusCell = row.querySelector('.status-cell');
774
  checkDogechainTxStatus(item.message).then(statusHtml => {
775
+ if (statusCell) statusCell.innerHTML = statusHtml;
776
+ const idx = history.findIndex(h => h.timestamp === item.timestamp && h.message === item.message);
777
+ if(idx !== -1) {
778
+ history[idx].dogechainTxStatus = statusHtml.replace(/<[^>]*>?/gm, '');
779
+ localStorage.setItem(TXID_HISTORY_KEY, JSON.stringify(history));
780
+ }
781
  });
782
  }
783
  }
784
  }
785
  clearHistoryBtn.addEventListener('click', () => {
786
+ if (confirm('Clear all TXID history?')) {
787
  localStorage.removeItem(TXID_HISTORY_KEY);
788
  renderTxidHistory();
789
  showMessage('TXID history cleared.', 'success');
 
792
 
793
  // --- DRC-20 Inspector Module ---
794
  fetchTokenDataBtn.addEventListener('click', async () => {
795
+ const tokenAddr = drc20TokenAddressInput.value.trim();
796
+ if (!ethers.isAddress(tokenAddr)) { showMessage("Invalid DRC-20 Address.", "error"); return; }
797
+ activeTokenAddress = tokenAddr;
798
+ showMessage(`Fetching data for ${activeTokenAddress.substring(0,10)}...`, "info", 3000);
 
 
799
 
 
800
  drc20MetadataSection.classList.add('hidden');
801
  drc20HoldersSection.classList.add('hidden');
802
  drc20ChartSection.classList.add('hidden');
803
  drc20TransfersSection.classList.add('hidden');
804
+ tokenHoldersTableBody.innerHTML = '<tr><td colspan="3" class="text-center py-3 text-gray-400"><span class="spinner"></span> Loading holders...</td></tr>';
805
+ tokenTransfersTableBody.innerHTML = '<tr><td colspan="5" class="text-center py-3 text-gray-400"><span class="spinner"></span> Loading transfers...</td></tr>';
806
  if (tokenDistributionChartInstance) tokenDistributionChartInstance.destroy();
807
 
808
  await fetchTokenMetadata(activeTokenAddress);
809
+ if (!drc20MetadataSection.classList.contains('hidden') && tokenMetaDecimalsSpan.textContent !== 'Error' && tokenMetaDecimalsSpan.textContent !== 'N/A') {
810
+ await fetchTokenHolders(activeTokenAddress, 1);
811
+ await fetchTokenTransfers(activeTokenAddress);
812
+ } else {
813
+ showMessage("Cannot fetch holders/transfers without token metadata.", "error");
814
+ }
815
  });
816
 
817
  whaleFilterCheckbox.addEventListener('change', () => {
818
+ if (activeTokenAddress && !drc20MetadataSection.classList.contains('hidden') && tokenMetaDecimalsSpan.textContent !== 'Error' && tokenMetaDecimalsSpan.textContent !== 'N/A') {
819
+ fetchTokenHolders(activeTokenAddress, 1);
820
+ }
821
+ });
822
+
823
+ toggleLiveUpdatesBtn.addEventListener('click', () => {
824
+ isLiveUpdatesEnabled = !isLiveUpdatesEnabled;
825
+ toggleLiveUpdatesBtn.textContent = isLiveUpdatesEnabled ? "Disable Live Updates" : "Enable Live Updates";
826
+ toggleLiveUpdatesBtn.classList.toggle('btn-danger', isLiveUpdatesEnabled);
827
+ if (isLiveUpdatesEnabled && activeTokenAddress && !drc20MetadataSection.classList.contains('hidden') && tokenMetaDecimalsSpan.textContent !== 'Error' && tokenMetaDecimalsSpan.textContent !== 'N/A') {
828
+ fetchTokenTransfers(activeTokenAddress);
829
+ showMessage("Live transfer updates enabled.", "success");
830
+ } else {
831
+ if (transferPollInterval) clearInterval(transferPollInterval);
832
+ showMessage("Live transfer updates disabled.", "info");
833
+ if (!activeTokenAddress || drc20MetadataSection.classList.contains('hidden') || tokenMetaDecimalsSpan.textContent === 'Error' || tokenMetaDecimalsSpan.textContent === 'N/A') {
834
+ showMessage("Cannot enable live updates without a valid token and its metadata.", "error");
835
+ isLiveUpdatesEnabled = false;
836
+ toggleLiveUpdatesBtn.textContent = "Enable Live Updates";
837
+ toggleLiveUpdatesBtn.classList.remove('btn-danger');
838
+ }
839
+ }
840
  });
841
 
842
  async function fetchTokenMetadata(tokenAddress) {
843
+ // ... (implementation is the same, using ethers.Contract with provider)
844
+ if (!provider) {
845
+ showMessage("Connect wallet for provider.", "error");
846
+ tokenMetaNameSpan.textContent = "Error"; tokenMetaSymbolSpan.textContent = "Error";
847
+ tokenMetaDecimalsSpan.textContent = "Error"; tokenMetaTotalSupplySpan.textContent = "Error";
848
+ drc20MetadataSection.classList.remove('hidden'); return;
849
+ }
850
+ const erc20Abi = ["function name() view returns (string)", "function symbol() view returns (string)", "function decimals() view returns (uint8)", "function totalSupply() view returns (uint256)"];
851
+ const originalButtonText = fetchTokenDataBtn.textContent;
852
+ showLoadingSpinner(fetchTokenDataBtn, true, originalButtonText);
853
  try {
854
+ const tokenContract = new ethers.Contract(tokenAddress, erc20Abi, provider);
855
+ const [name, symbol, decimalsResponse, totalSupplyResponse] = await Promise.all([
856
+ tokenContract.name(), tokenContract.symbol(), tokenContract.decimals(), tokenContract.totalSupply()
 
 
 
 
 
 
 
 
 
857
  ]);
858
+ const decimals = Number(decimalsResponse); // decimals() in ERC20 usually returns uint8
859
  tokenMetaNameSpan.textContent = name;
860
  tokenMetaSymbolSpan.textContent = symbol;
861
  tokenMetaDecimalsSpan.textContent = decimals.toString();
862
+ tokenMetaTotalSupplySpan.textContent = ethers.formatUnits(totalSupplyResponse, decimals);
863
  drc20MetadataSection.classList.remove('hidden');
864
+ showMessage("Token metadata fetched.", "success", 3000);
865
  } catch (error) {
866
+ console.error("Fetch metadata error:", error);
867
+ showMessage("Failed to fetch metadata. Valid DRC-20?", "error");
868
+ tokenMetaNameSpan.textContent = "Error"; tokenMetaSymbolSpan.textContent = "Error";
869
+ tokenMetaDecimalsSpan.textContent = "Error"; tokenMetaTotalSupplySpan.textContent = "Error";
870
+ drc20MetadataSection.classList.remove('hidden');
871
+ } finally {
872
+ showLoadingSpinner(fetchTokenDataBtn, false, originalButtonText);
873
  }
874
  }
875
 
876
  async function fetchTokenHolders(tokenAddress, page, offset = 10) {
877
+ // ... (implementation is the same, verify ethers.parseUnits and ethers.formatUnits)
878
  currentHoldersPage = page;
879
  const isWhaleFilterActive = whaleFilterCheckbox.checked;
880
+ tokenHoldersTableBody.innerHTML = '<tr><td colspan="3" class="text-center py-3 text-gray-400"><span class="spinner"></span> Loading...</td></tr>';
881
  try {
882
+ const response = await fetch(`${DOGECHAIN_EXPLORER_API_BASE}?module=account&action=tokentx&contractaddress=${tokenAddress}&page=1&offset=1000&sort=desc`);
883
+ if (!response.ok) throw new Error(`API error: ${response.status}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
884
  const data = await response.json();
885
 
886
+ if (data.status === "1" && Array.isArray(data.result)) {
887
+ let holders = new Map();
888
+ const decimalsText = tokenMetaDecimalsSpan.textContent;
889
+ if (decimalsText === 'Error' || decimalsText === 'N/A' || isNaN(parseInt(decimalsText))) {
890
+ throw new Error("Token decimals not available for balance calculation.");
891
+ }
892
+ const decimals = parseInt(decimalsText);
893
 
 
 
894
  data.result.forEach(tx => {
895
+ const valueInSmallestUnit = ethers.toBigInt(tx.value);
896
+ if (tx.to && ethers.isAddress(tx.to)) {
897
+ const toLower = tx.to.toLowerCase();
898
+ holders.set(toLower, (holders.get(toLower) || 0n) + valueInSmallestUnit);
 
899
  }
900
  });
901
 
902
+ let aggregatedHolders = Array.from(holders.entries())
903
+ .map(([address, balanceSmallestUnit]) => ({ address, balanceSmallestUnit }))
904
+ .filter(h => h.balanceSmallestUnit > 0n);
905
 
906
  if (isWhaleFilterActive) {
907
+ const whaleThreshold = ethers.parseUnits("10000", decimals);
908
+ aggregatedHolders = aggregatedHolders.filter(h => h.balanceSmallestUnit >= whaleThreshold);
909
  }
910
 
911
+ aggregatedHolders.sort((a, b) => { // BigInt safe sort
912
+ if (a.balanceSmallestUnit < b.balanceSmallestUnit) return 1;
913
+ if (a.balanceSmallestUnit > b.balanceSmallestUnit) return -1;
914
+ return 0;
915
+ });
916
 
 
917
  const paginatedHolders = aggregatedHolders.slice((page - 1) * offset, page * offset);
 
 
918
  tokenHoldersTableBody.innerHTML = '';
919
  if (paginatedHolders.length === 0) {
920
+ tokenHoldersTableBody.innerHTML = '<tr><td colspan="3" class="text-center text-gray-400">No holders found.</td></tr>';
921
  } else {
922
+ const totalSupplyStr = tokenMetaTotalSupplySpan.textContent.replace(/,/g, '');
923
+ let totalSupplySmallestUnit;
924
+ try { totalSupplySmallestUnit = ethers.parseUnits(totalSupplyStr, decimals); }
925
+ catch { totalSupplySmallestUnit = 0n; }
926
+
927
  paginatedHolders.forEach(holder => {
928
+ const balanceFormatted = ethers.formatUnits(holder.balanceSmallestUnit, decimals);
929
+ const percentage = totalSupplySmallestUnit > 0n ? (Number(holder.balanceSmallestUnit * 10000n / totalSupplySmallestUnit) / 100).toFixed(4) : "0.0000";
930
  const row = tokenHoldersTableBody.insertRow();
931
+ row.innerHTML = `<td class="word-break-all text-xs">${holder.address}</td><td class="text-xs">${parseFloat(balanceFormatted).toFixed(4)}</td><td class="text-xs">${percentage}%</td>`;
 
 
 
 
932
  });
933
  }
934
  drc20HoldersSection.classList.remove('hidden');
935
  renderHoldersPagination(page, aggregatedHolders.length, offset);
 
 
936
  renderTokenDistributionChart(aggregatedHolders.slice(0,10), decimals);
 
 
937
  } else {
938
+ showMessage("Could not fetch holders: " + (data.message || "API issue"), "error");
939
+ tokenHoldersTableBody.innerHTML = '<tr><td colspan="3" class="text-center text-gray-400">Error fetching.</td></tr>';
940
  }
941
  } catch (error) {
942
+ console.error("Fetch holders error:", error);
943
+ showMessage("Fetch holders error: " + error.message, "error");
944
+ tokenHoldersTableBody.innerHTML = '<tr><td colspan="3" class="text-center text-gray-400">Error fetching.</td></tr>';
945
  }
946
  }
947
 
948
  function renderHoldersPagination(currentPage, totalItems, itemsPerPage) {
949
+ // ... (implementation is the same)
950
  holdersPaginationControlsDiv.innerHTML = '';
951
  const totalPages = Math.ceil(totalItems / itemsPerPage);
952
  if (totalPages <= 1) return;
953
+ const createButton = (text, pageNum, isDisabled) => {
954
+ const button = document.createElement('button');
955
+ button.textContent = text;
956
+ button.className = 'btn-secondary text-xs mx-1 disabled:opacity-50';
957
+ button.disabled = isDisabled;
958
+ button.addEventListener('click', () => fetchTokenHolders(activeTokenAddress, pageNum));
959
+ return button;
960
+ };
961
+ holdersPaginationControlsDiv.appendChild(createButton('Previous', currentPage - 1, currentPage === 1));
962
+ const pageInfo = document.createElement('span'); pageInfo.textContent = ` Page ${currentPage} of ${totalPages} `; pageInfo.className = 'text-xs align-middle';
 
963
  holdersPaginationControlsDiv.appendChild(pageInfo);
964
+ holdersPaginationControlsDiv.appendChild(createButton('Next', currentPage + 1, currentPage === totalPages));
 
 
 
 
 
 
965
  }
966
 
967
+ function renderTokenDistributionChart(topHolders, decimals) {
968
+ // ... (implementation is the same)
969
+ if (tokenDistributionChartInstance) tokenDistributionChartInstance.destroy();
970
+ if (!topHolders || topHolders.length === 0) { drc20ChartSection.classList.add('hidden'); return; }
 
 
 
 
 
971
  const labels = topHolders.map(h => `${h.address.substring(0,6)}...${h.address.substring(h.address.length - 4)}`);
972
+ const data = topHolders.map(h => parseFloat(ethers.formatUnits(h.balanceSmallestUnit, decimals)));
 
973
  const chartData = {
974
  labels: labels,
975
+ datasets: [{ label: 'Token Distribution', data: data, backgroundColor: ['#FF6384','#36A2EB','#FFCE56','#4BC0C0','#9966FF','#FF9F40','#C9CBCF','#7BC225','#F263A2','#A136EB'], hoverOffset: 4, borderColor: '#374151', borderWidth: 1 }]
 
 
 
 
 
 
 
 
976
  };
977
+ tokenDistributionChartInstance = new Chart(tokenDistributionChartCanvas, { type: 'pie', data: chartData, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'top', labels: { color: '#f3f4f6' } } } } });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
978
  drc20ChartSection.classList.remove('hidden');
979
  }
980
+
 
981
  async function fetchTokenTransfers(tokenAddress, limit = 20) {
982
+ // ... (implementation is the same, verify ethers.formatUnits)
983
+ if (transferPollInterval) clearInterval(transferPollInterval);
984
  const loadTransfers = async () => {
985
  try {
986
+ const response = await fetch(`${DOGECHAIN_EXPLORER_API_BASE}?module=account&action=tokentx&contractaddress=${tokenAddress}&page=1&offset=${limit}&sort=desc`);
987
+ if (!response.ok) throw new Error(`API error: ${response.status}`);
988
  const data = await response.json();
989
+ if (data.status === "1" && Array.isArray(data.result)) {
990
  tokenTransfersTableBody.innerHTML = '';
991
+ const decimalsText = tokenMetaDecimalsSpan.textContent;
992
+ if (decimalsText === 'Error' || decimalsText === 'N/A' || isNaN(parseInt(decimalsText))) {
993
+ tokenTransfersTableBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400">Decimals not loaded.</td></tr>'; return;
994
+ }
995
+ const decimals = parseInt(decimalsText);
996
  data.result.forEach(tx => {
997
  const row = tokenTransfersTableBody.insertRow();
998
+ const amountFormatted = parseFloat(ethers.formatUnits(ethers.toBigInt(tx.value), decimals)).toFixed(4);
999
+ row.innerHTML = `<td class="word-break-all text-xs"><a href="https://explorer.dogechain.dog/tx/${tx.hash}" target="_blank" class="text-amber-300 hover:underline">${tx.hash.substring(0,10)}...</a></td><td class="word-break-all text-xs">${tx.from.substring(0,10)}...</td><td class="word-break-all text-xs">${tx.to.substring(0,10)}...</td><td class="text-xs">${amountFormatted}</td><td class="text-xs">${new Date(parseInt(tx.timeStamp) * 1000).toLocaleString()}</td>`;
 
 
 
 
 
1000
  });
1001
+ drc20TransfersSection.classList.remove('hidden');
1002
+ } else { tokenTransfersTableBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400">No transfers or API error.</td></tr>'; }
 
 
1003
  } catch (error) {
1004
+ console.error("Fetch transfers error:", error);
1005
+ tokenTransfersTableBody.innerHTML = '<tr><td colspan="5" class="text-center text-gray-400">Error fetching transfers.</td></tr>';
1006
+ if (isLiveUpdatesEnabled) { isLiveUpdatesEnabled = false; toggleLiveUpdatesBtn.textContent = "Enable Live Updates"; toggleLiveUpdatesBtn.classList.remove('btn-danger'); if (transferPollInterval) clearInterval(transferPollInterval); showMessage("Live updates stopped due to error.", "error"); }
1007
  }
1008
  };
1009
+ await loadTransfers();
1010
+ if (isLiveUpdatesEnabled) { transferPollInterval = setInterval(loadTransfers, 30000); }
 
1011
  }
1012
 
 
1013
  // --- Contract Interaction Module ---
 
1014
  loadContractBtn.addEventListener('click', () => {
1015
  const address = contractAddressInput.value.trim();
1016
  const abiString = contractAbiInput.value.trim();
1017
+ if (!ethers.isAddress(address)) { showMessage("Invalid Contract Address.", "error"); return; }
 
 
 
 
1018
  let abi;
1019
+ try { abi = JSON.parse(abiString); if (!Array.isArray(abi)) throw new Error("ABI must be JSON array."); }
1020
+ catch (error) { showMessage("Invalid ABI: " + error.message, "error"); return; }
1021
+ if (!provider) { showMessage("Connect wallet first (provider needed).", "error"); return; }
 
 
 
 
 
 
 
 
 
 
1022
 
1023
  currentContractInstance = new ethers.Contract(address, abi, signer || provider);
1024
  renderContractFunctions(abi);
1025
  contractFunctionsSection.classList.remove('hidden');
1026
  functionResultDisplay.classList.add('hidden');
1027
+ showMessage("Contract loaded.", "success");
1028
  });
1029
 
1030
  function renderContractFunctions(abi) {
1031
+ // ... (implementation is the same, just ensure event listener setup is correct)
1032
+ readFunctionsContainer.innerHTML = ''; writeFunctionsContainer.innerHTML = '';
 
1033
  abi.forEach(item => {
1034
  if (item.type === 'function') {
1035
+ const isRead = item.stateMutability === 'view' || item.stateMutability === 'pure';
1036
+ const container = isRead ? readFunctionsContainer : writeFunctionsContainer;
1037
+ const funcDiv = document.createElement('div'); funcDiv.className = 'p-3 bg-gray-700 rounded mb-3';
1038
+ let inputsHtml = item.inputs.map((input, index) => `<label for="${item.name}_${index}_${isRead ? 'r' : 'w'}" class="block text-xs mt-2 mb-1">${input.name||'input_'+index} (${input.type})</label><input type="${input.type.includes('uint')||input.type.includes('int')?'number':'text'}" id="${item.name}_${index}_${isRead ? 'r' : 'w'}" class="text-sm w-full" placeholder="${input.type}">`).join('');
1039
+ if (!isRead && item.payable) { inputsHtml += `<label for="${item.name}_value_${isRead ? 'r' : 'w'}" class="block text-xs mt-2 mb-1">Value (DOGE to send):</label><input type="number" id="${item.name}_value_${isRead ? 'r' : 'w'}" class="text-sm w-full" placeholder="0.0" step="any">`; }
1040
+ funcDiv.innerHTML = `<h5 class="font-semibold text-amber-300">${item.name}</h5>${inputsHtml}<button data-function="${item.name}" data-payable="${item.payable||false}" data-inputs='${JSON.stringify(item.inputs)}' data-readonly="${isRead}" class="btn-secondary text-sm mt-3 contract-call-btn">${isRead?'Query':'Execute'}</button>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1041
  container.appendChild(funcDiv);
1042
  }
1043
  });
1044
+ document.querySelectorAll('.contract-call-btn').forEach(button => button.addEventListener('click', handleContractCall));
 
 
 
1045
  }
1046
 
1047
  async function handleContractCall(event) {
1048
+ // ... (implementation is the same, verify ethers.parseEther and error parsing logic with Ethers v6)
 
 
 
1049
  const button = event.target;
1050
  const functionName = button.dataset.function;
1051
  const isPayable = button.dataset.payable === 'true';
1052
+ const isReadOnly = button.dataset.readonly === 'true';
1053
  const inputsMeta = JSON.parse(button.dataset.inputs);
1054
+
1055
+ if (!currentContractInstance) { showMessage("Contract not loaded.", "error"); return; }
1056
+ if (!isReadOnly && !signer) { showMessage("Wallet Signer required for write ops.", "error"); return; }
1057
+ if (isReadOnly && !provider) { showMessage("Provider not available.", "error"); return; }
1058
 
1059
  const args = [];
1060
+ try {
1061
+ for (let i = 0; i < inputsMeta.length; i++) {
1062
+ const inputElement = document.getElementById(`${functionName}_${i}_${isReadOnly ? 'r' : 'w'}`);
1063
+ let value = inputElement.value.trim();
1064
+ if (inputsMeta[i].type === 'bool') value = (value.toLowerCase()==='true'||value==='1');
1065
+ else if (inputsMeta[i].type.endsWith('[]')) { try { value = JSON.parse(value); if (!Array.isArray(value)) throw new Error("Not JSON array"); } catch (e) { value = value.split(',').map(s => s.trim()).filter(s => s !== ''); } if (inputsMeta[i].type.startsWith('uint')||inputsMeta[i].type.startsWith('int')) value = value.map(v => ethers.toBigInt(v)); }
1066
+ else if (inputsMeta[i].type.startsWith('uint')||inputsMeta[i].type.startsWith('int')) { if (value==='') throw new Error(`Input for ${inputsMeta[i].name} required for numeric types.`); value = ethers.toBigInt(value); }
1067
+ else if (inputsMeta[i].type === 'address' && !ethers.isAddress(value)) throw new Error(`Invalid address for ${inputsMeta[i].name}: ${value}`);
1068
+ args.push(value);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1069
  }
1070
+ } catch (error) { showMessage(`Input error for ${functionName}: ${error.message}`, "error"); return; }
 
1071
 
1072
+ let txOptions = {};
1073
+ if (isPayable) { const valueElement = document.getElementById(`${functionName}_value_${isReadOnly?'r':'w'}`); if (valueElement && valueElement.value) { try { txOptions.value = ethers.parseEther(valueElement.value); } catch (e) { showMessage("Invalid DOGE value.", "error"); return; } } }
 
 
 
 
 
 
 
 
 
1074
 
1075
+ functionResultDisplay.classList.remove('hidden'); functionResultOutput.textContent = 'Processing...';
1076
+ const originalButtonText = button.textContent; showLoadingSpinner(button, true, originalButtonText);
 
1077
 
1078
  try {
 
 
 
 
 
1079
  let result;
1080
+ if (isReadOnly) {
1081
+ result = await currentContractInstance[functionName](...args);
 
 
 
 
 
 
 
 
1082
  functionResultOutput.textContent = `Result: ${formatContractResult(result)}`;
1083
  showMessage("Query successful.", "success");
1084
+ } else {
 
 
 
 
1085
  const contractWithSigner = currentContractInstance.connect(signer);
1086
+ const txResponse = await contractWithSigner[functionName](...args, txOptions);
1087
+ functionResultOutput.textContent = `TX Sent! Hash: ${txResponse.hash}\nWaiting for confirmation...`;
1088
+ showMessage(`TX ${txResponse.hash} sent.`, "info", 10000);
1089
+ const receipt = await txResponse.wait();
1090
+ functionResultOutput.textContent = `TX Confirmed!\nHash: ${receipt.hash}\nBlock: ${receipt.blockNumber}\nStatus: ${receipt.status === 1 ? 'Success' : 'Failed'}`;
1091
+ showMessage(`TX ${receipt.hash} confirmed! Status: ${receipt.status === 1 ? 'Success' : 'Failed'}`, receipt.status === 1 ? "success" : "error");
1092
+ if (ethers.isHexString(receipt.hash, 32)) saveTxidToHistory(receipt.hash, "N/A (Contract TX)", currentAccount);
 
 
1093
  }
1094
  } catch (error) {
1095
+ console.error(`Call ${functionName} error:`, error);
1096
+ let displayError = error.shortMessage || error.message || (error.reason) || (error.data ? JSON.stringify(error.data) : 'Unknown contract call error.');
1097
+ if (error.revert && error.revert.args && error.revert.args.length > 0) displayError = `Reverted: ${error.revert.args.join(', ')}`;
1098
+ else if (error.data && typeof error.data === 'string' && error.data.startsWith('0x') && currentContractInstance) { try { const iface = currentContractInstance.interface; const decodedError = iface.parseError(error.data); if (decodedError) displayError = `Reverted: ${decodedError.name}(${decodedError.args.join(', ')})`; } catch(e) { /* ignore */ } }
1099
+ functionResultOutput.textContent = `Error: ${displayError}`;
1100
+ showMessage(`Error calling ${functionName}: ${displayError}`, "error", 10000);
1101
+ } finally { showLoadingSpinner(button, false, originalButtonText); }
1102
  }
1103
 
1104
  function formatContractResult(result) {
1105
+ // ... (implementation is the same)
1106
  if (result === null || result === undefined) return "null/undefined";
1107
+ if (typeof result === 'bigint') return result.toString();
1108
+ if (Array.isArray(result)) {
1109
+ let formattedArray = result.map(formatContractResult).join(', ');
1110
+ const namedProps = Object.keys(result).filter(key => isNaN(parseInt(key)));
1111
+ if(namedProps.length > 0 && namedProps.length === result.length) {
1112
+ let objString = "{ ";
1113
+ namedProps.forEach((key, index) => { objString += `${key}: ${formatContractResult(result[key])}`; if (index < namedProps.length -1) objString += ", "; });
1114
+ objString += " }"; return objString;
1115
+ }
1116
+ return `[${formattedArray}]`;
1117
  }
1118
+ if (typeof result === 'object' && result.constructor === Object) { try { return JSON.stringify(result, (key, value) => typeof value === 'bigint' ? value.toString() : value, 2); } catch (e) { return result.toString(); } }
1119
  return result.toString();
1120
  }
1121
 
1122
  // --- Initialization ---
1123
+ renderTxidHistory();
 
 
1124
  });
1125
  </script>
1126
+
1127
  </body>
1128
  </html>