[Gas Prices Tutorial] CF not working (returning a null list)

Hey guys,

This is my first time using Moralis, I’m following the guided tutorial, I’m using a mainnet instance.

here is the CF code:

Moralis.Cloud.define("getAvgGas", async function (request) {
  const query = new Moralis.Query("EthTransactions");
  const pipeline = [
    {
      group: {
        // group by "from_address"
        objectId: "$from_address",
        // add computed property avgGas
        // get average and convert wei to gwei
        avgGas: { $avg: { $divide: ["$gas_price", 1000000000]} },
      },
    },
    { sort: { avgGas: -1 } }, // sort by avgGas high to low
    { limit: 10 }, // only return top 10 results
  ];

  // the master key is required for aggregate queries
  const results = await query.aggregate(pipeline, { useMasterKey: true });
  return results;
})

here is the log for when I try and call the CF:

2021-09-11T21:42:11.311Z - Ran cloud function getAvgGas for user ediZ5GI9AlBUXxndYX1mjK06 with:
  Input: {}
  Result: []

Screenshot of the console logs:
Capture1

1 Like

here is the

index.html (its exactly like the tutorial, except the Server URL and APP ID, ofcourse)

<html>
  <head>
    <!-- Moralis SDK code -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web3.min.js"></script>
    <script src="https://unpkg.com/moralis/dist/moralis.js"></script>
  </head>
  <body>
    <h1>Moralis Gas Stats</h1>

    <button id="btn-login">Moralis Login</button>
    <button id="btn-logout">Logout</button>
    <button id="btn-get-stats">Refresh Stats</button>

    <!-- stats will go here -->
    <ul id="gas-stats"></ul>

    <script>
      // connect to Moralis server
      Moralis.initialize("YwoWv8U8eU0uGwhVs2OzEkI8ykTwgKfDVveYUiip");
      Moralis.serverURL = "https://krj7obcct46e.bigmoralis.com:2053/server";

      // LOG IN WITH METAMASK
      async function login() {
        let user = Moralis.User.current();
        if (!user) {
          user = await Moralis.authenticate();
        }
        console.log("logged in user:", user);
        getStats();
      }

      // LOG OUT
      async function logOut() {
        await Moralis.User.logOut();
        console.log("logged out");
      }

      // bind button click handlers
      document.getElementById("btn-login").onclick = login;
      document.getElementById("btn-logout").onclick = logOut;
      document.getElementById("btn-get-stats").onclick = getStats;

      // refresh stats
      function getStats() {
        const user = Moralis.User.current();
        if (user) {
          getUserTransactions(user);
        }
        getAverageGasPrices();
        console.log(user);
      }

      // HISTORICAL TRANSACTIONS
      async function getUserTransactions(user) {
        // create query
        const query = new Moralis.Query("EthTransactions");
        query.equalTo("from_address", user.get("ethAddress"));

        // subscribe to query updates
        const subscription = await query.subscribe();
        handleNewTransaction(subscription);

        // run query
        const results = await query.find();
        console.log("user transactions:", results);
      }

      // REAL-TIME TRANSACTIONS
      async function handleNewTransaction(subscription) {
        // log each new transaction
        subscription.on("create", function (data) {
          console.log("new transaction: ", data);
        });
      }

      // CLOUD FUNCTION
      async function getAverageGasPrices() {
        const results = await Moralis.Cloud.run("getAvgGas");
        console.log("average user gas prices:", results);
        renderGasStats(results);
      }

      function renderGasStats(data) {
        const container = document.getElementById("gas-stats");
        container.innerHTML = data
          .map(function (row, rank) {
            return `<li>#${rank + 1}: ${Math.round(row.avgGas)} gwei</li>`;
          })
          .join("");
      }

      //get stats on page load
      getStats();
    </script>
  </body>
</html>

Hi,
When you look In your server dashboard, do you see any entries in that EthTransactions table?
If you don’t see any entries there, then the cloud function will return an empty list.

Okay so apparently there was no issue, its just that the gas prices are being fetched from the user’s previous transactions and I was using a fresh account with 0 transactions so the list was null.

I instead created a new TestNet instance on Ropsten Network and went to a faucet and got some eth which is counted as a transaction and now I see one element returned in the array and EthTransactions table was automatically generated since my user now has at least 1 transaction!

So if you are going through this tutorial make sure you are using an account with some transactions :slight_smile:

Thank you @cryptokid

3 Likes