DeFi Basics for Devs — Web3

DeFi is financial services running on smart contracts with no central middleman. An AMM sets the price from the ratio of a liquidity pool's contents, with no…

In front of Raka's Shirt Shop there's a swap box. It holds PTS and play money, and anyone may swap without a cashier. No person sets the price; a rule written on the box does: the more PTS in the box, the cheaper PTS gets. A box like this is the heart of DeFi (Decentralised Finance): financial services (swapping tokens, lending and borrowing, storing value) that run on smart contracts, with no central middleman holding the money or matching orders. As a developer you need to understand that rule to call it safely, and to know when a number from that box must not be trusted.

A toy pool on the local chain

Every number in this lesson comes from the local Hardhat chain and toy tokens: MILL (Test Mill, an OpenZeppelin ERC-20, 1 MILL counted as $0.001, a tenth of a cent) and RakaPoints. Not real tokens, not investment advice. If a pool like this is ever used with real tokens, first read the note on crypto rules in the Blockchain Fundamentals lesson (as of November 2026, not legal advice). Raka fills the pool with 10,000 PTS and 500,000 MILL, matching PTS's value in the shop (100 PTS = $5).

AMM: a price from the formula x · y = k

An AMM (Automated Market Maker) is an algorithm that sets a token's price from the ratio of what's in a liquidity pool, with no order book. The simplest uses a constant product: x · y = k. x = the PTS reserve, y = the MILL reserve, and k must not drop after a swap. The spot price = y / x = 500,000 / 10,000 = 50 MILL per PTS. Here is the heart of the contract (the same formula Uniswap v2 uses, 0.3% fee):

function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut) public pure returns (uint256) {
    uint256 inWithFee = amountIn * 997;                                 // the 0.3% fee stays in the pool
    return (inWithFee * reserveOut) / (reserveIn * 1000 + inWithFee);
}

function sellPoints(uint256 amountIn, uint256 minOut) external returns (uint256 out) {
    out = getAmountOut(amountIn, reservePoints, reserveMill);
    if (out < minOut) revert Slippage(out, minOut);                     // slippage protection
    reservePoints += amountIn;
    reserveMill -= out;
    points.safeTransferFrom(msg.sender, address(this), amountIn);
    mill.safeTransfer(msg.sender, out);
}

Dinda's first swap

Before you run the code below, guess: the pool holds 10,000 PTS and 500,000 MILL, so 1 PTS = 50 MILL. Dinda sells 100 PTS. How much MILL does she get: exactly 5,000, a little under 5,000, or more than 5,000?

await pool.read.getAmountOut([parseUnits('100', 18), parseUnits('10000', 18), parseUnits('500000', 18)])
// 4935790171985306494252n
await pool.write.sellPoints([parseUnits('100', 18), parseUnits('4900', 18)], { account: dinda.account })
// receipt: status 'success', gasUsed 84917n
await pool.read.reservePoints() // 10100000000000000000000n
await pool.read.reserveMill()  // 495064209828014693505748n

Dinda receives 4,935.79 MILL, a little under 5,000. The 64.21 MILL gap has two causes: the 0.3% fee (without it she'd get 4,950.50) and price impact: every PTS that goes in makes the next one cheaper. k actually rises from 5,000,000,000 to about 5,000,148,519, because the fee stays in the pool. Sell 2,000 PTS at once? You get 83,124.90 MILL, not 100,000: almost 17% lost because the pool is too small for a trade that size.

Slippage and minOut

Between Dinda signing and her transaction landing in a block, someone else can swap first. Yoga sells 2,000 PTS first, and Dinda's 100 PTS are now worth only 3,434.99 MILL. Because Dinda set minOut 1% under the estimate (4,886.43 MILL), the contract refuses:

The contract function "sellPoints" reverted.

Error: Slippage(uint256 out, uint256 minOut)
               (3434998214055883422976, 4886432270265453429309)

Without minOut (or with minOut = 0), Dinda would quietly lose 30%. Always compute minOut from a freshly read estimate, and add a time limit (deadline) in a real app.

Liquidity providers and impermanent loss

The pool's contents come from liquidity providers (LPs): Raka deposits 10,000 PTS + 500,000 MILL (worth 1,000,000 MILL) and earns the fee from every swap. The risk is impermanent loss. If PTS's outside price rises to 100 MILL, arbitrage buys PTS from the pool until the pool's price is 100 too. Ignoring fees, the pool then holds √(k/100) = 7,071.07 PTS and √(k·100) = 707,106.78 MILL:

Holdings Value at price 100
Left in the pool 7,071.07 PTS + 707,106.78 MILL 1,414,213.56 MILL
Just held (HODL) 10,000 PTS + 500,000 MILL 1,500,000 MILL

The gap is 5.72%: the formula 2√r / (1 + r) - 1 with r = 2. A price ×4 or ×¼ gives 20%. "Impermanent" because if the price returns to 50 the gap disappears; if the LP withdraws while the price has moved, the loss becomes real. Fees have to beat it for the LP to come out ahead.

Oracles: don't trust the pool's price

A contract can't see prices outside the blockchain. An oracle brings that data on-chain. The easiest temptation: use the pool's spot price (reserveMill / reservePoints). That's dangerous. On the local chain, one transaction buying PTS with 500,000 MILL moves the price from 50 to 199.70 MILL per PTS. A lending contract that values collateral at that price would count 100 PTS as almost 20,000 MILL, while its fair value is 5,000. With a flash loan (borrowed and repaid inside one transaction) that much capital is available for a moment, so this weakness is real. The defences:

Lending and liquidation

A lending protocol takes collateral and lends another asset up to a limit. Say Dinda pledges 1,000 PTS (50,000 MILL) and borrows 25,000 MILL. If PTS falls to 30 MILL, her collateral is worth only 30,000; with a liquidation threshold of 80% (24,000 MILL) her debt is past the limit, and anyone may liquidate her: repay that debt and take her collateral plus a bonus. That's why the oracle's price must be right: a wrong price can liquidate someone who was actually safe.

⚠️ DeFi numbers you shouldn't take at face value

TL;DR: DeFi is financial services running on smart contracts with no central middleman. An AMM sets the price from the ratio of a liquidity pool's contents, with no order book: x · y = k, spot price y / x, a 0.3% fee (amountIn * 997). In the toy pool of 10,000 PTS / 500,000 MILL, selling 100 PTS gives 4,935.79 MILL (fee + price impact), selling 2,000 gives 83,124.90 (almost 17% worse). minOut makes a swap revert with Slippage(out, minOut) when the price moves. LPs earn fees but carry impermanent loss (5.72% when the price doubles). A pool's spot price can be moved within one transaction (50 becomes 199.70), so use an oracle or a TWAP. Lending needs collateral and can be liquidated. Everything here is toy tokens on a local chain: real DeFi is risky, and this is not investment advice.

⚡ DeFi: finance with no middleman

Meaning: DeFi is financial services (swapping tokens, lending and borrowing, storing value) that run on smart contracts, with no central middleman holding the money or matching orders.

⚡ AMM: a price from x · y = k

Write:

uint256 inWithFee = amountIn * 997;                                 // the 0.3% fee stays in the pool
return (inWithFee * reserveOut) / (reserveIn * 1000 + inWithFee);
Guess first: the pool holds 10,000 PTS and 500,000 MILL, so 1 PTS = 50 MILL. Dinda sells 100 PTS. Does she get exactly 5,000 MILL?

A little under: 4,935.79 MILL. There's the 0.3% fee, and every PTS that goes in makes the next one cheaper (price impact).

Meaning: The price comes from the ratio of what's in the pool, with no order book. The bigger amountIn, the further the price moves.

⚡ minOut protects against slippage

Meaning: If Yoga sells first and Dinda's result drops under minOut, the contract reverts with Slippage(out, minOut). Without minOut, Dinda would quietly lose 30%.

⚡ Don't trust the pool's price

Meaning: One transaction can move the pool's spot price from 50 to 199.70 MILL. Use an oracle or a TWAP, not the pool's current reserves.

What you will learn