Custom Ethereum Events via Moralis Streams

Xyz Zyx
2 min readJun 2, 2023

Moralis stream is a service that will send a POST webhook to your server with the filtered event from your contract.

They have some pre-sets like erc20/nfts but what interests us is the custom events.

BEFORE YOU BEGIN

Please be advised that presently, their complimentary plan offers an allocation of 300 streams on a daily basis, with the caveat that for every event, two requests are dispatched — one denoting an unverified transaction and the other indicating a verified one. While the allowance of 300 is suitable for developmental purposes, it may prove insufficient for production-oriented endeavors.

Additionally, securing a WebSocket-compatible provider capable of facilitating event monitoring is a challenging endeavor, as Alchemy did not yield favorable results during my previous attempt. Perhaps Quicknode would be a more viable alternative. It is worth noting that upon perusing the code, no contract address or concerns pertaining to RPC providers need be entertained.

Configure the stream

If you don’t do a security sensitive project then just make the webhook url some random chars “your_api/webhook_jk3roi2j32k89ygfduioj3284yu923ujF”

Configure the stream

Everything is self explanatory.

Their documentation on streams is lacking on other SDKs like Python so here’s me trying JavaScript

const express = require("express");

const app = express();
const port = 5000;
app.use(cors());
app.use(express.json());

const hexToNumber = (hex) => {
return parseInt(hex, 16);
};

app.post("/webhook_RANDOM_HERE_1231fdaslfkjads", async (req, res) => {
try {
const payload = req.body;

console.log(
"Received webhook event at",
new Date(Number(payload.block.timestamp) * 1000).toLocaleDateString(
"en-US"
)
);

// Log the parsed JSON payload to the console
console.log(payload);

if (payload.logs.length === 0) {
console.log("test request, returning ok!");
res.status(200).json({ message: "ok" });
return;
}

//if (payload.confirmed === false) ....return ok, but not needed for this use-case

let log = payload.logs[0];
// Extract the values from the data field
const tokenID = hexToNumber(log.data.slice(2, 66));
const tokenA = hexToNumber(log.data.slice(66, 130));
const tokenB = hexToNumber(log.data.slice(130));

await core(tokenID, tokenA, tokenB);

console.log("NewMint event:", tokenID, tokenA, tokenB);

you can either integrate it with ethers.js to parse the logs or use chatgpt to generate the slice indexes for your events.

--

--