0
0
Blockchain / Solidityprogramming~5 mins

Automated Market Makers (AMM) in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Automated Market Makers (AMMs) help people trade cryptocurrencies without needing a middleman. They use math formulas to set prices and let anyone buy or sell tokens easily.

You want to trade tokens on a decentralized exchange without waiting for a buyer or seller.
You want to provide liquidity to earn fees by adding your tokens to a pool.
You want to understand how prices change automatically based on supply and demand.
You want to build or use a decentralized finance (DeFi) app that needs token swaps.
You want to learn how blockchain apps handle trading without traditional order books.
Syntax
Blockchain / Solidity
function getAmountOut(amountIn, reserveIn, reserveOut) {
  const amountInWithFee = amountIn * 0.997;
  const numerator = amountInWithFee * reserveOut;
  const denominator = reserveIn * 1 + amountInWithFee;
  return numerator / denominator;
}

This function calculates how many tokens you get when you swap.

It uses a simple formula from the constant product model: reserveIn * reserveOut = constant.

Examples
Swapping 100 tokens when both reserves are 1000 returns about 90.73 tokens out.
Blockchain / Solidity
const amountOut = getAmountOut(100, 1000, 1000);
console.log(amountOut);
Swapping 50 tokens with different reserves shows how output changes with pool size.
Blockchain / Solidity
const amountOut = getAmountOut(50, 500, 1500);
console.log(amountOut);
Sample Program

This program shows how many TokenB you get when swapping 100 TokenA using an AMM formula.

Blockchain / Solidity
function getAmountOut(amountIn, reserveIn, reserveOut) {
  const amountInWithFee = amountIn * 0.997;
  const numerator = amountInWithFee * reserveOut;
  const denominator = reserveIn * 1 + amountInWithFee;
  return numerator / denominator;
}

const reserveTokenA = 1000;
const reserveTokenB = 1000;
const amountInTokenA = 100;

const amountOutTokenB = getAmountOut(amountInTokenA, reserveTokenA, reserveTokenB);
console.log(`Swapping ${amountInTokenA} TokenA gives you ${amountOutTokenB.toFixed(2)} TokenB`);
OutputSuccess
Important Notes

AMMs use a fee (like 0.3%) to reward liquidity providers.

The constant product formula keeps the pool balanced and prices fair.

Prices change automatically based on how much you swap and the pool reserves.

Summary

AMMs let you trade tokens without a middleman using math formulas.

They use reserves and a constant product formula to set prices.

You can calculate how many tokens you get from a swap with a simple function.