Functions are not updating after refresh

Hey I have just created a Decentralised Lottery. I have integrated it with front-end. I have a function to fetch which is minimumContribution. It was working fine when a user logs in with metamask but when the user hits the refresh button of the webpage the value automatically sets to 0. Can anyonehelp!

//SPDX-License-Identifier: Unlicense

pragma solidity ^0.8.7;

contract Lottery{

    uint private trackMappping;

    mapping(uint256=>mapping(address=>uint256)) private trackPlayers;

    address public manager;

    uint256 private immutable minContribution;

    address[] private players;

    event playerEntry(address indexed player);

    event winnerPicked(address indexed winner);

    bool public isOpen=true;

    constructor(uint256 _amount){

        minContribution=_amount;

        manager=msg.sender;

    }

    function enterLottery() public payable{

        if(msg.value<=minContribution){

            revert("your value is less than minimium contribution");

        }else if(!isOpen){

            revert("Lottery is closed");

        }

        else if(trackPlayers[trackMappping][msg.sender]==0){

            players.push(msg.sender);

        }

        trackPlayers[trackMappping][msg.sender]+=msg.value;

        emit playerEntry(msg.sender);

    }

    function getminContribution()public view returns(uint256){

        require(isOpen, "Lottery Closed!");

        return minContribution;

    }

    function random() internal view returns(uint){

        return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, players.length)));

    }

    function pickWinner()public{

        require(isOpen,"Lottery has been closed");

        require(msg.sender==manager,"You aren't the manager of this smart contract");

        require(players.length>3,"Can't declare winner with less than 4 players");

        uint count=random();

        uint winner=count%players.length;

        (bool success,)=payable(players[winner]).call{value:address(this).balance}("");

        if(!success){

            revert("Transfer failed due to some error");

        }

        emit winnerPicked(players[winner]);

        delete players;

        trackMappping++;

        isOpen=false;

       

    }

    function getBalance() public view returns (uint256){

        require(isOpen,"Lottery has been closed");

        return address(this).balance;

    }

    function getParticipants()public view returns(uint256){

        require(isOpen,"Lottery has been closed");

        return players.length;

    }

    function startLottery() public{

        require(msg.sender==manager,"You aren't the manager of this smart contract");

        isOpen=true;

    }

   

}

My front-end code-

import {useMoralis} from "react-moralis";

import swal from 'sweetalert';

import React from "react";

function App() {

  const ABI= [{"inputs":[{"internalType":"uint256","name":"_amount","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"player","type":"address"}],"name":"playerEntry","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"winner","type":"address"}],"name":"winnerPicked","type":"event"},{"inputs":[],"name":"enterLottery","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"getBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getParticipants","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getminContribution","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isOpen","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pickWinner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"startLottery","outputs":[],"stateMutability":"nonpayable","type":"function"}]

  const[par, setPar]=React.useState(0);

  const[bal, setBal]=React.useState(0);

  const[min, setMin]=React.useState(0);

  const[status, setStatus]=React.useState(false);

  const {authenticate, isAuthenticated, isAuthenticating, user, account, logout}=useMoralis();

  const {Moralis} = useMoralis();

  async function login(){

      if(!isAuthenticated){

        await authenticate();

      }

      lotteryStatus();

      minContribution();

  }

  async function exit(){

    await logout();

  }

  async function enterLottery(){

    const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "enterLottery",

      abi: ABI,

      msgValue: await Moralis.Units.ETH(prompt("Enter the amount in ETH:"))

    }

   

    const transaction = await Moralis.executeFunction(sendOptions);

       

  }

  async function minContribution(){

    // const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getminContribution",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setMin(Moralis.Units.FromWei(transaction._hex));

  }

  async function pickWinner(){

      const sendOptions = {

        contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

        functionName: "pickWinner",

        abi: ABI

      }

      const transaction = await Moralis.executeFunction(sendOptions);

      setStatus(false);

  }

      

  async function getBalance(){

    const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getBalance",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setBal(Moralis.Units.FromWei(transaction._hex));

  }

  async function getParticipants(){

    //const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getParticipants",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    swal({

      title: `Participants: ${Moralis.Units.FromWei(transaction._hex, 0)}`,

      icon: "info",

  });

  }

  async function showInfo(){

    const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getParticipants",

      abi: ABI

    }

    const lists = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getBalance",

      abi: ABI

    }

    const participants = await Moralis.executeFunction(sendOptions);

    const balances=await Moralis.executeFunction(lists);

    swal({

      title: `Participants: ${Moralis.Units.FromWei(participants._hex, 0)}`,

      text: `Balance: ${Moralis.Units.FromWei(balances._hex)}`,

      icon: "info",

  });

  }

  async function startLottery(){

    // const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "startLottery",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setStatus(true);

  }

  async function lotteryStatus(){

    // const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "isOpen",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setStatus(transaction);

  }

 

return (

  <>

    <div className="card text-center bg2" >

       <div className="card-body bg2" >

       

         {/* {isAuthenticated? <button type="button" className="btn btn-outline-warning" onClick={Update}>Balance: {balances}</button> : null} */}

         {isAuthenticated? <p className="lottery">Lottery : {status? "Running": "Closed"}</p> : <p className="lottery">Lottery</p>}

         {isAuthenticated? <p className=" text-gradient">Account : {user.get("ethAddress")}</p> : <p className=" text-gradient">Account : Not Connected</p>}

         {isAuthenticated? <p className=" text-gradient">{null}</p> : null}

         {isAuthenticated? <p className="min">Minimum Contribution : {min} ETH</p> : null}

         {isAuthenticated? <button className="button-custom" onClick={showInfo}>INFO</button> : null}

         &nbsp;

         &nbsp;

         {!isAuthenticated? <button type="button" className="btn btn-outline-light button-85" onClick={login}>

           Connect to metamask

         </button> : null}

         &nbsp;

         {isAuthenticated? <button type="button" className="button-33" onClick={enterLottery} >Enter Lottery</button> : null}

         &nbsp;

         {(isAuthenticated && user.get('ethAddress')==="0x846A519f8c6ceF4db5ABa30Fc3c36BE38DA48F06".toLowerCase())? <button type="button" className="btn btn-outline-success" onClick={startLottery}>Start Lottery</button> : null}

         &nbsp;

         {(isAuthenticated && user.get('ethAddress')==="0x846A519f8c6ceF4db5ABa30Fc3c36BE38DA48F06".toLowerCase())? <button type="button" className="btn btn-outline-primary" onClick={pickWinner}>Pick Winner</button> : null}

         &nbsp;

         &nbsp;

        {isAuthenticated?<button type="button" className="button-78" onClick={exit}>Logout</button> : null}

       </div>

       <div className="card-footer text-gradient">Copyright @Abir Dutta</div>

     </div>

  </>

 );

}

export default App;

Please review it once.

This project is hosted- https://deadmanabir.github.io/Lottery/ ](https://deadmanabir.github.io/Lottery/

You need to call the getBalance function from your app and update the data in UI after every refresh or after every user authentication.

hey can you just write that process of how to update the value after every refresh, as I don’t know how to do that.

As you are setting the minimum contribution in UI using minContribution function this need to be called on every refresh.

I think this should work.

useEffect(() => {
if (isAuthenticated) {
minContribution();
}
}, [isAuthenticated]) 

ok let me try this code

Hey after implementing your code I got the following error on my console-

Uncaught (in promise) Error: Missing web3 instance, make sure to call Moralis.enableWeb3() or Moralis.authenticate()
    at Function.value (MoralisWeb3.js:1869:1)
    at Function.<anonymous> (MoralisWeb3.js:1679:1)
    at tryCatch (runtime.js:63:1)
    at Generator.invoke [as _invoke] (runtime.js:294:1)
    at Generator.next (runtime.js:119:1)
    at asyncGeneratorStep (asyncToGenerator.js:5:1)
    at _next (asyncToGenerator.js:27:1)
    at asyncToGenerator.js:34:1
    at new Promise (<anonymous>)
    at new Wrapper (export.js:18:1

This is how I implemented your code-

async function minContribution(){

    const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getminContribution",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setMin(Moralis.Units.FromWei(transaction._hex));

  }

  async function pickWinner(){

      const sendOptions = {

        contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

        functionName: "pickWinner",

        abi: ABI

      }

      const transaction = await Moralis.executeFunction(sendOptions);

      setStatus(false);

  }

  async function showInfo(){

    const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getParticipants",

      abi: ABI

    }

    const lists = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getBalance",

      abi: ABI

    }

    const participants = await Moralis.executeFunction(sendOptions);

    const balances=await Moralis.executeFunction(lists);

    swal({

      title: `Participants: ${Moralis.Units.FromWei(participants._hex, 0)}`,

      text: `Balance: ${Moralis.Units.FromWei(balances._hex)}`,

      icon: "info",

  });

  }

  async function startLottery(){

    // const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "startLottery",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setStatus(true);

  }

  async function lotteryStatus(){

    const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "isOpen",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setStatus(transaction);

  }

  React.useEffect(() => {

    if (isAuthenticated && isAuthenticated !==null) {

    minContribution();

    lotteryStatus();

    }

    }, [isAuthenticated])

    

return (

  <>

    <div className="card text-center bg2" >

       <div className="card-body bg2" >

       

         {/* {isAuthenticated? <button type="button" className="btn btn-outline-warning" onClick={Update}>Balance: {balances}</button> : null} */}

         {isAuthenticated? <p className="lottery">Lottery : {status? "Running": "Closed"}</p> : <p className="lottery">Lottery</p>}

         {isAuthenticated? <p className=" text-gradient">Account : {user.get("ethAddress")}</p> : <p className=" text-gradient">Account : Not Connected</p>}

         {isAuthenticated? <p className=" text-gradient">{null}</p> : null}

         {isAuthenticated? <p className="min">Minimum Contribution : {min} ETH</p> : null}

         {isAuthenticated? <button className="button-custom" onClick={showInfo}>INFO</button> : null}

         &nbsp;

         &nbsp;

         {!isAuthenticated? <button type="button" className="btn btn-outline-light button-85" onClick={login}>

           Connect to metamask

         </button> : null}

         &nbsp;

         {isAuthenticated? <button type="button" className="button-33" onClick={enterLottery} >Enter Lottery</button> : null}

         &nbsp;

         {(isAuthenticated && user.get('ethAddress')==="0x846A519f8c6ceF4db5ABa30Fc3c36BE38DA48F06".toLowerCase())? <button type="button" className="btn btn-outline-success" onClick={startLottery}>Start Lottery</button> : null}

         &nbsp;

         {(isAuthenticated && user.get('ethAddress')==="0x846A519f8c6ceF4db5ABa30Fc3c36BE38DA48F06".toLowerCase())? <button type="button" className="btn btn-outline-primary" onClick={pickWinner}>Pick Winner</button> : null}

         &nbsp;

         &nbsp;

        {isAuthenticated?<button type="button" className="button-78" onClick={exit}>Logout</button> : null}

       </div>

       <div className="card-footer text-gradient">Copyright @Abir Dutta</div>

     </div>

  </>

 );

}

export default App;

Can you elaborate why I am getting the error

I got the following error after implementing your code-

MoralisWeb3.js:348 Uncaught (in promise) Error: Cannot execute Moralis.enableWeb3(), as Moralis Moralis.enableWeb3() already has been called, but is not finished yet 
    at Function.<anonymous> (MoralisWeb3.js:348:1)
    at tryCatch (runtime.js:63:1)
    at Generator.invoke [as _invoke] (runtime.js:294:1)
    at Generator.next (runtime.js:119:1)
    at asyncGeneratorStep (asyncToGenerator.js:5:1)
    at _next (asyncToGenerator.js:27:1)
    at asyncToGenerator.js:34:1
    at new Promise (<anonymous>)
    at new Wrapper (export.js:18:1)
    at Function.<anonymous> (asyncToGenerator.js:23:1)
(anonymous) @ MoralisWeb3.js:348
tryCatch @ runtime.js:63
invoke @ runtime.js:294
(anonymous) @ runtime.js:119
asyncGeneratorStep @ asyncToGenerator.js:5
_next @ asyncToGenerator.js:27
(anonymous) @ asyncToGenerator.js:34
Wrapper @ export.js:18
(anonymous) @ asyncToGenerator.js:23
(anonymous) @ MoralisWeb3.js:437
lotteryStatus @ App.js:97
(anonymous) @ App.js:109
commitHookEffectListMount @ react-dom.development.js:23049
commitPassiveMountOnFiber @ react-dom.development.js:24816
commitPassiveMountEffects_complete @ react-dom.development.js:24781
commitPassiveMountEffects_begin @ react-dom.development.js:24768
commitPassiveMountEffects @ react-dom.development.js:24756
flushPassiveEffectsImpl @ react-dom.development.js:26990
flushPassiveEffects @ react-dom.development.js:26935
commitRootImpl @ react-dom.development.js:26886
commitRoot @ react-dom.development.js:26638
performSyncWorkOnRoot @ react-dom.development.js:26073
flushSyncCallbacks @ react-dom.development.js:12009
flushSync @ react-dom.development.js:26157
scheduleRefresh @ react-dom.development.js:27749
renderer.scheduleRefresh @ react_devtools_backend.js:6466
(anonymous) @ react-refresh-runtime.development.js:304
performReactRefresh @ react-refresh-runtime.development.js:293
(anonymous) @ RefreshUtils.js:85
await in (anonymous) (async)
(anonymous) @ App.js:109
commitHookEffectListMount @ react-dom.development.js:23049
commitPassiveMountOnFiber @ react-dom.development.js:24816
commitPassiveMountEffects_complete @ react-dom.development.js:24781
commitPassiveMountEffects_begin @ react-dom.development.js:24768
commitPassiveMountEffects @ react-dom.development.js:24756
flushPassiveEffectsImpl @ react-dom.development.js:26990
flushPassiveEffects @ react-dom.development.js:26935
commitRootImpl @ react-dom.development.js:26886
commitRoot @ react-dom.development.js:26638
performSyncWorkOnRoot @ react-dom.development.js:26073
flushSyncCallbacks @ react-dom.development.js:12009
flushSync @ react-dom.development.js:26157
scheduleRefresh @ react-dom.development.js:27749
renderer.scheduleRefresh @ react_devtools_backend.js:6466
(anonymous) @ react-refresh-runtime.development.js:304
performReactRefresh @ react-refresh-runtime.development.js:293
(anonymous) @ RefreshUtils.js:85
setTimeout (async)
enqueueUpdate @ RefreshUtils.js:83
executeRuntime @ RefreshUtils.js:243
$ReactRefreshModuleRuntime$ @ App.js:148
./src/App.js @ App.js:148
options.factory @ react refresh:6
__webpack_require__ @ bootstrap:24
_requireSelf @ hot module replacement:102
apply @ jsonp chunk loading:407
(anonymous) @ hot module replacement:344
internalApply @ hot module replacement:342
(anonymous) @ hot module replacement:279
waitForBlockingPromises @ hot module replacement:233
(anonymous) @ hot module replacement:277
Promise.then (async)
(anonymous) @ hot module replacement:276
Promise.then (async)
(anonymous) @ hot module replacement:256
Promise.then (async)
hotCheck @ hot module replacement:247
check @ dev-server.js:13
(anonymous) @ dev-server.js:55
emit @ events.js:153
reloadApp @ reloadApp.js:46
warnings @ index.js:227
(anonymous) @ socket.js:60
client.onmessage @ WebSocketClient.js:50

I have implemented this-

React.useEffect(() => {

    if (isAuthenticated && isAuthenticated !==null) {

    minContribution();

    lotteryStatus();

    }

    }, [isAuthenticated])

just before the return tag

This should not happen as you already have an enableweb3 function inside minContribution function.

Try with this.

const { enableWeb3, isWeb3Enabled } = useMoralis()
useEffect(() => {
if (isAuthenticated) {
enableWeb3()
}
if (isAuthenticated && isWeb3Enabled) {
minContribution();
}
}, [isAuthenticated])

bro it fon’t give error if I run just one function in useEffect but whenever I try to run the startLottery function with minContribution it says

Uncaught (in promise) Error: Cannot execute Moralis.enableWeb3(), as Moralis Moralis.enableWeb3() already has been called, but is not finished yet

I have also tried to use two different useEffect for the two function but it gives the same error

This happens if the enableweb3() function is called twice. You can add an if condition before calling the enableweb3 to check if web3 is already enabled.

if(!isWeb3Enabled){
enableWeb3();
}

Now getting this type of error twice everytime I refresh -

Missing web3 instance, make sure to call Moralis.enableWeb3() or Moralis.authenticate()

the code is -

const {authenticate, isAuthenticated, isAuthenticating, user, account, logout, enableWeb3, isWeb3Enabled}=useMoralis();

async function lotteryStatus(){

    //const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "isOpen",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setStatus(transaction);

  }

async function minContribution(){

    //const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {

      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getminContribution",

      abi: ABI

    }

    const transaction = await Moralis.executeFunction(sendOptions);

    setMin(Moralis.Units.FromWei(transaction._hex));

  }

React.useEffect(() => {

    if(!isWeb3Enabled){

      enableWeb3();

      }

    if (isAuthenticated && isAuthenticated !==null) {

    minContribution();

    lotteryStatus();

    }

    }, [isAuthenticated])

Any function is getting called on every refresh?

It will probably require an isWeb3enabled check before running the function.

if(isWeb3Enabled){
//fucntion to run after enabling web3
}

can you write the full code please I want to run minimumContribution and lotteryStatus on every refresh, now please write the full useEffect for this

Hey john can you please reply

Share your updated github repo, so i can test from my side.

Here is the git link- https://github.com/DeadmanAbir/Lottery_checking

Please figure the problem out!

Not able to access the link. Is this a private repo?

Hey check now I think you should access it now.

1 Like

I suppressed the errors with some if conditions, but it is not the right way to do in react.
You need to use the useWeb3Contract hook to run the smart contract function depending on the state variable data change.

import React, { useState, useEffect } from "react";
import { useMoralis } from "react-moralis";
import swal from "sweetalert";

function Test() {
  const ABI = [
    {
      inputs: [{ internalType: "uint256", name: "_amount", type: "uint256" }],
      stateMutability: "nonpayable",
      type: "constructor",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "player",
          type: "address",
        },
      ],
      name: "playerEntry",
      type: "event",
    },
    {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "winner",
          type: "address",
        },
      ],
      name: "winnerPicked",
      type: "event",
    },
    {
      inputs: [],
      name: "enterLottery",
      outputs: [],
      stateMutability: "payable",
      type: "function",
    },
    {
      inputs: [],
      name: "getBalance",
      outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "getParticipants",
      outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "getminContribution",
      outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "isOpen",
      outputs: [{ internalType: "bool", name: "", type: "bool" }],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "manager",
      outputs: [{ internalType: "address", name: "", type: "address" }],
      stateMutability: "view",
      type: "function",
    },
    {
      inputs: [],
      name: "pickWinner",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
    {
      inputs: [],
      name: "startLottery",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    },
  ];

  const [par, setPar] = React.useState(0);

  const [bal, setBal] = React.useState(0);

  const [min, setMin] = React.useState(0);

  const [status, setStatus] = React.useState(false);

  const {
    authenticate,
    isAuthenticated,
    isAuthenticating,
    user,
    account,
    logout,
  } = useMoralis();

  const {
    web3,
    enableWeb3,
    isWeb3Enabled,
    isWeb3EnableLoading,
    web3EnableError,
  } = useMoralis();

  const { Moralis } = useMoralis();

  async function login() {
    if (!isAuthenticated) {
      await authenticate();
    }
  }

  useEffect(() => {
    const init = async () => {
      await Moralis.enableWeb3().then(lotteryStatus()).then(minContribution());
    };
    if (user) {
      init();
    }
  }, []);

  async function exit() {
    await logout();
  }
  async function enterLottery() {
    //const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "enterLottery",

      abi: ABI,

      msgValue: await Moralis.Units.ETH(prompt("Enter the amount in ETH:")),
    };

    const transaction = await Moralis.executeFunction(sendOptions);
  }

  async function minContribution() {
    if (!Moralis.isWeb3Enabled) {
      await Moralis.enableWeb3({ provider: "metamask" });
    } else if (Moralis.isWeb3Enabled()) {
      const sendOptions = {
        contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",
        functionName: "getminContribution",
        abi: ABI,
      };
      const transaction = await Moralis.executeFunction(sendOptions);
      setMin(Moralis.Units.FromWei(transaction._hex));
    }
  }

  async function pickWinner() {
    const sendOptions = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "pickWinner",

      abi: ABI,
    };

    const transaction = await Moralis.executeFunction(sendOptions);

    setStatus(false);
  }

  async function getBalance() {
    const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getBalance",

      abi: ABI,
    };

    const transaction = await Moralis.executeFunction(sendOptions);

    setBal(Moralis.Units.FromWei(transaction._hex));
  }

  async function getParticipants() {
    //const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getParticipants",

      abi: ABI,
    };

    const transaction = await Moralis.executeFunction(sendOptions);

       swal({
         title: `Participants: ${Moralis.Units.FromWei(transaction._hex, 0)}`,

         icon: "info",
       });
  }

  async function showInfo() {
    const web3 = await Moralis.enableWeb3({ provider: "metamask" });

    const sendOptions = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getParticipants",

      abi: ABI,
    };

    const lists = {
      contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

      functionName: "getBalance",

      abi: ABI,
    };

    const participants = await Moralis.executeFunction(sendOptions);

    const balances = await Moralis.executeFunction(lists);

     swal({
       title: `Participants: ${Moralis.Units.FromWei(participants._hex, 0)}`,

       text: `Balance: ${Moralis.Units.FromWei(balances._hex)}`,

       icon: "info",
     });
  }

  async function startLottery() {
    // const web3 = await Moralis.enableWeb3({ provider: "metamask" });
    if (isWeb3Enabled) {
      const sendOptions = {
        contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

        functionName: "startLottery",

        abi: ABI,
      };
      const transaction = await Moralis.executeFunction(sendOptions);
      setStatus(true);
    }
  }

  async function lotteryStatus() {
    if (!Moralis.isWeb3Enabled) {
      await Moralis.enableWeb3({ provider: "metamask" });
    } else if (Moralis.isWeb3Enabled()) {

      const sendOptions = {
        contractAddress: "0x8d61466b42308fc259E875Fe71Fe173555F8731A",

        functionName: "isOpen",
        abi: ABI,
      };

      const transaction = await Moralis.executeFunction(sendOptions);

      setStatus(transaction);
    }
  }

  return (
    <>
      <div className="card text-center bg2">
        <div className="card-body bg2">
          {/* {isAuthenticated? <button type="button" className="btn btn-outline-warning" onClick={Update}>Balance: {balances}</button> : null} */}
          {isAuthenticated ? (
            <p className="lottery">Lottery : {status ? "Running" : "Closed"}</p>
          ) : (
            <p className="lottery">Lottery</p>
          )}
          {isAuthenticated ? (
            <p className=" text-gradient">Account : {user.get("ethAddress")}</p>
          ) : (
            <p className=" text-gradient">Account : Not Connected</p>
          )}
          {isAuthenticated ? <p className=" text-gradient">{null}</p> : null}
          {isAuthenticated ? (
            <p className="min">Minimum Contribution : {min} ETH</p>
          ) : null}
          {isAuthenticated ? (
            <button className="button-custom" onClick={showInfo}>
              INFO
            </button>
          ) : null}
          &nbsp; &nbsp;
          {!isAuthenticated ? (
            <button
              type="button"
              className="btn btn-outline-light button-85"
              onClick={login}
            >
              Connect to metamask
            </button>
          ) : null}
          &nbsp;
          {isAuthenticated ? (
            <button type="button" className="button-33" onClick={enterLottery}>
              Enter Lottery
            </button>
          ) : null}
          &nbsp;
          {isAuthenticated &&
          user.get("ethAddress") ===
            "0x846A519f8c6ceF4db5ABa30Fc3c36BE38DA48F06".toLowerCase() ? (
            <button
              type="button"
              className="btn btn-outline-success"
              onClick={startLottery}
            >
              Start Lottery
            </button>
          ) : null}
          &nbsp;
          {isAuthenticated &&
          user.get("ethAddress") ===
            "0x846A519f8c6ceF4db5ABa30Fc3c36BE38DA48F06".toLowerCase() ? (
            <button
              type="button"
              className="btn btn-outline-primary"
              onClick={pickWinner}
            >
              Pick Winner
            </button>
          ) : null}
          &nbsp; &nbsp;
          {isAuthenticated ? (
            <button type="button" className="button-78" onClick={exit}>
              Logout
            </button>
          ) : null}
        </div>

        <div className="card-footer text-gradient">Copyright @Abir Dutta</div>
      </div>
    </>
  );
}

export default Test;


Now the output is showing like this the minimum Contribution is 0 and it’s showing that Lottery is closed.:cry: