Skip to content

Instantly share code, notes, and snippets.

@rollodex
Forked from JayWelsh/SimulatedKyber.sol
Created October 18, 2019 05:38
Show Gist options
  • Save rollodex/a3113b6a977198253b974f51b9bf8ce6 to your computer and use it in GitHub Desktop.
Save rollodex/a3113b6a977198253b974f51b9bf8ce6 to your computer and use it in GitHub Desktop.
SimulatedKyber.sol
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