[SOLVED] Can't make the afterSave trigger work

Hello,

Here is what I try to achieve.

When someone transfers my ERC20 token, I want the recipient to be added to my Dividends table.

So I need an afterSave trigger that will listen to the PolygonTokenTransfers table and whenever there’s a new entry, runs the update/save function.

Here is how I implemented this function, but it doesn’t work for some reason. Can you spot why?

Moralis.Cloud.afterSave("PolygonTokenTransfers", async () => {
  const query = new Moralis.Query("PolygonTokenTransfers");
  query.descending("createdAt");
  const result = await query.first();

  if (
    result.attributes.token_address ===
    "0xb07f84cab9f87___my_ERC20_token_address__a54"
  ) {
     // if the recipient is already in the Dividends table combine his old balance with the newly received balance and update the table

    const dividendsQuery = new Moralis.Query("Dividends");
    dividendsQuery.equalTo("address", result.attributes.to_address);
    const dividendsResult = await dividendsQuery.first();

    if (dividendsResult) {
      const currentTokenBalance = dividendsResult.attributes.tokens;
      const newTokenBalance = Number(currentTokenBalance) + Number(result.attributes.value);
      dividendsResult.attributes.tokens = `${newTokenBalance}`;

      await dividendsResult.save();
    } else {

     // if the recipient is not in the Dividends table create a new record for him

      const DividendsTable = Moralis.Object.extend("Dividends");
      const dividendsInstance = new DividendsTable();
      dividendsInstance.set("tokens", `${result.attributes.value}`);

      await dividendsInstance.save();
    }
  }
});

I tried adding a logger, but it simply doesn’t execute. Either the whole trigger doesn’t execute, or just logger.

So, does my code look correct? What do you think? Is there a better way to achieve my goal in your opinion?

Thank you,

how did you add the logger?

try with logger.info("here is step 1")

you can try to make a change to a row from this table
PolygonTokenTransfers to see if that function executes

1 Like

The logger wasn’t working because I forgot to define it.

And the trigger wasn’t working because I forgot to use the master key with a null parameter as a first parameter.

await dividendsResult.save(null, { useMasterKey: true });

Now it works.

Btw I think that this first parameter is very confusing and should be explicitly mentioned in docs.

Thank you for your time.

1 Like