Moralis self hosted server with vanilla js

hi
is it possible to authenticate with self hosted server with vanilla js

Hi @Ayush

It could be possible but there might be a limitation here. I think latest moralis-v1 sdk version 1.12.0 is not available in cdn url.

@johnversus right
but i am unable to authenticate with moralis version 2

    if (!user) {
      console.log(chainId)
      user = await Moralis.authenticate({
        provider: wallet_name,
        signingMessage: 'login ',
      })
        .then(async function (user) {
          user_address = user.get("ethAddress").substring(0, 6);

          const chainId = await Moralis.chainId;
          console.log(chainId)

          const accepted_chains = ["0x61", "0x38"];

          if (accepted_chains.includes(chainId)) {
            chain = chainId;
          } else {
            try {
              await Moralis.switchNetwork("0x38");
            } catch {
              alert(
                "Could not connect to Metamask. Please try switching chains."
              );
            }
          }

          // Subscribe to onChainChanged events
          const unsubscribe = Moralis.onChainChanged(async (chainId) => {
            if (accepted_chains.includes(chainId)) {
              chain = chainId;
            } else {
              try {
                await Moralis.switchNetwork("0x38");
              } catch {
                alert(
                  "Could not connect to Metamask. Please try switching chains."
                );
              }
            }
          });


        })
        .catch(function (error) {
          console.log(error);
        });
    }

but this shows error “moralis auth failed: invalid data”

Please try updating the signinMessage as per this reply.

Let me know if you still get the same error.

@johnversus
after updating

 async function login() {
    
    const { account, chainId } = Moralis;
  

    const { message } = await Moralis.Cloud.run("requestMessage", {
        address: account,
        chain: chainId,
        network: "evm",
      });
    let user = Moralis.User.current();
    if (!user) {
      console.log(chainId)
      user = await Moralis.authenticate({
        provider: wallet_name,
        signingMessage: message,
      })
        .then(async function (user) {
          user_address = user.get("ethAddress").substring(0, 6);

          const chainId = await Moralis.chainId;
          console.log(chainId)

          const accepted_chains = ["0x61", "0x38"];

          if (accepted_chains.includes(chainId)) {
            chain = chainId;
          } else {
            try {
              await Moralis.switchNetwork("0x38");
            } catch {
              alert(
                "Could not connect to Metamask. Please try switching chains."
              );
            }
          }

          // Subscribe to onChainChanged events
          const unsubscribe = Moralis.onChainChanged(async (chainId) => {
            if (accepted_chains.includes(chainId)) {
              chain = chainId;
            } else {
              try {
                await Moralis.switchNetwork("0x38");
              } catch {
                alert(
                  "Could not connect to Metamask. Please try switching chains."
                );
              }
            }
          });


        })
        .catch(function (error) {
          console.log(error);
        });
    }
  }

i am getting error: Invalid provided chain, value must be a positive number, or a hex-string starting with ‘0x’

can you try hardcoding the chain Id as 1 ?
chain: 1,

@johnversus
it’s showing
after adding 1
Error: [C0005] Invalid address provided: null

What was the address in account variable?

You need to pass the address as string. Try adding console.log(account) to check if it is a valid address or not

@johnversus
after updating this and console

const { account, chainId } = Moralis;
 console.log(account)
    

    const { message } = await Moralis.Cloud.run("requestMessage", {
        account: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
        chain: 1,
        network: "evm",
      });

still same issue
Invalid address provided: undefined
and after console account is showing null

this should be address rather than account

address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',

hi @johnversus
it’s authenticating now but after account is showing null after console

  async function login() {
    
    const { account, chainId } = Moralis;
    console.log(account)
    

    const { message } = await Moralis.Cloud.run("requestMessage", {
        address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
        chain: 1,
        network: "evm",
      });

account is a react variable so use a useEffect to log the account.

And also make sure you are importing moralis correctly
import Moralis from "moralis-v1";

// example
useEffect(() => {
console.log(account)
},[account])

hi @johnversus
as i am writing code svlete not react and in the below code user_address is same as account

  async function login() {
     
    let user = await Moralis.User.current();
    console.log(user)
    const { message } = await Moralis.Cloud.run("requestMessage", {

        address: '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266',
        chain: 1,
        network: "evm",
      });
    if (!user) {
      user = await Moralis.authenticate({
        provider: wallet_name,
        signingMessage: message,
      })
        .then(async function (user) {
          user_address = user.get("ethAddress");

          const chainId = await Moralis.chainId;
          console.log(user_address)

          const accepted_chains = ["0x61", "0x38"];

          if (accepted_chains.includes(chainId)) {
            chain = chainId;
          } else {
            try {
              await Moralis.switchNetwork("0x38");
            } catch {
              alert(
                "Could not connect to Metamask. Please try switching chains."
              );
            }
          }

          // Subscribe to onChainChanged events
          const unsubscribe = Moralis.onChainChanged(async (chainId) => {
            if (accepted_chains.includes(chainId)) {
              chain = chainId;
            } else {
              try {
                await Moralis.switchNetwork("0x38");
              } catch {
                alert(
                  "Could not connect to Metamask. Please try switching chains."
                );
              }
            }
          });


        })
        .catch(function (error) {
          console.log(error);
        });
    }

    
  }

so here
address: ‘0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266’,
chain: 1,
i need to remove hardcodes address and chain
but when i am passing user_address in place hardcoded address then it’s showing error

Invalid address provided: null

I am not sure why it is not working here. However since you are trying to connect to metamask you can also use the metamask API to detect the chain Id and address directly.

You can find more details in metamask docs

const chainId = await window.ethereum.request({ method: 'eth_chainId' });

const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' }) 

is there any other solution if possible?
also it’s showing error Moralis auth failed, invalid data
here invalid data what can be the reason
any idea?

Not sure why it is not working in your svelt. When I test with below code in vanilla js i can log the address and chainId without any issue.

  console.log(Moralis.chainId);
  console.log(Moralis.account);

btw we also need to run await Moralis.enableWeb3(); before using Moralis.chainId or Moralis.account to make sure there is a connection with the wallet.

hi @johnversus it works thanks for the help , now it’s authenticating

so after connecting with moralis self hosted server it’s authenticating but like other functionalities like create launchpads, locker and all those creating problems to working like as before our database was moralis but now in self hosted server so before creating launchpads we need create token , so create token is successful but when i am going to approve token to create launchpad then it’s showing error : ‘Request contains unknown parameter: address. This operation supports the following parameters: chain, addresses’

here below are the code of check token address

  async function checkToken(...args) {
    if (token_address && token_address.length == 42) {
      token_loading = true;
      token_error = false;
      await checkTokenAddress(token_address)
        .then(async (exists) => {
          if (exists) {
            token_loading = false;
            token_already_used = true;
            setTimeout(() => {
              token_already_used = false;
            }, 3000);
          } else {
            try {
              token_already_used = false;
              const metadata = await getTokenMetadata(token_address, chainId);
              token_metadata = metadata[0];

              token_loading = false;
            } catch (error) {
              console.log(error)
              token_loading = false;
              token_error = true;
            }
          }
        })
        .catch((error) => {
          // console.log("Error occurred while checking token address: ", error);
        });
    } else {
      token_metadata = null;
    }
  }

//
export async function getTokenMetadata(token_address, chainId) {
  let options = {};

  if (chainId == "0x61") {
    //Get metadata for one token. Ex: USDT token on ETH
    options = {
      chain: "bsc testnet",
      addresses: token_address,
    };
  } else if (chainId == "0x38") {
    //Get metadata for one token. Ex: USDT token on ETH
    options = {
      chain: "bsc",
      addresses: token_address,
    };
  }

  const tokenMetadata = await Moralis.Web3API.token.getTokenMetadata(options);

  // const isLP = new ethers.Contract('0xB7926C0430Afb07AA7DEfDE6DA862aE0Bde767bc', Factory)
  // const abc = await isLP.getPair('0x69859eB3160ad104E268725f4d310B8cD2f56E8F', '0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd' )
  // // console.log(abc)
  
  const getLp= await getIsLPTOken(chainId, token_address)
  let isLP= false
  if(getLp != ethers.constants.AddressZero){
       isLP=true
  }
  // console.log(isLP)
  

  const totalSupply = await getTotalSupply(token_address);

  const formattedSupply = ethers.utils.formatUnits(
    totalSupply.toString(),
    tokenMetadata[0].decimals
  );

  const walletBalance = await getBalanceOf(
    token_address,
    Moralis.User.current().get("ethAddress")
  );

  const formattedBalance = ethers.utils.formatUnits(
    walletBalance.toString(),
    tokenMetadata[0].decimals
  );
  

  tokenMetadata[0].balance = formattedBalance;
  tokenMetadata[0].totalSupply = formattedSupply;
 tokenMetadata[0].isLP=isLP;
  return tokenMetadata;
}

Can you show the code is returning this error.