// 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/token/ERC1155/IERC1155.sol



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

pragma solidity ^0.8.0;

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

/**
 * @dev Required interface of an ERC1155 compliant contract, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1155[EIP].
 *
 * _Available since v3.1._
 */
interface IERC1155 is IERC165 {
    /**
     * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
     */
    event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);

    /**
     * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
     * transfers.
     */
    event TransferBatch(
        address indexed operator,
        address indexed from,
        address indexed to,
        uint256[] ids,
        uint256[] values
    );

    /**
     * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
     * `approved`.
     */
    event ApprovalForAll(address indexed account, address indexed operator, bool approved);

    /**
     * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
     *
     * If an {URI} event was emitted for `id`, the standard
     * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
     * returned by {IERC1155MetadataURI-uri}.
     */
    event URI(string value, uint256 indexed id);

    /**
     * @dev Returns the amount of tokens of token type `id` owned by `account`.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function balanceOf(address account, uint256 id) external view returns (uint256);

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
     *
     * Requirements:
     *
     * - `accounts` and `ids` must have the same length.
     */
    function balanceOfBatch(
        address[] calldata accounts,
        uint256[] calldata ids
    ) external view returns (uint256[] memory);

    /**
     * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
     *
     * Emits an {ApprovalForAll} event.
     *
     * Requirements:
     *
     * - `operator` cannot be the caller.
     */
    function setApprovalForAll(address operator, bool approved) external;

    /**
     * @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
     *
     * See {setApprovalForAll}.
     */
    function isApprovedForAll(address account, address operator) external view returns (bool);

    /**
     * @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
     *
     * Emits a {TransferSingle} event.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
     * - `from` must have a balance of tokens of type `id` of at least `amount`.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
     * acceptance magic value.
     */
    function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;

    /**
     * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
     *
     * Emits a {TransferBatch} event.
     *
     * Requirements:
     *
     * - `ids` and `amounts` must have the same length.
     * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
     * acceptance magic value.
     */
    function safeBatchTransferFrom(
        address from,
        address to,
        uint256[] calldata ids,
        uint256[] calldata amounts,
        bytes calldata data
    ) external;
}

// File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)

pragma solidity ^0.8.0;

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

/**
 * @dev _Available since v3.1._
 */
interface IERC1155Receiver is IERC165 {
    /**
     * @dev Handles the receipt of a single ERC1155 token type. This function is
     * called at the end of a `safeTransferFrom` after the balance has been updated.
     *
     * NOTE: To accept the transfer, this must return
     * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
     * (i.e. 0xf23a6e61, or its own function selector).
     *
     * @param operator The address which initiated the transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param id The ID of the token being transferred
     * @param value The amount of tokens being transferred
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
     */
    function onERC1155Received(
        address operator,
        address from,
        uint256 id,
        uint256 value,
        bytes calldata data
    ) external returns (bytes4);

    /**
     * @dev Handles the receipt of a multiple ERC1155 token types. This function
     * is called at the end of a `safeBatchTransferFrom` after the balances have
     * been updated.
     *
     * NOTE: To accept the transfer(s), this must return
     * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
     * (i.e. 0xbc197c81, or its own function selector).
     *
     * @param operator The address which initiated the batch transfer (i.e. msg.sender)
     * @param from The address which previously owned the token
     * @param ids An array containing ids of each token being transferred (order and length must match values array)
     * @param values An array containing amounts of each token being transferred (order and length must match ids array)
     * @param data Additional data with no specified format
     * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
     */
    function onERC1155BatchReceived(
        address operator,
        address from,
        uint256[] calldata ids,
        uint256[] calldata values,
        bytes calldata data
    ) external returns (bytes4);
}

// File: @openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/utils/ERC1155Holder.sol)

pragma solidity ^0.8.0;

import "./ERC1155Receiver.sol";

/**
 * Simple implementation of `ERC1155Receiver` that will allow a contract to hold ERC1155 tokens.
 *
 * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
 * stuck.
 *
 * @dev _Available since v3.1._
 */
contract ERC1155Holder is ERC1155Receiver {
    function onERC1155Received(
        address,
        address,
        uint256,
        uint256,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155Received.selector;
    }

    function onERC1155BatchReceived(
        address,
        address,
        uint256[] memory,
        uint256[] memory,
        bytes memory
    ) public virtual override returns (bytes4) {
        return this.onERC1155BatchReceived.selector;
    }
}

// File: @openzeppelin/contracts/token/ERC1155/utils/ERC1155Receiver.sol



// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)

pragma solidity ^0.8.0;

import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";

/**
 * @dev _Available since v3.1._
 */
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
    }
}

// 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/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/token/ERC721/utils/ERC721Holder.sol



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

pragma solidity ^0.8.0;

import "../IERC721Receiver.sol";

/**
 * @dev Implementation of the {IERC721Receiver} interface.
 *
 * Accepts all token transfers.
 * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
 */
contract ERC721Holder is IERC721Receiver {
    /**
     * @dev See {IERC721Receiver-onERC721Received}.
     *
     * Always returns `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) {
        return this.onERC721Received.selector;
    }
}

// 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/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: contracts/CollateralVerifier.sol



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

import { CollateralType } from "./lib/Structs.sol";

import { InvalidCollateralType, InvalidCollateral, InvalidCollateralCriteria } from "./lib/Errors.sol";

library CollateralVerifier {

    function mapCollateralType(
        uint8 collateralType
    ) external pure returns (uint8) {
        if (
            collateralType == uint8(CollateralType.ERC721) ||
            collateralType == uint8(CollateralType.ERC721_WITH_CRITERIA)
        ) {
            return uint8(CollateralType.ERC721);
        } else if (
            collateralType == uint8(CollateralType.ERC1155) ||
            collateralType == uint8(CollateralType.ERC1155_WITH_CRITERIA)
        ) {
            return uint8(CollateralType.ERC1155);
        } else {
            revert InvalidCollateralType();
        }
    }

    function verifyCollateral(
        uint8 collateralType,
        uint256 collateralRoot,
        uint256 tokenId,
        bytes32[] calldata proof
    ) external pure {
        if (
            collateralType == uint8(CollateralType.ERC721) ||
            collateralType == uint8(CollateralType.ERC1155)
        ) {
            if (tokenId != collateralRoot) {
                revert InvalidCollateral();
            }
            return;
        }

        bytes32 computedRoot = processProofCalldata(proof, bytes32(tokenId));
        if (computedRoot != bytes32(collateralRoot)) {
            revert InvalidCollateralCriteria();
        }
    }

    function processProofCalldata(
        bytes32[] calldata proof,
        bytes32 leaf
    ) internal pure returns (bytes32) {
        bytes32 computedHash = keccak256(abi.encode(leaf));
        for (uint256 i = 0; i < proof.length; i++) {
            computedHash = _hashPair(computedHash, proof[i]);
        }
        return computedHash;
    }

    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) {
        // solhint-disable-next-line
        assembly {
            mstore(0x00, a)
            mstore(0x20, b)
            value := keccak256(0x00, 0x40)
        }
    }
}

// File: contracts/Helpers.sol



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

import { wadDiv, wadMul } from "solmate/src/utils/SignedWadMath.sol";
import { InvalidCollateralType } from "./lib/Errors.sol";
import { CollateralType, Fee } from "./lib/Structs.sol";

library Helpers {
    int256 private constant _YEAR_WAD = 365 days * 1e18;
    uint256 private constant _LIQUIDATION_THRESHOLD = 10_000_000;
    uint256 private constant _MILLI_BASIS_POINTS = 1_000_000;

    function bipsToSignedWads(uint256 bips) public pure returns (int256) {
        return int256((bips * 1e18) / _MILLI_BASIS_POINTS);
    }

    function computeCurrentDebt(
        uint256 amount,
        uint256 rate,
        uint256 duration
    ) public pure returns (uint256) {
        int256 yearsWad = wadDiv(int256(duration) * 1e18, _YEAR_WAD);
        return
            amount +
            uint256(
                wadMul(int256(amount), wadMul(yearsWad, bipsToSignedWads(rate)))
            );
    }

    function computeAmountAfterFees(
        uint256 amount,
        Fee[] memory fees
    ) public pure returns (uint256 netAmount) {
        netAmount = amount;
        for (uint256 i = 0; i < fees.length; i++) {
            netAmount = netAmount - computeFeeAmount(amount, fees[i].rate);
        }
        return netAmount;
    }

    function computeFeeAmount(
        uint256 amount,
        uint256 rate
    ) public pure returns (uint256) {
        return ((amount * rate) + _MILLI_BASIS_POINTS - 1) / _MILLI_BASIS_POINTS;
    }
}

// File: contracts/interfaces/IKettle.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

import { OfferAuth, LoanOffer, BorrowOffer, LoanOfferInput, LoanFullfillment, BorrowOfferInput, BorrowFullfillment, RepayFullfillment, RefinanceFullfillment, Lien, LienPointer } from "../lib/Structs.sol";

interface IKettle is IOfferController {
    event Repay(
        uint256 lienId, 
        address collection, 
        uint256 startTime,
        uint256 repayTime,
        uint256 amount,
        uint256 rate,
        uint256 duration,
        uint256 repayAmount
    );

    event Seize(uint256 lienId, address collection);

    event Refinance(
        uint256 lienId,
        address oldLender,
        address newLender,
        uint256 oldAmount,
        uint256 newAmount,
        uint256 oldDuration,
        uint256 newDuration,
        uint256 oldRate,
        uint256 newRate
    );

    event Renegotiate(
        uint256 lienId,
        uint256 oldRate,
        uint256 newRate,
        uint256 oldDuration,
        uint256 newDuration
    );

    function liens(uint256 lienId) external view returns (bytes32 lienHash);

    function getRepaymentAmount(
        uint256 borrowAmount,
        uint256 rate,
        uint256 duration
    ) external returns (uint256 repayAmount);

    /*//////////////////////////////////////////////////
                    BORROW FLOWS
    //////////////////////////////////////////////////*/
    function borrow(
        LoanOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature,
        uint256 loanAmount,
        uint256 collateralTokenId,
        address borrower,
        bytes32[] calldata proof
    ) external returns (uint256 lienId);

    function borrowBatch(
        LoanOfferInput[] calldata loanOffers,
        LoanFullfillment[] calldata fullfillments,
        address borrower
    ) external returns (uint256[] memory lienIds);

    /*//////////////////////////////////////////////////
                    LOAN FLOWS
    //////////////////////////////////////////////////*/
    function loan(
        BorrowOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature
    ) external returns (uint256 lienId);

    function loanBatch(
        BorrowOfferInput[] calldata borrowOffers,
        BorrowFullfillment[] calldata fullfillments
    ) external returns (uint256[] memory lienIds);

    /*//////////////////////////////////////////////////
                      REPAYMENT FLOWS
    //////////////////////////////////////////////////*/
    function repay(Lien calldata lien, uint256 lienId) external;

    function repayBatch(RepayFullfillment[] calldata repayments) external;

    /*//////////////////////////////////////////////////
                    REFINANCING FLOWS
    //////////////////////////////////////////////////*/
    function refinance(
        Lien calldata lien,
        uint256 lienId,
        uint256 loanAmount,
        LoanOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature,
        bytes32[] calldata proof
    ) external;
    
    function refinanceBatch(
        LoanOfferInput[] calldata loanOffers,
        RefinanceFullfillment[] calldata fullfillments
    ) external;

    /*//////////////////////////////////////////////////
                    SEIZE FLOWS
    //////////////////////////////////////////////////*/
    function seize(LienPointer[] calldata lienPointers) external;
}

// File: contracts/interfaces/IOfferController.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { ISignatures } from "./ISignatures.sol";
import { Fee } from "../lib/Structs.sol";

interface IOfferController is ISignatures {
    
    event Loan(
        bytes32 offerHash,
        uint256 lienId,
        address lender,
        address borrower,
        uint8 collateralType,
        address collection,
        uint256 tokenId,
        uint256 size,
        address currency,
        uint256 amount,
        uint256 rate,
        uint256 duration,
        uint256 startTime,
        Fee[] fees
    );

    event OfferCancelled(address indexed user, uint256 salt);

    event NonceIncremented(address indexed user, uint256 newNonce);

    function amountTaken(bytes32 offerHash) external view returns (uint256);

    function cancelOffer(uint256 salt) external;

    function cancelOffers(uint256[] calldata salts) external;

    function incrementNonce() external;
}

// File: contracts/interfaces/ISignatures.sol



// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import { LoanOffer, BorrowOffer } from "../lib/Structs.sol";

interface ISignatures {
    function information()
        external
        view
        returns (string memory version, bytes32 domainSeparator);

    function getLoanOfferHash(
        LoanOffer calldata offer
    ) external view returns (bytes32);

    function getBorrowOfferHash(
        BorrowOffer calldata offer
    ) external view returns (bytes32);

    function cancelledOrFulfilled(
        address user,
        uint256 salt
    ) external view returns (uint256);

    function nonces(address user) external view returns (uint256);
}

// File: contracts/Kettle.sol



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

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import { ERC1155Holder } from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";

import { Helpers } from "./Helpers.sol";
import { CollateralVerifier } from "./CollateralVerifier.sol";
import { SafeTransfer } from "./SafeTransfer.sol";

import { Signatures } from "./lib/Signatures.sol";
import { OfferController } from "./OfferController.sol";
import { IKettle } from "./interfaces/IKettle.sol";

import { CollateralType, Fee, Lien, LoanOffer, BorrowOffer, RenegotiationOffer, LoanOfferInput, BorrowOfferInput, LienPointer, LoanFullfillment, BorrowFullfillment, RepayFullfillment, RefinanceFullfillment, OfferAuth } from "./lib/Structs.sol";

import { InvalidLien, Unauthorized, LienIsDefaulted, LienNotDefaulted, CollectionsDoNotMatch, CurrenciesDoNotMatch, NoEscrowImplementation, InvalidCollateralSize, InvalidCollateralType, TotalFeeTooHigh, InvalidLienHash, LienIdMismatch, InvalidDuration, LendersDoNotMatch } from "./lib/Errors.sol";

///      ██████  ███           ████                                                █████                
///    ████████████████        ████                            ████       ████     █████                
///  ██████   ██████████       ████                            ████       ████     █████                
/// █████████████████████      ████     ████     ███████    ██████████ ██████████  █████      ███████   
/// █████   ██████████████     ████   █████    ███████████  █████████████████████  █████    ███████████ 
/// █████   ██████████████     ████ █████     ████     ████    ████      █████     █████   ████    █████
/// ██████████████████████     █████████     ███████████████   ████      █████     █████  ██████████████
/// █████████████████████      ██████████    ███████████████   ████      █████     █████  ██████████████
///  ██████   ██████████       █████ █████   █████             ████      █████     █████  █████         
///    ███████████████         ████   █████   █████   █████    ████████  ████████  █████   █████   █████
///       █████  ███           ████    █████    █████████       ███████   ███████  █████     ██████████ 
///
/// @title Kettle
/// @author diamondjim.eth
/// @custom:version 2.0
/// @notice Kettle is a decentralized lending protocol

contract Kettle is IKettle, Ownable, Signatures, OfferController, SafeTransfer, ERC721Holder, ERC1155Holder {
    uint256 private _nextLienId;

    mapping(uint256 => bytes32) public liens;
    mapping(address => address) public escrows;
    mapping(bytes32 => uint256) private _gracePeriod;

    uint256[50] private _gap;

    constructor(address authSigner) OfferController(authSigner) { }

    /// @notice calculate repayment amount given amount, rate, and duration
    /// @param amount loan amount
    /// @param rate loan rate
    /// @param duration loan duration
    /// @return repayment amount
    function getRepaymentAmount(
        uint256 amount,
        uint256 rate,
        uint256 duration
    ) public pure returns (uint256) {
        return Helpers.computeCurrentDebt(amount, rate, duration);
    }

    /// @notice get custom escrow address for collection
    /// @dev if no escrow is set, return this contract address
    /// @param collection collection address
    /// @return escrow address
    function getEscrow(
        address collection
    ) public view returns (address escrow) {
        escrow = escrows[collection];
        if (escrow == address(0)) {
            return address(this);
        }
    }

    /// @notice return grace period given a lien id
    /// @dev grace periods are set per lien hash
    /// @dev if lien hash changes, grace period will default to 0
    /// @param lienId lien id
    /// @return duration grace period duration
    function getGracePeriodForLien(uint256 lienId) public view returns (uint256 duration) {
        duration = _gracePeriod[liens[lienId]];
    }

    /// @notice set custom escrow address for collection (only owner can call this method)
    /// @dev if no escrow is set, return this contract address
    /// @param collection collection address
    /// @param escrow escrow address
    function setEscrow(address collection, address escrow) external onlyOwner {
        escrows[collection] = escrow;
    }

    /// @notice set grace period for a lien id (only owner can call this method)
    /// @dev grace periods are set per lien hash
    /// @dev if lien hash changes, grace period will default to 0
    /// @param lienId lien id
    /// @param duration grace period duration
    function setGracePeriodForLien(uint256 lienId, uint256 duration) external onlyOwner {
        _gracePeriod[liens[lienId]] = duration;
    }

    /// @notice pay fees to recipients based on rates
    /// @dev gas efficiency to check if rate is 0 and pass over
    /// @dev reverts if fees are over 100%
    /// @param currency currency address
    /// @param payer address from which fees are paid
    /// @param amount loan amount
    /// @param fees array of fees
    /// @return totalFees total fees paid
    function payFees(
        address currency,
        address payer,
        uint256 amount,
        Fee[] calldata fees
    ) internal returns (uint256 totalFees) {

        totalFees = 0;
        for (uint256 i = 0; i < fees.length; i++) {
            // skip if fee rate is 0
            if (fees[i].rate == 0) {
                continue;
            }

            uint256 feeAmount = Helpers.computeFeeAmount(
                amount,
                fees[i].rate
            );

            SafeTransfer.transferERC20(
                currency, 
                payer, 
                fees[i].recipient, 
                feeAmount
            );

            unchecked {
                totalFees += feeAmount;
            }
        }

        // revert if total fees are more than loan amount (over 100% fees)
        if (totalFees >= amount) {
            revert TotalFeeTooHigh();
        }
    }

    
    /// @notice Verifies and starts multiple liens against loan offers
    /// @param loanOffers Loan offers
    /// @param fullfillments Loan offer fullfillments
    /// @param borrower address of borrower (optional)
    /// @return lienIds array of lienIds
    function borrowBatch(
        LoanOfferInput[] calldata loanOffers,
        LoanFullfillment[] calldata fullfillments,
        address borrower
    ) external returns (uint256[] memory lienIds) {
        uint256 numFills = fullfillments.length;
        lienIds = new uint256[](numFills);

        for (uint256 i = 0; i < numFills; i++) {
            LoanFullfillment calldata fullfillment = fullfillments[i];
            LoanOfferInput calldata offer = loanOffers[fullfillment.offerIndex];

            lienIds[i] = borrow(
                offer.offer,
                fullfillment.auth,
                offer.offerSignature,
                fullfillment.authSignature,
                fullfillment.amount,
                fullfillment.tokenId,
                borrower,
                fullfillment.proof
            );
        }
    }

    /// @notice Verifies and takes loan offer
    /// @param offer Loan offer
    /// @param auth Offer auth
    /// @param offerSignature Lender offer signature
    /// @param authSignature Auth signer signature
    /// @param amount Loan amount
    /// @param tokenId Token id to provide as collateral
    /// @param borrower address of borrower
    /// @param proof proof for criteria offer
    /// @return lienId New lien id
    function borrow(
        LoanOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature,
        uint256 amount,
        uint256 tokenId,
        address borrower,
        bytes32[] calldata proof
    ) public returns (uint256 lienId) {

        /// set custom borrower
        if (borrower == address(0)) {
            borrower = msg.sender;
        }

        /// verify collateral
        CollateralVerifier.verifyCollateral(
            offer.collateralType,
            offer.identifier,
            tokenId,
            proof
        );

        /// initiate borrow
        lienId = _borrow(
            offer,
            auth,
            offerSignature,
            authSignature,
            amount,
            tokenId,
            borrower
        );

        /// transfer collateral from borrower to escrow
        SafeTransfer.transfer(
            offer.collateralType, 
            offer.collection, 
            msg.sender, 
            getEscrow(offer.collection), 
            tokenId, 
            offer.size
        );

        /// transfer fees from lender
        uint256 totalFees = payFees(
            offer.currency,
            offer.lender,
            amount,
            offer.fees
        );

        /// transfer net loan amount to borrower
        unchecked {
            SafeTransfer.transferERC20(
                offer.currency, 
                offer.lender,
                borrower, 
                amount - totalFees
            );
        }
    }

    /// @notice verifies and takes loan offer; creates new lien
    /// @param offer Loan offer
    /// @param auth Offer auth
    /// @param offerSignature Lender offer signature
    /// @param authSignature Auth signer signature
    /// @param amount Loan amount
    /// @param tokenId Token id to provide as collateral
    /// @param borrower address of borrower (optional)
    /// @return lienId New lien id
    function _borrow(
        LoanOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature,
        uint256 amount,
        uint256 tokenId,
        address borrower
    ) internal returns (uint256 lienId) {
        bytes32 offerHash = _hashLoanOffer(offer);

        /// store lien in memory
        /// map collateral type from WITH_CRITERIA to respective type
        Lien memory lien = Lien({
            offerHash: offerHash,
            lender: offer.lender,
            borrower: borrower,
            collateralType: CollateralVerifier.mapCollateralType(offer.collateralType),
            collection: offer.collection,
            tokenId: tokenId,
            size: offer.size,
            currency: offer.currency,
            amount: amount,
            startTime: block.timestamp,
            duration: offer.duration,
            rate: offer.rate
        });

        /// store the lien in struct
        unchecked {
            liens[lienId = _nextLienId++] = keccak256(abi.encode(lien));
        }

        /// execute the loan offer
        _takeLoanOffer(offer, auth, offerSignature, authSignature, lien, lienId);
    }

    /// @notice Verifies and starts multiple liens against loan offers
    /// @param borrowOffers Borrow offers
    /// @param fullfillments Borrow fullfillments
    /// @return lienIds array of lienIds
    function loanBatch(
        BorrowOfferInput[] calldata borrowOffers,
        BorrowFullfillment[] calldata fullfillments
    ) external returns (uint256[] memory lienIds) {
        lienIds = new uint256[](fullfillments.length);

        for (uint256 i = 0; i < fullfillments.length; i++) {
            BorrowFullfillment calldata fullfillment = fullfillments[i];
            BorrowOfferInput calldata offer = borrowOffers[fullfillment.offerIndex];

            lienIds[i] = loan(
                offer.offer,
                fullfillment.auth,
                offer.offerSignature,
                fullfillment.authSignature
            );
        }
    }

    /// @notice Verifies and takes loan offer
    /// @param offer Loan offer
    /// @param auth Offer auth
    /// @param offerSignature Lender offer signature
    /// @param authSignature Auth signer signature
    /// @return lienId New lien id
    function loan(
        BorrowOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature
    ) public returns (uint256 lienId) {

        /// initiate loan
        lienId = _loan(
            offer,
            auth,
            offerSignature,
            authSignature
        );

        /// transfer collateral from borrower to escrow
        SafeTransfer.transfer(
            offer.collateralType,
            offer.collection,
            offer.borrower,
            getEscrow(offer.collection),
            offer.tokenId,
            offer.size
        );

        //// transfer fees from lender
        uint256 totalFees = payFees(
            offer.currency,
            msg.sender,
            offer.amount,
            offer.fees
        );

        //// transfer net loan amount to borrower
        unchecked {
            SafeTransfer.transferERC20(
                offer.currency,
                msg.sender,
                offer.borrower,
                offer.amount - totalFees
            );
        }
    }

    /// @notice Verifies and takes loan offer; creates new lien
    /// @param offer Loan offer
    /// @param auth Offer auth
    /// @param offerSignature Borrower offer signature
    /// @param authSignature Auth signer signature
    /// @return lienId New lien id
    function _loan(
        BorrowOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature
    ) internal returns (uint256 lienId) {
        bytes32 offerHash = _hashBorrowOffer(offer);

        /// store lien in memory
        /// map collateral type from WITH_CRITERIA to respective type
        Lien memory lien = Lien({
            offerHash: offerHash,
            lender: msg.sender,
            borrower: offer.borrower,
            collateralType: CollateralVerifier.mapCollateralType(offer.collateralType),
            collection: offer.collection,
            tokenId: offer.tokenId,
            size: offer.size,
            currency: offer.currency,
            amount: offer.amount,
            startTime: block.timestamp,
            duration: offer.duration,
            rate: offer.rate
        });

        /// store the lien in struct
        unchecked {
            liens[lienId = _nextLienId++] = keccak256(abi.encode(lien));
        }

        /// take the borrow offer
        _takeBorrowOffer(offer, auth, offerSignature, authSignature, lien, lienId);
    }

    /// @notice repays loans in batch
    /// @param repayments Loan repayments
    function repayBatch(
        RepayFullfillment[] calldata repayments
    ) external validateLiens(repayments) liensAreActive(repayments) {
        for (uint256 i = 0; i < repayments.length; i++) {
            RepayFullfillment calldata repayment = repayments[i];
            repay(repayment.lien, repayment.lienId);
        }
    }

    /// @notice repays loan and retrieves collateral
    /// @param lien Lien preimage
    /// @param lienId Lien id
    function repay(
        Lien calldata lien,
        uint256 lienId
    ) public validateLien(lien, lienId) lienIsActive(lien) {

        /// calculate the repayment amount
        uint256 _repayAmount = _repay(lien, lienId);

        /// transfer collateral from escrow to borrower
        SafeTransfer.transfer(
            lien.collateralType,
            lien.collection,
            getEscrow(lien.collection),
            lien.borrower,
            lien.tokenId,
            lien.size
        );

        /// transfer repayment amount from borrower to lender
        SafeTransfer.transferERC20(
            lien.currency,
            msg.sender, 
            lien.lender, 
            _repayAmount
        );
    }

    /// @notice Computes the current debt repayment and burns the lien
    /// @param lien Lien preimage
    /// @param lienId Lien id
    /// @return repayAmount Current amount of debt owed on the lien
    function _repay(
        Lien calldata lien,
        uint256 lienId
    ) internal returns (uint256 repayAmount) {

        /// calculate repayment amount
        repayAmount = getRepaymentAmount(
            lien.amount,
            lien.rate,
            lien.duration
        );

        /// remove lien and grace period
        delete _gracePeriod[liens[lienId]];
        delete liens[lienId];

        /// emit repayment event
        emit Repay(
            lienId, 
            lien.collection,
            lien.startTime,
            block.timestamp,
            lien.amount,
            lien.rate,
            lien.duration,
            repayAmount
        );
    }

    /// @notice Refinances multiple liens with new loan offers;
    /// @param loanOffers Loan offers
    /// @param fullfillments Loan offer fullfillments
    function refinanceBatch(
        LoanOfferInput[] calldata loanOffers,
        RefinanceFullfillment[] calldata fullfillments
    ) external {
        for (uint256 i = 0; i < fullfillments.length; i++) {
            RefinanceFullfillment calldata fullfillment = fullfillments[i];
            LoanOfferInput calldata offer = loanOffers[fullfillment.offerIndex];

            refinance(
                fullfillment.lien,
                fullfillment.lienId,
                fullfillment.amount,
                offer.offer,
                fullfillment.auth,
                offer.offerSignature,
                fullfillment.authSignature,
                fullfillment.proof
            );
        }
    }

    /// @notice Refinance and existing lien with new loan offer
    /// @param lien Existing lien
    /// @param lienId Identifier of existing lien
    /// @param amount Loan amount in ETH
    /// @param offer Loan offer
    /// @param auth Offer auth
    /// @param offerSignature Lender offer signature
    /// @param authSignature Auth signer signature
    /// @param proof proof for criteria offer
    function refinance(
        Lien calldata lien,
        uint256 lienId,
        uint256 amount,
        LoanOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature,
        bytes32[] calldata proof
    ) public validateLien(lien, lienId) lienIsActive(lien) {

        // caller must be borrower
        if (msg.sender != lien.borrower) {
            revert Unauthorized();
        }

        /// verify collateral is takeable by loan offer 
        /// use token id from lien against collateral identifier of offer
        /// make sure the offer is specifying collateral that matches
        /// the current lien
        CollateralVerifier.verifyCollateral(
            offer.collateralType,
            offer.identifier,
            lien.tokenId,
            proof
        );

        //// refinance initial loan to new loan
        _refinance(lien, lienId, amount, offer, auth, offerSignature, authSignature);

        /// calculate repayment amount on original loan
        uint256 repayAmount = getRepaymentAmount(
            lien.amount,
            lien.rate,
            lien.duration
        );

        /// transfer fees 
        /// caller of method must pay fees in order to refinance offer
        /// fees are calculated based on the new loan amount
        payFees(
            offer.currency,
            msg.sender,
            amount,
            offer.fees
        );

        /// if amount is greater than repayment amount
        /// transfer repayment amount from new lender to old lender (if different)
        /// transfer leftover from new lender to borrower
        if (amount >= repayAmount) {
            if (offer.lender != lien.lender) {
                SafeTransfer.transferERC20(offer.currency, offer.lender, lien.lender, repayAmount);
            }
            unchecked {
                SafeTransfer.transferERC20(offer.currency, offer.lender, lien.borrower, amount - repayAmount);
            }

        /// if amount is less than repayment amount
        /// transfer amount from new lender to old lender (if different)
        /// transfer difference of repayment amount from borrower to old lender
        } else {
            if (offer.lender != lien.lender) {
                SafeTransfer.transferERC20(offer.currency, offer.lender, lien.lender, amount);
            }
            unchecked {
                SafeTransfer.transferERC20(offer.currency, lien.borrower, lien.lender, repayAmount - amount);
            }
        }
    }

    /// @notice Refinance and existing lien with new loan offer
    /// @param lien Existing lien
    /// @param lienId Identifier of existing lien
    /// @param amount Loan amount
    /// @param offer Loan offer
    /// @param auth Offer auth
    /// @param offerSignature Lender offer signature
    /// @param authSignature Auth signer signature
    function _refinance(
        Lien calldata lien,
        uint256 lienId,
        uint256 amount,
        LoanOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature
    ) internal {

        /// check lien collection matches offer collection
        if (lien.collection != offer.collection) {
            revert CollectionsDoNotMatch();
        }

        /// check lien currency matches offer currency
        if (lien.currency != offer.currency) {
            revert CurrenciesDoNotMatch();
        }

        /// check lien size matches offer size
        if (lien.size != offer.size) {
            revert InvalidCollateralSize();
        }

        /// check lien collateral type matches offer collateral type
        if (lien.collateralType != CollateralVerifier.mapCollateralType(offer.collateralType)) {
            revert InvalidCollateralType();
        }

        // initialize offer hash
        bytes32 offerHash = _hashLoanOffer(offer);

        //// update lien with new loan details
        Lien memory newLien = Lien({
            offerHash: offerHash,
            lender: offer.lender,
            borrower: lien.borrower,
            collateralType: lien.collateralType,
            collection: lien.collection,
            tokenId: lien.tokenId,
            size: lien.size,
            currency: lien.currency,
            amount: amount,
            startTime: block.timestamp,
            duration: offer.duration,
            rate: offer.rate
        });

        /// update stored lien hash
        unchecked {
            liens[lienId] = keccak256(abi.encode(newLien));
        }

        /// take the new loan offer
        _takeLoanOffer(offer, auth, offerSignature, authSignature, newLien, lienId);

        /// emit refinance event
        emit Refinance(
            lienId,
            lien.lender,
            newLien.lender,
            lien.amount,
            newLien.amount,
            lien.duration,
            newLien.duration,
            lien.rate,
            newLien.rate
        );
    }
    
    /// @notice Renegotiates lien with new parameters
    /// @param lien Lien preimage
    /// @param lienId Lien id
    /// @param offer Renegotiation offer
    /// @param auth Offer auth
    /// @param offerSignature Renegotiation offer signature
    /// @param authSignature Auth signer signature
    function renegotiate(
        Lien calldata lien,
        uint256 lienId,
        RenegotiationOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature
    ) public validateLien(lien, lienId) lienIsActive(lien) {

        // caller must be borrower
        if (msg.sender != lien.borrower) {
            revert Unauthorized();
        }

        // borrower pays fees on original borrow amount and offer specified rate
        payFees(
            lien.currency, 
            msg.sender, 
            lien.amount, 
            offer.fees
        );

        // renegotiate initial loan to new loan
        _renegotiate(lien, lienId, offer, auth, offerSignature, authSignature);
    }

    /// @notice Renegotiates lien with new parameters
    /// @param lien Lien preimage
    /// @param lienId Lien id
    /// @param offer Renegotiation offer
    /// @param auth Offer auth
    /// @param offerSignature Renegotiation offer signature
    function _renegotiate(
        Lien calldata lien,
        uint256 lienId,
        RenegotiationOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature
    ) internal {

        // current lender must be the renegotiation lender
        if (lien.lender != offer.lender) {
            revert LendersDoNotMatch();
        }

        // signed lien id must match provided lien id
        if (lienId != offer.lienId) {
            revert LienIdMismatch();
        }
        
        // signed lien hash must match stored lien hash
        // protects against renegotation after subsequent update to lien
        // if provided lien hash is 0, pass through (allows for renegoitation once per lien)
        if (offer.lienHash != bytes32(0)) {
            bytes32 _lienHash = liens[lienId];
            if (_lienHash != offer.lienHash) {
                revert InvalidLienHash();
            }
        }

        // updated duration must end after current block timestamp
        if (lien.startTime + offer.newDuration < block.timestamp) {
            revert InvalidDuration();
        }

        // initialize offer hash
        bytes32 offerHash = _hashRenegotiationOffer(offer);

        /// update lien with new loan details
        Lien memory newLien = Lien({
            offerHash: offerHash,
            lender: lien.lender,
            borrower: lien.borrower,
            collateralType: lien.collateralType,
            collection: lien.collection,
            tokenId: lien.tokenId,
            size: lien.size,
            currency: lien.currency,
            amount: lien.amount,
            startTime: lien.startTime,
            duration: offer.newDuration,
            rate: offer.newRate
        });

        /// store the lien in struct
        unchecked {
            liens[lienId] = keccak256(abi.encode(newLien));
        }

        //// take the renegotiation offer
        _takeRenegotiationOffer(offer, auth, offerSignature, authSignature, newLien, lienId);
        
        /// emit renegotiation event
        emit Renegotiate(
            lienId,
            lien.rate,
            newLien.rate,
            lien.duration,
            newLien.duration
        );
    }

    /// @notice Seizes collateral from defaulted lien, skipping liens that are not defaulted
    /// @param lienPointers List of lien, lienId pairs
    function seize(LienPointer[] calldata lienPointers) external {
        uint256 length = lienPointers.length;

        /// iterate over lien pointers
        for (uint256 i; i < length; ) {
            Lien calldata lien = lienPointers[i].lien;
            uint256 lienId = lienPointers[i].lienId;
            
            /// check that caller is lender
            if (msg.sender != lien.lender) {
                revert Unauthorized();
            }

            /// check that lien is valid
            if (!_validateLien(lien, lienId)) {
                revert InvalidLien();
            }

            /// check that lien is defaulted
            if (!_lienIsDefaulted(lien)) {
                revert LienNotDefaulted();
            }

            /// remove lien and grace period
            delete _gracePeriod[liens[lienId]];
            delete liens[lienId];

            /// transfer collateral to lender
            SafeTransfer.transfer(
                lien.collateralType, 
                lien.collection, 
                getEscrow(lien.collection), 
                lien.lender, 
                lien.tokenId,
                lien.size
            );

            /// emit seize event
            emit Seize(lienId, lien.collection);

            unchecked {
                ++i;
            }
        }
    }

    /// @notice Verifies lien matches stored lien hash
    modifier validateLien(Lien calldata lien, uint256 lienId) {
        if (!_validateLien(lien, lienId)) {
            revert InvalidLien();
        }

        _;
    }

    /// @notice batch verifies liens match stored lien hashes
    /// @dev only used in batch repayments
    modifier validateLiens(RepayFullfillment[] calldata repayments) {
        uint256 length = repayments.length;
        for (uint256 i; i < length; ) {
            Lien calldata lien = repayments[i].lien;
            uint256 lienId = repayments[i].lienId;

            if (!_validateLien(lien, lienId)) {
                revert InvalidLien();
            }

            unchecked {
                ++i;
            }
        }

        _;
    }

    /// @notice verifies lien is not defaulted
    modifier lienIsActive(Lien calldata lien) {
        if (_lienIsDefaulted(lien)) {
            revert LienIsDefaulted();
        }

        _;
    }

    /// @notice batch verifies liens are not defaulted
    /// @dev only used in batch repayments
    modifier liensAreActive(RepayFullfillment[] calldata repayments) {
        uint256 length = repayments.length;
        for (uint256 i; i < length; ) {
            Lien calldata lien = repayments[i].lien;

            if (_lienIsDefaulted(lien)) {
                revert LienIsDefaulted();
            }

            unchecked {
                ++i;
            }
        }

        _;
    }

    /// @notice hash given lien and compare against stored hash
    function _validateLien(
        Lien calldata lien,
        uint256 lienId
    ) internal view returns (bool) {
        return liens[lienId] == keccak256(abi.encode(lien));
    }

    /// @notice compute endtime of lien and compare against block timestamp
    /// @dev uses grace period for a lien
    function _lienIsDefaulted(Lien calldata lien) internal view returns (bool) {
        bytes32 lienHash = keccak256(abi.encode(lien));
        return lien.startTime + lien.duration + _gracePeriod[lienHash] < block.timestamp;
    }
}

// File: contracts/lib/Errors.sol



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

// Kettle
error Unauthorized();
error InvalidLoan();
error InvalidLien();
error InvalidLoanAmount();
error InsufficientOffer();
error InvalidRepayment();
error LienIsDefaulted();
error LienNotDefaulted();
error AuctionIsActive();
error AuctionIsNotActive();
error InvalidRefinanceRate();
error InvalidRefinanceDuration();
error RateTooHigh();
error FeesTooHigh();
error CollectionsDoNotMatch();
error CurrenciesDoNotMatch();
error InsufficientRefinance();
error InvalidAuctionDuration();
error NoEscrowImplementation();
error InvalidLienHash();
error InvalidDuration();
error LendersDoNotMatch();
error LienIdMismatch();
error TotalFeeTooHigh();

// CollateralVerifier
error InvalidCollateral();
error InvalidCollateralCriteria();
error InvalidCollateralType();
error InvalidCollateralSize();

// OfferController
error OfferExpired();
error OfferUnavailable();

// Signatures
error UnauthorizedOracle();
error SignatureExpired();
error InvalidSignature();
error InvalidVParameter();

// Auth
error AuthorizationExpired();
error UnauthorizedTaker();
error UnauthorizedOffer();
error UnauthorizedCollateral();

// File: contracts/lib/Signatures.sol



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

import { Fee, LoanOffer, BorrowOffer, OfferAuth, Collateral, RenegotiationOffer } from "./Structs.sol";
import { InvalidVParameter, InvalidSignature } from "./Errors.sol";
import { ISignatures } from "../interfaces/ISignatures.sol";

abstract contract Signatures is ISignatures {
    bytes32 private immutable _LOAN_OFFER_TYPEHASH;
    bytes32 private immutable _BORROW_OFFER_TYPEHASH;
    bytes32 private immutable _RENEGOTIATION_OFFER_TYPEHASH;
    bytes32 private immutable _COLLATERAL_TYPEHASH;
    bytes32 private immutable _OFFER_AUTH_TYPEHASH;
    bytes32 private immutable _FEE_TYPEHASH;
    bytes32 private immutable _EIP_712_DOMAIN_TYPEHASH;

    string private constant _NAME = "Kettle";
    string private constant _VERSION = "2";

    mapping(address => uint256) public nonces;
    uint256[50] private _gap;

    constructor() {
        (
            _LOAN_OFFER_TYPEHASH,
            _BORROW_OFFER_TYPEHASH,
            _RENEGOTIATION_OFFER_TYPEHASH,
            _FEE_TYPEHASH,
            _COLLATERAL_TYPEHASH,
            _OFFER_AUTH_TYPEHASH,
            _EIP_712_DOMAIN_TYPEHASH
        ) = _createTypehashes();
    }

    function information()
        external
        view
        returns (string memory version, bytes32 domainSeparator)
    {
        version = _VERSION;
        domainSeparator = _hashDomain(
            _EIP_712_DOMAIN_TYPEHASH,
            keccak256(bytes(_NAME)),
            keccak256(bytes(_VERSION))
        );
    }

    function getLoanOfferHash(
        LoanOffer calldata offer
    ) external view returns (bytes32) {
        return _hashLoanOffer(offer);
    }

    function getBorrowOfferHash(
        BorrowOffer calldata offer
    ) external view returns (bytes32) {
        return _hashBorrowOffer(offer);
    }

    function getRenegotiationOfferHash(
        RenegotiationOffer calldata offer
    ) external view returns (bytes32) {
        return _hashRenegotiationOffer(offer);
    }

    /**
     * @notice Generate all EIP712 Typehashes
     */
    function _createTypehashes()
        internal
        pure
        returns (
            bytes32 loanOfferTypehash,
            bytes32 borrowOfferTypehash,
            bytes32 renegotiationOfferTypehash,
            bytes32 feeTypehash,
            bytes32 collateralTypehash,
            bytes32 offerAuthTypehash,
            bytes32 eip712DomainTypehash
        )
    {
        eip712DomainTypehash = keccak256(
            bytes.concat(
                "EIP712Domain(",
                "string name,",
                "string version,",
                "uint256 chainId,",
                "address verifyingContract",
                ")"
            )
        );

        bytes memory feeTypestring = bytes.concat(
            "Fee(",
            "uint256 rate,",
            "address recipient"
            ")"
        );

        feeTypehash = keccak256(feeTypestring);

        loanOfferTypehash = keccak256(
            bytes.concat(
                "LoanOffer(",
                "uint8 collateralType,",
                "address collection,",
                "uint256 identifier,",
                "uint256 size,",
                "address currency,",
                "uint256 totalAmount,",
                "uint256 minAmount,",
                "uint256 maxAmount,",
                "uint256 duration,",
                "uint256 rate,",
                "uint256 salt,",
                "uint256 expiration,",
                "uint256 nonce,",
                "Fee[] fees",
                ")",
                feeTypestring
            )
        );

        borrowOfferTypehash = keccak256(
            bytes.concat(
                "BorrowOffer(",
                "uint8 collateralType,",
                "address collection,",
                "uint256 tokenId,",
                "uint256 size,",
                "address currency,",
                "uint256 amount,",
                "uint256 duration,",
                "uint256 rate,",
                "uint256 salt,",
                "uint256 expiration,",
                "uint256 nonce,",
                "Fee[] fees",
                ")",
                feeTypestring
            )
        );

        renegotiationOfferTypehash = keccak256(
            bytes.concat(
                "RenegotiationOffer(",
                "uint256 lienId,",
                "bytes32 lienHash,",
                "uint256 newDuration,",
                "uint256 newRate,",
                "uint256 expiration,",
                "uint256 salt,",
                "uint256 nonce,",
                "Fee[] fees",
                ")",
                feeTypestring
            )
        );

        collateralTypehash = keccak256(
            bytes.concat(
                "Collateral(",
                "uint8 collateralType,",
                "address collection,",
                "uint256 tokenId,",
                "uint256 size"
                ")"
            )
        );

        offerAuthTypehash = keccak256(
            bytes.concat(
                "OfferAuth(",
                "bytes32 offerHash,",
                "address taker,"
                "uint256 expiration,",
                "bytes32 collateralHash",
                ")"
            )
        );
    }

    function _hashDomain(
        bytes32 eip712DomainTypehash,
        bytes32 nameHash,
        bytes32 versionHash
    ) internal view returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    eip712DomainTypehash,
                    nameHash,
                    versionHash,
                    block.chainid,
                    address(this)
                )
            );
    }

    function _hashFee(Fee calldata fee) internal view returns (bytes32) {
        return keccak256(abi.encode(_FEE_TYPEHASH, fee.rate, fee.recipient));
    }

    function _packFees(Fee[] calldata fees) internal view returns (bytes32) {
        bytes32[] memory feeHashes = new bytes32[](fees.length);
        uint256 feesLength = fees.length;
        for (uint256 i; i < feesLength; ) {
            feeHashes[i] = _hashFee(fees[i]);
            unchecked {
                ++i;
            }
        }
        return keccak256(abi.encodePacked(feeHashes));
    }

    function _hashLoanOffer(
        LoanOffer calldata offer
    ) internal view returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    _LOAN_OFFER_TYPEHASH,
                    offer.collateralType,
                    offer.collection,
                    offer.identifier,
                    offer.size,
                    offer.currency,
                    offer.totalAmount,
                    offer.minAmount,
                    offer.maxAmount,
                    offer.duration,
                    offer.rate,
                    offer.salt,
                    offer.expiration,
                    nonces[offer.lender],
                    _packFees(offer.fees)
                )
            );
    }

    function _hashBorrowOffer(
        BorrowOffer calldata offer
    ) internal view returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    _BORROW_OFFER_TYPEHASH,
                    offer.collateralType,
                    offer.collection,
                    offer.tokenId,
                    offer.size,
                    offer.currency,
                    offer.amount,
                    offer.duration,
                    offer.rate,
                    offer.salt,
                    offer.expiration,
                    nonces[offer.borrower],
                    _packFees(offer.fees)
                )
            );
    }

    function _hashRenegotiationOffer(
        RenegotiationOffer calldata offer
    ) internal view returns (bytes32) {
        return 
            keccak256(
                abi.encode(
                    _RENEGOTIATION_OFFER_TYPEHASH,
                    offer.lienId,
                    offer.lienHash,
                    offer.newDuration,
                    offer.newRate,
                    offer.expiration,
                    offer.salt,
                    nonces[offer.lender],
                    _packFees(offer.fees)
                )
            );
    }

    function _hashCollateral(
        uint8 collateralType,
        address collection,
        uint256 tokenId,
        uint256 size
    ) internal view returns (bytes32) {
        return 
            keccak256(
                abi.encode(
                    _COLLATERAL_TYPEHASH, 
                    collateralType, 
                    collection,
                    tokenId,
                    size
                )
            );
    }

    function _hashOfferAuth(
        OfferAuth calldata auth
    ) internal view returns (bytes32) {
        return
            keccak256(
                abi.encode(
                    _OFFER_AUTH_TYPEHASH,
                    auth.offerHash,
                    auth.taker,
                    auth.expiration,
                    auth.collateralHash
                )
            );
    }

    function _hashToSign(bytes32 hash) internal view returns (bytes32) {
        bytes32 domain = _hashDomain(
            _EIP_712_DOMAIN_TYPEHASH,
            keccak256(bytes(_NAME)),
            keccak256(bytes(_VERSION))
        );

        return keccak256(abi.encodePacked(bytes2(0x1901), domain, hash));
    }

    /**
     * @notice Verify authorization of offer
     * @param offerHash Hash of offer struct
     * @param signer signer address
     * @param signature Packed offer signature
     */
    function _verifyOfferAuthorization(
        bytes32 offerHash,
        address signer,
        bytes calldata signature
    ) internal view {
        bytes32 hashToSign = _hashToSign(offerHash);
        bytes32 r;
        bytes32 s;
        uint8 v;

        // solhint-disable-next-line
        assembly {
            r := calldataload(signature.offset)
            s := calldataload(add(signature.offset, 0x20))
            v := shr(248, calldataload(add(signature.offset, 0x40)))
        }
        _verify(signer, hashToSign, v, r, s);
    }
    

    /**
     * @notice Verify signature of digest
     * @param signer Address of expected signer
     * @param digest Signature digest
     * @param v v parameter
     * @param r r parameter
     * @param s s parameter
     */
    function _verify(
        address signer,
        bytes32 digest,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure {
        if (v != 27 && v != 28) {
            revert InvalidVParameter();
        }

        address recoveredSigner = ecrecover(digest, v, r, s);
        if (recoveredSigner == address(0) || signer != recoveredSigner) {
            revert InvalidSignature();
        }
    }
}

// File: contracts/lib/Structs.sol



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

/*//////////////////////////////////////////////////
                COLLATERAL TYPES
//////////////////////////////////////////////////*/

enum CollateralType {
    ERC721,
    ERC1155,
    ERC721_WITH_CRITERIA,
    ERC1155_WITH_CRITERIA
}

struct Collateral {
    uint8 collateralType;
    address collection;
    uint256 tokenId;
    uint256 size;
}

/*//////////////////////////////////////////////////
                LIEN STRUCTS
//////////////////////////////////////////////////*/

struct LienPointer {
    Lien lien;
    uint256 lienId;
}

struct Lien {
    bytes32 offerHash;
    address lender;
    address borrower;
    uint8 collateralType;
    address collection;
    uint256 tokenId;
    uint256 size;
    address currency;
    uint256 amount;
    uint256 duration;
    uint256 rate;
    uint256 startTime;
}

/*//////////////////////////////////////////////////
                LOAN OFFER STRUCTS
//////////////////////////////////////////////////*/

struct LoanOffer {
    address lender;
    uint8 collateralType;
    address collection;
    uint256 identifier;
    uint256 size;
    address currency;
    uint256 totalAmount;
    uint256 minAmount;
    uint256 maxAmount;
    uint256 duration;
    uint256 rate;
    uint256 salt;
    uint256 expiration;
    Fee[] fees;
}

struct LoanOfferInput {
    LoanOffer offer;
    bytes offerSignature;
}

struct LoanFullfillment {
    uint256 offerIndex;
    uint256 amount;
    uint256 tokenId;
    OfferAuth auth;
    bytes authSignature;
    bytes32[] proof;
}

/*//////////////////////////////////////////////////
                BORROW OFFER STRUCTS
//////////////////////////////////////////////////*/

struct BorrowOffer {
    address borrower;
    uint8 collateralType;
    address collection;
    uint256 tokenId;
    uint256 size;
    address currency;
    uint256 amount;
    uint256 duration;
    uint256 rate;
    uint256 salt;
    uint256 expiration;
    Fee[] fees;
}

struct BorrowOfferInput {
    BorrowOffer offer;
    bytes offerSignature;
}

struct BorrowFullfillment {
    uint256 offerIndex;
    OfferAuth auth;
    bytes authSignature;
}

/*//////////////////////////////////////////////////
                RENEGOTIATE STRUCTS
//////////////////////////////////////////////////*/

struct RenegotiationOffer {
    address lender;
    uint256 lienId;
    bytes32 lienHash;
    uint256 newDuration;
    uint256 newRate;
    uint256 expiration;
    uint256 salt;
    Fee[] fees;
}

/*//////////////////////////////////////////////////
                REPAY STRUCTS
//////////////////////////////////////////////////*/

struct RepayFullfillment {
    Lien lien;
    uint256 lienId;
}

/*//////////////////////////////////////////////////
                REFINANCE STRUCTS
//////////////////////////////////////////////////*/

struct RefinanceFullfillment {
    Lien lien;
    uint256 lienId;
    uint256 offerIndex;
    uint256 amount;
    bytes32[] proof;
    OfferAuth auth;
    bytes authSignature;
}

/*//////////////////////////////////////////////////
                FEE STRUCTS
//////////////////////////////////////////////////*/

struct Fee {
    uint256 rate;
    address recipient;
}

/*//////////////////////////////////////////////////
                AUTH STRUCTS
//////////////////////////////////////////////////*/
struct OfferAuth {
    bytes32 offerHash;
    address taker;
    uint256 expiration;
    bytes32 collateralHash;
}

// File: contracts/OfferController.sol



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

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

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

import { IOfferController } from "./interfaces/IOfferController.sol";
import { Lien, LoanOffer, BorrowOffer, RenegotiationOffer, OfferAuth, Collateral } from "./lib/Structs.sol";
import { Signatures } from "./lib/Signatures.sol";

import { InvalidLoanAmount, InsufficientOffer, RateTooHigh, OfferExpired, OfferUnavailable, UnauthorizedOffer, UnauthorizedCollateral, UnauthorizedTaker, AuthorizationExpired } from "./lib/Errors.sol";

/// @title OfferController
/// @author diamondjim.eth
/// @notice offer controller for Kettle
contract OfferController is IOfferController, Ownable, Signatures {
    uint256 private constant _LIQUIDATION_THRESHOLD = 10_000_000;
    address public _AUTH_SIGNER;

    mapping(address => mapping(uint256 => uint256)) public cancelledOrFulfilled;
    mapping(bytes32 => uint256) private _amountTaken;

    uint256[50] private _gap;

    constructor (address authSigner) {
        setAuthSigner(authSigner);
    }

    /// @notice set the auth signer address (only owner can call this method)
    function setAuthSigner(address authSigner) public onlyOwner {
        _AUTH_SIGNER = authSigner;
    }

    /// @notice get the amount taken from a specific offer hash
    function amountTaken(bytes32 offerHash) external view returns (uint256) {
        return _amountTaken[offerHash];
    }

    /// @notice Verifies and takes loan offer
    /// @dev Does not transfer loan and collateral assets; does not update lien hash
    /// @param offer Loan offer
    /// @param auth Offer auth
    /// @param offerSignature Lender offer signature
    /// @param authSignature Auth Signer signature
    /// @param lien Lien preimage
    /// @param lienId Lien id
    function _takeLoanOffer(
        LoanOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature,
        Lien memory lien,
        uint256 lienId
    ) internal {

        /// validate offer signature and parameters
        _validateOffer(
            lien.offerHash,
            offer.lender,
            offerSignature,
            offer.expiration,
            offer.salt
        );

        /// validate loan offer was authenticated
        _validateAuth(
            lien.offerHash, 
            msg.sender, 
            auth, 
            lien, 
            authSignature
        );

        /// revert if rate is above 100% (10_000_000 bp)
        if (offer.rate > _LIQUIDATION_THRESHOLD) {
            revert RateTooHigh();
        }

        /// revert if amount is outside specified range
        if (
            lien.amount > offer.maxAmount ||
            lien.amount < offer.minAmount
        ) {
            revert InvalidLoanAmount();
        }

        /// check if there is sufficient amount left in the offer
        uint256 __amountTaken = _amountTaken[lien.offerHash];
        if (offer.totalAmount - __amountTaken < lien.amount) {
            revert InsufficientOffer();
        }

        /// update amount taken by specific loan offer
        unchecked {
            _amountTaken[lien.offerHash] = __amountTaken + lien.amount;
        }

        /// emit loan event
        emit Loan(
            lien.offerHash,
            lienId,
            lien.lender,
            lien.borrower,
            lien.collateralType,
            lien.collection,
            lien.tokenId,
            lien.size,
            lien.currency,
            lien.amount,
            lien.rate,
            lien.duration,
            lien.startTime,
            offer.fees
        );
    }

    /// @notice Verifies and takes borrow offer
    /// @dev Does not transfer loan and collateral assets; does not update lien hash
    /// @param offer Loan offer
    /// @param auth Offer auth
    /// @param offerSignature Lender offer signature
    /// @param authSignature Auth signer signature
    /// @param lien Lien preimage
    /// @param lienId Lien id
    function _takeBorrowOffer(
        BorrowOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature,
        Lien memory lien,
        uint256 lienId
    ) internal {

        /// validate offer signature and parameters
        _validateOffer(
            lien.offerHash,
            offer.borrower,
            offerSignature,
            offer.expiration,
            offer.salt
        );

        /// validate loan offer was authenticated
        _validateAuth(
            lien.offerHash, 
            msg.sender, 
            auth,
            lien, 
            authSignature
        );

        /// revert if rate is above 100% (10_000_000 bp)
        if (offer.rate > _LIQUIDATION_THRESHOLD) {
            revert RateTooHigh();
        }

        /// mark borrow offer as taken
        cancelledOrFulfilled[offer.borrower][offer.salt] = 1;

        /// emit loan event
        emit Loan(
            lien.offerHash,
            lienId,
            lien.lender,
            lien.borrower,
            lien.collateralType,
            lien.collection,
            lien.tokenId,
            lien.size,
            lien.currency,
            lien.amount,
            lien.rate,
            lien.duration,
            lien.startTime,
            offer.fees
        );
    }

    /// @notice Verifies and takes renegotiation offer
    /// @dev Does not transfer loan and collateral assets; does not update lien hash
    /// @param offer Renegotiation offer
    /// @param auth Offer auth
    /// @param offerSignature Renegotiation offer signature
    /// @param authSignature Auth signer signature
    /// @param lien Lien preimage
    /// @param lienId Lien id
    function _takeRenegotiationOffer(
        RenegotiationOffer calldata offer,
        OfferAuth calldata auth,
        bytes calldata offerSignature,
        bytes calldata authSignature,
        Lien memory lien,
        uint256 lienId
    ) internal {

        /// validate offer signature and parameters
        _validateOffer(
            lien.offerHash,
            offer.lender,
            offerSignature,
            offer.expiration,
            offer.salt
        );

        /// validate loan offer was authenticated
        _validateAuth(
            lien.offerHash, 
            msg.sender, 
            auth,
            lien, 
            authSignature
        );

        /// revert if rate is above 100% (10_000_000 bp)
        if (offer.newRate > _LIQUIDATION_THRESHOLD) {
            revert RateTooHigh();
        }

        /// mark renegotiation offer as taken
        cancelledOrFulfilled[offer.lender][offer.salt] = 1;

        /// emit loan event
        emit Loan(
            lien.offerHash,
            lienId,
            lien.lender,
            lien.borrower,
            lien.collateralType,
            lien.collection,
            lien.tokenId,
            lien.size,
            lien.currency,
            lien.amount,
            lien.rate,
            lien.duration,
            lien.startTime,
            offer.fees
        );
    }

    /// @notice verify offer authorization
    /// @param offerHash Offer hash
    /// @param taker Address of taker
    /// @param auth Offer auth
    /// @param lien Lien preimage
    /// @param signature Packed signature array
    function _validateAuth(
        bytes32 offerHash,
        address taker,
        OfferAuth calldata auth,
        Lien memory lien,
        bytes calldata signature
    ) internal view {

        bytes32 collateralHash = _hashCollateral(
            lien.collateralType,
            lien.collection,
            lien.tokenId,
            lien.size
        );

        bytes32 authHash = _hashOfferAuth(auth);
        _verifyOfferAuthorization(authHash, _AUTH_SIGNER, signature);

        if (auth.expiration < block.timestamp) {
            revert AuthorizationExpired();
        }

        if (auth.taker != taker) {
            revert UnauthorizedTaker();
        }

        if (auth.offerHash != offerHash) {
            revert UnauthorizedOffer();
        }

        if (auth.collateralHash != collateralHash) {
            revert UnauthorizedCollateral();
        }
    }

    /// @notice Assert offer validity
    /// @param offerHash Offer hash
    /// @param signer Address of offer signer
    /// @param signature Packed signature array
    /// @param expiration Offer expiration time
    /// @param salt Offer salt
    function _validateOffer(
        bytes32 offerHash,
        address signer,
        bytes calldata signature,
        uint256 expiration,
        uint256 salt
    ) internal view {
        _verifyOfferAuthorization(offerHash, signer, signature);

        if (expiration < block.timestamp) {
            revert OfferExpired();
        }
        if (cancelledOrFulfilled[signer][salt] == 1) {
            revert OfferUnavailable();
        }
    }

    /// @notice Cancels offer salt for caller
    /// @param salt Unique offer salt
    function cancelOffer(uint256 salt) external {
        _cancelOffer(msg.sender, salt);
    }

    /// @notice Cancels offers in bulk for caller
    /// @param salts List of offer salts
    function cancelOffers(uint256[] calldata salts) external {
        uint256 saltsLength = salts.length;
        for (uint256 i; i < saltsLength; ) {
            _cancelOffer(msg.sender, salts[i]);
            unchecked {
                ++i;
            }
        }
    }

    /// @notice Cancels all offers by incrementing caller nonce
    function incrementNonce() external {
        _incrementNonce(msg.sender);
    }

    /// @notice Cancel offer by user and salt
    /// @param user Address of user
    /// @param salt Unique offer salt
    function _cancelOffer(address user, uint256 salt) private {
        cancelledOrFulfilled[user][salt] = 1;
        emit OfferCancelled(user, salt);
    }

    /// @notice Cancel all orders by incrementing the user nonce
    /// @param user Address of user
    function _incrementNonce(address user) internal {
        emit NonceIncremented(user, ++nonces[user]);
    }
}

// File: contracts/SafeTransfer.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 { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";

import { CollateralType, Fee } from "./lib/Structs.sol";
import { InvalidCollateralType } from "./lib/Errors.sol";


contract SafeTransfer {
  using SafeERC20 for IERC20;

  function transfer(
    uint8 collateralType,
    address token,
    address from,
    address to,
    uint256 tokenId,
    uint256 amount
  ) internal {
    if (
      collateralType == uint8(CollateralType.ERC721) ||
      collateralType == uint8(CollateralType.ERC721_WITH_CRITERIA)
    ) {
      return _transferERC721(token, from, to, tokenId);
    } else if (
      collateralType == uint8(CollateralType.ERC1155) ||
      collateralType == uint8(CollateralType.ERC1155_WITH_CRITERIA)
    ) {
      return _transferERC1155(token, from, to, tokenId, amount);
    }
    revert InvalidCollateralType();
  }

  function _transferERC721(
    address token,
    address from,
    address to,
    uint256 tokenId
  ) internal {
    IERC721(token).safeTransferFrom(from, to, tokenId, "0x");
  }

  function _transferERC1155(
    address token,
    address from,
    address to,
    uint256 id,
    uint256 amount
  ) internal {
    IERC1155(token).safeTransferFrom(from, to, id, amount, "0x");
  }

  function transferERC20(
    address token,
    address from,
    address to,
    uint256 amount
  ) internal {
    IERC20(token).safeTransferFrom(from, to, amount);
  }
}

// File: solmate/src/utils/SignedWadMath.sol



// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;

/// @notice Signed 18 decimal fixed point (wad) arithmetic library.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SignedWadMath.sol)
/// @author Modified from Remco Bloemen (https://xn--2-umb.com/22/exp-ln/index.html)

/// @dev Will not revert on overflow, only use where overflow is not possible.
function toWadUnsafe(uint256 x) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18.
        r := mul(x, 1000000000000000000)
    }
}

/// @dev Takes an integer amount of seconds and converts it to a wad amount of days.
/// @dev Will not revert on overflow, only use where overflow is not possible.
/// @dev Not meant for negative second amounts, it assumes x is positive.
function toDaysWadUnsafe(uint256 x) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18 and then divide it by 86400.
        r := div(mul(x, 1000000000000000000), 86400)
    }
}

/// @dev Takes a wad amount of days and converts it to an integer amount of seconds.
/// @dev Will not revert on overflow, only use where overflow is not possible.
/// @dev Not meant for negative day amounts, it assumes x is positive.
function fromDaysWadUnsafe(int256 x) pure returns (uint256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 86400 and then divide it by 1e18.
        r := div(mul(x, 86400), 1000000000000000000)
    }
}

/// @dev Will not revert on overflow, only use where overflow is not possible.
function unsafeWadMul(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by y and divide by 1e18.
        r := sdiv(mul(x, y), 1000000000000000000)
    }
}

/// @dev Will return 0 instead of reverting if y is zero and will
/// not revert on overflow, only use where overflow is not possible.
function unsafeWadDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Multiply x by 1e18 and divide it by y.
        r := sdiv(mul(x, 1000000000000000000), y)
    }
}

function wadMul(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Store x * y in r for now.
        r := mul(x, y)

        // Equivalent to require(x == 0 || (x * y) / x == y)
        if iszero(or(iszero(x), eq(sdiv(r, x), y))) {
            revert(0, 0)
        }

        // Scale the result down by 1e18.
        r := sdiv(r, 1000000000000000000)
    }
}

function wadDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Store x * 1e18 in r for now.
        r := mul(x, 1000000000000000000)

        // Equivalent to require(y != 0 && ((x * 1e18) / 1e18 == x))
        if iszero(and(iszero(iszero(y)), eq(sdiv(r, 1000000000000000000), x))) {
            revert(0, 0)
        }

        // Divide r by y.
        r := sdiv(r, y)
    }
}

/// @dev Will not work with negative bases, only use when x is positive.
function wadPow(int256 x, int256 y) pure returns (int256) {
    // Equivalent to x to the power of y because x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)
    return wadExp((wadLn(x) * y) / 1e18); // Using ln(x) means x must be greater than 0.
}

function wadExp(int256 x) pure returns (int256 r) {
    unchecked {
        // When the result is < 0.5 we return zero. This happens when
        // x <= floor(log(0.5e18) * 1e18) ~ -42e18
        if (x <= -42139678854452767551) return 0;

        // When the result is > (2**255 - 1) / 1e18 we can not represent it as an
        // int. This happens when x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135.
        if (x >= 135305999368893231589) revert("EXP_OVERFLOW");

        // x is now in the range (-42, 136) * 1e18. Convert to (-42, 136) * 2**96
        // for more intermediate precision and a binary basis. This base conversion
        // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78.
        x = (x << 78) / 5**18;

        // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers
        // of two such that exp(x) = exp(x') * 2**k, where k is an integer.
        // Solving this gives k = round(x / log(2)) and x' = x - k * log(2).
        int256 k = ((x << 96) / 54916777467707473351141471128 + 2**95) >> 96;
        x = x - k * 54916777467707473351141471128;

        // k is in the range [-61, 195].

        // Evaluate using a (6, 7)-term rational approximation.
        // p is made monic, we'll multiply by a scale factor later.
        int256 y = x + 1346386616545796478920950773328;
        y = ((y * x) >> 96) + 57155421227552351082224309758442;
        int256 p = y + x - 94201549194550492254356042504812;
        p = ((p * y) >> 96) + 28719021644029726153956944680412240;
        p = p * x + (4385272521454847904659076985693276 << 96);

        // We leave p in 2**192 basis so we don't need to scale it back up for the division.
        int256 q = x - 2855989394907223263936484059900;
        q = ((q * x) >> 96) + 50020603652535783019961831881945;
        q = ((q * x) >> 96) - 533845033583426703283633433725380;
        q = ((q * x) >> 96) + 3604857256930695427073651918091429;
        q = ((q * x) >> 96) - 14423608567350463180887372962807573;
        q = ((q * x) >> 96) + 26449188498355588339934803723976023;

        /// @solidity memory-safe-assembly
        assembly {
            // Div in assembly because solidity adds a zero check despite the unchecked.
            // The q polynomial won't have zeros in the domain as all its roots are complex.
            // No scaling is necessary because p is already 2**96 too large.
            r := sdiv(p, q)
        }

        // r should be in the range (0.09, 0.25) * 2**96.

        // We now need to multiply r by:
        // * the scale factor s = ~6.031367120.
        // * the 2**k factor from the range reduction.
        // * the 1e18 / 2**96 factor for base conversion.
        // We do this all at once, with an intermediate result in 2**213
        // basis, so the final right shift is always by a positive amount.
        r = int256((uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k));
    }
}

function wadLn(int256 x) pure returns (int256 r) {
    unchecked {
        require(x > 0, "UNDEFINED");

        // We want to convert x from 10**18 fixed point to 2**96 fixed point.
        // We do this by multiplying by 2**96 / 10**18. But since
        // ln(x * C) = ln(x) + ln(C), we can simply do nothing here
        // and add ln(2**96 / 10**18) at the end.

        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            r := or(r, shl(2, lt(0xf, shr(r, x))))
            r := or(r, shl(1, lt(0x3, shr(r, x))))
            r := or(r, lt(0x1, shr(r, x)))
        }

        // Reduce range of x to (1, 2) * 2**96
        // ln(2^k * x) = k * ln(2) + ln(x)
        int256 k = r - 96;
        x <<= uint256(159 - k);
        x = int256(uint256(x) >> 159);

        // Evaluate using a (8, 8)-term rational approximation.
        // p is made monic, we will multiply by a scale factor later.
        int256 p = x + 3273285459638523848632254066296;
        p = ((p * x) >> 96) + 24828157081833163892658089445524;
        p = ((p * x) >> 96) + 43456485725739037958740375743393;
        p = ((p * x) >> 96) - 11111509109440967052023855526967;
        p = ((p * x) >> 96) - 45023709667254063763336534515857;
        p = ((p * x) >> 96) - 14706773417378608786704636184526;
        p = p * x - (795164235651350426258249787498 << 96);

        // We leave p in 2**192 basis so we don't need to scale it back up for the division.
        // q is monic by convention.
        int256 q = x + 5573035233440673466300451813936;
        q = ((q * x) >> 96) + 71694874799317883764090561454958;
        q = ((q * x) >> 96) + 283447036172924575727196451306956;
        q = ((q * x) >> 96) + 401686690394027663651624208769553;
        q = ((q * x) >> 96) + 204048457590392012362485061816622;
        q = ((q * x) >> 96) + 31853899698501571402653359427138;
        q = ((q * x) >> 96) + 909429971244387300277376558375;
        /// @solidity memory-safe-assembly
        assembly {
            // Div in assembly because solidity adds a zero check despite the unchecked.
            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already 2**96 too large.
            r := sdiv(p, q)
        }

        // r is in the range (0, 0.125) * 2**96

        // Finalization, we need to:
        // * multiply by the scale factor s = 5.549…
        // * add ln(2**96 / 10**18)
        // * add k * ln(2)
        // * multiply by 10**18 / 2**96 = 5**18 >> 78

        // mul s * 5e18 * 2**96, base is now 5**18 * 2**192
        r *= 1677202110996718588342820967067443963516166;
        // add ln(2) * k * 5e18 * 2**192
        r += 16597577552685614221487285958193947469193820559219878177908093499208371 * k;
        // add ln(2**96 / 10**18) * 5e18 * 2**192
        r += 600920179829731861736702779321621459595472258049074101567377883020018308;
        // base conversion: mul 2**18 / 2**192
        r >>= 174;
    }
}

/// @dev Will return 0 instead of reverting if y is zero.
function unsafeDiv(int256 x, int256 y) pure returns (int256 r) {
    /// @solidity memory-safe-assembly
    assembly {
        // Divide x by y.
        r := sdiv(x, y)
    }
}