0

I'm trying to fetch totalSupply from my smart contract using react-moralis useWeb3ExecuteFunction and got this problem enter image description here

the code

import Head from 'next/head'
import styles from '../styles/Home.module.css'
import { useMoralis, useWeb3ExecuteFunction } from 'react-moralis';
import Web3Modal from "web3modal";
import {ethers, BigNumber} from 'ethers';
import { useState, useCallback, useEffect } from 'react';
import abi from './ABI.json';
import { CoinbaseWalletSDK} from '@coinbase/wallet-sdk';

const providerOptions = {
}
const address = "0x92BcA0381D537942B427F785bA1FDFF8321B9e5d";


export default function Home() {
  const {isWeb3Enabled} = useMoralis();
  const [web3Provider, setWeb3Provider] = useState(null);
  const [mintAmount, setMintAmount] = useState(1);
  const maxMintAmountPerTx = 5;
  const cost = 0.001;
  const [totalSupply, setTotalSupply] = useState(0);

  const { fetch: getTotalSupply } = useWeb3ExecuteFunction({
    abi: abi,
    contractAddress: address,
    functionName: 'totalSupply',
  });

  const updateUiValues = useCallback(async () => {
    const totalSupplyFromCall = (await getTotalSupply());
    setTotalSupply(totalSupplyFromCall.toNumber());
  }, [getTotalSupply]);

  useEffect(() => {
    if (web3Provider) {
      updateUiValues();

      // cleanup
      return () => {
        setTotalSupply(0);
      };
    }
  }, [web3Provider, updateUiValues]);

  function handleDecrement() {
    setMintAmount(Math.max(1, mintAmount - 1));
  }

  function handleIncrement() {
    setMintAmount(Math.min(maxMintAmountPerTx, mintAmount + 1));
  }

  async function handleMint() {
    if (web3Provider) {
      let totalCost = String(cost * mintAmount);
      const web3Modal = new Web3Modal({
        cacheProvider: true, // optional
        providerOptions // required
      });
      const instance = await web3Modal.connect();
      const provider = new ethers.providers.Web3Provider(instance);
      const signer = provider.getSigner();
      const contract = new ethers.Contract(
        address,
        abi,
        signer
      );
      try {
        const response = await contract.mint(BigNumber.from(mintAmount),{value:ethers.utils.parseUnits(totalCost)});
        console.log('response: ', response)
      } catch (err) {
        console.log("error: ", err)
      }
    }
  }

  async function connect () {
    try {
        let web3Modal = new Web3Modal ({
            cacheProvider: true,
            providerOptions,
        });
        const web3ModalInstance = await web3Modal.connect();
        const web3ModalProvider = new ethers.providers.Web3Provider(web3ModalInstance)
        console.log(web3ModalProvider)
        if(web3ModalProvider){
            setWeb3Provider(web3ModalProvider);
        }
    } catch(err) {

    }
  }

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.