Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
143 changes: 143 additions & 0 deletions defi-automation/mev-detection-trap/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
# MEV Detection Trap

A comprehensive system of smart contract traps for detecting and responding to MEV (Maximal Extractable Value) activities on Ethereum and other EVM-compatible chains.


Common MEV activities include:
- **Sandwich Attacks**: Front-running and back-running large trades
- **Arbitrage**: Exploiting price differences across DEXs
- **Liquidation**: Profiting from liquidated positions
- **Front-running**: Executing trades before others based on pending transactions

## 🚀 Features

### 1. **MEVDetectionTrap** - General MEV Detection
- **Multi-DEX Monitoring**: Tracks multiple decentralized exchanges simultaneously
- **Pattern Recognition**: Identifies various MEV patterns using time-series analysis
- **Configurable Thresholds**: Adjustable parameters for different detection sensitivity
- **Real-time Alerts**: Immediate notification when MEV activities are detected

### 2. **SandwichAttackTrap** - Specialized Sandwich Detection
- **Advanced Pattern Recognition**: Sophisticated algorithms for detecting sandwich attacks
- **Historical Data Analysis**: Uses historical trading data for pattern validation
- **Volume Analysis**: Monitors unusual volume spikes and ratios
- **Timing Analysis**: Detects transactions that are suspiciously close together

### 3. **MEVResponse** - Automated Response System
- **Multi-Strategy Responses**: Different response strategies for different MEV types
- **Rate Limiting**: Configurable cooldown periods and execution limits
- **Emergency Controls**: Ability to pause responses in emergency situations
- **Event Logging**: Comprehensive logging of all detected activities and responses

## 🏗️ Architecture

```
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ MEV Traps │ │ Drosera │ │ Response │
│ │ │ Protocol │ │ Contracts │
│ • Collect Data │───▶│ • Run Logic │───▶│ • Execute │
│ • Analyze │ │ • Monitor │ │ • Alert │
│ • Detect │ │ • Trigger │ │ • Respond │
└─────────────────┘ └──────────────────┘ └─────────────────┘
```

## 📊 Detection Capabilities

### Sandwich Attack Detection
- **Volume Pattern Analysis**: Detects small → large → small trade patterns
- **Price Impact Monitoring**: Tracks significant price movements
- **Timing Analysis**: Identifies transactions executed in rapid succession
- **Gas Price Spikes**: Monitors for unusual gas price increases

### Arbitrage Opportunity Detection
- **Cross-DEX Price Monitoring**: Tracks price differences across exchanges
- **Threshold-Based Alerts**: Configurable profit thresholds
- **Real-time Analysis**: Continuous monitoring of arbitrage opportunities

### MEV Bot Activity Detection
- **Gas Price Anomalies**: Detects unusually high gas prices
- **Transaction Timing**: Identifies rapid successive transactions
- **Pattern Recognition**: Recognizes typical MEV bot behavior

### Suspicious Pattern Detection
- **Volume Anomalies**: Detects unusual trading volume patterns
- **Statistical Analysis**: Uses statistical methods to identify outliers
- **Multi-Factor Analysis**: Combines multiple indicators for detection

## 🛠️ Installation & Setup

### Prerequisites
- [Foundry](https://getfoundry.sh/) (latest version)
- Node.js 16+ and npm/yarn
- Access to Ethereum RPC endpoints

### Quick Start

1. **Install Dependencies**
```bash
forge install
```

2. **Build Contracts**
```bash
forge build
```

3. **Run Tests**
```bash
forge test
```

### Threshold Configuration

The traps use configurable thresholds that can be adjusted based on your needs:

```solidity
// MEVDetectionTrap thresholds
uint256 constant MIN_SANDWICH_THRESHOLD = 0.5e18; // 50% price impact
uint256 constant MAX_ARBITRAGE_THRESHOLD = 0.02e18; // 2% arbitrage threshold
uint256 constant MIN_MEV_PROFIT_THRESHOLD = 0.1e18; // 0.1 ETH minimum profit
uint256 constant SUSPICIOUS_GAS_THRESHOLD = 1000; // 1000 gwei gas price

// SandwichAttackTrap thresholds
uint256 constant MIN_PRICE_IMPACT = 0.1e18; // 10% minimum price impact
uint256 constant MAX_TIME_BETWEEN_TXS = 3; // 3 seconds max between transactions
uint256 constant MIN_VOLUME_RATIO = 5; // 5x volume ratio threshold
uint256 constant SUSPICIOUS_GAS_MULTIPLIER = 2; // 2x gas price multiplier
```

## 🔧 Usage Examples

### Adding Monitored DEXs

```solidity
// Add a new DEX to monitor
mevTrap.addMonitoredDEX(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Uniswap V2
mevTrap.addMonitoredDEX(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Uniswap V3
```

### Adding Known MEV Bots

```solidity
// Add known MEV bot addresses for tracking
mevTrap.addKnownMEVBot(0x1234567890123456789012345678901234567890);
```

### Event Logging

All activities are logged with comprehensive events:

```solidity
event SandwichAttackDetected(
uint256 indexed blockNumber,
uint256 timestamp,
address[] involvedAddresses,
uint256 estimatedProfit
);

event ResponseExecuted(
uint256 indexed blockNumber,
MEVType mevType,
bytes responseData
);
```
30 changes: 30 additions & 0 deletions defi-automation/mev-detection-trap/drosera.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
ethereum_rpc = "https://ethereum-hoodi-rpc.publicnode.com"
drosera_rpc = "https://relay.hoodi.drosera.io"
eth_chain_id = 560048
drosera_address = ""

[traps]

[traps.mev_detection_monitor]
path = "out/MEVDetectionTrap.sol/MEVDetectionTrap.json"
response_contract = "0x0000000000000000000000000000000000000000" # would be MEVResponse contract address
response_function = "handleMEVAlert(bytes)" # function to handle MEV alerts
cooldown_period_blocks = 10
min_number_of_operators = 3
max_number_of_operators = 8
block_sample_size = 15
private_trap = false
whitelist = []
address = "0x0000000000000000000000000000000000000000" # deployed trap address

[traps.sandwich_attack_monitor]
path = "out/SandwichAttackTrap.sol/SandwichAttackTrap.json"
response_contract = "0x0000000000000000000000000000000000000000" # would be MEVResponse contract address
response_function = "handleMEVAlert(bytes)" # function to handle sandwich attack alerts
cooldown_period_blocks = 5
min_number_of_operators = 2
max_number_of_operators = 6
block_sample_size = 20
private_trap = false
whitelist = []
address = "0x0000000000000000000000000000000000000000" # deployed trap address
12 changes: 12 additions & 0 deletions defi-automation/mev-detection-trap/foundry.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[profile.default]
src = "src"
out = "out"
libs = ["node_modules"]
remappings = [
"forge-std/=node_modules/forge-std/src/",
"contracts/=node_modules/contracts/src/"
]

[rpc_endpoints]
mainnet = "https://eth.llamarpc.com"

11 changes: 11 additions & 0 deletions defi-automation/mev-detection-trap/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "@trap-examples/defi-automation/mev-detection-trap",
"version": "1.0.0",
"description": "Comprehensive MEV detection traps for identifying sandwich attacks, arbitrage opportunities, and suspicious trading patterns",
"devDependencies": {
"forge-std": "^1.7.1"
},
"dependencies": {
"contracts": "https://github.com/drosera-network/contracts"
}
}
156 changes: 156 additions & 0 deletions defi-automation/mev-detection-trap/script/Deploy.s.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {Script, console2} from "forge-std/Script.sol";
import {MEVDetectionTrap} from "../src/MEVDetectionTrap.sol";
import {SandwichAttackTrap} from "../src/SandwichAttackTrap.sol";
import {MEVResponse} from "../src/MEVResponse.sol";

contract DeployScript is Script {
MEVDetectionTrap public mevTrap;
SandwichAttackTrap public sandwichTrap;
MEVResponse public mevResponse;

address public mevTrapAddress;
address public sandwichTrapAddress;
address public mevResponseAddress;

address public deployer;
address public trapConfig;

function setUp() public {
deployer = msg.sender;
trapConfig = deployer; // For now, deployer is also trap config
}

function run() public {
console2.log("Starting MEV Detection Trap deployment...");
console2.log("Deployer:", deployer);
console2.log("Chain ID:", block.chainid);

vm.startBroadcast(deployer);

// Deploy MEV Response contract first
console2.log("Deploying MEVResponse contract...");
mevResponse = new MEVResponse(trapConfig);
mevResponseAddress = address(mevResponse);
console2.log("MEVResponse deployed at:", mevResponseAddress);

// Deploy main MEV Detection Trap
console2.log("Deploying MEVDetectionTrap contract...");
mevTrap = new MEVDetectionTrap();
mevTrapAddress = address(mevTrap);
console2.log("MEVDetectionTrap deployed at:", mevTrapAddress);

// Deploy specialized Sandwich Attack Trap
console2.log("Deploying SandwichAttackTrap contract...");
sandwichTrap = new SandwichAttackTrap();
sandwichTrapAddress = address(sandwichTrap);
console2.log("SandwichAttackTrap deployed at:", sandwichTrapAddress);

vm.stopBroadcast();

console2.log("Configuring contracts...");
_configureContracts();
_displayDeploymentSummary();
_saveDeploymentAddresses();
}

function _configureContracts() internal {
vm.startBroadcast(deployer);

console2.log("Adding popular DEX addresses...");

// Uniswap V2 Router
mevTrap.addMonitoredDEX(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);

// Uniswap V3 Router
mevTrap.addMonitoredDEX(0xE592427A0AEce92De3Edee1F18E0157C05861564);

// SushiSwap Router
mevTrap.addMonitoredDEX(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);

// Add some known MEV bot addresses (this would be updated with real addresses)
console2.log("Adding known MEV bot addresses...");
mevTrap.addKnownMEVBot(0x0000000000000000000000000000000000000000);

console2.log("Adding popular DEX pairs...");

// Example pairs (replace with real addresses)
sandwichTrap.addMonitoredAddress(0x0000000000000000000000000000000000000000);
sandwichTrap.addMonitoredAddress(0x0000000000000000000000000000000000000000);
sandwichTrap.addMonitoredAddress(0x0000000000000000000000000000000000000000);

vm.stopBroadcast();

console2.log("Contract configuration completed");
}

function _displayDeploymentSummary() internal view {
console2.log("\nDeployment Summary");
console2.log("=====================");
console2.log("Chain ID:", block.chainid);
console2.log("Deployer:", deployer);
console2.log("Trap Config:", trapConfig);
console2.log("");
console2.log("MEVResponse:", mevResponseAddress);
console2.log("MEVDetectionTrap:", mevTrapAddress);
console2.log("SandwichAttackTrap:", sandwichTrapAddress);
console2.log("");
console2.log("Monitored DEXs:", mevTrap.getMonitoredDEXs().length);
console2.log("Known MEV Bots:", mevTrap.getKnownMEVBots().length);
console2.log("Monitored Addresses:", sandwichTrap.getMonitoredAddresses().length);
console2.log("");
console2.log("Next Steps:");
console2.log("1. Update drosera.toml with deployed addresses");
console2.log("2. Configure response contract addresses");
console2.log("3. Set up monitoring and alerts");
console2.log("4. Test with real MEV scenarios");
}

function _saveDeploymentAddresses() internal {
string memory deploymentInfo = string(abi.encodePacked(
"MEV Detection Trap Deployment\n",
"=============================\n",
"Chain ID: ", vm.toString(block.chainid), "\n",
"Deployer: ", vm.toString(deployer), "\n",
"Trap Config: ", vm.toString(trapConfig), "\n\n",
"MEVResponse: ", vm.toString(mevResponseAddress), "\n",
"MEVDetectionTrap: ", vm.toString(mevTrapAddress), "\n",
"SandwichAttackTrap: ", vm.toString(sandwichTrapAddress), "\n\n",
"Deployment Time: ", vm.toString(block.timestamp), "\n"
));

vm.writeFile("deployment.txt", deploymentInfo);
console2.log("Deployment addresses saved to deployment.txt");
}

function verify() public {
console2.log("Verifying contracts on Etherscan...");

console2.log("MEVResponse verification command:");
console2.log("forge verify-contract", mevResponseAddress, "src/MEVResponse.sol:MEVResponse --chain-id", block.chainid);

console2.log("MEVDetectionTrap verification command:");
console2.log("forge verify-contract", mevTrapAddress, "src/MEVDetectionTrap.sol:MEVDetectionTrap --chain-id", block.chainid);

console2.log("SandwichAttackTrap verification command:");
console2.log("forge verify-contract", sandwichTrapAddress, "src/SandwichAttackTrap.sol:SandwichAttackTrap --chain-id", block.chainid);
}

function generateDroseraConfig() public view {
console2.log("\nUpdate your drosera.toml with these addresses:");
console2.log("");
console2.log("[traps.mev_detection_monitor]");
console2.log("path = \"out/MEVDetectionTrap.sol/MEVDetectionTrap.json\"");
console2.log("response_contract = \"", mevResponseAddress, "\"");
console2.log("response_function = \"handleMEVAlert(bytes)\"");
console2.log("address = \"", mevTrapAddress, "\"");
console2.log("");
console2.log("[traps.sandwich_attack_monitor]");
console2.log("path = \"out/SandwichAttackTrap.sol/SandwichAttackTrap.json\"");
console2.log("response_contract = \"", mevResponseAddress, "\"");
console2.log("response_function = \"handleMEVAlert(bytes)\"");
console2.log("address = \"", sandwichTrapAddress, "\"");
}
}
Loading