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 Real-Time Threat Monitoring for Your Sale

A technical guide to building a monitoring and alerting system for a live token sale, covering on-chain metrics, frontend analytics, and incident response runbooks.
Chainscore © 2026
introduction
INTRODUCTION

Setting Up Real-Time Threat Monitoring for Your Sale

Proactive security monitoring is essential for detecting and mitigating threats during a token sale. This guide explains how to implement a real-time monitoring system.

A real-time threat monitoring system continuously analyzes on-chain and off-chain data to identify suspicious activity during a token sale. Unlike post-mortem analysis, real-time monitoring allows for immediate intervention, potentially preventing exploits like front-running, Sybil attacks, or liquidity manipulation. The core components include data ingestion from block explorers and mempools, threat detection logic, and alerting mechanisms to notify your team instantly.

To build an effective system, you need to define clear threat indicators. Common indicators for a sale include: - Unusual gas price spikes from a single address - Multiple transactions from wallets funded by a common source - Rapid, repetitive interactions with the sale contract - Transactions that consistently fail or revert. These signals, when correlated, can reveal coordinated attack patterns. Tools like Tenderly Alerts or custom scripts listening to WebSocket connections from providers like Alchemy or Infura are commonly used for this purpose.

Implementing the monitoring logic requires writing detection scripts. For example, you can use the Ethers.js library to listen for pending transactions and analyze their properties. A basic script might check if multiple pending transactions are targeting your sale contract's buyTokens function with gas prices above a certain threshold, which could indicate a front-running attempt. Setting up alerts to a Slack channel or PagerDuty ensures your team is notified the moment a potential threat is detected, enabling a swift response.

prerequisites
SETUP CHECKLIST

Prerequisites

Before implementing real-time threat monitoring, ensure your technical environment and data sources are correctly configured.

To monitor threats effectively, you need a secure and accessible data source. The most reliable method is to run a full node for the blockchain hosting your sale contract (e.g., an Ethereum execution client like Geth or Erigon). This provides direct, unfiltered access to the mempool and new blocks. If running a node is impractical, you can use a professional node provider service like Alchemy, Infura, or QuickNode. Their premium tiers often include enhanced APIs for mempool access, which is critical for seeing pending transactions before they are confirmed.

Your monitoring script requires a Web3 library to interact with the blockchain. For JavaScript/TypeScript environments, use web3.js or ethers.js. For Python, use web3.py. Install your chosen library via npm or pip. You will also need the Application Binary Interface (ABI) of your sale contract. This ABI, typically generated during compilation (e.g., with Hardhat or Foundry), defines the functions and events your script needs to listen for, such as TokensPurchased or WhitelistUpdated.

The core of threat detection is analyzing transaction data. Your script must decode transaction input data using the contract ABI to understand the intent—like the purchase amount or beneficiary address. It should also monitor the mempool for pending transactions and inspect new blocks as they are mined. Key data points to extract and log include: the transaction sender (msg.sender), the function being called, the arguments passed, the transaction hash, and the gas price. This data forms the basis for identifying suspicious patterns.

To act on threats, you need a predefined set of rules or heuristics. Common threats include Sybil attacks (multiple purchases from linked addresses), gas price manipulation (transactions with excessively high priority fees to front-run others), and contract exploitation attempts (calling unauthorized functions). Define thresholds for these behaviors, such as a maximum number of transactions per block from a cluster of addresses or a gas price cap. These rules will trigger alerts in your monitoring system.

Finally, set up an alerting mechanism. This can be as simple as logging events to a console or file, or as advanced as sending notifications to a Slack channel, Discord webhook, or PagerDuty. For immediate response, consider integrating with your contract's admin functions to potentially pause the sale if a critical threat is detected. Ensure your script runs on a reliable server or cloud function (like AWS Lambda or a dedicated VPS) with high uptime to maintain continuous surveillance throughout the sale period.

monitoring-architecture
SECURITY

Monitoring Architecture Overview

A robust monitoring architecture is the foundation for detecting and responding to threats during a token sale. This guide outlines the essential components for real-time surveillance.

A real-time threat monitoring system for a token sale is a multi-layered architecture designed to detect anomalies across the entire transaction lifecycle. It typically consists of three core layers: the Data Ingestion Layer, which collects raw on-chain and off-chain data; the Processing & Analysis Layer, where rules and machine learning models evaluate this data; and the Alerting & Visualization Layer, which surfaces critical insights to your team. Each layer must be scalable to handle high transaction volumes and low-latency to enable immediate response.

The Data Ingestion Layer is your system's eyes and ears. It connects to data sources like blockchain RPC nodes (e.g., for Ethereum, Solana), mempool watchers to see pending transactions, and your sale's smart contract events. For comprehensive coverage, you should also ingest off-chain data from your website's analytics, API gateways, and community channels like Discord and Telegram. Tools like Chainlink Functions or custom indexers using The Graph can be used to reliably fetch and structure this on-chain data for processing.

In the Processing & Analysis Layer, ingested data is evaluated against predefined threat models. This involves setting up heuristic rules (e.g., "flag transactions from addresses newly funded by Tornado Cash") and potentially machine learning models to detect sophisticated Sybil attack patterns or wash trading. This layer runs in a secure, isolated environment, often using serverless functions or dedicated analysis microservices. The output is a stream of enriched events tagged with risk scores and specific threat classifications.

The final component is the Alerting & Visualization Layer. High-risk events from the processing layer trigger immediate alerts via channels like PagerDuty, Slack, or SMS. For situational awareness, a real-time dashboard (built with tools like Grafana or a custom frontend) visualizes key metrics: total volume, unique participants, geographic distribution of IPs, and a live feed of flagged activities. This dashboard allows your security team to triage incidents and make data-driven decisions to pause the sale or block malicious addresses.

Implementing this architecture requires careful planning for data persistence and audit trails. All raw data, processed events, and alert actions should be logged immutably to a database or data warehouse. This creates an audit trail crucial for post-mortem analysis, regulatory compliance, and refining your detection rules. Services like Google BigQuery or Snowflake are common choices for storing this historical data at scale.

key-metrics-to-track
SALE SECURITY

Key Metrics and Signals to Monitor

Real-time monitoring is critical for detecting and mitigating threats during a token sale. Focus on these key data points to protect your project and participants.

01

Transaction Volume Anomalies

Monitor for sudden, abnormal spikes in transaction volume or gas fees, which can indicate a Sybil attack or bot-driven manipulation. Set thresholds based on your sale's expected scale.

  • Key Metric: Transactions per second (TPS) vs. baseline.
  • Signal: A 500%+ increase in TPS from unknown wallets.
  • Action: Implement rate-limiting or a temporary pause to investigate.
02

Wallet Behavior & Sybil Detection

Identify clusters of wallets exhibiting coordinated behavior, such as funding from a common source or identical transaction patterns. This signals potential Sybil attacks aiming to unfairly allocate tokens.

  • Key Metric: Unique deposit addresses vs. funding source correlation.
  • Tool: Use on-chain analytics (e.g., Chainalysis, Nansen) to trace funding.
  • Action: Flag suspicious clusters for manual review or exclusion.
03

Smart Contract Function Calls

Track all function calls to your sale contract in real-time. Unauthorized or unexpected calls to critical functions like setPrice, pause, or withdrawFunds are immediate red flags.

  • Key Metric: Failed or reverted transactions targeting admin functions.
  • Signal: Calls from non-whitelisted administrator addresses.
  • Action: Set up alerts for any call to privileged functions.
04

Liquidity & Price Impact

For sales involving DEX liquidity pools (e.g., Uniswap, PancakeSwap), monitor the pool's reserves and price impact. Large, imbalanced swaps before the sale can manipulate the opening price.

  • Key Metric: Pool reserve ratios (Token/ETH) and slippage.
  • Signal: A single wallet providing >30% of initial liquidity.
  • Action: Use a lock-up for initial liquidity and monitor for large pre-sale swaps.
05

Social Media & Sentiment Analysis

Correlate on-chain events with social media chatter on Twitter, Discord, and Telegram. A surge in complaints about failed transactions or scam allegations requires immediate investigation.

  • Key Metric: Negative sentiment spike and report volume.
  • Signal: Phishing links shared in official channels impersonating your project.
  • Action: Have moderators ready to pin official announcements and warn users.
06

Infrastructure Health & RPC Load

Your sale's frontend and RPC providers must handle peak load. Monitor response times, error rates, and failed connection attempts. Downtime during a sale can cause panic and loss of funds.

  • Key Metric: API/RPC latency (< 2 sec target) and error rate (< 0.1%).
  • Signal: 5xx HTTP errors or JSON-RPC -32005 rate limit errors.
  • Action: Use load-balanced RPC providers (Alchemy, Infura) and have a fallback UI.
implement-onchain-tenderly
GUIDE

Implement On-Chain Monitoring with Tenderly

Set up automated, real-time alerts for critical on-chain events in your token sale contracts to detect and respond to threats instantly.

On-chain monitoring is essential for detecting suspicious activity during a live token sale. Manually watching transaction mempools or block explorers is slow and error-prone. Tenderly provides a developer platform to create real-time alerts based on specific contract events, function calls, or transaction parameters. By integrating monitoring, you can get instant notifications for events like a whale accumulating tokens, a failed purchase due to slippage, or an unexpected contract interaction, allowing for proactive security and operational management.

To begin, you need a verified smart contract on a supported network like Ethereum, Arbitrum, or Polygon. After creating a Tenderly account and adding your project, use the Alerting feature to define your first Webhook Alert. You can trigger alerts based on various filters: - A specific event (e.g., TokensPurchased) is emitted. - A transaction calls a critical function (e.g., withdrawFunds). - A transaction value exceeds a threshold. - The transaction originates from a flagged address. This granularity lets you monitor precisely what matters for your sale's security.

For a token sale, a critical alert monitors large, rapid purchases that could indicate a bot or an attempt to manipulate the token distribution. Configure an alert for the buyTokens function where the msg.value parameter is greater than a set limit (e.g., 10 ETH). Use a State Diff filter to check if the buyer's token balance increased significantly. Send these alerts to a Slack channel, Discord webhook, or email to ensure your team is notified the moment the event occurs on-chain.

Here is a simplified example of a Node.js script that could be triggered by a Tenderly webhook to process an alert for a large purchase. It parses the transaction data and logs the details for further analysis.

javascript
// Example webhook handler for a large purchase alert
app.post('/tenderly-webhook', (req, res) => {
  const alert = req.body;
  // Extract key data from the Tenderly alert payload
  const txHash = alert.transaction.hash;
  const buyer = alert.transaction.from;
  const valueEth = alert.transaction.value / 1e18; // Convert from wei
  const eventLogs = alert.transaction.logs;

  console.log(`🚨 Large purchase detected!`);
  console.log(`Buyer: ${buyer}`);
  console.log(`Amount: ${valueEth} ETH`);
  console.log(`TX: https://etherscan.io/tx/${txHash}`);

  // Add your custom logic here (e.g., notify team, update dashboard)
  res.status(200).send('Alert received');
});

Beyond basic alerts, use Tenderly's Simulation feature to proactively test threat scenarios. Before your sale goes live, simulate transactions to see how your contract would behave under attack conditions, such as a flash loan attack or a reentrancy attempt. You can also set up Alert Actions to automatically respond to certain events, like pausing the sale contract via a multisig transaction if a critical vulnerability is detected. This creates a robust, automated defense layer for your on-chain operations.

Effective monitoring requires continuous refinement. Review your alert logs to identify false positives and adjust your filters. Monitor key metrics like the frequency of failed transactions or gas price spikes, which can indicate network congestion or malicious spam. By combining Tenderly's real-time alerts with proactive simulation and a clear response protocol, you transform on-chain monitoring from a passive watch into an active security system, significantly reducing your sale's operational risk.

implement-alerts-defender
TUTORIAL

Set Up Automated Alerts with OpenZeppelin Defender

Learn to configure real-time notifications for critical on-chain events to protect your token sale from exploits and operational failures.

Automated alerts are a critical component of secure smart contract management, allowing you to respond to threats before they escalate. For a token sale, key risks include unauthorized withdrawals, contract pausing, ownership transfers, and suspicious minting activity. OpenZeppelin Defender Sentinel is a service that monitors your contracts for these specific events by subscribing to on-chain logs. When a configured condition is met, it triggers a notification through channels like Slack, Telegram, Discord, or email, enabling immediate investigation.

To begin, you need a Defender account and an API key. Navigate to the Defender Admin and create a new Sentinel. The core configuration involves specifying the Contract Address, Network (e.g., Ethereum Mainnet, Arbitrum), and the Event Triggers. For a sale contract, essential events to monitor are:

  • Paused() and Unpaused() from the Pausable extension.
  • RoleGranted and RoleRevoked for access control changes.
  • OwnershipTransferred if using Ownable.
  • Custom events like TokensPurchased or FundsWithdrawn.

Defender uses a YAML-based condition language to filter events. A basic condition to alert on any pause action would be: event-signature: Paused() and event-signature: Unpaused(). For more granular control, you can filter by transaction parameters. For example, to only alert on withdrawals above a certain threshold, you could add: event-signature: Withdraw(address,uint256) and params.1 > 1000000000000000000 (1 ETH). This precision reduces alert fatigue and highlights only the most significant actions.

After defining conditions, configure the Notification Channels. Defender integrates directly with Slack, Telegram, Discord, and email. For each channel, you will need to provide webhook URLs or API tokens. The alert message is customizable using template variables like {{ transaction.hash }} and {{ block.number }}, allowing you to include direct links to Etherscan for rapid triage. It's best practice to set up a dedicated channel, like #defender-alerts, for your team's security notifications.

Finally, test your Sentinel by simulating the triggering event. For a Paused() event, you could manually pause your contract (if you have the pauser role) and verify the alert arrives as expected. Regularly review and update your Sentinel rules as your sale progresses through different phases—public mint, claim, or fund distribution—each of which may have unique risks. Combining Defender Sentinels with its Autotasks for automated responses creates a robust, proactive security layer for your on-chain operations.

frontend-analytics-bots
SECURITY

Monitor Frontend for Bots and Failed Txs

Learn how to implement real-time monitoring to detect malicious bots and analyze failed transactions, protecting your token sale's integrity and user experience.

Real-time frontend monitoring is a critical security layer for any token sale or decentralized application. It involves tracking user interactions and on-chain transaction attempts to identify patterns of malicious activity, such as sybil attacks, front-running bots, and wallet drainers. By analyzing failed transactions, you can distinguish between legitimate user errors and coordinated bot attacks that spam the network with reverting transactions to disrupt the sale. This proactive approach allows you to implement countermeasures before significant damage occurs.

To set up monitoring, you need to instrument your web application to capture key events. This includes tracking wallet connection attempts, transaction submissions, and their on-chain outcomes. Use a service like Chainscore's API to fetch real-time transaction data and statuses. For example, after a user submits a transaction via their wallet (e.g., MetaMask), your frontend should listen for the transaction hash and poll an endpoint to check its status (success, failed, pending). Failed transactions should be logged with metadata: the error reason, user's public address, gas parameters, and timestamp.

A common pattern for bot detection is analyzing the rate and origin of failed transactions. A single wallet address generating a high volume of failed approve() or buy() calls in a short timeframe is a strong indicator of a bot. Implement server-side logic to track these metrics. For instance, using a Node.js backend with Express and a database like PostgreSQL, you can create an endpoint that logs each transaction attempt and runs a query to flag addresses exceeding a threshold (e.g., 5 failed txs per minute).

Beyond simple rate limiting, advanced detection involves analyzing transaction revert reasons and calldata. Bots often fail transactions due to hardcoded, invalid parameters or attempts to exploit specific contract functions. By parsing the revert message from the Ethereum Virtual Machine (EVM)—accessible via RPC calls like eth_getTransactionReceipt—you can categorize failures. Common revert reasons for sales include "Insufficient payment", "Sale not active", or "Max purchase exceeded". A cluster of identical, rapid failures from different addresses suggests a botnet.

To visualize this data and set up alerts, integrate your logging system with a dashboard like Grafana or a dedicated security platform. Configure alerts to notify your team via Slack or Discord when anomalous activity is detected, such as a sudden spike in the failed transaction rate. This enables a swift response, which could involve temporarily adjusting smart contract parameters, deploying a CAPTCHA, or blacklisting malicious wallet addresses at the backend level before they can drain liquidity or block legitimate users.

Finally, complement your monitoring with preventative frontend measures. Implement proof-of-humanity checks like CAPTCHAs or interactive transaction simulations using tools like Tenderly or the eth_call RPC method before prompting a real wallet signature. This simulates the transaction and returns a revert reason client-side, preventing unnecessary on-chain failures. Continuously update your detection heuristics based on the attack patterns you observe, as bot strategies evolve rapidly in response to new defenses.

MONITORING GUIDE

Common Threat Scenarios and Alert Triggers

Key on-chain events that indicate potential threats to a token sale, with recommended monitoring triggers.

Threat ScenarioOn-Chain SignalRecommended Alert TriggerSeverity

Front-Running / MEV Attack

High gas price spike from known MEV bot addresses before user tx

Gas price > 500 Gwei from flagged address

High

Sybil Attack / Wallet Farming

Multiple new wallets receiving identical airdrop amounts from single funding source

50 wallets funded from same address in 1 hour

Critical

Liquidity Drain Attack

Large single swap (>30% of pool) on DEX post-sale

Swap size > $100k or 30% of pool liquidity

High

Flash Loan Price Manipulation

Rapid sequence of borrow, swap, and repay transactions on Aave/Compound

3+ borrow/swap/repay txs from same address in same block

Critical

Whale Wallet Dumping

Large token transfer from sale participant to a DEX router (e.g., Uniswap, 1inch)

Transfer > 5% of circulating supply to 0x... router address

High

Smart Contract Exploit

Unexpected function call to sale contract (e.g., emergencyWithdraw, admin function)

Any call to restricted function from non-admin address

Critical

Cross-Chain Bridge Arbitrage

Identical large deposit/withdrawal across multiple bridges (Wormhole, LayerZero) within minutes

$250k bridged within 5 min across 2+ bridges

Medium

incident-response-runbook
SECURITY

Create an Incident Response Runbook

A structured guide for preparing your team to detect and respond to security threats during a token sale or mint.

An incident response runbook is a predefined set of procedures for your security team to follow when a threat is detected. For a token sale, this means having clear, actionable steps for events like a smart contract exploit, a DDoS attack on your website, or a critical vulnerability in your minting mechanism. The goal is to minimize damage, restore normal operations, and preserve evidence. Without a runbook, teams waste precious time debating what to do while an attack unfolds. Your runbook should be a living document, stored in an accessible location like a private Notion page or GitHub repository, and reviewed before every major launch.

The first step is defining your incident severity levels. Categorize potential threats to prioritize response. A Severity 1 (Critical) incident might be active fund drainage from the sale contract or a complete frontend takedown. A Severity 2 (High) incident could be a surge in bot activity skewing the fair launch. Severity 3 (Medium) might be social engineering attempts against team members. For each level, specify the response team (e.g., lead developer, community manager, legal counsel), communication channels (e.g., a private War Room in Telegram or Discord), and the maximum time to acknowledge the alert (e.g., 5 minutes for Critical).

Next, establish your real-time monitoring and alerting setup. You need visibility into both on-chain and off-chain activity. For on-chain monitoring, use services like Chainscore, Tenderly Alerts, or OpenZeppelin Defender to watch for suspicious transactions, unexpected contract state changes, or abnormal withdrawal patterns from the sale wallet. For off-chain monitoring, configure alerts in your infrastructure (e.g., AWS CloudWatch, Datadog) for website uptime, API error rates, and bot traffic spikes from services like Cloudflare. All critical alerts should push to a dedicated channel like Slack or a paging service like PagerDuty to ensure immediate visibility.

The core of the runbook is the procedural playbook for each incident type. For a smart contract exploit, steps might include: 1) Confirm the exploit via block explorer and alert internal team, 2) Pause the contract if a pausable function is available (ensure private keys are secure and accessible), 3) Notify partners and liquidity providers, 4) Begin internal investigation and contact security auditors. For a DDoS attack, steps would involve: 1) Activate DDoS mitigation (e.g., Cloudflare "Under Attack" mode), 2) Switch to a static backup site if the primary is down, 3) Communicate transparently with the community about the issue via all social channels. Each step should list the responsible person and required tools.

Finally, incorporate post-incident analysis. After containing an incident, the team must conduct a formal review. This involves documenting the timeline, root cause, impact (e.g., funds lost, user count affected), and effectiveness of the response. The output is an action plan to improve systems—such as adding a new monitoring alert, modifying contract logic, or updating the runbook itself. This feedback loop is critical for hardening your security posture for future launches. Regularly tabletop exercise your runbook with the team to ensure everyone knows their role, which builds muscle memory and reveals gaps in your plans before a real crisis hits.

REAL-TIME MONITORING

Frequently Asked Questions

Common questions and troubleshooting for setting up real-time threat monitoring for your token sale or smart contract launch.

Real-time threat monitoring is a proactive security service that continuously scans the blockchain and associated infrastructure for malicious activity targeting your token sale or smart contract. It's critical because attacks like front-running, bot manipulation, and wallet draining often happen within seconds or minutes of a launch.

Key threats it detects:

  • Sybil attacks and wallet clustering
  • MEV bot front-running and sandwich attacks
  • Dusting attacks and phishing link deployments
  • Unusual gas price spikes indicative of an attack
  • Suspicious contract interactions from known malicious addresses

Without monitoring, you may only discover an exploit after significant funds are lost. Real-time alerts allow for immediate intervention, such as pausing a contract or adjusting sale parameters.

conclusion
IMPLEMENTATION SUMMARY

Conclusion and Next Steps

You have now configured a foundational real-time threat monitoring system for your token sale. This setup provides immediate visibility into critical on-chain risks.

Your monitoring dashboard should now be actively tracking key threat vectors: suspicious wallet clustering from services like Chainalysis or TRM Labs, smart contract exploits via platforms like Forta or OpenZeppelin Defender, and unusual liquidity movements on DEXs. The primary goal is to detect anomalies—such as a single entity acquiring a disproportionate share of tokens or a sudden, large withdrawal from the project's liquidity pool—before they impact the sale's integrity or token price.

To operationalize this system, establish clear response protocols. Define specific thresholds that trigger alerts, like a wallet receiving more than 5% of the total sale allocation or a contract interaction matching a known exploit signature. Assign team members to monitor the alert feeds during critical periods and create a runbook for common scenarios: - Pausing the sale via the pause() function in your ERC20Capped or ERC721 contract. - Blacklisting a malicious address using your access control functions. - Communicating transparently with your community about any protective actions taken.

For deeper analysis, integrate your monitoring tools with an on-chain analytics platform like Dune Analytics or Nansen. Create dashboards to visualize wallet behavior over time, track fund flows post-sale, and monitor the health of your token's liquidity pools on Uniswap V3 or Curve. This historical data is invaluable for post-mortem analysis and for demonstrating due diligence to investors and auditors.

Consider this setup a minimum viable monitoring stack. To enhance it, explore modular security services. Implement a bot protection solution like Jigger or AntiSniping to guard against MEV bots during the public sale. For long-term treasury management, use a multi-signature wallet solution like Safe{Wallet} with transaction policy engines. Regularly review and update the threat models for your specific tokenomics, as new attack vectors like donation attacks or liquidity pool manipulation constantly emerge.

Finally, document your security configuration and response procedures. This documentation is crucial for team onboarding, security audits by firms like OpenZeppelin or Trail of Bits, and for building trust with your community. Real-time monitoring is not a set-and-forget tool; it requires ongoing review and adaptation to the evolving threat landscape in decentralized finance.