Skip to content
Verified contractExactMIT

Kitchen

Address0xddaef9afa92f86bd89132f18fca79b10ed25e99c
Balance

0 ETH

 

Transactions

0

 

Compiler

solc 0.8.27

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.27+commit.40a35a09
Language
solidity
Optimization
Yes, 1,000 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,257,210
Creation transaction
0xc74623d483…fa03a3d333

src/Kitchen.sol

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

import {
    Ownable2StepUpgradeable
} from "../lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol";
import { Pot } from "./Pot.sol";
import { IKitchenDeployer } from "./interfaces/IKitchenDeployer.sol";
import { UUPSUpgradeable } from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import { Create2 } from "@openzeppelin/contracts/utils/Create2.sol";

/// @title Kitchen
/// @notice Factory / entry point that deterministically deploys {Pot} proxies: Private Pots, each
///         run by its owner, and Shared Pots, which anyone may cook.
/// @dev Each Pot is deployed via CREATE2 keyed on (owner, salt, whether its Router is fixed). The
///      Pot takes no constructor arguments — its owner, user salt and fixed flag
///      ({IKitchenDeployer.potParameters}) and its starting implementation ({router}) reach it
///      through construction-time callbacks. That keeps every Pot's initcode identical to
///      `type(Pot).creationCode`, so {potInitCodeHash} is a single value the engine gate can embed as
///      a constant; identity is still committed into the address through the CREATE2 salt ({_salt},
///      which {Pot.gateSalt} mirrors).
///
///      THREE KINDS, ONE BYTECODE. {deployPot} mints a Private Pot whose Router its owner moves, as
///      every Pot was before Shared Pots. {deployPot} with `routerFixed` mints a Private Pot whose
///      Router is the Kitchen's at mint, for good. {deploySharedPot} mints a Pot with no owner, which
///      anyone may cook, and always with a fixed Router: a Router any cooked program could rewrite
///      has no place on a Pot that runs everyone's programs (see {Pot}). The fixed flag is in the
///      CREATE2 salt, so the three never share an address, and minting one cannot occupy another's.
///
///      THE ROUTER IS STATE, NOT CODE. {router} lives in this proxy's storage and the owner moves it
///      with {setRouter}, so neither this implementation's bytecode nor any Pot's initcode or address
///      depends on it. Switching it moves no Pot, no engine's gate and no implementation: Pots minted
///      afterwards start on the new Router, and a Pot already deployed keeps its own Router — a
///      Private one until its owner calls that Pot's {Pot.setRouter}, a fixed one for good. The
///      Kitchen keeps nothing per Pot, and no function here reaches a deployed Pot's Router. The two
///      contracts share the names, the event and the error.
///
///      The Kitchen also owns the flat execution fee: {Pot.cook} reads {executionFee} and remits it
///      here. The owner controls the fee, the Router and UUPS upgrades; initialization requires a nonzero fee.
/// Ownership is two-step (via {Ownable2StepUpgradeable}) and renouncing is disabled — this proxy's
///      address is baked into every Pot's CREATE2 derivation, so an owner lost to a fat-fingered
///      transfer or a renounce cannot be recovered without abandoning the whole Pot family.
contract Kitchen is IKitchenDeployer, Ownable2StepUpgradeable, UUPSUpgradeable {
    /// @notice The uniform CREATE2 init-code hash shared by every Pot: `keccak256(type(Pot).creationCode)`,
    ///         with no constructor arguments and so nothing of the Router. The engine gate embeds
    ///         this same value as a constant, and only a change to the Pot's own compiled bytecode
    ///         moves it.
    bytes32 public immutable potInitCodeHash;

    /// @notice ERC-7201 namespaced storage for the Kitchen's mutable state.
    /// @dev The Kitchen sits behind a proxy, and namespaced storage is how OpenZeppelin's
    ///      upgradeable contracts keep mutable state out of the sequential-slot layout a proxy must
    ///      preserve. Each namespace and the layout within it must remain stable across upgrades. It
    ///      also keeps `forge inspect Kitchen storageLayout` empty, so the "declares no storage" CI
    ///      guard stands as "all mutable state must be namespaced". `executionFee` is set atomically
    ///      during initialization and updated via {setExecutionFee}. Ownership and initialization state use
    ///      OpenZeppelin's separate ERC-7201 namespaces in the same proxy storage.
    ///
    ///      `router` was APPENDED, so `executionFee` keeps offset 0 and a proxy initialized by an
    ///      implementation that held the Router as an immutable reads this field as zero until an
    ///      upgrade sets it. The deploy pipeline upgrades with `upgradeToAndCall(new, setRouter(r))`,
    ///      which does both in one transaction; {Pot}'s constructor refuses an unset Router, so a
    ///      zero here can never mint a Pot.
    /// @custom:storage-location erc7201:sauce.storage.Kitchen
    struct KitchenStorage {
        uint256 executionFee;
        address router;
    }

    // keccak256(abi.encode(uint256(keccak256("sauce.storage.Kitchen")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant KITCHEN_STORAGE_LOCATION =
        0x5384a20a2274531eff1a9d6e0fd4a21c7fd0f38287b942efdb9af2a20efe5a00;

    function _kitchenStorage() private pure returns (KitchenStorage storage $) {
        assembly {
            $.slot := KITCHEN_STORAGE_LOCATION
        }
    }

    /// @notice Thrown when {deployPot} is asked for the zero owner. A Pot with no owner is a Shared
    ///         Pot, which anyone may cook: {deploySharedPot} mints it, always with a fixed Router.
    error ZeroOwner();
    error ZeroInitialExecutionFee();

    /// @notice Thrown by {renounceOwnership}: the Kitchen's owner is the only party that can ever
    ///         authorize an upgrade, and every Pot's CREATE2 address commits to this proxy, so a
    ///         renounce would freeze the implementation behind a dead address with no recovery.
    error OwnershipIsPermanent();

    /// @notice Thrown when a withdrawal names the zero address, which would burn the fees.
    error ZeroRecipient();

    /// @notice Thrown when a withdrawal asks for more than the Kitchen holds. Explicit rather than
    ///         leaving it to the low-level call, whose failure cannot say which side was wrong.
    error InsufficientBalance(uint256 requested, uint256 available);

    /// @notice Thrown when the recipient rejects the transfer. The whole withdrawal reverts, so the
    ///         fees stay put rather than being partially released.
    error WithdrawalFailed();

    /// @notice Thrown by {setRouter} for an address with no code. A Pot started on one would answer
    ///         every swap self-call and pool callback with a silent, empty success.
    error RouterHasNoCode();

    event PotDeployed(address indexed owner, bytes32 indexed salt, address pot);
    event ExecutionFeeSet(uint256 fee);
    event RouterSet(address indexed router);
    event ExecutionFeesWithdrawn(address indexed recipient, uint256 amount);

    /// @dev Transient slots holding the parameters of the Pot currently being constructed, read
    ///      back through {potParameters}. Cleared immediately after the deploy.
    uint256 private constant CTX_OWNER = 0xc70011;
    uint256 private constant CTX_SALT = 0xc70022;
    uint256 private constant CTX_ROUTER_FIXED = 0xc70033;

    /// @dev No Router and no other argument: this implementation's bytecode is a function of the Pot
    ///      creation code and its own address, and of nothing a Router rollout changes.
    constructor() {
        _disableInitializers();
        potInitCodeHash = keccak256(type(Pot).creationCode);
    }

    /// @notice Initialize the proxy's owner and nonzero execution fee during KitchenProxy construction.
    /// @dev The owner is explicit because CREATE3 deploys through a helper contract. The Router is not
    ///      an argument because the call is fixed by `KitchenProxy`'s constructor, which is live at
    ///      generation 2 and cannot change without moving the proxy. A fresh deploy therefore sets it
    ///      with {setRouter} straight after, and {Pot}'s constructor refuses to mint in between.
    function initialize(
        address initialOwner,
        uint256 initialExecutionFee
    ) external initializer {
        if (initialExecutionFee == 0) {
            revert ZeroInitialExecutionFee();
        }
        __Ownable_init(initialOwner);
        _kitchenStorage().executionFee = initialExecutionFee;
        emit ExecutionFeeSet(initialExecutionFee);
    }

    /// @inheritdoc IKitchenDeployer
    /// @dev Integrators should read this on the Kitchen proxy before every cook and include the
    ///      quoted wei amount in msg.value. If the fee rises before execution, cook reverts.
    function executionFee() external view returns (uint256) {
        return _kitchenStorage().executionFee;
    }

    /// @inheritdoc IKitchenDeployer
    /// @dev Zero until {setRouter} runs on this proxy, and then whatever the owner last set.
    function router() external view returns (address) {
        return _kitchenStorage().router;
    }

    /// @notice Accept the execution fee remitted by Pots.
    receive() external payable { }

    /// @notice Deploy a Private Pot for `owner` at the given salt, or return it if already deployed.
    ///         Its Router starts as the Kitchen's {router}, and its owner moves it with
    ///         {Pot.setRouter}.
    function deployPot(
        address owner,
        bytes32 salt
    ) external returns (address pot) {
        return deployPot(owner, salt, false);
    }

    /// @notice Deploy a Private Pot for `owner` at the given salt, or return it if already deployed.
    ///         With `routerFixed`, its Router is the Kitchen's {router} at mint and nothing ever moves
    ///         it; without, this is {deployPot}`(owner, salt)`.
    /// @dev The same owner and salt derive a different address with and without `routerFixed`.
    function deployPot(
        address owner,
        bytes32 salt,
        bool routerFixed
    ) public returns (address pot) {
        if (owner == address(0)) {
            revert ZeroOwner();
        }
        return _deploy(owner, salt, routerFixed);
    }

    /// @notice Deploy the Shared Pot at `salt`, or return it if already deployed. It has no owner,
    ///         anyone may cook it, the Kitchen's fee is charged on every cook, and its Router is the
    ///         Kitchen's {router} at mint, for good.
    /// @dev Anyone may call this, as anyone may call {deployPot}. Whoever mints it first fixes its
    ///      Router to the Kitchen's at that moment; the address does not depend on which.
    function deploySharedPot(
        bytes32 salt
    ) external returns (address pot) {
        return _deploy(address(0), salt, true);
    }

    /// @notice Predict the address of the Private Pot {deployPot}`(owner, salt)` deploys.
    function predictPot(
        address owner,
        bytes32 salt
    ) external view returns (address) {
        return _predict(owner, salt, false);
    }

    /// @notice Predict the address of the Private Pot {deployPot}`(owner, salt, routerFixed)`
    ///         deploys.
    function predictPot(
        address owner,
        bytes32 salt,
        bool routerFixed
    ) external view returns (address) {
        return _predict(owner, salt, routerFixed);
    }

    /// @notice Predict the address of the Shared Pot {deploySharedPot}`(salt)` deploys.
    function predictSharedPot(
        bytes32 salt
    ) external view returns (address) {
        return _predict(address(0), salt, true);
    }

    /// @inheritdoc IKitchenDeployer
    /// @dev Read by a Pot's constructor (msg.sender == this Kitchen). Reverts to zero outside a
    ///      deploy, which a stray caller would see as an all-zero Pot.
    function potParameters() external view returns (address owner, bytes32 salt, bool routerFixed) {
        assembly {
            owner := tload(CTX_OWNER)
            salt := tload(CTX_SALT)
            routerFixed := tload(CTX_ROUTER_FIXED)
        }
    }

    /// @notice Set the {Router} that Pots minted from now on start on. Owner only.
    /// @dev No power the owner lacked: a UUPS upgrade could already install an implementation that
    ///      mints Pots on anything, and this reaches exactly as far — Pots minted after it. A Pot
    ///      already deployed keeps its own {Pot.router}: only a Private Pot's own owner moves it, and
    ///      nothing moves a fixed one.
    ///
    ///      Also the upgrade's call: `upgradeToAndCall(newImplementation, setRouter(router))` installs
    ///      an implementation and its Router in one transaction, which is how a proxy initialized
    ///      before the Router moved into storage gets one.
    function setRouter(
        address newRouter
    ) external onlyOwner {
        if (newRouter.code.length == 0) {
            revert RouterHasNoCode();
        }
        _kitchenStorage().router = newRouter;
        emit RouterSet(newRouter);
    }

    /// @notice Set the flat execution fee. Owner only.
    function setExecutionFee(
        uint256 fee
    ) external onlyOwner {
        _kitchenStorage().executionFee = fee;
        emit ExecutionFeeSet(fee);
    }

    /// @notice Withdraw collected execution fees to `recipient`. Owner only.
    /// @param recipient Where the fees go. Not stored: a destination the owner fixes in advance is a
    ///        different design (a permissionless pull to a set treasury), and storing one here
    ///        without that would only add state.
    /// @param amount How much to send, in wei. Pass the balance to sweep; there is deliberately no
    ///        "withdraw everything" sentinel, so the transaction that moves funds says how much.
    /// @dev PULL, not push. The alternative — forwarding each fee to a configured treasury inside
    ///      {Pot._chargeFee} — puts an owner-settable address on the cook path, where a recipient
    ///      that reverts or burns gas makes every cook more expensive or impossible and nothing can
    ///      route around it. Here the cook path still pays into this contract's empty {receive},
    ///      which is known-good, and collection is a separate owner action that can fail harmlessly.
    ///
    ///      `call` rather than `transfer`: the 2300-gas stipend fails against a multisig or any
    ///      recipient with a non-trivial `receive`, which is what an owner withdrawing fees usually
    ///      is.
    ///
    ///      Checks-effects-interactions, though this contract holds no state the call could reenter
    ///      into — the balance is the state, and it is read before the transfer. It is the
    ///      Kitchen's only outbound value transfer, and the ordering is kept so it stays that way.
    ///
    ///      Holding or releasing funds cannot move a Pot: its address derives from the owner, the user
    ///      salt, whether its Router is fixed, this proxy's address and {potInitCodeHash}, and a
    ///      balance appears in none of them.
    function withdrawExecutionFees(
        address recipient,
        uint256 amount
    ) external onlyOwner {
        if (recipient == address(0)) {
            revert ZeroRecipient();
        }
        uint256 available = address(this).balance;
        if (amount > available) {
            revert InsufficientBalance(amount, available);
        }

        emit ExecutionFeesWithdrawn(recipient, amount);

        (bool ok,) = recipient.call{ value: amount }("");
        if (!ok) {
            revert WithdrawalFailed();
        }
    }

    /// @dev UUPS invokes this check before changing the proxy's implementation.
    function _authorizeUpgrade(
        address
    ) internal override onlyOwner { }

    /// @dev Ownership transfer is two-step (via {Ownable2StepUpgradeable}) and renouncing is
    ///      disabled: this proxy's address is baked into every Pot's CREATE2 derivation, so an owner
    ///      lost to a fat-fingered transfer or a renounce cannot be recovered without abandoning the
    ///      whole Pot family behind a new `kitchenGeneration`.
    function renounceOwnership() public pure override {
        revert OwnershipIsPermanent();
    }

    /// @dev Mint the Pot `_predict` names, unless it exists. The parameters sit in transient storage
    ///      only while the Pot's constructor reads them back through {potParameters}.
    function _deploy(
        address owner,
        bytes32 salt,
        bool routerFixed
    ) private returns (address pot) {
        pot = _predict(owner, salt, routerFixed);
        if (pot.code.length == 0) {
            assembly {
                tstore(CTX_OWNER, owner)
                tstore(CTX_SALT, salt)
                tstore(CTX_ROUTER_FIXED, routerFixed)
            }
            address deployed = address(new Pot{ salt: _salt(owner, salt, routerFixed) }());
            assembly {
                tstore(CTX_OWNER, 0)
                tstore(CTX_SALT, 0)
                tstore(CTX_ROUTER_FIXED, 0)
            }
            // Determinism invariant: CREATE2 must land on the predicted address.
            assert(deployed == pot);
            emit PotDeployed(owner, salt, pot);
        }
    }

    function _predict(
        address owner,
        bytes32 salt,
        bool routerFixed
    ) private view returns (address) {
        return Create2.computeAddress(_salt(owner, salt, routerFixed), potInitCodeHash, address(this));
    }

    /// @dev Namespaces the user salt by owner, and by whether the Router is fixed, so a CREATE2
    ///      address is unique per (owner, salt, fixed). A Pot whose Router is not fixed keeps the
    ///      two-word preimage every Pot had before fixed Routers; a fixed one appends `true`. The
    ///      Router itself is in neither. {Pot.gateSalt} computes the same, which is how the engine
    ///      gate re-derives every kind of Pot with one init-code hash.
    function _salt(
        address owner,
        bytes32 salt,
        bool routerFixed
    ) private pure returns (bytes32) {
        if (!routerFixed) {
            return keccak256(abi.encode(owner, salt));
        }
        return keccak256(abi.encode(owner, salt, true));
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol

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

pragma solidity ^0.8.20;

import {OwnableUpgradeable} from "./OwnableUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.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 Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step
    struct Ownable2StepStorage {
        address _pendingOwner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00;

    function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) {
        assembly {
            $.slot := Ownable2StepStorageLocation
        }
    }

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

    function __Ownable2Step_init() internal onlyInitializing {
    }

    function __Ownable2Step_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev Returns the address of the pending owner.
     */
    function pendingOwner() public view virtual returns (address) {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        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 {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        $._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 {
        Ownable2StepStorage storage $ = _getOwnable2StepStorage();
        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-upgradeable/contracts/access/OwnableUpgradeable.sol

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

pragma solidity ^0.8.20;

import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * 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 OwnableUpgradeable is Initializable, ContextUpgradeable {
    /// @custom:storage-location erc7201:openzeppelin.storage.Ownable
    struct OwnableStorage {
        address _owner;
    }

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300;

    function _getOwnableStorage() private pure returns (OwnableStorage storage $) {
        assembly {
            $.slot := OwnableStorageLocation
        }
    }

    /**
     * @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.
     */
    function __Ownable_init(address initialOwner) internal onlyInitializing {
        __Ownable_init_unchained(initialOwner);
    }

    function __Ownable_init_unchained(address initialOwner) internal onlyInitializing {
        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) {
        OwnableStorage storage $ = _getOwnableStorage();
        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 {
        OwnableStorage storage $ = _getOwnableStorage();
        address oldOwner = $._owner;
        $._owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

lib/openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol

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

pragma solidity ^0.8.20;
import {Initializable} from "@openzeppelin/contracts/proxy/utils/Initializable.sol";

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

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

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

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

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

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

pragma solidity >=0.4.11;

/**
 * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
 */
interface IERC1967 {
    /**
     * @dev Emitted when the implementation is upgraded.
     */
    event Upgraded(address indexed implementation);

    /**
     * @dev Emitted when the admin account has changed.
     */
    event AdminChanged(address previousAdmin, address newAdmin);

    /**
     * @dev Emitted when the beacon is changed.
     */
    event BeaconUpgraded(address indexed beacon);
}

lib/openzeppelin-contracts/contracts/interfaces/draft-IERC1822.sol

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

pragma solidity >=0.4.16;

/**
 * @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
 * proxy whose upgrades are fully controlled by the current implementation.
 */
interface IERC1822Proxiable {
    /**
     * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
     * address.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy.
     */
    function proxiableUUID() external view returns (bytes32);
}

lib/openzeppelin-contracts/contracts/proxy/ERC1967/ERC1967Utils.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/ERC1967/ERC1967Utils.sol)

pragma solidity ^0.8.21;

import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";

/**
 * @dev This library provides getters and event emitting update functions for
 * https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
 */
library ERC1967Utils {
    /**
     * @dev Storage slot with the address of the current implementation.
     * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

    /**
     * @dev The `implementation` of the proxy is invalid.
     */
    error ERC1967InvalidImplementation(address implementation);

    /**
     * @dev The `admin` of the proxy is invalid.
     */
    error ERC1967InvalidAdmin(address admin);

    /**
     * @dev The `beacon` of the proxy is invalid.
     */
    error ERC1967InvalidBeacon(address beacon);

    /**
     * @dev An upgrade function sees `msg.value > 0` that may be lost.
     */
    error ERC1967NonPayable();

    /**
     * @dev Returns the current implementation address.
     */
    function getImplementation() internal view returns (address) {
        return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 implementation slot.
     */
    function _setImplementation(address newImplementation) private {
        if (newImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(newImplementation);
        }
        StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
    }

    /**
     * @dev Performs implementation upgrade with additional setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) internal {
        _setImplementation(newImplementation);
        emit IERC1967.Upgraded(newImplementation);

        if (data.length > 0) {
            Address.functionDelegateCall(newImplementation, data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Storage slot with the admin of the contract.
     * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;

    /**
     * @dev Returns the current admin.
     *
     * TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
     * the https://ethereum.org/developers/docs/apis/json-rpc/#eth_getstorageat[`eth_getStorageAt`] RPC call.
     * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
     */
    function getAdmin() internal view returns (address) {
        return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
    }

    /**
     * @dev Stores a new address in the ERC-1967 admin slot.
     */
    function _setAdmin(address newAdmin) private {
        if (newAdmin == address(0)) {
            revert ERC1967InvalidAdmin(address(0));
        }
        StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
    }

    /**
     * @dev Changes the admin of the proxy.
     *
     * Emits an {IERC1967-AdminChanged} event.
     */
    function changeAdmin(address newAdmin) internal {
        emit IERC1967.AdminChanged(getAdmin(), newAdmin);
        _setAdmin(newAdmin);
    }

    /**
     * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
     * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
     */
    // solhint-disable-next-line private-vars-leading-underscore
    bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;

    /**
     * @dev Returns the current beacon.
     */
    function getBeacon() internal view returns (address) {
        return StorageSlot.getAddressSlot(BEACON_SLOT).value;
    }

    /**
     * @dev Stores a new beacon in the ERC-1967 beacon slot.
     */
    function _setBeacon(address newBeacon) private {
        if (newBeacon.code.length == 0) {
            revert ERC1967InvalidBeacon(newBeacon);
        }

        StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;

        address beaconImplementation = IBeacon(newBeacon).implementation();
        if (beaconImplementation.code.length == 0) {
            revert ERC1967InvalidImplementation(beaconImplementation);
        }
    }

    /**
     * @dev Change the beacon and trigger a setup call if data is nonempty.
     * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
     * to avoid stuck value in the contract.
     *
     * Emits an {IERC1967-BeaconUpgraded} event.
     *
     * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
     * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
     * efficiency.
     */
    function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
        _setBeacon(newBeacon);
        emit IERC1967.BeaconUpgraded(newBeacon);

        if (data.length > 0) {
            Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
        } else {
            _checkNonPayable();
        }
    }

    /**
     * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
     * if an upgrade doesn't perform an initialization call.
     */
    function _checkNonPayable() private {
        if (msg.value > 0) {
            revert ERC1967NonPayable();
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/beacon/IBeacon.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/beacon/IBeacon.sol)

pragma solidity >=0.4.16;

/**
 * @dev This is the interface that {BeaconProxy} expects of its beacon.
 */
interface IBeacon {
    /**
     * @dev Must return an address that can be used as a delegate call target.
     *
     * {UpgradeableBeacon} will check that this address is a contract.
     */
    function implementation() external view returns (address);
}

lib/openzeppelin-contracts/contracts/proxy/utils/Initializable.sol

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

pragma solidity ^0.8.20;

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

    // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;

    /**
     * @dev The contract is already initialized.
     */
    error InvalidInitialization();

    /**
     * @dev The contract is not initializing.
     */
    error NotInitializing();

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

    /**
     * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
     * `onlyInitializing` functions can be used to initialize parent contracts.
     *
     * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
     * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
     * production.
     *
     * Emits an {Initialized} event.
     */
    modifier initializer() {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        // Cache values to avoid duplicated sloads
        bool isTopLevelCall = !$._initializing;
        uint64 initialized = $._initialized;

        // Allowed calls:
        // - initialSetup: the contract is not in the initializing state and no previous version was
        //                 initialized
        // - construction: the contract is initialized at version 1 (no reinitialization) and the
        //                 current contract is just being deployed
        bool initialSetup = initialized == 0 && isTopLevelCall;
        bool construction = initialized == 1 && address(this).code.length == 0;

        if (!initialSetup && !construction) {
            revert InvalidInitialization();
        }
        $._initialized = 1;
        if (isTopLevelCall) {
            $._initializing = true;
        }
        _;
        if (isTopLevelCall) {
            $._initializing = false;
            emit Initialized(1);
        }
    }

    /**
     * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
     * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
     * used to initialize parent contracts.
     *
     * A reinitializer may be used after the original initialization step. This is essential to configure modules that
     * are added through upgrades and that require initialization.
     *
     * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
     * cannot be nested. If one is invoked in the context of another, execution will revert.
     *
     * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
     * a contract, executing them in the right order is up to the developer or operator.
     *
     * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
     *
     * Emits an {Initialized} event.
     */
    modifier reinitializer(uint64 version) {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing || $._initialized >= version) {
            revert InvalidInitialization();
        }
        $._initialized = version;
        $._initializing = true;
        _;
        $._initializing = false;
        emit Initialized(version);
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} and {reinitializer} modifiers, directly or indirectly.
     */
    modifier onlyInitializing() {
        _checkInitializing();
        _;
    }

    /**
     * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
     */
    function _checkInitializing() internal view virtual {
        if (!_isInitializing()) {
            revert NotInitializing();
        }
    }

    /**
     * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
     * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
     * to any version. It is recommended to use this to lock implementation contracts that are designed to be called
     * through proxies.
     *
     * Emits an {Initialized} event the first time it is successfully executed.
     */
    function _disableInitializers() internal virtual {
        // solhint-disable-next-line var-name-mixedcase
        InitializableStorage storage $ = _getInitializableStorage();

        if ($._initializing) {
            revert InvalidInitialization();
        }
        if ($._initialized != type(uint64).max) {
            $._initialized = type(uint64).max;
            emit Initialized(type(uint64).max);
        }
    }

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

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

    /**
     * @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
     *
     * NOTE: Consider following the ERC-7201 formula to derive storage locations.
     */
    function _initializableStorageSlot() internal pure virtual returns (bytes32) {
        return INITIALIZABLE_STORAGE;
    }

    /**
     * @dev Returns a pointer to the storage namespace.
     */
    // solhint-disable-next-line var-name-mixedcase
    function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
        bytes32 slot = _initializableStorageSlot();
        assembly {
            $.slot := slot
        }
    }
}

lib/openzeppelin-contracts/contracts/proxy/utils/UUPSUpgradeable.sol

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

pragma solidity ^0.8.22;

import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";

/**
 * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
 * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
 *
 * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
 * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
 * `UUPSUpgradeable` with a custom implementation of upgrades.
 *
 * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
 *
 * @custom:stateless
 */
abstract contract UUPSUpgradeable is IERC1822Proxiable {
    /// @custom:oz-upgrades-unsafe-allow state-variable-immutable
    address private immutable __self = address(this);

    /**
     * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
     * and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
     * while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
     * If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
     * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
     * during an upgrade.
     */
    string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";

    /**
     * @dev The call is from an unauthorized context.
     */
    error UUPSUnauthorizedCallContext();

    /**
     * @dev The storage `slot` is unsupported as a UUID.
     */
    error UUPSUnsupportedProxiableUUID(bytes32 slot);

    /**
     * @dev Check that the execution is being performed through a delegatecall call and that the execution context is
     * a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
     * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
     * function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
     * fail.
     */
    modifier onlyProxy() {
        _checkProxy();
        _;
    }

    /**
     * @dev Check that the execution is not being performed through a delegate call. This allows a function to be
     * callable on the implementing contract but not through proxies.
     */
    modifier notDelegated() {
        _checkNotDelegated();
        _;
    }

    /**
     * @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
     * implementation. It is used to validate the implementation's compatibility when performing an upgrade.
     *
     * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
     * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
     * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
     */
    function proxiableUUID() external view notDelegated returns (bytes32) {
        return ERC1967Utils.IMPLEMENTATION_SLOT;
    }

    /**
     * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
     * encoded in `data`.
     *
     * Calls {_authorizeUpgrade}.
     *
     * Emits an {Upgraded} event.
     *
     * @custom:oz-upgrades-unsafe-allow-reachable delegatecall
     */
    function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
        _authorizeUpgrade(newImplementation);
        _upgradeToAndCallUUPS(newImplementation, data);
    }

    /**
     * @dev Reverts if the execution is not performed via delegatecall or the execution
     * context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
     */
    function _checkProxy() internal view virtual {
        if (
            address(this) == __self || // Must be called through delegatecall
            ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
        ) {
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Reverts if the execution is performed via delegatecall.
     * See {notDelegated}.
     */
    function _checkNotDelegated() internal view virtual {
        if (address(this) != __self) {
            // Must not be called through delegatecall
            revert UUPSUnauthorizedCallContext();
        }
    }

    /**
     * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
     * {upgradeToAndCall}.
     *
     * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
     *
     * ```solidity
     * function _authorizeUpgrade(address) internal onlyOwner {}
     * ```
     */
    function _authorizeUpgrade(address newImplementation) internal virtual;

    /**
     * @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
     *
     * As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
     * is expected to be the implementation slot in ERC-1967.
     *
     * Emits an {IERC1967-Upgraded} event.
     */
    function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
        try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
            if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
                revert UUPSUnsupportedProxiableUUID(slot);
            }
            ERC1967Utils.upgradeToAndCall(newImplementation, data);
        } catch {
            // The implementation is not UUPS
            revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
        }
    }
}

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

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

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev There's no code at `target` (it is not a contract).
     */
    error AddressEmptyCode(address target);

    /**
     * @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.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (LowLevelCall.callNoReturn(recipient, amount, "")) {
            // call successful, nothing to do
            return;
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @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 or custom error, it is bubbled
     * up by this function (like regular Solidity function calls). However, if
     * the call reverted with no returned reason, this function reverts with a
     * {Errors.FailedCall} error.
     *
     * 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.
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0);
    }

    /**
     * @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`.
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        if (address(this).balance < value) {
            revert Errors.InsufficientBalance(address(this).balance, value);
        }
        bool success = LowLevelCall.callNoReturn(target, value, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        bool success = LowLevelCall.staticcallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        bool success = LowLevelCall.delegatecallNoReturn(target, data);
        if (success && (LowLevelCall.returnDataSize() > 0 || target.code.length > 0)) {
            return LowLevelCall.returnData();
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (LowLevelCall.returnDataSize() > 0) {
            LowLevelCall.bubbleRevert();
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
     * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
     * of an unsuccessful call.
     *
     * NOTE: This function is DEPRECATED and may be removed in the next major release.
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata
    ) internal view returns (bytes memory) {
        // only check if target is a contract if the call was successful and the return data is empty
        // otherwise we already know that it was a contract
        if (success && (returndata.length > 0 || target.code.length > 0)) {
            return returndata;
        } else if (success) {
            revert AddressEmptyCode(target);
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
     * revert reason or with a default {Errors.FailedCall} error.
     */
    function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else if (returndata.length > 0) {
            LowLevelCall.bubbleRevert(returndata);
        } else {
            revert Errors.FailedCall();
        }
    }
}

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

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

pragma solidity ^0.8.20;

import {Errors} from "./Errors.sol";
import {LowLevelCall} from "./LowLevelCall.sol";

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev There's no code to deploy.
     */
    error Create2EmptyBytecode();

    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
        if (address(this).balance < amount) {
            revert Errors.InsufficientBalance(address(this).balance, amount);
        }
        if (bytecode.length == 0) {
            revert Create2EmptyBytecode();
        }
        assembly ("memory-safe") {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        if (addr == address(0)) {
            if (LowLevelCall.returnDataSize() == 0) {
                revert Errors.FailedDeployment();
            } else {
                LowLevelCall.bubbleRevert();
            }
        }
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
        assembly ("memory-safe") {
            let ptr := mload(0x40) // Get free memory pointer

            // |                     | ↓ ptr ...  ↓ ptr + 0x0B (start) ...  ↓ ptr + 0x20 ...  ↓ ptr + 0x40 ...   |
            // |---------------------|---------------------------------------------------------------------------|
            // | bytecodeHash        |                                                        CCCCCCCCCCCCC...CC |
            // | salt                |                                      BBBBBBBBBBBBB...BB                   |
            // | deployer            | 000000...0000AAAAAAAAAAAAAAAAAAA...AA                                     |
            // | 0xFF                |            FF                                                             |
            // |---------------------|---------------------------------------------------------------------------|
            // | memory              | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
            // | keccak(start, 0x55) |            ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |

            mstore(add(ptr, 0x40), bytecodeHash)
            mstore(add(ptr, 0x20), salt)
            mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
            let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
            mstore8(start, 0xff)
            addr := and(keccak256(start, 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
        }
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Collection of common custom errors used in multiple contracts
 *
 * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
 * It is recommended to avoid relying on the error API for critical functionality.
 *
 * _Available since v5.1._
 */
library Errors {
    /**
     * @dev The ETH balance of the account is not enough to perform the operation.
     */
    error InsufficientBalance(uint256 balance, uint256 needed);

    /**
     * @dev A call to an address target failed. The target may have reverted.
     */
    error FailedCall();

    /**
     * @dev The deployment failed.
     */
    error FailedDeployment();

    /**
     * @dev A necessary precompile is missing.
     */
    error MissingPrecompile(address);
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Library of low level call functions that implement different calling strategies to deal with the return data.
 *
 * WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
 * to use the {Address} library instead.
 */
library LowLevelCall {
    /// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
    function callNoReturn(address target, bytes memory data) internal returns (bool success) {
        return callNoReturn(target, 0, data);
    }

    /// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
    function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function callReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        return callReturn64Bytes(target, 0, data);
    }

    /// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
    function callReturn64Bytes(
        address target,
        uint256 value,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
    function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function staticcallReturn64Bytes(
        address target,
        bytes memory data
    ) internal view returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
    function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
        }
    }

    /// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
    /// in the scratch space of memory. Useful for functions that return a tuple of single-word values.
    ///
    /// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
    /// and this function doesn't zero it out.
    function delegatecallReturn64Bytes(
        address target,
        bytes memory data
    ) internal returns (bool success, bytes32 result1, bytes32 result2) {
        assembly ("memory-safe") {
            success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
            result1 := mload(0x00)
            result2 := mload(0x20)
        }
    }

    /// @dev Returns the size of the return data buffer.
    function returnDataSize() internal pure returns (uint256 size) {
        assembly ("memory-safe") {
            size := returndatasize()
        }
    }

    /// @dev Returns a buffer containing the return data from the last call.
    function returnData() internal pure returns (bytes memory result) {
        assembly ("memory-safe") {
            result := mload(0x40)
            mstore(result, returndatasize())
            returndatacopy(add(result, 0x20), 0x00, returndatasize())
            mstore(0x40, add(result, add(0x20, returndatasize())))
        }
    }

    /// @dev Revert with the return data from the last call.
    function bubbleRevert() internal pure {
        assembly ("memory-safe") {
            let fmp := mload(0x40)
            returndatacopy(fmp, 0x00, returndatasize())
            revert(fmp, returndatasize())
        }
    }

    function bubbleRevert(bytes memory returndata) internal pure {
        assembly ("memory-safe") {
            revert(add(returndata, 0x20), mload(returndata))
        }
    }
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC-1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(newImplementation.code.length > 0);
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * TIP: Consider using this library along with {SlotDerivation}.
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct Int256Slot {
        int256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `Int256Slot` with member `value` located at `slot`.
     */
    function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns a `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns a `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        assembly ("memory-safe") {
            r.slot := store.slot
        }
    }
}

src/Pot.sol

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

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

/// @title Pot
/// @notice Proxy that holds funds and executes sauce bytecode in its own context, while still
///         reaching the swap surface for pool interactions. A Private Pot runs its owner's programs
///         only; a Shared Pot, which has no owner, runs anyone's.
/// @dev A Pot is deployed deterministically by the {Kitchen}, one (or more, via salt) per owner.
///      Execution is split across TWO implementations:
///
///        - the engine — the standalone v12 Huff interpreter, named per {cook} call rather than
///          held. {cook} delegatecalls into it. The PRODUCTION engine is the GATED runtime, which
///          interprets only when `address(this)` is a canonical Pot — so the only way to reach it
///          is through {cook}, which is where the flat execution fee is charged. The engine's gate
///          re-derives this Pot's CREATE2 address by STATICCALLing {gateSalt} on the Pot it is
///          verifying: `address(this)` under {cook}, and `caller()` when the engine is called at its
///          own address — where it never interprets, and only relays an EVAL back to {eval}.
///        - {router} — the {Router} swap surface this Pot was minted with, unless its owner has
///          since named another through {setRouter}. The {fallback} delegatecalls into it. The
///          names are the Kitchen's own, and mean the same thing one level down: the Kitchen's
///          Router is the one its new Pots start on, a Pot's is the one it runs.
///
///      ONE BYTECODE, TWO SETTINGS. Every Pot is this contract, and two immutables set what kind:
///
///        - {owner}: who may {cook}. Zero makes the Pot SHARED: anyone may cook it, and the Kitchen's
///          fee is charged all the same.
///        - `fixedRouter`: where the {fallback} goes. Nonzero FIXES the Router: the fallback runs
///          that address and nothing else, and {setRouter} refuses. Zero keeps it in {PotStorage},
///          where the owner moves it.
///
///      A Shared Pot always has a fixed Router; the constructor refuses one that does not. A program
///      runs with this account's storage, so a Router held there is one every cooked program can
///      rewrite, and every later swap self-call and pool callback would then run that program's
///      choice with this Pot's funds. On a Private Pot every program is one the owner chose, so that
///      is the owner's own risk to take, and storage keeps the Router upgradable. A Pot that runs
///      anyone's programs cannot let any of them choose its Router, so its Router is code. A Private
///      Pot may fix its Router too ({Kitchen.deployPot} with `routerFixed`), for an owner who cooks
///      programs others wrote.
///
///      ANYTHING A SHARED POT HOLDS BETWEEN TRANSACTIONS IS ANYONE'S. Whoever cooks it next can move
///      it, and an allowance left behind can be spent by any contract a later program calls into. A
///      program cooked on a Shared Pot must leave nothing behind. Within one transaction the same
///      goes for its transient storage: a cook earlier in the transaction can leave any transient
///      slot set for a later one, the Router's callback context included, so a program holding
///      funds on a Shared Pot must not hand control to a contract it does not trust.
///
///      SIGNED COOKS. A Private Pot's owner may sign a cook off-chain, as EIP-712 typed data, and
///      anyone may submit it with {cookSigned}: a relayer paying the gas, a solver delivering funds
///      and running the owner's program in the same transaction, a keeper later on. The Pot runs it
///      exactly as it runs the owner's own {cook}, if and only if the owner signed that engine, that
///      program, that value, that fee ceiling, that nonce, that deadline and that submitter, for this
///      Pot on this chain. Each nonce runs once (an unordered bitmap, as Permit2's), and the owner
///      cancels outstanding ones with {invalidateNonces}. A Shared Pot takes none — it has no owner
///      to sign: see {cookSigned}.
///
///      IDENTITY VIA CALLBACK. The Pot takes NO constructor arguments: its owner, salt, whether its
///      Router is fixed, and its starting Router arrive through construction-time callbacks to the
///      {Kitchen} ({IKitchenDeployer}). This is deliberate — with no constructor args the initcode is
///      this contract's creation code and nothing else, so its hash is a single constant the engine
///      gate can embed rather than recompute per Pot. Identity is still bound into the address
///      through the CREATE2 salt ({gateSalt}), which commits to the owner, the user salt and whether
///      the Router is fixed — so a Shared Pot, a Private Pot and a Private Pot with a fixed Router
///      never share an address.
///
///      THE ROUTER IS NOT IDENTITY. The constructor reads it from the Kitchen and keeps it, and
///      neither the call nor the value is part of the creation code or the CREATE2 salt, so the
///      Kitchen owner's `setRouter` leaves {Kitchen.potInitCodeHash}, every Pot address and every
///      engine's gate where they were. It changes what Pots minted after it start with; an existing
///      Pot keeps the Router it has, a Private one until its own owner calls this Pot's {setRouter},
///      a fixed one for good. Neither the Kitchen nor its owner can change a deployed Pot's Router —
///      there is no beacon, and a Pot reads nothing about its Router from the Kitchen after it is
///      constructed.
contract Pot {
    error NotOwner();
    error EmptyProgram();
    error EngineHasNoCode();
    /// @notice {setRouter} named an address with no code. A delegatecall to one succeeds and returns
    ///         nothing, so every swap self-call and pool callback would look like it ran. The
    ///         Kitchen's `setRouter` refuses with the same error.
    error RouterHasNoCode();
    /// @notice The Kitchen had no Router when this Pot was being minted: a fresh proxy before its
    ///         first `setRouter`, or an upgrade that did not pass one.
    error RouterUnset();
    /// @notice {setRouter} on a Pot whose Router is fixed: nothing moves it. Also {cookSigned} on such a
    ///         Pot, every Shared Pot included, which takes no signed cooks.
    error RouterFixed();
    /// @notice The Kitchen asked for a Pot with no owner and a Router in storage: one anyone could
    ///         cook, and so one any program could re-route. No Kitchen implementation can mint it.
    error SharedRouterNotFixed();
    /// @notice {cook} was sent less than the Kitchen's {IKitchenDeployer.executionFee}; or, for
    ///         {cookSigned}, the fee is above the smaller of the Pot's balance and the signed
    ///         `maxExecutionFee`, which is `provided`.
    error FeeNotPaid(uint256 required, uint256 provided);
    /// @notice The Kitchen refused the forwarded fee.
    error FeeTransferFailed();
    /// @notice {eval} was called by something other than the engine this Pot's in-flight {cook}
    ///         delegatecalls, or outside a cook.
    error NotInFlightEngine();
    /// @notice {cookSigned} after the `deadline` its owner signed.
    error Expired();
    /// @notice {cookSigned} from a caller other than the `submitter` its owner signed.
    error WrongSubmitter();
    /// @notice {cookSigned}'s signature is not the owner's over this cook, on this Pot and chain. A
    ///         `msg.value` other than the signed `value` lands here too: the Pot hashes what it was
    ///         sent.
    error BadSignature();
    /// @notice {cookSigned} with a nonce already used, or cancelled through {invalidateNonces}.
    error NonceUsed();

    /// @notice A signed cook ran: its owner's `nonce`, submitted by `submitter`. The owner learns from
    ///         it when, and by whom, each signature was used.
    event SignedCook(uint256 indexed nonce, address indexed submitter);
    /// @notice {invalidateNonces} set `mask` in the bitmap `word`.
    event NoncesInvalidated(uint256 indexed word, uint256 mask);

    /// @notice {fallback} now delegatecalls `router`. Emitted at construction with the Router the Pot
    ///         starts on, and on every {setRouter} — so a Pot's latest one names what it runs, and its
    ///         first names the Router it started on. A fixed Pot emits it once, at construction. The
    ///         Kitchen emits the same event when ITS Router changes; the emitting address tells the
    ///         two apart. A program that writes {PotStorage} directly bypasses it; see there.
    event RouterSet(address indexed router);

    /// @notice The only external address allowed to {cook} or {setRouter} (besides the Pot itself,
    ///         for the VM's self-calls), and the one whose signature a {cookSigned} carries; or zero
    ///         for a Shared Pot, which anyone may cook. Sourced from the Kitchen at construction.
    address public immutable owner;
    /// @notice The caller-chosen user salt this Pot was deployed with. Part of {gateSalt}.
    bytes32 public immutable userSalt;
    /// @notice This Pot's CREATE2 salt, mirroring {Kitchen}'s `_salt`: keccak256(abi.encode(owner,
    ///         userSalt)) for a Pot whose Router is not fixed, and keccak256(abi.encode(owner,
    ///         userSalt, true)) for one whose Router is. The gated engine STATICCALLs this to re-derive
    ///         and verify the Pot address — for the outer cook (`address(this)` is this Pot) and for
    ///         an EVAL frame (where the engine reads it off `caller()`, this Pot). A non-Pot caller
    ///         has no such function, so the engine's gate rejects it.
    /// @dev The fixed flag is in the salt and the Router is not: two Pots that differ only in whether
    ///      their Router is fixed land at different addresses, so minting one never occupies the
    ///      other's, and a Router rollout moves no address. Computed once, by the constructor, from
    ///      the values it also keeps as {owner}, {userSalt} and `fixedRouter`; an immutable rather
    ///      than a hash per call, since the gate asks on every cook and every EVAL.
    bytes32 public immutable gateSalt;
    /// @notice The {Kitchen} that deployed this Pot and receives the execution fee.
    address public immutable kitchen;
    /// @dev The Router, when it is fixed: the Kitchen's at mint, and the only one {fallback} runs.
    ///      Zero when it is not, and {router} is then the one in {PotStorage}. Code, so nothing a
    ///      program does to this account's storage reaches it. Not public: {router} answers which
    ///      Router runs either way, and the fixed flag is in the address ({gateSalt}).
    address private immutable fixedRouter;
    /// @dev This Pot's EIP-712 domain separator, `{ name: "Sauce Pot", version: "1", chainId,
    ///      verifyingContract: this Pot }`, hashed once by the constructor and kept XORed with the
    ///      chain id it was hashed for. {cookSigned} XORs the chain id back in: on this chain that is
    ///      the separator, and on any other — a fork that changed its id — a value no owner signed
    ///      over, so every signature is refused there. One word, where a separator and a chain id
    ///      would be two.
    bytes32 private immutable domainSeparatorByChain;

    /// @dev Transient slot holding the engine of the in-flight {cook}. See {inFlightEngine}.
    bytes32 private constant ENGINE_SLOT = keccak256("V12Pot.engine");

    /// @dev `keccak256("Cook(address engine,bytes program,uint256 value,uint256 maxExecutionFee,uint256
    ///      nonce,uint256 deadline,address submitter)")`, written out because assembly reads it.
    bytes32 private constant COOK_TYPEHASH = 0xee063c16caa92a203b808bd65797df72ea8c821b890805ab457c5fdb28c7fc67;

    /// @notice ERC-7201 namespaced storage for the signed-cook nonces: bit `nonce & 255` of word
    ///         `nonce >> 8` is set once that nonce is used or cancelled. Nothing in the Pot clears one.
    /// @dev Its own namespace, not a field of {PotStorage}, whose whole-word {_storeRouter} would zero
    ///      a field packed beside the Router. A cooked program can write these words, as it can
    ///      {PotStorage}, which is why {cookSigned} is refused where the programs a Pot runs are not
    ///      its owner's own.
    /// @custom:storage-location erc7201:sauce.storage.CookNonces
    struct CookNonces {
        mapping(uint256 word => uint256 bits) bitmap;
    }

    // keccak256(abi.encode(uint256(keccak256("sauce.storage.CookNonces")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant COOK_NONCES_LOCATION = 0x08184ababcb38dd115581f50f6ee2ae87aeba9473b07b25b94798bbfbf936b00;

    /// @notice ERC-7201 namespaced storage for the Pot's one mutable setting.
    /// @dev `router` is written by the constructor and by {setRouter}, and read by every {fallback}
    ///      call, on a Pot whose Router is not fixed. On a fixed Pot nothing writes it and nothing
    ///      reads it.
    ///
    ///      Namespaced, not slot 0, because this account's storage is shared. The engine's SSTORE
    ///      writes whatever key a cooked program supplies, and whatever {router} is executes here too.
    ///      A cooked program CAN write this slot. On a Private Pot whose Router is not fixed, doing so
    ///      moves {fallback} exactly as {setRouter} would, without its code check or its event. That
    ///      is no new power: every program {cook} runs there is one the owner chose, and {cook}
    ///      already hands it this account's storage and funds. On a fixed Pot — every Shared Pot —
    ///      the write changes nothing, since {fallback} never reads the slot. What the namespace buys
    ///      is that a program deriving its keys by hashing, as `docs/runtime/storage.md` requires,
    ///      reaches it only through a keccak preimage. CI keeps `forge inspect Pot storageLayout`
    ///      empty, so the Pot declares nothing at a sequential slot that a program's constant key
    ///      could hit.
    /// @custom:storage-location erc7201:sauce.storage.Pot
    struct PotStorage {
        address router;
    }

    // keccak256(abi.encode(uint256(keccak256("sauce.storage.Pot")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant POT_STORAGE_LOCATION = 0x5dcf1afeb37fe4804d4db2aa42e07f76a76c328b0f50beb6b52ea4daec1f5f00;

    function _potStorage() private pure returns (PotStorage storage $) {
        assembly {
            $.slot := POT_STORAGE_LOCATION
        }
    }

    /// @dev A whole-word store. The typed `_potStorage().router = ...` would first SLOAD the slot to
    ///      preserve its other twelve bytes, and nothing else lives there — at construction that read
    ///      alone is a cold 2,100 gas on every Pot.
    ///
    ///      Which makes the slot the Router's alone, and that is a constraint on {PotStorage}, not
    ///      a detail of this function. A field of twelve bytes or fewer added to the struct packs in
    ///      beside `router` and is zeroed here by every `setRouter` and every Pot constructor —
    ///      silently, with no warning and nothing to fail. A new field needs its own ERC-7201
    ///      namespace, or this store has to become the typed one and pay the SLOAD.
    function _storeRouter(
        address newRouter
    ) private {
        assembly {
            sstore(POT_STORAGE_LOCATION, newRouter)
        }
    }

    /// @dev Everything arrives from the deployer (`msg.sender`, the Kitchen proxy). The starting
    ///      Router is its {IKitchenDeployer.router} at this moment, not a constructor argument, which
    ///      is what keeps it out of the initcode and so out of every Pot address. A fixed Pot keeps it
    ///      as `fixedRouter`; any other writes it to {PotStorage}.
    ///
    ///      Refused when zero, so no Pot ever starts on no Router at all, and so a fixed Pot's
    ///      `fixedRouter` is never zero, which is what lets zero mean "not fixed". Zero is the one bad
    ///      value that can reach here: the Kitchen's `setRouter` is the only writer of its Router and
    ///      refuses an address without code, and deployed code cannot disappear. What zero means is
    ///      unset — a fresh proxy before its first `setRouter`, or an upgrade that did not pass one.
    ///      A zero test rather than a code check, because the check's own cold account access would
    ///      cost 2.6k on every Pot to re-prove what `setRouter` already proved.
    ///
    ///      Refuses an owner of zero with a Router that is not fixed. {Kitchen} never asks for one,
    ///      and this check is what makes that true of every implementation the Kitchen proxy could
    ///      ever run: the engine gate pins this bytecode, so a Pot anyone can cook has a fixed Router
    ///      whoever minted it.
    constructor() {
        IKitchenDeployer deployer = IKitchenDeployer(msg.sender);
        (address o, bytes32 s, bool routerFixed) = deployer.potParameters();
        address startingRouter = deployer.router();
        if (startingRouter == address(0)) {
            revert RouterUnset();
        }
        if (o == address(0) && !routerFixed) {
            revert SharedRouterNotFixed();
        }
        owner = o;
        userSalt = s;
        gateSalt = routerFixed ? keccak256(abi.encode(o, s, true)) : keccak256(abi.encode(o, s));
        kitchen = msg.sender;
        fixedRouter = routerFixed ? startingRouter : address(0);
        if (!routerFixed) {
            _storeRouter(startingRouter);
        }
        emit RouterSet(startingRouter);
        domainSeparatorByChain = keccak256(
            abi.encode(
                keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
                keccak256("Sauce Pot"),
                keccak256("1"),
                block.chainid,
                address(this)
            )
        ) ^ bytes32(block.chainid);
    }

    /// @notice Execute a sauce program in this Pot's context, charging the flat execution fee. The
    ///         owner or the Pot itself only, unless the Pot is Shared: then anyone.
    /// @dev The fee is in the DOOR, not the engine: it is charged here regardless of which `engine`
    ///      the caller passes, so a fee-stripped forked engine cannot dodge it. The gated production
    ///      engine additionally refuses to run outside a Pot, so `cook` is the only path to it.
    ///
    ///      On a Shared Pot `engine` is the caller's choice like everything else, so anyone may have
    ///      this Pot delegatecall any code. That reaches what any cooked program reaches — this
    ///      account's storage, transient storage and funds — and not the Pot's code: its owner, its
    ///      Router and its Kitchen are immutables.
    ///
    ///      CALLERS MUST USE A RAW CALL AND NOT ABI-DECODE THE RESULT — the runtime's output is
    ///      bubbled verbatim with no ABI wrapper (see the prior Pot revision's note; unchanged).
    function cook(
        address engine,
        bytes calldata program
    ) external payable returns (bytes memory) {
        address o = owner;
        if (msg.sender != o && msg.sender != address(this) && o != address(0)) {
            _refuse(NotOwner.selector);
        }
        return _answer(_cook(engine, program, msg.value));
    }

    /// @notice Run a cook this Pot's owner signed, for whoever submits it. The program runs exactly as
    ///         under the owner's own {cook}: as this Pot, on `engine`, with `msg.sender` the submitter
    ///         and `msg.value` the signed value, its output answered raw.
    /// @dev The owner signs, under the EIP-712 domain `{ name: "Sauce Pot", version: "1", chainId,
    ///      verifyingContract: this Pot }`:
    ///
    ///        Cook(address engine, bytes program, uint256 value, uint256 maxExecutionFee,
    ///             uint256 nonce, uint256 deadline, address submitter)
    ///
    ///      - `engine`: what runs with this Pot's whole authority, so a submitter cannot name another.
    ///      - `program`: the bytecode with its entry arguments appended, exactly what the engine runs.
    ///      - `value`: what `msg.value` must be. There is no parameter: the Pot hashes what it was sent.
    ///      - `maxExecutionFee`: the most of the Kitchen's fee this Pot pays for it. The fee is the
    ///        Kitchen owner's to change, and here it comes out of the Pot's balance (which includes
    ///        `msg.value`), so the owner caps it. A fee above the smaller of the two refuses with
    ///        {FeeNotPaid}.
    ///      - `nonce`: each runs once, in any order; bit `nonce & 255` of word `nonce >> 8`.
    ///      - `deadline`: the last second it runs, inclusive.
    ///      - `submitter`: the only caller that may submit it, or zero for anyone.
    ///
    ///      The signature is the owner's 65-byte `r ‖ s ‖ v`, with `s` in the lower half of the curve
    ///      order and `v` 27 or 28; when that does not recover the owner and the owner has code (a
    ///      contract wallet, or an EIP-7702 account whose delegate answers), the owner's ERC-1271
    ///      `isValidSignature(digest, signature)`, of any length. ecrecover comes first so an EIP-7702
    ///      account's own key always works, whatever its delegate implements.
    ///
    ///      The nonce is spent, and {SignedCook} emitted, before the engine runs: the program, or
    ///      anything it calls, cannot submit the same signature again within it. Everything is all
    ///      or nothing — a refusal or a failed program reverts the whole call, the nonce stays unused
    ///      and no fee is paid, and the same signature may be submitted again until its deadline.
    ///
    ///      REFUSED ON A SHARED POT ({NotOwner}): there is no owner to have signed, and anyone may
    ///      {cook} it directly. That is also the condition the signature check itself rests on — with
    ///      no owner, a failed `ecrecover` leaves zero where the recovered address is compared, so
    ///      every malformed signature would verify. The gate states it rather than inheriting it.
    ///
    ///      A PRIVATE POT TAKES THEM WHETHER OR NOT ITS ROUTER IS FIXED. The nonce bitmap lives in
    ///      this account's storage and a cooked program can write any of it, so a program the owner
    ///      cooks can clear a spent bit and leave an unexpired signature — public in the calldata
    ///      that spent it — to run again for whoever resubmits it. That exposure is the owner's own,
    ///      as {setRouter}'s is, and an owner who signs nothing carries none of it. Fixing the Router
    ///      answers a different question, and keying this on it would be permanent: `routerFixed` is
    ///      in the CREATE2 salt, so there is no re-minting at the same address without it.
    ///
    ///      As with {cook}, CALLERS MUST USE A RAW CALL AND NOT ABI-DECODE THE RESULT.
    function cookSigned(
        address engine,
        bytes calldata program,
        uint256 maxExecutionFee,
        uint256 nonce,
        uint256 deadline,
        address submitter,
        bytes calldata signature
    ) external payable returns (bytes memory) {
        if (!_hasOwner()) {
            _refuse(NotOwner.selector);
        }
        if (block.timestamp > deadline) {
            _refuse(Expired.selector);
        }
        if (submitter != address(0) && submitter != msg.sender) {
            _refuse(WrongSubmitter.selector);
        }
        // A XOR, not a branch: on a chain other than the one it was hashed for, this is a domain no
        // owner signed, and the signature check below refuses.
        bytes32 domain = domainSeparatorByChain ^ bytes32(block.chainid);
        bytes32 digest;
        assembly {
            let m := mload(0x40)
            calldatacopy(m, program.offset, program.length)
            let programHash := keccak256(m, program.length)
            mstore(m, COOK_TYPEHASH)
            mstore(add(m, 0x20), engine)
            mstore(add(m, 0x40), programHash)
            mstore(add(m, 0x60), callvalue())
            mstore(add(m, 0x80), maxExecutionFee)
            mstore(add(m, 0xa0), nonce)
            mstore(add(m, 0xc0), deadline)
            mstore(add(m, 0xe0), submitter)
            let structHash := keccak256(m, 0x100)
            mstore(m, 0x1901)
            mstore(add(m, 0x20), domain)
            mstore(add(m, 0x40), structHash)
            digest := keccak256(add(m, 0x1e), 0x42)
        }
        if (!_signedByOwner(digest, signature)) {
            _refuse(BadSignature.selector);
        }
        uint256 bit = 1 << (nonce & 255);
        if (_spendNonces(nonce >> 8, bit) & bit != 0) {
            _refuse(NonceUsed.selector);
        }
        emit SignedCook(nonce, msg.sender);

        uint256 available = address(this).balance;
        return _answer(_cook(engine, program, available < maxExecutionFee ? available : maxExecutionFee));
    }

    /// @notice Spend every nonce `mask` names in bitmap `word`, used or not, so no signature for one
    ///         of them runs. The owner, or the Pot itself — so a cook, a signed one included, can
    ///         cancel others. Bits are only ever set. Refused on a Shared Pot, which spends no nonce.
    /// @dev A word holds nonces `word << 8` to `(word << 8) | 255`. Read one with `eth_getStorageAt`
    ///      at `keccak256(abi.encode(word, COOK_NONCES_LOCATION))`.
    function invalidateNonces(
        uint256 word,
        uint256 mask
    ) external {
        _requireOwnerOrSelf();
        _spendNonces(word, mask);
        emit NoncesInvalidated(word, mask);
    }

    /// @notice Point {fallback} at `newRouter`. The owner, or the Pot itself, only, and never on a
    ///         Pot whose Router is fixed.
    /// @dev {cook}'s gate on a Private Pot, deliberately the same one. The owner can already make this
    ///      Pot delegatecall any engine with its storage and funds, so choosing what its fallback
    ///      delegatecalls grants nothing new — which is also why it may be any contract, not only a
    ///      {Router}. `address(this)` passes for the reason it passes {cook}: only code executing AS
    ///      this Pot — a program the owner cooked, or the Router the owner chose — can call with that
    ///      sender, and such code can already write {PotStorage} directly. A pool or token this Pot
    ///      calls out to calls back with its own address as `msg.sender`, so none of them passes.
    ///
    ///      That argument, like {cook}'s, holds only while no Router lets an outside caller make this
    ///      Pot call ITSELF with a selector of the caller's choosing. The generation-4 {Router} has
    ///      no such path. An owner choosing any other contract must hold it to the same rule: one
    ///      that forwards arbitrary self-calls hands {cook} and this function to whoever calls it.
    ///
    ///      A fixed Pot refuses everyone ({RouterFixed}), itself included, which is what keeps a
    ///      Shared Pot's Router out of reach of the programs anyone cooks on it.
    ///
    ///      Refuses an address with no code, `address(0)` included. There is no sentinel for "back to
    ///      the default": the way back is to name the Router this Pot started on, which its
    ///      construction-time {RouterSet} records.
    function setRouter(
        address newRouter
    ) external {
        if (_isRouterFixed()) {
            _refuse(RouterFixed.selector);
        }
        _requireOwnerOrSelf();
        if (newRouter.code.length == 0) {
            _refuse(RouterHasNoCode.selector);
        }
        _storeRouter(newRouter);
        emit RouterSet(newRouter);
    }

    /// @notice Where {fallback} delegatecalls: the Router this Pot was minted with, unless its owner
    ///         has since named another through {setRouter}. A fixed Pot's never moves.
    function router() external view returns (address) {
        address fixed_ = fixedRouter;
        return fixed_ != address(0) ? fixed_ : _potStorage().router;
    }

    /// @notice Run `program` AS this Pot, read-only: how an EVAL in a program this Pot is cooking
    ///         gets back in.
    /// @dev EVAL STATICCALLs the engine at its own address, where the engine never interprets. It
    ///      relays the program to its caller — this Pot — and the program runs here, by DELEGATECALL
    ///      into that same engine:
    ///
    ///        program, AS this Pot (cook's DELEGATECALL)
    ///          EVAL: STATICCALL engine(program)              the relay, at the engine's address
    ///                  STATICCALL this.eval(program)         msg.sender = the engine
    ///                    DELEGATECALL engine(program)        the inner program, AS this Pot
    ///
    ///      So the inner program reads this Pot's storage, balance and address, and changes none of
    ///      them: every frame below the first STATICCALL is static. Its `msg.sender` is the engine.
    ///
    ///      Only the engine {cook} is delegatecalling may call this: no other account, contract or
    ///      engine, not this Pot itself, and nothing outside a cook, where {inFlightEngine} is zero.
    ///      That engine reaches here only through its relay, which STATICCALLs: its interpreter runs
    ///      only as a Pot, so no program can make a call whose sender is the engine. (An engine the
    ///      owner names that does otherwise already runs as this Pot, with everything {cook} hands
    ///      it, so it gains nothing here.)
    ///
    ///      No fee is charged — the cook that reached here paid it — and nothing is written: the
    ///      frame is static. As with {cook}, the output and revert data are bubbled verbatim, with no
    ///      ABI wrapper, and an empty program is not refused: the engine answers it as it answers any
    ///      program that stops at once.
    function eval(
        bytes calldata program
    ) external returns (bytes memory) {
        if (msg.sender != _inFlightEngine()) {
            _refuse(NotInFlightEngine.selector);
        }
        assembly {
            let len := program.length
            calldatacopy(0, program.offset, len)
            let ok := delegatecall(gas(), caller(), 0, len, 0, 0)
            returndatacopy(0, 0, returndatasize())

            switch ok
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }

    /// @notice The engine the in-flight {cook} is delegatecalling, or the zero address outside one. A
    ///         {cookSigned} arms it the same way.
    /// @dev Read by the {Router} when it arms a flash-callback continuation, and by {eval}, which
    ///      accepts no other caller.
    function inFlightEngine() external view returns (address) {
        return _inFlightEngine();
    }

    /// @notice Accept plain ETH transfers (e.g. WETH unwraps, native swap proceeds).
    receive() external payable { }

    /// @notice Pool swap callbacks and the sauce VM's swap self-calls land here.
    /// @dev Open forwarder to {router}; the Router applies its own onlySelf and per-pool callback
    ///      guards. The self-call fee is NOT charged here — only {cook} charges, so the VM's own swap
    ///      self-calls (which land in this fallback) run within the one paid cook.
    fallback() external payable {
        _delegateToRouter();
    }

    /// @dev The engine slot {cook} arms, read raw.
    function _inFlightEngine() private view returns (address armed) {
        bytes32 slot = ENGINE_SLOT;
        assembly {
            armed := tload(slot)
        }
    }

    /// @dev Whether anyone could have authorised anything here. Zero is SHARED: anyone may {cook} it,
    ///      so no signature stands behind it — and {cookSigned}'s check cannot tell on its own, since a
    ///      failed `ecrecover` writes nothing and leaves the zero the recovered address is compared to.
    function _hasOwner() private view returns (bool) {
        return owner != address(0);
    }

    /// @dev Whether {fallback} reads its Router out of code rather than storage, which is what makes
    ///      {setRouter} refuse. A SEPARATE QUESTION from {_hasOwner}: a Private Pot may be either, and
    ///      a Shared one is always fixed ({SharedRouterNotFixed}). Nothing may read one for the other.
    function _isRouterFixed() private view returns (bool) {
        return fixedRouter != address(0);
    }

    /// @dev {setRouter}'s gate, and {cook}'s on a Private Pot. There must BE an owner: `msg.sender` is
    ///      never `address(0)`, so on a Shared Pot the later tests already refuse every caller but the
    ///      Pot itself — which any cooked program reaches with a call to its own address. Without
    ///      {_hasOwner} such a program could {invalidateNonces} on a Pot that spends none, emitting a
    ///      cancellation no owner authorised. {setRouter}'s path is unchanged: a Shared Pot's Router is
    ///      fixed by construction, so {RouterFixed} refuses there before this runs.
    ///
    ///      The call costs 32 bytes of runtime — a second call site is one too many for the optimizer
    ///      to inline it — and that is paid deliberately. This contract shipped a predicate answering
    ///      two questions; two spellings of ONE predicate, in the two gates that ask it, is the same
    ///      hazard written smaller.
    function _requireOwnerOrSelf() private view {
        if (!_hasOwner() || (msg.sender != owner && msg.sender != address(this))) {
            _refuse(NotOwner.selector);
        }
    }

    /// @dev The owner's signature over `digest`: ecrecover, then ERC-1271 when the owner has code
    ///      (see {cookSigned}). Never asked on a Shared Pot, so the owner is never zero, and a
    ///      signature that recovers no key (zero) cannot match it.
    ///
    ///      The ERC-1271 answer must be the magic value in a whole word, its other 28 bytes zero, as
    ///      OpenZeppelin's `SignatureChecker` requires: an owner whose fallback echoes its calldata
    ///      returns the selector followed by the digest, and must not pass. Not that library itself,
    ///      whose pinned version takes one path by the owner's code size and would send an EIP-7702
    ///      account only to its delegate.
    function _signedByOwner(
        bytes32 digest,
        bytes calldata signature
    ) private view returns (bool signed) {
        address o = owner;
        assembly {
            let m := mload(0x40)
            if eq(signature.length, 65) {
                let s := calldataload(add(signature.offset, 0x20))
                let v := byte(0, calldataload(add(signature.offset, 0x40)))
                if and(
                    iszero(gt(s, 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0)),
                    or(eq(v, 27), eq(v, 28))
                ) {
                    mstore(m, digest)
                    mstore(add(m, 0x20), v)
                    mstore(add(m, 0x40), calldataload(signature.offset))
                    mstore(add(m, 0x60), s)
                    mstore(0, 0)
                    pop(staticcall(gas(), 1, m, 0x80, 0, 0x20))
                    signed := eq(mload(0), o)
                }
            }
            if and(iszero(signed), iszero(iszero(extcodesize(o)))) {
                // isValidSignature(bytes32,bytes): the selector in the last four bytes of the first
                // word, so the call starts 28 bytes in; the signature zero-padded to a whole word.
                let len := signature.length
                mstore(m, 0x1626ba7e)
                mstore(add(m, 0x20), digest)
                mstore(add(m, 0x40), 0x40)
                mstore(add(m, 0x60), len)
                calldatacopy(add(m, 0x80), signature.offset, len)
                mstore(add(add(m, 0x80), len), 0)
                mstore(0, 0)
                let ok := staticcall(gas(), o, add(m, 0x1c), add(0x64, and(add(len, 31), not(31))), 0, 0x20)
                let answer := mload(0)
                signed := and(
                    and(ok, gt(returndatasize(), 0x1f)),
                    and(eq(shr(224, answer), 0x1626ba7e), iszero(shl(32, answer)))
                )
            }
        }
    }

    /// @dev Set `mask` in nonce bitmap `word` ({CookNonces}), answering the word as it was before.
    function _spendNonces(
        uint256 word,
        uint256 mask
    ) private returns (uint256 before) {
        assembly {
            mstore(0, word)
            mstore(0x20, COOK_NONCES_LOCATION)
            let slot := keccak256(0, 0x40)
            before := sload(slot)
            sstore(slot, or(before, mask))
        }
    }

    /// @dev Revert with `error`'s selector and nothing else: the same bytes as `revert Error()`, which
    ///      the compiler writes as a 32-byte constant per site, where this takes four. Every Pot ever
    ///      minted pays 200 gas a byte for its runtime, so the difference is paid once per Pot.
    function _refuse(
        bytes4 error
    ) private pure {
        assembly {
            mstore(0, shr(224, error))
            revert(0x1c, 4)
        }
    }

    /// @dev Collect the Kitchen's flat execution fee out of `paid` and remit it. A zero fee is a no-op
    ///      (no value required, no transfer), so an un-priced Kitchen cooks for free. `paid` is
    ///      `msg.value` for {cook}, and for {cookSigned} the smaller of the Pot's balance and its
    ///      signed `maxExecutionFee`.
    ///
    ///      In assembly for size, behaving as the Solidity it replaced did: a Kitchen whose
    ///      `executionFee()` reverts has its revert bubbled, one that answers less than a word
    ///      reverts with nothing, and the remittance forwards all gas. Unlike that Solidity it copies
    ///      no return data from the remittance, which nothing read.
    function _chargeFee(
        uint256 paid
    ) private {
        address k = kitchen;
        uint256 feeSelector = uint32(IKitchenDeployer.executionFee.selector);
        uint256 notPaid = uint32(FeeNotPaid.selector);
        uint256 transferFailed = uint32(FeeTransferFailed.selector);
        assembly {
            mstore(0, feeSelector)
            if iszero(staticcall(gas(), k, 0x1c, 4, 0, 0x20)) {
                returndatacopy(0, 0, returndatasize())
                revert(0, returndatasize())
            }
            if lt(returndatasize(), 0x20) { revert(0, 0) }
            let fee := mload(0)
            if fee {
                if lt(paid, fee) {
                    mstore(0, notPaid)
                    mstore(0x20, fee)
                    mstore(0x40, paid)
                    revert(0x1c, 0x44)
                }
                if iszero(call(gas(), k, fee, 0, 0, 0, 0)) {
                    mstore(0, transferFailed)
                    revert(0x1c, 4)
                }
            }
        }
    }

    /// @dev The door's tail, shared by {cook} and {cookSigned} once each has decided the caller may
    ///      cook: refuse an engine with no code and an empty program, charge the fee out of `paid`,
    ///      then delegatecall the runtime with `program` as the entire calldata, restoring the
    ///      previous engine slot around the call so a nested cook does not leave its engine armed for
    ///      the outer one. Answers whether the runtime succeeded, its output left as the return data
    ///      for {_answer}.
    ///
    ///      Returns rather than halting, unlike {_answer}: the compiler copies a function that always
    ///      halts into each of its callers, and this is the bulk of the door.
    function _cook(
        address impl,
        bytes calldata program,
        uint256 paid
    ) private returns (bool ok) {
        if (impl.code.length == 0) {
            _refuse(EngineHasNoCode.selector);
        }
        if (program.length == 0) {
            _refuse(EmptyProgram.selector);
        }
        _chargeFee(paid);

        bytes32 slot = ENGINE_SLOT;
        assembly {
            let previous := tload(slot)
            tstore(slot, impl)

            let len := program.length
            calldatacopy(0, program.offset, len)
            ok := delegatecall(gas(), impl, 0, len, 0, 0)

            tstore(slot, previous)
        }
    }

    /// @dev Bubble the runtime's raw return/revert data verbatim, as {_cook} left it: nothing runs a
    ///      call between the two.
    function _answer(
        bool ok
    ) private pure returns (bytes memory) {
        assembly {
            returndatacopy(0, 0, returndatasize())
            switch ok
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }

    /// @dev Forward the full calldata to {router} via delegatecall and bubble its raw return/revert
    ///      data verbatim. A fixed Pot takes `fixedRouter` and never reads storage; any other reads
    ///      the slot raw rather than through {router}: DELEGATECALL takes the low 160 bits of its
    ///      address operand, which is exactly what the getter's masked read reports, so the mask
    ///      would only cost gas on every call.
    function _delegateToRouter() private {
        address fixed_ = fixedRouter;
        assembly {
            let impl := fixed_
            if iszero(impl) { impl := sload(POT_STORAGE_LOCATION) }
            calldatacopy(0, 0, calldatasize())
            let ok := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            switch ok
            case 0 { revert(0, returndatasize()) }
            default { return(0, returndatasize()) }
        }
    }
}

src/interfaces/IKitchenDeployer.sol

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

/// @title IKitchenDeployer
/// @notice The construction-time callbacks a {Pot} uses to fetch its identity and starting
///         implementation from the {Kitchen}.
/// @dev Transient storage is per-account, so a Pot cannot read a slot the Kitchen wrote in the
///      Kitchen's own namespace. Instead the Pot's constructor calls back into its deployer
///      (`msg.sender`) for the parameters the Kitchen stashed transiently just before `new Pot`.
///      This is the Uniswap V3 pool-deployer pattern, and it is what keeps the Pot's initcode free
///      of constructor args — so every Pot shares ONE initcode hash and the engine can hold it as a
///      single constant.
interface IKitchenDeployer {
    /// @notice The parameters for the Pot currently being constructed.
    /// @return owner The Pot's owner (the only external address that may {Pot.cook}), or zero for a
    ///         Shared Pot, which anyone may cook.
    /// @return salt The caller-chosen user salt this Pot was deployed with.
    /// @return routerFixed Whether the Pot keeps {router} as an immutable for good, rather than in
    ///         storage where its owner can move it. Always true for a Shared Pot.
    function potParameters() external view returns (address owner, bytes32 salt, bool routerFixed);

    /// @notice The {Router} a newly minted Pot starts with as its own {Pot.router}. Read once, in
    ///         the Pot's constructor: a Pot already deployed does not follow a later change. The
    ///         Pot refuses to be minted while it is unset.
    function router() external view returns (address);

    /// @notice The flat fee, in wei, that {Pot.cook} must collect and remit to the Kitchen.
    function executionFee() external view returns (uint256);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 1000,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "foundry-huff-neo/=lib/foundry-huff-neo/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.