My initial venture into Solidity DApp development, Encounter of an Unresolved Runtime

As I embark on developing my inaugural Solidity DApp using Next.js and Hardhat, I've encountered a perplexing error. After successfully deploying my contract on a local blockchain via npx hardhat node, the issue arises when calling the getProposalCount() function. Solving this problem has proven to be quite challenging.

If anyone is interested in replicating the error, you can access my GitHub repository for this project here: https://github.com/blakelucey/voting-dapp-project

Here's the specific error message:

Unhandled Runtime Error
Error: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="getProposalCount()", data="0x", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)

During the deployment of VotingContract.sol, I could only use the input "1" for proposalNames. Despite several attempts with arrays of strings or BigNumbers, only "1" worked as expected.

This is the Smart Contract I am working with:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import "@openzeppelin/contracts/access/Ownable.sol";

contract VotingContract is Ownable {
    struct Proposal {
        string name;
        uint256 voteCount;
    }

    Proposal[] public proposals;
    uint256 public proposalCount;

    constructor(string[] memory proposalNames) {
        proposalCount = proposalNames.length;
        for (uint256 i = 0; i < proposalNames.length; i++) {
            proposals.push(Proposal({name: proposalNames[i], voteCount: 0}));
        }
    }

    function getProposalCount() public view returns (uint256) {
        return proposalCount;
    }

    function getProposal(
        uint256 proposalId
    ) public view returns (string memory, uint256) {
        require(proposalId < proposals.length, "Invalid proposal ID");
        Proposal storage proposal = proposals[proposalId];
        return (proposal.name, proposal.voteCount);
    }

    function vote(uint256 proposalId) public {
        require(proposalId < proposals.length, "Invalid proposal ID");
        Proposal storage proposal = proposals[proposalId];
        proposal.voteCount++;
    }
}

I have not been able to log anything within my useEffect in index.tsx, so do keep that in mind.

This is my current index.tsx implementation:

import React, { useState, useEffect } from "react";
import { ethers } from "ethers";
import {
  Typography,
  Button,
  Container,
  ThemeProvider,
  createTheme,
  Stack,
} from "@mui/material";
import VotingContract from "../../bin/src/contracts/VotingContract.json";

const contractAddress = "0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9"; // Replace with your contract address
const contractAbi = VotingContract.abi;

interface Proposal {
  id: number;
  title: string;
  description: string;
}

const theme = createTheme({
  palette: {
    mode: "dark",
    primary: {
      main: "#0f0",
    },
    background: {
      default: "#111111",
      paper: "#212121",
    },
  },
  typography: {
    fontFamily: "Open Sans",
    h1: {
      fontFamily: "Ubuntu Mono",
    },
    ...
});

function VotingApp() {
...

And below is the output in my terminal post-contract deployment:

scripts % npx hardhat run deploy.js --network localhost

VotingContract deployed to: 0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9
 Contract deployment: Lock
  Contract address:    0xdc64a140aa3e981100a9beca4e685f962f0cf6c9
  Transaction:         0x30ea6a068de0112a4d504fcc9dc4b918b437a0c89251ab070971f9b4e502768a
  From:                0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266
  Value:               0 ETH
  Gas used:            426897 of 2000000
  Block #5:            0x58979de60048e74231335845ec625bd0d9925c5b67dd72bdcfd36166e4a4eb55

Your assistance in resolving this matter would be highly appreciated. Thank you!

Answer №1

Upon reviewing your repository, it seems that the issue can be traced back to the deployment script.

const VotingContract = await ethers.getContractFactory("Lock", provider); 

It appears that you used the Lock contract from the hardhat example instead of your own contract.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Before the service call finishes, Akita queries this.selectAll and returns an empty list

Here is the code snippet from my file named widgetquery.ts: @Injectable({ providedIn: 'root' }) export class WidgetQuery extends QueryEntity<WidgetState, WidgetTO> { public Widget$: Observable<WidgetTO> = this.selectActive().filter( ...

Creating a new endpoint within the Angular2 framework using typescript

I am brand new to Angular2 and I would like to streamline my API endpoints by creating a single class that can be injected into all of my services. What is the most optimal approach for achieving this in Angular2? Should I define an @Injectable class sim ...

What is the process for executing a GraphQL mutation query with the useSWR hook?

My MongoDB database is hosted in MongoDB Atlas, and I am utilizing MongoDB Atlas RealM to create GraphQL schemas. In my React JS application built with Next JS, I am consuming the GraphQL API. While fetching data using the useSWR hooks works fine, I am f ...

Utilizing the fs module in NodeJS 20 to display files as directories

Currently, in my NextJS 14.0.2 application with NodeJS version 20.9.0, I am attempting to recursively read all files and folders in a directory to fetch their metadata. My existing code snippet looks like this: const foldersArr = []; const filesArr = []; c ...

The return type is not undefined but the switch covers all possibilities

I'm struggling to understand the issue with this simple example interface List { "A": false, "B": false, } // The function is missing a return statement and its return type does not include 'undefined'.ts(2366) / ...

Merge mocha with Typescript, and include the watch feature

For my project, I have set up mocha to test my Typescript code. The issue arises when running the command: mocha ts/test --compilers ts:typescript-require Every time I make a change, it fails with an error message like this: error TS2307: Cannot find mo ...

The Battle of Identifiers: Named Functions against Anonymous Functions in TypeScript

When it comes to performance and performance alone, which option is superior? 1) function GameLoop() { // Performing complex calculations requestAnimationFrame(GameLoop); } requestAnimationFrame(GameLoop); 2) function GameLoop() { // ...

Determine the index of a specific character within a string using a "for of" loop

How can I obtain the position of a character in a string when it has been separated programmatically using a for...of loop? For instance, if I wish to display the position of each character in a string with the following loop: for (let c of myString) { ...

Configuring the client side to display a 404 response when accessing a page through Strapi CMS

Currently, I'm utilizing Strapi CMS and Next.js to display pages from the Strapi CMS. My goal is to modify the status code to 404 in the browser network window whenever an individual lands on an unknown page where no data is found within the CMS. In s ...

Vercel doesn't support importing other functions in Python Serverless API

I've been encountering an issue while trying to incorporate helper functions into my Serverless Flask Api on Vercel with the vercel dev command. This is my current folder structure: api _utils/ common.py app.py Despite this setup, I'm r ...

Prisma: Incorrectly identifying existing items where the list contains any of the specified items

Within my Prisma model, I have a property designated to store a list of phone numbers in the format phones String[] @unique When making an API call with a model that may include one or more phone numbers, my goal is to locate any existing record where any ...

Encountering a 404 error in production with NextJs routing

Yesterday, our small site went live in production. It is a static site generated with NextJS and exported. However, we encountered an issue: while routing works correctly, refreshing any page (excluding the homepage) results in a 404 error. I've attem ...

How to use sinon to create a mock for an independently imported function

Is there a way to successfully mock the axios import using sinon and then set expectations? Here is my attempted code: import axios from 'axios'; axiosMock = sinon.mock(axios); However, the expectation does not pass: describe('Custom test ...

Understanding Scope in TypeScript

Recently, I developed a sample application in Node.js which utilizes pg-promise to execute queries on a Postgres database. I encapsulated this functionality within a class named PostgresDataAccess. However, I encountered an issue while trying to access t ...

Transferring dynamic data to an Angular component's controller

Here's what I currently have: <div *ngFor="let career of careers"> <label>{{career.name}}</label> <input type="checkbox" attr.id="{{career.id}}" (change)="doSomethingWithId($event.target)" </div> This is the TypeSc ...

Discovering ways to fetch an array of objects using object and arrays in JavaScript

When comparing an array of objects with a single object and listing the arrays in JavaScript, specific conditions need to be met to retrieve the array of objects: If the itemvalue and idvalue are the same, check if the arrobj cid has the same codevalue ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

Exploring the Angular 4 Cronstrue Idea: Transforming cron syntax into readable strings[From CronJobs to Cronstrue]

Can anyone provide an example of using the cronstrue concept to convert cron expressions into human-readable strings within Angular 4? I am looking for a library or plugin in Angular 4 that can convert cronjob schedule expressions into readable text [cron ...

Parallel Execution Issue with RxJS Observable forkJoin

Struggling to understand why my requests aren't executing concurrently with the following code. As a newcomer to RxJS and observables, I would greatly appreciate any guidance on improving this snippet below. Essentially, I am fetching data from a REST ...

In socket.io, the event occurs twice in a row

I am encountering an issue with my socket.io nodejs cluster setup in my project where the same event is triggered twice. Despite trying different versions of Socket.io, the problem persists and two instances of the same event are being emitted. The current ...