// Contract: FractionalAsset
// Target function: function _safeTransfer(
0186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
        // for accounts without code, i.e. `keccak256('')`
        bytes32 codehash;
        bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
        // solhint-disable-next-line no-inline-assembly
        assembly { codehash := extcodehash(account) }
        return (codehash != accountHash && codehash != 0x0);
    }

}

contract FractionalAssetData is Context {

    /**
        Master Database Which Interacts With KYC And Auth Databases
     */
    IDatabase public constant Database = IDatabase(0x238a94E37a1bAde56Cfcc5dbE7f48DA88aa9Db19);

    /**
        Is Initialized
     */
    bool internal initialized;

    /**
        Name For NFT Compatibility
     */
    string internal _name;

    /**
        Symbol For NFT Compatibility
     */
    string internal _symbol;

    /**
        Current Token ID For Tracking Purposes
     */
    uint256 internal _currentTokenID;

    /**
        Mapping From Mint Tokens To Cost
     */
    mapping ( address => uint256 ) public mintCost;

    /**
        Mapping From A TokenID To An Address Which Dictates Ownership Of That Specific ID
     */
    mapping(uint256 => address) internal _owners;

    /**
        List Of Registered Owners Containing At Least 1 Fractional Asset
     */
    address[] internal _registeredOwners;

    /**
        Mapping Between An Owner And Their Index In The `_registeredOwners` List
     */
    mapping( address => uint256 ) internal _ownerIndex;

    /**
        Mapping From Owner Address To The Number Of Fractional Assets They Own In Total
        Ensures NFT Compatibility
     */
    mapping(address => uint256) internal _balances;

    /**
        Mapping from token ID to approved address
     */
    mapping(uint256 => address) internal _tokenApprovals;

    /**
        Mapping from owner to operator approvals
    */
    mapping(address => mapping(address => bool)) internal _operatorApprovals;

    /**
        Returns The URI Of The Images Associated With Each Collection
     */
    string internal baseURI;

    /**
        Number Of Fractions NFT Is Split Into
     */
    uint256 internal nFractions;

    /**
        Whether Or Not Minting Is Enabled
     */
    bool public mintingEnabled;

    /**
        Whether Or Not An Allowlist Is Enabled
     */
    bool public allowlistEnabled;

    /**
        Recipient of Mint Funds
     */
    address public mintRecipient;

    // Mapping from owner to excluded rewards
    mapping(address => uint256) totalExcluded;

    // total dividends for tracking
    uint256 internal dividendsPerNFT;

    // total rewards received
    uint256 public totalRewards;

    // Reward Token
    address public rewardToken;

    // precision value
    uint256 internal constant precision = 10**18;

    // Merkle Root
    bytes32 internal merkleRoot;

    /**
        Ensures `account` is KYC Verified Before Permitting
        Access To Certain Functionality
     */
    modifier isVerified(address account) {
        require(
            account != address(0),
            'Zero Address'
        );
        require(
            Database.isVerified(account),
            'Account Not KYC Verified'
        );
        _;
    }

    /**
        Ensures Caller Is Authorized To Call Restricted Functions
     */
    modifier onlyAuthorized() {
        require(
            Database.isAuthorized(_msgSender()) == true,
            'Not Authorized To Call'
        );
        _;
    }

    /**
        Events To Support Data Tracking
     */
    event BaseURIChange(string oldURI, string newURI);

}


contract FractionalAsset is FractionalAssetData, IFractionalAsset, Clones {

  using Address for address;

  // Event Declarations
event Mint(address indexed to, uint256 indexed tokenId);
event MintingEnabled();
event MintingDisabled();
event AllowlistEnabled();
event AllowlistDisabled();
event MerkleRootSet(bytes32 newRoot);
event Withdrawal(address indexed token, address indexed to, uint256 amount);
event MintCostSet(address indexed token, uint256 newCost);
event RewardsDeposited(uint256 amount);
event RewardsClaimed(address indexed user, uint256 amount);

  /**
      Initializes The FractionalAsset
   */
  function __init__(
      string[] calldata strings,
      uint256[] calldata values,
      address[] calldata addrs
  ) external override {
      require(
          !initialized,
          'Already Initialized'
      );
      initialized = true;
      _name = strings[0];
      _symbol = strings[1];
      baseURI = strings[2];
      nFractions = values[0];
      for (uint i = 0; i < values[1]; i++) {
          mintCost[addrs[i]] = values[2 + i];
      }
      rewardToken = addrs[values[1]];
      mintRecipient = addrs[values[1] + 1];
  }
  
  /**
      Sets The Base URI, Updating Images For ALL Collections
   */
  function setBaseURI(string calldata newURI) external onlyAuthorized {
      emit BaseURIChange(baseURI, newURI);
      baseURI = newURI;
  }

  function enableMinting() external onlyAuthorized {
      mintingEnabled = true;
      emit MintingEnabled();
  }

  function setMintRecipient(address newRecipient) external onlyAuthorized {
      mintRecipient = newRecipient;
  }

  function disableMinting() external onlyAuthorized {
      mintingEnabled = false;
      emit MintingDisabled();
  }

  function enableAllowlist() external onlyAuthorized {
      allowlistEnabled = true;
      emit AllowlistEnabled();
  }

  function disableAllowlist() external onlyAuthorized {
      allowlistEnabled = false;
      emit AllowlistDisabled();
  }

  function setMerkleRoot(bytes32 root) external onlyAuthorized {
      merkleRoot = root;
      emit MerkleRootSet(root);
  }

  function withdrawETH(address to) external onlyAuthorized {
      (bool s,) = payable(to).call{value: address(this).balance}("");
      require(s);
      emit Withdrawal(address(0), to, address(this).balance);
  }

  function withdrawToken(address token, address to) external onlyAuthorized {
      IERC20(token).transfer(to, IERC20(token).balanceOf(address(this)));
      emit Withdrawal(token, to, IERC20(token).balanceOf(address(this)));
  }

  function setCost(address mintToken, uint256 newCost) external onlyAuthorized {
      mintCost[mintToken] = newCost;
      emit MintCostSet(mintToken, newCost);
  }

  function ownerMint(address to, uint256 num) external onlyAuthorized {
      for (uint i = 0; i < num;) {
          _safeMint(to, _currentTokenID);
          unchecked { ++i; }
      }
  }

  function batchClaim(address[] calldata users) external onlyAuthorized {
      uint len = users.length;
      for (uint i = 0; i < len;) {
          _claimRewards(users[i]);
          unchecked { ++i; }
      }
  }

  function depositRewards(uint256 amount) external onlyAuthorized {
      require(
          _currentTokenID > 0,
          'Zero Tokens'
      );
      require(
          IERC20(rewardToken).allowance(msg.sender, address(this)) >= amount,
          'Insufficient Allowance'
      );
      require(
          IERC20(rewardToken).balanceOf(msg.sender) >= amount,
          'Insufficient Balance'
      );
      require(
          IERC20(rewardToken).transferFrom(msg.sender, address(this), amount),
          'Error TransferFrom'
      );
      unchecked {
          totalRewards += amount;
          dividendsPerNFT += ( amount * precision ) / _currentTokenID;
      }
      emit RewardsDeposited(amount);
  }

  function claimRewards() external {
      require(
          _balances[msg.sender] > 0,
          'Zero Balance'
      );
      _claimRewards(msg.sender);
  }

  function mint(address token, address to, uint256 num, bytes32[] calldata proof) external payable {
      require(
          mintingEnabled,
          'Minting Is Disabled'
      );
      require(
          to != address(0),
          'Zero Address'
      );
      require(
          num > 0,
          'Zero Num'
      );
      if (allowlistEnabled) {
          require(
              MerkleProof.verify(
                  proof,
                  merkleRoot,
                  keccak256(abi.encodePacked(_msgSender()))
              ),
              "User Is Not Whitelisted"
          );
      }

      require(
          mintCost[token] > 0,
          'Invalid Mint Token'
      );
      uint totalCost = mintCost[token] * num;

      if (token == address(0)) {
          require(
              msg.value >= totalCost,
              'Insufficient Value'
          );

          // add logic to swap to USDC if ETH
          (bool s,) = payable(mintRecipient).call{value: msg.value}("");
          require(s, 'Mint Recipient Transfer Failure');

      } else {
          require(
              IERC20(token).balanceOf(msg.sender) >= totalCost,
              'Insufficient Balance'
          );
          require(
              IERC20(token).allowance(msg.sender, address(this)) >= totalCost,
              'Insufficient Allowance'
          );
          require(
              IERC20(token).transferFrom(msg.sender, mintRecipient, totalCost),
              'Error Transfer From'
          );
      }
      
      for (uint i = 0; i < num;) {
          _safeMint(to, _currentTokenID);
          unchecked { ++i; }
      }
  }

  /**
      Cumulative Dividends For A Number Of Tokens
   */
  function getCumulativeDividends(uint256 share) internal view returns (uint256) {
      return ( share * dividendsPerNFT ) / precision;
  }

  /**
      Pending Rewards For `account`
   */
  function pendingRewards(address account) public view returns (uint256) {
      if(_balances[account] == 0){ return 0; }
      if (totalRewards == 0) { return 0; }

      uint256 accountTotalDividends = getCumulativeDividends(_balances[account]);
      uint256 accountTotalExcluded = totalExcluded[account];

      if(accountTotalDividends <= accountTotalExcluded){ return 0; }

      return accountTotalDividends - accountTotalExcluded;
  }

  /**
      Total Supply of NFT
   */
  function totalSupply() external view returns (uint256) {
      return _currentTokenID;
  }

  /**
      Name Of The Collection
   */
  function name() external view override returns (string memory) {
      return _name;
  }

  /**
      Symbol (ticker) Of The Collection
   */
  function symbol() external view override returns (string memory) {
      return _symbol;
  }

  /**
      Returns The Number Of Fractions This NFT Is Split Into
   */
  function numFractions() external view override returns (uint256) {
      return nFractions;
  }

  /**
      Returns The URI To An Image Representing This Fractional Asset
   */
  function tokenURI(uint256) external view override returns (string memory) {
      return baseURI;
  }

  /**
      Returns The URI To An Image Representing This Fractional Asset
   */
  function URI() external view override returns (string memory) {
      return baseURI;
  }

  /**
   * @dev Returns the number of tokens in ``owner``'s account.
   */
  function balanceOf(address owner) external view override returns (uint256 balance) {
      return _balances[owner];
  }

  /**
   * @dev Returns the owner of the `tokenId` token.
   *
   * Requirements:
   *
   * - `tokenId` must exist.
   */
  function ownerOf(uint256 tokenId) public view returns (address owner) {
      require(
          _exists(tokenId),
          'Token Does Not Exist'
      );
      return _owners[tokenId];
  }

  /**
   * @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 override {
      require(
          _isApprovedOrOwner(_msgSender(), tokenId), 
          "Transfer caller is not owner nor approved"
      );
      _safeTransfer(from, to, tokenId, new bytes(0));
  }

  /**
   * @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
  ) public override {
      require(
          _isApprovedOrOwner(_msgSender(), tokenId), 
          "Transfer caller is not owner nor approved"
      );
      _safeTransfer(from, to, tokenId, data);
  }

  /**
   * @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 override {
      require(
          _isApprovedOrOwner(_msgSender(), tokenId), 
          "Transfer caller is not owner nor approved"
      );
      _transfer(from, to, tokenId);
  }

  /**
   * @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 override {
      address owner = 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 Returns the account approved for `tokenId` token.
   *
   * Requirements:
   *
   * - `tokenId` must exist.
   */
  function getApproved(uint256 tokenId) public view override returns (address operator) {
      require(
          _exists(tokenId), 
          "Non Existent Token"
      );
      return _tokenApprovals[tokenId];
  }

  /**
   * @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 override {
      _setApprovalForAll(_msgSender(), operator, _approved);
  }

  /**
   * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
   *
   * See {setApprovalForAll}
   */
  function isApprovedForAll(address owner, address operator) public view override returns (bool) {
      return _operatorApprovals[owner][operator];
  }

  /**
      Claims Reward For User
   */
  function _claimRewards(address user) internal {

      // return if zero balance
      if (_balances[user] == 0) {
          return;
      }

      // fetch pending rewards
      uint pending = pendingRewards(user);
      uint bal = IERC20(rewardToken).balanceOf(address(this));
      if (pending > bal) {
          pending = bal;
      }

      // return if no rewards
      if (pending == 0) {
          return;
      }
      
      // reset total rewards
      totalExcluded[user] = getCumulativeDividends(_balances[user]);

      // transfer reward to user
      IERC20(rewardToken).transfer(user, pending);
      emit RewardsClaimed(user, pending);
  }