Skip to content

leooos33/ghost-engine

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

10 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ‘» Ghost Engine β€” Uniswap v4 Hook

A MEV-resistant matching engine that runs inside AMM swaps. Stream (TWAP) orders, limit orders, and JIT ghost fills β€” all settled at TWAP through a single v4 hook.

Unichain Sepolia Solidity Foundry


The Problem

DEX users face three flavors of execution pain:

  1. Large orders move the price against you (slippage)
  2. TWAP orders don't exist on-chain β€” you're stuck with bots or centralized services
  3. Limit orders require off-chain order books or fragmented protocols
  4. MEV extraction front-runs and sandwiches every swap

The Solution: Ghost Liquidity

Ghost Engine creates a virtual order book that lives inside a Uniswap v4 hook. Orders are accumulated as "ghost liquidity" β€” virtual balances that exist in the hook's state but aren't visible to MEV searchers until they're filled.

                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚       Ghost Engine Hook      β”‚
                    β”‚                               β”‚
  Stream Orders ──► β”‚  ACCRUE β†’ NET β†’ CROSS β†’      β”‚
  Limit Orders  ──► β”‚  ACTIVATE β†’ FILL              β”‚ ──► Filled at TWAP
  Market Swaps  ──► β”‚                               β”‚
                    β”‚  Ghost Pool (virtual liquidity)β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                               β”‚
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚   Uniswap v4 AMM    β”‚
                    β”‚   (remainder only)   β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key insight: The hook intercepts swaps via beforeSwap, fills what it can from ghost liquidity at TWAP, and only passes the unfilled remainder to the AMM. This means:

  • Zero slippage on the ghost-filled portion
  • MEV-resistant β€” ghost balances are virtual until filled
  • Composable β€” it's just a Uniswap v4 pool

Architecture

Smart Contracts (contracts/src/)

Contract Lines Purpose
GhostHook.sol 300 v4 Hook β€” beforeSwap fill pipeline + afterSwap settlement + token escrow
GhostPool.sol 469 Core engine β€” netting, accrual, limit activation, fill distribution
StreamLib.sol 180 O(1) TWAP accrual + epoch crossing (inspired by Franklin Templeton TWAMM)
JitFillLib.sol 90 Just-In-Time fill computation at TWAP price
PriceMath.sol 30 sqrtPriceX96 ↔ token amount conversions
TickBitmapLib.sol 30 Tick bitmap for limit order tracking
GhostTypes.sol 80 Shared structs: GhostPoolState, StreamOrder, LimitBucket, etc.

Python Reference Implementation (src/ghost_engine/)

Module Purpose
engine.py Full GhostEngine coordinator
ghost_pool.py Core pool state + netting
stream_module.py TWAP stream order management
limit_module.py Limit order buckets + activation
jit_fill.py JIT fill at TWAP
test_invariants.py 500-vector fuzz test suite

Ghost Solver β€” Uniswap API Integration (solver/)

A Python arbitrage bot that monitors ghost hook state and compares fill prices against Uniswap Trading API quotes to find profitable opportunities.

  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  β”‚  Ghost Hook  │────▢│   Ghost Solver    │◀────│  Uniswap API   β”‚
  β”‚  (on-chain)  β”‚     β”‚  (arbitrage bot)  β”‚     β”‚  /v1/quote     β”‚
  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                              β”‚
                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                   β”‚  Execute via web3    β”‚
                   β”‚  (ghost pool swap)   β”‚
                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Component Purpose
GhostStateReader Reads on-chain ghost pool state via web3 (ghost balances, TWAP, orders)
UniswapAPIClient Queries trade-api.gateway.uniswap.org/v1/quote for market prices
GhostArbitrageEngine Compares ghost TWAP fills vs market quotes, identifies spread
GhostSolver Main loop: monitor β†’ quote β†’ compare β†’ execute (dry-run or live)

Verified on real Unichain Sepolia:

{
  "twap_price": 1.0,
  "epoch_interval": 300,
  "stream_orders": 1,
  "hook": "0x7c1d6541482fE64e4D73069B0d7D73C408Eee0c8"
}

Hook Permission Flags

BEFORE_INITIALIZE        (bit 13)  β€” Initialize ghost pool state
BEFORE_SWAP              (bit 7)   β€” Run ghost fill pipeline
AFTER_SWAP               (bit 6)   β€” Take payment + update TWAP
BEFORE_SWAP_RETURNS_DELTA (bit 3)  β€” Custom fill accounting
                                     Combined: 0x20C8

Token Flow

  USER                         GHOST HOOK                    POOL MANAGER
   β”‚                              β”‚                              β”‚
   │── submitStream(amount) ──►   β”‚                              β”‚
   β”‚   transferFrom(user,hook)    β”‚                              β”‚
   β”‚                              β”‚                              β”‚
   β”‚                              │◄── beforeSwap() ──────────── β”‚
   β”‚                              β”‚  1. _accrueAll()             β”‚
   β”‚                              β”‚  2. _executeFill()           β”‚
   β”‚                              β”‚  3. sync() + transfer()      β”‚
   β”‚                              β”‚     + settle()          ──►  β”‚  (output to PM)
   β”‚                              β”‚  4. return BeforeSwapDelta   β”‚
   β”‚                              β”‚                              β”‚
   β”‚                              │◄── afterSwap() ────────────  β”‚
   β”‚                              β”‚  5. take()             ◄──   β”‚  (input from PM)
   β”‚                              β”‚  6. update TWAP              β”‚
   β”‚                              β”‚                              β”‚
   │◄── claimStream(earnings) ──  β”‚                              β”‚
   β”‚    transfer(hook,user)       β”‚                              β”‚

Live Deployment (Unichain Sepolia)

GhostHook: 0x7c1d6541482fE64e4D73069B0d7D73C408Eee0c8

Action TX Hash
CREATE2 Deploy 0x0715108e...
Pool Init (1:1) 0x48139da6...
Add Liquidity 0x0dcb5ac1...
TWAP Stream (1M/30min) 0xb944f47e...
Sell Limit (tick 100) 0xa89b30be...
Buy Limit (tick -100) 0xf62a851b...
Swap (ghost fill) 0xf2d7fd9a...

Test Results

Integration Tests (6/6 βœ…)

βœ… test_PoolInitialized         β€” 1:1 price, epoch=300s
βœ… test_StreamOrderLifecycle    β€” TWAP submit β†’ activate β†’ accrue β†’ swap
βœ… test_LimitOrderSubmit        β€” sell limit at tick 100
βœ… test_BuyLimitOrderSubmit     β€” buy limit at tick -100
βœ… test_GhostFillFlow           β€” stream β†’ accrue β†’ swap β†’ 48 tokens ghost-filled
βœ… test_MultipleOrderTypes      β€” stream + sell + buy limits coexist

CEX-Like Verification (9/9 βœ…)

βœ… TWAP constant rate           β€” 180000 = rate Γ— duration / RATE_SCALER (exact)
βœ… Proportional accrual         β€” Ghost = 90000 at 50% time (exact match)
βœ… Limit deposit integrity      β€” deposit = original = 50000 (exact)
βœ… Buy limit storage            β€” deposit = 30000, not activated above TWAP
βœ… Ghost fill economics         β€” 100 token0 out for 100 token1 in (price = 1.0 exact)
βœ… Opposing streams netting     β€” Both ghosts net to 0 (perfect internal market)
βœ… Cancel refund                β€” 119900 β‰ˆ 2/3 of 180000
βœ… Progressive consumption      β€” Ghost decreases monotonically: 333333 β†’ 333283 β†’ 333083
βœ… Full lifecycle               β€” Submit β†’ escrow β†’ accrue β†’ fill β†’ claim

Differential Fuzzing (208 vectors, 0 divergence)

Python reference ↔ Solidity implementation cross-validated across random parameters.


Getting Started

Prerequisites

  • Foundry
  • Python 3.10+ (for reference implementation)

Build & Test

cd contracts
forge build
forge test --rpc-url http://127.0.0.1:8545 -vvv

Deploy to Unichain Sepolia

# Start Anvil fork (for local testing)
anvil --fork-url https://sepolia.unichain.org --chain-id 1301

# Deploy (set PRIVATE_KEY env var for real testnet)
PRIVATE_KEY=0x... forge script script/DeployGhostHook.s.sol \
  --rpc-url https://sepolia.unichain.org --broadcast

# Run on-chain interactions
PRIVATE_KEY=0x... forge script script/InteractGhostHook.s.sol \
  --rpc-url https://sepolia.unichain.org --broadcast

Run Python Reference (Differential Fuzzing)

cd src
python -m ghost_engine.test_invariants

Run Ghost Solver (Uniswap API Arbitrage)

pip install web3 requests

# One-shot snapshot (reads live on-chain state)
python solver/ghost_solver.py --snapshot

# Monitoring mode (polls every 12s, compares ghost vs market)
python solver/ghost_solver.py --rpc https://sepolia.unichain.org --interval 12

# Live execution mode (CAUTION: will submit real transactions)
python solver/ghost_solver.py --live --min-spread 50

How It Works: The 5-Phase Pipeline

Every swap triggers the full ghost pipeline in beforeSwap:

Phase What Happens Gas
1. ACCRUE Stream ghost balances grow proportional to sellRate Γ— Ξ”t O(1)
2. NET Opposing ghost balances cancel at TWAP (internal market making) O(1)
3. CROSS Epoch boundaries: activate new streams, expire old ones O(epochs)
4. ACTIVATE Limit orders whose tick is crossed by TWAP become ghost O(ticks)
5. FILL Ghost liquidity fills the incoming swap at TWAP price O(1)

The unfilled remainder passes through to the AMM's constant-product curve.


Order Types

Type Description Settlement
Stream (TWAP) Drip-sell tokens over time at constant rate Continuous at TWAP
Sell Limit Sell token0 when price rises above tick On activation
Buy Limit Buy token0 when price falls below tick On activation
Market Regular swap β€” benefits from ghost fills Instant at TWAP + AMM

Key Design Decisions

  1. Token Escrow in Hook β€” Users deposit tokens to the hook on order submission. The hook settles with the PoolManager via sync β†’ transfer β†’ settle (output) and take (input) during swaps.

  2. CREATE2 Address Mining β€” Hook permissions are encoded in the contract address's lowest 14 bits. A HookMiner brute-forces a CREATE2 salt producing the correct 0x20C8 flags.

  3. O(1) Stream Accrual β€” Inspired by Franklin Templeton's TWAMM: track aggregate sellRate and earningsFactor instead of iterating per-order. Individual orders sync lazily on claim.

  4. Internal Netting β€” Opposing ghost balances (sell-T0 vs sell-T1) cancel at TWAP before touching the AMM. This is pure value: zero gas, zero slippage, zero MEV.

  5. Modular Architecture β€” GhostPool (abstract) handles all engine logic. GhostHook (concrete) handles v4 integration + token custody. New order types plug in without modifying core.


License

MIT


Built for the Uniswap v4 Hook track. Ghost Engine β€” invisible liquidity, perfect execution.

About

πŸ‘» Ghost Engine β€” MEV-resistant matching engine inside a Uniswap v4 Hook. Stream (TWAP) + limit orders + JIT ghost fills, settled at TWAP. Live on Unichain Sepolia.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors