# Uniswap — full corpus # LLM Wiki An open-source template for building LLM-powered knowledge bases, following [Andrej Karpathy's "LLM Wiki" pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f). You provide raw sources. The LLM reads them, writes structured wiki pages, cross-links everything, and maintains it over time. You never edit the wiki directly — you curate sources and ask questions. ## How It Works The system has three layers: ``` raw/ Sources you collect (articles, transcripts, notes, PDFs) wiki/ LLM-written & maintained pages (summaries, concepts, entities, syntheses) CLAUDE.md Schema that tells the LLM how to structure everything ``` Three operations drive the workflow: | Operation | Trigger | What happens | |-----------|---------|--------------| | **Ingest** | "ingest raw/my-source.txt" | LLM reads the source, creates a summary page, creates/updates concept and entity pages, adds cross-links, updates the index and log | | **Query** | Ask any question | LLM searches the wiki, synthesizes an answer with citations, optionally creates a synthesis page for novel insights | | **Lint** | "lint" or "health check" | LLM audits all pages for orphans, contradictions, missing links, incomplete sections, and low-confidence claims — fixes what it can, reports the rest | ## Quick Start 1. **Clone this repo** ```bash git clone https://github.com/YOUR_USERNAME/llm-wiki.git my-knowledge-base cd my-knowledge-base ``` 2. **Customize CLAUDE.md** for your domain - Update the Purpose section with your topic - Replace the placeholder tagging taxonomy with your own categories - Adjust confidence level descriptions if needed - Everything else (workflows, page formats, linking rules) works as-is 3. **Drop sources into `raw/`** - Text files, transcripts, articles, notes — any plain text - These are immutable once added; the LLM never modifies them 4. **Tell the LLM to ingest** ``` ingest raw/my-first-source.txt ``` The LLM will create summary pages, concept pages, entity pages, cross-links, and update the index. 5. **Ask questions** ``` What are the key differences between X and Y? ``` The LLM answers from the wiki, citing specific pages. 6. **Run health checks** ``` lint ``` The LLM audits the wiki and fixes issues. ## Directory Structure ``` . ├── CLAUDE.md # Schema — the LLM's instructions ├── raw/ # Your source documents (immutable) └── wiki/ ├── index.md # Master catalog of all pages ├── log.md # Append-only activity log ├── dashboard.md # Dataview dashboard (Obsidian) ├── analytics.md # Charts View analytics (Obsidian) ├── flashcards.md # Spaced repetition cards ├── summaries/ # One page per source document ├── concepts/ # Concept and framework pages ├── entities/ # People, tools, organizations, etc. ├── syntheses/ # Cross-cutting analyses and comparisons ├── journal/ # Research/session journal entries │ └── template.md # Journal entry template └── presentations/ # Marp slide decks ``` ## Enhancements This template includes several extras beyond the core wiki pattern: ### Dataview Dashboard (`wiki/dashboard.md`) Live queries that surface low-confidence pages, recent updates, concepts by tag, and pages with the most sources. Requires the [Dataview](https://github.com/blacksmithgu/obsidian-dataview) Obsidian plugin. ### Charts View Analytics (`wiki/analytics.md`) Visual analytics with pie charts, bar charts, and word clouds. Requires the [Charts View](https://github.com/caronchen/obsidian-chartsview-plugin) Obsidian plugin. ### Mermaid Diagrams Use Mermaid code blocks in any wiki page to create flowcharts, sequence diagrams, or concept maps. Native support in Obsidian and GitHub. ### Marp Slides (`wiki/presentations/`) Create slide decks from markdown using [Marp](https://marp.app/). Drop presentation files in this directory. ### Research Journal (`wiki/journal/`) Track your research sessions, experiments, or applied work with the included template. The LLM can reference journal entries when answering queries. ### Spaced Repetition (`wiki/flashcards.md`) Flashcards in the format used by the [Spaced Repetition](https://github.com/st3v3nmw/obsidian-spaced-repetition) Obsidian plugin. Ask the LLM to generate flashcards from any wiki page. ### MCP Server This repo works with Claude Code's MCP server capabilities. Point an MCP-compatible client at this repo and the LLM can read/write the wiki programmatically. ## Customizing for Your Domain The schema in `CLAUDE.md` is domain-agnostic. To adapt it: 1. **Purpose** — Describe your knowledge domain in one paragraph 2. **Tagging taxonomy** — Replace placeholder categories with your own (e.g., for a cooking KB: `cuisine`, `technique`, `ingredient`, `equipment`) 3. **Confidence levels** — Adjust the descriptions to match your domain's evidence standards 4. **Entity types** — Update the entity page description to match what entities mean in your domain (people, tools, companies, etc.) 5. **Journal template** — Customize `wiki/journal/template.md` for your workflow Everything else — page format, linking conventions, workflows, rules — is universal and works across domains. ## Example Domains This template works for any knowledge-intensive topic: - **Research notes** — papers, experiments, methodologies - **Book analysis** — themes, characters, author techniques - **Competitive analysis** — companies, products, market trends - **Course notes** — lectures, readings, key concepts - **Personal development** — frameworks, habits, book summaries - **Technical documentation** — APIs, architectures, design patterns - **Hobby deep-dives** — any subject you want to master ## License MIT --- title: "Knowledge Base Index" type: index updated: 2026-06-19 --- # Knowledge Base Index Master catalog of all wiki pages. Every page in the wiki must have an entry here. ## Concepts | Page | Tags | Confidence | Updated | |------|------|------------|---------| | [what-is-uniswap](concepts/what-is-uniswap.md) | uniswap, defi, amm | high | 2026-06-19 | | [how-amms-work](concepts/how-amms-work.md) | amm, constant-product, pricing | high | 2026-06-19 | | [protocol-versions](concepts/protocol-versions.md) | v2, v3, v4, comparison | high | 2026-06-19 | | [concentrated-liquidity](concepts/concentrated-liquidity.md) | concentrated-liquidity, ranges, ticks | high | 2026-06-19 | | [v4-hooks](concepts/v4-hooks.md) | hooks, v4, singleton | high | 2026-06-19 | | [fees](concepts/fees.md) | fees, fee-tiers, protocol-fee | high | 2026-06-19 | | [swaps-and-routing](concepts/swaps-and-routing.md) | swaps, routing, slippage | high | 2026-06-19 | | [flash-swaps](concepts/flash-swaps.md) | flash-swaps, flash-accounting | high | 2026-06-19 | | [oracles](concepts/oracles.md) | oracles, twap, price-feed | high | 2026-06-19 | | [permit2](concepts/permit2.md) | permit2, approvals, signatures | high | 2026-06-19 | | [universal-router](concepts/universal-router.md) | universal-router, commands | high | 2026-06-19 | | [uniswapx](concepts/uniswapx.md) | uniswapx, intents, auctions | high | 2026-06-19 | | [smart-contracts](concepts/smart-contracts.md) | contracts, core, periphery | high | 2026-06-19 | ## Entities | Page | Tags | Updated | |------|------|---------| | [sdks-and-api](entities/sdks-and-api.md) | sdk, api, integration | 2026-06-19 | ## Summaries | Page | Source | Key Topics | Created | |------|--------|------------|---------| | [docs-catalog](summaries/docs-catalog.md) | developers.uniswap.org llms.txt | area map + reference spaces | 2026-06-19 | ## Syntheses | Page | Pages Compared | Created | |------|----------------|---------| | [integrating-a-swap](syntheses/integrating-a-swap.md) | quote→permit2→execute flow | 2026-06-19 | | [liquidity-provision](syntheses/liquidity-provision.md) | LP economics + IL + ranges | 2026-06-19 | ## Statistics - **Total pages**: 17 - **Concepts**: 13 - **Entities**: 1 - **Summaries**: 1 - **Syntheses**: 2 - **Sources ingested**: 92 (developers.uniswap.org llms.txt: 1 index + 91 pages) - **High confidence**: 16 - **Medium confidence**: 1 --- title: "Concentrated Liquidity" type: concept tags: [concentrated-liquidity, v3, v4, ranges, ticks] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-concentrated-liquidity.md, raw/llms_txt_doc-range-orders.md, raw/llms_txt_doc-lp-calculations.md] --- # Concentrated Liquidity **Concentrated liquidity** — introduced in Uniswap v3 and continued in v4 — lets a liquidity provider allocate capital to a **specific price range** instead of the entire price curve, dramatically improving capital efficiency. ## How it works - An LP picks a **lower and upper price** (bounds, snapped to discrete **ticks**). Their liquidity is only active — earning [fees](fees.md) — while the market price is **within that range**. - Concentrating the same capital in a tighter range provides much deeper liquidity (and more fees) there than spreading it full-range — many times the capital efficiency for stable or correlated pairs. - Positions are **non-fungible** (each range is distinct), represented as NFTs. ## The trade-offs - **Out-of-range = idle** — if price leaves your range, your position stops earning fees and becomes entirely one token (you've effectively sold the other). You must **rebalance** (move the range) to resume earning — active management. - **Amplified impermanent loss** within the range vs full-range LPing. ## Range orders A clever use: set a one-sided narrow range so that as price crosses it, your position fully converts from token A to token B — approximating a **limit order** ("range order"). Useful for entering/exiting at target prices without a central order book. ## LP math Computing the token amounts, liquidity (`L`), and fees for a range is non-trivial; Uniswap documents the v2→v4 **LP calculations** and provides tools. Position value depends on current price relative to the range bounds. For the economics (IL, fee APR, rebalancing) see [liquidity-provision](../syntheses/liquidity-provision.md). --- title: "Fees" type: concept tags: [fees, fee-tiers, protocol-fee, lp-fee] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-fees.md, raw/llms_txt_doc-uniswap-protocol-fees.md, raw/llms_txt_doc-protocol-fee-configuration.md] --- # Fees Every Uniswap swap pays a fee that compensates [liquidity providers](../syntheses/liquidity-provision.md) for their capital; a portion can also go to the protocol. ## LP fee The **swap fee** is charged on every trade and accrues to the LPs whose liquidity is **active** at the time of the swap, distributed **pro-rata** to active liquidity ([concentrated-liquidity](concentrated-liquidity.md) means only in-range LPs earn). This is the LP's return for providing liquidity (alongside price risk). ## Fee tiers - **v2** — a single fixed fee (historically 0.30%) per pool. - **v3** — **multiple fee tiers** per pair (e.g. 0.01% / 0.05% / 0.30% / 1.00%): low tiers for stable/correlated pairs, higher tiers for volatile/exotic pairs. Each tier is a separate pool. - **v4** — fee tiers plus **dynamic fees** via [hooks](v4-hooks.md) (a hook can set the fee per swap). ## Protocol fee A **protocol fee** can optionally take a fraction *of the LP fee*, switchable via governance (`protocol-fee-configuration`). When off, 100% of the swap fee goes to LPs; when on, a configured share is diverted to the protocol treasury. It's a cut of the LP fee, not an extra charge on traders. ## Practical - Choosing a pool/tier affects both trader cost and LP earnings; routers pick the tier giving the best net price ([swaps-and-routing](swaps-and-routing.md)). - LP fee APR depends on volume and how concentrated your range is — see [liquidity-provision](../syntheses/liquidity-provision.md). --- title: "Flash Swaps" type: concept tags: [flash-swaps, flash-accounting, arbitrage] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-flash-swaps.md, raw/llms_txt_doc-flash-swaps-2.md] --- # Flash Swaps **Flash swaps** let you withdraw up to the full reserves of any ERC-20 from a Uniswap pool and **execute arbitrary logic at no upfront cost**, provided that by the end of the transaction you either pay for the withdrawn tokens with the corresponding pair token or return them (plus the fee). Everything happens atomically — if the repayment condition isn't met, the whole transaction reverts. ## How it works (v2 model) 1. Call the pool's swap, requesting output tokens **before paying**. 2. The pool sends you the tokens and calls your callback. 3. In the callback you do whatever you want (arbitrage, liquidation, collateral swap) using those tokens. 4. Before returning, you pay the pool: either the other token of the pair (a normal swap, just paid last) or return the same token + fee. 5. The pool checks its invariant holds; otherwise it reverts. ## Uses - **Arbitrage** — exploit a price difference across venues with zero capital: borrow via flash swap, sell high elsewhere, repay, keep the spread. - **Collateral swaps / liquidations** — restructure a DeFi position atomically without upfront funds. - **Self-liquidation** and complex multi-protocol operations. ## v4 flash accounting Uniswap v4 generalizes this idea with **flash accounting**: balances are tracked as deltas and **settled once at the end** of the transaction across all pool interactions ([protocol-versions](protocol-versions.md)). This makes multi-pool routes and hook-driven flows cheaper and makes flash-style operations a first-class part of the architecture rather than a special case. Flash swaps are powerful but require careful contract code — repayment must always succeed within the same transaction or it reverts. --- title: "How AMMs Work" type: concept tags: [amm, constant-product, pricing, price-impact] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-how-uniswap-works.md, raw/llms_txt_doc-swaps.md, raw/llms_txt_doc-pricing.md] --- # How AMMs Work Uniswap replaces an order book with an **automated market maker**: a pool holds reserves of two tokens, and a formula sets the price. ## Constant product (x·y=k) The classic Uniswap v2 invariant: a pool holds reserves `x` and `y` of two tokens, and trades must keep **`x · y = k`** constant (minus fees). Buying token Y removes it from the pool and adds token X, which **moves the price** — the more you buy relative to reserves, the worse the price. There's always liquidity at *some* price (the curve never empties), but large trades pay more. ## Price, price impact, slippage - **Price** is the ratio of reserves at the margin. - **Price impact** — how much your trade moves the pool price (a function of trade size vs liquidity). Big trade in a shallow pool = large impact. - **Slippage tolerance** — the max adverse price move you'll accept between submitting and execution; the trade reverts if exceeded (protects against front-running and volatility). ## LP shares Depositing both tokens earns you a share of the pool and its [fees](fees.md). How shares are tracked **differs by version**: v2 mints fungible pool tokens for a proportional share of reserves; v3/v4 use **concentrated liquidity** where each position is a chosen price range ([concentrated-liquidity](concentrated-liquidity.md), [protocol-versions](protocol-versions.md)). ## Swapping is permissionless Anyone can swap any listed token directly against pools; routing across multiple pools/hops to get the best price is handled by routers and the [API/SDK](../entities/sdks-and-api.md) ([swaps-and-routing](swaps-and-routing.md)). Arbitrage keeps Uniswap prices aligned with the broader market. --- title: "Price Oracles" type: concept tags: [oracles, twap, price-feed] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-oracles.md, raw/llms_txt_doc-building-an-oracle.md] --- # Price Oracles Uniswap pools double as **on-chain price oracles**: because every swap updates the pool price, the protocol can expose a manipulation-resistant price feed that other contracts consume. ## TWAP (time-weighted average price) The core oracle primitive is the **TWAP**. Rather than the spot price (cheap to manipulate within one block), the pool accumulates price over time; a consumer reads two cumulative observations and divides by the elapsed time to get the **average price over a window**. Averaging over a window makes manipulation expensive — an attacker must sustain a distorted price across many blocks, which arbitrage punishes. ## By version - **v2** — exposes `price0CumulativeLast` / `price1CumulativeLast`; consumers snapshot and compute TWAP themselves. - **v3** — built-in **observation arrays** store historical cumulative ticks; you can query a TWAP over a chosen window directly, with configurable observation cardinality. - **v4** — oracles can be implemented as **[hooks](v4-hooks.md)**, giving custom oracle behavior per pool. ## Building/using an oracle - Choose a **window** that trades off freshness vs manipulation cost (longer = safer, more lagged). - Use **deep, liquid pools** — TWAPs from thin pools are easier to manipulate. - Beware using spot price directly for anything security-sensitive (lending, liquidations) — that's a classic exploit; use a sufficiently long TWAP or an external oracle. Uniswap oracles are widely used across DeFi as a decentralized price source; the docs cover building one against each version's interfaces ([smart-contracts](smart-contracts.md)). --- title: "Permit2" type: concept tags: [permit2, approvals, signatures, allowances] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-permit2-approval.md, raw/llms_txt_doc-allowance-transfer.md, raw/llms_txt_doc-signature-transfer.md] --- # Permit2 **Permit2** is a shared token-approval contract that improves the ERC-20 approval UX and security across DeFi (not just Uniswap). It lets users approve the Permit2 contract once, then authorize specific spenders via **signatures** instead of a separate on-chain approval per protocol. ## The flow (in the Uniswap API swap) 1. The wallet grants a standard **ERC-20 approval to the Permit2 contract** (once per token). 2. For each action, the wallet **signs an off-chain message** authorizing Permit2 to let a specific spender (e.g. the [Universal Router](universal-router.md)) move a bounded amount, with an **expiry**. 3. The contract validates the signature and transfers — no per-protocol on-chain approval needed. This is the **default** Uniswap API swap flow and is safer than approving routers directly: approvals are **scoped (amount + spender + deadline)** rather than unlimited and permanent. ## Two modes - **AllowanceTransfer** — set a signed allowance (amount + expiration + nonce) a spender can draw from over time; good for repeated interactions. - **SignatureTransfer** — a one-shot signed transfer authorizing a single transfer (no stored allowance); maximal scoping for one action. ## Why it matters - **Security** — bounded, expiring approvals limit blast radius if a spender is compromised (vs the classic "infinite approval" risk). - **UX** — fewer approval transactions (gas + clicks); signatures are free. - **Shared standard** — many protocols use the same Permit2, so one approval serves an ecosystem. Common signing pitfalls (nonces, deadlines, domain) are noted in the API guide ([sdks-and-api](../entities/sdks-and-api.md)). --- title: "Protocol Versions: v2, v3, v4" type: concept tags: [v2, v3, v4, versions, comparison] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-how-uniswap-works.md, raw/llms_txt_doc-concentrated-liquidity.md, raw/llms_txt_doc-hooks.md] --- # Protocol Versions: v2, v3, v4 Uniswap's AMM has evolved through three live major versions, each a superset of ideas from the last. ## v2 The classic **constant-product** AMM ([how-amms-work](how-amms-work.md)). LP positions are **fungible ERC-20 pool tokens** representing a proportional share of the full-range reserves. Simple, battle-tested; introduced **[flash swaps](flash-swaps.md)** and price [oracles](oracles.md). Liquidity is spread across all prices (capital-inefficient). ## v3 Introduced **[concentrated liquidity](concentrated-liquidity.md)**: LPs allocate liquidity to a **custom price range** instead of the full curve, hugely improving capital efficiency. Positions become **non-fungible (ERC-721)** because each has a distinct range. Added **multiple fee tiers** per pair ([fees](fees.md)) and improved oracles. The defining v3 idea is concentrated liquidity. ## v4 Keeps v3's concentrated liquidity and adds major architecture changes: - **Hooks** — external contracts attached to a pool that run custom logic at lifecycle points (before/after swap, add/remove liquidity), enabling on-chain limit orders, dynamic fees, custom oracles, and more ([v4-hooks](v4-hooks.md)). - **Singleton** — all pools live in one contract (vs one contract per pair), drastically cutting pool-creation and multi-hop swap gas. - **Flash accounting** — net balances settle once at the end of a transaction, making complex multi-pool routes cheaper. - **Native ETH** support and more. ## Choosing / interoperating New custom-behavior pools target **v4**; deep existing liquidity still lives across **v3** and **v2**. Routers and the [API](../entities/sdks-and-api.md) route across all versions to find the best price ([swaps-and-routing](swaps-and-routing.md)). Contract differences are in [smart-contracts](smart-contracts.md). --- title: "Smart Contracts & Architecture" type: concept tags: [contracts, core, periphery, singleton, interfaces] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-core-interfaces.md, raw/llms_txt_doc-periphery-contracts.md, raw/llms_txt_doc-architecture.md] --- # Smart Contracts & Architecture Uniswap's onchain protocol splits into **core** (holds funds, enforces invariants) and **periphery** (safe, user-facing helpers), a separation that keeps the trusted core minimal. ## Core - **v2** — a `Factory` deploys one `Pair` contract per token pair; each pair holds reserves and enforces `x·y=k`. - **v3** — a `Factory` deploys `Pool` contracts per (pair, fee tier); pools implement [concentrated liquidity](concentrated-liquidity.md) with ticks and per-position state. - **v4** — a **singleton `PoolManager`** holds *all* pools, with **[flash accounting](flash-swaps.md)** (delta settlement at transaction end) and **[hooks](v4-hooks.md)**. Far less gas for pool creation and multi-pool routes ([protocol-versions](protocol-versions.md)). ## Periphery Contracts you actually call: - **Routers** — the [Universal Router](universal-router.md) (and version routers) execute swaps safely with slippage/deadline checks. - **Position managers** — `NonfungiblePositionManager` (v3) / v4 position manager mint and manage LP positions as NFTs. - **Quoters** — simulate swaps to get quotes off-chain. ## Interfaces & integration Core interfaces (`IUniswapV2Pair`, `IUniswapV3Pool`, v4 `IPoolManager`/`IHooks`) define the callable surface; the docs provide them per version. **Integrate through the periphery/[SDK](../entities/sdks-and-api.md), not the core directly** — calling pools raw skips safety checks. Deployment addresses per chain are published ([docs-catalog](../summaries/docs-catalog.md)). ## Security Core contracts are heavily audited and immutable; the risk surface for integrators is mostly **slippage**, **approvals** ([permit2](permit2.md)), and — in v4 — **untrusted [hooks](v4-hooks.md)**. The full per-contract API is large and version-specific — catalogued, not reproduced here ([docs-catalog](../summaries/docs-catalog.md)). --- title: "Swaps & Routing" type: concept tags: [swaps, routing, slippage, price-impact] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-swaps.md, raw/llms_txt_doc-swap-routing.md, raw/llms_txt_doc-price-discovery.md] --- # Swaps & Routing A **swap** trades one ERC-20 for another against pool liquidity — the most common Uniswap interaction, and permissionless. ## What happens in a swap 1. User picks an input token + amount and an output token. 2. A **route** is found across pools (possibly multiple hops and pool versions). 3. The user sets a **slippage tolerance** and **deadline**. 4. Tokens are approved (often via [Permit2](permit2.md)) and the swap executes through a router; it reverts if output < the slippage-protected minimum. ## Routing Liquidity is fragmented across token pairs, [fee tiers](fees.md), pool versions (v2/v3/v4), and chains. A **router** (and the [Uniswap API/SDK](../entities/sdks-and-api.md)) searches for the **best execution** — splitting a trade across multiple pools/paths and hopping through intermediary tokens (e.g. A→WETH→B) when that beats a direct pool. The [Universal Router](universal-router.md) executes the resulting multi-step plan atomically. ## Pricing factors - **Price impact** — your trade moving the pool price ([how-amms-work](how-amms-work.md)); larger in shallow pools. - **Slippage** — adverse movement between quote and execution; bounded by your tolerance. - **Gas** — more hops/splits cost more gas; the router weighs price vs gas for net best output. - **MEV** — public swaps can be sandwiched; [UniswapX](uniswapx.md) and private routing mitigate this. ## Getting a quote Use the [Uniswap API or SDK](../entities/sdks-and-api.md) to quote and build the calldata rather than hand-rolling routes — they handle multi-version routing, Permit2, and slippage. End-to-end integration: [integrating-a-swap](../syntheses/integrating-a-swap.md). --- title: "UniswapX" type: concept tags: [uniswapx, intents, auctions, fillers, gasless] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-uniswapx-overview.md, raw/llms_txt_doc-fillers-overview.md, raw/llms_txt_doc-request-for-quote-rfq.md] --- # UniswapX **UniswapX** is a permissionless, open-source, **auction-based, intent** swapping protocol. Instead of a user executing a route themselves, they **sign an order (intent)** describing what they want, and competitive **fillers** execute it — routing across AMMs *and* other (including private) liquidity sources. ## How it works 1. The swapper **signs an order** (an intent: sell X for at least Y, with parameters) — off-chain, gasless to create. 2. **Fillers** compete to fill the order at the best price, sourcing liquidity wherever they can (Uniswap pools, other DEXs, their own inventory, private market makers). 3. Pricing improves through **auction competition**; the winning filler executes on-chain and **pays the gas**. ## Benefits - **Gasless for the swapper** — the filler pays gas (cost is reflected in the price). Failed swaps cost the user nothing. - **Better prices** — competition across public + private liquidity, plus MEV that would otherwise be lost is returned as price improvement. - **MEV protection** — orders aren't naked public swaps, reducing sandwich risk ([swaps-and-routing](swaps-and-routing.md)). ## Order/auction types UniswapX uses several mechanisms — **Dutch auctions** (price decays until filled), **priority auctions**, and **RFQ (request-for-quote)** where market makers quote directly. Fillers integrate by watching for orders, quoting/bidding, and submitting fills (the `fillers` and RFQ docs cover quoter/filler integration). ## Participants - **Swappers** sign intents (via the [Uniswap API/app](../entities/sdks-and-api.md)). - **Fillers/quoters** compete to execute — a role with its own integration surface ([docs-catalog](../summaries/docs-catalog.md)). UniswapX complements the AMM: the [API](../entities/sdks-and-api.md) can route a swap through classic AMM execution *or* UniswapX depending on which gives the better outcome. --- title: "Universal Router" type: concept tags: [universal-router, commands, execution, routing] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-universal-router-commands.md] --- # Universal Router The **Universal Router** is Uniswap's flexible execution contract: it runs a **compact command stream** so a single transaction can compose many operations — multi-hop swaps across v2/v3/v4 pools, NFT purchases, wrapping/unwrapping ETH, and [Permit2](permit2.md) operations — atomically. ## Command encoding - A call to `execute` carries a **commands** byte string and an array of **inputs**. Each byte in `commands` selects an operation (a command), and the operation reads one ABI-encoded item from `inputs`. - Commands map to operation modules: e.g. `V2_SWAP_EXACT_IN`, `V3_SWAP_EXACT_IN`, `PERMIT2_PERMIT`, `WRAP_ETH`, `SWEEP`, `PAY_PORTION`, and v4 actions. - An overload of `execute` adds a **deadline** timestamp guard; both process the same command stream. ## Why a command stream Instead of a fixed set of router functions, the command pattern lets the off-chain router/[API](../entities/sdks-and-api.md) compose **exactly** the steps a trade needs — split routes, mixed versions, approvals, and ETH handling — in one atomic call. Composition patterns chain commands (permit → swap → sweep) so the user signs/sends once. ## Practical - You generally **don't hand-encode** commands — the Uniswap [SDK/API](../entities/sdks-and-api.md) builds the command stream and inputs for a routed swap. - Everything is atomic: if any command fails (or slippage/deadline is exceeded), the whole `execute` reverts. - The Universal Router is the standard execution layer the routing engine targets ([swaps-and-routing](swaps-and-routing.md)). --- title: "v4 Hooks" type: concept tags: [hooks, v4, customization, singleton] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-hooks.md, raw/llms_txt_doc-hooks-2.md, raw/llms_txt_doc-architecture.md] --- # v4 Hooks **Hooks** are the headline feature of Uniswap v4: external smart contracts attached to an individual pool that run **custom logic at lifecycle points**, letting developers extend and customize pool behavior without changing the core protocol. ## Hook points A hook contract can implement callbacks that the pool invokes around key actions, including: - **beforeInitialize / afterInitialize** (pool creation) - **beforeAddLiquidity / afterAddLiquidity**, **beforeRemoveLiquidity / afterRemoveLiquidity** - **beforeSwap / afterSwap** - **beforeDonate / afterDonate** A pool declares which hook callbacks it uses; the permissions are encoded in the **hook contract's address** (specific address bits flag which callbacks are active), so the core can cheaply know what to call. ## What hooks enable - **Dynamic fees** — adjust the [fee](fees.md) per swap based on volatility/conditions. - **On-chain limit orders** and **TWAMM** (time-weighted average market making). - **Custom oracles** ([oracles](oracles.md)) and MEV-internalizing designs. - **Custom curves / liquidity logic**, KYC'd pools, auto-compounding, and more. ## Architecture context Hooks pair with v4's **singleton** (all pools in one contract) and **flash accounting** (net settlement at transaction end), which make hook-rich, multi-pool interactions gas-efficient ([protocol-versions](protocol-versions.md)). A pool's hook is set at creation and immutable for that pool. ## Risks A hook is arbitrary code in the swap path — a malicious or buggy hook can break or drain a pool. **Only interact with audited/trusted hooks**; the hook address is part of the pool's identity, so vet it. Building hooks uses the v4 [smart-contracts](smart-contracts.md) interfaces. --- title: "What is Uniswap" type: concept tags: [uniswap, defi, amm, overview] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-protocols-overview.md, raw/llms_txt_doc-how-uniswap-works.md, raw/llms_txt_doc-ecosystem-participants.md] --- # What is Uniswap **Uniswap** is a suite of onchain protocols for swapping ERC-20 tokens — the largest decentralized exchange (DEX). At its core are **automated market maker (AMM)** contracts: pools that hold liquidity and execute swaps algorithmically, with no order book or intermediary. ## The pieces - **AMM core (v2 / v3 / v4)** — the pool contracts that hold liquidity and price swaps ([how-amms-work](how-amms-work.md), [protocol-versions](protocol-versions.md)). - **Periphery & routers** — the [Universal Router](universal-router.md) and SDKs/API that applications use to route and execute trades safely. - **Permit2** — a shared token-approval system ([permit2](permit2.md)). - **UniswapX** — an intent/auction-based, gasless trading protocol ([uniswapx](uniswapx.md)). - **Hooks (v4)** — custom contract logic attached to pools ([v4-hooks](v4-hooks.md)). ## Participants - **Traders** — swap tokens permissionlessly ([swaps-and-routing](swaps-and-routing.md)). - **Liquidity providers (LPs)** — deposit token pairs to earn [fees](fees.md) ([liquidity-provision](../syntheses/liquidity-provision.md)). - **Developers** — integrate swaps/liquidity via the [SDKs/API](../entities/sdks-and-api.md), or build [hooks](v4-hooks.md). - **Fillers/quoters** — fulfill [UniswapX](uniswapx.md) intents. ## Permissionless & composable Anyone can create a pool, provide liquidity, swap, or build on top — no permission needed. Uniswap is deployed across Ethereum and many L2s/chains ([docs-catalog](../summaries/docs-catalog.md)). This wiki covers the protocol concepts and developer integration; it is not financial advice and live prices/liquidity require onchain/API data. Start with [how-amms-work](how-amms-work.md). --- title: "Uniswap SDKs & API" type: entity tags: [sdk, api, integration, swapping] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-swapping-api-integration-guide.md, raw/llms_txt_doc-lp-api-integration-guide.md, raw/llms_txt_doc-managing-liquidity-via-the-uniswap-api.md] --- # Uniswap SDKs & API Developers integrate Uniswap through the **Uniswap API** (hosted) and the **SDKs** (client libraries) rather than calling contracts directly — they handle routing, [Permit2](../concepts/permit2.md), and calldata generation. ## The Uniswap API - **Swapping API** — quote a trade and get back the transaction to execute. It routes across v2/v3/v4 and [UniswapX](../concepts/uniswapx.md), returns price/impact, and produces the [Universal Router](../concepts/universal-router.md) calldata plus the required Permit2 signature request. The default flow uses **Permit2** ([permit2](../concepts/permit2.md)). - **LP API** — quote and build transactions for **providing/managing liquidity** (mint, increase/decrease, collect fees) across versions, including [concentrated-liquidity](../concepts/concentrated-liquidity.md) positions. - Returns are typed; you sign + submit the returned transaction from the user's wallet. ## The SDKs Client libraries (TypeScript) model the protocol: core entities (Token, Pool, Route, Trade), v3/v4 SDKs for concentrated-liquidity math and position management, the Universal Router SDK for command encoding, and the Permit2 SDK. Use them to compute routes/quotes and encode calldata in your own backend/frontend. ## When to use which - **Hosted API** — fastest integration; offloads routing and stays current across versions/chains. Best for most apps. - **SDKs** — when you need local computation, custom routing, or to avoid an external dependency. ## Integration tips - Always set **slippage tolerance** and **deadline** ([swaps-and-routing](../concepts/swaps-and-routing.md)). - Use the **Permit2** flow rather than infinite router approvals. - Quote immediately before executing (prices move). - End-to-end walkthrough: [integrating-a-swap](../syntheses/integrating-a-swap.md). Exact endpoints/SDK signatures are in the docs ([docs-catalog](../summaries/docs-catalog.md)). --- title: "Activity Log" type: log --- # Activity Log Append-only record of all wiki changes. ## Format Each entry follows this format: ``` ### YYYY-MM-DD HH:MM — [Action Type] - **Source/Trigger**: what initiated the action - **Pages created**: list of new pages - **Pages updated**: list of updated pages - **Notes**: any contradictions flagged, decisions made ``` --- ### 2026-04-08 00:00 — Setup - **Source/Trigger**: Repository initialized - **Pages created**: index.md, log.md, dashboard.md, analytics.md, flashcards.md - **Pages updated**: none - **Notes**: Empty knowledge base ready for first source ingestion ### 2026-06-19 00:00 — Initial curation (medium rung) - **Source/Trigger**: 92 developers.uniswap.org pages (llms.txt) - **Pages created**: 13 concepts, 1 entity (sdks-and-api), 1 summary (docs-catalog), 2 syntheses (integrating-a-swap, liquidity-provision) - **Pages updated**: index.md - **Notes**: Covers AMM concepts, v2/v3/v4, concentrated liquidity, v4 hooks, fees, swaps/routing, flash swaps, oracles, Permit2, Universal Router, UniswapX. v4/hooks/UniswapX newer (post-cutoff-ish) — grounded in sources. Per-contract API reference catalogued not ingested. liquidity-provision confidence:medium (economics synthesis). Category: blockchain. --- title: "Docs Catalog" type: summary tags: [catalog, map, reference] updated: 2026-06-19 confidence: high sources: [raw/llms_txt-llms-txt-index.md, raw/llms_txt_doc-protocols-overview.md] --- # Docs Catalog Map of the Uniswap developer docs (developers.uniswap.org, via llms.txt; ~91 pages mirrored in `raw/` as `llms_txt_doc-.md`). | Area | Raw slugs (selection) | Wiki coverage | |---|---|---| | Concepts | how-uniswap-works, swaps, fees, concentrated-liquidity, range-orders, hooks, glossary, ecosystem-participants | [what-is-uniswap](../concepts/what-is-uniswap.md), [how-amms-work](../concepts/how-amms-work.md), [concentrated-liquidity](../concepts/concentrated-liquidity.md), [v4-hooks](../concepts/v4-hooks.md), [fees](../concepts/fees.md) | | Protocols | protocols-overview, architecture, core-interfaces, periphery-contracts, flash-swaps, oracles, building-an-oracle | [protocol-versions](../concepts/protocol-versions.md), [smart-contracts](../concepts/smart-contracts.md), [flash-swaps](../concepts/flash-swaps.md), [oracles](../concepts/oracles.md) | | Universal Router | universal-router-commands | [universal-router](../concepts/universal-router.md) | | Permit2 | permit2-approval, allowance-transfer, signature-transfer | [permit2](../concepts/permit2.md) | | UniswapX | uniswapx-overview, fillers-overview, request-for-quote-rfq, filling-dutch-v3-auctions, auction-types | [uniswapx](../concepts/uniswapx.md) | | Trade/Swap API | swapping-api-integration-guide, swapping-via-the-uniswap-api, swap-routing, api-swapping-code-examples | [sdks-and-api](../entities/sdks-and-api.md), [swaps-and-routing](../concepts/swaps-and-routing.md) | | Liquidity API | lp-api-integration-guide, managing-liquidity-via-the-uniswap-api, liquidity-overview, lp-calculations | [sdks-and-api](../entities/sdks-and-api.md), [liquidity-provision](../syntheses/liquidity-provision.md) | | Deployments | deployments, supported-chains-tokens | [smart-contracts](../concepts/smart-contracts.md) | ## Not reproduced (look up live) - **Per-contract API reference** (every v2/v3/v4 core & periphery function, events, errors) — large and version-specific; use the docs / interface files. - **SDK API reference** — exact class/method signatures per SDK package. - **Deployment addresses** — per-chain contract addresses (`deployments`); always confirm on-chain. - **Filler/quoter deep integration** — UniswapX filling specifics (priority/Dutch auctions, RFQ wiring). - **v4/hooks are newer** — verify version-specific details against developers.uniswap.org. --- title: "Integrating a Swap (End to End)" type: synthesis tags: [integration, swap, workflow, synthesis] updated: 2026-06-19 confidence: high sources: [raw/llms_txt_doc-swapping-api-integration-guide.md, raw/llms_txt_doc-permit2-approval.md, raw/llms_txt_doc-swap-routing.md] --- # Integrating a Swap (End to End) The full path to add token swapping to an app, tying the concept pages together. ## 1. Quote Call the [Uniswap API/SDK](../entities/sdks-and-api.md) with input token, output token, and amount. It returns the **best route** across v2/v3/v4 (and possibly [UniswapX](../concepts/uniswapx.md)), the expected output, **price impact**, and gas estimate ([swaps-and-routing](../concepts/swaps-and-routing.md)). Quote right before executing — prices move. ## 2. Set protections Choose a **slippage tolerance** (min acceptable output) and a **deadline**. These guard against volatility and front-running; the swap reverts if violated ([how-amms-work](../concepts/how-amms-work.md)). ## 3. Approvals via Permit2 Ensure the wallet has approved the **[Permit2](../concepts/permit2.md)** contract for the input token (one-time per token), then have the user **sign a Permit2 message** authorizing the [Universal Router](../concepts/universal-router.md) to spend a bounded amount with an expiry. This is the default, safer-than-infinite-approval flow. ## 4. Execute Submit the transaction the API returned — Universal Router `execute(commands, inputs)` runs the routed swap (and the Permit2 permit) atomically. It reverts entirely on failure or slippage breach. ## 5. Confirm Watch for the transaction receipt; surface the actual output amount (may differ from quote within slippage). ## Common pitfalls - **Stale quote** → price moved past slippage → revert. Re-quote and retry. - **Missing Permit2 approval** or a malformed/expired signature (nonce/deadline/domain) → the most common API integration error. - **Slippage too tight** on volatile/illiquid pairs → frequent reverts; too loose → MEV/sandwich risk (consider [UniswapX](../concepts/uniswapx.md)). - **Wrong chain / token addresses** → check [deployments](../concepts/smart-contracts.md) and use canonical token lists. - Don't call pools directly — go through the periphery/[API](../entities/sdks-and-api.md) for slippage safety. --- title: "Liquidity Provision & Economics" type: synthesis tags: [liquidity, lp, impermanent-loss, ranges, synthesis] updated: 2026-06-19 confidence: medium sources: [raw/llms_txt_doc-concentrated-liquidity.md, raw/llms_txt_doc-fees.md, raw/llms_txt_doc-liquidity-overview.md, raw/llms_txt_doc-lp-calculations.md] --- # Liquidity Provision & Economics What being a liquidity provider actually entails, across versions. Confidence medium — economics synthesized from the concept docs; not financial advice. ## The LP bargain You deposit token pairs into a pool and earn a pro-rata share of [swap fees](../concepts/fees.md) on volume that trades against your active liquidity — in exchange for taking on **price risk** and **impermanent loss**. ## Impermanent loss (IL) When the pool price diverges from the price at deposit, an AMM LP ends up with **less value than simply holding** the two tokens (the pool sells the appreciating asset and buys the depreciating one). It's "impermanent" because it reverses if price returns — but is realized on withdrawal. Fees must outweigh IL for LPing to be profitable. ## v2 vs concentrated (v3/v4) - **v2 (full range)** — passive: deposit and earn across all prices, fungible LP tokens, lower fee capture per dollar but no rebalancing. - **v3/v4 ([concentrated-liquidity](../concepts/concentrated-liquidity.md))** — pick a range: far higher fee capture *while in range*, but **amplified IL** and **zero earnings out of range**, so it requires **active management** (rebalancing) or a [hook](../concepts/v4-hooks.md)/manager that automates it. Positions are NFTs. ## Choosing a strategy - **Stable/correlated pairs** (USDC/USDT, ETH/stETH) — tight ranges, low [fee tier](../concepts/fees.md); high capital efficiency, low IL. - **Volatile pairs** — wider ranges or higher fee tier to offset IL; expect to rebalance. - **Range orders** — one-sided narrow ranges to approximate limit orders ([concentrated-liquidity](../concepts/concentrated-liquidity.md)). - **Passive** — v2 or a full-range v3 position if you don't want to manage. ## Managing positions Use the [LP API/SDK](../entities/sdks-and-api.md) (or position-manager contracts) to mint, increase/decrease, collect fees, and rebalance. Track in-range time and fee APR vs IL to judge profitability ([lp-calculations](../concepts/concentrated-liquidity.md)). Always model the downside — concentrated LPing can underperform holding in trending markets.