Swap Issues encountered for Dex?

Dear all, I have followed exactly Flip’s tutorial on youtube on how to build a DEX How to Create a DEX Like Uniswap FULL COURSE - YouTube]. I have followed exactly the steps and the code. However after replacing the new init syntax

Moralis.start({ serverUrl: “https://a1zxiyoi7jle.moralishost.com:2053/server”, appId: “LtCAPag9Kl1f9oOtxJ5jr7xV9KbuBJbSklemDqvK” });

I have replaced it with my own moralis server and appID.

I encounter an issue when i click on swap it pops up a message says “Swap Complete” . where could i have gone wrong?

Code as follows

let currentTrade = {};

let currentSelectSide;

let tokens;

async function init(){

await Moralis.initPlugins();

await Moralis.enable();

await listAvailableTokens();

currentUser = Moralis.User.current();

if(currentUser){

    document.getElementById("swap_button").disabled = false;

}

}

async function listAvailableTokens(){

tokens ={

    "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee":{

        "symbol":"BNB",

        "name":"BNB",

        "decimals": 18,

        "address":"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",

        "logoURI":"https://tokens.1inch.io/0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c.png",

         

        },

    "0x73d8Fd2a7e264b0c19cB981294C0cd11389Cc0b8":{

        "symbol":"SKIDDO",

        "name":"SKIDDO",

        "decimals": 9,

        "address":"0x73d8Fd2a7e264b0c19cB981294C0cd11389Cc0b8",

        "logoURI":"https://static.wixstatic.com/media/c1d670_ae9ca0fd367c4faa9d5caca280c917b7~mv2.png",

        },

        };

        let parent = document.getElementById("token_list");

        for( const address in tokens){

            let token = tokens[address];

            let div = document.createElement("div");

            div.setAttribute("data-address", address)

            div.className = "token_row";

            let html = `

            <img class="token_list_img" src="${token.logoURI}">

            <span class="token_list_text">${token.symbol}</span>

            `

            div.innerHTML = html;

            div.onclick = (() => {selectToken(address)});

            parent.appendChild(div);

        }

    }

   

    function selectToken(address){

        closeModal();

        console.log(tokens);

        currentTrade[currentSelectSide] = tokens[address];

        console.log(currentTrade);

        renderInterface();

        getQuote();

    }

   

    function renderInterface(){

        if(currentTrade.from){

            document.getElementById("from_token_img").src = currentTrade.from.logoURI;

            document.getElementById("from_token_text").innerHTML = currentTrade.from.symbol;

        }

        if(currentTrade.to){

            document.getElementById("to_token_img").src = currentTrade.to.logoURI;

            document.getElementById("to_token_text").innerHTML = currentTrade.to.symbol;

        }

    }

           

    async function login() {

        try {

            currentUser = Moralis.User.current();

            if(!currentUser){

                currentUser = await Moralis.authenticate();

            }

            document.getElementById("swap_button").disabled = false;

        } catch (error) {

            console.log(error);

        }

    }

   

    function openModal(side){

        currentSelectSide = side;

        document.getElementById("token_modal").style.display = "block";

    }

    function closeModal(){

        document.getElementById("token_modal").style.display = "none";

    }

   

    async function getQuote(){

        if(!currentTrade.from || !currentTrade.to || !document.getElementById("from_amount").value) return;

       

        let amount = Number(

            document.getElementById("from_amount").value * 10**currentTrade.from.decimals

        )

   

        const quote = await Moralis.Plugins.oneInch.quote({

            chain: 'bsc', // The blockchain you want to use (eth/bsc/polygon)

            fromTokenAddress: currentTrade.from.address, // The token you want to swap

            toTokenAddress: currentTrade.to.address, // The token you want to receive

            amount: amount,

        })

        console.log(quote);

        document.getElementById("gas_estimate").innerHTML = quote.estimatedGas;

        document.getElementById("to_amount").value = quote.toTokenAmount / (10**quote.toToken.decimals)

    }

   

    async function trySwap(){

        let address = Moralis.User.current().get("ethAddress");

        let amount = Number(

            document.getElementById("from_amount").value * 10**currentTrade.from.decimals

        )

        if(currentTrade.from.symbol !== "ETH"){

            allowance = await Moralis.Plugins.oneInch.hasAllowance({

                chain: 'bsc', // The blockchain you want to use (eth/bsc/polygon)

                fromTokenAddress: currentTrade.from.address, // The token you want to swap

                fromAddress: address, // Your wallet address

                amount: amount,

            })

            console.log(allowance);

            if(!allowance){

                await Moralis.Plugins.oneInch.approve({

                    chain: 'bsc', // The blockchain you want to use (eth/bsc/polygon)

                    tokenAddress: currentTrade.from.address, // The token you want to swap

                    fromAddress: address, // Your wallet address

                  });

            }

        }

        try {

            let receipt = await doSwap(address, amount);

            alert("Swap Complete");

       

        } catch (error) {

            console.log(error);

        }

   

    }

   

    function doSwap(userAddress, amount){

        return Moralis.Plugins.oneInch.swap({

            chain: 'bsc', // The blockchain you want to use (eth/bsc/polygon)

            fromTokenAddress: currentTrade.from.address, // The token you want to swap

            toTokenAddress: currentTrade.to.address, // The token you want to receive

            amount: amount,

            fromAddress: userAddress, // Your wallet address

            slippage: 15,

          });

    }

   

    init();

   

    document.getElementById("modal_close").onclick = closeModal;

    document.getElementById("from_token_select").onclick = (() => {openModal("from")});

    document.getElementById("to_token_select").onclick = (() => {openModal("to")});

    document.getElementById("login_button").onclick = login;

    document.getElementById("from_amount").onblur = getQuote;

    document.getElementById("swap_button").onclick = trySwap;

The message “swap complete” pops up although MetaMask did not pop up to confirm the transaction . And there was no transaction happened despite the “swap complete” message. Seems it has skipped the allowance function ? I am a very newbie in programming

Hey @iwong

Please send a formatted code. It’s really hard to read and compare the code :raised_hands:
Take a look at READ BEFORE POSTING - How to post code in the forum

Moralis.start({serverUrl:"https://xxxxxxxxxxxxxxx/server", appId:"xxxxxxxxxxxxxxxxxxxxxx"});

let currentTrade = {};

let currentSelectSide;

let tokens;

async function init(){

    await Moralis.initPlugins();

    await Moralis.enable();

    await listAvailableTokens();

    currentUser = Moralis.User.current();

    if(currentUser){

        document.getElementById("swap_button").disabled = false;

    }

}

async function listAvailableTokens(){

    tokens ={

        "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee":{

            "symbol":"BNB",

            "name":"BNB",

            "decimals": 18,

            "address":"0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",

            "logoURI":"https://tokens.1inch.io/0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c.png",

             

            },

        "0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82":{

            "symbol":"CAKE",

            "name":"CAKE",

            "decimals": 18,

            "address":"0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82",

            "logoURI":"https://tokens.1inch.io/0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82.png",

            },

            };

            let parent = document.getElementById("token_list");

            for( const address in tokens){

                let token = tokens[address];

                let div = document.createElement("div");

                div.setAttribute("data-address", address)

                div.className = "token_row";

                let html = `

                <img class="token_list_img" src="${token.logoURI}">

                <span class="token_list_text">${token.symbol}</span>

                `

                div.innerHTML = html;

                div.onclick = (() => {selectToken(address)});

                parent.appendChild(div);

            }

        }

       

        function selectToken(address){

            closeModal();

            console.log(tokens);

            currentTrade[currentSelectSide] = tokens[address];

            console.log(currentTrade);

            renderInterface();

            getQuote();

        }

       

        function renderInterface(){

            if(currentTrade.from){

                document.getElementById("from_token_img").src = currentTrade.from.logoURI;

                document.getElementById("from_token_text").innerHTML = currentTrade.from.symbol;

            }

            if(currentTrade.to){

                document.getElementById("to_token_img").src = currentTrade.to.logoURI;

                document.getElementById("to_token_text").innerHTML = currentTrade.to.symbol;

            }

        }

               

        async function login() {

            try {

                currentUser = Moralis.User.current();

                if(!currentUser){

                    currentUser = await Moralis.authenticate();

                }

                document.getElementById("swap_button").disabled = false;

            } catch (error) {

                console.log(error);

            }

        }

       

        function openModal(side){

            currentSelectSide = side;

            document.getElementById("token_modal").style.display = "block";

        }

        function closeModal(){

            document.getElementById("token_modal").style.display = "none";

        }

       

        async function getQuote(){

            if(!currentTrade.from || !currentTrade.to || !document.getElementById("from_amount").value) return;

           

            let amount = Number(

                document.getElementById("from_amount").value * 10**currentTrade.from.decimals

            )

       

            const quote = await Moralis.Plugins.oneInch.quote({

                chain: 'bsc', // The blockchain you want to use (eth/bsc/polygon)

                fromTokenAddress: currentTrade.from.address, // The token you want to swap

                toTokenAddress: currentTrade.to.address, // The token you want to receive

                amount: amount,

            })

            console.log(quote);

            document.getElementById("gas_estimate").innerHTML = quote.estimatedGas;

            document.getElementById("to_amount").value = quote.toTokenAmount / (10**quote.toToken.decimals)

        }

       

        async function trySwap(){

            let address = Moralis.User.current().get("ethAddress");

            let amount = Number(

                document.getElementById("from_amount").value * 10**currentTrade.from.decimals

            )

            if(currentTrade.from.symbol !== "ETH"){

                allowance = await Moralis.Plugins.oneInch.hasAllowance({

                    chain: 'bsc', // The blockchain you want to use (eth/bsc/polygon)

                    fromTokenAddress: currentTrade.from.address, // The token you want to swap

                    fromAddress: address, // Your wallet address

                    amount: amount,

                })

                console.log(allowance);

                if(!allowance){

                    await Moralis.Plugins.oneInch.approve({

                        chain: 'bsc', // The blockchain you want to use (eth/bsc/polygon)

                        tokenAddress: currentTrade.from.address, // The token you want to swap

                        fromAddress: address, // Your wallet address

                      });

                }

            }

            try {

                let receipt = await doSwap(address, amount);

                alert("Swap Complete");

           

            } catch (error) {

                console.log(error);

            }

       

        }

       

        function doSwap(userAddress, amount){

            return Moralis.Plugins.oneInch.swap({

                chain: 'bsc', // The blockchain you want to use (eth/bsc/polygon)

                fromTokenAddress: currentTrade.from.address, // The token you want to swap

                toTokenAddress: currentTrade.to.address, // The token you want to receive

                amount: amount,

                fromAddress: userAddress, // Your wallet address

                slippage: 15,

              });

        }

       

        init();

       

        document.getElementById("modal_close").onclick = closeModal;

        document.getElementById("from_token_select").onclick = (() => {openModal("from")});

        document.getElementById("to_token_select").onclick = (() => {openModal("to")});

        document.getElementById("login_button").onclick = login;

        document.getElementById("from_amount").onblur = getQuote;

        document.getElementById("swap_button").onclick = trySwap;

Hi sir formatted code below. The Moralis Server URL and AppId is been represented by xxxx… as i do not want to show my details.

Anyone can advise and help?

1 Like

Hey @iwong

The code from the tutorial works correctly. You can find it there https://github.com/MoralisWeb3/demo-apps (has updated syntax)

Make sure you have installed 1inch plugin to your server.

Please always provide your server url if you want to get help from us. It’s a publick info.

https://docs.moralis.io/misc/faq#my-moralis-app-id-is-publicly-visible-on-the-frontend.-is-this-a-security-risk

I kidnly ask you to send code next time without blank lines, it’s really hard to read and check the code :man_mechanic:

It shows you success message because Moralis.Plugins.oneInch.swap is a https request. It can run successfully, but will return you statuscode 400 in response message

Your code works for me correctly.

Sorry sir i will take note on sending the code without breaklines in between. I am still doing something wrong. When i switch to BNB to CAKE the following happens? No Metamask pop up instead “Swap Complete” pops up. There is a could not check spender allowance. I have tried with both ETH and BNB on this code but still does not solve the issue
if(currentTrade.from.symbol !== “BNB”){

The below is when i use if(currentTrade.from.symbol !== “BNB”){

There is no “could not check spender allowance” but the Swap completes still pops up skipping the metamask pop up confirmation. Also no transaction has happened

Hi Sir my server url is https://4yjda7y7rljv.moralishost.com:2053/server

Are there issues with the 1inch plugin? Am still stuck with the same issue above

It’s a problem on your side. Plugin works correctly

Sorry sir are you able to advise me where is the problem on my end? I have been trying to troubleshoot for hours

I can’t reproduce the issue

im having the same problem metamask wont pop up for swap only for sign in it pops up