Tippi Fifestarr
Tippi Fifestarr

Reputation: 21

Handling JavaScript Modules and Event Listeners in Astro for Blockchain Interaction

Challenge

I've been following Richard Gottleber's tutorial on creating a decentralized news service using Chainlink and ethers.js, deployed via the Astro framework. I finished the tutorial, reading from the contract I deployed, but now I'm trying to go one step further and adapt this slightly to fit my hackathon project. The next step is to do a write transaction, triggering the sendRequest function to fetch another news article. All attempts have failed, so I'm switching to Scaffold-Eth for a while.

Project Setup:

Goal: Expand on the tutorial by adding functionality to fetch more articles using a sendRequest function, which should trigger updates to displayed articles and then incorporate Chainlink's RNG for added randomness and D&D flavor.

Current Behavior: Data displays correctly initially as per the tutorial. However, attempts to add dynamic functionality (fetching more articles on button click) are not working.

Issues Encountered:

  1. JavaScript Module Management: Trouble with ethers.js not being recognized when using module syntax in HTML.
  2. Event Handling: Switched from onclick attributes in HTML to adding event listeners via JavaScript to ensure proper loading order and scope resolution.
  3. 404 Errors: When moving function definitions around (sendRequest from a separate module into newsArchive.js), faced issues with file not found errors.
  4. Security Concerns: Concerns about exposing sensitive environment variables when moving JavaScript to a public directory to resolve module path issues.

Error Messages:

Code Sample (simplified version highlighting problematic parts) full code:

<!DOCTYPE html>
<html lang="en">
<head>
    <script src="https://cdn.jsdelivr.net/npm/ethers/dist/ethers.min.js"></script>
</head>
<body>
    <nav>
        <button id="fetchButton">Fetch More, Chainlink</button>
    </nav>
    <script type="module">
        import { sendRequest } from '/newsArchive.js';
        document.addEventListener('DOMContentLoaded', function() {
            document.getElementById('fetchButton').addEventListener('click', async function() {
                console.log('Fetching more articles...');
                try {
                const newArticles = await sendRequest();
                console.log('New articles fetched:', newArticles);
                } catch (error) {
                console.log('error fetching new articles', error);
                }
            });
        });
    </script>
</body>
</html>

Questions:

  1. What is the correct way to manage JavaScript modules in an Astro project when they need to interact with Ethereum blockchain?
  2. How can I ensure that ethers.js is correctly loaded and accessible in functions defined in my own scripts?
  3. Are there best practices to prevent exposing sensitive environment variables when scripts are moved to public directories?

Any insights, particularly those familiar with Astro and blockchain development, would be greatly appreciated. I'm currently planning to just shift my code into Scaffold-ETH and continue that way.

Attempts to Fix:

  1. JavaScript Module Management

    • Moved Files: Initially, JavaScript files like newsArchive.js were located in the src/lib directory. To resolve module path issues, I tried moving these files to the public directory of the Astro project, expecting them to be more accessible to the client-side scripts.
    • Script Tag Modifications: Changed the <script> tag's type attribute from module to text/javascript and back, attempting to address the issues related to ES module imports not being recognized in the browser.
    • CDN Usage: As ethers.js was not being recognized when imported as a module, I switched to loading it via a CDN in the HTML head section. This was meant to ensure its availability globally within the project without import statements.
  2. Event Handling

    • Inline to Listener: Initially used onclick attributes within HTML tags for interaction handling. Moved to adding event listeners via JavaScript to ensure they are attached after the DOM is fully loaded and the necessary JavaScript is initialized. This was supposed to fix issues with functions not being recognized at runtime.
    • DOMContentLoaded: Wrapped event listeners in a DOMContentLoaded event to ensure that they are not initialized before the entire page is loaded, thereby preventing any timing issues.
  3. Error Handling and Debugging

    • Console Logs and Debugging: Added extensive console logs to track the flow and identify the point of failure, especially for the ethers.js functions and AJAX calls.
    • Network and Console Monitoring: Used browser developer tools to monitor network requests for script loading and to check the console for any immediate JavaScript errors.
  4. File Path and Import Issues

    • Path Adjustments: Made multiple adjustments to the paths used in import statements, trying both relative and absolute paths to see if it would resolve the 404 errors.
    • Script Relocation: Experimented with different locations for scripts within the HTML document to manage load order more effectively.
  5. Security Concerns

    • Environment Variables: Evaluated the impact of moving potentially sensitive scripts to the public directory. Ensured that no sensitive keys or tokens are included in client-side scripts to avoid exposure.

Continuing Issues:

Despite these efforts, I am still facing:

Upvotes: 1

Views: 367

Answers (1)

Buns Enchantress
Buns Enchantress

Reputation: 11

Assuming I understand correctly, you're having issues triggering sendRequest(), fetching articles, and ethers being defined, so I have the following feedback based off what I understand to be your issues.

Please feel free to clarify any issues I may have missed

  1. Ensure the environment variables for PROVIDER_URL and CONTRACT_ADDRESS are set correctly.

    • PROVIDER_URL="https://sepolia.drpc.org" is what I used for troubleshooting.
  2. Ensure the subscriptionId on the deployed consumer aligns with a subscription you created, which may be found here for the subscriptionId you have in contracts/functions.sol, which may be found here for subscriptionId #2456.

  3. Ensure you are connected to the wallet address that owns the deployed consumer.

  4. Make use of an error report within the console when an onclick request fails to act as anticipated and respond here with the output you see in your console.

Also, what does submitting ones preferences do in this case? I noticed the button for setting preferences, but unsure of the desired outcome and thus implementation.

Note: I was able to get the articles to show for the consumer I deployed, however I understand this does not resolve your issue, but should let you know you're moving in the right direction.

Shows Articles: https://github.com/BunsDev/ceptor-tech-warmup-functions/tree/help

Upvotes: 1

Related Questions