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

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,
};

Dont know sever is syncing with another blockchain

I humbly told you that when try to deploy this file

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"];

using this command yarn hardhat deploy --network localhost --tags frontend
its gives me an error

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)

but with “yarn hardhat deploy” command it works fine and deployed the stuff

Now dont know it deployed where and using what blockchain but the chaindId says its localhost 31337

I am happy that you are helping @cryptokid

it looks like ie has that forking set there

Hmmm
Let me check it, after refining if it works or not
let me catch you back

Thanks btw

Hi Sir @cryptokid

I am in Woooooh condition
You saved me. :innocent:, you listened, you saved me
Thanks a lot :innocent: Praise to God

1 Like

@cryptokid
I’m also facing the same issue. I restart the Moralis server and hardhat local node as well. Still, I’m not seeing any events logged in the data base.

Server Url: https://xtqqb4chgkvl.usemoralis.com:2053/server

Can you please help?

I don’t see something wrong with that server now, I restarted the server now

I am facing the same issue with my moralis db
its not showing my events . I have tried creating new server but it still not updating my events

this is my sever URL:https://aewqzftsqjdz.usemoralis.com:2053/server

this is my addEvents.js

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

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 contarct address ${contractAddress}`)

    let itemListedOptions = {
        //Moralis understands a local chainas 1337
        chainId: moralisChainId,
        address: contractAddress,
        sync_historical: true,
        topic: "ItemListed(address,address,uint256,uint256)",
        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: "buyer",
                    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 itemCancledOptions = {
        chainId: moralisChainId,
        address: contractAddress,
        sync_historical: true,
        topic: "ItemCancled(address,address,uint256)",
        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",
                },
            ],
            name: "ItemCancled",
            type: "event",
        },
        tableName: "ItemCancled",
    }

    const listedResponse = await Moralis.Cloud.run("watchContractEvent", itemListedOptions, {
        useMasterKey: true,
    })
    const boughtResponse = await Moralis.Cloud.run("watchContractEvent", itemBoughtOptions, {
        useMasterKey: true,
    })
    const cancledResponse = await Moralis.Cloud.run("watchContractEvent", itemCancledOptions, {
        useMasterKey: true,
    })
    if (listedResponse.successs && cancledResponse.success && boughtResponse.success) {
        console.log("Success! database Updated with events")
    } else {
        console.log("Something went wrong")
    }
}

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

it also doesn’t showing the success condition when creating events on moralis instead it showing else case on my console but it is listing them there after that when I am minting my nft it is not recording the event

@cyptokid can you help me asap

were you able to make it work?

No tried everything still events are not updating
my githubb links
frontEnd: https://github.com/ritesh798/Next-js-Hardhat-NFT-Marketplace-frontend
backend: https://github.com/ritesh798/Hardhat-Nft-Marketplace
.

you could try it on a testnet instead of a local devchain

it should work, we just made it work on another server, double check the contract address and for chain id set “0x539” when you add the event sync