// File: /contracts/DROPS/MetaSkynet/ERC20/Goovy.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {ERC20Burnable, ERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../../../utils/WriteAccessControl.sol";
import "../../../Platform/MetaUnit/ERC20/IMetaUnit.sol";

contract Goovy is
    ERC20Burnable,
    ReentrancyGuard,
    WriteAccessControl,
    ERC721Holder
{
    enum VotingType {
        goovyPerMEU,
        percentage,
        addElegibleNFT,
        removeElegibleNFT,
        changeMEUAddress,
        changeMUTDAddress
    }

    struct Staking {
        uint256 uid;
        uint256 metaunit_staking_amount;
        uint256 start_day;
        uint256 end_day;
        uint256 rewardPerDay;
        bool finished;
    }

    struct Activated {
        uint256 uid;
        address owner_of;
        address eligibleNFT;
        uint256 nft_id;
        uint256 crystal_id;
        address meu_address;
        uint256 metaunit_amount;
        uint256 percentage;
        bool activated;
        bool isNFT;
    }
    struct Proposal {
        VotingType voting_type;
        bytes20 value;
        uint256 start_time;
        bool resolved;
    }
    struct Voice {
        address eth_address;
        bool voice;
    }

    uint256 public goovyPerMeu = 30;
    uint256 public startTime;
    uint256 public stakingUid;
    uint256 public activatedCount;
    uint256 private totalCrystalRewardPercentage;
    Activated[] public _activated;
    Proposal[] public _proposals;
    uint256 public _percentage = 10;
    uint256 private _min_amount = 1000000 ether;
    uint256 private _max_amount = 5000000 ether;

    mapping(address => mapping(uint256 => uint256)) public _activated_addresses;
    mapping(address => uint256) public _activated_addr_bal;
    mapping(address => uint256) public _activated_addr_bal_meu;
    mapping(address => uint256) public _activated_addr_bal_meu_dt;
    mapping(uint256 => mapping(address => bool)) private _is_voted;
    mapping(uint256 => Voice[]) private _voices;
    address public meta_unit_address;
    address public meta_unit_dt_address;
    address public generative_assets_crystal_address;

    mapping(uint256 => uint256) public globalToLocalStakeUids;
    mapping(address => Staking[]) public stakings;
    mapping(address => mapping(uint => mapping(uint => bool)))
        public hasStakeRewardClaimed;

    address[] private eligibleActivateNFTContracts;

    modifier checkCrystalHolder() {
        require(
            IERC721(generative_assets_crystal_address).balanceOf(msg.sender) >
                0 ||
                _activated_addr_bal[msg.sender] > 0, "017"
        );
        _;
    }

    constructor(
        address _mint_to,
        address _meta_unit_address,
        address _meta_unit_dt_address,
        address _generative_assets_crystal_address
    ) ERC20("Generator", "GOOVY") {
        _mint(_mint_to, 1000000000 * 10 ** 18);
        meta_unit_address = _meta_unit_address;
        meta_unit_dt_address = _meta_unit_dt_address;
        generative_assets_crystal_address = _generative_assets_crystal_address;
        startTime = block.timestamp;
    }

    event proposalCreated(
        uint256 uid,
        VotingType voting_type,
        bytes20 value,
        uint256 start_time,
        uint256 end_time
    );
    event voiceSubmited(address eth_address, bool voice);
    event proposalResolved(uint256 uid, bool submited);
    event crystalActivated(
        uint256 uid,
        address owner_of,
        address token_address,
        uint256 token_id,
        uint256 crystal_id,
        address meu_address,
        uint256 amount,
        uint256 percentage,
        bool useNFT
    );
    event crystalDeactivated(uint256 uid);
    event stakingCreated(
        uint256 uid,
        uint256 metaunit_staking_amount,
        uint256 start_day,
        uint256 end_day,
        address owner_of,
        bool finished
    );
    event claimed(uint256 uid, uint256 day, uint256 claimed, address owner_of);
    event claimedFromCrystal(uint256 uid, uint256 claimed, address owner_of);

    function addEligibleActivateNFTs(address _contract) public checkAccess {
        eligibleActivateNFTContracts.push(_contract);
    }

    function viewEligibleNFTs()
        public
        view
        returns (address[] memory)
    {
        return eligibleActivateNFTContracts;
    }

    function removeEligibleActivateNFTs(uint arrayNum) public checkAccess {
        delete eligibleActivateNFTContracts[arrayNum];
    }

    function createProposal(
        VotingType voting_type_,
        bytes20 value_
    ) external isEOA checkCrystalHolder {
        if (voting_type_ == VotingType.goovyPerMEU) {
            require(uint160(value_) >= 1 ether, "006");
        } else if (voting_type_ == VotingType.percentage) {
            require(uint160(value_) <= 100, "005");
        } else if (voting_type_ == VotingType.changeMEUAddress || voting_type_ == VotingType.changeMUTDAddress) {
            // no checks needed
        } else {
            require(IERC721(address(value_)).supportsInterface(0x80ac58cd), "016");
        }
        uint256 newProposalUid = _proposals.length;
        _proposals.push(
            Proposal(voting_type_, value_, block.timestamp, false)
        );
        emit proposalCreated(
            newProposalUid,
            voting_type_,
            value_,
            block.timestamp,
            block.timestamp + 5 days
        );
    }

    function vote(
        uint256 uid_,
        bool voice_
    ) public nonReentrant isEOA checkCrystalHolder {
        require(
            !_is_voted[uid_][msg.sender] &&
                block.timestamp < _proposals[uid_].start_time + 5 days &&
                balanceOf(msg.sender) > 0,
            "011"
        );
        _voices[uid_].push(Voice(msg.sender, voice_));
        emit voiceSubmited(msg.sender, voice_);
        _is_voted[uid_][msg.sender] = true;
    }

    function resolve(
        uint256 uid_
    ) external nonReentrant isEOA checkCrystalHolder {
        Proposal memory proposal = _proposals[uid_];
        require(
            !_proposals[uid_].resolved &&
                block.timestamp > proposal.start_time + 5 days,
            "008"
        );
        uint256 voices_for;
        uint256 voices_against;
        for (uint256 i = 0; i < _voices[uid_].length; i++) {
            Voice memory voice = _voices[uid_][i];
            uint256 balance = balanceOf(voice.eth_address);
            if (voice.voice) voices_for += balance;
            else voices_against += balance;
        }
        bool submited = voices_for > voices_against;
        if (submited) {
            if (proposal.voting_type == VotingType.goovyPerMEU)
                goovyPerMeu = uint256(uint160(proposal.value));
            else if (proposal.voting_type == VotingType.percentage)
                _percentage = uint256(uint160(proposal.value));
            else if (proposal.voting_type == VotingType.addElegibleNFT)
                eligibleActivateNFTContracts.push(address(proposal.value));
            else if (proposal.voting_type == VotingType.removeElegibleNFT) {
                for (uint256 i; i < eligibleActivateNFTContracts.length; i++) {
                    if (eligibleActivateNFTContracts[i] == address(proposal.value)) {
                        delete eligibleActivateNFTContracts[i];
                    }
                }
            } else if (proposal.voting_type == VotingType.changeMEUAddress) {
                meta_unit_address = address(proposal.value);
            } else if (proposal.voting_type == VotingType.changeMUTDAddress) {
                meta_unit_dt_address = address(proposal.value);
            }
        }
        emit proposalResolved(uid_, submited);
        _proposals[uid_].resolved = true;
    }

    function hasEligibleNFT(address _contract) public view returns (bool) {
        for (uint i = 0; i < eligibleActivateNFTContracts.length; i++) {
            if (_contract == eligibleActivateNFTContracts[i]) return true;
        }
        return false;
    }

    function activateCrystal(
        address eligible_nft_token_address,
        uint256 eligible_nft_token_id,
        address meu_address,
        uint256 meu_amount,
        uint256 crystal_id,
        uint256 percentage,
        bool useNFT
    ) external nonReentrant isEOA {
        require(percentage <= _percentage, "012");
        require(meu_address == meta_unit_address || meu_address == meta_unit_dt_address, "015");
        require(
            IERC721(generative_assets_crystal_address).ownerOf(crystal_id) ==
                msg.sender,
            "013"
        );
        uint256 stake_amount = useNFT ? _max_amount : meu_amount;
        if (useNFT) {
            require(hasEligibleNFT(eligible_nft_token_address), "004");
            IERC721(eligible_nft_token_address).transferFrom(
                msg.sender,
                address(this),
                eligible_nft_token_id
            );
            uint256 refund_amount = _activated_addr_bal_meu[msg.sender];
            if (refund_amount > 0) {
                _activated_addr_bal_meu[msg.sender] = 0;
                IERC20(meta_unit_address).transfer(
                    msg.sender,
                    refund_amount
                );
            }
            uint256 dt_refund_amount = _activated_addr_bal_meu_dt[msg.sender];
            if (dt_refund_amount > 0) {
                _activated_addr_bal_meu_dt[msg.sender] = 0;
                IERC20(meta_unit_dt_address).transfer(
                    msg.sender,
                    dt_refund_amount
                );
            }
        } else {
            if (meu_amount == 0) {
                // second and following activations can be free
                require(_activated_addr_bal[msg.sender] > 0, "003");
            } else {
                require(
                    meu_amount >= _min_amount && meu_amount <= _max_amount,
                    "014"
                );
                IERC20(meu_address).transferFrom(
                    msg.sender,
                    address(this),
                    meu_amount
                );
                if (meu_address == meta_unit_address) {
                    _activated_addr_bal_meu[msg.sender] += meu_amount;
                } else {
                    _activated_addr_bal_meu_dt[msg.sender] += meu_amount;
                }
            }
        }
        IERC721(generative_assets_crystal_address).safeTransferFrom(
            msg.sender,
            address(this),
            crystal_id
        );
        _activated_addr_bal[msg.sender] += stake_amount;
        activatedCount++;
        totalCrystalRewardPercentage += percentage;

        uint256 new_activated_uid = _activated.length;
        _activated.push(
            Activated(
                new_activated_uid,
                msg.sender,
                eligible_nft_token_address,
                eligible_nft_token_id,
                crystal_id,
                meu_address,
                stake_amount,
                percentage,
                true,
                useNFT
            )
        );

        emit crystalActivated(
            new_activated_uid,
            msg.sender,
            eligible_nft_token_address,
            eligible_nft_token_id,
            crystal_id,
            meu_address,
            stake_amount,
            percentage,
            useNFT
        );
    }

    function deactivateCrystal(uint256 uid) external nonReentrant isEOA {
        require(uid < _activated.length, "002");
        Activated memory activated = _activated[uid];
        require(activated.activated, "010");
        require(msg.sender == activated.owner_of, "009");
        uint256 stake_amount = activated.isNFT ? _max_amount : activated.metaunit_amount;
        _activated_addr_bal[msg.sender] -= stake_amount;
        if (activated.isNFT) {
            IERC721(activated.eligibleNFT).transferFrom(
                address(this),
                msg.sender,
                activated.nft_id
            );
        } else {
            if (activated.meu_address == meta_unit_address) {
                if (_activated_addr_bal_meu[msg.sender] > 0) {
                    // only transfer tokens back if not already refunded
                    _activated_addr_bal_meu[msg.sender] -= stake_amount;
                    IERC20(meta_unit_address).transfer(msg.sender, stake_amount);
                }
            } else {
                if (_activated_addr_bal_meu_dt[msg.sender] > 0) {
                    _activated_addr_bal_meu_dt[msg.sender] -= stake_amount;
                    IERC20(meta_unit_dt_address).transfer(msg.sender, stake_amount);
                }
            }
        }
        totalCrystalRewardPercentage -= activated.percentage;
        activatedCount--;
        delete _activated[uid]; // sets activated.activated to false
        emit crystalDeactivated(uid);
    }

    function getActivatedList()
        public
        view
        returns (Activated[] memory activated)
    {
        uint256 activated_len = activatedCount;
        uint256 last_pushed_id;
        activated = new Activated[](activated_len);
        for (uint256 i = 0; i < _activated.length; i++) {
            if (_activated[i].activated) {
                activated[last_pushed_id] = _activated[i];
                last_pushed_id++;
            }
        }
    }

    function getAveragePercent() public view returns (uint256) {
        if (activatedCount == 0) return 0;
        return totalCrystalRewardPercentage / activatedCount;
    }

    function stake(uint256 amount) external nonReentrant isEOA {
        Activated[] memory activated = getActivatedList();
        require(activated.length >= 3, "001");
        require(amount >= 100 ether, "022");
        IMetaUnit(meta_unit_address).burnFrom(msg.sender, amount);
        uint256 averagePercent = getAveragePercent();
        uint256 _amount = (goovyPerMeu *
            ((amount * (100 - averagePercent)) / 100)) / 30;
        uint256 localStakingUid = stakings[msg.sender].length;
        stakings[msg.sender].push(
            Staking(stakingUid, amount, today(), today() + 29, _amount, false)
        );
        globalToLocalStakeUids[stakingUid] = localStakingUid;
        emit stakingCreated(
            stakingUid,
            amount,
            block.timestamp,
            block.timestamp + 29 days,
            msg.sender,
            false
        );
        stakingUid++;
        uint256 nftActiveAmount = (goovyPerMeu * amount * averagePercent) / 100;
        for (uint256 i; i < activated.length; i++) {
            uint256 activatedBal = _activated_addr_bal[activated[i].owner_of];
            _activated_addresses[activated[i].owner_of][activated[i].uid] +=
                (nftActiveAmount * 
                    (activatedBal > _max_amount ? _max_amount : activatedBal)
                ) / (activatedCount * _max_amount);
        }
    }

    function claim(uint uid) public isEOA {
        require(uid <= stakingUid, "007");
        Staking memory staking = stakings[msg.sender][
            globalToLocalStakeUids[uid]
        ];
        uint256 _today = today();
        uint256 total_amount;
        for (uint i = staking.start_day; i <= staking.end_day; i++) {
            if (!hasStakeRewardClaimed[msg.sender][uid][i] && _today >= i) {
                hasStakeRewardClaimed[msg.sender][uid][i] = true;
                total_amount += staking.rewardPerDay;
                emit claimed(uid, i, staking.rewardPerDay, msg.sender);
            }
        }
        if (total_amount > 0) _mint(msg.sender, total_amount);
        if (_today - staking.start_day > 29) {
            stakings[msg.sender][globalToLocalStakeUids[uid]].finished = true;
        }
    }

    function claimAll() external isEOA {
        for (uint256 i; i < stakings[msg.sender].length; i++) {
            if (!stakings[msg.sender][i].finished) {
                claim(stakings[msg.sender][i].uid);
            }
        }
    }

    function stakerClaimable(uint uid, uint day) public view returns (uint) {
        if (hasStakeRewardClaimed[msg.sender][uid][day]) {
            return 0;
        } else {
            return
                stakings[msg.sender][globalToLocalStakeUids[uid]].rewardPerDay;
        }
    }

    function stakerClaimableUidTotal(
        uint uid
    ) public view returns (uint256 total) {
        Staking memory staking = stakings[msg.sender][
            globalToLocalStakeUids[uid]
        ];
        uint256 _today = today();
        for (uint i = staking.start_day; i <= staking.end_day; i++) {
            if (i > _today) return total;
            total += stakerClaimable(uid, i);
        }
    }

    function claimActivatedRewardsTotal() external isEOA nonReentrant {
        Activated[] memory activated = getActivatedList();
        uint256 amount;
        for (uint256 i; i < activated.length; i++) {
            if (activated[i].owner_of == msg.sender && activated[i].activated) {
                uint256 uid_amount = _activated_addresses[msg.sender][activated[i].uid];
                amount += uid_amount;
                if (amount > 0) {
                    _activated_addresses[msg.sender][activated[i].uid] = 0;
                    emit claimedFromCrystal(
                        activated[i].uid,
                        uid_amount,
                        msg.sender
                    );
                }
            }
        }
        require(amount > 0, "028");
        _mint(msg.sender, amount);
    }

    function claimActivatedRewards(uint256 uid) external isEOA nonReentrant {
        require(_activated_addresses[msg.sender][uid] > 0, "028");
        uint256 amount = _activated_addresses[msg.sender][uid];
        _activated_addresses[msg.sender][uid] = 0;
        _mint(msg.sender, amount);
        emit claimedFromCrystal(uid, amount, msg.sender);
    }

    function today() public view returns (uint) {
        uint256 timeStamp = block.timestamp;
        return
            timeStamp < startTime ? 0 : (timeStamp - startTime) / 24 hours + 1;
    }
}

// File: /contracts/utils/WriteAccessControl.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8;

import "./Ownable.sol";
import "../interfaces/IAccessControl.sol";

contract WriteAccessControl is Ownable{

  bool public checkEnabled;
  mapping(address => bool) internal accessList;

  event AddedAccess(address user);
  event RemovedAccess(address user);
  event CheckAccessEnabled();
  event CheckAccessDisabled();

  constructor()
  {
    checkEnabled = true;
  }

  function hasAccess(
    address _user
  )
    public
    view
    virtual
    returns (bool)
  {
    return accessList[_user] || !checkEnabled;
  }

  function addAccess(address _user)
    external
    onlyOwner()
  {
    if (!accessList[_user]) {
      accessList[_user] = true;

      emit AddedAccess(_user);
    }
  }

  function removeAccess(address _user)
    external
    onlyOwner()
  {
    if (accessList[_user]) {
      accessList[_user] = false;

      emit RemovedAccess(_user);
    }
  }

  function enableAccessCheck()
    external
    onlyOwner()
  {
    if (!checkEnabled) {
      checkEnabled = true;

      emit CheckAccessEnabled();
    }
  }

  function disableAccessCheck()
    external
    onlyOwner()
  {
    if (checkEnabled) {
      checkEnabled = false;

      emit CheckAccessDisabled();
    }
  }

  modifier checkAccess() {
    require(hasAccess(msg.sender), "No access");
    _;
  }

  modifier isEOA(){
    require(msg.sender == tx.origin, "user is not Ethereum Outer Address");
    _;
  }
}
// File: /contracts/utils/Ownable.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8;

contract Ownable {

  address public owner;
  address private pendingOwner;

  event OwnershipTransferRequested(
    address indexed from,
    address indexed to
  );
  event OwnershipTransferred(
    address indexed from,
    address indexed to
  );

  constructor() {
    owner = msg.sender;
  }

  function transferOwnership(address _to)
    external
    onlyOwner()
  {
    pendingOwner = _to;

    emit OwnershipTransferRequested(owner, _to);
  }

  function acceptOwnership()
    external
  {
    require(msg.sender == pendingOwner, "Must be proposed owner");

    address oldOwner = owner;
    owner = msg.sender;
    pendingOwner = address(0);

    emit OwnershipTransferred(oldOwner, msg.sender);
  }

  modifier onlyOwner() {
    require(msg.sender == owner, "Only callable by owner");
    _;
  }

}
// File: /contracts/interfaces/IAccessControl.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8;

interface IAccessControl {
  function hasAccess(address user, bytes calldata data) external view returns (bool);
}
// File: /contracts/Platform/MetaUnit/ERC20/IMetaUnit.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

interface IMetaUnit {
    function burnFrom(address account, uint256 amount) external;
}

// 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: @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/ERC721/utils/ERC721Holder.sol



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

pragma solidity ^0.8.0;

import "../IERC721Receiver.sol";

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
 */
contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (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 `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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`.
     *
     * 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;

    /**
     * @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 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: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * 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 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 the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

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

// 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/ERC20/extensions/ERC20Burnable.sol



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

pragma solidity ^0.8.0;

import "../ERC20.sol";
import "../../../utils/Context.sol";

/**
 * @dev Extension of {ERC20} that allows token holders to destroy both their own
 * tokens and those that they have an allowance for, in a way that can be
 * recognized off-chain (via event analysis).
 */
abstract contract ERC20Burnable is Context, ERC20 {
    /**
     * @dev Destroys `amount` tokens from the caller.
     *
     * See {ERC20-_burn}.
     */
    function burn(uint256 amount) public virtual {
        _burn(_msgSender(), amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, deducting from the caller's
     * allowance.
     *
     * See {ERC20-_burn} and {ERC20-allowance}.
     *
     * Requirements:
     *
     * - the caller must have allowance for ``accounts``'s tokens of at least
     * `amount`.
     */
    function burnFrom(address account, uint256 amount) public virtual {
        _spendAllowance(account, _msgSender(), amount);
        _burn(account, amount);
    }
}

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



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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

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

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * 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}.
     *
     * 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 default value returned by this function, unless
     * it's 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, allowance(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 = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * 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;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _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;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _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;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _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 Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * 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/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

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

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

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

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

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

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}