// File: contracts/BaseCAVO.sol



pragma solidity >=0.6.6;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import './libraries/SafeMath.sol';
import './libraries/Math.sol';
import './interfaces/ICAVO.sol';
import './interfaces/IExcavoERC20.sol';
import './interfaces/IxCAVO.sol';
import './interfaces/IEXCV.sol';
import './interfaces/IExcavoFactory.sol';

contract BaseCAVO is ICAVO, IExcavoERC20, ReentrancyGuard {
    using SafeMath for uint;

    string public constant override name = 'CAVO';
    string public constant override symbol = 'CAVO';
    uint8 public constant override decimals = 18;
    
    uint public constant override MAX_SUPPLY = 10**6 * 10**18;
    uint public constant override CREATOR_SUPPLY = 200 ether + 120 ether;

    address public override xCAVOToken;
    address public immutable override creator;
    address public override EXCVToken;

    uint public override totalSupply;
    mapping(address => uint) public override balanceOf;
    mapping(address => mapping(address => uint)) public override allowance;
    mapping(address => uint) private lastBalanceOf;
    mapping(address => uint) private lastBalanceBlockOf;

    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    constructor() public {
        creator = msg.sender;
        _mint(msg.sender, CREATOR_SUPPLY);
    }

    function initialize(address _factory) external override nonReentrant {
        require(msg.sender == creator && IEXCV(EXCVToken).factory() == address(0), 'EXCV: FORBIDDEN');
        IEXCV(EXCVToken).initialize(_factory);
        IxCAVO(xCAVOToken).initialize(_factory, EXCVToken);
    }

    function virtualBalanceOf(address account) external view override returns (uint) {
        uint balance = balanceOf[account];
        if (block.number - lastBalanceBlockOf[account] > 0) {
            return balance;
        }
        uint lastBalance = lastBalanceOf[account];
        return balance < lastBalance ? balance : lastBalance;
    }

    function mint(address account, uint256 amount) external override nonReentrant {
        require(msg.sender == xCAVOToken, 'Excavo: FORBIDDEN');
        _mint(account, amount);
    }

    function _mint(address to, uint value) internal {
        _saveLastBalance(to);
        uint _value = Math.min(value, MAX_SUPPLY.sub(totalSupply));
        totalSupply = totalSupply.add(_value);
        balanceOf[to] = balanceOf[to].add(_value);
        emit Transfer(address(0), to, _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) internal {
        _saveLastBalance(from);
        _saveLastBalance(to);
        balanceOf[from] = balanceOf[from].sub(value);
        balanceOf[to] = balanceOf[to].add(value);
        emit Transfer(from, to, value);
    }

    function approve(address spender, uint value) external virtual override returns (bool) {
        _approve(msg.sender, spender, value);
        return true;
    }

    function transfer(address to, uint value) external virtual override returns (bool) {
        _transfer(msg.sender, to, value);
        return true;
    }

    function transferFrom(address from, address to, uint value) external virtual override 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 _saveLastBalance(address account) private {
        if (block.number - lastBalanceBlockOf[account] > 0) {
            lastBalanceOf[account] = balanceOf[account];
            lastBalanceBlockOf[account] = block.number;
        } 
    }
}

// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor () internal {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and make it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

// File: contracts/libraries/SafeMath.sol



pragma solidity >=0.6.6;

// 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');
    }

    function div(uint x, uint y) internal pure returns (uint z) {
        require(y > 0, "SafeMath: division by zero");
        z = x / y;
    }
}

// File: contracts/libraries/Math.sol



pragma solidity >=0.6.6;

// 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/interfaces/ICAVO.sol



pragma solidity >=0.6.6;

interface ICAVO {
    function MAX_SUPPLY() external pure returns(uint);
    function CREATOR_SUPPLY() external pure returns(uint);
    function creator() external returns (address);
    function xCAVOToken() external view returns (address);
    function EXCVToken() external view returns (address);
    function mint(address to, uint value) external;
    function initialize(address _factory) external;
    function virtualBalanceOf(address account) external view returns (uint);
}   
// File: contracts/interfaces/IExcavoERC20.sol



pragma solidity >=0.6.6;

interface IExcavoERC20 {
    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);
}

// File: contracts/interfaces/IxCAVO.sol



pragma solidity >=0.6.6;

interface IxCAVO {
    function excvEthPair() external view returns (address);
    function cavoEthPair() external view returns (address);
    function getEXCV() external view returns (address);
    function getCAVO() external view returns (address);
    
    function redeem(address recipient) external;
    function initialize(address _factory, address _EXCV) external;
    function registerPairCreation() external;
    function mint(uint price) external;
    function accumulatedMintableCAVOAmount() external view returns (uint);
}

// File: contracts/interfaces/IEXCV.sol



pragma solidity >=0.6.6;

interface IEXCV {
    function MAX_SUPPLY() external pure returns(uint);
    function CREATOR_SUPPLY() external pure returns(uint);
    function xEXCVToken() external view returns (address);
    function factory() external view returns (address);

    function mint(address to, uint value) external;
    function initialize(address _factory) external;
}
// File: contracts/interfaces/IExcavoFactory.sol



pragma solidity >=0.6.6;

interface IExcavoFactory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);
    
    function EXCVToken() external view returns (address);
    function CAVOToken() external view returns (address);
    function WETHToken() external view returns (address);

    function feeToSetter() external view returns (address);
    function router() 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 initialize(address) external;
}

// File: contracts/PublicPresale.sol



pragma solidity >=0.6.6;

import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
import './libraries/TransferHelper.sol';
import './libraries/Math.sol';
import './libraries/SafeMath.sol';
import './libraries/DistributionLibrary.sol';
import './interfaces/ICAVO.sol';
import './interfaces/IExcavoERC20.sol';
import './interfaces/IxCAVO.sol';
import './interfaces/IPublicPresale.sol';
import './BaseCAVO.sol';

contract PublicPresale is BaseCAVO, IPublicPresale {
    
    using SafeMath for uint;
    using DistributionLibrary for DistributionLibrary.Data;

    event PublicPresalePurchase(address indexed recipient, uint amount);
    event PublicDistributed(address indexed recipient, uint amount);

    address public immutable override presaleOwner;
    uint private presaleDurationInBlocks;
    uint private presaleStartBlock;
    
    DistributionLibrary.Data private distribution;

    constructor(address _presaleOwner, uint32 _vestingBlocksInPeriod, uint _presaleDurationInBlocks) public {
        presaleOwner = _presaleOwner;
        distribution.blocksInPeriod = _vestingBlocksInPeriod;
        presaleDurationInBlocks = _presaleDurationInBlocks;
    }

    function availablePublicPresaleAmountOf(address account) external view override returns (uint) {
        return distribution.availableAmountOf(account);
    }

    function publicPresaleClaim(uint amount) external override nonReentrant {
        distribution.claim(amount);
        emit PublicDistributed(msg.sender, amount);
    }

    function startPublicPresaleDistribution() external override nonReentrant {
        require(presaleStartBlock != 0 && block.number >= presaleStartBlock.add(presaleDurationInBlocks), 'PublicPresale: INVALID_PARAMS');
        distribution.start();
    }

    function startPublicPresale() external override nonReentrant {
        require(presaleStartBlock == 0 && msg.sender == creator, 'PublicPresale: FORBIDDEN');
        presaleStartBlock = block.number;
    }

    receive() external payable nonReentrant {
        require(block.number >= presaleStartBlock && block.number < presaleStartBlock.add(presaleDurationInBlocks), 'PublicPresale: INACTIVE');
        // P = 0.5 ETH/CAVO
        uint mintedCAVO = msg.value.mul(100).div(50);
        payable(presaleOwner).transfer(msg.value);
        _mint(address(this), mintedCAVO);
        distribution.maxAmountOf[msg.sender] = distribution.maxAmountOf[msg.sender].add(mintedCAVO);
        emit PublicPresalePurchase(msg.sender, mintedCAVO);
    }
}
// File: contracts/libraries/TransferHelper.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.6;

// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
    function safeApprove(address token, address to, uint value) internal {
        // bytes4(keccak256(bytes('approve(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
    }

    function safeTransfer(address token, address to, uint value) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
    }

    function safeTransferFrom(address token, address from, address to, uint value) internal {
        // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
    }

    function safeTransferETH(address to, uint value) internal {
        (bool success,) = to.call{value:value}(new bytes(0));
        require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
    }
}

// File: contracts/libraries/DistributionLibrary.sol



pragma solidity >=0.6.6;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import './TransferHelper.sol';
import './Math.sol';
import './SafeMath.sol';
import '../interfaces/ICAVO.sol';

library DistributionLibrary {
    using SafeMath for uint;

    struct Data {
        mapping(address => uint) claimedAmountOf;
        mapping(address => uint) maxAmountOf;
        uint unlockBlock;
        uint32 blocksInPeriod;
    }

    function availableAmountOf(Data storage self, address account) internal view returns (uint) {
        if (self.unlockBlock == 0 || block.number <= self.unlockBlock || self.maxAmountOf[account] == 0) {
            return 0;
        }
        uint unlockedAmountPerPeriod = self.maxAmountOf[account].mul(10).div(100);
        uint unlockPeriodInBlocks = self.maxAmountOf[account].div(unlockedAmountPerPeriod).mul(self.blocksInPeriod);
        return Math.min(self.unlockBlock.add(unlockPeriodInBlocks), block.number)
            .sub(self.unlockBlock)
            .div(self.blocksInPeriod)
            .mul(unlockedAmountPerPeriod)
            .sub(self.claimedAmountOf[account]);
    }

    function start(Data storage self) internal {
        require(self.unlockBlock == 0 && msg.sender == ICAVO(address(this)).creator(), 'DistributionLibrary: FORBIDDEN');
        self.unlockBlock = block.number;
    }

    function claim(Data storage self, uint amount) internal {
        require(amount <= availableAmountOf(self, msg.sender), 'DistributionLibrary: OVERDRAFT');
        self.claimedAmountOf[msg.sender] = self.claimedAmountOf[msg.sender].add(amount);
        TransferHelper.safeTransfer(address(this), msg.sender, amount);
    }
}

// File: contracts/interfaces/IPublicPresale.sol



pragma solidity >=0.6.6;

interface IPublicPresale {
    function presaleOwner() external view returns (address);
    function availablePublicPresaleAmountOf(address account) external view returns (uint);

    function publicPresaleClaim(uint amount) external;
    function startPublicPresaleDistribution() external;
    function startPublicPresale() external;
}   
// File: contracts/test/TestCAVO.sol



pragma solidity >=0.6.6;

import '../PublicPresale.sol';
import '../TeamDistribution.sol';
import '../PrivatePresale.sol';
import './TestxCAVO.sol';
import './TestEXCV.sol';

contract TestCAVO is PublicPresale, PrivatePresale, TeamDistribution {

    uint public constant PUBLIC_PRESALE_DURATION_IN_BLOCKS = 10;
    uint32 public constant PRESALE_VESTING_PERIOD_IN_BLOCKS = 10;
    uint public constant PRIVATE_PRESALE_DISTRIBUTED_CAVO_IN_WEI = 10000;
    address private constant PUBLIC_PRESALE_OWNER = 0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4;
    address[] private _teamAddresses = [
        0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4, 
        0xE5904695748fe4A84b40b3fc79De2277660BD1D3, 
        0x92561F28Ec438Ee9831D00D1D59fbDC981b762b2
    ];
    uint[] private _teamAmounts = [
        1000000,
        1500000,
        2000000
    ];

    constructor() 
        public 
        PublicPresale(PUBLIC_PRESALE_OWNER, PRESALE_VESTING_PERIOD_IN_BLOCKS, PUBLIC_PRESALE_DURATION_IN_BLOCKS) 
        PrivatePresale(PRESALE_VESTING_PERIOD_IN_BLOCKS, PRIVATE_PRESALE_DISTRIBUTED_CAVO_IN_WEI) 
        TeamDistribution(PRESALE_VESTING_PERIOD_IN_BLOCKS, _teamAddresses, _teamAmounts) 
    {
        address _xCAVO;
        address _EXCV;
        bytes memory xCAVOBytecode = type(TestxCAVO).creationCode;
        bytes memory EXCVBytecode = type(TestEXCV).creationCode;
        bytes32 xCAVOSalt = keccak256(abi.encodePacked("xCAVO"));
        bytes32 EXCVSalt = keccak256(abi.encodePacked("EXCV"));
        assembly {
            _xCAVO := create2(0, add(xCAVOBytecode, 32), mload(xCAVOBytecode), xCAVOSalt)
            _EXCV := create2(0, add(EXCVBytecode, 32), mload(EXCVBytecode), EXCVSalt)
        }
        xCAVOToken = _xCAVO;
        EXCVToken = _EXCV;

        _mint(address(this), totalTeamDistribution.add(totalPrivatePresaleDistribution));
    }

    function teamAddresses() external view returns (address[] memory) {
        return _teamAddresses;
    }

    function teamAmounts() external view returns (uint[] memory) {
        return _teamAmounts;
    }

    function testMint(address account, uint256 amount) external {
        _mint(account, amount);
    }
}
// File: contracts/TeamDistribution.sol



pragma solidity >=0.6.6;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import './libraries/TransferHelper.sol';
import './libraries/Math.sol';
import './libraries/SafeMath.sol';
import './libraries/DistributionLibrary.sol';
import './interfaces/ICAVO.sol';
import './interfaces/IExcavoERC20.sol';
import './interfaces/IxCAVO.sol';
import './interfaces/ITeamDistribution.sol';

abstract contract TeamDistribution is ITeamDistribution, ICAVO, IExcavoERC20, ReentrancyGuard {
    using SafeMath for uint;
    using DistributionLibrary for DistributionLibrary.Data;

    event TeamDistributed(address indexed recipient, uint amount);

    uint public override totalTeamDistribution;
    DistributionLibrary.Data private distribution;

    constructor(uint32 _blocksInPeriod, address[] memory _team, uint[] memory _amounts) public {
        require(_team.length == _amounts.length, 'TeamDistribution: INVALID_PARAMS');
        uint total;
        for (uint i = 0; i < _team.length; ++i) {
            distribution.maxAmountOf[_team[i]] = _amounts[i];
            total = total.add(_amounts[i]);
        }
        totalTeamDistribution = total;
        distribution.blocksInPeriod = _blocksInPeriod;
    }

    function availableTeamMemberAmountOf(address account) external view override returns (uint) {
        return distribution.availableAmountOf(account);
    }

    function teamMemberClaim(uint amount) external override nonReentrant {
        distribution.claim(amount);
        emit TeamDistributed(msg.sender, amount);
    }

    function startTeamDistribution() external override nonReentrant {
        distribution.start();
    }
}
// File: contracts/PrivatePresale.sol



pragma solidity >=0.6.6;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import './libraries/TransferHelper.sol';
import './libraries/SafeMath.sol';
import './libraries/DistributionLibrary.sol';
import './interfaces/ICAVO.sol';
import './interfaces/IExcavoERC20.sol';
import './interfaces/IxCAVO.sol';
import './interfaces/IPrivatePresale.sol';

abstract contract PrivatePresale is IPrivatePresale, ICAVO, IExcavoERC20, ReentrancyGuard {
    using SafeMath for uint;
    using DistributionLibrary for DistributionLibrary.Data;

    event PrivateDistributionInitialized(address indexed recipient, uint amount);
    event PrivateDistributed(address indexed recipient, uint amount);

    DistributionLibrary.Data private distribution;
    uint public override totalPrivatePresaleDistribution;
    uint public override privatePresaleDistributed;

    constructor(uint32 _blocksInPeriod, uint _totalPrivatePresaleDistribution) public {
        distribution.blocksInPeriod = _blocksInPeriod;
        totalPrivatePresaleDistribution = _totalPrivatePresaleDistribution;
    }

    function distribute(address[] calldata _accounts, uint[] calldata _amounts) external override nonReentrant {
        require(msg.sender == ICAVO(address(this)).creator(), 'PrivatePresale: FORBIDDEN');
        require(_accounts.length == _amounts.length, 'PrivatePresale: INVALID_LENGTH');
        uint _distributed = privatePresaleDistributed;
        for (uint i = 0; i < _accounts.length; ++i) {
            uint max = distribution.maxAmountOf[_accounts[i]].add(_amounts[i]);
            distribution.maxAmountOf[_accounts[i]] = max;
            _distributed = _distributed.add(_amounts[i]);
            emit PrivateDistributionInitialized(_accounts[i], max);
        }
        require(_distributed <= totalPrivatePresaleDistribution, 'PrivatePresale: LIMIT_EXCEEDED');
        privatePresaleDistributed = _distributed;
    }

    function editDistributed(address _account, uint _amount) external override nonReentrant {
        // disabled if admin has started the private presale distribution
        require(distribution.unlockBlock == 0 && msg.sender == ICAVO(address(this)).creator(), 'PrivatePresale: FORBIDDEN');
        uint _distributed = privatePresaleDistributed.sub(distribution.maxAmountOf[_account]).add(_amount);
        distribution.maxAmountOf[_account] = _amount;
        require(_distributed <= totalPrivatePresaleDistribution, 'PrivatePresale: LIMIT_EXCEEDED');
        privatePresaleDistributed = _distributed;
        emit PrivateDistributionInitialized(_account, _amount);
    }

    function availablePrivatePresaleAmountOf(address account) external view override returns (uint) {
        return distribution.availableAmountOf(account);
    }

    function privatePresaleClaim(uint amount) external override nonReentrant {
        distribution.claim(amount);
        emit PrivateDistributed(msg.sender, amount);
    }

    function startPrivatePresaleDistribution() external override nonReentrant {
        // called, once admin has distributed all of the presale tokens
        require(privatePresaleDistributed == totalPrivatePresaleDistribution, 'PrivatePresale: DISTRIBUTION_UNFINISHED');
        distribution.start();
    }
}
// File: contracts/test/TestxCAVO.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.6;

import '../xCAVO.sol';

contract TestxCAVO is xCAVO {
    function testSetExpectedPrice(uint price) external {
        expectedPriceInUQ = price;
    }
}
// File: contracts/test/TestEXCV.sol



pragma solidity >=0.6.6;

import "../EXCV.sol";

contract TestEXCV is EXCV {
    function testMint(address account, uint256 amount) external {
        _mint(account, amount);
    }
}
// File: contracts/interfaces/ITeamDistribution.sol



pragma solidity >=0.6.6;

interface ITeamDistribution {
    function totalTeamDistribution() external view returns (uint);
    function availableTeamMemberAmountOf(address account) external view returns (uint);

    function teamMemberClaim(uint amount) external;
    function startTeamDistribution() external;
}   
// File: contracts/interfaces/IPrivatePresale.sol



pragma solidity >=0.6.6;

interface IPrivatePresale {
    function totalPrivatePresaleDistribution() external view returns (uint);
    function privatePresaleDistributed() external view returns (uint);
    function availablePrivatePresaleAmountOf(address account) external view returns (uint);

    function distribute(address[] calldata _accounts, uint[] calldata _amounts) external;
    function editDistributed(address _account, uint _amount) external;
    function privatePresaleClaim(uint amount) external;
    function startPrivatePresaleDistribution() external;
}   
// File: contracts/xCAVO.sol



pragma solidity >=0.6.6;

import './interfaces/IxCAVO.sol';
import './interfaces/ICAVO.sol';
import "./interfaces/IERC20.sol";
import "./interfaces/IEXCV.sol";
import "./interfaces/IExcavoPair.sol";
import "./interfaces/IExcavoFactory.sol";
import './libraries/SafeMath.sol';
import "./libraries/ExcavoLibrary.sol";
import './libraries/UQ112x112.sol';
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

contract xCAVO is IxCAVO, IERC20, ReentrancyGuard {
    using SafeMath for uint;
    
    event Redeem(address indexed sender, address indexed recipient, uint amount);

    string public constant override name = 'xCAVO';
    string public constant override symbol = 'xCAVO';
    uint8 public constant override decimals = 18;
    uint private constant Q112 = 2**112;
    uint private constant WEI_IN_CAVO = 10**18;
    uint private constant VESTING_PERIOD = 7020000; // 36 * 30 * 6500 = 7020000 = 36 months in blocks
    
    address public immutable override getCAVO;
    address public override excvEthPair;
    address public override cavoEthPair;
    address public override getEXCV;

    mapping(address => uint) private lastAccumulatedMintableCAVOAmount;
    mapping(address => uint) private lastAccumulatedUnclaimedLiquidity;

    uint public override accumulatedMintableCAVOAmount;
    uint private firstBlockNumber;
    uint private lastBlockNumber;
    uint internal expectedPriceInUQ;

    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    constructor() public {
        getCAVO = msg.sender;
    }

    function initialize(address _factory, address _EXCV) external override nonReentrant  {
        require(getEXCV == address(0) && excvEthPair == address(0) && cavoEthPair == address(0) && msg.sender == getCAVO, "xCAVO: FORBIDDEN"); 
        getEXCV = _EXCV;
        address WETH = IExcavoFactory(_factory).WETHToken();
        excvEthPair = ExcavoLibrary.pairFor(_factory, getEXCV, WETH);
        cavoEthPair = ExcavoLibrary.pairFor(_factory, getCAVO, WETH);
    }

    function registerPairCreation() external override nonReentrant {
        require(firstBlockNumber == 0 && msg.sender == cavoEthPair, "xCAVO: FORBIDDEN");
        firstBlockNumber = block.number;
        lastBlockNumber = block.number;
    }

    function totalSupply() external view override returns (uint) {
        return IERC20(getCAVO).totalSupply();
    }

    function balanceOf(address owner) external view override returns (uint) {
        uint totalUnclaimedLiquidity = IExcavoPair(excvEthPair).accumulatedLiquidityGrowth() - lastAccumulatedUnclaimedLiquidity[owner];
        if (totalUnclaimedLiquidity == 0) {
            return 0;
        }
        uint totalMintableCAVO = accumulatedMintableCAVOAmount - lastAccumulatedMintableCAVOAmount[owner];
        uint liquidity = IExcavoPair(excvEthPair).unclaimedLiquidityOf(owner);
        return liquidity.mul(totalMintableCAVO) / totalUnclaimedLiquidity;
    }

    function redeem(address recipient) external override nonReentrant {
        uint liquidity = IExcavoPair(excvEthPair).claimAllLiquidity(msg.sender);
        uint accumulatedUnclaimedLiquidity = IExcavoPair(excvEthPair).accumulatedUnclaimedLiquidity();
        uint totalUnclaimedLiquidity = accumulatedUnclaimedLiquidity - lastAccumulatedUnclaimedLiquidity[msg.sender]; // overflow desired
        if (totalUnclaimedLiquidity == 0) {
            revert('xCAVO: INSUFFICIENT_MINTED_AMOUNT');
        }
        uint totalMintableCAVO = accumulatedMintableCAVOAmount - lastAccumulatedMintableCAVOAmount[msg.sender]; // overflow desired
        uint mintedAmount = liquidity.mul(totalMintableCAVO) / totalUnclaimedLiquidity;
        require(mintedAmount > 0, 'xCAVO: INSUFFICIENT_MINTED_AMOUNT');
        lastAccumulatedUnclaimedLiquidity[msg.sender] = accumulatedUnclaimedLiquidity;
        lastAccumulatedMintableCAVOAmount[msg.sender] = accumulatedMintableCAVOAmount;
        ICAVO(getCAVO).mint(recipient, mintedAmount);
        emit Redeem(msg.sender, recipient, mintedAmount);
    }

    function mint(uint priceInUQ) external override nonReentrant {
        require(msg.sender == cavoEthPair, "xCAVO: FORBIDDEN");

        if (block.number - firstBlockNumber >= VESTING_PERIOD || block.number == lastBlockNumber) {
            return;
        }
        uint priceChangeInUQ = Q112.mul(block.number.sub(lastBlockNumber)).mul(3).div(6500000);

        if (expectedPriceInUQ + priceChangeInUQ < expectedPriceInUQ) {
            return; // overflow: stop minting
        }
        expectedPriceInUQ += priceChangeInUQ; // cannot overflow
        if (priceInUQ >= expectedPriceInUQ) {
            // mintedAmount = 10^6 * (N - Nprev) * (N + Nprev - 2 * N0) / ((36 * 30 * 6500)^2)
            // ((36 * 30 * 6500)**2) = 49280400000000
            // 10**6 = 1000000
            uint mintedAmount = block.number.sub(lastBlockNumber).mul(1000000)
                .mul(block.number.add(lastBlockNumber).sub(firstBlockNumber.mul(2)))
                .mul(WEI_IN_CAVO)
                .div(49280400000000);
            if (mintedAmount > 0) {
                accumulatedMintableCAVOAmount = accumulatedMintableCAVOAmount + mintedAmount; // overflow desired
            }
        }
        lastBlockNumber = block.number;
    }

    function allowance(address /*owner*/, address /*spender*/) external view override returns (uint) {
        revert("xCAVO: FORBIDDEN");
    }

    function approve(address /*spender*/, uint /*value*/) external override returns (bool) {
        revert("xCAVO: FORBIDDEN");
    }

    function transfer(address /*to*/, uint /*value*/) external override returns (bool) {
        revert("xCAVO: FORBIDDEN");
    }

    function transferFrom(address /*from*/, address /*to*/, uint /*value*/) external override returns (bool) {
        revert("xCAVO: FORBIDDEN");
    }
}

// File: contracts/interfaces/IERC20.sol



pragma solidity >=0.6.6;

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/IExcavoPair.sol



pragma solidity >=0.6.6;

import './IExcavoERC20.sol';

interface IExcavoPair is IExcavoERC20 {
    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 router() external view returns (address);
    function accumulatedLiquidityGrowth() external view returns (uint);
    function accumulatedUnclaimedLiquidity() external view returns (uint);
    function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
    function price0CumulativeLast() external view returns (uint);
    function price1CumulativeLast() 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, uint discount) external;
    function skim(address to) external;
    function sync() external;

    function initialize(address, address, address) external;
    function setxEXCV(address) external;

    function unclaimedLiquidityOf(address) external view returns (uint);
    function claimLiquidity(address account, uint256 amount) external returns (uint claimAmount);
    function claimAllLiquidity(address account) external returns (uint claimAmount);

    function compoundLiquidity() external;
    function setCAVO(address _CAVO, address _xCAVO) external;   
}
// File: contracts/libraries/ExcavoLibrary.sol



pragma solidity >=0.6.6;

import '../interfaces/IExcavoPair.sol';
import "./SafeMath.sol";
import './Math.sol';

library ExcavoLibrary {
    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, 'ExcavoLibrary: IDENTICAL_ADDRESSES');
        (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        require(token0 != address(0), 'ExcavoLibrary: 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'3b4596e5d4f0ba0faf3c029e2a152a4931e4da86804417810c5960569e839f1e' // 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,) = IExcavoPair(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, 'ExcavoLibrary: INSUFFICIENT_AMOUNT');
        require(reserveA > 0 && reserveB > 0, 'ExcavoLibrary: 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, uint discount) internal pure returns (uint amountOut) {
        require(amountIn > 0, 'ExcavoLibrary: INSUFFICIENT_INPUT_AMOUNT');
        require(reserveIn > 0 && reserveOut > 0, 'ExcavoLibrary: INSUFFICIENT_LIQUIDITY');
        uint amountInWithFee = amountIn.mul(10000 - 4 * discount);
        uint numerator = amountInWithFee.mul(reserveOut);
        uint denominator = reserveIn.mul(10000).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, uint discount) internal pure returns (uint amountIn) {
        require(amountOut > 0, 'ExcavoLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
        require(reserveIn > 0 && reserveOut > 0, 'ExcavoLibrary: INSUFFICIENT_LIQUIDITY');
        uint numerator = reserveIn.mul(amountOut).mul(10000);
        uint denominator = reserveOut.sub(amountOut).mul(10000 - 4 * discount);
        amountIn = (numerator / denominator).add(1);
    }

    // performs chained getAmountOut calculations on any number of pairs
    function getAmountsOut(address factory, uint amountIn, address[] memory path, uint discount) internal view returns (uint[] memory amounts) {
        require(path.length >= 2, 'ExcavoLibrary: 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, discount);
        }
    }

    // performs chained getAmountIn calculations on any number of pairs
    function getAmountsIn(address factory, uint amountOut, address[] memory path, uint discount) internal view returns (uint[] memory amounts) {
        require(path.length >= 2, 'ExcavoLibrary: 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, discount);
        }
    }
}

// File: contracts/libraries/UQ112x112.sol



pragma solidity >=0.6.6;

// 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/EXCV.sol



pragma solidity >=0.6.6;

import './interfaces/IExcavoERC20.sol';
import './interfaces/ICAVO.sol';
import './libraries/Math.sol';
import "./xEXCV.sol";

contract EXCV is IEXCV, IExcavoERC20, ReentrancyGuard {
    using SafeMath for uint;

    string public constant override name = 'EXCV';
    string public constant override symbol = 'EXCV';
    uint8 public constant override decimals = 18;

    uint public constant override MAX_SUPPLY = 10**9 * 10**18;
    // TODO: make sure, it's OK
    uint public constant override CREATOR_SUPPLY = 600 * 5 * 10**18;

    address public override immutable xEXCVToken;
    address public override factory;

    uint public override totalSupply;
    mapping(address => uint) public override balanceOf;
    mapping(address => mapping(address => uint)) public override allowance;
    address private immutable creator;

    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    constructor() public {
        creator = msg.sender;
        address _xEXCV;
        bytes memory bytecode = type(xEXCV).creationCode;
        bytes32 salt = keccak256(abi.encodePacked("xEXCV"));
        assembly {
            _xEXCV := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        xEXCVToken = _xEXCV;
    }

    function initialize(address _factory) external override nonReentrant {
        require(factory == address(0) && msg.sender == creator, "EXCV: FORBIDDEN");
        factory = _factory;
        IxEXCV(xEXCVToken).initialize(_factory);
        _mint(ICAVO(creator).creator(), CREATOR_SUPPLY);
    }

    function _mint(address to, uint value) internal {
        uint _value = Math.min(value, MAX_SUPPLY.sub(totalSupply));
        totalSupply = totalSupply.add(_value);
        balanceOf[to] = balanceOf[to].add(_value);
        emit Transfer(address(0), to, _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 mint(address to, uint value) external override nonReentrant {
        require(msg.sender == xEXCVToken, "EXCV: FORBIDDEN");
        _mint(to, value);
    }

    function approve(address spender, uint value) external virtual override nonReentrant returns (bool) {
        _approve(msg.sender, spender, value);
        return true;
    }

    function transfer(address to, uint value) external virtual override returns (bool) {
        _transfer(msg.sender, to, value);
        return true;
    }

    function transferFrom(address from, address to, uint value) external virtual override nonReentrant 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;
    }
}
// File: contracts/xEXCV.sol



pragma solidity >=0.6.6;

import "./interfaces/IxEXCV.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IEXCV.sol";
import "./interfaces/IExcavoFactory.sol";
import "./interfaces/IExcavoPair.sol";
import "./libraries/ExcavoLibrary.sol";
import './libraries/Math.sol';
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

contract xEXCV is IxEXCV, IERC20, ReentrancyGuard {
    // each time user adds liquidity to EXCV generating pairs, add active pair address
    // each time user removes liquidity to EXCV generating pairs, remove active pair address
    using SafeMath for uint;

    event Redeem(address indexed sender, address indexed recipient, uint amount);

    uint constant MIN_LIQUIDITY_PAIR_COUNT = 3;
    
    address public immutable override getEXCV;
    address public override factory;
    address public override excvEthPair;
    address[] private _liquidityPairs;

    string public constant override symbol = "xEXCV";
    string public constant override name = "xEXCV";
    uint8 public constant override decimals = 18; 

    constructor() public {
        getEXCV = msg.sender;
    }

    function initialize(address _factory) external override nonReentrant {
        require(msg.sender == getEXCV && factory == address(0) && excvEthPair == address(0), "xEXCV: FORBIDDEN");
        factory = _factory;
        address WETH = IExcavoFactory(_factory).WETHToken();
        excvEthPair = ExcavoLibrary.pairFor(_factory, getEXCV, WETH);
    }

    function addPair(address tokenA, address tokenB) external override nonReentrant {
        require(ExcavoLibrary.pairFor(factory, tokenA, tokenB) == msg.sender, "xEXCV: FORBIDDEN");
        if (!_pairExists(msg.sender)) {
            _liquidityPairs.push(msg.sender);
        }
    }

    function redeem(address recipient) external override nonReentrant {
        address[] memory pairs = _liquidityPairs;
        uint _circulatingSupply = circulatingSupply();
        uint excvQuantity;
        for (uint i = 0; i < pairs.length; i++) {
            uint lastK = IExcavoPair(pairs[i]).totalSupply();
            uint claimedLiquidity = IExcavoPair(pairs[i]).claimAllLiquidity(msg.sender);
            excvQuantity = excvQuantity.add(claimedLiquidity.mul(_circulatingSupply).div(lastK));
        }
        IEXCV(getEXCV).mint(recipient, excvQuantity);
        emit Redeem(msg.sender, recipient, excvQuantity);
    }

    function redeemPair(address recipient, address pair, uint claimedLiquidityAmount) external override nonReentrant {
        require(_pairExists(pair), "xEXCV: unknown pair");

        uint _circulatingSupply = circulatingSupply();
        uint lastK = IExcavoPair(pair).totalSupply();
        IExcavoPair(pair).claimLiquidity(msg.sender, claimedLiquidityAmount);
        uint excvQuantity = claimedLiquidityAmount.mul(_circulatingSupply).div(lastK);

        IEXCV(getEXCV).mint(recipient, excvQuantity);
        emit Redeem(msg.sender, recipient, excvQuantity);
    }

    function totalSupply() external view override returns (uint) {
        return IERC20(getEXCV).totalSupply();
    }

    function balanceOf(address owner) external view override returns (uint) {
        address[] memory pairs = _liquidityPairs;
        uint _circulatingSupply = circulatingSupply();
        uint excvQuantity;
        for (uint i = 0; i < pairs.length; i++) {
            uint accumulatedLiquidity = IExcavoPair(pairs[i]).unclaimedLiquidityOf(owner);
            uint lastK = IExcavoPair(pairs[i]).totalSupply();
            excvQuantity = excvQuantity.add(accumulatedLiquidity.mul(_circulatingSupply).div(lastK));
        }
        return excvQuantity;
    }

    function liquidityPairs() external view override returns (address[] memory) {
        return _liquidityPairs;
    }

    function pairBalanceOf(address owner, address pair) external view override returns (uint) {
        if (!_pairExists(pair)) {
            return 0;
        }
        uint lastK = IExcavoPair(pair).totalSupply();
        if (lastK == 0) {
            return 0;
        }
        uint _circulatingSupply = circulatingSupply();
        uint accumulatedLiquidity = IExcavoPair(pair).unclaimedLiquidityOf(owner);
        return accumulatedLiquidity.mul(_circulatingSupply) / lastK;
    }

    function circulatingSupply() private view returns (uint) {
        (uint reserve0, uint reserve1, ) = IExcavoPair(excvEthPair).getReserves();
        return IExcavoPair(excvEthPair).token0() == getEXCV ? reserve0 : reserve1;
    }

    function _pairExists(address pair) private view returns (bool) {
        address[] memory pairs = _liquidityPairs;
        for (uint i = 0; i < pairs.length; ++i) {
            if (pairs[i] == pair) {
                return true;
            }
        }
        return false;
    }

    function allowance(address /*owner*/, address /*spender*/) external view override returns (uint) {
        revert("xEXCV: FORBIDDEN");
    }

    function approve(address /*spender*/, uint /*value*/) external override returns (bool) {
        revert("xEXCV: FORBIDDEN");
    }

    function transfer(address /*to*/, uint /*value*/) external override returns (bool) {
        revert("xEXCV: FORBIDDEN");
    }

    function transferFrom(address /*from*/, address /*to*/, uint /*value*/) external override returns (bool) {
        revert("xEXCV: FORBIDDEN");
    }
}
// File: contracts/interfaces/IxEXCV.sol



pragma solidity >=0.6.6;

interface IxEXCV {
    function liquidityPairs() external view returns (address[] memory);
    function factory() external view returns (address);
    function excvEthPair() external view returns (address);
    function getEXCV() external view returns (address);

    function initialize(address _factory) external;
    function redeem(address recipient) external;
    function redeemPair(address recipient, address pair, uint claimedLiquidityAmount) external;
    function addPair(address tokenA, address tokenB) external;
    function pairBalanceOf(address owner, address pair) external view returns (uint);
}
// File: contracts/test/DistributionTest.sol



pragma solidity >=0.6.6;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import '../libraries/TransferHelper.sol';
import '../libraries/Math.sol';
import '../libraries/SafeMath.sol';
import '../libraries/DistributionLibrary.sol';
import '../interfaces/ICAVO.sol';
import '../interfaces/IExcavoERC20.sol';
import '../interfaces/IxCAVO.sol';
import './TestCAVO.sol';

contract DistributionTest is TestCAVO {
    using SafeMath for uint;
    using DistributionLibrary for DistributionLibrary.Data;

    event Distributed(address indexed recipient, uint amount);
    event DistributionStarted(address indexed sender, uint blockNumber);

    DistributionLibrary.Data private testDistribution;
    uint private totalDistribution;

    constructor(uint32 _blocksInPeriod, address[] memory _team, uint[] memory _amounts) public {
        require(_team.length == _amounts.length, 'DistributionTest: INVALID_PARAMS');
        uint total;
        for (uint i = 0; i < _team.length; ++i) {
            testDistribution.maxAmountOf[_team[i]] = _amounts[i];
            total = total.add(_amounts[i]);
        }
        totalDistribution = total;
        testDistribution.blocksInPeriod = _blocksInPeriod;

        _mint(address(this), totalDistribution);
    }

    function testAvailableAmountOf(address account) external view returns (uint) {
        return testDistribution.availableAmountOf(account);
    }

    function testClaim(uint amount) external {
        testDistribution.claim(amount);
        emit Distributed(msg.sender, amount);
    }

    function testStartDistribution() external nonReentrant {
        testDistribution.start();
        emit DistributionStarted(msg.sender, block.number);
    }
}
// File: contracts/ExcavoPair.sol



pragma solidity >=0.6.6;

import './interfaces/IERC20.sol';
import './interfaces/IxEXCV.sol';
import './interfaces/IxCAVO.sol';
import './interfaces/IExcavoFactory.sol';
import './interfaces/IExcavoCallee.sol';
import './interfaces/IExcavoPair.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './libraries/PairLibrary.sol';
import './BaseExcavoPair.sol';

contract ExcavoPair is IExcavoPair, BaseExcavoPair {
    using SafeMath  for uint;
    using UQ112x112 for uint224;

    event Compound(address indexed owner, uint liquidityGrowth);

    struct SwapDetails {
        uint balance0;
        uint balance1;
        address _token0;
        address _token1;
        uint balance0Adjusted;
        uint balance1Adjusted;
    }

    uint public constant override MINIMUM_LIQUIDITY = 10**3;
    bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));

    uint private unlocked = 1;
    modifier lock() {
        require(unlocked == 1, 'Excavo: LOCKED');
        unlocked = 0;
        _;
        unlocked = 1;
    }

    function getReserves() public view override returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
        _reserve0 = data.reserve0;
        _reserve1 = data.reserve1;
        _blockTimestampLast = data.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))), 'Excavo: TRANSFER_FAILED');
    }

    constructor() public {
        data.factory = msg.sender;
    }

    // called once by the factory at time of deployment
    function initialize(address _token0, address _token1, address _router) external override lock {
        data.initialize(_token0, _token1, _router);
    }       

    function setCAVO(address _CAVO, address _xCAVO) external override lock {
        data.setCAVO(_CAVO, _xCAVO);
    }

    function setxEXCV(address _xEXCV) external override lock {
        data.setxEXCV(_xEXCV);
    }

    // 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), 'Excavo: OVERFLOW');
        uint32 blockTimestamp = uint32(block.timestamp % 2**32);
        uint32 timeElapsed = blockTimestamp - data.blockTimestampLast; // overflow is desired
        if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
            // * never overflows, and + overflow is desired
            data.price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
            data.price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
        }
        data.reserve0 = uint112(balance0);
        data.reserve1 = uint112(balance1);
        data.blockTimestampLast = blockTimestamp;
        emit Sync(data.reserve0, data.reserve1);
    }

    // this low-level function should be called from a contract which performs important safety checks
    function mint(address to) external lock override returns (uint liquidity) {
        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
        uint balance0 = IERC20(data.token0).balanceOf(address(this));
        uint balance1 = IERC20(data.token1).balanceOf(address(this));
        uint amount0 = balance0.sub(_reserve0);
        uint amount1 = balance1.sub(_reserve1);
        uint _totalSupply = data.totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
        uint _liquidity = Math.sqrt(amount0.mul(amount1));
        if (_totalSupply == 0) {
            liquidity = _liquidity.sub(MINIMUM_LIQUIDITY);
            _mint(address(0), MINIMUM_LIQUIDITY, MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
            require(liquidity > 0, 'Excavo: INSUFFICIENT_LIQUIDITY_MINTED');
            _mint(to, liquidity, liquidity);
        } else {
            liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
            require(liquidity > 0, 'Excavo: INSUFFICIENT_LIQUIDITY_MINTED');
            _mint(to, liquidity, _liquidity);
        }
        _update(balance0, balance1, _reserve0, _reserve1);
        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) public override lock returns (uint amount0, uint amount1) {
        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
        address _token0 = data.token0;                                // gas savings
        address _token1 = data.token1;                                // gas savings
        uint balance0 = IERC20(_token0).balanceOf(address(this));
        uint balance1 = IERC20(_token1).balanceOf(address(this));
        uint liquidity = data.balanceOf[address(this)];
        uint _totalSupply = data.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, 'Excavo: 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);
        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, uint discount) external override lock {
        require(msg.sender == data.router, "Excavo: FORBIDDEN");
        SwapDetails memory details;
        require(amount0Out > 0 || amount1Out > 0, 'Excavo: INSUFFICIENT_OUTPUT_AMOUNT');
        (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
        require(amount0Out < _reserve0 && amount1Out < _reserve1, 'Excavo: INSUFFICIENT_LIQUIDITY');

        { // scope for _token{0,1}, avoids stack too deep errors
        details._token0 = data.token0;
        details._token1 = data.token1;
        require(to != details._token0 && to != details._token1, 'Excavo: INVALID_TO');
        if (amount0Out > 0) _safeTransfer(details._token0, to, amount0Out); // optimistically transfer tokens
        if (amount1Out > 0) _safeTransfer(details._token1, to, amount1Out); // optimistically transfer tokens
        if (_data.length > 0) IExcavoCallee(to).ExcavoCall(msg.sender, amount0Out, amount1Out, _data);
        details.balance0 = IERC20(details._token0).balanceOf(address(this));
        details.balance1 = IERC20(details._token1).balanceOf(address(this));
        }
        uint amount0In = details.balance0 > _reserve0 - amount0Out ? details.balance0 - (_reserve0 - amount0Out) : 0;
        uint amount1In = details.balance1 > _reserve1 - amount1Out ? details.balance1 - (_reserve1 - amount1Out) : 0;
        require(amount0In > 0 || amount1In > 0, 'Excavo: INSUFFICIENT_INPUT_AMOUNT');
        { // scope for reserve{0,1}Adjusted, avoids stack too deep errors
        details.balance0Adjusted = details.balance0.mul(10000).sub(amount0In.mul(4 * discount));
        details.balance1Adjusted = details.balance1.mul(10000).sub(amount1In.mul(4 * discount));
        require(details.balance0Adjusted.mul(details.balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(10000**2), 'Excavo: K');
        }
        
        if (data.CAVO != address(0)) {
            uint prevPriceCumulativeLast = data.token0 == data.CAVO ? data.price0CumulativeLast : data.price1CumulativeLast;
            uint prevBlockTimestampLast = data.blockTimestampLast;
            _update(details.balance0, details.balance1, _reserve0, _reserve1);
            // call mint first call per block 
            if (data.blockTimestampLast != prevBlockTimestampLast) {
                uint priceCumulativeLast = data.token0 == data.CAVO ? data.price0CumulativeLast : data.price1CumulativeLast;
                IxCAVO(data.xCAVO).mint((priceCumulativeLast - prevPriceCumulativeLast) / (data.blockTimestampLast - prevBlockTimestampLast));
            }
        } else {
            _update(details.balance0, details.balance1, _reserve0, _reserve1);
        }
        emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
    }

    // force balances to match reserves
    function skim(address to) external override lock {
        address _token0 = data.token0; // gas savings
        address _token1 = data.token1; // gas savings
        _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(data.reserve0));
        _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(data.reserve1));
    }

    // force reserves to match balances
    function sync() external override lock {
        _update(IERC20(data.token0).balanceOf(address(this)), IERC20(data.token1).balanceOf(address(this)), data.reserve0, data.reserve1);
    }

    function factory() external view override returns (address) {
        return data.factory;
    }

    function token0() external view override returns (address) {
        return data.token0;
    }

    function token1() external view override returns (address) {
        return data.token1;
    }

    function router() external view override returns (address) {
        return data.router;
    }

    function accumulatedUnclaimedLiquidity() external view override returns (uint) {
        return data.accumulatedUnclaimedLiquidity;
    }

    function price0CumulativeLast() external view override returns (uint) {
        return data.price0CumulativeLast;
    }

    function price1CumulativeLast() external view override returns (uint) {
        return data.price1CumulativeLast;
    }

    function claimLiquidity(address account, uint256 amount) external override lock returns (uint) {
        return data.claimLiquidity(account, amount);
    }

    function claimAllLiquidity(address account) external override lock returns (uint) {
        return data.claimAllLiquidity(account);
    }

    function accumulatedLiquidityGrowth() external view override returns (uint) {
        return data.accumulatedLiquidityGrowth();
    }

    function unclaimedLiquidityOf(address account) external view override returns (uint) {
        return data.unclaimedLiquidityOf(account);
    }

    function compoundLiquidity() external override lock {
        emit Compound(msg.sender, data.compoundLiquidity());
    }

    function _mint(address to, uint value, uint k) private {
        data.mint(to, value, k);
        emit Transfer(address(0), to, value);
    }

    function _burn(address from, uint value) private {
        data.burn(from, value);
        emit Transfer(from, address(0), value);
    }

    function _transfer(address from, address to, uint value) internal virtual override {
        data.transfer(from, to, value);
        emit Transfer(from, to, value);
    }
}
// File: contracts/interfaces/IExcavoCallee.sol



pragma solidity >=0.6.6;

interface IExcavoCallee {
    function ExcavoCall(address sender, uint amount0, uint amount1, bytes calldata data) external;
}

// File: contracts/libraries/PairLibrary.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.6;

import '../interfaces/IERC20.sol';
import '../interfaces/IxEXCV.sol';
import '../interfaces/IxCAVO.sol';
import '../interfaces/IExcavoFactory.sol';
import '../interfaces/IExcavoCallee.sol';
import '../interfaces/IERC20.sol';
import './SafeMath.sol';
import './Math.sol';

library PairLibrary {
    using SafeMath for uint;

    struct Data {
        address factory;
        address token0;
        address token1;
        address router;
        uint totalSupply;
        
        uint accumulatedUnclaimedLiquidity;
    
        uint112 reserve0;           // uses single storage slot, accessible via getReserves
        uint112 reserve1;           // uses single storage slot, accessible via getReserves
        uint32 blockTimestampLast;  // uses single storage slot, accessible via getReserves

        uint price0CumulativeLast;
        uint price1CumulativeLast;
    
        mapping(address => uint) kOf;
        mapping(address => uint) lastUnclaimedLiquidityOf;
        mapping(address => uint) virtualKOf;
        mapping(address => uint) balanceOf;

        uint totalK;
        address xEXCV;
        address xCAVO;
        address CAVO;
    }

    function initialize(Data storage self, address _token0, address _token1, address _router) external {
        require(msg.sender == self.factory, 'Excavo: FORBIDDEN'); // sufficient check
        self.token0 = _token0;
        self.token1 = _token1;
        self.router = _router;
    }       

    function setCAVO(Data storage self, address _CAVO, address _xCAVO) external {
        require(msg.sender == self.factory, 'Excavo: FORBIDDEN'); // sufficient check
        self.CAVO = _CAVO;
        self.xCAVO = _xCAVO;
        if (_CAVO != address(0)) {
            IxCAVO(_xCAVO).registerPairCreation();
        }
    }

    function setxEXCV(Data storage self, address _xEXCV) external {
        require(self.xEXCV == address(0) && msg.sender == IExcavoFactory(self.factory).feeToSetter(), "Excavo: FORBIDDEN"); 
        self.xEXCV = _xEXCV;
        IxEXCV(_xEXCV).addPair(self.token0, self.token1);
    }

    function claimLiquidity(Data storage self, address account, uint256 amount) external returns (uint claimAmount) {
        require(msg.sender == self.xEXCV || msg.sender == self.xCAVO, "Excavo: FORBIDDEN");
        _accumulateLiquidityGrowth(
            self,
            IERC20(self.token0).balanceOf(address(this)), 
            IERC20(self.token1).balanceOf(address(this)), 
            self.balanceOf[account], 
            self.totalSupply, 
            account
        );
        claimAmount = self.lastUnclaimedLiquidityOf[account].sub(amount); 
        self.lastUnclaimedLiquidityOf[account] = claimAmount;
    }

    function claimAllLiquidity(Data storage self, address account) public returns (uint claimAmount) {
        require(msg.sender == self.xEXCV || msg.sender == self.xCAVO, "Excavo: FORBIDDEN");
        self.virtualKOf[address(this)] = _accumulateTotalLiquidityGrowth(self);
        _accumulateLiquidityGrowth(
            self,
            IERC20(self.token0).balanceOf(address(this)), 
            IERC20(self.token1).balanceOf(address(this)), 
            self.balanceOf[account], 
            self.totalSupply, 
            account
        );
        claimAmount = self.lastUnclaimedLiquidityOf[account];
        self.lastUnclaimedLiquidityOf[account] = 0;
    }

    function accumulatedLiquidityGrowth(Data storage self) external view returns (uint) {
        uint lastTotalK = self.virtualKOf[address(this)].add(self.totalK);
        uint newTotalK = _calculateNewK(
            self.reserve0, 
            self.reserve1, 
            self.totalSupply,
            self.totalSupply,
            lastTotalK
        );
        if (newTotalK > lastTotalK) {
            return self.accumulatedUnclaimedLiquidity + (newTotalK - lastTotalK); // overflow desired
        }
        return self.accumulatedUnclaimedLiquidity;
    }

    function unclaimedLiquidityOf(Data storage self, address account) external view returns (uint) {
        uint newK = _calculateNewK(
            IERC20(self.token0).balanceOf(address(this)), 
            IERC20(self.token1).balanceOf(address(this)), 
            self.balanceOf[account],
            self.totalSupply,
            self.virtualKOf[account]
        );
        if (newK > self.virtualKOf[account]) {
            uint liquidityGrowth = newK - self.virtualKOf[account]; // cannot overflow
            return self.lastUnclaimedLiquidityOf[account].add(liquidityGrowth);
        }
        return self.lastUnclaimedLiquidityOf[account];
    }

    function compoundLiquidity(Data storage self) external returns (uint) {
        self.virtualKOf[address(this)] = _accumulateTotalLiquidityGrowth(self);
        return _accumulateLiquidityGrowth(
            self,
            IERC20(self.token0).balanceOf(address(this)), 
            IERC20(self.token1).balanceOf(address(this)), 
            self.balanceOf[msg.sender], 
            self.totalSupply, 
            msg.sender
        );
    }

    function mint(Data storage self, address to, uint value, uint k) external {
        _accumulateTotalLiquidityGrowth(self);
        _accumulateLiquidityGrowth(
            self,
            IERC20(self.token0).balanceOf(address(this)), 
            IERC20(self.token1).balanceOf(address(this)), 
            self.balanceOf[to], 
            self.totalSupply, 
            to
        );
        uint newKTo = self.kOf[to].add(k);
        _updateK(self, to, newKTo, newKTo);
        self.totalK = self.totalK.add(k);
        self.virtualKOf[address(this)] = 0;
       
        uint newBalance = self.balanceOf[to].add(value);
        self.totalSupply = self.totalSupply.add(value);
        self.balanceOf[to] = newBalance;
    }

    function burn(Data storage self, address from, uint value) external {
        uint newBalance = self.balanceOf[from].sub(value);
        _accumulateTotalLiquidityGrowth(self);
        _accumulateLiquidityGrowth(
            self,
            IERC20(self.token0).balanceOf(address(this)), 
            IERC20(self.token1).balanceOf(address(this)), 
            self.balanceOf[from], 
            self.totalSupply, 
            from
        );
        uint newK = self.kOf[from].mul(newBalance).div(self.balanceOf[from]);
        _updateK(self, from, newK, newK);
        
        self.totalK = self.totalK.sub(self.kOf[from].sub(newK));
        self.virtualKOf[address(this)] = 0;
        self.balanceOf[from] = newBalance;
        self.totalSupply = self.totalSupply.sub(value);
    }

    function transfer(Data storage self, address from, address to, uint value) external {
        uint newBalanceFrom = self.balanceOf[from].sub(value);
        uint newBalanceTo = self.balanceOf[to].add(value);

        uint balance0 = IERC20(self.token0).balanceOf(address(this));
        uint balance1 = IERC20(self.token1).balanceOf(address(this));
        uint _totalSupply = self.totalSupply;
        _accumulateLiquidityGrowth(
            self,
            balance0, 
            balance1, 
            self.balanceOf[from], 
            _totalSupply, 
            from
        );
        _accumulateLiquidityGrowth(
            self,
            balance0, 
            balance1, 
            self.balanceOf[to], 
            _totalSupply, 
            to
        );

        uint newKFrom = self.kOf[from].mul(newBalanceFrom).div(self.balanceOf[from]);
        uint newKTo = self.kOf[to].add(self.kOf[from].sub(newKFrom));
        uint virtualKTo = _calculateNewK(
            balance0, 
            balance1, 
            newBalanceTo,
            _totalSupply,
            newKTo
        );
        uint virtualKFrom = _calculateNewK(
            balance0, 
            balance1, 
            newBalanceFrom,
            _totalSupply,
            newKFrom
        );
        _updateK(self, to, newKTo, virtualKTo);
        _updateK(self, from, newKFrom, virtualKFrom);

        self.balanceOf[from] = newBalanceFrom;
        self.balanceOf[to] = newBalanceTo;
    }

    function _calculateNewK(
        uint balance0, 
        uint balance1,
        uint liquidity, 
        uint totalSupply,
        uint virtualK
    ) private pure returns (uint k) {
        if (totalSupply == 0) {
            return virtualK;
        } 
        uint amount0 = liquidity.mul(balance0) / totalSupply;
        uint amount1 = liquidity.mul(balance1) / totalSupply;
        if (amount0 == 0 || amount1 == 0) {
            return virtualK;
        }
        k = Math.sqrt(amount0.mul(amount1));
    }   

    function _accumulateTotalLiquidityGrowth(Data storage self) private returns (uint virtualTotalK) {
        virtualTotalK = self.virtualKOf[address(this)];
        uint lastTotalK = virtualTotalK.add(self.totalK);
        uint newTotalK = _calculateNewK(
            self.reserve0, 
            self.reserve1, 
            self.totalSupply,
            self.totalSupply,
            lastTotalK
        );
        if (newTotalK > lastTotalK) {
            virtualTotalK = newTotalK.sub(self.totalK);
            self.accumulatedUnclaimedLiquidity = self.accumulatedUnclaimedLiquidity + (newTotalK - lastTotalK); // overflow desired
        }
    }

    function _accumulateLiquidityGrowth(
        Data storage self, 
        uint balance0, 
        uint balance1,
        uint liquidity, 
        uint totalSupply,
        address account
    ) private returns (uint liquidityGrowth) {
        uint virtualK = self.virtualKOf[account];
        if (account == address(this)) {
            return virtualK;
        }
        uint newK = _calculateNewK(
            balance0, 
            balance1, 
            liquidity,
            totalSupply,
            virtualK
        );
        if (newK > virtualK) {
            liquidityGrowth = newK - virtualK; // cannot overflow
            self.virtualKOf[account] = newK;
            self.lastUnclaimedLiquidityOf[account] = self.lastUnclaimedLiquidityOf[account].add(liquidityGrowth);
        }
    }

    function _updateK(Data storage self, address account, uint k, uint virtualK) private {
        self.kOf[account] = k;
        self.virtualKOf[account] = virtualK;
    }
}
// File: contracts/BaseExcavoPair.sol



pragma solidity >=0.6.6;

import './interfaces/IExcavoERC20.sol';
import './libraries/SafeMath.sol';
import './libraries/PairLibrary.sol';

abstract contract BaseExcavoPair is IExcavoERC20 {
    using SafeMath for uint;
    using PairLibrary for PairLibrary.Data;

    string public constant override name = 'Excavo';
    string public constant override symbol = 'EXCAVO';
    uint8 public constant override decimals = 18;
    
    PairLibrary.Data internal data;
    mapping(address => mapping(address => uint)) public override allowance;

    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    constructor() public {}

    function totalSupply() external view override returns (uint) {
        return data.totalSupply;
    }

    function balanceOf(address account) external view override returns (uint) {
        return data.balanceOf[account];
    }

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

    function approve(address spender, uint value) external override returns (bool) {
        _approve(msg.sender, spender, value);
        return true;
    }

    function transfer(address to, uint value) external override returns (bool) {
        _transfer(msg.sender, to, value);
        return true;
    }

    function transferFrom(address from, address to, uint value) external override 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;
    }
}

// File: contracts/CAVOStaking.sol



pragma solidity >=0.6.6;

import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import './libraries/TransferHelper.sol';
import './libraries/SafeMath.sol';
import './libraries/Math.sol';
import './libraries/ExcavoLibrary.sol';
import './interfaces/ICAVO.sol';
import './interfaces/IxCAVO.sol';
import './interfaces/IEXCV.sol';
import './interfaces/IWETH.sol';
import './interfaces/IExcavoFactory.sol';
import './interfaces/IExcavoRouter.sol';
import './interfaces/IExcavoERC20.sol';
import './interfaces/IExcavoPair.sol';
import './interfaces/ICAVOStaking.sol';

contract CAVOStaking is ICAVOStaking, ReentrancyGuard {
    using SafeMath for uint;

    string public constant override name = 'xCAVO';
    string public constant override symbol = 'xCAVO';
    uint8 public constant override decimals = 18;
    
    mapping(address => mapping(address => uint)) public override allowance;
    mapping(address => uint) public override liquidityOf;

    address private WETH;
    address private xCAVO;
    address private CAVO;
    address private EXCV;
    address private router;
    address private factory;
    address private creator;
    address private excvEthPair;

    uint constant private BASE = 10**18;
    uint private accumulatedKGrowthOverTotalSupplyInBase; 
    uint private accumulatedKGrowth;
    uint private lastTotalK; 
    mapping(address => uint) private lastAccumulatedKGrowthOverTotalSupplyInBase;
    mapping(address => uint) private lastAccumulatedKGrowth;
    mapping(address => uint) private lastAccumulatedMintableCAVOAmount;
    mapping(address => uint) private _unclaimedOf;

    event Redeem(address indexed sender, address indexed recipient, uint amount);
    event Stake(address indexed sender, uint liquidity);
    event Unstake(address indexed sender, uint liquidity);

    constructor(address _router) public {
        CAVO = IExcavoRouter(_router).CAVO();
        require(ICAVO(CAVO).creator() == msg.sender, 'EXCAVO: FORBIDDEN');
        router = _router;
        factory = IExcavoRouter(_router).factory();
        WETH = IExcavoRouter(_router).WETH();
        xCAVO = ICAVO(CAVO).xCAVOToken();
        EXCV = ICAVO(CAVO).EXCVToken();
        creator = msg.sender;
        excvEthPair = ExcavoLibrary.pairFor(factory, EXCV, WETH);
        IExcavoERC20(EXCV).approve(_router, uint(-1));
        address excvEthPairCheck = IExcavoFactory(factory).getPair(EXCV, WETH);
        if (excvEthPairCheck == address(0)) {
            excvEthPairCheck = IExcavoFactory(factory).createPair(WETH, EXCV);
        }
        require(excvEthPair == excvEthPairCheck, 'EXCAVO: INVALID');
        IExcavoERC20(excvEthPair).approve(_router, uint(-1));
    }

    function approve(address spender, uint value) external override returns (bool) {
        revert('CAVO: FORBIDDEN');
    }

    function transfer(address to, uint value) external override returns (bool) {
        revert('CAVO: FORBIDDEN');
    }

    function transferFrom(address from, address to, uint value) external override returns (bool) {
        revert('CAVO: FORBIDDEN');
    }

    function totalSupply() public view override returns (uint) {
        return IExcavoERC20(CAVO).balanceOf(address(this));
    }

    function emergencyWithdraw() external override nonReentrant {
        require(msg.sender == creator, 'CAVO: FORBIDDEN');
        TransferHelper.safeTransfer(CAVO, creator, IExcavoERC20(CAVO).balanceOf(address(this)));
    }
    
    function stakeLiquidityETH(
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        uint deadline
    ) external override payable ensure(deadline) nonReentrant returns (uint amountToken, uint amountETH, uint liquidity) {
        _accumulateK(msg.sender);
        
        (amountToken, amountETH) = _addLiquidity(
            EXCV,
            WETH,
            amountTokenDesired,
            msg.value,
            amountTokenMin,
            amountETHMin
        );
        address pair = ExcavoLibrary.pairFor(factory, EXCV, WETH);
        TransferHelper.safeTransferFrom(EXCV, msg.sender, pair, amountToken);
        IWETH(WETH).deposit{value: amountETH}();
        assert(IWETH(WETH).transfer(pair, amountETH));
        liquidity = IExcavoPair(pair).mint(address(this));
        // refund dust eth, if any
        if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);

        liquidityOf[msg.sender] = liquidityOf[msg.sender].add(liquidity);
        _update(msg.sender);

        emit Stake(msg.sender, liquidity);
    }

    function unstakeLiquidityETH(
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external override nonReentrant {
        _accumulateK(msg.sender);
        
        liquidityOf[msg.sender] = liquidityOf[msg.sender].sub(liquidity);
        
        IExcavoRouter(router).removeLiquidityETH(
            EXCV,
            liquidity,
            amountTokenMin,
            amountETHMin,
            to,
            deadline
        );

        _update(msg.sender);

        emit Unstake(msg.sender, liquidity);
    }

    function redeem(address to) external override nonReentrant {
        (uint newK, uint newTotalK, uint unclaimed) = _accumulateK(msg.sender);
        _update(msg.sender);
        uint amount = balanceOf(to);
        require(amount > 0, 'CAVO: INSUFFICIENT_AMOUNT');
        _unclaimedOf[msg.sender] = 0;
        TransferHelper.safeTransfer(CAVO, to, amount);
        
        emit Redeem(msg.sender, to, amount);
    }

    function balanceOf(address account) public view override returns (uint) {
        (,, uint unclaimed) = unclaimedOf(account);
        return Math.min(unclaimed, totalSupply());
    }

    function _addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin
    ) internal virtual returns (uint amountA, uint amountB) {
        // create the pair if it doesn't exist yet
        if (IExcavoFactory(factory).getPair(tokenA, tokenB) == address(0)) {
            IExcavoFactory(factory).createPair(tokenA, tokenB);
        }

        (uint reserveA, uint reserveB) = ExcavoLibrary.getReserves(factory, tokenA, tokenB);

        if (reserveA == 0 && reserveB == 0) {
            (amountA, amountB) = (amountADesired, amountBDesired);
        } else {
            uint amountBOptimal = ExcavoLibrary.quote(amountADesired, reserveA, reserveB);
            if (amountBOptimal <= amountBDesired) {
                require(amountBOptimal >= amountBMin, 'ExcavoRouter: INSUFFICIENT_B_AMOUNT');
                (amountA, amountB) = (amountADesired, amountBOptimal);
            } else {
                uint amountAOptimal = ExcavoLibrary.quote(amountBDesired, reserveB, reserveA);
                assert(amountAOptimal <= amountADesired);
                require(amountAOptimal >= amountAMin, 'ExcavoRouter: INSUFFICIENT_A_AMOUNT');
                (amountA, amountB) = (amountAOptimal, amountBDesired);
            }
        }
    }

    function unclaimedOf(address account) public view override returns (uint kGrowthOverTotalSupplyInBase, uint kGrowth, uint unclaimed) {
        uint totalLiquidity = IExcavoPair(excvEthPair).balanceOf(address(this));
        if (totalLiquidity == 0) {
            return (0, 0, _unclaimedOf[account]);
        }
        uint newTotalK = _getK(); // can be zero
        if (newTotalK > lastTotalK) {
            kGrowth = newTotalK - lastTotalK;
            kGrowthOverTotalSupplyInBase = kGrowth.mul(BASE) / totalLiquidity;
        }
        uint newUnclaimed = _calculateNewUnclaimed(account, kGrowthOverTotalSupplyInBase, kGrowth);
        unclaimed = _unclaimedOf[account].add(newUnclaimed);
    }

    function _calculateNewUnclaimed(address account, uint kGrowthOverTotalSupplyInBase, uint kGrowth) private view returns (uint newUnclaimed) {
        uint totalKGrowth = (accumulatedKGrowth + kGrowth) - lastAccumulatedKGrowth[account];
        if (totalKGrowth > 0) {
            uint newCAVO = (IxCAVO(xCAVO).accumulatedMintableCAVOAmount() - lastAccumulatedMintableCAVOAmount[account]) / 200;  
            uint newKGrowthInBase = ((accumulatedKGrowthOverTotalSupplyInBase + kGrowthOverTotalSupplyInBase) - lastAccumulatedKGrowthOverTotalSupplyInBase[account]);
            uint userKGrowthInBase = liquidityOf[account].mul(newKGrowthInBase);
            newUnclaimed = (userKGrowthInBase.mul(newCAVO) / BASE) / totalKGrowth;
        }
    }

    function _accumulateK(address account) private returns (uint kGrowthOverTotalSupplyInBase, uint kGrowth, uint unclaimed) {
        (kGrowthOverTotalSupplyInBase, kGrowth, unclaimed) = unclaimedOf(account);
        if (kGrowthOverTotalSupplyInBase > 0) {
            accumulatedKGrowthOverTotalSupplyInBase += kGrowthOverTotalSupplyInBase; // overflow desired
            accumulatedKGrowth += kGrowth;
        }
        if (unclaimed > _unclaimedOf[account]) {
            _unclaimedOf[account] = unclaimed;
        }
    }

    function _getK() private view returns (uint k) {
        uint totalSupply = IExcavoPair(excvEthPair).totalSupply();
        if (totalSupply > 0) {
            uint stakedLiquidity = IExcavoPair(excvEthPair).balanceOf(address(this));
            (uint _reserve0, uint _reserve1,) = IExcavoPair(excvEthPair).getReserves();
            uint amount0 = stakedLiquidity.mul(_reserve0) / totalSupply;
            uint amount1 = stakedLiquidity.mul(_reserve1) / totalSupply;
            k = Math.sqrt(amount0.mul(amount1)); 
        }
    }

    function _update(address account) private {
        lastTotalK = _getK(); // can be zero
        lastAccumulatedMintableCAVOAmount[account] = IxCAVO(xCAVO).accumulatedMintableCAVOAmount();
        lastAccumulatedKGrowthOverTotalSupplyInBase[account] = accumulatedKGrowthOverTotalSupplyInBase;
        lastAccumulatedKGrowth[account] = accumulatedKGrowth;
    }

    modifier ensure(uint deadline) {
        require(deadline >= block.timestamp, 'ExcavoRouter: EXPIRED');
        _;
    }
}
// File: contracts/interfaces/IWETH.sol



pragma solidity >=0.6.6;

interface IWETH {
    function deposit() external payable;
    function transfer(address to, uint value) external returns (bool);
    function withdraw(uint) external;
}

// File: contracts/interfaces/IExcavoRouter.sol



pragma solidity >=0.6.6;

interface IExcavoRouter {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);
    function CAVO() external view returns (address);
    
    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 removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    // function removeLiquidityWithPermit(
    //     address tokenA,
    //     address tokenB,
    //     uint liquidity,
    //     uint amountAMin,
    //     uint amountBMin,
    //     address to,
    //     uint deadline,
    //     bool approveMax, uint8 v, bytes32 r, bytes32 s
    // ) external returns (uint amountA, uint amountB);
    // function removeLiquidityETHWithPermit(
    //     address token,
    //     uint liquidity,
    //     uint amountTokenMin,
    //     uint amountETHMin,
    //     address to,
    //     uint deadline,
    //     bool approveMax, uint8 v, bytes32 r, bytes32 s
    // ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

    function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external view returns (uint amountOut);
    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external view returns (uint amountIn);
    function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
    function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);

    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountETH);
    // function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
    //     address token,
    //     uint liquidity,
    //     uint amountTokenMin,
    //     uint amountETHMin,
    //     address to,
    //     uint deadline,
    //     bool approveMax, uint8 v, bytes32 r, bytes32 s
    // ) external returns (uint amountETH);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable;
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external;
}

// File: contracts/interfaces/ICAVOStaking.sol



pragma solidity >=0.6.6;

import './IExcavoERC20.sol';

interface ICAVOStaking is IExcavoERC20 {
      function stakeLiquidityETH(
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);

    function unstakeLiquidityETH(
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external;

    function redeem(address to) external;

    function liquidityOf(address) external view returns (uint);

    function unclaimedOf(address account) external view returns (uint kGrowthOverTotalSupplyInBase, uint kGrowth, uint unclaimed);

    function emergencyWithdraw() external;
}
// File: contracts/ExcavoERC20.sol



pragma solidity >=0.6.6;

import './interfaces/IExcavoERC20.sol';
import './libraries/SafeMath.sol';

contract ExcavoERC20 is IExcavoERC20 {
    using SafeMath for uint;

    string public constant override name = 'Excavo';
    string public constant override symbol = 'EXCAVO';
    uint8 public constant override decimals = 18;
    uint  public override totalSupply;
    mapping(address => uint) public override balanceOf;
    mapping(address => mapping(address => uint)) public override allowance;

    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    constructor() public {}

    function _mint(address to, uint value) internal virtual {
        totalSupply = totalSupply.add(value);
        balanceOf[to] = balanceOf[to].add(value);
        emit Transfer(address(0), to, value);
    }

    function _burn(address from, uint value) internal virtual {
        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) internal virtual {
        balanceOf[from] = balanceOf[from].sub(value);
        balanceOf[to] = balanceOf[to].add(value);
        emit Transfer(from, to, value);
    }

    function approve(address spender, uint value) external override returns (bool) {
        _approve(msg.sender, spender, value);
        return true;
    }

    function transfer(address to, uint value) external override returns (bool) {
        _transfer(msg.sender, to, value);
        return true;
    }

    function transferFrom(address from, address to, uint value) external override 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;
    }
}

// File: contracts/test/ERC20.sol



pragma solidity >=0.6.6;

import '../ExcavoERC20.sol';

contract ERC20 is ExcavoERC20 {
    constructor(uint _totalSupply) public {
        _mint(msg.sender, _totalSupply);
    }
}
// File: contracts/test/TestERC20.sol



pragma solidity >=0.6.6;

import '../libraries/SafeMath.sol';

contract TestERC20 {
    using SafeMath for uint;

    string public constant name = 'Test Token';
    string public constant symbol = 'TT';
    uint8 public constant decimals = 18;
    uint  public totalSupply;
    mapping(address => uint) public balanceOf;
    mapping(address => mapping(address => uint)) public allowance;

    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    constructor(uint _totalSupply) public {
        _mint(msg.sender, _totalSupply);
    }

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

// File: contracts/test/DeflatingERC20.sol



pragma solidity >=0.6.6;

import '../libraries/SafeMath.sol';

contract DeflatingERC20 {
    using SafeMath for uint;

    string public constant name = 'Deflating Test Token';
    string public constant symbol = 'DTT';
    uint8 public constant decimals = 18;
    uint  public totalSupply;
    mapping(address => uint) public balanceOf;
    mapping(address => mapping(address => uint)) public allowance;

    event Approval(address indexed owner, address indexed spender, uint value);
    event Transfer(address indexed from, address indexed to, uint value);

    constructor(uint _totalSupply) public {
        _mint(msg.sender, _totalSupply);
    }

    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 {
        uint burnAmount = value / 100;
        _burn(from, burnAmount);
        uint transferAmount = value.sub(burnAmount);
        balanceOf[from] = balanceOf[from].sub(transferAmount);
        balanceOf[to] = balanceOf[to].add(transferAmount);
        emit Transfer(from, to, transferAmount);
    }

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

// File: contracts/ExcavoRouter.sol



pragma solidity >=0.6.6;

import './interfaces/IExcavoFactory.sol';
import './libraries/TransferHelper.sol';

import './interfaces/IExcavoRouter.sol';
import './libraries/ExcavoLibrary.sol';
import "./libraries/TraderDiscount.sol";
import './libraries/SafeMath.sol';
import './interfaces/IERC20.sol';
import './interfaces/IWETH.sol';
import './interfaces/ICAVO.sol';

contract ExcavoRouter is IExcavoRouter {
    using SafeMath for uint;

    address public immutable override factory;
    address public immutable override WETH;
    address public immutable override CAVO;

    modifier ensure(uint deadline) {
        require(deadline >= block.timestamp, 'ExcavoRouter: EXPIRED');
        _;
    }

    constructor(address _factory, address _WETH, address _CAVO) public {
        factory = _factory;
        WETH = _WETH;
        CAVO = _CAVO;
    }

    receive() external payable {
        assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
    }

    // **** ADD LIQUIDITY ****
    function _addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin
    ) internal virtual returns (uint amountA, uint amountB) {
        // create the pair if it doesn't exist yet
        if (IExcavoFactory(factory).getPair(tokenA, tokenB) == address(0)) {
            IExcavoFactory(factory).createPair(tokenA, tokenB);
        }

        (uint reserveA, uint reserveB) = ExcavoLibrary.getReserves(factory, tokenA, tokenB);

        if (reserveA == 0 && reserveB == 0) {
            (amountA, amountB) = (amountADesired, amountBDesired);
        } else {
            uint amountBOptimal = ExcavoLibrary.quote(amountADesired, reserveA, reserveB);
            if (amountBOptimal <= amountBDesired) {
                require(amountBOptimal >= amountBMin, 'ExcavoRouter: INSUFFICIENT_B_AMOUNT');
                (amountA, amountB) = (amountADesired, amountBOptimal);
            } else {
                uint amountAOptimal = ExcavoLibrary.quote(amountBDesired, reserveB, reserveA);
                assert(amountAOptimal <= amountADesired);
                require(amountAOptimal >= amountAMin, 'ExcavoRouter: INSUFFICIENT_A_AMOUNT');
                (amountA, amountB) = (amountAOptimal, amountBDesired);
            }
        }
    }

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
        (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
        address pair = ExcavoLibrary.pairFor(factory, tokenA, tokenB);
        TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
        TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
        liquidity = IExcavoPair(pair).mint(to);  
    }
    
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
        (amountToken, amountETH) = _addLiquidity(
            token,
            WETH,
            amountTokenDesired,
            msg.value,
            amountTokenMin,
            amountETHMin
        );
        address pair = ExcavoLibrary.pairFor(factory, token, WETH);
        TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
        IWETH(WETH).deposit{value: amountETH}();
        assert(IWETH(WETH).transfer(pair, amountETH));
        liquidity = IExcavoPair(pair).mint(to);
        // refund dust eth, if any
        if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
    }

    // **** REMOVE LIQUIDITY ****
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
        address pair = ExcavoLibrary.pairFor(factory, tokenA, tokenB);
        IExcavoPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
        (uint amount0, uint amount1) = IExcavoPair(pair).burn(to);
        (address token0,) = ExcavoLibrary.sortTokens(tokenA, tokenB);
        (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
        require(amountA >= amountAMin, 'ExcavoRouter: INSUFFICIENT_A_AMOUNT');
        require(amountB >= amountBMin, 'ExcavoRouter: INSUFFICIENT_B_AMOUNT');
    }
    
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
        (amountToken, amountETH) = removeLiquidity(
            token,
            WETH,
            liquidity,
            amountTokenMin,
            amountETHMin,
            address(this),
            deadline
        );
        TransferHelper.safeTransfer(token, to, amountToken);
        IWETH(WETH).withdraw(amountETH);
        TransferHelper.safeTransferETH(to, amountETH);
    }

    // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
    function removeLiquidityETHSupportingFeeOnTransferTokens(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) public virtual override ensure(deadline) returns (uint amountETH) {
        (, amountETH) = removeLiquidity(
            token,
            WETH,
            liquidity,
            amountTokenMin,
            amountETHMin,
            address(this),
            deadline
        );
        TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
        IWETH(WETH).withdraw(amountETH);
        TransferHelper.safeTransferETH(to, amountETH);
    }
    // function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
    //     address token,
    //     uint liquidity,
    //     uint amountTokenMin,
    //     uint amountETHMin,
    //     address to,
    //     uint deadline,
    //     bool approveMax, uint8 v, bytes32 r, bytes32 s
    // ) external virtual override returns (uint amountETH) {
    //     // address pair = ExcavoLibrary.pairFor(factory, token, WETH);
    //     // uint value = approveMax ? uint(-1) : liquidity;
    //     // IExcavoPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
    //     // amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
    //     //     token, liquidity, amountTokenMin, amountETHMin, to, deadline
    //     // );
    // }

    // **** SWAP ****
    // requires the initial amount to have already been sent to the first pair
    function _swap(uint[] memory amounts, address[] memory path, address _to, uint discount) internal virtual {
        for (uint i; i < path.length - 1; i++) {
            (address input, address output) = (path[i], path[i + 1]);
            (address token0,) = ExcavoLibrary.sortTokens(input, output);
            uint amountOut = amounts[i + 1];
            (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
            address to = i < path.length - 2 ? ExcavoLibrary.pairFor(factory, output, path[i + 2]) : _to;
            
            IExcavoPair(ExcavoLibrary.pairFor(factory, input, output)).swap(
                amount0Out, amount1Out, to, new bytes(0), discount
            );
        }
    }
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        amounts = ExcavoLibrary.getAmountsOut(factory, amountIn, path, discount);
        require(amounts[amounts.length - 1] >= amountOutMin, 'ExcavoRouter: INSUFFICIENT_OUTPUT_AMOUNT');
        TransferHelper.safeTransferFrom(
            path[0], msg.sender, ExcavoLibrary.pairFor(factory, path[0], path[1]), amounts[0]
        );
        _swap(amounts, path, to, discount);
    }
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external virtual override ensure(deadline) returns (uint[] memory amounts) {
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        amounts = ExcavoLibrary.getAmountsIn(factory, amountOut, path, discount);
        require(amounts[0] <= amountInMax, 'ExcavoRouter: EXCESSIVE_INPUT_AMOUNT');
        TransferHelper.safeTransferFrom(
            path[0], msg.sender, ExcavoLibrary.pairFor(factory, path[0], path[1]), amounts[0]
        );
        _swap(amounts, path, to, discount);
    }
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable 
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'ExcavoRouter: INVALID_PATH');
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        amounts = ExcavoLibrary.getAmountsOut(factory, msg.value, path, discount);
        require(amounts[amounts.length - 1] >= amountOutMin, 'ExcavoRouter: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(ExcavoLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to, discount);
    }
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        virtual
        override 
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[path.length - 1] == WETH, 'ExcavoRouter: INVALID_PATH');
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        amounts = ExcavoLibrary.getAmountsIn(factory, amountOut, path, discount);
        require(amounts[0] <= amountInMax, 'ExcavoRouter: EXCESSIVE_INPUT_AMOUNT');
        TransferHelper.safeTransferFrom(
            path[0], msg.sender, ExcavoLibrary.pairFor(factory, path[0], path[1]), amounts[0]
        );
        _swap(amounts, path, address(this), discount);
        IWETH(WETH).withdraw(amounts[amounts.length - 1]);
        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
    }
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        virtual
        override 
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[path.length - 1] == WETH, 'ExcavoRouter: INVALID_PATH');
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        amounts = ExcavoLibrary.getAmountsOut(factory, amountIn, path, discount);
        require(amounts[amounts.length - 1] >= amountOutMin, 'ExcavoRouter: INSUFFICIENT_OUTPUT_AMOUNT');
        TransferHelper.safeTransferFrom(
            path[0], msg.sender, ExcavoLibrary.pairFor(factory, path[0], path[1]), amounts[0]
        );
        _swap(amounts, path, address(this), discount);
        IWETH(WETH).withdraw(amounts[amounts.length - 1]);
        TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
    }
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        virtual
        override
        payable 
        ensure(deadline)
        returns (uint[] memory amounts)
    {
        require(path[0] == WETH, 'ExcavoRouter: INVALID_PATH');
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        amounts = ExcavoLibrary.getAmountsIn(factory, amountOut, path, discount);
        require(amounts[0] <= msg.value, 'ExcavoRouter: EXCESSIVE_INPUT_AMOUNT');
        IWETH(WETH).deposit{value: amounts[0]}();
        assert(IWETH(WETH).transfer(ExcavoLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
        _swap(amounts, path, to, discount);
        // refund dust eth, if any
        if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
    }

    // **** SWAP (supporting fee-on-transfer tokens) ****
    // requires the initial amount to have already been sent to the first pair
    function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to, uint k) internal virtual {
        for (uint i; i < path.length - 1; i++) {
            {
            //(address input, address output) = (path[i], path[i + 1]);
            (address token0,) = ExcavoLibrary.sortTokens(path[i], path[i + 1]);
            IExcavoPair pair = IExcavoPair(ExcavoLibrary.pairFor(factory, path[i], path[i + 1]));
            uint amountInput;
            uint amountOutput;
            { // scope to avoid stack too deep errors
            (uint reserve0, uint reserve1,) = pair.getReserves();
            (uint reserveInput, uint reserveOutput) = path[i] == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
            amountInput = IERC20(path[i]).balanceOf(address(pair)).sub(reserveInput);
            amountOutput = ExcavoLibrary.getAmountOut(amountInput, reserveInput, reserveOutput, k);
            }

            {
            (uint amount0Out, uint amount1Out) = path[i] == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
            address to = i < path.length - 2 ? ExcavoLibrary.pairFor(factory, path[i + 1], path[i + 2]) : _to;
            pair.swap(amount0Out, amount1Out, to, new bytes(0), k);
            }
            }
        }
    }

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external virtual override ensure(deadline) {
        TransferHelper.safeTransferFrom(
            path[0], msg.sender, ExcavoLibrary.pairFor(factory, path[0], path[1]), amountIn
        );
        uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
        {
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        _swapSupportingFeeOnTransferTokens(path, to, discount);
        }
        require(
            IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
            'ExcavoRouter: INSUFFICIENT_OUTPUT_AMOUNT'
        );
    }
    function swapExactETHForTokensSupportingFeeOnTransferTokens(
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    )
        external
        virtual
        override
        payable 
        ensure(deadline)
    {
        require(path[0] == WETH, 'ExcavoRouter: INVALID_PATH');
        uint amountIn = msg.value;
        IWETH(WETH).deposit{value: amountIn}();
        assert(IWETH(WETH).transfer(ExcavoLibrary.pairFor(factory, path[0], path[1]), amountIn));
        uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        _swapSupportingFeeOnTransferTokens(path, to, discount);
        require(
            IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
            'ExcavoRouter: INSUFFICIENT_OUTPUT_AMOUNT'
        );
    }
    function swapExactTokensForETHSupportingFeeOnTransferTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    )
        external
        virtual
        override 
        ensure(deadline)
    {
        require(path[path.length - 1] == WETH, 'ExcavoRouter: INVALID_PATH');
        TransferHelper.safeTransferFrom(
            path[0], msg.sender, ExcavoLibrary.pairFor(factory, path[0], path[1]), amountIn
        );
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        _swapSupportingFeeOnTransferTokens(path, address(this), discount);
        uint amountOut = IERC20(WETH).balanceOf(address(this));
        require(amountOut >= amountOutMin, 'ExcavoRouter: INSUFFICIENT_OUTPUT_AMOUNT');
        IWETH(WETH).withdraw(amountOut);
        TransferHelper.safeTransferETH(to, amountOut);
    }

    // **** LIBRARY FUNCTIONS ****
    function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
        return ExcavoLibrary.quote(amountA, reserveA, reserveB);
    }

    function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
        public
        view
        virtual
        override
        returns (uint amountOut)
    {
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        return ExcavoLibrary.getAmountOut(amountIn, reserveIn, reserveOut, discount);
    }

    function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
        public
        view
        virtual
        override
        returns (uint amountIn)
    {
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        return ExcavoLibrary.getAmountIn(amountOut, reserveIn, reserveOut, discount);
    }

    function getAmountsOut(uint amountIn, address[] memory path)
        public
        view
        virtual
        override
        returns (uint[] memory amounts)
    {
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        return ExcavoLibrary.getAmountsOut(factory, amountIn, path, discount);
    }

    function getAmountsIn(uint amountOut, address[] memory path)
        public
        view
        virtual
        override
        returns (uint[] memory amounts)
    {
        uint discount = TraderDiscount.calculateDiscount(ICAVO(CAVO).virtualBalanceOf(msg.sender));
        
        return ExcavoLibrary.getAmountsIn(factory, amountOut, path, discount);
    }
}
// File: contracts/libraries/TraderDiscount.sol



pragma solidity >=0.6.6;

// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)

import '../interfaces/IERC20.sol';

library TraderDiscount {
    function calculateDiscount(uint tokenAmount) internal pure returns (uint k)  {
        k = 4;
        tokenAmount = tokenAmount / (10 ** 18);
        if (tokenAmount < 1 ) {
            k = 10;
        } else if (tokenAmount >= 1 && tokenAmount <= 5) {
            k = 9;
        } else if (tokenAmount > 5 && tokenAmount <= 10) {
            k = 8;
        } else if (tokenAmount > 10 && tokenAmount <= 20) {
            k = 7;
        } else if (tokenAmount > 20 && tokenAmount <= 50) {
            k = 6;
        } else if (tokenAmount > 50 && tokenAmount <= 100) {
            k = 5;
        }
    }
}

// File: contracts/test/TestExcavoRouter02.sol



pragma solidity >=0.6.6;

import '../ExcavoRouter.sol';

contract TestExcavoRouter is ExcavoRouter {
    constructor(address _factory, address _WETH, address _xCAVO) public ExcavoRouter(_factory, _WETH, _xCAVO) {}

    function testSwap(address pair, uint amount0Out, uint amount1Out, address to, bytes calldata data, uint k) external {
        IExcavoPair(pair).swap(amount0Out, amount1Out, to, data, k);
    }
}
// File: contracts/ExcavoFactory.sol



pragma solidity >=0.6.6;

import './interfaces/IExcavoFactory.sol';
import './interfaces/IEXCV.sol';
import './interfaces/ICAVO.sol';
import './ExcavoPair.sol';

contract ExcavoFactory is IExcavoFactory {
    address public immutable override EXCVToken;
    address public immutable override CAVOToken;
    address public immutable override WETHToken;
    address public immutable override feeToSetter;

    address public override router;
    // TODO: Remove
    bytes32 public immutable getCreationCode;

    mapping(address => mapping(address => address)) public override getPair;
    address[] public override allPairs;

    constructor(address _CAVO, address _EXCV, address _WETH) public {
        feeToSetter = msg.sender;
        CAVOToken = _CAVO;
        EXCVToken = _EXCV;
        WETHToken = _WETH;
        getCreationCode = keccak256(type(ExcavoPair).creationCode);
    }

    function allPairsLength() external view override returns (uint) {
        return allPairs.length;
    }

    function createPair(address tokenA, address tokenB) external override returns (address pair) {
        require(tokenA != tokenB, 'Excavo: FORBIDDEN');
        require(router != address(0), 'Excavo: ROUTER_NOT_SET');
        (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
        require(token0 != address(0), 'Excavo: ZERO_ADDRESS');
        require(getPair[token0][token1] == address(0), 'Excavo: PAIR_EXISTS'); // single check is sufficient
        bytes memory bytecode = type(ExcavoPair).creationCode;
        bytes32 salt = keccak256(abi.encodePacked(token0, token1));
        assembly {
            pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }

        IExcavoPair(pair).initialize(token0, token1, router);
       
        if ((token0 == CAVOToken || token1 == CAVOToken) && (token0 == WETHToken || token1 == WETHToken)) {
            // enable CAVO farming for CAVO/ETH pair only
            IExcavoPair(pair).setCAVO(CAVOToken, ICAVO(CAVOToken).xCAVOToken());
        } else if ((token0 == EXCVToken || token1 == EXCVToken) && (token0 == WETHToken || token1 == WETHToken)) {
            // enable xCAVO contract permissions for EXCV/ETH pair only
            IExcavoPair(pair).setCAVO(address(0), ICAVO(CAVOToken).xCAVOToken());
        }
        
        getPair[token0][token1] = pair;
        getPair[token1][token0] = pair; // populate mapping in the reverse direction
        allPairs.push(pair);
        emit PairCreated(token0, token1, pair, allPairs.length);
    }

    function initialize(address _router) external override {
        require(msg.sender == feeToSetter && router == address(0), 'Excavo: FORBIDDEN');
        router = _router;
    }
}
// File: contracts/libraries/ExcavoOracleLibrary.sol



pragma solidity >=0.6.6;

import '../interfaces/IExcavoPair.sol';
import './FixedPoint.sol';

// library with helper methods for oracles that are concerned with computing average prices
library ExcavoOracleLibrary {
    using FixedPoint for *;

    // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
    function currentBlockTimestamp() internal view returns (uint32) {
        return uint32(block.timestamp % 2 ** 32);
    }

    // produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
    function currentCumulativePrices(
        address pair
    ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
        blockTimestamp = currentBlockTimestamp();
        price0Cumulative = IExcavoPair(pair).price0CumulativeLast();
        price1Cumulative = IExcavoPair(pair).price1CumulativeLast();

        // if time has elapsed since the last update on the pair, mock the accumulated price values
        (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IExcavoPair(pair).getReserves();
        if (blockTimestampLast != blockTimestamp) {
            // subtraction overflow is desired
            uint32 timeElapsed = blockTimestamp - blockTimestampLast;
            // addition overflow is desired
            // counterfactual
            price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
            // counterfactual
            price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
        }
    }
}

// File: contracts/libraries/FixedPoint.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.6;

import './Babylonian.sol';

// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
    // range: [0, 2**112 - 1]
    // resolution: 1 / 2**112
    struct uq112x112 {
        uint224 _x;
    }

    // range: [0, 2**144 - 1]
    // resolution: 1 / 2**112
    struct uq144x112 {
        uint _x;
    }

    uint8 private constant RESOLUTION = 112;
    uint private constant Q112 = uint(1) << RESOLUTION;
    uint private constant Q224 = Q112 << RESOLUTION;

    // encode a uint112 as a UQ112x112
    function encode(uint112 x) internal pure returns (uq112x112 memory) {
        return uq112x112(uint224(x) << RESOLUTION);
    }

    // encodes a uint144 as a UQ144x112
    function encode144(uint144 x) internal pure returns (uq144x112 memory) {
        return uq144x112(uint256(x) << RESOLUTION);
    }

    // divide a UQ112x112 by a uint112, returning a UQ112x112
    function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) {
        require(x != 0, 'FixedPoint: DIV_BY_ZERO');
        return uq112x112(self._x / uint224(x));
    }

    // multiply a UQ112x112 by a uint, returning a UQ144x112
    // reverts on overflow
    function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {
        uint z;
        require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW");
        return uq144x112(z);
    }

    // returns a UQ112x112 which represents the ratio of the numerator to the denominator
    // equivalent to encode(numerator).div(denominator)
    function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) {
        require(denominator > 0, "FixedPoint: DIV_BY_ZERO");
        return uq112x112((uint224(numerator) << RESOLUTION) / denominator);
    }

    // decode a UQ112x112 into a uint112 by truncating after the radix point
    function decode(uq112x112 memory self) internal pure returns (uint112) {
        return uint112(self._x >> RESOLUTION);
    }

    // decode a UQ144x112 into a uint144 by truncating after the radix point
    function decode144(uq144x112 memory self) internal pure returns (uint144) {
        return uint144(self._x >> RESOLUTION);
    }

    // take the reciprocal of a UQ112x112
    function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
        require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL');
        return uq112x112(uint224(Q224 / self._x));
    }

    // square root of a UQ112x112
    function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
        return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56));
    }
}

// File: contracts/libraries/Babylonian.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.6;

// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
    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;
        }
        // else z = 0
    }
}

// File: contracts/test/FixedPointTest.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.6;
pragma experimental ABIEncoderV2;

import "../libraries/FixedPoint.sol";

contract FixedPointTest {
    function encode(uint112 x) external pure returns (FixedPoint.uq112x112 memory) {
        return FixedPoint.encode(x);
    }

    function encode144(uint144 x) external pure returns (FixedPoint.uq144x112 memory) {
        return FixedPoint.encode144(x);
    }

    // divide a UQ112x112 by a uint112, returning a UQ112x112
    function div(FixedPoint.uq112x112 calldata self, uint112 y) external pure returns (FixedPoint.uq112x112 memory) {
        return FixedPoint.div(self, y);
    }

    function fraction(uint112 numerator, uint112 denominator) external pure returns (FixedPoint.uq112x112 memory) {
        return FixedPoint.fraction(numerator, denominator);
    }

    // multiply a UQ112x112 by a uint, returning a UQ144x112
    function mul(FixedPoint.uq112x112 calldata self, uint y) external pure returns (FixedPoint.uq144x112 memory) {
        return FixedPoint.mul(self, y);
    }

    // decode a UQ112x112 in a uint container into a uint by truncating after the radix point
    function decode(FixedPoint.uq112x112 calldata self) external pure returns (uint112) {
        return FixedPoint.decode(self);
    }

    function decode144(FixedPoint.uq144x112 calldata self) external pure returns (uint144) {
        return FixedPoint.decode144(self);
    }

    function reciprocal(FixedPoint.uq112x112 calldata self) external pure returns (FixedPoint.uq112x112 memory) {
        return FixedPoint.reciprocal(self);
    }

    function sqrt(FixedPoint.uq112x112 calldata self) external pure returns (FixedPoint.uq112x112 memory) {
        return FixedPoint.sqrt(self);
    }
}

// File: contracts/test/BabylonianTest.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.6;

import '../libraries/Babylonian.sol';

// used for testing the logic of token naming
contract BabylonianTest {
    function sqrt(uint num) public pure returns (uint)  {
        return Babylonian.sqrt(num);
    }
}

// File: contracts/CAVO.sol



pragma solidity >=0.6.6;

import './PublicPresale.sol';
import './xCAVO.sol';
import './EXCV.sol';
import './TeamDistribution.sol';
import './PrivatePresale.sol';

contract CAVO is PublicPresale, PrivatePresale, TeamDistribution {
    
    uint private constant PUBLIC_PRESALE_DURATION_IN_BLOCKS = 7 * 6500;
    uint32 private constant PRESALE_VESTING_PERIOD_IN_BLOCKS = 7 * 6500;
    
    uint private constant PRIVATE_PRESALE_DISTRIBUTED_CAVO_IN_WEI = 1460.769 ether;
    
    address private constant PUBLIC_PRESALE_OWNER = 0xAb96C12881A2E9Ffa6706Ae68bCFA4EcD1A8bf21;

    address[] private teamAddresses = [
        0x381657fdE9bfE7558837757aC54249Ef748CACB7, // A.M.
        0x564569020c298D2487445CCa5C5ef3eD8cd408A3, // Y.O.
        0xDfe2abc3d395a87a1476f5B707E77f5F23B1d88b, // A.
        0x8CF3329E378c6196F35f5cB7eea5040873f8AC8C, // D.B.
        0x8B9a2b2d9a41909D613C81F2f344E364cD62b63C, // Z.
        0x57B93A6b8954938DE455BE95c9AA7843b99D7DEa, // V.
        0xf0393FB1e988317ca6E3fb986874D019dE712c7d, // M.
        0x698f4a1f42c3601579A3E40a9e4D90C2032C443a  // X.
    ];

    uint[] private teamAmounts = [
        40000 ether, // A.M.
        40000 ether, // Y.O.
        15000 ether, // A.
        10000 ether, // D.B.
        50000 ether, // Z.
        30000 ether, // V.
        10000 ether, // M.
        5000  ether  // X.
    ];
    
    constructor() 
        public 
        PublicPresale(PUBLIC_PRESALE_OWNER, PRESALE_VESTING_PERIOD_IN_BLOCKS, PUBLIC_PRESALE_DURATION_IN_BLOCKS) 
        PrivatePresale(PRESALE_VESTING_PERIOD_IN_BLOCKS, PRIVATE_PRESALE_DISTRIBUTED_CAVO_IN_WEI) 
        TeamDistribution(PRESALE_VESTING_PERIOD_IN_BLOCKS, teamAddresses, teamAmounts) 
    {
        address _xCAVO;
        address _EXCV;
        bytes memory xCAVOBytecode = type(xCAVO).creationCode;
        bytes memory EXCVBytecode = type(EXCV).creationCode;
        bytes32 xCAVOSalt = keccak256(abi.encodePacked("xCAVO"));
        bytes32 EXCVSalt = keccak256(abi.encodePacked("EXCV"));
        assembly {
            _xCAVO := create2(0, add(xCAVOBytecode, 32), mload(xCAVOBytecode), xCAVOSalt)
            _EXCV := create2(0, add(EXCVBytecode, 32), mload(EXCVBytecode), EXCVSalt)
        }
        xCAVOToken = _xCAVO;
        EXCVToken = _EXCV;

        _mint(address(this), totalTeamDistribution.add(totalPrivatePresaleDistribution));
    }
}

// File: contracts/test/TransferHelperTest.sol



// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.6;

import '../libraries/TransferHelper.sol';

// test helper for transfers
contract TransferHelperTest {
    function safeApprove(address token, address to, uint value) external {
        TransferHelper.safeApprove(token, to, value);
    }

    function safeTransfer(address token, address to, uint value) external {
        TransferHelper.safeTransfer(token, to, value);
    }

    function safeTransferFrom(address token, address from, address to, uint value) external {
        TransferHelper.safeTransferFrom(token, from, to, value);
    }

    function safeTransferETH(address to, uint value) external {
        TransferHelper.safeTransferETH(to, value);
    }
}

// can revert on failure and returns true if successful
contract TransferHelperTestFakeERC20Compliant {
    bool public success;
    bool public shouldRevert;

    function setup(bool success_, bool shouldRevert_) public {
        success = success_;
        shouldRevert = shouldRevert_;
    }

    function transfer(address, uint256) public view returns (bool) {
        require(!shouldRevert, 'REVERT');
        return success;
    }

    function transferFrom(address, address, uint256) public view returns (bool) {
        require(!shouldRevert, 'REVERT');
        return success;
    }

    function approve(address, uint256) public view returns (bool) {
        require(!shouldRevert, 'REVERT');
        return success;
    }
}

// only reverts on failure, no return value
contract TransferHelperTestFakeERC20Noncompliant {
    bool public shouldRevert;

    function setup(bool shouldRevert_) public {
        shouldRevert = shouldRevert_;
    }

    function transfer(address, uint256) view public {
        require(!shouldRevert);
    }

    function transferFrom(address, address, uint256) view public {
        require(!shouldRevert);
    }

    function approve(address, uint256) view public {
        require(!shouldRevert);
    }
}

contract TransferHelperTestFakeFallback {
    bool public shouldRevert;

    function setup(bool shouldRevert_) public {
        shouldRevert = shouldRevert_;
    }

    receive() external payable {
        require(!shouldRevert);
    }
}


// File: contracts/test/RouterEventEmitter.sol



pragma solidity >=0.6.6;

import '../interfaces/IExcavoRouter.sol';

contract RouterEventEmitter {
    event Amounts(uint[] amounts);

    receive() external payable {}

    function swapExactTokensForTokens(
        address router,
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external {
        (bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
            IExcavoRouter(router).swapExactTokensForTokens.selector, amountIn, amountOutMin, path, to, deadline
        ));
        assert(success);
        emit Amounts(abi.decode(returnData, (uint[])));
    }

    function swapTokensForExactTokens(
        address router,
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external {
        (bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
            IExcavoRouter(router).swapTokensForExactTokens.selector, amountOut, amountInMax, path, to, deadline
        ));
        assert(success);
        emit Amounts(abi.decode(returnData, (uint[])));
    }

    function swapExactETHForTokens(
        address router,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable {
        (bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
            IExcavoRouter(router).swapExactETHForTokens.selector, amountOutMin, path, to, deadline
        ));
        assert(success);
        emit Amounts(abi.decode(returnData, (uint[])));
    }

    function swapTokensForExactETH(
        address router,
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external {
        (bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
            IExcavoRouter(router).swapTokensForExactETH.selector, amountOut, amountInMax, path, to, deadline
        ));
        assert(success);
        emit Amounts(abi.decode(returnData, (uint[])));
    }

    function swapExactTokensForETH(
        address router,
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external {
        (bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
            IExcavoRouter(router).swapExactTokensForETH.selector, amountIn, amountOutMin, path, to, deadline
        ));
        assert(success);
        emit Amounts(abi.decode(returnData, (uint[])));
    }

    function swapETHForExactTokens(
        address router,
        uint amountOut,
        address[] calldata path,
        address to,
        uint deadline
    ) external payable {
        (bool success, bytes memory returnData) = router.delegatecall(abi.encodeWithSelector(
            IExcavoRouter(router).swapETHForExactTokens.selector, amountOut, path, to, deadline
        ));
        assert(success);
        emit Amounts(abi.decode(returnData, (uint[])));
    }
}