Last active
September 27, 2022 06:09
-
-
Save casweeney/7418fe4d871f89f4cbc4c412773111ab to your computer and use it in GitHub Desktop.
Smart contract that implements swapping different tokens using order book.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // SPDX-License-Identifier: MIT | |
| pragma solidity ^0.8.4; | |
| import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol"; | |
| contract Swap { | |
| struct Order { | |
| address orderOwner; | |
| address fromToken; | |
| address toToken; | |
| uint256 amountIn; | |
| uint256 amountOut; | |
| bool orderOpened; | |
| } | |
| uint256 ID = 1; | |
| mapping(uint => Order) orders; | |
| function createOrder(address _fromToken, address _toToken, uint256 _amountIn, uint256 _amountOut) external { | |
| require(IERC20(_fromToken).balanceOf(msg.sender) >= _amountIn, "insufficient funds"); | |
| require(IERC20(_fromToken).transferFrom(msg.sender, address(this), _amountIn), "transfer failed"); | |
| Order storage _order = orders[ID]; | |
| _order.orderOwner = msg.sender; | |
| _order.fromToken = _fromToken; | |
| _order.toToken = _toToken; | |
| _order.amountIn = _amountIn; | |
| _order.amountOut = _amountOut; | |
| _order.orderOpened = true; | |
| ID++; | |
| } | |
| function executeOrder(uint256 _ID) external { | |
| Order storage _order = orders[_ID]; | |
| assert(_order.orderOpened); | |
| require(IERC20(_order.toToken).balanceOf(msg.sender) > _order.amountOut, "insufficient funds"); | |
| require(IERC20(_order.toToken).transferFrom(msg.sender, address(this), _order.amountOut), "transfer failed"); | |
| _order.orderOpened = false; | |
| IERC20(_order.toToken).transfer(_order.orderOwner, _order.amountOut); | |
| IERC20(_order.fromToken).transfer(msg.sender, _order.amountIn); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment