VScode says "Property 'initialize' does not exist on type 'typeof" API Key Moralis [SOLVED]

wasn’t sure if this issue is related to the fact that I, too, have the warning “property web3api does not exist on typeof moralis ts(2339)” showing up in VSC

You have to add complete HTML and JS code to figure it out faster what would be the problem. You could be using an older version of Moralis SDK for example, latest one now is 0.0.45.



console.log('hello world');

// connection to Moralis Mainnet server
Moralis.initialize("UJurYwXbXkh4XU56MAPtPzKebxpzhiOc1YKtKrT6");
Moralis.serverURL = "https://ixnw6hipouw2.bigmoralis.com:2053/server";

// connect to Moralis Testnet server
// Moralis.initialize("bAS3EF7dwd0SosA18W6asFkHJoeg0LBMFZmcPK2p");
// Moralis.serverURL = "https://yhsppf8qokbr.grandmoralis.com:2053/server";

// TO DO : CHANGE WHEN LIVE
let homepage = "http://127.0.0.1:5500/index.html";

// logged in check
if (Moralis.User.current() == null && window.location.href != homepage) {
    document.querySelector('body').style.display = 'none';
    window.location.href = "index.html";
}

// login function 
login = async () => {
    await Moralis.Web3.authenticate().then(async function (user) {
        console.log('logged in');
        console.log(Moralis.User.current());
        user.set("name", document.getElementById('user-username').value);
        user.set("email", document.getElementById('user-email').value);
        await user.save();

        // TO DO : CHANGE ROUTING SOLUTION WHEN LIVE
        window.location.href = "dashboard.html";
    })
}

// logout function
logout = async () => {
    await Moralis.User.logOut();
    window.location.href = "index.html";
}


// transactions function
// TO DO : CHANGE TO MAINNET TRANSACTIONS WHEN LIVE
// const transactions = await Moralis.Web3API.account.getTransactions();
getTransactions = async () => {
    console.log('get transactions clicked');
    const options = { chain: "rinkeby", address: "0xefFA817fd5b838C06758D42CdC3132B9F1EdF917" };
    // const options = { chain: "ropsten", address: "0x07F307118f7CAC1934B442a6dc933072B0bFFe38" };
    const transactions = await Moralis.Web3API.account.getTransactions(options);
    console.log(transactions);

    // table variable
    if (transactions.total > 0) {
        let table = `
        <table class="table">
        <thead>
            <tr>
                <th scope="col">Transaction</th>
                <th scope="col">Block Number</th>
                <th scope="col">Age</th>
                <th scope="col">Type</th>
                <th scope="col">Fee</th>
                <th scope="col">Value</th>
            </tr>
        </thead>
        <tbody id="theTransactions">
        </tbody>
        </table>
        `

        document.querySelector('#tableOfTransactions').innerHTML = table;

        // transactions array
        transactions.result.forEach(t => {
            let content = `
            <tr>
                <td><a href='https://rinkeby.etherscan.io/tx/${t.hash}' target="_blank" rel="noopener noreferrer">${t.hash}</a></td>
                <td><a href='https://rinkeby.etherscan.io/block/${t.block_number}' target="_blank rel="noopener noreferrer">${t.block_number}</a></td>
                // <td><a href='https://ropsten.etherscan.io/tx/${t.hash}' target="_blank" rel="noopener noreferrer">${t.hash}</a></td>
                // <td><a href='https://ropsten.etherscan.io/block/${t.block_number}' target="_blank rel="noopener noreferrer">${t.block_number}</a></td>
                <td">${millisecondstoTime(Date.parse(new Date()) - Date.parse(t.block_timestamp))}</td>
                <td>${t.from_address == Moralis.user.current().get('ethAddress') ? 'Outgoing' : 'Incoming'}</td>
                <td>${((t.gas * t.gas_price) / 1e18).toFixed(5)} ETH</td>
                <td>${(t.value / 1e18).toFixed(5)} ETH</td>
            </tr>
            `
            theTransactions.innerHTML += content;
        })
    }
}

// balances function
getBalances = async () => {
    console.log('Get balances clicked');
    // get BSC native balance for a given address
    const ethBalance = await Moralis.Web3API.account.getNativeBalance();
    const ropstenBalance = await Moralis.Web3API.account.getNativeBalance({ chain: "ropsten" });
    const rinkebyBalance = await Moralis.Web3API.account.getNativeBalance({ chain: "rinkeby" });
    console.log((ethBalance.balance / 1e18).toFixed(5) + " ETH");
    console.log((ropstenBalance.balance / 1e18).toFixed(5) + " ETH");
    console.log((rinkebyBalance.balance / 1e18).toFixed(5) + " ETH");


    // multi-line string template literal
    let content = document.querySelector('#userBalances').innerHTML = `
     <table class="table">
        <thead>
            <tr>
                <th scope="col">Chain</th>
                <th scope="col">Balance</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <th>Ether</th>
                <td>${(ethBalance.balance / 1e18).toFixed(5)} ETH</td>
            </tr>
            <tr>
                <th>Ropsten</th>
                <td>${(ropstenBalance.balance / 1e18).toFixed(5)} ETH</td>
            </tr>
            <tr>
                <th>Rinkeby</th>
                <td>${(rinkebyBalance.balance / 1e18).toFixed(5)} ETH</td>
            </tr>
        </tbody>
        </table>
     `
}



// NFTs function
getNFTs = async () => {
    console.log('get nfts clicked');
    let nfts = await Moralis.Web3API.account.getNFTs({ chain: 'rinkeby' });
    console.log(nfts);
    let tableOfNFTs = document.querySelector('#tableOfNFTs');
    if (nfts.result > 0) {
        nfts.result.forEach(n => {
            let metadata = JSON.parse(n.metadata);
            let content = `
            <div class="card col-md-3>
                <img src="${fixURL(metadata.image_url)}" class="card-img-top" alt="..." height=300>
                <div class="card-body">
                    <h5 class="card-title">${metadata.name}</h5>
                    <p class="card-text">${metadata.content}</p>
                </div>
            </div>
            `
            tableOfNFTs.innerHTML += content;
        })
    }
}

// NFT ipfs url conversion function
fixURL = (url) => {
    if (url.startsWith("ipfs")) {
        return "https://ipfs.moralis.io:2053/ipfs/" + url.split("ipfs://").slice(-1)
    }
    else {
        return url + "?format=json"
    }
}






// timestamp function for table
// currenttime(ms) - blocktime(ms) = TIME IN MILLISECONDS
// millisecondstoTime(Date.parse(new Date()) - Date.parse(t.block_timestamp))

millisecondsToTime = (ms) => {
    let minutes = (ms / Math.floor(1000 * 60));
    let hours = (ms / Math.floor(1000 * 60 * 60));
    let days = (ms / Math.floor(1000 * 60 * 60 * 24));
    if (days < 1) {
        if (hours < 1) {
            if (minutes < 1) {
                return `less than a minute ago`
            } else return `${minutes} minute(s) ago`
        } else return `${hours} hour(s) ago`
    } else return `${days} day(s) ago`
}



// listeners
if (document.querySelector('#btn-login') != null) {
    document.querySelector('#btn-login').onclick = login;
}

if (document.querySelector('#btn-logout') != null) {
    document.querySelector('#btn-logout').onclick = logout;
}

if (document.querySelector('#get-transactions-link') != null) {
    document.querySelector('#get-transactions-link').onclick = getTransactions;
}

if (document.querySelector('#get-balances-link') != null) {
    document.querySelector('#get-balances-link').onclick = getBalances;
}

if (document.querySelector('#get-nfts-link') != null) {
    document.querySelector('#get-nfts-link').onclick = getNFTs;
}

// get-transactions-link
// get-balances-link
// get-nfts-link```

first page html

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.84.0">
    <title>Login Component</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/sign-in/">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="signin.css">
    <link rel="stylesheet" href="style.css">

    <!-- 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>


  </head>
  <body class="text-center">
    
<main class="form-signin">

    <img class="mb-4" src="sailorMoon.png" alt="" width="375" height="285">
    <h1 class="h3 mb-3 fw-normal">Please sign in</h1>

    <div class="form-floating">
      <input type="text" class="form-control" id="user-username" placeholder="Username">
      <label for="user-username">Username</label>
    </div>

    <div class="form-floating">
      <input type="email" class="form-control" id="user-email" placeholder="[email protected]">
      <label for="user-email">Email address</label>
    </div>

    <button id="btn-login" class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">&copy; 2021</p>

</main>
    <script src="main.js"></script>
  </body>
</html>


post sign in page html

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="">
  <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
  <meta name="generator" content="Hugo 0.84.0">
  <title>Dashboard</title>

  <link rel="canonical" href="https://getbootstrap.com/docs/5.0/examples/dashboard/">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="dashboard.css" rel="stylesheet">
  <link href="style.css" rel="stylesheet">

  <!-- 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>

</head>

<body>

  <header class="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
    <a class="navbar-brand col-md-3 col-lg-2 me-0 px-3" href="#">Company name</a>
    <button class="navbar-toggler position-absolute d-md-none collapsed" type="button" data-bs-toggle="collapse"
      data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <input class="form-control form-control-dark w-100" type="text" placeholder="Search" aria-label="Search">
    <div class="navbar-nav">
      <div class="nav-item text-nowrap">
        <a id="btn-logout" class="nav-link px-3" href="#">Sign out</a>
      </div>
    </div>
  </header>

  <div class="container-fluid">
    <div class="row">
      <nav id="sidebarMenu" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
        <div class="position-sticky pt-3">
          <ul class="nav flex-column">
            <li class="nav-item">
              <a class="nav-link active" aria-current="page" href="#">
                <span data-feather="home"></span>
                Dashboard
              </a>
            </li>
            <li id="get-transactions-link" class="nav-item">
              <a class="nav-link" href="#">
                Transactions
              </a>
            </li>
            <li id="get-balances-link"class="nav-item">
              <a class="nav-link" href="#">
                Balances
              </a>
            </li>
            <li id="get-nfts-link"class="nav-item">
              <a class="nav-link" href="#">
                NFTs
              </a>
            </li>
          </ul>
        </div>
      </nav>

      <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
        <div
          class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
          <h1 class="h2">Dashboard</h1>
        </div>


        <h2>Transactions</h2>
        <div id="tableOfTransactions" class="table-responsive">

        </div>

        <h2>Balances</h2>
        <div id="userBalances" class="table-responsive">
          
        </div>

        <h2>NFTs</h2>
        <div id="tableOfNFTs" class="table-responsive d-flex flex-wrap">
          
        </div>

      </main>
    </div>
  </div>


  <script src="js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/feather.min.js"
    integrity="sha384-uO3SXW5IuS1ZpFPKugNNWqTZRRglnUJK6UAZ/gxOX80nxEkN9NcGZTftn6RzhGWE"
    crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/Chart.min.js"
    integrity="sha384-zNy6FEbO50N+Cg5wap8IKA4M/ZnLJgzc6w2NqACZaK0u0FXfOWRRJOnQtpZun8ha"
    crossorigin="anonymous"></script>
  <script src="dashboard.js"></script>
  <script src="main.js"></script>
</body>

</html>```

Let me run your code and check it out. Give me some time.

I ran your code and the code seems to be working fine. I got authenticated and redirected to dashboard with links. Upon clicking “Transactions”, I was able to retrieve a response.

Most likely there’s an issue with the initialisation. Try updating your server and please double check your App ID and server ID.

Response -

Payload -

Thank you. I updated the server, and checked again my server url and application id. I am still receiving the same errors :frowning:

what is the exact error that you get now?

Ok, I tested and it looks like something is wrong with your server, as it works fine with my server but with yours it gets that error.
Can you check if this is your server info?:

Moralis.initialize("UJurYwXbXkh4XU56MAPtPzKebxpzhiOc1YKtKrT6");
Moralis.serverURL = "https://ixnw6hipouw2.bigmoralis.com:2053/server";

I see you have server https://yhsppf8qokbr.grandmoralis.com:2083 on your screens. So which one we should check?

yes, that is the correct server info

I get same error for:

        Moralis.initialize("bAS3EF7dwd0SosA18W6asFkHJoeg0LBMFZmcPK2p");
        Moralis.serverURL = "https://yhsppf8qokbr.grandmoralis.com:2053/server";

@a.princess.of.mars

It’s on our end. I’ll let you know when it is fixed :man_mechanic:

@a.princess.of.mars

Try to go Web3 API section and call the function again from the frontend
image

It seems like default api key has not been created.
Doing so will create one If it does not exist

getTransaction appears to be working in Web3 API: { "hash": "0x1ed85b3757a6d31d01a4d6677fc52fd3911d649a0af21fe5ca3f886b153773ed", "nonce": "1848059", "transaction_index": "108", "from_address": "0x267be1c1d684f78cb4f6a176c4911b741e4ffdc0", "to_address": "0x003dde3494f30d861d063232c6a8c04394b686ff", "value": "115580000000000000", "gas": "30000", "gas_price": "52500000000", "input": "0x", "receipt_cumulative_gas_used": "4923073", "receipt_gas_used": "21000", "receipt_contract_address": null, "receipt_root": null, "receipt_status": "1", "block_timestamp": "2021-05-07T11:08:35.000Z", "block_number": "12386788", "block_hash": "0x9b559aef7ea858608c2e554246fe4a24287e7aeeb976848df2b9a2531f4b9171", "logs": [ { "log_index": "273", "transaction_hash": "0xdd9006489e46670e0e85d1fb88823099e7f596b08aeaac023e9da0851f26fdd5", "transaction_index": "204", "address": "0x3105d328c66d8d55092358cf595d54608178e9b5", "data": "0x00000000000000000000000000000000000000000000000de05239bccd4d537400000000000000000000000000024dbc80a9f80e3d5fc0a0ee30e2693781a443", "topic0": "0x2caecd17d02f56fa897705dcc740da2d237c373f70686f4e0d9bd3bf0400ea7a", "topic1": "0x000000000000000000000000031002d15b0d0cd7c9129d6f644446368deae391", "topic2": "0x000000000000000000000000d25943be09f968ba740e0782a34e710100defae9", "topic3": null, "block_timestamp": "2021-05-07T11:08:35.000Z", "block_number": "12386788", "block_hash": "0x9b559aef7ea858608c2e554246fe4a24287e7aeeb976848df2b9a2531f4b9171" } ] }

This means that your code should work now too. Problem should be fixed now.

1 Like

@a.princess.of.mars

Yes, now the key has been created and everything will work fine.

1 Like