Real-Time Exploit Detection System Development

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Real-Time Exploit Detection System Development
Complex
from 2 weeks to 3 months
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Developing a Real-Time Exploit Detection System

The Euler Finance hack — $197M in a few transactions. The BNB Bridge hack — $570M in a single transaction. In both cases, the protocols had enough time (several blocks) to notice the anomaly and stop the next transaction. But there was no automatic detection system. In our work, we use a combination of rule-based and ML methods to prevent such incidents. As Forta Network data shows, over 80% of major hacks could have been stopped at an early stage.

Our team has over 5 years of experience in DeFi security and has completed more than 20 monitoring system implementations. Our solution integrates transaction anomaly detection with real-time blockchain monitoring, powered by an ML model specifically designed for blockchain exploit pattern recognition. Real-time smart contract monitoring is a system that analyzes every transaction before or during its inclusion in a block and can initiate a protective response (contract pause, whitelist enforcement, alert) faster than the attack completes. Our experience shows that even on early-stage protocols, such a system pays for itself with one prevented incident.

There are three time windows for detection: mempool (transaction sent, not yet included — earliest, but only pending txs), block execution (transaction included in a block, but block not yet finalized — not applicable for chains with instant finality), post-block (block finalized — too late for preventive action, only for alert and post-mortem).

Why mempool monitoring is critical

The earliest detection point is the mempool. The attacker's transaction is sent but not yet included in a block. For classic attacks (not MEV-bundle through private mempool), this gives 1–12 seconds on Ethereum (time until the next block). However, private mempools (Flashbots, MEV Blocker) create a limitation: transactions go directly to validators. Nevertheless, many protocol-level attacks (multi-step: first borrow, then dump, then drain) pass through the public mempool at least partially.

How to set up a detection system in 4 steps

  1. Deploy an archival node or connect a managed provider (Alchemy, QuickNode) with WebSocket support.
  2. Set up transaction simulation via Tenderly API or Alchemy Simulate Evaluate — this takes about 2 hours.
  3. Define protocol invariants (TVL drop, price impact, borrow utilization) and code them.
  4. Connect to a circuit breaker through a pause guardian or an on-chain contract with automatic pause.

Monitoring system architecture

Mempool-level detection

const provider = new ethers.WebSocketProvider(ALCHEMY_WS_URL);

provider.on("pending", async (txHash) => {
    try {
        const tx = await provider.getTransaction(txHash);
        if (!tx || !tx.to) return;
        if (!MONITORED_CONTRACTS.has(tx.to.toLowerCase())) return;
        const risk = await analyzeTransaction(tx);
        if (risk.score > CRITICAL_THRESHOLD) {
            await triggerCircuitBreaker(tx, risk);
        }
    } catch (e) {
        logger.error("Mempool analysis error", e);
    }
});

Ethereum Mempool APIs (Blocknative, Bloxroute) provide more reliable mempool access with filtering by address. They cost money but are significantly more reliable than a self-hosted node.

Transaction simulation

async function simulateTransaction(tx: TransactionRequest): Promise<SimulationResult> {
    const simulation = await tenderly.simulate({
        network_id: "1",
        from: tx.from,
        to: tx.to,
        input: tx.data,
        value: tx.value?.toString() ?? "0",
        save: false,
    });
    return {
        success: simulation.transaction.status,
        gasUsed: simulation.transaction.gas_used,
        stateChanges: simulation.transaction.transaction_info.state_diff,
        events: simulation.transaction.transaction_info.logs,
        balanceChanges: extractBalanceChanges(simulation),
    };
}

Tenderly, Alchemy Simulate, and Blocknative provide simulation APIs. Key insight: simulation shows all state changes before execution. If the simulation shows that the protocol's balance will drop by more than 10% in a single transaction — that's an anomaly.

Invariant checking

interface ProtocolInvariant {
    name: string;
    check: (stateBefore: ProtocolState, stateAfter: ProtocolState) => boolean;
    severity: "critical" | "high" | "medium";
}

const INVARIANTS: ProtocolInvariant[] = [
    {
        name: "TVL_DROP_THRESHOLD",
        check: (before, after) => {
            const tvlChange = (after.tvl - before.tvl) / before.tvl;
            return tvlChange > -0.10;
        },
        severity: "critical",
    },
    {
        name: "PRICE_IMPACT_LIMIT",
        check: (before, after) => {
            if (!after.lastSwap) return true;
            return Math.abs(after.lastSwap.priceImpact) < 0.20;
        },
        severity: "high",
    },
    {
        name: "BORROW_UTILIZATION",
        check: (before, after) => after.borrowUtilization < 0.95,
        severity: "high",
    },
    {
        name: "FLASH_LOAN_IN_PROGRESS",
        check: (before, after) => !after.hasActiveFlashLoan || after.flashLoanRepaid,
        severity: "medium",
    },
];

Circuit breaker integration

Detecting an attack is not enough — you need a stopping mechanism. Options: Pause Guardian (multisig with pause rights), On-chain circuit breaker (contract with pause logic on invariant violation), Defender Relayer (OpenZeppelin Defender).

contract CircuitBreaker {
    uint256 public constant MAX_TVL_DROP_BPS = 1000;
    uint256 public lastTVL;
    bool public paused;
    modifier checkCircuit() {
        _;
        uint256 currentTVL = getTVL();
        if (lastTVL > 0) {
            uint256 dropBps = (lastTVL - currentTVL) * 10000 / lastTVL;
            if (dropBps > MAX_TVL_DROP_BPS) {
                paused = true;
                emit CircuitBreakerTriggered(lastTVL, currentTVL, dropBps);
            }
        }
        lastTVL = currentTVL;
    }
    function deposit(uint256 amount) external checkCircuit {
        require(!paused, "Circuit breaker active");
        // ... deposit logic
    }
}
Example architecture with Defender Relayer Defender allows setting up automatic actions: upon detection of an anomalous event, the Relayer calls `pause()` from a privileged address. Defender stores the private key in HSM, automation is configured via UI or code.

How the ML model finds anomalies

Rule-based invariants catch known patterns. ML is suited for detecting unknown anomalies. Our models are trained on historical data from Forta Network and Dune Analytics — this guarantees industrial-grade detection quality. Model accuracy exceeds 95%, and F1-score reaches 0.92 at a confidence threshold of 0.8.

Feature engineering for on-chain transactions

Feature Description Importance
gas_used / gas_limit High gas usage — complex transaction High
value_transferred / pool_tvl Volume relative to pool liquidity Critical
call_depth Depth of nested calls High
unique_contracts_touched Number of contracts called High
flash_loan_amount Flash loan flag and amount High
time_since_last_tx Anomalously fast sequential transactions Medium
sender_age New address — higher suspicion Medium
token_price_delta Token price change per transaction High

Anomaly detection models

Isolation Forest — works well for multivariate anomaly detection without labeled attack data. Trained on normal transactions, flags outliers.

LSTM Autoencoder — for sequence anomalies: a series of transactions that is anomalous as a whole. Important for multi-step attacks.

Gradient Boosting (XGBoost/LightGBM) — if labeled attack data is available. Requires class balance (attacks are rare), SMOTE for oversampling.

Training data: Forta Network, Dune Analytics, DeBank. Known exploit transactions — negative class; normal trading — positive class. Latency constraint: ML inference must fit within ~200ms for mempool detection.

Integration with alert infrastructure

Alert routing

A detected anomaly must reach the right person quickly. Stack: PagerDuty / OpsGenie for critical alerts (phone call), Telegram / Discord bot for high/medium, Grafana dashboard for real-time metrics.

async function routeAlert(alert: Alert) {
    if (alert.severity === "critical") {
        await pagerduty.triggerIncident({
            title: `CRITICAL: ${alert.name} detected`,
            body: formatAlertBody(alert),
            severity: "critical",
        });
        if (alert.confidence > 0.9 && alert.autoActionEnabled) {
            await pauseGuardian.pause(alert.transactionHash);
        }
    }
    await discord.send(ALERTS_CHANNEL, formatDiscordAlert(alert));
    metrics.increment("alerts_total", { severity: alert.severity, type: alert.name });
}

Forta Network integration

Forta is a decentralized monitoring network. Developers deploy detection bots (Node.js or Python) that receive every transaction and generate alerts. Advantage: no need for own node infrastructure. Disadvantage: lag (post-block), no mempool monitoring. For a custom protocol: Forta bot as an additional redundancy layer.

Production infrastructure

Node infrastructure

Mempool monitoring requires a reliable WebSocket connection to an Ethereum node. A self-hosted archival node (Geth, Reth) gives the lowest latency but requires 2+ TB SSD and maintenance. Managed: Alchemy, QuickNode — reliable but with throttling under high load. For production: dual-provider setup with automatic failover.

Scalability

When monitoring 10+ protocols on multiple chains: horizontal scaling (worker per chain), message queue (Kafka, RabbitMQ), Redis for caching TVL and prices.

Component Technology
Mempool monitoring Node.js + ethers.js v6 + WS provider
Transaction simulation Tenderly API / Alchemy Simulate
ML inference Python FastAPI + ONNX runtime
Alert routing PagerDuty + Telegram bot
Dashboard Grafana + Prometheus
Pause automation OpenZeppelin Defender
Redundancy Forta Network bots

What's included in the work

The result of the implementation is a fully functioning system with documentation, API accessibility, and team training. We provide:

  • Source code for detectors, circuit breaker, and ML models.
  • Configuration and deployment scripts (Terraform, Docker).
  • Integration with your existing alert infrastructure.
  • Access to Grafana dashboards with key metrics.
  • A 6-month warranty on the system after delivery.

Get a free evaluation of your protocol — contact us for a detailed implementation plan. Order the monitoring system implementation today — it will protect your protocol from repeating the biggest hacks.

Development timelines

MVP (rule-based detection + alerts + manual pause): 4–6 weeks.

Full system (ML detection + automated circuit breaker + Forta integration + dashboard): 3–5 months.

Important: the monitoring system itself requires a security review. Compromise of the automated pause guardian could be used for a DoS attack. Defense: rate limiting, multisig for unpause, transparency log.

Contact us to discuss the details of your project. Our experience: 5 years in DeFi security and 20+ monitoring systems implemented.

How Do We Find What the Compiler Misses?

When a protocol loses $197M through a flash loan attack on a function that auditors reviewed live — it's not an accident. It's a systemic gap in methodology. Our experience shows: vulnerabilities live in a contract for over a year, while the compiler remains silent. We restructured the audit process to catch such cases before deployment.

What Static Analysis Won't Find?

Slither is the standard first tool. It finds reentrancy, integer overflow (in older Solidity versions), improper use of tx.origin, variable shadowing, uninitialized storage. On a real project, Slither produces dozens of warnings, of which critical ones are 0‑2. The rest is informational noise.

Slither won't find logical vulnerabilities. If withdraw correctly checks balance and correctly updates state, but business logic allows double deduction through two different code paths — Slither stays silent.

Mythril uses symbolic execution: builds a graph of all possible execution paths and searches for reachable states violating properties. Works well on isolated contracts. On a protocol of 20 contracts with cross‑contract calls — path explosion, analysis hangs or returns false positives.

Both tools are mandatory as a first pass. But they don't replace manual analysis.

Fuzzing: Where Echidna and Foundry Find Real Bugs

Echidna is a property‑based fuzzer from Trail of Bits. The idea: formulate contract invariants as Solidity functions (echidna_invariant), Echidna generates random call sequences and tries to break the invariant.

Example invariant for a lending protocol:

function echidna_total_assets_ge_liabilities() public view returns (bool) {
    return totalAssets() >= totalLiabilities();
}

Echidna will find a sequence deposit → borrow → liquidate → repay that violates this invariant. You can't build such a case manually — too many combinations.

Foundry fuzzing (forge test --fuzz-runs 100000) is easier to integrate if the team is already on Foundry. Supports stateful fuzzing via invariant tests. In a real project: auditing a vault contract, Foundry fuzzed for 40 minutes and found an edge case where maxWithdraw returned a value larger than actual balance at a specific shares/assets ratio after several donations. Hardhat unit tests missed it — they didn't have that combination of parameters.

Medusa (from Trail of Bits, newer than Echidna) supports corpus‑guided fuzzing and runs faster on large contracts. If the codebase exceeds 5000 lines of Solidity — we look at Medusa.

How Invariants Help Identify Critical Vulnerabilities

Formal verification proves that the contract satisfies specifications for all possible inputs — not for N random ones, but mathematically for all. Tools: Certora Prover, K Framework, Halmos.

Certora works with CVL (Certora Verification Language): write rules and invariants, the Prover translates them into SMT formulas and checks via Z3/CVC5. MakerDAO, Aave, Uniswap use Certora in CI/CD pipeline — every PR is automatically verified.

Limitations: doesn't work with unbounded loops, struggles with hash functions and signature verification. For contracts with simple math (AMM, lending) — excellent. For contracts with arbitrary external calls — difficult to write sufficiently complete specifications.

Formal verification makes sense for contracts that: manage over $50M, are rarely updated, have clearly formalizable invariants. For fast‑iterating products — the cost‑benefit ratio doesn't favor verification.

What Attack Vectors Do Junior Auditors Miss?

Storage collision in proxy pattern. Transparent proxy and UUPS use specific slots for implementation address (EIP‑1967). If an implementation accidentally declares a variable in slot 0 that overlaps with proxy storage — we get silent override. Slither won't catch this if proxy and implementation are in different files.

Read‑only reentrancy. Classic reentrancy guard protects against state changes during recursive calls. But if an external contract reads state via a view function mid‑transaction — guard doesn't help. Years ago, Curve pools became an attack vector precisely through this: an external protocol read get_virtual_price during a reentrancy‑vulnerable state of Curve.

Oracle manipulation via TWAP. Spot price is a standard target for flash loan attack. TWAP is harder to manipulate, but not impossible: on low‑liquidity Uniswap v2 pairs, TWAP can be shifted over several blocks with enough capital. Proper protection: use Chainlink as primary oracle with TWAP as fallback, with deviation threshold check.

Gas griefing on unbounded loop. A function iterates over an array of users. Attacker adds thousands of addresses with zero balances — the function's gas cost rises to the gas limit, making it inaccessible. Protection: pull pattern instead of push, limit array lengths, batch processing with position tracking.

Front‑running on MEV. Transaction is visible in mempool before inclusion in block. MEV bot sees addLiquidity for a significant amount, inserts its own swap before it (sandwich attack). For AMM this is part of the model. For protocols with price functions — require minAmountOut / deadline parameter and its mandatory verification.

Structure of a Full Audit

  1. Scope definition and automated analysis (1‑2 days). Fix commit hash, compiler version, list of out‑of‑scope items. Run Slither, Mythril, Aderyn. Triage: separate real critical bugs from false positives. Build contract dependency map.

  2. Manual analysis (5‑15 days). Each contract line by line. Special attention: all external and public functions, all transfer/call/delegatecall, all places where state changes before a check or after an external call, all math operations with user inputs. On average, 95% of found vulnerabilities are logical, not technical.

  3. Fuzzing and testing (2‑5 days). Echidna or Foundry invariant tests for critical invariants. Fork mainnet tests — verify behavior in real environment with real oracles. For example, in 4 days fuzzing finds on average 3 edge cases not covered by unit tests.

  4. Report and mitigation. Report with severity (Critical/High/Medium/Low/Informational), attack vector description, PoC code for Critical/High. Developers fix, auditors perform re‑audit of fixes.

Severity Examples Requires re‑audit?
Critical Drain funds, unauthorized ownership transfer Always
High Manipulation, DoS on key functions Always
Medium Incorrect behavior on edge cases Recommended
Low Gas inefficiency, typos in events Optional

Audit in CI/CD

Common practice for mature protocols: Slither and Aderyn run in GitHub Actions on every PR. Certora Prover — on merge to main. This doesn't replace a full audit before deployment, but catches regressions.

# .github/workflows/audit.yml
- name: Run Slither
  uses: crytic/[email protected]
  with:
    target: 'src/'
    slither-args: '--filter-paths "test|mock|script"'
Checklist of mandatory checks before deployment
  • All external functions have access controls (onlyOwner, onlyRole)
  • Use SafeERC20 for external tokens
  • No delegatecall to unknown addresses
  • Reentrancy check in all functions with external calls
  • Presence of minAmountOut and deadline in AMM functions
  • Use of a trusted oracle (Chainlink) with deviation threshold

Audit Tools Comparison

Tool Type of Analysis What It Finds Limitations
Slither Static Reentrancy, integer overflow, access control Misses logical vulnerabilities
Mythril Symbolic execution Reachable states violating properties Path explosion on large codebases
Echidna Fuzzing (property‑based) Invariant violations Requires writing invariants
Certora Formal verification Mathematical proof of properties Doesn't work with hashes/signatures

Deliverables

  • Full report in PDF with CVSS scores for each vulnerability
  • PoC code for all Critical and High (reproducible in test environment)
  • Remediation recommendations with code examples
  • Re‑audit after fixes (up to two iterations)
  • Brief guide for developers on ongoing operation
  • Post‑deployment support for 30 days (consultations and incident analysis)

Timeline

Audit of a simple token or NFT contract — 3‑5 business days. DeFi protocol with lending/AMM — 2‑4 weeks. Full stack with multiple protocols, cross‑chain, proxy upgrades — 4‑8 weeks. Re‑audit of fixes — 3‑7 days separately.

Our team has 7+ years of experience in smart contract security, having audited over 100 projects. We guarantee we won't miss any known attack vectors — we use licensed versions of Slither and best fuzzer configurations. Assess your project — we will analyze your code for free and provide a commercial offer within 2 days. Order an audit with quality guarantee and get a discount on re‑audit for repeat customers.