dev advocate at Chainstack here.
To create a server that continuously watches the events of multiple smart contracts and sends email alerts upon event detection, you can use Node.js with the web3.js library. Here's a high-level approach to achieve this:
Setup Node.js and web3.js: Begin by setting up a Node.js environment and installing web3.js, a popular library for interacting with Ethereum smart contracts.
Create WebSocket Connection: Web3.js allows you to create a WebSocket connection to an Ethereum node. This is crucial for real-time event listening.
Subscribe to Contract Events: Use web3.eth.subscribe('logs', options, callback)
to listen to events from smart contracts. You can specify the contract addresses and event signatures in the options
parameter.
Running the Server Continuously: You can make a simple server using Express.js.
Sending Email Alerts: Integrate an email service like Nodemailer with your Node.js application. Configure it to send emails within the callback of the event listener, which triggers when an event log is received.
Dynamically Adding New Contracts: To watch new contracts dynamically, you can create an API endpoint in your server application that accepts new contract details. You can set up a new subscription for its events when a new contract is added. Or you could pick the list of contracts from an environment variable.
Security and Reliability: Handle errors and network disconnections gracefully. Reconnection logic in WebSocket and proper error handling in both the event subscription and email sending are important for reliability.
Here's a simplified example demonstrating the key parts of such an application:
Install the packages
npm install express [email protected] nodemailer
const express = require('express');
const Web3 = require('web3');
const nodemailer = require('nodemailer');
const app = express();
const port = 3000;
// Web3 and WebSocket configuration
const NODE_URL = "YOUR_CHAINSTACK_WSS_ENDPOINT";
const websocketOptions = {
clientConfig: {
reconnect: {
auto: true,
delay: 5000,
maxRetries: 10,
},
},
};
const web3 = new Web3(new Web3.providers.WebsocketProvider(NODE_URL, websocketOptions));
// Email configuration (customize with your SMTP settings)
const transporter = nodemailer.createTransport({
service: 'gmail', // For example, using Gmail
auth: {
user: '[email protected]',
pass: 'yourpassword' // Use environment variables or a secure method to store credentials
}
});
// Function to send email
function sendEmail(logData) {
const mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Smart Contract Event Detected',
text: `New log data: ${JSON.stringify(logData)}`
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(`Error sending email: ${error}`);
} else {
console.log(`Email sent: ${info.response}`);
}
});
}
// Subscribe to contract logs
async function subscribeToContractLogs() {
try {
const logsFilter = {
address: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
topics: ["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"],
};
const subscription = await web3.eth.subscribe("logs", logsFilter);
subscription.on("connected", (subscriptionId) => {
console.log(`New subscription: ${subscriptionId}`);
});
subscription.on("data", (logData) => {
console.log(logData);
sendEmail(logData); // Send email on receiving log data
});
subscription.on("error", (error) => {
console.error(`Error receiving logs: ${error}`);
});
} catch (error) {
console.error(`Error subscribing to contract logs: ${error}`);
}
}
subscribeToContractLogs();
// Basic Express route
app.get('/', (req, res) => {
res.send('Ethereum log subscription server is running.');
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
In this example, you could pass the list of contracts from an env variable and update it when adding more contracts.
Keep in mind you need a WebSocket endpoint to get real-time events.
You can learn more about fetching real-time data here:
This approach should provide a good starting point for your server application that watches multiple smart contracts and sends email alerts. Remember to test thoroughly and consider security implications.