Congratulations on completing!

We know how much effort completing this course required. But now you have made a big step on your way to becoming a sought-after blockchain developer. BIG congratulations! :beers: :partying_face:

If you want to share or ask anything regarding the course do so below. :raised_hands:

Best of luck on your path!

1 Like

hello

i completed the course but i dont understand why my wallet balances arnt showing in the dex could you please give me advice on how too fix this

this is my current 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">


        <!-- Moralis SDK code -->

        <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
        <script src="https://unpkg.com/moralis@latest/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>

// connect to Moralis server

const serverUrl = "";
const appId = "";
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() {

  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.getElementById("btn-login").onclick = login;
document.getElementById("btn-buy-crypto").onclick =buycrypto;
document.getElementById("btn-logout").onclick = 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;

}



getTop10Tokens()
    .then(getTickerData)
    .then(renderTokenDropDown)
 .error {
    color: red;
}

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

.btn-sm {
    margin: 10px
}

i have no idea what is wrong

1 Like

hey can u share your githib code and i will clone and have a look. i seeen your post in the other forum. please share and we wiill get this sorted

Hi!
I want to make online blockchain services soon. I have a domain, Web3Crypto. com, and I want to have a DEX and NFT market with the site that I build on that domain. Can I use the DEX we made in this course? Do I need special permission, etc.? I can also send a copy of this message to my Moralis counselor. There are some online blockchain projects that I want to start this month.
Sincerely,
Aaron

Sorry I’m not sure what you mean, like doing a web app for them?

Carlos Z

You might need to host your project in a server, hosting your own server and configuring it can be a complicate process, so you can use a hosting service like:

https://vercel.com/docs?redirected=1
https://www.netlify.com/

You might be able to find videos on youtube for how to use this platforms.

Carlos Z

1 Like

@thecil
Hi Carlos,
I am studying parts of the ETH DEX course again. I noticed that there are 2 Github pages with code for that DEX: 1. a page which you made, which has dex.js,index.html, and style.css. To me these seem like files for the page that displays the DEX.
and 2. A page that Fillip made, which has the .sols files, etc.
I will soon deploy the ETH DEX, and I wonder what I should do. I can use the code on FIllip’s Github page, and follow his video for deploying the DEX. But should I also use the files on your Github page for the DEX? And if so, ow should I deploy and use them?

1 Like

I already replied to you here:

Carlos Z

1 Like

Hi Carlos! Thank you for answering my question. :smiley:

Hi Carlos!
I am studying the last part of Solidity 201, and deploying the DEX. This course video is outdated, and there should be some explanation of what to do. Filip uses Moralis Speedy Node, but this service has changed, and now seems to be called “Web 3 APIs”. I am not sure which api to use for the DEX. There are a range to choose from, including: NFT API, Token API, Balance API, Transaction API, Events API, Block API, Resolve API, DeFi API

There is also an EVM api, and an authentication api, which is confusing, since I assume that both of these api would be correct for the DEX.

What API should I choose for deploying the DEX, and where is it located?

Best regards,
Aaron

1 Like

Take a look at this little guide I made for that, instead of using a moralis speedy node (deprecated), you can use any other node provider and continue the course.

Carlos Z

The problem has been solved! The import connection for Safemath was version 3, but version 4 seems to be required for deploying the contract. Anyway, using and importing the latest version worked. Now I want to connect the deployed smart contract to a website, using a url. And I want to try it with matemask, etc. Do know how to do this? :smiley:

1 Like

OK. I set up a node Goerli, etc. More action than that was needed to deploy the contracts. Anyway, the deployment problem has been solved! The import connection for Safemath was version 3, but version 4 seems to be required for deploying the contract. Now I want to connect the deployed smart contract to a website, using a url. And I want to try it with matemask, etc. I am hoping for a vast way to do this action, as soon as possible, for example using a template. (I plan to study JavaScript more, and maybe React, but it would be good, this week, to make a simple version of a dapp connected to a website. Do know how to do this?

1 Like

You should check the Build an NFT Markpetplace course, which will teach you how to create a dapp using html/js.

The simplest way is to create a dapp using HTML/CSS and ethers.js instead of web3.js.

You can read more about ethers on their docs.
https://docs.ethers.org/v5/

Carlos Z

Hi Carlos,

Thank you!

1 Like

I made a DEX with Alchemy’s Road to Web 3 tutorial. Some of the code is from Moralis. The DEX mostly worked, when I tested it locally on my browser, with Visual Studio Code and Live Server. However, I put the DEX on my website, and it is not working now. I tested some of the URLs in the HTML file for the DEX, putting them in my browser and seeing where they went. The URL for Moralis, https://unpkg.com/moralis/dist/moralis.js did not work . What is the correct URL that Moralis uses?