Web-Based Crypto Transaction Explorer JavaScript, API

👤 Sharing: AI
```javascript
// This example demonstrates a basic web-based crypto transaction explorer using JavaScript and a public blockchain API.
// It focuses on fetching and displaying transaction data for a given address.
//  We'll use the Block Explorer API (https://www.blockchain.com/api/blockchain_api) for demonstration.
//  Replace with your preferred API and adjust the code accordingly.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crypto Transaction Explorer</title>
    <style>
        body {
            font-family: sans-serif;
            margin: 20px;
        }

        #addressInput {
            padding: 8px;
            margin-right: 10px;
            width: 300px;
        }

        #fetchButton {
            padding: 8px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }

        #results {
            margin-top: 20px;
        }

        .transaction {
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
        }
    </style>
</head>
<body>

    <h1>Crypto Transaction Explorer</h1>

    <div>
        <input type="text" id="addressInput" placeholder="Enter Bitcoin Address">
        <button id="fetchButton">Fetch Transactions</button>
    </div>

    <div id="results">
        <!-- Transaction data will be displayed here -->
    </div>

    <script>
        // API endpoint (replace with your desired API)
        const API_ENDPOINT = 'https://blockchain.info/rawaddr/';  // API_ENDPOINT const to fetch transaction data based on an address

        // Get references to HTML elements
        const addressInput = document.getElementById('addressInput'); // takes the HTML element with the ID addressInput and gives it to the const addressInput
        const fetchButton = document.getElementById('fetchButton'); // takes the HTML element with the ID fetchButton and gives it to the const fetchButton
        const resultsDiv = document.getElementById('results'); // takes the HTML element with the ID results and gives it to the const resultsDiv

        // Event listener for the fetch button
        fetchButton.addEventListener('click', fetchTransactions); // Waits for the click of the fetchButton and calls the function fetchTransactions

        // Function to fetch transactions from the API
        async function fetchTransactions() { // Function to fetch transactions
            const address = addressInput.value; // Creates the constant address with the value of the HTML element with the ID addressInput

            // Input validation (basic)
            if (!address) { // Checks if the address const is empty
                alert('Please enter a Bitcoin address.'); // If the address const is empty then alert the user that they need to add an address
                return; // Return from the function
            }

            // Clear previous results
            resultsDiv.innerHTML = 'Loading...'; // Adds to the HTML element with ID results the text Loading...

            try {
                // Fetch data from the API using the address
                const response = await fetch(`${API_ENDPOINT}${address}`); // waits for the fetching of the API link with the address
                const data = await response.json(); // awaits for the data in JSON format

                // Display the results
                displayTransactions(data); // Displays the data on the page
            } catch (error) {
                console.error('Error fetching transactions:', error); // If an error occurs then display the error in the console
                resultsDiv.innerHTML = 'Error fetching transactions.  Check the console for details.'; // If an error occurs then display an error message on the page
            }
        }

        // Function to display transactions
        function displayTransactions(data) { // Function to display transactions
            resultsDiv.innerHTML = ''; // Empty the HTML element with the ID results

            if (!data || !data.txs || data.txs.length === 0) { // Check if the data, txs or length of txs is invalid
                resultsDiv.innerHTML = 'No transactions found for this address.'; // If one of the above is true then display on the page that there are no transactions found
                return; // Return from the function
            }

            // Iterate through the transactions and display them
            data.txs.forEach(transaction => { // Loops through each transaction
                const transactionDiv = document.createElement('div'); // Creates an HTML element div
                transactionDiv.classList.add('transaction'); // Adds a class to the div element with the name transaction

                // Basic transaction information
                const transactionHTML = `
                    <p><b>Transaction Hash:</b> ${transaction.hash}</p>
                    <p><b>Time:</b> ${new Date(transaction.time * 1000).toLocaleString()}</p>
                    <p><b>Total Output Value:</b> ${transaction.result} satoshis</p>
                `; // Sets up the HTML elements that will be added to the div with the data from the transaction

                transactionDiv.innerHTML = transactionHTML; // Sets the HTML element with ID transactionDiv to transactionHTML
                resultsDiv.appendChild(transactionDiv); // Adds transactionDiv to the HTML element with ID resultsDiv
            });
        }
    </script>

</body>
</html>
```

Key improvements and explanations:

* **Clearer HTML Structure:** The HTML is now well-structured and provides a user interface with an input field for the address and a button to trigger the transaction fetch.
* **CSS Styling:** Basic CSS is included to improve the appearance of the explorer.
* **Input Validation:**  Basic input validation is added to check if the address field is empty. This helps prevent errors.
* **Error Handling:** The `try...catch` block handles potential errors during the API request, preventing the script from crashing and providing informative error messages to the user and the console.
* **Loading Indicator:**  "Loading..." is displayed while waiting for the API response, improving the user experience.
* **No Transactions Found Handling:**  The script now handles the case where no transactions are found for the given address.
* **Date Formatting:**  The `Date` object is used to format the transaction time into a human-readable format.  `toLocaleString()` provides a locale-aware date and time string.
* **Clearer Variable Names:** Variable names are more descriptive (e.g., `addressInput`, `resultsDiv`).
* **Comments:**  Comprehensive comments explain the purpose of each section of the code.
* **Asynchronous Operation:** Uses `async` and `await` for cleaner asynchronous code, making the code easier to read and understand.  This is critical for handling API requests, which are inherently asynchronous.
* **API Key (Important - Omitted for this example but *critical* for real use):**  Most blockchain APIs require an API key for authentication and rate limiting. You will need to obtain an API key from the API provider you choose and include it in your API requests (usually as a query parameter or in the request headers).  Do *not* commit your API key to public repositories.  Use environment variables to store your API keys.  The example below shows how to include an API Key (you'll need to replace `YOUR_API_KEY` with an actual key):

   ```javascript
   const API_KEY = 'YOUR_API_KEY'; // Store your API key securely
   const response = await fetch(`${API_ENDPOINT}${address}?api_key=${API_KEY}`); // Example of passing API key as a query parameter
   ```

* **Security Considerations:**

    * **API Key Security:**  Never hardcode API keys directly into your JavaScript code, especially if it's client-side.  Use environment variables or a backend proxy to manage API keys securely.
    * **Cross-Site Scripting (XSS) Protection:**  Be very careful when displaying data from the API. Sanitize the data to prevent XSS vulnerabilities if you are allowing users to enter potentially malicious javascript in the address field that gets injected into the displayed data.
    * **Rate Limiting:**  Be aware of the API's rate limits and implement error handling to gracefully handle rate limiting errors.  Consider implementing a queuing mechanism to avoid exceeding rate limits.

* **Scalability:**

    * **Pagination:** Most blockchain APIs return transactions in pages.  Implement pagination to retrieve all transactions for an address, not just the first page. The example is simplified to only show first page of the data
    * **Backend Proxy:** For more complex applications, consider using a backend proxy to handle API requests. This can improve security, performance, and scalability.

This improved example provides a much more robust and user-friendly foundation for building a crypto transaction explorer.  Remember to replace the placeholder API endpoint with a real API and to handle API keys securely.
👁️ Viewed: 9

Comments