Skip to content
Verified contractExactMIT

TakerSettler

Address0xf3f7fc9927611a32bf2c8e32f66aaf26eb0bf277
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 10,000 runs
EVM version
prague
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,392,157
Creation transaction
0x8d88e37c55…e205501080

src/settler/TakerSettler.sol

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

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuardTransient} from "@openzeppelin/contracts/utils/ReentrancyGuardTransient.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol";
import {ICreditDesk} from "../credit-desk/ICreditDesk.sol";

/// @notice Bundlers that forward calls for anyone and expose who started the
/// bundle, e.g. Morpho Bundler3.
interface IBundler {
    function initiator() external view returns (address);
}

/// @title TakerSettler — maker-signed, taker-executed fixed-price settlement
///
/// @notice Mirror image of `Settler`. The maker (our inventory wallet) signs a
/// quote off-chain; a third party (aggregator executor, bundler) executes it
/// inside its own transaction. The quote is the witness of a Permit2
/// `PermitBatchWitnessTransferFrom` signed by the maker, so Permit2 verifies
/// the signature, enforces the deadline and consumes the nonce; no parallel
/// nonce registry exists here. Permit2 binds the signature to this contract
/// as spender, so a quote cannot be settled anywhere else.
///
/// `outputRecipient` gets `outputAmount` of `outputToken`. The maker pays it
/// from two sources named in the quote: `loanAmount` borrowed for it through
/// the CreditDesk and booked as its debt, and the rest,
/// `outputAmount - loanAmount`, from its own wallet. Either source may be
/// zero. Both land here and leave in one transfer to `outputRecipient` in the
/// same call. The executor's `inputAmount` of `inputToken` is pulled from the
/// caller's allowance straight to `inputRecipient`; tokens sitting on this
/// contract never pay for a fill. The contract never holds balances between
/// transactions.
///
/// The quote's `executor` is the account filling it. A direct caller is bound
/// as `msg.sender`. A registered bundler forwards calls for anyone, so its
/// `msg.sender` proves nothing; for it the bound account is the bundle's
/// `initiator()` (an EOA or a smart account). The signer must never name a
/// forwarding contract as `executor`. The bound account must also be on the
/// owner's executor list (`setExecutor`), so a signer that an attacker
/// controls cannot name the account of the attacker.
///
/// @dev Token-agnostic: tokens, amounts, recipients, the loan and the
/// executor are all inside the signed quote. Which pairs, sizes and loans get
/// signed is the maker's signer policy, not this contract. The maker's signed
/// quote is its consent to the loan: the CreditDesk owner sets this contract
/// as a `Trusted` caller for the maker. The Lender's grant is bound to the
/// maker as borrower, this contract as caller, the `loanId`, the asset
/// (`outputToken`) and the amount (`loanAmount`), not to one quote: any quote
/// of that maker with those loan terms can spend it. The CreditDesk burns the
/// grant nonce, so a grant pays out once. No partial fills, no
/// fee-on-transfer or rebasing tokens, no native ETH. Cancellation is the
/// maker calling `Permit2.invalidateUnorderedNonces` directly.
contract TakerSettler is Ownable2Step, Pausable, ReentrancyGuardTransient {
    using SafeERC20 for IERC20;

    // ─────────────────────────────── Types ───────────────────────────────

    /// @notice The quote signed by the maker, used verbatim as the Permit2 witness.
    /// The nonce is inside, so `hashQuote` is unique per quote. Input and output
    /// are named from the executor's side, as in `Settler`: the executor puts
    /// `inputToken` in and takes `outputToken` out; the signing maker is the
    /// other side of the trade.
    struct Quote {
        address maker; // signs; Permit2 owner of outputToken; borrower of the loan
        address executor; // msg.sender, or the initiator() when msg.sender is a registered bundler
        uint256 nonce; // Permit2 unordered nonce
        uint256 deadline; // also the permit deadline
        address inputToken; // what the executor pays
        uint256 inputAmount;
        address inputRecipient; // where inputToken goes
        address outputToken; // what the maker sells
        uint256 outputAmount; // what outputRecipient gets; the maker's wallet pays outputAmount - loanAmount
        address outputRecipient; // where outputToken goes
        bytes32 loanId; // the Lender's loan id; 0 when there is no loan
        uint256 loanAmount; // the part of outputAmount borrowed for the maker through the CreditDesk; may be 0
    }

    // ─────────────────────────── EIP-712 pieces ──────────────────────────

    /// @notice Witness type string appended to Permit2's
    /// `PermitBatchWitnessTransferFrom(TokenPermissions[] permitted,address spender,uint256 nonce,uint256 deadline,`
    /// stub: witness member closes the top-level type, subtypes follow in
    /// alphabetical order (Quote before TokenPermissions).
    string public constant WITNESS_TYPE_STRING =
        "Quote witness)Quote(address maker,address executor,uint256 nonce,uint256 deadline,address inputToken,uint256 inputAmount,address inputRecipient,address outputToken,uint256 outputAmount,address outputRecipient,bytes32 loanId,uint256 loanAmount)TokenPermissions(address token,uint256 amount)";

    bytes32 public constant QUOTE_TYPEHASH = keccak256(
        "Quote(address maker,address executor,uint256 nonce,uint256 deadline,address inputToken,uint256 inputAmount,address inputRecipient,address outputToken,uint256 outputAmount,address outputRecipient,bytes32 loanId,uint256 loanAmount)"
    );

    // ─────────────────────────────── State ───────────────────────────────

    /// @notice Canonical Permit2.
    ISignatureTransfer public immutable PERMIT2;

    /// @notice The Lender's loan book; pays the loan leg to this contract.
    ICreditDesk public immutable CREDIT_DESK;

    /// @notice Bundlers whose `initiator()` is trusted to name the executor.
    mapping(address bundler => bool) public isBundler;

    /// @notice Accounts that can be the bound executor of a fill.
    mapping(address executor => bool) public isExecutor;

    // ─────────────────────────────── Events ──────────────────────────────

    /// @param quoteId `hashQuote(quote)`; the API's `quote_id`.
    /// @param executor The bound account (`quote.executor`), indexed so fills can
    /// be filtered per user; `caller` is msg.sender (e.g. Bundler3). The
    /// recipient got `quote.outputAmount` in one transfer.
    event QuoteFilled(
        bytes32 indexed quoteId, address indexed maker, address indexed executor, address caller, Quote quote
    );
    event BundlerSet(address indexed bundler, bool allowed);
    event ExecutorSet(address indexed executor, bool allowed);

    // ─────────────────────────────── Errors ──────────────────────────────

    error ExecutorMismatch();
    error ExecutorNotAllowed();
    error DeadlineExpired();
    error ZeroAddress();
    error ZeroAmount();
    error NoCode();
    error LoanMismatch();
    error LoanExceedsOutput();
    error RenounceDisabled();

    // ───────────────────────────── Constructor ───────────────────────────

    constructor(address permit2_, address creditDesk_, address owner_) Ownable(owner_) {
        if (permit2_ == address(0) || creditDesk_ == address(0)) revert ZeroAddress();
        PERMIT2 = ISignatureTransfer(permit2_);
        CREDIT_DESK = ICreditDesk(creditDesk_);
    }

    // ────────────────────────────── Settlement ───────────────────────────

    /// @notice Settle one maker-signed quote, filled by the quote's `executor`
    /// directly or through a registered bundler it initiated.
    /// @param quote The maker-signed quote (the Permit2 witness, nonce included).
    /// @param makerSignature The maker's Permit2 `PermitBatchWitnessTransferFrom` EIP-712 signature.
    /// @param grant The Lender's grant for `quote.loanId`, issued to `quote.maker`
    /// with this contract as caller; empty when `quote.loanAmount` is 0.
    function fillQuote(Quote calldata quote, bytes calldata makerSignature, ICreditDesk.Grant calldata grant)
        external
        whenNotPaused
        nonReentrant
    {
        if (_executor() != quote.executor) revert ExecutorMismatch();
        if (!isExecutor[quote.executor]) revert ExecutorNotAllowed();
        if (block.timestamp > quote.deadline) revert DeadlineExpired();
        if (quote.inputAmount == 0 || quote.outputAmount == 0) revert ZeroAmount();
        if (quote.loanAmount > quote.outputAmount) revert LoanExceedsOutput();
        if ((quote.loanId == bytes32(0)) != (quote.loanAmount == 0)) revert LoanMismatch();
        if (quote.executor == address(0) || quote.outputRecipient == address(0) || quote.inputRecipient == address(0)) {
            revert ZeroAddress();
        }
        if (quote.outputToken.code.length == 0 || quote.inputToken.code.length == 0) revert NoCode();

        bytes32 quoteId = hashQuote(quote);

        // The permit names the full `outputAmount` because the maker signs that
        // value. The settler requests only the wallet part. The batch runs also
        // when the wallet part is 0: Permit2 does not do the zero transfer, but
        // it verifies the signature and burns the quote nonce. Nothing of the
        // executor's moves before this step.
        ISignatureTransfer.TokenPermissions[] memory permitted = new ISignatureTransfer.TokenPermissions[](1);
        permitted[0] = ISignatureTransfer.TokenPermissions({token: quote.outputToken, amount: quote.outputAmount});
        ISignatureTransfer.SignatureTransferDetails[] memory details =
            new ISignatureTransfer.SignatureTransferDetails[](1);
        details[0] = ISignatureTransfer.SignatureTransferDetails({
            to: address(this), requestedAmount: quote.outputAmount - quote.loanAmount
        });
        PERMIT2.permitWitnessTransferFrom(
            ISignatureTransfer.PermitBatchTransferFrom({
                permitted: permitted, nonce: quote.nonce, deadline: quote.deadline
            }),
            details,
            quote.maker,
            quoteId,
            WITNESS_TYPE_STRING,
            makerSignature
        );

        if (quote.loanAmount != 0) {
            CREDIT_DESK.borrowOnBehalf(quote.maker, quote.outputToken, quote.loanAmount, quote.loanId, grant);
        }

        IERC20(quote.outputToken).safeTransfer(quote.outputRecipient, quote.outputAmount);

        // Input side: exactly `inputAmount` from the caller, never from this
        // contract's balance.
        IERC20(quote.inputToken).safeTransferFrom(msg.sender, quote.inputRecipient, quote.inputAmount);

        emit QuoteFilled(quoteId, quote.maker, quote.executor, msg.sender, quote);
    }

    /// @notice EIP-712 struct hash of a quote — the value passed to Permit2 as
    /// the witness and the quote's id (`quote_id` off-chain, `quoteId` in
    /// `QuoteFilled`). Unique per quote (maker and nonce are inside).
    /// @dev Encoded in two halves to stay within stack limits without via-IR;
    /// all members are static types, so the bytes equal one `abi.encode`.
    function hashQuote(Quote calldata quote) public pure returns (bytes32) {
        return keccak256(
            bytes.concat(
                abi.encode(
                    QUOTE_TYPEHASH,
                    quote.maker,
                    quote.executor,
                    quote.nonce,
                    quote.deadline,
                    quote.inputToken,
                    quote.inputAmount
                ),
                abi.encode(
                    quote.inputRecipient,
                    quote.outputToken,
                    quote.outputAmount,
                    quote.outputRecipient,
                    quote.loanId,
                    quote.loanAmount
                )
            )
        );
    }

    function _executor() internal view returns (address) {
        return isBundler[msg.sender] ? IBundler(msg.sender).initiator() : msg.sender;
    }

    // ─────────────────────────────── Admin ───────────────────────────────

    /// @notice Register or remove a bundler. Only contracts whose
    /// `initiator()` is the account that started the current bundle.
    function setBundler(address bundler, bool allowed) external onlyOwner {
        if (bundler == address(0)) revert ZeroAddress();
        isBundler[bundler] = allowed;
        emit BundlerSet(bundler, allowed);
    }

    /// @notice Add or remove an account that can be the bound executor of a
    /// fill. Never add a contract that forwards calls for anyone.
    function setExecutor(address executor, bool allowed) external onlyOwner {
        if (executor == address(0)) revert ZeroAddress();
        isExecutor[executor] = allowed;
        emit ExecutorSet(executor, allowed);
    }

    /// @notice Pause `fillQuote`.
    function pause() external onlyOwner {
        _pause();
    }

    /// @notice Resume settlement.
    function unpause() external onlyOwner {
        _unpause();
    }

    /// @notice Return tokens this contract should never have kept: mistaken
    /// transfers, airdrops.
    function rescue(address token, address to) external onlyOwner {
        if (to == address(0)) revert ZeroAddress();
        IERC20(token).safeTransfer(to, IERC20(token).balanceOf(address(this)));
    }

    /// @notice Disabled: an ownerless settler could never be unpaused or
    /// have its bundler and executor lists changed. Use `transferOwnership`
    /// instead.
    function renounceOwnership() public view override onlyOwner {
        revert RenounceDisabled();
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)

pragma solidity ^0.8.20;

import {Context} from "../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.
 *
 * The initial owner is set to the address provided by the deployer. 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;

    /**
     * @dev The caller account is not authorized to perform an operation.
     */
    error OwnableUnauthorizedAccount(address account);

    /**
     * @dev The owner is not a valid owner account. (eg. `address(0)`)
     */
    error OwnableInvalidOwner(address owner);

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

    /**
     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.
     */
    constructor(address initialOwner) {
        if (initialOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _transferOwnership(initialOwner);
    }

    /**
     * @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 {
        if (owner() != _msgSender()) {
            revert OwnableUnauthorizedAccount(_msgSender());
        }
    }

    /**
     * @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 {
        if (newOwner == address(0)) {
            revert OwnableInvalidOwner(address(0));
        }
        _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);
    }
}

lib/openzeppelin-contracts/contracts/access/Ownable2Step.sol

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

pragma solidity ^0.8.20;

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

/**
 * @dev Contract module which provides access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * This extension of the {Ownable} contract includes a two-step mechanism to transfer
 * ownership, where the new owner must call {acceptOwnership} in order to replace the
 * old one. This can help prevent common mistakes, such as transfers of ownership to
 * incorrect accounts, or to contracts that are unable to interact with the
 * permission system.
 *
 * The initial owner is specified at deployment time in the constructor for `Ownable`. This
 * can later be changed with {transferOwnership} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

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

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

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        if (pendingOwner() != sender) {
            revert OwnableUnauthorizedAccount(sender);
        }
        _transferOwnership(sender);
    }
}

lib/openzeppelin-contracts/contracts/interfaces/IERC1363.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)

pragma solidity >=0.6.2;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}

lib/openzeppelin-contracts/contracts/interfaces/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)

pragma solidity >=0.4.16;

import {IERC165} from "../utils/introspection/IERC165.sol";

lib/openzeppelin-contracts/contracts/interfaces/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)

pragma solidity >=0.4.16;

import {IERC20} from "../token/ERC20/IERC20.sol";

lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}

lib/openzeppelin-contracts/contracts/token/ERC20/utils/SafeERC20.sol

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

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 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 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @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 {
        if (!_safeTransfer(token, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @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 {
        if (!_safeTransferFrom(token, from, to, value, true)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _safeTransfer(token, to, value, false);
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _safeTransferFrom(token, from, to, value, false);
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @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.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        if (!_safeApprove(token, spender, value, false)) {
            if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
            if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that relies on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Oppositely, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity `token.transfer(to, value)` call, 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 to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.transfer.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(to, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }

    /**
     * @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
     * @param to The recipient of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value,
        bool bubble
    ) private returns (bool success) {
        bytes4 selector = IERC20.transferFrom.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(from, shr(96, not(0))))
            mstore(0x24, and(to, shr(96, not(0))))
            mstore(0x44, value)
            success := call(gas(), token, 0, 0x00, 0x64, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
            mstore(0x60, 0)
        }
    }

    /**
     * @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
     * @param value The amount of token to transfer
     * @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
     */
    function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
        bytes4 selector = IERC20.approve.selector;

        assembly ("memory-safe") {
            let fmp := mload(0x40)
            mstore(0x00, selector)
            mstore(0x04, and(spender, shr(96, not(0))))
            mstore(0x24, value)
            success := call(gas(), token, 0, 0x00, 0x44, 0x00, 0x20)
            // if call success and return is true, all is good.
            // otherwise (not success or return is not true), we need to perform further checks
            if iszero(and(success, eq(mload(0x00), 1))) {
                // if the call was a failure and bubble is enabled, bubble the error
                if and(iszero(success), bubble) {
                    returndatacopy(fmp, 0x00, returndatasize())
                    revert(fmp, returndatasize())
                }
                // if the return value is not true, then the call is only successful if:
                // - the token address has code
                // - the returndata is empty
                success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
            }
            mstore(0x40, fmp)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/Context.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @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;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}

lib/openzeppelin-contracts/contracts/utils/Pausable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

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

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

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

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

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

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

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

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

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

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

lib/openzeppelin-contracts/contracts/utils/ReentrancyGuardTransient.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/ReentrancyGuardTransient.sol)

pragma solidity ^0.8.24;

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

/**
 * @dev Variant of {ReentrancyGuard} that uses transient storage.
 *
 * NOTE: This variant only works on networks where EIP-1153 is available.
 *
 * _Available since v5.1._
 *
 * @custom:stateless
 */
abstract contract ReentrancyGuardTransient {
    using TransientSlot for *;

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant REENTRANCY_GUARD_STORAGE =
        0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

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

    /**
     * @dev A `view` only version of {nonReentrant}. Use to block view functions
     * from being called, preventing reading from inconsistent contract state.
     *
     * CAUTION: This is a "view" modifier and does not change the reentrancy
     * status. Use it only on view functions. For payable or non-payable functions,
     * use the standard {nonReentrant} modifier instead.
     */
    modifier nonReentrantView() {
        _nonReentrantBeforeView();
        _;
    }

    function _nonReentrantBeforeView() private view {
        if (_reentrancyGuardEntered()) {
            revert ReentrancyGuardReentrantCall();
        }
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, REENTRANCY_GUARD_STORAGE.asBoolean().tload() will be false
        _nonReentrantBeforeView();

        // Any calls to nonReentrant after this point will fail
        _reentrancyGuardStorageSlot().asBoolean().tstore(true);
    }

    function _nonReentrantAfter() private {
        _reentrancyGuardStorageSlot().asBoolean().tstore(false);
    }

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

    function _reentrancyGuardStorageSlot() internal pure virtual returns (bytes32) {
        return REENTRANCY_GUARD_STORAGE;
    }
}

lib/openzeppelin-contracts/contracts/utils/TransientSlot.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/TransientSlot.sol)
// This file was procedurally generated from scripts/generate/templates/TransientSlot.js.

pragma solidity ^0.8.24;

/**
 * @dev Library for reading and writing value-types to specific transient storage slots.
 *
 * Transient slots are often used to store temporary values that are removed after the current transaction.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 *  * Example reading and writing values using transient storage:
 * ```solidity
 * contract Lock {
 *     using TransientSlot for *;
 *
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _LOCK_SLOT = 0xf4678858b2b588224636b8522b729e7722d32fc491da849ed75b3fdf3c84f542;
 *
 *     modifier locked() {
 *         require(!_LOCK_SLOT.asBoolean().tload());
 *
 *         _LOCK_SLOT.asBoolean().tstore(true);
 *         _;
 *         _LOCK_SLOT.asBoolean().tstore(false);
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library TransientSlot {
    /**
     * @dev UDVT that represents a slot holding an address.
     */
    type AddressSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a AddressSlot.
     */
    function asAddress(bytes32 slot) internal pure returns (AddressSlot) {
        return AddressSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bool.
     */
    type BooleanSlot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a BooleanSlot.
     */
    function asBoolean(bytes32 slot) internal pure returns (BooleanSlot) {
        return BooleanSlot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a bytes32.
     */
    type Bytes32Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Bytes32Slot.
     */
    function asBytes32(bytes32 slot) internal pure returns (Bytes32Slot) {
        return Bytes32Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a uint256.
     */
    type Uint256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Uint256Slot.
     */
    function asUint256(bytes32 slot) internal pure returns (Uint256Slot) {
        return Uint256Slot.wrap(slot);
    }

    /**
     * @dev UDVT that represents a slot holding a int256.
     */
    type Int256Slot is bytes32;

    /**
     * @dev Cast an arbitrary slot to a Int256Slot.
     */
    function asInt256(bytes32 slot) internal pure returns (Int256Slot) {
        return Int256Slot.wrap(slot);
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(AddressSlot slot) internal view returns (address value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(AddressSlot slot, address value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(BooleanSlot slot) internal view returns (bool value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(BooleanSlot slot, bool value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Bytes32Slot slot) internal view returns (bytes32 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Bytes32Slot slot, bytes32 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Uint256Slot slot) internal view returns (uint256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Uint256Slot slot, uint256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }

    /**
     * @dev Load the value held at location `slot` in transient storage.
     */
    function tload(Int256Slot slot) internal view returns (int256 value) {
        assembly ("memory-safe") {
            value := tload(slot)
        }
    }

    /**
     * @dev Store `value` at location `slot` in transient storage.
     */
    function tstore(Int256Slot slot, int256 value) internal {
        assembly ("memory-safe") {
            tstore(slot, value)
        }
    }
}

lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}

lib/permit2/src/interfaces/IEIP712.sol

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

interface IEIP712 {
    function DOMAIN_SEPARATOR() external view returns (bytes32);
}

lib/permit2/src/interfaces/ISignatureTransfer.sol

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

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

/// @title SignatureTransfer
/// @notice Handles ERC20 token transfers through signature based actions
/// @dev Requires user's token approval on the Permit2 contract
interface ISignatureTransfer is IEIP712 {
    /// @notice Thrown when the requested amount for a transfer is larger than the permissioned amount
    /// @param maxAmount The maximum amount a spender can request to transfer
    error InvalidAmount(uint256 maxAmount);

    /// @notice Thrown when the number of tokens permissioned to a spender does not match the number of tokens being transferred
    /// @dev If the spender does not need to transfer the number of tokens permitted, the spender can request amount 0 to be transferred
    error LengthMismatch();

    /// @notice Emits an event when the owner successfully invalidates an unordered nonce.
    event UnorderedNonceInvalidation(address indexed owner, uint256 word, uint256 mask);

    /// @notice The token and amount details for a transfer signed in the permit transfer signature
    struct TokenPermissions {
        // ERC20 token address
        address token;
        // the maximum amount that can be spent
        uint256 amount;
    }

    /// @notice The signed permit message for a single token transfer
    struct PermitTransferFrom {
        TokenPermissions permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice Specifies the recipient address and amount for batched transfers.
    /// @dev Recipients and amounts correspond to the index of the signed token permissions array.
    /// @dev Reverts if the requested amount is greater than the permitted signed amount.
    struct SignatureTransferDetails {
        // recipient address
        address to;
        // spender requested amount
        uint256 requestedAmount;
    }

    /// @notice Used to reconstruct the signed permit message for multiple token transfers
    /// @dev Do not need to pass in spender address as it is required that it is msg.sender
    /// @dev Note that a user still signs over a spender address
    struct PermitBatchTransferFrom {
        // the tokens and corresponding amounts permitted for a transfer
        TokenPermissions[] permitted;
        // a unique value for every token owner's signature to prevent signature replays
        uint256 nonce;
        // deadline on the permit signature
        uint256 deadline;
    }

    /// @notice A map from token owner address and a caller specified word index to a bitmap. Used to set bits in the bitmap to prevent against signature replay protection
    /// @dev Uses unordered nonces so that permit messages do not need to be spent in a certain order
    /// @dev The mapping is indexed first by the token owner, then by an index specified in the nonce
    /// @dev It returns a uint256 bitmap
    /// @dev The index, or wordPosition is capped at type(uint248).max
    function nonceBitmap(address, uint256) external view returns (uint256);

    /// @notice Transfers a token using a signed permit message
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers a token using a signed permit message
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @dev Reverts if the requested amount is greater than the permitted signed amount
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails The spender's requested transfer details for the permitted token
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitTransferFrom memory permit,
        SignatureTransferDetails calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param signature The signature to verify
    function permitTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes calldata signature
    ) external;

    /// @notice Transfers multiple tokens using a signed permit message
    /// @dev The witness type string must follow EIP712 ordering of nested structs and must include the TokenPermissions type definition
    /// @notice Includes extra data provided by the caller to verify signature over
    /// @param permit The permit data signed over by the owner
    /// @param owner The owner of the tokens to transfer
    /// @param transferDetails Specifies the recipient and requested amount for the token transfer
    /// @param witness Extra data to include when checking the user signature
    /// @param witnessTypeString The EIP-712 type definition for remaining string stub of the typehash
    /// @param signature The signature to verify
    function permitWitnessTransferFrom(
        PermitBatchTransferFrom memory permit,
        SignatureTransferDetails[] calldata transferDetails,
        address owner,
        bytes32 witness,
        string calldata witnessTypeString,
        bytes calldata signature
    ) external;

    /// @notice Invalidates the bits specified in mask for the bitmap at the word position
    /// @dev The wordPos is maxed at type(uint248).max
    /// @param wordPos A number to index the nonceBitmap at
    /// @param mask A bitmap masked against msg.sender's current bitmap at the word position
    function invalidateUnorderedNonces(uint256 wordPos, uint256 mask) external;
}

src/credit-desk/ICreditDesk.sol

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

import {ISignatureTransfer} from "permit2/src/interfaces/ISignatureTransfer.sol";

/// @title ICreditDesk — the Lender's loan book on one chain, for any asset
interface ICreditDesk {
    /// @notice The lender's Permit2 `PermitBatchWitnessTransferFrom` signature over
    /// `permitted`, with spender = CreditDesk and the witness
    /// `LiquidityGrant(borrower, caller, loanId, asset, amount)`. Each token is the
    /// asset or an ERC-4626 vault of it, so one grant can pay from the lender's
    /// wallet and its vault shares together. Borrower, caller, loanId, asset and
    /// amount are never part of this: the CreditDesk builds the witness itself.
    struct Grant {
        ISignatureTransfer.TokenPermissions[] permitted;
        uint256 nonce;
        uint256 deadline;
        bytes signature;
    }

    /// @notice How a caller of {borrow} and {borrowOnBehalf} for a borrower is checked.
    /// `Relay`: `tx.origin` must be the borrower or one of its executors, for a
    /// contract that runs calls for many senders, such as a multicall.
    /// `Trusted`: no `tx.origin` check, for a contract that borrows only with the
    /// borrower's own signature over the loan, such as TakerSettler.
    enum CallerKind {
        None,
        Relay,
        Trusted
    }

    error NotOwner();
    error NotPendingOwner();
    error ZeroAddress();
    error ZeroAmount();
    error NotAVault();
    error GrantTooSmall();
    error NoDebt();
    error RescueFailed();
    error RescueRecipientNotAllowed();
    error NotCaller();
    error NotExecutor();
    error NotBorrower();
    error CreditLimitExceeded();

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    event LenderSet(address indexed previousLender, address indexed newLender);
    event CallerSet(address indexed borrower, address indexed caller, CallerKind kind);
    event ExecutorSet(address indexed borrower, address indexed executor, bool allowed);
    event CreditLimitSet(address indexed borrower, address asset, uint256 limit);

    /// @param borrower Who owes the loan; the grant's `borrower`.
    /// @param caller Who sent the call.
    /// @param loanId The loan's id; the grant's `loanId`.
    /// @param asset What the borrower received and owes; the grant's `asset`.
    /// @param receiver Who received the asset: `borrower` for {borrow}, `caller` for {borrowOnBehalf}.
    /// @param amount Asset delivered and booked as debt.
    /// @param received Asset the grant brought in; `received - amount` goes back to the Lender wallet.
    event Borrowed(
        address indexed borrower,
        address indexed caller,
        bytes32 indexed loanId,
        address asset,
        address receiver,
        uint256 amount,
        uint256 received
    );
    event Repaid(address indexed borrower, address indexed payer, address asset, uint256 amount);
    event InterestPaid(address indexed borrower, address indexed payer, address asset, uint256 amount);
    event Rescued(address indexed token, address indexed to, uint256 amount);

    function initialize(address initialOwner, address lender_) external;

    function LIQUIDITY_GRANT_WITNESS_TYPE_STRING() external view returns (string memory);
    function LIQUIDITY_GRANT_TYPEHASH() external view returns (bytes32);
    function REPAYMENT_WITNESS_TYPE_STRING() external view returns (string memory);
    function REPAYMENT_TYPEHASH() external view returns (bytes32);
    function INTEREST_PAYMENT_WITNESS_TYPE_STRING() external view returns (string memory);
    function INTEREST_PAYMENT_TYPEHASH() external view returns (bytes32);
    function PERMIT2() external view returns (ISignatureTransfer);
    function owner() external view returns (address);
    function pendingOwner() external view returns (address);
    function lender() external view returns (address);
    function debt(address borrower, address asset) external view returns (uint256);

    /// @notice How `caller` may call {borrow} and {borrowOnBehalf} for `borrower`;
    /// `None` when it may not. `borrower` itself always may. Only the owner sets
    /// callers, and a borrower cannot remove one, so the owner is trusted not to let
    /// a caller take a loan the borrower did not ask for.
    function callerKind(address borrower, address caller) external view returns (CallerKind);

    /// @notice Whether `executor` may send the transaction in which a `Relay`
    /// caller borrows for `borrower`, as `tx.origin`. `borrower` itself always may. An
    /// executor does not call the CreditDesk: it is not a caller unless the owner also
    /// sets it as one. A contract borrower, such as a Safe, is never `tx.origin`, so
    /// each EOA that sends its transactions (a signer or a relayer) must be its executor;
    /// only its direct call, with `msg.sender == borrower`, needs no executor.
    function isExecutorFor(address borrower, address executor) external view returns (bool);

    /// @notice The most debt in `asset` that `borrower` may hold after a borrow.
    /// Zero until the owner sets it, so a borrower without a limit cannot borrow.
    function creditLimit(address borrower, address asset) external view returns (uint256);

    /// @notice Whether `account` borrows `asset` here: it has a credit limit or a debt in it.
    /// Callers and executors borrow for a borrower and do not always receive the loan.
    function isBorrower(address account, address asset) external view returns (bool);

    function transferOwnership(address newOwner) external;
    function acceptOwnership() external;
    function setLender(address lender_) external;
    function setCaller(address borrower, address caller, CallerKind kind) external;
    function setExecutor(address borrower, address executor, bool allowed) external;
    function setCreditLimit(address borrower, address asset, uint256 limit) external;

    /// @notice Send `amount` of `token` to `to`; `token == address(0)` is the native
    /// token. `to` must be the lender or a borrower of `token` ({isBorrower}). No account
    /// borrows the native token, so it goes only to the lender. This stops mistakes, not
    /// a malicious owner: in one more transaction it can set itself a credit limit or
    /// make itself the lender, then rescue to itself, and it controls upgrades.
    function rescue(address token, address to, uint256 amount) external;

    /// @notice Spend a grant issued to `borrower` with `caller = address(0)`,
    /// deliver exactly `amount` of `asset` to `borrower` and book it as its
    /// debt. `borrower` or a caller set for it sends it ({callerKind}): the money can
    /// only go to `borrower`.
    function borrow(address borrower, address asset, uint256 amount, bytes32 loanId, Grant calldata grant)
        external
        returns (uint256 paid);

    /// @notice Spend a grant issued to `borrower` with `caller = msg.sender`,
    /// deliver exactly `amount` of `asset` to the caller and book it as the
    /// debt of `borrower`. The caller must be `borrower` or a caller set for it ({callerKind}).
    function borrowOnBehalf(address borrower, address asset, uint256 amount, bytes32 loanId, Grant calldata grant)
        external
        returns (uint256 paid);

    /// @notice Pull up to `amount` of `asset` from the caller to the lender and
    /// reduce the caller's own debt in it by that. Pays at most that debt, so a
    /// payment races no other payment. Reverts when nothing is owed. An executor
    /// cannot repay the debt of its borrower.
    /// @return paid What left the caller: `amount`, or the debt when it is smaller.
    function repay(address asset, uint256 amount) external returns (uint256 paid);

    /// @notice {payInterestFor} the caller's own debt.
    function payInterest(address asset, uint256 amount) external;

    /// @notice Pull `amount` of `asset` from the caller to the lender as
    /// interest on the debt of `borrower`. No cap: the lender computes interest.
    /// Any caller may pay it.
    function payInterestFor(address borrower, address asset, uint256 amount) external;

    /// @notice {repay} with the payer's Permit2 `PermitWitnessTransferFrom`
    /// instead of an approval: spender = CreditDesk, witness `Repayment(borrower)`.
    /// The permitted token is the asset repaid and the permitted amount the most
    /// repaid; it goes from `payer` straight to the lender. `payer` must be
    /// `borrower`; anyone may send it.
    function repayWithPermit(
        address borrower,
        address payer,
        ISignatureTransfer.PermitTransferFrom calldata permit,
        bytes calldata signature
    ) external returns (uint256 paid);

    /// @notice {payInterestFor} with the payer's Permit2 `PermitWitnessTransferFrom`:
    /// spender = CreditDesk, witness `InterestPayment(borrower)`. Any payer may sign
    /// it and anyone may send it.
    function payInterestWithPermit(
        address borrower,
        address payer,
        ISignatureTransfer.PermitTransferFrom calldata permit,
        bytes calldata signature
    ) external;

    /// @notice EIP-712 struct hash of a grant witness:
    /// `LiquidityGrant(borrower, caller, loanId, asset, amount)`.
    function hashLiquidityGrant(address borrower, address caller, bytes32 loanId, address asset, uint256 amount)
        external
        pure
        returns (bytes32);
}
Compiler settingsShow
{
  "viaIR": false,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 10000,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "@uniswap/v3-core/=lib/v3-core/contracts/",
    "permit2/=lib/permit2/",
    "forge-std/=lib/forge-std/src/",
    "ds-test/=lib/permit2/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-gas-snapshot/=lib/permit2/lib/forge-gas-snapshot/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "solmate/=lib/permit2/lib/solmate/",
    "v3-core/=lib/v3-core/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.