Last active
October 18, 2019 05:38
-
-
Save JayWelsh/dd2a03e4d15f1f3058d6ae974925feaa to your computer and use it in GitHub Desktop.
SimulatedKyber.sol
This file contains 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
pragma solidity 0.5.7; | |
pragma experimental ABIEncoderV2; | |
import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; | |
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; | |
contract SimulatedKyber { | |
using SafeMath for uint256; | |
IERC20 public dai; | |
uint256 public daiPerEth; | |
constructor(IERC20 _dai, uint256 _daiPerEth) public { | |
dai = _dai; | |
daiPerEth = _daiPerEth; // Exchange rate | |
} | |
function exchangeEthToDai() public payable { | |
require( | |
msg.value > 0, | |
"Ether value must be more than zero" | |
); | |
uint256 daiResult = msg.value.mul(daiPerEth); | |
require( | |
dai.balanceOf(address(this)) >= daiResult, | |
"Insufficient DAI liquidity in Simulated Kyber" | |
); | |
dai.transfer(msg.sender, daiResult); | |
} | |
function exchangeDaiToEth(uint256 _daiValue) public { | |
require( | |
_daiValue > 0, | |
"_daiValue must be more than zero" | |
); | |
require( | |
dai.allowance(msg.sender, address(this)) >= _daiValue, | |
"SimulatedKyber DAI allowance is insufficient, please increase this contract's DAI allowance to facilitate the DAI -> ETH exchange" | |
); | |
uint256 ethResult = _daiValue.div(daiPerEth); | |
require( | |
address(this).balance >= ethResult, | |
"Insufficient DAI liquidity in Simulated Kyber" | |
); | |
require( | |
ethResult.mul(daiPerEth) == _daiValue, | |
"Trade would cause precision loss" | |
); | |
dai.transferFrom(msg.sender, address(this), _daiValue); | |
msg.sender.transfer(ethResult); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment