// Vulnerability label: TO1
{{
  "language": "Solidity",
  "sources": {
    "KongISland.sol": {
      "content": "// SPDX-License-Identifier: MIT\r\n\r\npragma solidity ^0.8.0;\r\n\r\nlibrary Address {\r\n    /**\r\n     * @dev Returns true if `account` is a contract.\r\n     *\r\n     * [IMPORTANT]\r\n     * ====\r\n     * It is unsafe to assume that an address for which this function returns\r\n     * false is an externally-owned account (EOA) and not a contract.\r\n     *\r\n     * Among others, `isContract` will return false for the following\r\n     * types of addresses:\r\n     *\r\n     *  - an externally-owned account\r\n     *  - a contract in construction\r\n     *  - an address where a contract will be created\r\n     *  - an address where a contract lived, but was destroyed\r\n     * ====\r\n     */\r\n    function isContract(address account) internal view returns (bool) {\r\n        // This method relies on extcodesize, which returns 0 for contracts in\r\n        // construction, since the code is only stored at the end of the\r\n        // constructor execution.\r\n\r\n        uint256 size;\r\n        assembly {\r\n            size := extcodesize(account)\r\n        }\r\n        return size > 0;\r\n    }\r\n\r\n    /**\r\n     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\r\n     * `recipient`, forwarding all available gas and reverting on errors.\r\n     *\r\n     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\r\n     * of certain opcodes, possibly making contracts go over the 2300 gas limit\r\n     * imposed by `transfer`, making them unable to receive funds via\r\n     * `transfer`. {sendValue} removes this limitation.\r\n     *\r\n     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\r\n     *\r\n     * IMPORTANT: because control is transferred to `recipient`, care must be\r\n     * taken to not create reentrancy vulnerabilities. Consider using\r\n     * {ReentrancyGuard} or the\r\n     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\r\n     */\r\n    function sendValue(address payable recipient, uint256 amount) internal {\r\n        require(address(this).balance >= amount, \"Address: insufficient balance\");\r\n\r\n        (bool success, ) = recipient.call{value: amount}(\"\");\r\n        require(success, \"Address: unable to send value, recipient may have reverted\");\r\n    }\r\n\r\n    /**\r\n     * @dev Performs a Solidity function call using a low level `call`. A\r\n     * plain `call` is an unsafe replacement for a function call: use this\r\n     * function instead.\r\n     *\r\n     * If `target` reverts with a revert reason, it is bubbled up by this\r\n     * function (like regular Solidity function calls).\r\n     *\r\n     * Returns the raw returned data. To convert to the expected return value,\r\n     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `target` must be a contract.\r\n     * - calling `target` with `data` must not revert.\r\n     *\r\n     * _Available since v3.1._\r\n     */\r\n    function functionCall(address target, bytes memory data) internal returns (bytes memory) {\r\n        return functionCall(target, data, \"Address: low-level call failed\");\r\n    }\r\n\r\n    /**\r\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\r\n     * `errorMessage` as a fallback revert reason when `target` reverts.\r\n     *\r\n     * _Available since v3.1._\r\n     */\r\n    function functionCall(\r\n        address target,\r\n        bytes memory data,\r\n        string memory errorMessage\r\n    ) internal returns (bytes memory) {\r\n        return functionCallWithValue(target, data, 0, errorMessage);\r\n    }\r\n\r\n    /**\r\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\r\n     * but also transferring `value` wei to `target`.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - the calling contract must have an ETH balance of at least `value`.\r\n     * - the called Solidity function must be `payable`.\r\n     *\r\n     * _Available since v3.1._\r\n     */\r\n    function functionCallWithValue(\r\n        address target,\r\n        bytes memory data,\r\n        uint256 value\r\n    ) internal returns (bytes memory) {\r\n        return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\r\n    }\r\n\r\n    /**\r\n     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\r\n     * with `errorMessage` as a fallback revert reason when `target` reverts.\r\n     *\r\n     * _Available since v3.1._\r\n     */\r\n    function functionCallWithValue(\r\n        address target,\r\n        bytes memory data,\r\n        uint256 value,\r\n        string memory errorMessage\r\n    ) internal returns (bytes memory) {\r\n        require(address(this).balance >= value, \"Address: insufficient balance for call\");\r\n        require(isContract(target), \"Address: call to non-contract\");\r\n\r\n        (bool success, bytes memory returndata) = target.call{value: value}(data);\r\n        return verifyCallResult(success, returndata, errorMessage);\r\n    }\r\n\r\n    /**\r\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\r\n     * but performing a static call.\r\n     *\r\n     * _Available since v3.3._\r\n     */\r\n    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\r\n        return functionStaticCall(target, data, \"Address: low-level static call failed\");\r\n    }\r\n\r\n    /**\r\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\r\n     * but performing a static call.\r\n     *\r\n     * _Available since v3.3._\r\n     */\r\n    function functionStaticCall(\r\n        address target,\r\n        bytes memory data,\r\n        string memory errorMessage\r\n    ) internal view returns (bytes memory) {\r\n        require(isContract(target), \"Address: static call to non-contract\");\r\n\r\n        (bool success, bytes memory returndata) = target.staticcall(data);\r\n        return verifyCallResult(success, returndata, errorMessage);\r\n    }\r\n\r\n    /**\r\n     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\r\n     * but performing a delegate call.\r\n     *\r\n     * _Available since v3.4._\r\n     */\r\n    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\r\n        return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\r\n    }\r\n\r\n    /**\r\n     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\r\n     * but performing a delegate call.\r\n     *\r\n     * _Available since v3.4._\r\n     */\r\n    function functionDelegateCall(\r\n        address target,\r\n        bytes memory data,\r\n        string memory errorMessage\r\n    ) internal returns (bytes memory) {\r\n        require(isContract(target), \"Address: delegate call to non-contract\");\r\n\r\n        (bool success, bytes memory returndata) = target.delegatecall(data);\r\n        return verifyCallResult(success, returndata, errorMessage);\r\n    }\r\n\r\n    /**\r\n     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\r\n     * revert reason using the provided one.\r\n     *\r\n     * _Available since v4.3._\r\n     */\r\n    function verifyCallResult(\r\n        bool success,\r\n        bytes memory returndata,\r\n        string memory errorMessage\r\n    ) internal pure returns (bytes memory) {\r\n        if (success) {\r\n            return returndata;\r\n        } else {\r\n            // Look for revert reason and bubble it up if present\r\n            if (returndata.length > 0) {\r\n                // The easiest way to bubble the revert reason is using memory via assembly\r\n\r\n                assembly {\r\n                    let returndata_size := mload(returndata)\r\n                    revert(add(32, returndata), returndata_size)\r\n                }\r\n            } else {\r\n                revert(errorMessage);\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\nabstract contract Context {\r\n    function _msgSender() internal view virtual returns (address) {\r\n        return msg.sender;\r\n    }\r\n\r\n    function _msgData() internal view virtual returns (bytes calldata) {\r\n        return msg.data;\r\n    }\r\n}\r\n\r\ninterface IKongIsland {\r\n  function addManyToKongIslandAndPack(address account, uint16[] calldata tokenIds) external;\r\n  function randomKongOwner(uint256 seed) external view returns (address);\r\n}\r\n\r\ninterface IFOOD{\r\n    function burn(address account, uint256 amount) external;\r\n    function mint(address account, uint256 amount) external;\r\n}\r\n\r\ninterface IERC165 {\r\n    /**\r\n     * @dev Returns true if this contract implements the interface defined by\r\n     * `interfaceId`. See the corresponding\r\n     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\r\n     * to learn more about how these ids are created.\r\n     *\r\n     * This function call must use less than 30 000 gas.\r\n     */\r\n    function supportsInterface(bytes4 interfaceId) external view returns (bool);\r\n}\r\n\r\ninterface IERC721Receiver {\r\n    /**\r\n     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\r\n     * by `operator` from `from`, this function is called.\r\n     *\r\n     * It must return its Solidity selector to confirm the token transfer.\r\n     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\r\n     *\r\n     * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.\r\n     */\r\n    function onERC721Received(\r\n        address operator,\r\n        address from,\r\n        uint256 tokenId,\r\n        bytes calldata data\r\n    ) external returns (bytes4);\r\n}\r\n\r\ninterface ITraits {\r\n  function tokenURI(uint256 tokenId) external view returns (string memory);\r\n}\r\n\r\ninterface IKONGS {\r\n\r\n  // struct to store each token's traits\r\n    struct KaijuKong {\r\n        bool isKaiju;\r\n        uint8 background;\r\n        uint8 species;\r\n        uint8 companion;\r\n        uint8 fur;\r\n        uint8 hat;\r\n        uint8 face;\r\n        uint8 weapons;\r\n        uint8 accessories;        \r\n        uint8 kingScore;\r\n    }\r\n\r\n\r\n  function getPaidTokens() external view returns (uint256);\r\n  function getTokenTraits(uint256 tokenId) external view returns (KaijuKong memory);\r\n}\r\n\r\nabstract contract Ownable is Context {\r\n    address private _owner;\r\n\r\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\r\n\r\n    /**\r\n     * @dev Initializes the contract setting the deployer as the initial owner.\r\n     */\r\n    constructor() {\r\n        _setOwner(_msgSender());\r\n    }\r\n\r\n    /**\r\n     * @dev Returns the address of the current owner.\r\n     */\r\n    function owner() public view virtual returns (address) {\r\n        return _owner;\r\n    }\r\n\r\n    /**\r\n     * @dev Throws if called by any account other than the owner.\r\n     */\r\n    modifier onlyOwner() {\r\n        require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\r\n        _;\r\n    }\r\n\r\n    /**\r\n     * @dev Leaves the contract without owner. It will not be possible to call\r\n     * `onlyOwner` functions anymore. Can only be called by the current owner.\r\n     *\r\n     * NOTE: Renouncing ownership will leave the contract without an owner,\r\n     * thereby removing any functionality that is only available to the owner.\r\n     */\r\n    function renounceOwnership() public virtual onlyOwner {\r\n        _setOwner(address(0));\r\n    }\r\n\r\n    /**\r\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\r\n     * Can only be called by the current owner.\r\n     */\r\n    function transferOwnership(address newOwner) public virtual onlyOwner {\r\n        require(newOwner != address(0), \"Ownable: new owner is the zero address\");\r\n        _setOwner(newOwner);\r\n    }\r\n\r\n    function _setOwner(address newOwner) private {\r\n        address oldOwner = _owner;\r\n        _owner = newOwner;\r\n        emit OwnershipTransferred(oldOwner, newOwner);\r\n    }\r\n}\r\n\r\nlibrary Strings {\r\n    bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\r\n\r\n    /**\r\n     * @dev Converts a `uint256` to its ASCII `string` decimal representation.\r\n     */\r\n    function toString(uint256 value) internal pure returns (string memory) {\r\n        // Inspired by OraclizeAPI's implementation - MIT licence\r\n        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\r\n\r\n        if (value == 0) {\r\n            return \"0\";\r\n        }\r\n        uint256 temp = value;\r\n        uint256 digits;\r\n        while (temp != 0) {\r\n            digits++;\r\n            temp /= 10;\r\n        }\r\n        bytes memory buffer = new bytes(digits);\r\n        while (value != 0) {\r\n            digits -= 1;\r\n            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\r\n            value /= 10;\r\n        }\r\n        return string(buffer);\r\n    }\r\n\r\n    /**\r\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\r\n     */\r\n    function toHexString(uint256 value) internal pure returns (string memory) {\r\n        if (value == 0) {\r\n            return \"0x00\";\r\n        }\r\n        uint256 temp = value;\r\n        uint256 length = 0;\r\n        while (temp != 0) {\r\n            length++;\r\n            temp >>= 8;\r\n        }\r\n        return toHexString(value, length);\r\n    }\r\n\r\n    /**\r\n     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\r\n     */\r\n    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\r\n        bytes memory buffer = new bytes(2 * length + 2);\r\n        buffer[0] = \"0\";\r\n        buffer[1] = \"x\";\r\n        for (uint256 i = 2 * length + 1; i > 1; --i) {\r\n            buffer[i] = _HEX_SYMBOLS[value & 0xf];\r\n            value >>= 4;\r\n        }\r\n        require(value == 0, \"Strings: hex length insufficient\");\r\n        return string(buffer);\r\n    }\r\n}\r\n\r\nabstract contract Pausable is Context {\r\n    /**\r\n     * @dev Emitted when the pause is triggered by `account`.\r\n     */\r\n    event Paused(address account);\r\n\r\n    /**\r\n     * @dev Emitted when the pause is lifted by `account`.\r\n     */\r\n    event Unpaused(address account);\r\n\r\n    bool private _paused;\r\n\r\n    /**\r\n     * @dev Initializes the contract in unpaused state.\r\n     */\r\n    constructor() {\r\n        _paused = false;\r\n    }\r\n\r\n    /**\r\n     * @dev Returns true if the contract is paused, and false otherwise.\r\n     */\r\n    function paused() public view virtual returns (bool) {\r\n        return _paused;\r\n    }\r\n\r\n    /**\r\n     * @dev Modifier to make a function callable only when the contract is not paused.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - The contract must not be paused.\r\n     */\r\n    modifier whenNotPaused() {\r\n        require(!paused(), \"Pausable: paused\");\r\n        _;\r\n    }\r\n\r\n    /**\r\n     * @dev Modifier to make a function callable only when the contract is paused.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - The contract must be paused.\r\n     */\r\n    modifier whenPaused() {\r\n        require(paused(), \"Pausable: not paused\");\r\n        _;\r\n    }\r\n\r\n    /**\r\n     * @dev Triggers stopped state.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - The contract must not be paused.\r\n     */\r\n    function _pause() internal virtual whenNotPaused {\r\n        _paused = true;\r\n        emit Paused(_msgSender());\r\n    }\r\n\r\n    /**\r\n     * @dev Returns to normal state.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - The contract must be paused.\r\n     */\r\n    function _unpause() internal virtual whenPaused {\r\n        _paused = false;\r\n        emit Unpaused(_msgSender());\r\n    }\r\n}\r\n\r\nabstract contract ERC165 is IERC165 {\r\n    /**\r\n     * @dev See {IERC165-supportsInterface}.\r\n     */\r\n    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\r\n        return interfaceId == type(IERC165).interfaceId;\r\n    }\r\n}\r\n\r\ninterface IERC721 is IERC165 {\r\n    /**\r\n     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\r\n     */\r\n    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\r\n\r\n    /**\r\n     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\r\n     */\r\n    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\r\n\r\n    /**\r\n     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\r\n     */\r\n    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\r\n\r\n    /**\r\n     * @dev Returns the number of tokens in ``owner``'s account.\r\n     */\r\n    function balanceOf(address owner) external view returns (uint256 balance);\r\n\r\n    /**\r\n     * @dev Returns the owner of the `tokenId` token.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `tokenId` must exist.\r\n     */\r\n    function ownerOf(uint256 tokenId) external view returns (address owner);\r\n\r\n    /**\r\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\r\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `from` cannot be the zero address.\r\n     * - `to` cannot be the zero address.\r\n     * - `tokenId` token must exist and be owned by `from`.\r\n     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.\r\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n     *\r\n     * Emits a {Transfer} event.\r\n     */\r\n    function safeTransferFrom(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId\r\n    ) external;\r\n\r\n    /**\r\n     * @dev Transfers `tokenId` token from `from` to `to`.\r\n     *\r\n     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `from` cannot be the zero address.\r\n     * - `to` cannot be the zero address.\r\n     * - `tokenId` token must be owned by `from`.\r\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\r\n     *\r\n     * Emits a {Transfer} event.\r\n     */\r\n    function transferFrom(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId\r\n    ) external;\r\n\r\n    /**\r\n     * @dev Gives permission to `to` to transfer `tokenId` token to another account.\r\n     * The approval is cleared when the token is transferred.\r\n     *\r\n     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - The caller must own the token or be an approved operator.\r\n     * - `tokenId` must exist.\r\n     *\r\n     * Emits an {Approval} event.\r\n     */\r\n    function approve(address to, uint256 tokenId) external;\r\n\r\n    /**\r\n     * @dev Returns the account approved for `tokenId` token.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `tokenId` must exist.\r\n     */\r\n    function getApproved(uint256 tokenId) external view returns (address operator);\r\n\r\n    /**\r\n     * @dev Approve or remove `operator` as an operator for the caller.\r\n     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - The `operator` cannot be the caller.\r\n     *\r\n     * Emits an {ApprovalForAll} event.\r\n     */\r\n    function setApprovalForAll(address operator, bool _approved) external;\r\n\r\n    /**\r\n     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\r\n     *\r\n     * See {setApprovalForAll}\r\n     */\r\n    function isApprovedForAll(address owner, address operator) external view returns (bool);\r\n\r\n    /**\r\n     * @dev Safely transfers `tokenId` token from `from` to `to`.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `from` cannot be the zero address.\r\n     * - `to` cannot be the zero address.\r\n     * - `tokenId` token must exist and be owned by `from`.\r\n     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\r\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n     *\r\n     * Emits a {Transfer} event.\r\n     */\r\n    function safeTransferFrom(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId,\r\n        bytes calldata data\r\n    ) external;\r\n}\r\n\r\n\r\ninterface IERC721Enumerable is IERC721 {\r\n    /**\r\n     * @dev Returns the total amount of tokens stored by the contract.\r\n     */\r\n    function totalSupply() external view returns (uint256);\r\n\r\n    /**\r\n     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.\r\n     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.\r\n     */\r\n    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);\r\n\r\n    /**\r\n     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.\r\n     * Use along with {totalSupply} to enumerate all tokens.\r\n     */\r\n    function tokenByIndex(uint256 index) external view returns (uint256);\r\n}\r\n\r\ninterface IERC721Metadata is IERC721 {\r\n    /**\r\n     * @dev Returns the token collection name.\r\n     */\r\n    function name() external view returns (string memory);\r\n\r\n    /**\r\n     * @dev Returns the token collection symbol.\r\n     */\r\n    function symbol() external view returns (string memory);\r\n\r\n    /**\r\n     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\r\n     */\r\n    function tokenURI(uint256 tokenId) external view returns (string memory);\r\n}\r\n\r\ncontract Traits is Ownable, ITraits {\r\n\r\n  using Strings for uint256;\r\n\r\n  // struct to store each trait's data for metadata and rendering\r\n  struct Trait {\r\n    string name;\r\n    string png;\r\n  }\r\n\r\n  // mapping from trait type (index) to its name\r\n  string[9] _traitTypes = [\r\n    \"Background\",\r\n    \"Species\",\r\n\t\"Companion\",\r\n    \"Fur\",\r\n    \"Hat\",\r\n    \"Face\",\r\n    \"Weapons\",\r\n    \"Accessories\",\r\n    \"King Score\"\r\n  ];\r\n  // storage of each traits name and base64 PNG data\r\n  mapping(uint8 => mapping(uint8 => Trait)) public traitData;\r\n  // mapping from KingScore to its score\r\n  string[6] _KingScore = [\r\n    \"8\",\r\n    \"8\",\r\n    \"8\",\r\n    \"7\",\r\n    \"6\",\r\n    \"5\"\r\n  ];\r\n\r\n  IKONGS public kongs;\r\n\r\n  constructor() {}\r\n\r\n  /** ADMIN */\r\n\r\n  function setKONGS(address _KONGS) external onlyOwner {\r\n    kongs = IKONGS(_KONGS);\r\n  }\r\n\r\n  /**\r\n   * administrative to upload the names and images associated with each trait\r\n   * @param traitType the trait type to upload the traits for (see traitTypes for a mapping)\r\n   * @param traits the names and base64 encoded PNGs for each trait\r\n   */\r\n  function uploadTraits(uint8 traitType, uint8[] calldata traitIds, Trait[] calldata traits) external onlyOwner {\r\n    require(traitIds.length == traits.length, \"Mismatched inputs\");\r\n    for (uint i = 0; i < traits.length; i++) {\r\n      traitData[traitType][traitIds[i]] = Trait(\r\n        traits[i].name,\r\n        traits[i].png\r\n      );\r\n    }\r\n  }\r\n\r\n  /** RENDER */\r\n\r\n  /**\r\n   * generates an <image> element using base64 encoded PNGs\r\n   * @param trait the trait storing the PNG data\r\n   * @return the <image> element\r\n   */\r\n  function drawTrait(Trait memory trait) internal pure returns (string memory) {\r\n    return string(abi.encodePacked(\r\n      '<image x=\"4\" y=\"4\" width=\"32\" height=\"32\" image-rendering=\"pixelated\" preserveAspectRatio=\"xMidYMid\" xlink:href=\"data:image/png;base64,',\r\n      trait.png,\r\n      '\"/>'\r\n    ));\r\n  }\r\n\r\n  /**\r\n   * generates an entire SVG by composing multiple <image> elements of PNGs\r\n   * @param tokenId the ID of the token to generate an SVG for\r\n   * @return a valid SVG of the Kaiju / Kong\r\n   */\r\n  function drawSVG(uint256 tokenId) public view returns (string memory) {\r\n    IKONGS.KaijuKong memory s = kongs.getTokenTraits(tokenId);\r\n    uint8 shift = s.isKaiju ? 0 : 9;\r\n\r\n    string memory svgString = string(abi.encodePacked(\r\n      drawTrait(traitData[0][s.background]),\r\n      s.isKaiju ? drawTrait(traitData[1 + shift][s.species]) : '',\r\n      s.isKaiju ? drawTrait(traitData[2 + shift][s.companion]) : '',\r\n      s.isKaiju ? '' : drawTrait(traitData[4 + shift][s.kingScore]),\r\n      s.isKaiju ? '' : drawTrait(traitData[5 + shift][s.hat]),\r\n      s.isKaiju ? '' : drawTrait(traitData[6 + shift][s.face]),\r\n\t  s.isKaiju ? '' : drawTrait(traitData[7 + shift][s.weapons]),\r\n\t  s.isKaiju ? '' : drawTrait(traitData[8 + shift][s.accessories])\r\n    ));\r\n\r\n    return string(abi.encodePacked(\r\n      '<svg id=\"woolf\" width=\"100%\" height=\"100%\" version=\"1.1\" viewBox=\"0 0 40 40\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">',\r\n      svgString,\r\n      \"</svg>\"\r\n    ));\r\n  }\r\n\r\n  /**\r\n   * generates an attribute for the attributes array in the ERC721 metadata standard\r\n   * @param traitType the trait type to reference as the metadata key\r\n   * @param value the token's trait associated with the key\r\n   * @return a JSON dictionary for the single attribute\r\n   */\r\n  function attributeForTypeAndValue(string memory traitType, string memory value) internal pure returns (string memory) {\r\n    return string(abi.encodePacked(\r\n      '{\"trait_type\":\"',\r\n      traitType,\r\n      '\",\"value\":\"',\r\n      value,\r\n      '\"}'\r\n    ));\r\n  }\r\n\r\n  /**\r\n   * generates an array composed of all the individual traits and values\r\n   * @param tokenId the ID of the token to compose the metadata for\r\n   * @return a JSON array of all of the attributes for given token ID\r\n   */\r\n  function compileAttributes(uint256 tokenId) public view returns (string memory) {\r\n    IKONGS.KaijuKong memory s = kongs.getTokenTraits(tokenId);\r\n    string memory traits;\r\n    if (s.isKaiju) {\r\n      traits = string(abi.encodePacked(\r\n        attributeForTypeAndValue(_traitTypes[0], traitData[0][s.background].name),',',\r\n        attributeForTypeAndValue(_traitTypes[1], traitData[1][s.species].name),',',\r\n        attributeForTypeAndValue(_traitTypes[2], traitData[2][s.companion].name),','\r\n      ));\r\n    } else {\r\n      traits = string(abi.encodePacked(\r\n        attributeForTypeAndValue(_traitTypes[0], traitData[0][s.background].name),',',\r\n        attributeForTypeAndValue(_traitTypes[3], traitData[13][s.kingScore].name),',',\r\n        attributeForTypeAndValue(_traitTypes[4], traitData[14][s.hat].name),',',\r\n        attributeForTypeAndValue(_traitTypes[5], traitData[15][s.face].name),',',\r\n        attributeForTypeAndValue(_traitTypes[6], traitData[16][s.weapons].name),',',\r\n\t\tattributeForTypeAndValue(_traitTypes[7], traitData[17][s.accessories].name),',',\r\n        attributeForTypeAndValue(\"King Score\", _KingScore[s.kingScore]),','\r\n      ));\r\n    }\r\n    return string(abi.encodePacked(\r\n      '[',\r\n      traits,\r\n      '{\"trait_type\":\"Generation\",\"value\":',\r\n      tokenId <= kongs.getPaidTokens() ? '\"Gen 0\"' : '\"Gen 1\"',\r\n      '},{\"trait_type\":\"Type\",\"value\":',\r\n      s.isKaiju ? '\"Kaiju\"' : '\"Kong\"',\r\n      '}]'\r\n    ));\r\n  }\r\n\r\n  /**\r\n   * generates a base64 encoded metadata response without referencing off-chain content\r\n   * @param tokenId the ID of the token to generate the metadata for\r\n   * @return a base64 encoded JSON dictionary of the token's metadata and SVG\r\n   */\r\n  function tokenURI(uint256 tokenId) public view override returns (string memory) {\r\n    IKONGS.KaijuKong memory s = kongs.getTokenTraits(tokenId);\r\n\r\n    string memory metadata = string(abi.encodePacked(\r\n      '{\"name\": \"',\r\n      s.isKaiju ? 'Kaiju #' : 'Kong #',\r\n      tokenId.toString(),\r\n      '\", \"description\": \"Thousands of Kaiju and Wolves compete on Kong Island. A tempting prize of $FOOD awaits, with deadly high stakes. All the metadata and images are generated and stored 100% on-chain. No IPFS. NO API. Just the Ethereum blockchain.\", \"image\": \"data:image/svg+xml;base64,',\r\n      base64(bytes(drawSVG(tokenId))),\r\n      '\", \"attributes\":',\r\n      compileAttributes(tokenId),\r\n      \"}\"\r\n    ));\r\n\r\n    return string(abi.encodePacked(\r\n      \"data:application/json;base64,\",\r\n      base64(bytes(metadata))\r\n    ));\r\n  }\r\n\r\n  /** BASE 64 - Written by Brech Devos */\r\n  \r\n  string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\r\n\r\n  function base64(bytes memory data) internal pure returns (string memory) {\r\n    if (data.length == 0) return '';\r\n    \r\n    // load the table into memory\r\n    string memory table = TABLE;\r\n\r\n    // multiply by 4/3 rounded up\r\n    uint256 encodedLen = 4 * ((data.length + 2) / 3);\r\n\r\n    // add some extra buffer at the end required for the writing\r\n    string memory result = new string(encodedLen + 32);\r\n\r\n    assembly {\r\n      // set the actual output length\r\n      mstore(result, encodedLen)\r\n      \r\n      // prepare the lookup table\r\n      let tablePtr := add(table, 1)\r\n      \r\n      // input ptr\r\n      let dataPtr := data\r\n      let endPtr := add(dataPtr, mload(data))\r\n      \r\n      // result ptr, jump over length\r\n      let resultPtr := add(result, 32)\r\n      \r\n      // run over the input, 3 bytes at a time\r\n      for {} lt(dataPtr, endPtr) {}\r\n      {\r\n          dataPtr := add(dataPtr, 3)\r\n          \r\n          // read 3 bytes\r\n          let input := mload(dataPtr)\r\n          \r\n          // write 4 characters\r\n          mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))\r\n          resultPtr := add(resultPtr, 1)\r\n          mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))\r\n          resultPtr := add(resultPtr, 1)\r\n          mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))\r\n          resultPtr := add(resultPtr, 1)\r\n          mstore(resultPtr, shl(248, mload(add(tablePtr, and(        input,  0x3F)))))\r\n          resultPtr := add(resultPtr, 1)\r\n      }\r\n      \r\n      // padding with '='\r\n      switch mod(mload(data), 3)\r\n      case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }\r\n      case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }\r\n    }\r\n    \r\n    return result;\r\n  }\r\n}\r\n\r\ncontract ERC721 is Context, ERC165, IERC721, IERC721Metadata {\r\n    using Address for address;\r\n    using Strings for uint256;\r\n\r\n    // Token name\r\n    string private _name;\r\n\r\n    // Token symbol\r\n    string private _symbol;\r\n\r\n    // Mapping from token ID to owner address\r\n    mapping(uint256 => address) private _owners;\r\n\r\n    // Mapping owner address to token count\r\n    mapping(address => uint256) private _balances;\r\n\r\n    // Mapping from token ID to approved address\r\n    mapping(uint256 => address) private _tokenApprovals;\r\n\r\n    // Mapping from owner to operator approvals\r\n    mapping(address => mapping(address => bool)) private _operatorApprovals;\r\n\r\n    /**\r\n     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\r\n     */\r\n    constructor(string memory name_, string memory symbol_) {\r\n        _name = name_;\r\n        _symbol = symbol_;\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC165-supportsInterface}.\r\n     */\r\n    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {\r\n        return\r\n            interfaceId == type(IERC721).interfaceId ||\r\n            interfaceId == type(IERC721Metadata).interfaceId ||\r\n            super.supportsInterface(interfaceId);\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-balanceOf}.\r\n     */\r\n    function balanceOf(address owner) public view virtual override returns (uint256) {\r\n        require(owner != address(0), \"ERC721: balance query for the zero address\");\r\n        return _balances[owner];\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-ownerOf}.\r\n     */\r\n    function ownerOf(uint256 tokenId) public view virtual override returns (address) {\r\n        address owner = _owners[tokenId];\r\n        require(owner != address(0), \"ERC721: owner query for nonexistent token\");\r\n        return owner;\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721Metadata-name}.\r\n     */\r\n    function name() public view virtual override returns (string memory) {\r\n        return _name;\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721Metadata-symbol}.\r\n     */\r\n    function symbol() public view virtual override returns (string memory) {\r\n        return _symbol;\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721Metadata-tokenURI}.\r\n     */\r\n    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\r\n        require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n\r\n        string memory baseURI = _baseURI();\r\n        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\r\n    }\r\n\r\n    /**\r\n     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\r\n     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\r\n     * by default, can be overriden in child contracts.\r\n     */\r\n    function _baseURI() internal view virtual returns (string memory) {\r\n        return \"\";\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-approve}.\r\n     */\r\n    function approve(address to, uint256 tokenId) public virtual override {\r\n        address owner = ERC721.ownerOf(tokenId);\r\n        require(to != owner, \"ERC721: approval to current owner\");\r\n\r\n        require(\r\n            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\r\n            \"ERC721: approve caller is not owner nor approved for all\"\r\n        );\r\n\r\n        _approve(to, tokenId);\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-getApproved}.\r\n     */\r\n    function getApproved(uint256 tokenId) public view virtual override returns (address) {\r\n        require(_exists(tokenId), \"ERC721: approved query for nonexistent token\");\r\n\r\n        return _tokenApprovals[tokenId];\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-setApprovalForAll}.\r\n     */\r\n    function setApprovalForAll(address operator, bool approved) public virtual override {\r\n        require(operator != _msgSender(), \"ERC721: approve to caller\");\r\n\r\n        _operatorApprovals[_msgSender()][operator] = approved;\r\n        emit ApprovalForAll(_msgSender(), operator, approved);\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-isApprovedForAll}.\r\n     */\r\n    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\r\n        return _operatorApprovals[owner][operator];\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-transferFrom}.\r\n     */\r\n    function transferFrom(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId\r\n    ) public virtual override {\r\n        //solhint-disable-next-line max-line-length\r\n        require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: transfer caller is not owner nor approved\");\r\n\r\n        _transfer(from, to, tokenId);\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-safeTransferFrom}.\r\n     */\r\n    function safeTransferFrom(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId\r\n    ) public virtual override {\r\n        safeTransferFrom(from, to, tokenId, \"\");\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721-safeTransferFrom}.\r\n     */\r\n    function safeTransferFrom(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId,\r\n        bytes memory _data\r\n    ) public virtual override {\r\n        require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: transfer caller is not owner nor approved\");\r\n        _safeTransfer(from, to, tokenId, _data);\r\n    }\r\n\r\n    /**\r\n     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\r\n     * are aware of the ERC721 protocol to prevent tokens from being forever locked.\r\n     *\r\n     * `_data` is additional data, it has no specified format and it is sent in call to `to`.\r\n     *\r\n     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\r\n     * implement alternative mechanisms to perform token transfer, such as signature-based.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `from` cannot be the zero address.\r\n     * - `to` cannot be the zero address.\r\n     * - `tokenId` token must exist and be owned by `from`.\r\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n     *\r\n     * Emits a {Transfer} event.\r\n     */\r\n    function _safeTransfer(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId,\r\n        bytes memory _data\r\n    ) internal virtual {\r\n        _transfer(from, to, tokenId);\r\n        require(_checkOnERC721Received(from, to, tokenId, _data), \"ERC721: transfer to non ERC721Receiver implementer\");\r\n    }\r\n\r\n    /**\r\n     * @dev Returns whether `tokenId` exists.\r\n     *\r\n     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\r\n     *\r\n     * Tokens start existing when they are minted (`_mint`),\r\n     * and stop existing when they are burned (`_burn`).\r\n     */\r\n    function _exists(uint256 tokenId) internal view virtual returns (bool) {\r\n        return _owners[tokenId] != address(0);\r\n    }\r\n\r\n    /**\r\n     * @dev Returns whether `spender` is allowed to manage `tokenId`.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `tokenId` must exist.\r\n     */\r\n    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\r\n        require(_exists(tokenId), \"ERC721: operator query for nonexistent token\");\r\n        address owner = ERC721.ownerOf(tokenId);\r\n        return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));\r\n    }\r\n\r\n    /**\r\n     * @dev Safely mints `tokenId` and transfers it to `to`.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `tokenId` must not exist.\r\n     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\r\n     *\r\n     * Emits a {Transfer} event.\r\n     */\r\n    function _safeMint(address to, uint256 tokenId) internal virtual {\r\n        _safeMint(to, tokenId, \"\");\r\n    }\r\n\r\n    /**\r\n     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\r\n     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\r\n     */\r\n    function _safeMint(\r\n        address to,\r\n        uint256 tokenId,\r\n        bytes memory _data\r\n    ) internal virtual {\r\n        _mint(to, tokenId);\r\n        require(\r\n            _checkOnERC721Received(address(0), to, tokenId, _data),\r\n            \"ERC721: transfer to non ERC721Receiver implementer\"\r\n        );\r\n    }\r\n\r\n    /**\r\n     * @dev Mints `tokenId` and transfers it to `to`.\r\n     *\r\n     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `tokenId` must not exist.\r\n     * - `to` cannot be the zero address.\r\n     *\r\n     * Emits a {Transfer} event.\r\n     */\r\n    function _mint(address to, uint256 tokenId) internal virtual {\r\n        require(to != address(0), \"ERC721: mint to the zero address\");\r\n        require(!_exists(tokenId), \"ERC721: token already minted\");\r\n\r\n        _beforeTokenTransfer(address(0), to, tokenId);\r\n\r\n        _balances[to] += 1;\r\n        _owners[tokenId] = to;\r\n\r\n        emit Transfer(address(0), to, tokenId);\r\n    }\r\n\r\n    /**\r\n     * @dev Destroys `tokenId`.\r\n     * The approval is cleared when the token is burned.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `tokenId` must exist.\r\n     *\r\n     * Emits a {Transfer} event.\r\n     */\r\n    function _burn(uint256 tokenId) internal virtual {\r\n        address owner = ERC721.ownerOf(tokenId);\r\n\r\n        _beforeTokenTransfer(owner, address(0), tokenId);\r\n\r\n        // Clear approvals\r\n        _approve(address(0), tokenId);\r\n\r\n        _balances[owner] -= 1;\r\n        delete _owners[tokenId];\r\n\r\n        emit Transfer(owner, address(0), tokenId);\r\n    }\r\n\r\n    /**\r\n     * @dev Transfers `tokenId` from `from` to `to`.\r\n     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\r\n     *\r\n     * Requirements:\r\n     *\r\n     * - `to` cannot be the zero address.\r\n     * - `tokenId` token must be owned by `from`.\r\n     *\r\n     * Emits a {Transfer} event.\r\n     */\r\n    function _transfer(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId\r\n    ) internal virtual {\r\n        require(ERC721.ownerOf(tokenId) == from, \"ERC721: transfer of token that is not own\");\r\n        require(to != address(0), \"ERC721: transfer to the zero address\");\r\n\r\n        _beforeTokenTransfer(from, to, tokenId);\r\n\r\n        // Clear approvals from the previous owner\r\n        _approve(address(0), tokenId);\r\n\r\n        _balances[from] -= 1;\r\n        _balances[to] += 1;\r\n        _owners[tokenId] = to;\r\n\r\n        emit Transfer(from, to, tokenId);\r\n    }\r\n\r\n    /**\r\n     * @dev Approve `to` to operate on `tokenId`\r\n     *\r\n     * Emits a {Approval} event.\r\n     */\r\n    function _approve(address to, uint256 tokenId) internal virtual {\r\n        _tokenApprovals[tokenId] = to;\r\n        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);\r\n    }\r\n\r\n    /**\r\n     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\r\n     * The call is not executed if the target address is not a contract.\r\n     *\r\n     * @param from address representing the previous owner of the given token ID\r\n     * @param to target address that will receive the tokens\r\n     * @param tokenId uint256 ID of the token to be transferred\r\n     * @param _data bytes optional data to send along with the call\r\n     * @return bool whether the call correctly returned the expected magic value\r\n     */\r\n    function _checkOnERC721Received(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId,\r\n        bytes memory _data\r\n    ) private returns (bool) {\r\n        if (to.isContract()) {\r\n            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {\r\n                return retval == IERC721Receiver.onERC721Received.selector;\r\n            } catch (bytes memory reason) {\r\n                if (reason.length == 0) {\r\n                    revert(\"ERC721: transfer to non ERC721Receiver implementer\");\r\n                } else {\r\n                    assembly {\r\n                        revert(add(32, reason), mload(reason))\r\n                    }\r\n                }\r\n            }\r\n        } else {\r\n            return true;\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @dev Hook that is called before any token transfer. This includes minting\r\n     * and burning.\r\n     *\r\n     * Calling conditions:\r\n     *\r\n     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\r\n     * transferred to `to`.\r\n     * - When `from` is zero, `tokenId` will be minted for `to`.\r\n     * - When `to` is zero, ``from``'s `tokenId` will be burned.\r\n     * - `from` and `to` are never both zero.\r\n     *\r\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\r\n     */\r\n    function _beforeTokenTransfer(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId\r\n    ) internal virtual {}\r\n}\r\n\r\nabstract contract ERC721Enumerable is ERC721, IERC721Enumerable {\r\n    // Mapping from owner to list of owned token IDs\r\n    mapping(address => mapping(uint256 => uint256)) private _ownedTokens;\r\n\r\n    // Mapping from token ID to index of the owner tokens list\r\n    mapping(uint256 => uint256) private _ownedTokensIndex;\r\n\r\n    // Array with all token ids, used for enumeration\r\n    uint256[] private _allTokens;\r\n\r\n    // Mapping from token id to position in the allTokens array\r\n    mapping(uint256 => uint256) private _allTokensIndex;\r\n\r\n    /**\r\n     * @dev See {IERC165-supportsInterface}.\r\n     */\r\n    function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {\r\n        return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.\r\n     */\r\n    function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {\r\n        require(index < ERC721.balanceOf(owner), \"ERC721Enumerable: owner index out of bounds\");\r\n        return _ownedTokens[owner][index];\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721Enumerable-totalSupply}.\r\n     */\r\n    function totalSupply() public view virtual override returns (uint256) {\r\n        return _allTokens.length;\r\n    }\r\n\r\n    /**\r\n     * @dev See {IERC721Enumerable-tokenByIndex}.\r\n     */\r\n    function tokenByIndex(uint256 index) public view virtual override returns (uint256) {\r\n        require(index < ERC721Enumerable.totalSupply(), \"ERC721Enumerable: global index out of bounds\");\r\n        return _allTokens[index];\r\n    }\r\n\r\n    /**\r\n     * @dev Hook that is called before any token transfer. This includes minting\r\n     * and burning.\r\n     *\r\n     * Calling conditions:\r\n     *\r\n     * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\r\n     * transferred to `to`.\r\n     * - When `from` is zero, `tokenId` will be minted for `to`.\r\n     * - When `to` is zero, ``from``'s `tokenId` will be burned.\r\n     * - `from` cannot be the zero address.\r\n     * - `to` cannot be the zero address.\r\n     *\r\n     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\r\n     */\r\n    function _beforeTokenTransfer(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId\r\n    ) internal virtual override {\r\n        super._beforeTokenTransfer(from, to, tokenId);\r\n\r\n        if (from == address(0)) {\r\n            _addTokenToAllTokensEnumeration(tokenId);\r\n        } else if (from != to) {\r\n            _removeTokenFromOwnerEnumeration(from, tokenId);\r\n        }\r\n        if (to == address(0)) {\r\n            _removeTokenFromAllTokensEnumeration(tokenId);\r\n        } else if (to != from) {\r\n            _addTokenToOwnerEnumeration(to, tokenId);\r\n        }\r\n    }\r\n\r\n    /**\r\n     * @dev Private function to add a token to this extension's ownership-tracking data structures.\r\n     * @param to address representing the new owner of the given token ID\r\n     * @param tokenId uint256 ID of the token to be added to the tokens list of the given address\r\n     */\r\n    function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {\r\n        uint256 length = ERC721.balanceOf(to);\r\n        _ownedTokens[to][length] = tokenId;\r\n        _ownedTokensIndex[tokenId] = length;\r\n    }\r\n\r\n    /**\r\n     * @dev Private function to add a token to this extension's token tracking data structures.\r\n     * @param tokenId uint256 ID of the token to be added to the tokens list\r\n     */\r\n    function _addTokenToAllTokensEnumeration(uint256 tokenId) private {\r\n        _allTokensIndex[tokenId] = _allTokens.length;\r\n        _allTokens.push(tokenId);\r\n    }\r\n\r\n    /**\r\n     * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that\r\n     * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for\r\n     * gas optimizations e.g. when performing a transfer operation (avoiding double writes).\r\n     * This has O(1) time complexity, but alters the order of the _ownedTokens array.\r\n     * @param from address representing the previous owner of the given token ID\r\n     * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address\r\n     */\r\n    function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {\r\n        // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and\r\n        // then delete the last slot (swap and pop).\r\n\r\n        uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;\r\n        uint256 tokenIndex = _ownedTokensIndex[tokenId];\r\n\r\n        // When the token to delete is the last token, the swap operation is unnecessary\r\n        if (tokenIndex != lastTokenIndex) {\r\n            uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];\r\n\r\n            _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\r\n            _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\r\n        }\r\n\r\n        // This also deletes the contents at the last position of the array\r\n        delete _ownedTokensIndex[tokenId];\r\n        delete _ownedTokens[from][lastTokenIndex];\r\n    }\r\n\r\n    /**\r\n     * @dev Private function to remove a token from this extension's token tracking data structures.\r\n     * This has O(1) time complexity, but alters the order of the _allTokens array.\r\n     * @param tokenId uint256 ID of the token to be removed from the tokens list\r\n     */\r\n    function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {\r\n        // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and\r\n        // then delete the last slot (swap and pop).\r\n\r\n        uint256 lastTokenIndex = _allTokens.length - 1;\r\n        uint256 tokenIndex = _allTokensIndex[tokenId];\r\n\r\n        // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so\r\n        // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding\r\n        // an 'if' statement (like in _removeTokenFromOwnerEnumeration)\r\n        uint256 lastTokenId = _allTokens[lastTokenIndex];\r\n\r\n        _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token\r\n        _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index\r\n\r\n        // This also deletes the contents at the last position of the array\r\n        delete _allTokensIndex[tokenId];\r\n        _allTokens.pop();\r\n    }\r\n}\r\n\r\ncontract KONGS is IKONGS, ERC721Enumerable, Ownable, Pausable {\r\n    uint256 public MINT_PRICE = .02 ether;\r\n    uint256 public MAX_TOKENS;\r\n    uint256 public PAID_TOKENS;\r\n    uint16 public minted;\r\n    uint256 reserved;\r\n    uint256 reserveLimit;\r\n    uint256 nonReserved;\r\n\r\n    struct whitelist{\r\n        uint256 amount;\r\n        }\r\n\r\n    mapping (address => whitelist) whitelisted;\r\n    mapping (address => whitelist) reservedMinters;\r\n    bool whitelistMode;\r\n\r\n \r\n    mapping(uint256 => uint256) private mintBlock;\r\n    mapping(uint256 => KaijuKong) private tokenTraits;\r\n    mapping(uint256 => uint256) private existingCombinations;\r\n    uint8[][19] public rarities;\r\n    uint8[][19] public aliases;\r\n    // reference to the KongIsland for choosing random Kong thieves\r\n    IKongIsland public kongIsland;\r\n    // reference to $FOOD for burning on mint\r\n    IFOOD public food;\r\n    // reference to Traits\r\n    ITraits public traits;\r\n\r\n\r\n    /**\r\n     * instantiates contract and rarity tables\r\n     */\r\n    constructor(\r\n        address _food,\r\n        address _traits,\r\n        uint256 _maxTokens,\r\n        uint256 _reserved\r\n    ) ERC721(\"Kong Game\", \"KGAME\") {\r\n        food = IFOOD(_food);\r\n        traits = ITraits(_traits);\r\n        MAX_TOKENS = _maxTokens;\r\n        PAID_TOKENS = _maxTokens / 5;\r\n        nonReserved = _reserved;\r\n        reserveLimit = _reserved;\r\n        rarities[0] = [255, 229, 204,178, 153, 127, 101, 76, 50, 24];\r\n        aliases[0] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];\r\n        rarities[1] = [255,242,229,216,203,190,177,164,151,138,125,112,99,86,73,60,54,48,42,36,30,24,18,12,3,4,5,5];\r\n        aliases[1] = [27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,10,9,8,7,6,5,4,3,2,1,0];\r\n        rarities[2] = [255,15,24,31,39,54,57,59,62,67,71,73,78,81,83,85,95,98,105,110,112,118,121,126,128];\r\n        aliases[2] = [25,24,23,22,21,20,19,18,17,16,15,14,13,12,0,0,9,0,0,0,0,0,0,0,0,0];\r\n        rarities[3] = [255];\r\n        aliases[3] = [0];\r\n\r\n        rarities[4] = [255];\r\n        aliases[4] = [0];\r\n        rarities[5] = [255];\r\n        aliases[5] = [0];\r\n        rarities[6] = [255];\r\n        aliases[6] = [0];\r\n        rarities[7] = [255];\r\n        aliases[7] = [0];\r\n        rarities[8] = [255];\r\n        aliases[8] = [0];\r\n        rarities[9] = [255];\r\n        aliases[9] = [0];\r\n        rarities[10] = [255];\r\n        aliases[10] = [0];\r\n        rarities[11] = [255];\r\n        aliases[11] = [0];\r\n        rarities[12] = [255];\r\n        aliases[12] = [0];\r\n\r\n        rarities[13] = [255,165,51,43,18,5];\r\n        aliases[13] = [0,1,2,3,4,5];\r\n\r\n\r\n        rarities[14] = [255,15,41,54,69,78,114,117];\r\n        aliases[14] = [0,1,2,3,4,5,6,7];\r\n\r\n        rarities[15] = [255,3,6,15,30,63,78,102,132];\r\n        aliases[15] = [0,1,2,3,4,5,6,7,8,9,10];\r\n\r\n        rarities[16] = [255,3,15,15,15,15,15,15,9,6,9,6,3];\r\n        aliases[16] = [0,1,2,3,4,5,6,7,8,9,10,11,12];\r\n\r\n\r\n        rarities[17] = [255,3,18,27,27,3,27,9,9,9,3,3,3];\r\n        aliases[17] = [0,1,2,3,4,5,6,7,8,9,10,11,12];\r\n\r\n        rarities[18] = [255,165,51,43,18,5];\r\n        aliases[18] = [3,3,3,2,1,0];\r\n    }\r\n\r\n    /** EXTERNAL */\r\n    function mint(uint256 amount) external payable whenNotPaused {\r\n    require(amount <= 5, \"Maxmimum 5 mints at a time\");\r\n    require(tx.origin == _msgSender(), \"Only EOA\");\r\n    require(minted + amount <= MAX_TOKENS, \"All tokens minted\");\r\n    if(whitelistMode){require(amount <= whitelisted[_msgSender()].amount, \"Whitelisted can mint maximum of 3\");}\r\n    if (minted < PAID_TOKENS) {\r\n      require(minted + amount <= PAID_TOKENS, \"All tokens on-sale already sold\");\r\n      require(amount * MINT_PRICE >= msg.value, \"Invalid payment amount\");\r\n    } else {\r\n      require(msg.value == 0);\r\n    }\r\n    uint256 totalFOODCost = 0;\r\n    uint256 seed;\r\n        for (uint256 i = 0; i < amount; i++) {\r\n            minted++;\r\n            nonReserved++;\r\n            if(whitelistMode){whitelisted[ _msgSender()].amount--;}\r\n\t        mintBlock[nonReserved] = block.number;\r\n            seed = random(nonReserved);\r\n            generate(nonReserved, seed);\r\n            address recipient = selectRecipient(seed);\r\n            totalFOODCost += mintCost(nonReserved);\r\n            _safeMint(recipient, nonReserved);\r\n        }\r\n        if (totalFOODCost > 0) food.burn(_msgSender(), totalFOODCost);\r\n    }\r\n\r\n    function reservedMint(uint256 amount) external {\r\n    require(amount <= 5, \"Maxmimum 5 mints at a time\");\r\n    require(amount <= reservedMinters[msg.sender].amount);\r\n    uint256 seed;\r\n        for (uint256 i = 0; i < amount; i++) {\r\n            minted++;\r\n            reserved++;\r\n\t        mintBlock[reserved] = block.number;\r\n            seed = random(reserved);\r\n            generate(reserved, seed);\r\n            _safeMint(msg.sender,reserved);\r\n        }\r\n    }\r\n\r\n  function mintCost(uint256 tokenId) public view returns (uint256) {\r\n    if (tokenId <= PAID_TOKENS) return 0;\r\n    if (tokenId <= MAX_TOKENS * 2 / 5) return 20000 ether;\r\n    if (tokenId <= MAX_TOKENS * 3 / 5) return 40000 ether;\r\n    if (tokenId <= MAX_TOKENS * 4 / 5) return 80000 ether;\r\n    return 100000 ether;\r\n  }\r\n\r\n    function transferFrom(\r\n        address from,\r\n        address to,\r\n        uint256 tokenId\r\n    ) public virtual override {\r\n        if (_msgSender() != address(kongIsland)) {\r\n            require(\r\n                _isApprovedOrOwner(_msgSender(), tokenId),\r\n                \"ERC721: transfer caller is not owner nor approved\"\r\n            );\r\n        }\r\n        _transfer(from, to, tokenId);\r\n    }\r\n\r\n    /** INTERNAL */\r\n\r\n    /**\r\n     * generates traits for a specific token, checking to make sure it's unique\r\n     * @param tokenId the id of the token to generate traits for\r\n     * @param seed a pseudorandom 256 bit number to derive traits from\r\n     * @return t - a struct of traits for the given token ID\r\n     */\r\n    function generate(uint256 tokenId, uint256 seed)\r\n        internal\r\n        returns (KaijuKong memory t)\r\n    {\r\n        t = selectTraits(seed);\r\n        if (existingCombinations[structToHash(t)] == 0) {\r\n            tokenTraits[tokenId] = t;\r\n            existingCombinations[structToHash(t)] = tokenId;\r\n            return t;\r\n        }\r\n        return generate(tokenId, random(seed));\r\n    }\r\n\r\n    /**\r\n     * uses A.J. Walker's Alias algorithm for O(1) rarity table lookup\r\n     * ensuring O(1) instead of O(n) reduces mint cost by more than 50%\r\n     * probability & alias tables are generated off-chain beforehand\r\n     * @param seed portion of the 256 bit seed to remove trait correlation\r\n     * @param traitType the trait type to select a trait for\r\n     * @return the ID of the randomly selected trait\r\n     */\r\n    function selectTrait(uint16 seed, uint8 traitType)\r\n        internal\r\n        view\r\n        returns (uint8)\r\n    {\r\n        uint8 trait = uint8(seed) % uint8(rarities[traitType].length);\r\n        if (seed >> 9 < rarities[traitType][trait]) return trait;\r\n        return aliases[traitType][trait];\r\n    }\r\n\r\n    /**\r\n     * the first 20% (ETH purchases) go to the minter\r\n     * the remaining 80% have a 10% chance to be given to a random staked Kong\r\n     * @param seed a random value to select a recipient from\r\n     * @return the address of the recipient (either the minter or the Kong thief's owner)\r\n     */\r\n\r\n     \r\n  function selectRecipient(uint256 seed) internal view returns (address) {\r\n    if (minted <= PAID_TOKENS || minted < 30000 && ((seed >> 245) % 10) != 0 || minted >30000 && ((seed >> 245) % 10) >=2) return _msgSender(); // top 10 bits haven't been used\r\n    address thief = kongIsland.randomKongOwner(seed >> 144); // 144 bits reserved for trait selection\r\n    if (thief == address(0x0)) return _msgSender();\r\n    return thief;\r\n  }\r\n\r\n    /**\r\n     * selects the species and all of its traits based on the seed value\r\n     * @param seed a pseudorandom 256 bit number to derive traits from\r\n     * @return t -  a struct of randomly selected traits\r\n     */\r\n    function selectTraits(uint256 seed)\r\n        internal\r\n        view\r\n        returns (KaijuKong memory t)\r\n    {\r\n        t.isKaiju = (seed & 0xFFFF) % 10 != 0;\r\n        uint8 shift = t.isKaiju ? 0 : 9;\r\n        seed >>= 16;\r\n        t.background = selectTrait(uint16(seed & 0xFFFF), 0);\r\n        seed >>= 16;\r\n        t.species = selectTrait(uint16(seed & 0xFFFF), 1 + shift);\r\n        seed >>= 16;\r\n        t.companion = selectTrait(uint16(seed & 0xFFFF), 2 + shift);\r\n        seed >>= 16;\r\n        t.kingScore = selectTrait(uint16(seed & 0xFFFF), 9 + shift);\r\n        seed >>= 16;\r\n        t.hat = selectTrait(uint16(seed & 0xFFFF), 5 + shift);\r\n        seed >>= 16;\r\n        t.face = selectTrait(uint16(seed & 0xFFFF), 6 + shift);\r\n        seed >>= 16;\r\n        t.weapons = selectTrait(uint16(seed & 0xFFFF), 7 + shift);\r\n        seed >>= 16;\r\n        t.accessories = selectTrait(uint16(seed & 0xFFFF), 8 + shift);\r\n        seed >>= 16;\r\n        t.fur = t.kingScore;\r\n    }\r\n\r\n    function structToHash(KaijuKong memory s) internal pure returns (uint256) {\r\n        return\r\n            uint256(\r\n                bytes32(\r\n                    abi.encodePacked(\r\n                        s.isKaiju,\r\n                        s.background,\r\n                        s.species,\r\n                        s.companion,\r\n                        s.fur,\r\n                        s.hat,\r\n                        s.face,\r\n                        s.weapons,\r\n                        s.accessories,\r\n                        s.kingScore\r\n                    )\r\n                )\r\n            );\r\n    }\r\n\r\n  function random(uint256 seed) internal view returns (uint256) {\r\n    return uint256(keccak256(abi.encodePacked(\r\n      tx.origin,\r\n      blockhash(block.number - 1),\r\n      block.timestamp,\r\n      seed\r\n    )));\r\n  }\r\n\r\n    /** READ */\r\n\r\n    function getTokenTraits(uint256 tokenId)\r\n        external\r\n        view\r\n        override\r\n        returns (KaijuKong memory)\r\n    {\r\n        require(mintBlock[tokenId] + 1 < block.number);\r\n        return tokenTraits[tokenId];\r\n    }\r\n\r\n    function getPaidTokens() external view override returns (uint256) {\r\n        return PAID_TOKENS;\r\n    }\r\n\r\n    function isKaiju(uint256 tokenId) external view returns (bool){\r\n        require(mintBlock[tokenId] + 1 < block.number);\r\n        return(tokenTraits[tokenId].isKaiju);\r\n    }\r\n\r\n    function KingScore(uint256 tokenId) external view returns (uint8) {\r\n        require(mintBlock[tokenId] + 1 < block.number);\r\n        return(tokenTraits[tokenId].kingScore);\r\n    }\r\n\r\n    function getIDsOwnedby(address _address) external view returns(uint256[] memory) {\r\n        uint256[] memory tokensOwned = new uint256[](balanceOf(_address));\r\n        for(uint256 i = 0; i < tokensOwned.length; i++) {\r\n            tokensOwned[i] = tokenOfOwnerByIndex(_address, i);\r\n        }\r\n        return tokensOwned;\r\n    }\r\n\r\n    /** ADMIN */\r\n\r\n    function setKongIsland(address _KongIsland) external onlyOwner {\r\n        kongIsland = IKongIsland(_KongIsland);\r\n    }\r\n\r\n    function addToWhitelist(address _whitelisted) external onlyOwner {\r\n        whitelisted[_whitelisted].amount = 3;\r\n    }\r\n\r\n    function bulkWhitelist(address[] calldata _whitelisted) external onlyOwner {\r\n        for (uint256 i = 0; i < _whitelisted.length; i++) {\r\n        whitelisted[_whitelisted[i]].amount = 3;\r\n        }\r\n    }\r\n\r\n    function addToReservedMinters(address _reserved, uint256 _amount) external onlyOwner {\r\n        reservedMinters[_reserved].amount = _amount;\r\n    }\r\n\r\n    function bulkWhitelist(address[] calldata _reserved,uint256[] calldata _amount) external onlyOwner {\r\n        for (uint256 i = 0; i < _reserved.length; i++) {\r\n        reservedMinters[_reserved[i]].amount = _amount[i];\r\n        }\r\n    }\r\n\r\n    function withdraw() external onlyOwner {\r\n        payable(owner()).transfer(address(this).balance);\r\n    }\r\n\r\n    function whitelistMinting(bool _whitelistMode)external onlyOwner {\r\n        whitelistMode = _whitelistMode;\r\n    }\r\n\r\n    function setPaidTokens(uint256 _paidTokens) external onlyOwner {\r\n        PAID_TOKENS = _paidTokens;\r\n    }\r\n\r\n    function setPaused(bool _paused) external onlyOwner {\r\n        if (_paused) _pause();\r\n        else _unpause();\r\n    }\r\n\r\n  function setMintPrice(uint256 mintprice) external onlyOwner{\r\n        MINT_PRICE = mintprice;\r\n    }\r\n\r\n  function updateFoodContract(address _food) external onlyOwner {\r\n        food = IFOOD(_food);\r\n    }\r\n\r\n    /** RENDER */\r\n\r\n  function tokenURI(uint256 tokenId) public view override returns (string memory) {\r\n    require(_exists(tokenId), \"ERC721Metadata: URI query for nonexistent token\");\r\n    require(mintBlock[tokenId] + 1 < block.number);\r\n    return traits.tokenURI(tokenId);\r\n  }\r\n\r\n}\r\n\r\ncontract KongIsland is Ownable, IERC721Receiver, Pausable {\r\n  \r\n  // maximum King score for a Kong\r\n  uint8 public constant MAX_King = 8;\r\n\r\n  // struct to store a stake's token, owner, and earning values\r\n  struct Stake {\r\n    uint16 tokenId;\r\n    uint80 value;\r\n    address owner;\r\n  }\r\n\r\n  struct StakedTokens {\r\n    uint256[] ID;\r\n  }\r\n\r\n  event TokenStaked(address owner, uint256 tokenId, uint256 value);\r\n  event KaijuClaimed(uint256 tokenId, bool unstaked);\r\n  event KongClaimed(uint256 tokenId, uint256 earned, bool unstaked);\r\n\r\n  // reference to the contracts\r\n  KONGS kongs;\r\n  IFOOD food;\r\n\r\n    mapping(address => StakedTokens) StakedByAddress;   \r\n  // maps tokenId to stake\r\n    mapping(uint256 => Stake) public kongIsland; \r\n  // maps King to all Kong stakes with that King\r\n     mapping(uint256 => Stake[]) public pack; \r\n  // tracks location of each Kong in Pack\r\n    mapping(uint256 => uint256) public packIndices; \r\n  // total King scores staked\r\n    uint256 public totalKingStaked = 0; \r\n    // total Kongs scores staked\r\n    uint256 public totalKongsStaked = 0; \r\n  // any rewards distributed when no Kongs are staked\r\n    uint256 public unaccountedRewards = 0; \r\n  // amount of $FOOD due for each King point staked\r\n    uint256 public FOODPerKing = 0; \r\n\r\n  mapping(address => uint256) private _lastUnstakeBlock;\r\n  mapping(address => uint256) private _owed;\r\n\r\n  // Kaiju earn 10000 $FOOD per day\r\n  uint256 public constant DAILY_FOOD_RATE = 10000 ether; //10000 ether;\r\n  // Kaiju must have 2 days worth of $FOOD to unstake or else it's too cold\r\n  uint256 public MINIMUM_TO_EXIT = 0 days; //2 days;\r\n  // Kongs take a 20% tax on all $FOOD claimed\r\n  uint256 public constant FOOD_CLAIM_TAX_PERCENTAGE = 20;\r\n  // there will only ever be (roughly) 2.4 billion $FOOD earned through staking\r\n  uint256 public constant MAXIMUM_GLOBAL_FOOD = 2400000000 ether;\r\n\r\n  // amount of $FOOD earned so far\r\n  uint256 public totalFOODEarned;\r\n  // number of Kaiju stake on  KongIsland\r\n  uint256 public totalKaijuStaked;\r\n  uint256  totalKaijuStakedOG;\r\n  uint256  totalKaijuStakedGen1;\r\n  uint256  totalKaijuStakedGen2;\r\n  // the last time $FOOD was claimed\r\n  uint256 public lastClaimTimestamp;\r\n\r\n  // emergency rescue to allow unstaking without any checks but without $FOOD\r\n  bool public rescueEnabled = false;\r\n\r\n  /**\r\n   * @param _KONGS reference to the KONGS NFT contract\r\n   * @param _FOOD reference to the $FOOD token\r\n   */\r\n  constructor(address _KONGS, address _FOOD) { \r\n    kongs = KONGS(_KONGS);\r\n    food = IFOOD(_FOOD);\r\n  }\r\n\r\n  /** STAKING */\r\n\r\n  /**\r\n   * adds Kaiju and Kongs to the KongIsland and Pack\r\n   * @param account the address of the staker\r\n   * @param tokenIds the IDs of the Kaiju and Kongs to stake\r\n   */\r\n  function addManyToKongIslandAndPack(address account, uint16[] calldata tokenIds) external {\r\n    require(account == tx.origin && _msgSender() == tx.origin, \"DONT GIVE YOUR TOKENS AWAY\");\r\n    for (uint i = 0; i < tokenIds.length; i++) {\r\n        require(kongs.ownerOf(tokenIds[i]) == _msgSender() && kongs.ownerOf(tokenIds[i]) == tx.origin, \"AINT YO TOKEN\");\r\n        kongs.transferFrom(_msgSender(), address(this), tokenIds[i]);\r\n        StakedByAddress[msg.sender].ID.push(tokenIds[i]);\r\n\r\n      if (isKaiju(tokenIds[i])) \r\n        _addKaijuToKongIsland(account, tokenIds[i]);\r\n      else \r\n        _addKongToPack(account, tokenIds[i]);\r\n    }\r\n  }\r\n\r\n  /**\r\n   * adds a single Kaiju to the KongIsland\r\n   * @param account the address of the staker\r\n   * @param tokenId the ID of the Kaiju to add to the KongIsland\r\n   */\r\n  function _addKaijuToKongIsland(address account, uint256 tokenId) internal whenNotPaused _updateEarnings {\r\n    kongIsland[tokenId] = Stake({\r\n      owner: account,\r\n      tokenId: uint16(tokenId),\r\n      value: uint80(block.timestamp)\r\n    });\r\n    totalKaijuStaked += 1;\r\n    if(tokenId >30000){totalKaijuStakedGen2 += 1;}\r\n    else if (tokenId >=20000&& tokenId <30000){totalKaijuStakedGen1 += 1;}\r\n    else {totalKaijuStakedOG += 1;}\r\n\r\n    emit TokenStaked(account, tokenId, block.timestamp);\r\n  }\r\n\r\n  /**\r\n   * adds a single Kong to the Pack\r\n   * @param account the address of the staker\r\n   * @param tokenId the ID of the Kong to add to the Pack\r\n   */\r\n  function _addKongToPack(address account, uint256 tokenId) internal {\r\n    uint256 King = _KingForKong(tokenId);\r\n    totalKingStaked += King;\r\n    totalKongsStaked += 1;\r\n    packIndices[tokenId] = pack[King].length; // Store the location of the Kong in the Pack\r\n    pack[King].push(Stake({\r\n      owner: account,\r\n      tokenId: uint16(tokenId),\r\n      value: uint80(FOODPerKing)\r\n    })); // Add the Kong to the Pack\r\n    kongIsland[tokenId] = Stake({\r\n      owner: account,\r\n      tokenId: uint16(tokenId),\r\n      value: uint80(block.timestamp)\r\n    });\r\n    emit TokenStaked(account, tokenId, FOODPerKing);\r\n  }\r\n\r\n  /** CLAIMING / UNSTAKING */\r\n\r\n  function unstakeFromKongIslandAndPack(uint16[] calldata tokenIds) external whenNotPaused _updateEarnings {\r\n    require(_lastUnstakeBlock[_msgSender()] + 1 < block.number, \"NoReEntrancy\");\r\n    _lastUnstakeBlock[_msgSender()] = block.number;\r\n    for (uint i = 0; i < tokenIds.length; i++) {\r\n      if (isKaiju(tokenIds[i]))\r\n       _owed[_msgSender()] += _claimKaijuFromKongIsland(tokenIds[i]);\r\n      else\r\n        _owed[_msgSender()] += _claimKongFromPack(tokenIds[i]);\r\n    }\r\n  }\r\n\r\n  function realiseEarningsFromKongIslandAndPack(uint16[] calldata tokenIds) external whenNotPaused  _updateEarnings {\r\n    require(_lastUnstakeBlock[_msgSender()] + 1 < block.number, \"No Reentrancy\");\r\n    _lastUnstakeBlock[_msgSender()] = block.number;\r\n    for (uint i = 0; i < tokenIds.length; i++) {\r\n      if (isKaiju(tokenIds[i]))\r\n       _owed[_msgSender()] += _claimKaijuFood(tokenIds[i]);\r\n      else\r\n        _owed[_msgSender()] += _claimKongFood(tokenIds[i]);\r\n    }\r\n  }\r\n\r\n  function claimFOOD() external whenNotPaused  {\r\n    require(_lastUnstakeBlock[_msgSender()] + 1 < block.number, \"No Reentrancy\");\r\n    require(_owed[_msgSender()] > 0, \"Nothing to claim\");\r\n    _lastUnstakeBlock[_msgSender()] = block.number;\r\n    uint256 owed = _owed[_msgSender()];\r\n    _owed[_msgSender()] = 0;\r\n    food.mint(_msgSender(), owed);\r\n   }\r\n\r\n  function _claimKaijuFromKongIsland(uint256 tokenId) internal returns (uint256 owed) {\r\n    Stake memory stake = kongIsland[tokenId];\r\n    require(stake.owner == _msgSender() && stake.owner == tx.origin, \"No swiping\");\r\n    require(!(block.timestamp - stake.value < MINIMUM_TO_EXIT), \"GONNA BE COLD WITHOUT TWO DAY'S FOOD\");\r\n    if (totalFOODEarned < MAXIMUM_GLOBAL_FOOD) {\r\n      owed = (block.timestamp - stake.value) * DAILY_FOOD_RATE / 1 days;\r\n    } else if (stake.value > lastClaimTimestamp) {\r\n      owed = 0; // $FOOD production stopped already\r\n    } else {\r\n      owed = (lastClaimTimestamp - stake.value) * DAILY_FOOD_RATE / 1 days; // stop earning additional $FOOD if it's all been earned\r\n    }\r\n    if(tokenId >= 20000 && tokenId < 30000 ){owed = ((owed*80)/100);}\r\n    else if(tokenId >= 30000){owed = ((owed*60)/100);} \r\n    uint256 stealChance = (random(tokenId) % 10);\r\n      if (tokenId <20000 && stealChance >= 5||tokenId >=20000 && stealChance >= 7 ) { // 50% chance of all $FOOD stolen\r\n        _payKongTax(owed);\r\n        owed = 0;\r\n      }\r\n      delete kongIsland[tokenId];\r\n      totalKaijuStaked -= 1;\r\n      removeTokenID(tokenId);\r\n      kongs.safeTransferFrom(address(this), _msgSender(), tokenId, \"\"); // send back Kaiju\r\n     emit KaijuClaimed(tokenId, true);\r\n  }\r\n\r\n\r\n  function _claimKongFromPack(uint256 tokenId) internal returns (uint256 owed) {\r\n    require(kongs.ownerOf(tokenId) == address(this), \"AINT A PART OF THE PACK\");\r\n    uint256 King = _KingForKong(tokenId);\r\n    Stake memory stake = pack[King][packIndices[tokenId]];\r\n    require(stake.owner == _msgSender(), \"SWIPER, NO SWIPING\");\r\n    owed = (King) * (FOODPerKing - stake.value); // Calculate portion of tokens based on King\r\n      totalKingStaked -= King; // Remove King from total staked\r\n      totalKongsStaked -= 1; \r\n      Stake memory lastStake = pack[King][pack[King].length - 1];\r\n      pack[King][packIndices[tokenId]] = lastStake; // Shuffle last Kong to current position\r\n      packIndices[lastStake.tokenId] = packIndices[tokenId];\r\n      pack[King].pop(); // Remove duplicate\r\n      delete packIndices[tokenId]; // Delete old mapping\r\n      delete kongIsland[tokenId];\r\n      removeTokenID(tokenId);\r\n      kongs.safeTransferFrom(address(this), _msgSender(), tokenId, \"\"); // Send back Kong\r\n    \r\n    emit KongClaimed(tokenId, owed, true);  }\r\n\t\r\n\t function _claimKaijuFood(uint256 tokenId) internal returns (uint256 owed) {\r\n    Stake memory stake = kongIsland[tokenId];\r\n    require(stake.owner == _msgSender() && stake.owner == tx.origin, \"No swiping\");\r\n    require(!(block.timestamp - stake.value < MINIMUM_TO_EXIT), \"GONNA BE COLD WITHOUT TWO DAY'S FOOD\");\r\n    if (totalFOODEarned < MAXIMUM_GLOBAL_FOOD) {\r\n      owed = (block.timestamp - stake.value) * DAILY_FOOD_RATE / 1 days;\r\n    } else if (stake.value > lastClaimTimestamp) {\r\n      owed = 0; // $FOOD production stopped already\r\n    } else {\r\n      owed = (lastClaimTimestamp - stake.value) * DAILY_FOOD_RATE / 1 days; // stop earning additional $FOOD if it's all been earned\r\n    }\r\n    if(tokenId >= 20000 && tokenId < 30000 ){owed = ((owed*80)/100);}\r\n    else if(tokenId >= 30000){owed = ((owed*60)/100);} \r\n\r\n      _payKongTax(owed * FOOD_CLAIM_TAX_PERCENTAGE / 100); // percentage tax to staked Kongs\r\n      owed = owed * (100 - FOOD_CLAIM_TAX_PERCENTAGE) / 100; // remainder goes to Kaiju owner\r\n      kongIsland[tokenId] = Stake({\r\n        owner: _msgSender(),\r\n        tokenId: uint16(tokenId),\r\n        value: uint80(block.timestamp)\r\n      }); // reset stake\r\n    emit KaijuClaimed(tokenId, false);\r\n  }\r\n\r\n  function _claimKongFood(uint256 tokenId) internal returns (uint256 owed) {\r\n    require(kongs.ownerOf(tokenId) == address(this), \"AINT A PART OF THE PACK\");\r\n    uint256 King = _KingForKong(tokenId);\r\n    Stake memory stake = pack[King][packIndices[tokenId]];\r\n    require(stake.owner == _msgSender(), \"SWIPER, NO SWIPING\");\r\n    owed = (King) * (FOODPerKing - stake.value); // Calculate portion of tokens based on King\r\n      pack[King][packIndices[tokenId]] = Stake({\r\n        owner: _msgSender(),\r\n        tokenId: uint16(tokenId),\r\n        value: uint80(FOODPerKing)\r\n      }); // reset stake\r\n    emit KongClaimed(tokenId, owed, false);  }\r\n\r\n  /**\r\n   * emergency unstake tokens\r\n   * @param tokenIds the IDs of the tokens to claim earnings from\r\n   */\r\n  function rescue(uint256[] calldata tokenIds) external {\r\n    require(rescueEnabled, \"RESCUE DISABLED\");\r\n    require(_lastUnstakeBlock[tx.origin] != block.number, \"No ReEntry\");\r\n    _lastUnstakeBlock[tx.origin] = block.number;\r\n    uint256 tokenId;\r\n    Stake memory stake;\r\n    Stake memory lastStake;\r\n    uint256 King;\r\n    for (uint i = 0; i < tokenIds.length; i++) {\r\n      tokenId = tokenIds[i];\r\n      delete kongIsland[tokenId];\r\n      if (isKaiju(tokenId)) {\r\n        stake = kongIsland[tokenId];\r\n        require(stake.owner == _msgSender(), \"SWIPER, NO SWIPING\");\r\n        totalKaijuStaked -= 1;\r\n        removeTokenID(tokenId);\r\n        kongs.safeTransferFrom(address(this), _msgSender(), tokenId, \"\"); // send back Kaiju\r\n        emit KaijuClaimed(tokenId, true);\r\n      } else {\r\n        King = _KingForKong(tokenId);\r\n        stake = pack[King][packIndices[tokenId]];\r\n        require(stake.owner == _msgSender(), \"SWIPER, NO SWIPING\");\r\n        totalKingStaked -= King; // Remove King from total staked\r\n        lastStake = pack[King][pack[King].length - 1];\r\n        pack[King][packIndices[tokenId]] = lastStake; // Shuffle last Kong to current position\r\n        packIndices[lastStake.tokenId] = packIndices[tokenId];\r\n        pack[King].pop(); // Remove duplicate\r\n        delete packIndices[tokenId]; // Delete old mapping\r\n        removeTokenID(tokenId);\r\n        kongs.safeTransferFrom(address(this), _msgSender(), tokenId, \"\"); // Send back Kong\r\n        emit KongClaimed(tokenId,0, true);\r\n      }\r\n    }\r\n  }\r\n\r\n    function removeTokenID(uint256 tokenID) internal {\r\n       for (uint256 i = 0; i < StakedByAddress[msg.sender].ID.length; i++) {\r\n            if (StakedByAddress[msg.sender].ID[i] == tokenID) {\r\n                StakedByAddress[msg.sender].ID[i] = StakedByAddress[msg.sender].ID[StakedByAddress[msg.sender].ID.length -1];\r\n                StakedByAddress[msg.sender].ID.pop();\r\n                break;\r\n            }\r\n        }\r\n    }\r\n\r\n  /** ACCOUNTING */\r\n\r\n  /** \r\n   * add $FOOD to claimable pot for the Pack\r\n   * @param amount $FOOD to add to the pot\r\n   */\r\n  function _payKongTax(uint256 amount) internal {\r\n    if (totalKingStaked == 0) { // if there's no staked Kongs\r\n      unaccountedRewards += amount; // keep track of $FOOD due to Kongs\r\n      return;\r\n    }\r\n    // makes sure to include any unaccounted $FOOD \r\n    FOODPerKing += (amount + unaccountedRewards) / totalKingStaked;\r\n    unaccountedRewards = 0;\r\n  }\r\n\r\n  /**\r\n   * tracks $FOOD earnings to ensure it stops once 2.4 billion is eclipsed\r\n   */\r\n  modifier _updateEarnings() {\r\n    if (totalFOODEarned < MAXIMUM_GLOBAL_FOOD) {\r\n      totalFOODEarned += \r\n        ((block.timestamp - lastClaimTimestamp)\r\n        * totalKaijuStakedOG\r\n        * DAILY_FOOD_RATE / 1 days) + \r\n        ((block.timestamp - lastClaimTimestamp)\r\n        * totalKaijuStakedGen1\r\n        * (((DAILY_FOOD_RATE / 1 days)*80)/100))\r\n        + ((block.timestamp - lastClaimTimestamp)\r\n        * totalKaijuStakedGen2\r\n        * (((DAILY_FOOD_RATE / 1 days)*60)/100));\r\n\r\n      lastClaimTimestamp = block.timestamp;\r\n    }\r\n    _;\r\n  }\r\n\r\n  /** ADMIN */\r\n\r\n  /**\r\n   * allows owner to enable \"rescue mode\"\r\n   * simplifies accounting, prioritizes tokens out in emergency\r\n   */\r\n  function setRescueEnabled(bool _enabled) external onlyOwner {\r\n    rescueEnabled = _enabled;\r\n  }\r\n\r\n\r\n  function UpdateContracts(address _KONGS, address _FOOD) external onlyOwner{ \r\n    kongs = KONGS(_KONGS);\r\n    food = IFOOD(_FOOD);\r\n  }\r\n\r\n  /**\r\n   * enables owner to pause / unpause minting\r\n   */\r\n  function setPaused(bool _paused) external onlyOwner {\r\n    if (_paused) _pause();\r\n    else _unpause();\r\n  }\r\n\r\n  function setMinDaysToStake(uint256 _days) external onlyOwner {\r\n    MINIMUM_TO_EXIT = _days * (1 days);\r\n  }\r\n\r\n  /** READ ONLY */\r\n\r\n  /**\r\n   * checks if a token is a Kaiju\r\n   * @param tokenId the ID of the token to check\r\n   * @return Kaiju - whether or not a token is a Kaiju\r\n   */\r\n  function isKaiju(uint256 tokenId) public view returns (bool Kaiju) {\r\n        return kongs.isKaiju(tokenId);\r\n  }\r\n\r\n  function stakedIDsbyAddress(address _staker) public view returns (uint256[] memory) {\r\n        return StakedByAddress[_staker].ID;\r\n  }\r\n\r\n  /**\r\n   * gets the King score for a Kong\r\n   * @param tokenId the ID of the Kong to get the King score for\r\n   * @return the King score of the Kong (5-8)\r\n   */\r\n  function _KingForKong(uint256 tokenId) internal view returns (uint8) {\r\n    return MAX_King - kongs.KingScore(tokenId); // King index is 0-4\r\n  }\r\n\r\n  function gainsUnclaimed(uint256 tokenId) external view returns(uint256 owed){\r\n        require(kongIsland[tokenId].value >0, \"Token not Staked\");\r\n        if(isKaiju(tokenId)){\r\n        if (totalFOODEarned < MAXIMUM_GLOBAL_FOOD) {\r\n        owed = (block.timestamp - kongIsland[tokenId].value) * DAILY_FOOD_RATE / 1 days;}\r\n        else if (kongIsland[tokenId].value > lastClaimTimestamp) {\r\n        owed = 0;} else {owed = (lastClaimTimestamp - kongIsland[tokenId].value) * DAILY_FOOD_RATE / 1 days;}\r\n        }else{\r\n        owed = (_KingForKong(tokenId)) * (FOODPerKing - kongIsland[tokenId].value);\r\n        }\r\n        if(isKaiju(tokenId) && tokenId >= 30000){return ((owed*60)/100);}\r\n        else if(isKaiju(tokenId) && tokenId >= 20000){return ((owed*80)/100);}\r\n        return owed;\r\n  }\r\n\r\n  /**\r\n   * chooses a random Kong thief when a newly minted token is stolen\r\n   * @param seed a random value to choose a Kong from\r\n   * @return the owner of the randomly selected Kong thief\r\n   */\r\n  function randomKongOwner(uint256 seed) external view returns (address) {\r\n    if (totalKingStaked == 0) return address(0x0);\r\n    uint256 bucket = (seed & 0xFFFFFFFF) % totalKingStaked; // choose a value from 0 to total King staked\r\n    uint256 cumulative;\r\n    seed >>= 32;\r\n    // loop through each bucket of Kongs with the same King score\r\n    for (uint i = MAX_King - 3; i <= MAX_King; i++) {\r\n      cumulative += pack[i].length * i;\r\n      // if the value is not inside of that bucket, keep going\r\n      if (bucket >= cumulative) continue;\r\n      // get the address of a random Kong with that King score\r\n      return pack[i][seed % pack[i].length].owner;\r\n    }\r\n    return address(0x0);\r\n  }\r\n\r\n  /**\r\n   * generates a pseudorandom number\r\n   * @param seed a value ensure different outcomes for different sources in the same block\r\n   * @return a pseudorandom value\r\n   */\r\n  function random(uint256 seed) internal view returns (uint256) {\r\n    return uint256(keccak256(abi.encodePacked(\r\n      tx.origin,\r\n      blockhash(block.number - 1),\r\n      block.timestamp,\r\n      seed\r\n    )));\r\n  }\r\n\r\n  function onERC721Received(\r\n        address,\r\n        address from,\r\n        uint256,\r\n        bytes calldata\r\n    ) external pure override returns (bytes4) {\r\n      require(from == address(0x0), \"Cannot send tokens to KongIsland directly\");\r\n      return IERC721Receiver.onERC721Received.selector;\r\n    }\r\n\r\n  \r\n}"
    }
  },
  "settings": {
    "optimizer": {
      "enabled": true,
      "runs": 99999
    },
    "outputSelection": {
      "*": {
        "*": [
          "evm.bytecode",
          "evm.deployedBytecode",
          "devdoc",
          "userdoc",
          "metadata",
          "abi"
        ]
      }
    }
  }
}}