// File: contracts/ERC-721/PeripheralERC721Pool.sol



// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.4;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./IPeripheralERC721Pool.sol";
import "./IERC721Pool.sol";

/// @title PeripheralERC721Pool
/// @author Hifi
contract PeripheralERC721Pool is IPeripheralERC721Pool {
    /// PUBLIC NON-CONSTANT FUNCTIONS ///

    /// @inheritdoc IPeripheralERC721Pool
    function bulkDeposit(IERC721Pool pool, uint256[] calldata ids) external override {
        // Checks: ids length must be greater than zero
        if (ids.length == 0) {
            revert PeripheralERC721Pool__InsufficientIn();
        }

        IERC721 erc721Asset = IERC721(pool.asset());

        // Effects: Approve the pool to transfer the NFTs.
        if (!erc721Asset.isApprovedForAll(address(this), address(pool)))
            erc721Asset.setApprovalForAll(address(pool), true);

        // `msg.sender` is the owner of the NFTs who will receive the pool tokens.
        for (uint256 i = 0; i < ids.length; ) {
            // Interactions: Transfer the NFTs from caller to this contract.
            // The transfer will revert if this contract is not approved to transfer the NFT.
            erc721Asset.transferFrom(msg.sender, address(this), ids[i]);

            // Effects: transfer NFTs from this contract to the pool and mint pool tokens to msg.sender.
            pool.deposit(ids[i], msg.sender);
            unchecked {
                ++i;
            }
        }

        emit BulkDeposit(address(pool), ids, msg.sender);
    }

    /// @inheritdoc IPeripheralERC721Pool
    function bulkWithdraw(IERC721Pool pool, uint256[] calldata ids) public override {
        uint256 idsLength = ids.length;

        withdrawInternal(pool, idsLength);

        for (uint256 i = 0; i < idsLength; ) {
            // `msg.sender` is the owner of the pool tokens who will receive the NFTs.
            // Effects: transfer NFTs from the pool to msg.sender in exchange for pool tokens.
            pool.withdraw(ids[i], msg.sender);
            unchecked {
                ++i;
            }
        }
        emit BulkWithdraw(address(pool), ids, msg.sender);
    }

    /// @inheritdoc IPeripheralERC721Pool
    function withdrawAvailable(IERC721Pool pool, uint256[] calldata ids) external override {
        uint256 idsLength = ids.length;

        withdrawInternal(pool, idsLength);

        uint256[] memory withdrawnIds = new uint256[](idsLength);
        uint256 withdrawnCount;
        for (uint256 i; i < idsLength; ) {
            // `msg.sender` is the owner of the pool tokens who will receive the NFTs.
            // Effects: transfer available NFTs from the pool to msg.sender in exchange for pool tokens
            if (pool.holdingContains(ids[i])) {
                pool.withdraw(ids[i], msg.sender);
                withdrawnIds[withdrawnCount] = ids[i];
                withdrawnCount++;
            }
            unchecked {
                ++i;
            }
        }

        if (withdrawnCount == 0) {
            revert PeripheralERC721Pool__NoNFTsWithdrawn();
        }

        // Resize the withdrawnIds array to fit the actual number of withdrawn NFTs
        assembly {
            mstore(withdrawnIds, withdrawnCount)
        }
        pool.transfer(msg.sender, (idsLength - withdrawnCount) * 10**18);
        emit WithdrawAvailable(address(pool), withdrawnIds, msg.sender);
    }

    /// @dev See the documentation for the public functions that call this internal function.
    function withdrawInternal(IERC721Pool pool, uint256 idsLength) internal {
        // Checks: ids length must be greater than zero
        if (idsLength == 0) {
            revert PeripheralERC721Pool__InsufficientIn();
        }

        // Checks: The caller must have allowed this contract to transfer the pool tokens.
        if (pool.allowance(msg.sender, address(this)) < idsLength * 10**18)
            revert PeripheralERC721Pool__UnapprovedOperator();

        // Interactions: Transfer the pool token from caller to this contract.
        pool.transferFrom(msg.sender, address(this), idsLength * 10**18);
    }
}

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



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

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

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

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

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

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

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

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

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

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

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

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

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

// File: contracts/ERC-721/IPeripheralERC721Pool.sol



// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.4;

import "./IERC721Pool.sol";

/// @title IPeripheralERC721Pool
/// @author Hifi
interface IPeripheralERC721Pool {
    /// CUSTOM ERRORS ///

    error PeripheralERC721Pool__InsufficientIn();
    error PeripheralERC721Pool__NoNFTsWithdrawn();
    error PeripheralERC721Pool__UnapprovedOperator();

    /// EVENTS ///

    /// @notice Emitted when NFTs are deposited in exchange for an equivalent amount of pool tokens.
    /// @param pool The address of the pool.
    /// @param ids The asset token IDs sent from the user's account to the pool.
    /// @param caller The caller of the function equal to msg.sender.
    event BulkDeposit(address pool, uint256[] ids, address caller);

    /// @notice Emitted when NFTs are withdrawn from the pool in exchange for an equivalent amount of pool tokens.
    /// @param pool The address of the pool.
    /// @param ids The asset token IDs released from the pool.
    /// @param caller The caller of the function equal to msg.sender.
    event BulkWithdraw(address pool, uint256[] ids, address caller);

    /// @notice Emitted when as many as available NFTs are withdrawn from the pool in exchange for an equal amount of pool tokens.
    /// @param pool The address of the pool.
    /// @param withdrawnIds The asset token IDs released from the pool.
    /// @param caller The caller of the function equal to msg.sender.
    event WithdrawAvailable(address pool, uint256[] withdrawnIds, address caller);

    /// CONSTANT FUNCTIONS ///

    // /// @notice The address of the pool.
    // function pool() external view returns (address);

    /// NON-CONSTANT FUNCTIONS ///

    /// @notice Deposit NFTs in exchange for an equivalent amount of pool tokens.
    ///
    /// @dev Emits a {Deposit} event.
    ///
    /// @dev Requirements:
    ///
    /// - The length of `ids` must be greater than zero.
    /// - The caller must have allowed the pool to transfer the NFTs.
    /// - The address `beneficiary` must not be the zero address.
    ///
    /// @param pool The address of the pool.
    /// @param ids The asset token IDs sent from the user's account to the pool.
    function bulkDeposit(IERC721Pool pool, uint256[] calldata ids) external;

    /// @notice Withdraw specified NFTs in exchange for an equivalent amount of pool tokens.
    ///
    /// @dev Emits a {Withdraw} event.
    ///
    /// @dev Requirements:
    ///
    /// - The length of `ids` must be greater than zero.
    /// - The caller must have allowed the PeripheralERC721Pool to transfer the pool tokens by calling
    ///   `approve()` on the pool token contract with sufficient allowance before calling this function.
    ///
    /// @param pool The address of the pool.
    /// @param ids The asset token IDs to be released from the pool.
    function bulkWithdraw(IERC721Pool pool, uint256[] calldata ids) external;

    /// @notice Withdraw specified available non-overlapping NFTs in exchange for an equivalent amount of pool tokens.
    ///
    /// @dev Emits a {WithdrawAvailable} event.
    ///
    /// @dev Requirements:
    ///
    /// - The length of `ids` must be greater than zero.
    /// - The caller must have allowed the PeripheralERC721Pool to transfer the pool tokens.
    /// - The address `beneficiary` must not be the zero address.
    ///
    /// @param pool The address of the pool.
    /// @param ids The asset token IDs to be released from the pool.
    function withdrawAvailable(IERC721Pool pool, uint256[] calldata ids) external;
}

// File: contracts/ERC-721/IERC721Pool.sol



// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.4;

import "./IERC20Wnft.sol";

/// @title IERC721Pool
/// @author Hifi
interface IERC721Pool is IERC20Wnft {
    /// CUSTOM ERRORS ///

    error ERC721Pool__CallerNotFactory(address factory, address caller);
    error ERC721Pool__MustContainExactlyOneNFT();
    error ERC721Pool__PoolFrozen();
    error ERC721Pool__NFTAlreadyInPool(uint256 id);
    error ERC721Pool__NFTNotFoundInPool(uint256 id);
    error ERC721Pool__ZeroAddress();

    /// EVENTS ///

    /// @notice Emitted when NFT are deposited and an equal amount of pool tokens are minted.
    /// @param id The asset token ID sent from the user's account to the pool.
    /// @param beneficiary The address to receive the pool tokens.
    /// @param caller The caller of the function equal to msg.sender.
    event Deposit(uint256 id, address beneficiary, address caller);

    /// @notice Emitted when the last NFT of a pool is rescued.
    /// @param lastNFT The last NFT of the pool.
    /// @param to The address to which the NFT was sent.
    event RescueLastNFT(uint256 lastNFT, address to);

    /// @notice Emitted when NFT are withdrawn from the pool in exchange for an equal amount of pool tokens.
    /// @param id The asset token IDs released from the pool.
    /// @param beneficiary The address to receive the NFT.
    /// @param caller The caller of the function equal to msg.sender.
    event Withdraw(uint256 id, address beneficiary, address caller);

    /// CONSTANT FUNCTIONS ///

    /// @notice Returns the asset token ID held at index.
    /// @param index The index to check.
    function holdingAt(uint256 index) external view returns (uint256);

    /// @notice Returns true if the asset token ID is held in the pool.
    /// @param id The asset token ID to check.
    function holdingContains(uint256 id) external view returns (bool);

    /// @notice Returns the total number of asset token IDs held.
    function holdingsLength() external view returns (uint256);

    /// @notice A boolean flag indicating whether the pool is frozen.
    function poolFrozen() external view returns (bool);

    /// NON-CONSTANT FUNCTIONS ///

    /// @notice Deposit NFT in exchange for an equivalent amount of pool tokens.
    ///
    /// @dev Emits a {Deposit} event.
    ///
    /// @dev Requirements:
    /// - The caller must have allowed the Pool to transfer the NFT.
    /// - The pool must not be frozen.
    /// - The address `beneficiary` must not be the zero address.
    ///
    /// @param id The asset token ID sent from the user's account to the pool.
    /// @param beneficiary The address to receive the pool tokens. Can be the caller themselves or any other address.
    function deposit(uint256 id, address beneficiary) external;

    /// @notice Allows the factory to rescue the last NFT in the pool and set the pool to frozen.
    ///
    /// Emits a {RescueLastNFT} event.
    ///
    /// @dev Requirements:
    /// - The caller must be the factory.
    /// - The pool must only hold one NFT.
    ///
    /// @param to The address to send the NFT to.
    function rescueLastNFT(address to) external;

    /// @notice Allows the factory to set the ENS name for the pool.
    ///
    /// Emits a {ENSNameSet} event.
    ///
    /// @dev Requirements:
    /// - The caller must be the factory.
    ///
    /// @param registrar The address of the ENS registrar.
    /// @param name The name to set.
    /// @return The ENS node hash.
    function setENSName(address registrar, string memory name) external returns (bytes32);

    /// @notice Withdraws a specified NFT in exchange for an equivalent amount of pool tokens.
    ///
    /// @dev Emits a {Withdraw} event.
    ///
    /// @dev Requirements:
    /// - The pool must not be frozen.
    /// - The address `beneficiary` must not be the zero address.
    /// - The specified NFT must be held in the pool.
    /// - The caller must hold the equivalent amount of pool tokens
    ///
    /// @param id The asset token ID to be released from the pool.
    /// @param beneficiary The address to receive the NFT. Can be the caller themselves or any other address.
    function withdraw(uint256 id, address beneficiary) external;
}

// File: @openzeppelin/contracts/utils/introspection/IERC165.sol



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

pragma solidity ^0.8.0;

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

// File: contracts/ERC-721/IERC20Wnft.sol



// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.8.4;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";

/// @title IERC20Wnft
/// @author Hifi
interface IERC20Wnft is IERC20Permit, IERC20Metadata {
    /// CUSTOM ERRORS ///

    error ERC20Wnft__Forbidden();
    error ERC20Wnft__InvalidSignature();
    error ERC20Wnft__PermitExpired();

    /// EVENTS ///

    /// @notice Emitted when the contract is initialized.
    /// @param name The ERC-20 name.
    /// @param symbol The ERC-20 symbol.
    /// @param asset The underlying ERC-721 asset contract address.
    event Initialize(string name, string symbol, address indexed asset);

    /// CONSTANT FUNCTIONS ///

    /// @notice Returns the address of the underlying ERC-721 asset.
    function asset() external view returns (address);

    /// @notice Returns the factory contract address.
    function factory() external view returns (address);

    /// NON-CONSTANT FUNCTIONS ///

    /// @notice Initializes the contract with the given values.
    ///
    /// @dev Emits an {Initialize} event.
    ///
    /// @dev Requirements:
    /// - Can only be called by the factory.
    ///
    /// @param name The ERC-20 name.
    /// @param symbol The ERC-20 symbol.
    /// @param asset The underlying ERC-721 asset contract address.
    function initialize(
        string memory name,
        string memory symbol,
        address asset
    ) external;
}

// File: @openzeppelin/contracts/token/ERC20/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: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol



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

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

// File: @openzeppelin/contracts/token/ERC20/extensions/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);
}