pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract LiquidityPool { mapping(address => uint256) public reserves; // Event emitted when a swap occurs event Swap( address indexed sender, address indexed tokenIn, address indexed tokenOut, uint256 amountIn, uint256 amountOut ); // Function to add liquidity to the pool function addLiquidity(address _token, uint256 _amount) public { require(_amount > 0, "Amount must be greater than 0"); // Transfer tokens from the user to the contract IERC20(_token).transferFrom(msg.sender, address(this), _amount); // Update reserves reserves[_token] += _amount; } // Function to swap tokens function swap( address _tokenIn, address _tokenOut, uint256 _amountIn ) public returns (uint256 amountOut) { require( reserves[_tokenIn] > 0 && reserves[_tokenOut] > 0, "Insufficient liquidity" ); require(_amountIn > 0, "Amount must be greater than 0"); // Transfer input tokens from the user to the contract IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn); // Calculate output amount using a simple constant product formula // (This is a basic example and can be replaced with more sophisticated AMM formulas) amountOut = (_amountIn * reserves[_tokenOut]) / reserves[_tokenIn]; // Update reserves reserves[_tokenIn] += _amountIn; reserves[_tokenOut] -= amountOut; // Transfer output tokens to the user IERC20(_tokenOut).transfer(msg.sender, amountOut); // Emit the Swap event emit Swap(msg.sender, _tokenIn, _tokenOut, _amountIn, amountOut); } }
0.4.18