MEV-protected Swap aggregator with dynamic limit orders & smart routing for optimal swaps
Every day, DeFi traders lose millions to MEV bots. When you submit a swap on any blockchain, sophisticated bots monitor the mempool and execute strategies to extract value from your trades:
While limit order protocols offer an alternative, they come with their own critical issues:
Our approach is inspired by Paradigm's research paper "Priority is All You Need", which demonstrates how priority fees can be leveraged by smart contracts to tax malicious actors attempting to exploit capital.
Blockchain Requirements: This MEV protection mechanism relies on standard priority fee ordering. It works optimally on:
Supported:
Limited Effectiveness:
Detection Algorithm:
Smart Taxation Formula:
if (priorityFee > threshold) {
tax = (priorityFee - threshold) × feeMultiplier
// Tax flows directly to LPs as compensation
}
Key Features:
Built as an extension to 1inch Limit Order Protocol
Traditional limit orders use fixed spreads, leading to poor execution in changing markets. Our dynamic system adapts spreads based on real-time market volatility.
| Market Condition | Volatility | Spread Behavior | Result | |------------------|------------|-----------------|--------| | Calm Markets | ~20% | Tight spreads | Competitive pricing | | Volatile Markets | ~200% | Wide spreads | Protection prioritized |
Formula: finalSpread = baseSpread + (volatility × multiplier)
Combining offchain limit orders with onchain AMM swaps in a single atomic transaction.
Step-by-Step Process:
User Input: 100,000 USDC → ETH
Aggregator Process:
├── Found: 30,000 USDC of limit orders @ 0.2% below market
├── Execute: Fill limit orders first (better price)
├── Route: Remaining 70,000 USDC through V4 (MEV protected)
└── Result: Optimal blended rate, single transaction
Outcome: Better execution than any single venue
Similar intent-based execution as CoWSwap, UniswapX, and 1inch Fusion, but with:
How It's Made Building the MEV-Taxing Hook: Turning Predators into Payers The Core Innovation: Flashblock-Aware MEV Detection We built our MEV taxation system on Uniswap V4's hooks, but the real magic comes from integrating L2 flashblocks. Traditional block-based detection is too coarse - flashblocks give us microsecond-level granularity: solidityuint256 currentFlashblock = flashBlockProvider.getFlashblockNumber(); if (currentFlashblock == lastSwapTaxedBlock[poolId]) { // Not first transaction, likely not MEV return (selector, ZERO_DELTA, 0); } Dual Tax Mechanism via Different Hooks:
beforeSwap(): Catches sandwich attacks and frontrunning - taxes flow to LPs as donations afterAddLiquidity(): Catches JIT liquidity - taxes extracted directly to admin (punitive)
The Fee Unit System: Instead of percentage-based taxes that require complex calculations, we use a simple unit multiplier: solidityuint256 tax = (priorityFee - threshold) * feeUnit; // Example: 100 gwei priority, 10 gwei threshold, 1 wei unit = 90 wei tax This makes gas costs predictable and calculations efficient. JIT gets 4x the fee unit because it's more extractive - they provide liquidity for microseconds just to steal LP fees. BeforeSwapDelta Magic: V4's delta accounting lets us inject taxes seamlessly: solidityreturn (selector, toBeforeSwapDelta(int128(taxAmount), 0), 0); // This makes the swapper owe extra tokens without modifying swap logic Building Dynamic Spread Orders with 1inch Protocol The IAmountGetter Interface Challenge: 1inch's limit order protocol uses a powerful but complex callback system. Orders don't specify exact amounts - they call external contracts to determine them dynamically. We inherited IAmountGetter: solidityfunction getTakingAmount( Order calldata order, uint256 makingAmount, bytes calldata extraData ) external view returns (uint256 takingAmount) SpreadParams Architecture: We encode volatility parameters into the order's extraData: soliditystruct SpreadParams { uint256 baseSpreadBps; // Starting spread (e.g., 10 = 0.1%) uint256 multiplier; // Volatility impact (e.g., 200 = 2x) uint256 maxSpreadBps; // Cap to prevent extreme spreads bool useMakerAsset; // Which asset's volatility to use } The genius: When 1inch calls our contract to get amounts, we calculate spreads based on current volatility, not when the order was placed. Orders automatically adapt to market conditions without any updates. Building Onchain Volatility with Pyth Oracle The 24-Hour Rolling Window Challenge: Calculating volatility onchain is expensive. We built an efficient circular buffer system: soliditystruct PriceHistory { uint256[24] hourlyPrices; // Fixed-size array, no reallocation uint8 currentIndex; // Where to write next uint8 dataPoints; // Valid data count } Pyth Integration with Graceful Degradation: solidityPythStructs.Price memory price = pythOracle.getPriceUnsafe(priceId); // getPriceUnsafe doesn't revert on stale prices - crucial for resilience if (price.price <= 0) return DEFAULT_VOLATILITY; Volatility Calculation Optimization: Instead of storing returns, we calculate them on-demand: solidity// Calculate returns between consecutive hours uint256 return_ = currPrice.mulDiv(SCALE, prevPrice); sumSquaredReturns += (return_ - mean) ** 2; // Standard deviation = sqrt(variance) volatility = variance.sqrt(); Special handling for stablecoins - they get fixed 1% volatility to save gas since their volatility is predictable. The Aggregator: Bridging Offchain Orders with Onchain Swaps The Integration Challenge: 1inch orders live offchain - they're signed messages, not smart contracts. V4 pools are entirely onchain. Combining them in a single atomic transaction was the hardest technical challenge:

