Here are my Dex and HTML files for reference to help debug. Thanks!
“dex.js”
// Connect to Moralis server
const serverUrl = "https://bfj7efbtjvtt.usemoralis.com:2053/server";
const appId = "b3ejOczyFpDIqZ5KLOwkRq1koDEeggNh5BE7NT0W";
Moralis.start({serverUrl, appId});
//Moralis.initialize("b3ejOczyFpDIqZ5KLOwkRq1koDEeggNh5BE7NT0W");
//Moralis.serverURL = "https://bfj7efbtjvtt.usemoralis.com:2053/server";
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);
// Login to Metamask
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.value = '';
document.querySelector('.js-submit').removeAttribute('disabled');
document.querySelector('.js-cancel').removeAttribute('disabled');
document.querySelector('.js-amount-error').innerHTML = '';
}
async function getStats () {
const balances = await Moralis.Web3API.account.getTokenBalances();
console.log(balances);
const ethbalance = await Moralis.Web3API.account.getNativeBalance();
console.log(ethbalance.balance / (10 ** 18));
balances[0] = {
token_address: "0x0FA81C4A4f79024a22A054bF24C310654D9903A3",
name: "Ethereum",
symbol: "ETH",
logo: "",
thumbnail: "",
decimals: 18,
balance: ethbalance.balance
}
$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
.querySelector("#btn-buy-crypto")
.addEventListener('click', buyCrypto);
document.getElementById("btn-logout").addEventListener('click', logOut);
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.';
} else {
document.querySelector('.js-amount-error').innerText = '';
}
}
async function formCancelled(event) {
event.preventDefault();
document.querySelector('.js-submit').setAttribute('disabled', '');
document.querySelector('.js-cancel').setAttribute('disabled', '');
$amountInput.value = '';
$amountInput.setAttribute('disabled');
$amountInput.removeAttribute('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', formCancelled);
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 <= 50)
.map(token => token.symbol);
}
async function getTickerData(tickerList) {
const response = await fetch('https://api.1inch.exchange/v3.0/1/tokens');
const tokens = await response.json();
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);
“index.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>Moralis DEX</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" 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 id="btn-login">Moralis Login</button>
<button id="btn-buy-crypto">Buy Crypto</button>
<button 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="form-row">
<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="form-row">
<label>
Swap to:
<select name="to-token"></select>
</label>
</div>
<div class="form-row">
<button type="submit" class="js-submit" disabled>Get Quote</button>
<button class="js-cancel" disabled>Cancel</button>
</div>
<div class="js-quote-container"></div>
</form>
</div>
<!-- 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>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
<script src="./dex.js"></script>
</body>
</html>