SmartSwaps

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

SmartSwaps

Created At

ETHGlobal New Delhi

Project Description

MEV-Protected Smart Trading Aggregator

The Problem We're Solving

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:

Types of MEV Attacks

  • Frontrunning: Bots place orders ahead of yours by paying higher gas fees
  • Sandwich Attacks: Your trade gets wrapped between two bot transactions, manipulating the price you receive
  • JIT Liquidity: Bots provide liquidity microseconds before your trade and remove it immediately after, stealing LP fees without taking real risk

The Limit Order Dilemma

While limit order protocols offer an alternative, they come with their own critical issues:

  • Static spreads that don't adapt to market volatility
  • Orders either remain unfilled during calm markets or give away too much edge during volatile periods
  • Example: 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,000

Our Three-Pronged Solution

1. MEV-Taxing Uniswap V4 Hook - The Protection Layer

Inspiration & Foundation

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.

Important Compatibility Note

Blockchain 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 ordering

Limited Effectiveness:

  • Ethereum mainnet due to PBS (Proposer-Builder Separation) and custom block building

How Our Hook Works

Detection Algorithm:

  • Normal User Priority Fee: 1-5 gwei
  • MEV Bot Priority Fee: 50-1000+ gwei
  • Our Hook: Monitors these fees in real-time

Smart 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 LPs
  • JIT Penalty: 4x higher tax rate for JIT liquidity (more extractive behavior)
  • User-Friendly: Regular users with normal priority fees pay nothing extra
  • Flashblock Support: Enhanced granularity for L2 chains with flashblock architecture

2. Dynamic Volatility-Based Limit Orders

Built as an extension to 1inch Limit Order Protocol

The Innovation

Traditional 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 System

  • Data Source: 24-hour rolling price window via Pyth oracles
  • Update Frequency: Hourly updates for fresh volatility data
  • Calculation Method: Standard deviation of hourly returns
  • Special 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 Worlds

The Challenge

Combining offchain limit orders with onchain AMM swaps in a single atomic transaction.

How It Works

Step-by-Step Process:

  1. Scan available 1inch limit orders for liquidity
  2. Check Uniswap V4 pool depths and current prices
  3. Calculate optimal split to minimize slippage and maximize output
  4. Execute everything in a single atomic transaction

Real-World Example

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

Comparison to Existing Solutions

Similar intent-based execution as CoWSwap, UniswapX, and 1inch Fusion, but with:

  • Built-in MEV protection at the AMM level
  • Dynamic volatility-based limit order pricing
  • Single transaction execution for gas efficiency

How it's Made

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:

background image mobile

Join the mailing list

Get the latest news and updates