// File: @openzeppelin/contracts/access/Ownable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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 Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

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

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby disabling 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: @openzeppelin/contracts/access/Ownable2Step.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.0;

import "./Ownable.sol";

/**
 * @dev Contract module which provides 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} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
        _transferOwnership(sender);
    }
}

// File: @openzeppelin/contracts/governance/utils/IVotes.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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 a specific moment in the past. If the `clock()` is
     * configured to use block numbers, this will return the value at the end of the corresponding block.
     */
    function getPastVotes(address account, uint256 timepoint) external view returns (uint256);

    /**
     * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
     * configured to use block numbers, this will return the value at the end of the corresponding block.
     *
     * 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 timepoint) 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: @openzeppelin/contracts/proxy/Clones.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)

pragma solidity ^0.8.0;

/**
 * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
 * deploying minimal proxy contracts, also known as "clones".
 *
 * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
 * > a minimal bytecode implementation that delegates all calls to a known, fixed address.
 *
 * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
 * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
 * deterministic method.
 *
 * _Available since v3.4._
 */
library Clones {
    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create opcode, which should never revert.
     */
    function clone(address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create(0, 0x09, 0x37)
        }
        require(instance != address(0), "ERC1167: create failed");
    }

    /**
     * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
     *
     * This function uses the create2 opcode and a `salt` to deterministically deploy
     * the clone. Using the same `implementation` and `salt` multiple time will revert, since
     * the clones cannot be deployed twice at the same address.
     */
    function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
            // of the `implementation` address with the bytecode before the address.
            mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
            // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
            mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
            instance := create2(0, 0x09, 0x37, salt)
        }
        require(instance != address(0), "ERC1167: create2 failed");
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(add(ptr, 0x38), deployer)
            mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
            mstore(add(ptr, 0x14), implementation)
            mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
            mstore(add(ptr, 0x58), salt)
            mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
            predicted := keccak256(add(ptr, 0x43), 0x55)
        }
    }

    /**
     * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
     */
    function predictDeterministicAddress(
        address implementation,
        bytes32 salt
    ) internal view returns (address predicted) {
        return predictDeterministicAddress(implementation, salt, address(this));
    }
}

// File: @openzeppelin/contracts/proxy/utils/Initializable.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.2;

import "../../utils/Address.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]
 * ```solidity
 * 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.
     *
     * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
     * constructor.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        bool isTopLevelCall = !_initializing;
        require(
            (isTopLevelCall && _initialized < 1) || (!Address.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.
     *
     * 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.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * 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.
     *
     * WARNING: setting the version to 255 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    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.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        require(!_initializing, "Initializable: contract is initializing");
        if (_initialized != type(uint8).max) {
            _initialized = type(uint8).max;
            emit Initialized(type(uint8).max);
        }
    }

    /**
     * @dev Returns the highest version that has been initialized. See {reinitializer}.
     */
    function _getInitializedVersion() internal view returns (uint8) {
        return _initialized;
    }

    /**
     * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
     */
    function _isInitializing() internal view returns (bool) {
        return _initializing;
    }
}

// File: @openzeppelin/contracts/security/Pausable.sol



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

pragma solidity ^0.8.0;

import "../utils/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: @openzeppelin/contracts/security/ReentrancyGuard.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}

// File: @openzeppelin/contracts/token/ERC20/ERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/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.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * 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}.
     *
     * 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 default value returned by this function, unless
     * it's 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;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _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;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _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;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _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: @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/IERC20Permit.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/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: @openzeppelin/contracts/token/ERC20/IERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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/utils/SafeERC20.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(IERC20 token, address spender, uint256 value) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
     * Revert on invalid signature.
     */
    function safePermit(
        IERC20Permit token,
        address owner,
        address spender,
        uint256 value,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        uint256 nonceBefore = token.nonces(owner);
        token.permit(owner, spender, value, deadline, v, r, s);
        uint256 nonceAfter = token.nonces(owner);
        require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
        // and not revert is the subcall reverts.

        (bool success, bytes memory returndata) = address(token).call(data);
        return
            success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
    }
}

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



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

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.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 ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings 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.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

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

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

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        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) {
        _requireMinted(tokenId);

        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 overridden 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 = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

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

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        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: caller is not token owner or 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: caller is not token owner or 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 the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @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 _ownerOf(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) {
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == 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, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

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

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

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

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

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

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

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

    /**
     * @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(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

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

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {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 Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @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 IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 firstTokenId, uint256 batchSize) internal virtual {}

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
     * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
     * that `ownerOf(tokenId)` is `a`.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __unsafe_increaseBalance(address account, uint256 amount) internal {
        _balances[account] += amount;
    }
}

// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol



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

pragma solidity ^0.8.0;

import "../ERC721.sol";
import "../../../utils/Context.sol";

/**
 * @title ERC721 Burnable Token
 * @dev ERC721 Token that can be burned (destroyed).
 */
abstract contract ERC721Burnable is Context, ERC721 {
    /**
     * @dev Burns `tokenId`. See {ERC721-_burn}.
     *
     * Requirements:
     *
     * - The caller must own `tokenId` or be an approved operator.
     */
    function burn(uint256 tokenId) public virtual {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _burn(tokenId);
    }
}

// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol



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

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @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: @openzeppelin/contracts/token/ERC721/IERC721.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (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 IERC721Receiver {
    /**
     * @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 `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

// File: @openzeppelin/contracts/utils/Address.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @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
     *
     * Furthermore, `isContract` will also return true if the target contract within
     * the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
     * which only has an effect at the end of a transaction.
     * ====
     *
     * [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://consensys.net/diligence/blog/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.8.0/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 Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(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: @openzeppelin/contracts/utils/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: @openzeppelin/contracts/utils/cryptography/ECDSA.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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 // Deprecated in v4.8
    }

    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");
        }
    }

    /**
     * @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) {
        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 {
            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 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 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @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 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}

// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.2) (utils/cryptography/MerkleProof.sol)

pragma solidity ^0.8.0;

/**
 * @dev These functions deal with verification of Merkle Tree proofs.
 *
 * The tree and the proofs can be generated using our
 * https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
 * You will find a quickstart guide in the readme.
 *
 * WARNING: You should avoid using leaf values that are 64 bytes long prior to
 * hashing, or use a hash function other than keccak256 for hashing leaves.
 * This is because the concatenation of a sorted pair of internal nodes in
 * the merkle tree could be reinterpreted as a leaf value.
 * OpenZeppelin's JavaScript library generates merkle trees that are safe
 * against this attack out of the box.
 */
library MerkleProof {
    /**
     * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
     * defined by `root`. For this, a `proof` must be provided, containing
     * sibling hashes on the branch from the leaf to the root of the tree. Each
     * pair of leaves and each pair of pre-images are assumed to be sorted.
     */
    function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProof(proof, leaf) == root;
    }

    /**
     * @dev Calldata version of {verify}
     *
     * _Available since v4.7._
     */
    function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
        return processProofCalldata(proof, leaf) == root;
    }

    /**
     * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
     * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
     * hash matches the root of the tree. When processing the proof, the pairs
     * of leafs & pre-images are assumed to be sorted.
     *
     * _Available since v4.4._
     */
    function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Calldata version of {processProof}
     *
     * _Available since v4.7._
     */
    function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
        bytes32 computedHash = leaf;
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    /**
     * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a merkle tree defined by
     * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerify(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProof(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Calldata version of {multiProofVerify}
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function multiProofVerifyCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32 root,
        bytes32[] memory leaves
    ) internal pure returns (bool) {
        return processMultiProofCalldata(proof, proofFlags, leaves) == root;
    }

    /**
     * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
     * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
     * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
     * respectively.
     *
     * CAUTION: Not all merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
     * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
     * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
     *
     * _Available since v4.7._
     */
    function processMultiProof(
        bytes32[] memory proof,
        bool[] memory proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            require(proofPos == proofLen, "MerkleProof: invalid multiproof");
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    /**
     * @dev Calldata version of {processMultiProof}.
     *
     * CAUTION: Not all merkle trees admit multiproofs. See {processMultiProof} for details.
     *
     * _Available since v4.7._
     */
    function processMultiProofCalldata(
        bytes32[] calldata proof,
        bool[] calldata proofFlags,
        bytes32[] memory leaves
    ) internal pure returns (bytes32 merkleRoot) {
        // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
        // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
        // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
        // the merkle tree.
        uint256 leavesLen = leaves.length;
        uint256 proofLen = proof.length;
        uint256 totalHashes = proofFlags.length;

        // Check proof validity.
        require(leavesLen + proofLen - 1 == totalHashes, "MerkleProof: invalid multiproof");

        // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
        // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
        bytes32[] memory hashes = new bytes32[](totalHashes);
        uint256 leafPos = 0;
        uint256 hashPos = 0;
        uint256 proofPos = 0;
        // At each step, we compute the next hash using two values:
        // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
        //   get the next hash.
        // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
        //   `proof` array.
        for (uint256 i = 0; i < totalHashes; i++) {
            bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
            bytes32 b = proofFlags[i]
                ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
                : proof[proofPos++];
            hashes[i] = _hashPair(a, b);
        }

        if (totalHashes > 0) {
            require(proofPos == proofLen, "MerkleProof: invalid multiproof");
            unchecked {
                return hashes[totalHashes - 1];
            }
        } else if (leavesLen > 0) {
            return leaves[0];
        } else {
            return proof[0];
        }
    }

    function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) {
        return a < b ? _efficientHash(a, b) : _efficientHash(b, a);
    }

    function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

// File: @openzeppelin/contracts/utils/introspection/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: @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: @openzeppelin/contracts/utils/math/Math.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.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) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 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. If 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)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 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) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}

// File: @openzeppelin/contracts/utils/math/SafeCast.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

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 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @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 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @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: @openzeppelin/contracts/utils/math/SignedMath.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}

// File: @openzeppelin/contracts/utils/Strings.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _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) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @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] = _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);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}

// File: @uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}

// File: @uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
    /// @notice Emitted when the owner of the factory is changed
    /// @param oldOwner The owner before the owner was changed
    /// @param newOwner The owner after the owner was changed
    event OwnerChanged(address indexed oldOwner, address indexed newOwner);

    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param pool The address of the created pool
    event PoolCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        int24 tickSpacing,
        address pool
    );

    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
    /// @param fee The enabled fee, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via setOwner
    /// @return The address of the factory owner
    function owner() external view returns (address);

    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
    /// @return The tick spacing
    function feeAmountTickSpacing(uint24 fee) external view returns (int24);

    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The pool address
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param fee The desired fee for the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external returns (address pool);

    /// @notice Updates the owner of the factory
    /// @dev Must be called by the current owner
    /// @param _owner The new owner of the factory
    function setOwner(address _owner) external;

    /// @notice Enables a fee amount with the given tickSpacing
    /// @dev Fee amounts may never be removed once enabled
    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}

// File: @uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolEvents
{

}

// File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}

// File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}

// File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}

// File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}

// File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}

// File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}

// File: @uniswap/v3-core/contracts/libraries/FixedPoint96.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;

/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
    uint8 internal constant RESOLUTION = 96;
    uint256 internal constant Q96 = 0x1000000000000000000000000;
}

// File: @uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}

// File: @uniswap/v3-periphery/contracts/libraries/TransferHelper.sol



// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import '@openzeppelin/contracts/token/ERC20/IERC20.sol';

library TransferHelper {
    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors with 'SA' if transfer fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Fails with `STE`
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'STE');
    }
}

// File: contracts/Constants.sol



// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;

library Constants {
    uint256 internal constant YEAR_IN_SECONDS = 365 days;
    uint256 internal constant BASE = 1e18;
    uint256 internal constant MAX_FEE_PER_ANNUM = 0.05e18; // 5% max in base
    uint256 internal constant MAX_SWAP_PROTOCOL_FEE = 0.01e18; // 1% max in base
    uint256 internal constant MAX_TOTAL_PROTOCOL_FEE = 0.05e18; // 5% max in base
    uint256 internal constant MAX_P2POOL_PROTOCOL_FEE = 0.05e18; // 5% max in base
    uint256 internal constant MIN_TIME_BETWEEN_EARLIEST_REPAY_AND_EXPIRY =
        1 days;
    uint256 internal constant MAX_PRICE_UPDATE_TIMESTAMP_DIVERGENCE = 1 days;
    uint256 internal constant SEQUENCER_GRACE_PERIOD = 1 hours;
    uint256 internal constant MIN_UNSUBSCRIBE_GRACE_PERIOD = 1 days;
    uint256 internal constant MAX_UNSUBSCRIBE_GRACE_PERIOD = 14 days;
    uint256 internal constant MIN_CONVERSION_GRACE_PERIOD = 1 days;
    uint256 internal constant MIN_REPAYMENT_GRACE_PERIOD = 1 days;
    uint256 internal constant LOAN_EXECUTION_GRACE_PERIOD = 1 days;
    uint256 internal constant MAX_CONVERSION_AND_REPAYMENT_GRACE_PERIOD =
        30 days;
    uint256 internal constant MIN_TIME_UNTIL_FIRST_DUE_DATE = 1 days;
    uint256 internal constant MIN_TIME_BETWEEN_DUE_DATES = 7 days;
    uint256 internal constant MIN_WAIT_UNTIL_EARLIEST_UNSUBSCRIBE = 60 seconds;
    uint256 internal constant MAX_ARRANGER_FEE = 0.5e18; // 50% max in base
    uint256 internal constant LOAN_TERMS_UPDATE_COOL_OFF_PERIOD = 15 minutes;
    uint256 internal constant MAX_REPAYMENT_SCHEDULE_LENGTH = 20;
    uint256 internal constant SINGLE_WRAPPER_MIN_MINT = 1000; // in wei
}

// File: contracts/Errors.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

library Errors {
    error UnregisteredVault();
    error InvalidDelegatee();
    error InvalidSender();
    error InvalidFee();
    error InsufficientSendAmount();
    error NoOracle();
    error InvalidOracleAnswer();
    error InvalidOracleDecimals();
    error InvalidOracleVersion();
    error InvalidAddress();
    error InvalidArrayLength();
    error InvalidQuote();
    error OutdatedQuote();
    error InvalidOffChainSignature();
    error InvalidOffChainMerkleProof();
    error InvalidCollUnlock();
    error InvalidAmount();
    error UnknownOnChainQuote();
    error NeitherTokenIsGOHM();
    error NoLpTokens();
    error ZeroReserve();
    error IncorrectGaugeForLpToken();
    error InvalidGaugeIndex();
    error AlreadyStaked();
    error InvalidWithdrawAmount();
    error InvalidBorrower();
    error OutsideValidRepayWindow();
    error InvalidRepayAmount();
    error ReclaimAmountIsZero();
    error UnregisteredGateway();
    error NonWhitelistedOracle();
    error NonWhitelistedCompartment();
    error NonWhitelistedCallback();
    error NonWhitelistedToken();
    error LtvHigherThanMax();
    error InsufficientVaultFunds();
    error InvalidInterestRateFactor();
    error InconsistentUnlockTokenAddresses();
    error InvalidEarliestRepay();
    error InvalidNewMinNumOfSigners();
    error AlreadySigner();
    error InvalidArrayIndex();
    error InvalidSignerRemoveInfo();
    error InvalidSendAmount();
    error TooSmallLoanAmount();
    error DeadlinePassed();
    error WithdrawEntered();
    error DuplicateAddresses();
    error OnChainQuoteAlreadyAdded();
    error OffChainQuoteHasBeenInvalidated();
    error Uninitialized();
    error InvalidRepaymentScheduleLength();
    error FirstDueDateTooCloseOrPassed();
    error InvalidGracePeriod();
    error UnregisteredLoanProposal();
    error NotInSubscriptionPhase();
    error NotInUnsubscriptionPhase();
    error InsufficientBalance();
    error InsufficientFreeSubscriptionSpace();
    error BeforeEarliestUnsubscribe();
    error InconsistentLastLoanTermsUpdateTime();
    error InvalidActionForCurrentStatus();
    error FellShortOfTotalSubscriptionTarget();
    error InvalidRollBackRequest();
    error UnsubscriptionAmountTooLarge();
    error InvalidSubscriptionRange();
    error InvalidMaxTotalSubscriptions();
    error OutsideConversionTimeWindow();
    error OutsideRepaymentTimeWindow();
    error NoDefault();
    error LoanIsFullyRepaid();
    error RepaymentIdxTooLarge();
    error AlreadyClaimed();
    error AlreadyConverted();
    error InvalidDueDates();
    error LoanTokenDueIsZero();
    error WaitForLoanTermsCoolOffPeriod();
    error ZeroConversionAmount();
    error InvalidNewOwnerProposal();
    error CollateralMustBeCompartmentalized();
    error InvalidCompartmentForToken();
    error InvalidSignature();
    error InvalidUpdate();
    error CannotClaimOutdatedStatus();
    error DelegateReducedBalance();
    error FundingPoolAlreadyExists();
    error InvalidLender();
    error NonIncreasingTokenAddrs();
    error NonIncreasingNonFungibleTokenIds();
    error TransferToWrappedTokenFailed();
    error TransferFromWrappedTokenFailed();
    error StateAlreadySet();
    error ReclaimableCollateralAmountZero();
    error InvalidSwap();
    error InvalidUpfrontFee();
    error InvalidOracleTolerance();
    error ReserveRatiosSkewedFromOraclePrice();
    error SequencerDown();
    error GracePeriodNotOver();
    error LoanExpired();
    error NoDsEth();
    error TooShortTwapInterval();
    error TooLongTwapInterval();
    error TwapExceedsThreshold();
    error Reentrancy();
    error TokenNotStuck();
    error InconsistentExpTransferFee();
    error InconsistentExpVaultBalIncrease();
    error DepositLockActive();
    error DisallowedSubscriptionLockup();
    error IncorrectLoanAmount();
    error Disabled();
    error CannotRemintUnlessZeroSupply();
    error TokensStillMissingFromWrapper();
    error OnlyMintFromSingleTokenWrapper();
    error NonMintableTokenState();
    error NoTokensTransferred();
    error TokenAlreadyCountedInWrapper();
    error TokenNotOwnedByWrapper();
    error TokenDoesNotBelongInWrapper(address tokenAddr, uint256 tokenId);
    error InvalidMintAmount();
    error QuoteViolatesPolicy();
    error AlreadyPublished();
    error PolicyAlreadySet();
    error NoPolicyToDelete();
    error InvalidTenorBounds();
    error InvalidLtvBounds();
    error InvalidLoanPerCollBounds();
    error InvalidMinApr();
    error NoPolicy();
    error InvalidMinFee();
}

// File: contracts/Helpers.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

library Helpers {
    function splitSignature(
        bytes memory sig
    ) internal pure returns (bytes32 r, bytes32 vs) {
        require(sig.length == 64, "invalid signature length");
        // solhint-disable no-inline-assembly
        assembly {
            // first 32 bytes, after the length prefix
            r := mload(add(sig, 32))
            // second 32 bytes
            vs := mload(add(sig, 64))
        }
        // implicitly return (r, vs)
    }
}

// File: contracts/interfaces/IMysoTokenManager.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {DataTypesPeerToPeer} from "../peer-to-peer/DataTypesPeerToPeer.sol";
import {DataTypesPeerToPool} from "../peer-to-pool/DataTypesPeerToPool.sol";

interface IMysoTokenManager {
    function processP2PBorrow(
        uint128[2] memory currProtocolFeeParams,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.Loan calldata loan,
        address lenderVault
    ) external returns (uint128[2] memory applicableProtocolFeeParams);

    function processP2PCreateVault(
        uint256 numRegisteredVaults,
        address vaultCreator,
        address newLenderVaultAddr
    ) external;

    function processP2PCreateWrappedTokenForERC721s(
        address tokenCreator,
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped,
        bytes calldata mysoTokenManagerData
    ) external;

    function processP2PCreateWrappedTokenForERC20s(
        address tokenCreator,
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped,
        bytes calldata mysoTokenManagerData
    ) external;

    function processP2PoolDeposit(
        address fundingPool,
        address depositor,
        uint256 depositAmount,
        uint256 depositLockupDuration,
        uint256 transferFee
    ) external;

    function processP2PoolSubscribe(
        address fundingPool,
        address subscriber,
        address loanProposal,
        uint256 subscriptionAmount,
        uint256 subscriptionLockupDuration,
        uint256 totalSubscriptions,
        DataTypesPeerToPool.LoanTerms calldata loanTerms
    ) external;

    function processP2PoolLoanFinalization(
        address loanProposal,
        address fundingPool,
        address arranger,
        address borrower,
        uint256 grossLoanAmount,
        bytes calldata mysoTokenManagerData
    ) external;

    function processP2PoolCreateLoanProposal(
        address fundingPool,
        address proposalCreator,
        address collToken,
        uint256 arrangerFee,
        uint256 numLoanProposals
    ) external;
}

// File: contracts/peer-to-peer/AddressRegistry.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {DataTypesPeerToPeer} from "./DataTypesPeerToPeer.sol";
import {Errors} from "../Errors.sol";
import {Helpers} from "../Helpers.sol";
import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol";
import {IERC721Wrapper} from "./interfaces/wrappers/ERC721/IERC721Wrapper.sol";
import {IERC20Wrapper} from "./interfaces/wrappers/ERC20/IERC20Wrapper.sol";
import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol";

/**
 * @dev AddressRegistry is a contract that stores addresses of other contracts and controls whitelist state
 * IMPORTANT: This contract allows for de-whitelisting as well. This is an important security feature because if
 * a contract or token is found to present a vulnerability, it can be de-whitelisted to prevent further borrowing
 * with that token (repays and withdrawals would still be allowed). In the limit of a total de-whitelisting of all
 * tokens, all borrowing in the protocol would be paused. This feature can also be utilized if a fork with the same chainId is found.
 */
contract AddressRegistry is Initializable, Ownable2Step, IAddressRegistry {
    using ECDSA for bytes32;

    address public lenderVaultFactory;
    address public borrowerGateway;
    address public quoteHandler;
    address public mysoTokenManager;
    address public erc721Wrapper;
    address public erc20Wrapper;
    mapping(address => bool) public isRegisteredVault;
    mapping(bytes => bool) internal _signatureIsInvalidated;
    mapping(address => mapping(address => uint256))
        internal _borrowerWhitelistedUntil;
    mapping(address => DataTypesPeerToPeer.WhitelistState)
        public whitelistState;
    // compartment => token => active
    mapping(address => mapping(address => bool))
        internal _isTokenWhitelistedForCompartment;
    address[] internal _registeredVaults;

    constructor() {
        super._transferOwnership(msg.sender);
    }

    function initialize(
        address _lenderVaultFactory,
        address _borrowerGateway,
        address _quoteHandler
    ) external initializer {
        _checkOwner();
        if (
            _lenderVaultFactory == address(0) ||
            _borrowerGateway == address(0) ||
            _quoteHandler == address(0)
        ) {
            revert Errors.InvalidAddress();
        }
        if (
            _lenderVaultFactory == _borrowerGateway ||
            _lenderVaultFactory == _quoteHandler ||
            _borrowerGateway == _quoteHandler
        ) {
            revert Errors.DuplicateAddresses();
        }
        lenderVaultFactory = _lenderVaultFactory;
        borrowerGateway = _borrowerGateway;
        quoteHandler = _quoteHandler;
    }

    function setWhitelistState(
        address[] calldata addrs,
        DataTypesPeerToPeer.WhitelistState state
    ) external {
        _checkIsInitialized();
        _checkOwner();
        uint256 addrsLen = addrs.length;
        if (addrsLen < 1) {
            revert Errors.InvalidArrayLength();
        }

        (
            address _erc721Wrapper,
            address _erc20Wrapper,
            address _mysoTokenManager
        ) = (erc721Wrapper, erc20Wrapper, mysoTokenManager);
        // note (1/2): ERC721WRAPPER, ERC20WRAPPER and MYSO_TOKEN_MANAGER state can only be "occupied" by
        // one addresses ("singleton state")
        if (
            state == DataTypesPeerToPeer.WhitelistState.ERC721WRAPPER ||
            state == DataTypesPeerToPeer.WhitelistState.ERC20WRAPPER ||
            state == DataTypesPeerToPeer.WhitelistState.MYSO_TOKEN_MANAGER
        ) {
            if (addrsLen != 1) {
                revert Errors.InvalidArrayLength();
            }
            if (addrs[0] == address(0)) {
                revert Errors.InvalidAddress();
            }
            _updateSingletonAddr(
                addrs[0],
                state,
                _erc721Wrapper,
                _erc20Wrapper,
                _mysoTokenManager
            );
            whitelistState[addrs[0]] = state;
        } else {
            // note (2/2): all other states can be "occupied" by multiple addresses
            for (uint256 i; i < addrsLen; ) {
                if (addrs[i] == address(0)) {
                    revert Errors.InvalidAddress();
                }
                if (whitelistState[addrs[i]] == state) {
                    revert Errors.StateAlreadySet();
                }
                // check if addr was singleton before and delete, if needed
                _checkAddrAndDeleteIfSingleton(
                    addrs[i],
                    _erc721Wrapper,
                    _erc20Wrapper,
                    _mysoTokenManager
                );
                whitelistState[addrs[i]] = state;
                unchecked {
                    ++i;
                }
            }
        }
        emit WhitelistStateUpdated(addrs, state);
    }

    function setAllowedTokensForCompartment(
        address compartmentImpl,
        address[] calldata tokens,
        bool allowTokensForCompartment
    ) external {
        _checkIsInitialized();
        _checkOwner();
        // check that tokens can only be whitelisted for valid compartment (whereas de-whitelisting is always possible)
        if (
            allowTokensForCompartment &&
            whitelistState[compartmentImpl] !=
            DataTypesPeerToPeer.WhitelistState.COMPARTMENT
        ) {
            revert Errors.NonWhitelistedCompartment();
        }
        uint256 tokensLen = tokens.length;
        if (tokensLen == 0) {
            revert Errors.InvalidArrayLength();
        }
        for (uint256 i; i < tokensLen; ) {
            if (allowTokensForCompartment && !isWhitelistedERC20(tokens[i])) {
                revert Errors.NonWhitelistedToken();
            }
            if (
                _isTokenWhitelistedForCompartment[compartmentImpl][tokens[i]] ==
                allowTokensForCompartment
            ) {
                revert Errors.InvalidUpdate();
            }
            _isTokenWhitelistedForCompartment[compartmentImpl][
                tokens[i]
            ] = allowTokensForCompartment;
            unchecked {
                ++i;
            }
        }
        emit AllowedTokensForCompartmentUpdated(
            compartmentImpl,
            tokens,
            allowTokensForCompartment
        );
    }

    function addLenderVault(address addr) external returns (uint256) {
        _checkIsInitialized();
        // catches case where address registry is uninitialized (lenderVaultFactory == address(0))
        if (msg.sender != lenderVaultFactory) {
            revert Errors.InvalidSender();
        }
        isRegisteredVault[addr] = true;
        _registeredVaults.push(addr);
        return _registeredVaults.length;
    }

    function claimBorrowerWhitelistStatus(
        address whitelistAuthority,
        uint256 whitelistedUntil,
        bytes calldata compactSig,
        bytes32 salt
    ) external {
        if (_signatureIsInvalidated[compactSig]) {
            revert Errors.InvalidSignature();
        }
        bytes32 payloadHash = keccak256(
            abi.encode(
                address(this),
                msg.sender,
                whitelistedUntil,
                block.chainid,
                salt
            )
        );
        bytes32 messageHash = ECDSA.toEthSignedMessageHash(payloadHash);
        (bytes32 r, bytes32 vs) = Helpers.splitSignature(compactSig);
        address recoveredSigner = messageHash.recover(r, vs);
        if (
            whitelistAuthority == address(0) ||
            recoveredSigner != whitelistAuthority
        ) {
            revert Errors.InvalidSignature();
        }
        mapping(address => uint256)
            storage whitelistedUntilPerBorrower = _borrowerWhitelistedUntil[
                whitelistAuthority
            ];
        if (
            whitelistedUntil < block.timestamp ||
            whitelistedUntil <= whitelistedUntilPerBorrower[msg.sender]
        ) {
            revert Errors.CannotClaimOutdatedStatus();
        }
        whitelistedUntilPerBorrower[msg.sender] = whitelistedUntil;
        _signatureIsInvalidated[compactSig] = true;
        emit BorrowerWhitelistStatusClaimed(
            whitelistAuthority,
            msg.sender,
            whitelistedUntil
        );
    }

    function createWrappedTokenForERC721s(
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol,
        bytes calldata mysoTokenManagerData
    ) external {
        address _erc721Wrapper = erc721Wrapper;
        if (_erc721Wrapper == address(0)) {
            revert Errors.InvalidAddress();
        }
        if (mysoTokenManager != address(0)) {
            IMysoTokenManager(mysoTokenManager)
                .processP2PCreateWrappedTokenForERC721s(
                    msg.sender,
                    tokensToBeWrapped,
                    mysoTokenManagerData
                );
        }
        address newERC20Addr = IERC721Wrapper(_erc721Wrapper)
            .createWrappedToken(msg.sender, tokensToBeWrapped, name, symbol);
        whitelistState[newERC20Addr] = DataTypesPeerToPeer
            .WhitelistState
            .ERC20_TOKEN;
        emit CreatedWrappedTokenForERC721s(
            tokensToBeWrapped,
            name,
            symbol,
            newERC20Addr
        );
    }

    function createWrappedTokenForERC20s(
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol,
        bytes calldata mysoTokenManagerData
    ) external {
        address _erc20Wrapper = erc20Wrapper;
        if (_erc20Wrapper == address(0)) {
            revert Errors.InvalidAddress();
        }
        if (mysoTokenManager != address(0)) {
            IMysoTokenManager(mysoTokenManager)
                .processP2PCreateWrappedTokenForERC20s(
                    msg.sender,
                    tokensToBeWrapped,
                    mysoTokenManagerData
                );
        }
        address newERC20Addr = IERC20Wrapper(_erc20Wrapper).createWrappedToken(
            msg.sender,
            tokensToBeWrapped,
            name,
            symbol
        );
        whitelistState[newERC20Addr] = DataTypesPeerToPeer
            .WhitelistState
            .ERC20_TOKEN;
        emit CreatedWrappedTokenForERC20s(
            tokensToBeWrapped,
            name,
            symbol,
            newERC20Addr
        );
    }

    function updateBorrowerWhitelist(
        address[] calldata borrowers,
        uint256 whitelistedUntil
    ) external {
        uint256 borrowersLen = borrowers.length;
        if (borrowersLen == 0) {
            revert Errors.InvalidArrayLength();
        }
        for (uint256 i; i < borrowersLen; ) {
            mapping(address => uint256)
                storage whitelistedUntilPerBorrower = _borrowerWhitelistedUntil[
                    msg.sender
                ];
            if (
                borrowers[i] == address(0) ||
                whitelistedUntil == whitelistedUntilPerBorrower[borrowers[i]]
            ) {
                revert Errors.InvalidUpdate();
            }
            whitelistedUntilPerBorrower[borrowers[i]] = whitelistedUntil;
            unchecked {
                ++i;
            }
        }
        emit BorrowerWhitelistUpdated(msg.sender, borrowers, whitelistedUntil);
    }

    function isWhitelistedBorrower(
        address whitelistAuthority,
        address borrower
    ) external view returns (bool) {
        return
            _borrowerWhitelistedUntil[whitelistAuthority][borrower] >=
            block.timestamp;
    }

    function isWhitelistedCompartment(
        address compartment,
        address token
    ) external view returns (bool) {
        return
            whitelistState[compartment] ==
            DataTypesPeerToPeer.WhitelistState.COMPARTMENT &&
            _isTokenWhitelistedForCompartment[compartment][token];
    }

    function registeredVaults() external view returns (address[] memory) {
        return _registeredVaults;
    }

    function numRegisteredVaults() external view returns (uint256) {
        return _registeredVaults.length;
    }

    function transferOwnership(
        address _newOwnerProposal
    ) public override(Ownable2Step, IAddressRegistry) {
        _checkIsInitialized();
        if (
            _newOwnerProposal == address(this) ||
            _newOwnerProposal == pendingOwner() ||
            _newOwnerProposal == owner()
        ) {
            revert Errors.InvalidNewOwnerProposal();
        }
        // @dev: access control check via super.transferOwnership()
        super.transferOwnership(_newOwnerProposal);
    }

    function owner()
        public
        view
        override(Ownable, IAddressRegistry)
        returns (address)
    {
        return super.owner();
    }

    function pendingOwner()
        public
        view
        override(Ownable2Step, IAddressRegistry)
        returns (address)
    {
        return super.pendingOwner();
    }

    function isWhitelistedERC20(address token) public view returns (bool) {
        DataTypesPeerToPeer.WhitelistState tokenWhitelistState = whitelistState[
            token
        ];
        return
            tokenWhitelistState ==
            DataTypesPeerToPeer.WhitelistState.ERC20_TOKEN ||
            tokenWhitelistState ==
            DataTypesPeerToPeer
                .WhitelistState
                .ERC20_TOKEN_REQUIRING_COMPARTMENT;
    }

    function renounceOwnership() public pure override {
        revert Errors.Disabled();
    }

    function _updateSingletonAddr(
        address newAddr,
        DataTypesPeerToPeer.WhitelistState state,
        address _erc721Wrapper,
        address _erc20Wrapper,
        address _mysoTokenManager
    ) internal {
        // check if address already has given state set or
        // other singleton addresses occupy target state
        if (
            whitelistState[newAddr] == state ||
            whitelistState[_erc721Wrapper] == state ||
            whitelistState[_erc20Wrapper] == state ||
            whitelistState[_mysoTokenManager] == state
        ) {
            revert Errors.StateAlreadySet();
        }
        // check if addr was singleton before and delete, if needed
        _checkAddrAndDeleteIfSingleton(
            newAddr,
            _erc721Wrapper,
            _erc20Wrapper,
            _mysoTokenManager
        );
        if (state == DataTypesPeerToPeer.WhitelistState.ERC721WRAPPER) {
            erc721Wrapper = newAddr;
        } else if (state == DataTypesPeerToPeer.WhitelistState.ERC20WRAPPER) {
            erc20Wrapper = newAddr;
        } else {
            mysoTokenManager = newAddr;
        }
    }

    function _checkAddrAndDeleteIfSingleton(
        address addr,
        address _erc721Wrapper,
        address _erc20Wrapper,
        address _mysoTokenManager
    ) internal {
        if (addr == _erc721Wrapper) {
            delete erc721Wrapper;
        } else if (addr == _erc20Wrapper) {
            delete erc20Wrapper;
        } else if (addr == _mysoTokenManager) {
            delete mysoTokenManager;
        }
    }

    function _checkIsInitialized() internal view {
        if (_getInitializedVersion() == 0) {
            revert Errors.Uninitialized();
        }
    }
}

// File: contracts/peer-to-peer/BorrowerGateway.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Constants} from "../Constants.sol";
import {DataTypesPeerToPeer} from "./DataTypesPeerToPeer.sol";
import {Errors} from "../Errors.sol";
import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol";
import {IBaseCompartment} from "./interfaces/compartments/IBaseCompartment.sol";
import {IBorrowerGateway} from "./interfaces/IBorrowerGateway.sol";
import {ILenderVaultImpl} from "./interfaces/ILenderVaultImpl.sol";
import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol";
import {IQuoteHandler} from "./interfaces/IQuoteHandler.sol";
import {IVaultCallback} from "./interfaces/IVaultCallback.sol";

contract BorrowerGateway is ReentrancyGuard, IBorrowerGateway {
    using SafeERC20 for IERC20Metadata;

    // putting fee info in borrow gateway since borrower always pays this upfront
    address public immutable addressRegistry;
    // index 0: base protocol fee is paid even for swap (no tenor)
    // index 1: protocol fee slope scales protocol fee with tenor
    uint128[2] internal protocolFeeParams;

    constructor(address _addressRegistry) {
        if (_addressRegistry == address(0)) {
            revert Errors.InvalidAddress();
        }
        addressRegistry = _addressRegistry;
    }

    function borrowWithOffChainQuote(
        address lenderVault,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.OffChainQuote calldata offChainQuote,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple,
        bytes32[] calldata proof
    ) external nonReentrant returns (DataTypesPeerToPeer.Loan memory) {
        _checkDeadlineAndRegisteredVault(
            borrowInstructions.deadline,
            lenderVault
        );
        {
            address quoteHandler = IAddressRegistry(addressRegistry)
                .quoteHandler();
            IQuoteHandler(quoteHandler).checkAndRegisterOffChainQuote(
                msg.sender,
                lenderVault,
                offChainQuote,
                quoteTuple,
                proof
            );
        }

        (
            DataTypesPeerToPeer.Loan memory loan,
            uint256 loanId,
            uint256 upfrontFee
        ) = _processBorrowTransaction(
                borrowInstructions,
                offChainQuote.generalQuoteInfo,
                quoteTuple,
                lenderVault
            );

        emit Borrowed(
            lenderVault,
            loan.borrower,
            loan,
            upfrontFee,
            loanId,
            borrowInstructions.callbackAddr,
            borrowInstructions.callbackData
        );
        return loan;
    }

    function borrowWithOnChainQuote(
        address lenderVault,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.OnChainQuote calldata onChainQuote,
        uint256 quoteTupleIdx
    ) external nonReentrant returns (DataTypesPeerToPeer.Loan memory) {
        // borrow gateway just forwards data to respective vault and orchestrates transfers
        // borrow gateway is oblivious towards and specific borrow details, and only fwds info
        // vaults needs to check details of given quote and whether it's valid
        // all lenderVaults need to approve BorrowGateway

        // 1. BorrowGateway "optimistically" pulls loanToken from lender vault: either transfers directly to (a) borrower or (b) callbacker for further processing
        // 2. BorrowGateway then pulls collToken from borrower to lender vault
        // 3. Finally, BorrowGateway updates lender vault storage state

        _checkDeadlineAndRegisteredVault(
            borrowInstructions.deadline,
            lenderVault
        );
        {
            address quoteHandler = IAddressRegistry(addressRegistry)
                .quoteHandler();
            IQuoteHandler(quoteHandler).checkAndRegisterOnChainQuote(
                msg.sender,
                lenderVault,
                quoteTupleIdx,
                onChainQuote
            );
        }
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple = onChainQuote
            .quoteTuples[quoteTupleIdx];

        (
            DataTypesPeerToPeer.Loan memory loan,
            uint256 loanId,
            uint256 upfrontFee
        ) = _processBorrowTransaction(
                borrowInstructions,
                onChainQuote.generalQuoteInfo,
                quoteTuple,
                lenderVault
            );

        emit Borrowed(
            lenderVault,
            loan.borrower,
            loan,
            upfrontFee,
            loanId,
            borrowInstructions.callbackAddr,
            borrowInstructions.callbackData
        );
        return loan;
    }

    function repay(
        DataTypesPeerToPeer.LoanRepayInstructions
            calldata loanRepayInstructions,
        address vaultAddr
    ) external nonReentrant {
        _checkDeadlineAndRegisteredVault(
            loanRepayInstructions.deadline,
            vaultAddr
        );
        if (
            loanRepayInstructions.callbackAddr != address(0) &&
            IAddressRegistry(addressRegistry).whitelistState(
                loanRepayInstructions.callbackAddr
            ) !=
            DataTypesPeerToPeer.WhitelistState.CALLBACK
        ) {
            revert Errors.NonWhitelistedCallback();
        }
        ILenderVaultImpl lenderVault = ILenderVaultImpl(vaultAddr);
        DataTypesPeerToPeer.Loan memory loan = lenderVault.loan(
            loanRepayInstructions.targetLoanId
        );
        if (msg.sender != loan.borrower) {
            revert Errors.InvalidBorrower();
        }
        if (
            block.timestamp < loan.earliestRepay ||
            block.timestamp >= loan.expiry
        ) {
            revert Errors.OutsideValidRepayWindow();
        }
        // checks repayAmount <= remaining loan balance
        if (
            loanRepayInstructions.targetRepayAmount == 0 ||
            loanRepayInstructions.targetRepayAmount + loan.amountRepaidSoFar >
            loan.initRepayAmount
        ) {
            revert Errors.InvalidRepayAmount();
        }
        bool noCompartment = loan.collTokenCompartmentAddr == address(0);
        // @dev: amountReclaimedSoFar cannot exceed initCollAmount for non-compartmentalized assets
        uint256 maxReclaimableCollAmount = noCompartment
            ? loan.initCollAmount - loan.amountReclaimedSoFar
            : IBaseCompartment(loan.collTokenCompartmentAddr)
                .getReclaimableBalance(loan.collToken);

        // @dev: amountRepaidSoFar cannot exceed initRepayAmount
        uint128 leftRepaymentAmount = loan.initRepayAmount -
            loan.amountRepaidSoFar;
        uint128 reclaimCollAmount = SafeCast.toUint128(
            (maxReclaimableCollAmount *
                uint256(loanRepayInstructions.targetRepayAmount)) /
                uint256(leftRepaymentAmount)
        );
        if (reclaimCollAmount == 0) {
            revert Errors.ReclaimAmountIsZero();
        }

        lenderVault.updateLoanInfo(
            loanRepayInstructions.targetRepayAmount,
            loanRepayInstructions.targetLoanId,
            reclaimCollAmount,
            noCompartment,
            loan.collToken
        );

        _processRepayTransfers(
            vaultAddr,
            loanRepayInstructions,
            loan,
            leftRepaymentAmount,
            reclaimCollAmount,
            noCompartment
        );

        emit Repaid(
            vaultAddr,
            loanRepayInstructions.targetLoanId,
            loanRepayInstructions.targetRepayAmount
        );
    }

    /**
     * @notice Protocol fee is allowed to be zero, so no min fee checks, only max fee checks
     */
    function setProtocolFeeParams(uint128[2] calldata _newFeeParams) external {
        if (msg.sender != IAddressRegistry(addressRegistry).owner()) {
            revert Errors.InvalidSender();
        }
        if (
            _newFeeParams[0] > Constants.MAX_SWAP_PROTOCOL_FEE ||
            _newFeeParams[1] > Constants.MAX_FEE_PER_ANNUM ||
            (_newFeeParams[0] == protocolFeeParams[0] &&
                _newFeeParams[1] == protocolFeeParams[1])
        ) {
            revert Errors.InvalidFee();
        }
        protocolFeeParams = _newFeeParams;
        emit ProtocolFeeSet(_newFeeParams);
    }

    function getProtocolFeeParams() external view returns (uint128[2] memory) {
        return protocolFeeParams;
    }

    function _processBorrowTransaction(
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple,
        address lenderVault
    ) internal returns (DataTypesPeerToPeer.Loan memory, uint256, uint256) {
        (
            DataTypesPeerToPeer.Loan memory loan,
            uint256 loanId,
            DataTypesPeerToPeer.TransferInstructions memory transferInstructions
        ) = ILenderVaultImpl(lenderVault).processQuote(
                msg.sender,
                borrowInstructions,
                generalQuoteInfo,
                quoteTuple
            );

        _processTransfers(
            lenderVault,
            borrowInstructions,
            loan,
            transferInstructions
        );
        return (loan, loanId, transferInstructions.upfrontFee);
    }

    // solhint-disable code-complexity
    function _processTransfers(
        address lenderVault,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.Loan memory loan,
        DataTypesPeerToPeer.TransferInstructions memory transferInstructions
    ) internal {
        if (
            borrowInstructions.callbackAddr != address(0) &&
            IAddressRegistry(addressRegistry).whitelistState(
                borrowInstructions.callbackAddr
            ) !=
            DataTypesPeerToPeer.WhitelistState.CALLBACK
        ) {
            revert Errors.NonWhitelistedCallback();
        }
        ILenderVaultImpl(lenderVault).transferTo(
            loan.loanToken,
            borrowInstructions.callbackAddr == address(0)
                ? loan.borrower
                : borrowInstructions.callbackAddr,
            loan.initLoanAmount
        );
        if (borrowInstructions.callbackAddr != address(0)) {
            IVaultCallback(borrowInstructions.callbackAddr).borrowCallback(
                loan,
                borrowInstructions.callbackData
            );
        }

        uint128[2] memory currProtocolFeeParams = protocolFeeParams;
        uint128[2] memory applicableProtocolFeeParams = currProtocolFeeParams;

        address mysoTokenManager = IAddressRegistry(addressRegistry)
            .mysoTokenManager();
        if (mysoTokenManager != address(0)) {
            applicableProtocolFeeParams = IMysoTokenManager(mysoTokenManager)
                .processP2PBorrow(
                    applicableProtocolFeeParams,
                    borrowInstructions,
                    loan,
                    lenderVault
                );
            for (uint256 i; i < 2; ) {
                if (applicableProtocolFeeParams[i] > currProtocolFeeParams[i]) {
                    revert Errors.InvalidFee();
                }
                unchecked {
                    ++i;
                }
            }
        }

        // Note: Collateral and fees flow and breakdown is as follows:
        //
        // collSendAmount ("collSendAmount")
        // |
        // |-- protocolFeeAmount ("protocolFeeAmount")
        // |
        // |-- gross pledge amount
        //     |
        //     |-- gross upfront fee
        //     |   |
        //     |   |-- net upfront fee ("upfrontFee")
        //     |   |
        //     |   |-- transfer fee 1
        //     |
        //     |-- gross reclaimable collateral
        //         |
        //         |-- net reclaimable collateral ("initCollAmount")
        //         |
        //         |-- transfer fee 2 ("expectedCompartmentTransferFee")
        //
        // where expectedProtocolAndVaultTransferFee = protocolFeeAmount + transfer fee 1

        uint256 protocolFeeAmount = _calculateProtocolFeeAmount(
            applicableProtocolFeeParams,
            borrowInstructions.collSendAmount,
            loan.initCollAmount == 0 ? 0 : loan.expiry - block.timestamp
        );

        // check protocolFeeAmount <= expectedProtocolAndVaultTransferFee
        if (
            protocolFeeAmount >
            borrowInstructions.expectedProtocolAndVaultTransferFee
        ) {
            revert Errors.InsufficientSendAmount();
        }

        if (protocolFeeAmount != 0) {
            // note: if coll token has a transfer fee, then protocolFeeAmount received by the protocol will be less than
            // protocolFeeAmount; this is by design to not tax borrowers or lenders for transfer fees on protocol fees
            IERC20Metadata(loan.collToken).safeTransferFrom(
                loan.borrower,
                IAddressRegistry(addressRegistry).owner(),
                protocolFeeAmount
            );
        }
        // determine any transfer fee for sending collateral to vault
        uint256 collTransferFeeForSendingToVault = borrowInstructions
            .expectedProtocolAndVaultTransferFee - protocolFeeAmount;
        // Note: initialize the coll amount that is sent to vault in case there's no compartment
        uint256 grossCollTransferAmountToVault = loan.initCollAmount +
            transferInstructions.upfrontFee +
            collTransferFeeForSendingToVault;
        // Note: initialize the vault's expected coll balance increase in case there's no compartment
        uint256 expVaultCollBalIncrease = loan.initCollAmount +
            transferInstructions.upfrontFee;
        if (transferInstructions.collReceiver != lenderVault) {
            // Note: if there's a compartment then adjust the coll amount that is sent to vault by deducting the amount
            // that goes to the compartment, i.e., the borrower's reclaimable coll amount and any associated transfer fees
            grossCollTransferAmountToVault -= loan.initCollAmount;
            // Note: similarly, adjust the vault's expected coll balance diff by deducting the reclaimable coll amount that
            // goes to the compartment
            expVaultCollBalIncrease -= loan.initCollAmount;

            uint256 collReceiverPreBal = IERC20Metadata(loan.collToken)
                .balanceOf(transferInstructions.collReceiver);
            IERC20Metadata(loan.collToken).safeTransferFrom(
                loan.borrower,
                transferInstructions.collReceiver,
                loan.initCollAmount +
                    borrowInstructions.expectedCompartmentTransferFee
            );
            // check that compartment balance increase matches the intended reclaimable collateral amount
            if (
                IERC20Metadata(loan.collToken).balanceOf(
                    transferInstructions.collReceiver
                ) != loan.initCollAmount + collReceiverPreBal
            ) {
                revert Errors.InvalidSendAmount();
            }
        }

        if (grossCollTransferAmountToVault > 0) {
            // @dev: grossCollTransferAmountToVault can be zero in case no upfront fee and compartment is used
            if (expVaultCollBalIncrease == 0) {
                revert Errors.InconsistentExpVaultBalIncrease();
            }
            uint256 vaultPreBal = IERC20Metadata(loan.collToken).balanceOf(
                lenderVault
            );
            IERC20Metadata(loan.collToken).safeTransferFrom(
                loan.borrower,
                lenderVault,
                grossCollTransferAmountToVault
            );
            if (
                IERC20Metadata(loan.collToken).balanceOf(lenderVault) !=
                vaultPreBal + expVaultCollBalIncrease
            ) {
                revert Errors.InvalidSendAmount();
            }
        }
    }

    function _processRepayTransfers(
        address lenderVault,
        DataTypesPeerToPeer.LoanRepayInstructions memory loanRepayInstructions,
        DataTypesPeerToPeer.Loan memory loan,
        uint128 leftRepaymentAmount,
        uint128 reclaimCollAmount,
        bool noCompartment
    ) internal {
        noCompartment
            ? ILenderVaultImpl(lenderVault).transferTo(
                loan.collToken,
                loanRepayInstructions.callbackAddr == address(0)
                    ? loan.borrower
                    : loanRepayInstructions.callbackAddr,
                reclaimCollAmount
            )
            : ILenderVaultImpl(lenderVault).transferCollFromCompartment(
                loanRepayInstructions.targetRepayAmount,
                leftRepaymentAmount,
                reclaimCollAmount,
                loan.borrower,
                loan.collToken,
                loanRepayInstructions.callbackAddr,
                loan.collTokenCompartmentAddr
            );
        if (loanRepayInstructions.callbackAddr != address(0)) {
            IVaultCallback(loanRepayInstructions.callbackAddr).repayCallback(
                loan,
                loanRepayInstructions.callbackData
            );
        }
        uint256 loanTokenReceived = IERC20Metadata(loan.loanToken).balanceOf(
            lenderVault
        );

        IERC20Metadata(loan.loanToken).safeTransferFrom(
            loan.borrower,
            lenderVault,
            loanRepayInstructions.targetRepayAmount +
                loanRepayInstructions.expectedTransferFee
        );

        loanTokenReceived =
            IERC20Metadata(loan.loanToken).balanceOf(lenderVault) -
            loanTokenReceived;
        if (loanTokenReceived != loanRepayInstructions.targetRepayAmount) {
            revert Errors.InvalidSendAmount();
        }
    }

    function _checkDeadlineAndRegisteredVault(
        uint256 deadline,
        address lenderVault
    ) internal view {
        if (block.timestamp > deadline) {
            revert Errors.DeadlinePassed();
        }
        if (!IAddressRegistry(addressRegistry).isRegisteredVault(lenderVault)) {
            revert Errors.UnregisteredVault();
        }
    }

    function _calculateProtocolFeeAmount(
        uint128[2] memory _protocolFeeParams,
        uint256 collSendAmount,
        uint256 borrowDuration
    ) internal pure returns (uint256 protocolFeeAmount) {
        bool useMaxProtocolFee = _protocolFeeParams[0] +
            ((_protocolFeeParams[1] * borrowDuration) /
                Constants.YEAR_IN_SECONDS) >
            Constants.MAX_TOTAL_PROTOCOL_FEE;
        protocolFeeAmount = useMaxProtocolFee
            ? (collSendAmount * Constants.MAX_TOTAL_PROTOCOL_FEE) /
                Constants.BASE
            : ((_protocolFeeParams[0] * collSendAmount) / Constants.BASE) +
                ((collSendAmount * _protocolFeeParams[1] * borrowDuration) /
                    (Constants.YEAR_IN_SECONDS * Constants.BASE));
    }
}

// File: contracts/peer-to-peer/callbacks/BalancerV2Looping.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20Metadata, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {BalancerDataTypes} from "../interfaces/callbacks/BalancerDataTypes.sol";
import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol";
import {VaultCallback} from "./VaultCallback.sol";
import {IBalancerAsset} from "../interfaces/callbacks/IBalancerAsset.sol";
import {IBalancerVault} from "../interfaces/callbacks/IBalancerVault.sol";
import {IVaultCallback} from "../interfaces/IVaultCallback.sol";

contract BalancerV2Looping is VaultCallback {
    using SafeERC20 for IERC20Metadata;

    address private constant BALANCER_V2_VAULT =
        0xBA12222222228d8Ba445958a75a0704d566BF2C8;

    constructor(address _borrowerGateway) VaultCallback(_borrowerGateway) {} // solhint-disable no-empty-blocks

    function borrowCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) external {
        BalancerDataTypes.FundManagement
            memory fundManagement = BalancerDataTypes.FundManagement({
                sender: address(this), // swap payer
                fromInternalBalance: false, // use payer's internal balance
                recipient: payable(loan.borrower), // swap receiver
                toInternalBalance: false // user receiver's internal balance
            });
        (bytes32 poolId, uint256 minSwapReceive, uint256 deadline) = abi.decode(
            data,
            (bytes32, uint256, uint256)
        );
        // swap whole loan token balance received from borrower gateway
        uint256 loanTokenBalance = IERC20(loan.loanToken).balanceOf(
            address(this)
        );
        IERC20Metadata(loan.loanToken).safeIncreaseAllowance(
            BALANCER_V2_VAULT,
            loanTokenBalance
        );
        BalancerDataTypes.SingleSwap memory singleSwap = BalancerDataTypes
            .SingleSwap({
                poolId: poolId,
                kind: BalancerDataTypes.SwapKind.GIVEN_IN,
                assetIn: IBalancerAsset(loan.loanToken),
                assetOut: IBalancerAsset(loan.collToken),
                amount: loanTokenBalance,
                userData: ""
            });
        IBalancerVault(BALANCER_V2_VAULT).swap(
            singleSwap,
            fundManagement,
            minSwapReceive,
            deadline
        );
        IERC20Metadata(loan.loanToken).safeDecreaseAllowance(
            BALANCER_V2_VAULT,
            IERC20Metadata(loan.loanToken).allowance(
                address(this),
                BALANCER_V2_VAULT
            )
        );
    }

    function _repayCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) internal override {
        BalancerDataTypes.FundManagement
            memory fundManagement = BalancerDataTypes.FundManagement({
                sender: address(this), // swap payer
                fromInternalBalance: false, // use payer's internal balance
                recipient: payable(loan.borrower), // swap receiver
                toInternalBalance: false // user receiver's internal balance
            });
        (bytes32 poolId, uint256 minSwapReceive, uint256 deadline) = abi.decode(
            data,
            (bytes32, uint256, uint256)
        );
        // swap whole coll token balance received from borrower gateway
        uint256 collBalance = IERC20(loan.collToken).balanceOf(address(this));
        BalancerDataTypes.SingleSwap memory singleSwap = BalancerDataTypes
            .SingleSwap({
                poolId: poolId,
                kind: BalancerDataTypes.SwapKind.GIVEN_IN,
                assetIn: IBalancerAsset(loan.collToken),
                assetOut: IBalancerAsset(loan.loanToken),
                amount: collBalance,
                userData: ""
            });
        IERC20Metadata(loan.collToken).safeIncreaseAllowance(
            BALANCER_V2_VAULT,
            collBalance
        );
        IBalancerVault(BALANCER_V2_VAULT).swap(
            singleSwap,
            fundManagement,
            minSwapReceive,
            deadline
        );
        IERC20Metadata(loan.collToken).safeDecreaseAllowance(
            BALANCER_V2_VAULT,
            IERC20Metadata(loan.collToken).allowance(
                address(this),
                BALANCER_V2_VAULT
            )
        );
    }
}

// File: contracts/peer-to-peer/callbacks/UniV3Looping.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20Metadata, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol";
import {VaultCallback} from "./VaultCallback.sol";
import {ISwapRouter} from "../interfaces/callbacks/ISwapRouter.sol";
import {IVaultCallback} from "../interfaces/IVaultCallback.sol";

contract UniV3Looping is VaultCallback {
    using SafeERC20 for IERC20Metadata;

    address private constant UNI_V3_SWAP_ROUTER =
        0xE592427A0AEce92De3Edee1F18E0157C05861564;

    constructor(address _borrowerGateway) VaultCallback(_borrowerGateway) {} // solhint-disable no-empty-blocks

    function borrowCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) external {
        (uint256 minSwapReceive, uint256 deadline, uint24 poolFee) = abi.decode(
            data,
            (uint256, uint256, uint24)
        );
        // swap whole loan token balance received from borrower gateway
        uint256 loanTokenBalance = IERC20(loan.loanToken).balanceOf(
            address(this)
        );
        IERC20Metadata(loan.loanToken).safeIncreaseAllowance(
            UNI_V3_SWAP_ROUTER,
            loanTokenBalance
        );
        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
            .ExactInputSingleParams({
                tokenIn: loan.loanToken,
                tokenOut: loan.collToken,
                fee: poolFee,
                recipient: loan.borrower,
                deadline: deadline,
                amountIn: loanTokenBalance,
                amountOutMinimum: minSwapReceive,
                sqrtPriceLimitX96: 0
            });
        ISwapRouter(UNI_V3_SWAP_ROUTER).exactInputSingle(params);
        IERC20Metadata(loan.loanToken).safeDecreaseAllowance(
            UNI_V3_SWAP_ROUTER,
            IERC20Metadata(loan.loanToken).allowance(
                address(this),
                UNI_V3_SWAP_ROUTER
            )
        );
    }

    function _repayCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) internal override {
        (uint256 minSwapReceive, uint256 deadline, uint24 poolFee) = abi.decode(
            data,
            (uint256, uint256, uint24)
        );
        // swap whole coll token balance received from borrower gateway
        uint256 collTokenBalance = IERC20(loan.collToken).balanceOf(
            address(this)
        );
        IERC20Metadata(loan.collToken).safeIncreaseAllowance(
            UNI_V3_SWAP_ROUTER,
            collTokenBalance
        );
        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
            .ExactInputSingleParams({
                tokenIn: loan.collToken,
                tokenOut: loan.loanToken,
                fee: poolFee,
                recipient: loan.borrower,
                deadline: deadline,
                amountIn: collTokenBalance,
                amountOutMinimum: minSwapReceive,
                sqrtPriceLimitX96: 0
            });

        ISwapRouter(UNI_V3_SWAP_ROUTER).exactInputSingle(params);
        IERC20Metadata(loan.collToken).safeDecreaseAllowance(
            UNI_V3_SWAP_ROUTER,
            IERC20Metadata(loan.collToken).allowance(
                address(this),
                UNI_V3_SWAP_ROUTER
            )
        );
    }
}

// File: contracts/peer-to-peer/callbacks/VaultCallback.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol";
import {Errors} from "../../Errors.sol";
import {IVaultCallback} from "../interfaces/IVaultCallback.sol";

abstract contract VaultCallback is IVaultCallback {
    address public immutable borrowerGateway;

    constructor(address _borrowerGateway) {
        if (_borrowerGateway == address(0)) {
            revert Errors.InvalidAddress();
        }
        borrowerGateway = _borrowerGateway;
    }

    function repayCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) external {
        if (msg.sender != borrowerGateway) {
            revert Errors.InvalidSender();
        }
        _repayCallback(loan, data);
    }

    function _repayCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) internal virtual {} // solhint-disable no-empty-blocks
}

// File: contracts/peer-to-peer/compartments/BaseCompartment.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IBaseCompartment} from "../interfaces/compartments/IBaseCompartment.sol";
import {ILenderVaultImpl} from "../interfaces/ILenderVaultImpl.sol";
import {Errors} from "../../Errors.sol";

abstract contract BaseCompartment is Initializable, IBaseCompartment {
    using SafeERC20 for IERC20;

    address public vaultAddr;
    uint256 public loanIdx;

    constructor() {
        _disableInitializers();
    }

    function initialize(
        address _vaultAddr,
        uint256 _loanIdx
    ) external initializer {
        if (_vaultAddr == address(0)) {
            revert Errors.InvalidAddress();
        }
        vaultAddr = _vaultAddr;
        loanIdx = _loanIdx;
    }

    // transfer coll on repays
    function _transferCollFromCompartment(
        uint128 reclaimCollAmount,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr
    ) internal {
        _withdrawCheck();
        if (msg.sender != vaultAddr) revert Errors.InvalidSender();
        address collReceiver = callbackAddr == address(0)
            ? borrowerAddr
            : callbackAddr;
        IERC20(collTokenAddr).safeTransfer(collReceiver, reclaimCollAmount);
    }

    function _unlockCollToVault(address collTokenAddr) internal {
        _withdrawCheck();
        if (msg.sender != vaultAddr) revert Errors.InvalidSender();
        uint256 currentCollBalance = IERC20(collTokenAddr).balanceOf(
            address(this)
        );
        IERC20(collTokenAddr).safeTransfer(msg.sender, currentCollBalance);
    }

    function _withdrawCheck() internal view {
        bool withdrawEntered = ILenderVaultImpl(vaultAddr).withdrawEntered();
        if (withdrawEntered) {
            revert Errors.WithdrawEntered();
        }
    }
}

// File: contracts/peer-to-peer/compartments/staking/AaveStakingCompartment.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {BaseCompartment} from "../BaseCompartment.sol";

contract AaveStakingCompartment is BaseCompartment {
    using SafeERC20 for IERC20;

    // transfer coll on repays
    function transferCollFromCompartment(
        uint256 /*repayAmount*/,
        uint256 /*repayAmountLeft*/,
        uint128 reclaimCollAmount,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr
    ) external {
        _transferCollFromCompartment(
            reclaimCollAmount,
            borrowerAddr,
            collTokenAddr,
            callbackAddr
        );
    }

    // unlockColl this would be called on defaults
    function unlockCollToVault(address collTokenAddr) external {
        _unlockCollToVault(collTokenAddr);
    }

    function getReclaimableBalance(
        address collToken
    ) external view override returns (uint256) {
        return IERC20(collToken).balanceOf(address(this));
    }
}

// File: contracts/peer-to-peer/compartments/staking/CurveLPStakingCompartment.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ICurveStakingHelper} from "../../interfaces/compartments/staking/ICurveStakingHelper.sol";
import {ILenderVaultImpl} from "../../interfaces/ILenderVaultImpl.sol";
import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol";
import {BaseCompartment} from "../BaseCompartment.sol";
import {Errors} from "../../../Errors.sol";

contract CurveLPStakingCompartment is BaseCompartment {
    using SafeERC20 for IERC20;

    address public liqGaugeAddr;

    address internal constant CRV_ADDR =
        0xD533a949740bb3306d119CC777fa900bA034cd52;
    address internal constant GAUGE_CONTROLLER =
        0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB;
    address internal constant CRV_MINTER_ADDR =
        0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;

    mapping(address => bool) public approvedStaker;

    function stake(uint256 gaugeIndex) external {
        DataTypesPeerToPeer.Loan memory loan = ILenderVaultImpl(vaultAddr).loan(
            loanIdx
        );
        if (msg.sender != loan.borrower && !approvedStaker[msg.sender]) {
            revert Errors.InvalidSender();
        }
        if (block.timestamp >= loan.expiry) {
            revert Errors.LoanExpired();
        }
        if (liqGaugeAddr != address(0)) {
            revert Errors.AlreadyStaked();
        }

        uint256 amount = IERC20(loan.collToken).balanceOf(address(this));

        address _liqGaugeAddr = ICurveStakingHelper(GAUGE_CONTROLLER).gauges(
            gaugeIndex
        );

        if (_liqGaugeAddr == address(0)) {
            revert Errors.InvalidGaugeIndex();
        }

        address lpTokenAddrForGauge = ICurveStakingHelper(_liqGaugeAddr)
            .lp_token();
        if (lpTokenAddrForGauge != loan.collToken) {
            revert Errors.IncorrectGaugeForLpToken();
        }
        liqGaugeAddr = _liqGaugeAddr;
        IERC20(loan.collToken).safeIncreaseAllowance(_liqGaugeAddr, amount);
        ICurveStakingHelper(_liqGaugeAddr).deposit(amount);
        IERC20(loan.collToken).safeDecreaseAllowance(
            _liqGaugeAddr,
            IERC20(loan.collToken).allowance(address(this), _liqGaugeAddr)
        );
        emit Staked(gaugeIndex, _liqGaugeAddr, amount);
    }

    function toggleApprovedStaker(address _staker) external {
        DataTypesPeerToPeer.Loan memory loan = ILenderVaultImpl(vaultAddr).loan(
            loanIdx
        );
        if (msg.sender != loan.borrower) {
            revert Errors.InvalidSender();
        }
        bool currStakingState = approvedStaker[_staker];
        approvedStaker[_staker] = !currStakingState;
        emit UpdatedApprovedStaker(_staker, !currStakingState);
    }

    // transfer coll on repays
    function transferCollFromCompartment(
        uint256 repayAmount,
        uint256 repayAmountLeft,
        uint128 /*reclaimCollAmount*/,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr
    ) external {
        _collAccountingHelper(
            repayAmount,
            repayAmountLeft,
            0,
            borrowerAddr,
            collTokenAddr,
            callbackAddr,
            false
        );
    }

    // unlockColl this would be called on defaults
    function unlockCollToVault(address collTokenAddr) external {
        _collAccountingHelper(
            1,
            1,
            0,
            address(0),
            collTokenAddr,
            address(0),
            true
        );
    }

    function getReclaimableBalance(
        address collToken
    ) external view override returns (uint256 reclaimableCollBalance) {
        reclaimableCollBalance = IERC20(collToken).balanceOf(address(this));
        address _liqGaugeAddr = liqGaugeAddr;
        if (_liqGaugeAddr != address(0)) {
            reclaimableCollBalance += IERC20(_liqGaugeAddr).balanceOf(
                address(this)
            );
        }
    }

    function _getRewardTokensAndWithdrawFromGauge(
        address _liqGaugeAddr,
        uint256 repayAmount,
        uint256 repayAmountLeft
    ) internal returns (address[8] memory _rewardTokenAddr) {
        uint256 currentStakedBal = IERC20(_liqGaugeAddr).balanceOf(
            address(this)
        );
        // withdraw proportion of gauge amount
        uint256 withdrawAmount = Math.mulDiv(
            repayAmount,
            currentStakedBal,
            repayAmountLeft
        );
        ICurveStakingHelper(CRV_MINTER_ADDR).mint(_liqGaugeAddr);
        try ICurveStakingHelper(_liqGaugeAddr).reward_tokens(0) returns (
            address rewardTokenAddrZeroIndex
        ) {
            // versions 2, 3, 4, or 5
            _rewardTokenAddr[0] = rewardTokenAddrZeroIndex;
            address rewardTokenAddr;
            for (uint256 i; i < 7; ) {
                rewardTokenAddr = ICurveStakingHelper(_liqGaugeAddr)
                    .reward_tokens(i + 1);
                if (rewardTokenAddr != address(0)) {
                    _rewardTokenAddr[i + 1] = rewardTokenAddr;
                } else {
                    break;
                }
                unchecked {
                    ++i;
                }
            }
            try
                ICurveStakingHelper(_liqGaugeAddr).withdraw(
                    withdrawAmount,
                    true
                )
            // solhint-disable no-empty-blocks
            {
                // version 3, 4, or 5 gauge
            } catch {
                // version 2 gauge
                if (_rewardTokenAddr[0] != address(0)) {
                    ICurveStakingHelper(_liqGaugeAddr).claim_rewards();
                }
                ICurveStakingHelper(_liqGaugeAddr).withdraw(withdrawAmount);
            }
        } catch {
            // version 1 gauge
            ICurveStakingHelper(_liqGaugeAddr).withdraw(withdrawAmount);
        }
    }

    function _collAccountingHelper(
        uint256 repayAmount,
        uint256 repayAmountLeft,
        uint128 /*reclaimableCollBalance*/,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr,
        bool isUnlock
    ) internal returns (uint128 lpTokenAmount) {
        _withdrawCheck();
        if (msg.sender != vaultAddr) revert Errors.InvalidSender();

        address _liqGaugeAddr = liqGaugeAddr;

        // if gaugeAddr has been set, withdraw from gauge and get reward token addresses
        address[8] memory _rewardTokenAddr;
        if (_liqGaugeAddr != address(0)) {
            _rewardTokenAddr = _getRewardTokensAndWithdrawFromGauge(
                _liqGaugeAddr,
                repayAmount,
                repayAmountLeft
            );
        }

        // now check lp token balance of compartment which will be portion unstaked (could have never been staked)
        uint256 currentCompartmentBal = IERC20(collTokenAddr).balanceOf(
            address(this)
        );

        // transfer proportion of compartment lp token balance if never staked or an unlock, else all balance if staked
        lpTokenAmount = SafeCast.toUint128(
            isUnlock || _liqGaugeAddr != address(0)
                ? currentCompartmentBal
                : Math.mulDiv(
                    repayAmount,
                    currentCompartmentBal,
                    repayAmountLeft
                )
        );

        // if unlock, send to vault (msg.sender), else if callback send directly there, else to borrower
        address lpTokenReceiver = isUnlock
            ? msg.sender
            : (callbackAddr == address(0) ? borrowerAddr : callbackAddr);

        IERC20(collTokenAddr).safeTransfer(lpTokenReceiver, lpTokenAmount);

        if (_liqGaugeAddr != address(0)) {
            _transferRewards(
                isUnlock,
                borrowerAddr,
                repayAmount,
                repayAmountLeft,
                collTokenAddr,
                _rewardTokenAddr
            );
        }
    }

    function _transferRewards(
        bool isUnlock,
        address borrowerAddr,
        uint256 repayAmount,
        uint256 repayAmountLeft,
        address collTokenAddr,
        address[8] memory _rewardTokenAddr
    ) internal {
        // rest of rewards are always sent to borrower, not for callback
        // if unlock then sent to vaultAddr (msg.sender)
        address rewardReceiver = isUnlock ? msg.sender : borrowerAddr;
        // check crv token balance
        uint256 currentCrvBal = IERC20(CRV_ADDR).balanceOf(address(this));
        // transfer proportion of crv token balance
        uint256 tokenAmount = isUnlock
            ? currentCrvBal
            : Math.mulDiv(repayAmount, currentCrvBal, repayAmountLeft);

        // only perform crv transfer if
        // 1) crv token amount > 0 and coll token is not CRV else skip
        // if unlock, still ok to skip since then all balance would have been
        // transferred to vault earlier in this _getRewardTokensAndWithdrawFromGauge function
        // note: this should never actually happen since crv
        // and this compartment should not be whitelisted, but just in case
        if (tokenAmount > 0 && CRV_ADDR != collTokenAddr) {
            IERC20(CRV_ADDR).safeTransfer(rewardReceiver, tokenAmount);
        }

        uint256 i;
        uint256 currentRewardTokenBal;
        while (i < 8 && _rewardTokenAddr[i] != address(0)) {
            // skip invalid reward tokens
            if (_checkIfValidRewardToken(collTokenAddr, i, _rewardTokenAddr)) {
                currentRewardTokenBal = IERC20(_rewardTokenAddr[i]).balanceOf(
                    address(this)
                );

                tokenAmount = isUnlock
                    ? currentRewardTokenBal
                    : Math.mulDiv(
                        repayAmount,
                        currentRewardTokenBal,
                        repayAmountLeft
                    );

                if (tokenAmount > 0) {
                    IERC20(_rewardTokenAddr[i]).safeTransfer(
                        rewardReceiver,
                        tokenAmount
                    );
                }
            }
            unchecked {
                ++i;
            }
        }
    }

    function _checkIfValidRewardToken(
        address collTokenAddr,
        uint256 index,
        address[8] memory rewardTokens
    ) internal pure returns (bool) {
        // invalid reward if it is equal to collateral or crv token
        if (
            rewardTokens[index] == collTokenAddr ||
            rewardTokens[index] == CRV_ADDR
        ) {
            return false;
        }
        // check if reward token is a duplicate in previous entries
        if (index > 0) {
            for (uint256 i; i < index; ) {
                if (rewardTokens[i] == rewardTokens[index]) {
                    return false;
                }
                unchecked {
                    ++i;
                }
            }
        }
        return true;
    }
}

// File: contracts/peer-to-peer/compartments/staking/GLPStakingCompartment.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IGLPStakingHelper} from "../../interfaces/compartments/staking/IGLPStakingHelper.sol";
import {BaseCompartment} from "../BaseCompartment.sol";

contract GLPStakingCompartment is BaseCompartment {
    using SafeERC20 for IERC20;

    // arbitrum WETH address
    address private constant WETH = 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1;
    address private constant FEE_GLP =
        0x4e971a87900b931fF39d1Aad67697F49835400b6;

    // transfer coll on repays
    function transferCollFromCompartment(
        uint256 repayAmount,
        uint256 repayAmountLeft,
        uint128 reclaimCollAmount,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr
    ) external {
        _transferCollFromCompartment(
            reclaimCollAmount,
            borrowerAddr,
            collTokenAddr,
            callbackAddr
        );

        _transferRewards(
            collTokenAddr,
            borrowerAddr,
            repayAmount,
            repayAmountLeft,
            false
        );
    }

    // unlockColl this would be called on defaults
    function unlockCollToVault(address collTokenAddr) external {
        _unlockCollToVault(collTokenAddr);
        _transferRewards(collTokenAddr, vaultAddr, 0, 0, true);
    }

    function getReclaimableBalance(
        address collToken
    ) external view override returns (uint256) {
        return IERC20(collToken).balanceOf(address(this));
    }

    function _transferRewards(
        address collTokenAddr,
        address recipient,
        uint256 repayAmount,
        uint256 repayAmountLeft,
        bool isUnlock
    ) internal {
        // if collTokenAddr is weth, then return so don't double transfer on partial repay
        // or waste gas on unlock when no rewards will be paid out
        // note: this should never actually happen since weth
        // and this compartment should not be whitelisted, but just in case
        if (collTokenAddr == WETH) {
            return;
        }

        // solhint-disable no-empty-blocks
        try IGLPStakingHelper(FEE_GLP).claim(address(this)) {
            // do nothing
            // solhint-disable no-empty-blocks
        } catch {
            // do nothing
        }

        // check weth token balance
        uint256 currentWethBal = IERC20(WETH).balanceOf(address(this));

        // transfer proportion of weth token balance
        uint256 wethTokenAmount = isUnlock
            ? currentWethBal
            : Math.mulDiv(repayAmount, currentWethBal, repayAmountLeft);
        IERC20(WETH).safeTransfer(recipient, wethTokenAmount);
    }
}

// File: contracts/peer-to-peer/compartments/voting/VoteCompartment.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IVotes} from "@openzeppelin/contracts/governance/utils/IVotes.sol";
import {IAddressRegistry} from "../../interfaces/IAddressRegistry.sol";
import {ILenderVaultImpl} from "../../interfaces/ILenderVaultImpl.sol";
import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol";
import {BaseCompartment} from "../BaseCompartment.sol";
import {Errors} from "../../../Errors.sol";

contract VoteCompartment is BaseCompartment {
    using SafeERC20 for IERC20;

    mapping(address => bool) public approvedDelegator;

    function delegate(address _delegatee) external {
        DataTypesPeerToPeer.Loan memory loan = ILenderVaultImpl(vaultAddr).loan(
            loanIdx
        );
        if (msg.sender != loan.borrower && !approvedDelegator[msg.sender]) {
            revert Errors.InvalidSender();
        }
        if (block.timestamp >= loan.expiry) {
            revert Errors.LoanExpired();
        }
        if (_delegatee == address(0)) {
            revert Errors.InvalidDelegatee();
        }
        uint256 preDelegateCompartmentBal = IERC20(loan.collToken).balanceOf(
            address(this)
        );
        IVotes(loan.collToken).delegate(_delegatee);
        if (
            preDelegateCompartmentBal >
            IERC20(loan.collToken).balanceOf(address(this))
        ) {
            revert Errors.DelegateReducedBalance();
        }
        emit Delegated(msg.sender, _delegatee);
    }

    function toggleApprovedDelegator(address _delegate) external {
        DataTypesPeerToPeer.Loan memory loan = ILenderVaultImpl(vaultAddr).loan(
            loanIdx
        );
        if (msg.sender != loan.borrower) {
            revert Errors.InvalidSender();
        }
        bool currDelegateState = approvedDelegator[_delegate];
        approvedDelegator[_delegate] = !currDelegateState;
        emit UpdatedApprovedDelegator(_delegate, !currDelegateState);
    }

    // transfer coll on repays
    function transferCollFromCompartment(
        uint256 /*repayAmount*/,
        uint256 /*repayAmountLeft*/,
        uint128 reclaimCollAmount,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr
    ) external {
        _transferCollFromCompartment(
            reclaimCollAmount,
            borrowerAddr,
            collTokenAddr,
            callbackAddr
        );
    }

    // unlockColl this would be called on defaults
    function unlockCollToVault(address collTokenAddr) external {
        _unlockCollToVault(collTokenAddr);
    }

    function getReclaimableBalance(
        address collToken
    ) external view override returns (uint256) {
        return IERC20(collToken).balanceOf(address(this));
    }
}

// File: contracts/peer-to-peer/DataTypesPeerToPeer.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

library DataTypesPeerToPeer {
    struct Loan {
        // address of borrower
        address borrower;
        // address of coll token
        address collToken;
        // address of loan token
        address loanToken;
        // timestamp after which any portion of loan unpaid defaults
        uint40 expiry;
        // timestamp before which borrower cannot repay
        uint40 earliestRepay;
        // initial collateral amount of loan
        uint128 initCollAmount;
        // loan amount given
        uint128 initLoanAmount;
        // full repay amount at start of loan
        uint128 initRepayAmount;
        // amount repaid (loan token) up until current time
        // note: partial repayments are allowed
        uint128 amountRepaidSoFar;
        // amount reclaimed (coll token) up until current time
        // note: partial repayments are allowed
        uint128 amountReclaimedSoFar;
        // flag tracking if collateral has been unlocked by vault
        bool collUnlocked;
        // address of the compartment housing the collateral
        address collTokenCompartmentAddr;
    }

    struct QuoteTuple {
        // loan amount per one unit of collateral if no oracle
        // LTV in terms of the constant BASE (10 ** 18) if using oracle
        uint256 loanPerCollUnitOrLtv;
        // interest rate percentage in BASE (can be negative but greater than -BASE)
        // i.e. -100% < interestRatePct since repay amount of 0 is not allowed
        // also interestRatePctInBase is not annualized
        int256 interestRatePctInBase;
        // fee percentage,in BASE, which will be paid in upfront in collateral
        uint256 upfrontFeePctInBase;
        // length of the loan in seconds
        uint256 tenor;
    }

    struct GeneralQuoteInfo {
        // address of collateral token
        address collToken;
        // address of loan token
        address loanToken;
        // address of oracle (optional)
        address oracleAddr;
        // min loan amount (in loan token) prevent griefing attacks or
        // amounts lender feels isn't worth unlocking on default
        uint256 minLoan;
        // max loan amount (in loan token) if lender wants a cap
        uint256 maxLoan;
        // timestamp after which quote automatically invalidates
        uint256 validUntil;
        // time, in seconds, that loan cannot be exercised
        uint256 earliestRepayTenor;
        // address of compartment implementation (optional)
        address borrowerCompartmentImplementation;
        // will invalidate quote after one use
        // if false, will be a standing quote
        bool isSingleUse;
        // whitelist address (optional)
        address whitelistAddr;
        // flag indicating whether whitelistAddr refers to a single whitelisted
        // borrower or to a whitelist authority that can whitelist multiple addresses
        bool isWhitelistAddrSingleBorrower;
    }

    struct OnChainQuote {
        // general quote info
        GeneralQuoteInfo generalQuoteInfo;
        // array of quote parameters
        QuoteTuple[] quoteTuples;
        // provides more distinguishability of quotes to reduce
        // likelihood of collisions w.r.t. quote creations and invalidations
        bytes32 salt;
    }

    struct OffChainQuote {
        // general quote info
        GeneralQuoteInfo generalQuoteInfo;
        // root of the merkle tree, where the merkle tree encodes all QuoteTuples the lender accepts
        bytes32 quoteTuplesRoot;
        // provides more distinguishability of quotes to reduce
        // likelihood of collisions w.r.t. quote creations and invalidations
        bytes32 salt;
        // for invalidating multiple parallel quotes in one click
        uint256 nonce;
        // array of compact signatures from vault signers
        bytes[] compactSigs;
    }

    struct LoanRepayInstructions {
        // loan id being repaid
        uint256 targetLoanId;
        // repay amount after transfer fees in loan token
        uint128 targetRepayAmount;
        // expected transfer fees in loan token (=0 for tokens without transfer fee)
        // note: amount that borrower sends is targetRepayAmount + expectedTransferFee
        uint128 expectedTransferFee;
        // deadline to prevent stale transactions
        uint256 deadline;
        // e.g., for using collateral to payoff debt via DEX
        address callbackAddr;
        // any data needed by callback
        bytes callbackData;
    }

    struct BorrowTransferInstructions {
        // amount of collateral sent
        uint256 collSendAmount;
        // sum of (i) protocol fee and (ii) transfer fees (if any) associated with sending any collateral to vault
        uint256 expectedProtocolAndVaultTransferFee;
        // transfer fees associated with sending any collateral to compartment (if used)
        uint256 expectedCompartmentTransferFee;
        // deadline to prevent stale transactions
        uint256 deadline;
        // slippage protection if oracle price is too loose
        uint256 minLoanAmount;
        // e.g., for one-click leverage
        address callbackAddr;
        // any data needed by callback
        bytes callbackData;
        // any data needed by myso token manager
        bytes mysoTokenManagerData;
    }

    struct TransferInstructions {
        // collateral token receiver
        address collReceiver;
        // effective upfront fee in collateral tokens (vault or compartment)
        uint256 upfrontFee;
    }

    struct WrappedERC721TokenInfo {
        // address of the ERC721_TOKEN
        address tokenAddr;
        // array of ERC721_TOKEN ids
        uint256[] tokenIds;
    }

    struct WrappedERC20TokenInfo {
        // token addresse
        address tokenAddr;
        // token amounts
        uint256 tokenAmount;
    }

    struct OnChainQuoteInfo {
        // hash of on chain quote
        bytes32 quoteHash;
        // valid until timestamp
        uint256 validUntil;
    }

    enum WhitelistState {
        // not whitelisted
        NOT_WHITELISTED,
        // can be used as loan or collateral token
        ERC20_TOKEN,
        // can be be used as oracle
        ORACLE,
        // can be used as compartment
        COMPARTMENT,
        // can be used as callback contract
        CALLBACK,
        // can be used as loan or collateral token, but if collateral then must
        // be used in conjunction with a compartment (e.g., for stETH with possible
        // negative rebase that could otherwise affect other borrowers in the vault)
        ERC20_TOKEN_REQUIRING_COMPARTMENT,
        // can be used in conjunction with an ERC721 wrapper
        ERC721_TOKEN,
        // can be used as ERC721 wrapper contract
        ERC721WRAPPER,
        // can be used as ERC20 wrapper contract
        ERC20WRAPPER,
        // can be used as MYSO token manager contract
        MYSO_TOKEN_MANAGER,
        // can be used as quote policy manager contract
        QUOTE_POLICY_MANAGER
    }
}

// File: contracts/peer-to-peer/interfaces/callbacks/BalancerDataTypes.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

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

library BalancerDataTypes {
    enum SwapKind {
        GIVEN_IN,
        GIVEN_OUT
    }

    struct FundManagement {
        address sender;
        bool fromInternalBalance;
        address payable recipient;
        bool toInternalBalance;
    }

    struct SingleSwap {
        bytes32 poolId;
        SwapKind kind;
        IBalancerAsset assetIn;
        IBalancerAsset assetOut;
        uint256 amount;
        bytes userData;
    }
}

// File: contracts/peer-to-peer/interfaces/callbacks/IBalancerAsset.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

interface IBalancerAsset {
    // solhint-disable-previous-line no-empty-blocks
}

// File: contracts/peer-to-peer/interfaces/callbacks/IBalancerVault.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

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

interface IBalancerVault {
    function swap(
        BalancerDataTypes.SingleSwap memory singleSwap,
        BalancerDataTypes.FundManagement memory funds,
        uint256 limit,
        uint256 deadline
    ) external payable returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/callbacks/ISwapRouter.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

interface ISwapRouter {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    function exactInputSingle(
        ExactInputSingleParams calldata params
    ) external payable returns (uint256 amountOut);

    function exactInput(
        ExactInputParams calldata params
    ) external payable returns (uint256 amountOut);

    function exactOutputSingle(
        ExactOutputSingleParams calldata params
    ) external payable returns (uint256 amountIn);

    function exactOutput(
        ExactOutputParams calldata params
    ) external payable returns (uint256 amountIn);
}

// File: contracts/peer-to-peer/interfaces/compartments/IBaseCompartment.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

interface IBaseCompartment {
    event Staked(uint256 gaugeIndex, address liqGaugeAddr, uint256 amount);

    event Delegated(address delegator, address delegatee);

    event UpdatedApprovedStaker(address staker, bool approvalState);

    event UpdatedApprovedDelegator(address delegator, bool approvalState);

    /**
     * @notice function to initialize collateral compartment
     * @dev factory creates clone and then initializes implementation contract
     * @param vaultAddr address of vault
     * @param loanId index of the loan
     */
    function initialize(address vaultAddr, uint256 loanId) external;

    /**
     * @notice function to transfer some amount of collateral to borrower on repay
     * @dev this function can only be called by vault and tranfers proportional amount
     * of compartment collTokenBalance to borrower address. This needs use a proportion
     * and not the amount to account for possible changes due to rewards accruing
     * @param repayAmount amount of loan token to be repaid
     * @param repayAmountLeft amount of loan token still outstanding
     * @param reclaimCollAmount amount of collateral token to be reclaimed
     * @param borrowerAddr address of borrower receiving transfer
     * @param collTokenAddr address of collateral token being transferred
     * @param callbackAddr address to send collateral to instead of borrower if using callback
     */
    function transferCollFromCompartment(
        uint256 repayAmount,
        uint256 repayAmountLeft,
        uint128 reclaimCollAmount,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr
    ) external;

    /**
     * @notice function to unlock all collateral left in compartment
     * @dev this function can only be called by vault and returns all collateral to vault
     * @param collTokenAddr pass in collToken addr to avoid callback reads gas cost
     */
    function unlockCollToVault(address collTokenAddr) external;

    /**
     * @notice function returns the potentially reclaimable collateral token balance
     * @param collTokenAddr address of collateral token for which reclaimable balance is being retrieved
     * @dev depending on compartment implementation this could be simple balanceOf or eg staked balance call
     */
    function getReclaimableBalance(
        address collTokenAddr
    ) external view returns (uint256 reclaimableBalance);
}

// File: contracts/peer-to-peer/interfaces/compartments/staking/ICurveStakingHelper.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

interface ICurveStakingHelper {
    /**
     * @notice Deposit `value` LP tokens, curve type take pools
     * @param value Number of tokens to deposit
     */
    function deposit(uint256 value) external;

    /**
     * @notice Withdraw `value` LP tokens, curve type take pools
     * @dev This withdraw function is for gauges v1 and v2
     * @param value Number of tokens to withdraw
     */
    function withdraw(uint256 value) external;

    /**
     * @notice Withdraw `value` LP tokens, curve type take pools
     * @dev This withdraw function is for gauges v3, v4 and v5
     * @param value Number of tokens to withdraw
     * @param withdrawRewards true if withdrawing rewards
     */
    function withdraw(uint256 value, bool withdrawRewards) external;

    /**
     * @notice Claim all available reward tokens for msg.sender
     */
    function claim_rewards() external;

    /**
     * @notice Mint allocated tokens for the caller based on a single gauge.
     * @param gaugeAddr address to get mintable amount from
     */
    function mint(address gaugeAddr) external;

    /**
     * @notice returns lpToken address for gauge
     */
    function lp_token() external view returns (address);

    /**
     * @notice returns reward token address for liquidity gauge by index
     * @param index index of particular token address in the reward token array
     */
    function reward_tokens(uint256 index) external view returns (address);

    /**
     * @notice returns gauge address by index from gaugeController
     * @param index index in gauge controller array that returns liquidity gauge address
     */
    function gauges(uint256 index) external view returns (address);
}

// File: contracts/peer-to-peer/interfaces/compartments/staking/IGLPStakingHelper.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

interface IGLPStakingHelper {
    /**
     * @notice Claim fee reward tokens
     * @param _receiver address which is recipient of the claim
     */
    function claim(address _receiver) external returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/IAddressRegistry.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

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

interface IAddressRegistry {
    event WhitelistStateUpdated(
        address[] indexed whitelistAddrs,
        DataTypesPeerToPeer.WhitelistState indexed whitelistState
    );
    event AllowedTokensForCompartmentUpdated(
        address indexed compartmentImpl,
        address[] tokens,
        bool isWhitelisted
    );
    event BorrowerWhitelistStatusClaimed(
        address indexed whitelistAuthority,
        address indexed borrower,
        uint256 whitelistedUntil
    );
    event BorrowerWhitelistUpdated(
        address indexed whitelistAuthority,
        address[] borrowers,
        uint256 whitelistedUntil
    );
    event CreatedWrappedTokenForERC721s(
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] wrappedTokensInfo,
        string name,
        string symbol,
        address newErc20Addr
    );
    event CreatedWrappedTokenForERC20s(
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] wrappedTokensInfo,
        string name,
        string symbol,
        address newERC20Addr
    );

    /**
     * @notice initializes factory, gateway, and quote handler contracts
     * @param _lenderVaultFactory address of the factory for lender vaults
     * @param _borrowerGateway address of the gateway with which borrowers interact
     * @param _quoteHandler address of contract which handles quote logic
     */
    function initialize(
        address _lenderVaultFactory,
        address _borrowerGateway,
        address _quoteHandler
    ) external;

    /**
     * @notice adds new lender vault to registry
     * @dev can only be called lender vault factory
     * @param addr address of new lender vault
     * @return numRegisteredVaults number of registered vaults
     */
    function addLenderVault(
        address addr
    ) external returns (uint256 numRegisteredVaults);

    /**
     * @notice Allows user to claim whitelisted status
     * @param whitelistAuthority Address of whitelist authorithy
     * @param whitelistedUntil Timestamp until when user is whitelisted
     * @param compactSig Compact signature from whitelist authority
     * @param salt Salt to make signature unique
     */
    function claimBorrowerWhitelistStatus(
        address whitelistAuthority,
        uint256 whitelistedUntil,
        bytes calldata compactSig,
        bytes32 salt
    ) external;

    /**
     * @notice Allows user to wrap (multiple) ERC721 into one ERC20
     * @param tokensToBeWrapped Array of WrappedERC721TokenInfo
     * @param name Name of the new wrapper token
     * @param symbol Symbol of the new wrapper token
     * @param mysoTokenManagerData Data to be passed to MysoTokenManager
     */
    function createWrappedTokenForERC721s(
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol,
        bytes calldata mysoTokenManagerData
    ) external;

    /**
     * @notice Allows user to wrap multiple ERC20 into one ERC20
     * @param tokensToBeWrapped Array of WrappedERC20TokenInfo
     * @param name Name of the new wrapper token
     * @param symbol Symbol of the new wrapper token
     * @param mysoTokenManagerData Data to be passed to MysoTokenManager
     */
    function createWrappedTokenForERC20s(
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol,
        bytes calldata mysoTokenManagerData
    ) external;

    /**
     * @notice Allows a whitelist authority to set the whitelistedUntil state for a given borrower
     * @dev Anyone can create their own whitelist, and lenders can decide if and which whitelist they want to use
     * @param borrowers Array of borrower addresses
     * @param whitelistedUntil Timestamp until which borrowers shall be whitelisted under given whitelist authority
     */
    function updateBorrowerWhitelist(
        address[] calldata borrowers,
        uint256 whitelistedUntil
    ) external;

    /**
     * @notice Sets the whitelist state for a given address
     * @dev Can only be called by registry owner
     * @param addrs Addresses for which whitelist state shall be set
     * @param whitelistState The whitelist state to which addresses shall be set
     */
    function setWhitelistState(
        address[] calldata addrs,
        DataTypesPeerToPeer.WhitelistState whitelistState
    ) external;

    /**
     * @notice Sets the allowed tokens for a given compartment implementation
     * @dev Can only be called by registry owner
     * @param compartmentImpl Compartment implementations for which allowed tokens shall be set
     * @param tokens List of tokens that shall be allowed for given compartment implementation
     * @param allowTokensForCompartment Boolean flag indicating whether tokens shall be allowed for compartment 
     implementation
     */
    function setAllowedTokensForCompartment(
        address compartmentImpl,
        address[] calldata tokens,
        bool allowTokensForCompartment
    ) external;

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     * @param newOwner the proposed new owner address
     */
    function transferOwnership(address newOwner) external;

    /**
     * @notice Returns boolean flag indicating whether the borrower has been whitelisted by whitelistAuthority
     * @param whitelistAuthority Addresses of the whitelist authority
     * @param borrower Addresses of the borrower
     * @return Boolean flag indicating whether the borrower has been whitelisted by whitelistAuthority
     */
    function isWhitelistedBorrower(
        address whitelistAuthority,
        address borrower
    ) external view returns (bool);

    /**
     * @notice Returns boolean flag indicating whether token is whitelisted
     * @param token Addresses of the given token to check
     * @return Boolean flag indicating whether the token is whitelisted
     */
    function isWhitelistedERC20(address token) external view returns (bool);

    /**
     * @notice Returns the address of the vault factory
     * @return Address of the vault factory contract
     */
    function lenderVaultFactory() external view returns (address);

    /**
     * @notice Returns the address of the borrower gateway
     * @return Address of the borrower gateway contract
     */
    function borrowerGateway() external view returns (address);

    /**
     * @notice Returns the address of the quote handler
     * @return Address of the quote handler contract
     */
    function quoteHandler() external view returns (address);

    /**
     * @notice Returns the address of the MYSO token manager
     * @return Address of the MYSO token manager contract
     */
    function mysoTokenManager() external view returns (address);

    /**
     * @notice Returns boolean flag indicating whether given address is a registered vault
     * @param addr Address to check if it is a registered vault
     * @return Boolean flag indicating whether given address is a registered vault
     */
    function isRegisteredVault(address addr) external view returns (bool);

    /**
     * @notice Returns whitelist state for given address
     * @param addr Address to check whitelist state for
     * @return whitelistState Whitelist state for given address
     */
    function whitelistState(
        address addr
    ) external view returns (DataTypesPeerToPeer.WhitelistState whitelistState);

    /**
     * @notice Returns an array of registered vault addresses
     * @return vaultAddrs The array of registered vault addresses
     */
    function registeredVaults()
        external
        view
        returns (address[] memory vaultAddrs);

    /**
     * @notice Returns address of the owner
     * @return Address of the owner
     */
    function owner() external view returns (address);

    /**
     * @notice Returns address of the pending owner
     * @return Address of the pending owner
     */
    function pendingOwner() external view returns (address);

    /**
     * @notice Returns boolean flag indicating whether given compartment implementation and token combination is whitelisted
     * @param compartmentImpl Address of compartment implementation to check if it is allowed for token
     * @param token Address of token to check if compartment implementation is allowed
     * @return isWhitelisted Boolean flag indicating whether compartment implementation is whitelisted for given token
     */
    function isWhitelistedCompartment(
        address compartmentImpl,
        address token
    ) external view returns (bool isWhitelisted);

    /**
     * @notice Returns current number of vaults registered
     * @return numVaults Current number of vaults registered
     */
    function numRegisteredVaults() external view returns (uint256 numVaults);
}

// File: contracts/peer-to-peer/interfaces/IBorrowerGateway.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol";

interface IBorrowerGateway {
    event Borrowed(
        address indexed vaultAddr,
        address indexed borrower,
        DataTypesPeerToPeer.Loan loan,
        uint256 upfrontFee,
        uint256 indexed loanId,
        address callbackAddr,
        bytes callbackData
    );

    event Repaid(
        address indexed vaultAddr,
        uint256 indexed loanId,
        uint256 repayAmount
    );

    event ProtocolFeeSet(uint128[2] newFeeParams);

    /**
     * @notice function which allows a borrower to use an offChain quote to borrow
     * @param lenderVault address of the vault whose owner(s) signed the offChain quote
     * @param borrowInstructions data needed for borrow (see DataTypesPeerToPeer comments)
     * @param offChainQuote quote data (see DataTypesPeerToPeer comments)
     * @param quoteTuple quote data (see DataTypesPeerToPeer comments)
     * @param proof array of bytes needed for merkle tree verification of quote
     * @return loan data
     */
    function borrowWithOffChainQuote(
        address lenderVault,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.OffChainQuote calldata offChainQuote,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple,
        bytes32[] memory proof
    ) external returns (DataTypesPeerToPeer.Loan memory);

    /**
     * @notice function which allows a borrower to use an onChain quote to borrow
     * @param lenderVault address of the vault whose owner(s) enacted onChain quote
     * @param borrowInstructions data needed for borrow (see DataTypesPeerToPeer comments)
     * @param onChainQuote quote data (see DataTypesPeerToPeer comments)
     * @param quoteTupleIdx index of quote tuple array
     * @return loan data
     */
    function borrowWithOnChainQuote(
        address lenderVault,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.OnChainQuote calldata onChainQuote,
        uint256 quoteTupleIdx
    ) external returns (DataTypesPeerToPeer.Loan memory);

    /**
     * @notice function which allows a borrower to repay a loan
     * @param loanRepayInstructions data needed for loan repay (see DataTypesPeerToPeer comments)
     * @param vaultAddr address of the vault in which loan was taken out
     */
    function repay(
        DataTypesPeerToPeer.LoanRepayInstructions
            calldata loanRepayInstructions,
        address vaultAddr
    ) external;

    /**
     * @notice function which allows owner to set new protocol fee params
     * @dev protocolFee params are in units of BASE constant (10**18) and variable portion is annualized
     * @param _newFeeParams new base fee (constant) and fee slope (variable) in BASE
     */
    function setProtocolFeeParams(uint128[2] calldata _newFeeParams) external;

    /**
     * @notice function returns address registry
     * @return address of registry
     */
    function addressRegistry() external view returns (address);

    /**
     * @notice function returns protocol fee
     * @return protocolFeeParams protocol fee Params in Base
     */
    function getProtocolFeeParams()
        external
        view
        returns (uint128[2] memory protocolFeeParams);
}

// File: contracts/peer-to-peer/interfaces/ILenderVaultFactory.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

interface ILenderVaultFactory {
    event NewVaultCreated(
        address indexed newLenderVaultAddr,
        address vaultOwner,
        uint256 numRegisteredVaults
    );

    /**
     * @notice function creates new lender vaults
     * @param salt salt used for deterministic cloning
     * @return newLenderVaultAddr address of created vault
     */
    function createVault(
        bytes32 salt
    ) external returns (address newLenderVaultAddr);

    /**
     * @notice function returns address registry
     * @return address of registry
     */
    function addressRegistry() external view returns (address);

    /**
     * @notice function returns address of lender vault implementation contract
     * @return address of lender vault implementation
     */
    function lenderVaultImpl() external view returns (address);
}

// File: contracts/peer-to-peer/interfaces/ILenderVaultImpl.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol";

interface ILenderVaultImpl {
    event AddedSigners(address[] _signers);

    event MinNumberOfSignersSet(uint256 minNumSigners);

    event RemovedSigner(
        address signerRemoved,
        uint256 signerIdx,
        address signerMovedFromEnd
    );

    event CollateralUnlocked(
        address indexed vaultOwner,
        address indexed collToken,
        uint256[] loanIds,
        uint256 amountUnlocked
    );

    event QuoteProcessed(
        uint256 netPledgeAmount,
        DataTypesPeerToPeer.TransferInstructions transferInstructions
    );

    event Withdrew(address indexed tokenAddr, uint256 withdrawAmount);

    event CircuitBreakerUpdated(
        address indexed newCircuitBreaker,
        address indexed oldCircuitBreaker
    );

    event ReverseCircuitBreakerUpdated(
        address indexed newReverseCircuitBreaker,
        address indexed oldReverseCircuitBreaker
    );

    event OnChainQuotingDelegateUpdated(
        address indexed newOnChainQuotingDelegate,
        address indexed oldOnChainQuotingDelegate
    );

    /**
     * @notice function to initialize lender vault
     * @dev factory creates clone and then initializes the vault
     * @param vaultOwner address of vault owner
     * @param addressRegistry registry address
     */
    function initialize(address vaultOwner, address addressRegistry) external;

    /**
     * @notice function to unlock defaulted collateral
     * @dev only loans with same collateral token can be unlocked in one call
     * function will revert if mismatch in coll token to a loan.collToken.
     * @param collToken address of the collateral token
     * @param _loanIds array of indices of the loans to unlock
     */
    function unlockCollateral(
        address collToken,
        uint256[] calldata _loanIds
    ) external;

    /**
     * @notice function to update loan info on a reoay
     * @dev only borrower gateway can call this function
     * loanId is needed by vault to store updated loan info
     * @param repayAmount amount of loan repaid
     * @param loanId index of loan in loans array
     * @param collAmount amount of collateral to unlock
     * @param noCompartment boolean flag indicating whether loan has no compartment
     * @param collToken address of the collateral token
     */
    function updateLoanInfo(
        uint128 repayAmount,
        uint256 loanId,
        uint128 collAmount,
        bool noCompartment,
        address collToken
    ) external;

    /**
     * @notice function to processQuote on a borrow
     * @dev only borrower gateway can call this function
     * @param borrower address of the borrower
     * @param borrowInstructions struct containing all info for borrow (see DataTypesPeerToPeer.sol notes)
     * @param generalQuoteInfo struct containing quote info (see Datatypes.sol notes)
     * @param quoteTuple struct containing specific quote tuple info (see DataTypesPeerToPeer.sol notes)
     * @return loan loan information after processing the quote
     * @return loanId index of loans in the loans array
     * @return transferInstructions struct containing transfer instruction info (see DataTypesPeerToPeer.sol notes)
     */
    function processQuote(
        address borrower,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple
    )
        external
        returns (
            DataTypesPeerToPeer.Loan calldata loan,
            uint256 loanId,
            DataTypesPeerToPeer.TransferInstructions memory transferInstructions
        );

    /**
     * @notice function to withdraw a token from a vault
     * @dev only vault owner can withdraw
     * @param token address of the token to withdraw
     * @param amount amount of token to withdraw
     */
    function withdraw(address token, uint256 amount) external;

    /**
     * @notice function to transfer token from vault
     * @dev only borrow gateway can call this function
     * @param token address of the token to transfer
     * @param recipient address which receives the tokens
     * @param amount amount of token to transfer
     */
    function transferTo(
        address token,
        address recipient,
        uint256 amount
    ) external;

    /**
     * @notice function to transfer token from a compartment
     * @dev only borrow gateway can call this function, if callbackAddr, then
     * the collateral will be transferred to the callback address
     * @param repayAmount amount of loan token to be repaid
     * @param repayAmountLeft amount of loan token still outstanding
     * @param reclaimCollAmount amount of collateral to be reclaimed
     * @param borrowerAddr address of the borrower
     * @param collTokenAddr address of the coll token to transfer to compartment
     * @param callbackAddr address of callback
     * @param collTokenCompartmentAddr address of the coll token compartment
     */
    function transferCollFromCompartment(
        uint256 repayAmount,
        uint256 repayAmountLeft,
        uint128 reclaimCollAmount,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr,
        address collTokenCompartmentAddr
    ) external;

    /**
     * @notice function to set minimum number of signers required for an offchain quote
     * @dev this function allows a multi-sig quorum to sign a quote offchain
     * @param _minNumOfSigners minimum number of signatures borrower needs to provide
     */
    function setMinNumOfSigners(uint256 _minNumOfSigners) external;

    /**
     * @notice function to add a signer
     * @dev this function only can be called by vault owner
     * @param _signers array of signers to add
     */
    function addSigners(address[] calldata _signers) external;

    /**
     * @notice function to remove a signer
     * @dev this function only can be called by vault owner
     * @param signer address of signer to be removed
     * @param signerIdx index of the signers array at which signer resides
     */
    function removeSigner(address signer, uint256 signerIdx) external;

    /**
     * @notice function to set a circuit breaker
     * @dev the circuit breaker (and vault owner) can pause all loan offers;
     * note: circuit breaker and reverse circuit breaker can be the same account
     * @param circuitBreaker address of the circuit breaker
     */
    function setCircuitBreaker(address circuitBreaker) external;

    /**
     * @notice function to set a reverse circuit breaker
     * @dev the reverse circuit breaker (and vault owner) can unpause all loan offers;
     * note: circuit breaker and reverse circuit breaker can be the same account
     * @param reverseCircuitBreaker address of the reverse circuit breaker
     */
    function setReverseCircuitBreaker(address reverseCircuitBreaker) external;

    /**
     * @notice function to set a delegate for on chain quoting
     * @dev the quote handler (and vault owner) can add, delete and update on chain quotes
     * @param onChainQuotingDelegate address of the delegate
     */
    function setOnChainQuotingDelegate(address onChainQuotingDelegate) external;

    /**
     * @notice function to pause all quotes from lendervault
     * @dev only vault owner and circuit breaker can pause quotes
     */
    function pauseQuotes() external;

    /**
     * @notice function to unpause all quotes from lendervault
     * @dev only vault owner and reverse circuit breaker can unpause quotes again
     */
    function unpauseQuotes() external;

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     * @param newOwner the proposed new owner address
     */
    function transferOwnership(address newOwner) external;

    /**
     * @notice function to retrieve loan from loans array in vault
     * @dev this function reverts on invalid index
     * @param index index of loan
     * @return loan loan stored at that index in vault
     */
    function loan(
        uint256 index
    ) external view returns (DataTypesPeerToPeer.Loan memory loan);

    /**
     * @notice function to return owner address
     * @return owner address
     */
    function owner() external view returns (address);

    /**
     * @notice Returns address of the pending owner
     * @return Address of the pending owner
     */
    function pendingOwner() external view returns (address);

    /**
     * @notice function to return the total number of signers
     * @return number of signers
     */
    function totalNumSigners() external view returns (uint256);

    /**
     * @notice function to return unlocked token balances
     * @param tokens array of token addresses
     * @return balances the vault balances of the token addresses
     * @return _lockedAmounts the vault locked amounts of the token addresses
     */
    function getTokenBalancesAndLockedAmounts(
        address[] calldata tokens
    )
        external
        view
        returns (uint256[] memory balances, uint256[] memory _lockedAmounts);

    /**
     * @notice function to return address of registry
     * @return registry address
     */
    function addressRegistry() external view returns (address);

    /**
     * @notice function to return address of the circuit breaker
     * @return circuit breaker address
     */
    function circuitBreaker() external view returns (address);

    /**
     * @notice function to return address of the reverse circuit breaker
     * @return reverse circuit breaker address
     */
    function reverseCircuitBreaker() external view returns (address);

    /**
     * @notice function to return address of the delegate for on chain quoting
     * @return approved delegate address
     */
    function onChainQuotingDelegate() external view returns (address);

    /**
     * @notice function returns signer at given index
     * @param index of the signers array
     * @return signer address
     */
    function signers(uint256 index) external view returns (address);

    /**
     * @notice function returns minimum number of signers
     * @return minimum number of signers
     */
    function minNumOfSigners() external view returns (uint256);

    /**
     * @notice function returns if address is a signer
     * @return true, if a signer, else false
     */
    function isSigner(address signer) external view returns (bool);

    /**
     * @notice function returns if withdraw mutex is activated
     * @return true, if withdraw already called, else false
     */
    function withdrawEntered() external view returns (bool);

    /**
     * @notice function returns current locked amounts of given token
     * @param token address of the token
     * @return amount of token locked
     */
    function lockedAmounts(address token) external view returns (uint256);

    /**
     * @notice function returns total number of loans
     * @return total number of loans
     */
    function totalNumLoans() external view returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/IOracle.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

interface IOracle {
    /**
     * @notice function checks oracle validity and calculates collTokenPriceInLoanToken
     * @param collToken address of coll token
     * @param loanToken address of loan token
     * @return collTokenPriceInLoanToken collateral price denominated in loan token
     */
    function getPrice(
        address collToken,
        address loanToken
    ) external view returns (uint256 collTokenPriceInLoanToken);

    /**
     * @notice function checks oracle validity and retrieves prices in base currency unit
     * @param collToken address of coll token
     * @param loanToken address of loan token
     * @return collTokenPriceRaw and loanTokenPriceRaw denominated in base currency unit
     */
    function getRawPrices(
        address collToken,
        address loanToken
    )
        external
        view
        returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw);
}

// File: contracts/peer-to-peer/interfaces/IQuoteHandler.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol";

interface IQuoteHandler {
    event OnChainQuoteAdded(
        address indexed lenderVault,
        DataTypesPeerToPeer.OnChainQuote onChainQuote,
        bytes32 indexed onChainQuoteHash
    );

    event OnChainQuoteDeleted(
        address indexed lenderVault,
        bytes32 indexed onChainQuoteHash
    );

    event OnChainQuoteInvalidated(
        address indexed lenderVault,
        bytes32 indexed onChainQuoteHash
    );
    event OffChainQuoteNonceIncremented(
        address indexed lenderVault,
        uint256 newNonce
    );
    event OffChainQuoteInvalidated(
        address indexed lenderVault,
        bytes32 indexed offChainQuoteHash
    );
    event OnChainQuoteUsed(
        address indexed lenderVault,
        bytes32 indexed onChainQuoteHash,
        uint256 indexed toBeRegisteredLoanId,
        uint256 quoteTupleIdx
    );
    event OffChainQuoteUsed(
        address indexed lenderVault,
        bytes32 indexed offChainQuoteHash,
        uint256 indexed toBeRegisteredLoanId,
        DataTypesPeerToPeer.QuoteTuple quoteTuple
    );
    event QuotePolicyManagerUpdated(
        address indexed lenderVault,
        address indexed newPolicyManagerAddress
    );
    event OnChainQuotePublished(
        DataTypesPeerToPeer.OnChainQuote onChainQuote,
        bytes32 indexed onChainQuoteHash,
        address indexed proposer
    );
    event OnChainQuoteCopied(
        address indexed lenderVault,
        bytes32 indexed onChainQuoteHash
    );

    /**
     * @notice function adds on chain quote
     * @dev function can only be called by vault owner or on chain quote delegate
     * @param lenderVault address of the vault adding quote
     * @param onChainQuote data for the onChain quote (See notes in DataTypesPeerToPeer.sol)
     */
    function addOnChainQuote(
        address lenderVault,
        DataTypesPeerToPeer.OnChainQuote calldata onChainQuote
    ) external;

    /**
     * @notice function updates on chain quote
     * @dev function can only be called by vault owner or on chain quote delegate
     * @param lenderVault address of the vault updating quote
     * @param oldOnChainQuoteHash quote hash for the old onChain quote marked for deletion
     * @param newOnChainQuote data for the new onChain quote (See notes in DataTypesPeerToPeer.sol)
     */
    function updateOnChainQuote(
        address lenderVault,
        bytes32 oldOnChainQuoteHash,
        DataTypesPeerToPeer.OnChainQuote calldata newOnChainQuote
    ) external;

    /**
     * @notice function deletes on chain quote
     * @dev function can only be called by vault owner or on chain quote delegate
     * @param lenderVault address of the vault deleting
     * @param onChainQuoteHash quote hash for the onChain quote marked for deletion
     */
    function deleteOnChainQuote(
        address lenderVault,
        bytes32 onChainQuoteHash
    ) external;

    /**
     * @notice function to copy a published on chain quote
     * @dev function can only be called by vault owner or on chain quote delegate
     * @param lenderVault address of the vault approving
     * @param onChainQuoteHash quote hash of a published onChain quote
     */
    function copyPublishedOnChainQuote(
        address lenderVault,
        bytes32 onChainQuoteHash
    ) external;

    /**
     * @notice function to publish an on chain quote
     * @dev function can be called by anyone and used by any vault
     * @param onChainQuote data for the onChain quote (See notes in DataTypesPeerToPeer.sol)
     */
    function publishOnChainQuote(
        DataTypesPeerToPeer.OnChainQuote calldata onChainQuote
    ) external;

    /**
     * @notice function increments the nonce for a vault
     * @dev function can only be called by vault owner
     * incrementing the nonce can bulk invalidate any
     * off chain quotes with that nonce in one txn
     * @param lenderVault address of the vault
     */
    function incrementOffChainQuoteNonce(address lenderVault) external;

    /**
     * @notice function invalidates off chain quote
     * @dev function can only be called by vault owner
     * this function invalidates one specific quote
     * @param lenderVault address of the vault
     * @param offChainQuoteHash hash of the off chain quote to be invalidated
     */
    function invalidateOffChainQuote(
        address lenderVault,
        bytes32 offChainQuoteHash
    ) external;

    /**
     * @notice function performs checks on quote and, if valid, updates quotehandler's state
     * @dev function can only be called by borrowerGateway
     * @param borrower address of borrower
     * @param lenderVault address of the vault
     * @param quoteTupleIdx index of the quote tuple in the vault's quote array
     * @param onChainQuote data for the onChain quote (See notes in DataTypesPeerToPeer.sol)
     */
    function checkAndRegisterOnChainQuote(
        address borrower,
        address lenderVault,
        uint256 quoteTupleIdx,
        DataTypesPeerToPeer.OnChainQuote memory onChainQuote
    ) external;

    /**
     * @notice function performs checks on quote and, if valid, updates quotehandler's state
     * @dev function can only be called by borrowerGateway
     * @param borrower address of borrower
     * @param lenderVault address of the vault
     * @param offChainQuote data for the offChain quote (See notes in DataTypesPeerToPeer.sol)
     * @param quoteTuple quote data (see notes in DataTypesPeerToPeer.sol)
     * @param proof array of bytes needed to verify merkle proof
     */
    function checkAndRegisterOffChainQuote(
        address borrower,
        address lenderVault,
        DataTypesPeerToPeer.OffChainQuote calldata offChainQuote,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple,
        bytes32[] memory proof
    ) external;

    /**
     * @notice function to update the quote policy manager for a vault
     * @param lenderVault address for which quote policy manager is being updated
     * @param newPolicyManagerAddress address of new quote policy manager
     * @dev function can only be called by vault owner
     */
    function updateQuotePolicyManagerForVault(
        address lenderVault,
        address newPolicyManagerAddress
    ) external;

    /**
     * @notice function to return address of registry
     * @return registry address
     */
    function addressRegistry() external view returns (address);

    /**
     * @notice function to return the current nonce for offchain quotes
     * @param lender address for which nonce is being retrieved
     * @return current value of nonce
     */
    function offChainQuoteNonce(address lender) external view returns (uint256);

    /**
     * @notice function returns if offchain quote hash is invalidated
     * @param lenderVault address of vault
     * @param hashToCheck hash of the offchain quote
     * @return true if invalidated, else false
     */
    function offChainQuoteIsInvalidated(
        address lenderVault,
        bytes32 hashToCheck
    ) external view returns (bool);

    /**
     * @notice function returns if hash is for an on chain quote
     * @param lenderVault address of vault
     * @param hashToCheck hash of the on chain quote
     * @return true if hash belongs to a valid on-chain quote, else false
     */
    function isOnChainQuote(
        address lenderVault,
        bytes32 hashToCheck
    ) external view returns (bool);

    /**
     * @notice function returns if hash belongs to a published on chain quote
     * @param hashToCheck hash of the on chain quote
     * @return true if hash belongs to a published on-chain quote, else false
     */
    function isPublishedOnChainQuote(
        bytes32 hashToCheck
    ) external view returns (bool);

    /**
     * @notice function returns valid until timestamp of the published on-chain quote
     * @param hashToCheck hash of the on chain quote
     * @return valid until timestamp of the published on-chain quote
     */
    function publishedOnChainQuoteValidUntil(
        bytes32 hashToCheck
    ) external view returns (uint256);

    /**
     * @notice function returns the address of the policy manager for a vault
     * @param lenderVault address of vault
     * @return address of quote policy manager for vault
     * @dev if policy manager address changes in registry, this function will still return the old address
     * unless and until the vault owner calls updateQuotePolicyManagerForVault
     */
    function quotePolicyManagerForVault(
        address lenderVault
    ) external view returns (address);

    /**
     * @notice function returns element of on-chain history
     * @param lenderVault address of vault
     * @return element of on-chain quote history
     */
    function getOnChainQuoteHistory(
        address lenderVault,
        uint256 idx
    ) external view returns (DataTypesPeerToPeer.OnChainQuoteInfo memory);

    /**
     * @notice function returns array of structs containing the on-chain quote hash and validUntil timestamp
     * @param lenderVault address of vault
     * @param startIdx starting index from on chain quote history array
     * @param endIdx ending index of on chain quote history array (non-inclusive)
     * @return array of quote hash and validUntil data for on-chain quote history of a vault
     */
    function getOnChainQuoteHistorySlice(
        address lenderVault,
        uint256 startIdx,
        uint256 endIdx
    ) external view returns (DataTypesPeerToPeer.OnChainQuoteInfo[] memory);

    /**
     * @notice function returns the number of on-chain quotes that were added or updated
     * @param lenderVault address of vault
     * @return number of on-chain quotes that were added or updated
     */
    function getOnChainQuoteHistoryLength(
        address lenderVault
    ) external view returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/IVaultCallback.sol



// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;

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

interface IVaultCallback {
    /**
     * @notice function which handles borrow side callback
     * @param loan loan data passed to the callback
     * @param data any extra info needed for the callback functionality
     */
    function borrowCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) external;

    /**
     * @notice function which handles repay side callback
     * @param loan loan data passed to the callback
     * @param data any extra info needed for the callback functionality
     */
    function repayCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) external;
}

// File: contracts/peer-to-peer/interfaces/oracles/chainlink/AggregatorV3Interface.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface AggregatorV3Interface {
    function decimals() external view returns (uint8);

    function version() external view returns (uint256);

    function getRoundData(
        uint80 _roundId
    )
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );

    function latestRoundData()
        external
        view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
}

// File: contracts/peer-to-peer/interfaces/oracles/IDSETH.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface IDSETH {
    /**
     * @notice gets addresses of all components
     * @return array of token addresses
     */
    function getComponents() external view returns (address[] memory);

    /**
     * @notice checks if token is a component
     * @param _token token address
     * @return true if token is a component
     */
    function isComponent(address _token) external view returns (bool);

    /**
     * @notice gets the unit of token used in price calculation
     * @param _token token address
     * @return unit of token
     */
    function getTotalComponentRealUnits(
        address _token
    ) external view returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/oracles/IOlympus.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface IOlympus {
    /**
     * @notice index is used to convert from sOhm to gOhm
     */
    function index() external view returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/oracles/IUniV2.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface IUniV2 {
    /**
     * @notice returns reserves of uni v2 pool
     * @return token0 reserves
     * @return token1 reserves
     * @return timestamp
     */
    function getReserves() external view returns (uint112, uint112, uint32);

    /**
     * @notice token0 address of pool
     */
    function token0() external view returns (address);

    /**
     * @notice token1 address of pool
     */
    function token1() external view returns (address);

    /**
     * @notice totalSupply of the lp token
     */
    function totalSupply() external view returns (uint256);

    /**
     * @notice decimals of the lp token
     */
    function decimals() external view returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/oracles/uniswap/ITwapGetter.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

interface ITwapGetter {
    /**
     * @dev returns the twap for the given uniswap v3 pool
     * @param inToken Address of the In Token
     * @param outToken Address of the Out Token
     * @param twapInterval Time interval for the twap
     * @param uniswapV3Pool Address of the Uniswap V3 Pool
     * @return twap The twap (in out token) for the given uniswap v3 pool
     */
    function getTwap(
        address inToken,
        address outToken,
        uint32 twapInterval,
        address uniswapV3Pool
    ) external view returns (uint256 twap);

    /**
     * @dev returns the sqrt twap for the given uniswap v3 pool
     * @param uniswapV3Pool Address of the Uniswap V3 Pool
     * @param twapInterval Time interval for the twap
     * @return sqrtTwapPriceX96 The sqrt twap for the given uniswap v3 pool
     */
    function getSqrtTwapX96(
        address uniswapV3Pool,
        uint32 twapInterval
    ) external view returns (uint160 sqrtTwapPriceX96);
}

// File: contracts/peer-to-peer/interfaces/policyManagers/IBasicQuotePolicyManager.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {DataTypesBasicPolicies} from "../../policyManagers/DataTypesBasicPolicies.sol";
import {IQuotePolicyManager} from "./IQuotePolicyManager.sol";

interface IBasicQuotePolicyManager is IQuotePolicyManager {
    /**
     * @notice Retrieve the global quoting policy for a specific lender's vault
     * @param lenderVault The address of the lender's vault
     * @return The global quoting policy for the specified lender's vault
     */
    function globalQuotingPolicy(
        address lenderVault
    ) external view returns (DataTypesBasicPolicies.GlobalPolicy memory);

    /**
     * @notice Retrieve the quoting policy for a specific lending pair involving collateral and loan tokens
     * @param lenderVault The address of the lender's vault
     * @param collToken The address of the collateral token
     * @param loanToken The address of the loan token
     * @return The quoting policy for the specified lender's vault, collateral, and loan tokens
     */
    function pairQuotingPolicy(
        address lenderVault,
        address collToken,
        address loanToken
    ) external view returns (DataTypesBasicPolicies.PairPolicy memory);

    /**
     * @notice Check if there is a global quoting policy for a specific lender's vault
     * @param lenderVault The address of the lender's vault
     * @return True if there is a global quoting policy, false otherwise
     */
    function hasGlobalQuotingPolicy(
        address lenderVault
    ) external view returns (bool);

    /**
     * @notice Check if there is a quoting policy for a specific lending pair involving collateral and loan tokens
     * @param lenderVault The address of the lender's vault
     * @param collToken The address of the collateral token
     * @param loanToken The address of the loan token
     * @return True if there is a quoting policy for the specified lender's vault, collateral, and loan tokens, false otherwise
     */
    function hasPairQuotingPolicy(
        address lenderVault,
        address collToken,
        address loanToken
    ) external view returns (bool);
}

// File: contracts/peer-to-peer/interfaces/policyManagers/IQuotePolicyManager.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol";

interface IQuotePolicyManager {
    event PairPolicySet(
        address indexed lenderVault,
        address indexed collToken,
        address indexed loanToken,
        bytes singlePolicyData
    );
    event GlobalPolicySet(address indexed lenderVault, bytes globalPolicyData);

    /**
     * @notice sets the global policy
     * @param lenderVault Address of the lender vault
     * @param globalPolicyData Global policy data to be set
     */
    function setGlobalPolicy(
        address lenderVault,
        bytes calldata globalPolicyData
    ) external;

    /**
     * @notice sets the policy for a pair of tokens
     * @param lenderVault Address of the lender vault
     * @param collToken Address of the collateral token
     * @param loanToken Address of the loan token
     * @param pairPolicyData Pair policy data to be set
     */
    function setPairPolicy(
        address lenderVault,
        address collToken,
        address loanToken,
        bytes calldata pairPolicyData
    ) external;

    /**
     * @notice Checks if a borrow is allowed
     * @param borrower Address of the borrower
     * @param lenderVault Address of the lender vault
     * @param generalQuoteInfo General quote info (see DataTypesPeerToPeer.sol)
     * @param quoteTuple Quote tuple (see DataTypesPeerToPeer.sol)
     * @return _isAllowed Flag to indicate if the borrow is allowed
     * @return minNumOfSignersOverwrite Overwrite of minimum number of signers (if zero ignored in quote handler)
     */
    function isAllowed(
        address borrower,
        address lenderVault,
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple
    ) external view returns (bool _isAllowed, uint256 minNumOfSignersOverwrite);

    /**
     * @notice Gets the address registry
     * @return Address of the address registry
     */
    function addressRegistry() external view returns (address);
}

// File: contracts/peer-to-peer/interfaces/wrappers/ERC20/IERC20Wrapper.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {DataTypesPeerToPeer} from "../../../../peer-to-peer/DataTypesPeerToPeer.sol";

interface IERC20Wrapper {
    event ERC20WrapperCreated(
        address indexed newErc20Addr,
        address indexed minter,
        uint256 numTokensCreated,
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] wrappedTokensInfo
    );

    /**
     * @notice Allows user to wrap multiple ERC20 into one ERC20
     * @param minter Address of the minter
     * @param tokensToBeWrapped Array of WrappedERC20TokenInfo
     * @param name Name of the new wrapper token
     * @param symbol Symbol of the new wrapper token
     */
    function createWrappedToken(
        address minter,
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol
    ) external returns (address);

    /**
     * @notice Returns address registry
     * @return address registry
     */
    function addressRegistry() external view returns (address);

    /**
     * @notice Returns implementation contract address
     * @return implementation contract address
     */
    function wrappedErc20Impl() external view returns (address);

    /**
     * @notice Returns array of tokens created
     * @return array of tokens created
     */
    function allTokensCreated() external view returns (address[] memory);

    /**
     * @notice Returns the address of a token created by index
     * @param idx the index of the token
     * @return address of the token created
     */
    function tokensCreated(uint256 idx) external view returns (address);

    /**
     * @notice Returns number of tokens created
     * @return number of tokens created
     */
    function numTokensCreated() external view returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/wrappers/ERC20/IWrappedERC20Impl.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {DataTypesPeerToPeer} from "../../../DataTypesPeerToPeer.sol";

interface IWrappedERC20Impl {
    event Redeemed(address indexed redeemer, address recipient, uint256 amount);

    /**
     * @notice Initializes the ERC20 wrapper
     * @param minter Address of the minter
     * @param wrappedTokens Array of WrappedERC20TokenInfo
     * @param totalInitialSupply Total initial supply of the wrapped token basket
     * @param name Name of the new wrapper token
     * @param symbol Symbol of the new wrapper token
     */
    function initialize(
        address minter,
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata wrappedTokens,
        uint256 totalInitialSupply,
        string calldata name,
        string calldata symbol
    ) external;

    /**
     * @notice Function to redeem wrapped token for underlying tokens
     * @param account Account that is redeeming wrapped tokens
     * @param recipient Account that is receiving underlying tokens
     * @param amount Amount of wrapped tokens to be redeemed
     */
    function redeem(
        address account,
        address recipient,
        uint256 amount
    ) external;

    /**
     * @notice Function to mint wrapped tokens for underlying token
     * @dev This function is only callable when the wrapped token has only one underlying token
     * @param recipient Account that is receiving the minted tokens
     * @param amount Amount of wrapped tokens to be minted
     * @param expectedTransferFee Expected transfer fee for the minted tokens (e.g. wrapping PAXG)
     */
    function mint(
        address recipient,
        uint256 amount,
        uint256 expectedTransferFee
    ) external;

    /**
     * @notice Returns wrapped token addresses
     * @return wrappedTokens array of wrapped token addresses
     */
    function getWrappedTokensInfo()
        external
        view
        returns (address[] calldata wrappedTokens);

    /**
     * @notice Returns whether wrapped token is IOU
     * @return boolean flag indicating whether wrapped token is IOU
     */
    function isIOU() external view returns (bool);
}

// File: contracts/peer-to-peer/interfaces/wrappers/ERC721/IERC721Wrapper.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {DataTypesPeerToPeer} from "../../../DataTypesPeerToPeer.sol";

interface IERC721Wrapper {
    event ERC721WrapperCreated(
        address indexed newErc20Addr,
        address indexed minter,
        uint256 numTokensCreated,
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] wrappedTokensInfo
    );

    /**
     * @notice Allows user to wrap (multiple) ERC721 into one ERC20
     * @param minter Address of the minter
     * @param tokensToBeWrapped Array of WrappedERC721TokenInfo
     * @param name Name of the new wrapper token
     * @param symbol Symbol of the new wrapper token
     */
    function createWrappedToken(
        address minter,
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol
    ) external returns (address);

    /**
     * @notice Returns address registry
     * @return address registry
     */
    function addressRegistry() external view returns (address);

    /**
     * @notice Returns implementation contract address
     * @return implementation contract address
     */
    function wrappedErc721Impl() external view returns (address);

    /**
     * @notice Returns array of tokens created
     * @return array of tokens created
     */
    function allTokensCreated() external view returns (address[] memory);

    /**
     * @notice Returns the address of a token created by index
     * @param idx the index of the token
     * @return address of the token created
     */
    function tokensCreated(uint256 idx) external view returns (address);

    /**
     * @notice Returns number of tokens created
     * @return number of tokens created
     */
    function numTokensCreated() external view returns (uint256);
}

// File: contracts/peer-to-peer/interfaces/wrappers/ERC721/IWrappedERC721Impl.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {DataTypesPeerToPeer} from "../../../DataTypesPeerToPeer.sol";

interface IWrappedERC721Impl {
    event Redeemed(address indexed redeemer, address recipient);

    event TransferFromWrappedTokenFailed(
        address indexed tokenAddr,
        uint256 indexed tokenId
    );

    event TokenSweepAttempted(address indexed tokenAddr, uint256[] tokenIds);

    /**
     * @notice Initializes the ERC20 wrapper
     * @param minter Address of the minter
     * @param tokensToBeWrapped Array of token info (address and ids array) for the tokens to be wrapped
     * @param name Name of the new wrapper token
     * @param symbol Symbol of the new wrapper token
     */
    function initialize(
        address minter,
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol
    ) external;

    /**
     * @notice Transfers any stuck wrapped tokens to the redeemer
     * @param tokenAddr Address of the token to be swept
     * @param tokenIds Array of token ids to be swept
     */
    function sweepTokensLeftAfterRedeem(
        address tokenAddr,
        uint256[] calldata tokenIds
    ) external;

    /**
     * @notice Function to redeem wrapped token for underlying tokens
     * @param account Account that is redeeming wrapped tokens
     * @param recipient Account that is receiving underlying tokens
     */
    function redeem(address account, address recipient) external;

    /**
     * @notice Function to remint wrapped token for underlying tokens
     * @param _wrappedTokensForRemint Array of token info (address and ids array) for the tokens to be reminted
     * @param recipient Account that is receiving the reminted ERC20 token
     */
    function remint(
        DataTypesPeerToPeer.WrappedERC721TokenInfo[]
            calldata _wrappedTokensForRemint,
        address recipient
    ) external;

    /**
     * @notice Function to sync the wrapper state with the underlying tokens
     * @dev This function is callable by anyone and can sync back up accounting.
     * e.g. in case of transfer occurring outside remint function directly to wrapped token address
     * @param tokenAddr Address of the token to be synced
     * @param tokenId Id of the token to be synced
     */
    function sync(address tokenAddr, uint256 tokenId) external;

    /**
     * @notice Returns wrapped token info
     * @return wrappedTokens array of struct containing information about wrapped tokens
     */
    function getWrappedTokensInfo()
        external
        view
        returns (
            DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata wrappedTokens
        );

    /**
     * @notice Returns the total and current number of tokens in the wrapper
     * @return Array of total and current number of tokens in the wrapper, respectively
     */
    function getTotalAndCurrentNumOfTokensInWrapper()
        external
        view
        returns (uint128[2] memory);

    /**
     * @notice Returns the address of the last redeemer
     * @return Address of the last redeemer
     */
    function lastRedeemer() external view returns (address);

    /**
     * @notice Returns stuck token status
     * @param tokenAddr Address of the token to be checked
     * @param tokenId Id of the token to be checked
     * @return Returns true if the token is stuck, false otherwise
     */
    function stuckTokens(
        address tokenAddr,
        uint256 tokenId
    ) external view returns (bool);

    /**
     * @notice Returns token currently counted in wrapper status
     * @param tokenAddr Address of the token to be checked
     * @param tokenId Id of the token to be checked
     * @return Returns true if the token is currently counted in the wrapper, false otherwise
     */
    function isTokenCountedInWrapper(
        address tokenAddr,
        uint256 tokenId
    ) external view returns (bool);

    /**
     * @notice Returns whether token is an underlying member of the wrapper
     * @param tokenAddr Address of the token to be checked
     * @param tokenId Id of the token to be checked
     * @return Returns true if the token is an underlying member of the wrapper, false otherwise
     */
    function isUnderlying(
        address tokenAddr,
        uint256 tokenId
    ) external view returns (bool);
}

// File: contracts/peer-to-peer/LenderVaultFactory.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {Errors} from "../Errors.sol";
import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol";
import {ILenderVaultFactory} from "./interfaces/ILenderVaultFactory.sol";
import {ILenderVaultImpl} from "./interfaces/ILenderVaultImpl.sol";
import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol";

contract LenderVaultFactory is ReentrancyGuard, ILenderVaultFactory {
    address public immutable addressRegistry;
    address public immutable lenderVaultImpl;

    constructor(address _addressRegistry, address _lenderVaultImpl) {
        if (_addressRegistry == address(0) || _lenderVaultImpl == address(0)) {
            revert Errors.InvalidAddress();
        }
        addressRegistry = _addressRegistry;
        lenderVaultImpl = _lenderVaultImpl;
    }

    function createVault(
        bytes32 salt
    ) external nonReentrant returns (address newLenderVaultAddr) {
        newLenderVaultAddr = Clones.cloneDeterministic(
            lenderVaultImpl,
            keccak256(abi.encode(msg.sender, salt))
        );
        ILenderVaultImpl(newLenderVaultAddr).initialize(
            msg.sender,
            addressRegistry
        );
        uint256 numRegisteredVaults = IAddressRegistry(addressRegistry)
            .addLenderVault(newLenderVaultAddr);
        address mysoTokenManager = IAddressRegistry(addressRegistry)
            .mysoTokenManager();
        if (mysoTokenManager != address(0)) {
            IMysoTokenManager(mysoTokenManager).processP2PCreateVault(
                numRegisteredVaults,
                msg.sender,
                newLenderVaultAddr
            );
        }
        emit NewVaultCreated(
            newLenderVaultAddr,
            msg.sender,
            numRegisteredVaults
        );
    }
}

// File: contracts/peer-to-peer/LenderVaultImpl.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {IERC20Metadata, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {Constants} from "../Constants.sol";
import {DataTypesPeerToPeer} from "./DataTypesPeerToPeer.sol";
import {Errors} from "../Errors.sol";
import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol";
import {IBaseCompartment} from "./interfaces/compartments/IBaseCompartment.sol";
import {ILenderVaultImpl} from "./interfaces/ILenderVaultImpl.sol";
import {IOracle} from "./interfaces/IOracle.sol";

/**
 * @title LenderVaultImpl
 * @notice This contract implements the logic for the Lender Vault.
 * IMPORTANT: Security best practices dictate that the signers should always take care to
 * keep their private keys safe. Signing only trusted and human-readable public schema data is a good practice. Additionally,
 * the Myso team recommends that the signer should use a purpose-bound address for signing to reduce the chance
 * for a compromised private key to result in loss of funds. The Myso team also recommends that even vaults owned
 * by an EOA should have multiple signers to reduce chance of forged quotes. In the event that a signer is compromised,
 * the vault owner should immediately remove the compromised signer and if possible, add a new signer.
 */

contract LenderVaultImpl is
    Initializable,
    Ownable2Step,
    Pausable,
    ILenderVaultImpl
{
    using SafeERC20 for IERC20Metadata;

    address public addressRegistry;
    address[] public signers;
    address public circuitBreaker;
    address public reverseCircuitBreaker;
    address public onChainQuotingDelegate;
    uint256 public minNumOfSigners;
    mapping(address => bool) public isSigner;
    bool public withdrawEntered;

    mapping(address => uint256) public lockedAmounts;
    DataTypesPeerToPeer.Loan[] internal _loans;

    constructor() {
        _disableInitializers();
    }

    function initialize(
        address _vaultOwner,
        address _addressRegistry
    ) external initializer {
        addressRegistry = _addressRegistry;
        minNumOfSigners = 1;
        if (_vaultOwner == address(0) || _addressRegistry == address(0)) {
            revert Errors.InvalidAddress();
        }
        super._transferOwnership(_vaultOwner);
    }

    function unlockCollateral(
        address collToken,
        uint256[] calldata _loanIds
    ) external {
        // only owner can call this function
        _checkOwner();
        // if empty array is passed, revert
        uint256 loanIdsLen = _loanIds.length;
        if (loanIdsLen == 0) {
            revert Errors.InvalidArrayLength();
        }
        uint256 totalUnlockableColl;
        for (uint256 i; i < loanIdsLen; ) {
            DataTypesPeerToPeer.Loan storage _loan = _loans[_loanIds[i]];

            if (_loan.collToken != collToken) {
                revert Errors.InconsistentUnlockTokenAddresses();
            }
            if (_loan.collUnlocked || block.timestamp < _loan.expiry) {
                revert Errors.InvalidCollUnlock();
            }
            if (_loan.collTokenCompartmentAddr != address(0)) {
                IBaseCompartment(_loan.collTokenCompartmentAddr)
                    .unlockCollToVault(collToken);
            } else {
                totalUnlockableColl += (_loan.initCollAmount -
                    _loan.amountReclaimedSoFar);
            }
            _loan.collUnlocked = true;
            unchecked {
                ++i;
            }
        }

        lockedAmounts[collToken] -= totalUnlockableColl;

        emit CollateralUnlocked(
            owner(),
            collToken,
            _loanIds,
            totalUnlockableColl
        );
    }

    function updateLoanInfo(
        uint128 repayAmount,
        uint256 loanId,
        uint128 reclaimCollAmount,
        bool noCompartment,
        address collToken
    ) external {
        _senderCheckGateway();

        _loans[loanId].amountRepaidSoFar += repayAmount;
        _loans[loanId].amountReclaimedSoFar += reclaimCollAmount;

        // only update lockedAmounts when no compartment
        if (noCompartment) {
            lockedAmounts[collToken] -= reclaimCollAmount;
        }
    }

    function processQuote(
        address borrower,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata borrowInstructions,
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple
    )
        external
        whenNotPaused
        returns (
            DataTypesPeerToPeer.Loan memory _loan,
            uint256 loanId,
            DataTypesPeerToPeer.TransferInstructions memory transferInstructions
        )
    {
        _senderCheckGateway();
        if (
            borrowInstructions.collSendAmount <
            borrowInstructions.expectedProtocolAndVaultTransferFee +
                borrowInstructions.expectedCompartmentTransferFee
        ) {
            revert Errors.InsufficientSendAmount();
        }
        // this check early in function removes need for other checks on sum of upfront plus transfer fees underflowing coll send amount
        if (quoteTuple.upfrontFeePctInBase > Constants.BASE) {
            revert Errors.InvalidUpfrontFee();
        }
        // determine the effective net pledge amount on which loan amount and upfront fee calculation is based
        uint256 netPledgeAmount = borrowInstructions.collSendAmount -
            borrowInstructions.expectedProtocolAndVaultTransferFee -
            borrowInstructions.expectedCompartmentTransferFee;
        transferInstructions.upfrontFee =
            (netPledgeAmount * quoteTuple.upfrontFeePctInBase) /
            Constants.BASE;
        (uint256 loanAmount, uint256 repayAmount) = _getLoanAndRepayAmount(
            netPledgeAmount,
            generalQuoteInfo,
            quoteTuple,
            quoteTuple.upfrontFeePctInBase
        );
        // checks to prevent griefing attacks (e.g. small unlocks that aren't worth it)
        if (
            loanAmount < generalQuoteInfo.minLoan ||
            loanAmount > generalQuoteInfo.maxLoan
        ) {
            revert Errors.InvalidSendAmount();
        }
        if (loanAmount < borrowInstructions.minLoanAmount || loanAmount == 0) {
            revert Errors.TooSmallLoanAmount();
        }
        transferInstructions.collReceiver = address(this);
        _loan.borrower = borrower;
        _loan.loanToken = generalQuoteInfo.loanToken;
        _loan.collToken = generalQuoteInfo.collToken;
        _loan.initLoanAmount = SafeCast.toUint128(loanAmount);
        _loan.initCollAmount = SafeCast.toUint128(
            netPledgeAmount - transferInstructions.upfrontFee
        );
        if (quoteTuple.upfrontFeePctInBase < Constants.BASE) {
            // note: if upfrontFee<100% this corresponds to a loan; check that tenor and earliest repay are consistent
            if (
                quoteTuple.tenor <
                SafeCast.toUint40(
                    generalQuoteInfo.earliestRepayTenor +
                        Constants.MIN_TIME_BETWEEN_EARLIEST_REPAY_AND_EXPIRY
                )
            ) {
                revert Errors.InvalidEarliestRepay();
            }
            _loan.expiry = SafeCast.toUint40(
                block.timestamp + quoteTuple.tenor
            );
            _loan.earliestRepay = SafeCast.toUint40(
                block.timestamp + generalQuoteInfo.earliestRepayTenor
            );
            if (_loan.initCollAmount == 0) {
                revert Errors.ReclaimableCollateralAmountZero();
            }
            loanId = _loans.length;
            if (
                generalQuoteInfo.borrowerCompartmentImplementation == address(0)
            ) {
                if (borrowInstructions.expectedCompartmentTransferFee > 0) {
                    revert Errors.InconsistentExpTransferFee();
                }
                lockedAmounts[_loan.collToken] += _loan.initCollAmount;
            } else {
                transferInstructions.collReceiver = _createCollCompartment(
                    generalQuoteInfo.borrowerCompartmentImplementation,
                    loanId
                );
                _loan.collTokenCompartmentAddr = transferInstructions
                    .collReceiver;
            }
            _loan.initRepayAmount = SafeCast.toUint128(repayAmount);
            _loans.push(_loan);
        } else {
            // note: only case left is upfrontFee = 100% and this corresponds to an outright swap;
            // check that tenor is zero and earliest repay is nonzero, and compartment is zero, with no compartment transfer fee
            if (
                _loan.initCollAmount != 0 ||
                quoteTuple.tenor + generalQuoteInfo.earliestRepayTenor != 0 ||
                generalQuoteInfo.borrowerCompartmentImplementation !=
                address(0) ||
                borrowInstructions.expectedCompartmentTransferFee != 0
            ) {
                revert Errors.InvalidSwap();
            }
        }
        emit QuoteProcessed(netPledgeAmount, transferInstructions);
    }

    function withdraw(address token, uint256 amount) external {
        if (withdrawEntered) {
            revert Errors.WithdrawEntered();
        }
        withdrawEntered = true;
        _checkOwner();
        uint256 vaultBalance = IERC20Metadata(token).balanceOf(address(this));
        if (amount == 0 || amount > vaultBalance - lockedAmounts[token]) {
            revert Errors.InvalidWithdrawAmount();
        }
        IERC20Metadata(token).safeTransfer(owner(), amount);
        withdrawEntered = false;
        emit Withdrew(token, amount);
    }

    function transferTo(
        address token,
        address recipient,
        uint256 amount
    ) external {
        _senderCheckGateway();
        if (
            amount >
            IERC20Metadata(token).balanceOf(address(this)) -
                lockedAmounts[token]
        ) {
            revert Errors.InsufficientVaultFunds();
        }
        IERC20Metadata(token).safeTransfer(recipient, amount);
    }

    function transferCollFromCompartment(
        uint256 repayAmount,
        uint256 repayAmountLeft,
        uint128 reclaimCollAmount,
        address borrowerAddr,
        address collTokenAddr,
        address callbackAddr,
        address collTokenCompartmentAddr
    ) external {
        _senderCheckGateway();
        IBaseCompartment(collTokenCompartmentAddr).transferCollFromCompartment(
            repayAmount,
            repayAmountLeft,
            reclaimCollAmount,
            borrowerAddr,
            collTokenAddr,
            callbackAddr
        );
    }

    function setMinNumOfSigners(uint256 _minNumOfSigners) external {
        _checkOwner();
        if (_minNumOfSigners == 0 || _minNumOfSigners == minNumOfSigners) {
            revert Errors.InvalidNewMinNumOfSigners();
        }
        minNumOfSigners = _minNumOfSigners;
        emit MinNumberOfSignersSet(_minNumOfSigners);
    }

    function addSigners(address[] calldata _signers) external {
        _checkOwner();
        uint256 signersLen = _signers.length;
        if (signersLen == 0) {
            revert Errors.InvalidArrayLength();
        }
        address vaultOwner = owner();
        for (uint256 i; i < signersLen; ) {
            if (_signers[i] == address(0) || _signers[i] == vaultOwner) {
                revert Errors.InvalidAddress();
            }
            if (isSigner[_signers[i]]) {
                revert Errors.AlreadySigner();
            }
            isSigner[_signers[i]] = true;
            signers.push(_signers[i]);
            unchecked {
                ++i;
            }
        }
        emit AddedSigners(_signers);
    }

    function removeSigner(address signer, uint256 signerIdx) external {
        _checkOwner();
        uint256 signersLen = signers.length;
        if (signerIdx >= signersLen) {
            revert Errors.InvalidArrayIndex();
        }

        if (!isSigner[signer] || signer != signers[signerIdx]) {
            revert Errors.InvalidSignerRemoveInfo();
        }
        address signerWithSwappedPosition;
        if (signerIdx != signersLen - 1) {
            signerWithSwappedPosition = signers[signersLen - 1];
            signers[signerIdx] = signerWithSwappedPosition;
        }
        signers.pop();
        isSigner[signer] = false;
        emit RemovedSigner(signer, signerIdx, signerWithSwappedPosition);
    }

    function setCircuitBreaker(address newCircuitBreaker) external {
        _checkOwner();
        address oldCircuitBreaker = circuitBreaker;
        _checkCircuitBreaker(newCircuitBreaker, oldCircuitBreaker);
        circuitBreaker = newCircuitBreaker;
        emit CircuitBreakerUpdated(newCircuitBreaker, oldCircuitBreaker);
    }

    function setReverseCircuitBreaker(
        address newReverseCircuitBreaker
    ) external {
        _checkOwner();
        address oldReverseCircuitBreaker = reverseCircuitBreaker;
        _checkCircuitBreaker(
            newReverseCircuitBreaker,
            oldReverseCircuitBreaker
        );
        reverseCircuitBreaker = newReverseCircuitBreaker;
        emit ReverseCircuitBreakerUpdated(
            newReverseCircuitBreaker,
            oldReverseCircuitBreaker
        );
    }

    function setOnChainQuotingDelegate(
        address newOnChainQuotingDelegate
    ) external {
        _checkOwner();
        address oldOnChainQuotingDelegate = onChainQuotingDelegate;
        // delegate is allowed to be a signer, unlike owner, circuit breaker or reverse circuit breaker
        if (
            newOnChainQuotingDelegate == oldOnChainQuotingDelegate ||
            newOnChainQuotingDelegate == owner()
        ) {
            revert Errors.InvalidAddress();
        }
        onChainQuotingDelegate = newOnChainQuotingDelegate;
        emit OnChainQuotingDelegateUpdated(
            newOnChainQuotingDelegate,
            oldOnChainQuotingDelegate
        );
    }

    function pauseQuotes() external {
        if (msg.sender != circuitBreaker && msg.sender != owner()) {
            revert Errors.InvalidSender();
        }
        _pause();
    }

    function unpauseQuotes() external {
        if (msg.sender != reverseCircuitBreaker && msg.sender != owner()) {
            revert Errors.InvalidSender();
        }
        _unpause();
    }

    function loan(
        uint256 loanId
    ) external view returns (DataTypesPeerToPeer.Loan memory _loan) {
        uint256 loansLen = _loans.length;
        if (loanId >= loansLen) {
            revert Errors.InvalidArrayIndex();
        }
        _loan = _loans[loanId];
    }

    function totalNumLoans() external view returns (uint256) {
        return _loans.length;
    }

    function getTokenBalancesAndLockedAmounts(
        address[] calldata tokens
    )
        external
        view
        returns (uint256[] memory balances, uint256[] memory _lockedAmounts)
    {
        uint256 tokensLen = tokens.length;
        if (tokensLen == 0) {
            revert Errors.InvalidArrayLength();
        }
        balances = new uint256[](tokensLen);
        _lockedAmounts = new uint256[](tokensLen);
        for (uint256 i; i < tokensLen; ) {
            if (tokens[i] == address(0)) {
                revert Errors.InvalidAddress();
            }
            balances[i] = IERC20Metadata(tokens[i]).balanceOf(address(this));
            _lockedAmounts[i] = lockedAmounts[tokens[i]];
            unchecked {
                ++i;
            }
        }
    }

    function totalNumSigners() external view returns (uint256) {
        return signers.length;
    }

    function transferOwnership(
        address _newOwnerProposal
    ) public override(Ownable2Step, ILenderVaultImpl) {
        if (
            _newOwnerProposal == address(this) ||
            _newOwnerProposal == pendingOwner() ||
            _newOwnerProposal == owner() ||
            isSigner[_newOwnerProposal]
        ) {
            revert Errors.InvalidNewOwnerProposal();
        }
        // @dev: access control check via super.transferOwnership()
        super.transferOwnership(_newOwnerProposal);
    }

    function owner()
        public
        view
        override(Ownable, ILenderVaultImpl)
        returns (address)
    {
        return super.owner();
    }

    function pendingOwner()
        public
        view
        override(Ownable2Step, ILenderVaultImpl)
        returns (address)
    {
        return super.pendingOwner();
    }

    function renounceOwnership() public pure override {
        revert Errors.Disabled();
    }

    function _createCollCompartment(
        address borrowerCompartmentImplementation,
        uint256 loanId
    ) internal returns (address collCompartment) {
        collCompartment = Clones.clone(borrowerCompartmentImplementation);
        IBaseCompartment(collCompartment).initialize(address(this), loanId);
    }

    function _senderCheckGateway() internal view {
        if (msg.sender != IAddressRegistry(addressRegistry).borrowerGateway()) {
            revert Errors.UnregisteredGateway();
        }
    }

    function _getLoanAndRepayAmount(
        uint256 netPledgeAmount,
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple,
        uint256 upfrontFeePctInBase
    ) internal view returns (uint256 loanAmount, uint256 repayAmount) {
        uint256 loanPerCollUnit;
        if (generalQuoteInfo.oracleAddr == address(0)) {
            loanPerCollUnit = quoteTuple.loanPerCollUnitOrLtv;
        } else {
            // arbitrage protection if LTV > 100% and no whitelist restriction
            if (
                quoteTuple.loanPerCollUnitOrLtv > Constants.BASE &&
                generalQuoteInfo.whitelistAddr == address(0)
            ) {
                revert Errors.LtvHigherThanMax();
            }
            (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) = IOracle(
                generalQuoteInfo.oracleAddr
            ).getRawPrices(
                    generalQuoteInfo.collToken,
                    generalQuoteInfo.loanToken
                );
            loanPerCollUnit =
                Math.mulDiv(
                    quoteTuple.loanPerCollUnitOrLtv,
                    collTokenPriceRaw *
                        10 **
                            IERC20Metadata(generalQuoteInfo.loanToken)
                                .decimals(),
                    loanTokenPriceRaw
                ) /
                Constants.BASE;
        }
        uint256 unscaledLoanAmount = loanPerCollUnit * netPledgeAmount;
        uint256 collTokenDecimals = IERC20Metadata(generalQuoteInfo.collToken)
            .decimals();

        // calculate loan amount
        loanAmount = unscaledLoanAmount / (10 ** collTokenDecimals);

        // calculate repay amount and interest rate factor only for loans
        if (upfrontFeePctInBase < Constants.BASE) {
            // calculate interest rate factor
            // @dev: custom typecasting rather than safecasting to catch when interest rate factor = 0
            int256 _interestRateFactor = int256(Constants.BASE) +
                quoteTuple.interestRatePctInBase;
            if (_interestRateFactor <= 0) {
                revert Errors.InvalidInterestRateFactor();
            }
            uint256 interestRateFactor = uint256(_interestRateFactor);

            // calculate repay amount
            repayAmount =
                Math.mulDiv(
                    unscaledLoanAmount,
                    interestRateFactor,
                    Constants.BASE
                ) /
                (10 ** collTokenDecimals);
        }
    }

    function _checkCircuitBreaker(
        address newCircuitBreaker,
        address oldCircuitBreaker
    ) internal view {
        if (
            newCircuitBreaker == oldCircuitBreaker ||
            newCircuitBreaker == owner() ||
            isSigner[newCircuitBreaker]
        ) {
            revert Errors.InvalidAddress();
        }
    }
}

// File: contracts/peer-to-peer/oracles/chainlink/ChainlinkArbitrumSequencerUSD.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {AggregatorV3Interface} from "../../interfaces/oracles/chainlink/AggregatorV3Interface.sol";
import {ChainlinkBase} from "./ChainlinkBase.sol";
import {Constants} from "../../../Constants.sol";
import {Errors} from "../../../Errors.sol";

/**
 * @dev supports oracles which are compatible with v2v3 or v3 interfaces
 */
contract ChainlinkArbitrumSequencerUSD is ChainlinkBase {
    address internal constant SEQUENCER_FEED =
        0xFdB631F5EE196F0ed6FAa767959853A9F217697D; // arbitrum sequencer feed
    uint256 internal constant ARB_USD_BASE_CURRENCY_UNIT = 1e8; // 8 decimals for USD based oracles

    constructor(
        address[] memory _tokenAddrs,
        address[] memory _oracleAddrs
    ) ChainlinkBase(_tokenAddrs, _oracleAddrs, ARB_USD_BASE_CURRENCY_UNIT) {} // solhint-disable no-empty-blocks

    function _checkAndReturnLatestRoundData(
        address oracleAddr
    ) internal view override returns (uint256 tokenPriceRaw) {
        (, int256 answer, uint256 startedAt, , ) = AggregatorV3Interface(
            SEQUENCER_FEED
        ).latestRoundData();
        // check if sequencer is live
        if (answer != 0) {
            revert Errors.SequencerDown();
        }
        // check if last restart was less than or equal grace period length
        if (startedAt + Constants.SEQUENCER_GRACE_PERIOD > block.timestamp) {
            revert Errors.GracePeriodNotOver();
        }
        tokenPriceRaw = super._checkAndReturnLatestRoundData(oracleAddr);
    }
}

// File: contracts/peer-to-peer/oracles/chainlink/ChainlinkBase.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {AggregatorV3Interface} from "../../interfaces/oracles/chainlink/AggregatorV3Interface.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Constants} from "../../../Constants.sol";
import {Errors} from "../../../Errors.sol";
import {IOracle} from "../../interfaces/IOracle.sol";

/**
 * @dev supports oracles which are compatible with v2v3 or v3 interfaces
 */
abstract contract ChainlinkBase is IOracle {
    // solhint-disable var-name-mixedcase
    uint256 public immutable BASE_CURRENCY_UNIT;
    mapping(address => address) public oracleAddrs;

    constructor(
        address[] memory _tokenAddrs,
        address[] memory _oracleAddrs,
        uint256 baseCurrencyUnit
    ) {
        uint256 tokenAddrsLength = _tokenAddrs.length;
        if (tokenAddrsLength == 0 || tokenAddrsLength != _oracleAddrs.length) {
            revert Errors.InvalidArrayLength();
        }
        uint8 oracleDecimals;
        uint256 version;
        for (uint256 i; i < tokenAddrsLength; ) {
            if (_tokenAddrs[i] == address(0) || _oracleAddrs[i] == address(0)) {
                revert Errors.InvalidAddress();
            }
            oracleDecimals = AggregatorV3Interface(_oracleAddrs[i]).decimals();
            if (10 ** oracleDecimals != baseCurrencyUnit) {
                revert Errors.InvalidOracleDecimals();
            }
            version = AggregatorV3Interface(_oracleAddrs[i]).version();
            if (version != 4) {
                revert Errors.InvalidOracleVersion();
            }
            oracleAddrs[_tokenAddrs[i]] = _oracleAddrs[i];
            unchecked {
                ++i;
            }
        }
        BASE_CURRENCY_UNIT = baseCurrencyUnit;
    }

    function getPrice(
        address collToken,
        address loanToken
    ) external view virtual returns (uint256 collTokenPriceInLoanToken) {
        (uint256 priceOfCollToken, uint256 priceOfLoanToken) = getRawPrices(
            collToken,
            loanToken
        );
        uint256 loanTokenDecimals = IERC20Metadata(loanToken).decimals();
        collTokenPriceInLoanToken = Math.mulDiv(
            priceOfCollToken,
            10 ** loanTokenDecimals,
            priceOfLoanToken
        );
    }

    function getRawPrices(
        address collToken,
        address loanToken
    )
        public
        view
        virtual
        returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw)
    {
        (collTokenPriceRaw, loanTokenPriceRaw) = (
            _getPriceOfToken(collToken),
            _getPriceOfToken(loanToken)
        );
    }

    function _getPriceOfToken(
        address token
    ) internal view virtual returns (uint256 tokenPriceRaw) {
        address oracleAddr = oracleAddrs[token];
        if (oracleAddr == address(0)) {
            revert Errors.NoOracle();
        }
        tokenPriceRaw = _checkAndReturnLatestRoundData(oracleAddr);
    }

    function _checkAndReturnLatestRoundData(
        address oracleAddr
    ) internal view virtual returns (uint256 tokenPriceRaw) {
        (
            uint80 roundId,
            int256 answer,
            ,
            uint256 updatedAt,
            uint80 answeredInRound
        ) = AggregatorV3Interface(oracleAddr).latestRoundData();
        if (
            roundId == 0 ||
            answeredInRound < roundId ||
            answer < 1 ||
            updatedAt > block.timestamp ||
            updatedAt + Constants.MAX_PRICE_UPDATE_TIMESTAMP_DIVERGENCE <
            block.timestamp
        ) {
            revert Errors.InvalidOracleAnswer();
        }
        tokenPriceRaw = uint256(answer);
    }
}

// File: contracts/peer-to-peer/oracles/chainlink/ChainlinkBasic.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {ChainlinkBase} from "./ChainlinkBase.sol";
import {Errors} from "../../../Errors.sol";

/**
 * @dev supports oracles which are compatible with v2v3 or v3 interfaces
 */
contract ChainlinkBasic is ChainlinkBase {
    // solhint-disable var-name-mixedcase
    address public immutable BASE_CURRENCY;

    constructor(
        address[] memory _tokenAddrs,
        address[] memory _oracleAddrs,
        address baseCurrency,
        uint256 baseCurrencyUnit
    ) ChainlinkBase(_tokenAddrs, _oracleAddrs, baseCurrencyUnit) {
        if (baseCurrency == address(0)) {
            revert Errors.InvalidAddress();
        }
        BASE_CURRENCY = baseCurrency;
    }

    function _getPriceOfToken(
        address token
    ) internal view virtual override returns (uint256 tokenPriceRaw) {
        tokenPriceRaw = token == BASE_CURRENCY
            ? BASE_CURRENCY_UNIT
            : super._getPriceOfToken(token);
    }
}

// File: contracts/peer-to-peer/oracles/chainlink/ChainlinkBasicWithWbtc.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {ChainlinkBasic} from "./ChainlinkBasic.sol";
import {Errors} from "../../../Errors.sol";

/**
 * @dev supports oracles which are compatible with v2v3 or v3 interfaces
 */
contract ChainlinkBasicWithWbtc is ChainlinkBasic {
    address internal constant WBTC_BTC_ORACLE =
        0xfdFD9C85aD200c506Cf9e21F1FD8dd01932FBB23;
    address internal constant BTC_USD_ORACLE =
        0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c;
    address internal constant WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
    uint256 internal constant WBTC_BASE_CURRENCY_UNIT = 1e8; // 8 decimals for USD based oracles

    constructor(
        address[] memory _tokenAddrs,
        address[] memory _oracleAddrs
    )
        ChainlinkBasic(_tokenAddrs, _oracleAddrs, WBTC, WBTC_BASE_CURRENCY_UNIT)
    {} // solhint-disable no-empty-blocks

    function _getPriceOfToken(
        address token
    ) internal view override returns (uint256 tokenPriceRaw) {
        if (token == BASE_CURRENCY) {
            uint256 answer1 = _checkAndReturnLatestRoundData(WBTC_BTC_ORACLE);
            uint256 answer2 = _checkAndReturnLatestRoundData(BTC_USD_ORACLE);
            tokenPriceRaw = (answer1 * answer2) / BASE_CURRENCY_UNIT;
        } else {
            tokenPriceRaw = super._getPriceOfToken(token);
        }
    }
}

// File: contracts/peer-to-peer/oracles/chainlink/OlympusOracle.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {IOlympus} from "../../interfaces/oracles/IOlympus.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {ChainlinkBasic} from "./ChainlinkBasic.sol";
import {Errors} from "../../../Errors.sol";

/**
 * @dev supports olympus gOhm oracles which are compatible with v2v3 or v3 interfaces
 * should only be utilized with eth based oracles, not usd-based oracles
 */
contract OlympusOracle is ChainlinkBasic {
    address internal constant GOHM_ADDR =
        0x0ab87046fBb341D058F17CBC4c1133F25a20a52f;
    uint256 internal constant SOHM_DECIMALS = 9;
    address internal constant ETH_OHM_ORACLE_ADDR =
        0x9a72298ae3886221820B1c878d12D872087D3a23;
    address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    uint256 internal constant GOHM_BASE_CURRENCY_UNIT = 1e18; // 18 decimals for ETH based oracles

    constructor(
        address[] memory _tokenAddrs,
        address[] memory _oracleAddrs
    ) ChainlinkBasic(_tokenAddrs, _oracleAddrs, WETH, GOHM_BASE_CURRENCY_UNIT) {
        oracleAddrs[GOHM_ADDR] = ETH_OHM_ORACLE_ADDR;
    }

    function getPrice(
        address collToken,
        address loanToken
    ) external view override returns (uint256 collTokenPriceInLoanToken) {
        if (collToken != GOHM_ADDR && loanToken != GOHM_ADDR) {
            revert Errors.NeitherTokenIsGOHM();
        }
        (uint256 priceOfCollToken, uint256 priceOfLoanToken) = (
            _getPriceOfToken(collToken),
            _getPriceOfToken(loanToken)
        );
        uint256 loanTokenDecimals = IERC20Metadata(loanToken).decimals();
        uint256 index = IOlympus(GOHM_ADDR).index();

        collTokenPriceInLoanToken = collToken == GOHM_ADDR
            ? Math.mulDiv(
                priceOfCollToken,
                (10 ** loanTokenDecimals) * index,
                priceOfLoanToken * (10 ** SOHM_DECIMALS)
            )
            : Math.mulDiv(
                priceOfCollToken,
                (10 ** loanTokenDecimals) * (10 ** SOHM_DECIMALS),
                priceOfLoanToken * index
            );
    }

    function getRawPrices(
        address collToken,
        address loanToken
    )
        public
        view
        override
        returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw)
    {
        if (collToken != GOHM_ADDR && loanToken != GOHM_ADDR) {
            revert Errors.NeitherTokenIsGOHM();
        }
        uint256 index = IOlympus(GOHM_ADDR).index();
        (collTokenPriceRaw, loanTokenPriceRaw) = (
            _getPriceOfToken(collToken),
            _getPriceOfToken(loanToken)
        );
        if (collToken == GOHM_ADDR) {
            collTokenPriceRaw = Math.mulDiv(
                collTokenPriceRaw,
                index,
                10 ** SOHM_DECIMALS
            );
        } else {
            loanTokenPriceRaw = Math.mulDiv(
                loanTokenPriceRaw,
                index,
                10 ** SOHM_DECIMALS
            );
        }
    }
}

// File: contracts/peer-to-peer/oracles/chainlink/UniV2Chainlink.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {IUniV2} from "../../interfaces/oracles/IUniV2.sol";
import {ChainlinkBasic} from "./ChainlinkBasic.sol";
import {Errors} from "../../../Errors.sol";

/**
 * @dev supports oracles which have one token which is a 50/50 LP token
 * compatible with v2v3 or v3 interfaces
 * should only be utilized with eth based oracles, not usd-based oracles
 */
contract UniV2Chainlink is ChainlinkBasic {
    uint256 internal immutable _tolerance; // tolerance must be an integer less than 10000 and greater than 0
    mapping(address => bool) public isLpToken;
    address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    uint256 internal constant UNI_V2_BASE_CURRENCY_UNIT = 1e18; // 18 decimals for ETH based oracles

    constructor(
        address[] memory _tokenAddrs,
        address[] memory _oracleAddrs,
        address[] memory _lpAddrs,
        uint256 _toleranceAmount
    )
        ChainlinkBasic(
            _tokenAddrs,
            _oracleAddrs,
            WETH,
            UNI_V2_BASE_CURRENCY_UNIT
        )
    {
        uint256 lpAddrsLen = _lpAddrs.length;
        if (lpAddrsLen == 0) {
            revert Errors.InvalidArrayLength();
        }
        if (_toleranceAmount >= 10000 || _toleranceAmount == 0) {
            revert Errors.InvalidOracleTolerance();
        }
        _tolerance = _toleranceAmount;
        for (uint256 i; i < lpAddrsLen; ) {
            if (_lpAddrs[i] == address(0)) {
                revert Errors.InvalidAddress();
            }
            isLpToken[_lpAddrs[i]] = true;
            unchecked {
                ++i;
            }
        }
    }

    function getPrice(
        address collToken,
        address loanToken
    ) external view override returns (uint256 collTokenPriceInLoanToken) {
        (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) = getRawPrices(
            collToken,
            loanToken
        );
        uint256 loanTokenDecimals = IERC20Metadata(loanToken).decimals();
        collTokenPriceInLoanToken = Math.mulDiv(
            collTokenPriceRaw,
            10 ** loanTokenDecimals,
            loanTokenPriceRaw
        );
    }

    function getRawPrices(
        address collToken,
        address loanToken
    )
        public
        view
        override
        returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw)
    {
        bool isCollTokenLpToken = isLpToken[collToken];
        bool isLoanTokenLpToken = isLpToken[loanToken];
        if (!isCollTokenLpToken && !isLoanTokenLpToken) {
            revert Errors.NoLpTokens();
        }
        collTokenPriceRaw = isCollTokenLpToken
            ? getLpTokenPrice(collToken)
            : _getPriceOfToken(collToken);
        loanTokenPriceRaw = isLoanTokenLpToken
            ? getLpTokenPrice(loanToken)
            : _getPriceOfToken(loanToken);
    }

    /**
     * @notice Returns the price of 1 "whole" LP token (in 1 base currency unit, e.g., 10**18) in ETH
     * @dev Since the uniswap reserves could be skewed in any direction by flash loans,
     * we need to calculate the "fair" reserve of each token in the pool using invariant K
     * and then calculate the price of each token in ETH using the oracle prices for each token
     * @param lpToken Address of LP token
     * @return lpTokenPriceInEth of LP token in ETH
     */
    function getLpTokenPrice(
        address lpToken
    ) public view returns (uint256 lpTokenPriceInEth) {
        // assign uint112 reserves to uint256 to also handle large k invariants
        (uint256 reserve0, uint256 reserve1, ) = IUniV2(lpToken).getReserves();
        if (reserve0 * reserve1 == 0) {
            revert Errors.ZeroReserve();
        }

        (address token0, address token1) = (
            IUniV2(lpToken).token0(),
            IUniV2(lpToken).token1()
        );
        uint256 totalLpSupply = IUniV2(lpToken).totalSupply();
        uint256 priceToken0 = _getPriceOfToken(token0);
        uint256 priceToken1 = _getPriceOfToken(token1);
        uint256 token0Decimals = IERC20Metadata(token0).decimals();
        uint256 token1Decimals = IERC20Metadata(token1).decimals();

        _reserveAndPriceCheck(
            reserve0,
            reserve1,
            priceToken0,
            priceToken1,
            token0Decimals,
            token1Decimals
        );

        // calculate fair LP token price based on "fair reserves" as described in
        // https://blog.alphaventuredao.io/fair-lp-token-pricing/
        // formula: p = 2 * sqrt(r0 * r1) * sqrt(p0) * sqrt(p1) / s
        // note: price is for 1 "whole" LP token unit, hence need to scale up by LP token decimals;
        // need to divide by sqrt reserve decimals to cancel out units of invariant k
        // IMPORTANT: while formula is robust against typical flashloan skews, lenders should use this
        // oracle with caution and take into account skew scenarios when setting their LTVs
        lpTokenPriceInEth = Math.mulDiv(
            2 * Math.sqrt(reserve0 * reserve1),
            Math.sqrt(priceToken0 * priceToken1) * UNI_V2_BASE_CURRENCY_UNIT,
            totalLpSupply *
                Math.sqrt(10 ** token0Decimals * 10 ** token1Decimals)
        );
    }

    /**
     * @notice function checks that price from reserves is within tolerance of price from oracle
     * @dev This function is needed because a one-sided donation and sync can skew the fair reserve
     * calculation above. This function checks that the price from reserves is within a tolerance
     * @param reserve0 Reserve of token0
     * @param reserve1 Reserve of token1
     * @param priceToken0 Price of token0 from oracle
     * @param priceToken1 Price of token1 from oracle
     * @param token0Decimals Decimals of token0
     * @param token1Decimals Decimals of token1
     */
    function _reserveAndPriceCheck(
        uint256 reserve0,
        uint256 reserve1,
        uint256 priceToken0,
        uint256 priceToken1,
        uint256 token0Decimals,
        uint256 token1Decimals
    ) internal view {
        uint256 priceFromReserves = (reserve0 * 10 ** token1Decimals) /
            reserve1;
        uint256 priceFromOracle = (priceToken1 * 10 ** token0Decimals) /
            priceToken0;

        if (
            priceFromReserves >
            ((10000 + _tolerance) * priceFromOracle) / 10000 ||
            priceFromReserves < ((10000 - _tolerance) * priceFromOracle) / 10000
        ) {
            revert Errors.ReserveRatiosSkewedFromOraclePrice();
        }
    }
}

// File: contracts/peer-to-peer/oracles/custom/DsEthOracle.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {OracleLibrary} from "../uniswap/OracleLibrary.sol";
import {ChainlinkBase} from "../chainlink/ChainlinkBase.sol";
import {Errors} from "../../../Errors.sol";
import {TwapGetter} from "../uniswap/TwapGetter.sol";
import {IDSETH} from "../../interfaces/oracles/IDSETH.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev custom oracle for ds-eth
 */
contract DsEthOracle is ChainlinkBase, TwapGetter {
    // must be paired with WETH and only allow components within ds eth to use TWAP
    mapping(address => address) public uniV3PairAddrs;
    uint256 internal immutable _tolerance; // tolerance must be an integer less than 10000 and greater than 0

    address internal constant DS_ETH =
        0x341c05c0E9b33C0E38d64de76516b2Ce970bB3BE;
    address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
    uint256 internal constant INDEX_COOP_BASE_CURRENCY_UNIT = 1e18; // 18 decimals for ETH based oracles
    uint32 internal immutable _twapInterval; // in seconds (e.g. 1 hour = 3600 seconds)

    constructor(
        address[] memory _tokenAddrs,
        address[] memory _oracleAddrs,
        address[] memory _uniswapV3PairAddrs,
        uint32 twapInterval,
        uint256 tolerance
    ) ChainlinkBase(_tokenAddrs, _oracleAddrs, INDEX_COOP_BASE_CURRENCY_UNIT) {
        if (tolerance >= 10000 || tolerance == 0) {
            revert Errors.InvalidOracleTolerance();
        }
        _tolerance = tolerance;
        // min 30 minute twap interval
        if (twapInterval < 30 minutes) {
            revert Errors.TooShortTwapInterval();
        }
        _twapInterval = twapInterval;

        // in future could be possible that all constituents are chainlink compatible
        // so _uniswapV3PairAddrs.length == 0 is allowed, hence no length == 0 check
        address token1;
        for (uint256 i; i < _uniswapV3PairAddrs.length; ) {
            if (_uniswapV3PairAddrs[i] == address(0)) {
                revert Errors.InvalidAddress();
            }
            // try could also pass if you passed in uni v2 pair address
            // though should later fail when trying to price in future
            // care must be taken not to pass in uni v2 pair address
            try IUniswapV3Pool(_uniswapV3PairAddrs[i]).token0() returns (
                address token0
            ) {
                token1 = IUniswapV3Pool(_uniswapV3PairAddrs[i]).token1();
                // must have one token weth and other token component in ds eth
                if (
                    !(token0 == WETH && IDSETH(DS_ETH).isComponent(token1)) &&
                    !(token1 == WETH && IDSETH(DS_ETH).isComponent(token0))
                ) {
                    revert Errors.InvalidAddress();
                }
                // store non weth token address as key with uni v3 pair address as value
                uniV3PairAddrs[
                    token0 == WETH ? token1 : token0
                ] = _uniswapV3PairAddrs[i];
            } catch {
                revert Errors.InvalidAddress();
            }
            unchecked {
                ++i;
            }
        }
    }

    function getPrice(
        address collToken,
        address loanToken
    ) external view override returns (uint256 collTokenPriceInLoanToken) {
        // must have at least one token is DS_ETH to use this oracle
        (uint256 priceOfCollToken, uint256 priceOfLoanToken) = getRawPrices(
            collToken,
            loanToken
        );
        uint256 loanTokenDecimals = (loanToken == WETH || loanToken == DS_ETH)
            ? 18
            : IERC20Metadata(loanToken).decimals();
        collTokenPriceInLoanToken =
            (priceOfCollToken * 10 ** loanTokenDecimals) /
            priceOfLoanToken;
    }

    function getRawPrices(
        address collToken,
        address loanToken
    )
        public
        view
        override
        returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw)
    {
        // must have at least one token is DS_ETH to use this oracle
        if (collToken != DS_ETH && loanToken != DS_ETH) {
            revert Errors.NoDsEth();
        }
        (collTokenPriceRaw, loanTokenPriceRaw) = (
            _getPriceOfToken(collToken),
            _getPriceOfToken(loanToken)
        );
    }

    function _getPriceOfToken(
        address token
    ) internal view virtual override returns (uint256 tokenPriceRaw) {
        // note: if token is not WETH or DS_ETH, then will revert if not a chainlink oracle
        // this is by design, even if that address has a TWAP, it will not be used
        // except only when calculating ds eth price to minimize risk
        // i.e. if stakewise eth has uni v3 address but no chainlink address, and lender
        // tries to use stakewise eth as loan and ds eth as collateral, then revert

        // @dev: no use of nested ternary operator for npx hardhat compatibility reasons
        if (token == WETH) {
            tokenPriceRaw = BASE_CURRENCY_UNIT;
        } else {
            tokenPriceRaw = token == DS_ETH
                ? _getDsEthPrice()
                : super._getPriceOfToken(token);
        }
    }

    function _getDsEthPrice() internal view returns (uint256 dsEthPriceRaw) {
        address[] memory components = IDSETH(DS_ETH).getComponents();
        address currComponent;
        uint256 currComponentPrice;
        uint256 totalPriceUniCumSum;
        for (uint256 i; i < components.length; ) {
            currComponent = components[i];
            if (
                oracleAddrs[currComponent] == address(0) &&
                uniV3PairAddrs[currComponent] == address(0)
            ) {
                // if component has no oracle and no uni v3 pair, then revert
                revert Errors.NoOracle();
            }
            // always try to use chainlink oracle if available even if also had uni v3 pair passed in by mistake too
            currComponentPrice = oracleAddrs[currComponent] == address(0)
                ? _getTwapPrice(uniV3PairAddrs[currComponent])
                : _getPriceOfToken(currComponent);
            totalPriceUniCumSum += (currComponentPrice *
                IDSETH(DS_ETH).getTotalComponentRealUnits(currComponent));
            unchecked {
                ++i;
            }
        }
        dsEthPriceRaw = totalPriceUniCumSum / INDEX_COOP_BASE_CURRENCY_UNIT;
    }

    function _getTwapPrice(
        address uniV3PairAddr
    ) internal view returns (uint256 twapPriceRaw) {
        (address token0, address token1) = (
            IUniswapV3Pool(uniV3PairAddr).token0(),
            IUniswapV3Pool(uniV3PairAddr).token1()
        );
        (address inToken, address outToken) = (
            token0 == WETH ? token1 : token0,
            token1 == WETH ? token1 : token0
        );
        twapPriceRaw = getTwap(inToken, outToken, _twapInterval, uniV3PairAddr);
        (, int24 tick, , , , , ) = IUniswapV3Pool(uniV3PairAddr).slot0();

        uint256 spotPrice = OracleLibrary.getQuoteAtTick(
            tick,
            SafeCast.toUint128(10 ** IERC20Metadata(inToken).decimals()),
            inToken,
            outToken
        );

        // if twap price exceeds threshold from spot proxy price, then revert
        if (
            twapPriceRaw > ((10000 + _tolerance) * spotPrice) / 10000 ||
            twapPriceRaw < ((10000 - _tolerance) * spotPrice) / 10000
        ) {
            revert Errors.TwapExceedsThreshold();
        }
    }
}

// File: contracts/peer-to-peer/oracles/uniswap/FullMath.sol



// SPDX-License-Identifier: MIT
/* solhint-disable */
pragma solidity ^0.8.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = a * b
            // Compute the product mod 2**256 and mod 2**256 - 1
            // then 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(a, b, not(0))
                prod0 := mul(a, b)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division
            if (prod1 == 0) {
                require(denominator > 0);
                assembly {
                    result := div(prod0, denominator)
                }
                return result;
            }

            // 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]
            // Compute remainder using mulmod
            uint256 remainder;
            assembly {
                remainder := mulmod(a, b, denominator)
            }
            // Subtract 256 bit number from 512 bit number
            assembly {
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator
            // Compute largest power of two divisor of denominator.
            // Always >= 1.
            uint256 twos = (0 - denominator) & denominator;
            // Divide denominator by power of two
            assembly {
                denominator := div(denominator, twos)
            }

            // Divide [prod1 prod0] by the factors of two
            assembly {
                prod0 := div(prod0, twos)
            }
            // Shift in bits from prod1 into prod0. For this we need
            // to flip `twos` such that it is 2**256 / twos.
            // If twos is zero, then it becomes one
            assembly {
                twos := add(div(sub(0, twos), twos), 1)
            }
            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
            // correct for four bits. That is, denominator * inv = 1 mod 2**4
            uint256 inv = (3 * denominator) ^ 2;
            // Now use 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.
            inv *= 2 - denominator * inv; // inverse mod 2**8
            inv *= 2 - denominator * inv; // inverse mod 2**16
            inv *= 2 - denominator * inv; // inverse mod 2**32
            inv *= 2 - denominator * inv; // inverse mod 2**64
            inv *= 2 - denominator * inv; // inverse mod 2**128
            inv *= 2 - denominator * inv; // 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 precoditions 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 * inv;
            return result;
        }
    }
}

// File: contracts/peer-to-peer/oracles/uniswap/OracleLibrary.sol



// SPDX-License-Identifier: MIT
/* solhint-disable */
pragma solidity ^0.8.0;

import {FullMath} from "./FullMath.sol"; // cannot import from @uniswap due to incompatible versions
import {TickMath} from "./TickMath.sol"; // cannot import from @uniswap due to incompatible versions

/// @title Oracle library
/// @notice Provides functions to integrate with V3 pool oracle
library OracleLibrary {
    /// @notice Given a tick and a token amount, calculates the amount of token received in exchange
    /// @param tick Tick value used to calculate the quote
    /// @param baseAmount Amount of token to be converted
    /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination
    /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination
    /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken
    function getQuoteAtTick(
        int24 tick,
        uint128 baseAmount,
        address baseToken,
        address quoteToken
    ) internal pure returns (uint256 quoteAmount) {
        uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);

        // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself
        if (sqrtRatioX96 <= type(uint128).max) {
            uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
                : FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
        } else {
            uint256 ratioX128 = FullMath.mulDiv(
                sqrtRatioX96,
                sqrtRatioX96,
                1 << 64
            );
            quoteAmount = baseToken < quoteToken
                ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
                : FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
        }
    }
}

// File: contracts/peer-to-peer/oracles/uniswap/TickMath.sol



// SPDX-License-Identifier: GPL-2.0-or-later
/* solhint-disable */
pragma solidity ^0.8.0;

/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
    error T();
    error R();

    /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
    int24 internal constant MIN_TICK = -887272;
    /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
    int24 internal constant MAX_TICK = -MIN_TICK;

    /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
    uint160 internal constant MIN_SQRT_RATIO = 4295128739;
    /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
    uint160 internal constant MAX_SQRT_RATIO =
        1461446703485210103287273052203988822378723970342;

    /// @notice Calculates sqrt(1.0001^tick) * 2^96
    /// @dev Throws if |tick| > max tick
    /// @param tick The input tick for the above formula
    /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
    /// at the given tick
    function getSqrtRatioAtTick(
        int24 tick
    ) internal pure returns (uint160 sqrtPriceX96) {
        unchecked {
            uint256 absTick = tick < 0
                ? uint256(-int256(tick))
                : uint256(int256(tick));
            if (absTick > uint256(int256(MAX_TICK))) revert T();

            uint256 ratio = absTick & 0x1 != 0
                ? 0xfffcb933bd6fad37aa2d162d1a594001
                : 0x100000000000000000000000000000000;
            if (absTick & 0x2 != 0)
                ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
            if (absTick & 0x4 != 0)
                ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
            if (absTick & 0x8 != 0)
                ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
            if (absTick & 0x10 != 0)
                ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
            if (absTick & 0x20 != 0)
                ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
            if (absTick & 0x40 != 0)
                ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
            if (absTick & 0x80 != 0)
                ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
            if (absTick & 0x100 != 0)
                ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
            if (absTick & 0x200 != 0)
                ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
            if (absTick & 0x400 != 0)
                ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
            if (absTick & 0x800 != 0)
                ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
            if (absTick & 0x1000 != 0)
                ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
            if (absTick & 0x2000 != 0)
                ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
            if (absTick & 0x4000 != 0)
                ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
            if (absTick & 0x8000 != 0)
                ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
            if (absTick & 0x10000 != 0)
                ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
            if (absTick & 0x20000 != 0)
                ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
            if (absTick & 0x40000 != 0)
                ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
            if (absTick & 0x80000 != 0)
                ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;

            if (tick > 0) ratio = type(uint256).max / ratio;

            // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
            // we then downcast because we know the result always fits within 160 bits due to our tick input constraint
            // we round up in the division so getTickAtSqrtRatio of the output price is always consistent
            sqrtPriceX96 = uint160(
                (ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)
            );
        }
    }
}

// File: contracts/peer-to-peer/oracles/uniswap/TwapGetter.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {FixedPoint96} from "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
import {IUniswapV3Factory} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";
import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {FullMath} from "./FullMath.sol"; // cannot import from @uniswap due to incompatible versions
import {TickMath} from "./TickMath.sol"; // cannot import from @uniswap due to incompatible versions
import {Errors} from "../../../Errors.sol";
import {ITwapGetter} from "../../interfaces/oracles/uniswap/ITwapGetter.sol";

abstract contract TwapGetter is ITwapGetter {
    // inToken: `1 unit of inToken`
    // outToken: resulting units of outToken (in "base unit" of outTokens, e.g. if 427518869723400 and outToken is eth, then this corresponds to 427518869723400/10^18)
    function getTwap(
        address inToken,
        address outToken,
        uint32 twapInterval,
        address uniswapV3Pool
    ) public view returns (uint256 twap) {
        (address token0, address token1) = inToken < outToken
            ? (inToken, outToken)
            : (outToken, inToken);

        // note: this returns the sqrt price
        uint160 sqrtPriceX96 = getSqrtTwapX96(uniswapV3Pool, twapInterval);

        // note: this returns the price in base 2**96 and denominated in token1
        // i.e., `1 unit of token0` corresponds to `sqrtPriceX96 units (divided by 2**96) of token1`
        uint256 priceX96 = FullMath.mulDiv(
            sqrtPriceX96,
            sqrtPriceX96,
            FixedPoint96.Q96
        );

        twap = inToken == token0
            ? FullMath.mulDiv(
                priceX96,
                10 ** IERC20Metadata(token0).decimals(),
                FixedPoint96.Q96
            )
            : FullMath.mulDiv(
                FixedPoint96.Q96,
                10 ** IERC20Metadata(token1).decimals(),
                priceX96
            );
    }

    function getSqrtTwapX96(
        address uniswapV3Pool,
        uint32 twapInterval
    ) public view returns (uint160 sqrtPriceX96) {
        if (twapInterval == 0) {
            (sqrtPriceX96, , , , , , ) = IUniswapV3Pool(uniswapV3Pool).slot0();
        } else {
            uint32[] memory secondsAgo = new uint32[](2);

            // @dev: revert if twapInterval doesn't fit into smaller int32
            if (twapInterval > uint32(type(int32).max)) {
                revert Errors.TooLongTwapInterval();
            }

            secondsAgo[0] = twapInterval;
            secondsAgo[1] = 0;
            (int56[] memory tickCumulatives, ) = IUniswapV3Pool(uniswapV3Pool)
                .observe(secondsAgo);

            int56 tickCumulativesDelta = tickCumulatives[1] -
                tickCumulatives[0];
            int24 averageTick = SafeCast.toInt24(
                tickCumulativesDelta / int32(twapInterval)
            );

            sqrtPriceX96 = TickMath.getSqrtRatioAtTick(averageTick);
        }
    }
}

// File: contracts/peer-to-peer/policyManagers/BasicQuotePolicyManager.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {DataTypesPeerToPeer} from "../DataTypesPeerToPeer.sol";
import {DataTypesBasicPolicies} from "./DataTypesBasicPolicies.sol";
import {Constants} from "../../Constants.sol";
import {Errors} from "../../Errors.sol";
import {IAddressRegistry} from "../interfaces/IAddressRegistry.sol";
import {ILenderVaultImpl} from "../interfaces/ILenderVaultImpl.sol";
import {IQuotePolicyManager} from "../interfaces/policyManagers/IQuotePolicyManager.sol";

contract BasicQuotePolicyManager is IQuotePolicyManager {
    mapping(address => DataTypesBasicPolicies.GlobalPolicy)
        internal _globalQuotingPolicies;
    mapping(address => mapping(address => mapping(address => DataTypesBasicPolicies.PairPolicy)))
        internal _pairQuotingPolicies;
    mapping(address => bool) internal _hasGlobalQuotingPolicy;
    mapping(address => mapping(address => mapping(address => bool)))
        internal _hasPairQuotingPolicy;
    address public immutable addressRegistry;

    constructor(address _addressRegistry) {
        addressRegistry = _addressRegistry;
    }

    // @dev: When no global policy is set (default case), all pairs are automatically blocked except
    // for those where a pair policy is explicitly set. In the case where a global policy is set,
    // all pairs are assumed to be allowed (no blocking).
    function setGlobalPolicy(
        address lenderVault,
        bytes calldata globalPolicyData
    ) external {
        // @dev: global policy applies across all pairs;
        // note: pair policies (if defined) take precedence over global policy
        _checkIsVaultAndSenderIsOwner(lenderVault);
        if (globalPolicyData.length > 0) {
            DataTypesBasicPolicies.GlobalPolicy memory globalPolicy = abi
                .decode(
                    globalPolicyData,
                    (DataTypesBasicPolicies.GlobalPolicy)
                );
            DataTypesBasicPolicies.GlobalPolicy
                memory currGlobalPolicy = _globalQuotingPolicies[lenderVault];
            if (
                globalPolicy.requiresOracle ==
                currGlobalPolicy.requiresOracle &&
                _equalQuoteBounds(
                    globalPolicy.quoteBounds,
                    currGlobalPolicy.quoteBounds
                )
            ) {
                revert Errors.PolicyAlreadySet();
            }
            _checkNewQuoteBounds(globalPolicy.quoteBounds);
            if (!_hasGlobalQuotingPolicy[lenderVault]) {
                _hasGlobalQuotingPolicy[lenderVault] = true;
            }
            _globalQuotingPolicies[lenderVault] = globalPolicy;
        } else {
            if (!_hasGlobalQuotingPolicy[lenderVault]) {
                revert Errors.NoPolicyToDelete();
            }
            delete _hasGlobalQuotingPolicy[lenderVault];
            delete _globalQuotingPolicies[lenderVault];
        }
        emit GlobalPolicySet(lenderVault, globalPolicyData);
    }

    // @dev: If no global policy is set, then setting a pair policy allows one to explicitly unblock a specific pair;
    // in the other case where a global policy is set, setting a pair policy allows overwriting global policy
    // parameters as well as overwriting minimum signer threshold requirements.
    function setPairPolicy(
        address lenderVault,
        address collToken,
        address loanToken,
        bytes calldata pairPolicyData
    ) external {
        // @dev: pair policies (if defined) take precedence over global policy
        _checkIsVaultAndSenderIsOwner(lenderVault);
        if (collToken == address(0) || loanToken == address(0)) {
            revert Errors.InvalidAddress();
        }
        mapping(address => bool)
            storage _hasSingleQuotingPolicy = _hasPairQuotingPolicy[
                lenderVault
            ][collToken];
        if (pairPolicyData.length > 0) {
            DataTypesBasicPolicies.PairPolicy memory singlePolicy = abi.decode(
                pairPolicyData,
                (DataTypesBasicPolicies.PairPolicy)
            );
            DataTypesBasicPolicies.PairPolicy
                memory currSinglePolicy = _pairQuotingPolicies[lenderVault][
                    collToken
                ][loanToken];
            if (
                singlePolicy.requiresOracle ==
                currSinglePolicy.requiresOracle &&
                singlePolicy.minNumOfSignersOverwrite ==
                currSinglePolicy.minNumOfSignersOverwrite &&
                singlePolicy.minLoanPerCollUnit ==
                currSinglePolicy.minLoanPerCollUnit &&
                singlePolicy.maxLoanPerCollUnit ==
                currSinglePolicy.maxLoanPerCollUnit &&
                _equalQuoteBounds(
                    singlePolicy.quoteBounds,
                    currSinglePolicy.quoteBounds
                )
            ) {
                revert Errors.PolicyAlreadySet();
            }
            _checkNewQuoteBounds(singlePolicy.quoteBounds);
            if (
                singlePolicy.minLoanPerCollUnit == 0 ||
                singlePolicy.minLoanPerCollUnit >
                singlePolicy.maxLoanPerCollUnit
            ) {
                revert Errors.InvalidLoanPerCollBounds();
            }
            if (!_hasSingleQuotingPolicy[loanToken]) {
                _hasSingleQuotingPolicy[loanToken] = true;
            }
            _pairQuotingPolicies[lenderVault][collToken][
                loanToken
            ] = singlePolicy;
        } else {
            if (!_hasSingleQuotingPolicy[loanToken]) {
                revert Errors.NoPolicyToDelete();
            }
            delete _hasSingleQuotingPolicy[loanToken];
            delete _pairQuotingPolicies[lenderVault][collToken][loanToken];
        }
        emit PairPolicySet(lenderVault, collToken, loanToken, pairPolicyData);
    }

    function isAllowed(
        address /*borrower*/,
        address lenderVault,
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple
    )
        external
        view
        returns (bool _isAllowed, uint256 minNumOfSignersOverwrite)
    {
        DataTypesBasicPolicies.GlobalPolicy
            memory globalPolicy = _globalQuotingPolicies[lenderVault];
        bool hasPairPolicy = _hasPairQuotingPolicy[lenderVault][
            generalQuoteInfo.collToken
        ][generalQuoteInfo.loanToken];
        if (!_hasGlobalQuotingPolicy[lenderVault] && !hasPairPolicy) {
            return (false, 0);
        }

        // @dev: pair policy (if defined) takes precedence over global policy
        bool hasOracle = generalQuoteInfo.oracleAddr != address(0);
        bool checkLoanPerColl;
        bool requiresOracle;
        uint256[2] memory minMaxLoanPerCollUnit;
        DataTypesBasicPolicies.QuoteBounds memory quoteBounds;
        if (hasPairPolicy) {
            DataTypesBasicPolicies.PairPolicy
                memory singlePolicy = _pairQuotingPolicies[lenderVault][
                    generalQuoteInfo.collToken
                ][generalQuoteInfo.loanToken];
            quoteBounds = singlePolicy.quoteBounds;
            minMaxLoanPerCollUnit[0] = singlePolicy.minLoanPerCollUnit;
            minMaxLoanPerCollUnit[1] = singlePolicy.maxLoanPerCollUnit;
            requiresOracle = singlePolicy.requiresOracle;
            minNumOfSignersOverwrite = singlePolicy.minNumOfSignersOverwrite;
            checkLoanPerColl = !hasOracle;
        } else {
            quoteBounds = globalPolicy.quoteBounds;
            requiresOracle = globalPolicy.requiresOracle;
        }

        if (requiresOracle && !hasOracle) {
            return (false, 0);
        }

        return (
            _isAllowedWithBounds(
                quoteBounds,
                minMaxLoanPerCollUnit,
                quoteTuple,
                generalQuoteInfo.earliestRepayTenor,
                hasOracle,
                checkLoanPerColl
            ),
            minNumOfSignersOverwrite
        );
    }

    function globalQuotingPolicy(
        address lenderVault
    ) external view returns (DataTypesBasicPolicies.GlobalPolicy memory) {
        if (!_hasGlobalQuotingPolicy[lenderVault]) {
            revert Errors.NoPolicy();
        }
        return _globalQuotingPolicies[lenderVault];
    }

    function pairQuotingPolicy(
        address lenderVault,
        address collToken,
        address loanToken
    ) external view returns (DataTypesBasicPolicies.PairPolicy memory) {
        if (!_hasPairQuotingPolicy[lenderVault][collToken][loanToken]) {
            revert Errors.NoPolicy();
        }
        return _pairQuotingPolicies[lenderVault][collToken][loanToken];
    }

    function hasGlobalQuotingPolicy(
        address lenderVault
    ) external view returns (bool) {
        return _hasGlobalQuotingPolicy[lenderVault];
    }

    function hasPairQuotingPolicy(
        address lenderVault,
        address collToken,
        address loanToken
    ) external view returns (bool) {
        return _hasPairQuotingPolicy[lenderVault][collToken][loanToken];
    }

    function _checkIsVaultAndSenderIsOwner(address lenderVault) internal view {
        if (!IAddressRegistry(addressRegistry).isRegisteredVault(lenderVault)) {
            revert Errors.UnregisteredVault();
        }
        if (ILenderVaultImpl(lenderVault).owner() != msg.sender) {
            revert Errors.InvalidSender();
        }
    }

    function _equalQuoteBounds(
        DataTypesBasicPolicies.QuoteBounds memory quoteBounds1,
        DataTypesBasicPolicies.QuoteBounds memory quoteBounds2
    ) internal pure returns (bool isEqual) {
        if (
            quoteBounds1.minTenor == quoteBounds2.minTenor &&
            quoteBounds1.maxTenor == quoteBounds2.maxTenor &&
            quoteBounds1.minFee == quoteBounds2.minFee &&
            quoteBounds1.minApr == quoteBounds2.minApr &&
            quoteBounds1.minLtv == quoteBounds2.minLtv &&
            quoteBounds1.maxLtv == quoteBounds2.maxLtv
        ) {
            isEqual = true;
        }
    }

    function _checkNewQuoteBounds(
        DataTypesBasicPolicies.QuoteBounds memory quoteBounds
    ) internal pure {
        // @dev: allow minTenor == 0 to enable swaps
        if (quoteBounds.minTenor > quoteBounds.maxTenor) {
            revert Errors.InvalidTenorBounds();
        }
        if (
            quoteBounds.minLtv == 0 || quoteBounds.minLtv > quoteBounds.maxLtv
        ) {
            revert Errors.InvalidLtvBounds();
        }
        if (quoteBounds.minApr + int(Constants.BASE) <= 0) {
            revert Errors.InvalidMinApr();
        }
        // @dev: if minFee = BASE, then only swaps will be allowed
        if (quoteBounds.minFee > Constants.BASE) {
            revert Errors.InvalidMinFee();
        }
    }

    function _isAllowedWithBounds(
        DataTypesBasicPolicies.QuoteBounds memory quoteBounds,
        uint256[2] memory minMaxLoanPerCollUnit,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple,
        uint256 earliestRepayTenor,
        bool checkLtv,
        bool checkLoanPerColl
    ) internal pure returns (bool) {
        if (
            quoteTuple.tenor < quoteBounds.minTenor ||
            quoteTuple.tenor > quoteBounds.maxTenor
        ) {
            return false;
        }

        if (checkLtv) {
            // @dev: check either against LTV bounds
            if (
                quoteTuple.loanPerCollUnitOrLtv < quoteBounds.minLtv ||
                quoteTuple.loanPerCollUnitOrLtv > quoteBounds.maxLtv
            ) {
                return false;
            }
        } else if (
            // @dev: only check against absolute loan-per-coll bounds on pair policy and if no oracle
            checkLoanPerColl &&
            (quoteTuple.loanPerCollUnitOrLtv < minMaxLoanPerCollUnit[0] ||
                quoteTuple.loanPerCollUnitOrLtv > minMaxLoanPerCollUnit[1])
        ) {
            return false;
        }

        // @dev: if tenor is zero then tx is swap and no need to check apr
        if (quoteTuple.tenor > 0) {
            int256 apr = (quoteTuple.interestRatePctInBase *
                SafeCast.toInt256(Constants.YEAR_IN_SECONDS)) /
                SafeCast.toInt256(quoteTuple.tenor);
            if (apr < quoteBounds.minApr) {
                return false;
            }
            // @dev: disallow if negative apr and earliest repay is below bound
            if (
                apr < 0 &&
                earliestRepayTenor < quoteBounds.minEarliestRepayTenor
            ) {
                return false;
            }

            // @dev: only check upfront fee for loans (can skip for swaps where tenor=0)
            if (quoteTuple.upfrontFeePctInBase < quoteBounds.minFee) {
                return false;
            }
        }

        return true;
    }
}

// File: contracts/peer-to-peer/policyManagers/DataTypesBasicPolicies.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

library DataTypesBasicPolicies {
    struct QuoteBounds {
        // Allowed minimum tenor for the quote (in seconds)
        uint32 minTenor;
        // Allowed maximum tenor for the quote (in seconds)
        uint32 maxTenor;
        // Allowed minimum fee for the quote (in BASE)
        uint80 minFee;
        // Allowed minimum APR for the quote (in BASE)
        int80 minApr;
        // Allowed minimum earliest repay tenor
        uint32 minEarliestRepayTenor;
        // Allowed minimum LTV for the quote
        uint128 minLtv;
        // Allowed maximum LTV for the quote
        uint128 maxLtv;
    }

    struct GlobalPolicy {
        // Applicable general bounds
        QuoteBounds quoteBounds;
        // Flag indicating if an oracle is required for the pair
        bool requiresOracle;
    }

    struct PairPolicy {
        // Applicable general bounds
        QuoteBounds quoteBounds;
        // Allowed minimum loan per collateral unit or LTV for the quote
        uint128 minLoanPerCollUnit;
        // Allowed maximum loan per collateral unit or LTV for the quote
        uint128 maxLoanPerCollUnit;
        // Flag indicating if an oracle is required for the pair
        bool requiresOracle;
        // Minimum number of signers required for the pair (if zero ignored, otherwise overwrites vault min signers)
        // @dev: can overwrite signer threshold to be lower or higher than vault min signers
        uint8 minNumOfSignersOverwrite;
    }
}

// File: contracts/peer-to-peer/QuoteHandler.sol



// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;

import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Constants} from "../Constants.sol";
import {DataTypesPeerToPeer} from "./DataTypesPeerToPeer.sol";
import {Errors} from "../Errors.sol";
import {Helpers} from "../Helpers.sol";
import {IAddressRegistry} from "./interfaces/IAddressRegistry.sol";
import {ILenderVaultImpl} from "./interfaces/ILenderVaultImpl.sol";
import {IQuoteHandler} from "./interfaces/IQuoteHandler.sol";
import {IQuotePolicyManager} from "./interfaces/policyManagers/IQuotePolicyManager.sol";

contract QuoteHandler is IQuoteHandler {
    using ECDSA for bytes32;

    address public immutable addressRegistry;
    mapping(address => uint256) public offChainQuoteNonce;
    mapping(address => mapping(bytes32 => bool))
        public offChainQuoteIsInvalidated;
    mapping(address => mapping(bytes32 => bool)) public isOnChainQuote;
    mapping(bytes32 => bool) public isPublishedOnChainQuote;
    mapping(bytes32 => uint256) public publishedOnChainQuoteValidUntil;
    mapping(address => address) public quotePolicyManagerForVault;
    mapping(address => DataTypesPeerToPeer.OnChainQuoteInfo[])
        internal _onChainQuoteHistory;

    constructor(address _addressRegistry) {
        if (_addressRegistry == address(0)) {
            revert Errors.InvalidAddress();
        }
        addressRegistry = _addressRegistry;
    }

    function addOnChainQuote(
        address lenderVault,
        DataTypesPeerToPeer.OnChainQuote calldata onChainQuote
    ) external {
        _checkIsVaultAndSenderIsApproved(lenderVault, false);
        if (!_isValidOnChainQuote(onChainQuote)) {
            revert Errors.InvalidQuote();
        }
        mapping(bytes32 => bool)
            storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault];
        bytes32 onChainQuoteHash = _hashOnChainQuote(onChainQuote);
        if (isOnChainQuoteFromVault[onChainQuoteHash]) {
            revert Errors.OnChainQuoteAlreadyAdded();
        }
        // @dev: on-chain quote history is append only
        _onChainQuoteHistory[lenderVault].push(
            DataTypesPeerToPeer.OnChainQuoteInfo({
                quoteHash: onChainQuoteHash,
                validUntil: onChainQuote.generalQuoteInfo.validUntil
            })
        );
        isOnChainQuoteFromVault[onChainQuoteHash] = true;
        emit OnChainQuoteAdded(lenderVault, onChainQuote, onChainQuoteHash);
    }

    function updateOnChainQuote(
        address lenderVault,
        bytes32 oldOnChainQuoteHash,
        DataTypesPeerToPeer.OnChainQuote calldata newOnChainQuote
    ) external {
        _checkIsVaultAndSenderIsApproved(lenderVault, false);
        if (!_isValidOnChainQuote(newOnChainQuote)) {
            revert Errors.InvalidQuote();
        }
        mapping(bytes32 => bool)
            storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault];
        bytes32 newOnChainQuoteHash = _hashOnChainQuote(newOnChainQuote);
        // this check will catch the case where the old quote is the same as the new quote
        if (isOnChainQuoteFromVault[newOnChainQuoteHash]) {
            revert Errors.OnChainQuoteAlreadyAdded();
        }
        if (!isOnChainQuoteFromVault[oldOnChainQuoteHash]) {
            revert Errors.UnknownOnChainQuote();
        }
        // @dev: on-chain quote history is append only
        _onChainQuoteHistory[lenderVault].push(
            DataTypesPeerToPeer.OnChainQuoteInfo({
                quoteHash: newOnChainQuoteHash,
                validUntil: newOnChainQuote.generalQuoteInfo.validUntil
            })
        );
        isOnChainQuoteFromVault[oldOnChainQuoteHash] = false;
        emit OnChainQuoteDeleted(lenderVault, oldOnChainQuoteHash);

        isOnChainQuoteFromVault[newOnChainQuoteHash] = true;
        emit OnChainQuoteAdded(
            lenderVault,
            newOnChainQuote,
            newOnChainQuoteHash
        );
    }

    function deleteOnChainQuote(
        address lenderVault,
        bytes32 onChainQuoteHash
    ) external {
        _checkIsVaultAndSenderIsApproved(lenderVault, false);
        mapping(bytes32 => bool)
            storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault];
        if (!isOnChainQuoteFromVault[onChainQuoteHash]) {
            revert Errors.UnknownOnChainQuote();
        }
        isOnChainQuoteFromVault[onChainQuoteHash] = false;
        emit OnChainQuoteDeleted(lenderVault, onChainQuoteHash);
    }

    function copyPublishedOnChainQuote(
        address lenderVault,
        bytes32 onChainQuoteHash
    ) external {
        _checkIsVaultAndSenderIsApproved(lenderVault, false);
        mapping(bytes32 => bool)
            storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault];
        uint256 validUntil = publishedOnChainQuoteValidUntil[onChainQuoteHash];
        if (
            !isPublishedOnChainQuote[onChainQuoteHash] ||
            isOnChainQuoteFromVault[onChainQuoteHash] ||
            validUntil < block.timestamp
        ) {
            revert Errors.InvalidQuote();
        }
        // @dev: on-chain quote history is append only
        _onChainQuoteHistory[lenderVault].push(
            DataTypesPeerToPeer.OnChainQuoteInfo({
                quoteHash: onChainQuoteHash,
                validUntil: validUntil
            })
        );
        isOnChainQuoteFromVault[onChainQuoteHash] = true;
        emit OnChainQuoteCopied(lenderVault, onChainQuoteHash);
    }

    function publishOnChainQuote(
        DataTypesPeerToPeer.OnChainQuote calldata onChainQuote
    ) external {
        if (!_isValidOnChainQuote(onChainQuote)) {
            revert Errors.InvalidQuote();
        }
        bytes32 onChainQuoteHash = _hashOnChainQuote(onChainQuote);
        if (isPublishedOnChainQuote[onChainQuoteHash]) {
            revert Errors.AlreadyPublished();
        }
        isPublishedOnChainQuote[onChainQuoteHash] = true;
        publishedOnChainQuoteValidUntil[onChainQuoteHash] = onChainQuote
            .generalQuoteInfo
            .validUntil;
        emit OnChainQuotePublished(onChainQuote, onChainQuoteHash, msg.sender);
    }

    function incrementOffChainQuoteNonce(address lenderVault) external {
        _checkIsVaultAndSenderIsApproved(lenderVault, true);
        uint256 newNonce = offChainQuoteNonce[lenderVault] + 1;
        offChainQuoteNonce[lenderVault] = newNonce;
        emit OffChainQuoteNonceIncremented(lenderVault, newNonce);
    }

    function invalidateOffChainQuote(
        address lenderVault,
        bytes32 offChainQuoteHash
    ) external {
        _checkIsVaultAndSenderIsApproved(lenderVault, true);
        offChainQuoteIsInvalidated[lenderVault][offChainQuoteHash] = true;
        emit OffChainQuoteInvalidated(lenderVault, offChainQuoteHash);
    }

    function checkAndRegisterOnChainQuote(
        address borrower,
        address lenderVault,
        uint256 quoteTupleIdx,
        DataTypesPeerToPeer.OnChainQuote calldata onChainQuote
    ) external {
        if (quoteTupleIdx >= onChainQuote.quoteTuples.length) {
            revert Errors.InvalidArrayIndex();
        }
        // @dev: ignore returned minNumOfSignersOverwrite for on-chain quotes
        _checkSenderAndPolicyAndQuoteInfo(
            borrower,
            lenderVault,
            onChainQuote.generalQuoteInfo,
            onChainQuote.quoteTuples[quoteTupleIdx]
        );
        mapping(bytes32 => bool)
            storage isOnChainQuoteFromVault = isOnChainQuote[lenderVault];
        bytes32 onChainQuoteHash = _hashOnChainQuote(onChainQuote);
        if (!isOnChainQuoteFromVault[onChainQuoteHash]) {
            revert Errors.UnknownOnChainQuote();
        }
        if (onChainQuote.generalQuoteInfo.isSingleUse) {
            isOnChainQuoteFromVault[onChainQuoteHash] = false;
            emit OnChainQuoteInvalidated(lenderVault, onChainQuoteHash);
        }
        uint256 nextLoanIdx = ILenderVaultImpl(lenderVault).totalNumLoans();
        emit OnChainQuoteUsed(
            lenderVault,
            onChainQuoteHash,
            nextLoanIdx,
            quoteTupleIdx
        );
    }

    function checkAndRegisterOffChainQuote(
        address borrower,
        address lenderVault,
        DataTypesPeerToPeer.OffChainQuote calldata offChainQuote,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple,
        bytes32[] calldata proof
    ) external {
        uint256 minNumOfSignersOverwrite = _checkSenderAndPolicyAndQuoteInfo(
            borrower,
            lenderVault,
            offChainQuote.generalQuoteInfo,
            quoteTuple
        );
        if (offChainQuote.nonce < offChainQuoteNonce[lenderVault]) {
            revert Errors.InvalidQuote();
        }
        mapping(bytes32 => bool)
            storage offChainQuoteFromVaultIsInvalidated = offChainQuoteIsInvalidated[
                lenderVault
            ];
        bytes32 offChainQuoteHash = _hashOffChainQuote(
            offChainQuote,
            lenderVault
        );
        if (offChainQuoteFromVaultIsInvalidated[offChainQuoteHash]) {
            revert Errors.OffChainQuoteHasBeenInvalidated();
        }
        if (
            !_areValidSignatures(
                lenderVault,
                offChainQuoteHash,
                minNumOfSignersOverwrite,
                offChainQuote.compactSigs
            )
        ) {
            revert Errors.InvalidOffChainSignature();
        }

        bytes32 leaf = keccak256(
            bytes.concat(
                keccak256(
                    abi.encode(
                        quoteTuple.loanPerCollUnitOrLtv,
                        quoteTuple.interestRatePctInBase,
                        quoteTuple.upfrontFeePctInBase,
                        quoteTuple.tenor
                    )
                )
            )
        );
        if (!MerkleProof.verify(proof, offChainQuote.quoteTuplesRoot, leaf)) {
            revert Errors.InvalidOffChainMerkleProof();
        }
        if (offChainQuote.generalQuoteInfo.isSingleUse) {
            offChainQuoteFromVaultIsInvalidated[offChainQuoteHash] = true;
            emit OffChainQuoteInvalidated(lenderVault, offChainQuoteHash);
        }
        uint256 toBeRegisteredLoanId = ILenderVaultImpl(lenderVault)
            .totalNumLoans();
        emit OffChainQuoteUsed(
            lenderVault,
            offChainQuoteHash,
            toBeRegisteredLoanId,
            quoteTuple
        );
    }

    function updateQuotePolicyManagerForVault(
        address lenderVault,
        address newPolicyManagerAddress
    ) external {
        _checkIsVaultAndSenderIsApproved(lenderVault, true);
        if (newPolicyManagerAddress == address(0)) {
            delete quotePolicyManagerForVault[lenderVault];
        } else {
            if (
                IAddressRegistry(addressRegistry).whitelistState(
                    newPolicyManagerAddress
                ) !=
                DataTypesPeerToPeer.WhitelistState.QUOTE_POLICY_MANAGER ||
                newPolicyManagerAddress ==
                quotePolicyManagerForVault[lenderVault]
            ) {
                revert Errors.InvalidAddress();
            }
            // note: this will overwrite any existing policy manager to a new valid quote policy manager
            quotePolicyManagerForVault[lenderVault] = newPolicyManagerAddress;
        }
        emit QuotePolicyManagerUpdated(lenderVault, newPolicyManagerAddress);
    }

    function getOnChainQuoteHistory(
        address lenderVault,
        uint256 idx
    ) external view returns (DataTypesPeerToPeer.OnChainQuoteInfo memory) {
        if (idx < _onChainQuoteHistory[lenderVault].length) {
            return _onChainQuoteHistory[lenderVault][idx];
        } else {
            revert Errors.InvalidArrayIndex();
        }
    }

    function getOnChainQuoteHistorySlice(
        address lenderVault,
        uint256 startIdx,
        uint256 endIdx
    ) external view returns (DataTypesPeerToPeer.OnChainQuoteInfo[] memory) {
        uint256 onChainQuoteHistoryLen = _onChainQuoteHistory[lenderVault]
            .length;
        if (startIdx > endIdx || startIdx >= onChainQuoteHistoryLen) {
            revert Errors.InvalidArrayIndex();
        }
        endIdx = endIdx < onChainQuoteHistoryLen
            ? endIdx
            : onChainQuoteHistoryLen;
        if (startIdx == 0 && endIdx == onChainQuoteHistoryLen) {
            return _onChainQuoteHistory[lenderVault];
        }
        DataTypesPeerToPeer.OnChainQuoteInfo[]
            memory onChainQuoteHistoryRequested = new DataTypesPeerToPeer.OnChainQuoteInfo[](
                endIdx - startIdx
            );
        for (uint256 i = startIdx; i < endIdx; ) {
            onChainQuoteHistoryRequested[i - startIdx] = _onChainQuoteHistory[
                lenderVault
            ][i];
            unchecked {
                ++i;
            }
        }
        return onChainQuoteHistoryRequested;
    }

    function getOnChainQuoteHistoryLength(
        address lenderVault
    ) external view returns (uint256) {
        return _onChainQuoteHistory[lenderVault].length;
    }

    /**
     * @dev The passed signatures must be sorted such that recovered addresses are increasing.
     */
    function _areValidSignatures(
        address lenderVault,
        bytes32 offChainQuoteHash,
        uint256 minNumOfSignersOverwrite,
        bytes[] calldata compactSigs
    ) internal view returns (bool) {
        uint256 compactSigsLength = compactSigs.length;
        // @dev: if defined in policy, allow overwriting of min number of signers (except zero)
        uint256 minNumOfSigners = minNumOfSignersOverwrite == 0
            ? ILenderVaultImpl(lenderVault).minNumOfSigners()
            : minNumOfSignersOverwrite;
        if (compactSigsLength < minNumOfSigners) {
            return false;
        }
        bytes32 messageHash = ECDSA.toEthSignedMessageHash(offChainQuoteHash);
        address recoveredSigner;
        address prevSigner;
        for (uint256 i; i < compactSigsLength; ) {
            (bytes32 r, bytes32 vs) = Helpers.splitSignature(compactSigs[i]);
            recoveredSigner = messageHash.recover(r, vs);
            if (!ILenderVaultImpl(lenderVault).isSigner(recoveredSigner)) {
                return false;
            }
            if (recoveredSigner <= prevSigner) {
                return false;
            }
            prevSigner = recoveredSigner;
            unchecked {
                ++i;
            }
        }
        return true;
    }

    function _hashOffChainQuote(
        DataTypesPeerToPeer.OffChainQuote memory offChainQuote,
        address lenderVault
    ) internal view returns (bytes32 quoteHash) {
        quoteHash = keccak256(
            abi.encode(
                offChainQuote.generalQuoteInfo,
                offChainQuote.quoteTuplesRoot,
                offChainQuote.salt,
                offChainQuote.nonce,
                lenderVault,
                block.chainid
            )
        );
    }

    function _checkSenderAndPolicyAndQuoteInfo(
        address borrower,
        address lenderVault,
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple
    ) internal view returns (uint256 minNumOfSignersOverwrite) {
        if (msg.sender != IAddressRegistry(addressRegistry).borrowerGateway()) {
            revert Errors.InvalidSender();
        }
        address quotePolicyManager = quotePolicyManagerForVault[lenderVault];
        if (quotePolicyManager != address(0)) {
            bool isAllowed;
            (isAllowed, minNumOfSignersOverwrite) = IQuotePolicyManager(
                quotePolicyManager
            ).isAllowed(borrower, lenderVault, generalQuoteInfo, quoteTuple);
            if (!isAllowed) {
                revert Errors.QuoteViolatesPolicy();
            }
        }
        _checkWhitelist(
            generalQuoteInfo.collToken,
            generalQuoteInfo.loanToken,
            generalQuoteInfo.borrowerCompartmentImplementation,
            generalQuoteInfo.oracleAddr,
            _isSwap(generalQuoteInfo, quoteTuple)
        );
        if (generalQuoteInfo.validUntil < block.timestamp) {
            revert Errors.OutdatedQuote();
        }
        if (
            generalQuoteInfo.collToken == generalQuoteInfo.loanToken ||
            generalQuoteInfo.maxLoan == 0 ||
            generalQuoteInfo.minLoan == 0 ||
            generalQuoteInfo.minLoan > generalQuoteInfo.maxLoan
        ) {
            revert Errors.InvalidQuote();
        }
        if (
            generalQuoteInfo.whitelistAddr != address(0) &&
            ((generalQuoteInfo.isWhitelistAddrSingleBorrower &&
                generalQuoteInfo.whitelistAddr != borrower) ||
                (!generalQuoteInfo.isWhitelistAddrSingleBorrower &&
                    !IAddressRegistry(addressRegistry).isWhitelistedBorrower(
                        generalQuoteInfo.whitelistAddr,
                        borrower
                    )))
        ) {
            revert Errors.InvalidBorrower();
        }
    }

    function _isValidOnChainQuote(
        DataTypesPeerToPeer.OnChainQuote calldata onChainQuote
    ) internal view returns (bool) {
        if (
            onChainQuote.generalQuoteInfo.collToken ==
            onChainQuote.generalQuoteInfo.loanToken
        ) {
            return false;
        }
        if (onChainQuote.generalQuoteInfo.validUntil < block.timestamp) {
            return false;
        }
        if (
            onChainQuote.generalQuoteInfo.maxLoan == 0 ||
            onChainQuote.generalQuoteInfo.minLoan == 0 ||
            onChainQuote.generalQuoteInfo.minLoan >
            onChainQuote.generalQuoteInfo.maxLoan
        ) {
            return false;
        }
        uint256 quoteTuplesLen = onChainQuote.quoteTuples.length;
        if (quoteTuplesLen == 0) {
            return false;
        }
        bool isSwap;
        for (uint256 k; k < quoteTuplesLen; ) {
            (bool isValid, bool isSwapCurr) = _isValidOnChainQuoteTuple(
                onChainQuote.generalQuoteInfo,
                onChainQuote.quoteTuples[k]
            );
            if (!isValid) {
                return false;
            }
            if (isSwapCurr && quoteTuplesLen > 1) {
                return false;
            }
            isSwap = isSwapCurr;
            unchecked {
                ++k;
            }
        }
        _checkWhitelist(
            onChainQuote.generalQuoteInfo.collToken,
            onChainQuote.generalQuoteInfo.loanToken,
            onChainQuote.generalQuoteInfo.borrowerCompartmentImplementation,
            onChainQuote.generalQuoteInfo.oracleAddr,
            isSwap
        );
        return true;
    }

    function _checkWhitelist(
        address collToken,
        address loanToken,
        address compartmentImpl,
        address oracleAddr,
        bool isSwap
    ) internal view {
        if (
            !IAddressRegistry(addressRegistry).isWhitelistedERC20(loanToken) ||
            !IAddressRegistry(addressRegistry).isWhitelistedERC20(collToken)
        ) {
            revert Errors.NonWhitelistedToken();
        }

        if (isSwap) {
            if (compartmentImpl != address(0)) {
                revert Errors.InvalidSwap();
            }
            return;
        }
        if (compartmentImpl == address(0)) {
            DataTypesPeerToPeer.WhitelistState collTokenWhitelistState = IAddressRegistry(
                    addressRegistry
                ).whitelistState(collToken);
            if (
                collTokenWhitelistState ==
                DataTypesPeerToPeer
                    .WhitelistState
                    .ERC20_TOKEN_REQUIRING_COMPARTMENT
            ) {
                revert Errors.CollateralMustBeCompartmentalized();
            }
        } else {
            if (
                !IAddressRegistry(addressRegistry).isWhitelistedCompartment(
                    compartmentImpl,
                    collToken
                )
            ) {
                revert Errors.InvalidCompartmentForToken();
            }
        }
        if (
            oracleAddr != address(0) &&
            IAddressRegistry(addressRegistry).whitelistState(oracleAddr) !=
            DataTypesPeerToPeer.WhitelistState.ORACLE
        ) {
            revert Errors.NonWhitelistedOracle();
        }
    }

    function _checkIsVaultAndSenderIsApproved(
        address lenderVault,
        bool onlyOwner
    ) internal view {
        if (!IAddressRegistry(addressRegistry).isRegisteredVault(lenderVault)) {
            revert Errors.UnregisteredVault();
        }
        if (
            ILenderVaultImpl(lenderVault).owner() != msg.sender &&
            (onlyOwner ||
                ILenderVaultImpl(lenderVault).onChainQuotingDelegate() !=
                msg.sender)
        ) {
            revert Errors.InvalidSender();
        }
    }

    function _hashOnChainQuote(
        DataTypesPeerToPeer.OnChainQuote memory onChainQuote
    ) internal pure returns (bytes32 quoteHash) {
        quoteHash = keccak256(abi.encode(onChainQuote));
    }

    function _isValidOnChainQuoteTuple(
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple
    ) internal pure returns (bool, bool) {
        bool isSwap = _isSwap(generalQuoteInfo, quoteTuple);
        if (quoteTuple.upfrontFeePctInBase < Constants.BASE) {
            // note: if upfrontFee<100% this corresponds to a loan; check that tenor and earliest repay are consistent
            if (
                quoteTuple.tenor <
                generalQuoteInfo.earliestRepayTenor +
                    Constants.MIN_TIME_BETWEEN_EARLIEST_REPAY_AND_EXPIRY
            ) {
                return (false, isSwap);
            }
        } else if (quoteTuple.upfrontFeePctInBase == Constants.BASE) {
            // note: if upfrontFee=100% this corresponds to an outright swap; check other fields are consistent
            if (!isSwap) {
                return (false, isSwap);
            }
        } else {
            // note: if upfrontFee>100% this is invalid
            return (false, isSwap);
        }

        if (quoteTuple.loanPerCollUnitOrLtv == 0) {
            return (false, isSwap);
        }
        // If the oracle address is set and there is not specified whitelistAddr
        // then LTV must be set to a value <= 100% (overcollateralized).
        // note: Loans with whitelisted borrowers CAN be undercollateralized with oracles (LTV > 100%).
        // oracle address is set
        // ---> whitelistAddr is not set
        // ---> ---> LTV must be overcollateralized
        // ---> whitelistAddr is set
        // ---> ---> LTV can be any
        // oracle address is not set
        // ---> loanPerCollUnit can be any with or without whitelistAddr
        if (
            generalQuoteInfo.oracleAddr != address(0) &&
            quoteTuple.loanPerCollUnitOrLtv > Constants.BASE &&
            generalQuoteInfo.whitelistAddr == address(0)
        ) {
            return (false, isSwap);
        }
        if (quoteTuple.interestRatePctInBase + int(Constants.BASE) <= 0) {
            return (false, isSwap);
        }
        return (true, isSwap);
    }

    function _isSwap(
        DataTypesPeerToPeer.GeneralQuoteInfo calldata generalQuoteInfo,
        DataTypesPeerToPeer.QuoteTuple calldata quoteTuple
    ) internal pure returns (bool) {
        return
            quoteTuple.upfrontFeePctInBase == Constants.BASE &&
            quoteTuple.tenor + generalQuoteInfo.earliestRepayTenor == 0 &&
            quoteTuple.interestRatePctInBase == 0 &&
            generalQuoteInfo.borrowerCompartmentImplementation == address(0);
    }
}

// File: contracts/peer-to-peer/wrappers/ERC20/ERC20Wrapper.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IAddressRegistry} from "../../interfaces/IAddressRegistry.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {DataTypesPeerToPeer} from "../../../peer-to-peer/DataTypesPeerToPeer.sol";
import {Errors} from "../../../Errors.sol";
import {IERC20Wrapper} from "../../interfaces/wrappers/ERC20/IERC20Wrapper.sol";
import {IWrappedERC20Impl} from "../../interfaces/wrappers/ERC20/IWrappedERC20Impl.sol";

/**
 * @dev ERC20Wrapper is a contract that wraps tokens from possibly multiple ERC20 contracts
 * IMPORTANT: This contract allows for wrapping tokens that are whitelisted with the address registry.
 */
contract ERC20Wrapper is ReentrancyGuard, IERC20Wrapper {
    using SafeERC20 for IERC20;
    address public immutable addressRegistry;
    address public immutable wrappedErc20Impl;
    address[] public tokensCreated;

    constructor(address _addressRegistry, address _wrappedErc20Impl) {
        if (_addressRegistry == address(0) || _wrappedErc20Impl == address(0)) {
            revert Errors.InvalidAddress();
        }
        addressRegistry = _addressRegistry;
        wrappedErc20Impl = _wrappedErc20Impl;
    }

    // token addresses must be unique and passed in increasing order.
    // token amounts must be non-zero.
    // minter must approve this contract to transfer all tokens to be wrapped.
    function createWrappedToken(
        address minter,
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol
    ) external nonReentrant returns (address newErc20Addr) {
        if (msg.sender != addressRegistry) {
            revert Errors.InvalidSender();
        }
        if (minter == address(0) || minter == address(this)) {
            revert Errors.InvalidAddress();
        }
        // @dev: allow multiple wrappers with same underlyings to exist
        // note: in case a griefer wanted to lock-up a wrapper token one could easily create another one
        newErc20Addr = Clones.clone(wrappedErc20Impl);
        tokensCreated.push(newErc20Addr);

        // @dev: external call happens before state update due to minTokenAmount determination
        (
            uint256 numTokensToBeWrapped,
            uint256 minTokenAmount
        ) = _transferTokens(minter, tokensToBeWrapped, newErc20Addr);
        // @dev: case where numTokensToBeWrapped == 0 represents an IOU token
        IWrappedERC20Impl(newErc20Addr).initialize(
            minter,
            tokensToBeWrapped,
            numTokensToBeWrapped == 0 ? 10 ** 18 : minTokenAmount,
            name,
            symbol
        );
        emit ERC20WrapperCreated(
            newErc20Addr,
            minter,
            tokensCreated.length,
            tokensToBeWrapped
        );
    }

    function allTokensCreated() external view returns (address[] memory) {
        return tokensCreated;
    }

    function numTokensCreated() external view returns (uint256) {
        return tokensCreated.length;
    }

    function _transferTokens(
        address minter,
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata tokensToBeWrapped,
        address newErc20Addr
    ) internal returns (uint256 numTokensToBeWrapped, uint256 minTokenAmount) {
        minTokenAmount = type(uint256).max;
        address prevTokenAddress;
        address currAddress;
        numTokensToBeWrapped = tokensToBeWrapped.length;
        for (uint256 i; i < numTokensToBeWrapped; ) {
            if (
                !IAddressRegistry(addressRegistry).isWhitelistedERC20(
                    tokensToBeWrapped[i].tokenAddr
                )
            ) {
                revert Errors.NonWhitelistedToken();
            }
            currAddress = tokensToBeWrapped[i].tokenAddr;
            if (currAddress <= prevTokenAddress) {
                revert Errors.NonIncreasingTokenAddrs();
            }
            if (tokensToBeWrapped[i].tokenAmount == 0) {
                revert Errors.InvalidSendAmount();
            }
            minTokenAmount = minTokenAmount > tokensToBeWrapped[i].tokenAmount
                ? tokensToBeWrapped[i].tokenAmount
                : minTokenAmount;
            IERC20(tokensToBeWrapped[i].tokenAddr).safeTransferFrom(
                minter,
                newErc20Addr,
                tokensToBeWrapped[i].tokenAmount
            );
            prevTokenAddress = currAddress;
            unchecked {
                ++i;
            }
        }
    }
}

// File: contracts/peer-to-peer/wrappers/ERC20/WrappedERC20Impl.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Constants} from "../../../Constants.sol";
import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol";
import {Errors} from "../../../Errors.sol";
import {IAddressRegistry} from "../../interfaces/IAddressRegistry.sol";
import {IWrappedERC20Impl} from "../../interfaces/wrappers/ERC20/IWrappedERC20Impl.sol";

contract WrappedERC20Impl is
    ERC20,
    Initializable,
    ReentrancyGuard,
    IWrappedERC20Impl
{
    using SafeERC20 for IERC20Metadata;

    string internal _tokenName;
    string internal _tokenSymbol;
    uint8 internal _tokenDecimals;
    address[] internal _wrappedTokens;

    constructor() ERC20("Wrapped ERC20 Impl", "Wrapped ERC20 Impl") {
        _disableInitializers();
    }

    function initialize(
        address minter,
        DataTypesPeerToPeer.WrappedERC20TokenInfo[] calldata wrappedTokens,
        uint256 totalInitialSupply,
        string calldata _name,
        string calldata _symbol
    ) external initializer {
        uint256 wrappedTokensLen = wrappedTokens.length;
        if (wrappedTokensLen == 1) {
            // check for minimum mint amount
            if (totalInitialSupply <= Constants.SINGLE_WRAPPER_MIN_MINT) {
                revert Errors.InvalidMintAmount();
            }
            _tokenDecimals = IERC20Metadata(wrappedTokens[0].tokenAddr)
                .decimals();
            _wrappedTokens.push(wrappedTokens[0].tokenAddr);

            // @dev: mint small dust amount to this address, which will be locked in contract
            // @note: given this initial mint amount the wrapper cannot easily be locked up for future mints
            _mint(address(this), Constants.SINGLE_WRAPPER_MIN_MINT);
            _mint(
                minter,
                totalInitialSupply - Constants.SINGLE_WRAPPER_MIN_MINT
            );
        } else {
            _tokenDecimals = 18;
            for (uint256 i; i < wrappedTokensLen; ) {
                _wrappedTokens.push(wrappedTokens[i].tokenAddr);
                unchecked {
                    ++i;
                }
            }
            _mint(
                minter,
                totalInitialSupply < 10 ** 18 ? totalInitialSupply : 10 ** 18
            );
        }
        _tokenName = _name;
        _tokenSymbol = _symbol;
    }

    function redeem(
        address account,
        address recipient,
        uint256 amount
    ) external nonReentrant {
        if (amount == 0) {
            revert Errors.InvalidAmount();
        }
        if (recipient == address(0)) {
            revert Errors.InvalidAddress();
        }
        uint256 currTotalSupply = totalSupply();
        if (msg.sender != account) {
            _spendAllowance(account, msg.sender, amount);
        }
        _burn(account, amount);

        // @dev: if isIOU then _wrappedTokens.length == 0 and this loop is skipped automatically
        uint256 wrappedTokensLen = _wrappedTokens.length;
        for (uint256 i; i < wrappedTokensLen; ) {
            address tokenAddr = _wrappedTokens[i];
            // @note: The underlying token transfers are all-or-nothing. In other words, if one token transfer fails,
            // the entire redemption process will fail as well. Users should only use wrappers if they deem this risk
            // to be acceptable or non-existent (for example, in cases where the underlying tokens can never have any
            // transfer restrictions).
            uint256 redemptionAmount = Math.mulDiv(
                IERC20Metadata(tokenAddr).balanceOf(address(this)),
                amount,
                currTotalSupply
            );
            IERC20Metadata(tokenAddr).safeTransfer(recipient, redemptionAmount);
            unchecked {
                ++i;
            }
        }
        emit Redeemed(account, recipient, amount);
    }

    function mint(
        address recipient,
        uint256 amount,
        uint256 expectedTransferFee
    ) external nonReentrant {
        if (_wrappedTokens.length != 1) {
            // @dev: only on single token wrappers do we allow minting
            // @note: IOU has no underlying tokens, so they are also disabled from minting
            revert Errors.OnlyMintFromSingleTokenWrapper();
        }
        if (amount == 0) {
            revert Errors.InvalidAmount();
        }
        if (recipient == address(0)) {
            revert Errors.InvalidAddress();
        }
        uint256 currTotalSupply = totalSupply();
        address tokenAddr = _wrappedTokens[0];
        uint256 tokenPreBal = IERC20Metadata(tokenAddr).balanceOf(
            address(this)
        );
        if (tokenPreBal == 0) {
            // @dev: this would be an unintended state, for instance a negative rebase down to 0 balance with still outstanding supply
            // in which case to not allow possibly diluted or unfair proportions for new minters, will revert
            // @note: the state token balance > 0, but total supply == 0 is allowed (e.g. donations to address before mint)
            revert Errors.NonMintableTokenState();
        }
        uint256 mintAmount = Math.mulDiv(amount, currTotalSupply, tokenPreBal);
        // @dev: revert in case mint amount is truncated to zero. This may also happen in case the mint transaction is front-run
        // with donations. Note that griefing with donations will be costly due to redemption fee.
        if (mintAmount == 0) {
            revert Errors.InvalidMintAmount();
        }
        _mint(recipient, mintAmount);
        IERC20Metadata(tokenAddr).safeTransferFrom(
            msg.sender,
            address(this),
            amount + expectedTransferFee
        );
        uint256 tokenPostBal = IERC20Metadata(tokenAddr).balanceOf(
            address(this)
        );
        if (tokenPostBal != tokenPreBal + amount) {
            revert Errors.InvalidSendAmount();
        }
    }

    function isIOU() external view returns (bool) {
        return _wrappedTokens.length == 0;
    }

    function getWrappedTokensInfo() external view returns (address[] memory) {
        return _wrappedTokens;
    }

    function name() public view virtual override returns (string memory) {
        return _tokenName;
    }

    function symbol() public view virtual override returns (string memory) {
        return _tokenSymbol;
    }

    function decimals() public view virtual override returns (uint8) {
        return _tokenDecimals;
    }
}

// File: contracts/peer-to-peer/wrappers/ERC721/ERC721Wrapper.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IAddressRegistry} from "../../interfaces/IAddressRegistry.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol";
import {Errors} from "../../../Errors.sol";
import {IERC721Wrapper} from "../../interfaces/wrappers/ERC721/IERC721Wrapper.sol";
import {IWrappedERC721Impl} from "../../interfaces/wrappers/ERC721/IWrappedERC721Impl.sol";

/**
 * @dev ERC721Wrapper is a contract that wraps tokens from possibly multiple contracts and ids
 * IMPORTANT: This contract allows for whitelisting registered token addresses IF an address registry is provided.
 * This is to prevent the creation of wrapped tokens for non-registered tokens if that is a functionality that
 * is desired. If not, then the address registry can be set to the zero address.
 */
contract ERC721Wrapper is ReentrancyGuard, IERC721Wrapper {
    address public immutable addressRegistry;
    address public immutable wrappedErc721Impl;
    address[] public tokensCreated;

    constructor(address _addressRegistry, address _wrappedErc721Impl) {
        if (
            _addressRegistry == address(0) || _wrappedErc721Impl == address(0)
        ) {
            revert Errors.InvalidAddress();
        }
        addressRegistry = _addressRegistry;
        wrappedErc721Impl = _wrappedErc721Impl;
    }

    // token ids must be unique and passed in increasing order for each token address.
    // minter must approve this contract to transfer all tokens to be wrapped.
    function createWrappedToken(
        address minter,
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped,
        string calldata name,
        string calldata symbol
    ) external nonReentrant returns (address newErc20Addr) {
        if (msg.sender != addressRegistry) {
            revert Errors.InvalidSender();
        }
        if (minter == address(0) || minter == address(this)) {
            revert Errors.InvalidAddress();
        }
        uint256 numTokensToBeWrapped = tokensToBeWrapped.length;
        if (numTokensToBeWrapped == 0) {
            revert Errors.InvalidArrayLength();
        }
        // note: this will revert if the wrapped token already exists
        // this is to prevent the creation of duplicate wrapped tokens
        // will need to use the remint on the already existing token address
        // also unique ordering of token addresses and ids enforces uniqueness of wrapped token address
        // e.g. you can't mint a wrapped token for token address A with token ids 1, 2, 3 and then
        // mint a wrapped token for token address A with token ids 3, 2, 1
        newErc20Addr = Clones.cloneDeterministic(
            wrappedErc721Impl,
            keccak256(abi.encode(tokensToBeWrapped))
        );
        tokensCreated.push(newErc20Addr);

        IWrappedERC721Impl(newErc20Addr).initialize(
            minter,
            tokensToBeWrapped,
            name,
            symbol
        );

        _transferTokens(
            minter,
            numTokensToBeWrapped,
            tokensToBeWrapped,
            newErc20Addr
        );
        emit ERC721WrapperCreated(
            newErc20Addr,
            minter,
            tokensCreated.length,
            tokensToBeWrapped
        );
    }

    function allTokensCreated() external view returns (address[] memory) {
        return tokensCreated;
    }

    function numTokensCreated() external view returns (uint256) {
        return tokensCreated.length;
    }

    function _transferTokens(
        address minter,
        uint256 numTokensToBeWrapped,
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped,
        address newErc20Addr
    ) internal {
        address prevNftAddress;
        address currNftAddress;
        uint256 checkedId;
        for (uint256 i; i < numTokensToBeWrapped; ) {
            uint256 numTokenIds = tokensToBeWrapped[i].tokenIds.length;
            if (numTokenIds == 0) {
                revert Errors.InvalidArrayLength();
            }
            if (
                IAddressRegistry(addressRegistry).whitelistState(
                    tokensToBeWrapped[i].tokenAddr
                ) != DataTypesPeerToPeer.WhitelistState.ERC721_TOKEN
            ) {
                revert Errors.NonWhitelistedToken();
            }
            currNftAddress = tokensToBeWrapped[i].tokenAddr;
            if (currNftAddress <= prevNftAddress) {
                revert Errors.NonIncreasingTokenAddrs();
            }
            for (uint256 j; j < numTokenIds; ) {
                if (tokensToBeWrapped[i].tokenIds[j] <= checkedId && j != 0) {
                    revert Errors.NonIncreasingNonFungibleTokenIds();
                }
                checkedId = tokensToBeWrapped[i].tokenIds[j];
                try
                    IERC721(tokensToBeWrapped[i].tokenAddr).transferFrom(
                        minter,
                        newErc20Addr,
                        checkedId
                    )
                {
                    unchecked {
                        ++j;
                    }
                } catch {
                    revert Errors.TransferToWrappedTokenFailed();
                }
            }
            prevNftAddress = currNftAddress;
            unchecked {
                ++i;
            }
        }
    }
}

// File: contracts/peer-to-peer/wrappers/ERC721/WrappedERC721Impl.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {DataTypesPeerToPeer} from "../../DataTypesPeerToPeer.sol";
import {Errors} from "../../../Errors.sol";
import {IWrappedERC721Impl} from "../../interfaces/wrappers/ERC721/IWrappedERC721Impl.sol";

contract WrappedERC721Impl is
    ERC20,
    Initializable,
    ReentrancyGuard,
    IWrappedERC721Impl
{
    string internal _tokenName;
    string internal _tokenSymbol;
    DataTypesPeerToPeer.WrappedERC721TokenInfo[] internal _wrappedTokens;
    address public lastRedeemer;
    mapping(address => mapping(uint256 => bool)) public stuckTokens;
    mapping(address => mapping(uint256 => bool)) public isTokenCountedInWrapper;
    mapping(address => mapping(uint256 => bool)) public isUnderlying;
    uint128[2] internal totalAndCurrentNumOfTokensInWrapper;

    constructor() ERC20("Wrapped ERC721 Impl", "Wrapped ERC721 Impl") {
        _disableInitializers();
    }

    function initialize(
        address minter,
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata wrappedTokens,
        string calldata _name,
        string calldata _symbol
    ) external initializer {
        uint128 numTokens;
        for (uint256 i; i < wrappedTokens.length; ) {
            _wrappedTokens.push(wrappedTokens[i]);
            for (uint256 j; j < wrappedTokens[i].tokenIds.length; ) {
                mapping(uint256 => bool) storage isTokenAddr = isUnderlying[
                    wrappedTokens[i].tokenAddr
                ];
                mapping(uint256 => bool)
                    storage isTokenIdInWrapper = isTokenCountedInWrapper[
                        wrappedTokens[i].tokenAddr
                    ];
                isTokenAddr[wrappedTokens[i].tokenIds[j]] = true;
                isTokenIdInWrapper[wrappedTokens[i].tokenIds[j]] = true;
                unchecked {
                    ++numTokens;
                    ++j;
                }
            }
            unchecked {
                ++i;
            }
        }
        _tokenName = _name;
        _tokenSymbol = _symbol;
        // @dev: packed storage layout to track total number of tokens and current number of tokens in wrapper
        // this is to prevent having to loop through all the tokens to get the total supply on remints with stuck tokens
        totalAndCurrentNumOfTokensInWrapper = [numTokens, numTokens];
        _mint(minter, 1);
    }

    function redeem(address account, address recipient) external nonReentrant {
        if (recipient == address(0)) {
            revert Errors.InvalidAddress();
        }
        if (msg.sender != account) {
            _spendAllowance(account, msg.sender, 1);
        }
        _burn(account, 1);
        lastRedeemer = account;
        address tokenAddr;
        uint256 tokenId;
        uint128 tokensRemoved;
        for (uint256 i; i < _wrappedTokens.length; ) {
            tokenAddr = _wrappedTokens[i].tokenAddr;
            for (uint256 j; j < _wrappedTokens[i].tokenIds.length; ) {
                tokenId = _wrappedTokens[i].tokenIds[j];
                try
                    IERC721(tokenAddr).safeTransferFrom(
                        address(this),
                        recipient,
                        tokenId
                    )
                {
                    ++tokensRemoved;
                    isTokenCountedInWrapper[tokenAddr][tokenId] = false;
                } catch {
                    stuckTokens[tokenAddr][tokenId] = true;
                    emit TransferFromWrappedTokenFailed(tokenAddr, tokenId);
                }
                unchecked {
                    ++j;
                }
            }
            unchecked {
                ++i;
            }
        }
        if (tokensRemoved == 0) {
            revert Errors.NoTokensTransferred();
        }
        unchecked {
            totalAndCurrentNumOfTokensInWrapper[1] -= tokensRemoved;
        }
        emit Redeemed(account, recipient);
    }

    function sweepTokensLeftAfterRedeem(
        address tokenAddr,
        uint256[] calldata tokenIds
    ) external nonReentrant {
        if (msg.sender != lastRedeemer) {
            revert Errors.InvalidSender();
        }
        if (tokenIds.length == 0) {
            revert Errors.InvalidArrayLength();
        }
        mapping(uint256 => bool) storage stuckTokenAddr = stuckTokens[
            tokenAddr
        ];
        mapping(uint256 => bool)
            storage isTokenIdInWrapper = isTokenCountedInWrapper[tokenAddr];
        uint128 tokensRemoved;
        for (uint256 i; i < tokenIds.length; ) {
            if (!stuckTokenAddr[tokenIds[i]]) {
                revert Errors.TokenNotStuck();
            }
            try
                IERC721(tokenAddr).safeTransferFrom(
                    address(this),
                    msg.sender,
                    tokenIds[i]
                )
            {
                delete stuckTokenAddr[tokenIds[i]];
                delete isTokenIdInWrapper[tokenIds[i]];
                ++tokensRemoved;
            } catch {
                emit TransferFromWrappedTokenFailed(tokenAddr, tokenIds[i]);
            }
            unchecked {
                ++i;
            }
        }
        if (tokensRemoved == 0) {
            revert Errors.NoTokensTransferred();
        }
        unchecked {
            totalAndCurrentNumOfTokensInWrapper[1] -= tokensRemoved;
        }
        emit TokenSweepAttempted(tokenAddr, tokenIds);
    }

    function remint(
        DataTypesPeerToPeer.WrappedERC721TokenInfo[]
            calldata _wrappedTokensForRemint,
        address recipient
    ) external nonReentrant {
        if (recipient == address(0)) {
            revert Errors.InvalidAddress();
        }
        if (totalSupply() != 0) {
            // @note: totalSupply can be zero yet there are still tokens in the wrapper due to being stuck
            revert Errors.CannotRemintUnlessZeroSupply();
        }
        // whoever remints must be able to transfer all the tokens to be reminted (all non-stuck tokens) back
        // to this contract. If even one transfer fails, then the remint fails.
        uint128 tokensNeeded = totalAndCurrentNumOfTokensInWrapper[0] -
            totalAndCurrentNumOfTokensInWrapper[1];
        totalAndCurrentNumOfTokensInWrapper[
            1
        ] = totalAndCurrentNumOfTokensInWrapper[0];
        if (tokensNeeded == 0 && msg.sender != lastRedeemer) {
            // @note: tokensNeeded = 0 is case where the wrapper through sync function has all tokens accounted for
            // in this special case, since no transfer is made, we allow only the lastRedeemer to remint to
            // avoid race conditions for anyone being able to remint. In cases where the wrapper has tokens
            // being transferred, then sender with that permission to transfer those tokens (owner or approved) can remint
            revert Errors.InvalidSender();
        }
        if (_wrappedTokensForRemint.length == 0 && tokensNeeded != 0) {
            revert Errors.InvalidArrayLength();
        }
        _mint(recipient, 1);
        uint128 tokensAdded = _wrappedTokensForRemint.length == 0
            ? 0
            : _transferTokens(_wrappedTokensForRemint);
        if (tokensAdded != tokensNeeded) {
            revert Errors.TokensStillMissingFromWrapper();
        }
    }

    function sync(address tokenAddr, uint256 tokenId) external nonReentrant {
        mapping(uint256 => bool)
            storage isTokenIdInWrapper = isTokenCountedInWrapper[tokenAddr];
        if (isTokenIdInWrapper[tokenId]) {
            revert Errors.TokenAlreadyCountedInWrapper();
        }
        if (!isUnderlying[tokenAddr][tokenId]) {
            revert Errors.TokenDoesNotBelongInWrapper(tokenAddr, tokenId);
        }
        isTokenIdInWrapper[tokenId] = true;
        unchecked {
            ++totalAndCurrentNumOfTokensInWrapper[1];
        }
        if (IERC721(tokenAddr).ownerOf(tokenId) != address(this)) {
            revert Errors.TokenNotOwnedByWrapper();
        }
    }

    function getWrappedTokensInfo()
        external
        view
        returns (DataTypesPeerToPeer.WrappedERC721TokenInfo[] memory)
    {
        return _wrappedTokens;
    }

    function getTotalAndCurrentNumOfTokensInWrapper()
        external
        view
        returns (uint128[2] memory)
    {
        return totalAndCurrentNumOfTokensInWrapper;
    }

    function name() public view virtual override returns (string memory) {
        return _tokenName;
    }

    function symbol() public view virtual override returns (string memory) {
        return _tokenSymbol;
    }

    function decimals() public view virtual override returns (uint8) {
        return 0;
    }

    // @dev: no need for ordering check here
    function _transferTokens(
        DataTypesPeerToPeer.WrappedERC721TokenInfo[] calldata tokensToBeWrapped
    ) internal returns (uint128 numTokensAdded) {
        uint256 checkedId;
        address currNftAddress;
        for (uint256 i; i < tokensToBeWrapped.length; ) {
            if (tokensToBeWrapped[i].tokenIds.length == 0) {
                revert Errors.InvalidArrayLength();
            }
            currNftAddress = tokensToBeWrapped[i].tokenAddr;
            for (uint256 j; j < tokensToBeWrapped[i].tokenIds.length; ) {
                checkedId = tokensToBeWrapped[i].tokenIds[j];
                if (!isUnderlying[currNftAddress][checkedId]) {
                    revert Errors.TokenDoesNotBelongInWrapper(
                        currNftAddress,
                        checkedId
                    );
                }
                try
                    IERC721(currNftAddress).transferFrom(
                        msg.sender,
                        address(this),
                        checkedId
                    )
                {
                    isTokenCountedInWrapper[currNftAddress][checkedId] = true;
                    unchecked {
                        ++numTokensAdded;
                        ++j;
                    }
                } catch {
                    revert Errors.TransferToWrappedTokenFailed();
                }
            }
            unchecked {
                ++i;
            }
        }
    }
}

// File: contracts/peer-to-pool/DataTypesPeerToPool.sol



// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;

library DataTypesPeerToPool {
    struct Repayment {
        // The loan token amount due for given period; initially, expressed in relative terms (100%=BASE), once
        // finalized in absolute terms (in loanToken)
        uint128 loanTokenDue;
        // The coll token amount that can be converted for given period; initially, expressed in relative terms w.r.t.
        // loanTokenDue (e.g., convert every 1 loanToken for 8 collToken), once finalized in absolute terms (in collToken)
        uint128 collTokenDueIfConverted;
        // Timestamp when repayment is due
        uint40 dueTimestamp;
    }

    struct LoanTerms {
        // Min subscription amount (in loan token) that the borrower deems acceptable
        uint128 minTotalSubscriptions;
        // Max subscription amount (in loan token) that the borrower deems acceptable
        uint128 maxTotalSubscriptions;
        // The number of collateral tokens the borrower pledges per loan token borrowed as collateral for default case
        uint128 collPerLoanToken;
        // Borrower who can finalize given loan proposal
        address borrower;
        // Array of scheduled repayments
        Repayment[] repaymentSchedule;
    }

    struct StaticLoanProposalData {
        // Factory address from which the loan proposal is created
        address factory;
        // Funding pool address that is associated with given loan proposal and from which loan liquidity can be
        // sourced
        address fundingPool;
        // Address of collateral token to be used for given loan proposal
        address collToken;
        // Address of arranger who can manage the loan proposal contract
        address arranger;
        // Address of whitelist authority who can manage the lender whitelist (optional)
        address whitelistAuthority;
        // Unsubscribe grace period (in seconds), i.e., after acceptance by borrower lenders can unsubscribe and
        // remove liquidity for this duration before being locked-in
        uint256 unsubscribeGracePeriod;
        // Conversion grace period (in seconds), i.e., lenders can exercise their conversion right between
        // [dueTimeStamp, dueTimeStamp+conversionGracePeriod]
        uint256 conversionGracePeriod;
        // Repayment grace period (in seconds), i.e., borrowers can repay between
        // [dueTimeStamp+conversionGracePeriod, dueTimeStamp+conversionGracePeriod+repaymentGracePeriod]
        uint256 repaymentGracePeriod;
    }

    struct DynamicLoanProposalData {
        // Arranger fee charged on final loan amount, initially in relative terms (100%=BASE), and after finalization
        // in absolute terms (in loan token)
        uint256 arrangerFee;
        // The gross loan amount; initially this is zero and gets set once loan proposal gets accepted and finalized;
        // note that the borrower receives the gross loan amount minus any arranger and protocol fees
        uint256 grossLoanAmount;
        // Final collateral amount reserved for defaults; initially this is zero and gets set once loan proposal got
        // accepted and finalized
        uint256 finalCollAmountReservedForDefault;
        // Final collateral amount reserved for conversions; initially this is zero and gets set once loan proposal got
        // accepted and finalized
        uint256 finalCollAmountReservedForConversions;
        // Timestamp when the loan terms get accepted by borrower and after which they cannot be changed anymore
        uint256 loanTermsLockedTime;
        // Current repayment index, mapping to currently relevant repayment schedule element; note the
        // currentRepaymentIdx (initially 0) only ever gets incremented on repay
        uint256 currentRepaymentIdx;
        // Status of current loan proposal
        DataTypesPeerToPool.LoanStatus status;
        // Protocol fee, initially in relative terms (100%=BASE), and after finalization in absolute terms (in loan token);
        // note that the relative protocol fee is locked in at the time when the loan proposal is created
        uint256 protocolFee;
    }

    enum LoanStatus {
        WITHOUT_LOAN_TERMS,
        IN_NEGOTIATION,
        LOAN_TERMS_LOCKED,
        READY_TO_EXECUTE,
        ROLLBACK,
        LOAN_DEPLOYED,
        DEFAULTED
    }
}

// File: contracts/peer-to-pool/Factory.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {Constants} from "../Constants.sol";
import {Errors} from "../Errors.sol";
import {Helpers} from "../Helpers.sol";
import {IFactory} from "./interfaces/IFactory.sol";
import {IFundingPoolImpl} from "./interfaces/IFundingPoolImpl.sol";
import {ILoanProposalImpl} from "./interfaces/ILoanProposalImpl.sol";
import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol";

contract Factory is Ownable2Step, ReentrancyGuard, IFactory {
    using ECDSA for bytes32;

    uint256 public protocolFee;
    address public immutable loanProposalImpl;
    address public immutable fundingPoolImpl;
    address public mysoTokenManager;
    address[] public loanProposals;
    address[] public fundingPools;
    mapping(address => bool) public isLoanProposal;
    mapping(address => bool) public isFundingPool;
    mapping(bytes => bool) internal _signatureIsInvalidated;
    mapping(address => bool) internal _depositTokenHasFundingPool;
    mapping(address => mapping(address => uint256))
        internal _lenderWhitelistedUntil;

    constructor(address _loanProposalImpl, address _fundingPoolImpl) {
        if (_loanProposalImpl == address(0) || _fundingPoolImpl == address(0)) {
            revert Errors.InvalidAddress();
        }
        loanProposalImpl = _loanProposalImpl;
        fundingPoolImpl = _fundingPoolImpl;
        _transferOwnership(msg.sender);
    }

    function createLoanProposal(
        address _fundingPool,
        address _collToken,
        address _whitelistAuthority,
        uint256 _arrangerFee,
        uint256 _unsubscribeGracePeriod,
        uint256 _conversionGracePeriod,
        uint256 _repaymentGracePeriod
    ) external nonReentrant {
        if (!isFundingPool[_fundingPool] || _collToken == address(0)) {
            revert Errors.InvalidAddress();
        }
        address newLoanProposal = Clones.clone(loanProposalImpl);
        loanProposals.push(newLoanProposal);
        uint256 _numLoanProposals = loanProposals.length;
        isLoanProposal[newLoanProposal] = true;
        address _mysoTokenManager = mysoTokenManager;
        if (_mysoTokenManager != address(0)) {
            IMysoTokenManager(_mysoTokenManager)
                .processP2PoolCreateLoanProposal(
                    _fundingPool,
                    msg.sender,
                    _collToken,
                    _arrangerFee,
                    _numLoanProposals
                );
        }
        ILoanProposalImpl(newLoanProposal).initialize(
            address(this),
            msg.sender,
            _fundingPool,
            _collToken,
            _whitelistAuthority,
            _arrangerFee,
            _unsubscribeGracePeriod,
            _conversionGracePeriod,
            _repaymentGracePeriod
        );

        emit LoanProposalCreated(
            newLoanProposal,
            _fundingPool,
            msg.sender,
            _collToken,
            _arrangerFee,
            _unsubscribeGracePeriod,
            _numLoanProposals
        );
    }

    function createFundingPool(address _depositToken) external {
        if (_depositTokenHasFundingPool[_depositToken]) {
            revert Errors.FundingPoolAlreadyExists();
        }
        address newFundingPool = Clones.clone(fundingPoolImpl);
        fundingPools.push(newFundingPool);
        isFundingPool[newFundingPool] = true;
        _depositTokenHasFundingPool[_depositToken] = true;
        IFundingPoolImpl(newFundingPool).initialize(
            address(this),
            _depositToken
        );

        emit FundingPoolCreated(
            newFundingPool,
            _depositToken,
            fundingPools.length
        );
    }

    function setProtocolFee(uint256 _newprotocolFee) external {
        _checkOwner();
        uint256 oldprotocolFee = protocolFee;
        if (
            _newprotocolFee > Constants.MAX_P2POOL_PROTOCOL_FEE ||
            _newprotocolFee == oldprotocolFee
        ) {
            revert Errors.InvalidFee();
        }
        protocolFee = _newprotocolFee;
        emit ProtocolFeeUpdated(oldprotocolFee, _newprotocolFee);
    }

    function claimLenderWhitelistStatus(
        address whitelistAuthority,
        uint256 whitelistedUntil,
        bytes calldata compactSig,
        bytes32 salt
    ) external {
        if (_signatureIsInvalidated[compactSig]) {
            revert Errors.InvalidSignature();
        }
        bytes32 payloadHash = keccak256(
            abi.encode(
                address(this),
                msg.sender,
                whitelistedUntil,
                block.chainid,
                salt
            )
        );
        bytes32 messageHash = ECDSA.toEthSignedMessageHash(payloadHash);
        (bytes32 r, bytes32 vs) = Helpers.splitSignature(compactSig);
        address recoveredSigner = messageHash.recover(r, vs);
        if (
            whitelistAuthority == address(0) ||
            recoveredSigner != whitelistAuthority
        ) {
            revert Errors.InvalidSignature();
        }
        mapping(address => uint256)
            storage whitelistedUntilPerLender = _lenderWhitelistedUntil[
                whitelistAuthority
            ];
        if (
            whitelistedUntil < block.timestamp ||
            whitelistedUntil <= whitelistedUntilPerLender[msg.sender]
        ) {
            revert Errors.CannotClaimOutdatedStatus();
        }
        whitelistedUntilPerLender[msg.sender] = whitelistedUntil;
        _signatureIsInvalidated[compactSig] = true;
        emit LenderWhitelistStatusClaimed(
            whitelistAuthority,
            msg.sender,
            whitelistedUntil
        );
    }

    function updateLenderWhitelist(
        address[] calldata lenders,
        uint256 whitelistedUntil
    ) external {
        uint256 lendersLen = lenders.length;
        if (lendersLen == 0) {
            revert Errors.InvalidArrayLength();
        }
        for (uint256 i; i < lendersLen; ) {
            mapping(address => uint256)
                storage whitelistedUntilPerLender = _lenderWhitelistedUntil[
                    msg.sender
                ];
            if (
                lenders[i] == address(0) ||
                whitelistedUntil == whitelistedUntilPerLender[lenders[i]]
            ) {
                revert Errors.InvalidUpdate();
            }
            whitelistedUntilPerLender[lenders[i]] = whitelistedUntil;
            unchecked {
                ++i;
            }
        }
        emit LenderWhitelistUpdated(msg.sender, lenders, whitelistedUntil);
    }

    function setMysoTokenManager(address newTokenManager) external {
        _checkOwner();
        address oldTokenManager = mysoTokenManager;
        if (oldTokenManager == newTokenManager) {
            revert Errors.InvalidAddress();
        }
        mysoTokenManager = newTokenManager;
        emit MysoTokenManagerUpdated(oldTokenManager, newTokenManager);
    }

    function isWhitelistedLender(
        address whitelistAuthority,
        address lender
    ) external view returns (bool) {
        return
            _lenderWhitelistedUntil[whitelistAuthority][lender] >=
            block.timestamp;
    }

    function numLoanProposals() external view returns (uint256) {
        return loanProposals.length;
    }

    function transferOwnership(
        address _newOwnerProposal
    ) public override(Ownable2Step, IFactory) {
        if (
            _newOwnerProposal == address(this) ||
            _newOwnerProposal == pendingOwner() ||
            _newOwnerProposal == owner()
        ) {
            revert Errors.InvalidNewOwnerProposal();
        }
        // @dev: access control check via super.transferOwnership()
        super.transferOwnership(_newOwnerProposal);
    }

    function owner() public view override(Ownable, IFactory) returns (address) {
        return super.owner();
    }

    function pendingOwner()
        public
        view
        override(Ownable2Step, IFactory)
        returns (address)
    {
        return super.pendingOwner();
    }

    function renounceOwnership() public pure override {
        revert Errors.Disabled();
    }
}

// File: contracts/peer-to-pool/FundingPoolImpl.sol



// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Constants} from "../Constants.sol";
import {DataTypesPeerToPool} from "./DataTypesPeerToPool.sol";
import {Errors} from "../Errors.sol";
import {IFactory} from "./interfaces/IFactory.sol";
import {IFundingPoolImpl} from "./interfaces/IFundingPoolImpl.sol";
import {ILoanProposalImpl} from "./interfaces/ILoanProposalImpl.sol";
import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol";

contract FundingPoolImpl is Initializable, ReentrancyGuard, IFundingPoolImpl {
    using SafeERC20 for IERC20Metadata;

    address public factory;
    address public depositToken;
    mapping(address => uint256) public balanceOf;
    mapping(address => uint256) public depositUnlockTime;
    mapping(address => uint256) public totalSubscriptions;
    mapping(address => mapping(address => uint256)) public subscriptionAmountOf;
    // note: earliest unsubscribe time is to prevent griefing loans through atomic flashborrow,
    // deposit, subscribe, lock, unsubscribe, and withdraw
    mapping(address => mapping(address => uint256))
        internal _earliestUnsubscribe;

    constructor() {
        _disableInitializers();
    }

    function initialize(
        address _factory,
        address _depositToken
    ) external initializer {
        if (_factory == address(0) || _depositToken == address(0)) {
            revert Errors.InvalidAddress();
        }
        factory = _factory;
        depositToken = _depositToken;
    }

    function deposit(
        uint256 amount,
        uint256 transferFee,
        uint256 depositLockupDuration
    ) external nonReentrant {
        if (amount == 0) {
            revert Errors.InvalidSendAmount();
        }
        if (depositLockupDuration > 0) {
            uint256 _depositUnlockTime = depositUnlockTime[msg.sender];
            if (_depositUnlockTime < block.timestamp + depositLockupDuration) {
                depositUnlockTime[msg.sender] =
                    block.timestamp +
                    depositLockupDuration;
            }
        }
        address mysoTokenManager = IFactory(factory).mysoTokenManager();
        if (mysoTokenManager != address(0)) {
            IMysoTokenManager(mysoTokenManager).processP2PoolDeposit(
                address(this),
                msg.sender,
                amount,
                depositLockupDuration,
                transferFee
            );
        }
        address _depositToken = depositToken;
        uint256 preBal = IERC20Metadata(_depositToken).balanceOf(address(this));
        IERC20Metadata(_depositToken).safeTransferFrom(
            msg.sender,
            address(this),
            amount + transferFee
        );
        uint256 postBal = IERC20Metadata(_depositToken).balanceOf(
            address(this)
        );
        if (postBal != preBal + amount) {
            revert Errors.InvalidSendAmount();
        }
        balanceOf[msg.sender] += amount;
        emit Deposited(msg.sender, amount, depositLockupDuration);
    }

    function withdraw(uint256 amount) external {
        uint256 _balanceOf = balanceOf[msg.sender];
        if (amount == 0 || amount > _balanceOf) {
            revert Errors.InvalidWithdrawAmount();
        }
        if (block.timestamp < depositUnlockTime[msg.sender]) {
            revert Errors.DepositLockActive();
        }
        unchecked {
            balanceOf[msg.sender] = _balanceOf - amount;
        }
        IERC20Metadata(depositToken).safeTransfer(msg.sender, amount);
        emit Withdrawn(msg.sender, amount);
    }

    function subscribe(
        address loanProposal,
        uint256 minSubscriptionAmount,
        uint256 maxSubscriptionAmount,
        uint256 subscriptionLockupDuration
    ) external nonReentrant {
        if (
            maxSubscriptionAmount == 0 ||
            minSubscriptionAmount > maxSubscriptionAmount
        ) {
            revert Errors.InvalidAmount();
        }
        address _factory = factory;
        if (!IFactory(_factory).isLoanProposal(loanProposal)) {
            revert Errors.UnregisteredLoanProposal();
        }
        if (!ILoanProposalImpl(loanProposal).canSubscribe()) {
            revert Errors.NotInSubscriptionPhase();
        }
        (, , , , address whitelistAuthority, , , ) = ILoanProposalImpl(
            loanProposal
        ).staticData();
        if (
            whitelistAuthority != address(0) &&
            !IFactory(_factory).isWhitelistedLender(
                whitelistAuthority,
                msg.sender
            )
        ) {
            revert Errors.InvalidLender();
        }
        uint256 _balanceOf = balanceOf[msg.sender];
        if (maxSubscriptionAmount > _balanceOf) {
            revert Errors.InsufficientBalance();
        }
        DataTypesPeerToPool.LoanTerms memory loanTerms = ILoanProposalImpl(
            loanProposal
        ).loanTerms();
        if (subscriptionLockupDuration > 0) {
            (
                ,
                ,
                ,
                ,
                ,
                ,
                DataTypesPeerToPool.LoanStatus status,

            ) = ILoanProposalImpl(loanProposal).dynamicData();
            if (status != DataTypesPeerToPool.LoanStatus.LOAN_TERMS_LOCKED) {
                revert Errors.DisallowedSubscriptionLockup();
            }
        }
        uint256 _totalSubscriptions = totalSubscriptions[loanProposal];
        uint256 _freeSubscriptionSpace = loanTerms.maxTotalSubscriptions -
            _totalSubscriptions;
        if (_freeSubscriptionSpace < minSubscriptionAmount) {
            revert Errors.InsufficientFreeSubscriptionSpace();
        }
        uint256 effectiveSubscriptionAmount = maxSubscriptionAmount <
            _freeSubscriptionSpace
            ? maxSubscriptionAmount
            : _freeSubscriptionSpace;
        address mysoTokenManager = IFactory(factory).mysoTokenManager();
        if (mysoTokenManager != address(0)) {
            IMysoTokenManager(mysoTokenManager).processP2PoolSubscribe(
                address(this),
                msg.sender,
                loanProposal,
                effectiveSubscriptionAmount,
                subscriptionLockupDuration,
                _totalSubscriptions,
                loanTerms
            );
        }
        unchecked {
            // @dev: can't underflow due to previous `maxSubscriptionAmount > _balanceOf` check
            balanceOf[msg.sender] = _balanceOf - effectiveSubscriptionAmount;
        }
        totalSubscriptions[loanProposal] =
            _totalSubscriptions +
            effectiveSubscriptionAmount;
        subscriptionAmountOf[loanProposal][
            msg.sender
        ] += effectiveSubscriptionAmount;
        _earliestUnsubscribe[loanProposal][msg.sender] =
            block.timestamp +
            (
                subscriptionLockupDuration <
                    Constants.MIN_WAIT_UNTIL_EARLIEST_UNSUBSCRIBE
                    ? Constants.MIN_WAIT_UNTIL_EARLIEST_UNSUBSCRIBE
                    : subscriptionLockupDuration
            );
        emit Subscribed(
            msg.sender,
            loanProposal,
            effectiveSubscriptionAmount,
            subscriptionLockupDuration
        );
    }

    function unsubscribe(address loanProposal, uint256 amount) external {
        if (amount == 0) {
            revert Errors.InvalidAmount();
        }
        if (!IFactory(factory).isLoanProposal(loanProposal)) {
            revert Errors.UnregisteredLoanProposal();
        }
        if (!ILoanProposalImpl(loanProposal).canUnsubscribe()) {
            revert Errors.NotInUnsubscriptionPhase();
        }
        mapping(address => uint256)
            storage subscriptionAmountPerLender = subscriptionAmountOf[
                loanProposal
            ];
        if (amount > subscriptionAmountPerLender[msg.sender]) {
            revert Errors.UnsubscriptionAmountTooLarge();
        }
        mapping(address => uint256)
            storage earliestUnsubscribePerLender = _earliestUnsubscribe[
                loanProposal
            ];
        (
            ,
            ,
            ,
            ,
            ,
            ,
            DataTypesPeerToPool.LoanStatus status,

        ) = ILoanProposalImpl(loanProposal).dynamicData();
        if (
            status != DataTypesPeerToPool.LoanStatus.ROLLBACK &&
            block.timestamp < earliestUnsubscribePerLender[msg.sender]
        ) {
            revert Errors.BeforeEarliestUnsubscribe();
        }
        balanceOf[msg.sender] += amount;
        totalSubscriptions[loanProposal] -= amount;
        subscriptionAmountPerLender[msg.sender] -= amount;
        earliestUnsubscribePerLender[msg.sender] = 0;

        emit Unsubscribed(msg.sender, loanProposal, amount);
    }

    function executeLoanProposal(address loanProposal) external {
        address _factory = factory;
        if (!IFactory(_factory).isLoanProposal(loanProposal)) {
            revert Errors.UnregisteredLoanProposal();
        }

        (
            uint256 arrangerFee,
            uint256 grossLoanAmount,
            ,
            ,
            ,
            ,
            ,
            uint256 protocolFee
        ) = ILoanProposalImpl(loanProposal).dynamicData();
        DataTypesPeerToPool.LoanTerms memory loanTerms = ILoanProposalImpl(
            loanProposal
        ).loanTerms();
        if (
            block.timestamp + Constants.MIN_TIME_UNTIL_FIRST_DUE_DATE >
            loanTerms.repaymentSchedule[0].dueTimestamp
        ) {
            revert Errors.FirstDueDateTooCloseOrPassed();
        }
        ILoanProposalImpl(loanProposal).checkAndUpdateStatus();
        if (grossLoanAmount != totalSubscriptions[loanProposal]) {
            revert Errors.IncorrectLoanAmount();
        }
        IERC20Metadata(depositToken).safeTransfer(
            loanTerms.borrower,
            grossLoanAmount - arrangerFee - protocolFee
        );
        (, , , address arranger, , , , ) = ILoanProposalImpl(loanProposal)
            .staticData();

        address _depositToken = depositToken;
        if (arrangerFee > 0) {
            IERC20Metadata(_depositToken).safeTransfer(arranger, arrangerFee);
        }
        if (protocolFee > 0) {
            IERC20Metadata(_depositToken).safeTransfer(
                IFactory(factory).owner(),
                protocolFee
            );
        }

        emit LoanProposalExecuted(
            loanProposal,
            loanTerms.borrower,
            grossLoanAmount,
            arrangerFee,
            protocolFee
        );
    }
}

// File: contracts/peer-to-pool/interfaces/IFactory.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

interface IFactory {
    event LoanProposalCreated(
        address indexed loanProposalAddr,
        address indexed fundingPool,
        address indexed sender,
        address collToken,
        uint256 arrangerFee,
        uint256 unsubscribeGracePeriod,
        uint256 numLoanProposals
    );
    event FundingPoolCreated(
        address indexed newFundingPool,
        address indexed depositToken,
        uint256 numFundingPools
    );
    event ProtocolFeeUpdated(uint256 oldProtocolFee, uint256 newProtocolFee);
    event LenderWhitelistStatusClaimed(
        address indexed whitelistAuthority,
        address indexed lender,
        uint256 whitelistedUntil
    );
    event LenderWhitelistUpdated(
        address indexed whitelistAuthority,
        address[] indexed lender,
        uint256 whitelistedUntil
    );
    event MysoTokenManagerUpdated(
        address oldTokenManager,
        address newTokenManager
    );

    /**
     * @notice Creates a new loan proposal
     * @param _fundingPool The address of the funding pool from which lenders are allowed to subscribe, and -if loan proposal is successful- from where loan amount is sourced
     * @param _collToken The address of collateral token to be provided by borrower
     * @param _whitelistAuthority The address of the whitelist authority that can manage the lender whitelist (optional)
     * @param _arrangerFee The relative arranger fee (where 100% = BASE)
     * @param _unsubscribeGracePeriod The unsubscribe grace period, i.e., after a loan gets accepted by the borrower lenders can still unsubscribe for this time period before being locked-in
     * @param _conversionGracePeriod The grace period during which lenders can convert
     * @param _repaymentGracePeriod The grace period during which borrowers can repay
     */
    function createLoanProposal(
        address _fundingPool,
        address _collToken,
        address _whitelistAuthority,
        uint256 _arrangerFee,
        uint256 _unsubscribeGracePeriod,
        uint256 _conversionGracePeriod,
        uint256 _repaymentGracePeriod
    ) external;

    /**
     * @notice Creates a new funding pool
     * @param _depositToken The address of the deposit token to be accepted by the given funding pool
     */
    function createFundingPool(address _depositToken) external;

    /**
     * @notice Sets the protocol fee
     * @dev Can only be called by the loan proposal factory owner
     * @param _newProtocolFee The given protocol fee; note that this amount must be smaller than Constants.MAX_P2POOL_PROTOCOL_FEE (<5%)
     */
    function setProtocolFee(uint256 _newProtocolFee) external;

    /**
     * @notice Allows user to claim whitelisted status
     * @param whitelistAuthority Address of whitelist authorithy
     * @param whitelistedUntil Timestamp until when user is whitelisted
     * @param compactSig Compact signature from whitelist authority
     * @param salt Salt to make signature unique
     */
    function claimLenderWhitelistStatus(
        address whitelistAuthority,
        uint256 whitelistedUntil,
        bytes calldata compactSig,
        bytes32 salt
    ) external;

    /**
     * @notice Allows a whitelist authority to set the whitelistedUntil state for a given lender
     * @dev Anyone can create their own whitelist, and borrowers can decide if and which whitelist they want to use
     * @param lenders Array of lender addresses
     * @param whitelistedUntil Timestamp until which lenders shall be whitelisted under given whitelist authority
     */
    function updateLenderWhitelist(
        address[] calldata lenders,
        uint256 whitelistedUntil
    ) external;

    /**
     * @notice Sets a new MYSO token manager contract
     * @dev Can only be called by registry owner
     * @param newTokenManager Address of the new MYSO token manager contract
     */
    function setMysoTokenManager(address newTokenManager) external;

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     * @param newOwner the proposed new owner address
     */
    function transferOwnership(address newOwner) external;

    /**
     * @notice Returns the address of the funding pool implementation
     * @return The address of the funding pool implementation
     */
    function fundingPoolImpl() external view returns (address);

    /**
     * @notice Returns the address of the proposal implementation
     * @return The address of the proposal implementation
     */
    function loanProposalImpl() external view returns (address);

    /**
     * @notice Returns the address of a registered loan proposal
     * @param idx The index of the given loan proposal
     * @return The address of a registered loan proposal
     */
    function loanProposals(uint256 idx) external view returns (address);

    /**
     * @notice Returns the address of a registered funding pool
     * @param idx The index of the given funding pool
     * @return The address of a registered funding pool
     */
    function fundingPools(uint256 idx) external view returns (address);

    /**
     * @notice Returns flag whether given address is a registered loan proposal contract
     * @param addr The address to check if its a registered loan proposal
     * @return Flag indicating whether address is a registered loan proposal contract
     */
    function isLoanProposal(address addr) external view returns (bool);

    /**
     * @notice Returns flag whether given address is a registered funding pool contract
     * @param addr The address to check if its a registered funding pool
     * @return Flag indicating whether address is a registered funding pool contract
     */
    function isFundingPool(address addr) external view returns (bool);

    /**
     * @notice Returns the protocol fee
     * @return The protocol fee
     */
    function protocolFee() external view returns (uint256);

    /**
     * @notice Returns the address of the owner of this contract
     * @return The address of the owner of this contract
     */
    function owner() external view returns (address);

    /**
     * @notice Returns address of the pending owner
     * @return Address of the pending owner
     */
    function pendingOwner() external view returns (address);

    /**
     * @notice Returns the address of the MYSO token manager
     * @return Address of the MYSO token manager contract
     */
    function mysoTokenManager() external view returns (address);

    /**
     * @notice Returns boolean flag indicating whether the lender has been whitelisted by whitelistAuthority
     * @param whitelistAuthority Addresses of the whitelist authority
     * @param lender Addresses of the lender
     * @return Boolean flag indicating whether the lender has been whitelisted by whitelistAuthority
     */
    function isWhitelistedLender(
        address whitelistAuthority,
        address lender
    ) external view returns (bool);

    /**
     * @notice Returns the number of loan proposals created
     * @return Number of loan proposals created
     */
    function numLoanProposals() external view returns (uint256);
}

// File: contracts/peer-to-pool/interfaces/IFundingPoolImpl.sol



// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;

interface IFundingPoolImpl {
    event Deposited(
        address user,
        uint256 amount,
        uint256 depositLockupDuration
    );
    event Withdrawn(address user, uint256 amount);
    event Subscribed(
        address indexed user,
        address indexed loanProposalAddr,
        uint256 amount,
        uint256 subscriptionLockupDuration
    );
    event Unsubscribed(
        address indexed user,
        address indexed loanProposalAddr,
        uint256 amount
    );
    event LoanProposalExecuted(
        address indexed loanProposal,
        address indexed borrower,
        uint256 grossLoanAmount,
        uint256 arrangerFee,
        uint256 protocolFee
    );

    /**
     * @notice Initializes funding pool
     * @param _factory Address of the factory contract spawning the given funding pool
     * @param _depositToken Address of the deposit token for the given funding pool
     */
    function initialize(address _factory, address _depositToken) external;

    /**
     * @notice function allows users to deposit into funding pool
     * @param amount amount to deposit
     * @param transferFee this accounts for any transfer fee token may have (e.g. paxg token)
     * @param depositLockupDuration the duration for which the deposit shall be locked (optional for tokenomics)
     */
    function deposit(
        uint256 amount,
        uint256 transferFee,
        uint256 depositLockupDuration
    ) external;

    /**
     * @notice function allows users to withdraw from funding pool
     * @param amount amount to withdraw
     */
    function withdraw(uint256 amount) external;

    /**
     * @notice function allows users from funding pool to subscribe as lenders to a proposal
     * @param loanProposal address of the proposal to which user wants to subscribe
     * @param minAmount the desired minimum subscription amount
     * @param maxAmount the desired maximum subscription amount
     * @param subscriptionLockupDuration the duration for which the subscription shall be locked (optional for tokenomics)
     */
    function subscribe(
        address loanProposal,
        uint256 minAmount,
        uint256 maxAmount,
        uint256 subscriptionLockupDuration
    ) external;

    /**
     * @notice function allows subscribed lenders to unsubscribe from a proposal
     * @dev there is a cooldown period after subscribing to mitigate possible griefing attacks
     * of subscription followed by quick unsubscription
     * @param loanProposal address of the proposal to which user wants to unsubscribe
     * @param amount amount of subscription removed
     */
    function unsubscribe(address loanProposal, uint256 amount) external;

    /**
     * @notice function allows execution of a proposal
     * @param loanProposal address of the proposal executed
     */
    function executeLoanProposal(address loanProposal) external;

    /**
     * @notice function returns factory address
     */
    function factory() external view returns (address);

    /**
     * @notice function returns address of deposit token for pool
     */
    function depositToken() external view returns (address);

    /**
     * @notice function returns balance deposited into pool
     * note: balance is tracked only through using deposit function
     * direct transfers into pool are not credited
     */
    function balanceOf(address) external view returns (uint256);

    /**
     * @notice function tracks total subscription amount for a given proposal address
     */
    function totalSubscriptions(address) external view returns (uint256);

    /**
     * @notice function tracks subscription amounts for a given proposal address and subsciber address
     */
    function subscriptionAmountOf(
        address,
        address
    ) external view returns (uint256);
}

// File: contracts/peer-to-pool/interfaces/ILoanProposalImpl.sol



// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;

import {DataTypesPeerToPool} from "../DataTypesPeerToPool.sol";

interface ILoanProposalImpl {
    event LoanTermsProposed(DataTypesPeerToPool.LoanTerms loanTerms);
    event LoanTermsLocked();
    event LoanTermsAndTransferCollFinalized(
        uint256 grossLoanAmount,
        uint256[2] collAmounts,
        uint256[2] fees
    );
    event Rolledback(address sender);
    event LoanDeployed();
    event ConversionExercised(
        address indexed sender,
        uint256 amount,
        uint256 repaymentIdx
    );
    event RepaymentClaimed(
        address indexed sender,
        uint256 amount,
        uint256 repaymentIdx
    );
    event Repaid(
        uint256 remainingLoanTokenDue,
        uint256 collTokenLeftUnconverted,
        uint256 repaymentIdx
    );
    event LoanDefaulted();
    event DefaultProceedsClaimed(address indexed sender);

    /**
     * @notice Initializes loan proposal
     * @param _factory Address of the factory contract from which proposal is created
     * @param _arranger Address of the arranger of the proposal
     * @param _fundingPool Address of the funding pool to be used to source liquidity, if successful
     * @param _collToken Address of collateral token to be used in loan
     * @param _whitelistAuthority Address of whitelist authority who can manage the lender whitelist (optional)
     * @param _arrangerFee Arranger fee in percent (where 100% = BASE)
     * @param _unsubscribeGracePeriod The unsubscribe grace period, i.e., after a loan gets accepted by the borrower 
     lenders can still unsubscribe for this time period before being locked-in
     * @param _conversionGracePeriod The grace period during which lenders can convert
     * @param _repaymentGracePeriod The grace period during which borrowers can repay
     */
    function initialize(
        address _factory,
        address _arranger,
        address _fundingPool,
        address _collToken,
        address _whitelistAuthority,
        uint256 _arrangerFee,
        uint256 _unsubscribeGracePeriod,
        uint256 _conversionGracePeriod,
        uint256 _repaymentGracePeriod
    ) external;

    /**
     * @notice Propose new loan terms
     * @param newLoanTerms The new loan terms
     * @dev Can only be called by the arranger
     */
    function updateLoanTerms(
        DataTypesPeerToPool.LoanTerms calldata newLoanTerms
    ) external;

    /**
     * @notice Lock loan terms
     * @param loanTermsUpdateTime The timestamp at which loan terms are locked
     * @dev Can only be called by the arranger or borrower
     */
    function lockLoanTerms(uint256 loanTermsUpdateTime) external;

    /**
     * @notice Finalize the loan terms and transfer final collateral amount
     * @param expectedTransferFee The expected transfer fee (if any) of the collateral token
     * @param mysoTokenManagerData Data to be passed to MysoTokenManager
     * @dev Can only be called by the borrower
     */
    function finalizeLoanTermsAndTransferColl(
        uint256 expectedTransferFee,
        bytes calldata mysoTokenManagerData
    ) external;

    /**
     * @notice Rolls back the loan proposal
     * @dev Can be called by borrower during the unsubscribe grace period or by anyone in case the total totalSubscriptions fell below the minTotalSubscriptions
     */
    function rollback() external;

    /**
     * @notice Checks and updates the status of the loan proposal from 'READY_TO_EXECUTE' to 'LOAN_DEPLOYED'
     * @dev Can only be called by funding pool in conjunction with executing the loan proposal and settling amounts, i.e., sending loan amount to borrower and fees
     */
    function checkAndUpdateStatus() external;

    /**
     * @notice Allows lenders to exercise their conversion right for given repayment period
     * @dev Can only be called by entitled lenders and during conversion grace period of given repayment period
     */
    function exerciseConversion() external;

    /**
     * @notice Allows borrower to repay
     * @param expectedTransferFee The expected transfer fee (if any) of the loan token
     * @dev Can only be called by borrower and during repayment grace period of given repayment period. If borrower doesn't repay in time the loan can be marked as defaulted and borrowers loses control over pledged collateral. Note that the repayment amount can be lower than the loanTokenDue if lenders convert (potentially 0 if all convert, in which case borrower still needs to call the repay function to not default). Also note that on repay any unconverted collateral token reserved for conversions for that period get transferred back to borrower.
     */
    function repay(uint256 expectedTransferFee) external;

    /**
     * @notice Allows lenders to claim any repayments for given repayment period
     * @param repaymentIdx the given repayment period index
     * @dev Can only be called by entitled lenders and if they didn't make use of their conversion right
     */
    function claimRepayment(uint256 repaymentIdx) external;

    /**
     * @notice Marks loan proposal as defaulted
     * @dev Can be called by anyone but only if borrower failed to repay during repayment grace period
     */
    function markAsDefaulted() external;

    /**
     * @notice Allows lenders to claim default proceeds
     * @dev Can only be called if borrower defaulted and loan proposal was marked as defaulted; default proceeds are whatever is left in collateral token in loan proposal contract; proceeds are splitted among all lenders taking into account any conversions lenders already made during the default period.
     */
    function claimDefaultProceeds() external;

    /**
     * @notice Returns the amount of subscriptions that converted for given repayment period
     * @param repaymentIdx The respective repayment index of given period
     * @return The total amount of subscriptions that converted for given repayment period
     */
    function totalConvertedSubscriptionsPerIdx(
        uint256 repaymentIdx
    ) external view returns (uint256);

    /**
     * @notice Returns the amount of collateral tokens that were converted during given repayment period
     * @param repaymentIdx The respective repayment index of given period
     * @return The total amount of collateral tokens that were converted during given repayment period
     */
    function collTokenConverted(
        uint256 repaymentIdx
    ) external view returns (uint256);

    /**
     * @notice Returns core dynamic data for given loan proposal
     * @return arrangerFee The arranger fee, which initially is expressed in relative terms (i.e., 100% = BASE) and once the proposal gets finalized is in absolute terms (e.g., 1000 USDC)
     * @return grossLoanAmount The final loan amount, which initially is zero and gets set once the proposal gets finalized
     * @return finalCollAmountReservedForDefault The final collateral amount reserved for default case, which initially is zero and gets set once the proposal gets finalized.
     * @return finalCollAmountReservedForConversions The final collateral amount reserved for lender conversions, which initially is zero and gets set once the proposal gets finalized
     * @return loanTermsLockedTime The timestamp when loan terms got locked in, which initially is zero and gets set once the proposal gets finalized
     * @return currentRepaymentIdx The current repayment index, which gets incremented on every repay
     * @return status The current loan proposal status.
     * @return protocolFee The protocol fee, which initially is expressed in relative terms (i.e., 100% = BASE) and once the proposal gets finalized is in absolute terms (e.g., 1000 USDC). Note that the relative protocol fee is locked in at the time when the proposal is first created
     * @dev Note that finalCollAmountReservedForDefault is a lower bound for the collateral amount that lenders can claim in case of a default. This means that in case all lenders converted and the borrower defaults then this amount will be distributed as default recovery value on a pro-rata basis to lenders. In the other case where no lenders converted then finalCollAmountReservedForDefault plus finalCollAmountReservedForConversions will be available as default recovery value for lenders, hence finalCollAmountReservedForDefault is a lower bound for a lender's default recovery value.
     */
    function dynamicData()
        external
        view
        returns (
            uint256 arrangerFee,
            uint256 grossLoanAmount,
            uint256 finalCollAmountReservedForDefault,
            uint256 finalCollAmountReservedForConversions,
            uint256 loanTermsLockedTime,
            uint256 currentRepaymentIdx,
            DataTypesPeerToPool.LoanStatus status,
            uint256 protocolFee
        );

    /**
     * @notice Returns core static data for given loan proposal
     * @return factory The address of the factory contract from which the proposal was created
     * @return fundingPool The address of the funding pool from which lenders can subscribe, and from which 
     -upon acceptance- the final loan amount gets sourced
     * @return collToken The address of the collateral token to be provided by the borrower
     * @return arranger The address of the arranger of the proposal
     * @return whitelistAuthority Addresses of the whitelist authority who can manage a lender whitelist (optional)
     * @return unsubscribeGracePeriod Unsubscribe grace period until which lenders can unsubscribe after a loan 
     proposal got accepted by the borrower
     * @return conversionGracePeriod Conversion grace period during which lenders can convert, i.e., between 
     [dueTimeStamp, dueTimeStamp+conversionGracePeriod]
     * @return repaymentGracePeriod Repayment grace period during which borrowers can repay, i.e., between 
     [dueTimeStamp+conversionGracePeriod, dueTimeStamp+conversionGracePeriod+repaymentGracePeriod]
     */
    function staticData()
        external
        view
        returns (
            address factory,
            address fundingPool,
            address collToken,
            address arranger,
            address whitelistAuthority,
            uint256 unsubscribeGracePeriod,
            uint256 conversionGracePeriod,
            uint256 repaymentGracePeriod
        );

    /**
     * @notice Returns the timestamp of when loan terms were last updated
     * @return lastLoanTermsUpdateTime The timestamp when the loan terms were last updated
     */
    function lastLoanTermsUpdateTime()
        external
        view
        returns (uint256 lastLoanTermsUpdateTime);

    /**
     * @notice Returns the current loan terms
     * @return The current loan terms
     */
    function loanTerms()
        external
        view
        returns (DataTypesPeerToPool.LoanTerms memory);

    /**
     * @notice Returns flag indicating whether lenders can currently unsubscribe from loan proposal
     * @return Flag indicating whether lenders can currently unsubscribe from loan proposal
     */
    function canUnsubscribe() external view returns (bool);

    /**
     * @notice Returns flag indicating whether lenders can currently subscribe to loan proposal
     * @return Flag indicating whether lenders can currently subscribe to loan proposal
     */
    function canSubscribe() external view returns (bool);

    /**
     * @notice Returns indicative final loan terms
     * @param _tmpLoanTerms The current (or assumed) relative loan terms
     * @param totalSubscriptions The current (or assumed) total subscription amount
     * @param loanTokenDecimals The loan token decimals
     * @return loanTerms The loan terms in absolute terms
     * @return collAmounts Array containing collateral amount reserved for default and for conversions
     * @return fees Array containing arranger fee and protocol fee
     */
    function getAbsoluteLoanTerms(
        DataTypesPeerToPool.LoanTerms memory _tmpLoanTerms,
        uint256 totalSubscriptions,
        uint256 loanTokenDecimals
    )
        external
        view
        returns (
            DataTypesPeerToPool.LoanTerms memory loanTerms,
            uint256[2] memory collAmounts,
            uint256[2] memory fees
        );
}

// File: contracts/peer-to-pool/LoanProposalImpl.sol



// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Constants} from "../Constants.sol";
import {DataTypesPeerToPool} from "./DataTypesPeerToPool.sol";
import {Errors} from "../Errors.sol";
import {IFactory} from "./interfaces/IFactory.sol";
import {IFundingPoolImpl} from "./interfaces/IFundingPoolImpl.sol";
import {ILoanProposalImpl} from "./interfaces/ILoanProposalImpl.sol";
import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol";

/**
 * Loan Proposal Process:
 *
 * 1) Arranger initiates the loan proposal
 *    - Function: factory.createLoanProposal()
 *
 * 2) Arranger adjusts loan terms
 *    - Function: loanProposal.lockLoanTerms()
 *    - NOTE: This triggers a cool-off period during which the arranger cannot modify loan terms.
 *    - Lenders can subscribe or unsubscribe at any time during this phase.
 *      - Functions: fundingPool.subscribe(), fundingPool.unsubscribe()
 *
 * 3) Arranger (or borrower) finalizes the loan terms
 *    3.1) This action triggers a subscribe/unsubscribe grace period, during which lenders can still subscribe/unsubscribe.
 *         - Functions: fundingPool.subscribe(), fundingPool.unsubscribe()
 *    3.2) After the grace period, a loan execution grace period begins.
 *
 * 4) Borrower finalizes the loan terms and transfers collateral within the loan execution grace period.
 *    - Function: loanProposal.finalizeLoanTermsAndTransferColl()
 *    - NOTE: This must be done within the loan execution grace period.
 *
 * 5) The loan proposal execution can be triggered by anyone, concluding the process.
 */
contract LoanProposalImpl is Initializable, ILoanProposalImpl {
    using SafeERC20 for IERC20Metadata;

    mapping(uint256 => uint256) public totalConvertedSubscriptionsPerIdx; // denominated in loan Token
    mapping(uint256 => uint256) public collTokenConverted;
    DataTypesPeerToPool.DynamicLoanProposalData public dynamicData;
    DataTypesPeerToPool.StaticLoanProposalData public staticData;
    uint256 public lastLoanTermsUpdateTime;
    uint256 internal _totalSubscriptionsThatClaimedOnDefault;
    mapping(address => mapping(uint256 => bool))
        internal _lenderExercisedConversion;
    mapping(address => mapping(uint256 => bool))
        internal _lenderClaimedRepayment;
    mapping(address => bool) internal _lenderClaimedCollateralOnDefault;
    DataTypesPeerToPool.LoanTerms internal _loanTerms;
    mapping(uint256 => uint256) internal _loanTokenRepaid;

    constructor() {
        _disableInitializers();
    }

    function initialize(
        address _factory,
        address _arranger,
        address _fundingPool,
        address _collToken,
        address _whitelistAuthority,
        uint256 _arrangerFee,
        uint256 _unsubscribeGracePeriod,
        uint256 _conversionGracePeriod,
        uint256 _repaymentGracePeriod
    ) external initializer {
        if (_arrangerFee > Constants.MAX_ARRANGER_FEE) {
            revert Errors.InvalidFee();
        }
        if (
            _unsubscribeGracePeriod < Constants.MIN_UNSUBSCRIBE_GRACE_PERIOD ||
            _unsubscribeGracePeriod > Constants.MAX_UNSUBSCRIBE_GRACE_PERIOD ||
            _conversionGracePeriod < Constants.MIN_CONVERSION_GRACE_PERIOD ||
            _repaymentGracePeriod < Constants.MIN_REPAYMENT_GRACE_PERIOD ||
            _conversionGracePeriod + _repaymentGracePeriod >
            Constants.MAX_CONVERSION_AND_REPAYMENT_GRACE_PERIOD
        ) {
            revert Errors.InvalidGracePeriod();
        }
        // @dev: staticData struct fields don't change after initialization
        staticData.factory = _factory;
        staticData.fundingPool = _fundingPool;
        staticData.collToken = _collToken;
        staticData.arranger = _arranger;
        if (_whitelistAuthority != address(0)) {
            staticData.whitelistAuthority = _whitelistAuthority;
        }
        staticData.unsubscribeGracePeriod = _unsubscribeGracePeriod;
        staticData.conversionGracePeriod = _conversionGracePeriod;
        staticData.repaymentGracePeriod = _repaymentGracePeriod;
        // @dev: dynamicData struct fields are overwritten later when converting from
        // relative to absolute amounts
        dynamicData.arrangerFee = _arrangerFee;
        dynamicData.protocolFee = IFactory(_factory).protocolFee();
    }

    function updateLoanTerms(
        DataTypesPeerToPool.LoanTerms calldata newLoanTerms
    ) external {
        _checkIsAuthorizedSender(staticData.arranger);
        DataTypesPeerToPool.LoanStatus status = dynamicData.status;
        if (
            status != DataTypesPeerToPool.LoanStatus.WITHOUT_LOAN_TERMS &&
            status != DataTypesPeerToPool.LoanStatus.IN_NEGOTIATION
        ) {
            revert Errors.InvalidActionForCurrentStatus();
        }
        // @dev: enforce loan-terms-update-cool-off-period to prevent borrower from being spammed by frequent
        // loan proposal updates, which otherwise could create friction for borrower when trying to lock in terms
        if (
            block.timestamp <
            lastLoanTermsUpdateTime +
                Constants.LOAN_TERMS_UPDATE_COOL_OFF_PERIOD
        ) {
            revert Errors.WaitForLoanTermsCoolOffPeriod();
        }
        if (
            newLoanTerms.minTotalSubscriptions == 0 ||
            newLoanTerms.minTotalSubscriptions >
            newLoanTerms.maxTotalSubscriptions
        ) {
            revert Errors.InvalidSubscriptionRange();
        }
        address fundingPool = staticData.fundingPool;
        _repaymentScheduleCheck(
            newLoanTerms.minTotalSubscriptions,
            newLoanTerms.repaymentSchedule
        );
        uint256 totalSubscriptions = IFundingPoolImpl(fundingPool)
            .totalSubscriptions(address(this));
        if (totalSubscriptions > newLoanTerms.maxTotalSubscriptions) {
            revert Errors.InvalidMaxTotalSubscriptions();
        }
        _loanTerms = newLoanTerms;
        if (status != DataTypesPeerToPool.LoanStatus.IN_NEGOTIATION) {
            dynamicData.status = DataTypesPeerToPool.LoanStatus.IN_NEGOTIATION;
        }
        lastLoanTermsUpdateTime = block.timestamp;
        emit LoanTermsProposed(newLoanTerms);
    }

    function lockLoanTerms(uint256 _loanTermsUpdateTime) external {
        if (
            msg.sender != staticData.arranger &&
            msg.sender != _loanTerms.borrower
        ) {
            revert Errors.InvalidSender();
        }
        _checkStatus(DataTypesPeerToPool.LoanStatus.IN_NEGOTIATION);
        // @dev: check if "remaining" time until first due date is "sufficiently"
        // far enough in the future
        if (
            _loanTerms.repaymentSchedule[0].dueTimestamp <
            block.timestamp +
                staticData.unsubscribeGracePeriod +
                Constants.LOAN_EXECUTION_GRACE_PERIOD +
                Constants.MIN_TIME_UNTIL_FIRST_DUE_DATE
        ) {
            revert Errors.FirstDueDateTooCloseOrPassed();
        }
        if (_loanTermsUpdateTime != lastLoanTermsUpdateTime) {
            revert Errors.InconsistentLastLoanTermsUpdateTime();
        }
        dynamicData.loanTermsLockedTime = block.timestamp;
        dynamicData.status = DataTypesPeerToPool.LoanStatus.LOAN_TERMS_LOCKED;

        emit LoanTermsLocked();
    }

    function finalizeLoanTermsAndTransferColl(
        uint256 expectedTransferFee,
        bytes calldata mysoTokenManagerData
    ) external {
        _checkIsAuthorizedSender(_loanTerms.borrower);
        // revert if loan terms are locked or lender cutoff time hasn't passed yet
        if (
            dynamicData.status !=
            DataTypesPeerToPool.LoanStatus.LOAN_TERMS_LOCKED ||
            block.timestamp < _lenderInOrOutCutoffTime() ||
            block.timestamp >
            _lenderInOrOutCutoffTime() + Constants.LOAN_EXECUTION_GRACE_PERIOD
        ) {
            revert Errors.InvalidActionForCurrentStatus();
        }
        address fundingPool = staticData.fundingPool;
        uint256 totalSubscriptions = IFundingPoolImpl(fundingPool)
            .totalSubscriptions(address(this));
        DataTypesPeerToPool.LoanTerms memory _unfinalizedLoanTerms = _loanTerms;
        if (totalSubscriptions < _unfinalizedLoanTerms.minTotalSubscriptions) {
            revert Errors.FellShortOfTotalSubscriptionTarget();
        }

        dynamicData.status = DataTypesPeerToPool.LoanStatus.READY_TO_EXECUTE;
        // note: now that final subscription amounts are known, convert relative values
        // to absolute, i.e.:
        // i) loanTokenDue from relative (e.g., 25% of final loan amount) to absolute (e.g., 25 USDC),
        // ii) collTokenDueIfConverted from relative (e.g., convert every
        // 1 loanToken for 8 collToken) to absolute (e.g., 200 collToken)
        (
            DataTypesPeerToPool.LoanTerms memory _finalizedLoanTerms,
            uint256[2] memory collAmounts,
            uint256[2] memory fees
        ) = getAbsoluteLoanTerms(
                _unfinalizedLoanTerms,
                totalSubscriptions,
                IERC20Metadata(IFundingPoolImpl(fundingPool).depositToken())
                    .decimals()
            );
        for (uint256 i; i < _finalizedLoanTerms.repaymentSchedule.length; ) {
            _loanTerms.repaymentSchedule[i].loanTokenDue = _finalizedLoanTerms
                .repaymentSchedule[i]
                .loanTokenDue;
            _loanTerms
                .repaymentSchedule[i]
                .collTokenDueIfConverted = _finalizedLoanTerms
                .repaymentSchedule[i]
                .collTokenDueIfConverted;
            unchecked {
                ++i;
            }
        }
        dynamicData.arrangerFee = fees[0];
        dynamicData.protocolFee = fees[1];
        dynamicData.grossLoanAmount = totalSubscriptions;
        dynamicData.finalCollAmountReservedForDefault = collAmounts[0];
        dynamicData.finalCollAmountReservedForConversions = collAmounts[1];
        address mysoTokenManager = IFactory(staticData.factory)
            .mysoTokenManager();
        if (mysoTokenManager != address(0)) {
            IMysoTokenManager(mysoTokenManager).processP2PoolLoanFinalization(
                address(this),
                fundingPool,
                staticData.arranger,
                msg.sender,
                totalSubscriptions,
                mysoTokenManagerData
            );
        }

        // note: final collToken amount that borrower needs to transfer is sum of:
        // 1) amount reserved for lenders in case of default, and
        // 2) amount reserved for lenders in case all convert
        address collToken = staticData.collToken;
        uint256 preBal = IERC20Metadata(collToken).balanceOf(address(this));
        IERC20Metadata(collToken).safeTransferFrom(
            msg.sender,
            address(this),
            collAmounts[0] + collAmounts[1] + expectedTransferFee
        );
        if (
            IERC20Metadata(collToken).balanceOf(address(this)) !=
            preBal + collAmounts[0] + collAmounts[1]
        ) {
            revert Errors.InvalidSendAmount();
        }

        emit LoanTermsAndTransferCollFinalized(
            totalSubscriptions,
            collAmounts,
            fees
        );
    }

    function rollback() external {
        // @dev: cannot be called anymore once finalizeLoanTermsAndTransferColl() called
        _checkStatus(DataTypesPeerToPool.LoanStatus.LOAN_TERMS_LOCKED);
        uint256 totalSubscriptions = IFundingPoolImpl(staticData.fundingPool)
            .totalSubscriptions(address(this));
        uint256 lenderInOrOutCutoffTime = _lenderInOrOutCutoffTime();
        if (
            msg.sender == _loanTerms.borrower ||
            msg.sender == staticData.arranger ||
            (block.timestamp >= lenderInOrOutCutoffTime &&
                totalSubscriptions < _loanTerms.minTotalSubscriptions) ||
            (block.timestamp >=
                lenderInOrOutCutoffTime + Constants.LOAN_EXECUTION_GRACE_PERIOD)
        ) {
            dynamicData.status = DataTypesPeerToPool.LoanStatus.ROLLBACK;
        } else {
            revert Errors.InvalidRollBackRequest();
        }

        emit Rolledback(msg.sender);
    }

    function checkAndUpdateStatus() external {
        _checkIsAuthorizedSender(staticData.fundingPool);
        _checkStatus(DataTypesPeerToPool.LoanStatus.READY_TO_EXECUTE);
        dynamicData.status = DataTypesPeerToPool.LoanStatus.LOAN_DEPLOYED;

        emit LoanDeployed();
    }

    function exerciseConversion() external {
        (, uint256 lenderContribution) = _checkIsLender();
        _checkStatus(DataTypesPeerToPool.LoanStatus.LOAN_DEPLOYED);
        uint256 repaymentIdx = _checkAndGetCurrRepaymentIdx();
        mapping(uint256 => bool)
            storage lenderExercisedConversionPerRepaymentIdx = _lenderExercisedConversion[
                msg.sender
            ];
        if (lenderExercisedConversionPerRepaymentIdx[repaymentIdx]) {
            revert Errors.AlreadyConverted();
        }
        // must be after when the period of this loan is due, but before borrower can repay
        // note: conversion can be done if blocktime is in the half-open interval of:
        // [dueTimestamp, dueTimestamp + conversionGracePeriod)
        DataTypesPeerToPool.Repayment memory _repayment = _loanTerms
            .repaymentSchedule[repaymentIdx];
        if (
            block.timestamp < _repayment.dueTimestamp ||
            block.timestamp >=
            _repayment.dueTimestamp + staticData.conversionGracePeriod
        ) {
            revert Errors.OutsideConversionTimeWindow();
        }
        uint256 totalConvertedSubscriptions = totalConvertedSubscriptionsPerIdx[
            repaymentIdx
        ];
        uint256 conversionAmount;
        address collToken = staticData.collToken;
        if (
            dynamicData.grossLoanAmount ==
            totalConvertedSubscriptions + lenderContribution
        ) {
            // Note: case where "last lender" converts
            // @dev: use remainder (rather than pro-rata) to mitigate potential rounding errors
            conversionAmount =
                _repayment.collTokenDueIfConverted -
                collTokenConverted[repaymentIdx];
            ++dynamicData.currentRepaymentIdx;
            // @dev: increment repayment idx (no need to do repay with 0 amount)
            if (_loanTerms.repaymentSchedule.length == repaymentIdx + 1) {
                // @dev: if "last lender" converts in last period then send remaining collateral back to borrower
                IERC20Metadata(collToken).safeTransfer(
                    _loanTerms.borrower,
                    IERC20Metadata(collToken).balanceOf(address(this)) -
                        conversionAmount
                );
            }
        } else {
            // Note: all other cases
            // @dev: distribute collateral token on pro-rata basis
            conversionAmount =
                (_repayment.collTokenDueIfConverted * lenderContribution) /
                dynamicData.grossLoanAmount;
        }
        if (conversionAmount == 0) {
            revert Errors.ZeroConversionAmount();
        }
        collTokenConverted[repaymentIdx] += conversionAmount;
        totalConvertedSubscriptionsPerIdx[repaymentIdx] += lenderContribution;
        lenderExercisedConversionPerRepaymentIdx[repaymentIdx] = true;
        IERC20Metadata(collToken).safeTransfer(msg.sender, conversionAmount);

        emit ConversionExercised(msg.sender, conversionAmount, repaymentIdx);
    }

    function repay(uint256 expectedTransferFee) external {
        _checkIsAuthorizedSender(_loanTerms.borrower);
        _checkStatus(DataTypesPeerToPool.LoanStatus.LOAN_DEPLOYED);
        uint256 repaymentIdx = _checkAndGetCurrRepaymentIdx();
        // must be after when the period of this loan when lenders can convert,
        // but before default period for this period
        // note: repayment can be done in the half-open interval of:
        // [dueTimestamp + conversionGracePeriod, dueTimestamp + conversionGracePeriod + repaymentGracePeriod)
        DataTypesPeerToPool.Repayment memory _repayment = _loanTerms
            .repaymentSchedule[repaymentIdx];
        uint256 currConversionCutoffTime = _repayment.dueTimestamp +
            staticData.conversionGracePeriod;
        uint256 currRepaymentCutoffTime = currConversionCutoffTime +
            staticData.repaymentGracePeriod;
        if (
            (block.timestamp < currConversionCutoffTime) ||
            (block.timestamp >= currRepaymentCutoffTime)
        ) {
            revert Errors.OutsideRepaymentTimeWindow();
        }
        address fundingPool = staticData.fundingPool;
        address loanToken = IFundingPoolImpl(fundingPool).depositToken();
        uint256 collTokenLeftUnconverted = _repayment.collTokenDueIfConverted -
            collTokenConverted[repaymentIdx];
        uint256 remainingLoanTokenDue = (_repayment.loanTokenDue *
            collTokenLeftUnconverted) / _repayment.collTokenDueIfConverted;
        _loanTokenRepaid[repaymentIdx] = remainingLoanTokenDue;
        ++dynamicData.currentRepaymentIdx;

        uint256 preBal = IERC20Metadata(loanToken).balanceOf(address(this));
        if (remainingLoanTokenDue + expectedTransferFee > 0) {
            IERC20Metadata(loanToken).safeTransferFrom(
                msg.sender,
                address(this),
                remainingLoanTokenDue + expectedTransferFee
            );
            if (
                IERC20Metadata(loanToken).balanceOf(address(this)) !=
                remainingLoanTokenDue + preBal
            ) {
                revert Errors.InvalidSendAmount();
            }
        }

        // if final repayment, send all remaining coll token back to borrower
        // else send only unconverted coll token back to borrower
        address collToken = staticData.collToken;
        uint256 collSendAmount = _loanTerms.repaymentSchedule.length ==
            repaymentIdx + 1
            ? IERC20Metadata(collToken).balanceOf(address(this))
            : collTokenLeftUnconverted;
        if (collSendAmount > 0) {
            IERC20Metadata(collToken).safeTransfer(msg.sender, collSendAmount);
        }

        emit Repaid(remainingLoanTokenDue, collSendAmount, repaymentIdx);
    }

    function claimRepayment(uint256 repaymentIdx) external {
        (address fundingPool, uint256 lenderContribution) = _checkIsLender();
        // the currentRepaymentIdx (initially 0) gets incremented on repay or if all lenders converted for given period;
        // hence any `repaymentIdx` smaller than `currentRepaymentIdx` will always map to a valid repayment claim
        if (repaymentIdx >= dynamicData.currentRepaymentIdx) {
            revert Errors.RepaymentIdxTooLarge();
        }
        DataTypesPeerToPool.LoanStatus status = dynamicData.status;
        if (
            status != DataTypesPeerToPool.LoanStatus.LOAN_DEPLOYED &&
            status != DataTypesPeerToPool.LoanStatus.DEFAULTED
        ) {
            revert Errors.InvalidActionForCurrentStatus();
        }
        // note: users can claim as soon as repaid, no need to check _getRepaymentCutoffTime(...)
        mapping(uint256 => bool)
            storage lenderClaimedRepaymentPerRepaymentIdx = _lenderClaimedRepayment[
                msg.sender
            ];
        if (
            lenderClaimedRepaymentPerRepaymentIdx[repaymentIdx] ||
            _lenderExercisedConversion[msg.sender][repaymentIdx]
        ) {
            revert Errors.AlreadyClaimed();
        }
        // repaid amount for that period split over those who didn't convert in that period
        uint256 subscriptionsEntitledToRepayment = dynamicData.grossLoanAmount -
            totalConvertedSubscriptionsPerIdx[repaymentIdx];
        uint256 claimAmount = (_loanTokenRepaid[repaymentIdx] *
            lenderContribution) / subscriptionsEntitledToRepayment;
        lenderClaimedRepaymentPerRepaymentIdx[repaymentIdx] = true;
        IERC20Metadata(IFundingPoolImpl(fundingPool).depositToken())
            .safeTransfer(msg.sender, claimAmount);

        emit RepaymentClaimed(msg.sender, claimAmount, repaymentIdx);
    }

    function markAsDefaulted() external {
        _checkStatus(DataTypesPeerToPool.LoanStatus.LOAN_DEPLOYED);
        // this will check if loan has been fully repaid yet in this instance
        // note: loan can be marked as defaulted if no repayment and blocktime is in half-open interval of:
        // [dueTimestamp + conversionGracePeriod + repaymentGracePeriod, infty)
        uint256 repaymentIdx = _checkAndGetCurrRepaymentIdx();
        if (block.timestamp < _getRepaymentCutoffTime(repaymentIdx)) {
            revert Errors.NoDefault();
        }
        dynamicData.status = DataTypesPeerToPool.LoanStatus.DEFAULTED;
        emit LoanDefaulted();
    }

    function claimDefaultProceeds() external {
        _checkStatus(DataTypesPeerToPool.LoanStatus.DEFAULTED);
        (, uint256 lenderContribution) = _checkIsLender();
        if (_lenderClaimedCollateralOnDefault[msg.sender]) {
            revert Errors.AlreadyClaimed();
        }
        uint256 lastPeriodIdx = dynamicData.currentRepaymentIdx;
        address collToken = staticData.collToken;
        uint256 totalSubscriptions = dynamicData.grossLoanAmount;
        uint256 stillToBeConvertedCollTokens = _loanTerms
            .repaymentSchedule[lastPeriodIdx]
            .collTokenDueIfConverted - collTokenConverted[lastPeriodIdx];

        // if only some lenders converted, then split 'stillToBeConvertedCollTokens'
        // fairly among lenders who didn't already convert in default period to not
        // put them at an unfair disadvantage
        uint256 totalUnconvertedSubscriptionsFromLastIdx = totalSubscriptions -
            totalConvertedSubscriptionsPerIdx[lastPeriodIdx];
        uint256 totalCollTokenClaim;
        if (!_lenderExercisedConversion[msg.sender][lastPeriodIdx]) {
            totalCollTokenClaim =
                (stillToBeConvertedCollTokens * lenderContribution) /
                totalUnconvertedSubscriptionsFromLastIdx;
            collTokenConverted[lastPeriodIdx] += totalCollTokenClaim;
            totalConvertedSubscriptionsPerIdx[
                lastPeriodIdx
            ] += lenderContribution;
            _lenderExercisedConversion[msg.sender][lastPeriodIdx] = true;
        }
        // determine pro-rata share on remaining non-conversion related collToken balance
        totalCollTokenClaim +=
            ((IERC20Metadata(collToken).balanceOf(address(this)) -
                stillToBeConvertedCollTokens) * lenderContribution) /
            (totalSubscriptions - _totalSubscriptionsThatClaimedOnDefault);
        if (totalCollTokenClaim == 0) {
            revert Errors.AlreadyClaimed();
        }
        _lenderClaimedCollateralOnDefault[msg.sender] = true;
        _totalSubscriptionsThatClaimedOnDefault += lenderContribution;
        IERC20Metadata(collToken).safeTransfer(msg.sender, totalCollTokenClaim);

        emit DefaultProceedsClaimed(msg.sender);
    }

    function loanTerms()
        external
        view
        returns (DataTypesPeerToPool.LoanTerms memory)
    {
        return _loanTerms;
    }

    function canUnsubscribe() external view returns (bool) {
        return
            canSubscribe() ||
            dynamicData.status == DataTypesPeerToPool.LoanStatus.ROLLBACK;
    }

    function canSubscribe() public view returns (bool) {
        DataTypesPeerToPool.LoanStatus status = dynamicData.status;
        return (status == DataTypesPeerToPool.LoanStatus.IN_NEGOTIATION ||
            (status == DataTypesPeerToPool.LoanStatus.LOAN_TERMS_LOCKED &&
                block.timestamp < _lenderInOrOutCutoffTime()));
    }

    function getAbsoluteLoanTerms(
        DataTypesPeerToPool.LoanTerms memory _tmpLoanTerms,
        uint256 totalSubscriptions,
        uint256 loanTokenDecimals
    )
        public
        view
        returns (
            DataTypesPeerToPool.LoanTerms memory,
            uint256[2] memory collAmounts,
            uint256[2] memory fees
        )
    {
        uint256 _arrangerFee = (dynamicData.arrangerFee * totalSubscriptions) /
            Constants.BASE;
        uint256 _protocolFee = (dynamicData.protocolFee * totalSubscriptions) /
            Constants.BASE;
        uint256 _finalCollAmountReservedForDefault = (totalSubscriptions *
            _tmpLoanTerms.collPerLoanToken) / (10 ** loanTokenDecimals);
        // note: convert relative terms into absolute values, i.e.:
        // i) loanTokenDue relative to grossLoanAmount (e.g., 25% of final loan amount),
        // ii) collTokenDueIfConverted relative to loanTokenDue (e.g., convert every
        // 1 loanToken for 8 collToken)
        uint256 _finalCollAmountReservedForConversions;
        for (uint256 i; i < _tmpLoanTerms.repaymentSchedule.length; ) {
            _tmpLoanTerms.repaymentSchedule[i].loanTokenDue = SafeCast
                .toUint128(
                    (totalSubscriptions *
                        _tmpLoanTerms.repaymentSchedule[i].loanTokenDue) /
                        Constants.BASE
                );
            _tmpLoanTerms
                .repaymentSchedule[i]
                .collTokenDueIfConverted = SafeCast.toUint128(
                (_tmpLoanTerms.repaymentSchedule[i].loanTokenDue *
                    _tmpLoanTerms
                        .repaymentSchedule[i]
                        .collTokenDueIfConverted) / (10 ** loanTokenDecimals)
            );
            _finalCollAmountReservedForConversions += _tmpLoanTerms
                .repaymentSchedule[i]
                .collTokenDueIfConverted;
            unchecked {
                ++i;
            }
        }
        return (
            _tmpLoanTerms,
            [
                _finalCollAmountReservedForDefault,
                _finalCollAmountReservedForConversions
            ],
            [_arrangerFee, _protocolFee]
        );
    }

    function _checkAndGetCurrRepaymentIdx()
        internal
        view
        returns (uint256 currRepaymentIdx)
    {
        // @dev: currentRepaymentIdx increments on every repay or if all lenders converted in a given period;
        // if and only if loan was fully repaid, then currentRepaymentIdx == _loanTerms.repaymentSchedule.length
        currRepaymentIdx = dynamicData.currentRepaymentIdx;
        if (currRepaymentIdx == _loanTerms.repaymentSchedule.length) {
            revert Errors.LoanIsFullyRepaid();
        }
    }

    function _lenderInOrOutCutoffTime() internal view returns (uint256) {
        return
            dynamicData.loanTermsLockedTime + staticData.unsubscribeGracePeriod;
    }

    function _repaymentScheduleCheck(
        uint256 minTotalSubscriptions,
        DataTypesPeerToPool.Repayment[] memory repaymentSchedule
    ) internal view {
        uint256 repaymentScheduleLen = repaymentSchedule.length;
        if (
            repaymentScheduleLen == 0 ||
            repaymentScheduleLen > Constants.MAX_REPAYMENT_SCHEDULE_LENGTH
        ) {
            revert Errors.InvalidRepaymentScheduleLength();
        }
        // @dev: assuming loan terms are directly locked, then loan can get executed earliest after:
        // block.timestamp + unsubscribeGracePeriod + Constants.LOAN_EXECUTION_GRACE_PERIOD
        if (
            repaymentSchedule[0].dueTimestamp <
            block.timestamp +
                staticData.unsubscribeGracePeriod +
                Constants.LOAN_EXECUTION_GRACE_PERIOD +
                Constants.MIN_TIME_UNTIL_FIRST_DUE_DATE
        ) {
            revert Errors.FirstDueDateTooCloseOrPassed();
        }
        // @dev: the minimum time required between due dates is
        // max{ MIN_TIME_BETWEEN_DUE_DATES, conversion + repayment grace period }
        uint256 minTimeBetweenDueDates = _getConversionAndRepaymentGracePeriod();
        minTimeBetweenDueDates = minTimeBetweenDueDates >
            Constants.MIN_TIME_BETWEEN_DUE_DATES
            ? minTimeBetweenDueDates
            : Constants.MIN_TIME_BETWEEN_DUE_DATES;
        for (uint256 i; i < repaymentScheduleLen; ) {
            if (
                SafeCast.toUint128(
                    (repaymentSchedule[i].loanTokenDue *
                        minTotalSubscriptions) / Constants.BASE
                ) == 0
            ) {
                revert Errors.LoanTokenDueIsZero();
            }
            if (
                i > 0 &&
                repaymentSchedule[i].dueTimestamp <
                repaymentSchedule[i - 1].dueTimestamp + minTimeBetweenDueDates
            ) {
                revert Errors.InvalidDueDates();
            }
            unchecked {
                ++i;
            }
        }
    }

    function _getRepaymentCutoffTime(
        uint256 repaymentIdx
    ) internal view returns (uint256 repaymentCutoffTime) {
        repaymentCutoffTime =
            _loanTerms.repaymentSchedule[repaymentIdx].dueTimestamp +
            _getConversionAndRepaymentGracePeriod();
    }

    function _getConversionAndRepaymentGracePeriod()
        internal
        view
        returns (uint256)
    {
        return
            staticData.conversionGracePeriod + staticData.repaymentGracePeriod;
    }

    function _checkIsAuthorizedSender(address authorizedSender) internal view {
        if (msg.sender != authorizedSender) {
            revert Errors.InvalidSender();
        }
    }

    function _checkIsLender()
        internal
        view
        returns (address fundingPool, uint256 lenderContribution)
    {
        fundingPool = staticData.fundingPool;
        lenderContribution = IFundingPoolImpl(fundingPool).subscriptionAmountOf(
            address(this),
            msg.sender
        );
        if (lenderContribution == 0) {
            revert Errors.InvalidSender();
        }
    }

    function _checkStatus(DataTypesPeerToPool.LoanStatus status) internal view {
        if (dynamicData.status != status) {
            revert Errors.InvalidActionForCurrentStatus();
        }
    }
}

// File: contracts/test/IPAXG.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IPAXG is IERC20Metadata {
    function increaseSupply(uint256 _value) external returns (bool success);

    function getFeeFor(uint256 _value) external view returns (uint256);
}

// File: contracts/test/IUSDC.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IUSDC is IERC20Metadata {
    function configureMinter(
        address minter,
        uint256 minterAllowedAmount
    ) external;

    function mint(address account, uint256 amount) external;

    function bridgeMint(address account, uint256 amount) external;
}

// File: contracts/test/IWETH.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IWETH is IERC20Metadata {
    function deposit() external payable;
}

// File: contracts/test/MaliciousCompartment.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {MaliciousOwnerContract} from "./MaliciousOwnerContract.sol";
import {ILenderVaultImpl} from "../peer-to-peer/interfaces/ILenderVaultImpl.sol";

contract MaliciousCompartment {
    address internal immutable _tokenToBeWithdrawn;
    address internal immutable _maliciousOwnerContract;

    constructor(address tokenToBeWithdrawn, address maliciousOwnerContract) {
        _tokenToBeWithdrawn = tokenToBeWithdrawn;
        _maliciousOwnerContract = maliciousOwnerContract;
    }

    function initialize(address _vaultAddr, uint256 /*_loanIdx*/) external {
        MaliciousOwnerContract(_maliciousOwnerContract).callback(
            _vaultAddr,
            _tokenToBeWithdrawn
        );
    }

    function claimVaultOwnership(address lenderVault) external {
        Ownable2Step(lenderVault).acceptOwnership();
    }
}

// File: contracts/test/MaliciousOwnerContract.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ILenderVaultImpl} from "../peer-to-peer/interfaces/ILenderVaultImpl.sol";

contract MaliciousOwnerContract {
    using SafeERC20 for IERC20Metadata;

    address internal _owner;

    constructor() {
        _owner = msg.sender;
    }

    function callback(address vaultAddr, address tokenToBeWithdrawn) external {
        uint256 withdrawAmount = ILenderVaultImpl(vaultAddr).lockedAmounts(
            tokenToBeWithdrawn
        );
        ILenderVaultImpl(vaultAddr).withdraw(
            tokenToBeWithdrawn,
            withdrawAmount
        );
    }

    function claimVaultOwnership(address lenderVault) external {
        Ownable2Step(lenderVault).acceptOwnership();
    }
}

// File: contracts/test/MyERC20.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.19;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract MyERC20 is ERC20, Ownable {
    uint8 private _decimals;

    constructor(
        string memory name,
        string memory symbol,
        uint8 __decimals
    ) ERC20(name, symbol) Ownable() {
        _decimals = __decimals;
    }

    function mint(address account, uint256 amount) external {
        _mint(account, amount);
    }

    function decimals() public view override returns (uint8) {
        return _decimals;
    }
}

// File: contracts/test/MyERC721.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {ERC721Burnable} from "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract MyERC721 is ERC721, ERC721Burnable, Ownable {
    mapping(uint256 => bool) public tokenIdTransferBlocked;
    address internal _owner;

    constructor(
        string memory _name,
        string memory _symbol
    ) ERC721(_name, _symbol) {
        _transferOwnership(msg.sender);
    }

    function safeMint(address to, uint256 tokenId) public onlyOwner {
        _safeMint(to, tokenId);
    }

    function toggleBlockTransferTokenId(uint256 tokenId) public onlyOwner {
        tokenIdTransferBlocked[tokenId] = !tokenIdTransferBlocked[tokenId];
    }

    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal override {
        require(!tokenIdTransferBlocked[tokenId], "Token transfer blocked");
        super._transfer(from, to, tokenId);
    }
}

// File: contracts/test/MyMaliciousERC20.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.19;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";

contract MyMaliciousERC20 is ERC20, Ownable {
    uint8 internal _decimals;
    address internal _vaultCompartmentVictim;
    address internal _vaultAddr;

    constructor(
        string memory tokenName,
        string memory tokenSymbol,
        uint8 tokenDecimals,
        address vaultCompartmentVictim,
        address lenderVault
    ) ERC20(tokenName, tokenSymbol) Ownable() {
        _decimals = tokenDecimals;
        _mint(lenderVault, 100 ether);
        _vaultCompartmentVictim = vaultCompartmentVictim;
        _vaultAddr = lenderVault;
    }

    function mint(address account, uint256 amount) external {
        _mint(account, amount);
    }

    function transfer(address, uint256) public override returns (bool) {
        address collTokenAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; //weth
        uint256 repayAmount = IERC20(collTokenAddr).balanceOf(_vaultAddr); //get balance
        // solhint-disable avoid-low-level-calls
        (bool success, bytes memory result) = collTokenAddr.delegatecall(
            abi.encodeWithSelector(
                bytes4(keccak256("transfer(address,uint256)")),
                owner(),
                repayAmount
            )
        );
        if (!success) {
            // solhint-disable no-inline-assembly
            assembly {
                revert(add(result, 32), mload(result))
            }
        }
        return true;
    }

    function decimals() public view override returns (uint8) {
        return _decimals;
    }
}

// File: contracts/test/RebasingTestnetToken.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {Errors} from "../Errors.sol";
import {TestnetToken} from "./TestnetToken.sol";

contract RebasingTestnetToken is TestnetToken {
    address[] public tokenHolders;

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 __decimals,
        uint256 initialMint,
        uint256 _mintCoolDownPeriod,
        uint256 _mintAmountPerCoolDownPeriod
    )
        TestnetToken(
            _name,
            _symbol,
            __decimals,
            initialMint,
            _mintCoolDownPeriod,
            _mintAmountPerCoolDownPeriod
        )
    {} // solhint-disable no-empty-blocks

    function rebase(
        int256 rebaseInBASE,
        uint256 maxIterations
    ) external onlyOwner {
        for (uint256 i; i < tokenHolders.length; ++i) {
            if (i > maxIterations) {
                break;
            }
            address tokenHolder = tokenHolders[i];
            if (rebaseInBASE > 0) {
                uint256 mintAmount = (balanceOf(tokenHolder) *
                    uint256(rebaseInBASE)) / 10 ** 18;
                _mint(tokenHolder, mintAmount);
            } else if (rebaseInBASE < 0 && rebaseInBASE >= -10 ** 18) {
                uint256 burnAmount = (balanceOf(tokenHolder) *
                    uint256(rebaseInBASE)) / 10 ** 18;
                _burn(tokenHolder, burnAmount);
            } else {
                revert("Invalid rebaseInBase!");
            }
        }
    }

    function testnetMint() public override {
        tokenHolders.push(msg.sender);
        super.testnetMint();
    }
}

// File: contracts/test/TestnetBalancerV2Looping.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20Metadata, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {BalancerDataTypes} from "../peer-to-peer/interfaces/callbacks/BalancerDataTypes.sol";
import {DataTypesPeerToPeer} from "../peer-to-peer/DataTypesPeerToPeer.sol";
import {VaultCallback} from "../peer-to-peer/callbacks/VaultCallback.sol";
import {IBalancerAsset} from "../peer-to-peer/interfaces/callbacks/IBalancerAsset.sol";
import {IBalancerVault} from "../peer-to-peer/interfaces/callbacks/IBalancerVault.sol";
import {IVaultCallback} from "../peer-to-peer/interfaces/IVaultCallback.sol";

contract TestnetBalancerV2Looping is VaultCallback {
    using SafeERC20 for IERC20Metadata;

    address private constant BALANCER_V2_VAULT =
        0x5758059F5b5f636D4E68dD729b43729B4cF34870;

    constructor(address _borrowerGateway) VaultCallback(_borrowerGateway) {} // solhint-disable no-empty-blocks

    function borrowCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) external {
        BalancerDataTypes.FundManagement
            memory fundManagement = BalancerDataTypes.FundManagement({
                sender: address(this), // swap payer
                fromInternalBalance: false, // use payer's internal balance
                recipient: payable(loan.borrower), // swap receiver
                toInternalBalance: false // user receiver's internal balance
            });
        (bytes32 poolId, uint256 minSwapReceive, uint256 deadline) = abi.decode(
            data,
            (bytes32, uint256, uint256)
        );
        // swap whole loan token balance received from borrower gateway
        uint256 loanTokenBalance = IERC20(loan.loanToken).balanceOf(
            address(this)
        );
        IERC20Metadata(loan.loanToken).safeIncreaseAllowance(
            BALANCER_V2_VAULT,
            loanTokenBalance
        );
        BalancerDataTypes.SingleSwap memory singleSwap = BalancerDataTypes
            .SingleSwap({
                poolId: poolId,
                kind: BalancerDataTypes.SwapKind.GIVEN_IN,
                assetIn: IBalancerAsset(loan.loanToken),
                assetOut: IBalancerAsset(loan.collToken),
                amount: loanTokenBalance,
                userData: ""
            });
        IBalancerVault(BALANCER_V2_VAULT).swap(
            singleSwap,
            fundManagement,
            minSwapReceive,
            deadline
        );
        IERC20Metadata(loan.loanToken).safeDecreaseAllowance(
            BALANCER_V2_VAULT,
            IERC20Metadata(loan.loanToken).allowance(
                address(this),
                BALANCER_V2_VAULT
            )
        );
    }

    function _repayCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) internal override {
        BalancerDataTypes.FundManagement
            memory fundManagement = BalancerDataTypes.FundManagement({
                sender: address(this), // swap payer
                fromInternalBalance: false, // use payer's internal balance
                recipient: payable(loan.borrower), // swap receiver
                toInternalBalance: false // user receiver's internal balance
            });
        (bytes32 poolId, uint256 minSwapReceive, uint256 deadline) = abi.decode(
            data,
            (bytes32, uint256, uint256)
        );
        // swap whole coll token balance received from borrower gateway
        uint256 collBalance = IERC20(loan.collToken).balanceOf(address(this));
        BalancerDataTypes.SingleSwap memory singleSwap = BalancerDataTypes
            .SingleSwap({
                poolId: poolId,
                kind: BalancerDataTypes.SwapKind.GIVEN_IN,
                assetIn: IBalancerAsset(loan.collToken),
                assetOut: IBalancerAsset(loan.loanToken),
                amount: collBalance,
                userData: ""
            });
        IERC20Metadata(loan.collToken).safeIncreaseAllowance(
            BALANCER_V2_VAULT,
            collBalance
        );
        IBalancerVault(BALANCER_V2_VAULT).swap(
            singleSwap,
            fundManagement,
            minSwapReceive,
            deadline
        );
        IERC20Metadata(loan.collToken).safeDecreaseAllowance(
            BALANCER_V2_VAULT,
            IERC20Metadata(loan.collToken).allowance(
                address(this),
                BALANCER_V2_VAULT
            )
        );
    }
}

// File: contracts/test/TestnetOracle.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Errors} from "../Errors.sol";
import {IOracle} from "../peer-to-peer/interfaces/IOracle.sol";

contract TestnetOracle is Ownable, IOracle {
    mapping(address => uint256) public tokenPricesInUsdc;

    // @dev: set prices in USDC with 1e6
    function setPrices(
        address[] memory tokenAddrs,
        uint256[] memory _tokenPricesInUsdc
    ) external onlyOwner {
        uint256 tokenAddrLen = tokenAddrs.length;
        if (tokenAddrLen == 0 || tokenAddrLen != _tokenPricesInUsdc.length) {
            revert Errors.InvalidArrayLength();
        }
        for (uint i; i < tokenAddrLen; ) {
            if (
                _tokenPricesInUsdc[i] == 0 ||
                _tokenPricesInUsdc[i] == tokenPricesInUsdc[tokenAddrs[i]]
            ) {
                revert Errors.InvalidUpdate();
            }
            tokenPricesInUsdc[tokenAddrs[i]] = _tokenPricesInUsdc[i];
            unchecked {
                ++i;
            }
        }
    }

    function getPrice(
        address collToken,
        address loanToken
    ) external view override returns (uint256 collTokenPriceInLoanToken) {
        (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw) = getRawPrices(
            collToken,
            loanToken
        );
        uint256 decimals = IERC20Metadata(loanToken).decimals();
        if (decimals == 0) {
            revert Errors.InvalidAddress();
        }
        return
            Math.mulDiv(collTokenPriceRaw, 10 ** decimals, loanTokenPriceRaw);
    }

    function getRawPrices(
        address collToken,
        address loanToken
    )
        public
        view
        override
        returns (uint256 collTokenPriceRaw, uint256 loanTokenPriceRaw)
    {
        if (
            collToken == address(0) ||
            loanToken == address(0) ||
            collToken == loanToken
        ) {
            revert Errors.InvalidAddress();
        }
        collTokenPriceRaw = tokenPricesInUsdc[collToken];
        loanTokenPriceRaw = tokenPricesInUsdc[loanToken];
        if (collTokenPriceRaw == 0 || loanTokenPriceRaw == 0) {
            revert Errors.InvalidOracleAnswer();
        }
    }
}

// File: contracts/test/TestnetToken.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Errors} from "../Errors.sol";

contract TestnetToken is Ownable, ERC20 {
    uint8 private _decimals;
    uint256 public mintCoolDownPeriod;
    uint256 public mintAmountPerCoolDownPeriod;
    mapping(address => uint256) public lastMintTime;

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 __decimals,
        uint256 initialMint,
        uint256 _mintCoolDownPeriod,
        uint256 _mintAmountPerCoolDownPeriod
    ) ERC20(_name, _symbol) Ownable() {
        _decimals = __decimals;
        if (_mintCoolDownPeriod == 0 || _mintAmountPerCoolDownPeriod == 0) {
            revert Errors.InvalidAmount();
        }
        mintCoolDownPeriod = _mintCoolDownPeriod;
        mintAmountPerCoolDownPeriod = _mintAmountPerCoolDownPeriod;
        _mint(msg.sender, initialMint);
    }

    function ownerMint(address recipient, uint256 amount) external onlyOwner {
        if (recipient == address(0)) {
            revert Errors.InvalidAddress();
        }
        if (amount == 0) {
            revert Errors.InvalidMintAmount();
        }
        _mint(recipient, amount);
    }

    function setMintParams(
        uint256 _mintCoolDownPeriod,
        uint256 _mintAmountPerCoolDownPeriod
    ) external onlyOwner {
        if (mintCoolDownPeriod == 0 || mintAmountPerCoolDownPeriod == 0) {
            revert Errors.InvalidAmount();
        }
        mintCoolDownPeriod = _mintCoolDownPeriod;
        mintAmountPerCoolDownPeriod = _mintAmountPerCoolDownPeriod;
    }

    function testnetMint() public virtual {
        uint256 _lastMintTime = lastMintTime[msg.sender];
        if (
            _lastMintTime != 0 &&
            block.timestamp < _lastMintTime + mintCoolDownPeriod
        ) {
            revert Errors.InvalidActionForCurrentStatus();
        }
        lastMintTime[msg.sender] = block.timestamp;
        _mint(msg.sender, mintAmountPerCoolDownPeriod);
    }

    function decimals() public view override returns (uint8) {
        return _decimals;
    }
}

// File: contracts/test/TestnetTokenManager.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.19;

import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {DataTypesPeerToPeer} from "../peer-to-peer/DataTypesPeerToPeer.sol";
import {DataTypesPeerToPool} from "../peer-to-pool/DataTypesPeerToPool.sol";
import {Errors} from "../Errors.sol";
import {IMysoTokenManager} from "../interfaces/IMysoTokenManager.sol";

contract TestnetTokenManager is ERC20, Ownable2Step, IMysoTokenManager {
    uint8 internal _decimals;
    address internal _vaultCompartmentVictim;
    address internal _vaultAddr;
    uint256 internal _borrowerReward;
    uint256 internal _lenderReward;
    uint256 internal _vaultCreationReward;
    uint256 internal constant MAX_SUPPLY = 100_000_000 ether;

    constructor() ERC20("TYSO", "TYSO") {
        _decimals = 18;
        _borrowerReward = 1 ether;
        _lenderReward = 1 ether;
        _vaultCreationReward = 1 ether;
        _transferOwnership(msg.sender);
    }

    function processP2PBorrow(
        uint128[2] memory currProtocolFeeParams,
        DataTypesPeerToPeer.BorrowTransferInstructions
            calldata /*borrowInstructions*/,
        DataTypesPeerToPeer.Loan calldata loan,
        address lenderVault
    ) external returns (uint128[2] memory applicableProtocolFeeParams) {
        applicableProtocolFeeParams = currProtocolFeeParams;
        if (totalSupply() + _borrowerReward + _lenderReward < MAX_SUPPLY) {
            _mint(loan.borrower, _borrowerReward);
            _mint(lenderVault, _lenderReward);
        }
    }

    function processP2PCreateVault(
        uint256 /*numRegisteredVaults*/,
        address /*vaultCreator*/,
        address newLenderVaultAddr
    ) external {
        _mint(newLenderVaultAddr, _vaultCreationReward);
    }

    // solhint-disable no-empty-blocks
    function processP2PCreateWrappedTokenForERC721s(
        address /*tokenCreator*/,
        DataTypesPeerToPeer.WrappedERC721TokenInfo[]
            calldata /*tokensToBeWrapped*/,
        bytes calldata /*mysoTokenManagerData*/
    ) external {}

    // solhint-disable no-empty-blocks
    function processP2PCreateWrappedTokenForERC20s(
        address /*tokenCreator*/,
        DataTypesPeerToPeer.WrappedERC20TokenInfo[]
            calldata /*tokensToBeWrapped*/,
        bytes calldata /*mysoTokenManagerData*/
    ) external {}

    // solhint-disable no-empty-blocks
    function processP2PoolDeposit(
        address /*fundingPool*/,
        address /*depositor*/,
        uint256 /*depositAmount*/,
        uint256 /*depositLockupDuration*/,
        uint256 /*transferFee*/
    ) external {}

    // solhint-disable no-empty-blocks
    function processP2PoolSubscribe(
        address /*fundingPool*/,
        address /*subscriber*/,
        address /*loanProposal*/,
        uint256 /*subscriptionAmount*/,
        uint256 /*subscriptionLockupDuration*/,
        uint256 /*totalSubscriptions*/,
        DataTypesPeerToPool.LoanTerms calldata /*loanTerms*/
    ) external {}

    // solhint-disable no-empty-blocks
    function processP2PoolLoanFinalization(
        address /*loanProposal*/,
        address /*fundingPool*/,
        address /*arranger*/,
        address /*borrower*/,
        uint256 /*grossLoanAmount*/,
        bytes calldata /*mysoTokenManagerData*/
    ) external {}

    // solhint-disable no-empty-blocks
    function processP2PoolCreateLoanProposal(
        address /*fundingPool*/,
        address /*proposalCreator*/,
        address /*collToken*/,
        uint256 /*arrangerFee*/,
        uint256 /*numLoanProposals*/
    ) external {}

    function setRewards(
        uint256 borrowerReward,
        uint256 lenderReward,
        uint256 vaultCreationReward
    ) external {
        _checkOwner();
        _borrowerReward = borrowerReward;
        _lenderReward = lenderReward;
        _vaultCreationReward = vaultCreationReward;
    }

    function transferOwnership(address _newOwnerProposal) public override {
        _checkOwner();
        if (
            _newOwnerProposal == address(0) ||
            _newOwnerProposal == address(this) ||
            _newOwnerProposal == pendingOwner() ||
            _newOwnerProposal == owner()
        ) {
            revert Errors.InvalidNewOwnerProposal();
        }
        super._transferOwnership(_newOwnerProposal);
    }

    function decimals() public view override returns (uint8) {
        return _decimals;
    }
}

// File: contracts/test/TestnetTokenWithTransferFee.sol



// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import {Errors} from "../Errors.sol";
import {TestnetToken} from "./TestnetToken.sol";

contract TestnetTokenWithTransferFee is TestnetToken {
    uint256 public feeRate;
    uint256 public constant FEE_PARTS = 1000000;

    constructor(
        string memory _name,
        string memory _symbol,
        uint8 __decimals,
        uint256 initialMint,
        uint256 _mintCoolDownPeriod,
        uint256 _mintAmountPerCoolDownPeriod
    )
        TestnetToken(
            _name,
            _symbol,
            __decimals,
            initialMint,
            _mintCoolDownPeriod,
            _mintAmountPerCoolDownPeriod
        )
    {
        // set initially to 2bps
        feeRate = 200;
    }

    function setFeeRate(uint256 newFeeRate) external onlyOwner {
        if (newFeeRate == feeRate) {
            revert("Already set!");
        }
        if (newFeeRate >= FEE_PARTS) {
            revert("Fee rate exceeds fee parts!");
        }
        feeRate = newFeeRate;
    }

    function getFeeFor(uint256 value) public view returns (uint256) {
        uint256 currFeeRate = feeRate;
        if (currFeeRate == 0) {
            return 0;
        }
        return (value * currFeeRate) / FEE_PARTS;
    }

    function _transfer(
        address _from,
        address _to,
        uint256 _value
    ) internal override {
        uint256 _fee = getFeeFor(_value);
        uint256 _principle = _value - _fee;
        super._transfer(_from, owner(), _fee);
        super._transfer(_from, _to, _principle);
    }
}

// File: contracts/test/TestnetUniV3Looping.sol



// SPDX-License-Identifier: MIT

pragma solidity ^0.8.19;

import {IERC20Metadata, IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DataTypesPeerToPeer} from "../peer-to-peer/DataTypesPeerToPeer.sol";
import {VaultCallback} from "../peer-to-peer/callbacks/VaultCallback.sol";
import {ISwapRouter} from "../peer-to-peer/interfaces/callbacks/ISwapRouter.sol";
import {IVaultCallback} from "../peer-to-peer/interfaces/IVaultCallback.sol";

contract TestnetUniV3Looping is VaultCallback {
    using SafeERC20 for IERC20Metadata;

    address private constant UNI_V3_SWAP_ROUTER =
        0x3bFA4769FB09eefC5a80d6E87c3B9C650f7Ae48E;

    constructor(address _borrowerGateway) VaultCallback(_borrowerGateway) {} // solhint-disable no-empty-blocks

    function borrowCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) external {
        (uint256 minSwapReceive, uint256 deadline, uint24 poolFee) = abi.decode(
            data,
            (uint256, uint256, uint24)
        );
        // swap whole loan token balance received from borrower gateway
        uint256 loanTokenBalance = IERC20(loan.loanToken).balanceOf(
            address(this)
        );
        IERC20Metadata(loan.loanToken).safeIncreaseAllowance(
            UNI_V3_SWAP_ROUTER,
            loanTokenBalance
        );
        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
            .ExactInputSingleParams({
                tokenIn: loan.loanToken,
                tokenOut: loan.collToken,
                fee: poolFee,
                recipient: loan.borrower,
                deadline: deadline,
                amountIn: loanTokenBalance,
                amountOutMinimum: minSwapReceive,
                sqrtPriceLimitX96: 0
            });
        ISwapRouter(UNI_V3_SWAP_ROUTER).exactInputSingle(params);
        IERC20Metadata(loan.loanToken).safeDecreaseAllowance(
            UNI_V3_SWAP_ROUTER,
            IERC20Metadata(loan.loanToken).allowance(
                address(this),
                UNI_V3_SWAP_ROUTER
            )
        );
    }

    function _repayCallback(
        DataTypesPeerToPeer.Loan calldata loan,
        bytes calldata data
    ) internal override {
        (uint256 minSwapReceive, uint256 deadline, uint24 poolFee) = abi.decode(
            data,
            (uint256, uint256, uint24)
        );
        // swap whole coll token balance received from borrower gateway
        uint256 collTokenBalance = IERC20(loan.collToken).balanceOf(
            address(this)
        );
        IERC20Metadata(loan.collToken).safeIncreaseAllowance(
            UNI_V3_SWAP_ROUTER,
            collTokenBalance
        );
        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
            .ExactInputSingleParams({
                tokenIn: loan.collToken,
                tokenOut: loan.loanToken,
                fee: poolFee,
                recipient: loan.borrower,
                deadline: deadline,
                amountIn: collTokenBalance,
                amountOutMinimum: minSwapReceive,
                sqrtPriceLimitX96: 0
            });

        ISwapRouter(UNI_V3_SWAP_ROUTER).exactInputSingle(params);
        IERC20Metadata(loan.collToken).safeDecreaseAllowance(
            UNI_V3_SWAP_ROUTER,
            IERC20Metadata(loan.collToken).allowance(
                address(this),
                UNI_V3_SWAP_ROUTER
            )
        );
    }
}

// File: contracts/test/UniV3TestSwap.sol



// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.19;

import {TransferHelper} from "@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
import {ISwapRouter} from "@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol";

/* solhint-disable */

contract UniV3TestSwap {
    ISwapRouter public immutable swapRouter;
    uint24 public constant poolFee = 3000;

    constructor(ISwapRouter _swapRouter) {
        swapRouter = _swapRouter;
    }

    function swapExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint256 amountIn
    ) external returns (uint256 amountOut) {
        // msg.sender must approve this contract

        // Transfer the specified amount to this contract.
        TransferHelper.safeTransferFrom(
            tokenIn,
            msg.sender,
            address(this),
            amountIn
        );

        // Approve the router
        TransferHelper.safeApprove(tokenIn, address(swapRouter), amountIn);

        ISwapRouter.ExactInputSingleParams memory params = ISwapRouter
            .ExactInputSingleParams({
                tokenIn: tokenIn,
                tokenOut: tokenOut,
                fee: poolFee,
                recipient: msg.sender,
                deadline: block.timestamp,
                amountIn: amountIn,
                amountOutMinimum: 0,
                sqrtPriceLimitX96: 0
            });

        // The call to `exactInputSingle` executes the swap.
        amountOut = swapRouter.exactInputSingle(params);
    }
}