Missing web3 instance with 1inch swap

Hi guys,
I’m about to finish the javascript course, but I find this error when I proceed to exchange 2 tokens with 1inch

moralis.js:7317 Uncaught (in promise) Error: Missing web3 instance, make sure to call Moralis.enableWeb3() or Moralis.authenticate()
    at Function.value (moralis.js:7317:48)
    at moralis.js:6553:41
    at tryCatch (moralis.js:73345:40)
    at Generator.invoke [as _invoke] (moralis.js:73576:22)
    at Generator.next (moralis.js:73401:21)
    at tryCatch (moralis.js:73345:40)
    at maybeInvokeDelegate (moralis.js:73639:18)
    at Generator.invoke [as _invoke] (moralis.js:73550:32)
    at Generator.next (moralis.js:73401:21)
    at asyncGeneratorStep (moralis.js:29991:24)

you can’t figure out where the error lies. I followed the tutorial and the guide… but nothing
below I put the 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">
    <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">
    <script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>

    <title>Portfolio&Dex</title>
</head>


<body>
    <header>
        <nav class="navbar navbar-light" style="background-color: #e3f2fd;">
            <!-- Navbar content -->


            <h1>Wallet and swap</h1>
            <div class="nav-button">
                <button class="btn btn-secondary" id="btn-buyCryto">Buy Crypto</button>
                <button class="btn btn-secondary" id="btn-login">Wallet connect</button>
                <button class="btn btn-secondary" id="btn-logout">Logout</button>
            </div>
        </nav>
    </header>
    <table class="table table-dark table-sm" id="js-lista-token-wallet">
        <thead class="table-dark">
            <td>
                #
            </td>
            <td>
                Token
            </td>
            <td>
                Amount
            </td>
            <td>
                Swap
            </td>
        </thead>
        <tbody id="body-tabella">
            ...
        </tbody>
        <tfoot>

        </tfoot>
    </table>

    <form action="post" class="swap">
        <div class="container">
            <div>
                <div class="form-floating">
                    <select class="form-select" id="js-coin-from" aria-label="">
                        <option selected>From</option>
                        <option value="18-0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee">MATIC ------->
                            0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee</option>)


                    </select>
                    <label for="floatingSelect">Sell</label>
                </div>
                <div class="input-group input-group-lg">
                    <span class="input-group-text" id="inputGroup-sizing-lg">Amount</span>
                    <input type="text" class="form-control" aria-label="Sizing example input"
                        aria-describedby="inputGroup-sizing-lg" id="js-value-from">
                </div>
            </div>
            <div>
                <div class="form-floating">
                    <select class="form-select" id="js-coin-to" aria-label="Floating label select example">
                        <option selected>To</option>
                        <option value="1">One</option>

                    </select>
                    <label for="floatingSelect">Buy</label>
                </div>
                <div class="input-group input-group-lg">
                    <span class="input-group-text" id="inputGroup-sizing-lg">Amount</span>
                    <input type="text" class="form-control" aria-label="Sizing example input"
                        aria-describedby="inputGroup-sizing-lg" id="js-value-to">
                </div>
            </div>
            <p class="css-information" id="js-p-gasfee"></p>
            <p class="css-information" id="js-p-router"></p>
            <button type="submit" class="btn btn-primary" id="js-submit-swap">Swap</button>
            <button class="btn btn-primary" id="js-clear-form">Clear</button>
        </div>

    </form>
    <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>

js.

/*COSTANTI DOM */
// tabella con la lista dell wallet
const $tabella = document.querySelector("#js-lista-token-wallet");
//selettori del form per lo swap.
const $list_coin_from = document.querySelector("#js-coin-from");
const $list_coin_to = document.querySelector("#js-coin-to");
// input box valori swap
const $value_from = document.querySelector("#js-value-from");
const $value_to = document.querySelector("#js-value-to");


/* INIZIAZIONE MORALIS SERVER */

const serverUrl = "*****************************";
const appId = "*******************************";
Moralis.start({ serverUrl, appId });

//const web3Provider = await Moralis.enableWeb3();


/*FUNZIONI */

const set_list_to = (coin_1inch) => {
    $list_coin_to.innerHTML = coin_1inch.map(token => `<option value="${token.decimals}-${token.address}">${token.symbol}  -------> ${token.address} </option>`);
}
const set_list_from = (event) => {
    const token = event.target.dataset;
    $list_coin_from.innerHTML = `<option value="${token.decimals}-${token.address}">${token.symbol}  -------> ${token.address} </option>`;
}


/*FUNZIONI ASINCRONE */
const Buy_Fiat = async () => { Moralis.Plugins.fiat.buy() }

const list_wallet = async () => {
    // funzione che scarica il contenuto del wallet durante il login
    const balances = await Moralis.Web3API.account.getTokenBalances({ chain: 'polygon' });
    console.log(balances);

    $tabella.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 type="button" class="btn btn-success" id="btn-swap"
                    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("");

    for (let $button_swap of $tabella.querySelectorAll("#btn-swap")) {
        // Swap crypto
        $button_swap.addEventListener("click", set_list_from)
    }


};

const coin_coinpaprika = async () => {
    //lista simboli token presi da coinpaprica
    const response = await fetch("https://api.coinpaprika.com/v1/coins");
    const coins = await response.json();
    const coin_list = Object.values(coins);

    return coin_list.filter(token => token.rank >= 1 && token.rank <= 300)
        .map(token => token.symbol);

}

const coin_1inch = async (coin_coinpaprika) => {
    //lista per lo swap filtrata con la top 300 di coinpaprika
    const response = await fetch("https://api.1inch.io/v4.0/137/tokens");
    const tokens = await response.json();
    const token_list = Object.values(tokens.tokens);

    return token_list.filter(token => coin_coinpaprika.includes(token.symbol));

}

const price = async (event) => {
    event.preventDefault();

    let token_from = $list_coin_from.value;
    let token_to = $list_coin_to.value;
    let amount_from = $value_from.value;
    let [decimal_from, address_from] = token_from.split("-");
    let [decimal_to, address_to] = token_to.split("-");
    let new_amount = amount_from * (10 ** decimal_from);
    console.log(new_amount);

    const Api = `https://api.1inch.io/v4.0/137/quote?fromTokenAddress=${address_from}&toTokenAddress=${address_to}&amount=${new_amount}`
    console.log(Api);
    const response = await fetch(Api);
    const quote = await response.json();

    const price = Number(quote.toTokenAmount);
    const router = Object.values(quote.protocols)
    console.log(router);

    $value_to.value = price / (10 ** decimal_to);

    const estimate_gas = Number(quote.estimatedGas);

    document.querySelector("#js-p-gasfee").innerHTML = `Estimate Gas fee => ${Moralis.Units.FromWei(estimate_gas)}`




    //document.querySelector("#js-p-router").innerHTML = router.map(token => `Router swap => ${token.name}`);





}

const clear = (event) => {
    event.preventDefault();
    $value_to.value = 0
    $value_from.value = 0;

}

async function login() {
    /*MORALIS LOGIN */
    let user = Moralis.User.current();
    if (!user) {
        user = await Moralis.authenticate();
    }
    console.log("logged in user:", user);
    list_wallet();
}

async function logOut() {
    /*MORALIS LOGIN */
    await Moralis.User.logOut();
    console.log("logged out");
    $tabella.innerHTML = `<table class="table table-dark table-sm" id="js-lista-token-wallet">
    <thead class="table-dark">
        <td>
            #
        </td>
        <td>
            Token
        </td>
        <td>
            Amount
        </td>
        <td>
            Swap
        </td>
    </thead>
    <tbody id="body-tabella">
        
    </tbody>
    <tfoot>

    </tfoot>
</table>`
}

/*AZIONI */
coin_coinpaprika()
    .then(coin_1inch)
    .then(set_list_to);


/*MORALIS LOGIN */
document.getElementById("btn-login").onclick = login;
document.getElementById("btn-logout").onclick = logOut;
/*BUY CRYPTOvsFiat*/
document.querySelector("#btn-buyCryto").addEventListener("click", Buy_Fiat);

// Aggiornamento form
$value_from.addEventListener("input", price);
$value_to.addEventListener("click", price);
$list_coin_from.addEventListener("click", price);
$list_coin_to.addEventListener("click", price);
document.querySelector("#js-clear-form").addEventListener("click", clear);



// swap 1inch 
const $swap = document.querySelector("#js-submit-swap");
$swap.addEventListener("click", swap)

async function swap(event) {
    event.preventDefault();
    let token_from = $list_coin_from.value;
    let token_to = $list_coin_to.value;
    let amount_from = $value_from.value;
    let [decimal_from, fromTokenAddress] = token_from.split("-");
    let [decimal_to, toTokenAddress] = token_to.split("-");
    let new_amount = amount_from * (10 ** decimal_from);


    const receipt = await Moralis.Plugins.oneInch.swap({
        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: new_amount,
        fromAddress: Moralis.User.current().get("ethAddress"), // Your wallet address
        slippage: 1,
    });
    console.log(receipt);
}


1 Like

Hey @LELUK911, hope you are well.

All I see in your code is that you are not initializing your web3 library, you can do it this way.
In code line 18 in dex.js, you need to enable web3 like this:

var web3Provider = async() => {
    return await Moralis.enableWeb3();
}
web3Provider();

Then the you should be able to swap through metamask.

Carlos Z

1 Like

hi @thecil thank for your help!

I had Resolved doing logout and login in the page every time. but thit solution is more funzionality.

1 Like