07.uniswap quick start demo
2024-04-14 14:41:06 # 03.Uniswap

uniswap quick start demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract Dex {

using SafeERC20 for IERC20;
address public apple;
address public orange;

constructor(address _apple, address _orange) {
apple = _apple;
orange = _orange;
}

function swap(address sell, address buy, uint amountSell) public {

require((sell == apple && buy == orange) || (sell == orange && buy == apple), "Invalid tokens");
require(IERC20(sell).balanceOf(msg.sender) >= amountSell, "Not enough to swap");
uint buyAmount = getAmountWithBuy(sell, buy, amountSell);
IERC20(sell).safeTransferFrom(msg.sender, address(this), amountSell);
IERC20(buy).safeTransfer(msg.sender, buyAmount);

}

function addLiquidity(address [] memory tokens, uint [] memory amounts) public{
IERC20(tokens[0]).safeTransferFrom(msg.sender, address(this), amounts[0]);
IERC20(tokens[1]).safeTransferFrom(msg.sender, address(this), amounts[1]);
}

function getAmountWithBuy(address sell, address buy, uint sellAmount) public view returns(uint){
uint sellReserveAmount = IERC20(sell).balanceOf(address(this));
uint buyReserveAmount = IERC20(buy).balanceOf(address(this));
// 根据公式写的
return (sellAmount * buyReserveAmount) / (sellReserveAmount + sellAmount);
}

function getLiquidity() public view returns(uint appleAmount, uint orangeAmount){
appleAmount = IERC20(apple).balanceOf(address(this));
orangeAmount = IERC20(orange).balanceOf(address(this));
}

function getK() public view returns (uint) {
(uint appleAmount, uint orangeAmount) = getLiquidity();
return appleAmount * orangeAmount;
}

function balanceOf(address token, address account) public view returns (uint){
return IERC20(token).balanceOf(account);
}

}


contract SwapToken is ERC20 {
constructor(string memory name, string memory symbol, uint initialSupply) ERC20(name, symbol) {
_mint(msg.sender, initialSupply * 10 ** decimals());
}

function mint(address to, uint256 amount) public {
_mint(to, amount);
}
}
Prev
2024-04-14 14:41:06 # 03.Uniswap
Next