kyber

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的数量)
    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)