1

I am trying to display the events that are emitted from a function in my smart contract to the front end of my dApp, and I feel like I am missing a step in the connection process with my dApp.

I've programmed it so the button handles the function on click, and that button should print the stringified JSON data to my console, but it's not. I'm also not getting any specified errors to my console either, so that makes me think the provider isn't properly connected.

Is there a step I am missing somewhere else, or am I just not properly connecting to a provider?

Here is my react code:

import { ethers } from "ethers";
// Importing the ABI
import CrowdGaming from "../artifacts/contracts/CrowdGaming.sol/CrowdGaming.json";

//Contract address
const contractAddress = "0x882978f7Afef5bc38c73461f4Bf096e5dF03Ef5C";

const provider = new ethers.providers.WebSocketProvider(
  `wss://eth-goerli.g.alchemy.com/v2/${process.env.REACT_APP_ALCHEMY_API}`
);

const contract = new ethers.Contract(
  contractAddress,
  CrowdGaming.abi,
  provider
);

// Launch Event
async function getLaunchEvents() {
  try {
    contract.on(
      "Launch",
      (id, owner, title, goal, description, startAt, endAt) => {
        let launchEvent = {
          id: id,
          owner: owner,
          title: title,
          goal: ethers.utils.formatEther(goal),
          description: description,
          startAt: startAt,
          endAt: endAt,
        };
        // Print to console
        console.log(JSON.stringify(launchEvent));
      }
    );
  } catch (err) {
    console.log(err);
  }
}

const AllCampaigns = () => {
  return (
    <div className="h-screen">
      <button onClick={getLaunchEvents}> Launch Events</button>
    </div>
  );
};

export default AllCampaigns;

And here is the event code within the contract:

event Launch(uint id, address indexed owner, string title, uint goal, string description, uint256 startAt, uint256 endAt);

The event is properly emitted on Goerli Etherscan so I know the contract is working as intended. If anyone has any guess or ideas, that would be awaesome!

1 Answer 1

0

If getLaunchEvents is a listener it should br working all the time and not once someone clicks on it. For that you should prepare a ws server with express and feed your frontend with that API. Who will perpetually listen to the event to display on console log since it occurs.

1
  • That makes senses. I was trying to display events but I meant to display the public mapping of the campaigns instead. I was confused about that and I ended up figuring out that I needed to call the getter functions from the public variables and got it to work
    – OhItsPM
    Mar 19 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.