← Back to home

SmartSwaps

MEV-protected Swap aggregator with dynamic limit orders & smart routing for optimal swaps

Problem Statement

MEV-Protected Smart Trading AggregatorThe Problem We're SolvingEvery 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:Types of MEV AttacksFrontrunning:Bots place orders ahead of yours by paying higher gas feesSandwich Attacks:Your trade gets wrapped between two bot transactions, manipulating the price you receiveJIT Liquidity:Bots provide liquidity microseconds before your trade and remove it immediately after, stealing LP fees without taking real riskThe Limit Order DilemmaWhile limit order protocols offer an alternative, they come with their own critical issues:Static spreads that don't adapt to market volatilityOrders either remain unfilled during calm markets or give away too much edge during volatile periodsExample:Setting a limit order to sell 2 ETH for 6,000 USDC when ETH = $3,000 makes sense today, but becomes problematic if ETH suddenly spikes to $100,000Our Three-Pronged Solution1. MEV-Taxing Uniswap V4 Hook - The Protection LayerInspiration & FoundationOur 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.Important Compatibility NoteBlockchain Requirements:This MEV protection mechanism relies on standard priority fee ordering. It works optimally on:Supported:L2s with standard sequencers (Optimism, Base, Arbitrum)Chains using flashblocks for microsecond orderingLimited Effectiveness:Ethereum mainnet due to PBS (Proposer-Builder Separation) and custom block buildingHow Our Hook WorksDetection Algorithm:Normal User Priority Fee: 1-5 gweiMEV Bot Priority Fee: 50-1000+ gweiOur Hook: Monitors these fees in real-timeSmart Taxation Formula:if (priorityFee > threshold) { tax = (priorityFee - threshold) × feeMultiplier // Tax flows directly to LPs as compensation }Key Features:Frontrun Protection:Bots can still frontrun but must compensate LPsJIT Penalty:4x higher tax rate for JIT liquidity (more extractive behavior)User-Friendly:Regular users with normal priority fees pay nothing extraFlashblock Support:Enhanced granularity for L2 chains with flashblock architecture2. Dynamic Volatility-Based Limit OrdersBuilt as an extension to 1inch Limit Order ProtocolThe InnovationTraditional limit orders use fixed spreads, leading to poor execution in changing markets. Our dynamic system adapts spreads based on real-time market volatility.Volatility Tracking SystemData Source:24-hour rolling price window via Pyth oraclesUpdate Frequency:Hourly updates for fresh volatility dataCalculation Method:Standard deviation of hourly returnsSpecial Cases:Stablecoins receive fixed 1% volatility (computation savings)Dynamic Spread Adjustment| 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)3. Smart Routing Aggregator - Best of Both WorldsThe ChallengeCombining offchain limit orders with onchain AMM swaps in a single atomic transaction.How It WorksStep-by-Step Process:Scan available 1inch limit orders for liquidityCheck Uniswap V4 pool depths and current pricesCalculate optimal split to minimize slippage and maximize outputExecute everything in a single atomic transactionReal-World ExampleUser Input:100,000 USDC → ETHAggregator 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 transactionOutcome:Better execution than any single venueComparison to Existing SolutionsSimilar intent-based execution as CoWSwap, UniswapX, and 1inch Fusion, but with:Built-in MEV protection at the AMM levelDynamic volatility-based limit order pricingSingle transaction execution for gas efficiency

Solution

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:

Hackathon

ETHGlobal New Delhi

2025

Contributors