Token balances not showing in javascript dex project

hello everyone

im really truly frusted.

i followed the course exactly andi have coins in my metamask. but the code says my balance is blank nothing is showing in my dex

this is the code

// connect to Moralis server

const serverUrl = "https://hzgprsd3s1da.usemoralis.com:2053/server";
const appId = "YwMvfUyGm50mRIrKsXsWCwlkPjQxji5zCuVNP3xe";
Moralis.start({ serverUrl, appId });

Moralis.initPlugins().then(console.log('Plugins have been initialized'))

const $tokenBalanceTBody = document.querySelector(".js-token-balances");
const $selectedToken = document.querySelector('.js-from-token');
const $amountInput = document.querySelector('.js-from-amount')



//Converting  from wei  using custom function 
const tokenValue = (value, decimals) => (decimals ? value / Math.pow(10, decimals): value);

// add from here down
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);
          });
  }
  getStats()
}





async function getStats() {

  await Moralis.enableWeb3();
  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>${Moralis.Units.FromWei(token.balance, token.decimals)}</td>
      <td>
          <button
          class="js-swap btn btn-success"
              data-address="${token.token_address}"
              data-symbol="${token.symbol}"
              data-decimals="${token.decimals}"
              data-max="${Moralis.Units.FromWei(token.balance, token.decimals)}"
          >
          Swap
          </button>
      </td>
  </tr>
`).join('');

}


async function initSwapForm(event) {
  event.preventDefault();
  $selectedToken.innerText = event.target.dataset.symbol;
  $selectedToken.dataset.address = event.target.dataset.address;
  $selectedToken.dataset.decimals = event.target.dataset.decimals;
  $selectedToken.dataset.max = event.target.dataset.max;
  $amountInput.removeAttribute('disabled');
  $amountInput.value = '';
  document.querySelector('.js-submit').removeAttribute('disabled');
  document.querySelector('.js-cancel').removeAttribute('disabled');
  document.querySelector('.js-quote-container').innerHTML = '';
  document.querySelector('.js-amount-error').innerText = ''
}



for ( let $btn of  $tokenBalanceTBody.querySelectorAll('js-initSwapForm')) {
$btn.addEventListener('click',swap);

}


async function buyCrypto() {
  Moralis.Plugins.fiat.buy()
}

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


document.querySelector("#btn-login").addEventListener('click', login)
document.getElementById("btn-buy-crypto").addEventListener('click', buyCrypto)
document.querySelector("#btn-logout").addEventListener('click', logOut)





/** Quote / Swap  */
async function formSubmitted(event) {
  event.preventDefault()
  const fromAmount = Number.parseFloat($amountInput.value);
  const fromMaxValue = Number.parseFloat($selectedToken.dataset.max);
  if (Number.isNaN(fromAmount) || fromAmount > fromMaxValue) {
      //invalid input
      document.querySelector('.js-amount-error').innerText = 'Invalid Amount'
      return
  } else {
    document.querySelector('.js-amount-error').innerText = ''
  }
  // submission of the quote request
  const fromDecimals = $selectedToken.dataset.decimals;
  const fromTokenAddress = $selectedToken.dataset.address;

  const [toTokenAddress, toDecimals] = document.querySelector('[name=to-token]').value.split('-');

  try {
      const quote = await Moralis.Plugins.oneInch.quote({
          chain: 'polygon', // The blockchain you want to use (eth/bsc/polygon)
          fromTokenAddress, // The token you want to swap
          toTokenAddress, // The token you want to receive
          amount: Moralis.Units.Token(fromAmount, fromDecimals).toString(),
      });

      const toAmount = Moralis.Units.FromWei(quote.toTokenAmount, toDecimals)
        document.querySelector('.js-quote-container').innerHTML = `
        <p>
        ${fromAmount} ${quote.fromToken.symbol} = ${toAmount} ${quote.toToken.symbol}
        </p>
        <p> Gas fee: ${quote.estimatedGas} </p>
    `;
    } catch (e) {
        document.querySelector('.js-quote-container').innerHTML = `
            <p class="error">The conversion didn't succed.</p>
        `;
    }
}



async function formCanceled(event){
  event.preventDefault()
  document.querySelector('.js-submit').setAttribute('disabled', '');
  document.querySelector('.js-cancel').setAttribute('disabled', '');
  $amountInput.value = '';
  $amountInput.setAttribute('disabled', '');
  delete $selectedToken.dataset.address;
  delete $selectedToken.dataset.decimals;
  delete $selectedToken.dataset.max;
  document.querySelector('.js-quote-container').innerHTML = '';
  document.querySelector('.js-amount-error').innerText = ''
}


document.querySelector('.js-submit').addEventListener('click', formSubmitted)
document.querySelector('.js-cancel').addEventListener('click', formCanceled)


/** to token dropdown preparation */


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 tokens = await Moralis.Plugins.oneInch.getSupportedTokens({
      chain: 'polygon', // The blockchain you want to use (eth/bsc/polygon)
  });
  console.log(tokens)
  const tokenList = Object.values(tokens.tokens);

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




function renderTokenDropDown(tokens) {
  const options = tokens.map(token => `
  <option value="${token.address}-${token.decimals}">
      ${token.name}
  </option>
  `).join('');
  document.querySelector('[name=to-token]').innerHTML = options;

}



/* Check if user is connected, IF true, execute stats */
function isUserConnected() {
  let user = Moralis.User.current();
  if (user) {
      getStats();
  }
}

isUserConnected()



getTop10Tokens()
    .then(getTickerData)
    .then(renderTokenDropDown)

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="shortcut icon" href="#">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">


        <!-- Moralis SDK code -->

        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
        <script src="https://unpkg.com/moralis/dist/moralis.js"></script>

        <title>Moralis Dex </title>
        <!-- CSS only -->
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
        <link rel="stylesheet" href="style.css">

</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-12 col-md-6">
                <h1>MoralisSwap</h1>
            </div>
            <div class="col-12 col-md-6 d-flex align-items-center justify-content-md-center">
                <button class="btn btn-success btn-sm" id="btn-login">Moralis login</button>
                <button class="btn btn-success btn-sm" id="btn-buy-crypto">Buy Crypto</button>
                <button class="btn btn-danger btn-sm" id="btn-logout">Logout</button>
            </div>
        </div>


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



    
    <form action="#" method="POST" class="exchange-form">
        <div class="row">
            <div class="col-12 col-md-6 mb-2">
                <label>
                    <span class="js-from-token"></span>
                    Amount:
                    <input type="text" name="from-amount" class="js-from-amount" disabled>
                </label>
                <div class="js-amount-error error"></div>
            </div>


        <div class="col-12 col-md-6">
            <label>
                Swap to:
                <select name="to-token"></select>
            </label>
        </div>

    </div>

        <div class="row">
            <div class="col">
                <button type="submit" class="js-submit btn btn-success  btn-sm" disabled > Get Qoute</button>
                <button class="js-cancel btn btn-warning btn-sm" disabled > Cancel</button>
        </div>
        <div class="js-qoute-container"></div>
        
    </form>



    <!-- JavaScript Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
    <script src="./dex.js"></script>

</body>
</html>
.error {
    color: red;
}

body {
    background-color: black;
    color:whitesmoke;
}

.btn-sm {
    margin: 10px
}

i followed the tutorial exactly and i even compared the final project code too mine and my balances arnt showing no matter what i do.

can anyone point out what im doing wrong"

2 Likes

Hey @Jeremiah, hope you are great.

I have just copy/paste your project and run it on my side, after login, it successfully get all the tokens i have with my address, are you sure that your address does have any token within it?

Carlos Z

hey can you share the code to your repository. i will have a look for you

ahahah @thecil to the rescue. your in good hands @Jeremiah

2 Likes

@thecil thank you for taking time too reply too me

i have eth in my wallet. i dont think this project can detect eth. im not really sure

this is my current github repository for this project

https://github.com/ghostoftheshell/moralis-crypto-dex-project

yes. ive also seen @thecil replies too alot of people. im supper grateful he replied. he has alot of knowledge

You are specifying to fetch your tokens from the polygon network, if you dont have any, the function will return an empty array.

await Moralis.Web3API.account.getTokenBalances({ chain: 'polygon' });

If you delete the option { chain: 'polygon' }, it will fetch the tokens from the ethereum network, and if your wallet have any, will return an array of them.

Carlos Z

const balances = await Moralis.Web3API.account.getTokenBalances({ chain: ‘’ });

is this the way too do it?

1 Like

no just dont pass in anything. so this const balances = await Moralis.Web3API.account.getTokenBalances();

1 Like