CORS and Server Questions

Hi everyone, I’ve been experiencing some weird problems with the testnet server.

Server info: (I just created this server but all servers have the same issue.)
https://skrazr9qzo4e.usemoralis.com:2053/server

Here is the list of the problems:

Problem 1: Our server stops sync after some events are emitted then I have to delete and create another server because if I just reset it does not sync anymore.

Problem 2: Our server is showing up an error about CORS that is intermittent too, but when it happens I have to reset the server

image

Problem 3: Whenever I reset the server the events stop firing then I have to delete and create a new server.

ps: we are rushing with our development to go live with the application by the middle of the month and it seems impossible with the events not firing, server error and etc. Please, I would appreciate some help to resolve this issue immediately.

My contract is:
rinkeby: 0x26d1059Ae5E6F3c3Ea0162a385D430eb54e9CDd2

I usually set up all events accordingly and it works the first time, maybe for some time but after it stops again and I start getting errors.

Here is my cloud function code:

Moralis.Cloud.define("getUserByUsername", async (request) => {
  try {
    const User = Moralis.Object.extend("User");
    const query = new Moralis.Query(User);

    request.params.username &&
      query.equalTo("username", request.params.username);
    request.params.address &&
      query.equalTo("ethAddress", request.params.address);

    const results = await query.first({ useMasterKey: true });

    return results;
  } catch (e) {
    logger.info(`INFO (getUserByUsername) -> ${JSON.stringify(e)}`);
  }
});

Moralis.Cloud.define("getFilePath", async (request) => {
  try {
    const ItemsPublished = Moralis.Object.extend("ItemsPublished");
    let query = new Moralis.Query(ItemsPublished);
    query.equalTo("objectId", request.params.objectId);
    query.equalTo("from", request.user.get("ethAddress"));

    let result = await query.first();

    if (result) {
      let fileData = await fetchIPFSDoc(result.get("uri"), false);

      return {
        file: fileData.properties.file,
      };
    }
  } catch (e) {
    logger.info(`INFO (getFilePath) -> ${JSON.stringify(e)}`);
  }
});

Moralis.Cloud.define("getAuthorRoyalties", async (request) => {
  try {
    const itemData = Moralis.Object.extend("ItemsPublished");
    const query = new Moralis.Query(itemData);
    query.equalTo("objectId", request.params.objectId);
    query.equalTo("from", request.user.get("ethAddress"));

    let result = await query.first();

    return {
      authorRoyalties: result.get("authorRoyalties"),
    };
  } catch (e) {
    logger.info(`Error getAuthorRoyalties -> ${e}`);
  }
});

Moralis.Cloud.define("getItem", async (request) => {
  try {
    const Items = Moralis.Object.extend("ItemsPublished");
    let query = new Moralis.Query(Items);

    query.equalTo("objectId", request.params.objectId);
    request.params.status && query.equalTo("status", request.params.status);

    // Count query
    if (request.params.onlyCount) {
      const queryResults = await query.count();
      return queryResults;
    }

    const queryResults = await query.first({ useMasterKey: true });

    return {
      objectId: queryResults.id,
      id: queryResults.attributes.uid,
      owner: await getUser(null, false, null, queryResults.attributes.owner_of),
      data: {
        metadata: await fetchIPFSDoc(queryResults.attributes.uri),
        likes: {
          count: queryResults.attributes.likes
            ? queryResults.attributes.likes.length
            : 0,
          isLiked:
            queryResults.attributes.likes &&
            queryResults.attributes.likes.includes(
              request.user.get("ethAddress")
            ),
        },
        views: {
          count: queryResults.attributes.views
            ? queryResults.attributes.views.length
            : 0,
          isViewed:
            queryResults.attributes.views &&
            queryResults.attributes.views.includes(
              request.user.get("ethAddress")
            ),
        },
      },
    };
  } catch (e) {
    logger.info(`INFO (getItem) -> ${JSON.stringify(e)}`);
  }
});

Moralis.Cloud.define("getItemsPublished", async (request) => {
  try {
    const ItemsPublished = Moralis.Object.extend("ItemsPublished");
    let query = new Moralis.Query(ItemsPublished);

    // Apply filters if existing
    query = await applyFilters(
      request,
      query,
      request.params,
      "ItemsPublished"
    );

    // Count query
    if (request.params.onlyCount) {
      const queryResults = await query.count();
      return queryResults;
    }

    const queryResults = await query.find({ useMasterKey: true });

    const results = [];

    for (let i = 0; i < queryResults.length; ++i) {
      logger.info(`QUERY RESULTS -> ${JSON.stringify(queryResults[i])}`);

      results.push({
        objectId: queryResults[i].id,
        id: queryResults[i].attributes.uid,
        owner: await getUser(
          null,
          false,
          null,
          queryResults[i].attributes.owner_of
        ),
        data: {
          metadata: await fetchIPFSDoc(queryResults[i].attributes.uri),
          likes: {
            count: queryResults[i].attributes.likes
              ? queryResults[i].attributes.likes.length
              : 0,
            isLiked:
              queryResults[i].attributes.likes &&
              queryResults[i].attributes.likes.includes(
                request.user.get("ethAddress")
              ),
          },
          views: {
            count: queryResults[i].attributes.views
              ? queryResults[i].attributes.views.length
              : 0,
            isViewed:
              queryResults[i].attributes.views &&
              queryResults[i].attributes.views.includes(
                request.user.get("ethAddress")
              ),
          },
        },
      });
    }

    return results;
  } catch (e) {
    logger.info(`INFO (getItemsPublished) -> ${e}`);
  }
});

Moralis.Cloud.define("getCollections", async (request) => {
  try {
    let query = new Moralis.Query("Collection");

    // Apply filters if existing
    query = await applyFilters(request, query, request.params);

    // Count query
    if (request.params.onlyCount) {
      const queryResults = await query.count();
      return queryResults;
    }

    const queryResults = await query.find({ useMasterKey: true });
    const results = [];

    for (let i = 0; i < queryResults.length; ++i) {
      results.push({
        user: await getUser(
          null,
          false,
          queryResults[i].attributes.user.id,
          null
        ),
        item: queryResults[i],
        likesCount: queryResults[i].attributes.likes
          ? queryResults[i].attributes.likes.length
          : 0,
        isLiked:
          queryResults[i].attributes.likes &&
          queryResults[i].attributes.likes.length
            ? await isLiked(
                queryResults[i],
                queryResults[i].attributes.likes,
                true,
                request.user
              )
            : false,
      });
    }

    return results;
  } catch (e) {
    logger.info(`INFO (getCollections) -> ${JSON.stringify(e)}`);
  }
});

/* After and Before Save functions */
Moralis.Cloud.afterSave("ItemsPublished", (request) => {
  try {
    logger.info(`Event fired (ItemsPublished) -> ${JSON.stringify(request)}`);

    updateItemTable(request, {
      status: "New",
      author: request.object.get("from").toLowerCase(),
      buyer: request.object.get("from").toLowerCase(),
      isSold: false,
      updateOnly: true,
      eventName: "publish",
    }).then((response) => {
      logger.info(`(ItemsPublished) -> ${response}`);
    });
    // Update only - never create a new item | Publish(address from, uint256 id, uint256 quantity, address tokenAddress, uint256 authorRoyalties, string uri) | DONE
  } catch (e) {
    logger.info(`Error - ItemsPublished -> ${e}`);
  }
});

Moralis.Cloud.beforeSave("ItemsOnSale", async (request) => {
  try {
    logger.info(`Event fired (ItemsOnSale) -> ${JSON.stringify(request)}`);
    let response = await updateItemTable(request, {
      status: "OnSale",
      isSold: true,
      updateOnly: true,
      eventName: "addselling",
    });

    // Update only - never create a new item | AddSelling(address owner, uint256 id, uint256 amount, string uri)     | DONE
    logger.info(`(ItemsOnSale)-> ${JSON.stringify(response)}`);
  } catch (e) {
    logger.info(`Error - ItemsOnSale -> ${e}`);
  }
});

Moralis.Cloud.beforeSave("ItemsTransfer", async (request) => {
  try {
    logger.info(`Event fired (ItemsTransfer) -> ${JSON.stringify(request)}`);
    let response = await updateItemTable(request, {
      buyer: request.object.get("buyer").toLowerCase(),
      seller: request.object.get("seller").toLowerCase(),
      amount: request.object.get("amount"),
      isSold: false,
      amountLeft: request.object.get("amountLeft"),
      eventName: "transfer",
    });

    // Update or Create | Transfer(address seller, address buyer, uint256 id, uint256 amount, uint256 amountLeft)
    // use cases
    /* 
      seller has 1 item and transfers 1 item to buyer   = seller(0) buyer(1) -> update owner_of
      seller has 10 items and transfer 5 items to buyer = seller(5) buyer(5) -> create new item with owner_of, quantity(amount),  
    */
    logger.info(`(ItemsTransfer)-> ${JSON.stringify(response)}`);
  } catch (e) {
    logger.info(`Error - ItemsTransfer -> ${e}`);
  }
});

/* Email functions */
Moralis.Cloud.define("EmailVerification", function (request) {
  Moralis.Cloud.sendEmail({
    to: request.params.email,
    subject: "Email verification",
    templateId: "d-edf86fc111ab46f5bd5ad98e3ccfa459",
    dynamic_template_data: {
      email: request.params.email,
    },
  });
});

Moralis.Cloud.define("EmailContact", function (request) {
  Moralis.Cloud.sendEmail({
    to: "[email protected]",
    subject: "Email verification",
    templateId: "d-9061a8be14974eb9b2940a749de2adb7",
    dynamic_template_data: {
      email: request.params.email,
      body: request.params.body,
    },
  });
});

async function updateItemTable(
  request,
  {
    status,
    isSold = undefined,
    updateOnly = false,
    author,
    buyer,
    seller,
    amount,
    amountLeft,
    eventName,
  }
) {
  try {
    const query = new Moralis.Query("ItemsPublished");
    request.object.get("uid") &&
      query.equalTo("uid", request.object.get("uid"));
    request.object.get("uri") &&
      query.equalTo("uri", request.object.get("uri"));
    request.object.get("tokenAddress") &&
      query.equalTo("tokenAddress", request.object.get("tokenAddress"));
    seller && query.equalTo("owner_of", seller);

    let itemPublished = await query.first({ useMasterKey: true });

    if (!itemPublished) {
      logger.info(`Item Not FOUND -> ${JSON.stringify(itemPublished)}`);

      return;
    }

    if (updateOnly) {
      const ItemsPublishedObj = Moralis.Object.extend("ItemsPublished");
      const ipobj = new ItemsPublishedObj();
      ipobj.set("objectId", itemPublished.id);
      author && eventName === "publish" && ipobj.set("author", author);
      status && ipobj.set("status", status);
      buyer && ipobj.set("owner_of", buyer);
      isSold !== undefined && ipobj.set("isSold", isSold);

      let resp = await ipobj.save();
      logger.info(`update [updateItemTable] -> ${JSON.stringify(resp)}`);
      return;
    }

    const ItemsPublishedObj = Moralis.Object.extend("ItemsPublished");
    const ipobj = new ItemsPublishedObj();

    //update if amount left is 0, but if amount zero is bigger than 0 we need to create a new item
    logger.info(`Amount Left (${amountLeft}) [updateItemTable]`);
    if (Number(amountLeft) === 0) {
      ipobj.set("objectId", itemPublished.id);
    } else {
      logger.info(`new [updateItemTable]`);
    }

    logger.info(`amountLeft -> ${Number(amountLeft)}`);

    ipobj.set("uid", itemPublished.get("uid"));
    ipobj.set("uri", itemPublished.get("uri"));
    amount && ipobj.set("quantity", amount);
    status && ipobj.set("status", status);
    isSold !== undefined && ipobj.set("isSold", isSold);
    author && ipobj.set("author", author);
    buyer && ipobj.set("owner_of", buyer);

    let response = await ipobj.save();
    if (response)
      logger.info(`save [updateItemTable] -> ${JSON.stringify(response)}`);
    else logger.info(`something happened [updateItemTable]`);
  } catch (e) {
    logger.info(
      `Err to updateItemTable -> ${
        typeof e === "object" ? JSON.stringify(e) : e
      }`
    );
  }
}

async function getUser(
  username,
  wholeObject = false,
  userId,
  userAddress = null
) {
  // Query userDwriter class
  let userQuery = new Moralis.Query(Moralis.User);

  logger.info(`username: ${username}`);
  logger.info(`byDwriterId: ${userId}`);
  logger.info(`ethAddress -> ${userAddress}`);

  userId && userQuery.equalTo("objectId", userId);
  username && userQuery.equalTo("username", username);
  userAddress && userQuery.equalTo("ethAddress", userAddress.toLowerCase());

  let result = await userQuery.first({
    useMasterKey: true,
  });

  logger.info(`result [getUser] -> ${JSON.stringify(result)}`);

  if (!result) {
    return {};
  }

  if (wholeObject) {
    logger.info(`ENTROU AQUI`);
    return result;
  }

  return {
    id: result.get("objectId"),
    username: result.get("username"),
    verified: result.get("verified"),
    image: result.get("profilePic") || "",
    displayName: result.get("displayName") || "",
    bio: result.get("bio") || "",
    address: {
      blockchain: "ethereum",
      value: result.get("ethAddress") || "",
    },
    social_media: {
      twitter: result.get("twitter") || "",
      instagram: result.get("instagram") || "",
      discord: result.get("discord") || "",
    },
    updated_at: result.get("updatedAt"),
    created_at: result.get("createdAt"),
  };
}

async function isLiked(data, likes, isCollection, user) {
  if (!likes) return false;

  let isliked = false;

  const queryLikes = new Moralis.Query(
    isCollection ? "CollectionLikes" : "ItemLikes"
  );

  if (!user) {
    return false;
  }

  queryLikes.equalTo("user", user.get("ethAddress"));

  isCollection
    ? queryLikes.equalTo("collection", data.attributes.collection_id)
    : queryLikes.equalTo("uid", data.attributes.uid);

  logger.info(`TEST -> ${data.attributes.uid}`);
  logger.info(`TEST 2 -> ${user.get("ethAddress")}`);

  const queryLikesResults = await queryLikes.find();

  logger.info(`QueryLikeResults  ${JSON.stringify(queryLikesResults)}`);

  if (!queryLikesResults || (queryLikesResults && !queryLikesResults.length)) {
    return false;
  }

  queryLikesResults.filter((result) => {
    if (likes && likes.includes(result.get("user"))) {
      isliked = true;
    } else {
      isliked = false;
    }
  });

  return isliked;
}

async function isViewed(data, views, isCollection, user) {
  if (!views) return false;

  let isViewed = false;

  const queryViews = new Moralis.Query(
    isCollection ? "CollectionViews" : "ItemViews"
  );

  if (!user) {
    return false;
  }

  queryViews.equalTo("user", user.get("ethAddress"));

  isCollection
    ? queryViews.equalTo("collection", data.attributes.collection_id)
    : queryViews.equalTo("uid", data.attributes.uid);

  logger.info(`UID -> ${data.attributes.uid}`);

  const queryViewsResults = await queryViews.find();

  logger.info(`queryViewsResults 123 -> ${JSON.stringify(queryViewsResults)}`);

  if (!queryViewsResults || (queryViewsResults && !queryViewsResults.length)) {
    return false;
  }

  queryViewsResults.filter((result) => {
    if (views && views.includes(result.get("user"))) {
      isViewed = true;
    } else {
      isViewed = false;
    }
  });

  return isViewed;
}

// Filters
async function applyFilters(
  request,
  query,
  {
    search,
    category,
    tag,
    status,
    startDate,
    endDate,
    minPrice,
    maxPrice,
    limit,
    page,
    ownedByUser,
    sortByLikes,
    belongsToCollection,
    collectionID,
    filterByUsername,
  },
  tableToSearch
) {
  if (belongsToCollection && collectionID) {
    query.equalTo("collection_id", collectionID);
    query.include("collection");
    logger.info(`Collection ID -> ${collectionID}`);
  }

  logger.info(`filterByUsername: ${filterByUsername}`);
  logger.info(`OwnedbyUser: ${ownedByUser}`);

  if (filterByUsername || ownedByUser) {
    query.equalTo("owner_of", request.user.get("ethAddress"));
  }

  sortByLikes && query.descending("likes");
  // //search && query.fullText("title", search);
  // //category && query.equalTo("category", category);
  // //tag && query.containedIn("tags", [tag]);
  // salesType && query.equalTo("salesType", salesType);
  status && query.equalTo("status", status);
  startDate &&
    query.greaterThan("createdAt", new Date(startDate.replace(/-/gm, "/")));
  endDate && query.lessThan("createdAt", new Date(endDate.replace(/-/gm, "/")));
  // //minPrice && query.greaterThan("price", parseInt(minPrice));
  // //maxPrice && query.lessThan("price", parseInt(maxPrice));
  limit && query.limit(page !== 0 ? limit * (page + 1) : limit);

  logger.info(`Filters applied.`);

  return query;
}

async function fetchIPFSDoc(ipfsHash, hiddenFile = true) {
  const url = `https://ipfs.moralis.io:2053/ipfs/${ipfsHash}`;

  let data;
  await Moralis.Cloud.httpRequest({
    url: url,
  }).then(
    function (httpResponse) {
      // success
      data = JSON.parse(httpResponse.text);

      hiddenFile && delete data["properties"]["file"];
    },
    function (httpResponse) {
      // error
      logger.info("Request failed with response code " + httpResponse.status);
    }
  );

  //logger.info(`Httpresponse 2 -> ${data}`);

  return data;
}

Here are the logs: (i don’t know why this is in loop (afterSave function))

we still have to figure out what it is going on, I have a similar behaviour on a server

1 Like

Good to know that I’m not the only one… Thanks for the response. We will be awaiting on new updates.

1 Like

Got this error too.

- Listening for logsError: Request failed with status code 504
    at createError (C:\Users\rbdes\AppData\Roaming\npm\node_modules\moralis-admin-cli\node_modules\axios\lib\core\createError.js:16:15)
    at settle (C:\Users\rbdes\AppData\Roaming\npm\node_modules\moralis-admin-cli\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (C:\Users\rbdes\AppData\Roaming\npm\node_modules\moralis-admin-cli\node_modules\axios\lib\adapters\http.js:269:11)
    at IncomingMessage.emit (events.js:412:35)
    at IncomingMessage.emit (domain.js:470:12)
    at endReadableNT (internal/streams/readable.js:1317:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  config: {
    url: 'https://shhef8pq69vj.usemoralis.com:2053/server/scriptlog?n=1000',
    method: 'get',
    headers: {
      Accept: 'application/json, text/plain, */*',
      Authorization: 'Basic eGdpekt5czFXVjU0Y25Zc1NhcWVNck9Jc283OXQ1QmRoZmtEdlk2RTpRUDZ1ZjA4MFdLdUx3QklNRXh6Y2JTTUVSRVdvUVVrSXlPUzRITzl6',
      'User-Agent': 'axios/0.21.4'
    },
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    adapter: [Function: httpAdapter],
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    data: undefined
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      error: [Array],
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      prefinish: [Function: requestOnPrefinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: false,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    _contentLength: 0,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'shhef8pq69vj.usemoralis.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 10,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'shhef8pq69vj.usemoralis.com',
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: 73,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(kSetNoDelay)]: false,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object],
      [Symbol(RequestTimeout)]: undefined
    },
    _header: 'GET /server/scriptlog?n=1000 HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Authorization: Basic eGdpekt5czFXVjU0Y25Zc1NhcWVNck9Jc283OXQ1QmRoZmtEdlk2RTpRUDZ1ZjA4MFdLdUx3QklNRXh6Y2JTTUVSRVdvUVVrSXlPUzRITzl6\r\n' +
      'User-Agent: axios/0.21.4\r\n' +
      'Host: shhef8pq69vj.usemoralis.com:2053\r\n' +
      'Connection: close\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: noopPendingOutput],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object],
      requests: {},
      sockets: [Object],
      freeSockets: {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 60,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'GET',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    path: '/server/scriptlog?n=1000',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      socket: [TLSSocket],
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      headers: [Object],
      rawHeaders: [Array],
      trailers: {},
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 504,
      statusMessage: 'Gateway Time-out',
      client: [TLSSocket],
      _consuming: true,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'https://shhef8pq69vj.usemoralis.com:2053/server/scriptlog?n=1000',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(RequestTimeout)]: undefined
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'shhef8pq69vj.usemoralis.com',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 0,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://shhef8pq69vj.usemoralis.com:2053/server/scriptlog?n=1000',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      authorization: [Array],
      'user-agent': [Array],
      host: [Array]
    }
  },
  response: {
    status: 504,
    statusText: 'Gateway Time-out',
    headers: {
      date: 'Mon, 03 Jan 2022 21:15:49 GMT',
      'content-type': 'text/html',
      'transfer-encoding': 'chunked',
      connection: 'close',
      'cf-cache-status': 'DYNAMIC',
      'expect-ct': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"',
      server: 'cloudflare',
      'cf-ray': '6c7f3d27ed31546d-YYZ'
    },
    config: {
      url: 'https://shhef8pq69vj.usemoralis.com:2053/server/scriptlog?n=1000',
      method: 'get',
      headers: [Object],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      adapter: [Function: httpAdapter],
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      transitional: [Object],
      data: undefined
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: false,
      _last: true,
      chunkedEncoding: false,
      shouldKeepAlive: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: false,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: 0,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      _header: 'GET /server/scriptlog?n=1000 HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Authorization: Basic eGdpekt5czFXVjU0Y25Zc1NhcWVNck9Jc283OXQ1QmRoZmtEdlk2RTpRUDZ1ZjA4MFdLdUx3QklNRXh6Y2JTTUVSRVdvUVVrSXlPUzRITzl6\r\n' +
        'User-Agent: axios/0.21.4\r\n' +
        'Host: shhef8pq69vj.usemoralis.com:2053\r\n' +
        'Connection: close\r\n' +
      '<body>\r\n' +
      '<center><h1>504 Gateway Time-out</h1></center>\r\n' +
      '<hr><center>nginx/1.18.0 (Ubuntu)</center>\r\n' +
      '</body>\r\n' +
      '</html>\r\n'
  },
  isAxiosError: true,
  toJSON: [Function: toJSON]

that seems like same error, you can also get CORS errors when server doesn’t respond in time

1 Like

Let me know if there is any way to delete this server, please.

URL: https://9orfzlskserv.moralishost.com:2053/server

can you delete it now?

1 Like

Perfect, I deleted it now. Thank you so much. I know we spoke before about this may not impact the other servers but just in case.

now you can restart/update the server that has problems to see if it works fine

Apparently no CORS problem anymore, however, I’m still having problems with the events.

Events:
ItemsPublished: Publish(address,uint256,uint256,address,uint256,string)
ItemsOnSale: AddSelling(address,uint256,uint256,string)
ItemsTransfer: Transfer(address,address,uint256,uint256,uint256,address)

Let me know if you need the abi too.

Here, I have a kind of loop on the event ItemsPublished, I will share my afterSave and beforeSave functions here:

/* After and Before Save functions */
Moralis.Cloud.afterSave("ItemsPublished", async (request) => {
  try {
    logger.info(`Event fired (ItemsPublished) -> entrou aqui`);

    const query = new Moralis.Query("ItemsPublished");
    query.equalTo("uid", request.object.get("uid"));
    query.equalTo("uri", request.object.get("uri"));
    query.equalTo("tokenAddress", request.object.get("tokenAddress"));

    query
      .first()
      .then(function (item) {
        logger.info(`itemPublished saved: -> ${JSON.stringify(item)}`);

        item.set("status", "New");
        item.set("owner_of", request.object.get("from"));
        item.set("isSold", false);
        item.set("author", request.object.get("from"));
        item
          .save()
          .then((response) => {
            logger.info(`Item saved -> ${JSON.stringify(response)}`);
          })
          .catch((e) => logger.info(`Error -> ${e}`));
      })
      .catch(function (error) {
        console.error("Got an error " + error.code + " : " + error.message);
      });
  } catch (e) {
    logger.info(`Error - ItemsPublished -> ${e}`);
  }
});

Moralis.Cloud.beforeSave("ItemsOnSale", async (request) => {
  try {
    logger.info(`Event fired (ItemsOnSale) -> entrou aqui`);

    const query = new Moralis.Query("ItemsPublished");
    query.equalTo("uid", request.object.get("uid"));
    query.equalTo("uri", request.object.get("uri"));
    query.equalTo("owner_of", request.object.get("owner"));

    query
      .first()
      .then(function (item) {
        logger.info(`ItemsOnSale updated: -> ${JSON.stringify(item)}`);

        item.set("status", "OnSale");
        item.set("isSold", true);
        item
          .save()
          .then((response) => {
            logger.info(`ItemOnSale updated -> ${JSON.stringify(response)}`);
          })
          .catch((e) => logger.info(`Error -> ${e}`));
      })
      .catch(function (error) {
        console.error("Got an error " + error.code + " : " + error.message);
      });
  } catch (e) {
    logger.info(`Error - ItemsOnSale -> ${e}`);
  }
});

Moralis.Cloud.beforeSave("ItemsTransfer", async (request) => {
  try {
    logger.info(`Event fired (ItemsTransfer) -> entrou aqui`);

    if (Number(request.object.get("amountLeft")) === 0) {
      logger.info(`No amount left [updateItemTable]`);

      const query = new Moralis.Query("ItemsPublished");
      query.equalTo("uid", request.object.get("uid"));
      query.equalTo("owner_of", request.object.get("seller"));
      query
        .first()
        .then(function (item) {
          logger.info(`ItemsTransfer updated: -> ${JSON.stringify(item)}`);

          item.set("status", "New");
          item.set("isSold", false);
          item.set("owner_of", request.object.get("buyer"));
          item
            .save()
            .then((response) => {
              logger.info(
                `ItemsTransfer updated -> ${JSON.stringify(response)}`
              );
            })
            .catch((e) => logger.info(`Error -> ${e}`));
        })
        .catch(function (error) {
          console.error(
            "Got an error (ItemsTransfer) " + error.code + " : " + error.message
          );
        });
    } else {
      logger.info(`There is amount left [updateItemTable]`);

      const querySeller = new Moralis.Query("ItemsPublished");
      querySeller.equalTo("uid", request.object.get("uid"));
      querySeller.equalTo("owner_of", request.object.get("seller"));
      querySeller
        .first()
        .then(async (itemSeller) => {
          itemSeller.set("quantity", Number(request.object.get("amountLeft")));

          let response = await itemSeller.save();

          if (response) {
            const queryBuyer = new Moralis.Query("ItemsPublished");
            queryBuyer.equalTo("owner_of", request.object.get("buyer"));
            queryBuyer.equalTo("uid", request.object.get("uid"));

            let findBuyer = await queryBuyer.first();
            if (findBuyer) {
              findBuyer.set(
                "quantity",
                Number(findBuyer.get("quantity")) +
                  Number(request.object.get("amount"))
              );
              findBuyer
                .save()
                .then((response) => {
                  logger.info(
                    `ItemsTransfer update existing buyer -> ${JSON.stringify(
                      response
                    )}`
                  );
                })
                .catch((e) =>
                  logger.info(`Error(update existing buyer) -> ${e}`)
                );
              return;
            }

            // Save new item
            const query = new Moralis.Query("ItemsPublished");
            query.equalTo("uid", request.object.get("uid"));
            query.equalTo("owner_of", request.object.get("seller"));
            query.first().then((response) => {
              const ItemsPublishedObj = Moralis.Object.extend("ItemsPublished");
              const ipobj = new ItemsPublishedObj();
              ipobj.set("uid", request.object.get("uid"));
              ipobj.set("uri", response.get("uri")); // getting from the seller
              ipobj.set("quantity", request.object.get("amount"));
              ipobj.set("status", "New");
              ipobj.set("isSold", false);
              ipobj.set("author", request.object.get("author"));
              ipobj.set("likes", []);
              ipobj.set("views", []);
              ipobj.set("owner_of", request.object.get("buyer"));
              ipobj
                .save()
                .then((response) => {
                  logger.info(
                    `ItemsTransfer create new -> ${JSON.stringify(response)}`
                  );
                })
                .catch((e) => logger.info(`Error -> ${e}`));
            });
          }
        })
        .catch((e) => logger.info(`Error(create new) -> ${e}`));
    }
  } catch (e) {
    logger.info(`Error - ItemsTransfer -> ${e}`);
  }
});

Can you explain exact the issue you face with the events?

In the logs it seems they are inserted properly?

Can you share some exact error logs maybe

1 Like

The problem is that I don’t see any errors nor the logs I added to the cloud function that is supposed to be executed.

It seems that the transfer event is not firing and the function Moralis.Cloud.afterSave(“ItemsPublished”) is in a loop because I see the log many times.

What else can I give you to help us with this problem?

One thing that is happening and I’m not sure if this is related is the CPU 100% and I can’t even reset the server too, btw I just created this server and I have a few data in it.

In addition to what I mentioned before about the CPU,

I’m also getting the event Publish in loop for no reason.

Cloud function ->

Moralis.Cloud.afterSave("ItemsPublished", (request) => {
  try {
    logger.info(`Event fired (ItemsPublished) -> entrou aqui`);

    const query = new Moralis.Query("ItemsPublished");
    query.equalTo("uid", request.object.get("uid"));
    query.equalTo("uri", request.object.get("uri"));
    query.equalTo("tokenAddress", request.object.get("tokenAddress"));

    query
      .first()
      .then(function (item) {
        logger.info(`itemPublished saved: -> ${JSON.stringify(item)}`);

        item.set("status", "New");
        item.set("owner_of", request.object.get("from"));
        item.set("isSold", false);
        item.set("author", request.object.get("from"));
        item
          .save()
          .then((response) => {
            logger.info(`Item saved -> ${JSON.stringify(response)}`);
          })
          .catch((e) => logger.info(`Error -> ${e}`));
      })
      .catch(function (error) {
        console.error("Got an error " + error.code + " : " + error.message);
      });
  } catch (e) {
    logger.info(`Error - ItemsPublished -> ${e}`);
  }
});

I was testing and I realized that the cloud function afterSave is being triggered when I update the column on the table ItemsPublished. I guess this is causing the problem with the other events and the loop. Does that make sense?

Fixed this way, I had to add a flag (published) when the item is saved and then I verify it afterward so this way the function does not execute again and give me a loop.

Moralis.Cloud.afterSave("ItemsPublished", async (request) => {

  try {
    logger.info(`Event fired (ItemsPublished) -> entrou aqui`);
    const query = new Moralis.Query("ItemsPublished");
    query.equalTo("uid", request.object.get("uid"));
    query.equalTo("uri", request.object.get("uri"));
    query.equalTo("tokenAddress", request.object.get("tokenAddress"));
    query.notEqualTo("published", true);

    let result = await query.first();

    if (result) {
      logger.info("executar");

      query
        .first()
        .then(function (item) {
          logger.info(`itemPublished saved: -> ${JSON.stringify(item)}`);
          item.set("published", true);
          item.set("status", "New");
          item.set("owner_of", request.object.get("from"));
          item.set("isSold", false);
          item.set("author", request.object.get("from"));
          item.save().then((response) => {
              logger.info(`Item saved -> ${JSON.stringify(response)}`);
            })
            .catch((e) => logger.info(`Error -> ${e}`));
        })
        .catch(function (error) {
         console.error("Got an error " + error.code + " : " + error.message);
        });

    } else {
      logger.info("Nao executar mais.");
    }
  } catch (e) {
    logger.info(`Error - ItemsPublished -> ${e}`);
  }
});
1 Like