contract YUANUSDxYUANPool is LPTokenWrapper, IRewardDistributionRecipient {
    IERC20 public yuan = IERC20(0x4A3e164684812DfB684AC36457E7fA805087c68E);
    uint256 public constant DURATION = 18 days;
    uint256 public constant halveInterval = 1 days;

    uint256 public starttime = 1604545200; // 2020/11/5 11:0:0 (UTC+8)
    uint256 public periodFinish = 0;
    uint256 public initialRewardRate = 0;
    uint256 public lastUpdateTime;
    uint256 public distributionTime;
    uint256 public rewardPerTokenStored;
    mapping(address => uint256) public userRewardPerTokenPaid;
    mapping(address => uint256) public rewards;

    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);

    modifier checkStart() {
        require(block.timestamp >= starttime, "not start");
        _;
    }

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

    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(
                getrewardPerTokenAmount().mul(1e18).div(totalSupply())
            );
    }

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

    // stake visibility is public as overriding LPTokenWrapper's stake() function
    function stake(uint256 amount) public updateReward(msg.sender) checkStart {
        require(amount > 0, "Cannot stake 0");
        super.stake(amount);
        emit Staked(msg.sender, amount);
    }

    function withdraw(uint256 amount)
        public
        updateReward(msg.sender)
        checkStart
    {
        require(amount > 0, "Cannot withdraw 0");
        super.withdraw(amount);
        emit Withdrawn(msg.sender, amount);
    }

    function exit() external {
        withdraw(balanceOf(msg.sender));
        getReward();
    }

    function getReward() public updateReward(msg.sender) checkStart {
        uint256 reward = rewards[msg.sender];
        if (reward > 0) {
            rewards[msg.sender] = 0;
            uint256 scalingFactor = YUAN(address(yuan)).yuansScalingFactor();
            uint256 trueReward = reward.mul(scalingFactor).div(10**18);
            yuan.safeTransfer(msg.sender, trueReward);
            emit RewardPaid(msg.sender, reward);
        }
    }

    /**
     * @dev Calculate the cumulative reward per token from lastUpdateTime to lastTimeRewardApplicable()
     * such time span could be divided into 3 parts by halve intervals:
     * (lastUpdateTime, firstIntervalEnd), (firstIntervalEnd, lastIntervalStart), (lastIntervalStart, lastTimeRewardApplicable())
     */
    function getrewardPerTokenAmount() public view returns (uint256) {
        uint256 _timestamp = lastTimeRewardApplicable();
        uint256 _distributionTime = distributionTime;
        uint256 _lastUpdateTime = lastUpdateTime;

        if (_timestamp < _distributionTime || _timestamp == _lastUpdateTime)
            return 0;

        uint256 _lastUpdateTimeOffset = _lastUpdateTime.sub(_distributionTime) %
            halveInterval;
        uint256 _firstIntervalEnd = _lastUpdateTime
            .sub(_lastUpdateTimeOffset)
            .add(halveInterval);

        // The time span is too short that it has not reach _firstIntervalEnd
        if (_timestamp < _firstIntervalEnd)
            return
                _timestamp.sub(_lastUpdateTime).mul(
                    getFixedRewardRate(_lastUpdateTime)
                );

        // The amount from _lastUpdateTime to _firstIntervalEnd
        uint256 _rewardPerTokenAmount = halveInterval
            .sub(_lastUpdateTimeOffset)
            .mul(getFixedRewardRate(_lastUpdateTime));

        // The amount from _firstIntervalEnd to last interval start, it may contains n full halve interval (n >= 0)
        // n = 0 if _firstIntervalEnd and _timestamp lay in the same halve interval
        // _currentRewardRate represents 1/2 of the reward rate of last full interval
        uint256 _currentRewardRate = getFixedRewardRate(_timestamp);
        _rewardPerTokenAmount = _rewardPerTokenAmount.add(
            (
                halveInterval.mul(
                    getFixedRewardRate(_firstIntervalEnd).sub(
                        _currentRewardRate
                    )
                )
            ) << 1
        );

        // Finally, the amount from last interval start to timestamp
        return
            _rewardPerTokenAmount.add(
                (_timestamp.sub(_distributionTime) % halveInterval).mul(
                    _currentRewardRate
                )
            );
    }

    function rewardRate() public view returns (uint256) {
        return getFixedRewardRate(block.timestamp);
    }

    function getFixedRewardRate(uint256 _timestamp)
        public
        view
        returns (uint256)
    {
        if (_timestamp < distributionTime) return 0;
        return
            initialRewardRate >>
            (Math.min(_timestamp, periodFinish).sub(distributionTime) /
                halveInterval);
    }

    function notifyRewardAmount(uint256 reward)
        external
        onlyRewardDistribution
        updateReward(address(0))
    {
        // https://sips.synthetix.io/sips/sip-77
        // increased buffer for scaling factor ( supports up to 10**4 * 10**18 scaling factor)
        require(reward < uint256(-1) / 10**22, "rewards too large, would lock");

        uint256 _firstReward = reward.mul(1e18).div(
            2e18 - (2e18 >> (DURATION.div(halveInterval)))
        );

        if (block.timestamp > starttime) {
            require(block.timestamp >= periodFinish, "not over yet");
            initialRewardRate = _firstReward.div(halveInterval);
            lastUpdateTime = block.timestamp;
            distributionTime = block.timestamp;
            periodFinish = block.timestamp.add(DURATION);
            emit RewardAdded(reward);
        } else {
            initialRewardRate = _firstReward.div(halveInterval);
            lastUpdateTime = starttime;
            distributionTime = starttime;
            periodFinish = starttime.add(DURATION);
            emit RewardAdded(reward);
        }
    }
}
function getrewardPerTokenAmount() public view returns (uint256) {
    uint256 _timestamp = lastTimeRewardApplicable();
    uint256 _distributionTime = distributionTime;
    uint256 _lastUpdateTime = lastUpdateTime;

    if (_timestamp < _distributionTime || _timestamp == _lastUpdateTime)
        return 0;

    uint256 _lastUpdateTimeOffset = _lastUpdateTime.sub(_distributionTime) %
        halveInterval;
    uint256 _firstIntervalEnd = _lastUpdateTime
        .sub(_lastUpdateTimeOffset)
        .add(halveInterval);

    // The time span is too short that it has not reach _firstIntervalEnd
    if (_timestamp < _firstIntervalEnd)
        return
            _timestamp.sub(_lastUpdateTime).mul(
                getFixedRewardRate(_lastUpdateTime)
            );

    // The amount from _lastUpdateTime to _firstIntervalEnd
    uint256 _rewardPerTokenAmount = halveInterval
        .sub(_lastUpdateTimeOffset)
        .mul(getFixedRewardRate(_lastUpdateTime));

    // The amount from _firstIntervalEnd to last interval start, it may contains n full halve interval (n >= 0)
    // n = 0 if _firstIntervalEnd and _timestamp lay in the same halve interval
    // _currentRewardRate represents 1/2 of the reward rate of last full interval
    uint256 _currentRewardRate = getFixedRewardRate(_timestamp);
    _rewardPerTokenAmount = _rewardPerTokenAmount.add(
        (
            halveInterval.mul(
                getFixedRewardRate(_firstIntervalEnd).sub(
                    _currentRewardRate
                )
            )
        ) << 1
    );

    // Finally, the amount from last interval start to timestamp
    return
        _rewardPerTokenAmount.add(
            (_timestamp.sub(_distributionTime) % halveInterval).mul(
                _currentRewardRate
            )
        );
}

/**
 * @dev Calculate the cumulative reward per token from lastUpdateTime to lastTimeRewardApplicable()
 * such time span could be divided into 3 parts by halve intervals:
 * (lastUpdateTime, firstIntervalEnd), (firstIntervalEnd, lastIntervalStart), (lastIntervalStart, lastTimeRewardApplicable())
 */