Here you can post questions, comments, answers regarding the final Dex project
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
- 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:
- 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!
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
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!
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
Hey the tutorials are really advanced for me i have trouble following, do you guys have any idea of others tutorials that are slower ?
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
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.
Thanks a lot i will look into that !
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
Can you please share your dex.js
file in the following way?
Carlos Z
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?
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
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
Still am getting the same error as shown in the my first post