A .NET Dinosaur in Web3. Day 18 - Automated Market Maker
🏦 Day 6 of 7: Building a Mini Uniswap in 80 Lines of Solidity Imagine a vending machine. It has 1,000 coffee beans and 1,000 coins. No menu, no cashier — just one iron rule: the product of the two numbers inside must never decrease. That's it! This is how Uniswap works — and this is what I built on Day 6, coming from .NET. Here's how, why it's elegant, and where you can step on a rake. Why an Order Book Doesn't Work on a Blockchain Traditional exchanges — Binance, NYSE, any CEX — run on an order book . Market makers post bids and asks. A matching engine pairs them. Millions of updates per second, all in a centralised database. In a blockchain, this is impossible. Transactions take 12 seconds. Every state change costs gas. Storing millions of constantly changing orders would eat all the profit before a single trade completes. Uniswap's solution: replace the order book with a liquidity pool — a smart contract holding two tokens — and replace the matching engine with pure math. Just a formula — below. x · y = k — The Formula That Broke Finance The Constant Product Invariant : x · y = k Where x is the reserve of Token0, y is the reserve of Token1, and k is a constant that must never decrease during swaps. When a trader sells Token0 into the pool, x increases. To keep k constant, y must decrease — the contract sends out Token1. The price is determined automatically by the ratio of reserves. Live example with numbers: Pool: 1,000 Token0, 1,000 Token1. k = 1,000,000. Trader sells 100 Token0: amountOut = (reserveOut × amountIn) / (reserveIn + amountIn) amountOut = (1000 × 100) / (1000 + 100) amountOut = 100,000 / 1,100 amountOut ≈ 90.9 Token1 The trader gets ~90.9, not 100. That gap is slippage — and it's not a bug. It's the formula protecting the pool. The more you buy relative to pool size, the worse your price gets. Naturally. Mathematically. After the swap: pool has 1,100 Token0 and ~909.1 Token1. k ≈ 1,000,000. Invariant holds. The Contract: SimpleAMM Three functions.