[SOLVED] addEvents.js - Can not use Moralis.Cloud.run

Hiii,

I need some help to start hearing the events and putting them in the database with Moralis.Cloud.run, I have tried several things but I keep stuck, this is the error:

useradd@PC-Sebas:~/hh-fcc/nextjs-nft-marketplace-fcc$ node addEvents.js 
Working with contract address: 0xb007167714e2940013EC3bb551584130B7497E22...
First got: [object Object]
Second got: [object Object]
Third got [object Object]
TypeError: Cannot read properties of undefined (reading 'run')
    at main (/home/useradd/hh-fcc/nextjs-nft-marketplace-fcc/addEvents.js:204:48)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I found this on the code of moralis-v1 but I can not get it to work, I do not know if that is involved in the issue, beacuse if so, I think more people would have my issue in the course, and it does not seem so…

This is the natspec I found about the function:

/**
 * Makes a call to a cloud function.
 *
 * @function run
 * @name Parse.Cloud.run
 * @param {string} name The function name.
 * @param {object} data The parameters to send to the cloud function.
 * @param {object} options
 * @returns {Promise} A promise that will be resolved with the result
 * of the function.
 */

I already tried Parse.Cloud.run requiring Parse from moralis-v1/node but I get that Cloud is not defined, or run when requiring Cloud as well.

This is my whole code:

/* import moralis */
const Moralis = require("moralis-v1/node");
require("dotenv").config();
const contractAddresses = require("./constants/networkMapping.json");

let chainId = process.env.chainId || 31337;

/* Moralis init code */
const contractAddress = contractAddresses[chainId]["NftMarketplace"][0];
const SERVER_URL = process.env.NEXT_PUBLIC_SERVER_URL;
const APP_ID = process.env.NEXT_PUBLIC_APP_ID;
const moralisChainId = chainId == "31337" ? "1337" : chainId;
const moralisSecret = process.env.NEXT_PUBLIC_MORALIS_SECRET;
const masterKey = process.env.NEXT_PUBLIC_MASTER_KEY;

async function main() {
    await Moralis.start({ SERVER_URL, APP_ID, moralisSecret });
    console.log(`Working with contract address: ${contractAddress}...`);

    let itemListedOptions = {
        //Moralis undestands that a local chain is 1337
        chainId: moralisChainId,
        sync_historical: true,
        address: contractAddress,
        topic: "ItemList(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: "ItemList",
            type: "event",
        },
        tableName: "ItemListed",
    };

    console.log(`First got: ${itemListedOptions}`);

    let itemBoughtOptions = {
        chainId: moralisChainId,
        sync_historical: true,
        address: contractAddress,
        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",
    };

    console.log(`Second got: ${itemBoughtOptions}`);

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

    console.log(`Third got ${itemCanceledOptions}`);

    // let priceUpdatedOptions = {
    //     chainId: moralisChainId,
    //     sync_historical: true,
    //     address: contractAddress,
    //     topic: "PriceUpdated(address, address, uint256, uint256)",
    //     abi: {
    //         anonymous: false,
    //         inputs: [
    //             {
    //                 indexed: false,
    //                 internalType: "address",
    //                 name: "changer",
    //                 type: "address",
    //             },
    //             {
    //                 indexed: false,
    //                 internalType: "address",
    //                 name: "tokenAddress",
    //                 type: "address",
    //             },
    //             {
    //                 indexed: false,
    //                 internalType: "uint256",
    //                 name: "tokenId",
    //                 type: "uint256",
    //             },
    //             {
    //                 indexed: false,
    //                 internalType: "uint256",
    //                 name: "newPrice",
    //                 type: "uint256",
    //             },
    //         ],
    //         name: "PriceUpdated",
    //         type: "event",
    //     },
    //     tableName: "PriceUpdated",
    // };

    // let withdrawalOptions = {
    //     chainId: moralisChainId,
    //     sync_historical: true,
    //     address: contractAddress,
    //     topic: "Withdrawal(address, uint256)",
    //     abi: {
    //         anonymous: false,
    //         inputs: [
    //             {
    //                 indexed: true,
    //                 internalType: "address",
    //                 name: "owner",
    //                 type: "address",
    //             },
    //             {
    //                 indexed: true,
    //                 internalType: "uint256",
    //                 name: "proceeds",
    //                 type: "uint256",
    //             },
    //         ],
    //         name: "Withdrawal",
    //         type: "event",
    //     },
    //     tableName: "Withdrawal",
    // };

    const listedResponse = await Moralis.Cloud.run("watchContractEvent", itemListedOptions, {
        useMasterKey: true,
    });

    console.log("Running first...");

    const boughtResponse = await Moralis.Cloud.run("watchContractEvent", itemBoughtOptions, {
        useMasterKey: true,
    });

    const canceledResponse = await Moralis.Cloud.run("watchContractEvent", itemCanceledOptions, {
        useMasterKey: true,
    });

    if (listedResponse.success && boughtResponse.success && canceledResponse.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);
    });

Please trust that the .env files are correct, I have checked each at least 3 times. And at await Moralis.start({ SERVER_URL, APP_ID, moralisSecret }); I am using the moralisSecret because it did not work with the masterKey after checking it was well set on the .env several times, I think somebody in the community saied that that way Moralis could not work ok, but if that is the case, I need some help to start Moralis with the masterKey.

Thank you very much again…


Update:

Saw that the start functions accepted more parameters and just added the masterKey inside and it runs perfectly and the same error is displayed, so, I think that confirms the issue is not from the start but from the Cloud function itself…

Looking like this right now:

await Moralis.start({ SERVER_URL, APP_ID, masterKey, moralisSecret });

Update:

Saw that the start functions accepted more parameters and just added the masterKey inside and it runs perfectly and the same error is displayed, so, I think that confirms the issue is not from the start but from the Cloud function itself…

What is the error you’re getting now? Which version of moralis-v1 are you using?

I already tried Parse.Cloud.run requiring Parse from moralis-v1/node but I get that Cloud is not defined, or run when requiring Cloud as well.

Yes you need to use Moralis.Cloud.run.

Hii

This is the error I am curretly having:

TypeError: Cannot read properties of undefined (reading 'length')
    at Object.request (/home/useradd/hh-fcc/nextjs-nft-marketplace-fcc/node_modules/moralis-v1/lib/node/RESTController.js:306:17)
    at Object.run (/home/useradd/hh-fcc/nextjs-nft-marketplace-fcc/node_modules/moralis-v1/lib/node/Cloud.js:167:36)
    at Object.run (/home/useradd/hh-fcc/nextjs-nft-marketplace-fcc/node_modules/moralis-v1/lib/node/Cloud.js:93:52)
    at main (/home/useradd/hh-fcc/nextjs-nft-marketplace-fcc/addEvents.js:209:42)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

This is my version:

"moralis-v1": "^1.11.0",

Yeah I am just using Morals.Cloud.run but can not make it, thanks for trying to help

Thank you.

await Moralis.start({ SERVER_URL, APP_ID, masterKey, moralisSecret });

Are you still using this? This should be:

await Moralis.start({ serverUrl: SERVER_URL, appId: APP_ID, moralisSecret });

Moralis.start expects an object with property names of serverUrl, appId, etc.

1 Like

Omg, Gladd really thank you very much! It worked fine with what you told me.

But the program do not work still as I am not getting the { success: true } from the Moralis.Cloud.run() calls…

It is weird because of the options are surely right, I already showed them in code with JSON.stringify() and values are saved correctly and other variables given to run() are obviously ok, so I would not now. And I already checked an the database did not update :frowning:

This is what I am getting right now:

Trying listed syncing...
Trying bought syncing...
Trying canceled syncing...
Something went wrong...

That from the code:

console.log("Trying listed syncing...");

    const listedResponse = Moralis.Cloud.run("watchContractEvent", itemListedOptions, {
        useMasterKey: true,
    });

    console.log("Trying bought syncing...");

    const boughtResponse = Moralis.Cloud.run("watchContractEvent", itemBoughtOptions, {
        useMasterKey: true,
    });

    console.log("Trying canceled syncing...");

    const canceledResponse = Moralis.Cloud.run("watchContractEvent", itemCanceledOptions, {
        useMasterKey: true,
    });

    if (listedResponse.success && boughtResponse.success && canceledResponse.success) {
        console.log("Success! Database Updated with watching events!");
    } else {
        console.log("Something went wrong...");
    }

Really appreciate your help a lot, it can be frustrating to not be able to find any info


Update:

Did moralis-admin-cli getLogs and got this:

 INFO  || 2022-10-19 22:53:37  
Ran cloud function getPluginSpecs for user undefined with:
  Input: {}
  Result: [{"name":"coreservices","functions":["getConfig","setConfig","getWeb3ApiToken","track","getOrganization","setOrganization","getEventSyncs","addEventSync","removeEventSync","listEventSyncStatus","getAddressSyncs","addAddressSync","removeAddressSync","listAddressSyncStatus","getProviders","setChains","getChains"]}]

Do not know what that exactly means, user undefined

None of the watchContractEvent syncs work? You should also add await in front of each Moralis.Cloud.run.

Ran cloud function getPluginSpecs for user undefined with:

You can ignore this - it means there was no user passed along with the call (if you didn’t use Moralis.authenticate()).

1 Like

Gladd, you really got me glad today, for real! Man this was really fucking helpful. At the start I had the await in fron of them but got rid of it after reading some Moralis documentation, now with it is working perfectly and the database is updated!

2 Likes