Skip to content

Moses-main/voltaic-fee-adjuster

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

78 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Voltaic Hook - Uniswap v4 Dynamic Volatility-Based Fee Hook

License: MIT Unichain Sepolia Tests: 27/27 UHI Hookathon 2026 GitHub issues

Table of Contents


Overview

Voltaic Hook is a smart contract hook for Uniswap v4 that dynamically adjusts swap fees based on real-time market volatility. Built for the UHI Hookathon 2026 and deployed on Unichain Sepolia.

Key Features

  • Oracle-Free Volatility Calculation - Uses only on-chain swap data (last 10 prices)
  • Dynamic Fee Tiers - Automatically adjusts fees based on volatility levels
  • Reactive Network Integration - Cross-chain automation for automated fee updates
  • Real-Time Updates - Event-driven architecture with sub-second updates
  • LP Protection - Higher fees during volatility protect liquidity providers from impermanent loss

Submission Criteria

This project meets all UHI Hookathon submission requirements:

✅ Core Requirements

Requirement Status Description
Uniswap v4 Hook VoltaicHook.sol implements beforeSwap() and afterSwap() hooks
Deployed on Testnet Deployed on Unichain Sepolia (Chain ID: 1301)
Verified on Explorer All contracts verified on Uniscan
Working Frontend React/TypeScript UI with wallet connection
README Documentation Complete documentation with architecture

✅ Technical Requirements

Requirement Status Description
Smart Contract Tests 27/27 tests passing with Foundry
Frontend TypeScript Full TypeScript implementation
Environment Variables Configurable via .env
Responsive UI Mobile-friendly design

✅ Innovation & Integration

Feature Status Description
Volatility Algorithm Custom oracle-free volatility calculation using price buffer
Reactive Network Cross-chain automation for fee updates
Dynamic Fee Tiers 3-tier fee system based on volatility
Real-time Events Event emission for threshold crossings

Architecture

System Architecture

flowchart TB
    subgraph Client["Client Layer"]
        Browser[Web Browser]
        Wallet[MetaMask/WalletConnect]
    end

    subgraph Frontend["Frontend Layer"]
        UI[React/TypeScript UI]
        Wagmi[Wagmi Client]
        Events[Event Listeners]
    end

    subgraph Unichain["Unichain Sepolia"]
        PoolMgr[Uniswap v4<br/>PoolManager]
        Hook[VoltaicHook<br/>Contract]
        Router[VoltaicRouter<br/>Contract]
    end

    subgraph Reactive["Reactive Network"]
        RSC[VoltaicReactive<br/>RSC Contract]
        Monitor[Event Monitor]
    end

    subgraph Tokens["Token Layer"]
        vETH[vETH Token]
        vUSDC[vUSDC Token]
    end

    Browser -->|Connect| Wallet
    Wallet -->|Sign| UI
    UI -->|Web3| Wagmi
    Wagmi -->|JSON-RPC| PoolMgr
    Wagmi -->|JSON-RPC| Hook
    Wagmi -->|JSON-RPC| Router
    PoolMgr <-->|Callbacks| Hook
    Hook -->|Events| RSC
    RSC -->|Callbacks| Hook
    PoolMgr -->|Tokens| vETH
    PoolMgr -->|Tokens| vUSDC
    Monitor -->|Monitor| RSC
Loading

Contract Architecture

classDiagram
    class VoltaicHook {
        +uint24 currentFee
        +uint24 FEE_TIER_LOW
        +uint24 FEE_TIER_MID
        +uint24 FEE_TIER_HIGH
        +uint256[10] priceBuffer
        +uint256 bufferIndex
        +uint256 bufferCount
        +IPoolManager poolManager
        +beforeSwap() BeforeSwapDelta
        +afterSwap() bytes
        +getCurrentFee() uint24
        +getVolatility() uint256
        +getBufferInfo() (uint256, uint256)
        +refreshFee() void
        +setThresholds() void
    }

    class VoltaicRouter {
        +IPoolManager poolManager
        +swap() external
        +executeSwap() internal
        +addLiquidity() external
        +executeAddLiquidity() internal
    }

    class VoltaicReactive {
        +VoltaicHook hook
        +subscribeToVolatilityEvents() external
        +react() external
        +triggerRefresh() external
    }

    VoltaicHook --> VoltaicRouter : Uses for swaps
    VoltaicHook --> VoltaicReactive : Emits events
    VoltaicReactive --> VoltaicHook : Calls refreshFee
Loading

Data Flow

sequenceDiagram
    participant User
    participant Frontend
    participant PoolMgr as Uniswap PoolManager
    participant Hook as VoltaicHook
    participant Reactive as VoltaicReactive

    User->>Frontend: Enter swap amount
    Frontend->>PoolMgr: Call swap() via Router
    PoolMgr->>Hook: beforeSwap() callback
    Hook->>Hook: Calculate dynamic fee based on volatility
    Hook-->>PoolMgr: Return dynamic fee
    PoolMgr->>PoolMgr: Execute swap at dynamic fee
    PoolMgr->>Hook: afterSwap() callback
    Hook->>Hook: Update price buffer
    Hook->>Hook: Calculate new volatility
    Hook->>Hook: Check if threshold crossed
    alt Threshold Crossed
        Hook->>Hook: Update currentFee
        Hook->>Hook: Emit VolatilityThresholdCrossed
        Hook->>Reactive: Event emitted
        Reactive->>Hook: Call refreshFee()
    end
    PoolMgr-->>Frontend: Return swap result
    Frontend-->>User: Display success
Loading

Fee Adjustment Flow

flowchart TD
    A[Swap Executed] --> B[afterSwap Called]
    B --> C[Update Price Buffer]
    C --> D[Calculate Volatility]
    D --> E{Volatility > Threshold?}
    
    E -->|Yes - Low to Mid| F[Update Fee: 0.50% → 1.50%]
    F --> G[Emit VolatilityThresholdCrossed]
    E -->|Yes - Mid to High| H[Update Fee: 1.50% → 3.00%]
    H --> G
    E -->|Yes - High to Mid| I[Update Fee: 3.00% → 1.50%]
    I --> G
    E -->|Yes - Mid to Low| J[Update Fee: 1.50% → 0.50%]
    J --> G
    E -->|No| K[Fee Unchanged]
    
    G --> L[Reactive Network Triggered]
    L --> M[Automatic Fee Refresh]
    M --> N[Fee Updated]
    
    K --> O[End]
    N --> O
Loading

How It Works

Volatility Calculation (Oracle-Free)

The hook calculates volatility using only on-chain swap data:

  1. Store last 10 swap prices in circular buffer
  2. Calculate price ratios (current/previous)
  3. Compute standard deviation of ratios
  4. Convert to percentage volatility
  5. Map to fee tier
// Volatility = Standard Deviation of Price Returns * 100
// Returns = (Current Price - Previous Price) / Previous Price

Fee Tiers Based on Volatility

Volatility Range Fee Tier Description
0-5% 0.50% (5000 bps) Calm Market
5-15% 1.50% (15000 bps) Normal Market
15%+ 3.00% (30000 bps) High Volatility

Hook Lifecycle

stateDiagram-v2
    [*] --> Idle
    Idle --> SwapRequested : User initiates swap
    SwapRequested --> BeforeSwap : PoolManager calls beforeSwap
    BeforeSwap --> ReturnFee : Calculate dynamic fee
    ReturnFee --> SwapExecuting : Return fee to PoolManager
    SwapExecuting --> AfterSwap : PoolManager calls afterSwap
    AfterSwap --> UpdateBuffer : Store new price
    UpdateBuffer --> CalculateVol : Compute volatility
    CalculateVol --> CheckThreshold : Compare to thresholds
    CheckThreshold --> UpdateFee : Threshold crossed
    CheckThreshold --> Idle : No change
    UpdateFee --> EmitEvent : Emit VolatilityThresholdCrossed
    EmitEvent --> Idle
    Idle --> [*]
Loading

Quick Start

Prerequisites

  • Node.js 18+
  • pnpm (recommended) or npm
  • Foundry (for contract development)
  • MetaMask or WalletConnect compatible wallet

Installation

# Clone repository
git clone https://github.com/Moses-main/voltaic-fee-adjuster.git
cd voltaic-fee-adjuster

# Install dependencies
pnpm install

# Install Foundry dependencies
cd contracts
forge install

# Build contracts
forge build

# Build frontend
pnpm run build

# Start development server
pnpm run dev

Environment Setup

  1. Copy .env.example to .env:
cp .env.example .env
  1. Configure your environment variables:
# Network Configuration
UNICHAIN_RPC_URL=https://sepolia.unichain.org
PRIVATE_KEY=your_private_key_here
ETHERSCAN_API_KEY=your_api_key

# Contract Addresses (already configured for Sepolia)
VOLTAIC_HOOK_ADDRESS=0xc9497Ec40951FbB98C02c666b7F9Fa143678E2Be

Deployment

Contract Deployment (Sepolia)

cd contracts

# Deploy VoltaicHook
forge script script/DeployVoltaicHook.s.sol:DeployVoltaicHookScript \
  --rpc-url $UNICHAIN_RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --verify

# Deploy VoltaicRouter
forge script script/DeployVoltaicRouter.s.sol:DeployVoltaicRouterScript \
  --rpc-url $UNICHAIN_RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast \
  --verify

# Deploy Test Pool
forge script script/DeployTestPool.s.sol:DeployTestPoolScript \
  --rpc-url $UNICHAIN_RPC_URL \
  --private-key $PRIVATE_KEY \
  --broadcast

Frontend Deployment

# Build for production
pnpm run build

# Deploy to Vercel (recommended)
vercel --prod

Interacting with the Application

1. Setup Your Wallet

  1. Install MetaMask or use WalletConnect compatible wallet

  2. Add Unichain Sepolia Network:

  3. Get Test ETH:

2. Connect to Application

  1. Open the application in your browser
  2. Click "Connect Wallet" in the Navbar
  3. Select your wallet (MetaMask or WalletConnect)
  4. Approve the connection in your wallet

3. View Pool Dashboard

Navigate to the Dashboard to see:

  • Current Fee - Dynamic fee based on volatility
  • Volatility Index - Real-time volatility percentage
  • Buffer Status - Number of prices tracked
  • LP Protection Score - Protection level (0-100)

4. Perform Swaps

  1. Navigate to Pool Interactions → Swap tab
  2. Select "You Pay" token (vETH or vUSDC)
  3. Enter amount to swap
  4. Click "Swap" and approve in your wallet
  5. Transaction will appear in Recent Transactions
  6. View transaction on Uniscan

Contract Addresses

Unichain Sepolia (Testnet)

Contract Address Explorer
VoltaicHook 0xDaa3B23DB3A078deF174314F4e8D4e68b14A55Dc View
VoltaicRouter 0x542dEF8ca751D015473788169F0dBe16F206AA43 View
SelfApprovingLiquidityAdder 0xd076910Ed1448bDD98A3625ed99B1b69Df2EF8Df View
PoolManager 0x00B036B58a818B1BC34d502D3fE730Db729e62AC View
vETH Token 0x9F50a6a0464C590d6ED48AEc36690Efd3752F5E1 View
vUSDC Token 0xe41c86dF5BaCE6bEceD57Ecd916C7aE58a471C02 View

Pool Details

  • Pool fee tier: 10000 (1.0%)
  • Pool tick spacing: 60
  • Pool initialized at sqrtPriceX96 = 2^96 (tick 0)
  • Hook flags: beforeSwap + afterSwap + afterInitialize

Reactive Network (Lasna Testnet)

Contract Address Explorer
VoltaicReactive 0xc9497Ec40951FbB98C02c666b7F9Fa143678E2Be View

Unichain Mainnet (Coming Soon)

Contract Address
VoltaicHook To be deployed
VoltaicRouter To be deployed
VoltaicReactive To be deployed

Testing

Smart Contracts

cd contracts

# Run all tests
forge test

# Run specific test suite
forge test --match-contract VoltaicHookTest
forge test --match-contract ReactiveIntegrationTest

# Run with gas reporting
forge test --gas-report

# Run with coverage
forge coverage

Frontend

# Type checking
pnpm run typecheck

# Linting
pnpm run lint

# Run tests (if configured)
pnpm run test

Project Structure

voltaic-fee-adjuster/
├── contracts/                    # Smart Contracts
│   ├── src/
│   │   ├── VoltaicHook.sol      # Main hook implementation
│   │   ├── VoltaicRouter.sol   # Router for swaps/liquidity
│   │   ├── VoltaicRSC.sol      # Reactive Smart Contract (Mock)
│   │   └── VoltaicReactive.sol # Reactive Network Contract
│   ├── script/
│   │   ├── DeployVoltaicHook.s.sol
│   │   ├── DeployVoltaicRouter.s.sol
│   │   ├── DeployVoltaicRSC.s.sol
│   │   └── DeployTestPool.s.sol
│   └── test/
│       ├── VoltaicHook.t.sol
│       └── ReactiveIntegration.t.sol
│
├── ui/                          # Frontend Application
│   ├── components/
│   │   ├── FeeDisplay.tsx       # Fee/volatility display
│   │   ├── PoolInteraction.tsx  # Swap/Liquidity UI
│   │   ├── Navbar.tsx          # navigation
│   │   ├── WalletConnect.tsx   # Wallet connection
│   │   └── NetworkSelector.tsx  # Chain switcher
│   ├── pages/
│   │   ├── Dashboard.tsx        # Main dashboard
│   │   └── Index.tsx            # Landing page
│   ├── hooks/
│   │   └── contracts/
│   │       └── useVoltaicHook.ts
│   └── lib/
│       ├── wagmi.ts             # Wagmi config
│       └── contracts/
│           ├── addresses.ts     # Contract addresses
│           ├── voltaicHook.ts   # Hook ABI
│           └── voltaicRouter.ts # Router ABI
│
├── docs/                        # Documentation
│   └── DEMO_SCRIPT.md          # Demo script
├── public/                      # Static assets
│   ├── favicon.svg             # Favicon
│   └── og-image.svg            # OpenGraph image
├── README.md                    # This file
├── LICENSE                      # MIT License
└── SECURITY.md                  # Security policy

Contributing

We welcome contributions! Please see CONTRIBUTING.md for details.

Development Workflow

  1. Fork the repository on GitHub
  2. Clone your fork locally
  3. Create a feature branch (git checkout -b feature/amazing-feature)
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

Code Standards

  • Contracts: Follow Solidity Style Guide
  • Frontend: Use TypeScript, follow existing patterns
  • Tests: Write tests for new features
  • Documentation: Update README and inline comments

License

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


Acknowledgments

  • Built for UHI Hookathon 2026 by Atrium Academy
  • Powered by Uniswap v4 and Unichain
  • Integrated with Reactive Network for cross-chain automation
  • Styled with Tailwind CSS and shadcn/ui

Support

If you have questions or issues:

  1. Check the GitHub Issues
  2. Read the Documentation
  3. Open a new issue with detailed description

Built with ❤️ by Moses-main for UHI Hookathon 2026

About

Voltaic Hook is a Uniswap v4 hook that dynamically adjusts swap fees in real time based on recent pool volatility—automatically raising fees during sharp price swings to protect liquidity providers from impermanent loss and lowering them in calm, stable markets to attract more traders and increase trading volume—deployed on Unichain

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors