0Pricing
Web3 & DApp Development Fundamentals · Lezione

Costruzione di uno swap semplice

Meccanismi degli AMM

Costruzione di uno swap semplice è una lezione Web3 & DApp Development Fundamentals gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Web3 & DApp Development Fundamentals, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Web3 & DApp Development Fundamentals include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Domande Frequenti

La lezione «Costruzione di uno swap semplice» è gratuita?

Sì — il testo completo di «Costruzione di uno swap semplice» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Web3 & DApp Development Fundamentals, passa a CoddyKit PRO. Il corso Web3 & DApp Development Fundamentals include 4 lezioni in totale.

Cosa imparerò in «Costruzione di uno swap semplice»?

Meccanismi degli AMM Eserciti Web3 & DApp Development Fundamentals con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Web3 & DApp Development Fundamentals?

Non è richiesta alcuna esperienza precedente. Web3 & DApp Development Fundamentals su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Costruzione di uno swap semplice»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Web3 & DApp Development Fundamentals?

Sì. Ogni lezione Web3 & DApp Development Fundamentals include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Panoramica della DeFi
  2. Automated Market Maker
  3. Pool di liquidità
  4. Costruzione di uno swap semplice
← Torna a Web3 & DApp Development Fundamentals