Moralis login _ metamask problem

HI everyone
im at the moralis section and I keep getting this error code and for the life of me can not see where the problem is

any help would be greatly appreciated

dex.js:21 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at dex.js:21:43

here is my dex.js

 // connect to Moralis server
 const serverUrl = "https://xiqxyv5bgozp.usemoralis.com:2053/server";
 const appId = "7ZyhnEhnPqCPvyN7zLl4vNrymoTQ2YUJYiXOWf9y";
 Moralis.start({ serverUrl, appId });

    async function login() {
        let user = Moralis.User.current();
        if (!user) {
          user = await Moralis.authenticate();
        }
        console.log("logged in user:", user);
      }

      async function logOut() {
        await Moralis.User.logOut();
        console.log("logged out");
      }



      document.querySelector("#btn-login").addEventListener('click', login);
      
      
      document.getElementById("btn-logout").addEventListener(`click`, logOut);
    


    async function getTop10Tokens () {
        const response = await fetch('https://api.coinpaprika.com/v1/coins');
        const tokens = await response.json();

    return tokens
        .filter(token => token.rank >= 1 && token.rank <= 10)
        .map(token => token.symbol);
}

async function getTickerData(tickerList) {
    const response = await fetch('https://api.1inch.exchange/v3.0/137/tokens');
    const tokens = await response.json();
    const tokenList = Object.values(tokens.tokens);

    return tokenList.filter(token => tickerList.includes(token.symbol));
}

getTop10Tokens()
    .then(getTickerData)
    .then(console.log);

Hey @OzzieAl, hope you are well.

Could you also please share the html index file? that way i can replicate the issue and help you solve it :nerd_face:

Carlos Z

no worries here it is

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Moralis Dex</title>
    <!-- Moralis SDK code -->
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
    <script src="./dex.js"></script>
</head>
<body>
    <h1></h1>

    <button id="btn-login">Moralis Login</button>
    <button id="btn-logout">Logout</button>


    


    
</body>
</html>

The issue here is that in your html file you load your script tags at the head tag, while they should be before the end of the body tag, like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Moralis Dex</title>    
</head>
<body>
    <h1></h1>

    <button id="btn-login">Moralis Login</button>
    <button id="btn-logout">Logout</button>

    <!-- Moralis SDK code -->
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
    <script src="./dex.js"></script>
</body>
</html>

Hope this helps.

Carlos Z

1 Like

Great thank you will give it a go

All worked thankyou

1 Like

Hey @thecil,

I have a problem a little bit similar. I took the SDK to start on the dApp programming course but the metamask login does not work.
Can you help me please?

index.html file:

<<!DOCTYPE html>
<html>
  <head>
    <title>Vanilla Boilerplate</title>
    
  </head>

  <body>
    <h1>Moralis Hello World!</h1>

    <button id="btn-login">Moralis Metamask Login</button>
    <button id="btn-logout">Logout</button>

    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
    <script type="text/javascript" src="main.js"></script>
  </body>
</html>

main.js file:

/* Moralis init code */
const serverUrl = "https://tgvj9b2fzccq.usemoralis.com:2053/server";
const appId = "0LSCgoM8SLXscypNsGrPIOSauRrz06P1tvm4EwC4";
Moralis.start({ serverUrl, appId });

/* Authentication code */
async function login() {
    let user = Moralis.User.current();
    if (!user) {
      user = await Moralis.authenticate({
        signingMessage: "Log in using Moralis",
      })
        .then(function (user) {
          console.log("logged in user:", user);
          console.log(user.get("ethAddress"));
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  }
  
  async function logOut() {
    await Moralis.User.logOut();
    console.log("logged out");
  }
  
  document.getElementById("btn-login").onclick = login;
  document.getElementById("btn-logout").onclick = logOut;

server url & app ID come from the server I made.

thanks!

1 Like

Your code is working fine from my side, clicking on login will popup the metamask windows, check that your metamask is enable in your browser (advice to use chrome or brave browser)

Carlos Z

hey @thecil

After trying everything I found my mistake! I had to do npm install moralis and everything worked just fine!

Thanks for the help!!!

1 Like

@thecil
re: Building a DEX with Javascript course
Hi Carlos, I get my Metamask to work, but in the console I get a huge list of data, and cannot find the token information that the teacher gets. Maybe i need to use a particular type of fetch, or a filter of some kind.

Also, the teacher in the video uses an older version of docs.moralis.io, and seems to be using older versions of code. I will try to show you my Javascript (dex.js), and HTML for the project (the CSS seems to be deleted now).

<!DOCTYPE html>

   <html lang="en">

   <head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Web3Crypto.com</title>

   <!-- Moralis SDK code -->

    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>

    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>

  </head>

  <body>

    <h1>Gas Stats With Moralis</h1>

    <button id="btn-login">Moralis Login</button>

    <button id="btn-logout">Logout</button>

    <script>

      // connect to Moralis server

      const serverUrl = "https://wrykycbkyhqn.usemoralis.com:2053/server";

      const appId = "ToLsWq6sLCb9L61DdGeTHUuI9fzN1hVQjgYWLIFJ";

      Moralis.start({ serverUrl, appId });

      async function login() {

        let user = Moralis.User.current();

        if (!user) {

          user = await Moralis.authenticate();

        }

        console.log("logged in user:", user);

      }

      async function logout() {

        await Moralis.User.logOut();

        console.log("logged out");

      }

      document.getElementById("btn-login").addEventListener("click", login);

      document.getElementById("btn-logout").addEventListener("click", logout);

    </script>

  </body>

</html>
//connect to Moralis server

Moralis.initialize("ToLsWq6sLCb9L61DdGeTHUuI9fzN1hVQjgYWLIFJ");

Moralis.serverURL = "https://wrykycbkyhqn.usemoralis.com:2053/server";

// the course teacher seems to be using an older version of docs.moralis.io/, and he added

//the next 2 functions to dex.js.

// However, even without these 2 function, I was got the Metamask login, by just adding the HTML items

// provided in the current version of docs.Moralis.io (which only has HTML to copy and paste, for Metamask login)

async function login() {

    let user = Moralis.User.current();

    if (!user) {

        user = await Moralis.authenticate();

    }

    console.log("logged in user:", user);

    getStats();

}

async function getStats() {

    const balances = await Moralis.Web3API.account.getTokenBalances();

    console.log(balances);

}

async function logOut() {

    await Moralis.User.logOut();

    console.log("logged out");

}

document.getElementById("btn-login").onclick = login;

document.getElementById("btn-logout").onclick = logOut;

async function getTop10Tokens() {

    const response =  await fetch("https://api.coinpaprika.com/v1/coins");

    const tokens = await response.json();

    return tokens

            .filter(token => token.rank >= 1 && token.rank <= 10)

            .map(token => token.symbol);

}

async function getTickerData(tickerList) {

    const response = await fetch("https://api.1inch.exchange/v3.0/137/tokens");

    const tokens = await response.json();

    const tokenList = Object.values(tokens.tokens);

    return tokenList.filter(token => tickerList.includes(token.symbol));

}

function renderForm(tokens){

    const options = tokens.map(token =>

        `<option value="${token.decimals}-${token.address}">${token.name}(${token.symbol})</option>`);

   

    document.querySelector("[name=from-token]").innerHTML = options;

    document.querySelector("[name=to-token]").innerHTML = options;

    document.querySelector(".js-submit-quote").removeAttribute("disabled");

}

async function formSubmitted(event) {

    event.preventDefault();

    const fromToken = document.querySelector("[name=from-token]").value;

    const toToken = document.querySelector("[name=to-token]").value;

    const [fromDecimals, fromAddress] = fromToken.split("-");

    const [toDecimals, toAddress] = toToken.split("-");

    const fromUnit = 10 ** fromDecimals;

    const decimalRatio = 10 ** (fromDecimals - toDecimals);

    const url = `https://api.1inch.exchange/v3.0/1/quote?fromTokenAddress=${fromAddress}&toTokenAddress=${toAddress}&amount=${fromUnit}`;

    try {

        const response = await fetch(url);

        const quote = await response.json();

        const exchange_rate = Number(quote.toTokenAmount) / Number(quote.fromTokenAmount) * decimalRatio;

        documentQuerySelector(".js-quote-container").innerHTML = `

        <p>1 ${quote.fromToken.symbol} = ${exchange_rate} ${quote.toToken.symbol}</p>

        <p>Gasfee: ${quote.estimatedGas}</p>

        `;

    } catch(e) {

        document.querySelector(".js-quote-container").innerHTML = `The conversion didn't succeed.`;

    }

}

document

.querySelector("js-submit-quote")

.addEventListener("click", formSubmitted);

console.log(url);

getTop10Tokens()

    .then(getTickerData)

    .then(console.log);