I have an authentication question

Hello, I have a metamask authentication function with moralis, and when connecting the function to the self-hosted server it returns an error: error: Moralis auth failed, invalid data {ā€œcodeā€:101,ā€œstackā€:ā€œError: Moralis auth failed , invalid data\n at C:\Users\david\Documents\Programming\react\Koolinart\backend\src\auth\MoralisEthAdapter.ts:32:13\n at runMicrotasks (< anonymous>)\n at processTicksAndRejections (node:internal/process/task_queues:96:5)\n at async Promise.all (index 0)ā€} I attached the authentication function, I have more questions about the authenticator, which I have not met Sure, but Iā€™ll go in parts. thank you.
The first function is via metamask, the second function is via email, the authentication function via email works fine, but the metamask one doesnā€™t, the question in the email one is how to authenticate the message data or some data that was required the authdata field in moralis. because when I authenticate myself, the authenticated user does not recognize me. I mean, the email authentication function works but halfway

const Login = async () => {

    setStateCircularProgress(true);

    const provider = "metamask";

    try {

      // () => setValuesAlertFunc(true, "Login success", "success");

      if (!state.authenticated) {

        await Moralis.enableWeb3({ provider });

        const chainId = Moralis.chainId;

        if (chainId != "0x13881") {

          await switchNetworkPolygon();

        }

        await authenticate({

          signingMessage: "Welcome to Koolinart",

          throwOnError: true,

        }).then(async function (user) {

          const userMarketType = user!.get("loginType");

          setValuesAlertFunc(true, "Welcome to Koolinart", "success");

          console.log('user', user)

          dispatch({

            type: "USER_AUTHENTICATED",

            payload: true,

          });

          dispatch({

            type: "GET_LOGIN_TYPE",

            payload: userMarketType,

          });

          dispatch({

            type: "USER_RENDER",

            payload: user,

          });

        });

        const ethAddress = state.userRender.attributes?.ethAddress

          ? state.userRender.attributes.ethAddress

          : "";

        await fetchTokenBalance(ethAddress);

      }

    } catch (e) {

      const errorMessage = JSON.stringify(e);

      const errorObjeto = JSON.parse(errorMessage);

      setValuesAlertFunc(true, errorObjeto.message, "error");

      console.log("error", e);

      setStateCircularProgress(false);

    }

  };
const LoginMail = async (values: any) => {

    setStateCircularProgress(true);

    if (!state.authenticated) {

      await Moralis.User.logIn(values.username, values.password)

        .then(async function (user) {

          const userMarketType = user.get("loginType");

          dispatch({

            type: "USER_AUTHENTICATED",

            payload: true,

          });

          dispatch({

            type: "GET_LOGIN_TYPE",

            payload: userMarketType,

          });

          dispatch({

            type: "USER_RENDER",

            payload: user,

          });

          setValuesAlertFunc(true, "Welcome to Koolinart", "success");

        })

        .catch(function (error) {

          // setValuesAlertFunc(true, " Invalid username/password.", "error");

          const errorMessage = JSON.stringify(error);

          const errorObjeto = JSON.parse(errorMessage);

          setValuesAlertFunc(true, errorObjeto.message, "error");

              setStateCircularProgress(false);

          console.log("šŸš€ error de login", error);

        });

      const ethAddress = state.userRender.attributes?.ethAddress

        ? state.userRender.attributes.ethAddress

        : "";

      await fetchTokenBalance(ethAddress);

    }

  };

When reading the log, I notice that they say that this will be disabled in the future, so the question would be how would I do it now?

Hi @davidzuccarini

Sign in message cannot be a hardcoded value here. You should get it from the requestMessage cloud function.

// example code
const { message } = await Moralis.Cloud.run("requestMessage", {
        address: account,
        chain: parseInt(chainId, 16),
        network: "evm",
      });

Refer this doc for an example code.

yes, i try it, but i receive this error front [C0008] Default instance of Core is not set

error back:


error: Failed running cloud function requestMessage for user undefined with:
  Input: {"address":null,"chain":null,"network":"evm"}
  Error: {"message":"[C0008] Default instance of Core is not set","code":141} {"error":{"code":141,"message":"[C0008] Default instance of Core is not set"},"functionName":"requestMessage","params":{"address":null,"chain":null,"network":"evm"}}   
error: [C0008] Default instance of Core is not set {"code":141,"stack":"Moralis SDK Core Error: [C0008] Default instance of Core is not set\n    at Function.CoreProvider.getDefault (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\node_modules\\@moralisweb3\\common-core\\lib\\cjs\\index.cjs:965:19)\n    at Function.EvmChain.create (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\node_modules\\@moralisweb3\\common-evm-utils\\lib\\cjs\\index.cjs:823:49)\n    at makeEvmRequestMessage (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\lib\\cjs\\index.cjs:113:155)\n    at C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\lib\\cjs\\index.cjs:138:43\n    at step (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\lib\\cjs\\index.cjs:98:23)\n    at Object.next (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\lib\\cjs\\index.cjs:79:53)\n    at C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\lib\\cjs\\index.cjs:72:71\n    at new Promise (<anonymous>)\n    at __awaiter (C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\lib\\cjs\\index.cjs:68:12)\n    at C:\\Users\\david\\Documents\\Programacion\\react\\Koolinart\\backend\\node_modules\\@moralisweb3\\auth\\lib\\cjs\\index.cjs:127:79"}

Try updating these two lines with your data.
Replace account with wallet address and chain with chain id.

The db does not contain any data, it is the first record, if I replace the values it would be for debug? Why before, if a user was not logged in, did it automatically add him to the db, is this error due to what?

It looks like the values are not set here

but that comes from:

const { message } = await Moralis.Cloud.run("requestMessage", {
         address: account,
         chain: parseInt(chainId, 16),
         network: "evm",
       });

when logging in, if the user does not exist in the db, it does not bring data, when it started with the moralis server, when logging in it automatically stored the first login, all the authentication data, now with the self-hosted server you have to do a sign up of the user so that the data is stored by metamask?

sign in code:

const Login = async () => {

    setStateCircularProgress(true);

    try {

      const provider = "metamask";

      await enableWeb3({ throwOnError: true, provider });

      const { message } = await Moralis.Cloud.run("requestMessage", {

        address: account,

        chain: parseInt(chainId, 16),

        network: "evm",

      });

 

      console.log("message", message)

      console.log("chainId", chainId)

      console.log("message", message)

      if (!account) {

        throw new Error(

          "Connecting to chain failed, as no connected account was found"

        );

      }

      if (!chainId) {

        throw new Error(

          "Connecting to chain failed, as no connected chain was found"

        );

      }

      // () => setValuesAlertFunc(true, "Login success", "success");

      if (!state.authenticated) {

        if (chainId != chainID.testNet ) {

          await switchNetworkPolygon();

        }

        await authenticate({

          signingMessage: message,

          throwOnError: true,

        }).then(async (user: any) => {

          const userMarketType = user!.get("loginType");

          setValuesAlertFunc(true, "Welcome to Koolinart", "success");

          console.log('user', user)

          dispatch({

            type: "USER_AUTHENTICATED",

            payload: true,

          });

          dispatch({

            type: "GET_LOGIN_TYPE",

            payload: userMarketType,

          });

          dispatch({

            type: "USER_RENDER",

            payload: user,

          });

        });

        const ethAddress = state.userRender.attributes?.ethAddress

          ? state.userRender.attributes.ethAddress

          : "";

        await fetchTokenBalance(ethAddress);

      }

    } catch (e) {

      const errorMessage = JSON.stringify(e);

      const errorObjeto = JSON.parse(errorMessage);

      setValuesAlertFunc(true, errorObjeto.message, "error");

      console.log("error", e);

      setStateCircularProgress(false);

    }

  };

and i have this parse server migration https://github.com/MoralisWeb3/Moralis-JS-SDK/tree/main/demos/parse-server-migration

you can add some logging to see where those values get lost

in backend? debug from the start of the frontend, and from here it tells me null the moralis calls

const { authenticate, logout, enableWeb3, account, chainId, Moralis }: any = useMoralis();

  console.log("account", account) ===> null
  console.log("chainId", chainId) ==> null

if I use import Moralis from "moralis-v1"; also account and chainId
is null and if you see the code I am initializing await enableWeb3({ throwOnError: true, provider });

It should be noted that it opens metamask and I get connected I click connect and there it throws the error [C0008] Default instance of Core is not set

Is the wallet connected?

It should be noted that it opens metamask and I get connected I click connect and there it throws the error [C0008] Default instance of Core is not set

What are you using in front end? What technology you are using for the application?

use react with vitejs

you can also get the eth address and hardcode the chain id as 0x1 with any other library like ethers or web3 or rainbowkit

mmm :thinking: yes it is a solution but I love the simple way of moralis, migrating the project has been a headache, since it is a big project it is a market, thanks for the help, I will sleep for a while it is 5am in my country. And I also comment that I have doubts with the streams when I start working I comment on the doubts and I open a new thread, sorry for so much inconvenience. And i will try more things and if not I will do it that way

Hello again, I have another question if I use this method to authenticate via mail:

const LoginMail = async (values: any) => {
     setStateCircularProgress(true);

     if (!state.authenticated) {
       await Moralis.User.logIn(values.username, values.password )
         .then(async function (user: { get: (arg0: string) => any; }) {
           const userMarketType = user.get("loginType");

           dispatch({
             type: "USER_AUTHENTICATED",
             payload: true,
           });
           dispatch({
             type: "GET_LOGIN_TYPE",
             payload: userMarketType,
           });
           dispatch({
             type: "USER_RENDER",
             payload: user,
           });
           setValuesAlertFunc(true, "Welcome to Koolinart", "success");
         })

         .catch(function (error: any) {

           const errorMessage = JSON.stringify(error);
           const errorObject = JSON.parse(errorMessage);

           setValuesAlertFunc(true, errorObject.message, "error");
               setStateCircularProgress(false);

           console.log("šŸš€ login error", error);
         });

       const ethAddress = state.userRender.attributes?.ethAddress
         ? state.userRender.attributes.ethAddress
         :"";

       await fetchTokenBalance(ethAddress);
       setStateCircularProgress(false);

     }
   };

why doesnā€™t it take me: const user = Moralis.User.current();
The authentication is correct but the user of moralis does not take me, should I give you any more information? I notice that in the db the authData field is empty while when authenticating with metamask I completed this field, is it because this field is empty?

This is the register function:

  const SetLoginMail = async (values: any) => {
     setStateCircularProgress(true);
     const user = new Moralis.User();
     user.set("fullname", values.fullname);
     user.set("username", values.username.toLowerCase());
     user.set("email", values.email);
     user.set("password", values.password);

     const wallet = ethers.Wallet.createRandom();

     user.set("mnemonic", wallet.mnemonic.phrase);
     user.set("privateKey", wallet.privateKey);
     user.set("ethAddress", wallet.address.toLowerCase());
     user.set("accounts", [wallet.address.toLowerCase()]);
     user.set("loginType", "email");

     try {
       const newUser = await user.signUp();
       console.log('newUser', newUser)
       setValuesAlertFunc(true, "Successful creation", "success");
     } catch(error) {
       const errorMessage = JSON.stringify(error);
       const errorObject = JSON.parse(errorMessage);

       setValuesAlertFunc(true, errorObject.message, "error");
     }
     setStateCircularProgress(false);
   };

Another question regarding the user is how with the own server, I reset the password and I check the mail.

I keep getting the same metamask authentication error, I pass the mentioned data with ethers but it doesnā€™t authenticate me, the error is because metamask was updated?, Iā€™m stuck with metamask authentication via moralis. what else could i do? I noticed on the forum that someone else got this same error.

what happens? at what step is stops working?

I donā€™t recognize the user in const user = Moralis.User.current(); when I login with this function await Moralis.User.logIn(values.username, values.password )

This doesnā€™t seem to be related to a wallet authentication