Implement walletconnect

Hi everyone,
I hope to find some help with implementing walletconnect into my dapps. I somehow struggle to even import it into my js file. First, it wouldn’t let me use the import command because of module type missing, now it seems that this is working, but now it will not let me import the file from the dependencies. Im following the walletconnect documentation but struggle already at the import command.
I never had any issue implementing metamask, but other wallets are quite different. :thinking:
oh yeah, in case you wonder, node version 16.3.0
@Malik @dan-i do you guys have any advice on this?
I get error:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

Here is my code:

index.js
const web3 = new Web3(window.ethereum);
import WalletConnectProvider from "./node_modules/@walletconnect/web3-provider";


let wwt;
let wwtAddress = "0x05FFcc649ae21EaE089C860f09240000afE4867D";
let wwtBar;
let wwtBarAddress = "0x2128Abae635eDD0CA5E34fD22866535Cb27EfeA9";
let isStakeUI = true;
let accounts;
let user;
let userxWWTBalance;
let userWWTBalance;
let amountToStake;
let xWWTTotalSupply;
let WWTBalanceOfBar;
let WWTxWWTPair;

$(document).ready( () => {

    $("#btnConnectWallet").click((e) => {
        try {
            window.ethereum.enable();
        } catch (error) {
            if(!window.ethereum){
                alert("Please install Metamask!");
                window.open("http://metamask.com");
            }
            console.error(error);
        }
    })

    window.ethereum.on('accountsChanged', function (accounts) {
        location.reload();
      })

    if(window.ethereum){
        window.ethereum.enable().then( async () => {

            //getting contract Instances
            wwt = new web3.eth.Contract(tokenAbi, wwtAddress);
            wwtBar = new web3.eth.Contract(tokenBarAbi, wwtBarAddress);
            accounts = await ethereum.request({ method: 'eth_accounts' });
            user = accounts[0];
            xWWTTotalSupply = await wwtBar.methods.totalSupply().call();
            WWTBalanceOfBar = await wwt.methods.balanceOf(wwtBarAddress).call();
            console.log("TotalSupply xWWT", xWWTTotalSupply);
            console.log("WWTBAlofBar", WWTBalanceOfBar);
            WWTxWWTPair = WWTBalanceOfBar/xWWTTotalSupply;
            console.log(WWTxWWTPair.toFixed(3));
            $("#Pair").text(`1WWT = ${WWTxWWTPair.toFixed(3)} xWWT`);
            
            console.log("Token Methods", await wwt.methods);
            console.log("BarMethods", await wwtBar.methods);
            loadContractData();
            
            // //  Event Listeners WebSocket
            //     usdtSocket.events.Transfer({})
            //     .on('data', (event) => {
            //         to.push(event.returnValues.to);
            //         from.push(event.returnValues.from);
            //         values.push(event.returnValues.value);
            //        $("#toOut").text(to[to.length-1]);
            //        $("#fromOut").text(from[from.length-1]);
            //        $("#amountOut").text(values[values.length-1]);
                    
            //     })
            //     .on('error', (error) => {
            //         console.log(error);
            //     });
            })
            $("#btnApproveAmount").show();
            $("#btnStakeAmount").hide();
            toggleStakeUI();
        
          
            
            $("#btnStake").click((e) => {
                e.preventDefault();
                isStakeUI = true;
                toggleStakeUI();
            })
                
            $("#btnUnstake").click((e) => {
                e.preventDefault();
                isStakeUI = false;
                toggleStakeUI();
            })
        
            $("#btnApproveAmount").click( async (e) => {
                e.preventDefault();
                amountToStake = $("#amountToStake").val();
                if(amountToStake <= 0 || undefined){
                    alert("Please insert valid amount");
                } else {
                    amountToStake = web3.utils.toWei(amountToStake, "ether");
                }
                
                if(amountToStake <= 0){
                    alert("Please enter a valid amount");
                } else {
                        await wwt.methods.approve(wwtBarAddress, amountToStake).send({from: user})
                        .on('confirmation', (confirmationNumber, receipt) => {
                            $("#btnApproveAmount").hide();
                            $("#btnStakeAmount").show();
                        })
                        .on('error', (error) => {
                            alert(error.message);
                        }) 
                }
                
            })

            $("#btnStakeAmount").click( async (e) => {
                e.preventDefault();
                amountToStake = $("#amountToStake").val();
                console.log("ATS", web3.utils.toWei(amountToStake, "ether"));
                if(amountToStake <= 0){
                    alert("Please enter a valid amount");
                } else {
                    amountToStake = web3.utils.toWei(amountToStake, "ether");
                        await wwtBar.methods.enter(amountToStake).send({from: user})
                        .on('confirmation', (confirmationNumber, receipt) => {
                            $("#btnStakeAmount").hide();
                            $("#btnApproveAmount").show();
                            location.reload();
                        })
                        .on('error', (error) => {
                            alert(error.message);
                        })
                }
            })
        
            $("#btnUnstakeAmount").click( async (e) => {
                e.preventDefault();
                var amountToUnstake = $("#amountToUnstake").val();
                amountToUnstake = web3.utils.toWei(amountToUnstake, "ether");
                if(amountToUnstake <= 0){
                    alert("Please enter a valid amount");
                } else {
                    try {
                        await wwtBar.methods.leave(amountToUnstake).send({from: user});
                        location.reload();
                    } catch (error) {
                        console.error(error);
                        alert("There was an error! Please check console for more information!");
                    }
                }
               
            })
              } else {
                alert("Please install MetaMask");
                window.open("http://metamask.com");
            }
    
    $("#btnAddTokenToWallet").click( async (event) => {
        event.preventDefault();
            await ethereum.request({
                method: 'wallet_watchAsset',
                params: {
                  type: 'ERC20',
                  options: {
                    address: wwtAddress,
                    symbol: 'WWT',
                    decimals: 18,
                    image: 'https://foo.io/token-image.svg',
                  },
                },
              });
        
    })

    $("#btnAddxTokenToWallet").click( async (event) => {
        event.preventDefault();
            await ethereum.request({
                method: 'wallet_watchAsset',
                params: {
                  type: 'ERC20',
                  options: {
                    address: wwtBarAddress,
                    symbol: 'xWWT',
                    decimals: 18,
                    image: 'https://foo.io/token-image.svg',
                  },
                },
              })
    })
   
})

loadContractData = async () => {
    userxWWTBalance = await wwtBar.methods.balanceOf(user).call();
    userWWTBalance = await wwt.methods.balanceOf(user).call();
    $("#xWWTBalance").text(web3.utils.fromWei(userxWWTBalance, "ether"));
    $("#WWTBalance").text(web3.utils.fromWei(userWWTBalance, "ether"));
} 

const toggleStakeUI = () => {
    if(isStakeUI === true){
        $("#stakeUI").show();
        $("#unstakeUI").hide();
    } else if (isStakeUI === false) {
        $("#stakeUI").hide();
        $("#unstakeUI").show();

    }
}



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">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <script src="web3.min.js"></script>
    <!-- Contract abis -->
    <script src="abiToken.js"></script>
    <script src="abi.js"></script>
    <script type="module" src="index.js"></script>
    <!-- CSS only -->

    <title>WWT Staking</title>
</head>
<body style="background-color: #333">
    <div class="d-sm-flex">
    <div class="container">
        <nav class="navbar navbar-dark text-light">
            <a class="navbar-brand" href="#">
              <img src="logoWWT.png" width="30" height="30" class="d-inline-block align-top" alt="">
              Welcome the the WWT Bar - the place to stake your WWT
            </a>
            <div class="row">
                <button class="btn btn-outline-success" id="btnConnectWallet">Connect Wallet</button>
                <button class="btn btn-outline-success" id="btnAddTokenToWallet">Add WWT To Wallet</button>
                <button class="btn btn-outline-success" id="btnAddxTokenToWallet">Add xWWT To Wallet</button>
            </div>
          
          </nav>
        <div class="row">
          <div class="col">
            <div class="card my-3 bg-dark text-light">
                <div class="card-body">
                    <div class="card-header bg-dark text-light">
                        Maximize Yield by staking WWT
                      </div>
                   <p id="name" style="font-size: 12px;">For every swap on the exchange on every chain, 0.05% of the swap fees are distributed as WWT proportional to your share of the WWTBar. When your WWT is staked into the WWTBar, you recieve xWWT in return for voting rights and a fully composable token that can interact with other protocols. Your xWWT is continuously compounding, when you unstake you will receive all the originally deposited WWT and any additional from fees.
                </p>
                </div>
              </div>
          </div>
          <div class="col">
              <img src="logoWWT.png" style="width: 200px; border-radius: 25%;">
          </div>
        </div>
        <div class="row">
            <div class="col-6">
                <div class="card bg-dark text-light" style="border-color: #fff">
                    <div class="card-body">
                        <div class="row">
                            <div class="card bg-dark text-light" style="border-color: #fff">
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col">
                                            <strong>Staking APR</strong>
                                        </div>
                                        <div class="col">
                                            <strong>6.53%</strong>
                                        </div>
                                    </div>
                                    <div class="row">
                                       <div class="col">
                                           <button class="btn btn-outline-primary btn-sm">View Stats</button>
                                       </div> 
                                       <div class="col">
                                        <small>Yesterdays APR</small>
                                       </div>
                                    </div>
                   
                                </div>
                              </div>
                            <div class="card my-3 bg-dark text-light" style="border-color: #fff">
                                <div>
                                    <div class="row">
                                        <div class="col-6">
                                            <button type="submit" class="btn btn-primary" id="btnStake" style="width: 100%; margin-top: 10px;">Stake</button>
                                        </div>
                                        <div class="col-6">   
                                            <button type="submit" class="btn btn-primary" id="btnUnstake" style="width: 100%; margin-top: 10px;">Unstake</button>
                                        </div>
                                    </div>
                                    
                                    
                                </div>
                               
                                <div class="card-body">
                                    
                                    <div id="stakeUI">
                                        <div class="row">
                                            <div class="col">
                                                <p>Stake WWT</p>
                                            </div>
                                            <div class="col">
                                                <p id="Pair"></p>
                                            </div>
                                        </div>
                                        <input type="number" id="amountToStake" placeholder="WWT" style="width: 100%; border-radius: 5px" required/>
                                        <button type="submit" class="btn btn-primary" id="btnApproveAmount" style="margin-bottom: 10px; width: 100%">Approve Amount</button>
                                        <button type="submit" class="btn btn-primary" id="btnStakeAmount" style="margin-bottom: 10px; width: 100%">Stake Amount</button>
                                    </div>
                                    <div id="unstakeUI">
                                        <div class="row">
                                            <div class="col">
                                                <p>Stake WWT</p>
                                            </div>
                                            <div class="col">
                                                <p id="Pair"></p>
                                            </div>
                                        </div>
                                        <input type="number" id="amountToUnstake" placeholder="xWWT" style="width: 100%; border-radius: 5px" required/>
                                        <button type="submit" class="btn btn-primary" id="btnUnstakeAmount" style="margin-bottom: 10px;  width: 100%">Unstake Amount</button>
                                    </div>
                                    
                                </div>
                               

                              </div>
                        </div>
                    </div>
                </div>
               
             
            </div>
            <div class="col-2">
                <div class="card bg-dark text-light" style="border-color: #fff">
                  <div class="card-body">
                    <strong><p>Balance</p></strong>
                    <div class="row">
                        <div class="card bg-dark text-light" style="border-color: #fff">
                            <div class="card-body">
                               <strong><p id="xWWTBalance"></p></strong> 
                                <p>xWWT</p>
                            </div>
                        </div>
                       
                    </div>
                    <div class="row">
                        <div class="card bg-dark text-light" style="border-color: #fff">
                            <div class="card-body">
                                <strong><p id="WWTBalance"></p></strong>
                                <p>Unstaked</p>
                            </div>
                        </div>
                    </div>
                </div>  
                  
                   
                </div>
              
 
            </div>
          </div>
      </div>
    </div>
</body>
</html>

Hello I had this issue too.

For me, it came to the conclusion that normal JS doesn’t support import.
https://stackoverflow.com/questions/41662017/javascript-function-import-not-working

I think you need to have babel. I think your code will work if you use React.

Correct me if I am wrong :pray:

Or, if the npm package ships with .min.js similar to:

../node_modules/web3/dist/web3.min.js

You can import the min file to HTML like this:

<script src="../node_modules/web3/dist/web3.min.js"></script>

Hi Rego, thanks for replying.
Yes, I know React is the thing, and I am digging into it as much as I can :slight_smile: But still not there.
I found out how to do it with Vanilla JS. It actually really broadened my understanding of what happens when we work with HTML and JavaScript.
So here is the deal:
You can import any JS-file in your HTML and BOOM! it will be available for you in the window property. I know…right? This is so obvious, but I never heard any instructor telling me that.
So, after doing that, I could just say:

const Whatever = window.TheImportedScript.default;

Cheez! no need to use import or require… it can be as simple as that.
So it worked for me with using min.js files served from unpkg.com, putting them into the window object and read the default export inside the javascript file.

:nerd_face:

1 Like

Thank you for the detailed reply.

Midnight here, I will try it out tomorrow!
So when you import JS-file in the HTML, you used unpkg?

1 Like
JS
const Web3Modal = window.Web3Modal.default;
const WalletConnectProvider = window.WalletConnectProvider.default;
const Fortmatic = window.Fortmatic;
const evmChains = window.evmChains;

HTMLHead
<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">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">
    <script src="web3.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/index.js"></script>
    <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/umd/index.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/@walletconnect/[email protected]/dist/umd/index.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/[email protected]/dist/fortmatic.js"></script>
    <!-- Contract abis -->
    <script src="abiToken.js"></script>
    <script src="abi.js"></script>
    <script src="index.js"></script>
    <!-- CSS only -->

    <title>WWT Staking</title>
</head>
2 Likes