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,