contract ElasticUSDTPool is Ownable, ReentrancyGuard {
    using SafeMath for uint256;
    using SafeERC20 for IERC20;
    using SafeERC20 for IESCToken;

    /* ========== STATE VARIABLES ========== */
    address public feeTo;
    uint8 public feePercent; //max 255 = 25.5% artificial clamp

    IESCToken public rewardsToken;
    IERC20 public stakingToken;
    uint256 public periodFinish = 0;
    uint256 public rewardRate = 0;
    uint256 public rewardsDuration = 60 days;
    uint256 public lastUpdateTime;
    uint256 public rewardPerTokenStored;

    mapping(address => uint256) public userRewardPerTokenPaid;
    mapping(address => uint256) public rewards;

    uint256 private _totalSupply;
    mapping(address => uint256) private _balances;

    function initialize(
        address rewardsTokenAddress,
        address stakingTokenAddress
    ) public onlyOwner {
        require(
            rewardsTokenAddress != address(0x0),
            "invalid rewardsTokenAddress"
        );
        require(
            stakingTokenAddress != address(0x0),
            "invalid stakingTokenAddress"
        );
        require(
            address(rewardsToken) == address(0x0) ||
                address(stakingToken) == address(0x0),
            "initialized"
        );
        rewardsToken = IESCToken(rewardsTokenAddress);
        stakingToken = IERC20(stakingTokenAddress);
    }

    /* ========== VIEWS ========== */

    function totalSupply() external view returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) external view returns (uint256) {
        return _balances[account];
    }

    function lastTimeRewardApplicable() public view returns (uint256) {
        return Math.min(block.timestamp, periodFinish);
    }

    function rewardPerToken() public view returns (uint256) {
        if (_totalSupply == 0) {
            return rewardPerTokenStored;
        }
        return
            rewardPerTokenStored.add(
                lastTimeRewardApplicable()
                    .sub(lastUpdateTime)
                    .mul(rewardRate)
                    .mul(1e18)
                    .div(_totalSupply)
            );
    }

    function earned(address account) public view returns (uint256) {
        return
            _balances[account]
                .mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
                .div(1e18)
                .add(rewards[account]);
    }

    function getRewardForDuration() external view returns (uint256) {
        return rewardRate.mul(rewardsDuration);
    }

    /* ========== MUTATIVE FUNCTIONS ========== */
    function stake(uint256 amount)
        external
        nonReentrant
        updateReward(msg.sender)
    {
        require(amount > 0, "Cannot stake 0");
        if (
            feePercent > 0 &&
            feeTo != address(0x0) &&
            msg.sender != address(feeTo)
        ) {
            uint256 feeAmount = amount.mul(feePercent).div(1000);
            uint256 finalAmount = (amount - feeAmount);
            _totalSupply = _totalSupply.add(finalAmount);
            _balances[msg.sender] = _balances[msg.sender].add(finalAmount);
            stakingToken.safeTransferFrom(msg.sender, address(this), amount);
            stakingToken.safeTransfer(feeTo, feeAmount);
        } else {
            _totalSupply = _totalSupply.add(amount);
            _balances[msg.sender] = _balances[msg.sender].add(amount);
            stakingToken.safeTransferFrom(msg.sender, address(this), amount);
        }
        emit Staked(msg.sender, amount);
    }

    function withdraw(uint256 amount)
        public
        nonReentrant
        updateReward(msg.sender)
    {
        require(amount > 0, "Cannot withdraw 0");
        _totalSupply = _totalSupply.sub(amount);
        _balances[msg.sender] = _balances[msg.sender].sub(amount);
        stakingToken.safeTransfer(msg.sender, amount);
        emit Withdrawn(msg.sender, amount);
    }

    function getReward() public nonReentrant updateReward(msg.sender) {
        uint256 reward = rewards[msg.sender];
        if (reward > 0) {
            rewards[msg.sender] = 0;
            uint256 perShareAmount = rewardsToken.perShareAmount();
            rewardsToken.safeTransfer(msg.sender, reward.mul(perShareAmount));
            emit RewardPaid(msg.sender, reward, perShareAmount);
        }
    }

    function exit() external {
        withdraw(_balances[msg.sender]);
        getReward();
    }

    /* ========== RESTRICTED FUNCTIONS ========== */

    function setFeePercent(uint8 _feePercent) public onlyOwner {
        feePercent = _feePercent;
    }

    function setFeeTo(address _feeTo) public onlyOwner {
        feeTo = _feeTo;
    }

    function clearToken(address tokenAddress)
        public
        onlyOwner
        canClearToken(tokenAddress)
    {
        address _receiver = msg.sender;
        IERC20 _erc20 = IERC20(tokenAddress);
        uint256 _balance = _erc20.balanceOf(address(this));
        _erc20.safeTransfer(_receiver, _balance);
    }

    function notifyRewardAmount(uint256 reward)
        external
        onlyOwner
        updateReward(address(0))
    {
        if (block.timestamp >= periodFinish) {
            rewardRate = reward.div(rewardsDuration);
        } else {
            uint256 remaining = periodFinish.sub(block.timestamp);
            uint256 leftover = remaining.mul(rewardRate);
            rewardRate = reward.add(leftover).div(rewardsDuration);
        }

        // Ensure the provided reward amount is not more than the balance in the contract.
        // This keeps the reward rate in the right range, preventing overflows due to
        // very high values of rewardRate in the earned and rewardsPerToken functions;
        // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
        uint256 balance = rewardsToken.balanceOf(address(this));
        uint256 perShareAmount = rewardsToken.perShareAmount();
        require(
            rewardRate <= balance.div(rewardsDuration).div(perShareAmount),
            "Provided reward too high"
        );

        lastUpdateTime = block.timestamp;
        periodFinish = block.timestamp.add(rewardsDuration);
        emit RewardAdded(reward);
    }

    /* ========== MODIFIERS ========== */
    modifier canClearToken(address tokenAddress) {
        require(
            tokenAddress != address(rewardsToken),
            "Can't clear rewards Token"
        );
        require(
            tokenAddress != address(stakingToken),
            "Can't clear staking Token"
        );
        _;
    }

    modifier updateReward(address account) {
        rewardPerTokenStored = rewardPerToken();
        lastUpdateTime = lastTimeRewardApplicable();
        if (account != address(0)) {
            rewards[account] = earned(account);
            userRewardPerTokenPaid[account] = rewardPerTokenStored;
        }
        _;
    }

    /* ========== EVENTS ========== */

    event RewardAdded(uint256 reward);
    event Staked(address indexed user, uint256 amount);
    event Withdrawn(address indexed user, uint256 amount);
    event RewardPaid(
        address indexed user,
        uint256 reward,
        uint256 perShareAmount
    );
}
function totalSupply() external view returns (uint256) {
    return _totalSupply;
}

/* ========== VIEWS ========== */