Building a DEX - Metamask Balances (keep getting an error)

Hey moralis brothers,
Since im in the academy is started learning JS from scretch and i learnd a lot so far!!!
but in this case i really cant figuer out what im doing wrong maybe one of you guys can help me with that. Much love to all of ya for hellping upfront!
Two things:

  1. my Array is still empty even if i got some coins on my Metamask.
  2. I keep continuesly getting that error and i cant figure out why:

Here is my code:

<!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>BTMC DEX</title>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
</head>
<body>
    <h1>BTMC-Swap</h1>
    <button id="btn-login">Moralis Metamask Login</button>
    <button id="btn-logout">Logout</button>

    <script type="text/javascript" src="./main.js"></script>


    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Symbol</th>
                <th>Amount</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody class="js-token-balances">
            
        </tbody>
    </table>
</body>
</html>

and here my js:

/* Moralis init code */
const serverUrl = "YYYYYYYYYYYYYYYYYYYYYYYYYYYY";
const appId = "XXXXXXXXXXXXXXXXXXXXXXXXXX";
Moralis.start({ serverUrl, appId });

const $tokenBalanceTBody = document.querySelector('.js-token-balances')

const tokenValue = (value, decimals) =>
    (decimals ? value / Math.pow(10, decimals) : value);

/* 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);
          getStats();
          console.log(user.get("ethAddress"));
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  }

  async function getStats() {
    const balances = await Moralis.Web3API.account.getTokenBalances({chain: 'polygon'});
    console.log(balances);
    $tokenBalanceTBody.innerHTML = balances.map( (token, index) => `
        <tr>
            <td>${index + 1}</td>
            <td>${token.symbol}</td>
            <td>${tokenValue(token.balance, token.decimals)}</td>
            <td>button</td>
        </tr>
        `).join('');
  }


  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.io/v4.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);

// you don’t need to use .then if are using await. 
async function login() {
  let user = Moralis.User.current();
  if (!user) {
    user = await Moralis.authenticate();
    console.log("user eth", user.get("ethAddress"));
  }
  console.log("logged in user:", user);
  await  getStats();
}

if your balance is in eth chain not in polygon the balance will return empty to avoid that.

//change the chain 
const balances = await Moralis.Web3API.account.getTokenBalances({
    chain: "eth",
  });

Hi Everybody!

I’m trying to login on metamask but appears these problems.

error

Hope someone can help me with that !!

Could you share your code in the following way?

Carlos Z

Hi !

I found on the web that my problem was this trying to connect to Moralis server because I omitted the "Moralis.start({serverUrl, appId})"; part.

server-Moralis

Thank you very much for your answer anyway. :slightly_smiling_face:

1 Like