Skip to content

Instantly share code, notes, and snippets.

@shreyakqss
Created May 12, 2022 08:01
Show Gist options
  • Save shreyakqss/a75f0f9bcf19b562c3d7e43855d42ca5 to your computer and use it in GitHub Desktop.
Save shreyakqss/a75f0f9bcf19b562c3d7e43855d42ca5 to your computer and use it in GitHub Desktop.
Simple DEX smart contract for swapping ETH and an ERC20 token
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./TrainingToken.sol";
contract DEX {
TrainingToken token;
address public tokenAddress;
event TokensBought(uint256 amount,uint256 etherAmount,address _buyer);
event TokensSold(uint256 amount,uint256 etherAmount,address _seller);
constructor(address _token) payable{
require(msg.value > 0 , "You have to at least deposit something to start a DEX");
tokenAddress = _token;
token = TrainingToken(address(tokenAddress));
}
//ETH required to buy all tokens in Pool. price is calculated based on constant product formula AMM
function etherPrice() public view returns (uint256) {
return token.balanceOf(address(this))/address(this).balance;
}
function buy() payable public {
uint256 amountTobuy = msg.value;
uint256 price = etherPrice();
uint256 dexBalance = token.balanceOf(address(this));
require(amountTobuy > 0, "You need to send some Ether");
require(amountTobuy*price <= dexBalance, "Not enough tokens in the reserve");
token.transfer(msg.sender, amountTobuy*price);
emit TokensBought(amountTobuy*price,amountTobuy,msg.sender);
}
function sell(uint256 amount) public {
require(amount > 0, "You need to sell at least some tokens");
uint256 approvedAmt = token.allowance(msg.sender, address(this));
require(approvedAmt >= amount, "Check the token allowance");
uint256 price = etherPrice();
token.transferFrom(msg.sender, payable(address(this)), amount);
payable(msg.sender).transfer(amount/price);
emit TokensSold(amount/price,amount,msg.sender);
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment