pragma solidity 0.6.2;
// ETH/USDT
contract Kyber{
using SafeMath for uint256;
ERC20 erc;
mapping(address => Amount) public deposit; // 每個用戶存儲金額
string public prefix = "\x19Ethereum Signed Message:\n32";
struct Amount{
uint256 ethAmount;
uint256 usdtAmount;
}
constructor(address _ercContractAddress) public{
erc = ERC20(_ercContractAddress);
}
// 交易 (_token:想要買賣ETH的數(shù)量)
function exchange(bytes memory _msg,bytes32 _r,bytes32 _s,uint8 _v) public payable{
address from = ecrecover(keccak256(abi.encodePacked(prefix,keccak256(abi.encodePacked(_msg)))),_v,_r,_s);
(uint256 _ethAmount,uint256 _usdtAmount,uint256 _status,uint256 _endTime) = _msgInfo(_msg);
require(now > _endTime,"The time has expired");
if(_status == 1){
_sellEth(msg.value,_ethAmount,_usdtAmount,from);
}else{
_buyEth(msg.value,_ethAmount,_usdtAmount,from);
}
}
function _sellEth(uint256 _sellEthAmount,uint256 _ethAmount,uint256 _usdtAmount,address _from) private{
require(_sellEthAmount == _ethAmount,"usdt balance is error");
Amount memory amount = deposit[_from];
amount.ethAmount = amount.ethAmount.add(_sellEthAmount);
amount.usdtAmount = amount.usdtAmount.sub(_usdtAmount);
deposit[_from] = amount;
bool success = erc.transfer(msg.sender,_usdtAmount);
require(success,"transfer usdt fail");
}
function _buyEth(uint256 _buyEthAmount,uint256 _ethAmount,uint256 _usdtAmount,address _from) private {
require(_buyEthAmount == _ethAmount,"eth balance is error");
Amount memory amount = deposit[_from];
amount.ethAmount = amount.ethAmount.sub(_buyEthAmount);
amount.usdtAmount = amount.usdtAmount.add(_usdtAmount);
deposit[_from] = amount;
msg.sender.transfer(_buyEthAmount);
}
function _msgInfo(bytes memory _msg) public pure returns (uint256 _ethAmount,uint256 _usdtAmount,uint256 _status,uint256 _endTime) {
assembly {
_ethAmount := mload(add(_msg,32))
_usdtAmount := mload(add(_msg,64))
_status := mload(add(_msg,96))
_endTime := mload(add(_msg,128))
}
}
}
interface ERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns(bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns(bool);
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
kyber
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 今天感恩節(jié)哎,感謝一直在我身邊的親朋好友。感恩相遇!感恩不離不棄。 中午開了第一次的黨會,身份的轉(zhuǎn)變要...