Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Guides

Setting Up a Smart Contract Monitoring and Alert System

A technical guide for developers on implementing monitoring and alert systems for Ethereum smart contracts. Covers Tenderly, OpenZeppelin Defender, and custom solutions for tracking critical on-chain events.
Chainscore © 2026
introduction
DEVELOPER GUIDE

Setting Up a Smart Contract Monitoring and Alert System

A practical guide to implementing real-time monitoring for on-chain activity, covering essential tools, alert configurations, and best practices for security and operational awareness.

Smart contract monitoring is a critical operational practice for developers and project teams. It involves tracking on-chain events, function calls, and state changes for your deployed contracts to ensure they behave as expected. Unlike traditional server monitoring, blockchain monitoring is event-driven and public, requiring tools that can parse transaction data from nodes. The primary goals are security incident detection (like unauthorized admin actions), operational awareness (tracking key user interactions), and performance analytics (monitoring gas usage and failure rates). Without a monitoring system, you are essentially operating blind to the live activity on your contracts.

The foundation of any monitoring system is an indexing or querying layer that processes raw blockchain data. While you could run your own node and listen for events, services like The Graph (for historical queries via subgraphs), Alchemy's Notify suite, and Tenderly's Webhooks abstract this complexity. For Ethereum and EVM chains, you configure these services to watch for specific contract events (e.g., Transfer, OwnershipTransferred) or track transactions to your contract address. A typical setup involves defining alert "triggers" based on event signatures, function selectors, or even transaction value thresholds.

Here is a basic example of setting up an alert for a suspicious ownership transfer using Ethers.js and a hypothetical webhook endpoint. This script listens for the OwnershipTransferred event and posts an alert.

javascript
const ethers = require('ethers');
const CONTRACT_ABI = [...]; // Your contract ABI
const CONTRACT_ADDRESS = '0x...';
const WEBHOOK_URL = 'https://your-alert-service.com/notify';

const provider = new ethers.providers.WebSocketProvider(ALCHEMY_WSS_URL);
const contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, provider);

contract.on('OwnershipTransferred', async (previousOwner, newOwner, event) => {
    console.log(`ALERT: Ownership changed from ${previousOwner} to ${newOwner}`);
    // Send alert to Slack, Discord, or PagerDuty
    await fetch(WEBHOOK_URL, {
        method: 'POST',
        body: JSON.stringify({ event: 'OwnershipTransferred', newOwner, txHash: event.transactionHash })
    });
});

For production systems, consider a multi-layered alert strategy. Critical security alerts (e.g., a upgrade to a malicious proxy implementation) should trigger immediate notifications via SMS or PagerDuty. Important operational alerts (e.g., a large deposit or withdrawal) can go to a Discord/Slack channel. Informational events (e.g., every token transfer) are best logged to a database for later analysis. Tools like OpenZeppelin Defender and Forta Network specialize in this, offering managed sentinel bots and agent networks that monitor for common attack patterns like flash loan exploits or gas price anomalies.

Effective monitoring also requires tracking metrics over time. Key Performance Indicators (KPIs) include transaction success/failure rate, average gas cost per function, unique active users, and total value locked (TVL) changes. Services like Dune Analytics and Flipside Crypto allow you to build dashboards for these metrics using SQL. Correlating on-chain alerts with off-chain logs (from your frontend or backend APIs) provides a complete picture of system health and user experience, enabling faster diagnosis of issues.

Finally, establish a regular review process for your alert rules. As your protocol evolves, so should your monitors. False positives from overly sensitive rules lead to alert fatigue, while false negatives create security gaps. Quarterly audits of your monitoring coverage, testing alert delivery, and updating triggers for new contract deployments are essential maintenance tasks. The goal is a system that provides high-signal notifications, giving your team the confidence that you will be promptly informed of any significant on-chain activity.

prerequisites
PREREQUISITES AND SETUP

Setting Up a Smart Contract Monitoring and Alert System

This guide covers the foundational steps required to build a system for monitoring on-chain events and receiving real-time alerts for your smart contracts.

A robust monitoring system requires a reliable data source. For most projects, this means connecting to a node provider like Alchemy, Infura, or QuickNode. These services offer WebSocket endpoints, which are essential for subscribing to real-time events without polling. You'll need to sign up for an account, create a new project, and obtain your API key and WebSocket URL. For development, you can also use a local node like Hardhat Network or Ganache, but a production-grade provider is necessary for mainnet and testnet monitoring.

Your development environment must be configured to interact with the blockchain. This typically involves installing Node.js (v18 or later) and a package manager like npm or yarn. You will also need the Ethers.js v6 or web3.js library to create the connection to your node provider and interact with smart contract ABIs. Initialize a new project with npm init -y and install your chosen library: npm install ethers or npm install web3. Ensure you have a .env file to securely store your provider API key using a package like dotenv.

The core of your monitoring logic is the smart contract's Application Binary Interface (ABI). This JSON file describes the contract's functions and events. You can obtain it from the compilation output if you are the developer, or from block explorers like Etherscan for verified contracts. Save this ABI in your project directory. You will use it to create a contract instance that can decode log data. For example, in Ethers.js: new ethers.Contract(contractAddress, contractABI, provider). This object is your gateway to listening for specific on-chain events.

With the provider and contract instance ready, you can set up an event listener. The key is to use the provider's WebSocket connection to subscribe to logs. In Ethers.js, you use contract.on("EventName", (arg1, arg2, event) => { ... }). This listener will trigger your callback function every time the specified event is emitted on-chain. Your callback should contain the alert logic—this could be logging to a console, sending a notification via a service like Discord (using webhooks), Telegram (via the Bot API), or PagerDuty, or writing to a database for further analysis.

For a production system, you must add error handling and resilience. Network connections can drop, and providers may have rate limits. Implement reconnection logic for your WebSocket and use try-catch blocks around your alerting code. Consider structuring your project into modular components: a configuration manager for secrets, a dedicated service for the blockchain connection, and separate modules for different alert channels. This makes the system easier to maintain and scale as you add monitoring for more contracts or events across different chains like Arbitrum or Polygon.

Finally, test your setup thoroughly before deploying. Deploy a simple test contract with an event to a testnet (e.g., Sepolia or Goerli) and verify your listener catches the emission and triggers the alert correctly. Monitor resource usage, as long-running processes can have memory leaks. For 24/7 reliability, you will need to run this script on a persistent server, a cloud function (like AWS Lambda or Google Cloud Functions), or a dedicated devops service. Proper logging of both successes and failures is critical for debugging issues in a live environment.

key-concepts
SMART CONTRACT MONITORING

Key Monitoring Concepts

Effective monitoring requires understanding core concepts, from event listening to anomaly detection. These are the foundational tools and techniques for building a robust alert system.

02

RPC Providers & WebSockets

Reliable data feeds are critical. While standard HTTPS JSON-RPC endpoints work for queries, WebSocket connections are essential for real-time subscription to new blocks and pending transactions. Compare providers like Alchemy, Infura, and QuickNode for uptime, archive data access, and rate limits. For high-frequency monitoring, dedicated nodes or services offering specialized endpoints (e.g., for mempool streaming) reduce latency.

04

On-Chain vs. Off-Chain Data

Monitoring systems must distinguish between verifiable on-chain data and interpretive off-chain data.

  • On-Chain: Transaction calldata, event logs, and storage slots. This data is immutable and consensus-verified.
  • Off-Chain: Derived metrics like Total Value Locked (TVL), token prices from oracles, or social sentiment. These require external data sources and introduce trust assumptions. A robust system validates oracle feeds and tracks price deviation.
05

Health Checks & Heartbeats

Ensure your monitoring system itself is operational. Implement health checks that verify:

  • RPC provider connectivity and sync status.
  • Indexer catch-up progress and data freshness.
  • Alert pipeline latency (time from on-chain event to notification). Use heartbeat alerts—regular pings from your system—to confirm it's running. If a heartbeat is missed, you know the monitor is down before a critical event occurs.
06

Notification Channels & Escalation

Deliver alerts to the right place at the right time. Configure multiple notification channels:

  • Immediate: PagerDuty, SMS, or phone calls for critical security events.
  • High-priority: Slack, Discord, or Telegram for urgent operational issues.
  • Logging: Data warehouses like Snowflake or BigQuery for audit trails. Establish escalation policies so unacknowledged alerts are forwarded to secondary responders after a defined period.
FEATURE MATRIX

Smart Contract Monitoring Platform Comparison

A comparison of key features, pricing, and capabilities for popular on-chain monitoring and alerting services.

Feature / MetricTenderlyOpenZeppelin DefenderChainlink FunctionsPythia

Real-time Event Monitoring

Custom Alert Logic (JavaScript)

Gas Usage & Cost Analysis

Mainnet Support

Testnet Support (Sepolia, Goerli)

Free Tier Available

Paid Tier Starting Price

$49/month

$100/month

$0.10/request

$25/month

Multi-Chain Monitoring

Slack/Discord/Webhook Alerts

Simulation & Forking

On-Chain Automation (Autotasks)

Maximum Free Alerts/Month

5,000

1,000

10,000

tenderly-implementation
TUTORIAL

Implementing Monitoring with Tenderly

A guide to setting up automated monitoring and alerts for your smart contracts using Tenderly's Web3 development platform.

Smart contract monitoring is essential for detecting critical on-chain events, failed transactions, and security anomalies in real-time. Tenderly provides a comprehensive suite of tools for this purpose, allowing developers to set up custom alerts without running their own infrastructure. This guide walks through creating a monitoring system that tracks specific contract functions, wallet activity, and transaction errors, sending notifications to platforms like Slack, Discord, or email.

The first step is to create a Tenderly Alert. Navigate to the Alerts dashboard in your Tenderly project and click "Create Alert." You define the trigger conditions using a flexible filtering system. Key filters include: Event Emission (e.g., Transfer(address,address,uint256)), Function Call to a specific method, Failed Transactions, and Value Transferred exceeding a threshold. You can also filter by specific contracts or wallets involved in the transaction.

For precise monitoring, use Tenderly's Alert Query Language. This allows you to write custom logic using transaction properties. For example, to alert on large USDC transfers from a specific vault contract, your query might be: event.name='Transfer' AND contract.address='0xa0b869...' AND tx.from='0xyourVault...' AND value > 1000000000. This granularity ensures you only receive alerts for the exact on-chain behavior you need to track.

After defining the trigger, configure the Alert Destination. Tenderly supports direct integrations with Slack, Discord, Microsoft Teams, and webhooks. For a webhook destination, you will receive a JSON payload containing the full transaction object, block data, and decoded event logs. This data can be parsed by your own server to trigger custom logic, update databases, or forward to other systems like PagerDuty.

To monitor contract health proactively, set up alerts for Failed Transactions and High Gas Usage. A spike in failed transactions for a specific function can indicate an integration error or a front-running attack. Monitoring gas usage helps identify inefficient code paths that could lead to user frustration and increased costs. Combining these alerts gives you a complete picture of your contract's operational status and user experience.

Finally, use Tenderly's Dashboard to visualize alert activity and trends. You can create widgets to see alert volume over time, group alerts by type, and monitor the performance of your notification channels. For production systems, establish severity levels (e.g., Critical, Warning) and route them to different channels. Regularly review and refine your alert filters to reduce noise and ensure you're capturing the most important on-chain events.

defender-implementation
TUTORIAL

Implementing Monitoring with OpenZeppelin Defender

A step-by-step guide to setting up automated monitoring and alerting for your smart contracts using OpenZeppelin Defender.

OpenZeppelin Defender is a security operations platform for Ethereum and other EVM-compatible blockchains. Its Autotasks and Sentinels features allow developers to automate monitoring and incident response. A Sentinel watches your contract for specific on-chain events or function calls, while an Autotask is a serverless function that executes logic, such as sending an alert, when a Sentinel is triggered. This creates a powerful, automated security layer for production deployments.

To begin, you'll need an OpenZeppelin Defender account and a project. Navigate to the Defender dashboard and create a new Relayer. This provides a funded wallet that your Autotasks will use to sign transactions or pay for gas. Next, create an Autotask. You can write its logic in JavaScript, connecting to services like Slack, Discord, or Telegram via webhooks. For example, an Autotask can format a message with transaction details and post it to a dedicated security channel.

The core monitoring component is the Sentinel. Create a new Sentinel and configure it to watch your contract address. You can set it to trigger on: specific event signatures (e.g., OwnershipTransferred), failed transactions, high-value transfers, or any contract method call. Define the network (Mainnet, Goerli, etc.) and the polling interval. Crucially, link this Sentinel to the Autotask you created, so an alert is fired automatically upon detection.

For advanced monitoring, use Defender's API. You can programmatically manage Sentinels and Autotasks, enabling dynamic monitoring setups. For instance, you could write a script that creates a new Sentinel for every newly deployed contract in your protocol. The API also allows you to fetch historical Sentinel notifications for audit trails. All secrets, like webhook URLs or API keys, are securely stored and encrypted within Defender's environment.

Effective monitoring requires defining meaningful alerts. Key scenarios include: monitoring for administrative actions (owner changes, upgrade proposals), financial thresholds (large withdrawals from a treasury contract), contract pauses, or failed interactions from known user interfaces. By combining these rules, you establish a 24/7 watchdog for your protocol's core contracts, enabling rapid response to suspicious activity or operational issues.

Integrate Defender monitoring into your development workflow. Include Sentinel configurations in your repository as code (e.g., JSON files) and use the CLI for deployment. This ensures your monitoring is version-controlled and reproducible across environments. Defender's robust, managed infrastructure removes the need to host and maintain your own alerting servers, allowing teams to focus on building and securing their applications.

custom-indexer-guide
TUTORIAL

Building a Custom Monitoring Indexer

A step-by-step guide to creating a system that tracks on-chain events and triggers alerts for your smart contracts.

A custom monitoring indexer is a backend service that actively listens to a blockchain for specific events emitted by your smart contracts. Unlike general-purpose block explorers, a custom indexer allows you to define the exact logic for what data to capture, how to process it, and when to send alerts. This is essential for tracking protocol-specific metrics, detecting anomalous user behavior, or automating responses to on-chain conditions. The core components are an RPC connection to a node, an event listener, a database for storing indexed data, and an alerting mechanism.

The first step is to define your indexing scope. You need to identify the smart contract addresses and the specific event signatures you want to monitor. For an ERC-20 token, you might track Transfer(address,address,uint256). For a lending protocol, you'd monitor events like Deposit or Liquidation. Use the contract's ABI to decode the event logs. You can set up your listener using libraries like ethers.js or web3.py, connecting to a node provider like Alchemy, Infura, or a self-hosted node. The listener should poll for new blocks or use WebSocket subscriptions for real-time updates.

Once you capture raw event logs, you must transform and store them in a queryable format. A structured database like PostgreSQL is ideal for this. Create a schema that maps event parameters to table columns. For a Transfer event, you'd store fields like from, to, value, block_number, and transaction_hash. This historical data becomes your indexed dataset, enabling complex queries such as "show all large transfers in the last 24 hours" or "calculate total volume per user." Proper indexing of database columns on fields like block_number and address is critical for performance.

The real power of a monitoring indexer lies in its alerting logic. This layer runs checks against your indexed data. You can write rules in your application code: for example, if a Liquidation event occurs where the debt size exceeds a threshold, send a notification. Alert destinations can include email, Slack, Discord webhooks, or SMS services like Twilio. For more complex logic, you can integrate with off-chain data or oracles. Always include idempotency checks, such as tracking alerted transaction hashes, to prevent duplicate notifications for the same on-chain event.

Deploy your indexer on a reliable server or cloud function (e.g., AWS Lambda, Google Cloud Run) to ensure 24/7 uptime. Implement robust error handling for RPC disconnections and database timeouts. Use a process manager like PM2 for Node.js applications. To validate your setup, test with a forked blockchain network using tools like Hardhat or Ganache to simulate events without spending real gas. Finally, consider open-source frameworks like The Graph for subgraphs or TrueBlocks for more complex indexing, but a custom solution offers maximum flexibility for specific monitoring needs.

critical-alert-types
SMART CONTRACT SECURITY

Critical Events to Monitor

Proactive monitoring of on-chain events is essential for security and operational awareness. This guide covers the key event types that require automated alerts.

05

Large or Anomalous Token Transfers

Set thresholds for significant value movements from key contracts. Monitor for:

  • Large withdrawals from treasury or fee collector contracts.
  • Unexpected outflows from protocol-owned liquidity pools.
  • Whale movements that could signal impending market actions.

Use percentage-based thresholds (e.g., >5% of TVL) or absolute value limits (e.g., >$1M) to filter noise.

>5% TVL
Alert Threshold
SMART CONTRACT MONITORING

Troubleshooting Common Issues

Common challenges and solutions for setting up reliable smart contract monitoring and alert systems, from data sourcing to alert fatigue.

Delayed or missing alerts are often caused by RPC node latency or event indexing lag. Public RPC endpoints can be rate-limited and have high latency, causing your listener to miss blocks or transactions.

Solutions:

  • Use a dedicated node provider (Alchemy, Infura, QuickNode) with WebSocket connections for real-time event streaming.
  • Implement block confirmation depth. Wait for 3-15 block confirmations before triggering alerts to avoid chain reorganizations.
  • For historical data, use a dedicated indexer like The Graph or Subsquid, which can process events faster than polling an RPC.
  • Set up health checks for your RPC connection and have a fallback provider.
SMART CONTRACT MONITORING

Frequently Asked Questions

Common questions and troubleshooting for developers implementing on-chain monitoring and alert systems.

Event listening and state polling are two primary methods for monitoring smart contracts.

Event Listening involves subscribing to on-chain events emitted by a contract (e.g., Transfer(address,address,uint256)). It's efficient for tracking specific, logged occurrences. Use libraries like ethers.js contract.on() or WebSocket providers for real-time updates.

State Polling involves periodically calling read-only functions (e.g., balanceOf()) or checking storage slots to detect state changes. This is necessary for monitoring values not exposed via events. Polling intervals must balance responsiveness with RPC rate limits and cost.

Best Practice: Combine both. Listen for events as the primary trigger and use periodic state checks as a fallback or for validating conditions.

conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have now configured a foundational system for monitoring smart contract events and receiving real-time alerts.

The system you've built provides a critical operational layer for any on-chain application. By integrating a provider like Chainscore for reliable RPC access, a service like Tenderly for event streaming, and a notification platform like PagerDuty, you have created a robust pipeline. This setup moves you from reactive debugging to proactive monitoring, allowing you to detect critical state changes—such as failed transactions, governance votes, or security events—as they happen. The key components are modular: you can swap the RPC provider, event source, or alert destination based on your specific needs for reliability, cost, or integration.

To extend this system, consider implementing more sophisticated logic. Instead of alerting on every event, write filter functions that only trigger notifications for specific conditions, like a treasury withdrawal exceeding a threshold or a contract pausing unexpectedly. You could also integrate with a database (e.g., PostgreSQL) or data warehouse (e.g., Google BigQuery via the BigQuery public datasets for blockchain) to log events for historical analysis and trend identification. For high-frequency contracts, implementing a deduplication layer or a cooldown period for alerts will prevent notification fatigue.

Your next steps should focus on hardening and scaling. First, write unit tests for your alerting logic using a framework like Jest or Mocha to ensure it correctly parses transaction receipts and event logs. Second, set up a staging environment that mirrors your production blockchain (using a testnet or a Tenderly fork) to test new alert rules safely. Finally, document your alert runbooks: for each type of alert, define the severity level, the immediate investigative steps, and the escalation path. This turns raw notifications into actionable operational intelligence, forming the backbone of a professional Web3 development and DevOps practice.