0

I am getting this error when i click the create a new issue I get this error in the log. here is the react code-

import React, { useState, useEffect } from "react";
import { ethers } from "ethers";
import BallotContract from "../ABI/Ballot.json"; // Import the Ballot contract ABI

const Ballots = () => {
  const [issueName, setIssueName] = useState("");
  const [issues, setIssues] = useState([]);
  const [isConnected, setIsConnected] = useState(false);

  const contractAddress = "0x9be868bad697c63C20E99Fe232DC10A6799C81Dc"; // Replace with the deployed contract address
  const provider = new ethers.BrowserProvider(window.ethereum);
  const signer = provider.getSigner();

  async function connectToContract() {
    await window.ethereum.request({ method: "eth_requestAccounts" });
  }

  const initializeEthers = async () => {
    // ethers connection for the smart contract
    const contract = new ethers.Contract(
      contractAddress,
      BallotContract.abi,
      provider.getSigner()
    );

    // Get the list of all issues
    const allIssues = await contract.getAllIssues();
    setIssues(allIssues);
    setIsConnected(true);
  };

  // Connects to the smart contract token id (check /contracts/contract-address.json)
  async function init() {
    try {
      await window.ethereum.enable();
      await initializeEthers();
    } catch (error) {
      console.error("Error connecting to contract:", error);
    }
  }

  useEffect(() => {
    // When the page loads, initialize the init function
    // to connect the frontend with the smart contract
    init();
  }, []);

  async function createNewIssue() {
    try {
      const contract = new ethers.Contract(
        contractAddress,
        BallotContract.abi,
        provider.getSigner()
      );

      await contract.createIssue(issueName, 24);
      setIssueName("");
      // After creating the issue, update the list of issues by fetching again from the contract
      const allIssues = await contract.getAllIssues();
      setIssues(allIssues);
    } catch (error) {
      console.error("Error creating issue:", error);
    }
  }

  return (
    <div>
      <h2>Ballot Interaction</h2>
      {typeof window.ethereum == "undefined" ? (
        <button onClick={connectToContract}>Connect to Contract</button>
      ) : (
        <div>
          <div>
            <h3>Create Issue</h3>
            <input
              type="text"
              value={issueName}
              onChange={(e) => setIssueName(e.target.value)}
              placeholder="Enter issue name"
            />
            <button onClick={createNewIssue}>Create Issue</button>
          </div>
          <div>
            <h3>Vote</h3>
            {/* Add code to select issue and vote */}
          </div>
          <div>
            <h3>Issues</h3>
            <ul>
              {issues.map((issue, index) => (
                <li key={index}>
                  {issue.name} - Yes Votes: {issue.yesVotes}, No Votes:{" "}
                  {issue.noVotes}
                </li>
              ))}
            </ul>
          </div>
        </div>
      )}
    </div>
  );
};

export default Ballots;


the contract-

pragma solidity ^0.8.4;

contract Ballot {
    struct IssueInfo {
        bytes32 name;
        uint votingDeadline;
    }

    struct VoterInfo {
        uint yesVotes;
        uint noVotes;
        mapping(address => bool) hasVoted;
        address[] voters;
    }

    IssueInfo[] private issueInfos;
    VoterInfo[] private voterInfos;

    function createIssue(bytes32 _name, uint _votingDurationHours) public returns (uint) {
        IssueInfo memory newIssue = IssueInfo({
            name: _name,
            votingDeadline: block.timestamp + (_votingDurationHours * 1 hours)
        });
        issueInfos.push(newIssue);
        voterInfos.push();
        return issueInfos.length - 1; // Return the index of the created issue
    }

    modifier votingOpen(uint issueIndex) {
        require(block.timestamp <= issueInfos[issueIndex].votingDeadline, "Voting is closed for this issue");
        _;
    }

    function castVote(uint issueIndex, bool isYesVote) public votingOpen(issueIndex) {
        require(issueIndex < issueInfos.length, "Invalid issue index");
        VoterInfo storage voterInfo = voterInfos[issueIndex];
        require(!voterInfo.hasVoted[msg.sender], "You have already voted for this issue");

        if (isYesVote) {
            voterInfo.yesVotes++;
        } else {
            voterInfo.noVotes++;
        }
        voterInfo.hasVoted[msg.sender] = true;
        voterInfo.voters.push(msg.sender); // Add the address to the list of voters for this issue
    }

    function getIssueVotes(uint issueIndex) public view returns (uint yesVotes, uint noVotes) {
        require(issueIndex < issueInfos.length, "Invalid issue index");
        VoterInfo storage voterInfo = voterInfos[issueIndex];
        return (voterInfo.yesVotes, voterInfo.noVotes);
    }

    function getVotersForIssue(uint issueIndex) public view returns (address[] memory) {
        require(issueIndex < issueInfos.length, "Invalid issue index");
        VoterInfo storage voterInfo = voterInfos[issueIndex];
        return voterInfo.voters;
    }

    function hasAddressVoted(uint issueIndex, address voter) public view returns (bool) {
        require(issueIndex < issueInfos.length, "Invalid issue index");
        VoterInfo storage voterInfo = voterInfos[issueIndex];
        return voterInfo.hasVoted[voter];
    }

    function determineWinner(uint issueIndex) public votingOpen(issueIndex) returns (string memory) {
        require(issueIndex < issueInfos.length, "Invalid issue index");
        IssueInfo storage issue = issueInfos[issueIndex];
        VoterInfo storage voterInfo = voterInfos[issueIndex];

        if (block.timestamp <= issue.votingDeadline) {
            return "Voting is still ongoing";
        } else {
            if (voterInfo.yesVotes > voterInfo.noVotes) {
                return "Yes wins";
            } else if (voterInfo.yesVotes < voterInfo.noVotes) {
                return "No wins";
            } else {
                return "It's a tie";
            }
        }
    }

    function getAllIssues() public view returns (bytes32[] memory) {
        bytes32[] memory allIssues = new bytes32[](issueInfos.length);
        for (uint i = 0; i < issueInfos.length; i++) {
            allIssues[i] = issueInfos[i].name;
        }
        return allIssues;
    }

}

1

1 Answer 1

0

The error message suggests that you are not correctly connecting the contract with the desired signer. Make sure you are correctly fetching the desired signer to call this contract.

Without the signer the contract can't specify the account or wallet that will be used to sign the transaction and pay for the gas fees when invoking the contract function.

Your Answer

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

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