[SOLVED] Event is not logging in Moralis database on devchain

Thanks. I am in middle of the course, not sure how to change to ganache, will look around it.

it should work now with hardhat if you update the server

I tried with same setup, but it didn’t work. Do I need to reset anything? I mean I have restarted the proxy server, hardhat local server and run the script that fire event. But still I can not see events getting log in table.

you need to update the server, after that you can also try to click on reset local devchain

what is the server url that you use now?

http://4l7ifivmqekk.usemoralis.com/ Using this one

I am going to delete the current server and create a new one and will test then

2 Likes

make sure to update the server after you create it

Wow… great its working. Thanks for helping.
So for anyone who is struggling, you should start with a fresh server. It has issue which has been resolved by the @cryptokid for hardhat

2 Likes

I’m having a similar problem, I tried resetting my local dev chain from the UI and its not responding,

If you try with a new server then it works?

Did you also try to reset the local dev chain programmatically or from the legacy UI?

Hi. I’m facing the same issue. All is connected but the problem is the event is not logging in to the Moralis database. I tried deleting and creating new servers many times but it doesn’t work. My server URL is https://q7v0uk9l7iqg.usemoralis.com. What else can I try to solve?

it looks like you added a topic like this: ItemCanceled(address,address,uint256
I would expect to see a topic that ends with )

1 Like

Thanks, @cryptokid. It was just a typo issue. Solved now.

1 Like

Hi @cryptokid

Hope you will be fine
I am facing the same issue, tried creating server many times, reseting existing chaing, configuring frpc, but all in vain.

Here is my addEvents.js file

const Moralis = require("moralis/node");
require("dotenv").config();
const contractAddresses = require("./constants/networkMapping.json");
let chainId = process.env.chainId || 31337;
let moralisChainId = chainId == "31337" ? "1337" : chainId;
const contractAddressArray = contractAddresses[chainId]["NftMarketplace"];
const contractAddress = contractAddressArray[contractAddressArray.length - 1];

const serverUrl = process.env.NEXT_PUBLIC_SERVER_URL;
const appId = process.env.NEXT_PUBLIC_APP_ID;
const masterKey = process.env.masterKey;

async function main() {
  await Moralis.start({ serverUrl, appId, masterKey });
  console.log(`Working with contrat address ${contractAddress}`);

  let itemListedOptions = {
    // Moralis understands a local chain is 1337
    chainId: moralisChainId,
    sync_historical: true,
    topic: "ItemListed(address,address,uint256,uint256)",
    address: contractAddress,
    abi: {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "seller",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "nftAddress",
          type: "address",
        },
        {
          indexed: true,
          internalType: "uint256",
          name: "tokenId",
          type: "uint256",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "price",
          type: "uint256",
        },
      ],
      name: "ItemListed",
      type: "event",
    },
    tableName: "ItemListed",
  };

  let itemBoughtOptions = {
    chainId: moralisChainId,
    address: contractAddress,
    sync_historical: true,
    topic: "ItemBought(address,address,uint256,uint256)",
    abi: {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "sender",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "nftAddress",
          type: "address",
        },
        {
          indexed: true,
          internalType: "uint256",
          name: "tokenId",
          type: "uint256",
        },
        {
          indexed: false,
          internalType: "uint256",
          name: "price",
          type: "uint256",
        },
      ],
      name: "ItemBought",
      type: "event",
    },
    tableName: "ItemBought",
  };

  let itemCanceledOptions = {
    chainId: moralisChainId,
    address: contractAddress,
    topic: "ItemCanceled(address,address,uint256)",
    sync_historical: true,
    abi: {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "sender",
          type: "address",
        },
        {
          indexed: true,
          internalType: "address",
          name: "nftAddress",
          type: "address",
        },
        {
          indexed: true,
          internalType: "uint256",
          name: "tokenId",
          type: "uint256",
        },
      ],
      name: "ItemCanceled",
      type: "event",
    },
    tableName: "ItemCanceled",
  };

  const listedResponse = await Moralis.Cloud.run(
    "watchContractEvent",
    itemListedOptions,
    {
      useMasterKey: true,
    }
  );
  const boughtResponse = await Moralis.Cloud.run(
    "watchContractEvent",
    itemBoughtOptions,
    {
      useMasterKey: true,
    }
  );
  const canceledResponse = await Moralis.Cloud.run(
    "watchContractEvent",
    itemCanceledOptions,
    {
      useMasterKey: true,
    }
  );
  if (
    listedResponse.success &&
    canceledResponse.success &&
    boughtResponse.success
  ) {
    console.log("Success! Database Updated with watching events");
  } else {
    console.log("Something went wrong...");
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

Here is my events at NftMarketplace.sol file

//events
  event ItemListed(
    address indexed seller,
    address indexed nftAddress,
    uint256 indexed tokenId,
    uint256 price
  );
  event ItemBought(
    address indexed sender,
    address indexed nftAddress,
    uint256 indexed tokenId,
    uint256 price
  );
  event ItemCanceled(
    address indexed sender,
    address indexed nftAddress,
    uint256 indexed tokenId
  );

Hardhat node is running,
yarn moralis:sync is working and moralis is connected with Hardhat node

This is the error of moralis log


One this i noticed is that
When i run this script with this command
yarn hardhat deploy --network localhost --tags frontend

const {
  frontEndContractsFile,
  frontEndAbiLocation,
} = require("../helper-hardhat-config");
require("dotenv").config();
const fs = require("fs");
const { network, ethers } = require("hardhat");

module.exports = async () => {
  if (process.env.UPDATE_FRONT_END) {
    console.log("Writing to front end...");
    await updateContractAddresses();
    await updateAbi();
    console.log("Front end written!");
  }
};

async function updateAbi() {
  const nftMarketplace = await ethers.getContract("NftMarketplace");
  const basicNft = await ethers.getContract("BasicNft");
  fs.writeFileSync(
    `${frontEndAbiLocation}NftMarketplace.json`,
    //do formate the nftMarkeplace contracts interface/abi code into ethers.utils.FormatTypes.json format
    nftMarketplace.interface.format(ethers.utils.FormatTypes.json)
  );
  fs.writeFileSync(
    `${frontEndAbiLocation}BasicNft.json`,
    basicNft.interface.format(ethers.utils.FormatTypes.json)
  );
}

async function updateContractAddresses() {
  const chainId = network.config.chainId.toString();
  const nftMarketplace = await ethers.getContract("NftMarketplace");
  const contractAddresses = JSON.parse(
    fs.readFileSync(frontEndContractsFile, "utf8")
  );
  if (chainId in contractAddresses) {
    if (
      !contractAddresses[chainId]["NftMarketplace"].includes(
        nftMarketplace.address
      )
    ) {
      contractAddresses[chainId]["NftMarketplace"].push(nftMarketplace.address);
    }
  } else {
    contractAddresses[chainId] = { NftMarketplace: [nftMarketplace.address] };
  }
  fs.writeFileSync(frontEndContractsFile, JSON.stringify(contractAddresses));
}
module.exports.tags = ["all", "frontend"];

its give me this error after runing;

Error: ERROR processing /Users/apple/Documents/Projects/blockchain/hardhat-nft-marketplace-backend/deploy/03-update-front-end.js:
TypeError: Cannot read properties of undefined (reading 'toString')
    at updateContractAddresses (/Users/apple/Documents/Projects/blockchain/hardhat-nft-marketplace-backend/deploy/03-update-front-end.js:33:42)
    at Object.module.exports [as func] (/Users/apple/Documents/Projects/blockchain/hardhat-nft-marketplace-backend/deploy/03-update-front-end.js:12:11)
    at DeploymentsManager.executeDeployScripts (/Users/apple/Documents/Projects/blockchain/hardhat-nft-marketplace-backend/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1220:41)
    at DeploymentsManager.runDeploy (/Users/apple/Documents/Projects/blockchain/hardhat-nft-marketplace-backend/node_modules/hardhat-deploy/src/DeploymentsManager.ts:1053:16)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)

because it not able to find the the chainId in this line network.config.chainId.

But when i ran this command
hh deploy
it works fine and deploy the stuff

then When i mint the nft using mint-and-list.js file , nft is minted and listed
But no event triger at Moralis side and DB is empty

Please help on this
Will be thankful

DB condition

what is the server url?

you can try to reset local dev chain from the legacy interface: legacy.moralis.io

I tried but did’nt work
I created new server, this is the url
https://aym7khsdtaqg.usemoralis.com:2053/server

it looks like that server synced ~5k blocks by now and continue syncing data, maybe you have some configs in hardhat that are trying to sync data from another blockchain?

These are the hardhat configs:

require("@nomiclabs/hardhat-waffle");
require("@nomiclabs/hardhat-etherscan");
require("hardhat-deploy");
require("solidity-coverage");
require("hardhat-gas-reporter");
require("hardhat-contract-sizer");
require("dotenv").config();

/** @type import('hardhat/config').HardhatUserConfig */

const RINKEBY_RPC_URL = process.env.RINKEBY_RPC_URL;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const COINMARKETCAP_API_KEY = process.env.COINMARKETCAP_API_KEY;
const ETHERSCAN_API_KEY = process.env.ETHERSCAN_API_KEY;
const MAINNET_PRC_URL = process.env.MAINNET_PRC_URL;

module.exports = {
  solidity: "0.8.7",
  networks: {
    hardhat: {
      chainId: 31337,
      forking: {
        url: MAINNET_PRC_URL,
      },
      blockConfirmations: 6,
    },
    rinkeby: {
      url: RINKEBY_RPC_URL,
      accounts: [PRIVATE_KEY],
      chainId: 4,
      //wait upto 6 blocks for the transaction to be mined
      blockConfirmations: 6,
    },
  },
  solidity: {
    compilers: [
      {
        version: "0.8.7",
      },
      {
        version: "0.8.8",
      },
      {
        version: "0.6.6",
      },
      {
        version: "0.6.12",
      },
      {
        version: "0.6.0",
      },
      {
        version: "0.4.19",
      },
    ],
  },
  gasReporter: {
    enabled: false,
    outputFile: "gas-reporter.txt",
    noColors: true,
    currency: "USD",
    coinmarketcap: COINMARKETCAP_API_KEY,
    token: "MATIC",
  },
  etherscan: {
    apiKey: ETHERSCAN_API_KEY,
  },
  namedAccounts: {
    deployer: {
      default: 0, // first account is the default one from all the hardhat accounts
      // 1: 0, // same on othe mainnet , first one is default
    },
    player: {
      default: 1,
    },
  },
  mocha: {
    timeout: 300000,
  },
};

This is the helper-hardhat-config.js

const networkConfig = {
  default: {
    name: "hardhat",
    keepersUpdateInterval: "30",
    subscriptionId: "588",
    gasLane:
      "0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc",
    interval: "30",
    raffleEntranceFee: "10000000000000000",
    callbackGasLimit: "500000",
  },
  31337: {
    name: "localhost",
    ethUsdPriceFeed: "0x9326BFA02ADD2366b30bacB125260Af641031331",
    subscriptionId: "588",
    gasLane:
      "0xd89b2bf150e3b9e13446986e571fb9cab24b13cea0a43ea20a6049a85cc807cc", // 30 gwei
    interval: "30",
    raffleEntranceFee: "10000000000000000",
    mintFee: "10000000000000000", // 0.01 ETH
    callbackGasLimit: "500000", // 500,000 gas
  },
};

const DECIMALS = "18";
const INITIAL_PRICE = "200000000000000000000";
const VERIFICATION_BLOCK_CONFIRMATIONS = 6;
const developmentChains = ["hardhat", "localhost"];

const frontEndContractsFile =
  "../hardhat-nft-marketplace-nextjs/constants/networkMapping.json";
const frontEndAbiLocation = "../hardhat-nft-marketplace-nextjs/constants/";

module.exports = {
  VERIFICATION_BLOCK_CONFIRMATIONS,
  frontEndContractsFile,
  frontEndAbiLocation,
  networkConfig,
  developmentChains,
  DECIMALS,
  INITIAL_PRICE,
};