Section: Building a Dex (Final Assignment)

Here you can post questions, comments, answers regarding the final Dex project

1 Like

Hi @zsolt-nagy @thecil,

I completed the DEX project. However, I am running into issues which I have not been able to solve.

Here is the link to my Github repo: https://github.com/ren132710/mDex

  1. As requested in the last lesson, for Github, I tried hiding the Moralis serverUrl and appId variables. I am using an approach I saw recommended somewhere on this forum. I put the variables in a .env file and added require(‘dotenv’).config() to the top of the dex.js file. Unfortunately, I have not been able to get require to load properly. I am getting ‘ReferenceError: require is not defined’. (Note: I npm installed dotenv and my .env file is in the root directory.)

Here is a screenshot of the error:

  1. The Moralis.Plugins.oneInch.getSupportedTokens call regularly fails with “TypeError: Cannot read properties of undefined (reading getSupportedTokens)”. I think there is something wrong with the async process, but I don’t see where. Right now, my only work around is to keep saving the dex.js file until the call finally works. See screen shot:

I would love to understand and solve these issues so any help would be greatly appreciated. Thanks!

2 Likes

dotenv is a module from nodejs, but you app is not initialized by nodejs. so might be that why is not recognizing the module.

You can try follow this guide to execute your website with a live server module than later should execute all node modules (like dotenv).
https://dev.to/sanfra1407/how-to-use-env-file-in-javascript-applications-with-webpack-18df

Carlos Z

1 Like

OK, thanks for the link, @thecil. I read the article and tried the solution but that resulted in a new class of errors, don’t think it’s wise to do down that rabbit hole right now. So I backed out the dotenv code and will keep Moralis server credentials visible in the code for now.

Hi @zsolt-nagy @thecil,

Link to repo: https://github.com/ren132710/mDex

The Moralis.Plugins.oneInch.getSupportedTokens call regularly fails with “TypeError: Cannot read properties of undefined (reading getSupportedTokens)”.

I think there is something wrong with the async process, but I don’t see where. Right now, my only work around is to keep saving the dex.js file until the call finally works. See screen shot:

Any thoughts? Thanks!

1 Like

The function fetchTopTokenInfo triggers getSupportedTokens, the problem here is that the plugin is not initialized first.

You can try:

Moralis.initPlugins()
.then(() =>
{
console.log('Plugins have been initialized')
fetchTopTickers()
.then((tickers)=>fetchTopTokenInfo(tickers))
.then((tokens) => renderToTokenList(tokens))
})

Carlos Z

1 Like

@thecil…hey, that solved it. Thank you!

Hey the tutorials are really advanced for me i have trouble following, do you guys have any idea of others tutorials that are slower ?

1 Like

Hey, I felt the same in the beginning…In addition to w3schools and MDN, I spent a lot of time on the Web Dev Simplified youtube channel to supplement this course.

I used this/Zsolt’s course as a guide for what I needed to learn, and then spent many hours digging deeper online…it’s worth it…eventually it all starts to come together…and then it’s onward to React. Haha :slight_smile:

PS: Oh, and I highly recommend installing the Quokka.js extension in VSCode. The extension displays in real-time the values of your variables right in the js file as you are typing and experimenting. I wish I had discovered this extension sooner.

Here is a screen shot of Quokka while exploring different Array methods. Quokka displays the return values in light blue, including the execution duration, in real-time in the .js file. Pretty useful way to explore javascript features.

1 Like

Thanks a lot i will look into that !

1 Like

Hi, I am on the Asynchronous Programming part API. Using different APIs. Also from different computers. But none of them works for me. Can you help me? I have watched the videos but I don’t know if I am doing something wrong. Thanks

Hello guys, I’m building a DEX in Javascript course and I’m getting error:

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)
at dex.js:86:5

Plus if I want to get top 10 tokens, it is pending… It doesn’t give me anything.

Could you please assist me with issue?

Thank you. Martina

1 Like

Can you please share your dex.js file in the following way?

Carlos Z

1 Like

I have continued, but still showing me errors like this, plus I can’t somehow get top 10 tokens or 50.

If I log in with metamask, it is showing me array:0, even if I change it for ‘eth’, so basically if it is 0, I can’t see swap buttons etc…

error1:
Refused to apply style from ‘http://127.0.0.1:5500/#styledex.css’ because its MIME type (‘text/html’) is not a supported stylesheet MIME type, and strict MIME checking is enabled.

error2:
Failed to load resource: the server responded with a status of 404 (Not Found)

code:

// connect to Moralis server

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

 const appId = "Gc8VjQmyuCv29buPmkjWr0CJPmZoqoVgQEiIY0Fs";

 Moralis.start({ serverUrl, appId });

 Moralis

   .initPlugins()

   .then(() => console.log('Plugins has 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();

       }

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

    getStats();

   }

   

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 = '';

       document.querySelector('.js-submit').removeAttribute('disabled');

       document.querySelector('.js-cancel').removeAttribute('disabled');

       document.querySelector('.js-quote-container').innerHTML = '';

    }

   

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

                     class="js-swap"

                     data-address="${token.token_address}"

                     data-symbol="${token.symbol}"

                     data-decimals="${token.decimals}"

                     data-max="${tokenValue(token.balance, token.decimals)}"

                  >

                     Swap

                  </button>

               </td>

            </tr>

       `).join('');

       for(let $btn of $tokenBalanceTBody.querySelectorAll('.js-swap')) {

           $btn.addEventListener('click', initSwapForm);}

       }

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.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 <=30)

        .map(token => token.symbol);

}

async function getTickerData(tickerList) {

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

    const tokens = await response.json();

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

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

}

function renderDropdown(tokens) {

    const options = tokens.map(token => `

    <option value="${token.address}-${token.decimals}">

      ${token.name}

    </option>

   

    `).join('');

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

}

 getTop10Tokens()

   .then(getTickerData)

   .then(renderDropdown);

I am doing the login part of DEX with metamask. When I run the code, Below one is showing.

dex.html

<!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>Ali Swap</title>
</head>
<body>
    <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>

dex.js

const serverUrl = "https://crixzoshpewy.usemoralis.com:2053/server";
const appId = "KxHpYcmCSmieEL6vUl4C4vvdI9su0aSMciz6NmBg";
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.querySelector("#btn-logout").addEventListener('click', logOut);

async function getTop10Tokens(){
    try{
        let response = await fetch('https://api.coinpaprika.com/v1/coins');
        let tokens = await response.json();
        listItems = tokens.filter(x => x.rank > 0 && x.rank <=10).map(x => x.symbol);
        return listItems;
        //document.body.innerHTML = `<ol>${listItems.join('')}</ol>`
    } catch(e){
        console.log(`Error: ${e}`)
    }
}

async function getTickerAddress(tickerList){
    try{
        let response = await fetch('https://api.1inch.exchange/v3.0/137/tokens');
        let tokens = await response.json();
        let tokenList = Object.values(tokens.tokens);
        return tokenList.filter(x => tickerList.includes(x.symbol));
    }catch(e){
        console.log(`Error : ${e}`);}
}


Can someone help me to resolve this problem?

2 Likes

I have just copy/paste your code, run it with live server from visual code and it does work well from my side, i was able to sign with my account too.

You might want to try to run it again, let me know if it works.

Carlos Z

1 Like

I am using Bravo browser. Let me try with chrome @thecil

1 Like

I am getting same error. I am kind of stuck here.

seems this url is not getting connected.

2 Likes

You should not be able to go into that URL, your server is protected from that kind of requests, what you should do is to open you index.html with the visual code live server. Then it should work properly like my image

Carlos Z

1 Like

Still am getting the same error as shown in the my first post

1 Like