ETH Price: $2,732.29 (+0.39%)

Contract

0x4ca99304285d9209526BdF359ddEaa6c40369bC1
 

Overview

ETH Balance

0 ETH

Eth Value

$0.00

Multichain Info

No addresses found
Transaction Hash
Method
Block
From
To

There are no matching entries

Please try again later

View more zero value Internal Transactions in Advanced View mode

Advanced mode:
Loading...
Loading

Contract Source Code Verified (Exact Match)

Contract Name:
IkaniV2Staking

Compiler Version
v0.8.9+commit.e5eed63a

Optimization Enabled:
Yes with 200 runs

Other Settings:
default evmVersion
File 1 of 73 : IkaniV2Staking.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { IS2Admin } from "./impl/IS2Admin.sol";
import { IS2Core } from "./impl/IS2Core.sol";
import { IS2Erc20 } from "./impl/IS2Erc20.sol";
import { IS2Getters } from "./impl/IS2Getters.sol";
import { IS2Storage } from "./impl/IS2Storage.sol";
import { MinHeap } from "./lib/MinHeap.sol";

/**
 * @title IkaniV2Staking
 * @author Cyborg Labs, LLC
 *
 * @dev Implements ERC-721 in-place staking with rewards.
 *
 *  Rewards are earned at a configurable base rate per staked NFT, with four bonus multipliers:
 *
 *    - Account-level (i.e. owner-level) bonuses:
 *      - Number of unique staked fabric traits
 *      - Number of unique staked season traits
 *
 *    - Token-level bonuses:
 *      - Foil trait
 *      - Staked duration checkpoints
 */
contract IkaniV2Staking is
    IS2Admin,
    IS2Getters
{
    //---------------- Constructor ----------------//

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(
        address ikani,
        address rewardsErc20
    )
        IS2Erc20(rewardsErc20)
        IS2Storage(ikani)
    {
        _disableInitializers();
    }

    //---------------- Initializer ----------------//

    function initialize(
        address admin
    )
        external
        initializer
    {
        __AccessControl_init();
        __Pausable_init();

        _grantRole(DEFAULT_ADMIN_ROLE, admin);
    }
}

File 2 of 73 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

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

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

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

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

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

File 3 of 73 : ERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./AddressUpgradeable.sol";
import "./ContextUpgradeable.sol";
import "./StringsUpgradeable.sol";
import "./ERC165Upgradeable.sol";
import "./Initializable.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
    using AddressUpgradeable for address;
    using StringsUpgradeable for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

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

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

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

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

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
        __ERC721_init_unchained(name_, symbol_);
    }

    function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
        _name = name_;
        _symbol = symbol_;
    }

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

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

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

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

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

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

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

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

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

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

        _approve(to, tokenId);
    }

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

        return _tokenApprovals[tokenId];
    }

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

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

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

        _transfer(from, to, tokenId);
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        _beforeTokenTransfer(from, to, tokenId);

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

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

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId);
    }

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

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

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

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

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[44] private __gap;
}

File 4 of 73 : IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";

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

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

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

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

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

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

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

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

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

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

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

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

File 5 of 73 : IERC721ReceiverUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

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

File 6 of 73 : IERC721MetadataUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "./IERC721Upgradeable.sol";

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

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

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

File 7 of 73 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "./Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 8 of 73 : StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

File 9 of 73 : ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "./Initializable.sol";

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

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 10 of 73 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.0;

import "./AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
 * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() initializer {}
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Modifier to protect an initializer function from being invoked twice.
     */
    modifier initializer() {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
        // contract may have been reentered.
        require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} modifier, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    function _isConstructor() private view returns (bool) {
        return !AddressUpgradeable.isContract(address(this));
    }
}

File 11 of 73 : IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

File 12 of 73 : IkaniV2.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { ERC721Upgradeable } from "../../deps//ERC721Upgradeable.sol";
import { IERC165Upgradeable } from "../../deps/IERC165Upgradeable.sol";
import { IERC2981Upgradeable } from "../../deps/IERC2981Upgradeable.sol";
import { PausableUpgradeable } from "../../deps/PausableUpgradeable.sol";

import { IIkaniV2Staking } from "../../staking/v2/interfaces/IIkaniV2Staking.sol";
import { IIkaniV1MetadataController } from "../v1/interfaces/IIkaniV1MetadataController.sol";
import { ContractUriUpgradeable } from "../v1/lib/ContractUriUpgradeable.sol";
import { ERC721SequentialUpgradeable } from "../v1/lib/ERC721SequentialUpgradeable.sol";
import { PersonalSign } from "../v1/lib/PersonalSign.sol";
import { WithdrawableUpgradeable } from "../v1/lib/WithdrawableUpgradeable.sol";
import { IkaniV2SeriesLib } from "./lib/IkaniV2SeriesLib.sol";
import { IIkaniV2 } from "./interfaces/IIkaniV2.sol";

/**
 * @title IkaniV2
 * @author Cyborg Labs, LLC
 *
 * @notice The IKANI.AI ERC-721 NFT.
 */
contract IkaniV2 is
    ERC721SequentialUpgradeable,
    ContractUriUpgradeable,
    WithdrawableUpgradeable,
    PausableUpgradeable,
    IERC2981Upgradeable,
    IIkaniV2
{
    //---------------- Constants ----------------//

    uint256 internal constant BIPS_DENOMINATOR = 10000;

    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    uint256 public immutable MAX_SUPPLY; // e.g. 8888

    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    IIkaniV2Staking public immutable STAKING_CONTRACT;

    //---------------- Storage V1 ----------------//

    IIkaniV1MetadataController internal _METADATA_CONTROLLER_;

    address internal _MINT_SIGNER_;

    /// @dev The set of message digests signed and consumed for minting.
    mapping(bytes32 => bool) internal _USED_MINT_DIGESTS_;

    /// @dev DEPRECATED: Poem text and metadata by token ID.
    mapping(uint256 => bytes) internal __DEPRECATED_POEM_INFO_;

    /// @dev Series information by index.
    mapping(uint256 => IIkaniV2.Series) internal _SERIES_INFO_;

    /// @dev Index of the current series available for minting.
    uint256 internal _CURRENT_SERIES_INDEX_;

    //---------------- Storage V1_1 ----------------//

    /// @dev Poem text by token ID.
    mapping(uint256 => string) internal _POEM_TEXT_;

    /// @dev Metadata traits by token ID.
    mapping(uint256 => IIkaniV2.PoemTraits) internal _POEM_TRAITS_;

    //---------------- Storage V2 ----------------//

    address internal _ROYALTY_RECEIVER_;

    uint96 internal _ROYALTY_BIPS_;

    //---------------- Constructor & Initializer ----------------//

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(
        uint256 maxSupply,
        IIkaniV2Staking stakingContract
    )
        initializer
    {
        MAX_SUPPLY = maxSupply;
        STAKING_CONTRACT = stakingContract;
    }

    //---------------- Owner-Only External Functions ----------------//

    function pause()
        external
        onlyOwner
    {
        _pause();
    }

    function unpause()
        external
        onlyOwner
    {
        _unpause();
    }

    function setContractUri(
        string memory contractUri
    )
        external
        onlyOwner
    {
        _setContractUri(contractUri);
    }

    function setMetadataController(
        IIkaniV1MetadataController metadataController
    )
        external
        onlyOwner
    {
        _METADATA_CONTROLLER_ = metadataController;
    }

    function setMintSigner(
        address mintSigner
    )
        external
        onlyOwner
    {
        _MINT_SIGNER_ = mintSigner;
    }

    function setRoyaltyReceiver(
        address royaltyReceiver
    )
        external
        onlyOwner
    {
        _ROYALTY_RECEIVER_ = royaltyReceiver;
        emit SetRoyaltyReceiver(royaltyReceiver);
    }

    function setRoyaltyBips(
        uint96 royaltyBips
    )
        external
        onlyOwner
    {
        _ROYALTY_BIPS_ = royaltyBips;
        emit SetRoyaltyBips(uint256(royaltyBips));
    }

    function setPoemText(
        uint256[] calldata tokenIds,
        string[] calldata poemText
    )
        external
        onlyOwner
    {
        // Note: To save gas, we don't check that the token was minted; however,
        //       the owner should only call this function with minted token IDs.

        uint256 n = tokenIds.length;

        require(
            poemText.length == n,
            "Params length mismatch"
        );

        for (uint256 i = 0; i < n;) {
            _POEM_TEXT_[tokenIds[i]] = poemText[i];

            unchecked { ++i; }
        }
    }

    function setPoemTraits(
        uint256[] calldata tokenIds,
        IIkaniV2.PoemTraits[] calldata poemTraits
    )
        external
        onlyOwner
    {
        // Note: To save gas, we don't check that the token was minted; however,
        //       the owner should only call this function with minted token IDs.

        uint256 n = tokenIds.length;

        require(
            poemTraits.length == n,
            "Params length mismatch"
        );

        for (uint256 i = 0; i < n;) {
            uint256 tokenId = tokenIds[i];
            IIkaniV2.PoemTraits memory traits = poemTraits[i];

            require(
                traits.theme != IIkaniV2.Theme.NULL,
                "Theme cannot be null"
            );
            require(
                traits.fabric != IIkaniV2.Fabric.NULL,
                "Fabric cannot be null"
            );

            _POEM_TRAITS_[tokenId] = traits;

            emit FinishedPoem(tokenId);

            unchecked { ++i; }
        }
    }

    function setSeriesInfo(
        uint256 seriesIndex,
        string calldata name,
        bytes32 provenanceHash
    )
        external
        onlyOwner
    {
        IIkaniV2.Series storage _series_ = _SERIES_INFO_[seriesIndex];

        _series_.name = name;
        _series_.provenanceHash = provenanceHash;

        emit SetSeriesInfo(
            seriesIndex,
            name,
            provenanceHash
        );
    }

    function endCurrentSeries(
        uint256 poemCreationDeadline
    )
        external
        onlyOwner
    {
        uint256 seriesIndex = _CURRENT_SERIES_INDEX_++;

        IkaniV2SeriesLib.endCurrentSeries(
            _SERIES_INFO_[seriesIndex],
            seriesIndex,
            poemCreationDeadline,
            getNextTokenId()
        );
    }

    function advancePoemCreationDeadline(
        uint256 seriesIndex,
        uint256 poemCreationDeadline
    )
        external
        onlyOwner
    {
        IIkaniV2.Series storage _series_ = _SERIES_INFO_[seriesIndex];

        require(
            poemCreationDeadline > _series_.poemCreationDeadline,
            "Deadline can only move forward"
        );

        _series_.poemCreationDeadline = poemCreationDeadline;

        emit AdvancedPoemCreationDeadline(
            seriesIndex,
            poemCreationDeadline
        );
    }

    function mintByOwner(
        address[] calldata recipients
    )
        external
        onlyOwner
    {
        uint256 n = recipients.length;

        for (uint256 i = 0; i < n;) {
            // Note: Intentionally not using _safeMint().
            _mint(recipients[i]);

            unchecked { ++i; }
        }

        require(
            getNextTokenId() <= MAX_SUPPLY,
            "Global max supply exceeded"
        );
    }

    function expire(
        uint256 tokenId
    )
        external
        onlyOwner
    {
        require(
            !isPoemFinished(tokenId),
            "Cannot expire a finished poem"
        );

        uint256 seriesIndex = getPoemSeriesIndex(tokenId);

        IIkaniV2.Series storage _series_ = _SERIES_INFO_[seriesIndex];

        require(
            _series_.startingIndexBlockNumber != 0,
            "Series not ended"
        );
        require(
            block.timestamp > _series_.poemCreationDeadline,
            "Token has not expired"
        );

        _burn(tokenId);
    }

    function expireBatch(
        uint256[] calldata tokenIds,
        uint256 seriesIndex
    )
        external
        onlyOwner
    {
        require(
            seriesIndex <= _CURRENT_SERIES_INDEX_,
            "Invalid series index"
        );

        IkaniV2SeriesLib.validateExpireBatch(
            _SERIES_INFO_,
            tokenIds,
            seriesIndex
        );

        uint256 n = tokenIds.length;

        for (uint256 i = 0; i < n;) {
            require(
                !isPoemFinished(tokenIds[i]),
                "Cannot expire a finished poem"
            );
            _burn(tokenIds[i]);

            unchecked { ++i; }
        }
    }

    //---------------- Other State-Changing External Functions ----------------//

    function mint(
        IIkaniV2.MintArgs calldata mintArgs,
        bytes calldata signature
    )
        external
        payable
        whenNotPaused
    {
        require(
            mintArgs.seriesIndex == _CURRENT_SERIES_INDEX_,
            "Not the current series"
        );

        require(
            msg.value == mintArgs.mintPrice,
            "Wrong msg.value"
        );

        address sender = msg.sender;
        bytes memory message = abi.encode(
            sender,
            mintArgs
        );
        bytes32 messageDigest = keccak256(message);

        // Only allow one mint per message/digest/signature.
        require(
            !_USED_MINT_DIGESTS_[messageDigest],
            "Mint digest already used"
        );
        _USED_MINT_DIGESTS_[messageDigest] = true;

        // Note: Since the only signer is our admin, we don't need EIP-712.
        require(
            PersonalSign.isValidSignature(messageDigest, signature, _MINT_SIGNER_),
            "Invalid signature"
        );

        // Note: Intentionally not using _safeMint().
        uint256 tokenId = _mint(sender);

        require(
            tokenId < mintArgs.maxTokenIdExclusive,
            "Series max supply exceeded"
        );
        require(
            tokenId < MAX_SUPPLY,
            "Global max supply exceeded"
        );
    }

    function trySetSeriesStartingIndex(
        uint256 seriesIndex
    )
        external
        whenNotPaused
    {
        IkaniV2SeriesLib.trySetSeriesStartingIndex(
            _SERIES_INFO_,
            seriesIndex
        );
    }

    //---------------- View-Only External Functions ----------------//

    function getMetadataController()
        external
        view
        returns (IIkaniV1MetadataController)
    {
        return _METADATA_CONTROLLER_;
    }

    function getMintSigner()
        external
        view
        returns (address)
    {
        return _MINT_SIGNER_;
    }

    function getSeriesSupply(
        uint256 seriesIndex
    )
        external
        view
        returns (uint256)
    {
        return IkaniV2SeriesLib.getSeriesSupply(_SERIES_INFO_, seriesIndex);
    }

    function royaltyInfo(
        uint256 /* tokenId */,
        uint256 salePrice
    )
        external
        view
        override
        returns (address, uint256)
    {
        uint256 royaltyAmount = (salePrice * uint256(_ROYALTY_BIPS_)) / BIPS_DENOMINATOR;
        return (_ROYALTY_RECEIVER_, royaltyAmount);
    }

    function isUsedMintDigest(
        bytes32 digest
    )
        external
        view
        returns (bool)
    {
        return _USED_MINT_DIGESTS_[digest];
    }

    function getSeriesInfo(
        uint256 seriesIndex
    )
        external
        view
        returns (IIkaniV2.Series memory)
    {
        return _SERIES_INFO_[seriesIndex];
    }

    function getCurrentSeriesIndex()
        external
        view
        returns (uint256)
    {
        return _CURRENT_SERIES_INDEX_;
    }

    function exists(
        uint256 tokenId
    )
        external
        view
        returns (bool)
    {
        return _exists(tokenId);
    }

    //---------------- Public Functions ----------------//

    function getPoemSeriesIndex(
        uint256 tokenId
    )
        public
        view
        returns (uint256)
    {
        uint256 currentSeriesIndex = _CURRENT_SERIES_INDEX_;
        uint256 seriesIndex;
        for (seriesIndex = 0; seriesIndex < currentSeriesIndex;) {
            IIkaniV2.Series storage _series_ = _SERIES_INFO_[seriesIndex];

            if (tokenId < _series_.maxTokenIdExclusive) {
                break;
            }

            unchecked { ++seriesIndex; }
        }
        return seriesIndex;
    }

    function getPoemText(
        uint256 tokenId
    )
        public
        view
        returns (string memory)
    {
        return _POEM_TEXT_[tokenId];
    }

    function getPoemTraits(
        uint256 tokenId
    )
        public
        view
        returns (IIkaniV2.PoemTraits memory)
    {
        return _POEM_TRAITS_[tokenId];
    }

    function isPoemFinished(
        uint256 tokenId
    )
        public
        view
        returns (bool)
    {
        return _POEM_TRAITS_[tokenId].theme != IIkaniV2.Theme.NULL;
    }

    function tokenURI(
        uint256 tokenId
    )
        public
        view
        override
        returns (string memory)
    {
        return _METADATA_CONTROLLER_.tokenURI(tokenId);
    }

    function supportsInterface(
        bytes4 interfaceId
    )
        public
        view
        override(ERC721Upgradeable, IERC165Upgradeable)
        returns (bool)
    {
        return (
            interfaceId == type(IERC2981Upgradeable).interfaceId ||
            super.supportsInterface(interfaceId)
        );
    }

    //---------------- Internal Functions ----------------//

    function _beforeTokenTransfer(
        address /* from */,
        address /* to */,
        uint256 tokenId
    )
        internal
        view
        override
    {
        // Ensure that staked tokens can only be transfered via the staking contract.
        if (msg.sender != address(STAKING_CONTRACT)) {
            require(
                !STAKING_CONTRACT.isStaked(tokenId),
                "Cannot transfer staked token"
            );
        }
    }
}

File 13 of 73 : IERC2981Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (interfaces/IERC2981.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";

/**
 * @dev Interface for the NFT Royalty Standard.
 *
 * A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
 * support for royalty payments across all NFT marketplaces and ecosystem participants.
 *
 * _Available since v4.5._
 */
interface IERC2981Upgradeable is IERC165Upgradeable {
    /**
     * @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
     * exchange. The royalty amount is denominated and should be paid in that same unit of exchange.
     */
    function royaltyInfo(uint256 tokenId, uint256 salePrice)
        external
        view
        returns (address receiver, uint256 royaltyAmount);
}

File 14 of 73 : PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "./ContextUpgradeable.sol";
import "./Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        require(!paused(), "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        require(paused(), "Pausable: not paused");
        _;
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 15 of 73 : IIkaniV2Staking.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

/**
 * @title IIkaniV2Staking
 * @author Cyborg Labs, LLC
 *
 * @notice Interface for the IIkaniV2Staking features of the IkaniV1 ERC-721 NFT contract.
 */
interface IIkaniV2Staking {

    //---------------- Structs ----------------//

    struct RateChange {
        uint32 baseRate;
        uint32 timestamp;
    }

    struct SettlementContext {
        // The timestamp of the last settlement of this account.
        uint32 timestamp;
        // The number of global rate changes taken into account as of the last settlement
        // of this account.
        uint32 numRateChanges;
        // The global base earning rate.
        uint32 baseRate;
        // The current number of points for the account's staked tokens.
        uint32 points;
        // Current multiplier derived from the account's staked traits.
        uint32 multiplier;
        // The trait counts for the account's staked tokens.
        uint8 fabricKoyamaki;
        uint8 fabricSeigaiha;
        uint8 fabricNami;
        uint8 fabricKumo;
        uint8 fabricTba5;
        uint8 fabricTba6;
        uint8 fabricTba7;
        uint8 fabricTba8;
        uint8 seasonSpring;
        uint8 seasonSummer;
        uint8 seasonAutumn;
        uint8 seasonWinter;
    }

    struct Checkpoint {
        uint128 tokenId;
        uint32 stakedNonce;
        uint32 basePoints;
        uint32 level;
        uint32 timestamp;
    }

    struct TokenStakingState {
        uint32 timestamp;
        uint32 nonce;
    }

    //---------------- Events ----------------//

    event SetBaseRate(
        uint256 baseRate
    );

    event AdminUnstaked(
        address indexed owner,
        uint256[] indexed tokenIds,
        bytes32 indexed receipt,
        bytes receiptData
    );

    event Staked(
        address indexed owner,
        uint256 indexed tokenId,
        uint256 stakingStartTimestamp
    );

    event Unstaked(
        address indexed owner,
        uint256 indexed tokenId
    );

    event ClaimedRewards(
        address indexed owner,
        uint256 amount
    );

    //---------------- Functions ----------------//

    function isStaked(
        uint256 tokenId
    )
        external
        view
        returns (bool);
}

File 16 of 73 : IIkaniV1MetadataController.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

/**
 * @title IIkaniV1MetadataController
 * @author Cyborg Labs, LLC
 *
 * @notice Interface for a contract that provides token metadata via tokenURI().
 */
interface IIkaniV1MetadataController {

    function tokenURI(
        uint256 tokenId
    )
        external
        view
        returns (string memory);
}

File 17 of 73 : ContractUriUpgradeable.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { Initializable } from "../../../deps/Initializable.sol";

/**
 * @title ContractUriUpgradeable
 * @author Cyborg Labs, LLC
 *
 * @dev Simple base contract supporting the contractURI() function used by OpenSea.
 */
abstract contract ContractUriUpgradeable is
    Initializable
{
    string private _CONTRACT_URI_;

    uint256[49] private __gap;

    event SetContractUri(
        string contractUri
    );

    function __ContractUri_init()
        internal
        onlyInitializing
    {}

    function __ContractUri_init_unchained()
        internal
        onlyInitializing
    {}

    function contractURI()
        external
        view
        returns (string memory)
    {
        return _CONTRACT_URI_;
    }

    function _setContractUri(
        string memory contractUri
    )
        internal
    {
        _CONTRACT_URI_ = contractUri;
        emit SetContractUri(contractUri);
    }
}

File 18 of 73 : ERC721SequentialUpgradeable.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { ERC721Upgradeable } from "../../../deps/ERC721Upgradeable.sol";

/**
 * @title ERC721SequentialUpgradeable
 * @author Cyborg Labs, LLC
 *
 * @dev Base contract for an ERC-721 that is minted sequentially. Supports totalSupply().
 */
abstract contract ERC721SequentialUpgradeable is
    ERC721Upgradeable
{
    //---------------- Storage ----------------//

    uint256 internal _NEXT_TOKEN_ID_;

    uint256 internal _BURNED_COUNT_;

    uint256[48] private __gap;

    //---------------- Initializers ----------------//

    function __ERC721Sequential_init(
        string memory name,
        string memory symbol
    )
        internal
        onlyInitializing
    {
        __ERC721_init(name, symbol);
    }

    function __ERC721Sequential_init_unchained()
        internal
        onlyInitializing
    {}

    //---------------- Public Functions ----------------//

    function getNextTokenId()
        public
        view
        returns (uint256)
    {
        return _NEXT_TOKEN_ID_;
    }

    function getBurnedCount()
        public
        view
        returns (uint256)
    {
        return _BURNED_COUNT_;
    }

    function totalSupply()
        public
        view
        returns (uint256)
    {
        return _NEXT_TOKEN_ID_ - _BURNED_COUNT_;
    }

    //---------------- Internal Functions ----------------//

    function _mint(
        address recipient
    )
        internal
        returns (uint256)
    {
        uint256 tokenId = _NEXT_TOKEN_ID_++;
        ERC721Upgradeable._mint(recipient, tokenId);
        return tokenId;
    }

    function _burn(
        uint256 tokenId
    )
        internal
        override
    {
        _BURNED_COUNT_++;
        ERC721Upgradeable._burn(tokenId);
    }
}

File 19 of 73 : PersonalSign.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

/**
 * @title PersonalSign
 * @author Cyborg Labs, LLC
 *
 * @dev Helper function to verify messages signed with personal_sign.
 *
 *  IMPORTANT: Use cases which require users to sign some data (i.e. most signing use cases)
 *  should NOT use this. They should instead follow EIP-712, for security reasons.
 *
 *  NOTE: For our puroses, we assume that the message is hashed before being signed.
 *  The message length is therefore fixed at 32 bytes.
 *
 *  Signing example using ethers.js:
 *
 *  ```
 *    const encodedDataString = ethers.utils.defaultAbiCoder.encode(
 *      [
 *        // types
 *      ],
 *      [
 *        // values
 *      ],
 *    );
 *    const encodedData = Buffer.from(encodedDataString.slice(2), "hex");
 *    const innerDigestString = ethers.utils.keccak256(encodedData);
 *    const innerDigest = Buffer.from(innerDigestString.slice(2), "hex");
 *    const signature = await signer.signMessage(innerDigest);
 *  ```
 */
library PersonalSign {

  bytes constant private PERSONAL_SIGN_HEADER = "\x19Ethereum Signed Message:\n32";

  function isValidSignature(
    bytes32 messageDigest,
    bytes memory signature,
    address expectedSigner
  )
    internal
    pure
    returns (bool)
  {
    // Parse the signature into (v, r, s) components.
    require(
      signature.length == 65,
      "Bad signature length"
    );
    uint8 v;
    bytes32 r;
    bytes32 s;
    assembly {
      r := mload(add(signature, 0x20))
      s := mload(add(signature, 0x40))
      v := byte(0, mload(add(signature, 0x60)))
    }

    // Construct the digest hash which is signed within the `personal_sign` operation.
    bytes32 digest = keccak256(
      abi.encodePacked(
        PERSONAL_SIGN_HEADER,
        messageDigest
      )
    );

    // Check whether the recovered address is the required address.
    address recovered = ecrecover(digest, v, r, s);
    return recovered == expectedSigner;
  }

  function isValidSignature(
    bytes memory message,
    bytes memory signature,
    address expectedSigner
  )
    internal
    pure
    returns (bool)
  {
    return isValidSignature(
      keccak256(message),
      signature,
      expectedSigner
    );
  }
}

File 20 of 73 : WithdrawableUpgradeable.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { OwnableUpgradeable } from "../../../deps/OwnableUpgradeable.sol";

/**
 * @title WithdrawableUpgradeable
 * @author Cyborg Labs, LLC
 *
 * @dev Supports ETH withdrawals by the owner.
 */
abstract contract WithdrawableUpgradeable is
    OwnableUpgradeable
{
    event Withdrawal(
        address recipient,
        uint256 balance
    );

    function __Withdrawable_init()
        internal
        onlyInitializing
    {
        __Ownable_init();
    }

    function __Withdrawable_init_unchained()
        internal
        onlyInitializing
    {}

    function withdrawTo(
        address recipient
    )
        external
        onlyOwner
        returns (uint256)
    {
        uint256 balance = address(this).balance;
        payable(recipient).transfer(balance);
        emit Withdrawal(recipient, balance);
        return balance;
    }
}

File 21 of 73 : IkaniV2SeriesLib.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { IIkaniV2 } from "../interfaces/IIkaniV2.sol";

library IkaniV2SeriesLib {

    // TODO: De-dup event definitions.

    event ResetSeriesStartingIndexBlockNumber(
        uint256 indexed seriesIndex,
        uint256 startingIndexBlockNumber
    );

    event SetSeriesStartingIndex(
        uint256 indexed seriesIndex,
        uint256 startingIndex
    );

    event EndedSeries(
        uint256 indexed seriesIndex,
        uint256 poemCreationDeadline,
        uint256 maxTokenIdExclusive,
        uint256 startingIndexBlockNumber
    );

    uint256 internal constant STARTING_INDEX_ADD_BLOCKS = 10;

    function trySetSeriesStartingIndex(
        mapping(uint256 => IIkaniV2.Series) storage _series_info_,
        uint256 seriesIndex
    )
        external
    {
        IIkaniV2.Series storage _series_ = _series_info_[seriesIndex];

        require(
            !_series_.startingIndexWasSet,
            "Starting index already set"
        );

        uint256 targetBlockNumber = _series_.startingIndexBlockNumber;
        require(
            targetBlockNumber != 0,
            "Series not ended"
        );

        require(
            block.number >= targetBlockNumber,
            "Starting index block not reached"
        );

        // If the hash for the target block is not available, set a new block number and exit.
        if (block.number - targetBlockNumber > 256) {
            uint256 newStartingIndexBlockNumber = block.number + STARTING_INDEX_ADD_BLOCKS;
            _series_.startingIndexBlockNumber = newStartingIndexBlockNumber;
            emit ResetSeriesStartingIndexBlockNumber(
                seriesIndex,
                newStartingIndexBlockNumber
            );
            return;
        }

        uint256 seriesSupply = getSeriesSupply(_series_info_, seriesIndex);
        uint256 startingIndex = uint256(blockhash(targetBlockNumber)) % seriesSupply;

        // Update storage.
        _series_.startingIndex = startingIndex;
        _series_.startingIndexWasSet = true;

        emit SetSeriesStartingIndex(
            seriesIndex,
            startingIndex
        );
    }

    function endCurrentSeries(
        IIkaniV2.Series storage _series_,
        uint256 seriesIndex,
        uint256 poemCreationDeadline,
        uint256 maxTokenIdExclusive
    )
        external
    {
        uint256 startingIndexBlockNumber = block.number + STARTING_INDEX_ADD_BLOCKS;

        _series_.poemCreationDeadline = poemCreationDeadline;
        _series_.maxTokenIdExclusive = maxTokenIdExclusive;
        _series_.startingIndexBlockNumber = startingIndexBlockNumber;

        emit EndedSeries(
            seriesIndex,
            poemCreationDeadline,
            maxTokenIdExclusive,
            startingIndexBlockNumber
        );
    }

    function validateExpireBatch(
        mapping(uint256 => IIkaniV2.Series) storage _series_info_,
        uint256[] calldata tokenIds,
        uint256 seriesIndex
    )
        external
        view
    {
        IIkaniV2.Series storage _series_ = _series_info_[seriesIndex];

        require(
            _series_.startingIndexBlockNumber != 0,
            "Series not ended"
        );
        require(
            block.timestamp > _series_.poemCreationDeadline,
            "Series has not expired"
        );

        uint256 n = tokenIds.length;

        uint256 maxTokenIdExclusive = _series_.maxTokenIdExclusive;
        for (uint256 i = 0; i < n;) {
            require(
                tokenIds[i] < maxTokenIdExclusive,
                "Token ID not part of the series"
            );
            unchecked { ++i; }
        }

        if (seriesIndex > 0) {
            uint256 startTokenId = _series_info_[seriesIndex - 1].maxTokenIdExclusive;
            for (uint256 i = 0; i < n;) {
                require(
                    tokenIds[i] >= startTokenId,
                    "Token ID not part of the series"
                );
                unchecked { ++i; }
            }
        }
    }

    function getSeriesSupply(
        mapping(uint256 => IIkaniV2.Series) storage _series_info_,
        uint256 seriesIndex
    )
        public
        view
        returns (uint256)
    {
        IIkaniV2.Series storage _series_ = _series_info_[seriesIndex];

        require(
            _series_.startingIndexBlockNumber != 0,
            "Series not ended"
        );

        uint256 maxTokenIdExclusive = _series_.maxTokenIdExclusive;

        if (seriesIndex == 0) {
            return maxTokenIdExclusive;
        }

        IIkaniV2.Series storage _previous_series_ = _series_info_[seriesIndex - 1];

        return maxTokenIdExclusive - _previous_series_.maxTokenIdExclusive;
    }
}

File 22 of 73 : IIkaniV2.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

/**
 * @title IIkaniV2
 * @author Cyborg Labs, LLC
 *
 * @notice Interface for the IkaniV1 ERC-721 NFT contract.
 */
interface IIkaniV2 {

    //---------------- Enums ----------------//

    enum Theme {
        NULL,
        SKY,
        OCEAN,
        MOUNTAIN,
        FLOWERS,
        TBA_THEME_5,
        TBA_THEME_6,
        TBA_THEME_7,
        TBA_THEME_8
    }

    enum Season {
        NONE,
        SPRING,
        SUMMER,
        AUTUMN,
        WINTER
    }

    enum Fabric {
        NULL,
        KOYAMAKI,
        SEIGAIHA,
        NAMI,
        KUMO,
        TBA_FABRIC_5,
        TBA_FABRIC_6,
        TBA_FABRIC_7,
        TBA_FABRIC_8
    }

    enum Foil {
        NONE,
        GOLD,
        PLATINUM,
        SUI_GENERIS
    }

    //---------------- Structs ----------------//

    /**
     * @notice The poem metadata traits.
     */
    struct PoemTraits {
        Theme theme;
        Season season;
        Fabric fabric;
        Foil foil;
    }

    /**
     * @notice Information about a series within the collection.
     */
    struct Series {
        string name;
        bytes32 provenanceHash;
        uint256 poemCreationDeadline;
        uint256 maxTokenIdExclusive;
        uint256 startingIndexBlockNumber;
        uint256 startingIndex;
        bool startingIndexWasSet;
    }

    /**
     * @notice Arguments to be signed by the mint authority to authorize a mint.
     */
    struct MintArgs {
        uint256 seriesIndex;
        uint256 mintPrice;
        uint256 maxTokenIdExclusive;
        uint256 nonce;
    }

    //---------------- Events ----------------//

    event SetRoyaltyReceiver(
        address royaltyReceiver
    );

    event SetRoyaltyBips(
        uint256 royaltyBips
    );

    event SetSeriesInfo(
        uint256 indexed seriesIndex,
        string name,
        bytes32 provenanceHash
    );

    event AdvancedPoemCreationDeadline(
        uint256 indexed seriesIndex,
        uint256 poemCreationDeadline
    );

    event ResetSeriesStartingIndexBlockNumber(
        uint256 indexed seriesIndex,
        uint256 startingIndexBlockNumber
    );

    event SetSeriesStartingIndex(
        uint256 indexed seriesIndex,
        uint256 startingIndex
    );

    event EndedSeries(
        uint256 indexed seriesIndex,
        uint256 poemCreationDeadline,
        uint256 maxTokenIdExclusive,
        uint256 startingIndexBlockNumber
    );

    event FinishedPoem(
        uint256 indexed tokenId
    );

    //---------------- Functions ----------------//

    function getPoemTraits(
        uint256 tokenId
    )
        external
        view
        returns (IIkaniV2.PoemTraits memory);
}

File 23 of 73 : OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "./ContextUpgradeable.sol";
import "./Initializable.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    function __Ownable_init() internal onlyInitializing {
        __Ownable_init_unchained();
    }

    function __Ownable_init_unchained() internal onlyInitializing {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 24 of 73 : IS2Getters.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { IIkaniV2 } from "../../../nft/v2/interfaces/IIkaniV2.sol";
import { IS2Lib } from "../lib/IS2Lib.sol";
import { IS2Storage } from "./IS2Storage.sol";

/**
 * @title IS2Getters
 * @author Cyborg Labs, LLC
 *
 * @dev Simple getter functions that are only needed externally.
 */
abstract contract IS2Getters is
    IS2Storage
{
    //---------------- Constants ----------------//

    /// @dev Must match the value in IS2Lib.sol.
    uint256 public constant MULTIPLIER_BASE = 1e6;

    //---------------- External Functions ----------------//

    function isStaked(
        uint256 tokenId
    )
        external
        view
        override
        returns (bool)
    {
        return _TOKEN_STAKING_STATE_[tokenId].timestamp != 0;
    }

    function getStakedTimestamp(
        uint256 tokenId
    )
        external
        view
        returns (uint256)
    {
        return _TOKEN_STAKING_STATE_[tokenId].timestamp;
    }

    function getHistoricalBaseRate(
        uint256 i
    )
        external
        view
        returns (RateChange memory)
    {
        require(
            i <= _NUM_RATE_CHANGES_,
            "Invalid base rate index"
        );
        return _RATE_CHANGES_[i];
    }

    function getNumBaseRateChanges()
        external
        view
        returns (uint256)
    {
        return _NUM_RATE_CHANGES_;
    }

    function getAccountRewardsMultiplier(
        address account
    )
        external
        view
        returns (uint256)
    {
        return IS2Lib.getAccountRewardsMultiplier(_SETTLEMENT_CONTEXT_[account]);
    }

    function getFabricsRewardsMultiplier(
        address account
    )
        external
        view
        returns (uint256)
    {
        return IS2Lib.getFabricsRewardsMultiplier(_SETTLEMENT_CONTEXT_[account]);
    }

    function getSeasonsRewardsMultiplier(
        address account
    )
        external
        view
        returns (uint256)
    {
        return IS2Lib.getSeasonsRewardsMultiplier(_SETTLEMENT_CONTEXT_[account]);
    }

    function getNumFabricsStaked(
        address account
    )
        external
        view
        returns (uint256)
    {
        return IS2Lib.getNumFabricsStaked(_SETTLEMENT_CONTEXT_[account]);
    }

    function getNumSeasonsStaked(
        address account
    )
        external
        view
        returns (uint256)
    {
        return IS2Lib.getNumSeasonsStaked(_SETTLEMENT_CONTEXT_[account]);
    }

    /**
     * @notice Get the token rewards rate for a token.
     */
    function getTokenRewardsRate(
        uint256 tokenId
    )
        external
        view
        returns (uint256)
    {
        return (
            getBaseRate() *
            getDurationRewardsMultiplier(tokenId) *
            getFoilRewardsMultiplier(tokenId) /
            (MULTIPLIER_BASE * MULTIPLIER_BASE)
        );
    }

    /**
     * @notice Get the staked duration level for a token.
     */
    function getDurationLevel(
        uint256 tokenId
    )
        external
        view
        returns (uint256)
    {
        uint256 stakedTimestamp = _TOKEN_STAKING_STATE_[tokenId].timestamp;
        uint256 stakedDuration = block.timestamp - stakedTimestamp;
        return IS2Lib.getLevelForStakedDuration(stakedDuration);
    }

    //---------------- Public Functions ----------------//

    function getBaseRate()
        public
        view
        returns (uint256)
    {
        return _RATE_CHANGES_[_NUM_RATE_CHANGES_].baseRate;
    }

    function getDurationRewardsMultiplier(
        uint256 tokenId
    )
        public
        view
        returns (uint256)
    {
        uint256 stakedTimestamp = _TOKEN_STAKING_STATE_[tokenId].timestamp;

        // If the token is not staked, return multipler of 1.
        if (stakedTimestamp == 0) {
            return MULTIPLIER_BASE;
        }

        uint256 stakedDuration = block.timestamp - stakedTimestamp;
        return IS2Lib.getStakedDurationRewardsMultiplier(stakedDuration);
    }

    function getFoilRewardsMultiplier(
        uint256 tokenId
    )
        public
        view
        returns (uint256)
    {
        IIkaniV2.PoemTraits memory traits = IIkaniV2(IKANI).getPoemTraits(tokenId);
        return IS2Lib.getFoilRewardsMultiplier(traits);
    }
}

File 25 of 73 : IS2Lib.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { SafeCastUpgradeable } from "../../../deps/oz_cu_4_7_2/SafeCastUpgradeable.sol";

import { IIkaniV2 } from "../../../nft/v2/interfaces/IIkaniV2.sol";
import { IIkaniV2Staking } from "../interfaces/IIkaniV2Staking.sol";
import { MinHeap } from "../lib/MinHeap.sol";

library IS2Lib {
    using MinHeap for MinHeap.Heap;
    using SafeCastUpgradeable for uint256;

    //---------------- External Functions ----------------//

    /**
     * @dev Settle rewards to current timestamp, returning updated context and new rewards.
     *
     *  After calling this function, the returned updated context should be saved to storage.
     *  The new rewards should also be saved to storage (or spent).
     */
    function settleAccountAndGetOwedRewards(
        IIkaniV2Staking.SettlementContext memory intialContext,
        mapping(uint256 => IIkaniV2Staking.RateChange) storage _rate_changes_,
        MinHeap.Heap storage _checkpoints_,
        mapping(uint256 => IIkaniV2Staking.TokenStakingState) storage _token_staking_state_,
        uint256 globalNumRateChanges
    )
        external
        returns (
            IIkaniV2Staking.SettlementContext memory context,
            uint256 newRewards
        )
    {
        context = intialContext;
        newRewards = 0;
    }

    function stakeLogic(
        IIkaniV2Staking.SettlementContext memory intialContext,
        IIkaniV2.PoemTraits memory traits,
        uint256 stakingStartTimestamp,
        uint256 stakedNonce,
        uint256 tokenId
    )
        external
        view
        returns (
            IIkaniV2Staking.SettlementContext memory context,
            IIkaniV2Staking.Checkpoint memory checkpoint
        )
    {
        context = intialContext;
    }

    function unstakeLogic(
        IIkaniV2Staking.SettlementContext memory intialContext,
        IIkaniV2.PoemTraits memory traits,
        uint256 stakedTimestamp
    )
        external
        view
        returns (
            IIkaniV2Staking.SettlementContext memory context
        )
    {
        context = intialContext;
    }

    //---------------- Public State-Changing Functions ----------------//

    function _insertCheckpoint(
        MinHeap.Heap storage _checkpoints_,
        IIkaniV2Staking.Checkpoint memory checkpoint
    )
        public
    {
        uint256 checkpointUint = (
            (uint256(checkpoint.timestamp) << 224) +
            (uint256(checkpoint.level) << 192) +
            (uint256(checkpoint.basePoints) << 160) +
            (uint256(checkpoint.stakedNonce) << 128) +
            checkpoint.tokenId
        );
        _checkpoints_.insert(checkpointUint);
    }

    //---------------- Public Pure Functions ----------------//

    function getFoilRewardsMultiplier(
        IIkaniV2.PoemTraits memory traits
    )
        public
        pure
        returns (uint256)
    {
        return 0;
    }

    function getStakedDurationRewardsMultiplier(
        uint256 stakedDuration
    )
        public
        pure
        returns (uint256)
    {
        return 0;
    }

    function getAccountRewardsMultiplier(
        IIkaniV2Staking.SettlementContext memory context
    )
        public
        pure
        returns (uint256)
    {
        return 0;
    }

    function getFabricsRewardsMultiplier(
        IIkaniV2Staking.SettlementContext memory context
    )
        public
        pure
        returns (uint256)
    {
        return 0;
    }

    function getSeasonsRewardsMultiplier(
        IIkaniV2Staking.SettlementContext memory context
    )
        public
        pure
        returns (uint256)
    {
        return 0;
    }

    function getNumFabricsStaked(
        IIkaniV2Staking.SettlementContext memory context
    )
        public
        pure
        returns (uint256)
    {
        return 0;
    }

    function getNumSeasonsStaked(
        IIkaniV2Staking.SettlementContext memory context
    )
        public
        pure
        returns (uint256)
    {
        return 0;
    }

    function getLevelForStakedDuration(
        uint256 stakedDuration
    )
        public
        pure
        returns (uint256)
    {
        return 0;
    }
}

File 26 of 73 : IS2Storage.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { AccessControlUpgradeable } from "../../../deps/oz_cu_4_7_2/AccessControlUpgradeable.sol";
import { PausableUpgradeable } from "../../../deps/oz_cu_4_7_2/PausableUpgradeable.sol";

import { IIkaniV2Staking } from "../interfaces/IIkaniV2Staking.sol";
import { MinHeap } from "../lib/MinHeap.sol";

/**
 * @title IS2Storage
 * @author Cyborg Labs, LLC
 */
abstract contract IS2Storage is
    AccessControlUpgradeable,
    PausableUpgradeable,
    IIkaniV2Staking
{
    //---------------- Constants ----------------//

    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address public immutable IKANI;

    //---------------- Constructor ----------------//

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(
        address ikani
    ) {
        IKANI = ikani;
    }

    //---------------- Storage ----------------//

    /// @dev Storage gap to allow for flexibility in contract upgrades.
    uint256[1_000_000] private __gap;

    /// @dev Historical record of all changes to the global base rewards rate.
    ///
    ///  The base rate at index zero is always zero.
    ///  The first configured base rate is at index one.
    mapping(uint256 => RateChange) internal _RATE_CHANGES_;

    /// @dev The number of changes to the global base rewards rate.
    uint256 internal _NUM_RATE_CHANGES_;

    /// @dev The rewards state and settlement info for an account.
    mapping(address => SettlementContext) internal _SETTLEMENT_CONTEXT_;

    /// @dev The priority queue of unlockable duration-based bonus points for an account.
    ///
    ///  These are encoded as IIkaniV2Staking.Checkpoint structs and ordered by timestamp.
    mapping(address => MinHeap.Heap) internal _CHECKPOINTS_;

    /// @dev The settled rewards held by an account.
    ///
    ///  Converts to an ERC-20 amount as specified in IS2Erc20.sol.
    mapping(address => uint256) internal _REWARDS_;

    /// @dev The staking state of a token, including the timestamp and nonce.
    ///
    ///  timestamp  The timestamp when the token was staked, if currently staked, otherwise zero.
    ///  nonce      The number of times the token has been unstaked.
    mapping(uint256 => TokenStakingState) internal _TOKEN_STAKING_STATE_;
}

File 27 of 73 : SafeCastUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCastUpgradeable {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248) {
        require(value >= type(int248).min && value <= type(int248).max, "SafeCast: value doesn't fit in 248 bits");
        return int248(value);
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240) {
        require(value >= type(int240).min && value <= type(int240).max, "SafeCast: value doesn't fit in 240 bits");
        return int240(value);
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232) {
        require(value >= type(int232).min && value <= type(int232).max, "SafeCast: value doesn't fit in 232 bits");
        return int232(value);
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224) {
        require(value >= type(int224).min && value <= type(int224).max, "SafeCast: value doesn't fit in 224 bits");
        return int224(value);
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216) {
        require(value >= type(int216).min && value <= type(int216).max, "SafeCast: value doesn't fit in 216 bits");
        return int216(value);
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208) {
        require(value >= type(int208).min && value <= type(int208).max, "SafeCast: value doesn't fit in 208 bits");
        return int208(value);
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200) {
        require(value >= type(int200).min && value <= type(int200).max, "SafeCast: value doesn't fit in 200 bits");
        return int200(value);
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192) {
        require(value >= type(int192).min && value <= type(int192).max, "SafeCast: value doesn't fit in 192 bits");
        return int192(value);
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184) {
        require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits");
        return int184(value);
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176) {
        require(value >= type(int176).min && value <= type(int176).max, "SafeCast: value doesn't fit in 176 bits");
        return int176(value);
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168) {
        require(value >= type(int168).min && value <= type(int168).max, "SafeCast: value doesn't fit in 168 bits");
        return int168(value);
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160) {
        require(value >= type(int160).min && value <= type(int160).max, "SafeCast: value doesn't fit in 160 bits");
        return int160(value);
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152) {
        require(value >= type(int152).min && value <= type(int152).max, "SafeCast: value doesn't fit in 152 bits");
        return int152(value);
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144) {
        require(value >= type(int144).min && value <= type(int144).max, "SafeCast: value doesn't fit in 144 bits");
        return int144(value);
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136) {
        require(value >= type(int136).min && value <= type(int136).max, "SafeCast: value doesn't fit in 136 bits");
        return int136(value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128) {
        require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
        return int128(value);
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120) {
        require(value >= type(int120).min && value <= type(int120).max, "SafeCast: value doesn't fit in 120 bits");
        return int120(value);
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112) {
        require(value >= type(int112).min && value <= type(int112).max, "SafeCast: value doesn't fit in 112 bits");
        return int112(value);
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104) {
        require(value >= type(int104).min && value <= type(int104).max, "SafeCast: value doesn't fit in 104 bits");
        return int104(value);
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96) {
        require(value >= type(int96).min && value <= type(int96).max, "SafeCast: value doesn't fit in 96 bits");
        return int96(value);
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88) {
        require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits");
        return int88(value);
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80) {
        require(value >= type(int80).min && value <= type(int80).max, "SafeCast: value doesn't fit in 80 bits");
        return int80(value);
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72) {
        require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits");
        return int72(value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64) {
        require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
        return int64(value);
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56) {
        require(value >= type(int56).min && value <= type(int56).max, "SafeCast: value doesn't fit in 56 bits");
        return int56(value);
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48) {
        require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits");
        return int48(value);
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40) {
        require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits");
        return int40(value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32) {
        require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
        return int32(value);
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24) {
        require(value >= type(int24).min && value <= type(int24).max, "SafeCast: value doesn't fit in 24 bits");
        return int24(value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16) {
        require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
        return int16(value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8) {
        require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
        return int8(value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 28 of 73 : MinHeap.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

/**
 * @title IkaniV2Staking
 * @author Cyborg Labs, LLC
 *
 * @dev Priority queue implemented as a heap.
 */
library MinHeap {

    struct Heap {
        mapping(uint256 => uint256) data;
        uint256 length;
    }

    function insert(
        Heap storage _heap_,
        uint256 value
    )
        internal
    {
        unchecked {
            uint256 index = _heap_.length + 1;
            _heap_.length = index;

            while (index != 1) {
                uint256 parentIndex = index >> 1;
                uint256 parentValue = _heap_.data[parentIndex];
                if (parentValue <= value) {
                    break;
                }
                _heap_.data[index] = parentValue;
                index = parentIndex;
            }

            _heap_.data[index] = value;
        }
    }

    function unsafePeek(
        Heap storage _heap_
    )
        internal
        view
        returns (uint256)
    {
        return _heap_.data[1];
    }

    function safePeek(
        Heap storage _heap_
    )
        internal
        view
        returns (uint256)
    {
        require(
            _heap_.length != 0,
            "Heap is empty"
        );
        return _heap_.data[1];
    }

    function popMin(
        Heap storage _heap_
    )
        internal
    {
        unchecked {
            // We implicitly move the last value to the top of the heap, and heapify it down.
            uint256 oldLength = _heap_.length--;
            uint256 lastValue = _heap_.data[oldLength];

            if (oldLength == 1) {
                return;
            }

            uint256 index = 1;
            uint256 leftChildIndex = 2;
            uint256 rightChildIndex = 3;

            // While there is a left child...
            while (leftChildIndex < oldLength) {

                // Get the smaller of the left child and (if it exists) the right child.
                uint256 childIndex = leftChildIndex;
                uint256 childValue = _heap_.data[leftChildIndex];
                if (rightChildIndex < oldLength) {
                    uint256 rightChildValue = _heap_.data[rightChildIndex];
                    if (rightChildValue < childValue) {
                        childIndex = rightChildIndex;
                        childValue = rightChildValue;
                    }
                }

                // If the child value is smaller than our value, bring the child up.
                if (childValue < lastValue) {
                    _heap_.data[index] = childValue;
                    index = childIndex;
                } else {
                    break;
                }

                leftChildIndex = index << 1;
                rightChildIndex = leftChildIndex + 1;
            }

            _heap_.data[index] = lastValue;
        }
    }
}

File 29 of 73 : AccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";
import "./ContextUpgradeable.sol";
import "./StringsUpgradeable.sol";
import "./ERC165Upgradeable.sol";
import "./Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

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

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(account),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 30 of 73 : PausableUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "./ContextUpgradeable.sol";
import "./Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}

File 31 of 73 : IAccessControlUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

File 32 of 73 : ContextUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

import "./Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 33 of 73 : StringsUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

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

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

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

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

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

File 34 of 73 : ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "./Initializable.sol";

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

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}

File 35 of 73 : Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "./AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
 * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
 * case an upgrade adds a module that needs to be initialized.
 *
 * For example:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * contract MyToken is ERC20Upgradeable {
 *     function initialize() initializer public {
 *         __ERC20_init("MyToken", "MTK");
 *     }
 * }
 * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
 *     function initializeV2() reinitializer(2) public {
 *         __ERC20Permit_init("MyToken");
 *     }
 * }
 * ```
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
 * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() {
 *     _disableInitializers();
 * }
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     * @custom:oz-retyped-from bool
     */
    uint8 private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Triggered when the contract has been initialized or reinitialized.
     */
    event Initialized(uint8 version);

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
            "Initializable: contract is already initialized"
        );
        _initialized = 1;
        if (isTopLevelCall) {
            _initializing = true;
        }
        _;
        if (isTopLevelCall) {
            _initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
     * initialization step. This is essential to configure modules that are added through upgrades and that require
     * initialization.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     */
    modifier reinitializer(uint8 version) {
        require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
        _initialized = version;
        _initializing = true;
        _;
        _initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized < type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }
}

File 36 of 73 : AddressUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)

pragma solidity ^0.8.1;

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

        return account.code.length > 0;
    }

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

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

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

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

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

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

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

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) private pure {
        // Look for revert reason and bubble it up if present
        if (returndata.length > 0) {
            // The easiest way to bubble the revert reason is using memory via assembly
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}

File 37 of 73 : IERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

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

File 38 of 73 : IS2Roles.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { IS2Storage } from "./IS2Storage.sol";

/**
 * @title IS2Storage
 * @author Cyborg Labs, LLC
 */
abstract contract IS2Roles is
    IS2Storage
{
    //---------------- Constants ----------------//

    bytes32 public constant PAUSER_ROLE = keccak256('PAUSER_ROLE');
    bytes32 public constant UNPAUSER_ROLE = keccak256('UNPAUSER_ROLE');
    bytes32 public constant BASE_RATE_CONTROLLER_ROLE = keccak256('BASE_RATE_CONTROLLER_ROLE');
    bytes32 public constant BURN_CONTROLLER_ROLE = keccak256('BURN_CONTROLLER_ROLE');
    bytes32 public constant CLAIM_CONTROLLER_ROLE = keccak256('CLAIM_CONTROLLER_ROLE');
    bytes32 public constant UNSTAKE_CONTROLLER_ROLE = keccak256('UNSTAKE_CONTROLLER_ROLE');
}

File 39 of 73 : IS2Admin.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { IERC721Upgradeable } from "../../../deps/oz_cu_4_7_2/IERC721Upgradeable.sol";
import { SafeCastUpgradeable } from "../../../deps/oz_cu_4_7_2/SafeCastUpgradeable.sol";

import { IIkaniERC20 } from "../../../erc20/interfaces/IIkaniERC20.sol";
import { IS2Core } from "./IS2Core.sol";
import { IS2Roles } from "./IS2Roles.sol";

/**
 * @title IS2Admin
 * @author Cyborg Labs, LLC
 *
 *  Role-restricted functions.
 */
abstract contract IS2Admin is
    IS2Core,
    IS2Roles
{
    using SafeCastUpgradeable for uint256;

    //---------------- External Functions ----------------//

    function pause()
        external
        onlyRole(PAUSER_ROLE)
    {
        _pause();
    }

    function unpause()
        external
        onlyRole(UNPAUSER_ROLE)
    {
        _unpause();
    }

    function setBaseRate(
        uint32 baseRate
    )
        external
        onlyRole(BASE_RATE_CONTROLLER_ROLE)
    {
        _setBaseRate(baseRate);
    }

    function adminUnstake(
        address owner,
        uint256[] calldata tokenIds,
        bytes32 receipt,
        bytes calldata receiptData
    )
        external
        onlyRole(UNSTAKE_CONTROLLER_ROLE)
        whenNotPaused
    {
        // Verify owner.
        _requireSameOwnerAndAuthorized(owner, tokenIds, true);

        // Get the updated rewards context and new rewards.
        (SettlementContext memory context, uint256 rewardsDiff) = _settleAccount(owner);

        // Unstake the tokens.
        context = _unstake(context, owner, tokenIds);

        // Update storage for the account.
        _SETTLEMENT_CONTEXT_[owner] = context;
        _REWARDS_[owner] += rewardsDiff;

        emit AdminUnstaked(owner, tokenIds, receipt, receiptData);
    }

    function adminClaimRewards(
        address owner
    )
        external
        onlyRole(CLAIM_CONTROLLER_ROLE)
        whenNotPaused
    {
        _claimRewards(owner, owner);
    }

    function adminClaimRewardsAndBurnWithPermit(
        address owner,
        uint256 burnAmount,
        bytes32 burnReceipt,
        bytes calldata burnReceiptData,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s

    )
        external
        onlyRole(CLAIM_CONTROLLER_ROLE)
        onlyRole(BURN_CONTROLLER_ROLE)
        whenNotPaused
    {
        _claimRewards(owner, owner);
        _burnErc20(owner, burnAmount, burnReceipt, burnReceiptData, deadline, v, r, s);
    }

    //---------------- Internal Functions ----------------//

    function _setBaseRate(
        uint32 baseRate
    )
        internal
    {
        // The base rate at index zero is always zero.
        // The first configured base rate is at index one.
        unchecked {
            _RATE_CHANGES_[++_NUM_RATE_CHANGES_] = RateChange({
                baseRate: baseRate,
                timestamp: block.timestamp.toUint32()
            });
        }

        emit SetBaseRate(baseRate);
    }
}

File 40 of 73 : IERC721Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";

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

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

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

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

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

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

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

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

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

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

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

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

File 41 of 73 : IIkaniERC20.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

interface IIkaniERC20 {

    //---------------- Events ----------------//

    event Minted(
        address indexed to,
        uint256 amount,
        bytes32 indexed receipt,
        bytes receiptData
    );

    event Burned(
        address indexed from,
        uint256 amount,
        bytes32 indexed receipt,
        bytes receiptData
    );

    //---------------- Functions ----------------//

    function mint(
        address to,
        uint256 amount,
        bytes32 receipt,
        bytes calldata receiptData
    )
        external;

    function burn(
        address from,
        uint256 amount,
        bytes32 receipt,
        bytes calldata receiptData
    )
        external;

    function burnWithPermit(
        address from,
        uint256 amount,
        bytes32 receipt,
        bytes calldata receiptData,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    )
        external;

    function burnFrom(
        address from,
        uint256 amount,
        bytes32 receipt,
        bytes calldata receiptData
    )
        external;
}

File 42 of 73 : IS2Core.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { AddressUpgradeable } from "../../../deps/oz_cu_4_7_2/AddressUpgradeable.sol";
import { IERC721Upgradeable } from "../../../deps/oz_cu_4_7_2/IERC721Upgradeable.sol";
import { SafeCastUpgradeable } from "../../../deps/oz_cu_4_7_2/SafeCastUpgradeable.sol";

import { IIkaniV2 } from "../../../nft/v2/interfaces/IIkaniV2.sol";

import { IS2Lib } from "../lib/IS2Lib.sol";
import { MinHeap } from "../lib/MinHeap.sol";
import { IS2Erc20 } from "./IS2Erc20.sol";

/**
 * @title IS2Core
 * @author Cyborg Labs, LLC
 */
abstract contract IS2Core is
    IS2Erc20
{
    using SafeCastUpgradeable for uint256;

    //---------------- External Functions ----------------//

    /**
     * @notice Stake one or more tokens owned by a single owner.
     *
     *  Will revert if any of the tokens are already staked.
     *  Will revert if the same token is included more than once.
     */
    function stake(
        address owner,
        uint256[] calldata tokenIds
    )
        external
        whenNotPaused
    {
        // Verify owner and authorization.
        _requireSameOwnerAndAuthorized(owner, tokenIds, false);

        // Get the updated rewards context and new rewards.
        (SettlementContext memory context, uint256 rewardsDiff) = _settleAccount(owner);

        // Stake the tokens.
        context = _stake(context, owner, tokenIds, new uint256[](0));

        // Update storage for the account.
        _SETTLEMENT_CONTEXT_[owner] = context;
        if (rewardsDiff != 0) {
            _REWARDS_[owner] += rewardsDiff;
        }
    }

    function unstake(
        address owner,
        uint256[] calldata tokenIds
    )
        external
        whenNotPaused
    {
        // Verify owner and authorization.
        _requireSameOwnerAndAuthorized(owner, tokenIds, false);

        // Get the updated rewards context and new rewards.
        (SettlementContext memory context, uint256 rewardsDiff) = _settleAccount(owner);

        // Unstake the tokens.
        context = _unstake(context, owner, tokenIds);

        // Update storage for the account.
        _SETTLEMENT_CONTEXT_[owner] = context;
        _REWARDS_[owner] += rewardsDiff;
    }

    function batchSafeTransferFromStaked(
        address owner,
        address recipient,
        uint256[] calldata tokenIds
    )
        external
        whenNotPaused
    {
        require(
            msg.sender == owner,
            "Only owner can transfer staked"
        );

        // Verify owner.
        _requireSameOwnerAndAuthorized(owner, tokenIds, true);

        // Get the updated rewards context and new rewards.
        (
            SettlementContext memory ownerContext,
            uint256 ownerRewardsDiff
        ) = _settleAccount(owner);
        (
            SettlementContext memory recipientContext,
            uint256 recipientRewardsDiff
        ) = _settleAccount(recipient);

        // Get the staked timestamps.
        uint256 n = tokenIds.length;
        uint256[] memory stakedTimestamps = new uint256[](n);
        for (uint256 i = 0; i < n;) {
            stakedTimestamps[i] = _TOKEN_STAKING_STATE_[tokenIds[i]].timestamp;
            unchecked { ++i; }
        }

        // Unstake and restake the tokens.
        ownerContext = _unstake(ownerContext, owner, tokenIds);
        recipientContext = _stake(recipientContext, recipient, tokenIds, stakedTimestamps);

        // Update storage for the accounts.
        _SETTLEMENT_CONTEXT_[owner] = ownerContext;
        _REWARDS_[owner] += ownerRewardsDiff;
        _SETTLEMENT_CONTEXT_[recipient] = recipientContext;
        _REWARDS_[recipient] += recipientRewardsDiff;

        // Do transfers last, since a “safe” transfer can execute arbitrary smart contract code.
        // This is important to prevent reentrancy attacks.
        for (uint256 i = 0; i < n;) {
            IERC721Upgradeable(IKANI).safeTransferFrom(owner, recipient, tokenIds[i]);
            unchecked { ++i; }
        }
    }

    /**
     * @notice Claim all rewards for the account.
     *
     *  This function can be called with eth_call (e.g. callStatic in ethers.js) to get the
     *  current unclaimed rewards balance for an account.
     */
    function claimRewards(
        address owner,
        address recipient
    )
        external
        whenNotPaused
        returns (uint256)
    {
        require(
            msg.sender == owner,
            "Sender is not owner"
        );
        return _claimRewards(owner, recipient);
    }

    function claimAndBurnRewards(
        address owner,
        uint256 burnAmount,
        bytes32 burnReceipt,
        bytes calldata burnReceiptData,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    )
        external
        whenNotPaused
    {
        require(
            msg.sender == owner,
            "Sender is not owner"
        );
        _claimRewards(owner, owner);
        _burnErc20(owner, burnAmount, burnReceipt, burnReceiptData, deadline, v, r, s);
    }

    /**
     * @notice Settle rewards for an account.
     *
     *  Note: There is no access control on this function.
     */
    function settleRewards(
        address owner
    )
        external
        whenNotPaused
        returns (uint256)
    {
        return _settleRewards(owner);
    }

    //---------------- Internal Functions ----------------//

    function _settleRewards(
        address owner
    )
        internal
        returns (uint256)
    {
        uint256 rewardsOld = _REWARDS_[owner];

        // Get the updated rewards context and new rewards.
        (SettlementContext memory context, uint256 rewardsDiff) = _settleAccount(owner);

        uint256 rewardsNew = rewardsOld + rewardsDiff;

        // Update storage.
        _SETTLEMENT_CONTEXT_[owner] = context;
        _REWARDS_[owner] = rewardsNew;

        return _getErc20Amount(rewardsNew);
    }

    function _claimRewards(
        address owner,
        address recipient
    )
        internal
        returns (uint256)
    {
        uint256 rewardsOld = _REWARDS_[owner];

        // Get the updated rewards context and new rewards.
        (SettlementContext memory context, uint256 rewardsDiff) = _settleAccount(owner);

        // Update storage.
        _SETTLEMENT_CONTEXT_[owner] = context;
        _REWARDS_[owner] = 0;

        // Mint the rewards amount.
        uint256 rewardsNew = rewardsOld + rewardsDiff;
        uint256 erc20Amount = _issueRewards(recipient, rewardsNew);

        emit ClaimedRewards(owner, erc20Amount);

        return erc20Amount;
    }

    function _stake(
        SettlementContext memory initialContext,
        address owner,
        uint256[] calldata tokenIds,
        uint256[] memory maybeStakingStartTimestamps
    )
        internal
        returns (SettlementContext memory context)
    {
        context = initialContext;
        uint256 n = tokenIds.length;

        for (uint256 i = 0; i < n;) {
            uint256 tokenId = tokenIds[i];

            // Get the current staking state for the token.
            TokenStakingState memory stakingState = _TOKEN_STAKING_STATE_[tokenId];

            // Require that the token is not currently staked.
            // Note that this will revert if the same token appeared twice in the list.
            require(
                stakingState.timestamp == 0,
                "Already staked"
            );

            // The timestamp to use as the staking start timestamp for the token.
            uint256 stakingStartTimestamp = maybeStakingStartTimestamps.length > 0
                ? maybeStakingStartTimestamps[i]
                : block.timestamp;

            Checkpoint memory checkpoint;
            (context, checkpoint) = IS2Lib.stakeLogic(
                context,
                IIkaniV2(IKANI).getPoemTraits(tokenId),
                stakingStartTimestamp,
                stakingState.nonce,
                tokenId
            );

            // Update storage for the token.
            if (checkpoint.timestamp != 0) {
                IS2Lib._insertCheckpoint(_CHECKPOINTS_[owner], checkpoint);
            }
            _TOKEN_STAKING_STATE_[tokenId].timestamp = stakingStartTimestamp.toUint32();

            emit Staked(owner, tokenId, stakingStartTimestamp);

            unchecked { ++i; }
        }
    }

    function _unstake(
        SettlementContext memory initialContext,
        address owner,
        uint256[] calldata tokenIds
    )
        internal
        returns (SettlementContext memory context)
    {
        context = initialContext;
        uint256 n = tokenIds.length;

        for (uint256 i = 0; i < n;) {
            uint256 tokenId = tokenIds[i];

            // Get the current staking state for the token.
            TokenStakingState memory stakingState = _TOKEN_STAKING_STATE_[tokenId];

            // Require that the token is currently staked.
            // Note that this will revert if the same token appeared twice in the list.
            require(
                stakingState.timestamp != 0,
                "Not staked"
            );

            context = IS2Lib.unstakeLogic(
                context,
                IIkaniV2(IKANI).getPoemTraits(tokenId),
                stakingState.timestamp
            );

            // Update storage for the token.
            unchecked {
                _TOKEN_STAKING_STATE_[tokenId] = TokenStakingState({
                    timestamp: 0,
                    nonce: stakingState.nonce + 1
                });
            }

            emit Unstaked(owner, tokenId);

            unchecked { ++i; }
        }
    }

    function _requireSameOwnerAndAuthorized(
        address owner,
        uint256[] calldata tokenIds,
        bool alreadyAuthorized
    )
        internal
        view
    {
        address sender = msg.sender;
        bool senderIsOwner = sender == owner;
        uint256 n = tokenIds.length;

        // Verify owner and authorization.
        for (uint256 i = 0; i < n;) {
            uint256 tokenId = tokenIds[i];

            require(
                IERC721Upgradeable(IKANI).ownerOf(tokenId) == owner,
                "Wrong owner"
            );
            require(
                alreadyAuthorized || senderIsOwner || _isApproved(sender, owner, tokenId),
                "Not authorized to stake/unstake"
            );

            unchecked { ++i; }
        }
    }

    function _settleAccount(
        address owner
    )
        internal
        returns (
            SettlementContext memory context,
            uint256 rewardsDiff
        )
    {
        (context, rewardsDiff) = IS2Lib.settleAccountAndGetOwedRewards(
            _SETTLEMENT_CONTEXT_[owner],
            _RATE_CHANGES_,
            _CHECKPOINTS_[owner],
            _TOKEN_STAKING_STATE_,
            _NUM_RATE_CHANGES_
        );
    }

    function _isApproved(
        address spender,
        address owner,
        uint256 tokenId
    )
        internal
        view
        returns (bool)
    {
        return (
            IERC721Upgradeable(IKANI).isApprovedForAll(owner, spender) ||
            IERC721Upgradeable(IKANI).getApproved(tokenId) == spender
        );
    }
}

File 43 of 73 : IS2Erc20.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { IERC20 } from "../../../deps/oz_c_4_7_2/IERC20.sol";

import { IIkaniERC20 } from "../../../erc20/interfaces/IIkaniERC20.sol";

import { IS2Storage } from "./IS2Storage.sol";

/**
 * @title IS2Erc20
 * @author Cyborg Labs, LLC
 *
 * @notice Handles interactions with the ERC20 token.
 */
abstract contract IS2Erc20 is
    IS2Storage
{
    //---------------- Constants ----------------//

    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable REWARDS_ERC20;

    uint256 private constant REWARDS_CONVERSION_FACTOR = 1e6;

    //---------------- Constructor ----------------//

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(
        address rewardsErc20
    ) {
        REWARDS_ERC20 = rewardsErc20;
    }

    //---------------- Internal Functions ----------------//

    function _issueRewards(
        address recipient,
        uint256 rewardsAmount
    )
        internal
        returns (uint256)
    {
        uint256 erc20Amount = _getErc20Amount(rewardsAmount);
        // Note: Not using SafeERC20, to save a bit of gas, since this is our own token.
        IERC20(REWARDS_ERC20).transfer(
            recipient,
            erc20Amount
        );
        return erc20Amount;
    }

    function _burnErc20(
        address owner,
        uint256 burnAmount,
        bytes32 burnReceipt,
        bytes calldata burnReceiptData,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    )
        internal
    {
        IIkaniERC20(REWARDS_ERC20).burnWithPermit(
            owner,
            burnAmount,
            burnReceipt,
            burnReceiptData,
            deadline,
            v,
            r,
            s
        );
    }

    function _getErc20Amount(
        uint256 rewardsAmount
    )
        internal
        pure
        returns (uint256)
    {
        return rewardsAmount * REWARDS_CONVERSION_FACTOR;
    }
}

File 44 of 73 : IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the amount of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves `amount` tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) external returns (bool);
}

File 45 of 73 : IkaniERC20.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { AccessControl } from "../deps/oz_c_4_7_2/AccessControl.sol";
import { ERC20 } from "../deps/oz_c_4_7_2/ERC20.sol";
import { ERC20Permit } from "../deps/oz_c_4_7_2/draft-ERC20Permit.sol";
import { ERC20Votes } from "../deps/oz_c_4_7_2/ERC20Votes.sol";
import { Pausable } from "../deps/oz_c_4_7_2/Pausable.sol";

import { IIkaniERC20 } from "./interfaces/IIkaniERC20.sol";

/**
 * @title IkaniERC20
 * @author Cyborg Labs, LLC
 *
 * @notice The IKANI.AI ERC-20 utility token.
 *
 *  Has the following features:
 *    - Mintable
 *    - Burnable
 *    - Pausable
 *    - Permit
 *    - Votes
 *
 *  When paused, transfers are disabled, except for minting and burning.
 */
contract IkaniERC20 is
    ERC20,
    Pausable,
    AccessControl,
    ERC20Permit,
    ERC20Votes,
    IIkaniERC20
{
    //---------------- Constants ----------------//

    bytes32 public constant MINTER_ADMIN_ROLE = keccak256("MINTER_ADMIN_ROLE");
    bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
    bytes32 public constant PAUSER_ADMIN_ROLE = keccak256("PAUSER_ADMIN_ROLE");
    bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");

    //---------------- Constructor ----------------//

    constructor(
        string memory name,
        string memory symbol,
        address admin
    )
        ERC20(name, symbol)
        ERC20Permit(name)
    {
        _grantRole(DEFAULT_ADMIN_ROLE, admin);
        _grantRole(MINTER_ADMIN_ROLE, admin);
        _grantRole(PAUSER_ADMIN_ROLE, admin);

        // Define separate admins for each role. This gives us the flexibility to be able to fully
        // renounce minter or pauser capabilities independently of each other while retaining
        // the ability to separate role-granters from role-bearers.
        _setRoleAdmin(MINTER_ROLE, MINTER_ADMIN_ROLE);
        _setRoleAdmin(PAUSER_ROLE, PAUSER_ADMIN_ROLE);
    }

    //---------------- Admin-Only External Functions ----------------//

    function pause()
        external
        onlyRole(PAUSER_ROLE)
    {
        _pause();
    }

    function unpause()
        external
        onlyRole(PAUSER_ROLE)
    {
        _unpause();
    }

    function mint(
        address to,
        uint256 amount,
        bytes32 receipt,
        bytes calldata receiptData
    )
        external
        override
        onlyRole(MINTER_ROLE)
    {
        _mint(to, amount);
        emit Minted(to, amount, receipt, receiptData);
    }

    //---------------- External Functions ----------------//

    function burn(
        address from,
        uint256 amount,
        bytes32 receipt,
        bytes calldata receiptData
    )
        external
        override
    {
        require(
            msg.sender == from,
            "Not authorized to burn"
        );
        _burn(from, amount);
        emit Burned(from, amount, receipt, receiptData);
    }

    /**
     * @notice Convenience function for the specific use case of burning exactly the permit amount.
     */
    function burnWithPermit(
        address from,
        uint256 amount,
        bytes32 receipt,
        bytes calldata receiptData,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    )
        external
        override
    {
        permit(from, msg.sender, amount, deadline, v, r, s);
        burnFrom(from, amount, receipt, receiptData);
    }

    //---------------- Public Functions ----------------//

    function burnFrom(
        address from,
        uint256 amount,
        bytes32 receipt,
        bytes calldata receiptData
    )
        public
        override
    {
        _spendAllowance(from, msg.sender, amount);
        _burn(from, amount);
        emit Burned(from, amount, receipt, receiptData);
    }

    //---------------- Overrides ----------------//

    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    )
        internal
        override
    {
        require(
            (
                !paused() ||
                to == address(0) ||
                from == address(0)
            ),
            "Transfers are disabled"
        );
        super._beforeTokenTransfer(from, to, amount);
    }

    //---------------- Trivial Overrides ----------------//

    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    )
        internal
        override(ERC20, ERC20Votes)
    {
        super._afterTokenTransfer(from, to, amount);
    }

    function _mint(
        address to,
        uint256 amount
    )
        internal
        override(ERC20, ERC20Votes)
    {
        super._mint(to, amount);
    }

    function _burn(
        address account,
        uint256 amount
    )
        internal
        override(ERC20, ERC20Votes)
    {
        super._burn(account, amount);
    }
}

File 46 of 73 : AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControl.sol";
import "./Context.sol";
import "./Strings.sol";
import "./ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

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

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `_msgSender()` is missing `role`.
     * Overriding this function changes the behavior of the {onlyRole} modifier.
     *
     * Format of the revert message is described in {_checkRole}.
     *
     * _Available since v4.6._
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        Strings.toHexString(uint160(account), 20),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * May emit a {RoleGranted} event.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }
}

File 47 of 73 : ERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./IERC20Metadata.sol";
import "./Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

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

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address from,
        address to,
        uint256 amount
    ) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

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

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

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

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

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

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

File 48 of 73 : draft-ERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/extensions/draft-ERC20Permit.sol)

pragma solidity ^0.8.0;

import "./draft-IERC20Permit.sol";
import "./ERC20.sol";
import "./draft-EIP712.sol";
import "./ECDSA.sol";
import "./Counters.sol";

/**
 * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 *
 * _Available since v3.4._
 */
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
    using Counters for Counters.Counter;

    mapping(address => Counters.Counter) private _nonces;

    // solhint-disable-next-line var-name-mixedcase
    bytes32 private constant _PERMIT_TYPEHASH =
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
    /**
     * @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
     * However, to ensure consistency with the upgradeable transpiler, we will continue
     * to reserve a slot.
     * @custom:oz-renamed-from _PERMIT_TYPEHASH
     */
    // solhint-disable-next-line var-name-mixedcase
    bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;

    /**
     * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
     *
     * It's a good idea to use the same `name` that is defined as the ERC20 token name.
     */
    constructor(string memory name) EIP712(name, "1") {}

    /**
     * @dev See {IERC20Permit-permit}.
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= deadline, "ERC20Permit: expired deadline");

        bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));

        bytes32 hash = _hashTypedDataV4(structHash);

        address signer = ECDSA.recover(hash, v, r, s);
        require(signer == owner, "ERC20Permit: invalid signature");

        _approve(owner, spender, value);
    }

    /**
     * @dev See {IERC20Permit-nonces}.
     */
    function nonces(address owner) public view virtual override returns (uint256) {
        return _nonces[owner].current();
    }

    /**
     * @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view override returns (bytes32) {
        return _domainSeparatorV4();
    }

    /**
     * @dev "Consume a nonce": return the current value and increment.
     *
     * _Available since v4.1._
     */
    function _useNonce(address owner) internal virtual returns (uint256 current) {
        Counters.Counter storage nonce = _nonces[owner];
        current = nonce.current();
        nonce.increment();
    }
}

File 49 of 73 : ERC20Votes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Votes.sol)

pragma solidity ^0.8.0;

import "./draft-ERC20Permit.sol";
import "./Math.sol";
import "./IVotes.sol";
import "./SafeCast.sol";
import "./ECDSA.sol";

/**
 * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's,
 * and supports token supply up to 2^224^ - 1, while COMP is limited to 2^96^ - 1.
 *
 * NOTE: If exact COMP compatibility is required, use the {ERC20VotesComp} variant of this module.
 *
 * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either
 * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting
 * power can be queried through the public accessors {getVotes} and {getPastVotes}.
 *
 * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it
 * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked.
 *
 * _Available since v4.2._
 */
abstract contract ERC20Votes is IVotes, ERC20Permit {
    struct Checkpoint {
        uint32 fromBlock;
        uint224 votes;
    }

    bytes32 private constant _DELEGATION_TYPEHASH =
        keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");

    mapping(address => address) private _delegates;
    mapping(address => Checkpoint[]) private _checkpoints;
    Checkpoint[] private _totalSupplyCheckpoints;

    /**
     * @dev Get the `pos`-th checkpoint for `account`.
     */
    function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoint memory) {
        return _checkpoints[account][pos];
    }

    /**
     * @dev Get number of checkpoints for `account`.
     */
    function numCheckpoints(address account) public view virtual returns (uint32) {
        return SafeCast.toUint32(_checkpoints[account].length);
    }

    /**
     * @dev Get the address `account` is currently delegating to.
     */
    function delegates(address account) public view virtual override returns (address) {
        return _delegates[account];
    }

    /**
     * @dev Gets the current votes balance for `account`
     */
    function getVotes(address account) public view virtual override returns (uint256) {
        uint256 pos = _checkpoints[account].length;
        return pos == 0 ? 0 : _checkpoints[account][pos - 1].votes;
    }

    /**
     * @dev Retrieve the number of votes for `account` at the end of `blockNumber`.
     *
     * Requirements:
     *
     * - `blockNumber` must have been already mined
     */
    function getPastVotes(address account, uint256 blockNumber) public view virtual override returns (uint256) {
        require(blockNumber < block.number, "ERC20Votes: block not yet mined");
        return _checkpointsLookup(_checkpoints[account], blockNumber);
    }

    /**
     * @dev Retrieve the `totalSupply` at the end of `blockNumber`. Note, this value is the sum of all balances.
     * It is but NOT the sum of all the delegated votes!
     *
     * Requirements:
     *
     * - `blockNumber` must have been already mined
     */
    function getPastTotalSupply(uint256 blockNumber) public view virtual override returns (uint256) {
        require(blockNumber < block.number, "ERC20Votes: block not yet mined");
        return _checkpointsLookup(_totalSupplyCheckpoints, blockNumber);
    }

    /**
     * @dev Lookup a value in a list of (sorted) checkpoints.
     */
    function _checkpointsLookup(Checkpoint[] storage ckpts, uint256 blockNumber) private view returns (uint256) {
        // We run a binary search to look for the earliest checkpoint taken after `blockNumber`.
        //
        // During the loop, the index of the wanted checkpoint remains in the range [low-1, high).
        // With each iteration, either `low` or `high` is moved towards the middle of the range to maintain the invariant.
        // - If the middle checkpoint is after `blockNumber`, we look in [low, mid)
        // - If the middle checkpoint is before or equal to `blockNumber`, we look in [mid+1, high)
        // Once we reach a single value (when low == high), we've found the right checkpoint at the index high-1, if not
        // out of bounds (in which case we're looking too far in the past and the result is 0).
        // Note that if the latest checkpoint available is exactly for `blockNumber`, we end up with an index that is
        // past the end of the array, so we technically don't find a checkpoint after `blockNumber`, but it works out
        // the same.
        uint256 high = ckpts.length;
        uint256 low = 0;
        while (low < high) {
            uint256 mid = Math.average(low, high);
            if (ckpts[mid].fromBlock > blockNumber) {
                high = mid;
            } else {
                low = mid + 1;
            }
        }

        return high == 0 ? 0 : ckpts[high - 1].votes;
    }

    /**
     * @dev Delegate votes from the sender to `delegatee`.
     */
    function delegate(address delegatee) public virtual override {
        _delegate(_msgSender(), delegatee);
    }

    /**
     * @dev Delegates votes from signer to `delegatee`
     */
    function delegateBySig(
        address delegatee,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) public virtual override {
        require(block.timestamp <= expiry, "ERC20Votes: signature expired");
        address signer = ECDSA.recover(
            _hashTypedDataV4(keccak256(abi.encode(_DELEGATION_TYPEHASH, delegatee, nonce, expiry))),
            v,
            r,
            s
        );
        require(nonce == _useNonce(signer), "ERC20Votes: invalid nonce");
        _delegate(signer, delegatee);
    }

    /**
     * @dev Maximum token supply. Defaults to `type(uint224).max` (2^224^ - 1).
     */
    function _maxSupply() internal view virtual returns (uint224) {
        return type(uint224).max;
    }

    /**
     * @dev Snapshots the totalSupply after it has been increased.
     */
    function _mint(address account, uint256 amount) internal virtual override {
        super._mint(account, amount);
        require(totalSupply() <= _maxSupply(), "ERC20Votes: total supply risks overflowing votes");

        _writeCheckpoint(_totalSupplyCheckpoints, _add, amount);
    }

    /**
     * @dev Snapshots the totalSupply after it has been decreased.
     */
    function _burn(address account, uint256 amount) internal virtual override {
        super._burn(account, amount);

        _writeCheckpoint(_totalSupplyCheckpoints, _subtract, amount);
    }

    /**
     * @dev Move voting power when tokens are transferred.
     *
     * Emits a {DelegateVotesChanged} event.
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual override {
        super._afterTokenTransfer(from, to, amount);

        _moveVotingPower(delegates(from), delegates(to), amount);
    }

    /**
     * @dev Change delegation for `delegator` to `delegatee`.
     *
     * Emits events {DelegateChanged} and {DelegateVotesChanged}.
     */
    function _delegate(address delegator, address delegatee) internal virtual {
        address currentDelegate = delegates(delegator);
        uint256 delegatorBalance = balanceOf(delegator);
        _delegates[delegator] = delegatee;

        emit DelegateChanged(delegator, currentDelegate, delegatee);

        _moveVotingPower(currentDelegate, delegatee, delegatorBalance);
    }

    function _moveVotingPower(
        address src,
        address dst,
        uint256 amount
    ) private {
        if (src != dst && amount > 0) {
            if (src != address(0)) {
                (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[src], _subtract, amount);
                emit DelegateVotesChanged(src, oldWeight, newWeight);
            }

            if (dst != address(0)) {
                (uint256 oldWeight, uint256 newWeight) = _writeCheckpoint(_checkpoints[dst], _add, amount);
                emit DelegateVotesChanged(dst, oldWeight, newWeight);
            }
        }
    }

    function _writeCheckpoint(
        Checkpoint[] storage ckpts,
        function(uint256, uint256) view returns (uint256) op,
        uint256 delta
    ) private returns (uint256 oldWeight, uint256 newWeight) {
        uint256 pos = ckpts.length;
        oldWeight = pos == 0 ? 0 : ckpts[pos - 1].votes;
        newWeight = op(oldWeight, delta);

        if (pos > 0 && ckpts[pos - 1].fromBlock == block.number) {
            ckpts[pos - 1].votes = SafeCast.toUint224(newWeight);
        } else {
            ckpts.push(Checkpoint({fromBlock: SafeCast.toUint32(block.number), votes: SafeCast.toUint224(newWeight)}));
        }
    }

    function _add(uint256 a, uint256 b) private pure returns (uint256) {
        return a + b;
    }

    function _subtract(uint256 a, uint256 b) private pure returns (uint256) {
        return a - b;
    }
}

File 50 of 73 : Pausable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)

pragma solidity ^0.8.0;

import "./Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        require(!paused(), "Pausable: paused");
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        require(paused(), "Pausable: not paused");
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

File 51 of 73 : IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControl {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}

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

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 53 of 73 : Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

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

pragma solidity ^0.8.0;

import "./IERC165.sol";

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

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

pragma solidity ^0.8.0;

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

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

pragma solidity ^0.8.0;

import "./IERC20.sol";

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

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

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

File 57 of 73 : draft-IERC20Permit.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
interface IERC20Permit {
    /**
     * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
     * given ``owner``'s signed approval.
     *
     * IMPORTANT: The same issues {IERC20-approve} has related to transaction
     * ordering also apply here.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `deadline` must be a timestamp in the future.
     * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
     * over the EIP712-formatted function arguments.
     * - the signature must use ``owner``'s current nonce (see {nonces}).
     *
     * For more information on the signature format, see the
     * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
     * section].
     */
    function permit(
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
     * @dev Returns the current nonce for `owner`. This value must be
     * included whenever a signature is generated for {permit}.
     *
     * Every successful call to {permit} increases ``owner``'s nonce by one. This
     * prevents a signature from being used multiple times.
     */
    function nonces(address owner) external view returns (uint256);

    /**
     * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
     */
    // solhint-disable-next-line func-name-mixedcase
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

File 58 of 73 : draft-EIP712.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;
    address private immutable _CACHED_THIS;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _CACHED_THIS = address(this);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

File 59 of 73 : ECDSA.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "./Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        // Check the signature length
        // - case 65: r,s,v signature (standard)
        // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else if (signature.length == 64) {
            bytes32 r;
            bytes32 vs;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                vs := mload(add(signature, 0x40))
            }
            return tryRecover(hash, r, vs);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

File 60 of 73 : Counters.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)

pragma solidity ^0.8.0;

/**
 * @title Counters
 * @author Matt Condon (@shrugs)
 * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
 * of elements in a mapping, issuing ERC721 ids, or counting request ids.
 *
 * Include with `using Counters for Counters.Counter;`
 */
library Counters {
    struct Counter {
        // This variable should never be directly accessed by users of the library: interactions must be restricted to
        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
        // this feature: see https://github.com/ethereum/solidity/issues/4637
        uint256 _value; // default: 0
    }

    function current(Counter storage counter) internal view returns (uint256) {
        return counter._value;
    }

    function increment(Counter storage counter) internal {
        unchecked {
            counter._value += 1;
        }
    }

    function decrement(Counter storage counter) internal {
        uint256 value = counter._value;
        require(value > 0, "Counter: decrement overflow");
        unchecked {
            counter._value = value - 1;
        }
    }

    function reset(Counter storage counter) internal {
        counter._value = 0;
    }
}

File 61 of 73 : Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`.
        // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
        // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
        // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
        // good first aproximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1;
        uint256 x = a;
        if (x >> 128 > 0) {
            x >>= 128;
            result <<= 64;
        }
        if (x >> 64 > 0) {
            x >>= 64;
            result <<= 32;
        }
        if (x >> 32 > 0) {
            x >>= 32;
            result <<= 16;
        }
        if (x >> 16 > 0) {
            x >>= 16;
            result <<= 8;
        }
        if (x >> 8 > 0) {
            x >>= 8;
            result <<= 4;
        }
        if (x >> 4 > 0) {
            x >>= 4;
            result <<= 2;
        }
        if (x >> 2 > 0) {
            result <<= 1;
        }

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        uint256 result = sqrt(a);
        if (rounding == Rounding.Up && result * result < a) {
            result += 1;
        }
        return result;
    }
}

File 62 of 73 : IVotes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (governance/utils/IVotes.sol)
pragma solidity ^0.8.0;

/**
 * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
 *
 * _Available since v4.5._
 */
interface IVotes {
    /**
     * @dev Emitted when an account changes their delegate.
     */
    event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);

    /**
     * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of votes.
     */
    event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);

    /**
     * @dev Returns the current amount of votes that `account` has.
     */
    function getVotes(address account) external view returns (uint256);

    /**
     * @dev Returns the amount of votes that `account` had at the end of a past block (`blockNumber`).
     */
    function getPastVotes(address account, uint256 blockNumber) external view returns (uint256);

    /**
     * @dev Returns the total supply of votes available at the end of a past block (`blockNumber`).
     *
     * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
     * Votes that have not been delegated are still part of total supply, even though they would not participate in a
     * vote.
     */
    function getPastTotalSupply(uint256 blockNumber) external view returns (uint256);

    /**
     * @dev Returns the delegate that `account` has chosen.
     */
    function delegates(address account) external view returns (address);

    /**
     * @dev Delegates votes from the sender to `delegatee`.
     */
    function delegate(address delegatee) external;

    /**
     * @dev Delegates votes from signer to `delegatee`.
     */
    function delegateBySig(
        address delegatee,
        uint256 nonce,
        uint256 expiry,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;
}

File 63 of 73 : SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248) {
        require(value >= type(int248).min && value <= type(int248).max, "SafeCast: value doesn't fit in 248 bits");
        return int248(value);
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240) {
        require(value >= type(int240).min && value <= type(int240).max, "SafeCast: value doesn't fit in 240 bits");
        return int240(value);
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232) {
        require(value >= type(int232).min && value <= type(int232).max, "SafeCast: value doesn't fit in 232 bits");
        return int232(value);
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224) {
        require(value >= type(int224).min && value <= type(int224).max, "SafeCast: value doesn't fit in 224 bits");
        return int224(value);
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216) {
        require(value >= type(int216).min && value <= type(int216).max, "SafeCast: value doesn't fit in 216 bits");
        return int216(value);
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208) {
        require(value >= type(int208).min && value <= type(int208).max, "SafeCast: value doesn't fit in 208 bits");
        return int208(value);
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200) {
        require(value >= type(int200).min && value <= type(int200).max, "SafeCast: value doesn't fit in 200 bits");
        return int200(value);
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192) {
        require(value >= type(int192).min && value <= type(int192).max, "SafeCast: value doesn't fit in 192 bits");
        return int192(value);
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184) {
        require(value >= type(int184).min && value <= type(int184).max, "SafeCast: value doesn't fit in 184 bits");
        return int184(value);
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176) {
        require(value >= type(int176).min && value <= type(int176).max, "SafeCast: value doesn't fit in 176 bits");
        return int176(value);
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168) {
        require(value >= type(int168).min && value <= type(int168).max, "SafeCast: value doesn't fit in 168 bits");
        return int168(value);
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160) {
        require(value >= type(int160).min && value <= type(int160).max, "SafeCast: value doesn't fit in 160 bits");
        return int160(value);
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152) {
        require(value >= type(int152).min && value <= type(int152).max, "SafeCast: value doesn't fit in 152 bits");
        return int152(value);
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144) {
        require(value >= type(int144).min && value <= type(int144).max, "SafeCast: value doesn't fit in 144 bits");
        return int144(value);
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136) {
        require(value >= type(int136).min && value <= type(int136).max, "SafeCast: value doesn't fit in 136 bits");
        return int136(value);
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128) {
        require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
        return int128(value);
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120) {
        require(value >= type(int120).min && value <= type(int120).max, "SafeCast: value doesn't fit in 120 bits");
        return int120(value);
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112) {
        require(value >= type(int112).min && value <= type(int112).max, "SafeCast: value doesn't fit in 112 bits");
        return int112(value);
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104) {
        require(value >= type(int104).min && value <= type(int104).max, "SafeCast: value doesn't fit in 104 bits");
        return int104(value);
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96) {
        require(value >= type(int96).min && value <= type(int96).max, "SafeCast: value doesn't fit in 96 bits");
        return int96(value);
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88) {
        require(value >= type(int88).min && value <= type(int88).max, "SafeCast: value doesn't fit in 88 bits");
        return int88(value);
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80) {
        require(value >= type(int80).min && value <= type(int80).max, "SafeCast: value doesn't fit in 80 bits");
        return int80(value);
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72) {
        require(value >= type(int72).min && value <= type(int72).max, "SafeCast: value doesn't fit in 72 bits");
        return int72(value);
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64) {
        require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
        return int64(value);
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56) {
        require(value >= type(int56).min && value <= type(int56).max, "SafeCast: value doesn't fit in 56 bits");
        return int56(value);
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48) {
        require(value >= type(int48).min && value <= type(int48).max, "SafeCast: value doesn't fit in 48 bits");
        return int48(value);
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40) {
        require(value >= type(int40).min && value <= type(int40).max, "SafeCast: value doesn't fit in 40 bits");
        return int40(value);
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32) {
        require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
        return int32(value);
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24) {
        require(value >= type(int24).min && value <= type(int24).max, "SafeCast: value doesn't fit in 24 bits");
        return int24(value);
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16) {
        require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
        return int16(value);
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8) {
        require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
        return int8(value);
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}

File 64 of 73 : HeapTest.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { MinHeap } from "../lib/MinHeap.sol";

contract HeapTest {
    using MinHeap for MinHeap.Heap;

    MinHeap.Heap internal _heap;

    function size()
        external
        view
        returns (uint256)
    {
        return _heap.length;
    }

    function insert(
        uint256 value
    )
        external
    {
        _heap.insert(value);
    }

    function insertMany(
        uint256[] calldata values
    )
        external
    {
        for (uint256 i = 0; i < values.length; i++) {
            _heap.insert(values[i]);
        }
    }

    function peek()
        external
        view
        returns (uint256)
    {
        return _heap.safePeek();
    }

    function pop()
        external
    {
        _heap.popMin();
    }

    function popMany(
        uint256 count
    )
        external
        returns (uint256[] memory)
    {
        uint256[] memory result = new uint256[](count);
        for (uint256 i = 0; i < count; i++) {
            result[i] = _heap.safePeek();
            _heap.popMin();
        }
        return result;
    }

    function heap(
        uint256 index
    )
        external
        view
        returns (uint256)
    {
        return _heap.data[index];
    }

    function read(
        uint256 start,
        uint256 end
    )
        public
        view
        returns (uint256[] memory)
    {
        uint256 length = end - start;
        uint256[] memory result = new uint256[](length);
        for (uint256 i = 0; i < length; i++) {
            result[i] = _heap.data[start + i];
        }
        return result;
    }

    function readAll()
        external
        view
        returns (uint256[] memory)
    {
        return read(0, _heap.length);
    }
}

File 65 of 73 : IkaniV1.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { PausableUpgradeable } from "../../deps/PausableUpgradeable.sol";

import { IIkaniV1 } from "./interfaces/IIkaniV1.sol";
import { IIkaniV1MetadataController } from "./interfaces/IIkaniV1MetadataController.sol";
import { ContractUriUpgradeable } from "./lib/ContractUriUpgradeable.sol";
import { ERC721SequentialUpgradeable } from "./lib/ERC721SequentialUpgradeable.sol";
import { PersonalSign } from "./lib/PersonalSign.sol";
import { WithdrawableUpgradeable } from "./lib/WithdrawableUpgradeable.sol";

/**
 * @title IkaniV1
 * @author Cyborg Labs, LLC
 *
 * @notice The IKANI.AI ERC-721 NFT.
 */
contract IkaniV1 is
    ERC721SequentialUpgradeable,
    ContractUriUpgradeable,
    WithdrawableUpgradeable,
    PausableUpgradeable,
    IIkaniV1
{
    //---------------- Constants ----------------//

    uint256 public constant STARTING_INDEX_ADD_BLOCKS = 10;

    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    uint256 public immutable MAX_SUPPLY; // e.g. 8888

    //---------------- Storage ----------------//

    IIkaniV1MetadataController internal _METADATA_CONTROLLER_;

    address internal _MINT_SIGNER_;

    /// @dev The set of message digests signed and consumed for minting.
    mapping(bytes32 => bool) internal _USED_MINT_DIGESTS_;

    /// @dev Poem text and metadata by token ID.
    mapping(uint256 => IIkaniV1.Poem) internal _POEM_INFO_;

    /// @dev Series information by index.
    mapping(uint256 => IIkaniV1.Series) internal _SERIES_INFO_;

    /// @dev Index of the current series available for minting.
    uint256 internal _CURRENT_SERIES_INDEX_;

    //---------------- Constructor & Initializer ----------------//

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(
        uint256 maxSupply
    )
        initializer
    {
        MAX_SUPPLY = maxSupply;
    }

    function initialize(
        IIkaniV1MetadataController metadataController,
        address mintSigner
    )
        external
        initializer
    {
        __ERC721Sequential_init("IKANI.AI", "IKANI");
        __ContractUri_init();
        __Withdrawable_init();
        __Pausable_init();

        _METADATA_CONTROLLER_ = metadataController;
        _MINT_SIGNER_ = mintSigner;
    }

    //---------------- Owner-Only External Functions ----------------//

    function pause()
        external
        onlyOwner
    {
        _pause();
    }

    function unpause()
        external
        onlyOwner
    {
        _unpause();
    }

    function setContractUri(
        string memory contractUri
    )
        external
        onlyOwner
    {
        _setContractUri(contractUri);
    }

    function setMetadataController(
        IIkaniV1MetadataController metadataController
    )
        external
        onlyOwner
    {
        _METADATA_CONTROLLER_ = metadataController;
    }

    function setMintSigner(
        address mintSigner
    )
        external
        onlyOwner
    {
        _MINT_SIGNER_ = mintSigner;
    }

    function setPoemInfo(
        uint256[] calldata tokenIds,
        IIkaniV1.Poem[] calldata poemInfo
    )
        external
        onlyOwner
    {
        // Note: To save gas, we don't check that the token was minted; however,
        //       the owner should only call this function with minted token IDs.

        uint256 n = tokenIds.length;

        require(
            poemInfo.length == n,
            "Params length mismatch"
        );

        for (uint256 i = 0; i < n; i++) {
            require(
                bytes(poemInfo[i].poemText).length != 0,
                "Poem text cannot be empty"
            );
            _POEM_INFO_[i] = poemInfo[i];
        }
    }

    function setSeriesInfo(
        uint256 seriesIndex,
        string calldata name,
        bytes32 provenanceHash
    )
        external
        onlyOwner
    {
        IIkaniV1.Series storage series = _SERIES_INFO_[seriesIndex];

        series.name = name;
        series.provenanceHash = provenanceHash;

        emit SetSeriesInfo(
            seriesIndex,
            name,
            provenanceHash
        );
    }

    function endCurrentSeries(
        uint256 poemCreationDeadline
    )
        external
        onlyOwner
    {
        uint256 seriesIndex = _CURRENT_SERIES_INDEX_++;

        IIkaniV1.Series storage series = _SERIES_INFO_[seriesIndex];

        uint256 maxTokenIdExclusive = getNextTokenId();
        uint256 startingIndexBlockNumber = block.number + STARTING_INDEX_ADD_BLOCKS;

        series.poemCreationDeadline = poemCreationDeadline;
        series.maxTokenIdExclusive = maxTokenIdExclusive;
        series.startingIndexBlockNumber = startingIndexBlockNumber;

        emit EndedSeries(
            seriesIndex,
            poemCreationDeadline,
            maxTokenIdExclusive,
            startingIndexBlockNumber
        );
    }

    function advancePoemCreationDeadline(
        uint256 seriesIndex,
        uint256 poemCreationDeadline
    )
        external
        onlyOwner
    {
        IIkaniV1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            poemCreationDeadline > series.poemCreationDeadline,
            "Can only move the deadline forward"
        );

        series.poemCreationDeadline = poemCreationDeadline;

        emit AdvancedPoemCreationDeadline(
            seriesIndex,
            poemCreationDeadline
        );
    }

    function mintByOwner(
        address[] calldata recipients
    )
        external
        onlyOwner
    {
        uint256 n = recipients.length;

        for (uint256 i = 0; i < n; i++) {
            // Note: Intentionally not using _safeMint().
            _mint(recipients[i]);
        }

        require(
            getNextTokenId() <= MAX_SUPPLY,
            "Global max supply exceeded"
        );
    }

    function expire(
        uint256 tokenId
    )
        external
        onlyOwner
    {
        require(
            bytes(_POEM_INFO_[tokenId].poemText).length == 0,
            "Cannot expire a finished poem"
        );

        uint256 seriesIndex = getPoemSeriesIndex(tokenId);

        IIkaniV1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            series.startingIndexBlockNumber != 0,
            "Series not ended"
        );
        require(
            block.timestamp > series.poemCreationDeadline,
            "Token has not expired"
        );

        _burn(tokenId);
    }

    function expireBatch(
        uint256[] calldata tokenIds,
        uint256 seriesIndex
    )
        external
        onlyOwner
    {
        require(
            seriesIndex <= _CURRENT_SERIES_INDEX_,
            "Invalid series index"
        );

        IIkaniV1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            series.startingIndexBlockNumber != 0,
            "Series not ended"
        );
        require(
            block.timestamp > series.poemCreationDeadline,
            "Series has not expired"
        );

        uint256 n = tokenIds.length;

        uint256 maxTokenIdExclusive = series.maxTokenIdExclusive;
        for (uint256 i = 0; i < n; i++) {
            require(
                tokenIds[i] < maxTokenIdExclusive,
                "Token ID not part of the series"
            );
        }

        if (seriesIndex > 0) {
            uint256 startTokenId = _SERIES_INFO_[seriesIndex - 1].maxTokenIdExclusive;
            for (uint256 i = 0; i < n; i++) {
                require(
                    tokenIds[i] >= startTokenId,
                    "Token ID not part of the series"
                );
            }
        }

        for (uint256 i = 0; i < n; i++) {
            require(
                bytes(_POEM_INFO_[tokenIds[i]].poemText).length == 0,
                "Cannot expire a finished poem"
            );
            _burn(tokenIds[i]);
        }
    }

    //---------------- Other State-Changing External Functions ----------------//

    function mint(
        IIkaniV1.MintArgs calldata mintArgs,
        bytes calldata signature
    )
        external
        payable
        whenNotPaused
    {
        require(
            mintArgs.seriesIndex == _CURRENT_SERIES_INDEX_,
            "Not the current series"
        );

        require(
            msg.value == mintArgs.mintPrice,
            "Wrong msg.value"
        );

        address sender = msg.sender;
        bytes memory message = abi.encode(
            sender,
            mintArgs
        );
        bytes32 messageDigest = keccak256(message);

        // Only allow one mint per message/digest/signature.
        require(
            !_USED_MINT_DIGESTS_[messageDigest],
            "Mint digest already used"
        );
        _USED_MINT_DIGESTS_[messageDigest] = true;

        // Note: Since the only signer is our admin, we don't need EIP-712.
        require(
            PersonalSign.isValidSignature(messageDigest, signature, _MINT_SIGNER_),
            "Invalid signature"
        );

        // Note: Intentionally not using _safeMint().
        uint256 tokenId = _mint(sender);

        require(
            tokenId < mintArgs.maxTokenIdExclusive,
            "Series max supply exceeded"
        );
        require(
            tokenId < MAX_SUPPLY,
            "Global max supply exceeded"
        );
    }

    function trySetSeriesStartingIndex(
        uint256 seriesIndex
    )
        external
        whenNotPaused
    {
        IIkaniV1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            !series.startingIndexWasSet,
            "Starting index already set"
        );

        uint256 targetBlockNumber = series.startingIndexBlockNumber;
        require(
            targetBlockNumber != 0,
            "Series not ended"
        );

        require(
            block.number >= targetBlockNumber,
            "Starting index block not reached"
        );

        // If the hash for the target block is not available, set a new block number and exit.
        if (block.number - targetBlockNumber > 256) {
            uint256 newStartingIndexBlockNumber = block.number + STARTING_INDEX_ADD_BLOCKS;
            series.startingIndexBlockNumber = newStartingIndexBlockNumber;
            emit ResetSeriesStartingIndexBlockNumber(
                seriesIndex,
                newStartingIndexBlockNumber
            );
            return;
        }

        uint256 seriesSupply = getSeriesSupply(seriesIndex);
        uint256 startingIndex = uint256(blockhash(targetBlockNumber)) % seriesSupply;

        series.startingIndex = startingIndex;
        series.startingIndexWasSet = true;

        emit SetSeriesStartingIndex(
            seriesIndex,
            startingIndex
        );
    }

    //---------------- View-Only External Functions ----------------//

    function getMetadataController()
        external
        view
        returns (IIkaniV1MetadataController)
    {
        return _METADATA_CONTROLLER_;
    }

    function getMintSigner()
        external
        view
        returns (address)
    {
        return _MINT_SIGNER_;
    }

    function isUsedMintDigest(
        bytes32 digest
    )
        external
        view
        returns (bool)
    {
        return _USED_MINT_DIGESTS_[digest];
    }

    function getPoemInfo(
        uint256 tokenId
    )
        external
        view
        returns (IIkaniV1.Poem memory)
    {
        require(
            _exists(tokenId),
            "Token does not exist"
        );
        return _POEM_INFO_[tokenId];
    }

    function getSeriesInfo(
        uint256 seriesIndex
    )
        external
        view
        returns (IIkaniV1.Series memory)
    {
        return _SERIES_INFO_[seriesIndex];
    }

    function getCurrentSeriesIndex()
        external
        view
        returns (uint256)
    {
        return _CURRENT_SERIES_INDEX_;
    }

    function exists(
        uint256 tokenId
    )
        external
        view
        returns (bool)
    {
        return _exists(tokenId);
    }

    //---------------- Public Functions ----------------//

    function getPoemSeriesIndex(
        uint256 tokenId
    )
        public
        view
        returns (uint256)
    {
        require(
            _exists(tokenId),
            "Token does not exist"
        );

        uint256 currentSeriesIndex = _CURRENT_SERIES_INDEX_;
        uint256 seriesIndex;
        for (seriesIndex = 0; seriesIndex < currentSeriesIndex; seriesIndex++) {
            IIkaniV1.Series storage series = _SERIES_INFO_[seriesIndex];

            if (tokenId < series.maxTokenIdExclusive) {
                break;
            }
        }
        return seriesIndex;
    }

    function getSeriesSupply(
        uint256 seriesIndex
    )
        public
        view
        returns (uint256)
    {
        IIkaniV1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            series.startingIndexBlockNumber != 0,
            "Series not ended"
        );

        uint256 maxTokenIdExclusive = series.maxTokenIdExclusive;

        if (seriesIndex == 0) {
            return maxTokenIdExclusive;
        }

        IIkaniV1.Series storage previousSeries = _SERIES_INFO_[seriesIndex - 1];

        return maxTokenIdExclusive - previousSeries.maxTokenIdExclusive;
    }

    function tokenURI(
        uint256 tokenId
    )
        public
        view
        override
        returns (string memory)
    {
        return _METADATA_CONTROLLER_.tokenURI(tokenId);
    }
}

File 66 of 73 : IIkaniV1.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

/**
 * @title IIkaniV1
 * @author Cyborg Labs, LLC
 *
 * @notice Interface for the IkaniV1 ERC-721 NFT contract.
 */
interface IIkaniV1 {

    //---------------- Enums ----------------//

    enum Theme {
        NULL,
        SKY,
        OCEAN,
        MOUNTAIN,
        FLOWERS,
        TBA_THEME_5,
        TBA_THEME_6,
        TBA_THEME_7,
        TBA_THEME_8
    }

    enum Season {
        NONE,
        SPRING,
        SUMMER,
        AUTUMN,
        WINTER
    }

    enum Fabric {
        NULL,
        KOYAMAKI,
        SEIGAIHA,
        NAMI,
        KUMO,
        TBA_FABRIC_5,
        TBA_FABRIC_6,
        TBA_FABRIC_7,
        TBA_FABRIC_8
    }

    enum Foil {
        NONE,
        GOLD,
        PLATINUM,
        SUI_GENERIS
    }

    //---------------- Structs ----------------//

    /**
     * @notice The poem text and metadata traits.
     */
    // TODO: Make sure these fields are packed efficiently.
    struct Poem {
        string poemText;
        Theme theme;
        Season season;
        Fabric fabric;
        Foil foil;
    }

    /**
     * @notice Information about a series within the collection.
     */
    struct Series {
        string name;
        bytes32 provenanceHash;
        uint256 poemCreationDeadline;
        uint256 maxTokenIdExclusive;
        uint256 startingIndexBlockNumber;
        uint256 startingIndex;
        bool startingIndexWasSet;
    }

    /**
     * @notice Arguments to be signed by the mint authority to authorize a mint.
     */
    struct MintArgs {
        uint256 seriesIndex;
        uint256 mintPrice;
        uint256 maxTokenIdExclusive;
        uint256 nonce;
    }

    //---------------- Events ----------------//

    event SetSeriesInfo(
        uint256 indexed seriesIndex,
        string name,
        bytes32 provenanceHash
    );

    event EndedSeries(
        uint256 indexed seriesIndex,
        uint256 poemCreationDeadline,
        uint256 maxTokenIdExclusive,
        uint256 startingIndexBlockNumber
    );

    event AdvancedPoemCreationDeadline(
        uint256 indexed seriesIndex,
        uint256 poemCreationDeadline
    );

    event ResetSeriesStartingIndexBlockNumber(
        uint256 indexed seriesIndex,
        uint256 startingIndexBlockNumber
    );

    event SetSeriesStartingIndex(
        uint256 indexed seriesIndex,
        uint256 startingIndex
    );
}

File 67 of 73 : IkaniV1_1.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { PausableUpgradeable } from "../../deps/PausableUpgradeable.sol";

import { IIkaniV1_1 } from "./interfaces/IIkaniV1_1.sol";
import { IIkaniV1MetadataController } from "./interfaces/IIkaniV1MetadataController.sol";
import { ContractUriUpgradeable } from "./lib/ContractUriUpgradeable.sol";
import { ERC721SequentialUpgradeable } from "./lib/ERC721SequentialUpgradeable.sol";
import { PersonalSign } from "./lib/PersonalSign.sol";
import { WithdrawableUpgradeable } from "./lib/WithdrawableUpgradeable.sol";

/**
 * @title IkaniV1_1
 * @author Cyborg Labs, LLC
 *
 * @notice The IKANI.AI ERC-721 NFT.
 */
contract IkaniV1_1 is
    ERC721SequentialUpgradeable,
    ContractUriUpgradeable,
    WithdrawableUpgradeable,
    PausableUpgradeable,
    IIkaniV1_1
{
    //---------------- Constants ----------------//

    uint256 public constant STARTING_INDEX_ADD_BLOCKS = 10;

    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    uint256 public immutable MAX_SUPPLY; // e.g. 8888

    //---------------- Storage V1 ----------------//

    IIkaniV1MetadataController internal _METADATA_CONTROLLER_;

    address internal _MINT_SIGNER_;

    /// @dev The set of message digests signed and consumed for minting.
    mapping(bytes32 => bool) internal _USED_MINT_DIGESTS_;

    /// @dev DEPRECATED: Poem text and metadata by token ID.
    mapping(uint256 => bytes) internal __DEPRECATED_POEM_INFO_;

    /// @dev Series information by index.
    mapping(uint256 => IIkaniV1_1.Series) internal _SERIES_INFO_;

    /// @dev Index of the current series available for minting.
    uint256 internal _CURRENT_SERIES_INDEX_;

    //---------------- Storage V1_1 ----------------//

    /// @dev Poem text by token ID.
    mapping(uint256 => string) internal _POEM_TEXT_;

    /// @dev Metadata traits by token ID.
    mapping(uint256 => IIkaniV1_1.PoemTraits) internal _POEM_TRAITS_;

    //---------------- Constructor & Initializer ----------------//

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor(
        uint256 maxSupply
    )
        initializer
    {
        MAX_SUPPLY = maxSupply;
    }

    //---------------- Owner-Only External Functions ----------------//

    function pause()
        external
        onlyOwner
    {
        _pause();
    }

    function unpause()
        external
        onlyOwner
    {
        _unpause();
    }

    function setContractUri(
        string memory contractUri
    )
        external
        onlyOwner
    {
        _setContractUri(contractUri);
    }

    function setMetadataController(
        IIkaniV1MetadataController metadataController
    )
        external
        onlyOwner
    {
        _METADATA_CONTROLLER_ = metadataController;
    }

    function setMintSigner(
        address mintSigner
    )
        external
        onlyOwner
    {
        _MINT_SIGNER_ = mintSigner;
    }

    function setPoemText(
        uint256[] calldata tokenIds,
        string[] calldata poemText
    )
        external
        onlyOwner
    {
        // Note: To save gas, we don't check that the token was minted; however,
        //       the owner should only call this function with minted token IDs.

        uint256 n = tokenIds.length;

        require(
            poemText.length == n,
            "Params length mismatch"
        );

        for (uint256 i = 0; i < n;) {
            _POEM_TEXT_[tokenIds[i]] = poemText[i];
            unchecked { ++i; }
        }
    }

    function setPoemTraits(
        uint256[] calldata tokenIds,
        IIkaniV1_1.PoemTraits[] calldata poemTraits
    )
        external
        onlyOwner
    {
        // Note: To save gas, we don't check that the token was minted; however,
        //       the owner should only call this function with minted token IDs.

        uint256 n = tokenIds.length;

        require(
            poemTraits.length == n,
            "Params length mismatch"
        );

        for (uint256 i = 0; i < n;) {
            uint256 tokenId = tokenIds[i];
            IIkaniV1_1.PoemTraits memory traits = poemTraits[i];
            require(
                traits.theme != IIkaniV1_1.Theme.NULL,
                "Theme cannot be null"
            );
            require(
                traits.fabric != IIkaniV1_1.Fabric.NULL,
                "Fabric cannot be null"
            );
            _POEM_TRAITS_[tokenId] = traits;
            emit FinishedPoem(tokenId);
            unchecked { ++i; }
        }
    }

    function setSeriesInfo(
        uint256 seriesIndex,
        string calldata name,
        bytes32 provenanceHash
    )
        external
        onlyOwner
    {
        IIkaniV1_1.Series storage series = _SERIES_INFO_[seriesIndex];

        series.name = name;
        series.provenanceHash = provenanceHash;

        emit SetSeriesInfo(
            seriesIndex,
            name,
            provenanceHash
        );
    }

    function endCurrentSeries(
        uint256 poemCreationDeadline
    )
        external
        onlyOwner
    {
        uint256 seriesIndex = _CURRENT_SERIES_INDEX_++;

        IIkaniV1_1.Series storage series = _SERIES_INFO_[seriesIndex];

        uint256 maxTokenIdExclusive = getNextTokenId();
        uint256 startingIndexBlockNumber = block.number + STARTING_INDEX_ADD_BLOCKS;

        series.poemCreationDeadline = poemCreationDeadline;
        series.maxTokenIdExclusive = maxTokenIdExclusive;
        series.startingIndexBlockNumber = startingIndexBlockNumber;

        emit EndedSeries(
            seriesIndex,
            poemCreationDeadline,
            maxTokenIdExclusive,
            startingIndexBlockNumber
        );
    }

    function advancePoemCreationDeadline(
        uint256 seriesIndex,
        uint256 poemCreationDeadline
    )
        external
        onlyOwner
    {
        IIkaniV1_1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            poemCreationDeadline > series.poemCreationDeadline,
            "Can only move the deadline forward"
        );

        series.poemCreationDeadline = poemCreationDeadline;

        emit AdvancedPoemCreationDeadline(
            seriesIndex,
            poemCreationDeadline
        );
    }

    function mintByOwner(
        address[] calldata recipients
    )
        external
        onlyOwner
    {
        uint256 n = recipients.length;

        for (uint256 i = 0; i < n; i++) {
            // Note: Intentionally not using _safeMint().
            _mint(recipients[i]);
        }

        require(
            getNextTokenId() <= MAX_SUPPLY,
            "Global max supply exceeded"
        );
    }

    function expire(
        uint256 tokenId
    )
        external
        onlyOwner
    {
        require(
            !isPoemFinished(tokenId),
            "Cannot expire a finished poem"
        );

        uint256 seriesIndex = getPoemSeriesIndex(tokenId);

        IIkaniV1_1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            series.startingIndexBlockNumber != 0,
            "Series not ended"
        );
        require(
            block.timestamp > series.poemCreationDeadline,
            "Token has not expired"
        );

        _burn(tokenId);
    }

    function expireBatch(
        uint256[] calldata tokenIds,
        uint256 seriesIndex
    )
        external
        onlyOwner
    {
        require(
            seriesIndex <= _CURRENT_SERIES_INDEX_,
            "Invalid series index"
        );

        IIkaniV1_1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            series.startingIndexBlockNumber != 0,
            "Series not ended"
        );
        require(
            block.timestamp > series.poemCreationDeadline,
            "Series has not expired"
        );

        uint256 n = tokenIds.length;

        uint256 maxTokenIdExclusive = series.maxTokenIdExclusive;
        for (uint256 i = 0; i < n; i++) {
            require(
                tokenIds[i] < maxTokenIdExclusive,
                "Token ID not part of the series"
            );
        }

        if (seriesIndex > 0) {
            uint256 startTokenId = _SERIES_INFO_[seriesIndex - 1].maxTokenIdExclusive;
            for (uint256 i = 0; i < n; i++) {
                require(
                    tokenIds[i] >= startTokenId,
                    "Token ID not part of the series"
                );
            }
        }

        for (uint256 i = 0; i < n; i++) {
            require(
                !isPoemFinished(tokenIds[i]),
                "Cannot expire a finished poem"
            );
            _burn(tokenIds[i]);
        }
    }

    //---------------- Other State-Changing External Functions ----------------//

    function mint(
        IIkaniV1_1.MintArgs calldata mintArgs,
        bytes calldata signature
    )
        external
        payable
        whenNotPaused
    {
        require(
            mintArgs.seriesIndex == _CURRENT_SERIES_INDEX_,
            "Not the current series"
        );

        require(
            msg.value == mintArgs.mintPrice,
            "Wrong msg.value"
        );

        address sender = msg.sender;
        bytes memory message = abi.encode(
            sender,
            mintArgs
        );
        bytes32 messageDigest = keccak256(message);

        // Only allow one mint per message/digest/signature.
        require(
            !_USED_MINT_DIGESTS_[messageDigest],
            "Mint digest already used"
        );
        _USED_MINT_DIGESTS_[messageDigest] = true;

        // Note: Since the only signer is our admin, we don't need EIP-712.
        require(
            PersonalSign.isValidSignature(messageDigest, signature, _MINT_SIGNER_),
            "Invalid signature"
        );

        // Note: Intentionally not using _safeMint().
        uint256 tokenId = _mint(sender);

        require(
            tokenId < mintArgs.maxTokenIdExclusive,
            "Series max supply exceeded"
        );
        require(
            tokenId < MAX_SUPPLY,
            "Global max supply exceeded"
        );
    }

    function trySetSeriesStartingIndex(
        uint256 seriesIndex
    )
        external
        whenNotPaused
    {
        IIkaniV1_1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            !series.startingIndexWasSet,
            "Starting index already set"
        );

        uint256 targetBlockNumber = series.startingIndexBlockNumber;
        require(
            targetBlockNumber != 0,
            "Series not ended"
        );

        require(
            block.number >= targetBlockNumber,
            "Starting index block not reached"
        );

        // If the hash for the target block is not available, set a new block number and exit.
        if (block.number - targetBlockNumber > 256) {
            uint256 newStartingIndexBlockNumber = block.number + STARTING_INDEX_ADD_BLOCKS;
            series.startingIndexBlockNumber = newStartingIndexBlockNumber;
            emit ResetSeriesStartingIndexBlockNumber(
                seriesIndex,
                newStartingIndexBlockNumber
            );
            return;
        }

        uint256 seriesSupply = getSeriesSupply(seriesIndex);
        uint256 startingIndex = uint256(blockhash(targetBlockNumber)) % seriesSupply;

        series.startingIndex = startingIndex;
        series.startingIndexWasSet = true;

        emit SetSeriesStartingIndex(
            seriesIndex,
            startingIndex
        );
    }

    //---------------- View-Only External Functions ----------------//

    function getMetadataController()
        external
        view
        returns (IIkaniV1MetadataController)
    {
        return _METADATA_CONTROLLER_;
    }

    function getMintSigner()
        external
        view
        returns (address)
    {
        return _MINT_SIGNER_;
    }

    function isUsedMintDigest(
        bytes32 digest
    )
        external
        view
        returns (bool)
    {
        return _USED_MINT_DIGESTS_[digest];
    }

    function getSeriesInfo(
        uint256 seriesIndex
    )
        external
        view
        returns (IIkaniV1_1.Series memory)
    {
        return _SERIES_INFO_[seriesIndex];
    }

    function getCurrentSeriesIndex()
        external
        view
        returns (uint256)
    {
        return _CURRENT_SERIES_INDEX_;
    }

    function exists(
        uint256 tokenId
    )
        external
        view
        returns (bool)
    {
        return _exists(tokenId);
    }

    //---------------- Public Functions ----------------//

    function getPoemSeriesIndex(
        uint256 tokenId
    )
        public
        view
        returns (uint256)
    {
        uint256 currentSeriesIndex = _CURRENT_SERIES_INDEX_;
        uint256 seriesIndex;
        for (seriesIndex = 0; seriesIndex < currentSeriesIndex; seriesIndex++) {
            IIkaniV1_1.Series storage series = _SERIES_INFO_[seriesIndex];

            if (tokenId < series.maxTokenIdExclusive) {
                break;
            }
        }
        return seriesIndex;
    }

    function getSeriesSupply(
        uint256 seriesIndex
    )
        public
        view
        returns (uint256)
    {
        IIkaniV1_1.Series storage series = _SERIES_INFO_[seriesIndex];

        require(
            series.startingIndexBlockNumber != 0,
            "Series not ended"
        );

        uint256 maxTokenIdExclusive = series.maxTokenIdExclusive;

        if (seriesIndex == 0) {
            return maxTokenIdExclusive;
        }

        IIkaniV1_1.Series storage previousSeries = _SERIES_INFO_[seriesIndex - 1];

        return maxTokenIdExclusive - previousSeries.maxTokenIdExclusive;
    }

    function getPoemText(
        uint256 tokenId
    )
        public
        view
        returns (string memory)
    {
        return _POEM_TEXT_[tokenId];
    }

    function getPoemTraits(
        uint256 tokenId
    )
        public
        view
        returns (IIkaniV1_1.PoemTraits memory)
    {
        return _POEM_TRAITS_[tokenId];
    }

    function isPoemFinished(
        uint256 tokenId
    )
        public
        view
        returns (bool)
    {
        return _POEM_TRAITS_[tokenId].theme != IIkaniV1_1.Theme.NULL;
    }

    function tokenURI(
        uint256 tokenId
    )
        public
        view
        override
        returns (string memory)
    {
        return _METADATA_CONTROLLER_.tokenURI(tokenId);
    }
}

File 68 of 73 : IIkaniV1_1.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

/**
 * @title IIkaniV1_1
 * @author Cyborg Labs, LLC
 *
 * @notice Interface for the IkaniV1 ERC-721 NFT contract.
 */
interface IIkaniV1_1 {

    //---------------- Enums ----------------//

    enum Theme {
        NULL,
        SKY,
        OCEAN,
        MOUNTAIN,
        FLOWERS,
        TBA_THEME_5,
        TBA_THEME_6,
        TBA_THEME_7,
        TBA_THEME_8
    }

    enum Season {
        NONE,
        SPRING,
        SUMMER,
        AUTUMN,
        WINTER
    }

    enum Fabric {
        NULL,
        KOYAMAKI,
        SEIGAIHA,
        NAMI,
        KUMO,
        TBA_FABRIC_5,
        TBA_FABRIC_6,
        TBA_FABRIC_7,
        TBA_FABRIC_8
    }

    enum Foil {
        NONE,
        GOLD,
        PLATINUM,
        SUI_GENERIS
    }

    //---------------- Structs ----------------//

    /**
     * @notice The poem metadata traits.
     */
    struct PoemTraits {
        Theme theme;
        Season season;
        Fabric fabric;
        Foil foil;
    }

    /**
     * @notice Information about a series within the collection.
     */
    struct Series {
        string name;
        bytes32 provenanceHash;
        uint256 poemCreationDeadline;
        uint256 maxTokenIdExclusive;
        uint256 startingIndexBlockNumber;
        uint256 startingIndex;
        bool startingIndexWasSet;
    }

    /**
     * @notice Arguments to be signed by the mint authority to authorize a mint.
     */
    struct MintArgs {
        uint256 seriesIndex;
        uint256 mintPrice;
        uint256 maxTokenIdExclusive;
        uint256 nonce;
    }

    //---------------- Events ----------------//

    event SetSeriesInfo(
        uint256 indexed seriesIndex,
        string name,
        bytes32 provenanceHash
    );

    event EndedSeries(
        uint256 indexed seriesIndex,
        uint256 poemCreationDeadline,
        uint256 maxTokenIdExclusive,
        uint256 startingIndexBlockNumber
    );

    event AdvancedPoemCreationDeadline(
        uint256 indexed seriesIndex,
        uint256 poemCreationDeadline
    );

    event ResetSeriesStartingIndexBlockNumber(
        uint256 indexed seriesIndex,
        uint256 startingIndexBlockNumber
    );

    event SetSeriesStartingIndex(
        uint256 indexed seriesIndex,
        uint256 startingIndex
    );

    event FinishedPoem(
        uint256 indexed tokenId
    );
}

File 69 of 73 : StaticUriMetadataController.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import { IIkaniV1MetadataController } from "../interfaces/IIkaniV1MetadataController.sol";

/**
 * @title StaticUriMetadataController
 * @author Cyborg Labs, LLC
 *
 * @notice Implementation of the tokenURI function using a static URI.
 */
contract StaticUriMetadataController is
    Ownable,
    IIkaniV1MetadataController
{
    string internal _STATIC_URI_;

    constructor(
        string memory staticUri
    ) {
        _STATIC_URI_ = staticUri;
    }

    function setStaticUri(
        string calldata staticUri
    )
        external
        onlyOwner
    {
        _STATIC_URI_ = staticUri;
    }

    function tokenURI(
        uint256 /* tokenId */
    )
        external
        view
        override
        returns (string memory)
    {
        return _STATIC_URI_;
    }
}

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

pragma solidity ^0.8.0;

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

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

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

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

pragma solidity ^0.8.0;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}

File 72 of 73 : BaseUriMetadataController.sol
// SPDX-License-Identifier: Apache-2.0

pragma solidity ^0.8.0;

import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";

import { IIkaniV1MetadataController } from "../interfaces/IIkaniV1MetadataController.sol";

/**
 * @title BaseUriMetadataController
 * @author Cyborg Labs, LLC
 *
 * @notice Implementation of the tokenURI function using a base URI.
 */
contract BaseUriMetadataController is
    Ownable,
    IIkaniV1MetadataController
{
    using Strings for uint256;

    string internal _BASE_URI_;

    constructor(
        string memory baseUri
    ) {
        _BASE_URI_ = baseUri;
    }

    function setBaseUri(
        string calldata baseUri
    )
        external
        onlyOwner
    {
        _BASE_URI_ = baseUri;
    }

    function baseURI()
        external
        view
        returns (string memory)
    {
        return _BASE_URI_;
    }

    function tokenURI(
        uint256 tokenId
    )
        external
        view
        override
        returns (string memory)
    {
        string memory baseUri = _BASE_URI_;
        return bytes(baseUri).length > 0
            ? string(abi.encodePacked(baseUri, tokenId.toString()))
            : "";
    }
}

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

pragma solidity ^0.8.0;

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

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

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

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

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

Settings
{
  "optimizer": {
    "enabled": true,
    "runs": 200
  },
  "evmVersion": "berlin",
  "outputSelection": {
    "*": {
      "*": [
        "evm.bytecode",
        "evm.deployedBytecode",
        "devdoc",
        "userdoc",
        "metadata",
        "abi"
      ]
    }
  },
  "libraries": {
    "contracts/staking/v2/lib/IS2Lib.sol": {
      "IS2Lib": "0xac25c2fb42b08ebab4d185efe4f9c8a430d97b1e"
    }
  }
}

Contract Security Audit

Contract ABI

[{"inputs":[{"internalType":"address","name":"ikani","type":"address"},{"internalType":"address","name":"rewardsErc20","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"indexed":true,"internalType":"bytes32","name":"receipt","type":"bytes32"},{"indexed":false,"internalType":"bytes","name":"receiptData","type":"bytes"}],"name":"AdminUnstaked","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ClaimedRewards","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Paused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"previousAdminRole","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"newAdminRole","type":"bytes32"}],"name":"RoleAdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleGranted","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"role","type":"bytes32"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"}],"name":"RoleRevoked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"baseRate","type":"uint256"}],"name":"SetBaseRate","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"stakingStartTimestamp","type":"uint256"}],"name":"Staked","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"}],"name":"Unpaused","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Unstaked","type":"event"},{"inputs":[],"name":"BASE_RATE_CONTROLLER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"BURN_CONTROLLER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"CLAIM_CONTROLLER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"DEFAULT_ADMIN_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"IKANI","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MULTIPLIER_BASE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNPAUSER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"UNSTAKE_CONTROLLER_ROLE","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"adminClaimRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"burnAmount","type":"uint256"},{"internalType":"bytes32","name":"burnReceipt","type":"bytes32"},{"internalType":"bytes","name":"burnReceiptData","type":"bytes"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"adminClaimRewardsAndBurnWithPermit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"},{"internalType":"bytes32","name":"receipt","type":"bytes32"},{"internalType":"bytes","name":"receiptData","type":"bytes"}],"name":"adminUnstake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"batchSafeTransferFromStaked","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"burnAmount","type":"uint256"},{"internalType":"bytes32","name":"burnReceipt","type":"bytes32"},{"internalType":"bytes","name":"burnReceiptData","type":"bytes"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"claimAndBurnRewards","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"recipient","type":"address"}],"name":"claimRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getAccountRewardsMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getBaseRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getDurationLevel","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getDurationRewardsMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getFabricsRewardsMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getFoilRewardsMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"i","type":"uint256"}],"name":"getHistoricalBaseRate","outputs":[{"components":[{"internalType":"uint32","name":"baseRate","type":"uint32"},{"internalType":"uint32","name":"timestamp","type":"uint32"}],"internalType":"struct IIkaniV2Staking.RateChange","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getNumBaseRateChanges","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getNumFabricsStaked","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getNumSeasonsStaked","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"}],"name":"getRoleAdmin","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"getSeasonsRewardsMultiplier","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getStakedTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getTokenRewardsRate","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"grantRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"hasRole","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"admin","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"isStaked","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"paused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"renounceRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"role","type":"bytes32"},{"internalType":"address","name":"account","type":"address"}],"name":"revokeRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"baseRate","type":"uint32"}],"name":"setBaseRate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"settleRewards","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"stake","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"unpause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256[]","name":"tokenIds","type":"uint256[]"}],"name":"unstake","outputs":[],"stateMutability":"nonpayable","type":"function"}]

60c06040523480156200001157600080fd5b506040516200491638038062004916833981016040819052620000349162000138565b6001600160a01b03808316608052811660a0526200005162000059565b505062000170565b600054610100900460ff1615620000c65760405162461bcd60e51b815260206004820152602760248201527f496e697469616c697a61626c653a20636f6e747261637420697320696e697469604482015266616c697a696e6760c81b606482015260840160405180910390fd5b60005460ff908116101562000119576000805460ff191660ff9081179091556040519081527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b565b80516001600160a01b03811681146200013357600080fd5b919050565b600080604083850312156200014c57600080fd5b62000157836200011b565b915062000167602084016200011b565b90509250929050565b60805160a051614748620001ce600039600081816125e60152613463015260008181610350015281816119a801528181611ab10152818161276301528181612a540152818161307c0152818161355c01526135ea01526147486000f3fe608060405234801561001057600080fd5b50600436106102695760003560e01c806386907ef311610151578063c10cdf94116100c3578063d547741f11610087578063d547741f1461060a578063e63ab1e91461061d578063eb9feb7614610644578063f1e42ccd14610657578063f97136af1461066a578063fb1bb9de1461067457600080fd5b8063c10cdf94146105b4578063c4d66de8146105be578063c9a3911e146105d1578063cf2601ca146105e4578063d0899bad146105f757600080fd5b8063a0f1deb211610115578063a0f1deb2146104ff578063a217fddf14610527578063a40882921461052f578063b655d0c414610556578063baa51f8614610577578063bb14d20e146105a157600080fd5b806386907ef31461048c578063872448431461049f5780638ed0462f146104b257806391d14854146104d95780639f729a6e146104ec57600080fd5b806336568abe116101ea5780635c975abb116101ae5780635c975abb1461042d5780635dbe4756146104385780636f23cb191461044b578063718b6c661461045e5780638456cb59146104715780638662489c1461047957600080fd5b806336568abe146103d957806337a96fcd146103ec57806337d5b514146103ff578063384085b2146104125780633f4ba83a1461042557600080fd5b8063248a9ca311610231578063248a9ca3146103285780632e85556d1461034b5780632f2ff15d1461038a57806330d863ff1461039f578063356221fc146103b257600080fd5b806301ffc9a71461026e5780630ae5dec7146102965780630dbb8b10146102b7578063183224ce146102de57806323ed48a214610315575b600080fd5b61028161027c36600461397d565b61069b565b60405190151581526020015b60405180910390f35b6102a96102a43660046139bc565b6106d2565b60405190815260200161028d565b6102a97fd732b487a91d56c42b88fd4b1d271f12f03f244b8857e8b4270cc835dab3dc5981565b6102f16102ec3660046139d9565b610772565b60408051825163ffffffff908116825260209384015116928101929092520161028d565b6102a96103233660046139bc565b610818565b6102a96103363660046139d9565b60009081526065602052604090206001015490565b6103727f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b03909116815260200161028d565b61039d6103983660046139f2565b610868565b005b61039d6103ad366004613a7a565b610892565b6102a97f8585736fef124c318e85f82b5ce4c5d3878b7ff2fff2191b60ef74595a59a7b481565b61039d6103e73660046139f2565b61090f565b61039d6103fa3660046139bc565b61098d565b6102a961040d3660046139bc565b6109c9565b61039d610420366004613a7a565b610a19565b61039d610a9e565b60975460ff16610281565b61039d610446366004613b59565b610ad3565b6102a96104593660046139bc565b610dcc565b6102a961046c3660046139d9565b610de4565b61039d610ea6565b61039d610487366004613bae565b610ed8565b6102a961049a3660046139d9565b61125c565b61039d6104ad366004613c3a565b6112b9565b6102a97fcdebdf9373e7e5c847c3e6cb50c46a7442f1e563a69477a7263d23c6f732684981565b6102816104e73660046139f2565b611a63565b6102a96104fa3660046139d9565b611a8e565b6102a961050d3660046139d9565b6000908152620f430e602052604090205463ffffffff1690565b6102a9600081565b6102a97f700a6a86f87f295447af4608d910099313633af610c1fbf9da48c91659ea46f181565b620f430a546000908152620f4309602052604090205463ffffffff166102a9565b6102816105853660046139d9565b6000908152620f430e602052604090205463ffffffff16151590565b6102a96105af3660046139bc565b611bbc565b620f430a546102a9565b61039d6105cc3660046139bc565b611c0c565b61039d6105df366004613b59565b611d30565b6102a96105f23660046139bc565b61204c565b6102a96106053660046139d9565b61209c565b61039d6106183660046139f2565b6120f7565b6102a97f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a81565b61039d610652366004613cb1565b61211c565b6102a9610665366004613cce565b61214f565b6102a9620f424081565b6102a97f427da25fe773164f88948d3e215c94b6554e2ed5e5f203a821c9f2f6131cf75a81565b60006001600160e01b03198216637965db0b60e01b14806106cc57506301ffc9a760e01b6001600160e01b03198316145b92915050565b6001600160a01b0381166000908152620f430b6020526040808220905163f41a545360e01b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163f41a5453916107229190600401613e2c565b60206040518083038186803b15801561073a57600080fd5b505af415801561074e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106cc9190613e3b565b6040805180820190915260008082526020820152620f430a548211156107df5760405162461bcd60e51b815260206004820152601760248201527f496e76616c69642062617365207261746520696e64657800000000000000000060448201526064015b60405180910390fd5b506000908152620f4309602090815260409182902082518084019093525463ffffffff8082168452640100000000909104169082015290565b6001600160a01b0381166000908152620f430b60205260408082209051637d0c0db960e11b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163fa181b72916107229190600401613e2c565b600082815260656020526040902060010154610883816121b1565b61088d83836121bb565b505050565b61089a612241565b336001600160a01b038a16146108e85760405162461bcd60e51b815260206004820152601360248201527229b2b73232b91034b9903737ba1037bbb732b960691b60448201526064016107d6565b6108f2898a612289565b506109048989898989898989896125cf565b505050505050505050565b6001600160a01b038116331461097f5760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016107d6565b6109898282612668565b5050565b7f700a6a86f87f295447af4608d910099313633af610c1fbf9da48c91659ea46f16109b7816121b1565b6109bf612241565b61088d8283612289565b6001600160a01b0381166000908152620f430b6020526040808220905163547fecb960e01b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163547fecb9916107229190600401613e2c565b7f700a6a86f87f295447af4608d910099313633af610c1fbf9da48c91659ea46f1610a43816121b1565b7fcdebdf9373e7e5c847c3e6cb50c46a7442f1e563a69477a7263d23c6f7326849610a6d816121b1565b610a75612241565b610a7f8b8c612289565b50610a918b8b8b8b8b8b8b8b8b6125cf565b5050505050505050505050565b7f427da25fe773164f88948d3e215c94b6554e2ed5e5f203a821c9f2f6131cf75a610ac8816121b1565b610ad06126cf565b50565b610adb612241565b610ae88383836000612721565b600080610af4856128bc565b91509150610b048286868661298c565b915081620f430b6000876001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505080620f430d6000876001600160a01b03166001600160a01b031681526020019081526020016000206000828254610dc09190613e6a565b90915550505050505050565b6000610dd6612241565b6106cc82612c04565b919050565b6000818152620f430e602052604081205463ffffffff1680610e0b5750620f424092915050565b6000610e178242613e82565b604051633bf46d2960e11b81526004810182905290915073ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e906377e8da52906024015b60206040518083038186803b158015610e6657600080fd5b505af4158015610e7a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e9e9190613e3b565b949350505050565b7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a610ed0816121b1565b610ad0612eff565b7fd732b487a91d56c42b88fd4b1d271f12f03f244b8857e8b4270cc835dab3dc59610f02816121b1565b610f0a612241565b610f178787876001612721565b600080610f23896128bc565b91509150610f33828a8a8a61298c565b915081620f430b60008b6001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505080620f430d60008b6001600160a01b03166001600160a01b0316815260200190815260200160002060008282546111ef9190613e6a565b90915550506040518690611206908a908a90613e99565b60405180910390208a6001600160a01b03167f1c3faf66cba9b4c4b916ac285c4e22b9647b7f00eadcb4ca01a5a10b65b18ebc8888604051611249929190613eee565b60405180910390a4505050505050505050565b6000818152620f430e602052604081205463ffffffff168161127e8242613e82565b604051630b21e43b60e31b81526004810182905290915073ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9063590f21d890602401610e4e565b6112c1612241565b336001600160a01b038516146113195760405162461bcd60e51b815260206004820152601e60248201527f4f6e6c79206f776e65722063616e207472616e73666572207374616b6564000060448201526064016107d6565b6113268483836001612721565b600080611332866128bc565b91509150600080611342876128bc565b90925090508460008167ffffffffffffffff81111561136357611363613f02565b60405190808252806020026020018201604052801561138c578160200160208202803683370190505b50905060005b828110156113fc57620f430e60008a8a848181106113b2576113b2613f18565b6020908102929092013583525081019190915260400160002054825163ffffffff909116908390839081106113e9576113e9613f18565b6020908102919091010152600101611392565b50611409868b8a8a61298c565b9550611418848a8a8a85612f3c565b935085620f430b60008c6001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505084620f430d60008c6001600160a01b03166001600160a01b0316815260200190815260200160002060008282546116d49190613e6a565b9250508190555083620f430b60008b6001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505082620f430d60008b6001600160a01b03166001600160a01b0316815260200190815260200160002060008282546119959190613e6a565b90915550600090505b82811015610a91577f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166342842e0e8c8c8c8c868181106119e9576119e9613f18565b6040516001600160e01b031960e088901b1681526001600160a01b03958616600482015294909316602485015250602090910201356044820152606401600060405180830381600087803b158015611a4057600080fd5b505af1158015611a54573d6000803e3d6000fd5b5050505080600101905061199e565b60009182526065602090815260408084206001600160a01b0393909316845291905290205460ff1690565b60405163269f5cb960e01b81526004810182905260009081906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063269f5cb99060240160806040518083038186803b158015611af357600080fd5b505afa158015611b07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b2b9190613fa4565b6040516331e9c30f60e21b815290915073ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9063c7a70c3c90611b659084906004016140bf565b60206040518083038186803b158015611b7d57600080fd5b505af4158015611b91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bb59190613e3b565b9392505050565b6001600160a01b0381166000908152620f430b602052604080822090516372e1603160e11b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163e5c2c062916107229190600401613e2c565b600054610100900460ff1615808015611c2c5750600054600160ff909116105b80611c465750303b158015611c46575060005460ff166001145b611ca95760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016107d6565b6000805460ff191660011790558015611ccc576000805461ff0019166101001790555b611cd46132d6565b611cdc6132fd565b611ce76000836121bb565b8015610989576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15050565b611d38612241565b611d458383836000612721565b600080611d51856128bc565b9092509050611d8e828686866000604051908082528060200260200182016040528015611d88578160200160208202803683370190505b50612f3c565b915081620f430b6000876001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505080600014612045576001600160a01b0385166000908152620f430d602052604081208054839290610dc0908490613e6a565b5050505050565b6001600160a01b0381166000908152620f430b60205260408082209051637ba0aaf560e11b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163f74155ea916107229190600401613e2c565b60006120ab620f4240806140cd565b6120b483611a8e565b6120bd84610de4565b620f430a546000908152620f4309602052604090205463ffffffff166120e391906140cd565b6120ed91906140cd565b6106cc91906140ec565b600082815260656020526040902060010154612112816121b1565b61088d8383612668565b7f8585736fef124c318e85f82b5ce4c5d3878b7ff2fff2191b60ef74595a59a7b4612146816121b1565b6109898261332c565b6000612159612241565b336001600160a01b038416146121a75760405162461bcd60e51b815260206004820152601360248201527229b2b73232b91034b9903737ba1037bbb732b960691b60448201526064016107d6565b611bb58383612289565b610ad081336133d5565b6121c58282611a63565b6109895760008281526065602090815260408083206001600160a01b03851684529091529020805460ff191660011790556121fd3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60975460ff16156122875760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b60448201526064016107d6565b565b6001600160a01b0382166000908152620f430d602052604081205481806122af866128bc565b9150915081620f430b6000886001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff1602179055509050506000620f430d6000886001600160a01b03166001600160a01b0316815260200190815260200160002081905550600081846125719190613e6a565b9050600061257f878361342e565b9050876001600160a01b03167f2d5429efdeca7741a8cd94067b18d988bc4e5f1d5b8272c37b7bfc31e9bfa32c826040516125bc91815260200190565b60405180910390a2979650505050505050565b604051636380303360e11b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063c70060669061262b908c908c908c908c908c908c908c908c908c9060040161410e565b600060405180830381600087803b15801561264557600080fd5b505af1158015612659573d6000803e3d6000fd5b50505050505050505050505050565b6126728282611a63565b156109895760008281526065602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6126d76134e9565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b336001600160a01b03851681148360005b818110156128b257600087878381811061274e5761274e613f18565b905060200201359050886001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316636352211e836040518263ffffffff1660e01b81526004016127af91815260200190565b60206040518083038186803b1580156127c757600080fd5b505afa1580156127db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127ff9190614169565b6001600160a01b0316146128435760405162461bcd60e51b815260206004820152600b60248201526a2bb937b7339037bbb732b960a91b60448201526064016107d6565b858061284c5750835b8061285d575061285d858a83613532565b6128a95760405162461bcd60e51b815260206004820152601f60248201527f4e6f7420617574686f72697a656420746f207374616b652f756e7374616b650060448201526064016107d6565b50600101612732565b5050505050505050565b6128c46138f1565b6001600160a01b0382166000908152620f430b60209081526040808320620f430c909252808320620f430a5491516324e948eb60e21b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e936393a523ac93612931939192620f43099291620f430e91600401614186565b6102406040518083038186803b15801561294a57600080fd5b505af415801561295e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129829190614318565b9094909350915050565b6129946138f1565b50838160005b81811015612bfa5760008585838181106129b6576129b6613f18565b602090810292909201356000818152620f430e845260409081902081518083019092525463ffffffff80821680845264010000000090920416948201949094529093509115159050612a375760405162461bcd60e51b815260206004820152600a602482015269139bdd081cdd185ad95960b21b60448201526064016107d6565b73ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e637726dc4f867f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663269f5cb9866040518263ffffffff1660e01b8152600401612aa091815260200190565b60806040518083038186803b158015612ab857600080fd5b505afa158015612acc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612af09190613fa4565b84516040516001600160e01b031960e086901b168152612b1593929190600401614474565b6102206040518083038186803b158015612b2e57600080fd5b505af4158015612b42573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b6691906144a6565b604080518082018252600080825260208581015160010163ffffffff908116828501908152888452620f430e90925284832093518454925182166401000000000267ffffffffffffffff1990931691161717909155905191965083916001600160a01b038b16917f0f5bb82176feb1b5e747e28471aa92156a04d9f3ab9f45f28e2d704232b93f7591a3505060010161299a565b5050949350505050565b6001600160a01b0381166000908152620f430d60205260408120548180612c2a856128bc565b90925090506000612c3b8285613e6a565b905082620f430b6000886001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505080620f430d6000886001600160a01b03166001600160a01b0316815260200190815260200160002081905550612ef581613698565b9695505050505050565b612f07612241565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586127043390565b612f446138f1565b50848260005b818110156132cb576000868683818110612f6657612f66613f18565b602090810292909201356000818152620f430e845260409081902081518083019092525463ffffffff808216808452640100000000909204169482019490945290935091159050612fea5760405162461bcd60e51b815260206004820152600e60248201526d105b1c9958591e481cdd185ad95960921b60448201526064016107d6565b600080875111612ffa5742613015565b86848151811061300c5761300c613f18565b60200260200101515b6040805160a081018252600080825260208201819052818301819052606082018190526080820152905163269f5cb960e01b8152600481018690529192509073ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e90633ad9726c9089906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063269f5cb99060240160806040518083038186803b1580156130be57600080fd5b505afa1580156130d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130f69190613fa4565b858760200151896040518663ffffffff1660e01b815260040161311d9594939291906144c3565b6102c06040518083038186803b15801561313657600080fd5b505af415801561314a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061316e9190614505565b6080810151919850915063ffffffff161561324a576001600160a01b038b166000908152620f430c6020908152604091829020825163c6043c7760e01b8152600481019190915283516001600160801b031660248201529083015163ffffffff90811660448301529183015182166064820152606083015182166084820152608083015190911660a482015273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9063c6043c779060c40160006040518083038186803b15801561323157600080fd5b505af4158015613245573d6000803e3d6000fd5b505050505b613253826136a7565b6000858152620f430e6020908152604091829020805463ffffffff191663ffffffff94909416939093179092555183815285916001600160a01b038e16917f1449c6dd7851abc30abf37f57715f492010519147cc2652fbc38202c18a6ee90910160405180910390a384600101945050505050612f4a565b505095945050505050565b600054610100900460ff166122875760405162461bcd60e51b81526004016107d6906145ba565b600054610100900460ff166133245760405162461bcd60e51b81526004016107d6906145ba565b612287613710565b60405180604001604052808263ffffffff16815260200161334c426136a7565b63ffffffff908116909152620f430a8054600101908190556000908152620f43096020908152604091829020845181549583015185166401000000000267ffffffffffffffff1990961690851617949094179093555190831681527f16bacabd495cd45d904b6dc6184eabc5a6d654a4ee84569a5489ee7b20bc4364910160405180910390a150565b6133df8282611a63565b610989576133ec81613743565b6133f7836020613755565b604051602001613408929190614631565b60408051601f198184030181529082905262461bcd60e51b82526107d6916004016146a6565b60008061343a83613698565b60405163a9059cbb60e01b81526001600160a01b038681166004830152602482018390529192507f00000000000000000000000000000000000000000000000000000000000000009091169063a9059cbb90604401602060405180830381600087803b1580156134a957600080fd5b505af11580156134bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134e191906146d9565b509392505050565b60975460ff166122875760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b60448201526064016107d6565b60405163e985e9c560e01b81526001600160a01b03838116600483015284811660248301526000917f00000000000000000000000000000000000000000000000000000000000000009091169063e985e9c59060440160206040518083038186803b1580156135a057600080fd5b505afa1580156135b4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135d891906146d9565b80610e9e5750836001600160a01b03167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663081812fc846040518263ffffffff1660e01b815260040161363691815260200190565b60206040518083038186803b15801561364e57600080fd5b505afa158015613662573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136869190614169565b6001600160a01b031614949350505050565b60006106cc620f4240836140cd565b600063ffffffff82111561370c5760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b60648201526084016107d6565b5090565b600054610100900460ff166137375760405162461bcd60e51b81526004016107d6906145ba565b6097805460ff19169055565b60606106cc6001600160a01b03831660145b606060006137648360026140cd565b61376f906002613e6a565b67ffffffffffffffff81111561378757613787613f02565b6040519080825280601f01601f1916602001820160405280156137b1576020820181803683370190505b509050600360fc1b816000815181106137cc576137cc613f18565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106137fb576137fb613f18565b60200101906001600160f81b031916908160001a905350600061381f8460026140cd565b61382a906001613e6a565b90505b60018111156138a2576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061385e5761385e613f18565b1a60f81b82828151811061387457613874613f18565b60200101906001600160f81b031916908160001a90535060049490941c9361389b816146fb565b905061382d565b508315611bb55760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016107d6565b6040805161022081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081018290526101408101829052610160810182905261018081018290526101a081018290526101c081018290526101e0810182905261020081019190915290565b60006020828403121561398f57600080fd5b81356001600160e01b031981168114611bb557600080fd5b6001600160a01b0381168114610ad057600080fd5b6000602082840312156139ce57600080fd5b8135611bb5816139a7565b6000602082840312156139eb57600080fd5b5035919050565b60008060408385031215613a0557600080fd5b823591506020830135613a17816139a7565b809150509250929050565b60008083601f840112613a3457600080fd5b50813567ffffffffffffffff811115613a4c57600080fd5b602083019150836020828501011115613a6457600080fd5b9250929050565b60ff81168114610ad057600080fd5b60008060008060008060008060006101008a8c031215613a9957600080fd5b8935613aa4816139a7565b985060208a0135975060408a0135965060608a013567ffffffffffffffff811115613ace57600080fd5b613ada8c828d01613a22565b90975095505060808a0135935060a08a0135613af581613a6b565b8093505060c08a0135915060e08a013590509295985092959850929598565b60008083601f840112613b2657600080fd5b50813567ffffffffffffffff811115613b3e57600080fd5b6020830191508360208260051b8501011115613a6457600080fd5b600080600060408486031215613b6e57600080fd5b8335613b79816139a7565b9250602084013567ffffffffffffffff811115613b9557600080fd5b613ba186828701613b14565b9497909650939450505050565b60008060008060008060808789031215613bc757600080fd5b8635613bd2816139a7565b9550602087013567ffffffffffffffff80821115613bef57600080fd5b613bfb8a838b01613b14565b9097509550604089013594506060890135915080821115613c1b57600080fd5b50613c2889828a01613a22565b979a9699509497509295939492505050565b60008060008060608587031215613c5057600080fd5b8435613c5b816139a7565b93506020850135613c6b816139a7565b9250604085013567ffffffffffffffff811115613c8757600080fd5b613c9387828801613b14565b95989497509550505050565b63ffffffff81168114610ad057600080fd5b600060208284031215613cc357600080fd5b8135611bb581613c9f565b60008060408385031215613ce157600080fd5b8235613cec816139a7565b91506020830135613a17816139a7565b805463ffffffff8082168452602082811c821690850152604082811c821690850152606082811c821690850152608082811c8216908501525060ff613d4b60a08501828460a01c1660ff169052565b613d5f60c08501828460a81c1660ff169052565b613d7360e08501828460b01c1660ff169052565b613d886101008501828460b81c1660ff169052565b613d9d6101208501828460c01c1660ff169052565b613db26101408501828460c81c1660ff169052565b613dc76101608501828460d01c1660ff169052565b613ddc6101808501828460d81c1660ff169052565b613df16101a08501828460e01c1660ff169052565b613e066101c08501828460e81c1660ff169052565b613e1b6101e08501828460f01c1660ff169052565b5060f881901c610200840152505050565b61022081016106cc8284613cfc565b600060208284031215613e4d57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b60008219821115613e7d57613e7d613e54565b500190565b600082821015613e9457613e94613e54565b500390565b60006001600160fb1b03831115613eaf57600080fd5b8260051b80858437600092019182525092915050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b602081526000610e9e602083018486613ec5565b634e487b7160e01b600052604160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b604051610220810167ffffffffffffffff81118282101715613f6057634e487b7160e01b600052604160045260246000fd5b60405290565b60405160a0810167ffffffffffffffff81118282101715613f6057634e487b7160e01b600052604160045260246000fd5b60098110610ad057600080fd5b600060808284031215613fb657600080fd5b6040516080810181811067ffffffffffffffff82111715613fe757634e487b7160e01b600052604160045260246000fd5b6040528251613ff581613f97565b815260208301516005811061400957600080fd5b6020820152604083015161401c81613f97565b604082015260608301516004811061403357600080fd5b60608201529392505050565b634e487b7160e01b600052602160045260246000fd5b60098110610ad057610ad061403f565b805161407081614055565b82526020810151600581106140875761408761403f565b6020830152604081015161409a81614055565b60408301526060810151600481106140b4576140b461403f565b806060840152505050565b608081016106cc8284614065565b60008160001904831182151516156140e7576140e7613e54565b500290565b60008261410957634e487b7160e01b600052601260045260246000fd5b500490565b600061010060018060a01b038c1683528a602084015289604084015280606084015261413d818401898b613ec5565b91505085608083015260ff851660a08301528360c08301528260e08301529a9950505050505050505050565b60006020828403121561417b57600080fd5b8151611bb5816139a7565b6102a081016141958288613cfc565b856102208301528461024083015283610260830152826102808301529695505050505050565b8051610ddf81613c9f565b8051610ddf81613a6b565b600061022082840312156141e457600080fd5b6141ec613f2e565b90506141f7826141bb565b8152614205602083016141bb565b6020820152614216604083016141bb565b6040820152614227606083016141bb565b6060820152614238608083016141bb565b608082015261424960a083016141c6565b60a082015261425a60c083016141c6565b60c082015261426b60e083016141c6565b60e082015261010061427e8184016141c6565b908201526101206142908382016141c6565b908201526101406142a28382016141c6565b908201526101606142b48382016141c6565b908201526101806142c68382016141c6565b908201526101a06142d88382016141c6565b908201526101c06142ea8382016141c6565b908201526101e06142fc8382016141c6565b9082015261020061430e8382016141c6565b9082015292915050565b600080610240838503121561432c57600080fd5b61433684846141d1565b915061022083015190509250929050565b805163ffffffff1682526020810151614368602084018263ffffffff169052565b506040810151614380604084018263ffffffff169052565b506060810151614398606084018263ffffffff169052565b5060808101516143b0608084018263ffffffff169052565b5060a08101516143c560a084018260ff169052565b5060c08101516143da60c084018260ff169052565b5060e08101516143ef60e084018260ff169052565b506101008181015160ff90811691840191909152610120808301518216908401526101408083015182169084015261016080830151821690840152610180808301518216908401526101a0808301518216908401526101c0808301518216908401526101e0808301518216908401526102008083015191821681850152905b50505050565b6102c081016144838286614347565b614491610220830185614065565b63ffffffff83166102a0830152949350505050565b600061022082840312156144b957600080fd5b611bb583836141d1565b61030081016144d28288614347565b6144e0610220830187614065565b846102a083015263ffffffff84166102c0830152826102e08301529695505050505050565b6000808284036102c081121561451a57600080fd5b61452485856141d1565b925060a061021f198201121561453957600080fd5b50614542613f66565b6102208401516001600160801b038116811461455d57600080fd5b815261024084015161456e81613c9f565b602082015261026084015161458281613c9f565b604082015261028084015161459681613c9f565b60608201526102a08401516145aa81613c9f565b6080820152919491935090915050565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b60005b83811015614620578181015183820152602001614608565b8381111561446e5750506000910152565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351614669816017850160208801614605565b7001034b99036b4b9b9b4b733903937b6329607d1b601791840191820152835161469a816028840160208801614605565b01602801949350505050565b60208152600082518060208401526146c5816040850160208701614605565b601f01601f19169190910160400192915050565b6000602082840312156146eb57600080fd5b81518015158114611bb557600080fd5b60008161470a5761470a613e54565b50600019019056fea2646970667358221220c9cbb8c1be6e9fb8a760d0d52cdca9cf46642ad07b5a6e66a50b6987dd354b8964736f6c63430008090033000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c036000000000000000000000000a203b4af1e1fdda5f76bed36a63c7a6ef3e308ff

Deployed Bytecode

0x608060405234801561001057600080fd5b50600436106102695760003560e01c806386907ef311610151578063c10cdf94116100c3578063d547741f11610087578063d547741f1461060a578063e63ab1e91461061d578063eb9feb7614610644578063f1e42ccd14610657578063f97136af1461066a578063fb1bb9de1461067457600080fd5b8063c10cdf94146105b4578063c4d66de8146105be578063c9a3911e146105d1578063cf2601ca146105e4578063d0899bad146105f757600080fd5b8063a0f1deb211610115578063a0f1deb2146104ff578063a217fddf14610527578063a40882921461052f578063b655d0c414610556578063baa51f8614610577578063bb14d20e146105a157600080fd5b806386907ef31461048c578063872448431461049f5780638ed0462f146104b257806391d14854146104d95780639f729a6e146104ec57600080fd5b806336568abe116101ea5780635c975abb116101ae5780635c975abb1461042d5780635dbe4756146104385780636f23cb191461044b578063718b6c661461045e5780638456cb59146104715780638662489c1461047957600080fd5b806336568abe146103d957806337a96fcd146103ec57806337d5b514146103ff578063384085b2146104125780633f4ba83a1461042557600080fd5b8063248a9ca311610231578063248a9ca3146103285780632e85556d1461034b5780632f2ff15d1461038a57806330d863ff1461039f578063356221fc146103b257600080fd5b806301ffc9a71461026e5780630ae5dec7146102965780630dbb8b10146102b7578063183224ce146102de57806323ed48a214610315575b600080fd5b61028161027c36600461397d565b61069b565b60405190151581526020015b60405180910390f35b6102a96102a43660046139bc565b6106d2565b60405190815260200161028d565b6102a97fd732b487a91d56c42b88fd4b1d271f12f03f244b8857e8b4270cc835dab3dc5981565b6102f16102ec3660046139d9565b610772565b60408051825163ffffffff908116825260209384015116928101929092520161028d565b6102a96103233660046139bc565b610818565b6102a96103363660046139d9565b60009081526065602052604090206001015490565b6103727f000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c03681565b6040516001600160a01b03909116815260200161028d565b61039d6103983660046139f2565b610868565b005b61039d6103ad366004613a7a565b610892565b6102a97f8585736fef124c318e85f82b5ce4c5d3878b7ff2fff2191b60ef74595a59a7b481565b61039d6103e73660046139f2565b61090f565b61039d6103fa3660046139bc565b61098d565b6102a961040d3660046139bc565b6109c9565b61039d610420366004613a7a565b610a19565b61039d610a9e565b60975460ff16610281565b61039d610446366004613b59565b610ad3565b6102a96104593660046139bc565b610dcc565b6102a961046c3660046139d9565b610de4565b61039d610ea6565b61039d610487366004613bae565b610ed8565b6102a961049a3660046139d9565b61125c565b61039d6104ad366004613c3a565b6112b9565b6102a97fcdebdf9373e7e5c847c3e6cb50c46a7442f1e563a69477a7263d23c6f732684981565b6102816104e73660046139f2565b611a63565b6102a96104fa3660046139d9565b611a8e565b6102a961050d3660046139d9565b6000908152620f430e602052604090205463ffffffff1690565b6102a9600081565b6102a97f700a6a86f87f295447af4608d910099313633af610c1fbf9da48c91659ea46f181565b620f430a546000908152620f4309602052604090205463ffffffff166102a9565b6102816105853660046139d9565b6000908152620f430e602052604090205463ffffffff16151590565b6102a96105af3660046139bc565b611bbc565b620f430a546102a9565b61039d6105cc3660046139bc565b611c0c565b61039d6105df366004613b59565b611d30565b6102a96105f23660046139bc565b61204c565b6102a96106053660046139d9565b61209c565b61039d6106183660046139f2565b6120f7565b6102a97f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a81565b61039d610652366004613cb1565b61211c565b6102a9610665366004613cce565b61214f565b6102a9620f424081565b6102a97f427da25fe773164f88948d3e215c94b6554e2ed5e5f203a821c9f2f6131cf75a81565b60006001600160e01b03198216637965db0b60e01b14806106cc57506301ffc9a760e01b6001600160e01b03198316145b92915050565b6001600160a01b0381166000908152620f430b6020526040808220905163f41a545360e01b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163f41a5453916107229190600401613e2c565b60206040518083038186803b15801561073a57600080fd5b505af415801561074e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106cc9190613e3b565b6040805180820190915260008082526020820152620f430a548211156107df5760405162461bcd60e51b815260206004820152601760248201527f496e76616c69642062617365207261746520696e64657800000000000000000060448201526064015b60405180910390fd5b506000908152620f4309602090815260409182902082518084019093525463ffffffff8082168452640100000000909104169082015290565b6001600160a01b0381166000908152620f430b60205260408082209051637d0c0db960e11b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163fa181b72916107229190600401613e2c565b600082815260656020526040902060010154610883816121b1565b61088d83836121bb565b505050565b61089a612241565b336001600160a01b038a16146108e85760405162461bcd60e51b815260206004820152601360248201527229b2b73232b91034b9903737ba1037bbb732b960691b60448201526064016107d6565b6108f2898a612289565b506109048989898989898989896125cf565b505050505050505050565b6001600160a01b038116331461097f5760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016107d6565b6109898282612668565b5050565b7f700a6a86f87f295447af4608d910099313633af610c1fbf9da48c91659ea46f16109b7816121b1565b6109bf612241565b61088d8283612289565b6001600160a01b0381166000908152620f430b6020526040808220905163547fecb960e01b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163547fecb9916107229190600401613e2c565b7f700a6a86f87f295447af4608d910099313633af610c1fbf9da48c91659ea46f1610a43816121b1565b7fcdebdf9373e7e5c847c3e6cb50c46a7442f1e563a69477a7263d23c6f7326849610a6d816121b1565b610a75612241565b610a7f8b8c612289565b50610a918b8b8b8b8b8b8b8b8b6125cf565b5050505050505050505050565b7f427da25fe773164f88948d3e215c94b6554e2ed5e5f203a821c9f2f6131cf75a610ac8816121b1565b610ad06126cf565b50565b610adb612241565b610ae88383836000612721565b600080610af4856128bc565b91509150610b048286868661298c565b915081620f430b6000876001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505080620f430d6000876001600160a01b03166001600160a01b031681526020019081526020016000206000828254610dc09190613e6a565b90915550505050505050565b6000610dd6612241565b6106cc82612c04565b919050565b6000818152620f430e602052604081205463ffffffff1680610e0b5750620f424092915050565b6000610e178242613e82565b604051633bf46d2960e11b81526004810182905290915073ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e906377e8da52906024015b60206040518083038186803b158015610e6657600080fd5b505af4158015610e7a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e9e9190613e3b565b949350505050565b7f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a610ed0816121b1565b610ad0612eff565b7fd732b487a91d56c42b88fd4b1d271f12f03f244b8857e8b4270cc835dab3dc59610f02816121b1565b610f0a612241565b610f178787876001612721565b600080610f23896128bc565b91509150610f33828a8a8a61298c565b915081620f430b60008b6001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505080620f430d60008b6001600160a01b03166001600160a01b0316815260200190815260200160002060008282546111ef9190613e6a565b90915550506040518690611206908a908a90613e99565b60405180910390208a6001600160a01b03167f1c3faf66cba9b4c4b916ac285c4e22b9647b7f00eadcb4ca01a5a10b65b18ebc8888604051611249929190613eee565b60405180910390a4505050505050505050565b6000818152620f430e602052604081205463ffffffff168161127e8242613e82565b604051630b21e43b60e31b81526004810182905290915073ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9063590f21d890602401610e4e565b6112c1612241565b336001600160a01b038516146113195760405162461bcd60e51b815260206004820152601e60248201527f4f6e6c79206f776e65722063616e207472616e73666572207374616b6564000060448201526064016107d6565b6113268483836001612721565b600080611332866128bc565b91509150600080611342876128bc565b90925090508460008167ffffffffffffffff81111561136357611363613f02565b60405190808252806020026020018201604052801561138c578160200160208202803683370190505b50905060005b828110156113fc57620f430e60008a8a848181106113b2576113b2613f18565b6020908102929092013583525081019190915260400160002054825163ffffffff909116908390839081106113e9576113e9613f18565b6020908102919091010152600101611392565b50611409868b8a8a61298c565b9550611418848a8a8a85612f3c565b935085620f430b60008c6001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505084620f430d60008c6001600160a01b03166001600160a01b0316815260200190815260200160002060008282546116d49190613e6a565b9250508190555083620f430b60008b6001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505082620f430d60008b6001600160a01b03166001600160a01b0316815260200190815260200160002060008282546119959190613e6a565b90915550600090505b82811015610a91577f000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c0366001600160a01b03166342842e0e8c8c8c8c868181106119e9576119e9613f18565b6040516001600160e01b031960e088901b1681526001600160a01b03958616600482015294909316602485015250602090910201356044820152606401600060405180830381600087803b158015611a4057600080fd5b505af1158015611a54573d6000803e3d6000fd5b5050505080600101905061199e565b60009182526065602090815260408084206001600160a01b0393909316845291905290205460ff1690565b60405163269f5cb960e01b81526004810182905260009081906001600160a01b037f000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c036169063269f5cb99060240160806040518083038186803b158015611af357600080fd5b505afa158015611b07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b2b9190613fa4565b6040516331e9c30f60e21b815290915073ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9063c7a70c3c90611b659084906004016140bf565b60206040518083038186803b158015611b7d57600080fd5b505af4158015611b91573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bb59190613e3b565b9392505050565b6001600160a01b0381166000908152620f430b602052604080822090516372e1603160e11b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163e5c2c062916107229190600401613e2c565b600054610100900460ff1615808015611c2c5750600054600160ff909116105b80611c465750303b158015611c46575060005460ff166001145b611ca95760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016107d6565b6000805460ff191660011790558015611ccc576000805461ff0019166101001790555b611cd46132d6565b611cdc6132fd565b611ce76000836121bb565b8015610989576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15050565b611d38612241565b611d458383836000612721565b600080611d51856128bc565b9092509050611d8e828686866000604051908082528060200260200182016040528015611d88578160200160208202803683370190505b50612f3c565b915081620f430b6000876001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505080600014612045576001600160a01b0385166000908152620f430d602052604081208054839290610dc0908490613e6a565b5050505050565b6001600160a01b0381166000908152620f430b60205260408082209051637ba0aaf560e11b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9163f74155ea916107229190600401613e2c565b60006120ab620f4240806140cd565b6120b483611a8e565b6120bd84610de4565b620f430a546000908152620f4309602052604090205463ffffffff166120e391906140cd565b6120ed91906140cd565b6106cc91906140ec565b600082815260656020526040902060010154612112816121b1565b61088d8383612668565b7f8585736fef124c318e85f82b5ce4c5d3878b7ff2fff2191b60ef74595a59a7b4612146816121b1565b6109898261332c565b6000612159612241565b336001600160a01b038416146121a75760405162461bcd60e51b815260206004820152601360248201527229b2b73232b91034b9903737ba1037bbb732b960691b60448201526064016107d6565b611bb58383612289565b610ad081336133d5565b6121c58282611a63565b6109895760008281526065602090815260408083206001600160a01b03851684529091529020805460ff191660011790556121fd3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60975460ff16156122875760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b60448201526064016107d6565b565b6001600160a01b0382166000908152620f430d602052604081205481806122af866128bc565b9150915081620f430b6000886001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff1602179055509050506000620f430d6000886001600160a01b03166001600160a01b0316815260200190815260200160002081905550600081846125719190613e6a565b9050600061257f878361342e565b9050876001600160a01b03167f2d5429efdeca7741a8cd94067b18d988bc4e5f1d5b8272c37b7bfc31e9bfa32c826040516125bc91815260200190565b60405180910390a2979650505050505050565b604051636380303360e11b81526001600160a01b037f000000000000000000000000a203b4af1e1fdda5f76bed36a63c7a6ef3e308ff169063c70060669061262b908c908c908c908c908c908c908c908c908c9060040161410e565b600060405180830381600087803b15801561264557600080fd5b505af1158015612659573d6000803e3d6000fd5b50505050505050505050505050565b6126728282611a63565b156109895760008281526065602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6126d76134e9565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b336001600160a01b03851681148360005b818110156128b257600087878381811061274e5761274e613f18565b905060200201359050886001600160a01b03167f000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c0366001600160a01b0316636352211e836040518263ffffffff1660e01b81526004016127af91815260200190565b60206040518083038186803b1580156127c757600080fd5b505afa1580156127db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127ff9190614169565b6001600160a01b0316146128435760405162461bcd60e51b815260206004820152600b60248201526a2bb937b7339037bbb732b960a91b60448201526064016107d6565b858061284c5750835b8061285d575061285d858a83613532565b6128a95760405162461bcd60e51b815260206004820152601f60248201527f4e6f7420617574686f72697a656420746f207374616b652f756e7374616b650060448201526064016107d6565b50600101612732565b5050505050505050565b6128c46138f1565b6001600160a01b0382166000908152620f430b60209081526040808320620f430c909252808320620f430a5491516324e948eb60e21b815273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e936393a523ac93612931939192620f43099291620f430e91600401614186565b6102406040518083038186803b15801561294a57600080fd5b505af415801561295e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129829190614318565b9094909350915050565b6129946138f1565b50838160005b81811015612bfa5760008585838181106129b6576129b6613f18565b602090810292909201356000818152620f430e845260409081902081518083019092525463ffffffff80821680845264010000000090920416948201949094529093509115159050612a375760405162461bcd60e51b815260206004820152600a602482015269139bdd081cdd185ad95960b21b60448201526064016107d6565b73ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e637726dc4f867f000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c0366001600160a01b031663269f5cb9866040518263ffffffff1660e01b8152600401612aa091815260200190565b60806040518083038186803b158015612ab857600080fd5b505afa158015612acc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612af09190613fa4565b84516040516001600160e01b031960e086901b168152612b1593929190600401614474565b6102206040518083038186803b158015612b2e57600080fd5b505af4158015612b42573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b6691906144a6565b604080518082018252600080825260208581015160010163ffffffff908116828501908152888452620f430e90925284832093518454925182166401000000000267ffffffffffffffff1990931691161717909155905191965083916001600160a01b038b16917f0f5bb82176feb1b5e747e28471aa92156a04d9f3ab9f45f28e2d704232b93f7591a3505060010161299a565b5050949350505050565b6001600160a01b0381166000908152620f430d60205260408120548180612c2a856128bc565b90925090506000612c3b8285613e6a565b905082620f430b6000886001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160086101000a81548163ffffffff021916908363ffffffff160217905550606082015181600001600c6101000a81548163ffffffff021916908363ffffffff16021790555060808201518160000160106101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160000160146101000a81548160ff021916908360ff16021790555060c08201518160000160156101000a81548160ff021916908360ff16021790555060e08201518160000160166101000a81548160ff021916908360ff1602179055506101008201518160000160176101000a81548160ff021916908360ff1602179055506101208201518160000160186101000a81548160ff021916908360ff1602179055506101408201518160000160196101000a81548160ff021916908360ff16021790555061016082015181600001601a6101000a81548160ff021916908360ff16021790555061018082015181600001601b6101000a81548160ff021916908360ff1602179055506101a082015181600001601c6101000a81548160ff021916908360ff1602179055506101c082015181600001601d6101000a81548160ff021916908360ff1602179055506101e082015181600001601e6101000a81548160ff021916908360ff16021790555061020082015181600001601f6101000a81548160ff021916908360ff16021790555090505080620f430d6000886001600160a01b03166001600160a01b0316815260200190815260200160002081905550612ef581613698565b9695505050505050565b612f07612241565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586127043390565b612f446138f1565b50848260005b818110156132cb576000868683818110612f6657612f66613f18565b602090810292909201356000818152620f430e845260409081902081518083019092525463ffffffff808216808452640100000000909204169482019490945290935091159050612fea5760405162461bcd60e51b815260206004820152600e60248201526d105b1c9958591e481cdd185ad95960921b60448201526064016107d6565b600080875111612ffa5742613015565b86848151811061300c5761300c613f18565b60200260200101515b6040805160a081018252600080825260208201819052818301819052606082018190526080820152905163269f5cb960e01b8152600481018690529192509073ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e90633ad9726c9089906001600160a01b037f000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c036169063269f5cb99060240160806040518083038186803b1580156130be57600080fd5b505afa1580156130d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130f69190613fa4565b858760200151896040518663ffffffff1660e01b815260040161311d9594939291906144c3565b6102c06040518083038186803b15801561313657600080fd5b505af415801561314a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061316e9190614505565b6080810151919850915063ffffffff161561324a576001600160a01b038b166000908152620f430c6020908152604091829020825163c6043c7760e01b8152600481019190915283516001600160801b031660248201529083015163ffffffff90811660448301529183015182166064820152606083015182166084820152608083015190911660a482015273ac25c2fb42b08ebab4d185efe4f9c8a430d97b1e9063c6043c779060c40160006040518083038186803b15801561323157600080fd5b505af4158015613245573d6000803e3d6000fd5b505050505b613253826136a7565b6000858152620f430e6020908152604091829020805463ffffffff191663ffffffff94909416939093179092555183815285916001600160a01b038e16917f1449c6dd7851abc30abf37f57715f492010519147cc2652fbc38202c18a6ee90910160405180910390a384600101945050505050612f4a565b505095945050505050565b600054610100900460ff166122875760405162461bcd60e51b81526004016107d6906145ba565b600054610100900460ff166133245760405162461bcd60e51b81526004016107d6906145ba565b612287613710565b60405180604001604052808263ffffffff16815260200161334c426136a7565b63ffffffff908116909152620f430a8054600101908190556000908152620f43096020908152604091829020845181549583015185166401000000000267ffffffffffffffff1990961690851617949094179093555190831681527f16bacabd495cd45d904b6dc6184eabc5a6d654a4ee84569a5489ee7b20bc4364910160405180910390a150565b6133df8282611a63565b610989576133ec81613743565b6133f7836020613755565b604051602001613408929190614631565b60408051601f198184030181529082905262461bcd60e51b82526107d6916004016146a6565b60008061343a83613698565b60405163a9059cbb60e01b81526001600160a01b038681166004830152602482018390529192507f000000000000000000000000a203b4af1e1fdda5f76bed36a63c7a6ef3e308ff9091169063a9059cbb90604401602060405180830381600087803b1580156134a957600080fd5b505af11580156134bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134e191906146d9565b509392505050565b60975460ff166122875760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b60448201526064016107d6565b60405163e985e9c560e01b81526001600160a01b03838116600483015284811660248301526000917f000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c0369091169063e985e9c59060440160206040518083038186803b1580156135a057600080fd5b505afa1580156135b4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135d891906146d9565b80610e9e5750836001600160a01b03167f000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c0366001600160a01b031663081812fc846040518263ffffffff1660e01b815260040161363691815260200190565b60206040518083038186803b15801561364e57600080fd5b505afa158015613662573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136869190614169565b6001600160a01b031614949350505050565b60006106cc620f4240836140cd565b600063ffffffff82111561370c5760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203360448201526532206269747360d01b60648201526084016107d6565b5090565b600054610100900460ff166137375760405162461bcd60e51b81526004016107d6906145ba565b6097805460ff19169055565b60606106cc6001600160a01b03831660145b606060006137648360026140cd565b61376f906002613e6a565b67ffffffffffffffff81111561378757613787613f02565b6040519080825280601f01601f1916602001820160405280156137b1576020820181803683370190505b509050600360fc1b816000815181106137cc576137cc613f18565b60200101906001600160f81b031916908160001a905350600f60fb1b816001815181106137fb576137fb613f18565b60200101906001600160f81b031916908160001a905350600061381f8460026140cd565b61382a906001613e6a565b90505b60018111156138a2576f181899199a1a9b1b9c1cb0b131b232b360811b85600f166010811061385e5761385e613f18565b1a60f81b82828151811061387457613874613f18565b60200101906001600160f81b031916908160001a90535060049490941c9361389b816146fb565b905061382d565b508315611bb55760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016107d6565b6040805161022081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101829052610100810182905261012081018290526101408101829052610160810182905261018081018290526101a081018290526101c081018290526101e0810182905261020081019190915290565b60006020828403121561398f57600080fd5b81356001600160e01b031981168114611bb557600080fd5b6001600160a01b0381168114610ad057600080fd5b6000602082840312156139ce57600080fd5b8135611bb5816139a7565b6000602082840312156139eb57600080fd5b5035919050565b60008060408385031215613a0557600080fd5b823591506020830135613a17816139a7565b809150509250929050565b60008083601f840112613a3457600080fd5b50813567ffffffffffffffff811115613a4c57600080fd5b602083019150836020828501011115613a6457600080fd5b9250929050565b60ff81168114610ad057600080fd5b60008060008060008060008060006101008a8c031215613a9957600080fd5b8935613aa4816139a7565b985060208a0135975060408a0135965060608a013567ffffffffffffffff811115613ace57600080fd5b613ada8c828d01613a22565b90975095505060808a0135935060a08a0135613af581613a6b565b8093505060c08a0135915060e08a013590509295985092959850929598565b60008083601f840112613b2657600080fd5b50813567ffffffffffffffff811115613b3e57600080fd5b6020830191508360208260051b8501011115613a6457600080fd5b600080600060408486031215613b6e57600080fd5b8335613b79816139a7565b9250602084013567ffffffffffffffff811115613b9557600080fd5b613ba186828701613b14565b9497909650939450505050565b60008060008060008060808789031215613bc757600080fd5b8635613bd2816139a7565b9550602087013567ffffffffffffffff80821115613bef57600080fd5b613bfb8a838b01613b14565b9097509550604089013594506060890135915080821115613c1b57600080fd5b50613c2889828a01613a22565b979a9699509497509295939492505050565b60008060008060608587031215613c5057600080fd5b8435613c5b816139a7565b93506020850135613c6b816139a7565b9250604085013567ffffffffffffffff811115613c8757600080fd5b613c9387828801613b14565b95989497509550505050565b63ffffffff81168114610ad057600080fd5b600060208284031215613cc357600080fd5b8135611bb581613c9f565b60008060408385031215613ce157600080fd5b8235613cec816139a7565b91506020830135613a17816139a7565b805463ffffffff8082168452602082811c821690850152604082811c821690850152606082811c821690850152608082811c8216908501525060ff613d4b60a08501828460a01c1660ff169052565b613d5f60c08501828460a81c1660ff169052565b613d7360e08501828460b01c1660ff169052565b613d886101008501828460b81c1660ff169052565b613d9d6101208501828460c01c1660ff169052565b613db26101408501828460c81c1660ff169052565b613dc76101608501828460d01c1660ff169052565b613ddc6101808501828460d81c1660ff169052565b613df16101a08501828460e01c1660ff169052565b613e066101c08501828460e81c1660ff169052565b613e1b6101e08501828460f01c1660ff169052565b5060f881901c610200840152505050565b61022081016106cc8284613cfc565b600060208284031215613e4d57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b60008219821115613e7d57613e7d613e54565b500190565b600082821015613e9457613e94613e54565b500390565b60006001600160fb1b03831115613eaf57600080fd5b8260051b80858437600092019182525092915050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b602081526000610e9e602083018486613ec5565b634e487b7160e01b600052604160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b604051610220810167ffffffffffffffff81118282101715613f6057634e487b7160e01b600052604160045260246000fd5b60405290565b60405160a0810167ffffffffffffffff81118282101715613f6057634e487b7160e01b600052604160045260246000fd5b60098110610ad057600080fd5b600060808284031215613fb657600080fd5b6040516080810181811067ffffffffffffffff82111715613fe757634e487b7160e01b600052604160045260246000fd5b6040528251613ff581613f97565b815260208301516005811061400957600080fd5b6020820152604083015161401c81613f97565b604082015260608301516004811061403357600080fd5b60608201529392505050565b634e487b7160e01b600052602160045260246000fd5b60098110610ad057610ad061403f565b805161407081614055565b82526020810151600581106140875761408761403f565b6020830152604081015161409a81614055565b60408301526060810151600481106140b4576140b461403f565b806060840152505050565b608081016106cc8284614065565b60008160001904831182151516156140e7576140e7613e54565b500290565b60008261410957634e487b7160e01b600052601260045260246000fd5b500490565b600061010060018060a01b038c1683528a602084015289604084015280606084015261413d818401898b613ec5565b91505085608083015260ff851660a08301528360c08301528260e08301529a9950505050505050505050565b60006020828403121561417b57600080fd5b8151611bb5816139a7565b6102a081016141958288613cfc565b856102208301528461024083015283610260830152826102808301529695505050505050565b8051610ddf81613c9f565b8051610ddf81613a6b565b600061022082840312156141e457600080fd5b6141ec613f2e565b90506141f7826141bb565b8152614205602083016141bb565b6020820152614216604083016141bb565b6040820152614227606083016141bb565b6060820152614238608083016141bb565b608082015261424960a083016141c6565b60a082015261425a60c083016141c6565b60c082015261426b60e083016141c6565b60e082015261010061427e8184016141c6565b908201526101206142908382016141c6565b908201526101406142a28382016141c6565b908201526101606142b48382016141c6565b908201526101806142c68382016141c6565b908201526101a06142d88382016141c6565b908201526101c06142ea8382016141c6565b908201526101e06142fc8382016141c6565b9082015261020061430e8382016141c6565b9082015292915050565b600080610240838503121561432c57600080fd5b61433684846141d1565b915061022083015190509250929050565b805163ffffffff1682526020810151614368602084018263ffffffff169052565b506040810151614380604084018263ffffffff169052565b506060810151614398606084018263ffffffff169052565b5060808101516143b0608084018263ffffffff169052565b5060a08101516143c560a084018260ff169052565b5060c08101516143da60c084018260ff169052565b5060e08101516143ef60e084018260ff169052565b506101008181015160ff90811691840191909152610120808301518216908401526101408083015182169084015261016080830151821690840152610180808301518216908401526101a0808301518216908401526101c0808301518216908401526101e0808301518216908401526102008083015191821681850152905b50505050565b6102c081016144838286614347565b614491610220830185614065565b63ffffffff83166102a0830152949350505050565b600061022082840312156144b957600080fd5b611bb583836141d1565b61030081016144d28288614347565b6144e0610220830187614065565b846102a083015263ffffffff84166102c0830152826102e08301529695505050505050565b6000808284036102c081121561451a57600080fd5b61452485856141d1565b925060a061021f198201121561453957600080fd5b50614542613f66565b6102208401516001600160801b038116811461455d57600080fd5b815261024084015161456e81613c9f565b602082015261026084015161458281613c9f565b604082015261028084015161459681613c9f565b60608201526102a08401516145aa81613c9f565b6080820152919491935090915050565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b60005b83811015614620578181015183820152602001614608565b8381111561446e5750506000910152565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351614669816017850160208801614605565b7001034b99036b4b9b9b4b733903937b6329607d1b601791840191820152835161469a816028840160208801614605565b01602801949350505050565b60208152600082518060208401526146c5816040850160208701614605565b601f01601f19169190910160400192915050565b6000602082840312156146eb57600080fd5b81518015158114611bb557600080fd5b60008161470a5761470a613e54565b50600019019056fea2646970667358221220c9cbb8c1be6e9fb8a760d0d52cdca9cf46642ad07b5a6e66a50b6987dd354b8964736f6c63430008090033

Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)

000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c036000000000000000000000000a203b4af1e1fdda5f76bed36a63c7a6ef3e308ff

-----Decoded View---------------
Arg [0] : ikani (address): 0xC232599b4359bEb071b435134AB7AEf3EC78C036
Arg [1] : rewardsErc20 (address): 0xA203b4Af1e1fDDA5F76bEd36a63C7a6ef3E308Ff

-----Encoded View---------------
2 Constructor Arguments found :
Arg [0] : 000000000000000000000000c232599b4359beb071b435134ab7aef3ec78c036
Arg [1] : 000000000000000000000000a203b4af1e1fdda5f76bed36a63c7a6ef3e308ff


Block Transaction Difficulty Gas Used Reward
View All Blocks Produced

Block Uncle Number Difficulty Gas Used Reward
View All Uncles
Loading...
Loading
Loading...
Loading

Validator Index Block Amount
View All Withdrawals

Transaction Hash Block Value Eth2 PubKey Valid
View All Deposits
Loading...
Loading

A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.