// Contract: VcgERC721TokenWithRoyalty
// Target function: function tokenURI(uint256 tokenId) override(IVcgERC721Token,VcgERC721Token) public view returns (string memory)
TokensIndex[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();
    }
}


pragma solidity ^0.8.0;

// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.

/**
 * @dev Wrappers over Solidity's arithmetic operations.
 *
 * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
 * now has built in overflow checking.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        return a * b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator.
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b <= a, errorMessage);
            return a - b;
        }
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a / b;
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(
        uint256 a,
        uint256 b,
        string memory errorMessage
    ) internal pure returns (uint256) {
        unchecked {
            require(b > 0, errorMessage);
            return a % b;
        }
    }
}


contract VcgERC721Token is IVcgERC721Token, ERC721Enumerable, Ownable {
  using Strings for string;
  using SafeMath for *;

  string private _baseTokenURI;
  string constant private _NFT_NAME = "Vault by 500px's NFT";
  string constant private _NFT_SYMBOL = "NFT@Vault by 500px";

  constructor() ERC721(_NFT_NAME, _NFT_SYMBOL) {
    _baseTokenURI = "https://vault.world/nft/721/";
  }

  /**
    * @dev Mints a token to an address with a tokenURI.
    * @param to address of the future owner of the token
    */
  function mintTo(address to) public onlyOwner returns (uint256){
    uint256 newTokenId = _getNextTokenId();
    _mint(to, newTokenId);
    //2021-10-08 , return New TokenID
    return newTokenId;
  }

  /**
    * @dev calculates the next token ID based on _currentTokenId
    * @return uint256 for the next token ID
    */
  function _getNextTokenId() /**private**/internal view returns (uint256) {
     return totalSupply().add(1);
  }


  /**
    * @dev get getBaseTokenURI
    * @return string of _baseTokenURI
    */
  function getBaseTokenURI() public view override returns (string memory) {
    return _baseTokenURI;
  }

  /**
    * @dev setBaseTokenURI
    * @param url string of baseTokenURI
    */
  function setBaseTokenURI(string memory url) public override onlyOwner() {
    _baseTokenURI = url;
  }  

  /**
    * @dev get baseTokenURI
    * @param tokenId uint256 ID of the token to query
    * @return string of TokenURI
    */
  function tokenURI(uint256 tokenId) override(IVcgERC721Token, ERC721) virtual public view returns (string memory) {
        return string(abi.encodePacked(_baseTokenURI, Strings.toString(tokenId)));
  }

  /**
    * @dev See {IERC165-supportsInterface}.
    * @param interfaceId qeSelector
    */
  function supportsInterface(bytes4 interfaceId) public view override(IERC165, ERC721Enumerable) returns (bool) {
      return interfaceId == type(IVcgERC721Token).interfaceId || super.supportsInterface(interfaceId);
  }  


  function isVcgNftToken(address tokenAddress) public view override(IVcgERC721Token)returns(bool) {
      if( !Address.isContract(tokenAddress) ) 
      {
        return false;
      }
    
      bool result = false;
      string memory name = VcgERC721Token(tokenAddress).name();
      string memory symbol = VcgERC721Token(tokenAddress).symbol();   
      
      result = (keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked(_NFT_NAME))) 
            && (keccak256(abi.encodePacked(symbol)) == keccak256(abi.encodePacked(_NFT_SYMBOL))) 
            && (supportsInterface(type(IVcgERC721Token).interfaceId) );
           
      return result;
  }

  function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) {
    if(!_exists(tokenId) || (address(0) == spender))
    {
      return(false);      
    }

    return super._isApprovedOrOwner(spender, tokenId);
  }  

  function exists(uint256 tokenId) external view override returns (bool) {
    
    return(_exists(tokenId));    
  }
}  

//pragma solidity ^0.6.0;

/**
 * @dev Implementation of royalties for 721s
 * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2981.md
 */
interface IERC2981 {
    // ERC165 bytes to add to interface array - set in parent contract
    // implementing this standard
    //
    // bytes4(keccak256("royaltyInfo(uint256)")) == 0xcef6d368
    // bytes4(keccak256("onRoyaltiesReceived(address,address,uint256,address,uint256,bytes32)")) == 0xe8cb9d99
    // bytes4(0xcef6d368) ^ bytes4(0xe8cb9d99) == 0x263d4ef1
    // bytes4 private constant _INTERFACE_ID_ERC721ROYALTIES = 0x263d4ef1;
    // _registerInterface(_INTERFACE_ID_ERC721ROYALTIES);

    // @notice Called to return both the creator's address and the royalty percentage
    // @param _tokenId - the NFT asset queried for royalty information
    // @return receiver - address of who should be sent the royalty payment
    // @return amount - a percentage calculated as a fixed point
    //         with a scaling factor of 100000 (5 decimals), such that
    //         100% would be the value 10000000, as 10000000/100000 = 100.
    //         1% would be the value 100000, as 100000/100000 = 1
    function royaltyInfo(uint256 _tokenId) external view 
    returns (address receiver, uint256 amount);

    /// @notice Called with the sale price to determine how much royalty
    //          is owed and to whom.
    /// @param _tokenId - the NFT asset queried for royalty information
    /// @param _salePrice - the sale price of the NFT asset specified by _tokenId
    /// @return receiver - address of who should be sent the royalty payment
    /// @return royaltyAmount - the royalty payment amount for _salePrice
    function royaltyInfo(
        uint256 _tokenId,
        uint256 _salePrice
    ) external view returns (
        address receiver,
        uint256 royaltyAmount
    );


    // @notice Called when royalty is transferred to the receiver. This
    //         emits the RoyaltiesReceived event as we want the NFT contract
    //         itself to contain the event for easy tracking by royalty receivers.
    // @param _royaltyRecipient - The address of who is entitled to the
    //                            royalties as specified by royaltyInfo().
    // @param _buyer - If known, the address buying the NFT on a secondary
    //                 sale. 0x0 if not known.
    // @param _tokenId - the ID of the ERC-721 token that was sold
    // @param _tokenPaid - The address of the ERC-20 token used to pay the
    //                     royalty fee amount. Set to 0x0 if paid in the
    //                     native asset (ETH).
    // @param _amount - The amount being paid to the creator using the
    //                  correct decimals from _tokenPaid's ERC-20 contract
    //                  (i.e. if 7 decimals, 10000000 for 1 token paid)
    // @param _metadata - Arbitrary data attached to this payment
    // @return `bytes4(keccak256("onRoyaltiesReceived(address,address,uint256,address,uint256,bytes32)"))`
    function onRoyaltiesReceived(address _royaltyRecipient, address _buyer, uint256 _tokenId, address _tokenPaid, uint256 _amount, bytes32 _metadata) external returns (bytes4);

    // @dev This event MUST be emitted by `onRoyaltiesReceived()`.
    event RoyaltiesReceived(
        address indexed _royaltyRecipient,
        address indexed _buyer,
        uint256 indexed _tokenId,
        address _tokenPaid,
        uint256 _amount,
        bytes32 _metadata
    );

}

interface IVcgERC721TokenWithRoyalty is IVcgERC721Token,IERC2981 {
    
}
/**
 * @title VcgERC721TokenWithRoyalty
 * 
 */
contract VcgERC721TokenWithRoyalty is IVcgERC721TokenWithRoyalty,VcgERC721Token{

    struct CreatorRight{
        address creator;
        uint32 royalty;
    }
    uint256 public _scaling_factor = 100000;//5 decimals
    event CreatorChanged(uint256 indexed _id, address indexed _creator);
    event DefultRoyaltyChanged(uint256 _royalty);

    // Mapping from Token ID to Creater whith royalty rate.
    mapping(uint256 => CreatorRight) private _royaltyInfos;

    modifier creatorOnly(uint256 _tokenId) {
        require(
            _royaltyInfos[_tokenId].creator == msg.sender, 
            "MintTLToken: ONLY_CREATOR_ALLOWED"
        );
        _;
    }