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.
DEX users face three flavors of execution pain:
- Large orders move the price against you (slippage)
- TWAP orders don't exist on-chain β you're stuck with bots or centralized services
- Limit orders require off-chain order books or fragmented protocols
- MEV extraction front-runs and sandwiches every swap
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
| 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. |
| 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 |
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"
}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
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) β β
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_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
β
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
Python reference β Solidity implementation cross-validated across random parameters.
- Foundry
- Python 3.10+ (for reference implementation)
cd contracts
forge build
forge test --rpc-url http://127.0.0.1:8545 -vvv# 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 --broadcastcd src
python -m ghost_engine.test_invariantspip 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 50Every 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.
| 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 |
-
Token Escrow in Hook β Users deposit tokens to the hook on order submission. The hook settles with the PoolManager via
sync β transfer β settle(output) andtake(input) during swaps. -
CREATE2 Address Mining β Hook permissions are encoded in the contract address's lowest 14 bits. A
HookMinerbrute-forces a CREATE2 salt producing the correct0x20C8flags. -
O(1) Stream Accrual β Inspired by Franklin Templeton's TWAMM: track aggregate
sellRateandearningsFactorinstead of iterating per-order. Individual orders sync lazily on claim. -
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.
-
Modular Architecture β
GhostPool(abstract) handles all engine logic.GhostHook(concrete) handles v4 integration + token custody. New order types plug in without modifying core.
MIT
Built for the Uniswap v4 Hook track. Ghost Engine β invisible liquidity, perfect execution.