ETH Price: $2,172.29 (+3.33%)

Transaction Decoder

Block:
12246981 at Apr-15-2021 08:58:06 PM +UTC
Transaction Fee:
0.0082346 ETH $17.89
Gas Used:
86,680 Gas / 95 Gwei

Emitted Events:

293 Token.Transfer( from=[Sender] 0xde3c0b11e86e2d1e4cd4c2d66276e1a1ca78babd, to=0xa7A4d919202DFA2f4E44FFAc422d21095bF9770a, value=23180819259708904676 )
294 Token.Approval( owner=[Sender] 0xde3c0b11e86e2d1e4cd4c2d66276e1a1ca78babd, spender=[Receiver] PoolStake, value=115792089237316195423570985008687907853269984665640564039434403188653420735259 )
295 Token.Transfer( from=[Receiver] PoolStake, to=[Sender] 0xde3c0b11e86e2d1e4cd4c2d66276e1a1ca78babd, value=231808192597089173198 )
296 PoolStake.UserTokenBonusWithdrawn( sender=[Sender] 0xde3c0b11e86e2d1e4cd4c2d66276e1a1ca78babd, amount=231808192597089173198, fee=23180819259708917319 )

Account State Difference:

  Address   Before After State Difference Code
0x7d9FfF9D...740535C75
0x9Ed8e7C9...8AAB64E5E
0xDE3C0B11...1Ca78BABD
1.290597383829832215 Eth
Nonce: 3426
1.282362783829832215 Eth
Nonce: 3427
0.0082346
(Ethermine)
938.158972953697382356 Eth938.167207553697382356 Eth0.0082346

Execution Trace

PoolStake.CALL( )
  • UniswapV2Pair.STATICCALL( )
  • UniswapV2Pair.STATICCALL( )
  • Token.transferFrom( sender=0xDE3C0B11e86E2d1E4cd4c2D66276E1A1Ca78BABD, recipient=0xa7A4d919202DFA2f4E44FFAc422d21095bF9770a, amount=23180819259708904676 ) => ( True )
  • Token.transfer( recipient=0xDE3C0B11e86E2d1E4cd4c2D66276E1A1Ca78BABD, amount=231808192597089173198 ) => ( True )
    File 1 of 3: PoolStake
    //"SPDX-License-Identifier: UNLICENSED"
    
    /**
     *Submitted for verification at Etherscan.io on 2021-03-01
    */
    
    //"SPDX-License-Identifier: UNLICENSED"
    
    pragma solidity ^0.6.6;
    
    library SafeMath {
        /**
         * @dev Returns the addition of two unsigned integers, reverting on
         * overflow.
         *
         * Counterpart to Solidity's `+` operator.
         *
         * Requirements:
         *
         * - Addition cannot overflow.
         */
        function add(uint256 a, uint256 b) internal pure returns (uint256) {
            uint256 c = a + b;
            require(c >= a, "SafeMath: addition overflow");
    
            return c;
        }
    
        /**
         * @dev Returns the subtraction of two unsigned integers, reverting on
         * overflow (when the result is negative).
         *
         * Counterpart to Solidity's `-` operator.
         *
         * Requirements:
         *
         * - Subtraction cannot overflow.
         */
        function sub(uint256 a, uint256 b) internal pure returns (uint256) {
            return sub(a, b, "SafeMath: subtraction overflow");
        }
    
        /**
         * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
         * overflow (when the result is negative).
         *
         * Counterpart to Solidity's `-` operator.
         *
         * Requirements:
         *
         * - Subtraction cannot overflow.
         */
        function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b <= a, errorMessage);
            uint256 c = a - b;
    
            return c;
        }
    
        /**
         * @dev Returns the multiplication of two unsigned integers, reverting on
         * overflow.
         *
         * Counterpart to Solidity's `*` operator.
         *
         * Requirements:
         *
         * - Multiplication cannot overflow.
         */
        function mul(uint256 a, uint256 b) internal pure returns (uint256) {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) {
                return 0;
            }
    
            uint256 c = a * b;
            require(c / a == b, "SafeMath: multiplication overflow");
    
            return c;
        }
    
        /**
         * @dev Returns the integer division of two unsigned integers. Reverts on
         * division by zero. The result is rounded towards zero.
         *
         * Counterpart to Solidity's `/` operator. Note: this function uses a
         * `revert` opcode (which leaves remaining gas untouched) while Solidity
         * uses an invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function div(uint256 a, uint256 b) internal pure returns (uint256) {
            return div(a, b, "SafeMath: division by zero");
        }
    
        /**
         * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
         * division by zero. The result is rounded towards zero.
         *
         * Counterpart to Solidity's `/` operator. Note: this function uses a
         * `revert` opcode (which leaves remaining gas untouched) while Solidity
         * uses an invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b > 0, errorMessage);
            uint256 c = a / b;
            // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    
            return c;
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
         * Reverts when dividing by zero.
         *
         * Counterpart to Solidity's `%` operator. This function uses a `revert`
         * opcode (which leaves remaining gas untouched) while Solidity uses an
         * invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function mod(uint256 a, uint256 b) internal pure returns (uint256) {
            return mod(a, b, "SafeMath: modulo by zero");
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
         * Reverts with custom message when dividing by zero.
         *
         * Counterpart to Solidity's `%` operator. This function uses a `revert`
         * opcode (which leaves remaining gas untouched) while Solidity uses an
         * invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b != 0, errorMessage);
            return a % b;
        }
    }
    
    interface IERC20 {
      /**
       * @dev Returns the amount of tokens in existence.
       */
      function totalSupply() external view returns (uint256);
    
      /**
       * @dev Returns the amount of tokens owned by `account`.
       */
      function balanceOf(address account) external view returns (uint256);
    
      /**
       * @dev Moves `amount` tokens from the caller's account to `recipient`.
       *
       * Returns a boolean value indicating whether the operation succeeded.
       *
       * Emits a {Transfer} event.
       */
      function transfer(address recipient, uint256 amount) external returns (bool);
    
      /**
       * @dev Returns the remaining number of tokens that `spender` will be
       * allowed to spend on behalf of `owner` through {transferFrom}. This is
       * zero by default.
       *
       * This value changes when {approve} or {transferFrom} are called.
       */
      function allowance(address owner, address spender)
        external
        view
        returns (uint256);
    
      /**
       * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
       *
       * Returns a boolean value indicating whether the operation succeeded.
       *
       * IMPORTANT: Beware that changing an allowance with this method brings the risk
       * that someone may use both the old and the new allowance by unfortunate
       * transaction ordering. One possible solution to mitigate this race
       * condition is to first reduce the spender's allowance to 0 and set the
       * desired value afterwards:
       * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
       *
       * Emits an {Approval} event.
       */
      function approve(address spender, uint256 amount) external returns (bool);
    
      /**
       * @dev Moves `amount` tokens from `sender` to `recipient` using the
       * allowance mechanism. `amount` is then deducted from the caller's
       * allowance.
       *
       * Returns a boolean value indicating whether the operation succeeded.
       *
       * Emits a {Transfer} event.
       */
      function transferFrom(
        address sender,
        address recipient,
        uint256 amount
      ) external returns (bool);
    
      /**
       * @dev Emitted when `value` tokens are moved from one account (`from`) to
       * another (`to`).
       *
       * Note that `value` may be zero.
       */
      event Transfer(address indexed from, address indexed to, uint256 value);
    
      /**
       * @dev Emitted when the allowance of a `spender` for an `owner` is set by
       * a call to {approve}. `value` is the new allowance.
       */
      event Approval(address indexed owner, address indexed spender, uint256 value);
    }
    
    interface IUniswapV2Factory {
        event PairCreated(address indexed token0, address indexed token1, address pair, uint);
    
        function feeTo() external view returns (address);
        function feeToSetter() external view returns (address);
    
        function getPair(address tokenA, address tokenB) external view returns (address pair);
        function allPairs(uint) external view returns (address pair);
        function allPairsLength() external view returns (uint);
    
        function createPair(address tokenA, address tokenB) external returns (address pair);
    
        function setFeeTo(address) external;
        function setFeeToSetter(address) external;
    }
    
    interface UniswapV2Router{
        
        function addLiquidity(
          address tokenA,
          address tokenB,
          uint amountADesired,
          uint amountBDesired,
          uint amountAMin,
          uint amountBMin,
          address to,
          uint deadline
        ) external returns (uint amountA, uint amountB, uint liquidity);
        
        function addLiquidityETH(
          address token,
          uint amountTokenDesired,
          uint amountTokenMin,
          uint amountETHMin,
          address to,
          uint deadline
        ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
         
        function removeLiquidityETH(
            address token,
            uint liquidity,
            uint amountTokenMin,
            uint amountETHMin,
            address to,
            uint deadline
        ) external returns (uint amountToken, uint amountETH);
        
        function removeLiquidity(
            address tokenA,
            address tokenB,
            uint liquidity,
            uint amountAMin,
            uint amountBMin,
            address to,
            uint deadline
        ) external returns (uint amountA, uint amountB);
        
        function swapExactTokensForTokens(
            uint amountIn,
            uint amountOutMin,
            address[] calldata path,
            address to,
            uint deadline
        ) external returns (uint[] memory amounts);
        
        function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
    
    }
    
    library UniswapV2Library {
        using SafeMath for uint;
    
        // returns sorted token addresses, used to handle return values from pairs sorted in this order
        function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
            require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
            (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
            require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
        }
    
        // calculates the CREATE2 address for a pair without making any external calls
        function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
            (address token0, address token1) = sortTokens(tokenA, tokenB);
            pair = address(uint(keccak256(abi.encodePacked(
                    hex'ff',
                    factory,
                    keccak256(abi.encodePacked(token0, token1)),
                    hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
                ))));
        }
    
        // fetches and sorts the reserves for a pair
        function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
            (address token0,) = sortTokens(tokenA, tokenB);
            (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
            (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
        }
    
        // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
        function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
            require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
            require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
            amountB = amountA.mul(reserveB) / reserveA;
        }
    
        // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
        function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
            require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
            require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
            uint amountInWithFee = amountIn.mul(997);
            uint numerator = amountInWithFee.mul(reserveOut);
            uint denominator = reserveIn.mul(1000).add(amountInWithFee);
            amountOut = numerator / denominator;
        }
    
        // given an output amount of an asset and pair reserves, returns a required input amount of the other asset
        function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
            require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
            require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
            uint numerator = reserveIn.mul(amountOut).mul(1000);
            uint denominator = reserveOut.sub(amountOut).mul(997);
            amountIn = (numerator / denominator).add(1);
        }
    
        // performs chained getAmountOut calculations on any number of pairs
        function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
            require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
            amounts = new uint[](path.length);
            amounts[0] = amountIn;
            for (uint i; i < path.length - 1; i++) {
                (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
                amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
            }
        }
    
        // performs chained getAmountIn calculations on any number of pairs
        function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
            require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
            amounts = new uint[](path.length);
            amounts[amounts.length - 1] = amountOut;
            for (uint i = path.length - 1; i > 0; i--) {
                (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
                amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
            }
        }
    }
    
    interface IUniswapV2Pair {
        event Approval(address indexed owner, address indexed spender, uint value);
        event Transfer(address indexed from, address indexed to, uint value);
    
        function name() external pure returns (string memory);
        function symbol() external pure returns (string memory);
        function decimals() external pure returns (uint8);
        function totalSupply() external view returns (uint);
        function balanceOf(address owner) external view returns (uint);
        function allowance(address owner, address spender) external view returns (uint);
    
        function approve(address spender, uint value) external returns (bool);
        function transfer(address to, uint value) external returns (bool);
        function transferFrom(address from, address to, uint value) external returns (bool);
    
        function DOMAIN_SEPARATOR() external view returns (bytes32);
        function PERMIT_TYPEHASH() external pure returns (bytes32);
        function nonces(address owner) external view returns (uint);
    
        function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
    
        event Mint(address indexed sender, uint amount0, uint amount1);
        event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
        event Swap(address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to);
        event Sync(uint112 reserve0, uint112 reserve1);
    
        function MINIMUM_LIQUIDITY() external pure returns (uint);
        function factory() external view returns (address);
        function token0() external view returns (address);
        function token1() external view returns (address);
        function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
        function price0CumulativeLast() external view returns (uint);
        function price1CumulativeLast() external view returns (uint);
        function kLast() external view returns (uint);
    
        function mint(address to) external returns (uint liquidity);
        function burn(address to) external returns (uint amount0, uint amount1);
        function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
        function skim(address to) external;
        function sync() external;
    
        function initialize(address, address) external;
    }
    
    contract Owned {
        
        //address of contract owner
        address public owner;
    
        //event for transfer of ownership
        event OwnershipTransferred(address indexed _from, address indexed _to);
    
        /**
         * @dev Initializes the contract setting the _owner as the initial owner.
         */
        constructor(address _owner) public {
            owner = _owner;
        }
    
        /**
         * @dev Throws if called by any account other than the owner.
         */
        modifier onlyOwner {
            require(msg.sender == owner, 'only owner allowed');
            _;
        }
    
        /**
         * @dev Transfers ownership of the contract to a new account (`_newOwner`).
         * Can only be called by the current owner.
         */
        function transferOwnership(address _newOwner) external onlyOwner {
            owner = _newOwner;
            emit OwnershipTransferred(owner, _newOwner);
        }
    }
    
    interface Multiplier {
        function updateLockupPeriod(address _user, uint _lockup) external returns(bool);
        function getMultiplierCeiling() external pure returns (uint);
        function balance(address user) external view returns (uint);
        function approvedContract(address _user) external view returns(address);
        function lockupPeriod(address user) external view returns (uint);
    }
    
    /* 
     * @dev PoolStakes contract for locking up liquidity to earn bonus rewards.
     */
    contract PoolStake is Owned {
        //instantiate SafeMath library
        using SafeMath for uint;
        
        IERC20 internal weth;                       //represents weth.
        IERC20 internal token;                      //represents the project's token which should have a weth pair on uniswap
        IERC20 internal lpToken;                    //lpToken for liquidity provisioning
        
        address internal uToken;                    //utility token
        address internal wallet;                    //company wallet
        uint internal scalar = 10**36;              //unit for scaling
        uint internal cap;                          //ETH limit that can be provided
        
        Multiplier internal multiplier;                         //Interface of Multiplier contract
        UniswapV2Router internal uniswapRouter;                 //Interface of Uniswap V2 router
        IUniswapV2Factory internal iUniswapV2Factory;           //Interface of uniswap V2 factory
        
        //user struct
        struct User {
            uint start;                 //starting period
            uint release;               //release period
            uint tokenBonus;            //user token bonus
            uint wethBonus;             //user weth bonus
            uint tokenWithdrawn;        //amount of token bonus withdrawn
            uint wethWithdrawn;         //amount of weth bonus withdrawn
            uint liquidity;             //user liquidity gotten from uniswap
            bool migrated;              //if migrated to uniswap V3
        }
        
        //address to User mapping
        mapping(address => User) internal _users;
        
        uint32 internal constant _012_HOURS_IN_SECONDS = 43200;
        
        //term periods
        uint32 internal period1;
        uint32 internal period2;
        uint32 internal period3;
        uint32 internal period4;
        
        //return percentages for ETH and token                          1000 = 1% 
        uint internal period1RPWeth; 
        uint internal period2RPWeth;
        uint internal period3RPWeth;
        uint internal period4RPWeth;
        uint internal period1RPToken; 
        uint internal period2RPToken;
        uint internal period3RPToken;
        uint internal period4RPToken;
        
        //available bonuses rto be claimed
        uint internal _pendingBonusesWeth;
        uint internal _pendingBonusesToken;
        
        //migration contract for Uniswap V3
        address public migrationContract;
        
        //events
        event BonusAdded(address indexed sender, uint ethAmount, uint tokenAmount);
        event BonusRemoved(address indexed sender, uint amount);
        event CapUpdated(address indexed sender, uint amount);
        event LPWithdrawn(address indexed sender, uint amount);
        event LiquidityAdded(address indexed sender, uint liquidity, uint amountETH, uint amountToken);
        event LiquidityWithdrawn(address indexed sender, uint liquidity, uint amountETH, uint amountToken);
        event UserTokenBonusWithdrawn(address indexed sender, uint amount, uint fee);
        event UserETHBonusWithdrawn(address indexed sender, uint amount, uint fee);
        event VersionMigrated(address indexed sender, uint256 time, address to);
        event LiquidityMigrated(address indexed sender, uint amount, address to);
        
        /* 
         * @dev initiates a new PoolStake.
         * ------------------------------------------------------
         * @param _token    --> token offered for staking liquidity.
         * @param _Owner    --> address for the initial contract owner.
         */ 
        constructor(address _token, address _Owner) public Owned(_Owner) {
                
            require(_token != address(0), "can not deploy a zero address");
            token = IERC20(_token);
            weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); 
            
            iUniswapV2Factory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
            address _lpToken = iUniswapV2Factory.getPair(address(token), address(weth));
            require(_lpToken != address(0), "Pair must first be created on uniswap");
            lpToken = IERC20(_lpToken);
            
            uToken = 0x9Ed8e7C9604790F7Ec589F99b94361d8AAB64E5E;
            wallet = 0xa7A4d919202DFA2f4E44FFAc422d21095bF9770a;
            multiplier = Multiplier(0xbc962d7be33d8AfB4a547936D8CE6b9a1034E9EE);
            uniswapRouter = UniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);        
        }
        
        /* 
         * @dev change the return percentage for locking up liquidity for ETH and Token (only Owner).
         * ------------------------------------------------------------------------------------
         * @param _period1RPETH - _period4RPToken --> the new return percentages.
         * ----------------------------------------------
         * returns whether successfully changed or not.
         */ 
        function changeReturnPercentages(
            uint _period1RPETH, uint _period2RPETH, uint _period3RPETH, uint _period4RPETH, 
            uint _period1RPToken, uint _period2RPToken, uint _period3RPToken, uint _period4RPToken
        ) external onlyOwner returns(bool) {
            
            period1RPWeth = _period1RPETH;
            period2RPWeth = _period2RPETH;
            period3RPWeth = _period3RPETH;
            period4RPWeth = _period4RPETH;
            
            period1RPToken = _period1RPToken;
            period2RPToken = _period2RPToken;
            period3RPToken = _period3RPToken;
            period4RPToken = _period4RPToken;
            
            return true;
        }
        
        /* 
         * @dev change the lockup periods (only Owner).
         * ------------------------------------------------------------------------------------
         * @param _firstTerm - _fourthTerm --> the new term periods.
         * ----------------------------------------------
         * returns whether successfully changed or not.
         */ 
        function changeTermPeriods(
            uint32 _firstTerm, uint32 _secondTerm, 
            uint32 _thirdTerm, uint32 _fourthTerm
        ) external onlyOwner returns(bool) {
            
            period1 = _firstTerm;
            period2 = _secondTerm;
            period3 = _thirdTerm;
            period4 = _fourthTerm;
            
            return true;
        }
        
        /* 
         * @dev change the maximum ETH that a user can enter with (only Owner).
         * ------------------------------------------------------------------------------------
         * @param _cap      --> the new cap value.
         * ----------------------------------------------
         * returns whether successfully changed or not.
         */ 
        function changeCap(uint _cap) external onlyOwner returns(bool) {
            
            cap = _cap;
            
            emit CapUpdated(msg.sender, _cap);
            return true;
        }
        
        /* 
         * @dev makes migration possible for uniswap V3 (only Owner).
         * ----------------------------------------------------------
         * @param _unistakeMigrationContract      --> the migration contract address.
         * -------------------------------------------------------------------------
         * returns whether successfully migrated or not.
         */ 
        function allowMigration(address _unistakeMigrationContract) external onlyOwner returns (bool) {
            
            require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address");
            migrationContract = _unistakeMigrationContract;
            
            emit VersionMigrated(msg.sender, now, migrationContract);
            return true;
        }
        
        /* 
         * @dev initiates migration for a user (only when migration is allowed).
         * -------------------------------------------------------------------
         * @param _unistakeMigrationContract      --> the migration contract address.
         * -------------------------------------------------------------------------
         * returns whether successfully migrated or not.
         */ 
        function startMigration(address _unistakeMigrationContract) external returns (bool) {
            
            require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address");
            require(migrationContract == _unistakeMigrationContract, "must confirm endpoint");
            require(!getUserMigration(msg.sender), "must not be migrated already");
            
            _users[msg.sender].migrated = true;
            
            uint256 liquidity = _users[msg.sender].liquidity;
            lpToken.transfer(migrationContract, liquidity);
            
            emit LiquidityMigrated(msg.sender, liquidity, migrationContract);
            return true;
        }
        
        /* 
         * @dev add more staking bonuses to the pool.
         * ----------------------------------------
         * @param              --> input value along with call to add ETH
         * @param _tokenAmount --> the amount of token to be added.
         * --------------------------------------------------------
         * returns whether successfully added or not.
         */ 
        function addBonus(uint _tokenAmount) external payable returns(bool) {
            
            require(_tokenAmount > 0 || msg.value > 0, "must send value");
            if (_tokenAmount > 0)
            require(token.transferFrom(msg.sender, address(this), _tokenAmount), "must approve smart contract");
            
            emit BonusAdded(msg.sender, msg.value, _tokenAmount);
            return true;
        }
        
        /* 
         * @dev remove staking bonuses to the pool. (only owner)
         * must have enough asset to be removed
         * ----------------------------------------
         * @param _amountETH   --> eth amount to be removed
         * @param _amountToken --> token amount to be removed.
         * --------------------------------------------------------
         * returns whether successfully added or not.
         */ 
        function removeETHAndTokenBouses(uint _amountETH, uint _amountToken) external onlyOwner returns (bool success) {
           
            require(_amountETH > 0 || _amountToken > 0, "amount must be larger than zero");
        
            if (_amountETH > 0) {
                require(_checkForSufficientStakingBonusesForETH(_amountETH), 'cannot withdraw above current ETH bonus balance');
                msg.sender.transfer(_amountETH);
                emit BonusRemoved(msg.sender, _amountETH);
            }
            
            if (_amountToken > 0) {
                require(_checkForSufficientStakingBonusesForToken(_amountToken), 'cannot withdraw above current token bonus balance');
                require(token.transfer(msg.sender, _amountToken), "error: token transfer failed");
                emit BonusRemoved(msg.sender, _amountToken);
            }
            
            return true;
        }
        
        /* 
         * @dev add unwrapped liquidity to staking pool.
         * --------------------------------------------
         * @param _tokenAmount  --> must input token amount along with call
         * @param _term         --> the lockup term.
         * @param _multiplier   --> whether multiplier should be used or not
         *                        1 means you want to use the multiplier. !1 means no multiplier
         * --------------------------------------------------------------
         * returns whether successfully added or not.
         */
        function addLiquidity(uint _term, uint _multiplier) external payable returns(bool) {
            
            require(!getUserMigration(msg.sender), "must not be migrated already");
            require(now >= _users[msg.sender].release, "cannot override current term");
            require(_isValidTerm(_term), "must select a valid term");
            require(msg.value > 0, "must send ETH along with transaction");
            if (cap != 0) require(msg.value <= cap, "cannot provide more than the cap");
            
            uint rate = _proportion(msg.value, address(weth), address(token));
            require(token.transferFrom(msg.sender, address(this), rate), "must approve smart contract");
            
            (uint ETH_bonus, uint token_bonus) = getUserBonusPending(msg.sender);
            require(ETH_bonus == 0 && token_bonus == 0, "must first withdraw available bonus");
            
            uint oneTenthOfRate = (rate.mul(10)).div(100);
            token.approve(address(uniswapRouter), rate);
    
            (uint amountToken, uint amountETH, uint liquidity) = 
            uniswapRouter.addLiquidityETH{value: msg.value}(
                address(token), 
                rate.add(oneTenthOfRate), 
                0, 
                0, 
                address(this), 
                now.add(_012_HOURS_IN_SECONDS));
            
            _users[msg.sender].start = now;
            _users[msg.sender].release = now.add(_term);
            
            uint previousLiquidity = _users[msg.sender].liquidity; 
            _users[msg.sender].liquidity = previousLiquidity.add(liquidity);  
            
            uint wethRP = _calculateReturnPercentage(weth, _term);
            uint tokenRP = _calculateReturnPercentage(token, _term);
                   
            (uint provided_ETH, uint provided_token) = getUserLiquidity(msg.sender);
            
            if (_multiplier == 1) 
            _withMultiplier(_term, provided_ETH, provided_token, wethRP,  tokenRP);
            else _withoutMultiplier(provided_ETH, provided_token, wethRP, tokenRP);
            
            emit LiquidityAdded(msg.sender, liquidity, amountETH, amountToken);
            return true;
        }
        
        /* 
         * @dev uses the Multiplier contract for double rewarding
         * ------------------------------------------------------
         * @param _term       --> the lockup term.
         * @param amountETH   --> ETH amount provided in liquidity
         * @param amountToken --> token amount provided in liquidity
         * @param wethRP      --> return percentge for ETH based on term period
         * @param tokenRP     --> return percentge for token based on term period
         * --------------------------------------------------------------------
         */
        function _withMultiplier(
            uint _term, uint amountETH, uint amountToken, uint wethRP, uint tokenRP
        ) internal {
            
            require(multiplier.balance(msg.sender) > 0, "No Multiplier balance to use");
            if (_term > multiplier.lockupPeriod(msg.sender)) multiplier.updateLockupPeriod(msg.sender, _term);
            
            uint multipliedETH = _proportion(multiplier.balance(msg.sender), uToken, address(weth));
            uint multipliedToken = _proportion(multipliedETH, address(weth), address(token));
            uint addedBonusWeth;
            uint addedBonusToken;
            
            if (_offersBonus(weth) && _offersBonus(token)) {
                        
                if (multipliedETH > amountETH) {
                    multipliedETH = (_calculateBonus((amountETH.mul(multiplier.getMultiplierCeiling())), wethRP));
                    addedBonusWeth = multipliedETH;
                } else {
                    addedBonusWeth = (_calculateBonus((amountETH.add(multipliedETH)), wethRP));
                }
                        
                if (multipliedToken > amountToken) {
                    multipliedToken = (_calculateBonus((amountToken.mul(multiplier.getMultiplierCeiling())), tokenRP));
                    addedBonusToken = multipliedToken;
                } else {
                    addedBonusToken = (_calculateBonus((amountToken.add(multipliedToken)), tokenRP));
                }
                    
                require(_checkForSufficientStakingBonusesForETH(addedBonusWeth)
                && _checkForSufficientStakingBonusesForToken(addedBonusToken),
                "must be sufficient staking bonuses available in pool");
                                
                _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth);
                _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken);
                _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth);
                _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken);
                        
            } else if (_offersBonus(weth) && !_offersBonus(token)) {
                        
                if (multipliedETH > amountETH) {
                    multipliedETH = (_calculateBonus((amountETH.mul(multiplier.getMultiplierCeiling())), wethRP));
                    addedBonusWeth = multipliedETH;
                } else {
                    addedBonusWeth = (_calculateBonus((amountETH.add(multipliedETH)), wethRP));
                }
                        
                require(_checkForSufficientStakingBonusesForETH(addedBonusWeth), 
                "must be sufficient staking bonuses available in pool");
                        
                _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth);
                _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth);
                        
            } else if (!_offersBonus(weth) && _offersBonus(token)) {
            
                if (multipliedToken > amountToken) {
                    multipliedToken = (_calculateBonus((amountToken.mul(multiplier.getMultiplierCeiling())), tokenRP));
                    addedBonusToken = multipliedToken;
                } else {
                    addedBonusToken = (_calculateBonus((amountToken.add(multipliedToken)), tokenRP));
                }
                        
                require(_checkForSufficientStakingBonusesForToken(addedBonusToken),
                "must be sufficient staking bonuses available in pool");
                        
                _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken);
                _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken);
            }
        }
        
        /* 
         * @dev distributes bonus without considering Multiplier
         * ------------------------------------------------------
         * @param amountETH   --> ETH amount provided in liquidity
         * @param amountToken --> token amount provided in liquidity
         * @param wethRP      --> return percentge for ETH based on term period
         * @param tokenRP     --> return percentge for token based on term period
         * --------------------------------------------------------------------
         */
        function _withoutMultiplier(
            uint amountETH, uint amountToken, uint wethRP, uint tokenRP
        ) internal {
                
            uint addedBonusWeth;
            uint addedBonusToken;
            
            if (_offersBonus(weth) && _offersBonus(token)) {
                
                addedBonusWeth = _calculateBonus(amountETH, wethRP);
                addedBonusToken = _calculateBonus(amountToken, tokenRP);
                    
                require(_checkForSufficientStakingBonusesForETH(addedBonusWeth)
                && _checkForSufficientStakingBonusesForToken(addedBonusToken),
                "must be sufficient staking bonuses available in pool");
                            
                _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth);
                _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken);
                _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth);
                _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken);
                    
            } else if (_offersBonus(weth) && !_offersBonus(token)) {
                    
                addedBonusWeth = _calculateBonus(amountETH, wethRP);
                    
                require(_checkForSufficientStakingBonusesForETH(addedBonusWeth), 
                "must be sufficient staking bonuses available in pool");
                    
                _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth);
                _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth);
                    
            } else if (!_offersBonus(weth) && _offersBonus(token)) {
                    
                addedBonusToken = _calculateBonus(amountToken, tokenRP);
                    
                require(_checkForSufficientStakingBonusesForToken(addedBonusToken),
                "must be sufficient staking bonuses available in pool");
                    
                _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken);
                _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken);
            }
            
        }
        
        /* 
         * @dev relocks liquidity already provided
         * --------------------------------------------
         * @param _term       --> the lockup term.
         * @param _multiplier --> whether multiplier should be used or not
         *                        1 means you want to use the multiplier. !1 means no multiplier
         * --------------------------------------------------------------
         * returns whether successfully relocked or not.
         */
        function relockLiquidity(uint _term, uint _multiplier) external returns(bool) {
            
            require(!getUserMigration(msg.sender), "must not be migrated already");
            require(_users[msg.sender].liquidity > 0, "do not have any liquidity to lock");
            require(now >= _users[msg.sender].release, "cannot override current term");
            require(_isValidTerm(_term), "must select a valid term");
            
            (uint ETH_bonus, uint token_bonus) = getUserBonusPending(msg.sender);
            require (ETH_bonus == 0 && token_bonus == 0, 'must withdraw available bonuses first');
            
            (uint provided_ETH, uint provided_token) = getUserLiquidity(msg.sender);
            if (cap != 0) require(provided_ETH <= cap, "cannot provide more than the cap");
            
            uint wethRP = _calculateReturnPercentage(weth, _term);
            uint tokenRP = _calculateReturnPercentage(token, _term);
            
            _users[msg.sender].start = now;
            _users[msg.sender].release = now.add(_term);
            
            if (_multiplier == 1) _withMultiplier(_term, provided_ETH, provided_token, wethRP,  tokenRP);
            else _withoutMultiplier(provided_ETH, provided_token, wethRP, tokenRP); 
            
            return true;
        }
        
        /* 
         * @dev withdraw unwrapped liquidity by user if released.
         * -------------------------------------------------------
         * @param _lpAmount --> takes the amount of user's lp token to be withdrawn.
         * -------------------------------------------------------------------------
         * returns whether successfully withdrawn or not.
         */
        function withdrawLiquidity(uint _lpAmount) external returns(bool) {
            
            require(!getUserMigration(msg.sender), "must not be migrated already");
            
            uint liquidity = _users[msg.sender].liquidity;
            require(_lpAmount > 0 && _lpAmount <= liquidity, "do not have any liquidity");
            require(now >= _users[msg.sender].release, "cannot override current term");
            
            _users[msg.sender].liquidity = liquidity.sub(_lpAmount); 
            
            lpToken.approve(address(uniswapRouter), _lpAmount);                                         
            
            (uint amountToken, uint amountETH) = 
                uniswapRouter.removeLiquidityETH(
                    address(token),
                    _lpAmount,
                    1,
                    1,
                    msg.sender,
                    now.add(_012_HOURS_IN_SECONDS));
            
            emit LiquidityWithdrawn(msg.sender, _lpAmount, amountETH, amountToken);
            return true;
        }
        
        /* 
         * @dev withdraw LP token by user if released.
         * -------------------------------------------------------
         * returns whether successfully withdrawn or not.
         */
        function withdrawUserLP() external returns(bool) {
            
            require(!getUserMigration(msg.sender), "must not be migrated already");
            
            uint liquidity = _users[msg.sender].liquidity;
            require(liquidity > 0, "do not have any liquidity");
            require(now >= _users[msg.sender].release, "cannot override current term");
            
            _users[msg.sender].liquidity = 0; 
            
            lpToken.transfer(msg.sender, liquidity);                                         
            
            emit LPWithdrawn(msg.sender, liquidity);
            return true;
        }
        
        /* 
         * @dev withdraw available staking bonuses earned from locking up liquidity. 
         * --------------------------------------------------------------
         * returns whether successfully withdrawn or not.
         */  
        function withdrawUserBonus() public returns(bool) {
            
            (uint ETH_bonus, uint token_bonus) = getUserBonusAvailable(msg.sender);
            require(ETH_bonus > 0 || token_bonus > 0, "you do not have any bonus available");
            
            uint releasedToken = _calculateTokenReleasedAmount(msg.sender);
            uint releasedETH = _calculateETHReleasedAmount(msg.sender);
            
            if (releasedToken > 0 && releasedETH > 0) {
                
                _withdrawUserTokenBonus(msg.sender, releasedToken);
                _withdrawUserETHBonus(msg.sender, releasedETH);
                
            } else if (releasedETH > 0 && releasedToken == 0) 
                _withdrawUserETHBonus(msg.sender, releasedETH);
            
            else if (releasedETH == 0 && releasedToken > 0)
                _withdrawUserTokenBonus(msg.sender, releasedToken);
            
            if (_users[msg.sender].release <= now) {
                
                _users[msg.sender].wethWithdrawn = 0;
                _users[msg.sender].tokenWithdrawn = 0;
                _users[msg.sender].wethBonus = 0;
                _users[msg.sender].tokenBonus = 0;
            }
            return true;
        }
        
        /* 
         * @dev withdraw ETH bonus earned from locking up liquidity
         * --------------------------------------------------------------
         * @param _user          --> address of the user making withdrawal
         * @param releasedAmount --> released ETH to be withdrawn
         * ------------------------------------------------------------------
         * returns whether successfully withdrawn or not.
         */
        function _withdrawUserETHBonus(address payable _user, uint releasedAmount) internal returns(bool) {
         
            _users[_user].wethWithdrawn = _users[_user].wethWithdrawn.add(releasedAmount);
            _pendingBonusesWeth = _pendingBonusesWeth.sub(releasedAmount);
            
            (uint fee, uint feeInETH) = _calculateETHFee(releasedAmount);
            
            require(IERC20(uToken).transferFrom(_user, wallet, fee), "must approve fee");
            _user.transfer(releasedAmount);
        
            emit UserETHBonusWithdrawn(_user, releasedAmount, feeInETH);
            return true;
        }
        
        /* 
         * @dev withdraw token bonus earned from locking up liquidity
         * --------------------------------------------------------------
         * @param _user          --> address of the user making withdrawal
         * @param releasedAmount --> released token to be withdrawn
         * ------------------------------------------------------------------
         * returns whether successfully withdrawn or not.
         */
        function _withdrawUserTokenBonus(address _user, uint releasedAmount) internal returns(bool) {
            
            _users[_user].tokenWithdrawn = _users[_user].tokenWithdrawn.add(releasedAmount);
            _pendingBonusesToken = _pendingBonusesToken.sub(releasedAmount);
            
            (uint fee, uint feeInToken) = _calculateTokenFee(releasedAmount);
            
            require(IERC20(uToken).transferFrom(_user, wallet, fee), "must approve fee");
            token.transfer(_user, releasedAmount);
        
            emit UserTokenBonusWithdrawn(_user, releasedAmount, feeInToken);
            return true;
        }
        
        /* 
         * @dev gets an asset's amount in proportion of a pair asset
         * ---------------------------------------------------------
         * param _amount --> the amount of first asset
         * param _tokenA --> the address of the first asset
         * param _tokenB --> the address of the second asset
         * -------------------------------------------------
         * returns the propotion of the _tokenB
         */ 
        function _proportion(uint _amount, address _tokenA, address _tokenB) internal view returns(uint tokenBAmount) {
            
            (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(address(iUniswapV2Factory), _tokenA, _tokenB);
            
            return UniswapV2Library.quote(_amount, reserveA, reserveB);
        }
        
        /* 
         * @dev gets the released Token value
         * --------------------------------
         * param _user --> the address of the user
         * ------------------------------------------------------
         * returns the released amount in Token
         */ 
        function _calculateTokenReleasedAmount(address _user) internal view returns(uint) {
    
            uint release = _users[_user].release;
            uint start = _users[_user].start;
            uint taken = _users[_user].tokenWithdrawn;
            uint tokenBonus = _users[_user].tokenBonus;
            uint releasedPct;
            
            if (now >= release) releasedPct = 100;
            else releasedPct = ((now.sub(start)).mul(100000)).div((release.sub(start)).mul(1000));
            
            uint released = (((tokenBonus).mul(releasedPct)).div(100));
            return released.sub(taken);
        }
        
        /* 
         * @dev gets the released ETH value
         * --------------------------------
         * param _user --> the address of the user
         * ------------------------------------------------------
         * returns the released amount in ETH
         */ 
        function _calculateETHReleasedAmount(address _user) internal view returns(uint) {
            
            uint release = _users[_user].release;
            uint start = _users[_user].start;
            uint taken = _users[_user].wethWithdrawn;
            uint wethBonus = _users[_user].wethBonus;
            uint releasedPct;
            
            if (now >= release) releasedPct = 100;
            else releasedPct = ((now.sub(start)).mul(10000)).div((release.sub(start)).mul(100));
            
            uint released = (((wethBonus).mul(releasedPct)).div(100));
            return released.sub(taken);
        }
        
        /* 
         * @dev get the required fee for the released token bonus in the utility token
         * -------------------------------------------------------------------------------
         * param _user --> the address of the user
         * ----------------------------------------------------------
         * returns the fee amount in the utility token and Token
         */ 
        function _calculateTokenFee(uint _amount) internal view returns(uint uTokenFee, uint tokenFee) {
            
            uint fee = (_amount.mul(10)).div(100);
            uint feeInETH = _proportion(fee, address(token), address(weth));
            uint feeInUtoken = _proportion(feeInETH, address(weth), address(uToken));  
            
            return (feeInUtoken, fee);
        
        }
        
        /* 
         * @dev get the required fee for the released ETH bonus in the utility token
         * -------------------------------------------------------------------------------
         * param _user --> the address of the user
         * ----------------------------------------------------------
         * returns the fee amount in the utility token and ETH
         */ 
        function _calculateETHFee(uint _amount) internal view returns(uint uTokenFee, uint ethFee) {
            
            uint fee = (_amount.mul(10)).div(100);
            uint feeInUtoken = _proportion(fee, address(weth), address(uToken));  
            
            return (feeInUtoken, fee);
        }
        
        /* 
         * @dev get the required fee for the released ETH bonus   
         * -------------------------------------------------------------------------------
         * param _user --> the address of the user
         * ----------------------------------------------------------
         * returns the fee amount.
         */ 
        function calculateETHBonusFee(address _user) external view returns(uint ETH_Fee) {
            
            uint wethReleased = _calculateETHReleasedAmount(_user);
            
            if (wethReleased > 0) {
                
                (uint feeForWethInUtoken,) = _calculateETHFee(wethReleased);
                
                return feeForWethInUtoken;
                
            } else return 0;
        }
        
        /* 
         * @dev get the required fee for the released token bonus   
         * -------------------------------------------------------------------------------
         * param _user --> the address of the user
         * ----------------------------------------------------------
         * returns the fee amount.
         */ 
        function calculateTokenBonusFee(address _user) external view returns(uint token_Fee) {
            
            uint tokenReleased = _calculateTokenReleasedAmount(_user);
            
            if (tokenReleased > 0) {
                
                (uint feeForTokenInUtoken,) = _calculateTokenFee(tokenReleased);
                
                return feeForTokenInUtoken;
                
            } else return 0;
        }
        
        /* 
         * @dev get the bonus based on the return percentage for a particular locking term.   
         * -------------------------------------------------------------------------------
         * param _amount           --> the amount to calculate bonus from.
         * param _returnPercentage --> the returnPercentage of the term.
         * ----------------------------------------------------------
         * returns the bonus amount.
         */ 
        function _calculateBonus(uint _amount, uint _returnPercentage) internal pure returns(uint) {
            
            return ((_amount.mul(_returnPercentage)).div(100000)) / 2;                                  //  1% = 1000
        }
        
        /* 
         * @dev get the correct return percentage based on locked term.   
         * -----------------------------------------------------------
         * @param _token --> associated asset.
         * @param _term --> the locking term.
         * ----------------------------------------------------------
         * returns the return percentage.
         */   
        function _calculateReturnPercentage(IERC20 _token, uint _term) internal view returns(uint) {
            
            if (_token == weth) {
                if (_term == period1) return period1RPWeth;
                else if (_term == period2) return period2RPWeth;
                else if (_term == period3) return period3RPWeth;
                else if (_term == period4) return period4RPWeth;
                else return 0;
                
            } else if (_token == token) {
                if (_term == period1) return period1RPToken;
                else if (_term == period2) return period2RPToken;
                else if (_term == period3) return period3RPToken;
                else if (_term == period4) return period4RPToken;
                else return 0;
            }
        }
        
        /* 
         * @dev check whether the input locking term is one of the supported terms.  
         * ----------------------------------------------------------------------
         * @param _term --> the locking term.
         * -------------------------------
         * returns whether true or not.
         */   
        function _isValidTerm(uint _term) internal view returns(bool) {
            
            if (_term == period1
                || _term == period2
                || _term == period3
                || _term == period4) 
                return true; 
                else return false;
        }
        
        /* 
         * @dev get the amount ETH and Token liquidity provided by the user.   
         * ------------------------------------------------------------------
         * @param _user --> the address of the user.
         * ---------------------------------------
         * returns the amount of ETH and Token liquidity provided.
         */   
        function getUserLiquidity(address _user) public view returns(uint provided_ETH, uint provided_token) {
            
            uint total = lpToken.totalSupply();
            uint ratio = ((_users[_user].liquidity).mul(scalar)).div(total);
            uint tokenHeld = token.balanceOf(address(lpToken));
            uint wethHeld = weth.balanceOf(address(lpToken));
            
            return ((ratio.mul(wethHeld)).div(scalar), (ratio.mul(tokenHeld)).div(scalar));
        }
        
        /* 
         * @dev check whether the inputted user address has been migrated.  
         * ----------------------------------------------------------------------
         * @param _user --> ddress of the user
         * ---------------------------------------
         * returns whether true or not.
         */  
        function getUserMigration(address _user) public view returns (bool) {
            
            return _users[_user].migrated;
        }
        
        /* 
         * @dev check whether the inputted user token has currently offers bonus  
         * ----------------------------------------------------------------------
         * @param _token --> associated token
         * ---------------------------------------
         * returns whether true or not.
         */  
        function _offersBonus(IERC20 _token) internal view returns (bool) {
            
            if (_token == weth) {
                uint wethRPTotal = period1RPWeth.add(period2RPWeth).add(period3RPWeth).add(period4RPWeth);
                if (wethRPTotal > 0) return true; 
                else return false;
                
            } else if (_token == token) {
                uint tokenRPTotal = period1RPToken.add(period2RPToken).add(period3RPToken).add(period4RPToken);
                if (tokenRPTotal > 0) return true;
                else return false;
            }
        }
        
        /* 
         * @dev check whether the pool has sufficient amount of bonuses available for new deposits/stakes.   
         * ----------------------------------------------------------------------------------------------
         * @param amount --> the _amount to be evaluated against.
         * ---------------------------------------------------
         * returns whether true or not.
         */ 
        function _checkForSufficientStakingBonusesForETH(uint _amount) internal view returns(bool) {
            
            if ((address(this).balance).sub(_pendingBonusesWeth) >= _amount) {
                return true;
            } else {
                return false;
            }
        }
        
        /* 
         * @dev check whether the pool has sufficient amount of bonuses available for new deposits/stakes.   
         * ----------------------------------------------------------------------------------------------
         * @param amount --> the _amount to be evaluated against.
         * ---------------------------------------------------
         * returns whether true or not.
         */ 
        function _checkForSufficientStakingBonusesForToken(uint _amount) internal view returns(bool) {
           
            if ((token.balanceOf(address(this)).sub(_pendingBonusesToken)) >= _amount) {
                
                return true;
                
            } else {
                
                return false;
            }
        }
        
        /* 
         * @dev get the timestamp of when the user balance will be released from locked term. 
         * ---------------------------------------------------------------------------------
         * @param _user --> the address of the user.
         * ---------------------------------------
         * returns the timestamp for the release.
         */     
        function getUserRelease(address _user) external view returns(uint release_time) {
            
            uint release = _users[_user].release;
            if (release > now) {
                
                return (release.sub(now));
           
            } else {
                
                return 0;
            }
            
        }
        
        /* 
         * @dev get the amount of bonuses rewarded from staking to a user.   
         * --------------------------------------------------------------
         * @param _user --> the address of the user.
         * ---------------------------------------
         * returns the amount of staking bonuses.
         */  
        function getUserBonusPending(address _user) public view returns(uint ETH_bonus, uint token_bonus) {
            
            uint takenWeth = _users[_user].wethWithdrawn;
            uint takenToken = _users[_user].tokenWithdrawn;
            
            return (_users[_user].wethBonus.sub(takenWeth), _users[_user].tokenBonus.sub(takenToken));
        }
        
        /* 
         * @dev get the amount of released bonuses rewarded from staking to a user.   
         * --------------------------------------------------------------
         * @param _user --> the address of the user.
         * ---------------------------------------
         * returns the amount of released staking bonuses.
         */  
        function getUserBonusAvailable(address _user) public view returns(uint ETH_Released, uint token_Released) {
            
            uint ETHValue = _calculateETHReleasedAmount(_user);
            uint tokenValue = _calculateTokenReleasedAmount(_user);
            
            return (ETHValue, tokenValue);
        }   
        
        /* 
         * @dev get the amount of liquidity pool tokens staked/locked by user.   
         * ------------------------------------------------------------------
         * @param _user --> the address of the user.
         * ---------------------------------------
         * returns the amount of locked liquidity.
         */   
        function getUserLPTokens(address _user) external view returns(uint user_LP) {
    
            return _users[_user].liquidity;
        }
        
        /* 
         * @dev get the lp token address for the pair.  
         * -----------------------------------------------------------
         * returns the lp address for eth/token pair.
         */ 
        function getLPAddress() external view returns(address) {
            return address(lpToken);
        }
        
        /* 
         * @dev get the amount of staking bonuses available in the pool.  
         * -----------------------------------------------------------
         * returns the amount of staking bounses available for ETH and Token.
         */ 
        function getAvailableBonus() external view returns(uint available_ETH, uint available_token) {
            
            available_ETH = (address(this).balance).sub(_pendingBonusesWeth);
            available_token = (token.balanceOf(address(this))).sub(_pendingBonusesToken);
            
            return (available_ETH, available_token);
        }
        
        /* 
         * @dev get the maximum amount of ETH allowed for provisioning.  
         * -----------------------------------------------------------
         * returns the maximum ETH allowed
         */ 
        function getCap() external view returns(uint maxETH) {
            
            return cap;
        }
        
        /* 
         * @dev checks the term period and return percentages 
         * --------------------------------------------------
         * returns term period and return percentages 
         */
        function getTermPeriodAndReturnPercentages() external view returns(
            uint Term_Period_1, uint Term_Period_2, uint Term_Period_3, uint Term_Period_4,
            uint Period_1_Return_Percentage_Token, uint Period_2_Return_Percentage_Token,
            uint Period_3_Return_Percentage_Token, uint Period_4_Return_Percentage_Token,
            uint Period_1_Return_Percentage_ETH, uint Period_2_Return_Percentage_ETH,
            uint Period_3_Return_Percentage_ETH, uint Period_4_Return_Percentage_ETH
        ) {
            
            return (
                period1, period2, period3, period4, period1RPToken, period2RPToken, period3RPToken, 
                period4RPToken,period1RPWeth, period2RPWeth, period3RPWeth, period4RPWeth);
        }
        
    }

    File 2 of 3: Token
    pragma solidity 0.6.6;
    
    /**
     * @dev Wrappers over Solidity's arithmetic operations with added overflow
     * checks.
     *
     * Arithmetic operations in Solidity wrap on overflow. This can easily result
     * in bugs, because programmers usually assume that an overflow raises an
     * error, which is the standard behavior in high level programming languages.
     * `SafeMath` restores this intuition by reverting the transaction when an
     * operation overflows.
     *
     * Using this library instead of the unchecked operations eliminates an entire
     * class of bugs, so it's recommended to use it always.
     */
    library SafeMath {
        /**
         * @dev Returns the addition of two unsigned integers, reverting on
         * overflow.
         *
         * Counterpart to Solidity's `+` operator.
         *
         * Requirements:
         *
         * - Addition cannot overflow.
         */
        function add(uint256 a, uint256 b) internal pure returns (uint256) {
            uint256 c = a + b;
            require(c >= a, "SafeMath: addition overflow");
    
            return c;
        }
    
        /**
         * @dev Returns the subtraction of two unsigned integers, reverting on
         * overflow (when the result is negative).
         *
         * Counterpart to Solidity's `-` operator.
         *
         * Requirements:
         *
         * - Subtraction cannot overflow.
         */
        function sub(uint256 a, uint256 b) internal pure returns (uint256) {
            return sub(a, b, "SafeMath: subtraction overflow");
        }
    
        /**
         * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
         * overflow (when the result is negative).
         *
         * Counterpart to Solidity's `-` operator.
         *
         * Requirements:
         *
         * - Subtraction cannot overflow.
         */
        function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b <= a, errorMessage);
            uint256 c = a - b;
    
            return c;
        }
    
        /**
         * @dev Returns the multiplication of two unsigned integers, reverting on
         * overflow.
         *
         * Counterpart to Solidity's `*` operator.
         *
         * Requirements:
         *
         * - Multiplication cannot overflow.
         */
        function mul(uint256 a, uint256 b) internal pure returns (uint256) {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) {
                return 0;
            }
    
            uint256 c = a * b;
            require(c / a == b, "SafeMath: multiplication overflow");
    
            return c;
        }
    
        /**
         * @dev Returns the integer division of two unsigned integers. Reverts on
         * division by zero. The result is rounded towards zero.
         *
         * Counterpart to Solidity's `/` operator. Note: this function uses a
         * `revert` opcode (which leaves remaining gas untouched) while Solidity
         * uses an invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function div(uint256 a, uint256 b) internal pure returns (uint256) {
            return div(a, b, "SafeMath: division by zero");
        }
    
        /**
         * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
         * division by zero. The result is rounded towards zero.
         *
         * Counterpart to Solidity's `/` operator. Note: this function uses a
         * `revert` opcode (which leaves remaining gas untouched) while Solidity
         * uses an invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b > 0, errorMessage);
            uint256 c = a / b;
            // assert(a == b * c + a % b); // There is no case in which this doesn't hold
    
            return c;
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
         * Reverts when dividing by zero.
         *
         * Counterpart to Solidity's `%` operator. This function uses a `revert`
         * opcode (which leaves remaining gas untouched) while Solidity uses an
         * invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function mod(uint256 a, uint256 b) internal pure returns (uint256) {
            return mod(a, b, "SafeMath: modulo by zero");
        }
    
        /**
         * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
         * Reverts with custom message when dividing by zero.
         *
         * Counterpart to Solidity's `%` operator. This function uses a `revert`
         * opcode (which leaves remaining gas untouched) while Solidity uses an
         * invalid opcode to revert (consuming all remaining gas).
         *
         * Requirements:
         *
         * - The divisor cannot be zero.
         */
        function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
            require(b != 0, errorMessage);
            return a % b;
        }
    }
    
    
    interface IUniswapV2Router01 {
      function factory() external pure returns (address);
    
      function WETH() external pure returns (address);
    
      function addLiquidity(
        address tokenA,
        address tokenB,
        uint256 amountADesired,
        uint256 amountBDesired,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
      )
        external
        returns (
          uint256 amountA,
          uint256 amountB,
          uint256 liquidity
        );
    
      function addLiquidityETH(
        address token,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
      )
        external
        payable
        returns (
          uint256 amountToken,
          uint256 amountETH,
          uint256 liquidity
        );
    
      function removeLiquidity(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
      ) external returns (uint256 amountA, uint256 amountB);
    
      function removeLiquidityETH(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
      ) external returns (uint256 amountToken, uint256 amountETH);
    
      function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
      ) external returns (uint256 amountA, uint256 amountB);
    
      function removeLiquidityETHWithPermit(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
      ) external returns (uint256 amountToken, uint256 amountETH);
    
      function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external returns (uint256[] memory amounts);
    
      function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external returns (uint256[] memory amounts);
    
      function swapExactETHForTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external payable returns (uint256[] memory amounts);
    
      function swapTokensForExactETH(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external returns (uint256[] memory amounts);
    
      function swapExactTokensForETH(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external returns (uint256[] memory amounts);
    
      function swapETHForExactTokens(
        uint256 amountOut,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external payable returns (uint256[] memory amounts);
    
      function quote(
        uint256 amountA,
        uint256 reserveA,
        uint256 reserveB
      ) external pure returns (uint256 amountB);
    
      function getAmountOut(
        uint256 amountIn,
        uint256 reserveIn,
        uint256 reserveOut
      ) external pure returns (uint256 amountOut);
    
      function getAmountIn(
        uint256 amountOut,
        uint256 reserveIn,
        uint256 reserveOut
      ) external pure returns (uint256 amountIn);
    
      function getAmountsOut(uint256 amountIn, address[] calldata path)
        external
        view
        returns (uint256[] memory amounts);
    
      function getAmountsIn(uint256 amountOut, address[] calldata path)
        external
        view
        returns (uint256[] memory amounts);
    }
    
    
    interface IUniswapV2Router02 is IUniswapV2Router01 {
      function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline
      ) external returns (uint256 amountETH);
    
      function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountETHMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
      ) external returns (uint256 amountETH);
    
      function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external;
    
      function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external payable;
    
      function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
      ) external;
    }
    
    
    /**
     * @dev Interface of the ERC20 standard as defined in the EIP.
     */
    interface IERC20 {
      /**
       * @dev Returns the amount of tokens in existence.
       */
      function totalSupply() external view returns (uint256);
    
      /**
       * @dev Returns the amount of tokens owned by `account`.
       */
      function balanceOf(address account) external view returns (uint256);
    
      /**
       * @dev Moves `amount` tokens from the caller's account to `recipient`.
       *
       * Returns a boolean value indicating whether the operation succeeded.
       *
       * Emits a {Transfer} event.
       */
      function transfer(address recipient, uint256 amount) external returns (bool);
    
      /**
       * @dev Returns the remaining number of tokens that `spender` will be
       * allowed to spend on behalf of `owner` through {transferFrom}. This is
       * zero by default.
       *
       * This value changes when {approve} or {transferFrom} are called.
       */
      function allowance(address owner, address spender)
        external
        view
        returns (uint256);
    
      /**
       * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
       *
       * Returns a boolean value indicating whether the operation succeeded.
       *
       * IMPORTANT: Beware that changing an allowance with this method brings the risk
       * that someone may use both the old and the new allowance by unfortunate
       * transaction ordering. One possible solution to mitigate this race
       * condition is to first reduce the spender's allowance to 0 and set the
       * desired value afterwards:
       * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
       *
       * Emits an {Approval} event.
       */
      function approve(address spender, uint256 amount) external returns (bool);
    
      /**
       * @dev Moves `amount` tokens from `sender` to `recipient` using the
       * allowance mechanism. `amount` is then deducted from the caller's
       * allowance.
       *
       * Returns a boolean value indicating whether the operation succeeded.
       *
       * Emits a {Transfer} event.
       */
      function transferFrom(
        address sender,
        address recipient,
        uint256 amount
      ) external returns (bool);
    
      /**
       * @dev Emitted when `value` tokens are moved from one account (`from`) to
       * another (`to`).
       *
       * Note that `value` may be zero.
       */
      event Transfer(address indexed from, address indexed to, uint256 value);
    
      /**
       * @dev Emitted when the allowance of a `spender` for an `owner` is set by
       * a call to {approve}. `value` is the new allowance.
       */
      event Approval(address indexed owner, address indexed spender, uint256 value);
    }
    
    
    /**
     * @dev Implementation of the {IERC20} interface.
     *
     * This implementation is agnostic to the way tokens are created. This means
     * that a supply mechanism has to be added in a derived contract using {_mint}.
     * For a generic mechanism see {ERC20PresetMinterPauser}.
     *
     * TIP: For a detailed writeup see our guide
     * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
     * to implement supply mechanisms].
     *
     * We have followed general OpenZeppelin guidelines: functions revert instead
     * of returning `false` on failure. This behavior is nonetheless conventional
     * and does not conflict with the expectations of ERC20 applications.
     *
     * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
     * This allows applications to reconstruct the allowance for all accounts just
     * by listening to said events. Other implementations of the EIP may not emit
     * these events, as it isn't required by the specification.
     *
     * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
     * functions have been added to mitigate the well-known issues around setting
     * allowances. See {IERC20-approve}.
     */
    contract ERC20 is IERC20 {
      using SafeMath for uint256;
    
      mapping(address => uint256) private _balances;
    
      mapping(address => mapping(address => uint256)) private _allowances;
    
      uint256 private _totalSupply;
    
      string private _name;
      string private _symbol;
      uint8 private _decimals;
    
      /**
       * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
       * a default value of 18.
       *
       * To select a different value for {decimals}, use {_setupDecimals}.
       *
       * All three of these values are immutable: they can only be set once during
       * construction.
       */
      constructor(string memory name, string memory symbol) public {
        _name = name;
        _symbol = symbol;
        _decimals = 18;
      }
    
      /**
       * @dev Returns the name of the token.
       */
      function name() public view returns (string memory) {
        return _name;
      }
    
      /**
       * @dev Returns the symbol of the token, usually a shorter version of the
       * name.
       */
      function symbol() public view returns (string memory) {
        return _symbol;
      }
    
      /**
       * @dev Returns the number of decimals used to get its user representation.
       * For example, if `decimals` equals `2`, a balance of `505` tokens should
       * be displayed to a user as `5,05` (`505 / 10 ** 2`).
       *
       * Tokens usually opt for a value of 18, imitating the relationship between
       * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
       * called.
       *
       * NOTE: This information is only used for _display_ purposes: it in
       * no way affects any of the arithmetic of the contract, including
       * {IERC20-balanceOf} and {IERC20-transfer}.
       */
      function decimals() public view returns (uint8) {
        return _decimals;
      }
    
      /**
       * @dev See {IERC20-totalSupply}.
       */
      function totalSupply() public override view returns (uint256) {
        return _totalSupply;
      }
    
      /**
       * @dev See {IERC20-balanceOf}.
       */
      function balanceOf(address account) public override view returns (uint256) {
        return _balances[account];
      }
    
      /**
       * @dev See {IERC20-transfer}.
       *
       * Requirements:
       *
       * - `recipient` cannot be the zero address.
       * - the caller must have a balance of at least `amount`.
       */
      function transfer(address recipient, uint256 amount)
        public
        override
        returns (bool)
      {
        _transfer(msg.sender, recipient, amount);
        return true;
      }
    
      /**
       * @dev See {IERC20-allowance}.
       */
      function allowance(address owner, address spender)
        public
        override
        view
        returns (uint256)
      {
        return _allowances[owner][spender];
      }
    
      /**
       * @dev See {IERC20-approve}.
       *
       * Requirements:
       *
       * - `spender` cannot be the zero address.
       */
      function approve(address spender, uint256 amount)
        public
        override
        returns (bool)
      {
        _approve(msg.sender, spender, amount);
        return true;
      }
    
      /**
       * @dev See {IERC20-transferFrom}.
       *
       * Emits an {Approval} event indicating the updated allowance. This is not
       * required by the EIP. See the note at the beginning of {ERC20};
       *
       * Requirements:
       * - `sender` and `recipient` cannot be the zero address.
       * - `sender` must have a balance of at least `amount`.
       * - the caller must have allowance for ``sender``'s tokens of at least
       * `amount`.
       */
      function transferFrom(
        address sender,
        address recipient,
        uint256 amount
      ) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(
          sender,
          msg.sender,
          _allowances[sender][msg.sender].sub(
            amount,
            'ERC20: transfer amount exceeds allowance'
          )
        );
        return true;
      }
    
      /**
       * @dev Atomically increases the allowance granted to `spender` by the caller.
       *
       * This is an alternative to {approve} that can be used as a mitigation for
       * problems described in {IERC20-approve}.
       *
       * Emits an {Approval} event indicating the updated allowance.
       *
       * Requirements:
       *
       * - `spender` cannot be the zero address.
       */
      function increaseAllowance(address spender, uint256 addedValue)
        public
        returns (bool)
      {
        _approve(
          msg.sender,
          spender,
          _allowances[msg.sender][spender].add(addedValue)
        );
        return true;
      }
    
      /**
       * @dev Atomically decreases the allowance granted to `spender` by the caller.
       *
       * This is an alternative to {approve} that can be used as a mitigation for
       * problems described in {IERC20-approve}.
       *
       * Emits an {Approval} event indicating the updated allowance.
       *
       * Requirements:
       *
       * - `spender` cannot be the zero address.
       * - `spender` must have allowance for the caller of at least
       * `subtractedValue`.
       */
      function decreaseAllowance(address spender, uint256 subtractedValue)
        public
        virtual
        returns (bool)
      {
        _approve(
          msg.sender,
          spender,
          _allowances[msg.sender][spender].sub(
            subtractedValue,
            'ERC20: decreased allowance below zero'
          )
        );
        return true;
      }
    
      /**
       * @dev Moves tokens `amount` from `sender` to `recipient`.
       *
       * This is internal function is equivalent to {transfer}, and can be used to
       * e.g. implement automatic token fees, slashing mechanisms, etc.
       *
       * Emits a {Transfer} event.
       *
       * Requirements:
       *
       * - `sender` cannot be the zero address.
       * - `recipient` cannot be the zero address.
       * - `sender` must have a balance of at least `amount`.
       */
      function _transfer(
        address sender,
        address recipient,
        uint256 amount
      ) internal virtual {
        require(sender != address(0), 'ERC20: transfer from the zero address');
        require(recipient != address(0), 'ERC20: transfer to the zero address');
        _balances[sender] = _balances[sender].sub(
          amount,
          'ERC20: transfer amount exceeds balance'
        );
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
      }
    
      /** @dev Creates `amount` tokens and assigns them to `account`, increasing
       * the total supply.
       *
       * Emits a {Transfer} event with `from` set to the zero address.
       *
       * Requirements
       *
       * - `to` cannot be the zero address.
       */
      function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), 'ERC20: mint to the zero address');
        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
      }
    
      /**
       * @dev Destroys `amount` tokens from `account`, reducing the
       * total supply.
       *
       * Emits a {Transfer} event with `to` set to the zero address.
       *
       * Requirements
       *
       * - `account` cannot be the zero address.
       * - `account` must have at least `amount` tokens.
       */
      function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), 'ERC20: burn from the zero address');
        _balances[account] = _balances[account].sub(
          amount,
          'ERC20: burn amount exceeds balance'
        );
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(account, address(0), amount);
      }
    
      /**
       * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
       *
       * This is internal function is equivalent to `approve`, and can be used to
       * e.g. set automatic allowances for certain subsystems, etc.
       *
       * Emits an {Approval} event.
       *
       * Requirements:
       *
       * - `owner` cannot be the zero address.
       * - `spender` cannot be the zero address.
       */
      function _approve(
        address owner,
        address spender,
        uint256 amount
      ) internal virtual {
        require(owner != address(0), 'ERC20: approve from the zero address');
        require(spender != address(0), 'ERC20: approve to the zero address');
    
        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
      }
    }
    
    
    /**
     * @dev Extension of {ERC20} that allows token holders to destroy both their own
     * tokens and those that they have an allowance for, in a way that can be
     * recognized off-chain (via event analysis).
     */
    abstract contract ERC20Burnable is ERC20 {
      /**
       * @dev Destroys `amount` tokens from the caller.
       *
       * See {ERC20-_burn}.
       */
      function burn(uint256 amount) public virtual {
        _burn(msg.sender, amount);
      }
    
      /**
       * @dev Destroys `amount` tokens from `account`, deducting from the caller's
       * allowance.
       *
       * See {ERC20-_burn} and {ERC20-allowance}.
       *
       * Requirements:
       *
       * - the caller must have allowance for ``accounts``'s tokens of at least
       * `amount`.
       */
      function burnFrom(address account, uint256 amount) public virtual {
        uint256 decreasedAllowance = allowance(account, msg.sender).sub(
          amount,
          'ERC20: burn amount exceeds allowance'
        );
        _approve(account, msg.sender, decreasedAllowance);
        _burn(account, amount);
      }
    }
    
    
    /* 
     * @dev Implementation of a token compliant with the ERC20 Token protocol;
     * The token has additional burn functionality. 
     */
    contract Token is ERC20Burnable {
      using SafeMath for uint256;
    
      /* 
     * @dev Initialization of the token, 
     * following arguments are provided via the constructor: name, symbol, recipient, totalSupply.
     * The total supply of tokens is minted to the specified recipient.
     */
      constructor(
        string memory name,
        string memory symbol,
        address recipient,
        uint256 totalSupply
      ) public ERC20(name, symbol) {
        _mint(recipient, totalSupply);
      }
    }
    
    
    /* 
     * @dev Implementation of the Initial Stake Offering (ISO). 
     * The ISO is a decentralized token offering with trustless liquidity provisioning, 
     * dividend accumulation and bonus rewards from staking.
     */
    contract UnistakeTokenSale {
      using SafeMath for uint256;
    
      struct Contributor {
            uint256 phase;
            uint256 remainder;
            uint256 fromTotalDivs;
        }
      
      address payable public immutable wallet;
    
      uint256 public immutable totalSupplyR1;
      uint256 public immutable totalSupplyR2;
      uint256 public immutable totalSupplyR3;
    
      uint256 public immutable totalSupplyUniswap;
    
      uint256 public immutable rateR1;
      uint256 public immutable rateR2;
      uint256 public immutable rateR3;
    
      uint256 public immutable periodDurationR3;
    
      uint256 public immutable timeDelayR1;
      uint256 public immutable timeDelayR2;
    
      uint256 public immutable stakingPeriodR1;
      uint256 public immutable stakingPeriodR2;
      uint256 public immutable stakingPeriodR3;
    
      Token public immutable token;
      IUniswapV2Router02 public immutable uniswapRouter;
    
      uint256 public immutable decreasingPctToken;
      uint256 public immutable decreasingPctETH;
      uint256 public immutable decreasingPctRate;
      uint256 public immutable decreasingPctBonus;
      
      uint256 public immutable listingRate;
      address public immutable platformStakingContract;
    
      mapping(address => bool)        private _contributor;
      mapping(address => Contributor) private _contributors;
      mapping(address => uint256)[3]  private _contributions;
      
      bool[3]    private _hasEnded;
      uint256[3] private _actualSupply;
    
      uint256 private _startTimeR2 = 2**256 - 1;
      uint256 private _startTimeR3 = 2**256 - 1;
      uint256 private _endTimeR3   = 2**256 - 1;
    
      mapping(address => bool)[3] private _hasWithdrawn;
    
      bool    private _bonusOfferingActive;
      uint256 private _bonusOfferingActivated;
      uint256 private _bonusTotal;
      
      uint256 private _contributionsTotal;
    
      uint256 private _contributorsTotal;
      uint256 private _contributedFundsTotal;
     
      uint256 private _bonusReductionFactor;
      uint256 private _fundsWithdrawn;
      
      uint256 private _endedDayR3;
      
      uint256 private _latestStakingPlatformPayment;
      
      uint256 private _totalDividends;
      uint256 private _scaledRemainder;
      uint256 private _scaling = uint256(10) ** 12;
      uint256 private _phase = 1;
      uint256 private _totalRestakedDividends;
      
      mapping(address => uint256) private _restkedDividends;
      mapping(uint256 => uint256) private _payouts;         
    
      
      event Staked(
          address indexed account, 
          uint256 amount);
          
      event Claimed(
          address indexed account, 
          uint256 amount);
          
      event Reclaimed(
          address indexed account, 
          uint256 amount);
          
      event Withdrawn(
          address indexed account, 
          uint256 amount); 
          
      event Penalized(
          address indexed account, 
          uint256 amount);
          
      event Ended(
          address indexed account, 
          uint256 amount, 
          uint256 time);
          
      event Splitted(
          address indexed account, 
          uint256 amount1, 
          uint256 amount2);  
      
      event Bought(
          uint8 indexed round, 
          address indexed account,
          uint256 amount);
          
      event Activated(
          bool status, 
          uint256 time);
    
    
      /* 
     * @dev Initialization of the ISO,
     * following arguments are provided via the constructor: 
     * ----------------------------------------------------
     * tokenArg                    - token offered in the ISO.
     * totalSupplyArg              - total amount of tokens allocated for each round.
     * totalSupplyUniswapArg       - amount of tokens that will be sent to uniswap.
     * ratesArg                    - contribution ratio ETH:Token for each round.
     * periodDurationR3            - duration of a day during round 3.
     * timeDelayR1Arg              - time delay between round 1 and round 2.
     * timeDelayR2Arg              - time delay between round 2 and round 3.
     * stakingPeriodArg            - staking duration required to get bonus tokens for each round.
     * uniswapRouterArg            - contract address of the uniswap router object.
     * decreasingPctArg            - decreasing percentages associated with: token, ETH, rate, and bonus.
     * listingRateArg              - initial listing rate of the offered token.
     * platformStakingContractArg  - contract address of the timed distribution contract.
     * walletArg                   - account address of the team wallet.
     * 
     */
      constructor(
        address tokenArg,
        uint256[3] memory totalSupplyArg,
        uint256 totalSupplyUniswapArg,
        uint256[3] memory ratesArg,
        uint256 periodDurationR3Arg,
        uint256 timeDelayR1Arg,
        uint256 timeDelayR2Arg,
        uint256[3] memory stakingPeriodArg,
        address uniswapRouterArg,
        uint256[4] memory decreasingPctArg,
        uint256 listingRateArg,
        address platformStakingContractArg,
        address payable walletArg
        ) public {
        for (uint256 j = 0; j < 3; j++) {
            require(totalSupplyArg[j] > 0, 
            "The 'totalSupplyArg' argument must be larger than zero");
            require(ratesArg[j] > 0, 
            "The 'ratesArg' argument must be larger than zero");
            require(stakingPeriodArg[j] > 0, 
            "The 'stakingPeriodArg' argument must be larger than zero");
        }
        for (uint256 j = 0; j < 4; j++) {
            require(decreasingPctArg[j] < 10000, 
            "The 'decreasingPctArg' arguments must be less than 100 percent");
        }
        require(totalSupplyUniswapArg > 0, 
        "The 'totalSupplyUniswapArg' argument must be larger than zero");
        require(periodDurationR3Arg > 0, 
        "The 'slotDurationR3Arg' argument must be larger than zero");
        require(tokenArg != address(0), 
        "The 'tokenArg' argument cannot be the zero address");
        require(uniswapRouterArg != address(0), 
        "The 'uniswapRouterArg' argument cannot be the zero addresss");
        require(listingRateArg > 0,
        "The 'listingRateArg' argument must be larger than zero");
        require(platformStakingContractArg != address(0), 
        "The 'vestingContractArg' argument cannot be the zero address");
        require(walletArg != address(0), 
        "The 'walletArg' argument cannot be the zero address");
        
        token = Token(tokenArg);
        
        totalSupplyR1 = totalSupplyArg[0];
        totalSupplyR2 = totalSupplyArg[1];
        totalSupplyR3 = totalSupplyArg[2];
        
        totalSupplyUniswap = totalSupplyUniswapArg;
        
        periodDurationR3 = periodDurationR3Arg;
        
        timeDelayR1 = timeDelayR1Arg;
        timeDelayR2 = timeDelayR2Arg;
        
        rateR1 = ratesArg[0];
        rateR2 = ratesArg[1];
        rateR3 = ratesArg[2];
        
        stakingPeriodR1 = stakingPeriodArg[0];
        stakingPeriodR2 = stakingPeriodArg[1];
        stakingPeriodR3 = stakingPeriodArg[2];
        
        uniswapRouter = IUniswapV2Router02(uniswapRouterArg);
        
        decreasingPctToken = decreasingPctArg[0];
        decreasingPctETH = decreasingPctArg[1];
        decreasingPctRate = decreasingPctArg[2];
        decreasingPctBonus = decreasingPctArg[3];
        
        listingRate = listingRateArg;
        
        platformStakingContract = platformStakingContractArg;
        wallet = walletArg;
      }
      
      /**
       * @dev The fallback function is used for all contributions
       * during the ISO. The function monitors the current 
       * round and manages token contributions accordingly.
       */
      receive() external payable {
          if (token.balanceOf(address(this)) > 0) {
              uint8 currentRound = _calculateCurrentRound();
              
              if (currentRound == 0) {
                  _buyTokenR1();
              } else if (currentRound == 1) {
                  _buyTokenR2();
              } else if (currentRound == 2) {
                  _buyTokenR3();
              } else {
                  revert("The stake offering rounds are not active");
              }
        } else {
            revert("The stake offering must be active");
        }
      }
      
      /**
       * @dev Wrapper around the round 3 closing function.
       */     
      function closeR3() external {
          uint256 period = _calculatePeriod(block.timestamp);
          _closeR3(period);
      }
      
      /**
       * @dev This function prepares the staking and bonus reward settings
       * and it also provides liquidity to a freshly created uniswap pair.
       */  
      function activateStakesAndUniswapLiquidity() external {
          require(_hasEnded[0] && _hasEnded[1] && _hasEnded[2], 
          "all rounds must have ended");
          require(!_bonusOfferingActive, 
          "the bonus offering and uniswap paring can only be done once per ISO");
          
          uint256[3] memory bonusSupplies = [
              (_actualSupply[0].mul(_bonusReductionFactor)).div(10000),
              (_actualSupply[1].mul(_bonusReductionFactor)).div(10000),
              (_actualSupply[2].mul(_bonusReductionFactor)).div(10000)
              ];
              
          uint256 totalSupply = totalSupplyR1.add(totalSupplyR2).add(totalSupplyR3);
          uint256 soldSupply = _actualSupply[0].add(_actualSupply[1]).add(_actualSupply[2]);
          uint256 unsoldSupply = totalSupply.sub(soldSupply);
              
          uint256 exceededBonus = totalSupply
          .sub(bonusSupplies[0])
          .sub(bonusSupplies[1])
          .sub(bonusSupplies[2]);
          
          uint256 exceededUniswapAmount = _createUniswapPair(_endedDayR3); 
          
          _bonusOfferingActive = true;
          _bonusOfferingActivated = block.timestamp;
          _bonusTotal = bonusSupplies[0].add(bonusSupplies[1]).add(bonusSupplies[2]);
          _contributionsTotal = soldSupply;
          
          _distribute(unsoldSupply.add(exceededBonus).add(exceededUniswapAmount));
         
          emit Activated(true, block.timestamp);
      }
      
      /**
       * @dev This function allows the caller to stake claimable dividends.
       */   
      function restakeDividends() external {
          uint256 pending = _pendingDividends(msg.sender);
          pending = pending.add(_contributors[msg.sender].remainder);
          require(pending >= 0, "You do not have dividends to restake");
          _restkedDividends[msg.sender] = _restkedDividends[msg.sender].add(pending);
          _totalRestakedDividends = _totalRestakedDividends.add(pending);
          _bonusTotal = _bonusTotal.sub(pending);
    
          _contributors[msg.sender].phase = _phase;
          _contributors[msg.sender].remainder = 0;
          _contributors[msg.sender].fromTotalDivs = _totalDividends;
          
          emit Staked(msg.sender, pending);
      }
    
      /**
       * @dev This function is called by contributors to 
       * withdraw round 1 tokens. 
       * -----------------------------------------------------
       * Withdrawing tokens might result in bonus tokens, dividends,
       * or similar (based on the staking duration of the contributor).
       * 
       */  
      function withdrawR1Tokens() external {
          require(_bonusOfferingActive, 
          "The bonus offering is not active yet");
          
          _withdrawTokens(0);
      }
     
      /**
       * @dev This function is called by contributors to 
       * withdraw round 2 tokens. 
       * -----------------------------------------------------
       * Withdrawing tokens might result in bonus tokens, dividends,
       * or similar (based on the staking duration of the contributor).
       * 
       */      
      function withdrawR2Tokens() external {
          require(_bonusOfferingActive, 
          "The bonus offering is not active yet");
          
          _withdrawTokens(1);
      }
     
      /**
       * @dev This function is called by contributors to 
       * withdraw round 3 tokens. 
       * -----------------------------------------------------
       * Withdrawing tokens might result in bonus tokens, dividends,
       * or similar (based on the staking duration of the contributor).
       * 
       */   
      function withdrawR3Tokens() external {
          require(_bonusOfferingActive, 
          "The bonus offering is not active yet");  
    
          _withdrawTokens(2);
      }
     
      /**
       * @dev wrapper around the withdrawal of funds function. 
       */    
      function withdrawFunds() external {
          uint256 amount = ((address(this).balance).sub(_fundsWithdrawn)).div(2);
          
          _withdrawFunds(amount);
      }  
     
      /**
       * @dev Returns the total amount of restaked dividends in the ISO.
       */    
      function getRestakedDividendsTotal() external view returns (uint256) { 
          return _totalRestakedDividends;
      }
      
      /**
       * @dev Returns the total staking bonuses in the ISO. 
       */     
      function getStakingBonusesTotal() external view returns (uint256) {
          return _bonusTotal;
      }
    
      /**
       * @dev Returns the latest amount of tokens sent to the timed distribution contract.  
       */    
      function getLatestStakingPlatformPayment() external view returns (uint256) {
          return _latestStakingPlatformPayment;
      }
     
      /**
       * @dev Returns the current day of round 3.
       */   
      function getCurrentDayR3() external view returns (uint256) {
          if (_endedDayR3 != 0) {
              return _endedDayR3;
          }
          return _calculatePeriod(block.timestamp);
      }
    
      /**
       * @dev Returns the ending day of round 3. 
       */    
      function getEndedDayR3() external view returns (uint256) {
          return _endedDayR3;
      }
    
      /**
       * @dev Returns the start time of round 2. 
       */    
      function getR2Start() external view returns (uint256) {
          return _startTimeR2;
      }
    
      /**
       * @dev Returns the start time of round 3. 
       */  
      function getR3Start() external view returns (uint256) {
          return _startTimeR3;
      }
    
      /**
       * @dev Returns the end time of round 3. 
       */  
      function getR3End() external view returns (uint256) {
          return _endTimeR3;
      }
    
      /**
       * @dev Returns the total amount of contributors in the ISO. 
       */  
      function getContributorsTotal() external view returns (uint256) {
          return _contributorsTotal;
      }
    
      /**
       * @dev Returns the total amount of contributed funds (ETH) in the ISO 
       */  
      function getContributedFundsTotal() external view returns (uint256) {
          return _contributedFundsTotal;
      }
      
      /**
       * @dev Returns the current round of the ISO. 
       */  
      function getCurrentRound() external view returns (uint8) {
          uint8 round = _calculateCurrentRound();
          
          if (round == 0 && !_hasEnded[0]) {
              return 1;
          } 
          if (round == 1 && !_hasEnded[1] && _hasEnded[0]) {
              if (block.timestamp <= _startTimeR2) {
                  return 0;
              }
              return 2;
          }
          if (round == 2 && !_hasEnded[2] && _hasEnded[1]) {
              if (block.timestamp <= _startTimeR3) {
                  return 0;
              }
              return 3;
          } 
          else {
              return 0;
          }
      }
    
      /**
       * @dev Returns whether round 1 has ended or not. 
       */   
      function hasR1Ended() external view returns (bool) {
          return _hasEnded[0];
      }
    
      /**
       * @dev Returns whether round 2 has ended or not. 
       */   
      function hasR2Ended() external view returns (bool) {
          return _hasEnded[1];
      }
    
      /**
       * @dev Returns whether round 3 has ended or not. 
       */   
      function hasR3Ended() external view returns (bool) { 
          return _hasEnded[2];
      }
    
      /**
       * @dev Returns the remaining time delay between round 1 and round 2.
       */    
      function getRemainingTimeDelayR1R2() external view returns (uint256) {
          if (timeDelayR1 > 0) {
              if (_hasEnded[0] && !_hasEnded[1]) {
                  if (_startTimeR2.sub(block.timestamp) > 0) {
                      return _startTimeR2.sub(block.timestamp);
                  } else {
                      return 0;
                  }
              } else {
                  return 0;
              }
          } else {
              return 0;
          }
      }
    
      /**
       * @dev Returns the remaining time delay between round 2 and round 3.
       */  
      function getRemainingTimeDelayR2R3() external view returns (uint256) {
          if (timeDelayR2 > 0) {
              if (_hasEnded[0] && _hasEnded[1] && !_hasEnded[2]) {
                  if (_startTimeR3.sub(block.timestamp) > 0) {
                      return _startTimeR3.sub(block.timestamp);
                  } else {
                      return 0;
                  }
              } else {
                  return 0;
              }
          } else {
              return 0;
          }
      }
    
      /**
       * @dev Returns the total sales for round 1.
       */  
      function getR1Sales() external view returns (uint256) {
          return _actualSupply[0];
      }
    
      /**
       * @dev Returns the total sales for round 2.
       */  
      function getR2Sales() external view returns (uint256) {
          return _actualSupply[1];
      }
    
      /**
       * @dev Returns the total sales for round 3.
       */  
      function getR3Sales() external view returns (uint256) {
          return _actualSupply[2];
      }
    
      /**
       * @dev Returns whether the staking- and bonus functionality has been activated or not.
       */    
      function getStakingActivationStatus() external view returns (bool) {
          return _bonusOfferingActive;
      }
      
      /**
       * @dev This function allows the caller to withdraw claimable dividends.
       */    
      function claimDividends() public {
          if (_totalDividends > _contributors[msg.sender].fromTotalDivs) {
              uint256 pending = _pendingDividends(msg.sender);
              pending = pending.add(_contributors[msg.sender].remainder);
              require(pending >= 0, "You do not have dividends to claim");
              
              _contributors[msg.sender].phase = _phase;
              _contributors[msg.sender].remainder = 0;
              _contributors[msg.sender].fromTotalDivs = _totalDividends;
              
              _bonusTotal = _bonusTotal.sub(pending);
    
              require(token.transfer(msg.sender, pending), "Error in sending reward from contract");
    
              emit Claimed(msg.sender, pending);
    
          }
      }
    
      /**
       * @dev This function allows the caller to withdraw restaked dividends.
       */     
      function withdrawRestakedDividends() public {
          uint256 amount = _restkedDividends[msg.sender];
          require(amount >= 0, "You do not have restaked dividends to withdraw");
          
          claimDividends();
          
          _restkedDividends[msg.sender] = 0;
          _totalRestakedDividends = _totalRestakedDividends.sub(amount);
          
          token.transfer(msg.sender, amount);      
          
          emit Reclaimed(msg.sender, amount);
      }    
      
      /**
       * @dev Returns claimable dividends.
       */    
      function getDividends(address accountArg) public view returns (uint256) {
          uint256 amount = ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))).div(_scaling);
          amount += ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))) % _scaling ;
          return (amount.add(_contributors[msg.sender].remainder));
      }
     
      /**
       * @dev Returns restaked dividends.
       */   
      function getRestakedDividends(address accountArg) public view returns (uint256) { 
          return _restkedDividends[accountArg];
      }
    
      /**
       * @dev Returns round 1 contributions of an account. 
       */  
      function getR1Contribution(address accountArg) public view returns (uint256) {
          return _contributions[0][accountArg];
      }
      
      /**
       * @dev Returns round 2 contributions of an account. 
       */    
      function getR2Contribution(address accountArg) public view returns (uint256) {
          return _contributions[1][accountArg];
      }
      
      /**
       * @dev Returns round 3 contributions of an account. 
       */  
      function getR3Contribution(address accountArg) public view returns (uint256) { 
          return _contributions[2][accountArg];
      }
    
      /**
       * @dev Returns the total contributions of an account. 
       */    
      function getContributionTotal(address accountArg) public view returns (uint256) {
          uint256 contributionR1 = getR1Contribution(accountArg);
          uint256 contributionR2 = getR2Contribution(accountArg);
          uint256 contributionR3 = getR3Contribution(accountArg);
          uint256 restaked = getRestakedDividends(accountArg);
    
          return contributionR1.add(contributionR2).add(contributionR3).add(restaked);
      }
    
      /**
       * @dev Returns the total contributions in the ISO (including restaked dividends). 
       */    
      function getContributionsTotal() public view returns (uint256) {
          return _contributionsTotal.add(_totalRestakedDividends);
      }
    
      /**
       * @dev Returns expected round 1 staking bonus for an account. 
       */  
      function getStakingBonusR1(address accountArg) public view returns (uint256) {
          uint256 contribution = _contributions[0][accountArg];
          
          return (contribution.mul(_bonusReductionFactor)).div(10000);
      }
    
      /**
       * @dev Returns expected round 2 staking bonus for an account. 
       */ 
      function getStakingBonusR2(address accountArg) public view returns (uint256) {
          uint256 contribution = _contributions[1][accountArg];
          
          return (contribution.mul(_bonusReductionFactor)).div(10000);
      }
    
      /**
       * @dev Returns expected round 3 staking bonus for an account. 
       */ 
      function getStakingBonusR3(address accountArg) public view returns (uint256) {
          uint256 contribution = _contributions[2][accountArg];
          
          return (contribution.mul(_bonusReductionFactor)).div(10000);
      }
    
      /**
       * @dev Returns the total expected staking bonuses for an account. 
       */   
      function getStakingBonusTotal(address accountArg) public view returns (uint256) {
          uint256 stakeR1 = getStakingBonusR1(accountArg);
          uint256 stakeR2 = getStakingBonusR2(accountArg);
          uint256 stakeR3 = getStakingBonusR3(accountArg);
    
          return stakeR1.add(stakeR2).add(stakeR3);
     }   
    
      /**
       * @dev This function handles distribution of extra supply.
       */    
      function _distribute(uint256 amountArg) private {
          uint256 vested = amountArg.div(2);
          uint256 burned = amountArg.sub(vested);
          
          token.transfer(platformStakingContract, vested);
          token.burn(burned);
      }
    
      /**
       * @dev This function handles calculation of token withdrawals
       * (it also withdraws dividends and restaked dividends 
       * during certain circumstances).
       */    
      function _withdrawTokens(uint8 indexArg) private {
          require(_hasEnded[0] && _hasEnded[1] && _hasEnded[2], 
          "The rounds must be inactive before any tokens can be withdrawn");
          require(!_hasWithdrawn[indexArg][msg.sender], 
          "The caller must have withdrawable tokens available from this round");
          
          claimDividends();
          
          uint256 amount = _contributions[indexArg][msg.sender];
          uint256 amountBonus = (amount.mul(_bonusReductionFactor)).div(10000);
          
          _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].sub(amount);
          _contributionsTotal = _contributionsTotal.sub(amount);
          
          uint256 contributions = getContributionTotal(msg.sender);
          uint256 restaked = getRestakedDividends(msg.sender);
          
          if (contributions.sub(restaked) == 0) withdrawRestakedDividends();
        
          uint pending = _pendingDividends(msg.sender);
          _contributors[msg.sender].remainder = (_contributors[msg.sender].remainder).add(pending);
          _contributors[msg.sender].fromTotalDivs = _totalDividends;
          _contributors[msg.sender].phase = _phase;
          
          _hasWithdrawn[indexArg][msg.sender] = true;
          
          token.transfer(msg.sender, amount);
          
          _endStake(indexArg, msg.sender, amountBonus);
      }
     
      /**
       * @dev This function handles fund withdrawals.
       */  
      function _withdrawFunds(uint256 amountArg) private {
          require(msg.sender == wallet, 
          "The caller must be the specified funds wallet of the team");
          require(amountArg <= ((address(this).balance.sub(_fundsWithdrawn)).div(2)),
          "The 'amountArg' argument exceeds the limit");
          require(!_hasEnded[2], 
          "The third round is not active");
          
          _fundsWithdrawn = _fundsWithdrawn.add(amountArg);
          
          wallet.transfer(amountArg);
      }  
    
      /**
       * @dev This function handles token purchases for round 1.
       */ 
      function _buyTokenR1() private {
          if (token.balanceOf(address(this)) > 0) {
              require(!_hasEnded[0], 
              "The first round must be active");
              
              bool isRoundEnded = _buyToken(0, rateR1, totalSupplyR1);
              
              if (isRoundEnded == true) {
                  _startTimeR2 = block.timestamp.add(timeDelayR1);
              }
          } else {
              revert("The stake offering must be active");
        }
      }
     
      /**
       * @dev This function handles token purchases for round 2.
       */   
      function _buyTokenR2() private {
          require(_hasEnded[0] && !_hasEnded[1],
          "The first round one must not be active while the second round must be active");
          require(block.timestamp >= _startTimeR2,
          "The time delay between the first round and the second round must be surpassed");
          
          bool isRoundEnded = _buyToken(1, rateR2, totalSupplyR2);
          
          if (isRoundEnded == true) {
              _startTimeR3 = block.timestamp.add(timeDelayR2);
          }
      }
     
      /**
       * @dev This function handles token purchases for round 3.
       */   
      function _buyTokenR3() private {
          require(_hasEnded[1] && !_hasEnded[2],
          "The second round one must not be active while the third round must be active");
          require(block.timestamp >= _startTimeR3,
          "The time delay between the first round and the second round must be surpassed"); 
          
          uint256 period = _calculatePeriod(block.timestamp);
          
          (bool isRoundClosed, uint256 actualPeriodTotalSupply) = _closeR3(period);
    
          if (!isRoundClosed) {
              bool isRoundEnded = _buyToken(2, rateR3, actualPeriodTotalSupply);
              
              if (isRoundEnded == true) {
                  _endTimeR3 = block.timestamp;
                  uint256 endingPeriod = _calculateEndingPeriod();
                  uint256 reductionFactor = _calculateBonusReductionFactor(endingPeriod);
                  _bonusReductionFactor = reductionFactor;
                  _endedDayR3 = endingPeriod;
              }
          }
      }
      
      /**
       * @dev This function handles bonus payouts and the split of forfeited bonuses.
       */     
      function _endStake(uint256 indexArg, address accountArg, uint256 amountArg) private {
          uint256 elapsedTime = (block.timestamp).sub(_bonusOfferingActivated);
          uint256 payout;
          
          uint256 duration = _getDuration(indexArg);
          
          if (elapsedTime >= duration) {
              payout = amountArg;
          } else if (elapsedTime >= duration.mul(3).div(4) && elapsedTime < duration) {
              payout = amountArg.mul(3).div(4);
          } else if (elapsedTime >= duration.div(2) && elapsedTime < duration.mul(3).div(4)) {
              payout = amountArg.div(2);
          } else if (elapsedTime >= duration.div(4) && elapsedTime < duration.div(2)) {
              payout = amountArg.div(4);
          } else {
              payout = 0;
          }
          
          _split(amountArg.sub(payout));
          
          if (payout != 0) {
              token.transfer(accountArg, payout);
          }
          
          emit Ended(accountArg, amountArg, block.timestamp);
      }
     
      /**
       * @dev This function splits forfeited bonuses into dividends 
       * and to timed distribution contract accordingly.
       */     
      function _split(uint256 amountArg) private {
          if (amountArg == 0) {
            return;
          }
          
          uint256 dividends = amountArg.div(2);
          uint256 platformStakingShare = amountArg.sub(dividends);
          
          _bonusTotal = _bonusTotal.sub(platformStakingShare);
          _latestStakingPlatformPayment = platformStakingShare;
          
          token.transfer(platformStakingContract, platformStakingShare);
          
          _addDividends(_latestStakingPlatformPayment);
          
          emit Splitted(msg.sender, dividends, platformStakingShare);
      }
      
       /**
       * @dev this function handles addition of new dividends.
       */   
      function _addDividends(uint256 bonusArg) private {
          uint256 latest = (bonusArg.mul(_scaling)).add(_scaledRemainder);
          uint256 dividendPerToken = latest.div(_contributionsTotal.add(_totalRestakedDividends));
          _scaledRemainder = latest.mod(_contributionsTotal.add(_totalRestakedDividends));
          _totalDividends = _totalDividends.add(dividendPerToken);
          _payouts[_phase] = _payouts[_phase-1].add(dividendPerToken);
          _phase++;
      }
      
       /**
       * @dev returns pending dividend rewards.
       */    
      function _pendingDividends(address accountArg) private returns (uint256) {
          uint256 amount = ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))).div(_scaling);
          _contributors[accountArg].remainder += ((_totalDividends.sub(_payouts[_contributors[accountArg].phase - 1])).mul(getContributionTotal(accountArg))) % _scaling ;
          return amount;
      }
      
      /**
       * @dev This function creates a uniswap pair and handles liquidity provisioning.
       * Returns the uniswap token leftovers.
       */  
      function _createUniswapPair(uint256 endingPeriodArg) private returns (uint256) {
          uint256 listingPrice = endingPeriodArg.mul(decreasingPctRate);
    
          uint256 ethDecrease = uint256(5000).sub(endingPeriodArg.mul(decreasingPctETH));
          uint256 ethOnUniswap = (_contributedFundsTotal.mul(ethDecrease)).div(10000);
          
          ethOnUniswap = ethOnUniswap <= (address(this).balance)
          ? ethOnUniswap
          : (address(this).balance);
          
          uint256 tokensOnUniswap = ethOnUniswap
          .mul(listingRate)
          .mul(10000)
          .div(uint256(10000).sub(listingPrice))
          .div(100000);
          
          token.approve(address(uniswapRouter), tokensOnUniswap);
          
          uniswapRouter.addLiquidityETH.value(ethOnUniswap)(
          address(token),
          tokensOnUniswap,
          0,
          0,
          wallet,
          block.timestamp
          );
          
          wallet.transfer(address(this).balance);
          
          return (totalSupplyUniswap.sub(tokensOnUniswap));
      } 
     
      /**
       * @dev this function will close round 3 if based on day and sold supply.
       * Returns whether a particular round has ended or not and 
       * the max supply of a particular day during round 3.
       */    
      function _closeR3(uint256 periodArg) private returns (bool isRoundEnded, uint256 maxPeriodSupply) {
          require(_hasEnded[0] && _hasEnded[1] && !_hasEnded[2],
          'Round 3 has ended or Round 1 or 2 have not ended yet');
          require(block.timestamp >= _startTimeR3,
          'Pause period between Round 2 and 3');
          
          uint256 decreasingTokenNumber = totalSupplyR3.mul(decreasingPctToken).div(10000);
          maxPeriodSupply = totalSupplyR3.sub(periodArg.mul(decreasingTokenNumber));
          
          if (maxPeriodSupply <= _actualSupply[2]) {
              msg.sender.transfer(msg.value);
              _hasEnded[2] = true;
              
              _endTimeR3 = block.timestamp;
              
              uint256 endingPeriod = _calculateEndingPeriod();
              uint256 reductionFactor = _calculateBonusReductionFactor(endingPeriod);
              
              _endedDayR3 = endingPeriod;
              
              _bonusReductionFactor = reductionFactor;
              return (true, maxPeriodSupply);
              
          } else {
              return (false, maxPeriodSupply);
          }
      }
     
      /**
       * @dev this function handles low level token purchases. 
       * Returns whether a particular round has ended or not.
       */     
      function _buyToken(uint8 indexArg, uint256 rateArg, uint256 totalSupplyArg) private returns (bool isRoundEnded) {
          uint256 tokensNumber = msg.value.mul(rateArg).div(100000);
          uint256 actualTotalBalance = _actualSupply[indexArg];
          uint256 newTotalRoundBalance = actualTotalBalance.add(tokensNumber);
          
          if (!_contributor[msg.sender]) {
              _contributor[msg.sender] = true;
              _contributorsTotal++;
          }  
          
          if (newTotalRoundBalance < totalSupplyArg) {
              _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].add(tokensNumber);
              _actualSupply[indexArg] = newTotalRoundBalance;
              _contributedFundsTotal = _contributedFundsTotal.add(msg.value);
              
              emit Bought(uint8(indexArg + 1), msg.sender, tokensNumber);
              
              return false;
              
          } else {
              uint256 availableTokens = totalSupplyArg.sub(actualTotalBalance);
              uint256 availableEth = availableTokens.mul(100000).div(rateArg);
              
              _contributions[indexArg][msg.sender] = _contributions[indexArg][msg.sender].add(availableTokens);
              _actualSupply[indexArg] = totalSupplyArg;
              _contributedFundsTotal = _contributedFundsTotal.add(availableEth);
              _hasEnded[indexArg] = true;
              
              msg.sender.transfer(msg.value.sub(availableEth));
    
              emit Bought(uint8(indexArg + 1), msg.sender, availableTokens);
              
              return true;
          }
      }
    
      /**
       * @dev Returns the staking duration of a particular round.
       */   
      function _getDuration(uint256 indexArg) private view returns (uint256) {
          if (indexArg == 0) {
              return stakingPeriodR1;
          }
          if (indexArg == 1) {
              return stakingPeriodR2;
          }
          if (indexArg == 2) {
              return stakingPeriodR3;
          }
        }
     
      /**
       * @dev Returns the bonus reduction factor.
       */       
      function _calculateBonusReductionFactor(uint256 periodArg) private view returns (uint256) {
          uint256 reductionFactor = uint256(10000).sub(periodArg.mul(decreasingPctBonus));
          return reductionFactor;
      } 
     
      /**
       * @dev Returns the current round.
       */     
      function _calculateCurrentRound() private view returns (uint8) {
          if (!_hasEnded[0]) {
              return 0;
          } else if (_hasEnded[0] && !_hasEnded[1] && !_hasEnded[2]) {
              return 1;
          } else if (_hasEnded[0] && _hasEnded[1] && !_hasEnded[2]) {
              return 2;
          } else {
              return 2**8 - 1;
          }
      }
     
      /**
       * @dev Returns the current day.
       */     
      function _calculatePeriod(uint256 timeArg) private view returns (uint256) {
          uint256 period = ((timeArg.sub(_startTimeR3)).div(periodDurationR3));
          uint256 maxPeriods = uint256(10000).div(decreasingPctToken);
          
          if (period > maxPeriods) {
              return maxPeriods;
          }
          return period;
      }
     
      /**
       * @dev Returns the ending day of round 3.
       */     
      function _calculateEndingPeriod() private view returns (uint256) {
          require(_endTimeR3 != (2**256) - 1, 
          "The third round must be active");
          
          uint256 endingPeriod = _calculatePeriod(_endTimeR3);
          return endingPeriod;
      }
     
    
      
      
      
      
      
    }

    File 3 of 3: UniswapV2Pair
    // File: contracts/interfaces/IUniswapV2Pair.sol
    
    pragma solidity >=0.5.0;
    
    interface IUniswapV2Pair {
        event Approval(address indexed owner, address indexed spender, uint value);
        event Transfer(address indexed from, address indexed to, uint value);
    
        function name() external pure returns (string memory);
        function symbol() external pure returns (string memory);
        function decimals() external pure returns (uint8);
        function totalSupply() external view returns (uint);
        function balanceOf(address owner) external view returns (uint);
        function allowance(address owner, address spender) external view returns (uint);
    
        function approve(address spender, uint value) external returns (bool);
        function transfer(address to, uint value) external returns (bool);
        function transferFrom(address from, address to, uint value) external returns (bool);
    
        function DOMAIN_SEPARATOR() external view returns (bytes32);
        function PERMIT_TYPEHASH() external pure returns (bytes32);
        function nonces(address owner) external view returns (uint);
    
        function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
    
        event Mint(address indexed sender, uint amount0, uint amount1);
        event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
        event Swap(
            address indexed sender,
            uint amount0In,
            uint amount1In,
            uint amount0Out,
            uint amount1Out,
            address indexed to
        );
        event Sync(uint112 reserve0, uint112 reserve1);
    
        function MINIMUM_LIQUIDITY() external pure returns (uint);
        function factory() external view returns (address);
        function token0() external view returns (address);
        function token1() external view returns (address);
        function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
        function price0CumulativeLast() external view returns (uint);
        function price1CumulativeLast() external view returns (uint);
        function kLast() external view returns (uint);
    
        function mint(address to) external returns (uint liquidity);
        function burn(address to) external returns (uint amount0, uint amount1);
        function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
        function skim(address to) external;
        function sync() external;
    
        function initialize(address, address) external;
    }
    
    // File: contracts/interfaces/IUniswapV2ERC20.sol
    
    pragma solidity >=0.5.0;
    
    interface IUniswapV2ERC20 {
        event Approval(address indexed owner, address indexed spender, uint value);
        event Transfer(address indexed from, address indexed to, uint value);
    
        function name() external pure returns (string memory);
        function symbol() external pure returns (string memory);
        function decimals() external pure returns (uint8);
        function totalSupply() external view returns (uint);
        function balanceOf(address owner) external view returns (uint);
        function allowance(address owner, address spender) external view returns (uint);
    
        function approve(address spender, uint value) external returns (bool);
        function transfer(address to, uint value) external returns (bool);
        function transferFrom(address from, address to, uint value) external returns (bool);
    
        function DOMAIN_SEPARATOR() external view returns (bytes32);
        function PERMIT_TYPEHASH() external pure returns (bytes32);
        function nonces(address owner) external view returns (uint);
    
        function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
    }
    
    // File: contracts/libraries/SafeMath.sol
    
    pragma solidity =0.5.16;
    
    // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
    
    library SafeMath {
        function add(uint x, uint y) internal pure returns (uint z) {
            require((z = x + y) >= x, 'ds-math-add-overflow');
        }
    
        function sub(uint x, uint y) internal pure returns (uint z) {
            require((z = x - y) <= x, 'ds-math-sub-underflow');
        }
    
        function mul(uint x, uint y) internal pure returns (uint z) {
            require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
        }
    }
    
    // File: contracts/UniswapV2ERC20.sol
    
    pragma solidity =0.5.16;
    
    
    
    contract UniswapV2ERC20 is IUniswapV2ERC20 {
        using SafeMath for uint;
    
        string public constant name = 'Uniswap V2';
        string public constant symbol = 'UNI-V2';
        uint8 public constant decimals = 18;
        uint  public totalSupply;
        mapping(address => uint) public balanceOf;
        mapping(address => mapping(address => uint)) public allowance;
    
        bytes32 public DOMAIN_SEPARATOR;
        // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
        bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
        mapping(address => uint) public nonces;
    
        event Approval(address indexed owner, address indexed spender, uint value);
        event Transfer(address indexed from, address indexed to, uint value);
    
        constructor() public {
            uint chainId;
            assembly {
                chainId := chainid
            }
            DOMAIN_SEPARATOR = keccak256(
                abi.encode(
                    keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
                    keccak256(bytes(name)),
                    keccak256(bytes('1')),
                    chainId,
                    address(this)
                )
            );
        }
    
        function _mint(address to, uint value) internal {
            totalSupply = totalSupply.add(value);
            balanceOf[to] = balanceOf[to].add(value);
            emit Transfer(address(0), to, value);
        }
    
        function _burn(address from, uint value) internal {
            balanceOf[from] = balanceOf[from].sub(value);
            totalSupply = totalSupply.sub(value);
            emit Transfer(from, address(0), value);
        }
    
        function _approve(address owner, address spender, uint value) private {
            allowance[owner][spender] = value;
            emit Approval(owner, spender, value);
        }
    
        function _transfer(address from, address to, uint value) private {
            balanceOf[from] = balanceOf[from].sub(value);
            balanceOf[to] = balanceOf[to].add(value);
            emit Transfer(from, to, value);
        }
    
        function approve(address spender, uint value) external returns (bool) {
            _approve(msg.sender, spender, value);
            return true;
        }
    
        function transfer(address to, uint value) external returns (bool) {
            _transfer(msg.sender, to, value);
            return true;
        }
    
        function transferFrom(address from, address to, uint value) external returns (bool) {
            if (allowance[from][msg.sender] != uint(-1)) {
                allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
            }
            _transfer(from, to, value);
            return true;
        }
    
        function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
            require(deadline >= block.timestamp, 'UniswapV2: EXPIRED');
            bytes32 digest = keccak256(
                abi.encodePacked(
                    '\x19\x01',
                    DOMAIN_SEPARATOR,
                    keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
                )
            );
            address recoveredAddress = ecrecover(digest, v, r, s);
            require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE');
            _approve(owner, spender, value);
        }
    }
    
    // File: contracts/libraries/Math.sol
    
    pragma solidity =0.5.16;
    
    // a library for performing various math operations
    
    library Math {
        function min(uint x, uint y) internal pure returns (uint z) {
            z = x < y ? x : y;
        }
    
        // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
        function sqrt(uint y) internal pure returns (uint z) {
            if (y > 3) {
                z = y;
                uint x = y / 2 + 1;
                while (x < z) {
                    z = x;
                    x = (y / x + x) / 2;
                }
            } else if (y != 0) {
                z = 1;
            }
        }
    }
    
    // File: contracts/libraries/UQ112x112.sol
    
    pragma solidity =0.5.16;
    
    // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
    
    // range: [0, 2**112 - 1]
    // resolution: 1 / 2**112
    
    library UQ112x112 {
        uint224 constant Q112 = 2**112;
    
        // encode a uint112 as a UQ112x112
        function encode(uint112 y) internal pure returns (uint224 z) {
            z = uint224(y) * Q112; // never overflows
        }
    
        // divide a UQ112x112 by a uint112, returning a UQ112x112
        function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
            z = x / uint224(y);
        }
    }
    
    // File: contracts/interfaces/IERC20.sol
    
    pragma solidity >=0.5.0;
    
    interface IERC20 {
        event Approval(address indexed owner, address indexed spender, uint value);
        event Transfer(address indexed from, address indexed to, uint value);
    
        function name() external view returns (string memory);
        function symbol() external view returns (string memory);
        function decimals() external view returns (uint8);
        function totalSupply() external view returns (uint);
        function balanceOf(address owner) external view returns (uint);
        function allowance(address owner, address spender) external view returns (uint);
    
        function approve(address spender, uint value) external returns (bool);
        function transfer(address to, uint value) external returns (bool);
        function transferFrom(address from, address to, uint value) external returns (bool);
    }
    
    // File: contracts/interfaces/IUniswapV2Factory.sol
    
    pragma solidity >=0.5.0;
    
    interface IUniswapV2Factory {
        event PairCreated(address indexed token0, address indexed token1, address pair, uint);
    
        function feeTo() external view returns (address);
        function feeToSetter() external view returns (address);
    
        function getPair(address tokenA, address tokenB) external view returns (address pair);
        function allPairs(uint) external view returns (address pair);
        function allPairsLength() external view returns (uint);
    
        function createPair(address tokenA, address tokenB) external returns (address pair);
    
        function setFeeTo(address) external;
        function setFeeToSetter(address) external;
    }
    
    // File: contracts/interfaces/IUniswapV2Callee.sol
    
    pragma solidity >=0.5.0;
    
    interface IUniswapV2Callee {
        function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
    }
    
    // File: contracts/UniswapV2Pair.sol
    
    pragma solidity =0.5.16;
    
    
    
    
    
    
    
    
    contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
        using SafeMath  for uint;
        using UQ112x112 for uint224;
    
        uint public constant MINIMUM_LIQUIDITY = 10**3;
        bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
    
        address public factory;
        address public token0;
        address public token1;
    
        uint112 private reserve0;           // uses single storage slot, accessible via getReserves
        uint112 private reserve1;           // uses single storage slot, accessible via getReserves
        uint32  private blockTimestampLast; // uses single storage slot, accessible via getReserves
    
        uint public price0CumulativeLast;
        uint public price1CumulativeLast;
        uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
    
        uint private unlocked = 1;
        modifier lock() {
            require(unlocked == 1, 'UniswapV2: LOCKED');
            unlocked = 0;
            _;
            unlocked = 1;
        }
    
        function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
            _reserve0 = reserve0;
            _reserve1 = reserve1;
            _blockTimestampLast = blockTimestampLast;
        }
    
        function _safeTransfer(address token, address to, uint value) private {
            (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
            require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED');
        }
    
        event Mint(address indexed sender, uint amount0, uint amount1);
        event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
        event Swap(
            address indexed sender,
            uint amount0In,
            uint amount1In,
            uint amount0Out,
            uint amount1Out,
            address indexed to
        );
        event Sync(uint112 reserve0, uint112 reserve1);
    
        constructor() public {
            factory = msg.sender;
        }
    
        // called once by the factory at time of deployment
        function initialize(address _token0, address _token1) external {
            require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
            token0 = _token0;
            token1 = _token1;
        }
    
        // update reserves and, on the first call per block, price accumulators
        function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
            require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW');
            uint32 blockTimestamp = uint32(block.timestamp % 2**32);
            uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
            if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
                // * never overflows, and + overflow is desired
                price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
                price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
            }
            reserve0 = uint112(balance0);
            reserve1 = uint112(balance1);
            blockTimestampLast = blockTimestamp;
            emit Sync(reserve0, reserve1);
        }
    
        // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
        function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
            address feeTo = IUniswapV2Factory(factory).feeTo();
            feeOn = feeTo != address(0);
            uint _kLast = kLast; // gas savings
            if (feeOn) {
                if (_kLast != 0) {
                    uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
                    uint rootKLast = Math.sqrt(_kLast);
                    if (rootK > rootKLast) {
                        uint numerator = totalSupply.mul(rootK.sub(rootKLast));
                        uint denominator = rootK.mul(5).add(rootKLast);
                        uint liquidity = numerator / denominator;
                        if (liquidity > 0) _mint(feeTo, liquidity);
                    }
                }
            } else if (_kLast != 0) {
                kLast = 0;
            }
        }
    
        // this low-level function should be called from a contract which performs important safety checks
        function mint(address to) external lock returns (uint liquidity) {
            (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
            uint balance0 = IERC20(token0).balanceOf(address(this));
            uint balance1 = IERC20(token1).balanceOf(address(this));
            uint amount0 = balance0.sub(_reserve0);
            uint amount1 = balance1.sub(_reserve1);
    
            bool feeOn = _mintFee(_reserve0, _reserve1);
            uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
            if (_totalSupply == 0) {
                liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
               _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
            } else {
                liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
            }
            require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED');
            _mint(to, liquidity);
    
            _update(balance0, balance1, _reserve0, _reserve1);
            if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
            emit Mint(msg.sender, amount0, amount1);
        }
    
        // this low-level function should be called from a contract which performs important safety checks
        function burn(address to) external lock returns (uint amount0, uint amount1) {
            (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
            address _token0 = token0;                                // gas savings
            address _token1 = token1;                                // gas savings
            uint balance0 = IERC20(_token0).balanceOf(address(this));
            uint balance1 = IERC20(_token1).balanceOf(address(this));
            uint liquidity = balanceOf[address(this)];
    
            bool feeOn = _mintFee(_reserve0, _reserve1);
            uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
            amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
            amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
            require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED');
            _burn(address(this), liquidity);
            _safeTransfer(_token0, to, amount0);
            _safeTransfer(_token1, to, amount1);
            balance0 = IERC20(_token0).balanceOf(address(this));
            balance1 = IERC20(_token1).balanceOf(address(this));
    
            _update(balance0, balance1, _reserve0, _reserve1);
            if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
            emit Burn(msg.sender, amount0, amount1, to);
        }
    
        // this low-level function should be called from a contract which performs important safety checks
        function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
            require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT');
            (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
            require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY');
    
            uint balance0;
            uint balance1;
            { // scope for _token{0,1}, avoids stack too deep errors
            address _token0 = token0;
            address _token1 = token1;
            require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO');
            if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
            if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
            if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data);
            balance0 = IERC20(_token0).balanceOf(address(this));
            balance1 = IERC20(_token1).balanceOf(address(this));
            }
            uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
            uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
            require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT');
            { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
            uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
            uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
            require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K');
            }
    
            _update(balance0, balance1, _reserve0, _reserve1);
            emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
        }
    
        // force balances to match reserves
        function skim(address to) external lock {
            address _token0 = token0; // gas savings
            address _token1 = token1; // gas savings
            _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
            _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
        }
    
        // force reserves to match balances
        function sync() external lock {
            _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
        }
    }