// File: Context.sol



// SPDX-License-Identifier: MIT

// File @openzeppelin/contracts/utils/Context.sol@v4.0.0

pragma solidity ^0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}

// File: EnumerableSet.sol



// SPDX-License-Identifier: MIT

// File @openzeppelin/contracts/utils/structs/EnumerableSet.sol@v4.0.0

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;

        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping (bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) { // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
            // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.

            bytes32 lastvalue = set._values[lastIndex];

            // Move the last value to the index where the value to delete is
            set._values[toDeleteIndex] = lastvalue;
            // Update the index for the moved value
            set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        require(set._values.length > index, "EnumerableSet: index out of bounds");
        return set._values[index];
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }


    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }
}

// File: ERC20.sol



// SPDX-License-Identifier: MIT

// File @openzeppelin/contracts/token/ERC20/ERC20.sol@v4.0.0

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC20 applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20 {
    mapping (address => uint256) private _balances;

    mapping (address => mapping (address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The defaut value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5,05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overloaded;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        _approve(sender, _msgSender(), currentAllowance - amount);

        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        _approve(_msgSender(), spender, currentAllowance - subtractedValue);

        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(address sender, address recipient, uint256 amount) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        _balances[sender] = senderBalance - amount;
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        _balances[account] = accountBalance - amount;
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}

// File: FeesHelper.sol



// SPDX-License-Identifier: UNLICENSED
// ALL RIGHTS RESERVED
// Unicrypt by SDDTech reserves all rights on this code. You may NOT copy these contracts.

pragma solidity 0.8.3;

import "./Ownable.sol";

interface IFeeHelper {
    function getFee() view external returns(uint256);
    
    function getFeeDenominator() view external returns(uint256);
    
    function setFee(uint _fee) external;
    
    function getFeeAddress() view external returns(address);
    
    function setFeeAddress(address payable _feeAddress) external;
}

contract FeeHelper is Ownable{
    
    struct Settings {
        uint256 FEE; 
        uint256 DENOMINATOR;
        address payable FEE_ADDRESS;
    }
    
    Settings public SETTINGS;
    
    constructor() {
        SETTINGS.FEE = 100;
        SETTINGS.DENOMINATOR = 10000;
        SETTINGS.FEE_ADDRESS = payable(msg.sender);
    }
    
    function getFee() view external returns(uint256) {
        return SETTINGS.FEE;
    }

    function getFeeDenominator() view external returns(uint256) {
        return SETTINGS.DENOMINATOR;
    }
    
    function setFee(uint _fee) external onlyOwner {
        SETTINGS.FEE = _fee;
    }
    
    function getFeeAddress() view external returns(address) {
        return SETTINGS.FEE_ADDRESS;
    }
    
    function setFeeAddress(address payable _feeAddress) external onlyOwner {
        SETTINGS.FEE_ADDRESS = _feeAddress;
    }
} 
// File: FixedPoint128.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
    uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
// File: FixedPoint96.sol



pragma solidity 0.8.3;

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// File: FullMath.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
   /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
    uint256 a,
    uint256 b,
    uint256 denominator
) internal pure returns (uint256 result) {
    // 512-bit multiply [prod1 prod0] = a * b
    // Compute the product mod 2**256 and mod 2**256 - 1
    // then use the Chinese Remainder Theorem to reconstruct
    // the 512 bit result. The result is stored in two 256
    // variables such that product = prod1 * 2**256 + prod0
    uint256 prod0; // Least significant 256 bits of the product
    uint256 prod1; // Most significant 256 bits of the product
    assembly {
        let mm := mulmod(a, b, not(0))
        prod0 := mul(a, b)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    // Handle non-overflow cases, 256 by 256 division
    if (prod1 == 0) {
        require(denominator > 0);
        assembly {
            result := div(prod0, denominator)
        }
        return result;
    }

    // Make sure the result is less than 2**256.
    // Also prevents denominator == 0
    require(denominator > prod1);

    ///////////////////////////////////////////////
    // 512 by 256 division.
    ///////////////////////////////////////////////

    // Make division exact by subtracting the remainder from [prod1 prod0]
    // Compute remainder using mulmod
    uint256 remainder;
    assembly {
        remainder := mulmod(a, b, denominator)
    }
    // Subtract 256 bit number from 512 bit number
    assembly {
        prod1 := sub(prod1, gt(remainder, prod0))
        prod0 := sub(prod0, remainder)
    }

    // Factor powers of two out of denominator
    // Compute largest power of two divisor of denominator.
    // Always >= 1.
    unchecked {
        uint256 twos = (type(uint256).max - denominator + 1) & denominator;
        // Divide denominator by power of two
        assembly {
            denominator := div(denominator, twos)
        }

        // Divide [prod1 prod0] by the factors of two
        assembly {
            prod0 := div(prod0, twos)
        }
        // Shift in bits from prod1 into prod0. For this we need
        // to flip `twos` such that it is 2**256 / twos.
        // If twos is zero, then it becomes one
        assembly {
            twos := add(div(sub(0, twos), twos), 1)
        }
        prod0 |= prod1 * twos;

        // Invert denominator mod 2**256
        // Now that denominator is an odd number, it has an inverse
        // modulo 2**256 such that denominator * inv = 1 mod 2**256.
        // Compute the inverse by starting with a seed that is correct
        // correct for four bits. That is, denominator * inv = 1 mod 2**4
        uint256 inv = (3 * denominator) ^ 2;
        // Now use Newton-Raphson iteration to improve the precision.
        // Thanks to Hensel's lifting lemma, this also works in modular
        // arithmetic, doubling the correct bits in each step.
        inv *= 2 - denominator * inv; // inverse mod 2**8
        inv *= 2 - denominator * inv; // inverse mod 2**16
        inv *= 2 - denominator * inv; // inverse mod 2**32
        inv *= 2 - denominator * inv; // inverse mod 2**64
        inv *= 2 - denominator * inv; // inverse mod 2**128
        inv *= 2 - denominator * inv; // inverse mod 2**256

        // Because the division is now exact we can divide by multiplying
        // with the modular inverse of denominator. This will give us the
        // correct result modulo 2**256. Since the precoditions guarantee
        // that the outcome is less than 2**256, this is the final result.
        // We don't need to compute the high bits of the result and prod1
        // is no longer required.
        result = prod0 * inv;
        return result;
        }
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        result = mulDiv(a, b, denominator);
        if (mulmod(a, b, denominator) > 0) {
            require(result < type(uint256).max);
            result++;
        }
    }
}
// File: ICountryList.sol



// SPDX-License-Identifier: UNLICENSED

pragma solidity 0.8.3;

/**
 * @dev Interface of the CountryList contract
 */
interface ICountryList {
  function countryIsValid (uint16 _countryCode) external view returns (bool);
}

// File: IERC20.sol



// SPDX-License-Identifier: MIT

// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v4.0.0

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

// File: IFeeHelper.sol




// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

/// @title The interface for the FeeHelper
/// @notice The FeeHelper manages the fee percentages and wallets to use within the Unicrypt / Uniswap V3 integration
interface IFeeHelper {

    /// @notice Returns the fee percentage
    /// @return fee percentage
    function getFee() view external returns(uint256);

    /// @notice Returns the fee denominator to calculate fee percentages.
    /// @return fee denominator
    function getFeeDenominator() view external returns(uint256);
    
    /// @notice Sets a new fee. Only Owner can call
    /// @param _fee the new fee.
    function setFee(uint _fee) external;
    
    /// @notice Returns the fee wallet address
    /// @return fee wallet address
    function getFeeAddress() view external returns(address);

    /// @notice Sets a new fee wallet address. Only Owner can call
    /// @param _feeAddress the new fee wallet address.
    function setFeeAddress(address payable _feeAddress) external;

}

// File: ITickHelper.sol




// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

/// @title The interface for the TickHelper
/// @notice The TickHelper automates the calculations to determine the Max or Min Ticks to use within the Unicrypt / Uniswap V3 integration
interface ITickHelper {

    /// @notice Returns the max tick for a given fee amount
    /// @param fee the fee used in the pool
    /// @return maxTick The tick spacing
    function getMaxTick(uint24 fee) external view returns (int24 maxTick);

    /// @notice Returns the min tick for a given fee amount
    /// @param fee the fee used in the pool
    /// @return minTick The tick spacing
    function getMinTick(uint24 fee) external view returns (int24 minTick);

    /// @notice Sets a new fee and tickSpace for that fee. Only Owner can call
    /// Should only be used when uniswap v3 adds new fees
    /// @param fee the new fee to be added.
    /// @param tickSpace the new ticks space related to the fee
    function setTickSpace(uint24 fee, uint24 tickSpace) external;

}

// File: IUnicryptUniV3LPFactory.sol




// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

/// @title The interface for the Uniswap V3 LP Factory on Unicrypt
/// @notice The Uniswap V3 LPFactory facilitates creation of Uniswap V3 pools and Unicrypt LP tokens
interface IUnicryptUniV3LPFactory {

    /// @notice Returns the LP Token address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param _token0 The contract address of either token0 or token1
    /// @param _token1 The contract address of the other token
    /// @param _fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return lpToken The pool address
    function getLPTokenAddress(
        address _token0,
        address _token1,
        uint24 _fee
    ) external view returns (address lpToken);

    /// @notice Returns the LP Token address for a given index
    /// @dev Use NUM_TOKENS to get the array length, then iterate through the array with this function
    /// @param _index The index
    /// @return lpToken The pool address
    function getLPTokenByIndex(
        uint256 _index
    ) external view returns (address lpToken);

    /// @notice Creates a pool for the given two tokens and fee, or updates a pool if it already exists. Creates an LP token.
    /// @param _token0 One of the two tokens in the desired pool
    /// @param _token1 The other of the two tokens in the desired pool
    /// @param _fee The desired fee for the pool
    /// @param _sqrtPriceX96 to initiate the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
    /// The call will revert if the fee is invalid, or the token arguments
    /// are invalid.
    /// @return lpToken The address of the newly created LP Token
    function createOrUpdatePool(
        address  _token0,
        address _token1,
        uint24 _fee,
        uint160 _sqrtPriceX96
    ) external returns (address lpToken);

    /// @notice Sets the address for the current or desired TickHelper Contract
    /// @dev called only when updating the TickHelper Contract
    /// @param _newtickHelper address of the new contract
    function updateTickHelper(
        address  _newtickHelper
    ) external;

    /// @notice Sets the address for the current or desired FeeHelper Contract
    /// @dev called only when updating the FeeHelper Contract
    /// @param _newFeeHelper address of the new contract
    function updateFeeHelper(
        address  _newFeeHelper
    ) external;

    /// @notice Returns the feeHelper Address
    /// @return feeHelper Address
    function getFeeHelperAddress() external view returns (address);

    /// @notice Sets the address for the current or desired lpTokenHelper Contract
    /// @dev called only when updating the lpTokenHelper Contract
    /// @param _newLPTokenHelper address of the new contract
    function updateLPTokenHelper(
        address  _newLPTokenHelper
    ) external;

    /// @notice Returns the lpTokenHelper Address
    /// @return lpTokenHelper Address
    function getLPTokenHelperAddress() external view returns (address);

}

// File: IUnicryptUniV3LPToken.sol




// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

import "./IERC20.sol";

/// @title The interface for the Uniswap V3 LP Token on Unicrypt
/// @notice The Uniswap V3 LP Token facilitates creates and manages Unicrypt LP tokens and 
///  interactions with the pool
interface IUnicryptUniV3LPToken is IERC20{

    /// @notice Sets the ticks on the LP Token
    /// @dev Must call this from the factory before doing any liquidity operations
    /// @param _tickUpper The higher tick
    /// @param _tickLower The lower tick
    function setTicks(
        int24 _tickUpper,
        int24 _tickLower
    ) external;

    /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
    /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
    /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
    function uniswapV3MintCallback(
        uint256 amount0Owed,
        uint256 amount1Owed,
        bytes calldata data
    ) external;

    /// @notice Mints liquidity to the Uniswap V3 Pool, and adds to the total supply
    /// of the LP Token
    /// @param amount0Desired The desired amount of token0 added to the liquidity pool
    /// @param amount1Desired The desired amount of token1 added to the liquidity pool
    /// @return amount0 and amount1 - the amount eof each token used to provide liquidity
    function addLiquidity(
        uint256 amount0Desired,
        uint256 amount1Desired
    ) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Removes liquidity from the Uniswap V3 Pool, and burns the total supply
    /// of the LP Token, sends the owed tokens to the msg.sender
    /// @param _desiredLiquidity The desired amount of liquidity to remove
    /// @return amount0 and amount1 - the amount eof each token removed
    function removeLiquidity(
        uint128 _desiredLiquidity
    ) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed from the liquidity pool and sends back to the LP Token
    /// @dev the LP Token receives the fees, then mints them back into the pool. 
    /// @param amount0Max The maximum amount of token0 to collect from the liquidity pool
    /// @param amount1Max The maximum amount of token1 to collect from the liquidity pool
    /// @return amount0 and amount1 - the amount of each token collected
    function collect(
        uint256 amount0Max,
        uint256 amount1Max
    ) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Sets the initial price for the pool. Can only be called once.
    /// @param _sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initializePool(
        uint160 _sqrtPriceX96
    ) external;

        // @notice Multicall to mint and collect
    /// @param _amount0Desired The desired amount of token0 added to the liquidity pool
    /// @param _amount1Desired The desired amount of token1 added to the liquidity pool
    /// @param _amount0Max The maximum amount of token0 to collect from the liquidity pool
    /// @param _amount1Max The maximum amount of token1 to collect from the liquidity pool
    /// @return results
    function addMulticall(uint256 _amount0Desired, uint256 _amount1Desired, uint128 _amount0Max, uint128 _amount1Max) external payable returns (bytes[] memory results);


        // @notice Multicall to remove and collect
    /// @param _desiredLiquidity The desired amount of liquidity to remove
    /// @param _amount0Max The maximum amount of token0 to collect from the liquidity pool
    /// @param _amount1Max The maximum amount of token1 to collect from the liquidity pool
    /// @return results
    function removeMulticall(uint256 _desiredLiquidity, uint128 _amount0Max, uint128 _amount1Max) external payable returns (bytes[] memory results);
}

// File: IUniswapV3Factory.sol




// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;

/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
    /// @notice Emitted when the owner of the factory is changed
    /// @param oldOwner The owner before the owner was changed
    /// @param newOwner The owner after the owner was changed
    event OwnerChanged(address indexed oldOwner, address indexed newOwner);

    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param pool The address of the created pool
    event PoolCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        int24 tickSpacing,
        address pool
    );

    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
    /// @param fee The enabled fee, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via setOwner
    /// @return The address of the factory owner
    function owner() external view returns (address);

    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
    /// @return The tick spacing
    function feeAmountTickSpacing(uint24 fee) external view returns (int24);

    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The pool address
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param fee The desired fee for the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external returns (address pool);

    /// @notice Updates the owner of the factory
    /// @dev Must be called by the current owner
    /// @param _owner The new owner of the factory
    function setOwner(address _owner) external;

    /// @notice Enables a fee amount with the given tickSpacing
    /// @dev Fee amounts may never be removed once enabled
    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}

// File: IUniswapV3MintCallback.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
    /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
    /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
    /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
    function uniswapV3MintCallback(
        uint256 amount0Owed,
        uint256 amount1Owed,
        bytes calldata data
    ) external;
}
// File: IUniswapV3Pool.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

import './IUniswapV3PoolImmutables.sol';
import './IUniswapV3PoolState.sol';
import './IUniswapV3PoolDerivedState.sol';
import './IUniswapV3PoolActions.sol';
import './IUniswapV3PoolOwnerActions.sol';
import './IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolEvents
{

}

// File: IUniswapV3PoolActions.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

// File: IUniswapV3PoolDerivedState.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

// File: IUniswapV3PoolEvents.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

// File: IUniswapV3PoolImmutables.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

// File: IUniswapV3PoolOwnerActions.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

// File: IUniswapV3PoolState.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

// File: IWETH9.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

import './IERC20.sol';

/// @title Interface for WETH9
interface IWETH9 is IERC20 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;
}
// File: LiquidityAmounts.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

import './FullMath.sol';
import './FixedPoint96.sol';

/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
    /// @notice Downcasts uint256 to uint128
    /// @param x The uint258 to be downcasted
    /// @return y The passed value, downcasted to uint128
    function toUint128(uint256 x) private pure returns (uint128 y) {
        require((y = uint128(x)) == x);
    }

    /// @notice Computes the amount of liquidity received for a given amount of token0 and price range
    /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount0 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount0(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
        return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
    }

    /// @notice Computes the amount of liquidity received for a given amount of token1 and price range
    /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount1 The amount1 being sent in
    /// @return liquidity The amount of returned liquidity
    function getLiquidityForAmount1(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
        return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
    }

    /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtRatioX96 A sqrt price representing the current pool prices
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param amount0 The amount of token0 being sent in
    /// @param amount1 The amount of token1 being sent in
    /// @return liquidity The maximum amount of liquidity received
    function getLiquidityForAmounts(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount0,
        uint256 amount1
    ) internal pure returns (uint128 liquidity) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
            uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);

            liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
        } else {
            liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
        }
    }

    /// @notice Computes the amount of token0 for a given amount of liquidity and a price range
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    function getAmount0ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return
            FullMath.mulDiv(
                uint256(liquidity) << FixedPoint96.RESOLUTION,
                sqrtRatioBX96 - sqrtRatioAX96,
                sqrtRatioBX96
            ) / sqrtRatioAX96;
    }

    /// @notice Computes the amount of token1 for a given amount of liquidity and a price range
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount1 The amount of token1
    function getAmount1ForLiquidity(
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
    }

    /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
    /// pool prices and the prices at the tick boundaries
    /// @param sqrtRatioX96 A sqrt price representing the current pool prices
    /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
    /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
    /// @param liquidity The liquidity being valued
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function getAmountsForLiquidity(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint128 liquidity
    ) internal pure returns (uint256 amount0, uint256 amount1) {
        if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);

        if (sqrtRatioX96 <= sqrtRatioAX96) {
            amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
        } else if (sqrtRatioX96 < sqrtRatioBX96) {
            amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
            amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
        } else {
            amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
        }
    }
}
// File: LPTokenHelper.sol



// SPDX-License-Identifier: UNLICENSED
// ALL RIGHTS RESERVED
// Unicrypt by SDDTech reserves all rights on this code. You may NOT copy these contracts.

pragma solidity 0.8.3;

import "./ERC20.sol";
import "./Ownable.sol";

import "./TransferHelper.sol";
import "./LiquidityAmounts.sol";
import "./TickMath.sol";
import "./FixedPoint128.sol";

import "./IERC20.sol";
import "./IUniswapV3MintCallback.sol";
import "./IUniswapV3Pool.sol";
import "./IWETH9.sol";
import "./IUnicryptUniV3LPFactory.sol";
import "./IFeeHelper.sol";

/// @title Uniswap V3 LP Token Helper on Unicrypt
/// @notice The Uniswap V3 LP Token Helper holds the logic for the Unicrypt LP tokens

contract UnicryptUniV3LPTokenHelper is ERC20, Ownable, IUniswapV3MintCallback {

    uint256 constant public CONTRACT_VERSION = 1;

    address public token0;
    address public token1;
    address public pool;
    uint24 public fee;
    /// @dev stores tick data, used by the V3 pool to calculate the range of concentrated liquidity
    int24 public tickUpper;
    int24 public tickLower;

    /// @dev stores position data from the V3 pool, used to calculate rewards from fees
    /// updated after each call to the V3 pool
    struct Position {
        uint256 liquidity;
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
        uint128 tokensOwed0;
        uint128 tokensOwed1;
    }

    Position public positionState;

    /// @dev pool cannot be initiallized twice
    bool public initialized = false;

    address public WETH9;

    /// @dev used to create a unique pool key similar to what V3 uses
    struct PoolKey {
        address token0;
        address token1;
        uint24 fee;
    }

    /// @dev data format needed to decode the mintcallback data from the pool
    struct MintCallbackData {
        PoolKey poolKey;
        address payer;
    }
    
    PoolKey private poolKey;

    event Mint(address sender, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 amount0, uint256 amount1);
    event Burn(address sender, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 _desiredLiquidity, uint256 amount0, uint256 amount1);
    event Collect(address pool, uint128 amount0Collect, uint128 amount1Collect);
    event Fee(address token, address sender, address recipient, uint256 fee);
    event SetTicks(int24 tickUpper, int24 tickLower);
    event InitializePool(uint160 sqrtPriceX96);

    address private lpTokenHelper;

    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor(string memory name, string memory symbol) ERC20(name, symbol) {
        _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 making 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;
    }

    /// @notice Sets the ticks on the LP Token
    /// @dev Must call this from the factory before doing any liquidity operations
    /// @param _tickUpper The higher tick
    /// @param _tickLower The lower tick
    function setTicks(int24 _tickUpper, int24 _tickLower) external onlyOwner{
        tickUpper = _tickUpper;
        tickLower = _tickLower;
        emit SetTicks(_tickUpper, _tickLower);
    }

    /// @dev helper to handle different types of payments depending on transactions.
    function pay(address token, address payer, address recipient, uint256 value) internal {
        if (token == WETH9 && address(this).balance >= value) {
            // pay with WETH9
            IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay
            bool res = IWETH9(WETH9).transfer(recipient, value);
            require(res);
        } else if (payer == address(this)) {
            // pay with tokens already in the contract (for the exact input multihop case)
            TransferHelper.safeTransfer(token, recipient, value);
        } else {
            // pull payment
            TransferHelper.safeTransferFrom(token, payer, recipient, value);
        }
    }

    /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
    /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
    /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
    function uniswapV3MintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata data) external override {
        require(msg.sender == pool);
        MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));

        if (amount0Owed > 0) {
            pay(decoded.poolKey.token0, decoded.payer, msg.sender, amount0Owed);
        } 

        if (amount1Owed > 0) {
            pay(decoded.poolKey.token1, decoded.payer, msg.sender, amount1Owed);
        }
    }

    /// @dev approves the pool for the amount desired to use by the user
    function _approvePool(uint256 amount0Desired, uint256 amount1Desired) internal {
        IERC20 token0Interface = IERC20(token0);
        token0Interface.approve(pool, amount0Desired);
        IERC20 token1Interface = IERC20(token1);
        token1Interface.approve(pool, amount1Desired);
    }

    /// @dev approves the pool for the amount desired to use by the user
    function _computePositionKey (address lpToken) internal view returns (bytes32) {
        return keccak256(abi.encodePacked(lpToken, tickLower, tickUpper));
    }

    /// @dev handles the updating of position data from the V3 pool to our end when adding liquidity
    /// required to calculate an accurate amount of tokens to collect from fees
    function _addPosition(IUniswapV3Pool poolContract) internal {
        bytes32 positionKey = _computePositionKey(address(this));
        (, uint256 _feeGrowthInside0LastX128, uint256 _feeGrowthInside1LastX128, , ) = poolContract.positions(positionKey);

        positionState.tokensOwed0 += uint128(
            FullMath.mulDiv(
                _feeGrowthInside0LastX128 - positionState.feeGrowthInside0LastX128,
                positionState.liquidity,
                FixedPoint128.Q128
            )
        );

        positionState.tokensOwed1 += uint128(
            FullMath.mulDiv(
                _feeGrowthInside1LastX128 - positionState.feeGrowthInside1LastX128,
                positionState.liquidity,
                FixedPoint128.Q128
            )
        );

        positionState.feeGrowthInside0LastX128 = _feeGrowthInside0LastX128;
        positionState.feeGrowthInside1LastX128 = _feeGrowthInside1LastX128;
    }

    /// @dev handles the updating of position data from the V3 pool to our end when removing liquidity
    /// required to calculate an accurate amount of tokens to collect from fees
    function _removePosition(IUniswapV3Pool poolContract, uint256 amount0 , uint256 amount1) internal {
        bytes32 positionKey = _computePositionKey(address(this));
        (, uint256 _feeGrowthInside0LastX128, uint256 _feeGrowthInside1LastX128, , ) = poolContract.positions(positionKey);

        positionState.tokensOwed0 +=
            uint128(amount0) +
            uint128(
                FullMath.mulDiv(
                    _feeGrowthInside0LastX128 - positionState.feeGrowthInside0LastX128,
                    positionState.liquidity,
                    FixedPoint128.Q128
                )
            );

        positionState.tokensOwed1 +=
            uint128(amount1) +
            uint128(
                FullMath.mulDiv(
                    _feeGrowthInside1LastX128 - positionState.feeGrowthInside1LastX128,
                    positionState.liquidity,
                    FixedPoint128.Q128
                )
            );

        positionState.feeGrowthInside0LastX128 = _feeGrowthInside0LastX128;
        positionState.feeGrowthInside1LastX128 = _feeGrowthInside1LastX128;
    }

    /// @dev handles the updating of position data from the V3 pool to our end when collecting fees
    /// required to calculate an accurate amount of tokens to collect from fees
    function _getTokensOwed(IUniswapV3Pool poolContract) internal returns (uint128 tokensOwed0, uint128 tokensOwed1) {
        poolContract.burn(tickLower, tickUpper, 0);

        bytes32 positionKey = _computePositionKey(address(this));
        (, uint256 _feeGrowthInside0LastX128, uint256 _feeGrowthInside1LastX128, , ) = poolContract.positions(positionKey);

        tokensOwed0 += uint128(
            FullMath.mulDiv(
                _feeGrowthInside0LastX128 - positionState.feeGrowthInside0LastX128,
                positionState.liquidity,
                FixedPoint128.Q128
            )
        );

        tokensOwed1 += uint128(
            FullMath.mulDiv(
                _feeGrowthInside1LastX128 - positionState.feeGrowthInside1LastX128,
                positionState.liquidity,
                FixedPoint128.Q128
            )
        );

        positionState.feeGrowthInside0LastX128 = _feeGrowthInside0LastX128;
        positionState.feeGrowthInside1LastX128 = _feeGrowthInside1LastX128;
    }

    /// @dev uses V3 libraries to calculate the amount of liquidity as a single number from 
    /// the amount of each token desired for liquidity
    /// @return liquidity as a uint128
    function getLiquidityAmount(uint256 amount0Desired, uint256 amount1Desired) public view returns (uint128 liquidity) {
        IUniswapV3Pool poolContract = IUniswapV3Pool(pool);

        (uint160 sqrtPriceX96, , , , , , ) = poolContract.slot0();
        uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
        uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);

        liquidity = LiquidityAmounts.getLiquidityForAmounts(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, amount0Desired, amount1Desired);
    }

    modifier isLPToken() {
        require(IUnicryptUniV3LPFactory(owner()).getLPTokenAddress(token0, token1, fee) != address(0), "Nice try! Contact boka@unicrypt.network for potential integrations");
        _;
    }


    function handleLiquidity(uint256 __amount0Desired, uint256 __amount1Desired, uint256 __amount0AfterFees, uint256 __amount1AfterFees) external isLPToken returns (uint128)  {
        uint128 __liquidity;
        _approvePool(__amount0Desired, __amount1Desired);

        __liquidity = getLiquidityAmount(__amount0AfterFees, __amount1AfterFees);  
        return __liquidity;
    }

    function finalizeLiquidity(uint128 liquidity, uint256 amount0, uint256 amount1, uint256 amount0Fee, uint256 amount1Fee) external isLPToken {
        IUnicryptUniV3LPFactory factory = IUnicryptUniV3LPFactory(owner());
        IUniswapV3Pool poolContract = IUniswapV3Pool(pool);
        IFeeHelper feeHelper = IFeeHelper(factory.getFeeHelperAddress());

        _mint(msg.sender, liquidity);
        _addPosition(poolContract);
        
        positionState.liquidity += liquidity;

        pay(token0, msg.sender, feeHelper.getFeeAddress(), amount0Fee);
        pay(token1, msg.sender, feeHelper.getFeeAddress(), amount1Fee);

        emit Fee(token0, msg.sender, feeHelper.getFeeAddress(), amount0Fee);
        emit Fee(token1, msg.sender, feeHelper.getFeeAddress(), amount1Fee);
        emit Mint(msg.sender, tickLower, tickUpper, liquidity, amount0, amount1); 
    }

    function getActualLiquidity(uint256 _desiredLiquidity) external payable isLPToken returns (uint128 actualLiquidity) {
        require(totalSupply() > 0, "No liquidity to remove");
        require(balanceOf(msg.sender) - _desiredLiquidity >= 0, "Not enough liquidity");
        actualLiquidity = uint128(FullMath.mulDiv(_desiredLiquidity, positionState.liquidity, totalSupply()));
    }

    function removeLiquidity(uint256 _desiredLiquidity, uint128 actualLiquidity, uint256 amount0 , uint256 amount1) external payable nonReentrant isLPToken {
        IUniswapV3Pool poolContract = IUniswapV3Pool(pool);
        _burn(msg.sender, _desiredLiquidity);
        _removePosition(poolContract, amount0, amount1);
        positionState.liquidity -= actualLiquidity;
        poolContract.collect(msg.sender, tickLower, tickUpper, uint128(amount0), uint128(amount1));

        emit Burn(msg.sender, tickLower, tickUpper, actualLiquidity, _desiredLiquidity, amount0, amount1);
    }


    /// @notice Collects tokens owed from the liquidity pool and sends back to the LP Token
    /// @dev the LP Token receives the fees, then mints them back into the pool. 
    /// @param amount0Max The maximum amount of token0 to collect from the liquidity pool
    /// @param amount1Max The maximum amount of token1 to collect from the liquidity pool
    /// @return amount0 and amount1 - the amount of each token collected
    function collect(uint128 amount0Max, uint128 amount1Max) external nonReentrant isLPToken returns (uint256 amount0, uint256 amount1,  uint128 liquidity) {
        require(amount0Max > 0 || amount1Max > 0, "Need to specify amount(s) to collect");

        IUniswapV3Pool poolContract = IUniswapV3Pool(pool);
        (uint128 _tokensOwed0, uint128 _tokensOwed1) = _getTokensOwed(poolContract);
        (uint128 amount0Collect, uint128 amount1Collect) =
            (
                amount0Max > _tokensOwed0 ? _tokensOwed0 : amount0Max,
                amount1Max > _tokensOwed1 ? _tokensOwed1 : amount1Max
            );
        (amount0, amount1) = poolContract.collect(
            address(this),
            tickLower,
            tickUpper,
            amount0Collect,
            amount1Collect
        );

        (positionState.tokensOwed0, positionState.tokensOwed1) = (_tokensOwed0 - amount0Collect, _tokensOwed1 - amount1Collect);

        emit Collect(pool, amount0Collect, amount1Collect);

        uint256 token0Balance = balance0();
        uint256 token1Balance = balance1();

        if(token0Balance != 0 && token1Balance != 0) {
            liquidity = getLiquidityAmount(token0Balance, token1Balance);
        } else {
            liquidity = 0;
        }
    }

    function mintCollected(uint128 liquidity) isLPToken external {
        IUniswapV3Pool poolContract = IUniswapV3Pool(pool);
        _addPosition(poolContract);

        positionState.liquidity += liquidity;
    }

    /// @dev retrieves the current balance of the LP Token from token0 
    function balance0() private view returns (uint256) {
        (bool success, bytes memory data) =
            token0.staticcall(abi.encodeWithSelector(IERC20.balanceOf.selector, address(this)));
        require(success && data.length >= 32);
        return abi.decode(data, (uint256));
    }

    /// @dev retrieves the current balance of the LP Token from token1
    function balance1() private view returns (uint256) {
        (bool success, bytes memory data) =
            token1.staticcall(abi.encodeWithSelector(IERC20.balanceOf.selector, address(this)));
        require(success && data.length >= 32);
        return abi.decode(data, (uint256));
    }

    /// @notice Sets the initial price for the pool. Can only be called once.
    /// @param _sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initializePool(uint160 _sqrtPriceX96) external isLPToken{
        require(!initialized, "Already Initialized");
        IUniswapV3Pool poolContract = IUniswapV3Pool(pool);
        (uint160 sqrtPriceX96, , , , , , ) = poolContract.slot0();
        if(sqrtPriceX96 != 0) {
            initialized = true;
            return;
        }
        IUniswapV3Pool(pool).initialize(_sqrtPriceX96);
        initialized = true;
        emit InitializePool(sqrtPriceX96);
    }
} 
// File: MigrateLP.sol



// SPDX-License-Identifier: UNLICENSED

// This contract locks uniswap v2 liquidity tokens. Used to give investors piece of mind a token team has locked liquidity
// and that the univ2 tokens cannot be removed from uniswap until the specified unlock date has been reached.

pragma solidity 0.8.3;

import "./TransferHelper.sol";
import "./EnumerableSet.sol";

contract MigrateLP {
    using EnumerableSet for EnumerableSet.AddressSet;
    
    address public sender;
    address public lockOwner;
    
    address public uniswapV2Locker;
    
    struct TokenLock {
      uint256 lockDate; // the date the token was locked
      uint256 amount; // the amount of tokens still locked (initialAmount minus withdrawls)
      uint256 initialAmount; // the initial lock amount
      uint256 unlockDate; // the date the token can be withdrawn
      uint256 lockID; // lockID nonce per uni pair
      address owner;
    }
    
    EnumerableSet.AddressSet private lockedTokens;
    mapping(address => TokenLock[]) public tokenLocks; //map univ2 pair to all its locks
    
    constructor(address _uniswapV2Locker) public {
      uniswapV2Locker = _uniswapV2Locker;
    }
    
    function migrate(address _lpToken, uint256 _amount, uint256 _unlockDate, address payable _owner) external returns (bool) {
      require(msg.sender == uniswapV2Locker, 'OWNER NOT LOCKER');
      TransferHelper.safeTransferFrom(_lpToken, address(msg.sender), address(this), _amount);
      sender = msg.sender;
      lockOwner = _owner;
      
      TokenLock memory token_lock;
      token_lock.lockDate = block.timestamp;
      token_lock.amount = _amount;
      token_lock.initialAmount = _amount;
      token_lock.unlockDate = _unlockDate;
      token_lock.lockID = tokenLocks[_lpToken].length;
      token_lock.owner = _owner;

      // record the lock for the univ2pair
      tokenLocks[_lpToken].push(token_lock);
      lockedTokens.add(_lpToken);
    
      return true;
    }
    
    function getNumLocksForToken (address _lpToken) external view returns (uint256) {
      return tokenLocks[_lpToken].length;
    }
}
// File: Ownable.sol



// SPDX-License-Identifier: MIT

// File @openzeppelin/contracts/access/Ownable.sol@v4.0.0

pragma solidity ^0.8.0;

import "./Context.sol";
/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

// File: ReentrancyGuard.sol



// SPDX-License-Identifier: MIT

// File @openzeppelin/contracts/security/ReentrancyGuard.sol@v4.0.0

pragma solidity 0.8.3;

/**
 * @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].
 */
abstract 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 () {
        _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: TickHelper.sol



// SPDX-License-Identifier: UNLICENSED
// ALL RIGHTS RESERVED
// Unicrypt by SDDTech reserves all rights on this code. You may NOT copy these contracts.

pragma solidity 0.8.3;

import "./Ownable.sol";

contract TickHelper is Ownable {

    int24 constant public maxTickValue = 887272;

    struct FeeAmount {
        uint24 LOW;
        uint24 MEDIUM;
        uint24 HIGH;
    }

    mapping(uint24 => uint24) public tick_spacings;

    FeeAmount public fees;

    event UpdatedTickSpace(uint24 fee, uint24 tickSpace);

    constructor() {
        fees = FeeAmount(500,3000,10000); 
        tick_spacings[fees.LOW] = 10;
        tick_spacings[fees.MEDIUM] = 60;
        tick_spacings[fees.HIGH] = 200;
        emit UpdatedTickSpace(fees.LOW, 10);
        emit UpdatedTickSpace(fees.MEDIUM, 60);
        emit UpdatedTickSpace(fees.HIGH, 200);
    }

    function ceil(int24 a, int24 m) internal pure returns (int24) {
        return (a + m - 1) / m;
    }

    /// @notice Returns the max tick for a given fee amount
    /// @param fee the fee used in the pool
    /// @return maxTick The tick spacing
    function getMaxTick(uint24 fee) external view returns(int24 maxTick) {
       int24 tickSpacing = int24(tick_spacings[fee]);  
       maxTick = tickSpacing * (maxTickValue / tickSpacing);    
    }

    /// @notice Returns the min tick for a given fee amount
    /// @param fee the fee used in the pool
    /// @return minTick The tick spacing
    function getMinTick(uint24 fee) external view returns(int24 minTick) {
       int24 tickSpacing = int24(tick_spacings[fee]);  
       int24 maxTick = tickSpacing * (maxTickValue / tickSpacing); 
       minTick = -maxTick;
    }

    /// @notice Sets a new fee and tickSpace for that fee. Only Owner can call
    /// Should only be used when uniswap v3 adds new fees
    /// @param fee the new fee to be added.
    /// @param tickSpace the new ticks space related to the fee
    function setTickSpace(uint24 fee, uint24 tickSpace) external onlyOwner {
        tick_spacings[fee] = tickSpace;
        emit UpdatedTickSpace(fee, tickSpace);
    }
}
// File: TickMath.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
        uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
        require(absTick <= uint256(uint24(MAX_TICK)), 'T');

        uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
        if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
        if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
        if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
        if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
        if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
        if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
        if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
        if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
        if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
        if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
        if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
        if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
        if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
        if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
        if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
        if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
        if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
        if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
        if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

        if (tick > 0) ratio = type(uint256).max / ratio;

        // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
        // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
        // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
        sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
    }

    /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
    /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
    /// ever return.
    /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
    /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
    function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
        // second inequality must be < because the price can never reach the price at the max tick
        require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
        uint256 ratio = uint256(sqrtPriceX96) << 32;

        uint256 r = ratio;
        uint256 msb = 0;

        assembly {
            let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(5, gt(r, 0xFFFFFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(4, gt(r, 0xFFFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(3, gt(r, 0xFF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(2, gt(r, 0xF))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := shl(1, gt(r, 0x3))
            msb := or(msb, f)
            r := shr(f, r)
        }
        assembly {
            let f := gt(r, 0x1)
            msb := or(msb, f)
        }

        if (msb >= 128) r = ratio >> (msb - 127);
        else r = ratio << (127 - msb);

        int256 log_2 = (int256(msb) - 128) << 64;

        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(63, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(62, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(61, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(60, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(59, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(58, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(57, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(56, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(55, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(54, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(53, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(52, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(51, f))
            r := shr(f, r)
        }
        assembly {
            r := shr(127, mul(r, r))
            let f := shr(128, r)
            log_2 := or(log_2, shl(50, f))
        }

        int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number

        int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
        int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);

        tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
    }
}
// File: TransferHelper.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.3;

import './IERC20.sol';

library TransferHelper {
    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), ' ');
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors with 'SA' if transfer fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Fails with `STE`
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'STE');
    }
}
// File: UnicryptUniV3LPFactory.sol



// SPDX-License-Identifier: UNLICENSED
// ALL RIGHTS RESERVED
// Unicrypt by SDDTech reserves all rights on this code. You may NOT copy these contracts.

pragma solidity 0.8.3;

import "./IUniswapV3Factory.sol";
import "./IUnicryptUniV3LPToken.sol";
import "./ITickHelper.sol";

import "./Ownable.sol";
import "./EnumerableSet.sol";

import "./UnicryptUniV3LPToken.sol";

contract UnicryptUniV3LPFactory is Ownable{
    using EnumerableSet for EnumerableSet.AddressSet;

    address public uniswapV3Factory;
    address public WETH9;
    address public tickHelper;
    address public feeHelper;
    address public lpTokenHelper;

    mapping(address => mapping(address => mapping(uint24 => address))) public getLPToken;

    uint256 public NUM_TOKENS;
    EnumerableSet.AddressSet private LP_TOKENS; 


    event LPTokenCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        address lpToken,
        address pool
    );
    event UpdatedTickHelper(address newTickHelper);
    event UpdatedFeeHelper(address newFeeHelper);
    event UpdatedLPTokenHelper(address newLPTokenHelper);

    constructor(address _uniswapV3Factory, address _WETH9, address _tickHelper, address _feeHelper, address _lpTokenHelper) {
        require(_uniswapV3Factory != address(0));
        require(_WETH9 != address(0));
        require(_tickHelper != address(0));
        require(_feeHelper != address(0));
        require(_lpTokenHelper != address(0));
        uniswapV3Factory = _uniswapV3Factory;
        WETH9 = _WETH9;
        tickHelper = _tickHelper;
        feeHelper = _feeHelper;
        lpTokenHelper = _lpTokenHelper;
        emit UpdatedTickHelper(_tickHelper);
        emit UpdatedFeeHelper(_feeHelper);
    }

    /// @notice Creates a pool for the given two tokens and fee, or updates a pool if it already exists. Creates an LP token.
    /// @param _token0 One of the two tokens in the desired pool
    /// @param _token1 The other of the two tokens in the desired pool
    /// @param _fee The desired fee for the pool
    /// @param _sqrtPriceX96 to initiate the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
    /// The call will revert if the fee is invalid, or the token arguments
    /// are invalid.
    /// @return lpToken The address of the newly created LP Token
    function createOrUpdatePool(address _token0, address _token1, uint24 _fee, uint160 _sqrtPriceX96) external returns (address lpToken) {
        require(IUniswapV3Factory(uniswapV3Factory).feeAmountTickSpacing(_fee) > 0, "Invalid fee selected");
        require(_token0 != address(0));
        require(_token1 != address(0));
        require(getLPToken[_token0][_token1][_fee] == address(0));

        (address token0, address token1) = _token0 < _token1 ? (_token0, _token1) : (_token1, _token0);

        address pool = IUniswapV3Factory(uniswapV3Factory).getPool(token0, token1, _fee);

        if(pool == address(0)){
           pool = IUniswapV3Factory(uniswapV3Factory).createPool(token0, token1, _fee); 
        } 

        UnicryptUniV3LPToken lpTokenContract = new UnicryptUniV3LPToken("Unicrypt/Uniswap-V3 LP","UNCX-UNIV3-LP", token0, token1, _fee, pool, WETH9);
        lpToken = address(lpTokenContract);
        getLPToken[token0][token1][_fee] = lpToken;
        getLPToken[token1][token0][_fee] = lpToken;
        NUM_TOKENS++;
        LP_TOKENS.add(lpToken);

        setTicksOnLPToken(lpToken, _fee);

        lpTokenContract.initializePool(_sqrtPriceX96);

        emit LPTokenCreated(token0, token1, _fee, lpToken, pool);
    }

    /// @notice Returns the LP Token address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param _token0 The contract address of either token0 or token1
    /// @param _token1 The contract address of the other token
    /// @param _fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return lpToken The pool address
    function getLPTokenAddress(address _token0, address _token1, uint24 _fee) external view returns (address) {
        return getLPToken[_token0][_token1][_fee];
    }

    /// @dev sets ticks on LP token. Called upon creation
    function setTicksOnLPToken(address lpTokenAddress, uint24 fee) internal {
        IUnicryptUniV3LPToken lpToken = IUnicryptUniV3LPToken(lpTokenAddress);
        ITickHelper tickHelperContract = ITickHelper(tickHelper);
        int24 tickUpper = tickHelperContract.getMaxTick(fee);
        int24 tickLower = tickHelperContract.getMinTick(fee);
        lpToken.setTicks(tickUpper, tickLower);
    }

    /// @notice Sets the address for the current or desired TickHelper Contract
    /// @dev called only when updating the TickHelper Contract
    /// @param _newtickHelper address of the new contract
    function updateTickHelper(address _newtickHelper) external onlyOwner {
        require(_newtickHelper != address(0));
        tickHelper = _newtickHelper;
        emit UpdatedTickHelper(_newtickHelper);
    }    

    /// @notice Returns the LP Token address for a given index
    /// @dev Use NUM_TOKENS to get the array length, then iterate through the array with this function
    /// @param _index The index
    /// @return lpToken The pool address
    function getLPTokenByIndex(uint256 _index) external view returns (address lpToken) {
        return LP_TOKENS.at(_index);
    }

    /// @notice Returns the LP Token length
    /// @return lpToken array length
    function getLPTokenLength() external view returns (uint256) {
        return LP_TOKENS.length();
    }

    /// @notice Used to check if a lpToken address was generated by the Unicrypt Uniswap V3 Factory
    /// @param _lpToken lpToken address
    /// @return true if generated by this factory
    function isLPToken(address _lpToken) external view returns (bool) {
        return LP_TOKENS.contains(_lpToken);
    }

    /// @notice Sets the address for the current or desired FeeHelper Contract
    /// @dev called only when updating the FeeHelper Contract
    /// @param _newFeeHelper address of the new contract
    function updateFeeHelper(address  _newFeeHelper) external onlyOwner{
        require(_newFeeHelper != address(0));
        feeHelper = _newFeeHelper;
        emit UpdatedFeeHelper(_newFeeHelper);
    }

    /// @notice Returns the feeHelper Address
    /// @return feeHelper Address
    function getFeeHelperAddress() external view returns (address) {
        return feeHelper;
    }

    /// @notice Sets the address for the current or desired lpTokenHelper Contract
    /// @dev called only when updating the lpTokenHelper Contract
    /// @param _newLPTokenHelper address of the new contract
    function updateLPTokenHelper(address  _newLPTokenHelper) external onlyOwner{
        require(_newLPTokenHelper != address(0));
        lpTokenHelper = _newLPTokenHelper;
        emit UpdatedLPTokenHelper(_newLPTokenHelper);
    }

    /// @notice Returns the lpTokenHelper Address
    /// @return lpTokenHelper Address
    function getLPTokenHelperAddress() external view returns (address) {
        return lpTokenHelper;
    }

}
// File: UnicryptUniV3LPToken.sol



// SPDX-License-Identifier: UNLICENSED
// ALL RIGHTS RESERVED
// Unicrypt by SDDTech reserves all rights on this code. You may NOT copy these contracts.

pragma solidity 0.8.3;

import "./ERC20.sol";
import "./Ownable.sol";

import "./TransferHelper.sol";
import "./FullMath.sol";

import "./IUniswapV3MintCallback.sol";
import "./IUniswapV3Pool.sol";
import "./IWETH9.sol";
import "./IUnicryptUniV3LPFactory.sol";
import "./IFeeHelper.sol";

/// @title Uniswap V3 LP Token on Unicrypt
/// @notice The Uniswap V3 LP Token facilitates creates and manages Unicrypt LP tokens and 
///  interactions with the pool

contract UnicryptUniV3LPToken is ERC20, Ownable, IUniswapV3MintCallback {

    uint256 constant public CONTRACT_VERSION = 1;

    address public token0;
    address public token1;
    address public pool;
    uint24 public fee;
    /// @dev stores tick data, used by the V3 pool to calculate the range of concentrated liquidity
    int24 public tickUpper;
    int24 public tickLower;

    /// @dev stores position data from the V3 pool, used to calculate rewards from fees
    /// updated after each call to the V3 pool
    struct Position {
        uint256 liquidity;
        uint256 feeGrowthInside0LastX128;
        uint256 feeGrowthInside1LastX128;
        uint128 tokensOwed0;
        uint128 tokensOwed1;
    }

    Position public positionState;

    /// @dev pool cannot be initiallized twice
    bool public initialized = false;

    address public WETH9;

    /// @dev used to create a unique pool key similar to what V3 uses
    struct PoolKey {
        address token0;
        address token1;
        uint24 fee;
    }

    /// @dev data format needed to decode the mintcallback data from the pool
    struct MintCallbackData {
        PoolKey poolKey;
        address payer;
    }
    
    PoolKey private poolKey;

    event Mint(address sender, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 amount0, uint256 amount1);
    event Burn(address sender, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 _desiredLiquidity, uint256 amount0, uint256 amount1);
    event Collect(address pool, uint128 amount0Collect, uint128 amount1Collect);
    event Fee(address token, address sender, address recipient, uint256 fee);
    event SetTicks(int24 tickUpper, int24 tickLower);
    event InitializePool(uint160 sqrtPriceX96);

    constructor(string memory name, string memory symbol, address _token0, address _token1, uint24 _fee, address _pool, address _WETH9) ERC20(name, symbol) {
        require(_token0 != address(0));
        require(_token1 != address(0));
        require(_pool != address(0));
        require(_WETH9 != address(0));

        token0 = _token0;
        token1 = _token1;
        fee = _fee;
        pool = _pool;
        WETH9 = _WETH9;
        poolKey = PoolKey(token0, token1, fee);
    }

    /// @notice Sets the ticks on the LP Token
    /// @dev Must call this from the factory before doing any liquidity operations
    /// @param _tickUpper The higher tick
    /// @param _tickLower The lower tick
    function setTicks(int24 _tickUpper, int24 _tickLower) external onlyOwner{
        tickUpper = _tickUpper;
        tickLower = _tickLower;
        emit SetTicks(_tickUpper, _tickLower);
    }

    /// @dev helper to handle different types of payments depending on transactions.
    function pay(address token, address payer, address recipient, uint256 value) internal {
        if (token == WETH9 && address(this).balance >= value) {
            // pay with WETH9
            IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay
            bool res = IWETH9(WETH9).transfer(recipient, value);
            require(res);
        } else if (payer == address(this)) {
            // pay with tokens already in the contract (for the exact input multihop case)
            TransferHelper.safeTransfer(token, recipient, value);
        } else {
            // pull payment
            TransferHelper.safeTransferFrom(token, payer, recipient, value);
        }
    }

    /// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
    /// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
    /// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
    function uniswapV3MintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata data) external override {
        require(msg.sender == pool);
        MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));

        if (amount0Owed > 0) {
            pay(decoded.poolKey.token0, decoded.payer, msg.sender, amount0Owed);
        } 

        if (amount1Owed > 0) {
            pay(decoded.poolKey.token1, decoded.payer, msg.sender, amount1Owed);
        }
    }

    /// @notice Mints liquidity to the Uniswap V3 Pool, and adds to the total supply
    /// of the LP Token. A fee is taken from each token before minting liquidity
    /// @param amount0Desired The desired amount of token0 added to the liquidity pool
    /// @param amount1Desired The desired amount of token1 added to the liquidity pool
    /// @return amount0 and amount1 - the amount eof each token used to provide liquidity
    function addLiquidity(uint256 amount0Desired, uint256 amount1Desired) external returns (uint256 amount0 , uint256 amount1) {
        uint128 liquidity;
        IFeeHelper feeHelper = IFeeHelper(IUnicryptUniV3LPFactory(owner()).getFeeHelperAddress());

        uint256 amount0Fee = FullMath.mulDiv(amount0Desired, feeHelper.getFee(), feeHelper.getFeeDenominator());
        uint256 amount1Fee = FullMath.mulDiv(amount1Desired, feeHelper.getFee(), feeHelper.getFeeDenominator());
        uint256 amount0AfterFees = amount0Desired - amount0Fee;
        uint256 amount1AfterFees = amount1Desired - amount1Fee;

        
        address lpTokenHelper = IUnicryptUniV3LPFactory(owner()).getLPTokenHelperAddress();

        (bool success0, bytes memory result0) = lpTokenHelper.delegatecall(abi.encodeWithSignature("handleLiquidity(uint256,uint256,uint256,uint256)", amount0Desired, amount1Desired, amount0AfterFees, amount1AfterFees));

        if (!success0) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (result0.length < 68) revert();
            revert(abi.decode(result0, (string)));
        }
        (liquidity) = abi.decode(result0, (uint128));


        IUniswapV3Pool poolContract = IUniswapV3Pool(pool);
        (amount0, amount1) = poolContract.mint(address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({poolKey: poolKey, payer: msg.sender})));
        require(amount0 + amount0Fee <= amount0Desired);
        require(amount1 + amount1Fee <= amount1Desired);
        (bool success1, bytes memory result1) = lpTokenHelper.delegatecall(abi.encodeWithSignature("finalizeLiquidity(uint128,uint256,uint256,uint256,uint256)", liquidity, amount0, amount1, amount0Fee, amount1Fee));
        if (!success1) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (result1.length < 68) revert();
            revert(abi.decode(result1, (string)));
        }
    }

    /// @notice Removes liquidity from the Uniswap V3 Pool, and burns the total supply
    /// of the LP Token, sends the owed tokens to the msg.sender
    /// @param _desiredLiquidity The desired amount of liquidity to remove
    /// @return amount0 and amount1 - the amount eof each token removed
    function removeLiquidity(uint256 _desiredLiquidity) external payable returns (uint256 amount0 , uint256 amount1) {
        IUnicryptUniV3LPFactory factory = IUnicryptUniV3LPFactory(owner());
        address lpTokenHelper = factory.getLPTokenHelperAddress();
        (bool success, bytes memory result) = lpTokenHelper.delegatecall(abi.encodeWithSignature("getActualLiquidity(uint256)", _desiredLiquidity));
        if (!success) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (result.length < 68) revert();
            revert(abi.decode(result, (string)));
        }
        (uint128 actualLiquidity) = abi.decode(result, (uint128));
        IUniswapV3Pool poolContract = IUniswapV3Pool(pool);
        (amount0, amount1) = poolContract.burn(tickLower, tickUpper, actualLiquidity);
        (bool success2, bytes memory result2) = lpTokenHelper.delegatecall(abi.encodeWithSignature("removeLiquidity(uint256,uint128,uint256,uint256)", _desiredLiquidity, actualLiquidity, amount0, amount1));
        if (!success2) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (result2.length < 68) revert();
            revert(abi.decode(result2, (string)));
        }
    }
    /// @notice Collects tokens owed from the liquidity pool and sends back to the LP Token
    /// @dev the LP Token receives the fees, then mints them back into the pool. 
    /// @param amount0Max The maximum amount of token0 to collect from the liquidity pool
    /// @param amount1Max The maximum amount of token1 to collect from the liquidity pool
    /// @return amount0 and amount1 - the amount of each token collected
    function collect(uint128 amount0Max, uint128 amount1Max) external returns (uint256 amount0, uint256 amount1) {
        IUnicryptUniV3LPFactory factory = IUnicryptUniV3LPFactory(owner());
        address lpTokenHelper = factory.getLPTokenHelperAddress();
        (bool success, bytes memory result) = lpTokenHelper.delegatecall(abi.encodeWithSignature("collect(uint128,uint128)", amount0Max, amount1Max));
        if (!success) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (result.length < 68) revert();

            revert(abi.decode(result, (string)));
        }
        uint128 liquidity;
        (amount0, amount1, liquidity) = abi.decode(result, (uint256, uint256, uint128));
        if(liquidity != 0) {
            IUniswapV3Pool poolContract = IUniswapV3Pool(pool);
            (uint256 amount0Added, uint256 amount1Added) = poolContract.mint(address(this), tickLower, tickUpper, liquidity, abi.encode(MintCallbackData({poolKey: poolKey, payer: address(this)})));
            (bool success2, bytes memory result2) = lpTokenHelper.delegatecall(abi.encodeWithSignature("mintCollected(uint128)", liquidity));
            if (!success2) {
                // Next 5 lines from https://ethereum.stackexchange.com/a/83577
                if (result2.length < 68) revert();

                revert(abi.decode(result2, (string)));
            }
            emit Mint(address(this), tickLower, tickUpper, liquidity, amount0Added, amount1Added);  
        }
    }

    /// @notice Sets the initial price for the pool. Can only be called once.
    /// @param _sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initializePool(uint160 _sqrtPriceX96) external {
        IUnicryptUniV3LPFactory factory = IUnicryptUniV3LPFactory(owner());
        address lpTokenHelper = factory.getLPTokenHelperAddress();
        (bool success, bytes memory result) = lpTokenHelper.delegatecall(abi.encodeWithSignature("initializePool(uint160)", _sqrtPriceX96));
        if (!success) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (result.length < 68) revert();
            assembly {
                result := add(result, 0x04)
            }
            revert(abi.decode(result, (string)));
        }
    }

    // @notice Multicall to mint and collect
    /// @param _amount0Desired The desired amount of token0 added to the liquidity pool
    /// @param _amount1Desired The desired amount of token1 added to the liquidity pool
    /// @param _amount0Max The maximum amount of token0 to collect from the liquidity pool
    /// @param _amount1Max The maximum amount of token1 to collect from the liquidity pool
    /// @return results
    function addMulticall(uint256 _amount0Desired, uint256 _amount1Desired, uint128 _amount0Max, uint128 _amount1Max) external payable returns (bytes[] memory results){
        results = new bytes[](2);
        (bool successAdd, bytes memory resultAdd) = address(this).delegatecall(abi.encodeWithSignature("addLiquidity(uint256,uint256)", _amount0Desired, _amount1Desired));
        (bool successCollect, bytes memory resultCollect) = address(this).delegatecall(abi.encodeWithSignature("collect(uint128,uint128)", _amount0Max, _amount1Max));
        if (!successAdd) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (resultAdd.length < 68) revert();
            assembly {
                resultAdd := add(resultAdd, 0x04)
            }
            revert(abi.decode(resultAdd, (string)));
        }
        if (!successCollect) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (resultCollect.length < 68) revert();
            assembly {
                resultCollect := add(resultCollect, 0x04)
            }
            revert(abi.decode(resultCollect, (string)));
        }
        results[0] = resultAdd;
        results[1] = resultCollect;
    }

    // @notice Multicall to remove and collect
    /// @param _desiredLiquidity The desired amount of liquidity to remove
    /// @param _amount0Max The maximum amount of token0 to collect from the liquidity pool
    /// @param _amount1Max The maximum amount of token1 to collect from the liquidity pool
    /// @return results
    function removeMulticall(uint256 _desiredLiquidity, uint128 _amount0Max, uint128 _amount1Max) external payable returns (bytes[] memory results){
        results = new bytes[](2);
        (bool successCollect, bytes memory resultCollect) = address(this).delegatecall(abi.encodeWithSignature("collect(uint128,uint128)", _amount0Max, _amount1Max));
        (bool successRemove, bytes memory resultRemove) = address(this).delegatecall(abi.encodeWithSignature("removeLiquidity(uint256)", _desiredLiquidity));
        if (!successRemove) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (resultRemove.length < 68) revert();
            assembly {
                resultRemove := add(resultRemove, 0x04)
            }
            revert(abi.decode(resultRemove, (string)));
        }
        if (!successCollect) {
            // Next 5 lines from https://ethereum.stackexchange.com/a/83577
            if (resultCollect.length < 68) revert();
            assembly {
                resultCollect := add(resultCollect, 0x04)
            }
            revert(abi.decode(resultCollect, (string)));
        }
        results[0] = resultRemove;
        results[1] = resultCollect;
    }
} 
// File: UniswapV3Locker.sol



// SPDX-License-Identifier: UNLICENSED
// ALL RIGHTS RESERVED
// Unicrypt by SDDTech reserves all rights on this code. You may NOT copy these contracts.

// This contract locks Uniswap V3 liquidity tokens. Used to give investors peace of mind a token team has locked liquidity
// and that the liquidity tokens cannot be removed from the AMM until the specified unlock date has been reached. This is one of many
// important industry standards to ensure safety.

pragma solidity 0.8.3;

import "./TransferHelper.sol";
import "./EnumerableSet.sol";
import "./Ownable.sol";
import "./ReentrancyGuard.sol";
import "./ICountryList.sol";

interface IERCBurn {
    function burn(uint256 _amount) external;
    function approve(address spender, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external returns (uint256);
    function balanceOf(address account) external view returns (uint256);
}

interface IUniV3LPFactory {
    function isLPToken(address _lpToken) external view returns (bool);
}

interface IMigrator {
    function migrate(address lpToken, uint256 amount, uint256 unlockDate, address owner, uint16 countryCode, uint256 option) external returns (bool);
}

contract UniswapV3Locker is Ownable, ReentrancyGuard {
  using EnumerableSet for EnumerableSet.AddressSet;
  using EnumerableSet for EnumerableSet.UintSet;

  IUniV3LPFactory public uniswapFactory;

  struct UserInfo {
    EnumerableSet.AddressSet lockedTokens; // records all unique tokens the user has locked
    mapping(address => EnumerableSet.UintSet) locksForToken; // map erc20 address to lock id list for that user / token.
  }

  struct TokenLock {
    address lpToken; // The LP token
    uint256 lockDate; // the date the token was locked
    uint256 amount; // the amount of tokens still locked (initialAmount minus withdrawls)
    uint256 initialAmount; // the initial lock amount
    uint256 unlockDate; // the date the token can be withdrawn
    uint256 lockID; // lockID nonce per uni pair
    address owner; // who can withdraw the lock
    uint16 countryCode; // the country code of the locker / business
  }

  mapping(address => UserInfo) private USERS; // Get lock user info

  mapping(uint256 => TokenLock) public LOCKS; // ALL locks are registered here in chronological lock id order.
  uint256 public NONCE = 0; // incremental lock nonce counter, this is the unique ID for the next lock

  EnumerableSet.AddressSet private lockedTokens; // a list of all unique locked liquidity tokens
  mapping(address => uint256[]) public TOKEN_LOCKS; // map univ2 pair to an array of all its lock ids
  
  struct FeeStruct {
    uint256 ethFee; // Small eth fee to prevent spam on the platform
    IERCBurn secondaryFeeToken; // UNCX or UNCL
    uint256 secondaryTokenFee; // optional, UNCX or UNCL
    uint256 secondaryTokenDiscount; // discount on liquidity fee for burning secondaryToken
    uint256 liquidityFee; // fee on univ2 liquidity tokens
    uint256 referralPercent; // fee for referrals
    IERCBurn referralToken; // token the refferer must hold to qualify as a referrer
    uint256 referralHold; // balance the referrer must hold to qualify as a referrer
    uint256 referralDiscount; // discount on flatrate fees for using a valid referral address
  }
    
  FeeStruct public gFees;
  EnumerableSet.AddressSet private feeWhitelist;
  
  address payable devaddr;
  
  IMigrator public migrator; // migration contract
  ICountryList public COUNTRY_LIST;

  event onNewLock(uint256 lockID, address lpToken, address owner, uint256 amount, uint256 lockDate, uint256 unlockDate, uint16 countryCode);
  event onRelock(uint256 lockID, address lpToken, address owner, uint256 amountRemainingInLock, uint256 liquidityFee, uint256 unlockDate);
  event onWithdraw(uint256 lockID, address lpToken, address owner, uint256 amountRemainingInLock, uint256 amountRemoved);
  event onIncrementLock(uint256 lockID, address lpToken, address owner, address payer, uint256 amountRemainingInLock, uint256 amountAdded, uint256 liquidityFee);
  event onSplitLock(uint256 lockID, address lpToken, address owner, uint256 amountRemainingInLock, uint256 amountRemoved);
  event onTransferLockOwnership(uint256 lockID, address lpToken, address oldOwner, address newOwner);
  event OnMigrate(uint256 lockID, address lpToken, address owner, uint256 amountRemainingInLock, uint256 amountMigrated, uint256 migrationOption);

  constructor(IUniV3LPFactory _uniswapFactory, ICountryList _countryList) {
    devaddr = payable(msg.sender);
    gFees.referralPercent = 250; // 25%
    gFees.ethFee = 1e18;
    gFees.secondaryTokenFee = 100e18;
    gFees.secondaryTokenDiscount = 200; // 20%
    gFees.liquidityFee = 10; // 1%
    gFees.referralHold = 10e18;
    gFees.referralDiscount = 100; // 10%
    uniswapFactory = _uniswapFactory;
    COUNTRY_LIST = _countryList;
  }
  
  function setDev(address payable _devaddr) public onlyOwner {
    devaddr = _devaddr;
  }
  
  /**
   * @notice set the migrator contract which allows locked lp tokens to be migrated to future AMM versions
   */
  function setMigrator(IMigrator _migrator) public onlyOwner {
    migrator = _migrator;
  }
  
  function setSecondaryFeeToken(address _secondaryFeeToken) public onlyOwner {
    gFees.secondaryFeeToken = IERCBurn(_secondaryFeeToken);
  }
  
  /**
   * @notice referrers need to hold the specified token and hold amount to be elegible for referral fees
   */
  function setReferralTokenAndHold(IERCBurn _referralToken, uint256 _hold) public onlyOwner {
    gFees.referralToken = _referralToken;
    gFees.referralHold = _hold;
  }
  
  function setFees(uint256 _referralPercent, uint256 _referralDiscount, uint256 _ethFee, uint256 _secondaryTokenFee, uint256 _secondaryTokenDiscount, uint256 _liquidityFee) public onlyOwner {
    gFees.referralPercent = _referralPercent;
    gFees.referralDiscount = _referralDiscount;
    gFees.ethFee = _ethFee;
    gFees.secondaryTokenFee = _secondaryTokenFee;
    gFees.secondaryTokenDiscount = _secondaryTokenDiscount;
    gFees.liquidityFee = _liquidityFee;
  }
  
  /**
   * @notice whitelisted accounts dont pay flatrate fees on locking
   */
  function whitelistFeeAccount(address _user, bool _add) public onlyOwner {
    if (_add) {
      feeWhitelist.add(_user);
    } else {
      feeWhitelist.remove(_user);
    }
  }

  /**
   * @notice Creates a new lock
   * @param _lpToken the univ3 token address
   * @param _amount amount of LP tokens to lock
   * @param _unlock_date the unix timestamp (in seconds) until unlock
   * @param _referral the referrer address if any or address(0) for none
   * @param _fee_in_eth fees can be paid in eth or in a secondary token such as UNCX with a discount on univ2 tokens
   * @param _withdrawer the user who can withdraw liquidity once the lock expires.
   * @param _countryCode the code of the country from which the lock user account / business is from
   */
  function lockLPToken (address _lpToken, uint256 _amount, uint256 _unlock_date, address payable _referral, bool _fee_in_eth, address payable _withdrawer, uint16 _countryCode) external payable nonReentrant {
    require(_unlock_date < 10000000000, 'TIMESTAMP INVALID'); // prevents errors when timestamp entered in milliseconds
    require(_amount > 0, 'INSUFFICIENT');
    require(COUNTRY_LIST.countryIsValid(_countryCode), 'COUNTRY');

    // ensure the lp token is a valid Unicrypt Uniswap V3 LP token querying the factory
    require(uniswapFactory.isLPToken(_lpToken), 'NOT UNI V3');

    TransferHelper.safeTransferFrom(_lpToken, address(msg.sender), address(this), _amount);
    
    if (_referral != address(0) && address(gFees.referralToken) != address(0)) {
      require(gFees.referralToken.balanceOf(_referral) >= gFees.referralHold, 'INADEQUATE BALANCE');
    }
    
    // flatrate fees
    if (!feeWhitelist.contains(msg.sender)) {
      if (_fee_in_eth) { // charge fee in eth
        uint256 ethFee = gFees.ethFee;
        if (_referral != address(0)) {
          ethFee = ethFee * (1000 - gFees.referralDiscount) / 1000;
        }
        require(msg.value == ethFee, 'FEE NOT MET');
        uint256 devFee = ethFee;
        if (ethFee != 0 && _referral != address(0)) { // referral fee
          uint256 referralFee = devFee * gFees.referralPercent / 1000;
          _referral.transfer(referralFee);
          devFee -= referralFee;
        }
        devaddr.transfer(devFee);
      } else { // charge fee in token
        uint256 burnFee = gFees.secondaryTokenFee;
        if (_referral != address(0)) {
          burnFee = burnFee * (1000 - gFees.referralDiscount) / 1000;
        }
        TransferHelper.safeTransferFrom(address(gFees.secondaryFeeToken), address(msg.sender), address(this), burnFee);
        if (gFees.referralPercent != 0 && _referral != address(0)) { // referral fee
          uint256 referralFee = burnFee * gFees.referralPercent / 1000;
          TransferHelper.safeApprove(address(gFees.secondaryFeeToken), _referral, referralFee);
          TransferHelper.safeTransfer(address(gFees.secondaryFeeToken), _referral, referralFee);
          burnFee -= referralFee;
        }
        gFees.secondaryFeeToken.burn(burnFee);
      }
    } else if (msg.value > 0){
      // refund eth if a whitelisted member sent it by mistake
      payable(msg.sender).transfer(msg.value);
    }
    
    // percent fee
    uint256 liquidityFee = _amount * gFees.liquidityFee / 1000;
    if (!_fee_in_eth && !feeWhitelist.contains(msg.sender)) { // fee discount for large lockers using secondary token
      liquidityFee = liquidityFee * (1000 - gFees.secondaryTokenDiscount) / 1000;
    }
    TransferHelper.safeTransfer(_lpToken, devaddr, liquidityFee);
    uint256 amountLocked = _amount - liquidityFee;

    TokenLock memory token_lock;
    token_lock.lpToken = _lpToken;
    token_lock.lockDate = block.timestamp;
    token_lock.amount = amountLocked;
    token_lock.initialAmount = amountLocked;
    token_lock.unlockDate = _unlock_date;
    token_lock.lockID = NONCE;
    token_lock.owner = _withdrawer;
    token_lock.countryCode = _countryCode;

    // record the lock for the univ2pair
    LOCKS[NONCE] = token_lock;
    lockedTokens.add(_lpToken);
    TOKEN_LOCKS[_lpToken].push(NONCE);

    // record the lock for the user
    UserInfo storage user = USERS[_withdrawer];
    user.lockedTokens.add(_lpToken);
    EnumerableSet.UintSet storage user_locks = user.locksForToken[_lpToken];
    user_locks.add(token_lock.lockID);

    NONCE ++;
    
    emit onNewLock(token_lock.lockID, _lpToken, _withdrawer, token_lock.amount, token_lock.lockDate, token_lock.unlockDate, token_lock.countryCode);
  }
  
  /**
   * @notice extend a lock with a new unlock date
   */
  function relock (uint256 _lockID, uint256 _unlock_date) external nonReentrant {
    require(_unlock_date < 10000000000, 'TIMESTAMP INVALID'); // prevents errors when timestamp entered in milliseconds
    TokenLock storage userLock = LOCKS[_lockID];
    require(userLock.owner == msg.sender, 'NOT OWNER');
    require(userLock.unlockDate < _unlock_date, 'UNLOCK BEFORE');
    
    uint256 liquidityFee = userLock.amount * gFees.liquidityFee / 1000;
    uint256 amountLocked = userLock.amount - liquidityFee;
    
    userLock.amount = amountLocked;
    userLock.unlockDate = _unlock_date;

    // send univ2 fee to dev address
    TransferHelper.safeTransfer(userLock.lpToken, devaddr, liquidityFee);
    emit onRelock(userLock.lockID, userLock.lpToken, msg.sender, userLock.amount, liquidityFee, userLock.unlockDate);
  }
  
  /**
   * @notice withdraw a specified amount from a lock
   */
  function withdraw (uint256 _lockID, uint256 _amount) external nonReentrant {
    require(_amount > 0, 'ZERO WITHDRAWL');
    TokenLock storage userLock = LOCKS[_lockID];
    require(userLock.owner == msg.sender, 'NOT OWNER');
    require(userLock.unlockDate < block.timestamp, 'NOT YET');
    userLock.amount -= _amount;

    // clean user storage
    if (userLock.amount == 0) {
      EnumerableSet.UintSet storage userLocks = USERS[msg.sender].locksForToken[userLock.lpToken];
      userLocks.remove(userLock.lockID);
      if (userLocks.length() == 0) {
        USERS[msg.sender].lockedTokens.remove(userLock.lpToken);
      }
    }
    
    TransferHelper.safeTransfer(userLock.lpToken, msg.sender, _amount);
    emit onWithdraw(userLock.lockID, userLock.lpToken, msg.sender, userLock.amount, _amount);
  }
  
  /**
   * @notice PLEASE BE AWARE THIS FUNCTION CONTAINS NO OWNER CHECK. ANYONE CAN LOCK THEIR LPS INTO SOMEONE ELSES
   * LOCK, BASICALLY GIVING THEM THEIR LP TOKENS.
   * The use here is a CONTRACT which is not the owner of a lock can increment locks periodically (for example with fees) on behalf of the owner.
   * This works well with taxing tokens.
   *
   * Increase the amount of tokens per a specific lock, this is preferable to creating a new lock,
   * less fees, and faster loading on our live block explorer.
   */
  function incrementLock (uint256 _lockID, uint256 _amount) external nonReentrant {
    require(_amount > 0, 'ZERO AMOUNT');
    TokenLock storage userLock = LOCKS[_lockID];
    // require(userLock.owner == msg.sender, 'NOT OWNER'); // disabled to allow contracts to lock on behalf of owners
    
    TransferHelper.safeTransferFrom(userLock.lpToken, address(msg.sender), address(this), _amount);
    
    // send univ2 fee to dev address
    uint256 liquidityFee = _amount * gFees.liquidityFee / 1000;
    TransferHelper.safeTransfer(userLock.lpToken, devaddr, liquidityFee);
    uint256 amountLocked = _amount - liquidityFee;
    
    userLock.amount += amountLocked;
    
    emit onIncrementLock(userLock.lockID, userLock.lpToken, userLock.owner, msg.sender, userLock.amount, amountLocked, liquidityFee);
  }
  
  /**
   * @notice split a lock into two seperate locks, useful when a lock is about to expire and youd like to relock a portion
   * and withdraw a smaller portion
   */
  function splitLock (uint256 _lockID, uint256 _amount) external payable nonReentrant {
    require(_amount > 0, 'ZERO AMOUNT');
    TokenLock storage userLock = LOCKS[_lockID];
    require(userLock.owner == msg.sender, 'NOT OWNER');
    
    require(msg.value == gFees.ethFee, 'FEE NOT MET');
    devaddr.transfer(gFees.ethFee);
    
    userLock.amount -= _amount;
    
    TokenLock memory token_lock;
    token_lock.lpToken = userLock.lpToken;
    token_lock.lockDate = userLock.lockDate;
    token_lock.amount = _amount;
    token_lock.initialAmount = _amount;
    token_lock.unlockDate = userLock.unlockDate;
    token_lock.lockID = NONCE;
    token_lock.owner = msg.sender;
    token_lock.countryCode = userLock.countryCode;

    // record the lock for the univ2pair
    TOKEN_LOCKS[userLock.lpToken].push(NONCE);
    LOCKS[NONCE] = token_lock;

    // record the lock for the user
    UserInfo storage user = USERS[msg.sender];
    EnumerableSet.UintSet storage user_locks = user.locksForToken[userLock.lpToken];
    user_locks.add(NONCE);
    NONCE ++;
    emit onSplitLock(userLock.lockID, userLock.lpToken, msg.sender, userLock.amount, _amount);
    emit onNewLock(token_lock.lockID, token_lock.lpToken, msg.sender, token_lock.amount, token_lock.lockDate, token_lock.unlockDate, token_lock.countryCode);
  }
  
  /**
   * @notice transfer a lock to a new owner, e.g. presale project -> project owner
   */
  function transferLockOwnership (uint256 _lockID, address payable _newOwner) external {
    require(msg.sender != _newOwner, 'OWNER');
    TokenLock storage transferredLock = LOCKS[_lockID];
    require(transferredLock.owner == msg.sender, 'NOT OWNER');
    
    // record the lock for the new Owner
    UserInfo storage user = USERS[_newOwner];
    user.lockedTokens.add(transferredLock.lpToken);
    EnumerableSet.UintSet storage user_locks = user.locksForToken[transferredLock.lpToken];
    user_locks.add(transferredLock.lockID);

    // remove the lock from the old owner
    EnumerableSet.UintSet storage userLocks = USERS[msg.sender].locksForToken[transferredLock.lpToken];
    userLocks.remove(transferredLock.lockID);
    if (userLocks.length() == 0) {
      USERS[msg.sender].lockedTokens.remove(transferredLock.lpToken);
    }
    
    transferredLock.owner = _newOwner;
    emit onTransferLockOwnership(_lockID, transferredLock.lpToken, msg.sender, _newOwner);
  }
  
  /**
   * @notice migrates liquidity to the next release of an AMM
   * @param _migration_option to be used as an AMM selector
   */
  function migrate (uint256 _lockID, uint256 _amount, uint256 _migration_option) external nonReentrant {
    require(address(migrator) != address(0), "NOT SET");
    require(_amount > 0, 'ZERO MIGRATION');
    
    TokenLock storage userLock = LOCKS[_lockID];
    require(userLock.owner == msg.sender, 'NOT OWNER');
    userLock.amount -= _amount;

    // clean user storage
    if (userLock.amount == 0) {
      EnumerableSet.UintSet storage userLocks = USERS[msg.sender].locksForToken[userLock.lpToken];
      userLocks.remove(userLock.lockID);
      if (userLocks.length() == 0) {
        USERS[msg.sender].lockedTokens.remove(userLock.lpToken);
      }
    }
    
    TransferHelper.safeApprove(userLock.lpToken, address(migrator), _amount);
    migrator.migrate(userLock.lpToken, _amount, userLock.unlockDate, msg.sender, userLock.countryCode, _migration_option);
    emit OnMigrate(_lockID, userLock.lpToken, msg.sender, userLock.amount, _amount, _migration_option);
  }
  
  function getNumLocksForToken (address _lpToken) external view returns (uint256) {
    return TOKEN_LOCKS[_lpToken].length;
  }
  
  function getNumLockedTokens () external view returns (uint256) {
    return lockedTokens.length();
  }
  
  function getLockedTokenAtIndex (uint256 _index) external view returns (address) {
    return lockedTokens.at(_index);
  }
  
  // user functions
  function getUserNumLockedTokens (address _user) external view returns (uint256) {
    UserInfo storage user = USERS[_user];
    return user.lockedTokens.length();
  }
  
  function getUserLockedTokenAtIndex (address _user, uint256 _index) external view returns (address) {
    UserInfo storage user = USERS[_user];
    return user.lockedTokens.at(_index);
  }
  
  function getUserNumLocksForToken (address _user, address _lpToken) external view returns (uint256) {
    UserInfo storage user = USERS[_user];
    return user.locksForToken[_lpToken].length();
  }
  
  function getUserLockForTokenAtIndex (address _user, address _lpToken, uint256 _index) external view 
  returns (TokenLock memory) {
    uint256 lockID = USERS[_user].locksForToken[_lpToken].at(_index);
    TokenLock storage tokenLock = LOCKS[lockID];
    return tokenLock;
  }
  
  // whitelist
  function getWhitelistedUsersLength () external view returns (uint256) {
    return feeWhitelist.length();
  }
  
  function getWhitelistedUserAtIndex (uint256 _index) external view returns (address) {
    return feeWhitelist.at(_index);
  }
  
  function getUserWhitelistStatus (address _user) external view returns (bool) {
    return feeWhitelist.contains(_user);
  }
}