Skip to content

Commit 7998157

Browse files
committed
more-graphs
1 parent 766d499 commit 7998157

File tree

2 files changed

+444
-1
lines changed

2 files changed

+444
-1
lines changed

β€Žarchitecture.mdβ€Ž

Lines changed: 167 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,111 @@
1+
# TLISHook Architecture
2+
3+
## Context: Uniswap V4 and MEV
4+
5+
**Important:** Uniswap V4 pools are **NOT MEV-resistant by default**. V4 provides:
6+
- βœ… Hooks system (extensibility)
7+
- βœ… Singleton architecture (gas efficiency)
8+
- βœ… Flash accounting (capital efficiency)
9+
- ❌ NO built-in MEV protection
10+
11+
**Standard V4 pools** (without special hooks) **still suffer from:**
12+
- Sandwich attacks
13+
- Front-running
14+
- JIT liquidity attacks
15+
- Toxic order flow
16+
17+
**TLISHook is a V4 hook that ADDS MEV protection** on top of V4's infrastructure. Without this hook, V4 pools have the same MEV vulnerabilities as V2/V3.
18+
19+
---
20+
21+
## Pain Points
22+
23+
### 🎯 MEV Exploitation in Standard V4 Pools
24+
**Problem:** Even on Uniswap V4, sophisticated bots scan the mempool and front-run profitable trades. A user submitting a large swap to a vanilla V4 pool can still lose 2-5% to sandwich attacks.
25+
26+
**How TLISHook Solves It:** Time-locked encryption hides trade details during collection phase. Intents are XOR encrypted with future drand randomness - nobody can decrypt until the unlock time passes.
27+
28+
### πŸ” Privacy Leakage in V4 Swaps
29+
**Problem:** All V4 swap transaction details (amounts, directions, addresses) are public in the mempool before execution. Large traders reveal their positions, market makers can adjust prices, competitors gain intelligence.
30+
31+
**How TLISHook Solves It:** Encrypted intents hide all parameters for 5 minutes during batch collection. Decryption only happens atomically at execution time.
32+
33+
### πŸ“Š Predictable Execution in V4
34+
**Problem:** V4 swaps have deterministic execution prices, enabling "just-in-time" MEV attacks. Attackers submit transactions that execute right before victim trades, manipulating prices profitably.
35+
36+
**How TLISHook Solves It:** Surprise pricing adds Β±1% randomness (verifiable via drand). Even if encrypted data leaks, execution price remains unpredictable until drand publishes randomness.
37+
38+
### ⚑ Front-Running (Still Possible in V4)
39+
**Problem:** Even with V4, validators and searchers can reorder transactions to extract value. Priority gas auctions (PGA) waste user funds competing for block space.
40+
41+
**How TLISHook Solves It:** Batch execution with randomized prices makes front-running unprofitable. All trades execute atomically in single transaction at surprise prices.
42+
43+
### πŸ›‘οΈ Slippage Manipulation in V4 Swaps
44+
**Problem:** Users set wide slippage bounds (5-10%) to ensure execution on V4 pools, but attackers exploit this by pushing prices to the worst acceptable level via sandwich attacks.
45+
46+
**How TLISHook Solves It:** User-defined price bounds (minSqrtPriceX96, maxSqrtPriceX96) + minAmountOut protection + surprise pricing. Random execution price always clamped to user limits. If random price exceeds bounds, users get their limit price (best case scenario).
47+
48+
---
49+
50+
## Core Innovations
51+
52+
### πŸ” Time-Locked Intent System (TLIS)
53+
**What:** Intents encrypted with XOR using future drand randomness (per-intent drandRound). Decryption key only available after batch unlock time.
54+
55+
**Why:** Creates temporal privacy - intents visible on-chain but unreadable until execution. No trusted third party needed (drand is decentralized beacon).
56+
57+
**Impact:** 5-minute collection window where trade flow is completely hidden, preventing all mempool-based attacks.
58+
59+
### 🎲 Surprise Pricing: Gamified Trading with Safety Nets
60+
**What:** Every swap executes at a **surprise price** = market price Β± random offset (Β±1% in sqrtPriceX96 space). You might get lucky and pay less, or unlucky and pay more, but **always within your bounds**. Randomness from drand (verifiable, unpredictable).
61+
62+
**The Game Element:**
63+
- 🎰 **Risk/Reward:** Set wide bounds for higher chance of surprise upside, or tight bounds for predictability
64+
- 🎲 **Luck Factor:** Alice sells at $1964 (unlucky -1.8%), Bob buys at $2014 (lucky +0.7%), Carol hits max bound at $2020
65+
- 🎯 **Strategic Betting:** Trade during volatile batches for bigger surprises, or wait for stable batches for safety
66+
- πŸ›‘οΈ **Protected Gambling:** Unlike casino, you can't lose more than your specified worst-case (bounds always enforced)
67+
68+
**The MEV Protection:**
69+
- Makes arbitrage/front-running unprofitable since execution price unknown until after commitment
70+
- Even attackers face same price uncertainty as honest users (can't predict if they'll win or lose)
71+
- Converts zero-sum MEV game into fun user gamble with house protection
72+
73+
**Why It's Powerful:** Combines **excitement** (random outcomes, potential for better prices) + **safety** (bounds guarantee worst-case protection) + **fairness** (same randomness for everyone) + **fun** (trading feels like skill-based lottery, not sterile finance).
74+
75+
**User Perspective:** "I'm willing to get anywhere between $1950-$2050 for my ETH. Let's see if I get lucky!" β†’ Executes at $2014 β†’ "Nice! I beat the market by $14 πŸŽ‰"
76+
77+
### πŸ“¦ Batch Atomicity
78+
**What:** All intents in a batch execute in single `poolManager.unlock()` β†’ `unlockCallback()` flow. No partial execution, no state changes between swaps.
79+
80+
**Why:** Prevents inter-batch MEV and toxic flow. Settlement happens atomically - either all swaps succeed or all revert.
81+
82+
**Impact:** Eliminates sandwich attacks within batch. Hook acts as escrow, settling all trades simultaneously.
83+
84+
### ⏰ Timestamp-Based Coordination
85+
**What:** Batch IDs calculated from `block.timestamp / 300` (not sequential counters). Unlock time = `(batchId + 1) * 300 + 60`.
86+
87+
**Why:** Makes batch timing predictable without central coordination. Anyone can calculate when a batch closes and unlocks.
88+
89+
**Impact:** Enables decentralized keeper network - no single entity controls execution timing.
90+
91+
### πŸ”— Drand Integration
92+
**What:** Uses drand quicknet (3-second rounds) for both encryption and randomness. Each intent stores target drandRound calculated at submission.
93+
94+
**Why:** Drand is decentralized, verifiable, and unpredictable. Nobody (including hook operator) can manipulate or predict future randomness.
95+
96+
**Impact:** Trustless randomness source that's already live and battle-tested. No additional oracle assumptions.
97+
98+
### πŸ’° Escrow-Based Settlement
99+
**What:** Users deposit tokens into hook's `s_userBalances` mapping. At execution, hook debits inputs and credits outputs atomically.
100+
101+
**Why:** Encrypted intents mean users can't pre-approve exact amounts. Escrow gives hook the ability to settle without user interaction.
102+
103+
**Impact:** Enables fully autonomous execution. After intent submission, users don't need to sign anything - keeper can execute and settle automatically.
104+
105+
---
106+
107+
## High-Level Architecture
108+
1109
```mermaid
2110
flowchart TB
3111
User([πŸ‘€ User])
@@ -45,4 +153,62 @@ flowchart TB
45153
class User,Keeper,Done userClass
46154
class Deposit,Submit,Batch,Lock,Withdraw processClass
47155
class Execute,Surprise,Swap,Settle execClass
48-
```
156+
```
157+
158+
## User Flow Steps
159+
160+
1. **Deposit** - User deposits ETH/USDC into hook's escrow (`s_userBalances`)
161+
2. **Submit** - User submits encrypted intent with price bounds (pays 0.001 ETH fee)
162+
3. **Execute** - Keeper executes batch after time-lock expires, decrypts intents with drand
163+
4. **Withdraw** - User withdraws resulting tokens from escrow
164+
165+
## Why This Works
166+
167+
**Privacy + Surprise = MEV Resistance**
168+
169+
The combination of time-locked encryption (hiding trade details) and random surprise pricing (unpredictable execution prices) creates a two-layer defense:
170+
171+
1. **First Layer (Encryption):** Attackers can't see trade flow during collection phase
172+
2. **Second Layer (Randomness):** Even if encryption breaks, execution price is random Β±1%
173+
174+
**Result:** Front-running and sandwich attacks become unprofitable because attackers can't:
175+
- See intent details before batch closes (encrypted)
176+
- Predict execution prices before drand reveals (random)
177+
- Execute partial batches to extract value (atomic settlement)
178+
179+
**User Protection:** Price bounds ensure users never get worse than their specified limits, while surprise pricing gives them a chance to get better prices than market.
180+
181+
---
182+
183+
## The Innovation: Trading as a Game
184+
185+
**TLISHook transforms boring swaps into exciting gambles** - but with safety rails:
186+
187+
### 🎰 The Bet
188+
- You're betting on randomness, not against the house
189+
- Set your risk tolerance via bounds: tight bounds (safe) vs wide bounds (adventurous)
190+
- Every trade is a mini-lottery where you might beat the market
191+
192+
### 🎲 The Randomness
193+
- Verifiable via drand - provably fair, can't be manipulated
194+
- Same randomness for everyone in the batch (no favoritism)
195+
- Β±1% range means real possibility of significantly better/worse prices
196+
197+
### πŸ›‘οΈ The Safety Net
198+
- Can't lose more than your worst-case bound (minSqrtPriceX96/maxSqrtPriceX96)
199+
- minAmountOut provides additional protection
200+
- If random price exceeds your bound, you get your bound (best case for you)
201+
202+
### 🎯 The Strategy
203+
- **Conservative:** Set bounds Β±0.2% from market β†’ guaranteed near-market execution
204+
- **Moderate:** Set bounds Β±2% from market β†’ good chance of surprise upside
205+
- **Aggressive:** Set bounds Β±5% from market β†’ high risk, high reward potential
206+
- **Timing:** Trade during high volatility for bigger surprise potential
207+
208+
### πŸŽ‰ The Experience
209+
**Traditional V4 swap:** "I'm selling 1 ETH at market price ~$2000"
210+
**TLISHook swap:** "I'm okay with $1950-$2050 for my ETH... let's see what I get! 🎲"
211+
β†’ Executes at $2014 β†’ "YES! I beat the market! πŸŽ‰"
212+
β†’ Or $1964 β†’ "Unlucky this time, but still within my limits βœ…"
213+
214+
**Result:** Trading becomes engaging, strategic, and fun - while being MORE secure than traditional swaps due to MEV protection. You're not just avoiding MEV extraction; you're actively participating in a fair game where luck might give you BETTER prices than market.

0 commit comments

Comments
Β (0)