0

I am builing a simple crud dapp . Where I am adding user name ,email , gender ,functionality to blockchain . This dapp has 4 function Create ,update ,delete ,getting Userlist . All the three functions add ,update,delete works fine ,struggling with userlist function to get data from the blockchain

This is my addUser.jsx


import "./addUser.css";


const addUser = ({state}) => {

    const adduser = async(event)=>{
        event.preventDefault();
        const {contract}=state;
        const name = document.querySelector("#name").value;
        const Email = document.querySelector("#email").value;
        const gen= document.querySelector("#gender").value;
        const nation= document.querySelector("#nationa").value;
        //const amount = document.querySelector("#amount").value;
        // const amount = {value:ethers.utils.parseEther("0.001")}
        const ADD = await contract.addUser(name,Email,gen,nation)
        await ADD.wait();
        alert("Adding is successul");
        window.location.reload();
    }

  return (
  <>
      <div className="center">
       <p>ADD USER </p>
        <form onSubmit={adduser} id="form">
          
              <div className="inputbox"> 
           <span>Name</span>
            <input type="text" required="required" id="name" />
           
          </div>
          <div className="inputbox">
             <span>Email</span>
            <input type="email" required="required" id="email" />
           
          </div>
          <div className="inputbox">
            <span>Gender</span>
            <input type="text" required="required" id="gender" />
            
          </div>
          <div className="inputbox"> 
          <span>Nationality</span>
            <input  type="text" required="required" id="nationa" />
           
          </div>
          <div className="inputbox">
          <span>Add here</span>
            <input type="submit" value="ADD" id="submit" />
          </div>   
        
         
        </form>
          
        </div>
  </>
  )
}

export default addUser

This is my userList.jsx

import { useState, useEffect } from "react";
import { ethers } from 'ethers';
//import "./UserList.css";
import "./get.css";

const userList = ({ state }) => {
  const [users, setUsers] = useState([]);


    const getuser = async () => { 
       const { contract } = state;
      console.log(contract);
      const userlist = await contract.getUser();
      console.log(userlist)
      setUsers(userlist);
      await userlist.wait();
      alert("Fetched successully");
    };



  return (
    <>
      <div>
        <h1>User List</h1>
        <button onClick={getuser}>Get Users</button>
        <ul>
          {users.map((user, index) => (
            <li key={index}>
              <strong>Name:</strong> {user.name}
              <br />
              <strong>Email:</strong> {user.email}
              <br />
              <strong>Gender:</strong> {user.gender}
              <br />
              <strong>Nationality:</strong> {user.nationality}
            </li>
          ))}
        </ul>
      </div>
    </>

  );
};

export default userList;

This is my app.jsx

import { useState, useEffect } from "react";
import {
  BrowserRouter as Router,
  Route,
  Routes,
  Link,
  Navigate,
} from "react-router-dom";
import { ethers } from "ethers";
import abi from "./contractJSON/chai.json";
import "./App.css";
import AddUser from "./components/addUser";
import UserList from "./components/userList";
import UpdateUser from "./components/updateUser";
import DeleteUser from "./components/deleteUser";

function App() {
  const [state, setState] = useState({
    provider: null,
    signer: null,
    contract: null,
  });

  const [account, setAccount] = useState("");

  useEffect(() => {
    const initialize = async () => {
      const contractAddress = "0xF83F28e186920184E4FEDf52a97fb25563cBF178";
      const contractABI = abi.abi;

      try {
        if (!window.ethereum) {
          alert("Please install MetaMask!");
        }
        const { ethereum } = window;
        const accounts = await ethereum.request({
          method: "eth_requestAccounts",
        });

        window.ethereum.on("accountsChanged", () => {
          window.location.reload();
        });
        setAccount(accounts[0]);

        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();

        const contract = new ethers.Contract(
          contractAddress,
          contractABI,
          signer
        );
        setState({ provider, signer, contract });
      } catch (error) {
        alert(error.message || "Error occurred while initializing.");
      }
    };
    initialize();
  }, []);

  const hideNavRoutes = ["/addUser", "/updateUser", "/deleteUser"]; // Routes where nav should be hidden

  return (
    <Router>
      <div className="divv">
        {hideNavRoutes.indexOf(window.location.pathname) === -1 && ( // Check if current route is in hidden list
          <div className="div_design">
            <nav className="ul_design">
              <ul>
                <li>
                  <Link to="/addUser" className="link_style">
                    Add User
                  </Link>
                </li>
                <li>
                  <Link to="/updateUser" className="link_style">
                    Update User
                  </Link>
                </li>
                <li>
                  <Link to="/deleteUser" className="link_style">
                    Delete User
                  </Link>
                </li>
                <li>
                  <Link to="/userList" className="link_style">
                    User List
                  </Link>
                </li>
              </ul>
            </nav>
          </div>
        )}

        <Routes>
          <Route path="/addUser" element={<AddUser state={state} />} />
          <Route path="/updateUser" element={<UpdateUser state={state} />} />
          <Route path="/deleteUser" element={<DeleteUser state={state} />} />
          <Route path="/userList" element={<UserList state={state} />} />
          <Route path="/" element={<Home />} />
        </Routes>
      </div>
    </Router>
  );
}

function Home() {
  return (
    <div>
      <h1>Welcome to the Home Page</h1>
    </div>
  );
}

export default App;

smart contract

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

contract chai {
    struct User {
        string name;
        string email;
        string gender;
        string nationality;
    }
    
    User[] user;
    mapping(address => User) public users;
    uint256 public totalUsers;

    // Function to add a new user
    function addUser(string memory _name, string memory _email, string memory _gender, string memory _nationality) public {
        users[msg.sender] = User(_name, _email, _gender, _nationality);
        user.push(User(_name,_email,_gender,_nationality));
        totalUsers++;
    }

    // Function to delete a user
    function deleteUser() public {
        delete users[msg.sender];
        totalUsers--;
    }

    // Function to update a user's information
    function updateUser(string memory _name, string memory _email, string memory _gender, string memory _nationality) public {
        users[msg.sender] = User(_name, _email, _gender, _nationality);
    }

    // Function to get the total number of users
    function getTotalUsers() public view returns (uint256) {
        return totalUsers;
    }

    // Function to get a user's details by address
    function getUser() public view returns (User [] memory) {
      return user;
    }
}

The error I get

Uncaught (in promise) Error: missing argument: passed to contract (count=0, expectedCount=1, code=MISSING_ARGUMENT, version=contracts/5.6.0) at _Logger.makeError (ethers.js?v=056a9c92:6568:19) at _Logger.throwError (ethers.js?v=056a9c92:6577:16) at _Logger.checkArgumentCount (ethers.js?v=056a9c92:6637:12) at ethers.js?v=056a9c92:13770:14 at Generator.next () at ethers.js?v=056a9c92:13697:67 at new Promise () at __awaiter5 (ethers.js?v=056a9c92:13679:10) at populateTransaction (ethers.js?v=056a9c92:13765:10) at Contract. (ethers.js?v=056a9c92:13945:24)

Full project link https://github.com/1804049Shorna/CRUD-DAPP

1 Answer 1

1

The ABI that you're using, is having an address input field in the corresponding getUser() function:

{
  "inputs": [
        {
          "internalType": "address",
          "name": "_userAddress",
          "type": "address"
        }
  ],
  "name": "getUser",
  "outputs": [
    {
      "components": [
        {
          "internalType": "string",
          "name": "name",
          "type": "string"
        },
        {
          "internalType": "string",
          "name": "email",
          "type": "string"
        },
        {
          "internalType": "string",
          "name": "gender",
          "type": "string"
        },
        {
          "internalType": "string",
          "name": "nationality",
          "type": "string"
        }
      ],
      "internalType": "struct chai.User[]",
      "name": "",
      "type": "tuple[]"
    }
  ],
  "stateMutability": "view",
  "type": "function"
}

If you redeploy the contract and use that ABI, then the portion for getUser() would be:

{
  "inputs": [],
  "name": "getUser",
  "outputs": [
    {
      "components": [
        {
          "internalType": "string",
          "name": "name",
          "type": "string"
        },
        {
          "internalType": "string",
          "name": "email",
          "type": "string"
        },
        {
          "internalType": "string",
          "name": "gender",
          "type": "string"
        },
        {
          "internalType": "string",
          "name": "nationality",
          "type": "string"
        }
      ],
      "internalType": "struct chai.User[]",
      "name": "",
      "type": "tuple[]"
    }
  ],
  "stateMutability": "view",
  "type": "function"
}

I've redeployed the contract using hardhat-ignition, it's available at 0x5e59b8A43FF9212B0F25cD52D1ED3FcF4a001539. And, you can find the generated chai.json containing the revised ABI in this gist.

I've also created a PR for the same.

5
  • I redeployed the smart contract , got the JSON file as yours , still getting the same error ,don't know why ,is it something to do with my UserList.jsx ? >>ethers.js?v=056a9c92:6568 Uncaught (in promise) Error: missing argument: passed to contract (count=0, expectedCount=1, code=MISSING_ARGUMENT, version=contracts/5.6.0) at _Logger.makeError (ethers.js?v=056a9c92:6568:19) at _Logger.throwError (ethers.js?v=056a9c92:6577:16) at _Logger.checkArgumentCount (ethers.js?v=056a9c92:6637:12) at ethers.js?v=056a9c92:13770:14
    – Shorna
    Commented May 14 at 1:47
  • You're having two folders (one inside root folder of vite-project and other inside components folder) named as contractJSON and both of them contains chai.json. So, I would recommend you to delete one of them, and import the latest one in your App.jsx. As, you can see in the PR, it's only retaining the root one and importing the same. Commented May 14 at 1:56
  • Thank you so much ,it worked
    – Shorna
    Commented May 14 at 3:21
  • You’re welcome, @Shorna. Happy coding! Commented May 14 at 5:05
  • Kindly please accept the answer, if it helped you. Commented May 14 at 5:06

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.