0Pricing
Web3 & DApp Development Fundamentals · Урок

Создание простого обмена

Механика AMM

«Создание простого обмена» — бесплатный урок Web3 & DApp Development Fundamentals на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Web3 & DApp Development Fundamentals, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Goal: A Minimal AMM Swap

In this lesson we sketch a minimal constant-product swap contract in Solidity to see how the formula becomes code.

We keep it simple to focus on mechanics, not production safety.

Pool State

Our contract tracks two token reserves and the LP token supply. These three values fully describe the pool.

contract SimpleSwap {
    IERC20 public tokenA;
    IERC20 public tokenB;
    uint public reserveA;
    uint public reserveB;
    uint public totalShares;
}

Adding Liquidity

When a provider adds liquidity, we pull both tokens, update reserves, and mint shares proportional to the deposit.

function addLiquidity(uint amtA, uint amtB) external {
    tokenA.transferFrom(msg.sender, address(this), amtA);
    tokenB.transferFrom(msg.sender, address(this), amtB);
    reserveA += amtA;
    reserveB += amtB;
    // mint shares to msg.sender
}

The Swap Function Signature

A swap takes an input amount of one token and returns the maximum possible output of the other, governed by x * y = k.

function swapAforB(uint amountAIn)
    external
    returns (uint amountBOut)
{
    // ... apply constant product
}

Applying the Fee

Before computing output, we deduct a 0.30% fee by scaling the input to 99.7% of its value.

uint amountInWithFee = amountAIn * 997 / 1000;
// 0.30% of the input stays in the pool

Computing the Output Amount

Using constant product, the output is derived so the product of new reserves still equals k.

amountBOut =
    (reserveB * amountInWithFee) /
    (reserveA + amountInWithFee);

Updating Reserves

After computing the output we update both reserves and transfer the output token to the trader.

reserveA += amountAIn;
reserveB -= amountBOut;
tokenB.transfer(msg.sender, amountBOut);

Putting the Swap Together

Here is the full swap path: pull input, apply fee, compute output, update reserves, send output.

function swapAforB(uint amountAIn) external returns (uint out) {
    tokenA.transferFrom(msg.sender, address(this), amountAIn);
    uint inWithFee = amountAIn * 997 / 1000;
    out = (reserveB * inWithFee) / (reserveA + inWithFee);
    reserveA += amountAIn;
    reserveB -= out;
    tokenB.transfer(msg.sender, out);
}

Protecting Against Slippage

Real swaps accept a minAmountOut parameter and revert if the output is worse than expected.

This shields traders from price changes (or front-running) between submitting and executing.

require(out >= minAmountOut, "slippage");

What We Left Out

A production AMM adds much more:

  • Reentrancy guards
  • Fee accounting for LPs
  • Flash-loan and price-manipulation defenses
  • Events for indexers

Never deploy a teaching contract to mainnet.

Putting It Together

A swap is just the constant-product formula expressed in code: take input minus fee, compute the output that keeps k, update reserves, and transfer.

Everything else (LP accounting, safety) wraps around this core idea.

Quick Check

Test your swap implementation understanding.

Recap: Building a Simple Swap

You learned that:

  • A pool tracks reserves and shares
  • The swap applies a fee then the constant product formula
  • Output = reserveB * inWithFee / (reserveA + inWithFee)
  • minAmountOut guards against slippage
  • Production needs guards, events, and audits

Course complete! Next course: DAO Development.

Часто задаваемые вопросы

Урок «Создание простого обмена» бесплатный?

Да — полный текст урока «Создание простого обмена» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Web3 & DApp Development Fundamentals, подпишись на CoddyKit PRO. Курс Web3 & DApp Development Fundamentals содержит 4 уроков всего.

Чему я научусь в уроке «Создание простого обмена»?

Механика AMM Ты практикуешь Web3 & DApp Development Fundamentals с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Web3 & DApp Development Fundamentals?

Предыдущий опыт не требуется. Web3 & DApp Development Fundamentals на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Создание простого обмена»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Web3 & DApp Development Fundamentals?

Да. Каждый урок Web3 & DApp Development Fundamentals включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Обзор DeFi
  2. Автоматические маркетмейкеры
  3. Пулы ликвидности
  4. Создание простого обмена
← Назад к Web3 & DApp Development Fundamentals