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 Flash Loan Attack Detection

This guide provides a technical walkthrough for building a system to detect the preparatory and execution phases of a flash loan attack by monitoring for specific transaction patterns on-chain.
Chainscore © 2026
introduction
SECURITY GUIDE

Setting Up Real-Time Flash Loan Attack Detection

A technical walkthrough for developers to implement a monitoring system that identifies and alerts on suspicious flash loan activity on-chain.

Flash loans enable uncollateralized borrowing within a single transaction block, a feature exploited in numerous high-profile DeFi attacks. Real-time detection is critical because the attack lifecycle—borrow, manipulate, repay—completes before the block is finalized. To monitor this, you need to track specific on-chain events and transaction patterns. The core components are an EVM-compatible node (like Alchemy or a self-hosted Geth), an event listener, and a logic engine to analyze the data. This setup allows you to intercept malicious transactions as they occur, rather than analyzing them post-mortem.

Your detection system must listen for the FlashLoan event emitted by lending pools such as Aave V3 or the swap events from DEXs like Uniswap V3. In Solidity, the Aave event is typically defined as event FlashLoan(address indexed target, address initiator, address asset, uint256 amount, uint256 premium). Using a library like ethers.js or viem, you can create a script that subscribes to these logs. The key is filtering for transactions where the borrowed amount exceeds a sensible threshold for normal use—often hundreds of thousands or millions of dollars in value—which is a primary signal of potential market manipulation.

Analyzing Transaction Traces

Beyond simple event listening, effective detection requires analyzing the full transaction trace. A flash loan attack involves a sequence of actions: the loan, a series of swaps to manipulate an oracle or pool price, and a final swap or liquidation to profit. By using a node's debug_traceTransaction RPC method, you can programmatically reconstruct the call path. Look for patterns like a large loan from a known pool (0x...) followed by multiple swaps on a DEX, and finally a large transfer to a contract like MEV Bot: 0x000.... This trace analysis separates complex arbitrage from outright manipulation.

To operationalize this, implement a scoring heuristic. Assign risk points for: - Loan size exceeding 5% of the pool's liquidity - Multiple large swaps across correlated assets within the same transaction - Interactions with known, often-manipulated price oracles like Chainlink - Final profit sent to a new or non-interacted-with address. A script running this logic can then trigger an alert via a webhook to Discord, Telegram, or a security dashboard. For scalability, consider using The Graph to index historical flash loan data and establish baseline patterns for more accurate anomaly detection.

Maintaining this system requires constant updates. Attackers adapt, using new protocols or obfuscation techniques like intermediate proxy contracts. Regularly update your list of monitored lending pool addresses (from Aave, dYdX, Balancer) and DEX routers. Incorporate blockchain intelligence from platforms like Chainalysis or TRM Labs to flag addresses associated with known exploits. Open-source tools like Forta Network bots can provide a foundation, but for proprietary protection, a custom detection layer tuned to your protocol's specific liquidity pools and price feeds is essential.

prerequisites
REAL-TIME DETECTION

Prerequisites and Setup

Configure your environment to monitor for flash loan attacks on EVM-compatible blockchains.

To build a real-time flash loan attack detection system, you need a development environment capable of listening to and analyzing on-chain transactions. The core requirements are: a Node.js runtime (v18 or later) for running the detection scripts, a Web3.js or Ethers.js library to interact with the blockchain, and access to a JSON-RPC node provider like Alchemy, Infura, or a self-hosted node. This setup allows you to subscribe to pending transactions and new blocks, which is the foundation for live monitoring.

You must also understand the key signatures of a flash loan attack. This involves monitoring for specific patterns in transaction mempools and executed blocks, such as large, complex bundles of transactions originating from a single address. The primary indicators are: a flash loan origination from a protocol like Aave or dYdX, followed by a series of swap operations across multiple DEXs to manipulate an asset's price, and concluding with a liquidation or arbitrage action that repays the loan and captures profit, all within a single block.

For effective detection, implement listeners for critical events. Using Ethers.js, you can create a provider subscription: provider.on('pending', (txHash) => { analyzeTransaction(txHash) }). The analyzeTransaction function should decode the transaction's input data to identify calls to known flash loan contracts and trace the flow of funds. Setting up a local database (e.g., PostgreSQL) or cache (Redis) to track suspicious address patterns and token price deviations across blocks is also recommended for historical analysis.

Finally, integrate with on-chain data sources for accuracy. Use price oracles like Chainlink to establish baseline asset values and query liquidity pool reserves from DEXs like Uniswap V3 to calculate real-time price impacts. Your detection logic should flag transactions where the calculated price slippage from a swap exceeds a defined threshold (e.g., 5-10%) immediately after a large loan is taken, as this is a strong signal of market manipulation.

key-concepts-text
FLASH LOAN DETECTION

Key Attack Patterns to Monitor

Flash loan attacks exploit uncollateralized borrowing to manipulate DeFi protocols. This guide explains how to set up real-time detection for common attack patterns.

Flash loans allow users to borrow large sums of assets without collateral, provided the loan is repaid within a single blockchain transaction. While a legitimate tool for arbitrage and refinancing, they are frequently weaponized. Attackers use these loans to temporarily control massive capital, enabling market manipulation, price oracle exploitation, and governance attacks. Real-time detection focuses on identifying the transaction patterns and on-chain footprints that signal malicious intent, rather than the flash loan itself.

The most common pattern is the oracle manipulation attack. Here, an attacker uses a flash loan to drain a lending protocol like Aave or Compound. The steps are: 1) Borrow a large amount of asset A via flash loan. 2) Swap asset A for asset B on a low-liquidity DEX, artificially inflating asset B's price. 3) Use the overvalued asset B as collateral to borrow more of other assets from a lending pool. 4) Repay the initial flash loan, keeping the stolen funds. Detection systems monitor for extreme price deviations on decentralized oracles and large, circular swaps within a single transaction.

Another critical pattern is the governance attack. Projects like MakerDAO or Uniswap use governance tokens for voting. An attacker can borrow a majority of tokens via flash loan, push through a malicious proposal (e.g., to drain the treasury), and vote it through—all before returning the tokens. Monitoring for sudden, large token inflows to a voting contract, followed by a proposal creation and vote within the same block, is key. Tools like Tally and OpenZeppelin Defender can be configured with custom alert rules for such events.

To build a detection system, you need to track specific smart contract events and transaction parameters. Key data points include: transaction hash, involved addresses, asset amounts, and the sequence of internal calls. Services like Chainscore, Tenderly, and Forta Network provide streams of real-time transaction data. You can write detection bots that analyze this data, looking for thresholds like swap size (>$1M), price impact (>30%), or interactions with known vulnerable contract patterns.

Here is a simplified example of a detection rule written in JavaScript for a Forta bot, looking for large swaps followed by lending pool interactions:

javascript
async function handleTransaction(txEvent) {
  const largeSwaps = txEvent.filterLog(swapEventAbi);
  const borrows = txEvent.filterLog(borrowEventAbi);
  if (largeSwaps.length > 0 && borrows.length > 0) {
    const swapAmount = largeSwaps[0].args.amountIn;
    if (swapAmount > ONE_MILLION_DOLLARS) {
      return {
        alertId: 'FLASH-LOAN-ATTACK',
        severity: FindingSeverity.High,
        metadata: { swapAmount: swapAmount.toString() }
      };
    }
  }
}

This bot triggers an alert if a single transaction contains both a large swap and a borrow event, a hallmark of many attack patterns.

Effective monitoring requires combining automated alerts with human analysis. Set up alerts for: single-block profit (a wallet's balance change exceeding a threshold), repeated failed transactions (probing for vulnerabilities), and interaction with newly deployed contracts. Keep detection rules updated, as attackers constantly evolve their methods. Integrating with incident response platforms like OpenZeppelin Defender Sentinels or setting up Slack/Telegram webhooks ensures your team can react immediately to potential threats.

detection-components
SETTING UP REAL-TIME FLASH LOAN ATTACK DETECTION

Core Components of a Detection System

A robust detection system requires specific technical components working in concert to identify malicious transactions before they finalize.

02

Anomaly Detection & Heuristics

Simulation results must be analyzed against a set of predefined heuristics. Key signals for flash loan attacks include:

  • Extreme leverage ratios: Borrowed amount vastly exceeding collateral
  • Multi-step arbitrage paths across 3+ DEXs in a single transaction
  • Targeted liquidity removal from a specific pool
  • Abnormal profit margins (e.g., >50% ROI in one block) These rules should be codified and weighted, with thresholds tuned to minimize false positives while catching novel attack vectors.
04

Alerting & Response Layer

When an attack is detected, the system must trigger an immediate response. This layer handles:

  • Priority Alerting: Sending notifications via PagerDuty, Telegram bots, or SMS
  • Automated Mitigation: Executing pre-defined counter-transactions (e.g., pausing a vulnerable contract) via Gelato or Keep3r networks
  • Dashboard Logging: Recording all flagged transactions, heuristics triggered, and false positives for post-mortem analysis and rule refinement.
05

Attack Pattern Database

Maintain a database of known and suspected attack signatures. This should include:

  • Transaction Hashes from historical exploits (Euler, Cream Finance, etc.)
  • Malicious Contract Addresses and deployer patterns
  • Function Signature Patterns commonly abused in price manipulation This database feeds into the heuristics engine and allows for pattern-matching against new pending transactions, providing a first line of defense against copycat attacks.
06

Performance & Scalability

A production system must handle peak load. Key considerations:

  • Parallel Simulation: Running multiple simulations concurrently to keep up with mempool volume
  • Gas Estimation: Accurately predicting gas for the malicious tx to ensure your mitigation tx lands first
  • Cost Management: Simulation and mitigation transactions incur real gas costs; budgets and efficiency are crucial. Systems that cannot process transactions faster than block time (e.g., ~12 seconds on Ethereum) are ineffective.
DETECTION METHODS

Flash Loan Attack Indicator Matrix

Comparison of on-chain data patterns and their effectiveness for identifying potential flash loan attacks in real-time.

Detection IndicatorHigh-Frequency MonitoringAnomaly Detection EngineManual Analysis

Large, Single-Block Loan Size

Profit-to-Loan Ratio > 1000%

Multi-Step Arbitrage Path Complexity

Oracle Price Manipulation Detection

Response Time to Alert

< 2 seconds

< 5 seconds

30 minutes

False Positive Rate

0.5%

2-5%

N/A

Coverage for New Attack Vectors

Low

High

Medium

Required Technical Expertise

Low

High

Expert

step-1-monitor-loans
REAL-TIME DETECTION

Step 1: Monitor Flash Loan Contracts for Large Borrows

The first line of defense against flash loan exploits is establishing a real-time monitoring system for large borrows. This step focuses on tracking the primary entry points for these attacks.

Flash loan attacks begin when an attacker borrows a significant amount of capital from a lending pool like Aave, dYdX, or Uniswap V3. To detect this, you need to monitor the specific smart contracts that facilitate these uncollateralized loans. The key is to track the flashLoan or flashSwap function calls on these protocols. For instance, on Aave V3, you would listen for events emitted by the Pool contract (e.g., 0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2 on Ethereum mainnet) when a flash loan is executed. Setting up a blockchain indexer or using a service like The Graph to subscribe to these events is the foundational step.

The monitoring logic must filter for borrows that exceed a predefined threshold, which indicates potential malicious intent rather than regular usage. For example, you might set an alert for any single flash loan exceeding $1 million in value. This requires calculating the USD value of the borrowed assets using an oracle or price feed at the time of the transaction. Your detection script should decode the transaction input data to extract the amount parameter and the asset address, then cross-reference it with a real-time price from Chainlink or a similar decentralized oracle network to assess the fiat value.

Implementing this involves writing a script, often in JavaScript or Python, that connects to a node provider like Alchemy or Infura. The script uses the Web3.js or Ethers.js library to listen for new blocks, parse transaction receipts, and check for interactions with the target flash loan contracts. Here is a simplified conceptual outline:

javascript
// Pseudo-code for monitoring Aave V3 flash loans
const loanEvent = poolContract.filters.FlashLoan();
poolContract.on(loanEvent, (initiator, target, asset, amount, premium, referralCode) => {
  const usdValue = await getAssetValueInUSD(asset, amount);
  if (usdValue > THRESHOLD) {
    triggerAlert(`Large flash loan detected: $${usdValue} of ${asset}`);
  }
});

This continuous stream of data forms the raw input for your detection pipeline.

Beyond simple value thresholds, consider monitoring the destination of the borrowed funds. Flash loans for legitimate purposes (e.g., arbitrage, collateral swapping) are often repaid within the same transaction to a known DeFi protocol. Suspicious activity may involve sending funds to a newly deployed or obscure contract. By analyzing the transaction trace, you can see if the borrowed assets are being routed through multiple protocols in a complex sequence designed to manipulate prices—a hallmark of an attack. Integrating with a tracing node or using a service like Tenderly for simulation can provide this deeper insight.

Finally, ensure your monitoring system is resilient and low-latency. Flash loan attacks are executed and completed within a single blockchain block, often in under 15 seconds. Your detection must operate at block-time speed to have any chance of providing an early warning. This requires a robust infrastructure with redundant node connections and efficient event processing logic to avoid falling behind the chain head, which would render your alerts useless for proactive defense.

step-2-trace-transaction
DETECTION LOGIC

Step 2: Trace the Transaction's Internal Calls

To detect a flash loan attack, you must analyze the sequence of internal calls within a transaction, not just its final outcome. This step focuses on identifying the specific on-chain patterns that signal malicious intent.

A flash loan attack is not a single function call but a complex, multi-step transaction. Your detection system must trace the entire call tree. Start by using an Ethereum node's debug_traceTransaction RPC method or a service like Alchemy's Trace API. This returns a detailed log of every CALL, DELEGATECALL, STATICCALL, and CREATE operation, along with their inputs, outputs, and gas usage. This trace is your primary data source for identifying attack vectors like price manipulation, collateral swapping, or governance exploits.

Within the trace, search for the hallmark pattern: a large, uncollateralized loan followed by a series of state-changing operations, and finally, loan repayment—all within one block. Key indicators include: a call to a lending pool (e.g., Aave's flashLoan or dYdX's operate), subsequent swaps on a DEX that could manipulate a price oracle, and a final call to repay the loan. The profit is often extracted via an arbitrage swap or by liquidating undercollateralized positions created by the manipulated prices.

For accurate detection, implement logic to calculate the profit delta. Compare the attacker's token balances before the first call and after the final call in the trace. A significant positive delta, especially when combined with the loan pattern, is a strong signal. Use libraries like ethers.js or web3.py to decode the input data for each call, parsing function selectors and arguments to understand the exact operations performed, such as which pools were targeted and which price oracles were affected.

Optimize your tracer for real-time use. Processing full traces for every pending transaction is computationally expensive. Implement a filtering layer that first screens for high-value transactions or interactions with known DeFi protocol addresses before initiating a full trace. Services like Tenderly or OpenZeppelin Defender can help streamline this process by providing webhook-based alerts for specific trace patterns, allowing you to focus your custom analysis on high-risk candidates.

step-3-analyze-arbitrage
DETECTION LOGIC

Step 3: Identify Arbitrage and Profit Extraction

This section details the core detection logic for identifying profitable arbitrage opportunities from flash loan transactions.

The detection process begins by filtering for successful flash loan transactions. We analyze the transaction's internal call trace, focusing on the sequence of operations after the loan is taken and before it is repaid. The key is to identify a profitable delta between the starting and ending balance of a specific token, typically a stablecoin like DAI or USDC, within the same transaction. This delta represents the arbitrage profit extracted by the attacker's contract before the flash loan is repaid. Tools like Tenderly's debugger or the debug_traceTransaction RPC method are essential for this deep transaction inspection.

A profitable pattern often follows this structure: 1) Borrow asset X via flash loan, 2) Swap X for asset Y on DEX A, 3) Swap Y back for X on DEX B, 4) Repay the flash loan of X, 5) Keep the surplus X as profit. Your detection script must calculate the net change in the balance of the borrowed asset held by the attacker's contract. This is done by tracking balanceOf calls for the contract address at the start and end of the traced execution, accounting for the repayment. A positive net change after repayment confirms profit extraction.

Here is a simplified conceptual check in pseudocode:

python
loan_amount = 1_000_000 * 10**18  # 1M DAI
repaid_amount = loan_amount + fee
final_balance = get_balance(attacker_contract, DAI, at_block='final')
initial_balance = get_balance(attacker_contract, DAI, at_block='initial')

# Profit is the DAI left after accounting for the loan and fee
profit = final_balance - initial_balance - repaid_amount
if profit > 0:
    log_arbitrage(tx_hash, profit)

In reality, you must parse the low-level call trace to find these balance snapshots, as the initial balance is often zero.

Beyond simple DEX arbitrage, be aware of complex strategies involving multiple protocols. An attacker might use a flash loan to: manipulate an oracle price on a lending platform to enable an undercollateralized borrow, perform a liquidation with skewed pricing, or create a large imbalance in a Curve pool to exploit its get_virtual_price. Each strategy leaves a distinct signature in the transaction trace—a series of calls to specific contract functions like swap, add_liquidity, or liquidate. Mapping common function selectors to known protocols (Uniswap V2: 0x022c0d9f, Aave: 0x617ba037) helps classify the attack vector.

Finally, to operationalize this, your detection system should subscribe to pending transactions via a WebSocket connection to an Ethereum node or use a service like Alchemy's alchemy_pendingTransactions. For each transaction, quickly simulate it using eth_call on a forked network or analyze its calldata for known flash loan pool addresses (e.g., Aave's LendingPool, dYdX's SoloMargin, Uniswap V3 flash loans). Flagging transactions before they are mined allows for real-time alerts, though profit confirmation requires the transaction receipt to analyze the final state changes.

step-4-configure-alerts
IMPLEMENTATION

Step 4: Configure and Send Real-Time Alerts

This step details how to configure alerting logic and integrate with notification services to receive immediate warnings about suspicious flash loan activity on your monitored protocols.

After your detection system identifies a potential flash loan attack, the next critical step is to configure the alerting pipeline. This involves defining the logic for what constitutes an alert-worthy event and formatting the data payload. A typical alert trigger is a transaction where the borrowed amount exceeds a predefined threshold (e.g., $1M in ETH) and results in a significant profit for the attacker (e.g., >$100k) within the same block. You should also filter for known benign protocols like DEX arbitrage bots by whitelisting their contract addresses.

The alert payload must be structured to provide actionable intelligence. It should include the transaction hash, the attacker's address, the exploited protocol, the flash loan pool used (e.g., Aave, dYdX), the borrowed amount in USD, the estimated profit, and a link to the block explorer. This data allows your security team to quickly assess the severity and begin mitigation procedures, such as pausing vulnerable contracts if you have admin controls.

For delivery, integrate with real-time notification services. A common approach is to use webhook integrations with platforms like Discord, Slack, Telegram, or PagerDuty. Your monitoring script should serialize the alert payload into JSON and send an HTTP POST request to your configured webhook URL. For maximum reliability, implement retry logic for failed sends and consider using a message queue like RabbitMQ to handle alert bursts during widespread market events.

Here is a simplified Python example using the requests library to send a Discord alert:

python
import requests
WEBHOOK_URL = "your_discord_webhook_url_here"
alert_data = {
    "content": "🚨 FLASH LOAN ALERT",
    "embeds": [{
        "title": "High-Value Attack Detected",
        "fields": [
            {"name": "Protocol", "value": "Uniswap V3", "inline": true},
            {"name": "Borrowed", "value": "$2.1M (WETH)", "inline": true},
            {"name": "Tx Hash", "value": "0xabc...123"}
        ]
    }]
}
response = requests.post(WEBHOOK_URL, json=alert_data)

Finally, establish an alert triage and response protocol. Not all alerts will be critical exploits; some may be false positives or non-malicious arbitrage. Define clear severity levels (e.g., Critical, High, Medium) based on profit amount and protocol TVL impact. Critical alerts should trigger immediate on-call pages, while lower-severity alerts can be logged for daily review. Regularly review and tune your detection thresholds to balance alert sensitivity with signal-to-noise ratio, using historical attack data from platforms like Rekt for calibration.

FLASH LOAN DETECTION

Frequently Asked Questions

Common questions and troubleshooting for developers implementing real-time flash loan attack monitoring.

A flash loan attack is a DeFi exploit where a malicious actor borrows a large, uncollateralized loan within a single blockchain transaction, manipulates on-chain prices or protocols, and repays the loan before the transaction ends, profiting from the manipulation. Real-time detection is critical because these attacks unfold and conclude within seconds. By the time a block explorer shows the transaction, the attacker's funds are gone. Detection systems must analyze pending transactions in the mempool to identify attack patterns before they are finalized, enabling protocols to potentially front-run or block the malicious transaction.

conclusion-next-steps
IMPLEMENTATION GUIDE

Conclusion and Next Steps

You have configured a real-time monitoring system for flash loan attacks. This section outlines how to operationalize your detection logic and expand your security coverage.

Your detection system is now configured to listen for events like FlashLoan on Aave V3 and monitor for large-scale arbitrage or liquidation patterns. The next step is to integrate this logic into your operational workflow. For a production environment, you should deploy your listener to a reliable server or serverless function (e.g., AWS Lambda, Google Cloud Functions) and connect it to a dedicated WebSocket endpoint from a node provider like Alchemy or Infura for uninterrupted data flow. Implement robust error handling and reconnection logic to maintain 24/7 surveillance.

To make your alerts actionable, integrate the detection output with notification channels. You can use the axios library to send HTTP POST requests to services like Slack, Discord, or PagerDuty when an attack signature is identified. Format your alert to include critical details: the transaction hash, the protocol involved (e.g., Aave, dYdX), the profit amount in USD, and a direct link to a block explorer like Etherscan. This allows your security team to investigate potential threats within seconds.

Consider expanding your detection parameters beyond simple profit thresholds. Sophisticated attacks may involve multiple transactions across several blocks or exploit price oracle manipulations. You can enhance your script by tracking token price deviations on DEXs like Uniswap or monitoring for sudden, large withdrawals from lending pools that precede an attack. Incorporating machine learning models to analyze transaction sequence patterns can further reduce false positives and identify novel attack vectors.

Finally, continuous improvement is key. Subscribe to security bulletins from platforms like DeFiYield and Rekt, and monitor forums for emerging attack methodologies. Regularly backtest your detection logic against historical flash loan attacks (e.g., the PancakeBunny or Cream Finance exploits) to validate its effectiveness. By maintaining and evolving this system, you transition from reactive security to proactive risk management, safeguarding your protocol's assets and user funds in real-time.