-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleDEX.sol
More file actions
31 lines (26 loc) · 1.13 KB
/
Copy pathSimpleDEX.sol
File metadata and controls
31 lines (26 loc) · 1.13 KB
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
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20 {
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
contract SimpleDEX {
address public tokenA;
address public tokenB;
uint256 public exchangeRate; // tokenA -> tokenB
constructor(address _tokenA, address _tokenB, uint256 _exchangeRate) {
tokenA = _tokenA;
tokenB = _tokenB;
exchangeRate = _exchangeRate;
}
function swapAtoB(uint256 amountA) public {
uint256 amountB = amountA * exchangeRate;
require(IERC20(tokenA).transferFrom(msg.sender, address(this), amountA), "Token A transfer failed");
require(IERC20(tokenB).transfer(msg.sender, amountB), "Token B transfer failed");
}
function swapBtoA(uint256 amountB) public {
uint256 amountA = amountB / exchangeRate;
require(IERC20(tokenB).transferFrom(msg.sender, address(this), amountB), "Token B transfer failed");
require(IERC20(tokenA).transfer(msg.sender, amountA), "Token A transfer failed");
}
}