// File: contracts/Farmer/FarmerCheems.sol



// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.7;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

contract FarmerCheems is ERC721, ERC721Enumerable, ERC721URIStorage, Ownable  {
    uint256 public _tokenIds;
    uint256 public price = 100000000000000000;

    event FarmersManufactured(address to, uint256 quantity);

    bytes4 ERC721_RECEIVED = 0x150b7a02;

    address public EmergencyAddress;
    address public Oracle;
    bool public transferFarmEnabled;
    uint256 public farmingPeriod;

    address public Cinu;
    uint public deposits;
    uint256 public stakeRequired = 500000 * 10 ** 9;

    mapping ( uint256 => Farm ) public Farms;
    mapping ( address => uint256[] ) public userFarms;
    mapping ( address =>uint256 ) public  userFarmCount;
    uint256 public FarmCount=0;

    mapping ( address => uint256[] ) public usersFarmers;
    mapping ( uint256 => uint256 ) public FarmerPosition;

    mapping ( uint256 => uint256 ) public FarmerArrayPosition;
    mapping ( uint256 => uint256 ) public FarmArrayPosition;

    uint256 public globalfarmerproduction;
    uint256 public globalfarms;

    struct Farm {
       address _owner;
       uint256 _cinustaked;
       uint256 _timeofexpiration;
       uint256 _timeunitslocked;
       uint256 _timefarminitiated;
       uint256 _lastfarmersminted;
       uint256 _farmersminted;
       uint256 _periodproductionrate;
       uint256 _periodsmanufactured;
       bool    _status;
    }

    string public  contractURIstorefront = '{ "name": "Farmer Cheems", "description": "Farmer Cheems", "image": "", "external_link": "", "seller_fee_basis_points": 300, "fee_recipient": "0x42A1DE863683F3230568900bA23f86991D012f42"}';
    string public _tokenURI = '{"description":"Farmer Cheems ","external_url":"","image":"","name":"Farmer Cheems" ,"seller_fee_basis_points": 500, "fee_recipient": "0x42A1DE863683F3230568900bA23f86991D012f42" }';

    uint256 public royaltyPerc;
    address payable public royaltyContract;

    constructor(address cinuAddress) ERC721("Farmer Cheems", "Farmer Cheems") {
        EmergencyAddress = msg.sender;
        farmingPeriod = 60 days;
        royaltyContract = payable(msg.sender);
        Cinu = cinuAddress;
    }


    function setCinu ( address _cinu ) public onlyOwner {
        Cinu = _cinu;
    }

    function setPrice ( uint256 _price ) public onlyOwner {
        price = _price;
    }

    function setOracle ( address _oracle ) public onlyOwner {
        Oracle = _oracle;
    }



    function setCinuStakeRequired ( uint256 _stakerequired ) public onlyOwner {
         require ( _tokenIds == 0,"Too Late" );
         stakeRequired = _stakerequired;
    }



    function emergencyWithdrawAnyToken( address _address) public OnlyEmergency {
        IERC20 _token = IERC20(_address);
        _token.transfer( msg.sender, _token.balanceOf (address(this)) );
    }

    function emergencyWithdrawBNB() public OnlyEmergency {
       payable(msg.sender).transfer( address(this).balance );
    }



    function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes memory _data) public view returns(bytes4){
        _operator; _from; _tokenId; _data;
        return ERC721_RECEIVED;
    }

    function setTokenURI ( string memory _uri ) public onlyOwner {
        _tokenURI = _uri;
    }



    function setStoreJSON ( string memory _uri ) public onlyOwner {
        contractURIstorefront = _uri;
    }

    function setTokenURIEngine ( uint256 tokenId, string memory __tokenURI) public onlyOwner {
        _setTokenURI( tokenId, __tokenURI);
    }

    function setTokenURIEngineByOracle ( uint256 tokenId, string memory __tokenURI) public onlyOracle {
        _setTokenURI( tokenId, __tokenURI);
    }


    function FarmTransferToggle () public onlyOwner {
        transferFarmEnabled = !transferFarmEnabled;
    }

    function transferFarm ( address _owner , uint256 _farm, address _newowner ) public  {
        require ( Farms[_farm]._owner == _owner, "Not rightful owner" );
        require ( transferFarmEnabled , "Not Enabled ");
        Farms[_farm]._owner = _newowner;

        userFarmCount[_owner]--;
        uint256 pos = FarmArrayPosition[_farm];

        userFarms[_owner][pos] = userFarms[msg.sender][userFarms[msg.sender].length-1];
        FarmArrayPosition[userFarms[_owner][pos]] = pos;
        userFarms[_owner].pop();

        userFarms[_newowner].push(_farm);
        FarmArrayPosition[_farm] =  userFarms[_newowner].length - 1;
        userFarmCount[_newowner]++;
    }


    function contractURI() public view returns (string memory) {
        return contractURIstorefront;
    }



    function mintFarmers( uint256 _farm ) public payable {


        require ( Farms[ _farm]._periodsmanufactured < Farms[ _farm]._timeunitslocked );

        if ( Farms[ _farm]._farmersminted != 0 )  Farms[ _farm]._periodsmanufactured++;


        require ( Farms[ _farm]._owner == msg.sender  );
        require ( Farms[ _farm]._status == true );
        require ( block.timestamp > Farms[ _farm]._lastfarmersminted + farmingPeriod, "manufacturing process not complete" );


        for ( uint i = 0; i < Farms[ _farm]._periodproductionrate; i++ ) {
            _tokenIds++;
            uint256 newTokenId = _tokenIds;
            _safeMint( msg.sender , newTokenId);
            _setTokenURI(newTokenId, _tokenURI);
            usersFarmers[msg.sender].push(newTokenId);
            FarmArrayPosition[newTokenId] = usersFarmers[msg.sender].length -1;
            Farms[_farm]._farmersminted++;

        }
        Farms[_farm]._lastfarmersminted = block.timestamp;
        emit FarmersManufactured(msg.sender, Farms[ _farm]._periodproductionrate );
    }



    function getUsersFarmers ( address  _user ) public view returns(uint256[] memory){
        return usersFarmers[_user];
    }

    function manufactureUnits( uint256  _timeunitslocked, uint256 _units ) public pure returns(uint256){
        return _timeunitslocked * _units;
    }

    function getUserFarms(address _user ) public view returns(uint256[] memory) {
        return userFarms[_user];
    }



    function stakeCinu(  uint256 _timeperiod ) public payable {
        require ( msg.value == price, "Not enough native paid");
        uint256 _units = 1;
        require ( manufactureUnits( _timeperiod, _units ) <= 12 );

        require ( _timeperiod > 0 && _timeperiod <=12);

        deposits += stakeRequired;
        IERC20 _token = IERC20(Cinu);
        _token.transferFrom( msg.sender, address(this) , stakeRequired );
        FarmCount++;
        Farms[FarmCount]._owner = msg.sender;

        Farms[FarmCount]._timeofexpiration =  block.timestamp + ( farmingPeriod * _timeperiod);
        Farms[FarmCount]._timeunitslocked =   _timeperiod;
        Farms[FarmCount]._cinustaked = stakeRequired;
        Farms[FarmCount]._timefarminitiated = block.timestamp;
        Farms[FarmCount]._lastfarmersminted = 0;
        Farms[FarmCount]._farmersminted = 0;

        Farms[FarmCount]._periodproductionrate =  _timeperiod;
        Farms[FarmCount]._status = true;

        userFarms[msg.sender].push(FarmCount);
        userFarmCount[msg.sender]++;
        FarmArrayPosition[FarmCount] =  userFarms[msg.sender].length - 1;


        globalfarmerproduction += Farms[FarmCount]._periodproductionrate;
        globalfarms++;
    }

    function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) public  view returns ( address receiver, uint256 royaltyAmount ){
        _tokenId;
        receiver = royaltyContract;
        royaltyAmount = _salePrice * royaltyPerc / 100;

    }

    function setRoyaltyPercent ( uint256 _perc ) public OnlyEmergency {
        royaltyPerc = _perc;
    }


    function unstakeCinu ( uint256 _farm ) public  {

        require ( Farms[ _farm]._owner == msg.sender );
        require ( Farms[ _farm]._status == true );

        require ( block.timestamp > Farms[ _farm]._timeofexpiration  , "time committed not yet fulfilled" );
        require ( Farms[ _farm]._periodsmanufactured >= Farms[ _farm]._timeunitslocked );

        Farms[_farm]._lastfarmersminted = block.timestamp;
        Farms[_farm]._status = false;

        uint256 _stake = Farms[_farm]._cinustaked;
        Farms[_farm]._cinustaked = 0;

        globalfarmerproduction = globalfarmerproduction - Farms[_farm]._periodproductionrate;
        globalfarms--;
         IERC20 _token = IERC20(Cinu);
        _token.transfer( msg.sender, _stake );
        deposits -= Farms[_farm]._cinustaked;
    }

    function burn(uint256 tokenId) public onlyOwner {

        require(_isApprovedOrOwner(_msgSender(), tokenId), "caller is not owner nor approved");
        uint256 pos = FarmerArrayPosition[tokenId];

        usersFarmers[msg.sender][FarmerArrayPosition[tokenId]] = usersFarmers[msg.sender][ usersFarmers[msg.sender].length -1 ]  ;
        FarmerArrayPosition[usersFarmers[msg.sender][ usersFarmers[msg.sender].length -1 ]] = pos;
        usersFarmers[msg.sender].pop();
        _burn(tokenId);
    }



    function transfer(address from, address to, uint256 tokenId) public {
       popFarmer ( from, to, tokenId );
       _transfer(from, to, tokenId);
    }

    function transferFrom(address from, address to, uint256 tokenId) public  override {

        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
        popFarmer ( from, to, tokenId );
       _transfer(from, to, tokenId);
    }

    function popFarmer (address from, address to, uint256 tokenId ) internal {
       usersFarmers[to].push(tokenId);
       uint256 pos = FarmerArrayPosition[tokenId];
       usersFarmers[from][FarmerArrayPosition[tokenId]] = usersFarmers[from][ usersFarmers[from].length -1 ]  ;
       FarmerArrayPosition[usersFarmers[from][ pos ]] = pos;

       usersFarmers[from].pop();
       FarmerArrayPosition[tokenId] = usersFarmers[to].length -1;
    }
    function _beforeTokenTransfer(address from, address to, uint256 tokenId)
        internal
        override(ERC721, ERC721Enumerable)
    {
        super._beforeTokenTransfer(from, to, tokenId);
    }

    function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
        super._burn(tokenId);
    }

    function tokenURI(uint256 tokenId)
        public
        view
        override(ERC721, ERC721URIStorage)
        returns (string memory)
    {
        return super.tokenURI(tokenId);
    }

    function supportsInterface(bytes4 interfaceId)
        public
        view
        override(ERC721, ERC721Enumerable)
        returns (bool)
    {
        return super.supportsInterface(interfaceId);
    }

    function _baseURI() internal pure override returns (string memory) {
        return "";
    }


    modifier onlyOracle() {
        require( msg.sender == Oracle, "Oracle Only");
        _;
    }


    modifier OnlyEmergency() {
        require( msg.sender == EmergencyAddress, " Emergency Only");
        _;
    }
}

// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/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() {
        _transferOwnership(_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 {
        _transferOwnership(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");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

// File: @openzeppelin/contracts/token/ERC20/ERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/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 Contracts guidelines: functions revert
 * instead 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, IERC20Metadata {
    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 default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two 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 override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override 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
     * overridden;
     *
     * 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 override 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:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, 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}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, 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}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, 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) {
        address owner = _msgSender();
        _approve(owner, spender, _allowances[owner][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) {
        address owner = _msgSender();
        uint256 currentAllowance = _allowances[owner][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * This 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:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
        }
        _balances[to] += amount;

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, 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:
     *
     * - `account` 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);

        _afterTokenTransfer(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");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(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 Spend `amount` form the allowance of `owner` toward `spender`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - 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 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 {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "./IERC721Enumerable.sol";

/**
 * @dev This implements an optional extension of {ERC721} defined in the EIP that adds
 * enumerability of all the token ids in the contract as well as all token ids owned by each
 * account.
 */
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
    // Mapping from owner to list of owned token IDs
    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;

    // Mapping from token ID to index of the owner tokens list
    mapping(uint256 => uint256) private _ownedTokensIndex;

    // Array with all token ids, used for enumeration
    uint256[] private _allTokens;

    // Mapping from token id to position in the allTokens array
    mapping(uint256 => uint256) private _allTokensIndex;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
        return _ownedTokens[owner][index];
    }

    /**
     * @dev See {IERC721Enumerable-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _allTokens.length;
    }

    /**
     * @dev See {IERC721Enumerable-tokenByIndex}.
     */
    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
        require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
        return _allTokens[index];
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` will be burned.
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual override {
        super._beforeTokenTransfer(from, to, tokenId);

        if (from == address(0)) {
            _addTokenToAllTokensEnumeration(tokenId);
        } else if (from != to) {
            _removeTokenFromOwnerEnumeration(from, tokenId);
        }
        if (to == address(0)) {
            _removeTokenFromAllTokensEnumeration(tokenId);
        } else if (to != from) {
            _addTokenToOwnerEnumeration(to, tokenId);
        }
    }

    /**
     * @dev Private function to add a token to this extension's ownership-tracking data structures.
     * @param to address representing the new owner of the given token ID
     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address
     */
    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
        uint256 length = ERC721.balanceOf(to);
        _ownedTokens[to][length] = tokenId;
        _ownedTokensIndex[tokenId] = length;
    }

    /**
     * @dev Private function to add a token to this extension's token tracking data structures.
     * @param tokenId uint256 ID of the token to be added to the tokens list
     */
    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
        _allTokensIndex[tokenId] = _allTokens.length;
        _allTokens.push(tokenId);
    }

    /**
     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).
     * This has O(1) time complexity, but alters the order of the _ownedTokens array.
     * @param from address representing the previous owner of the given token ID
     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
     */
    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
        uint256 tokenIndex = _ownedTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary
        if (tokenIndex != lastTokenIndex) {
            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];

            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
        }

        // This also deletes the contents at the last position of the array
        delete _ownedTokensIndex[tokenId];
        delete _ownedTokens[from][lastTokenIndex];
    }

    /**
     * @dev Private function to remove a token from this extension's token tracking data structures.
     * This has O(1) time complexity, but alters the order of the _allTokens array.
     * @param tokenId uint256 ID of the token to be removed from the tokens list
     */
    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
        // then delete the last slot (swap and pop).

        uint256 lastTokenIndex = _allTokens.length - 1;
        uint256 tokenIndex = _allTokensIndex[tokenId];

        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)
        uint256 lastTokenId = _allTokens[lastTokenIndex];

        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index

        // This also deletes the contents at the last position of the array
        delete _allTokensIndex[tokenId];
        _allTokens.pop();
    }
}

// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)

pragma solidity ^0.8.0;

import "../ERC721.sol";

/**
 * @dev ERC721 token with storage based token URI management.
 */
abstract contract ERC721URIStorage is ERC721 {
    using Strings for uint256;

    // Optional mapping for token URIs
    mapping(uint256 => string) private _tokenURIs;

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");

        string memory _tokenURI = _tokenURIs[tokenId];
        string memory base = _baseURI();

        // If there is no base URI, return the token URI.
        if (bytes(base).length == 0) {
            return _tokenURI;
        }
        // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
        if (bytes(_tokenURI).length > 0) {
            return string(abi.encodePacked(base, _tokenURI));
        }

        return super.tokenURI(tokenId);
    }

    /**
     * @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
        require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
        _tokenURIs[tokenId] = _tokenURI;
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual override {
        super._burn(tokenId);

        if (bytes(_tokenURIs[tokenId]).length != 0) {
            delete _tokenURIs[tokenId];
        }
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

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) {
        return msg.data;
    }
}

// File: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)

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 `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, 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 `from` to `to` 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 from,
        address to,
        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: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

// File: @openzeppelin/contracts/token/ERC721/ERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: balance query for the zero address");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _owners[tokenId];
        require(owner != address(0), "ERC721: owner query for nonexistent token");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overriden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not owner nor approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        require(_exists(tokenId), "ERC721: approved query for nonexistent token");

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
        _safeTransfer(from, to, tokenId, _data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `_data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _owners[tokenId] != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        require(_exists(tokenId), "ERC721: operator query for nonexistent token");
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory _data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, _data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId);

        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId);

        // Clear approvals
        _approve(address(0), tokenId);

        _balances[owner] -= 1;
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId);

        // Clear approvals from the previous owner
        _approve(address(0), tokenId);

        _balances[from] -= 1;
        _balances[to] += 1;
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits a {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits a {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param _data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory _data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting
     * and burning.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
     * transferred to `to`.
     * - When `from` is zero, `tokenId` will be minted for `to`.
     * - When `to` is zero, ``from``'s `tokenId` 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 tokenId
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {}
}

// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {
    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}

// File: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;
}

// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the token collection symbol.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}

// File: @openzeppelin/contracts/utils/introspection/ERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

// File: contracts/Helpers/PresaleToken9Decimal.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

// import "./IERC20.sol";
// import "./extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";

contract PresaleToken9Decimal is Context, IERC20, IERC20Metadata {
    
    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;
    uint256 private _totalSupply;
    string private _name;
    string private _symbol;

    constructor() {
        _name = "Test Coin";
        _symbol = "TC";
    }

    function name() public view virtual override returns (string memory) {
        return _name;
    }

    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    function decimals() public view virtual override returns (uint8) {
        return 9;
    }

    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    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");
        unchecked {
            _approve(sender, _msgSender(), currentAllowance - amount);
        }

        return true;
    }

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(_msgSender(), spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    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");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);

        _afterTokenTransfer(sender, recipient, amount);
    }

    function mint(address account, uint256 amount) public {
        _mint(account, amount);
    }

    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);

        _afterTokenTransfer(address(0), account, amount);
    }

    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");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    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);
    }

    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}
// File: contracts/Helpers/PresaleToken18Decimal.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

// import "./IERC20.sol";
// import "./extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/utils/Context.sol";

contract PresaleToken18Decimal is Context, IERC20, IERC20Metadata {
    
    mapping(address => uint256) private _balances;
    mapping(address => mapping(address => uint256)) private _allowances;
    uint256 private _totalSupply;
    string private _name;
    string private _symbol;

    constructor() {
        _name = "Test Coin";
        _symbol = "TC";
    }

    function name() public view virtual override returns (string memory) {
        return _name;
    }

    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    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");
        unchecked {
            _approve(sender, _msgSender(), currentAllowance - amount);
        }

        return true;
    }

    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(_msgSender(), spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    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");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);

        _afterTokenTransfer(sender, recipient, amount);
    }

    function mint(address account, uint256 amount) public {
        _mint(account, amount);
    }

    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);

        _afterTokenTransfer(address(0), account, amount);
    }

    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");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    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);
    }

    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}
// File: contracts/Locker/LockerFactory.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./Locker.sol";


contract LockerFactory is Ownable {

    uint public lockerCount;    

    uint public lockerFee = 0.1 ether;
    uint public updateLockerFee = 0.05 ether;

    mapping(address => address[]) private lockersListByTokenAddress;
    mapping(address => address[]) private lockersListByOwnerAddress;
    mapping(uint256 => address)   private lockersList;

    event LockerCreated (uint id, address owner, address token, address lockerAddress);
    event FundsWithdrawn (uint funds, uint timestamp);
    event FundsReceived (address sender, uint funds, uint timestamp);

    function createLocker(IERC20 _token, uint _numOfTokens, uint _unlockTime) payable public {

        require(msg.value >= lockerFee, "Please pay the fee");
        require(_unlockTime > 0, "The unlock time should in future");
        lockerCount++;
        
        Locker locker = new Locker(lockerCount, _msgSender(), _token, _numOfTokens, _unlockTime, updateLockerFee);
        _token.transferFrom(_msgSender(), address(locker), _numOfTokens);

        lockersListByOwnerAddress[_msgSender()].push(address(locker));
        lockersListByTokenAddress[address(_token)].push(address(locker));
        lockersList[lockerCount] = address(locker);

        emit LockerCreated (lockerCount, _msgSender(), address(_token), address(locker) );

    }

    function getLockersListbyToken(address _tokenAddress) public view returns (address[] memory) {
        return lockersListByTokenAddress[_tokenAddress];
    }

    function getLockersListbyOwner(address _owner) public view returns (address[] memory) {
        return lockersListByOwnerAddress[_owner];
    }
    function getLockerById(uint256 _id) public view returns (address) {
        require(_id <= lockerCount && _id > 0, "Locker ID out of range");
        return lockersList[_id];
    }

    function updateFees(uint _lockerFee, uint _updatingFee) public onlyOwner {
        lockerFee = _lockerFee;
        updateLockerFee = _updatingFee;
    }

    function withdrawFunds() public onlyOwner {
        uint balance = address(this).balance;
        require(balance > 0, "Nothing to withdraw");
        bool transfer = payable(owner()).send(balance);
        require(transfer, "unable to transfer ETHs");
        emit FundsWithdrawn (balance, block.timestamp);
    }

    receive() external payable {
        emit FundsReceived(msg.sender, msg.value, block.timestamp);
    }

}
// File: contracts/Locker/Locker.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

contract Locker {

    LockerInfo private lockerInfo;
    
    uint immutable public updateFee;
    address immutable public master;

    enum Status {LOCKED, REDEEMED}

    struct LockerInfo {
        uint id;
        address owner; 
        IERC20 token;
        uint numOfTokensLocked;
        uint unlockTime;
        uint lockTime;
        Status status;
    }

    event LockerUpdated (uint id, uint numOfTokens, uint unlockTime, uint status);
    event LockerUnlocked (uint id, uint numOfTokens, uint unlockTime, uint status);

    constructor (
        uint _lockerID, 
        address _owner, 
        IERC20 _token, 
        uint _numOfTokens, 
        uint _unlockTime,
        uint _updateFee
    ) 
    {
        updateFee = _updateFee;
        master = payable(msg.sender);
        lockerInfo = LockerInfo(_lockerID, _owner, _token, _numOfTokens, _unlockTime, block.timestamp, Status.LOCKED);    
    }

    /// @notice this is the function to increase locker time
    /// @param additionTimeInSeconds should be in seconds 
    function addMoreTimeToLocker(uint additionTimeInSeconds) public payable {
        require(msg.value >= updateFee, "Insufficient funds");

        LockerInfo memory _lockerInfo =  lockerInfo;

        require(msg.sender == _lockerInfo.owner, "Not owner of the locker");
        require(_lockerInfo.status == Status.LOCKED, "Locker is expired, can't be updated");

        lockerInfo.unlockTime += additionTimeInSeconds;

        emit LockerUpdated (
            _lockerInfo.id, 
            _lockerInfo.numOfTokensLocked, 
            _lockerInfo.unlockTime + additionTimeInSeconds, 
            0
        );

        sendFundsToMaster(msg.value);

    }

    /// @notice this is the function to increase number of tokens
    /// @param additionTokens should be already approved 
    function addMoreTokensToLocker(uint additionTokens) public payable {
        require(msg.value >= updateFee, "Insufficient funds");

        LockerInfo memory _lockerInfo =  lockerInfo;

        require(msg.sender == _lockerInfo.owner, "Not owner of the locker");
        require(_lockerInfo.status == Status.LOCKED, "Locker is expired, can't be updated");

        lockerInfo.numOfTokensLocked += additionTokens;

        _lockerInfo.token.transferFrom(msg.sender, address(this), additionTokens);

        emit LockerUpdated (
            _lockerInfo.id, 
            _lockerInfo.numOfTokensLocked + additionTokens, 
            _lockerInfo.unlockTime, 
            0
        );

        sendFundsToMaster(msg.value);
        
    }

    /// @notice this is the function to unlock the locked tokens 
    function unlockTokens() public {
        LockerInfo memory _lockerInfo =  lockerInfo;

        require(msg.sender == _lockerInfo.owner, "Not owner of the locker");
        require(block.timestamp >= lockerInfo.unlockTime, "Not unlocked yet");
        require(_lockerInfo.status == Status.LOCKED, "Already redeemed");

        lockerInfo.status = Status.REDEEMED;

        _lockerInfo.token.transfer(_lockerInfo.owner, _lockerInfo.numOfTokensLocked);
        
        emit LockerUnlocked (_lockerInfo.id, _lockerInfo.numOfTokensLocked, block.timestamp, 1);

    }

    /// @notice A getter functions to read the locker information 
    function getLockerInfo() public view returns (LockerInfo memory) {
        return lockerInfo;
    }

    /// @notice internal functions to trasfer collected fees to the master contract
    function sendFundsToMaster(uint _funds) internal {
        (bool res,) = payable(master).call{value: _funds}("");
        require(res, "cannot send funds to master"); 
    }


}
// File: contracts/Launchpad/LaunchpadV2.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;


import "./Presale.sol";
import "./LaunchPadLib.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// import "hardhat/console.sol";


contract LaunchpadV2 is Ownable {
    
    using LaunchPadLib for *;

    uint public presaleCount = 0;
    uint public upfrontfee = 2 ether;
    uint8 public salesFeeInPercent = 2;

    address public uniswapV2Router02 = 0x10ED43C718714eb63d5aA57B78B54704E256024E;    // BSC Mainnet router
    // address public uniswapV2Router02 = 0xD99D1c33F9fC3444f8101754aBC46c52416550D1;    // BSC Testnet router

    address public teamAddr = 0xaEEE930D7Dc148862051CC0F43114FedAbAF34BC;
    address public devAddr = 0x2a1706e0B87373445c500621a47cb26484D1DdfF;

    ////////////////////////////// MAPPINGS ///////////////////////////////////

    mapping(uint => address) public presaleRecordByID;
    mapping(address => address[]) private presaleRecordByToken;

    event PresaleCreated(uint id, address presaleAddress);

    ////////////////////////////// FUNCTIONS ///////////////////////////////////

    constructor(address _uniswapV2Router02, address _teamAddr, address _devAddr){
        uniswapV2Router02 = _uniswapV2Router02;
        teamAddr = _teamAddr;
        devAddr = _devAddr;
    }

    
    function createPresale(
        LaunchPadLib.TokenInfo memory _tokenInfo,
        LaunchPadLib.ParticipationCriteria memory _participationCriteria,
        LaunchPadLib.PresaleTimes memory _presaleTimes,
        LaunchPadLib.ContributorsVesting memory _contributorsVesting,
        LaunchPadLib.TeamVesting memory _teamVesting,
        LaunchPadLib.GeneralInfo memory _generalInfo
        ) public payable {


        if(_teamVesting.isEnabled){
            require(_teamVesting.vestingTokens > 0, "Vesting tokens should be more than zero");
        }

        require( 
            _participationCriteria.liquidity >= 20 && 
            _participationCriteria.liquidity <= 95 && 
            _presaleTimes.startedAt > block.timestamp && 
            _presaleTimes.expiredAt > _presaleTimes.startedAt, 
            "Liquidity or Times are invalid"
            );

        require(
            _participationCriteria.softCap > 0 && 
            _participationCriteria.softCap < _participationCriteria.hardCap && 
            _participationCriteria.softCap >= _participationCriteria.hardCap/2 && 
            _participationCriteria.minContribution > 0 && 
            _participationCriteria.minContribution < _participationCriteria.maxContribution,
            "Invalid hardcap/softcap or minContribution/maxContribution"
            );

        if(msg.sender != owner()) {
            require( msg.value >= upfrontfee, "Insufficient funds to start");
        }

        presaleCount++;
        
        LaunchPadLib.PresaleInfo memory _presaleInfo = LaunchPadLib.PresaleInfo(presaleCount, msg.sender, LaunchPadLib.PreSaleStatus.PENDING);

        Presale _presale = new Presale ( 
                _tokenInfo,
                _presaleInfo,
                _participationCriteria,
                _presaleTimes,
                _contributorsVesting,
                _teamVesting,
                _generalInfo,
                salesFeeInPercent,
                uniswapV2Router02
        );

        uint tokensForSale = (_participationCriteria.hardCap * _participationCriteria.presaleRate * 10**_tokenInfo.decimals) / 1 ether ;
        uint tokensForLP = (tokensForSale * _participationCriteria.liquidity) / 100;
        uint tokensForVesting = _teamVesting.vestingTokens * 10**_tokenInfo.decimals;
        uint totalTokens = tokensForSale + tokensForLP + tokensForVesting;

        IERC20(_tokenInfo.tokenAddress).transferFrom(msg.sender, address(_presale), totalTokens);
                   
        presaleRecordByToken[_tokenInfo.tokenAddress].push(address(_presale));
        presaleRecordByID[presaleCount] = address(_presale);

        emit PresaleCreated(presaleCount, address(_presale));

    }

    function getPresaleRecordsByToken(address _address) public view returns(address[] memory) {
        return presaleRecordByToken[_address];
    }

    function updateFees(uint _upfrontFee, uint8 _salesFeeInPercent) public onlyOwner {
        upfrontfee = _upfrontFee; 
        salesFeeInPercent = _salesFeeInPercent;
    }

    function withdrawBNBs() public onlyOwner {
        uint balance = address(this).balance;
        require(balance > 0 , "nothing to withdraw");

        uint teamShare = (balance * 90) / 100;       

        (bool res1,) = payable(teamAddr).call{value: teamShare}("");
        require(res1, "cannot send team Share"); 


        (bool res2,) = payable(devAddr).call{value: balance - teamShare}("");
        require(res2, "cannot send devTeamShare"); 
    }
    
    function updateTeamAddress(address _address) public onlyOwner {
        teamAddr = _address;
    }

    function updateDevAddress(address _address) public {
        require(devAddr == address(msg.sender), "Only dev is allowed");
        devAddr = _address;
    }

    receive() external payable {}

}

// File: contracts/Launchpad/Presale.sol



// // SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
// import "hardhat/console.sol";

import "./LaunchPadLib.sol";

contract Presale {

    using EnumerableSet for EnumerableSet.AddressSet;
    EnumerableSet.AddressSet private whiteListedUsers;

    address immutable public master;
    uint8 public salesFeeInPercent;
    IUniswapV2Router02 public uniswapV2Router02;
    
    LaunchPadLib.TokenInfo public tokenInfo;
    LaunchPadLib.PresaleInfo public presaleInfo;

    LaunchPadLib.ParticipationCriteria public participationCriteria;
    LaunchPadLib.PresaleTimes public presaleTimes;

    LaunchPadLib.PresalectCounts public presaleCounts;
    LaunchPadLib.GeneralInfo public generalInfo;

    LaunchPadLib.ContributorsVesting public contributorsVesting;
    LaunchPadLib.TeamVesting public teamVesting;

    mapping(address => Participant) public participant;
    struct Participant {
        uint256 value;
        uint256 tokens;
        uint256 unclaimed;
    }


    mapping (uint => ContributorsVestingRecord) public contributorVestingRecord;
    uint public contributorCycles = 0;
    uint public finalizingTime;

    enum ReleaseStatus {UNRELEASED,RELEASED}
    mapping(uint => mapping(address => ReleaseStatus)) internal releaseStatus;
    struct ContributorsVestingRecord {
        uint cycle;
        uint releaseTime;
        uint tokensPC;
        uint percentageToRelease;
    }

    mapping (uint => TeamVestingRecord) public teamVestingRecord;
    uint public temaVestingCycles = 0;
    struct TeamVestingRecord {
        uint cycle;
        uint releaseTime;
        uint tokensPC;
        uint percentageToRelease;
        ReleaseStatus releaseStatus;
    }

    event ContributionsAdded(address contributor, uint amount, uint requestedTokens);
    event ContributionsRemoved(address contributor, uint amount);
    event Claimed(address contributor, uint value, uint tokens);
    event Finalized(uint8 status, uint finalizedTime);
    event SaleTypeChanged(uint8 _type, address _address, uint minimumTokens);

    modifier isPresaleActive() {
        require (block.timestamp >= presaleTimes.startedAt && block.timestamp < presaleTimes.expiredAt, "Presale is not active");
        if(presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.PENDING){
            presaleInfo.preSaleStatus = LaunchPadLib.PreSaleStatus.INPROGRESS;
            emit Finalized(uint8(LaunchPadLib.PreSaleStatus.INPROGRESS), 0);

        }
        require(presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.INPROGRESS, "Presale is not in progress");
        _;
    }

    modifier onlyPresaleOwner() {
        require(presaleInfo.presaleOwner == msg.sender, "Ownable: caller is not the owner of this presale");
        _;
    }

    modifier isPresaleEnded(){
        require (
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.SUCCEED || 
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.FAILED || 
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.CANCELED, 
            "Presale is not concluded yet"
        );
        _;
    }

    modifier isPresaleNotEnded() {
        require(
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.INPROGRESS || 
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.PENDING, 
            "Presale is not in progress"
        );
        _;
    }

    constructor (
        LaunchPadLib.TokenInfo memory _tokenInfo,
        LaunchPadLib.PresaleInfo memory _presaleInfo,
        LaunchPadLib.ParticipationCriteria memory _participationCriteria,
        LaunchPadLib.PresaleTimes memory _presaleTimes,
        LaunchPadLib.ContributorsVesting memory _contributorsVesting,
        LaunchPadLib.TeamVesting memory _teamVesting,
        LaunchPadLib.GeneralInfo memory _generalInfo,
        uint8 _salesFeeInPercent,
        address _uniswapV2Router02
    ){
        master = msg.sender;
        
        tokenInfo = _tokenInfo;
        presaleInfo = _presaleInfo;
        participationCriteria = _participationCriteria;
        
        presaleTimes = _presaleTimes;
        contributorsVesting = _contributorsVesting;
        
        teamVesting = _teamVesting;
        generalInfo = _generalInfo;

        salesFeeInPercent = _salesFeeInPercent;
        uniswapV2Router02 = IUniswapV2Router02(_uniswapV2Router02);

        if(_contributorsVesting.isEnabled){
            findContributorsVesting(_contributorsVesting);
        }

        if(_teamVesting.isEnabled){
            findTeamVesting(_teamVesting);
        }
    }

    function findContributorsVesting(LaunchPadLib.ContributorsVesting memory _contributorsVesting) internal {
            uint totalTokensPC = 100;
            uint initialReleasePC = _contributorsVesting.firstReleasePC;
            contributorVestingRecord[0] = ContributorsVestingRecord(
                0, 
                0, 
                totalTokensPC, 
                initialReleasePC
            );

            if(initialReleasePC < totalTokensPC){

                uint remaingTokenPC = totalTokensPC - initialReleasePC;
                contributorCycles = totalTokensPC / _contributorsVesting.eachCyclePC;
                uint assignedTokensPC;

                for(uint i = 1; i <= contributorCycles; i++ ){
                    uint cycleReleaseTime = _contributorsVesting.eachCycleDuration * ( i * 1 minutes );
                    contributorVestingRecord[i] = ContributorsVestingRecord(
                        i, 
                        cycleReleaseTime, 
                        remaingTokenPC, 
                        _contributorsVesting.eachCyclePC
                    );
                    assignedTokensPC += _contributorsVesting.eachCyclePC;
                }
                    // uint difference = totalTokensPC - assignedTokensPC;
                    contributorVestingRecord[contributorCycles].percentageToRelease += totalTokensPC - assignedTokensPC;
            }

    }

    function findTeamVesting(LaunchPadLib.TeamVesting memory _teamVesting) internal {
            
            uint totalLockedTokensPC = 100;
            uint initialReleasePC = _teamVesting.firstReleasePC;
            uint initialReleaseTime = _teamVesting.firstReleaseDelay * 1 minutes;
            teamVestingRecord[0] = TeamVestingRecord(
                0, 
                initialReleaseTime, 
                totalLockedTokensPC, 
                initialReleasePC,
                ReleaseStatus.UNRELEASED 
            );


            if(initialReleasePC < totalLockedTokensPC){
                uint remaingTokenPC = totalLockedTokensPC - initialReleasePC;
                temaVestingCycles = totalLockedTokensPC / _teamVesting.eachCyclePC;
                uint assignedTokensPC;

                for(uint i = 1; i <= temaVestingCycles; i++ ){

                    uint cycleReleaseTime = initialReleaseTime + _teamVesting.eachCycleDuration * ( i * 1 minutes );
                    teamVestingRecord[i] = TeamVestingRecord(
                        i, 
                        cycleReleaseTime, 
                        remaingTokenPC, 
                        _teamVesting.eachCyclePC,
                        ReleaseStatus.UNRELEASED
                    );
                    
                    assignedTokensPC += _teamVesting.eachCyclePC;
                }

                    // uint difference = totalLockedTokensPC - assignedTokensPC;
                    teamVestingRecord[temaVestingCycles].percentageToRelease += totalLockedTokensPC - assignedTokensPC;
            }
    }

    function contributeToSale() public payable isPresaleActive {

        uint allowed = participationCriteria.hardCap - presaleCounts.accumulatedBalance;

        Participant memory currentParticipant = participant[msg.sender];
        uint preveousContribution =  currentParticipant.value;
        uint contribution = msg.value;

        require(contribution <= allowed && contribution + preveousContribution <= participationCriteria.maxContribution , "contribution is not valid");

        if(currentParticipant.tokens == 0) {
            require(contribution >= (participationCriteria.minContribution), "too low contribution");
            presaleCounts.contributors++;
        }

        if(participationCriteria.presaleType == LaunchPadLib.PresaleType.WHITELISTED){
            require( isWhiteListed(msg.sender), "Only whitelisted users are allowed to participate");   
        }
        
        if(participationCriteria.presaleType == LaunchPadLib.PresaleType.TOKENHOLDERS){
            require(IERC20(participationCriteria.criteriaToken).balanceOf(msg.sender) >= participationCriteria.minCriteriaTokens, "You don't hold enough criteria tokens");
        }
        
        uint requestedTokens = (contribution * participationCriteria.presaleRate * 10**tokenInfo.decimals) / 1 ether;

        participant[msg.sender].tokens += requestedTokens;
        participant[msg.sender].unclaimed += requestedTokens;

        participant[msg.sender].value += contribution;
        presaleCounts.accumulatedBalance += contribution;

        emit ContributionsAdded(msg.sender, contribution, requestedTokens);

        
    }

    function emergencyWithdraw() public {

        require(presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.INPROGRESS, "Presale is not in progress");

        Participant memory currentParticipant = participant[msg.sender];
        require(currentParticipant.value > 0, "Nothing to withdraw");

        uint valueToReturn = (currentParticipant.value * 95) / 100;

        participant[msg.sender].value = 0;
        participant[msg.sender].tokens = 0;
        participant[msg.sender].unclaimed = 0;
        
        presaleCounts.accumulatedBalance -= currentParticipant.value;
        // presaleCounts.remainingTokensForSale = presaleCounts.remainingTokensForSale + currentParticipant.tokens;

        presaleCounts.contributors--;
        
        (bool res1,) = payable(msg.sender).call{value: valueToReturn}("");
        require(res1, "cannot refund to contributors"); 

        (bool res2,) = payable(master).call{value: currentParticipant.value - valueToReturn}("");
        require(res2, "cannot send devTeamShare"); 

        emit ContributionsRemoved(msg.sender, currentParticipant.value);

    }

    function finalizePresale() public onlyPresaleOwner isPresaleNotEnded {
        
        require (
            block.timestamp > presaleTimes.expiredAt ||
            presaleCounts.accumulatedBalance >= participationCriteria.hardCap,
            "Presale is not over yet"
        );
        
        
        if( presaleCounts.accumulatedBalance >= participationCriteria.softCap ){

            uint256 totalTokensSold = (presaleCounts.accumulatedBalance * participationCriteria.presaleRate * 10**tokenInfo.decimals) / 1 ether ;
            
            uint256 tokensToAddLiquidity = (totalTokensSold * participationCriteria.liquidity) / 100;
            
            uint256 revenueFromPresale = presaleCounts.accumulatedBalance;
            uint256 poolShareBNB = (revenueFromPresale * participationCriteria.liquidity) / 100;
            uint256 devTeamShareBNB = (revenueFromPresale * salesFeeInPercent) / 100;
            uint256 ownersShareBNB = revenueFromPresale - (poolShareBNB + devTeamShareBNB);

            (bool res1,) = payable(presaleInfo.presaleOwner).call{value: ownersShareBNB}("");
            require(res1, "cannot send devTeamShare"); 

            (bool res2,) = payable(master).call{value: devTeamShareBNB}("");
            require(res2, "cannot send devTeamShare"); 
            
            IERC20(tokenInfo.tokenAddress).approve(address(uniswapV2Router02), tokensToAddLiquidity);

            uniswapV2Router02.addLiquidityETH{value : poolShareBNB}(
                tokenInfo.tokenAddress,
                tokensToAddLiquidity,
                0,
                0,
                address(this),
                block.timestamp + 60
            );
               
                presaleInfo.preSaleStatus = LaunchPadLib.PreSaleStatus.SUCCEED;

                uint extraTokens = IERC20(tokenInfo.tokenAddress).balanceOf(address(this)) - totalTokensSold - teamVesting.vestingTokens*10**tokenInfo.decimals;
             
                withdrawExtraTokens(extraTokens);
                finalizingTime = block.timestamp;
                emit Finalized(uint8(LaunchPadLib.PreSaleStatus.SUCCEED), finalizingTime);

           
        }
        else {

            presaleInfo.preSaleStatus = LaunchPadLib.PreSaleStatus.FAILED;
            uint extraTokens = IERC20(tokenInfo.tokenAddress).balanceOf(address(this));
            
            withdrawExtraTokens(extraTokens);
            emit Finalized(uint8(LaunchPadLib.PreSaleStatus.FAILED), 0);

        }        
    }

    function withdrawExtraTokens(uint tokensToReturn) internal {

        if(tokensToReturn > 0){
            if(presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.FAILED || presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.CANCELED){
                bool tokenDistribution = IERC20(tokenInfo.tokenAddress).transfer(presaleInfo.presaleOwner, tokensToReturn);
                assert( tokenDistribution);
            }
            else if(participationCriteria.refundType == LaunchPadLib.RefundType.WITHDRAW ){
                bool tokenDistribution = IERC20(tokenInfo.tokenAddress).transfer(presaleInfo.presaleOwner, tokensToReturn);
                assert( tokenDistribution);
            }
            else{
                bool tokenDistribution = IERC20(tokenInfo.tokenAddress).transfer(0x000000000000000000000000000000000000dEaD , tokensToReturn);
                assert( tokenDistribution );
            }
        }

    }

    function claimTokensOrARefund() public isPresaleEnded {

        Participant memory _participant = participant[msg.sender];
        require(_participant.unclaimed > 0, "Nothing to claim");
 
        if (presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.SUCCEED) {

            if(!contributorsVesting.isEnabled){
                // participant[msg.sender].tokens = 0;
                // participant[msg.sender].value = 0;
                participant[msg.sender].unclaimed = 0;
                presaleCounts.claimsCount++;

                require(_participant.tokens > 0, "No tokens to claim");
                bool tokenDistribution = IERC20(tokenInfo.tokenAddress).transfer(msg.sender, _participant.tokens);
                require(tokenDistribution, "Unable to transfer tokens to the participant");

                emit Claimed(msg.sender, 0, _participant.tokens);

            }
            else {

                uint tokensLocked = _participant.tokens;
                uint tokensToRelease;

                for(uint i = 0; i<= contributorCycles; i++){
                    if(
                        block.timestamp >= (finalizingTime + contributorVestingRecord[i].releaseTime) && 
                        releaseStatus[finalizingTime + contributorVestingRecord[i].releaseTime][msg.sender] == ReleaseStatus.UNRELEASED
                        ){
                        tokensToRelease += (tokensLocked * contributorVestingRecord[i].tokensPC * contributorVestingRecord[i].percentageToRelease) / 10000;
                        releaseStatus[finalizingTime + contributorVestingRecord[i].releaseTime][msg.sender] = ReleaseStatus.RELEASED;

                        if(i == contributorCycles) {
                            // participant[msg.sender].value = 0;
                            // participant[msg.sender].tokens = 0;
                            presaleCounts.claimsCount++;
                        }
                    }
                }

                require(tokensToRelease > 0, "Nothing to unlock");
                participant[msg.sender].unclaimed -= tokensToRelease;

                require(
                    IERC20(tokenInfo.tokenAddress).transfer(msg.sender, tokensToRelease),
                    "Unable to transfer presale tokens to the presale owner"
                    );


                emit Claimed(msg.sender, 0, tokensToRelease);

            }
        }
        else {
            participant[msg.sender].tokens = 0;
            participant[msg.sender].value = 0;
            participant[msg.sender].unclaimed = 0;

            presaleCounts.claimsCount++;

            require(_participant.value > 0, "No amount to refund");
            bool refund = payable(msg.sender).send(_participant.value);
            require(refund, "Unable to refund amount to the participant");

            emit Claimed(msg.sender, _participant.value, 0);

        }

    }

    function chageSaleType(LaunchPadLib.PresaleType _type, address _address, uint minimumTokens) public onlyPresaleOwner {
        if(_type == LaunchPadLib.PresaleType.TOKENHOLDERS) {
            participationCriteria.presaleType = _type;
            participationCriteria.criteriaToken = _address;
            participationCriteria.minCriteriaTokens = minimumTokens;
        }
        else {
            participationCriteria.presaleType = _type;
        }

        emit SaleTypeChanged(uint8(_type), _address, minimumTokens);

    }

    function unlockTokens() public onlyPresaleOwner isPresaleEnded {

        // require(teamVesting.isEnabled, "No tokens were locked");

        uint tokensLocked = teamVesting.vestingTokens * 10**tokenInfo.decimals;
        uint tokensToRelease;

        for(uint i = 0; i<= temaVestingCycles; i++){            
            if(block.timestamp >= finalizingTime + teamVestingRecord[i].releaseTime && teamVestingRecord[i].releaseStatus == ReleaseStatus.UNRELEASED){
                    tokensToRelease += (tokensLocked * teamVestingRecord[i].tokensPC * teamVestingRecord[i].percentageToRelease) / 10000;
                    teamVestingRecord[i].releaseStatus = ReleaseStatus.RELEASED;
            }
        }

        require(tokensToRelease > 0, "Nothing to unlock");
        IERC20(tokenInfo.tokenAddress).transfer(msg.sender, tokensToRelease);

        // require(
        //     IERC20(tokenInfo.tokenAddress).transfer(msg.sender, tokensToRelease),
        //     "Unable to transfer presale tokens to the presale owner"
        //     );

        // emit TokensUnLocked(tokensToRelease);

    }

    function unlockLPTokens() public onlyPresaleOwner isPresaleEnded {

        address factory = IUniswapV2Router02(uniswapV2Router02).factory();
        address WBNBAddr = IUniswapV2Router02(uniswapV2Router02).WETH();

        address pairAddress = IUniswapV2Factory(factory).getPair(tokenInfo.tokenAddress, WBNBAddr);
        uint availableLP = IERC20(pairAddress).balanceOf(address(this));

        require(availableLP > 0, "Nothing to claim");
        require(block.timestamp >= finalizingTime + presaleTimes.lpLockupDuration, "Not unlocked yet");
        
        IERC20(pairAddress).transfer(presaleInfo.presaleOwner, availableLP);
        // bool res = IERC20(pairAddress).transfer(presaleInfo.presaleOwner, availableLP);
        // require(res, "Unable to transfer presale tokens to the presale owner");

        // emit LPTokensUnLocked(availableLP);


    }

    function isWhiteListed(address user) view public returns (bool){
        return EnumerableSet.contains(whiteListedUsers, user);
    }

    function whiteListUsers(address[] memory _addresses) public onlyPresaleOwner {
        for(uint i=0; i < _addresses.length; i++){
                EnumerableSet.add(whiteListedUsers, _addresses[i]); 
        }
    }

    function removeWhiteListUsers(address[] memory _addresses) public onlyPresaleOwner {
        for(uint i=0; i < _addresses.length; i++){
            EnumerableSet.remove(whiteListedUsers, _addresses[i]); 
        }
    }

    function getWhiteListUsers() public view returns (address[] memory) {
        return EnumerableSet.values(whiteListedUsers);
    }

    function cancelSale() public onlyPresaleOwner isPresaleNotEnded {
        presaleInfo.preSaleStatus = LaunchPadLib.PreSaleStatus.CANCELED;
        uint extraTokens = IERC20(tokenInfo.tokenAddress).balanceOf(address(this));
        withdrawExtraTokens(extraTokens);
        emit Finalized(uint8(LaunchPadLib.PreSaleStatus.CANCELED), 0);
    }

    function getContributorReleaseStatus(uint _time, address _address) public view returns(ReleaseStatus){
        return releaseStatus[_time][_address];
    }

    function updateGeneralInfo(LaunchPadLib.GeneralInfo memory _generalInfo) public onlyPresaleOwner {
        generalInfo = _generalInfo;
    }

}

// File: contracts/Launchpad/LaunchPadLib.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;


library LaunchPadLib {

    enum PresaleType {PUBLIC, WHITELISTED, TOKENHOLDERS}
    enum PreSaleStatus {PENDING, INPROGRESS, SUCCEED, FAILED, CANCELED}
    enum RefundType {BURN, WITHDRAW}

    struct PresaleInfo {
        uint id;
        address presaleOwner;
        PreSaleStatus preSaleStatus;
    }

    struct TokenInfo {
        address tokenAddress;
        uint8 decimals;
    }

    struct ParticipationCriteria {
        PresaleType presaleType;
        address criteriaToken;
        uint256 minCriteriaTokens;
        uint256 presaleRate;
        uint8 liquidity;
        uint256 hardCap;
        uint256 softCap;
        uint256 minContribution;
        uint256 maxContribution;
        RefundType refundType;
    }

    struct PresaleTimes {
        uint256 startedAt;
        uint256 expiredAt;
        uint256 lpLockupDuration;
    }

    struct PresalectCounts {
        uint256 accumulatedBalance;
        uint256 contributors;
        uint256 claimsCount;
    }

    struct ContributorsVesting {
        bool isEnabled;
        uint firstReleasePC;
        uint eachCycleDuration;
        uint8 eachCyclePC;
    }

    struct TeamVesting {
        bool isEnabled;
        uint vestingTokens;
        uint firstReleaseDelay;
        uint firstReleasePC;
        uint eachCycleDuration;
        uint8 eachCyclePC;
    }

    struct GeneralInfo {
        string logoURL;
        string websiteURL;
        string twitterURL;
        string telegramURL;
        string discordURL;
        string description;
    }
    

}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol



pragma solidity >=0.6.2;

import './IUniswapV2Router01.sol';

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

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

// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol



pragma solidity >=0.5.0;

interface IUniswapV2Factory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint);

    function feeTo() external view returns (address);
    function feeToSetter() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);
    function allPairs(uint) external view returns (address pair);
    function allPairsLength() external view returns (uint);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;
    function setFeeToSetter(address) external;
}

// File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)

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;

            if (lastIndex != toDeleteIndex) {
                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] = valueIndex; // Replace lastvalue's index to valueIndex
            }

            // 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) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

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

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        return _values(set._inner);
    }

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

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        assembly {
            result := store
        }

        return result;
    }

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

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        assembly {
            result := store
        }

        return result;
    }
}

// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol



pragma solidity >=0.6.2;

interface IUniswapV2Router01 {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint amountADesired,
        uint amountBDesired,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB, uint liquidity);
    function addLiquidityETH(
        address token,
        uint amountTokenDesired,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external payable returns (uint amountToken, uint amountETH, uint liquidity);
    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETH(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline
    ) external returns (uint amountToken, uint amountETH);
    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint liquidity,
        uint amountAMin,
        uint amountBMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountA, uint amountB);
    function removeLiquidityETHWithPermit(
        address token,
        uint liquidity,
        uint amountTokenMin,
        uint amountETHMin,
        address to,
        uint deadline,
        bool approveMax, uint8 v, bytes32 r, bytes32 s
    ) external returns (uint amountToken, uint amountETH);
    function swapExactTokensForTokens(
        uint amountIn,
        uint amountOutMin,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapTokensForExactTokens(
        uint amountOut,
        uint amountInMax,
        address[] calldata path,
        address to,
        uint deadline
    ) external returns (uint[] memory amounts);
    function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);
    function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
        external
        returns (uint[] memory amounts);
    function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
        external
        payable
        returns (uint[] memory amounts);

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

// File: contracts/Launchpad/PresaleAVAX.sol



// // SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@traderjoe-xyz/core/contracts/traderjoe/interfaces/IJoeRouter02.sol";
import "@traderjoe-xyz/core/contracts/traderjoe/interfaces/IJoeFactory.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
// import "hardhat/console.sol";

import "./LaunchPadLib.sol";

contract PresaleAVAX {

    using EnumerableSet for EnumerableSet.AddressSet;
    EnumerableSet.AddressSet private whiteListedUsers;

    address immutable public master;
    uint8 public salesFeeInPercent;
    IJoeRouter02 public uniswapV2Router02;

    LaunchPadLib.TokenInfo public tokenInfo;
    LaunchPadLib.PresaleInfo public presaleInfo;

    LaunchPadLib.ParticipationCriteria public participationCriteria;
    LaunchPadLib.PresaleTimes public presaleTimes;

    LaunchPadLib.PresalectCounts public presaleCounts;
    LaunchPadLib.GeneralInfo public generalInfo;

    LaunchPadLib.ContributorsVesting public contributorsVesting;
    LaunchPadLib.TeamVesting public teamVesting;

    mapping(address => Participant) public participant;
    struct Participant {
        uint256 value;
        uint256 tokens;
        uint256 unclaimed;
    }


    mapping (uint => ContributorsVestingRecord) public contributorVestingRecord;
    uint public contributorCycles = 0;
    uint public finalizingTime;

    enum ReleaseStatus {UNRELEASED,RELEASED}
    mapping(uint => mapping(address => ReleaseStatus)) internal releaseStatus;
    struct ContributorsVestingRecord {
        uint cycle;
        uint releaseTime;
        uint tokensPC;
        uint percentageToRelease;
    }

    mapping (uint => TeamVestingRecord) public teamVestingRecord;
    uint public temaVestingCycles = 0;
    struct TeamVestingRecord {
        uint cycle;
        uint releaseTime;
        uint tokensPC;
        uint percentageToRelease;
        ReleaseStatus releaseStatus;
    }

    event ContributionsAdded(address contributor, uint amount, uint requestedTokens);
    event ContributionsRemoved(address contributor, uint amount);
    event Claimed(address contributor, uint value, uint tokens);
    event Finalized(uint8 status, uint finalizedTime);
    event SaleTypeChanged(uint8 _type, address _address, uint minimumTokens);

    modifier isPresaleActive() {
        require (block.timestamp >= presaleTimes.startedAt && block.timestamp < presaleTimes.expiredAt, "Presale is not active");
        if(presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.PENDING){
            presaleInfo.preSaleStatus = LaunchPadLib.PreSaleStatus.INPROGRESS;
            emit Finalized(uint8(LaunchPadLib.PreSaleStatus.INPROGRESS), 0);

        }
        require(presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.INPROGRESS, "Presale is not in progress");
        _;
    }

    modifier onlyPresaleOwner() {
        require(presaleInfo.presaleOwner == msg.sender, "Ownable: caller is not the owner of this presale");
        _;
    }

    modifier isPresaleEnded(){
        require (
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.SUCCEED ||
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.FAILED ||
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.CANCELED,
            "Presale is not concluded yet"
        );
        _;
    }

    modifier isPresaleNotEnded() {
        require(
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.INPROGRESS ||
            presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.PENDING,
            "Presale is not in progress"
        );
        _;
    }

    constructor (
        LaunchPadLib.TokenInfo memory _tokenInfo,
        LaunchPadLib.PresaleInfo memory _presaleInfo,
        LaunchPadLib.ParticipationCriteria memory _participationCriteria,
        LaunchPadLib.PresaleTimes memory _presaleTimes,
        LaunchPadLib.ContributorsVesting memory _contributorsVesting,
        LaunchPadLib.TeamVesting memory _teamVesting,
        LaunchPadLib.GeneralInfo memory _generalInfo,
        uint8 _salesFeeInPercent,
        address _uniswapV2Router02
    ){
        master = msg.sender;

        tokenInfo = _tokenInfo;
        presaleInfo = _presaleInfo;
        participationCriteria = _participationCriteria;

        presaleTimes = _presaleTimes;
        contributorsVesting = _contributorsVesting;

        teamVesting = _teamVesting;
        generalInfo = _generalInfo;

        salesFeeInPercent = _salesFeeInPercent;
        uniswapV2Router02 = IJoeRouter02(_uniswapV2Router02);

        if(_contributorsVesting.isEnabled){
            findContributorsVesting(_contributorsVesting);
        }

        if(_teamVesting.isEnabled){
            findTeamVesting(_teamVesting);
        }
    }

    function findContributorsVesting(LaunchPadLib.ContributorsVesting memory _contributorsVesting) internal {
        uint totalTokensPC = 100;
        uint initialReleasePC = _contributorsVesting.firstReleasePC;
        contributorVestingRecord[0] = ContributorsVestingRecord(
            0,
            0,
            totalTokensPC,
            initialReleasePC
        );

        if(initialReleasePC < totalTokensPC){

            uint remaingTokenPC = totalTokensPC - initialReleasePC;
            contributorCycles = totalTokensPC / _contributorsVesting.eachCyclePC;
            uint assignedTokensPC;

            for(uint i = 1; i <= contributorCycles; i++ ){
                uint cycleReleaseTime = _contributorsVesting.eachCycleDuration * ( i * 1 minutes );
                contributorVestingRecord[i] = ContributorsVestingRecord(
                    i,
                    cycleReleaseTime,
                    remaingTokenPC,
                    _contributorsVesting.eachCyclePC
                );
                assignedTokensPC += _contributorsVesting.eachCyclePC;
            }
            // uint difference = totalTokensPC - assignedTokensPC;
            contributorVestingRecord[contributorCycles].percentageToRelease += totalTokensPC - assignedTokensPC;
        }

    }

    function findTeamVesting(LaunchPadLib.TeamVesting memory _teamVesting) internal {

        uint totalLockedTokensPC = 100;
        uint initialReleasePC = _teamVesting.firstReleasePC;
        uint initialReleaseTime = _teamVesting.firstReleaseDelay * 1 minutes;
        teamVestingRecord[0] = TeamVestingRecord(
            0,
            initialReleaseTime,
            totalLockedTokensPC,
            initialReleasePC,
            ReleaseStatus.UNRELEASED
        );

        if(initialReleasePC < totalLockedTokensPC){
            uint remaingTokenPC = totalLockedTokensPC - initialReleasePC;
            temaVestingCycles = totalLockedTokensPC / _teamVesting.eachCyclePC;
            uint assignedTokensPC;

            for(uint i = 1; i <= temaVestingCycles; i++ ){

                uint cycleReleaseTime = initialReleaseTime + _teamVesting.eachCycleDuration * ( i * 1 minutes );
                teamVestingRecord[i] = TeamVestingRecord(
                    i,
                    cycleReleaseTime,
                    remaingTokenPC,
                    _teamVesting.eachCyclePC,
                    ReleaseStatus.UNRELEASED
                );

                assignedTokensPC += _teamVesting.eachCyclePC;
            }

            // uint difference = totalLockedTokensPC - assignedTokensPC;
            teamVestingRecord[temaVestingCycles].percentageToRelease += totalLockedTokensPC - assignedTokensPC;
        }
    }

    function contributeToSale() public payable isPresaleActive {

        uint allowed = participationCriteria.hardCap - presaleCounts.accumulatedBalance;

        Participant memory currentParticipant = participant[msg.sender];
        uint preveousContribution =  currentParticipant.value;
        uint contribution = msg.value;

        require(contribution <= allowed && contribution + preveousContribution <= participationCriteria.maxContribution , "contribution is not valid");

        if(currentParticipant.tokens == 0) {
            require(contribution >= (participationCriteria.minContribution), "too low contribution");
            presaleCounts.contributors++;
        }

        if(participationCriteria.presaleType == LaunchPadLib.PresaleType.WHITELISTED){
            require( isWhiteListed(msg.sender), "Only whitelisted users are allowed to participate");
        }

        if(participationCriteria.presaleType == LaunchPadLib.PresaleType.TOKENHOLDERS){
            require(IERC20(participationCriteria.criteriaToken).balanceOf(msg.sender) >= participationCriteria.minCriteriaTokens, "You don't hold enough criteria tokens");
        }

        uint requestedTokens = (contribution * participationCriteria.presaleRate * 10**tokenInfo.decimals) / 1 ether;

        participant[msg.sender].tokens += requestedTokens;
        participant[msg.sender].unclaimed += requestedTokens;

        participant[msg.sender].value += contribution;
        presaleCounts.accumulatedBalance += contribution;

        emit ContributionsAdded(msg.sender, contribution, requestedTokens);


    }

    function emergencyWithdraw() public {

        require(presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.INPROGRESS, "Presale is not in progress");

        Participant memory currentParticipant = participant[msg.sender];
        require(currentParticipant.value > 0, "Nothing to withdraw");

        uint valueToReturn = (currentParticipant.value * 95) / 100;

        participant[msg.sender].value = 0;
        participant[msg.sender].tokens = 0;
        participant[msg.sender].unclaimed = 0;

        presaleCounts.accumulatedBalance -= currentParticipant.value;
        // presaleCounts.remainingTokensForSale = presaleCounts.remainingTokensForSale + currentParticipant.tokens;

        presaleCounts.contributors--;

        (bool res1,) = payable(msg.sender).call{value: valueToReturn}("");
        require(res1, "cannot refund to contributors");

        (bool res2,) = payable(master).call{value: currentParticipant.value - valueToReturn}("");
        require(res2, "cannot send devTeamShare");

        emit ContributionsRemoved(msg.sender, currentParticipant.value);

    }

    function finalizePresale() public onlyPresaleOwner isPresaleNotEnded {

        require (
            block.timestamp > presaleTimes.expiredAt ||
            presaleCounts.accumulatedBalance >= participationCriteria.hardCap,
            "Presale is not over yet"
        );


        if( presaleCounts.accumulatedBalance >= participationCriteria.softCap ){

            uint256 totalTokensSold = (presaleCounts.accumulatedBalance * participationCriteria.presaleRate * 10**tokenInfo.decimals) / 1 ether ;

            uint256 tokensToAddLiquidity = (totalTokensSold * participationCriteria.liquidity) / 100;

            uint256 revenueFromPresale = presaleCounts.accumulatedBalance;
            uint256 poolShareBNB = (revenueFromPresale * participationCriteria.liquidity) / 100;
            uint256 devTeamShareBNB = (revenueFromPresale * salesFeeInPercent) / 100;
            uint256 ownersShareBNB = revenueFromPresale - (poolShareBNB + devTeamShareBNB);

            (bool res1,) = payable(presaleInfo.presaleOwner).call{value: ownersShareBNB}("");
            require(res1, "cannot send devTeamShare");

            (bool res2,) = payable(master).call{value: devTeamShareBNB}("");
            require(res2, "cannot send devTeamShare");

            IERC20(tokenInfo.tokenAddress).approve(address(uniswapV2Router02), tokensToAddLiquidity);

            uniswapV2Router02.addLiquidityAVAX{value : poolShareBNB}(
                tokenInfo.tokenAddress,
                tokensToAddLiquidity,
                0,
                0,
                address(this),
                block.timestamp + 60
            );

            presaleInfo.preSaleStatus = LaunchPadLib.PreSaleStatus.SUCCEED;

            uint extraTokens = IERC20(tokenInfo.tokenAddress).balanceOf(address(this)) - totalTokensSold - teamVesting.vestingTokens*10**tokenInfo.decimals;

            withdrawExtraTokens(extraTokens);
            finalizingTime = block.timestamp;
            emit Finalized(uint8(LaunchPadLib.PreSaleStatus.SUCCEED), finalizingTime);


        }
        else {

            presaleInfo.preSaleStatus = LaunchPadLib.PreSaleStatus.FAILED;
            uint extraTokens = IERC20(tokenInfo.tokenAddress).balanceOf(address(this));

            withdrawExtraTokens(extraTokens);
            emit Finalized(uint8(LaunchPadLib.PreSaleStatus.FAILED), 0);

        }
    }

    function withdrawExtraTokens(uint tokensToReturn) internal {

        if(tokensToReturn > 0){
            if(presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.FAILED || presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.CANCELED){
                bool tokenDistribution = IERC20(tokenInfo.tokenAddress).transfer(presaleInfo.presaleOwner, tokensToReturn);
                assert( tokenDistribution);
            }
            else if(participationCriteria.refundType == LaunchPadLib.RefundType.WITHDRAW ){
                bool tokenDistribution = IERC20(tokenInfo.tokenAddress).transfer(presaleInfo.presaleOwner, tokensToReturn);
                assert( tokenDistribution);
            }
            else{
                bool tokenDistribution = IERC20(tokenInfo.tokenAddress).transfer(0x000000000000000000000000000000000000dEaD , tokensToReturn);
                assert( tokenDistribution );
            }
        }

    }

    function claimTokensOrARefund() public isPresaleEnded {

        Participant memory _participant = participant[msg.sender];
        require(_participant.unclaimed > 0, "Nothing to claim");

        if (presaleInfo.preSaleStatus == LaunchPadLib.PreSaleStatus.SUCCEED) {

            if(!contributorsVesting.isEnabled){
                // participant[msg.sender].tokens = 0;
                // participant[msg.sender].value = 0;
                participant[msg.sender].unclaimed = 0;
                presaleCounts.claimsCount++;

                require(_participant.tokens > 0, "No tokens to claim");
                bool tokenDistribution = IERC20(tokenInfo.tokenAddress).transfer(msg.sender, _participant.tokens);
                require(tokenDistribution, "Unable to transfer tokens to the participant");

                emit Claimed(msg.sender, 0, _participant.tokens);

            }
            else {

                uint tokensLocked = _participant.tokens;
                uint tokensToRelease;

                for(uint i = 0; i<= contributorCycles; i++){
                    if(
                        block.timestamp >= (finalizingTime + contributorVestingRecord[i].releaseTime) &&
                        releaseStatus[finalizingTime + contributorVestingRecord[i].releaseTime][msg.sender] == ReleaseStatus.UNRELEASED
                    ){
                        tokensToRelease += (tokensLocked * contributorVestingRecord[i].tokensPC * contributorVestingRecord[i].percentageToRelease) / 10000;
                        releaseStatus[finalizingTime + contributorVestingRecord[i].releaseTime][msg.sender] = ReleaseStatus.RELEASED;

                        if(i == contributorCycles) {
                            // participant[msg.sender].value = 0;
                            // participant[msg.sender].tokens = 0;
                            presaleCounts.claimsCount++;
                        }
                    }
                }

                require(tokensToRelease > 0, "Nothing to unlock");
                participant[msg.sender].unclaimed -= tokensToRelease;

                require(
                    IERC20(tokenInfo.tokenAddress).transfer(msg.sender, tokensToRelease),
                    "Unable to transfer presale tokens to the presale owner"
                );


                emit Claimed(msg.sender, 0, tokensToRelease);

            }
        }
        else {
            participant[msg.sender].tokens = 0;
            participant[msg.sender].value = 0;
            participant[msg.sender].unclaimed = 0;

            presaleCounts.claimsCount++;

            require(_participant.value > 0, "No amount to refund");
            bool refund = payable(msg.sender).send(_participant.value);
            require(refund, "Unable to refund amount to the participant");

            emit Claimed(msg.sender, _participant.value, 0);

        }

    }

    function chageSaleType(LaunchPadLib.PresaleType _type, address _address, uint minimumTokens) public onlyPresaleOwner {
        if(_type == LaunchPadLib.PresaleType.TOKENHOLDERS) {
            participationCriteria.presaleType = _type;
            participationCriteria.criteriaToken = _address;
            participationCriteria.minCriteriaTokens = minimumTokens;
        }
        else {
            participationCriteria.presaleType = _type;
        }

        emit SaleTypeChanged(uint8(_type), _address, minimumTokens);

    }

    function unlockTokens() public onlyPresaleOwner isPresaleEnded {

        // require(teamVesting.isEnabled, "No tokens were locked");

        uint tokensLocked = teamVesting.vestingTokens * 10**tokenInfo.decimals;
        uint tokensToRelease;

        for(uint i = 0; i<= temaVestingCycles; i++){
            if(block.timestamp >= finalizingTime + teamVestingRecord[i].releaseTime && teamVestingRecord[i].releaseStatus == ReleaseStatus.UNRELEASED){
                tokensToRelease += (tokensLocked * teamVestingRecord[i].tokensPC * teamVestingRecord[i].percentageToRelease) / 10000;
                teamVestingRecord[i].releaseStatus = ReleaseStatus.RELEASED;
            }
        }

        require(tokensToRelease > 0, "Nothing to unlock");
        IERC20(tokenInfo.tokenAddress).transfer(msg.sender, tokensToRelease);

        // require(
        //     IERC20(tokenInfo.tokenAddress).transfer(msg.sender, tokensToRelease),
        //     "Unable to transfer presale tokens to the presale owner"
        //     );

        // emit TokensUnLocked(tokensToRelease);

    }

    function unlockLPTokens() public onlyPresaleOwner isPresaleEnded {

        address factory = uniswapV2Router02.factory();
        address WBNBAddr = uniswapV2Router02.WAVAX();

        address pairAddress = IJoeFactory(factory).getPair(tokenInfo.tokenAddress, WBNBAddr);
        uint availableLP = IERC20(pairAddress).balanceOf(address(this));

        require(availableLP > 0, "Nothing to claim");
        require(block.timestamp >= finalizingTime + presaleTimes.lpLockupDuration, "Not unlocked yet");

        IERC20(pairAddress).transfer(presaleInfo.presaleOwner, availableLP);
        // bool res = IERC20(pairAddress).transfer(presaleInfo.presaleOwner, availableLP);
        // require(res, "Unable to transfer presale tokens to the presale owner");

        // emit LPTokensUnLocked(availableLP);


    }

    function isWhiteListed(address user) view public returns (bool){
        return EnumerableSet.contains(whiteListedUsers, user);
    }

    function whiteListUsers(address[] memory _addresses) public onlyPresaleOwner {
        for(uint i=0; i < _addresses.length; i++){
            EnumerableSet.add(whiteListedUsers, _addresses[i]);
        }
    }

    function removeWhiteListUsers(address[] memory _addresses) public onlyPresaleOwner {
        for(uint i=0; i < _addresses.length; i++){
            EnumerableSet.remove(whiteListedUsers, _addresses[i]);
        }
    }

    function getWhiteListUsers() public view returns (address[] memory) {
        return EnumerableSet.values(whiteListedUsers);
    }

    function cancelSale() public onlyPresaleOwner isPresaleNotEnded {
        presaleInfo.preSaleStatus = LaunchPadLib.PreSaleStatus.CANCELED;
        uint extraTokens = IERC20(tokenInfo.tokenAddress).balanceOf(address(this));
        withdrawExtraTokens(extraTokens);
        emit Finalized(uint8(LaunchPadLib.PreSaleStatus.CANCELED), 0);
    }

    function getContributorReleaseStatus(uint _time, address _address) public view returns(ReleaseStatus){
        return releaseStatus[_time][_address];
    }

    function updateGeneralInfo(LaunchPadLib.GeneralInfo memory _generalInfo) public onlyPresaleOwner {
        generalInfo = _generalInfo;
    }

}

// File: @traderjoe-xyz/core/contracts/traderjoe/interfaces/IJoeRouter02.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.6.2;

import "./IJoeRouter01.sol";

interface IJoeRouter02 is IJoeRouter01 {
    function removeLiquidityAVAXSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountAVAXMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountAVAX);

    function removeLiquidityAVAXWithPermitSupportingFeeOnTransferTokens(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountAVAXMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountAVAX);

    function swapExactTokensForTokensSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;

    function swapExactAVAXForTokensSupportingFeeOnTransferTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable;

    function swapExactTokensForAVAXSupportingFeeOnTransferTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external;
}

// File: @traderjoe-xyz/core/contracts/traderjoe/interfaces/IJoeFactory.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.5.0;

interface IJoeFactory {
    event PairCreated(address indexed token0, address indexed token1, address pair, uint256);

    function feeTo() external view returns (address);

    function feeToSetter() external view returns (address);

    function migrator() external view returns (address);

    function getPair(address tokenA, address tokenB) external view returns (address pair);

    function allPairs(uint256) external view returns (address pair);

    function allPairsLength() external view returns (uint256);

    function createPair(address tokenA, address tokenB) external returns (address pair);

    function setFeeTo(address) external;

    function setFeeToSetter(address) external;

    function setMigrator(address) external;
}

// File: @traderjoe-xyz/core/contracts/traderjoe/interfaces/IJoeRouter01.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.6.2;

interface IJoeRouter01 {
    function factory() external pure returns (address);

    function WAVAX() external pure returns (address);

    function addLiquidity(
        address tokenA,
        address tokenB,
        uint256 amountADesired,
        uint256 amountBDesired,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    )
        external
        returns (
            uint256 amountA,
            uint256 amountB,
            uint256 liquidity
        );

    function addLiquidityAVAX(
        address token,
        uint256 amountTokenDesired,
        uint256 amountTokenMin,
        uint256 amountAVAXMin,
        address to,
        uint256 deadline
    )
        external
        payable
        returns (
            uint256 amountToken,
            uint256 amountAVAX,
            uint256 liquidity
        );

    function removeLiquidity(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountA, uint256 amountB);

    function removeLiquidityAVAX(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountAVAXMin,
        address to,
        uint256 deadline
    ) external returns (uint256 amountToken, uint256 amountAVAX);

    function removeLiquidityWithPermit(
        address tokenA,
        address tokenB,
        uint256 liquidity,
        uint256 amountAMin,
        uint256 amountBMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountA, uint256 amountB);

    function removeLiquidityAVAXWithPermit(
        address token,
        uint256 liquidity,
        uint256 amountTokenMin,
        uint256 amountAVAXMin,
        address to,
        uint256 deadline,
        bool approveMax,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external returns (uint256 amountToken, uint256 amountAVAX);

    function swapExactTokensForTokens(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);

    function swapTokensForExactTokens(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);

    function swapExactAVAXForTokens(
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable returns (uint256[] memory amounts);

    function swapTokensForExactAVAX(
        uint256 amountOut,
        uint256 amountInMax,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);

    function swapExactTokensForAVAX(
        uint256 amountIn,
        uint256 amountOutMin,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external returns (uint256[] memory amounts);

    function swapAVAXForExactTokens(
        uint256 amountOut,
        address[] calldata path,
        address to,
        uint256 deadline
    ) external payable returns (uint256[] memory amounts);

    function quote(
        uint256 amountA,
        uint256 reserveA,
        uint256 reserveB
    ) external pure returns (uint256 amountB);

    function getAmountOut(
        uint256 amountIn,
        uint256 reserveIn,
        uint256 reserveOut
    ) external pure returns (uint256 amountOut);

    function getAmountIn(
        uint256 amountOut,
        uint256 reserveIn,
        uint256 reserveOut
    ) external pure returns (uint256 amountIn);

    function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);

    function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}

// File: contracts/Launchpad/LaunchpadAVAX.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;


import "./PresaleAVAX.sol";
import "./LaunchPadLib.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// import "hardhat/console.sol";


contract LaunchpadAVAX is Ownable {

    using LaunchPadLib for *;

    uint public presaleCount = 0;
    uint public upfrontfee = 2 ether;
    uint8 public salesFeeInPercent = 2;

    address public uniswapV2Router02 = 0x10ED43C718714eb63d5aA57B78B54704E256024E;    // BSC Mainnet router
    // address public uniswapV2Router02 = 0xD99D1c33F9fC3444f8101754aBC46c52416550D1;    // BSC Testnet router

    address public teamAddr = 0xaEEE930D7Dc148862051CC0F43114FedAbAF34BC;
    address public devAddr = 0x2a1706e0B87373445c500621a47cb26484D1DdfF;

    ////////////////////////////// MAPPINGS ///////////////////////////////////

    mapping(uint => address) public presaleRecordByID;
    mapping(address => address[]) private presaleRecordByToken;

    event PresaleCreated(uint id, address presaleAddress);

    ////////////////////////////// FUNCTIONS ///////////////////////////////////

    constructor(address _uniswapV2Router02, address _teamAddr, address _devAddr){
        uniswapV2Router02 = _uniswapV2Router02;
        teamAddr = _teamAddr;
        devAddr = _devAddr;
    }


    function createPresale(
        LaunchPadLib.TokenInfo memory _tokenInfo,
        LaunchPadLib.ParticipationCriteria memory _participationCriteria,
        LaunchPadLib.PresaleTimes memory _presaleTimes,
        LaunchPadLib.ContributorsVesting memory _contributorsVesting,
        LaunchPadLib.TeamVesting memory _teamVesting,
        LaunchPadLib.GeneralInfo memory _generalInfo
    ) public payable {


        if(_teamVesting.isEnabled){
            require(_teamVesting.vestingTokens > 0, "Vesting tokens should be more than zero");
        }

        require(
            _participationCriteria.liquidity >= 20 &&
            _participationCriteria.liquidity <= 95 &&
            _presaleTimes.startedAt > block.timestamp &&
            _presaleTimes.expiredAt > _presaleTimes.startedAt,
            "Liquidity or Times are invalid"
        );

        require(
            _participationCriteria.softCap > 0 &&
            _participationCriteria.softCap < _participationCriteria.hardCap &&
            _participationCriteria.softCap >= _participationCriteria.hardCap/2 &&
            _participationCriteria.minContribution > 0 &&
            _participationCriteria.minContribution < _participationCriteria.maxContribution,
            "Invalid hardcap/softcap or minContribution/maxContribution"
        );

        if(msg.sender != owner()) {
            require( msg.value >= upfrontfee, "Insufficient funds to start");
        }

        presaleCount++;

        LaunchPadLib.PresaleInfo memory _presaleInfo = LaunchPadLib.PresaleInfo(presaleCount, msg.sender, LaunchPadLib.PreSaleStatus.PENDING);

        PresaleAVAX _presale = new PresaleAVAX (
            _tokenInfo,
            _presaleInfo,
            _participationCriteria,
            _presaleTimes,
            _contributorsVesting,
            _teamVesting,
            _generalInfo,
            salesFeeInPercent,
            uniswapV2Router02
        );

        uint tokensForSale = (_participationCriteria.hardCap * _participationCriteria.presaleRate * 10**_tokenInfo.decimals) / 1 ether ;
        uint tokensForLP = (tokensForSale * _participationCriteria.liquidity) / 100;
        uint tokensForVesting = _teamVesting.vestingTokens * 10**_tokenInfo.decimals;
        uint totalTokens = tokensForSale + tokensForLP + tokensForVesting;

        IERC20(_tokenInfo.tokenAddress).transferFrom(msg.sender, address(_presale), totalTokens);

        presaleRecordByToken[_tokenInfo.tokenAddress].push(address(_presale));
        presaleRecordByID[presaleCount] = address(_presale);

        emit PresaleCreated(presaleCount, address(_presale));

    }

    function getPresaleRecordsByToken(address _address) public view returns(address[] memory) {
        return presaleRecordByToken[_address];
    }

    function updateFees(uint _upfrontFee, uint8 _salesFeeInPercent) public onlyOwner {
        upfrontfee = _upfrontFee;
        salesFeeInPercent = _salesFeeInPercent;
    }

    function withdrawBNBs() public onlyOwner {
        uint balance = address(this).balance;
        require(balance > 0 , "nothing to withdraw");

        uint teamShare = (balance * 90) / 100;

        (bool res1,) = payable(teamAddr).call{value: teamShare}("");
        require(res1, "cannot send team Share");


        (bool res2,) = payable(devAddr).call{value: balance - teamShare}("");
        require(res2, "cannot send devTeamShare");
    }

    function updateTeamAddress(address _address) public onlyOwner {
        teamAddr = _address;
    }

    function updateDevAddress(address _address) public {
        require(devAddr == address(msg.sender), "Only dev is allowed");
        devAddr = _address;
    }

    receive() external payable {}

}

// File: contracts/Launchpad/AuxilliaryAVAX.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import "./LaunchPadLib.sol";
import "./AuxLibrary.sol";

interface ILocker {
    function unlockCycles() view external returns(uint);
    function unlockSchedule(uint cycle) view external returns(AuxLibrary.UnlockScheduleInternal memory);
    function lockerInfo() view external returns(AuxLibrary.LockerInfo memory);
}

interface IPresale {
    function tokenInfo() view external returns(LaunchPadLib.TokenInfo memory);
    function presaleTimes() view external returns(LaunchPadLib.PresaleTimes memory);
    function finalizingTime() view external returns(uint);
    function temaVestingCycles() view external returns(uint);
    function teamVestingRecord(uint cycle) view external returns(AuxLibrary.TeamVestingRecordInternal memory);
    function teamVesting() view external returns(LaunchPadLib.TeamVesting memory);

    function participant(address _address) view external returns(AuxLibrary.Participant memory);
    function contributorVestingRecord(uint cycle) view external returns(AuxLibrary.ContributorsVestingRecordInternal memory);
    function contributorCycles() view external returns(uint);
    function getContributorReleaseStatus(uint _time, address _address) view external returns(uint8);

    function uniswapV2Router02() view external returns (address);
}

interface IUniswapRouter {
    function factory() external pure returns (address);
    function WAVAX() external pure returns (address);

}

interface IUniswapFactory {
    function getPair(address tokenA, address tokenB) external view returns (address pair);
}

contract AuxilliaryAVAX {

    function getLockerSchedule(ILocker locker) public view returns(AuxLibrary.UnlockSchedule[] memory)  {
        uint tokensLocked = locker.lockerInfo().numOfTokensLocked;
        uint cycles = locker.unlockCycles();
        AuxLibrary.UnlockSchedule[] memory unlockSchedule = new AuxLibrary.UnlockSchedule[](cycles+1);

        for(uint i=0; i <= cycles; i++){
            AuxLibrary.UnlockScheduleInternal memory schedule = locker.unlockSchedule(i);
            unlockSchedule[i].cycle = schedule.cycle;
            unlockSchedule[i].releaseTime = schedule.releaseTime;
            unlockSchedule[i].tokens = tokensLocked * schedule.percentageToRelease * schedule.tokensPC / 10000;
            unlockSchedule[i].releaseStatus = schedule.releaseStatus;
        }

        return unlockSchedule;
    }

    function getTeamVestingSchedule(IPresale presale) public view returns(AuxLibrary.TeamVestingRecord[] memory)  {
        uint decimals = presale.tokenInfo().decimals;
        uint tokensLocked = presale.teamVesting().vestingTokens;
        uint finalizingTime = presale.finalizingTime();
        uint expiredAt = presale.presaleTimes().expiredAt;

        if (finalizingTime == 0) {
            finalizingTime = expiredAt;
        }

        uint cycles = presale.temaVestingCycles();
        AuxLibrary.TeamVestingRecord[] memory unlockSchedule = new AuxLibrary.TeamVestingRecord[](cycles+1);

        for(uint i=0; i <= cycles; i++){
            AuxLibrary.TeamVestingRecordInternal memory schedule = presale.teamVestingRecord(i);
            unlockSchedule[i].cycle = schedule.cycle;
            unlockSchedule[i].releaseTime = finalizingTime + schedule.releaseTime;
            unlockSchedule[i].tokens = (tokensLocked * schedule.percentageToRelease * schedule.tokensPC * (10**decimals)) / 10000;
            unlockSchedule[i].releaseStatus = schedule.releaseStatus;
        }

        return unlockSchedule;

    }

    function getContributorVestingSchedule(IPresale presale, address _address) public view returns(AuxLibrary.ContributorsVestingRecord[] memory)  {
        uint tokens = presale.participant(_address).tokens;
        uint finalizingTime = presale.finalizingTime();
        uint expiredAt = presale.presaleTimes().expiredAt;

        if (finalizingTime == 0) {
            finalizingTime = expiredAt;
        }

        uint cycles = presale.contributorCycles();
        AuxLibrary.ContributorsVestingRecord[] memory unlockSchedule = new AuxLibrary.ContributorsVestingRecord[](cycles+1);

        for (uint i=0; i <= cycles; i++){
            AuxLibrary.ContributorsVestingRecordInternal memory schedule = presale.contributorVestingRecord(i);
            uint8 releaseStatus = presale.getContributorReleaseStatus(finalizingTime + schedule.releaseTime, _address);
            unlockSchedule[i].cycle = schedule.cycle;
            unlockSchedule[i].releaseTime = finalizingTime + schedule.releaseTime;
            unlockSchedule[i].tokens = (tokens * schedule.percentageToRelease * schedule.tokensPC ) / 10000;
            unlockSchedule[i].releaseStatus = releaseStatus;
        }

        return unlockSchedule;

    }

    function getPresaleLpBalance(IPresale presale) public view returns(address _lpToken, uint256 _balance) {

        IUniswapRouter router = IUniswapRouter(presale.uniswapV2Router02());
        IUniswapFactory factory = IUniswapFactory(router.factory());

        address wethAddress = router.WAVAX();
        address pairAddress = factory.getPair(presale.tokenInfo().tokenAddress, wethAddress);

        if (pairAddress == address(0)) {
            return (address(0), 0);
        }

        uint balance = IERC20(pairAddress).balanceOf(address(presale));
        return (pairAddress, balance);
    }
}



// File: contracts/Launchpad/AuxLibrary.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

library AuxLibrary {

    struct UnlockScheduleInternal {
        uint cycle;
        uint percentageToRelease;
        uint releaseTime;
        uint tokensPC;
        uint releaseStatus;
    }
    struct UnlockSchedule {
        uint cycle;
        uint releaseTime;
        uint tokens;
        uint releaseStatus;
    }

    struct LockerInfo {
        uint id;
        address owner;
        IERC20 token;
        uint numOfTokensLocked;
        uint numOfTokensClaimed;
    }

    struct TeamVestingRecordInternal {
        uint cycle;
        uint releaseTime;
        uint tokensPC;
        uint percentageToRelease;
        uint releaseStatus;
    }

    struct TeamVestingRecord {
        uint cycle;
        uint releaseTime;
        uint tokens;
        uint releaseStatus;
    }

    struct Participant {
        uint256 value;
        uint256 tokens;
        uint256 unclaimed;
    }
    struct ContributorsVestingRecordInternal {
        uint cycle;
        uint releaseTime;
        uint tokensPC;
        uint percentageToRelease;
    }

    struct ContributorsVestingRecord {
        uint cycle;
        uint releaseTime;
        uint tokens;
        uint releaseStatus;
    }
}

// File: contracts/Launchpad/Auxilliary.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";

import "./LaunchPadLib.sol";
import "./AuxLibrary.sol";

interface ILocker {
    function unlockCycles() view external returns(uint);
    function unlockSchedule(uint cycle) view external returns(AuxLibrary.UnlockScheduleInternal memory);
    function lockerInfo() view external returns(AuxLibrary.LockerInfo memory);
}

interface IPresale {
    function tokenInfo() view external returns(LaunchPadLib.TokenInfo memory);
    function presaleTimes() view external returns(LaunchPadLib.PresaleTimes memory);
    function finalizingTime() view external returns(uint);
    function temaVestingCycles() view external returns(uint);
    function teamVestingRecord(uint cycle) view external returns(AuxLibrary.TeamVestingRecordInternal memory);
    function teamVesting() view external returns(LaunchPadLib.TeamVesting memory);

    function participant(address _address) view external returns(AuxLibrary.Participant memory);
    function contributorVestingRecord(uint cycle) view external returns(AuxLibrary.ContributorsVestingRecordInternal memory);
    function contributorCycles() view external returns(uint);
    function getContributorReleaseStatus(uint _time, address _address) view external returns(uint8);

    function uniswapV2Router02() view external returns (address);
}

interface IUniswapRouter {
    function factory() external pure returns (address);
    function WETH() external pure returns (address);
}

interface IUniswapFactory {
    function getPair(address tokenA, address tokenB) external view returns (address pair);
}

contract Auxilliary {

    function getLockerSchedule(ILocker locker) public view returns(AuxLibrary.UnlockSchedule[] memory)  {
        uint tokensLocked = locker.lockerInfo().numOfTokensLocked;
        uint cycles = locker.unlockCycles();
        AuxLibrary.UnlockSchedule[] memory unlockSchedule = new AuxLibrary.UnlockSchedule[](cycles+1);

        for(uint i=0; i <= cycles; i++){
            AuxLibrary.UnlockScheduleInternal memory schedule = locker.unlockSchedule(i);
            unlockSchedule[i].cycle = schedule.cycle;
            unlockSchedule[i].releaseTime = schedule.releaseTime;
            unlockSchedule[i].tokens = tokensLocked * schedule.percentageToRelease * schedule.tokensPC / 10000;
            unlockSchedule[i].releaseStatus = schedule.releaseStatus;
        }

        return unlockSchedule;
    }

    function getTeamVestingSchedule(IPresale presale) public view returns(AuxLibrary.TeamVestingRecord[] memory)  {
        uint decimals = presale.tokenInfo().decimals;
        uint tokensLocked = presale.teamVesting().vestingTokens;
        uint finalizingTime = presale.finalizingTime();
        uint expiredAt = presale.presaleTimes().expiredAt;

        if (finalizingTime == 0) {
            finalizingTime = expiredAt;
        }

        uint cycles = presale.temaVestingCycles();
        AuxLibrary.TeamVestingRecord[] memory unlockSchedule = new AuxLibrary.TeamVestingRecord[](cycles+1);

        for(uint i=0; i <= cycles; i++){
            AuxLibrary.TeamVestingRecordInternal memory schedule = presale.teamVestingRecord(i);
            unlockSchedule[i].cycle = schedule.cycle;
            unlockSchedule[i].releaseTime = finalizingTime + schedule.releaseTime;
            unlockSchedule[i].tokens = (tokensLocked * schedule.percentageToRelease * schedule.tokensPC * (10**decimals)) / 10000;
            unlockSchedule[i].releaseStatus = schedule.releaseStatus;
        }

        return unlockSchedule;

    }

    function getContributorVestingSchedule(IPresale presale, address _address) public view returns(AuxLibrary.ContributorsVestingRecord[] memory)  {
        uint tokens = presale.participant(_address).tokens;
        uint finalizingTime = presale.finalizingTime();
        uint expiredAt = presale.presaleTimes().expiredAt;

        if (finalizingTime == 0) {
            finalizingTime = expiredAt;
        }

        uint cycles = presale.contributorCycles();
        AuxLibrary.ContributorsVestingRecord[] memory unlockSchedule = new AuxLibrary.ContributorsVestingRecord[](cycles+1);

        for (uint i=0; i <= cycles; i++){
            AuxLibrary.ContributorsVestingRecordInternal memory schedule = presale.contributorVestingRecord(i);
            uint8 releaseStatus = presale.getContributorReleaseStatus(finalizingTime + schedule.releaseTime, _address);
            unlockSchedule[i].cycle = schedule.cycle;
            unlockSchedule[i].releaseTime = finalizingTime + schedule.releaseTime;
            unlockSchedule[i].tokens = (tokens * schedule.percentageToRelease * schedule.tokensPC ) / 10000;
            unlockSchedule[i].releaseStatus = releaseStatus;
        }

        return unlockSchedule;

    }

    function getPresaleLpBalance(IPresale presale) public view returns(address _lpToken, uint256 _balance) {

        IUniswapRouter router = IUniswapRouter(presale.uniswapV2Router02());
        IUniswapFactory factory = IUniswapFactory(router.factory());

        address wethAddress = router.WETH();
        address pairAddress = factory.getPair(presale.tokenInfo().tokenAddress, wethAddress);

        if (pairAddress == address(0)) {
            return (address(0), 0);
        }

        uint balance = IERC20(pairAddress).balanceOf(address(presale));
        return (pairAddress, balance);
    }
}