solidityethereumdefiadvanced

Simple AMM Swap (Solidity)

A minimal constant-product AMM (x*y=k) swap function, like Uniswap V2.

All snippets

Code

solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract SimpleAMM {
    IERC20 public tokenA;
    IERC20 public tokenB;
    uint256 public reserveA;
    uint256 public reserveB;
    uint256 public fee = 3; // 0.3%

    constructor(address _a, address _b) {
        tokenA = IERC20(_a);
        tokenB = IERC20(_b);
    }

    function swapAforB(uint256 amountIn) external {
        tokenA.transferFrom(msg.sender, address(this), amountIn);
        uint256 amountInWithFee = (amountIn * (1000 - fee)) / 1000;
        uint256 amountOut = (amountInWithFee * reserveB) / (reserveA + amountInWithFee);
        reserveA += amountIn;
        reserveB -= amountOut;
        tokenB.transfer(msg.sender, amountOut);
    }

    function addLiquidity(uint256 amountA, uint256 amountB) external {
        tokenA.transferFrom(msg.sender, address(this), amountA);
        tokenB.transferFrom(msg.sender, address(this), amountB);
        reserveA += amountA;
        reserveB += amountB;
    }
}

Explanation

The constant product formula x*y=k ensures the pool's reserves always maintain the invariant after fees. The swap calculates output amount as (amountIn * reserveOut) / (reserveIn + amountIn), adjusting for a 0.3% fee.

ammswapdefiuniswap