Skip to content

Aaditya1273/Flow-Sentinel

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

49 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

flow senital

Flow Sentinel

The Autonomous, MEV-Resistant Wealth Manager on Flow Blockchain

Flow Blockchain Cadence 1.0 Next.js 15 Status License

Transform static liquidity into autonomous, MEV-protected capital β€” with zero daily maintenance.



πŸ“‹ Table of Contents


🚩 The Problem

Decentralized Finance (DeFi) is one of the most transformative innovations in finance β€” yet it remains inaccessible to the masses due to three fundamental broken pillars:

πŸ”΄ The Invisible Tax of MEV

Every on-chain transaction is visible in the public mempool before it's confirmed. Maximal Extractable Value (MEV) bots continuously scan this mempool, identifying profitable transactions to:

  • Frontrun: Buy an asset seconds before your large purchase, then dump it on you at a higher price
  • Sandwich: Place a buy order before your transaction and a sell order immediately after, skimming profit from both sides
  • Backrun: Exploit the price impact of your transaction for arbitrage

This invisible tax extracts >$500M annually from DeFi users, disproportionately hurting larger trades and automated strategies.

πŸ”΄ Fragmented Complexity

DeFi yield opportunities are scattered across hundreds of protocols:

  • Liquid Staking (Lido, Stader, EigenLayer)
  • DEX Liquidity Pools (Uniswap, Balancer, Trader Joe)
  • Yield Aggregators (Yearn, Beefy, Harvest)
  • Lending Markets (Aave, Compound, Morpho)

Managing positions across all these protocols requires constant attention β€” claiming rewards, restaking, rebalancing, and monitoring β€” creating unsustainable manual fatigue.

πŸ”΄ Capital Inefficiency

Most DeFi users hold their assets in simple wallets, earning zero yield, because the complexity of active management outweighs the perceived benefits. Static liquidity fails to participate in the broader economy, leaving billions in idle capital.

πŸ”΄ UX Friction for Institutions

Institutional adoption of DeFi is stalled by:

  • Complex wallet interactions and seed phrase management
  • Lack of passkey/biometric authorization
  • No auditable, transparent execution trail
  • No MEV guarantees for large capital deployments

πŸ’‘ The Solution

Flow Sentinel transforms static liquidity into autonomous, MEV-protected capital. Think of it as a self-driving car for your crypto assets β€” once you define your strategy and deposit capital, the Sentinel handles everything autonomously on-chain.

Core Innovation: MEV Resistance by Architecture

Flow Sentinel is the first DeFi wealth manager to implement a full 4-layer MEV protection stack directly on the Flow Blockchain, inspired by Flashbots MEV-Boost (Ethereum's gold standard) but adapted for Flow's unique Cadence 1.0 runtime.

Concept Problem Flow Sentinel Solution
Mempool Frontrunning Bots see and frontrun your transactions Commit-Reveal: Execution hash is committed first, revealed later β€” bots can't see what you're doing
Timing Games Bots predict and exploit execution timing VRF Block-Delay Jitter: Random 0-5 block delay using Flow's native verifiable randomness β€” unpredictable timing
Price Manipulation Bots manipulate oracles before your trade Price Deviation Guard: Expected APY vs real-time oracle APY β€” trades abort if deviation exceeds configured slippage (default 3%)
Sandwich Attacks Bots sandwich large trades Execution Queue: VRF-shuffled processing order β€” nobody knows which trade executes when

Beyond MEV Protection

Flow Sentinel also delivers:

  • πŸ€– Zero-Click Automation: Once configured, vaults autonomously execute strategies on-chain β€” harvest yields, restake rewards, rebalance positions
  • πŸ” Passkey Authorization: Biometric (FaceID/TouchID) vault operations for institutional-grade security
  • πŸ“Š Bloomberg-Terminal UI: Professional-grade dashboard with real-time P&L, vault analytics, and strategy performance tracking
  • πŸ”— Verifiable On-Chain History: Every yield harvest, rebalance, and protection trigger is a transparent, explorable on-chain event
  • ⚑ Multi-Strategy Execution: Liquid Staking, Yield Farming, and Arbitrage β€” all managed from a single vault interface

🌟 What Makes Flow Sentinel Unique

1. Flow-Native MEV Protection

The only wealth manager to implement Flashbots-inspired MEV resistance directly in Cadence 1.0 smart contracts. We don't just talk about MEV protection β€” we deliver it in 4 verifiable, on-chain layers.

2. VRF-Powered Security

Leveraging Flow's native revertibleRandom() for every critical operation:

  • Commit-reveal nonce generation
  • Block-delay jitter (unpredictable execution timing)
  • Execution queue shuffling (prevents sandwich attacks)

3. Zero-Daily-Maintenance Architecture

Unlike traditional DeFi positions that require daily claiming, restaking, and monitoring, Flow Sentinel vaults execute autonomously on-chain:

  • executeStrategyWithMEV() is the single entry point for all strategy execution
  • MEV protection is applied automatically to every execution
  • Yield accrues transparently in the vault, claimable at any time

4. Institutional-Grade UX from Day One

  • Passkey/biometric vault authorization (via WebAuthn)
  • Professional analytics dashboard with real-time P&L charts
  • Configurable MEV protection levels (None β†’ Basic β†’ Standard β†’ Full)
  • Auditor-friendly: every operation emits structured, explorable events

5. Production-Ready Testnet Deployment

  • All 10 contracts deployed and verified on Flow Testnet
  • Full 4-layer MEV protection test suite passing
  • TypeScript frontend with zero compilation errors
  • Next.js 15 with App Router for optimal performance

πŸ—οΈ System Architecture

Contract Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                        Flow Sentinel                                β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚   Core Contracts     β”‚   MEV Protection     β”‚   Strategies          β”‚
β”‚                      β”‚                      β”‚                      β”‚
β”‚  SentinelVaultFinal  β”‚   MEVShieldCore      β”‚  LiquidStakingStrat   β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚    Vault     β”‚    β”‚   β”‚  Commits     β”‚    β”‚  β”‚  Execute()   β”‚    β”‚
β”‚  β”‚  Resource    │───▢│   β”‚  Dictionary  β”‚    β”‚  β”‚              β”‚    β”‚
β”‚  β”‚  (per-user)  β”‚    β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚   β”‚  Pending     β”‚    β”‚  β”‚ YieldFarming β”‚    β”‚
β”‚  β”‚  Collection  β”‚    β”‚   β”‚  Executions  β”‚    β”‚  β”‚  Strategy    β”‚    β”‚
β”‚  β”‚  Resource    │───▢│   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚                      β”‚   β”‚  VaultMEV    β”‚    β”‚  β”‚  Arbitrage   β”‚    β”‚
β”‚  SentinelInterfaces  β”‚   β”‚  Configs     β”‚    β”‚  β”‚  Strategy    β”‚    β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚  β”‚  IStrategy   β”‚    β”‚                      β”‚                      β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚   MultiSigAdmin       β”‚   StrategyRegistry   β”‚
β”‚                      β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  SentinelVaultFinal  β”‚   β”‚  Admin       β”‚    β”‚   β”‚  Strategy    β”‚    β”‚
β”‚  (V2)                β”‚   β”‚  Multi-Sig   β”‚    β”‚   β”‚  Catalog     β”‚    β”‚
β”‚                      β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

MEV-Shield Pro β€” 4 Protection Layers

                    ╔═══════════════════════════════╗
                    β•‘     MEV-SHIELD PRO            β•‘
                    β•‘   Full Protection Active      β•‘
                    β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
                             β”‚
          β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
          β–Ό                  β–Ό                  β–Ό
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚  Layer 1     β”‚  β”‚  Layer 2     β”‚  β”‚  Layer 3     β”‚
   β”‚ Commit-Revealβ”‚  β”‚ VRF Block-   β”‚  β”‚ Price        β”‚
   β”‚              β”‚  β”‚ Delay Jitter β”‚  β”‚ Deviation    β”‚
   β”‚ Execution    β”‚  β”‚ Random 0-5   β”‚  β”‚ Guard        β”‚
   β”‚ hidden from  β”‚  β”‚ block delay  β”‚  β”‚ APY Β± slippageβ”‚
   β”‚ mempool      β”‚  β”‚ (unpredict.) β”‚  β”‚ tolerance    β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                             β”‚
                                             β–Ό
                                      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                      β”‚  Layer 4     β”‚
                                      β”‚ Execution    β”‚
                                      β”‚ Queue        β”‚
                                      β”‚ VRF-shuffled β”‚
                                      β”‚ order        β”‚
                                      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

MEV Protection Flow

sequenceDiagram
    participant U as User/Mastermind
    participant C as MEVShieldCore
    participant V as SentinelVaultFinal
    participant S as Strategy
    participant O as YieldOracle

    Note over U,O: LAYER 1 β€” COMMIT-REVEAL
    U->>C: createCommit(vaultId, commitHash, level=3)
    C-->>U: CommitCreated (stored, hidden)

    Note over U,O: LAYER 2 β€” VRF BLOCK-DELAY JITTER
    U->>C: revealExecution(vaultId, commitHash, preimage...)
    C->>C: verify preimage hash βœ“
    C->>C: revertibleRandom() β†’ jitterBlocks (0-5)
    C-->>U: ExecutionScheduled (at block N + jitter)

    Note over U,O: LAYER 3 β€” PRICE DEVIATION GUARD
    V->>O: getYieldData(strategyId)
    O-->>V: actualOracleAPY
    V->>C: checkPriceDeviation(expectedAPY, actualAPY, slippage)
    C-->>V: shouldExecute=true (deviation within bounds)

    Note over U,O: LAYER 4 β€” EXECUTION QUEUE
    V->>S: executeStrategy(vaultBalance)
    S-->>V: yieldGenerated
    V->>C: markExecutionProcessed(commitHash)
    C->>C: vrfShuffle(pendingExecutions)
    C-->>U: ExecutionCompleted (yield, status)
Loading

User β†’ Vault β†’ Strategy Flow

graph TD
    User((User)) -->|1. Create Vault<br/>(with MEV config)| CreateVault[SentinelVaultFinal.createVault]
    CreateVault -->|2. Register| MEV[MEVShieldCore.registerVaultMEV]
    CreateVault -->|3. Store| Collection[(VaultCollection)]
    
    User -->|4. Deposit FLOW| Deposit[SentinelVaultFinal.deposit]
    Deposit --> Vault[(Vault Resource)]
    
    User -->|5. Trigger Strategy| Trigger[mev_reveal / mev_execute]
    Trigger -->|6. Create Commit| MEV
    MEV -->|7. Reveal + VRF Jitter| MEV
    
    subgraph "MEV-Protected Execution"
        MEV -->|8. Price Guard| Vault
        Vault -->|9. Execute| Strategy{Strategy Engine}
        Strategy -->|10a. Stake| LST[Liquid Staking]
        Strategy -->|10b. Farm| Farm[Yield Farming]
        Strategy -->|10c. Arbitrage| Arb[DEX Arbitrage]
    end
    
    Strategy -->|11. Yield Generated| Vault
    Vault -->|12. Event Emitted| Chain[(On-Chain Log)]
    
    User -.->|Query Vault Info| Script[get_vault_info.cdc]
    Script -- MEV Stats --> User
Loading

Data Flow Architecture

graph LR
    subgraph "Blockchain Layer"
        SC[Smart Contracts<br/>Cadence 1.0]
        EV[Events]
        ST[Script Queries]
    end
    
    subgraph "Service Layer"
        FCL[FCL Client<br/>@onflow/fcl]
        FSV[FlowService<br/>TypeScript Class]
    end
    
    subgraph "State Layer"
        Hooks[React Hooks<br/>useVaultData<br/>useActivityFeed]
        CTX[FlowContext<br/>Wallet State]
    end
    
    subgraph "UI Layer"
        Pages[Next.js Pages<br/>Dashboard / Vaults / Portfolio]
        Comp[Components<br/>VaultCard / Charts]
    end
    
    SC -- Events --> FCL
    SC -- Script Results --> FCL
    FCL -- JSON Data --> FSV
    FSV -- Typed Data --> Hooks
    Hooks -- VaultInfo[] --> Pages
    Hooks -- MEV Config --> Comp
    CTX -- Wallet Status --> Pages
Loading

πŸ”„ User Workflow

1. Connect Wallet

Choose Flow Wallet (native Cadence) or EVM Gateway (MetaMask/RainbowKit)

2. Create a Vault

# Via the CLI or frontend:
flow transactions send transactions/init_sentinel.cdc \
    --args-json '[
        {"type": "String", "value": "My MEV-Protected Vault"},
        {"type": "String", "value": "Liquid Staking Pro"},
        {"type": "String", "value": "liquid-staking-pro"}
    ]' --network testnet

Your vault is created with Full MEV Protection (Level 3) by default:

  • βœ… Layer 1 β€” Commit-Reveal: Active
  • βœ… Layer 2 β€” VRF Block-Delay: Active
  • βœ… Layer 3 β€” Price Deviation Guard: Active (3% slippage)
  • βœ… Layer 4 β€” Execution Queue: Active

3. Deposit Capital

Deposit FLOW tokens into your vault. The vault balance is tracked on-chain.

4. Trigger Strategy Execution (MEV-Protected)

Two options:

πŸ”΄ Full Protection (Recommended): Commit-Reveal flow

# Step 1: Generate commit hash off-chain
# Step 2: Commit (hash hidden from mempool)
flow transactions send transactions/mev_commit.cdc \
    --args-json '[
        {"type": "UInt64", "value": "0"},
        {"type": "String", "value": "SENTINEL-MEV-COMMIT:0:12345:100.0:liquid-staking-pro:1000000:0xc13..."},
        {"type": "UInt8", "value": "3"}
    ]' --network testnet

# Step 3: Reveal + Execute (after commit window)
flow transactions send transactions/mev_reveal.cdc \
    --args-json '[...preimage params...]' --network testnet

🟑 Standard Protection: Direct execution with VRF jitter + price guard

flow transactions send transactions/mev_execute_direct.cdc \
    --args-json '[...]' --network testnet

5. Monitor & Claim

Use the web dashboard to:

  • View real-time vault balance and yield accrued
  • Monitor MEV protection triggers and rejections
  • Adjust protection level (None β†’ Basic β†’ Standard β†’ Full)
  • Claim accumulated yield
  • View performance history with P&L charts

πŸ› οΈ Technical Stack

Layer Technology Purpose
Blockchain Flow (Cadence 1.0) Smart contract runtime with native randomness
Smart Contracts 10 Cadence contracts Vault logic, MEV protection, strategy execution
Web Framework Next.js 15 (App Router) SSR, React Server Components, optimized builds
UI Library React 19 Component-based UI architecture
Styling Tailwind CSS 4 Utility-first CSS with glassmorphism design
Animations Framer Motion 60FPS interactive UI animations
Wallet Connect FCL + RainbowKit Flow Wallet + EVM wallet support
Diagrams Mermaid Architecture diagrams in README
Deployment Netlify Edge functions + SSR
Flow CLI flow-cli Contract deployment, scripts, transactions

πŸ“ Project Structure

Flow-Sentinel/
β”œβ”€β”€ app/                          # Next.js 15 App Router pages
β”‚   β”œβ”€β”€ dashboard/                # Main dashboard with vault management
β”‚   β”œβ”€β”€ vaults/                   # Vault list and details
β”‚   β”œβ”€β”€ portfolio/                # Portfolio analytics
β”‚   β”œβ”€β”€ analytics/                # Performance analytics
β”‚   β”œβ”€β”€ settings/                 # User settings
β”‚   β”œβ”€β”€ docs/                     # Documentation
β”‚   β”œβ”€β”€ landing/                  # Marketing landing page
β”‚   └── page.tsx                  # Root page
β”œβ”€β”€ components/
β”‚   β”œβ”€β”€ dashboard/                # VaultCard, CreateVaultModal, Charts
β”‚   β”œβ”€β”€ immersive/                # Particle fields, animated text, cards
β”‚   β”œβ”€β”€ layout/                   # Navbar, Footer
β”‚   └── ui/                       # Reusable UI primitives
β”œβ”€β”€ contracts/
β”‚   β”œβ”€β”€ MEVShieldCore.cdc         # ⭐ 4-layer MEV protection engine
β”‚   β”œβ”€β”€ SentinelVaultV2.cdc       # ⭐ MEV-protected vault (deployed as SentinelVaultFinal)
β”‚   β”œβ”€β”€ SentinelInterfaces.cdc    # Core interfaces
β”‚   β”œβ”€β”€ StrategyRegistry.cdc      # Strategy catalog
β”‚   β”œβ”€β”€ YieldOracle.cdc           # Yield data oracle
β”‚   β”œβ”€β”€ MultiSigAdmin.cdc         # Multi-sig admin
β”‚   └── strategies/               # Strategy implementations
β”‚       β”œβ”€β”€ LiquidStakingStrategy.cdc
β”‚       β”œβ”€β”€ YieldFarmingStrategy.cdc
β”‚       └── ArbitrageStrategy.cdc
β”œβ”€β”€ transactions/                 # Cadence transactions
β”‚   β”œβ”€β”€ mev_commit.cdc            # Layer 1: Create commit hash
β”‚   β”œβ”€β”€ mev_reveal.cdc            # Layer 1-4: Reveal + execute
β”‚   β”œβ”€β”€ mev_execute_direct.cdc    # Direct execution with MEV
β”‚   β”œβ”€β”€ mev_set_protection.cdc    # Update protection level
β”‚   β”œβ”€β”€ init_sentinel.cdc         # Initialize vault
β”‚   └── ...
β”œβ”€β”€ scripts/                      # Shell & Cadence scripts
β”‚   β”œβ”€β”€ test_mev_protection.sh    # ⭐ Full MEV test suite
β”‚   β”œβ”€β”€ mev_status.cdc            # Query MEV stats
β”‚   β”œβ”€β”€ get_vault_info.cdc        # Query vault info
β”‚   β”œβ”€β”€ deploy-all-contracts.sh   # Deploy all contracts
β”‚   └── verify_deployment.js      # Verify deployment
β”œβ”€β”€ hooks/                        # React hooks
β”‚   β”œβ”€β”€ useVaultData.ts           # Vault data with MEV fields
β”‚   └── useActivityFeed.ts        # On-chain event feed
β”œβ”€β”€ lib/
β”‚   β”œβ”€β”€ flow-service.ts           # Cadence transaction templates
β”‚   β”œβ”€β”€ flow.tsx                  # FCL configuration + FlowProvider
β”‚   └── wagmi.ts                  # EVM wallet config
β”œβ”€β”€ flow.json                     # Flow CLI config (networks, accounts, contracts)
β”œβ”€β”€ .env.local.example            # Environment variable template
β”œβ”€β”€ netlify.toml                  # Netlify deployment config
└── README.md                     # This file

πŸš€ Getting Started

Prerequisites

  • Node.js 18+ and npm/pnpm/yarn
  • Flow CLI (flow command in PATH)
  • A Flow wallet (e.g., Flow Wallet browser extension)
  • (Optional) A testnet account with FLOW tokens from the Flow Testnet Faucet

Local Development

# 1. Clone the repository
git clone https://github.com/Aaditya1273/Flow-Sentinel.git
cd Flow-Sentinel

# 2. Install dependencies
npm install

# 3. Copy environment configuration
cp .env.local.example .env.local
# Edit .env.local with your values (defaults work for testnet)

# 4. Start the development server
npm run dev
# Open http://localhost:3000

# 5. (Optional) Deploy contracts to testnet
flow deploy --network testnet

# 6. (Optional) Run the MEV test suite
bash scripts/test_mev_protection.sh testnet

Environment Variables

See .env.local.example for the complete list. Key variables:

Variable Default (Testnet) Mainnet
NEXT_PUBLIC_FLOW_ACCESS_NODE https://rest-testnet.onflow.org https://rest-mainnet.onflow.org
NEXT_PUBLIC_SENTINEL_VAULT_ADDRESS 0xc13b08053be24e87 Deploy-specific
NEXT_PUBLIC_SENTINEL_INTERFACES_ADDRESS 0x136b642d0aa31ca9 Deploy-specific
NEXT_PUBLIC_WALLET_CONNECT_PROJECT_ID Your project ID Your project ID
NEXT_PUBLIC_FLOW_TOKEN_ADDRESS 0x7e60df042a9c0868 0x1654653399040a61
NEXT_PUBLIC_FUNGIBLE_TOKEN_ADDRESS 0x9a0766d93b6608b7 0xf233dcee88fe0abe

πŸ§ͺ Testing

Run the MEV Protection Test Suite

The test suite verifies all 4 layers of MEV protection on-chain:

bash scripts/test_mev_protection.sh testnet

This will:

  1. βœ… Verify MEVShieldCore deployment
  2. βœ… Create a vault with Full MEV protection
  3. βœ… Layer 1: Commit a hash (hidden from mempool)
  4. βœ… Layer 2: Reveal + VRF block-delay jitter applied
  5. βœ… Layer 3: Price deviation guard check
  6. βœ… Layer 4: Execution queue tracking
  7. βœ… Query and verify MEV statistics
  8. βœ… Update protection level settings

On-Chain Verification

# Query global MEV stats
flow scripts execute scripts/mev_status.cdc nil --network testnet

# Query vault-specific MEV config
flow scripts execute scripts/mev_status.cdc 0 --network testnet

# Query all vault info
flow scripts execute scripts/get_vault_info.cdc 0xc13b08053be24e87 --network testnet

TypeScript & Build Validation

# TypeScript type checking
npx tsc --noEmit

# Full Next.js build
npx next build

πŸ“œ Smart Contracts

Core Contracts

Contract Address (Testnet) Description
MEVShieldCore 0xc13b08053be24e87 4-layer MEV protection engine β€” commit-reveal, VRF jitter, price guard, execution queue
SentinelVaultFinal 0xc13b08053be24e87 MEV-protected vault (V2) with full protection integration
SentinelInterfaces 0x136b642d0aa31ca9 Core interfaces: IMEVShield, IStrategy
StrategyRegistry 0xc13b08053be24e87 Strategy catalog β€” register, query, and update strategy TVL
YieldOracle 0xc13b08053be24e87 Yield data provider for price deviation guard
MultiSigAdmin 0xc13b08053be24e87 Multi-signature administration for yield reserve

Strategy Contracts

Strategy Description
LiquidStakingStrategy Delegates FLOW to liquid staking protocols, generates staking yield with VRF-driven variance
YieldFarmingStrategy Harvests and compounds yields from DeFi farming protocols
ArbitrageStrategy Executes arbitrage opportunities across DEX aggregators

Transactions

Transaction Purpose
mev_commit.cdc Create a commit hash (Layer 1 β€” hide execution from mempool)
mev_reveal.cdc Reveal hash, apply VRF jitter, check price deviation, execute (Layers 1-4)
mev_execute_direct.cdc Direct execution with VRF jitter + price guard (no commit-reveal)
mev_set_protection.cdc Update vault protection level and slippage tolerance
init_sentinel.cdc Initialize a new vault with MEV protection
deposit_flow.cdc Deposit FLOW tokens into a vault
withdraw_flow.cdc Withdraw FLOW tokens from a vault

Deployment Order

Contracts must be deployed in this order (dependency chain):

graph TD
    A[SentinelInterfaces] --> B[YieldOracle]
    A --> C[MultiSigAdmin]
    B --> D[MEVShieldCore]
    C --> D
    D --> E[SentinelVaultFinal]
    A --> F[LiquidStakingStrategy]
    A --> G[YieldFarmingStrategy]
    A --> H[ArbitrageStrategy]
    E --> I[StrategyRegistry]
    F --> I
    G --> I
    H --> I
Loading
# Deploy everything in one command (using flow.json config)
flow deploy --network testnet --update

πŸ“Š MEV Protection (Full Technical Deep Dive)

Layer 1 β€” Commit-Reveal (πŸ”΄ Mempool Frontrunning)

Concept: Adapted from Flashbots' Proposer-Builder Separation (PBS). Instead of submitting the actual execution parameters to the mempool where bots can see them, the user first submits a commitment hash β€” a one-way hash of the execution preimage. The actual execution details are revealed later, after the commit has been confirmed.

Cadence Implementation:

// Step 1: Commit (only the hash is visible on-chain)
MEVShieldCore.createCommit(
    vaultId: vaultId,
    commitHash: commitHash,  // "SENTINEL-MEV-COMMIT:<vaultId>:<nonce>:..."
    protectionLevel: 3
)

// Step 2: Reveal + Execute (after commit window)
// The preimage is verified against the stored hash
MEVShieldCore.revealExecution(
    vaultId: vaultId,
    commitHash: commitHash,
    nonce: nonce,
    amount: amount,
    strategyId: strategyId,
    deadlineBlock: deadlineBlock,
    expectedAPY: expectedAPY,
    slippageBps: slippageBps
)

Security Properties:

  • βœ… Execution is hidden from mempool until the commit is confirmed
  • βœ… Preimage includes a random nonce (generated via revertibleRandom()) β€” unpredictable
  • βœ… Commit has a 200-block deadline window (~3 minutes) β€” enough time for honest reveal
  • βœ… Commits are one-time use β€” once revealed, the hash cannot be reused
  • βœ… Expired commits are automatically cleaned up

Layer 2 β€” VRF Block-Delay Jitter (⏱️ Timing Games)

Concept: Even if an execution is revealed, a sophisticated MEV bot could predict its exact execution time and frontrun it. Flow Sentinel uses Flow's native revertibleRandom() to add a random delay of 0-5 blocks before execution β€” making the exact execution time unpredictable.

Cadence Implementation:

let jitterBlocks = revertibleRandom<UInt64>() % (self.getMEVDelayMax() + 1)
let executeAtBlock = currentBlock + jitterBlocks + 1

emit ExecutionScheduled(
    vaultId: vaultId,
    executeAtBlock: executeAtBlock,
    jitterBlocks: jitterBlocks
)

Security Properties:

  • βœ… Unpredictable timing β€” revertibleRandom() is verifiable, non-deterministic randomness from Flow consensus
  • βœ… 0-5 blocks delay β€” short enough for acceptable UX, long enough to break bot timing
  • βœ… Configurable max delay via getMEVDelayMax() β€” can be updated without redeployment

Layer 3 β€” Price Deviation Guard (πŸ’Ή Price Manipulation)

Concept: Before executing any strategy, the vault fetches the actual APY from the YieldOracle and compares it against the expected APY provided by the user. If the deviation exceeds the configured slippage tolerance (default 3% = 300 bps), the execution is rejected and the MEV attack is prevented.

Cadence Implementation:

// Fetch real-time oracle data
let oracleData = YieldOracle.getYieldData(self.strategyId)
let actualOracleAPY = oracleData?.apy ?? expectedAPY

// Check deviation against slippage tolerance
let oracleCheck = MEVShieldCore.checkPriceDeviation(
    vaultId: self.id,
    expectedAPY: expectedAPY,
    actualOracleAPY: actualOracleAPY,
    slippageBps: self.slippageBps  // e.g., 300 = 3%
)

if !oracleCheck.shouldExecute {
    // Execution rejected β€” MEV protection triggered!
    emit MEVExecutionGuard(
        vaultId: self.id,
        deviation: oracleCheck.deviation,
        allowed: false,
        reason: "Price deviation exceeds bounds"
    )
    return  // Abort execution
}

Security Properties:

  • βœ… Real-time oracle data β€” fetches current APY at execution time, not cached
  • βœ… Configurable slippage β€” vault-level setting, independent per vault
  • βœ… Hard upper bound β€” MEV_DEVIATION_TOLERANCE (50%) as absolute limit
  • βœ… Auditable β€” every guard trigger emits a structured event with deviation and reason

Layer 4 β€” Execution Queue (πŸ”„ Sandwich Attacks)

Concept: When multiple executions are pending, they are processed through a queue that is shuffled using VRF randomness β€” ensuring no attacker can predict which execution will be processed first, effectively preventing sandwich attacks.

Cadence Implementation:

// VRF-shuffled execution queue
access(self) fun vrfShuffle(_ items: [PendingExecution]): [PendingExecution] {
    if items.length <= 1 { return items }
    var shuffled: [PendingExecution] = []
    var remaining = items
    while remaining.length > 0 {
        let randomIndex = revertibleRandom<UInt64>() % UInt64(remaining.length)
        shuffled.append(remaining[randomIndex])
        // Remove selected element
        var newRemaining: [PendingExecution] = []
        for i, item in remaining {
            if UInt64(i) != randomIndex { newRemaining.append(item) }
        }
        remaining = newRemaining
    }
    return shuffled
}

Security Properties:

  • βœ… VRF-shuffled order β€” nobody knows which execution processes next
  • βœ… Fisher-Yates algorithm β€” unbiased shuffling, every permutation equally likely
  • βœ… Ready-only β€” only executions past their scheduled block are included

MEV Protection Configuration Per Vault

Each vault has independent MEV protection settings:

// Protection level 0-3
vault.setProtectionLevel(newLevel: 3)  // Full protection

// Slippage tolerance in basis points
vault.setSlippageBps(newSlippageBps: 300.0)  // 3%

// Protection levels:
// 0 = None      β€” MEV protection DISABLED
// 1 = Basic     β€” VRF Block-Delay Jitter only
// 2 = Standard  β€” Commit-Reveal + Block-Delay Jitter  
// 3 = Full      β€” All 4 layers active βœ… (DEFAULT)

The vault's executeStrategyWithMEV() function automatically applies the correct protection layers based on the vault's configured level:

access(StrategyExecution) fun executeStrategyWithMEV(
    executor: @{SentinelInterfaces.IStrategy},
    commitHash: String,
    expectedAPY: UFix64,
    nonce: UInt64
) {
    // Layer 1: Commit-Reveal guard (if enabled)
    // Layer 2: VRF block-delay jitter (if enabled)
    // Layer 3: Price deviation check (always for level >= 1)
    // Layer 4: Execution queue processing (always)
    // Execute strategy
}

πŸ”¬ MEV Protection Comparison

Feature Flow Sentinel Typical DeFi Protocol Ethereum mev-boost
Commit-Reveal Execution βœ… Cadence-native ❌ βœ… (PBS)
VRF Randomness βœ… revertibleRandom() ❌ ❌ (external oracles)
Price Deviation Guard βœ… On-chain oracle ❌ βœ… (Relay mux)
Execution Queue βœ… VRF-shuffled ❌ ❌
Per-Vault Protection Config βœ… Yes ❌ ❌
Native Flow Integration βœ… Yes ❌ ❌ (Ethereum only)
Off-Chain Dependencies ❌ Zero Varies Required (relays)

πŸ—ΊοΈ Roadmap

  • Phase 1: Core Vault Logic & Testnet Deployment
  • Phase 2: MEV-Shield Pro β€” 4-Layer Protection
  • Phase 3: Professional Analytics Dashboard
  • Phase 4: Multi-sig Governance for Community Vaults
  • Phase 5: Mainnet Launch
  • Phase 6: Institutional API & SDK

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


Built for the future of finance on the Flow Blockchain
Flow Sentinel β€” Where DeFi meets Autonomy

Built with Codebuff Β· Flow Blockchain Β· Cadence Language

About

Flow Sentinel is the world's first autonomous, MEV-resistant wealth manager built on the Flow blockchain.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors