Construção de um swap simples
Mecânica de AMM
Construção de um swap simples é uma aula grátis de Web3 & DApp Development Fundamentals no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Web3 & DApp Development Fundamentals, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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 poolComputing 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.
Perguntas Frequentes
A aula “Construção de um swap simples” é grátis?
Sim — o texto completo de “Construção de um swap simples” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Web3 & DApp Development Fundamentals, atualize para CoddyKit PRO. O curso de Web3 & DApp Development Fundamentals inclui 4 aulas no total.
O que vou aprender em “Construção de um swap simples”?
Mecânica de AMM Você pratica Web3 & DApp Development Fundamentals com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Web3 & DApp Development Fundamentals?
Nenhuma experiência prévia é necessária. Web3 & DApp Development Fundamentals no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Construção de um swap simples”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Web3 & DApp Development Fundamentals?
Sim. Cada aula de Web3 & DApp Development Fundamentals inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Visão geral de DeFi
- Formadores de mercado automatizados
- Pools de liquidez
- Construção de um swap simples