Skip to content
Verified contractPartialMIT

TacitEvmPoolRouter

Address0x0000006c96afa6f1cd4df8fe19bc0d8b6a6cd7b5
Balance

0 ETH

 

Transactions

98

 

Compiler

solc 0.8.36

 

Same code

6 more contracts

 

Details

Compiler
solc 0.8.36+commit.8a079791
Language
solidity
Optimization
Yes, 1 runs
EVM version
prague
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,069,246
Creation transaction
0xbe8a25820c…65e2e83c93

src/TacitEvmPoolRouter.sol

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

import {LibClone} from "solady/utils/LibClone.sol";
import {ReentrancyGuardTransient} from "solady/utils/ReentrancyGuardTransient.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {IPermit2, IERC2612, IERC20Allowance} from "./ConfidentialRouter.sol";

interface ITacitEvmPool {
    function ASSET() external view returns (address);
    function transact(
        uint256[2] calldata pA,
        uint256[2][2] calldata pB,
        uint256[2] calldata pC,
        uint256[11] calldata publicInputs,
        address recipient,
        int256 extAmount,
        address relayer,
        uint256 fee,
        bytes calldata memo0,
        bytes calldata memo1
    ) external payable;
}

/// Poseidon over BN254 with four inputs (circomlib parameters): the pool's note-leaf hash.
interface IPoseidonT5 {
    function hash(uint256[4] memory inputs) external pure returns (uint256);
}

/// The two ConfidentialPool calls a wrap box needs.
interface IConfidentialPoolWrap {
    function wrap(bytes32 assetId, uint256 amount, bytes32 commit) external payable;
    function assets(bytes32 assetId)
        external
        view
        returns (bool registered, address underlying, uint256 unitScale, bytes32 crossChainLink, bool poolMinted, uint8 decimals);
}

/// @title TacitEvmPoolRouter
/// @notice Periphery for one TacitEvmPool, and its bridge to and from the confidential pool (V1).
///
///   1. DEPOSIT (depositWith*): a signature approval (EIP-2612 / Permit2) instead of a separate approve tx.
///   2. ZAPS (zap*): swap ETH or any token into the pool's asset through zRouter and deposit it, in one tx.
///   3. DEPOSIT BOXES (depositBoxOf / completeDeposit / reclaimDeposit): a counterfactual address per deposit intent.
///      Anything can pay it (a V1 withdrawal or exit recipe, an exchange, a bridge); later anyone completes the
///      deposit with a proof against the pool's root at that moment, so a source that settles minutes later needs
///      no proof of its own. The intent fixes the amount, both output leaves and both memos, so the completer can
///      only deliver the notes the owner chose; it is paid the pool's relayer fee, amount − Σ output values.
///   4. WRAP BOXES (wrapBoxOf / completeWrap / reclaimWrap): the same for a V1 note. Anyone completes
///      `wrap(assetId, amount, commit)` on V1; `tip` goes to `tipTo`, or to the completer when `tipTo` is zero.
///   5. POOL → V1 (withdrawToV1): withdraw from this pool into a wrap box and complete it, in one tx.
///   6. RECEIVE BOXES (receiveBoxOf / sweepReceive): a standing address for one owner's note key `npk`, paid any number
///      of times by anyone. Anyone sweeps its balance into the pool as one note the router computes itself,
///      leaf = Poseidon(asset, amount − fee, npk, rho) with rho fixed by the box and a per-box counter, so a sweeper
///      can only credit `npk` and keeps at most `feeBps`. On an ETH pool the box has code only within a sweep, so the
///      address takes plain transfers. The owner recovers every note from its keys and the Received events.
///   7. WITHDRAW AND CALL (callEscrowOf / withdrawAndCall / executeCall / refundCall): a withdrawal to a
///      counterfactual escrow keyed by a `CallIntent` (calls to run with the funds, outputs and their floors, a
///      refund address, a deadline). The proof binds the escrow, so a relayer can change neither the calls nor where
///      their outputs go. `withdrawAndCall` withdraws and runs it atomically.
///   8. FUNDING WITH A CALL (fundDeposit / fundReceive): for contracts and bridge messages that deliver funds by
///      calling a contract: pay a deposit box (publishing the keeper hint) or a receive box, from msg.value or an
///      approved token.
///
/// On Ethereum mainnet a withdrawal can also name a ConfidentialRouter exit-recipe escrow, run by that router's
/// permissionless `activateExit`.
///
/// Trust model: tokens pass through the router only within a call, and each leg's leftover goes back to the caller;
/// a stray balance is taken by the next caller, so never leave value here. The pool, zRouter, Permit2 and V1 are
/// immutable. A box releases only what was paid to it, and only to its intent's destination (the pool deposit, the V1
/// wrap, the call intent's calls, outputs and refund) or, after its deadline, any token to its `refund`. A tampered
/// intent maps to a different, empty box. A receive box has no refund: it releases only the pool asset, only into a
/// note for its `npk`; anything else sent to it stays there. Every entrypoint is nonReentrant.
contract TacitEvmPoolRouter is ReentrancyGuardTransient {
    ITacitEvmPool public immutable POOL;
    /// @notice The pool's asset; address(0) is native ETH.
    address public immutable ASSET;
    /// @notice The swap aggregator for zaps; address(0) disables them.
    address public immutable ZROUTER;
    /// @notice address(0) disables Permit2 flows.
    IPermit2 public immutable PERMIT2;
    /// @notice The confidential pool wrap boxes deposit into; address(0) disables them.
    IConfidentialPoolWrap public immutable V1;
    /// @notice The TacitBox implementation every box and escrow clones.
    address public immutable boxImpl;
    /// @notice PoseidonT5 for receive-box leaves; address(0) disables receive boxes.
    IPoseidonT5 public immutable POSEIDON4;
    uint256 internal immutable ASSET_FIELD; // the pool's `asset` public input

    bytes32 internal constant DEPOSIT_TAG = keccak256("tacit-evm-pool-deposit-box-v1");
    bytes32 internal constant WRAP_TAG = keccak256("tacit-evm-pool-wrap-box-v1");
    bytes32 internal constant RECEIVE_TAG = keccak256("tacit-evm-pool-receive-box-v1");
    bytes32 internal constant CALL_TAG = keccak256("tacit-evm-pool-call-escrow-v1");
    uint256 internal constant P = 21888242871839275222246405745257275088548364400416034343698204186575808495617;

    /// @notice Sweeps so far per receive box; the next sweep's rho is derived from it.
    mapping(address box => uint256) public receiveCount;

    /// @notice The arguments of one TacitEvmPool.transact(), passed through verbatim.
    struct Tx {
        uint256[2] pA;
        uint256[2][2] pB;
        uint256[2] pC;
        uint256[11] publicInputs;
        address recipient;
        int256 extAmount;
        address relayer;
        uint256 fee;
        bytes memo0;
        bytes memo1;
    }

    /// @notice A pool deposit a box completes. The leaves fix the notes and their values; the completer's fee is
    ///         whatever `amount` exceeds their sum.
    struct DepositIntent {
        uint256 amount;
        uint256 outLeaf0;
        uint256 outLeaf1;
        bytes32 memo0Hash;
        bytes32 memo1Hash;
        address refund;
        uint64 deadline; // reclaim opens after this; completion stays open while the box holds `amount`
        uint256 nonce;
    }

    /// @notice A V1 wrap a box completes: `wrap(assetId, amount, commit)` on V1, and `tip` of the same token to
    ///         `tipTo`, or to whichever completer lands first when `tipTo` is zero.
    struct WrapIntent {
        bytes32 assetId;
        uint256 amount;
        uint256 tip;
        address tipTo;
        bytes32 commit;
        address refund;
        uint64 deadline;
        uint256 nonce;
    }

    /// @notice One step of a call escrow: if `token` and `amount` are set, first transfer (`push`) or approve that
    ///         much of `token` to `target`, then call `target` with `value` wei and `data`. An approval is reset to 0
    ///         after the call.
    struct Call {
        address target;
        uint256 value;
        address token;
        uint256 amount;
        bool push;
        bytes data;
    }

    /// @notice What a withdrawal to `callEscrowOf(intent)` does. The escrow runs `calls` in order, then sends its
    ///         whole balance of each `outTokens[i]` (address(0) = ETH), at least `minOuts[i]`, to `to`, and what is
    ///         left of the pool asset to `refund`. Until `deadline` anyone can run it; after, anyone can return its
    ///         funds to `refund`.
    struct CallIntent {
        Call[] calls;
        address[] outTokens;
        uint256[] minOuts;
        address to;
        address refund;
        uint64 deadline;
        uint256 nonce;
    }

    error BadTarget();
    error BadIntent();
    error BadPermit2();
    error AmountTooLarge();
    error ShortSwapOutput();
    error ZRouterCallFailed();
    error NotExpired();
    error NothingToReclaim();
    error Expired();
    error EscrowEmpty();

    event DepositBoxCompleted(address indexed box, address indexed completer);
    event CallExecuted(address indexed escrow, address indexed caller);
    /// @notice A deposit box paid through `fundDeposit`: its intent and the hint a keeper proves it from.
    event DepositFunded(address indexed box, DepositIntent intent, bytes hint);
    /// @notice A receive box paid through `fundReceive`.
    event ReceiveFunded(address indexed box, uint256 npk, uint16 feeBps, uint256 amount);
    event WrapBoxCompleted(address indexed box, address indexed completer);
    /// @notice A box's or escrow's balance of one token returned to its refund address after the deadline.
    event BoxReclaimed(address indexed box, address indexed refund, uint256 amount);
    /// @notice Sweep `n` of a receive box: the note (value, rho) at leaf `index`, and the sweeper's fee.
    event Received(address indexed box, uint256 indexed n, uint256 index, uint256 value, uint256 rho, uint256 fee);

    constructor(address pool_, address zRouter_, address permit2_, address v1_, address poseidon4_) {
        if (pool_ == address(0) || pool_.code.length == 0) revert BadTarget();
        if (zRouter_ != address(0) && zRouter_.code.length == 0) revert BadTarget();
        if (permit2_ != address(0) && permit2_.code.length == 0) revert BadTarget();
        if (v1_ != address(0) && v1_.code.length == 0) revert BadTarget();
        if (poseidon4_ != address(0) && poseidon4_.code.length == 0) revert BadTarget();
        POOL = ITacitEvmPool(pool_);
        ASSET = ITacitEvmPool(pool_).ASSET();
        POSEIDON4 = IPoseidonT5(poseidon4_);
        ASSET_FIELD = uint256(keccak256(abi.encode(block.chainid, pool_, ASSET))) % P;
        ZROUTER = zRouter_;
        PERMIT2 = IPermit2(permit2_);
        V1 = IConfidentialPoolWrap(v1_);
        boxImpl = address(new TacitBox());
        // The pool pulls only from its caller, and this router calls it only with its own deposits.
        if (ASSET != address(0)) SafeTransferLib.safeApproveWithRetry(ASSET, pool_, type(uint256).max);
    }

    /// ETH arrives from box releases and from token→ETH zap swaps.
    receive() external payable {}

    // ──────────────────── 1. Deposits with a signature approval ────────────────────

    /// @notice Deposit `t.extAmount` of the pool's ERC-20 with an EIP-2612 permit (a failing permit is skipped, so an
    ///         existing allowance still works).
    function depositWithPermit(Tx calldata t, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant {
        uint256 amount = _depositAmount(t);
        if (ASSET == address(0)) revert BadTarget();
        try IERC2612(ASSET).permit(msg.sender, address(this), amount, deadline, v, r, s) {} catch {}
        SafeTransferLib.safeTransferFrom(ASSET, msg.sender, address(this), amount);
        _deposit(t, amount);
    }

    /// @notice Deposit `t.extAmount` of the pool's ERC-20 through Permit2 (a failing permit is skipped, so an
    ///         existing Permit2 allowance still works).
    function depositWithPermit2(Tx calldata t, IPermit2.PermitSingle calldata permitSingle, bytes calldata signature)
        external
        nonReentrant
    {
        uint256 amount = _depositAmount(t);
        if (ASSET == address(0)) revert BadTarget();
        _pullPermit2(ASSET, amount, permitSingle, signature);
        _deposit(t, amount);
    }

    // ──────────────────── 2. Zaps ────────────────────

    /// @notice ETH → the pool's ERC-20 through zRouter (output to this router), then deposit exactly `t.extAmount`.
    ///         Surplus output and unspent ETH go back to the caller.
    function zapETHToDeposit(Tx calldata t, bytes calldata zrSwapData) external payable nonReentrant {
        uint256 amount = _depositAmount(t);
        if (ASSET == address(0)) revert BadTarget();
        if (_zRouterReceive(ASSET, msg.value, zrSwapData) < amount) revert ShortSwapOutput();
        _deposit(t, amount);
        _refund(ASSET, msg.sender);
        _refundETH(msg.sender);
    }

    /// @notice Any ERC-20 (via Permit2) → the pool's asset (ERC-20 or ETH) through zRouter, then deposit exactly
    ///         `t.extAmount`. Unspent input and surplus output go back to the caller.
    function zapTokenToDepositWithPermit2(
        Tx calldata t,
        uint256 amountIn,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata zrSwapData
    ) external nonReentrant {
        uint256 amount = _depositAmount(t);
        address tokenIn = permitSingle.details.token;
        if (tokenIn == ASSET) revert BadTarget();
        _pullPermit2(tokenIn, amountIn, permitSingle, signature);
        _lazyApprove(tokenIn, ZROUTER, amountIn);
        if (_zRouterReceive(ASSET, 0, zrSwapData) < amount) revert ShortSwapOutput();
        _deposit(t, amount);
        _refund(tokenIn, msg.sender);
        if (ASSET == address(0)) _refundETH(msg.sender);
        else _refund(ASSET, msg.sender);
    }

    // ──────────────────── 3. Deposit boxes ────────────────────

    /// @notice The deposit box address for `intent`.
    function depositBoxOf(DepositIntent calldata intent) public view returns (address) {
        return _boxAt(_depositSalt(intent));
    }

    /// @notice Permissionless. `t` must deposit exactly `intent.amount` with the intent's leaves and memos; the
    ///         completer names `t.relayer` (normally itself) to collect the fee.
    function completeDeposit(DepositIntent calldata intent, Tx calldata t) external nonReentrant {
        if (t.extAmount != _int(intent.amount) || t.recipient != address(0)) revert BadIntent();
        if (t.publicInputs[9] != intent.outLeaf0 || t.publicInputs[10] != intent.outLeaf1) revert BadIntent();
        if (keccak256(t.memo0) != intent.memo0Hash || keccak256(t.memo1) != intent.memo1Hash) revert BadIntent();
        address box = _deployBox(_depositSalt(intent));
        TacitBox(payable(box)).release(ASSET, address(this), intent.amount);
        _deposit(t, intent.amount);
        emit DepositBoxCompleted(box, msg.sender);
    }

    /// @notice Permissionless, after the deadline: the box's whole balance of `token` (address(0) = ETH) goes to
    ///         `intent.refund`. Works for any token, not only the pool asset.
    function reclaimDeposit(DepositIntent calldata intent, address token) external nonReentrant {
        _reclaim(_depositSalt(intent), token, intent.refund, intent.deadline);
    }

    // ──────────────────── 4. Wrap boxes (into a V1 note) ────────────────────

    /// @notice The wrap box address for `intent`.
    function wrapBoxOf(WrapIntent calldata intent) public view returns (address) {
        return _boxAt(_wrapSalt(intent));
    }

    /// @notice Permissionless: wraps `intent.amount` to `intent.commit` on V1 and pays `intent.tip`.
    function completeWrap(WrapIntent calldata intent) external nonReentrant {
        bytes32 salt = _wrapSalt(intent);
        _completeWrap(intent, salt, _boxAt(salt));
    }

    /// @notice Permissionless, after the deadline: as `reclaimDeposit`, for a wrap box.
    function reclaimWrap(WrapIntent calldata intent, address token) external nonReentrant {
        _reclaim(_wrapSalt(intent), token, intent.refund, intent.deadline);
    }

    // ──────────────────── 5. Pool → V1 in one transaction ────────────────────

    /// @notice Withdraw from the pool into `intent`'s wrap box (the proof binds the box as recipient) and complete the
    ///         wrap. The pool's relayer fee goes to `t.relayer`.
    function withdrawToV1(Tx calldata t, WrapIntent calldata intent) external nonReentrant {
        bytes32 salt = _wrapSalt(intent);
        address box = _boxAt(salt);
        if (t.extAmount >= 0 || t.recipient != box) revert BadIntent();
        POOL.transact(t.pA, t.pB, t.pC, t.publicInputs, t.recipient, t.extAmount, t.relayer, t.fee, t.memo0, t.memo1);
        _completeWrap(intent, salt, box);
    }

    // ──────────────────── 6. Receive boxes ────────────────────

    /// @notice The receive box address for note key `npk` with sweep fee cap `feeBps`.
    function receiveBoxOf(uint256 npk, uint16 feeBps) public view returns (address) {
        return _boxAt(_receiveSalt(npk, feeBps));
    }

    /// @notice What the next sweep of `receiveBoxOf(npk, feeBps)` proves against: its sweep number `n`, the note's
    ///         `rho`, and the box's balance of the pool asset (the sweep's `extAmount`).
    function receiveState(uint256 npk, uint16 feeBps) external view returns (address box, uint256 n, uint256 rho, uint256 balance) {
        box = receiveBoxOf(npk, feeBps);
        n = receiveCount[box];
        rho = _receiveRho(box, n);
        balance = _balanceOf(ASSET, box);
    }

    /// @notice Permissionless. `t` deposits the box's whole balance of the pool asset (`t.extAmount`) into one note
    ///         for `npk`, with no memos, paying `t.relayer` at most `feeBps` of it. On an ETH pool the box is created,
    ///         emptied and removed within the sweep, so between sweeps the address has no code and takes a plain
    ///         21,000-gas transfer.
    function sweepReceive(uint256 npk, uint16 feeBps, Tx calldata t) external nonReentrant {
        if (address(POSEIDON4) == address(0)) revert BadTarget();
        if (npk >= P || feeBps > 10_000) revert BadIntent();
        uint256 amount = _depositAmount(t);
        if (t.fee * 10_000 > amount * feeBps) revert BadIntent();
        if (t.recipient != address(0) || t.memo0.length != 0 || t.memo1.length != 0 || t.publicInputs[10] != 0) {
            revert BadIntent();
        }
        bytes32 salt = _receiveSalt(npk, feeBps);
        address box = _boxAt(salt);
        if (_balanceOf(ASSET, box) != amount) revert BadIntent();
        uint256 n = receiveCount[box]++;
        uint256 rho = _receiveRho(box, n);
        uint256 value = amount - t.fee;
        if (t.publicInputs[9] != POSEIDON4.hash([ASSET_FIELD, value, npk, rho])) revert BadIntent();
        _ensureBox(salt, box);
        if (ASSET == address(0)) {
            // Closing hands the box's ETH to this router and removes its code, so the address keeps taking plain
            // transfers. If closing fails or leaves the ETH, the box keeps its code and releases it instead.
            (bool closed,) = box.call{gas: 50_000}(abi.encodeCall(TacitBox.close, ()));
            if (!closed || box.balance != 0) TacitBox(payable(box)).release(address(0), address(this), box.balance);
        } else {
            // A token payment never runs the box's code, so the box stays; anything else sent to it stays with it.
            TacitBox(payable(box)).release(ASSET, address(this), amount);
        }
        _deposit(t, amount);
        // The note is inserted at `startIndex`, which the pool requires to be its current size.
        emit Received(box, n, t.publicInputs[3], value, rho, t.fee);
    }

    // ──────────────────── 7. Withdraw and call ────────────────────

    /// @notice The call escrow address for `intent`: the recipient a `withdrawAndCall` proof binds.
    function callEscrowOf(CallIntent calldata intent) public view returns (address) {
        return _boxAt(_callSalt(intent));
    }

    /// @notice Withdraw from the pool into `intent`'s escrow (the proof binds it as recipient) and run the intent. A
    ///         failed call or short output reverts the whole transaction, spending nothing. The pool's relayer fee goes
    ///         to `t.relayer`.
    function withdrawAndCall(Tx calldata t, CallIntent calldata intent) external nonReentrant {
        if (t.extAmount >= 0 || t.recipient != callEscrowOf(intent)) revert BadIntent();
        POOL.transact(t.pA, t.pB, t.pC, t.publicInputs, t.recipient, t.extAmount, t.relayer, t.fee, t.memo0, t.memo1);
        _runCall(intent);
    }

    /// @notice Permissionless, until the deadline: runs an escrow that holds the pool asset, e.g. one reached by a
    ///         withdrawal sent to the pool directly rather than through `withdrawAndCall`.
    function executeCall(CallIntent calldata intent) external nonReentrant {
        if (_balanceOf(ASSET, callEscrowOf(intent)) == 0) revert EscrowEmpty();
        _runCall(intent);
    }

    /// @notice Permissionless, after the deadline: the escrow's whole balance of `token` (address(0) = ETH) goes to
    ///         `intent.refund`, without running the calls.
    function refundCall(CallIntent calldata intent, address token) external nonReentrant {
        _reclaim(_callSalt(intent), token, intent.refund, intent.deadline);
    }

    // ──────────────────── 8. Funding with a call ────────────────────

    /// @notice Pays `intent`'s deposit box exactly `intent.amount` from the caller (msg.value, or a transferFrom of
    ///         the pool's token) and publishes `hint` in DepositFunded, so any keeper can complete it. Refuses a box
    ///         that is already paid or completed, or past its deadline.
    function fundDeposit(DepositIntent calldata intent, bytes calldata hint) external payable nonReentrant {
        if (block.timestamp > intent.deadline) revert Expired();
        if (intent.refund == address(0)) revert BadIntent();
        address box = depositBoxOf(intent);
        if (box.code.length != 0 || _balanceOf(ASSET, box) != 0) revert BadIntent();
        _pay(box, intent.amount);
        emit DepositFunded(box, intent, hint);
    }

    /// @notice Pays `amount` into receive box (npk, feeBps) from the caller (msg.value, or a transferFrom of the
    ///         pool's token) and announces it in ReceiveFunded, so a keeper can sweep it without registration.
    function fundReceive(uint256 npk, uint16 feeBps, uint256 amount) external payable nonReentrant {
        if (address(POSEIDON4) == address(0)) revert BadTarget();
        if (npk == 0 || npk >= P || feeBps > 10_000) revert BadIntent();
        address box = receiveBoxOf(npk, feeBps);
        _pay(box, amount);
        emit ReceiveFunded(box, npk, feeBps, amount);
    }

    // ──────────────────── internals ────────────────────

    function _runCall(CallIntent calldata intent) internal {
        if (block.timestamp > intent.deadline) revert Expired();
        if (intent.refund == address(0) || intent.outTokens.length != intent.minOuts.length) revert BadIntent();
        if (intent.outTokens.length != 0 && intent.to == address(0)) revert BadIntent();
        address escrow = _deployBox(_callSalt(intent));
        TacitBox(payable(escrow)).run(intent, ASSET, address(POOL));
        emit CallExecuted(escrow, msg.sender);
    }

    /// Moves `amount` of the pool asset from the caller to `to`: exactly msg.value for ETH, a transferFrom otherwise.
    function _pay(address to, uint256 amount) internal {
        if (amount == 0) revert BadIntent();
        if (ASSET == address(0)) {
            if (msg.value != amount) revert BadIntent();
            SafeTransferLib.safeTransferETH(to, amount);
        } else {
            if (msg.value != 0) revert BadIntent();
            SafeTransferLib.safeTransferFrom(ASSET, msg.sender, to, amount);
        }
    }

    function _balanceOf(address token, address holder) internal view returns (uint256) {
        return token == address(0) ? holder.balance : SafeTransferLib.balanceOf(token, holder);
    }

    function _depositAmount(Tx calldata t) internal pure returns (uint256) {
        if (t.extAmount <= 0) revert BadIntent();
        return uint256(t.extAmount);
    }

    /// Deposit `amount` held by this router. The pool pulls an ERC-20 from msg.sender (this router).
    function _deposit(Tx calldata t, uint256 amount) internal {
        if (ASSET == address(0)) {
            POOL.transact{value: amount}(t.pA, t.pB, t.pC, t.publicInputs, t.recipient, t.extAmount, t.relayer, t.fee, t.memo0, t.memo1);
        } else {
            POOL.transact(t.pA, t.pB, t.pC, t.publicInputs, t.recipient, t.extAmount, t.relayer, t.fee, t.memo0, t.memo1);
        }
    }

    function _completeWrap(WrapIntent calldata intent, bytes32 salt, address box) internal {
        (address token, bool poolMinted) = _wrapToken(intent.assetId);
        _ensureBox(salt, box);
        TacitBox(payable(box)).release(token, address(this), intent.amount + intent.tip);
        if (token == address(0)) {
            V1.wrap{value: intent.amount}(intent.assetId, intent.amount, intent.commit);
        } else {
            // A pool-minted canonical token is burned from the caller; an external token is pulled.
            if (!poolMinted) _lazyApprove(token, address(V1), intent.amount);
            V1.wrap(intent.assetId, intent.amount, intent.commit);
        }
        _deliver(token, intent.tipTo == address(0) ? msg.sender : intent.tipTo, intent.tip);
        emit WrapBoxCompleted(box, msg.sender);
    }

    function _wrapToken(bytes32 assetId) internal view returns (address token, bool poolMinted) {
        if (address(V1) == address(0)) revert BadTarget();
        bool registered;
        (registered, token,,, poolMinted,) = V1.assets(assetId);
        if (!registered) revert BadTarget();
    }

    function _reclaim(bytes32 salt, address token, address refund, uint64 deadline) internal {
        if (block.timestamp <= deadline) revert NotExpired();
        if (refund == address(0)) revert BadIntent();
        address box = _deployBox(salt);
        uint256 bal = _balanceOf(token, box);
        if (bal == 0) revert NothingToReclaim();
        TacitBox(payable(box)).release(token, refund, bal);
        emit BoxReclaimed(box, refund, bal);
    }

    function _depositSalt(DepositIntent calldata intent) internal pure returns (bytes32) {
        return keccak256(abi.encode(DEPOSIT_TAG, intent));
    }

    function _wrapSalt(WrapIntent calldata intent) internal pure returns (bytes32) {
        return keccak256(abi.encode(WRAP_TAG, intent));
    }

    function _receiveSalt(uint256 npk, uint16 feeBps) internal pure returns (bytes32) {
        return keccak256(abi.encode(RECEIVE_TAG, npk, feeBps));
    }

    function _callSalt(CallIntent calldata intent) internal pure returns (bytes32) {
        return keccak256(abi.encode(CALL_TAG, intent));
    }

    function _receiveRho(address box, uint256 n) internal pure returns (uint256) {
        return uint256(keccak256(abi.encode(RECEIVE_TAG, box, n))) % P;
    }

    function _boxAt(bytes32 salt) internal view returns (address) {
        return LibClone.predictDeterministicAddress_PUSH0(boxImpl, salt, address(this));
    }

    function _ensureBox(bytes32 salt, address box) internal {
        if (box.code.length == 0) LibClone.cloneDeterministic_PUSH0(boxImpl, salt);
    }

    function _deployBox(bytes32 salt) internal returns (address box) {
        box = _boxAt(salt);
        _ensureBox(salt, box);
    }

    function _pullPermit2(address token, uint256 amount, IPermit2.PermitSingle calldata permitSingle, bytes calldata signature)
        internal
    {
        if (address(PERMIT2) == address(0)) revert BadTarget();
        if (amount > type(uint160).max) revert AmountTooLarge();
        if (
            permitSingle.details.token != token || permitSingle.spender != address(this)
                || permitSingle.details.amount < amount || permitSingle.sigDeadline < block.timestamp
        ) revert BadPermit2();
        try PERMIT2.permit(msg.sender, permitSingle, signature) {} catch {}
        PERMIT2.transferFrom(msg.sender, address(this), uint160(amount), token);
    }

    /// Call zRouter with the caller's swap calldata and return what it delivered here in `token`
    /// (address(0) = ETH, measured net of the `value` sent).
    function _zRouterReceive(address token, uint256 value, bytes calldata zrSwapData) internal returns (uint256) {
        if (ZROUTER == address(0)) revert BadTarget();
        uint256 before = token == address(0) ? address(this).balance - value : SafeTransferLib.balanceOf(token, address(this));
        (bool ok, bytes memory ret) = ZROUTER.call{value: value}(zrSwapData);
        if (!ok) {
            if (ret.length != 0) {
                assembly ("memory-safe") {
                    revert(add(ret, 0x20), mload(ret))
                }
            }
            revert ZRouterCallFailed();
        }
        uint256 after_ = token == address(0) ? address(this).balance : SafeTransferLib.balanceOf(token, address(this));
        return after_ - before;
    }

    function _lazyApprove(address token, address spender, uint256 amount) internal {
        if (IERC20Allowance(token).allowance(address(this), spender) < amount) {
            SafeTransferLib.safeApproveWithRetry(token, spender, type(uint256).max);
        }
    }

    function _deliver(address token, address to, uint256 amount) internal {
        if (amount == 0) return;
        if (token == address(0)) SafeTransferLib.forceSafeTransferETH(to, amount);
        else SafeTransferLib.safeTransfer(token, to, amount);
    }

    function _refund(address token, address to) internal {
        uint256 bal = SafeTransferLib.balanceOf(token, address(this));
        if (bal != 0) SafeTransferLib.safeTransfer(token, to, bal);
    }

    function _refundETH(address to) internal {
        uint256 bal = address(this).balance;
        if (bal != 0) SafeTransferLib.forceSafeTransferETH(to, bal);
    }

    function _int(uint256 x) internal pure returns (int256) {
        if (x > uint256(type(int256).max)) revert AmountTooLarge();
        return int256(x);
    }
}

/// @title TacitBox
/// @notice A counterfactual box: a PUSH0 minimal-proxy clone at an intent-bound address. It accepts any payment
///         before or after deployment and releases only on its router's instruction.
contract TacitBox {
    address private immutable ROUTER;

    error NotRouter();
    error BadTarget();
    error ShortOutput();

    constructor() {
        ROUTER = msg.sender;
    }

    function release(address token, address to, uint256 amount) external {
        if (msg.sender != ROUTER) revert NotRouter();
        _send(token, to, amount);
    }

    /// Runs a call intent from this box's funds: the calls in order, then each output in full to `c.to` (at least
    /// its floor) and the rest of the pool asset to `c.refund`. Called by the router on a call escrow only.
    function run(TacitEvmPoolRouter.CallIntent calldata c, address asset, address pool) external {
        if (msg.sender != ROUTER) revert NotRouter();
        for (uint256 i; i < c.calls.length; ++i) {
            TacitEvmPoolRouter.Call calldata k = c.calls[i];
            if (k.target == pool || k.target == ROUTER || k.target == address(this)) revert BadTarget();
            bool moves = k.token != address(0) && k.amount != 0;
            if (moves) {
                if (k.push) SafeTransferLib.safeTransfer(k.token, k.target, k.amount);
                else SafeTransferLib.safeApproveWithRetry(k.token, k.target, k.amount);
            }
            (bool ok, bytes memory ret) = k.target.call{value: k.value}(k.data);
            if (!ok) {
                assembly ("memory-safe") {
                    revert(add(ret, 0x20), mload(ret))
                }
            }
            if (moves && !k.push) SafeTransferLib.safeApproveWithRetry(k.token, k.target, 0);
        }
        for (uint256 i; i < c.outTokens.length; ++i) {
            uint256 bal = _balance(c.outTokens[i]);
            if (bal < c.minOuts[i]) revert ShortOutput();
            _send(c.outTokens[i], c.to, bal);
        }
        _send(asset, c.refund, _balance(asset));
    }

    /// Removes a box created earlier in the same transaction (EIP-6780), leaving its address without code, and
    /// hands its ETH to the router. Called on a receive box only, once its balance has been checked.
    function close() external {
        if (msg.sender != ROUTER) revert NotRouter();
        selfdestruct(payable(ROUTER));
    }

    function _balance(address token) internal view returns (uint256) {
        return token == address(0) ? address(this).balance : SafeTransferLib.balanceOf(token, address(this));
    }

    function _send(address token, address to, uint256 amount) internal {
        if (amount == 0) return;
        if (token == address(0)) SafeTransferLib.forceSafeTransferETH(to, amount);
        else SafeTransferLib.safeTransfer(token, to, amount);
    }

    receive() external payable {}
}

/Users/z/tacit/contracts/lib/solady/src/utils/LibClone.sol

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

/// @notice Minimal proxy library.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibClone.sol)
/// @author Minimal proxy by 0age (https://github.com/0age)
/// @author Clones with immutable args by wighawag, zefram.eth, Saw-mon & Natalie
/// (https://github.com/Saw-mon-and-Natalie/clones-with-immutable-args)
/// @author Minimal ERC1967 proxy by jtriley-eth (https://github.com/jtriley-eth/minimum-viable-proxy)
///
/// @dev Minimal proxy:
/// Although the sw0nt pattern saves 5 gas over the ERC1167 pattern during runtime,
/// it is not supported out-of-the-box on Etherscan. Hence, we choose to use the 0age pattern,
/// which saves 4 gas over the ERC1167 pattern during runtime, and has the smallest bytecode.
/// - Automatically verified on Etherscan.
///
/// @dev Minimal proxy (PUSH0 variant):
/// This is a new minimal proxy that uses the PUSH0 opcode introduced during Shanghai.
/// It is optimized first for minimal runtime gas, then for minimal bytecode.
/// The PUSH0 clone functions are intentionally postfixed with a jarring "_PUSH0" as
/// many EVM chains may not support the PUSH0 opcode in the early months after Shanghai.
/// Please use with caution.
/// - Automatically verified on Etherscan.
///
/// @dev Clones with immutable args (CWIA):
/// The implementation of CWIA here does NOT append the immutable args into the calldata
/// passed into delegatecall. It is simply an ERC1167 minimal proxy with the immutable arguments
/// appended to the back of the runtime bytecode.
/// - Uses the identity precompile (0x4) to copy args during deployment.
///
/// @dev Minimal ERC1967 proxy:
/// A minimal ERC1967 proxy, intended to be upgraded with UUPS.
/// This is NOT the same as ERC1967Factory's transparent proxy, which includes admin logic.
/// - Automatically verified on Etherscan.
///
/// @dev Minimal ERC1967 proxy with immutable args:
/// - Uses the identity precompile (0x4) to copy args during deployment.
/// - Automatically verified on Etherscan.
///
/// @dev ERC1967I proxy:
/// A variant of the minimal ERC1967 proxy, with a special code path that activates
/// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the
/// `implementation` address. The returned implementation is guaranteed to be valid if the
/// keccak256 of the proxy's code is equal to `ERC1967I_CODE_HASH`.
///
/// @dev ERC1967I proxy with immutable args:
/// A variant of the minimal ERC1967 proxy, with a special code path that activates
/// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the
/// - Uses the identity precompile (0x4) to copy args during deployment.
///
/// @dev Minimal ERC1967 beacon proxy:
/// A minimal beacon proxy, intended to be upgraded with an upgradable beacon.
/// - Automatically verified on Etherscan.
///
/// @dev Minimal ERC1967 beacon proxy with immutable args:
/// - Uses the identity precompile (0x4) to copy args during deployment.
/// - Automatically verified on Etherscan.
///
/// @dev ERC1967I beacon proxy:
/// A variant of the minimal ERC1967 beacon proxy, with a special code path that activates
/// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the
/// `implementation` address. The returned implementation is guaranteed to be valid if the
/// keccak256 of the proxy's code is equal to `ERC1967I_CODE_HASH`.
///
/// @dev ERC1967I proxy with immutable args:
/// A variant of the minimal ERC1967 beacon proxy, with a special code path that activates
/// if `calldatasize() == 1`. This code path skips the delegatecall and directly returns the
/// - Uses the identity precompile (0x4) to copy args during deployment.
library LibClone {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The keccak256 of deployed code for the clone proxy,
    /// with the implementation set to `address(0)`.
    bytes32 internal constant CLONE_CODE_HASH =
        0x48db2cfdb2853fce0b464f1f93a1996469459df3ab6c812106074c4106a1eb1f;

    /// @dev The keccak256 of deployed code for the PUSH0 proxy,
    /// with the implementation set to `address(0)`.
    bytes32 internal constant PUSH0_CLONE_CODE_HASH =
        0x67bc6bde1b84d66e267c718ba44cf3928a615d29885537955cb43d44b3e789dc;

    /// @dev The keccak256 of deployed code for the ERC-1167 CWIA proxy,
    /// with the implementation set to `address(0)`.
    bytes32 internal constant CWIA_CODE_HASH =
        0x3cf92464268225a4513da40a34d967354684c32cd0edd67b5f668dfe3550e940;

    /// @dev The keccak256 of the deployed code for the ERC1967 proxy.
    bytes32 internal constant ERC1967_CODE_HASH =
        0xaaa52c8cc8a0e3fd27ce756cc6b4e70c51423e9b597b11f32d3e49f8b1fc890d;

    /// @dev The keccak256 of the deployed code for the ERC1967I proxy.
    bytes32 internal constant ERC1967I_CODE_HASH =
        0xce700223c0d4cea4583409accfc45adac4a093b3519998a9cbbe1504dadba6f7;

    /// @dev The keccak256 of the deployed code for the ERC1967 beacon proxy.
    bytes32 internal constant ERC1967_BEACON_PROXY_CODE_HASH =
        0x14044459af17bc4f0f5aa2f658cb692add77d1302c29fe2aebab005eea9d1162;

    /// @dev The keccak256 of the deployed code for the ERC1967 beacon proxy.
    bytes32 internal constant ERC1967I_BEACON_PROXY_CODE_HASH =
        0xf8c46d2793d5aa984eb827aeaba4b63aedcab80119212fce827309788735519a;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unable to deploy the clone.
    error DeploymentFailed();

    /// @dev The salt must start with either the zero address or `by`.
    error SaltDoesNotStartWith();

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  MINIMAL PROXY OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a clone of `implementation`.
    function clone(address implementation) internal returns (address instance) {
        instance = clone(0, implementation);
    }

    /// @dev Deploys a clone of `implementation`.
    /// Deposits `value` ETH during deployment.
    function clone(uint256 value, address implementation) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            /**
             * --------------------------------------------------------------------------+
             * CREATION (9 bytes)                                                        |
             * --------------------------------------------------------------------------|
             * Opcode     | Mnemonic          | Stack     | Memory                       |
             * --------------------------------------------------------------------------|
             * 60 runSize | PUSH1 runSize     | r         |                              |
             * 3d         | RETURNDATASIZE    | 0 r       |                              |
             * 81         | DUP2              | r 0 r     |                              |
             * 60 offset  | PUSH1 offset      | o r 0 r   |                              |
             * 3d         | RETURNDATASIZE    | 0 o r 0 r |                              |
             * 39         | CODECOPY          | 0 r       | [0..runSize): runtime code   |
             * f3         | RETURN            |           | [0..runSize): runtime code   |
             * --------------------------------------------------------------------------|
             * RUNTIME (44 bytes)                                                        |
             * --------------------------------------------------------------------------|
             * Opcode  | Mnemonic       | Stack                  | Memory                |
             * --------------------------------------------------------------------------|
             *                                                                           |
             * ::: keep some values in stack ::::::::::::::::::::::::::::::::::::::::::: |
             * 3d      | RETURNDATASIZE | 0                      |                       |
             * 3d      | RETURNDATASIZE | 0 0                    |                       |
             * 3d      | RETURNDATASIZE | 0 0 0                  |                       |
             * 3d      | RETURNDATASIZE | 0 0 0 0                |                       |
             *                                                                           |
             * ::: copy calldata to memory ::::::::::::::::::::::::::::::::::::::::::::: |
             * 36      | CALLDATASIZE   | cds 0 0 0 0            |                       |
             * 3d      | RETURNDATASIZE | 0 cds 0 0 0 0          |                       |
             * 3d      | RETURNDATASIZE | 0 0 cds 0 0 0 0        |                       |
             * 37      | CALLDATACOPY   | 0 0 0 0                | [0..cds): calldata    |
             *                                                                           |
             * ::: delegate call to the implementation contract :::::::::::::::::::::::: |
             * 36      | CALLDATASIZE   | cds 0 0 0 0            | [0..cds): calldata    |
             * 3d      | RETURNDATASIZE | 0 cds 0 0 0 0          | [0..cds): calldata    |
             * 73 addr | PUSH20 addr    | addr 0 cds 0 0 0 0     | [0..cds): calldata    |
             * 5a      | GAS            | gas addr 0 cds 0 0 0 0 | [0..cds): calldata    |
             * f4      | DELEGATECALL   | success 0 0            | [0..cds): calldata    |
             *                                                                           |
             * ::: copy return data to memory :::::::::::::::::::::::::::::::::::::::::: |
             * 3d      | RETURNDATASIZE | rds success 0 0        | [0..cds): calldata    |
             * 3d      | RETURNDATASIZE | rds rds success 0 0    | [0..cds): calldata    |
             * 93      | SWAP4          | 0 rds success 0 rds    | [0..cds): calldata    |
             * 80      | DUP1           | 0 0 rds success 0 rds  | [0..cds): calldata    |
             * 3e      | RETURNDATACOPY | success 0 rds          | [0..rds): returndata  |
             *                                                                           |
             * 60 0x2a | PUSH1 0x2a     | 0x2a success 0 rds     | [0..rds): returndata  |
             * 57      | JUMPI          | 0 rds                  | [0..rds): returndata  |
             *                                                                           |
             * ::: revert :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * fd      | REVERT         |                        | [0..rds): returndata  |
             *                                                                           |
             * ::: return :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b      | JUMPDEST       | 0 rds                  | [0..rds): returndata  |
             * f3      | RETURN         |                        | [0..rds): returndata  |
             * --------------------------------------------------------------------------+
             */
            mstore(0x21, 0x5af43d3d93803e602a57fd5bf3)
            mstore(0x14, implementation)
            mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73)
            instance := create(value, 0x0c, 0x35)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Deploys a deterministic clone of `implementation` with `salt`.
    function cloneDeterministic(address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = cloneDeterministic(0, implementation, salt);
    }

    /// @dev Deploys a deterministic clone of `implementation` with `salt`.
    /// Deposits `value` ETH during deployment.
    function cloneDeterministic(uint256 value, address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x21, 0x5af43d3d93803e602a57fd5bf3)
            mstore(0x14, implementation)
            mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73)
            instance := create2(value, 0x0c, 0x35, salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the initialization code of the clone of `implementation`.
    function initCode(address implementation) internal pure returns (bytes memory c) {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            mstore(add(c, 0x40), 0x5af43d3d93803e602a57fd5bf30000000000000000000000)
            mstore(add(c, 0x28), implementation)
            mstore(add(c, 0x14), 0x602c3d8160093d39f33d3d3d3d363d3d37363d73)
            mstore(c, 0x35) // Store the length.
            mstore(0x40, add(c, 0x60)) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the clone of `implementation`.
    function initCodeHash(address implementation) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x21, 0x5af43d3d93803e602a57fd5bf3)
            mstore(0x14, implementation)
            mstore(0x00, 0x602c3d8160093d39f33d3d3d3d363d3d37363d73)
            hash := keccak256(0x0c, 0x35)
            mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the address of the clone of `implementation`, with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddress(address implementation, bytes32 salt, address deployer)
        internal
        pure
        returns (address predicted)
    {
        bytes32 hash = initCodeHash(implementation);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*          MINIMAL PROXY OPERATIONS (PUSH0 VARIANT)          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a PUSH0 clone of `implementation`.
    function clone_PUSH0(address implementation) internal returns (address instance) {
        instance = clone_PUSH0(0, implementation);
    }

    /// @dev Deploys a PUSH0 clone of `implementation`.
    /// Deposits `value` ETH during deployment.
    function clone_PUSH0(uint256 value, address implementation)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            /**
             * --------------------------------------------------------------------------+
             * CREATION (9 bytes)                                                        |
             * --------------------------------------------------------------------------|
             * Opcode     | Mnemonic          | Stack     | Memory                       |
             * --------------------------------------------------------------------------|
             * 60 runSize | PUSH1 runSize     | r         |                              |
             * 5f         | PUSH0             | 0 r       |                              |
             * 81         | DUP2              | r 0 r     |                              |
             * 60 offset  | PUSH1 offset      | o r 0 r   |                              |
             * 5f         | PUSH0             | 0 o r 0 r |                              |
             * 39         | CODECOPY          | 0 r       | [0..runSize): runtime code   |
             * f3         | RETURN            |           | [0..runSize): runtime code   |
             * --------------------------------------------------------------------------|
             * RUNTIME (45 bytes)                                                        |
             * --------------------------------------------------------------------------|
             * Opcode  | Mnemonic       | Stack                  | Memory                |
             * --------------------------------------------------------------------------|
             *                                                                           |
             * ::: keep some values in stack ::::::::::::::::::::::::::::::::::::::::::: |
             * 5f      | PUSH0          | 0                      |                       |
             * 5f      | PUSH0          | 0 0                    |                       |
             *                                                                           |
             * ::: copy calldata to memory ::::::::::::::::::::::::::::::::::::::::::::: |
             * 36      | CALLDATASIZE   | cds 0 0                |                       |
             * 5f      | PUSH0          | 0 cds 0 0              |                       |
             * 5f      | PUSH0          | 0 0 cds 0 0            |                       |
             * 37      | CALLDATACOPY   | 0 0                    | [0..cds): calldata    |
             *                                                                           |
             * ::: delegate call to the implementation contract :::::::::::::::::::::::: |
             * 36      | CALLDATASIZE   | cds 0 0                | [0..cds): calldata    |
             * 5f      | PUSH0          | 0 cds 0 0              | [0..cds): calldata    |
             * 73 addr | PUSH20 addr    | addr 0 cds 0 0         | [0..cds): calldata    |
             * 5a      | GAS            | gas addr 0 cds 0 0     | [0..cds): calldata    |
             * f4      | DELEGATECALL   | success                | [0..cds): calldata    |
             *                                                                           |
             * ::: copy return data to memory :::::::::::::::::::::::::::::::::::::::::: |
             * 3d      | RETURNDATASIZE | rds success            | [0..cds): calldata    |
             * 5f      | PUSH0          | 0 rds success          | [0..cds): calldata    |
             * 5f      | PUSH0          | 0 0 rds success        | [0..cds): calldata    |
             * 3e      | RETURNDATACOPY | success                | [0..rds): returndata  |
             *                                                                           |
             * 60 0x29 | PUSH1 0x29     | 0x29 success           | [0..rds): returndata  |
             * 57      | JUMPI          |                        | [0..rds): returndata  |
             *                                                                           |
             * ::: revert :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d      | RETURNDATASIZE | rds                    | [0..rds): returndata  |
             * 5f      | PUSH0          | 0 rds                  | [0..rds): returndata  |
             * fd      | REVERT         |                        | [0..rds): returndata  |
             *                                                                           |
             * ::: return :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b      | JUMPDEST       |                        | [0..rds): returndata  |
             * 3d      | RETURNDATASIZE | rds                    | [0..rds): returndata  |
             * 5f      | PUSH0          | 0 rds                  | [0..rds): returndata  |
             * f3      | RETURN         |                        | [0..rds): returndata  |
             * --------------------------------------------------------------------------+
             */
            mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16
            mstore(0x14, implementation) // 20
            mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9
            instance := create(value, 0x0e, 0x36)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x24, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Deploys a deterministic PUSH0 clone of `implementation` with `salt`.
    function cloneDeterministic_PUSH0(address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = cloneDeterministic_PUSH0(0, implementation, salt);
    }

    /// @dev Deploys a deterministic PUSH0 clone of `implementation` with `salt`.
    /// Deposits `value` ETH during deployment.
    function cloneDeterministic_PUSH0(uint256 value, address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16
            mstore(0x14, implementation) // 20
            mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9
            instance := create2(value, 0x0e, 0x36, salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x24, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the initialization code of the PUSH0 clone of `implementation`.
    function initCode_PUSH0(address implementation) internal pure returns (bytes memory c) {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            mstore(add(c, 0x40), 0x5af43d5f5f3e6029573d5ffd5b3d5ff300000000000000000000) // 16
            mstore(add(c, 0x26), implementation) // 20
            mstore(add(c, 0x12), 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9
            mstore(c, 0x36) // Store the length.
            mstore(0x40, add(c, 0x60)) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the PUSH0 clone of `implementation`.
    function initCodeHash_PUSH0(address implementation) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x24, 0x5af43d5f5f3e6029573d5ffd5b3d5ff3) // 16
            mstore(0x14, implementation) // 20
            mstore(0x00, 0x602d5f8160095f39f35f5f365f5f37365f73) // 9 + 9
            hash := keccak256(0x0e, 0x36)
            mstore(0x24, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the address of the PUSH0 clone of `implementation`, with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddress_PUSH0(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHash_PUSH0(implementation);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*           CLONES WITH IMMUTABLE ARGS OPERATIONS            */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a clone of `implementation` with immutable arguments encoded in `args`.
    function clone(address implementation, bytes memory args) internal returns (address instance) {
        instance = clone(0, implementation, args);
    }

    /// @dev Deploys a clone of `implementation` with immutable arguments encoded in `args`.
    /// Deposits `value` ETH during deployment.
    function clone(uint256 value, address implementation, bytes memory args)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            /**
             * ---------------------------------------------------------------------------+
             * CREATION (10 bytes)                                                        |
             * ---------------------------------------------------------------------------|
             * Opcode     | Mnemonic          | Stack     | Memory                        |
             * ---------------------------------------------------------------------------|
             * 61 runSize | PUSH2 runSize     | r         |                               |
             * 3d         | RETURNDATASIZE    | 0 r       |                               |
             * 81         | DUP2              | r 0 r     |                               |
             * 60 offset  | PUSH1 offset      | o r 0 r   |                               |
             * 3d         | RETURNDATASIZE    | 0 o r 0 r |                               |
             * 39         | CODECOPY          | 0 r       | [0..runSize): runtime code    |
             * f3         | RETURN            |           | [0..runSize): runtime code    |
             * ---------------------------------------------------------------------------|
             * RUNTIME (45 bytes + extraLength)                                           |
             * ---------------------------------------------------------------------------|
             * Opcode   | Mnemonic       | Stack                  | Memory                |
             * ---------------------------------------------------------------------------|
             *                                                                            |
             * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::: |
             * 36       | CALLDATASIZE   | cds                    |                       |
             * 3d       | RETURNDATASIZE | 0 cds                  |                       |
             * 3d       | RETURNDATASIZE | 0 0 cds                |                       |
             * 37       | CALLDATACOPY   |                        | [0..cds): calldata    |
             *                                                                            |
             * ::: delegate call to the implementation contract ::::::::::::::::::::::::: |
             * 3d       | RETURNDATASIZE | 0                      | [0..cds): calldata    |
             * 3d       | RETURNDATASIZE | 0 0                    | [0..cds): calldata    |
             * 3d       | RETURNDATASIZE | 0 0 0                  | [0..cds): calldata    |
             * 36       | CALLDATASIZE   | cds 0 0 0              | [0..cds): calldata    |
             * 3d       | RETURNDATASIZE | 0 cds 0 0 0 0          | [0..cds): calldata    |
             * 73 addr  | PUSH20 addr    | addr 0 cds 0 0 0 0     | [0..cds): calldata    |
             * 5a       | GAS            | gas addr 0 cds 0 0 0 0 | [0..cds): calldata    |
             * f4       | DELEGATECALL   | success 0 0            | [0..cds): calldata    |
             *                                                                            |
             * ::: copy return data to memory ::::::::::::::::::::::::::::::::::::::::::: |
             * 3d       | RETURNDATASIZE | rds success 0          | [0..cds): calldata    |
             * 82       | DUP3           | 0 rds success 0         | [0..cds): calldata   |
             * 80       | DUP1           | 0 0 rds success 0      | [0..cds): calldata    |
             * 3e       | RETURNDATACOPY | success 0              | [0..rds): returndata  |
             * 90       | SWAP1          | 0 success              | [0..rds): returndata  |
             * 3d       | RETURNDATASIZE | rds 0 success          | [0..rds): returndata  |
             * 91       | SWAP2          | success 0 rds          | [0..rds): returndata  |
             *                                                                            |
             * 60 0x2b  | PUSH1 0x2b     | 0x2b success 0 rds     | [0..rds): returndata  |
             * 57       | JUMPI          | 0 rds                  | [0..rds): returndata  |
             *                                                                            |
             * ::: revert ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * fd       | REVERT         |                        | [0..rds): returndata  |
             *                                                                            |
             * ::: return ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b       | JUMPDEST       | 0 rds                  | [0..rds): returndata  |
             * f3       | RETURN         |                        | [0..rds): returndata  |
             * ---------------------------------------------------------------------------+
             */
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n))
            mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3)
            mstore(add(m, 0x14), implementation)
            mstore(m, add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n)))
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`.
            instance := create(value, add(m, add(0x0b, lt(n, 0xffd3))), add(n, 0x37))
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Deploys a deterministic clone of `implementation`
    /// with immutable arguments encoded in `args` and `salt`.
    function cloneDeterministic(address implementation, bytes memory args, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = cloneDeterministic(0, implementation, args, salt);
    }

    /// @dev Deploys a deterministic clone of `implementation`
    /// with immutable arguments encoded in `args` and `salt`.
    function cloneDeterministic(
        uint256 value,
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n))
            mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3)
            mstore(add(m, 0x14), implementation)
            mstore(m, add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n)))
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`.
            instance := create2(value, add(m, add(0x0b, lt(n, 0xffd3))), add(n, 0x37), salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Deploys a deterministic clone of `implementation`
    /// with immutable arguments encoded in `args` and `salt`.
    /// This method does not revert if the clone has already been deployed.
    function createDeterministicClone(address implementation, bytes memory args, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicClone(0, implementation, args, salt);
    }

    /// @dev Deploys a deterministic clone of `implementation`
    /// with immutable arguments encoded in `args` and `salt`.
    /// This method does not revert if the clone has already been deployed.
    function createDeterministicClone(
        uint256 value,
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (bool alreadyDeployed, address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x43), n))
            mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3)
            mstore(add(m, 0x14), implementation)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`.
            // forgefmt: disable-next-item
            mstore(add(m, gt(n, 0xffd2)), add(0xfe61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n)))
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, keccak256(add(m, 0x0c), add(n, 0x37)))
            mstore(0x01, shl(96, address()))
            mstore(0x15, salt)
            instance := keccak256(0x00, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, add(m, 0x0c), add(n, 0x37), salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x35, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the initialization code of the clone of `implementation`
    /// using immutable arguments encoded in `args`.
    function initCode(address implementation, bytes memory args)
        internal
        pure
        returns (bytes memory c)
    {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffd2))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(c, 0x57), i), mload(add(add(args, 0x20), i)))
            }
            mstore(add(c, 0x37), 0x5af43d82803e903d91602b57fd5bf3)
            mstore(add(c, 0x28), implementation)
            mstore(add(c, 0x14), add(0x61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n)))
            mstore(c, add(0x37, n)) // Store the length.
            mstore(add(c, add(n, 0x57)), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(c, add(n, 0x77))) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the clone of `implementation`
    /// using immutable arguments encoded in `args`.
    function initCodeHash(address implementation, bytes memory args)
        internal
        pure
        returns (bytes32 hash)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x2d = 0xffd2`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffd2))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(m, 0x43), i), mload(add(add(args, 0x20), i)))
            }
            mstore(add(m, 0x23), 0x5af43d82803e903d91602b57fd5bf3)
            mstore(add(m, 0x14), implementation)
            mstore(m, add(0x61002d3d81600a3d39f3363d3d373d3d3d363d73, shl(136, n)))
            hash := keccak256(add(m, 0x0c), add(n, 0x37))
        }
    }

    /// @dev Returns the address of the clone of
    /// `implementation` using immutable arguments encoded in `args`, with `salt`, by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddress(
        address implementation,
        bytes memory data,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHash(implementation, data);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /// @dev Equivalent to `argsOnClone(instance, 0, 2 ** 256 - 1)`.
    function argsOnClone(address instance) internal view returns (bytes memory args) {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x2d))) // Store the length.
            extcodecopy(instance, add(args, 0x20), 0x2d, add(mload(args), 0x20))
            mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory.
        }
    }

    /// @dev Equivalent to `argsOnClone(instance, start, 2 ** 256 - 1)`.
    function argsOnClone(address instance, uint256 start)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(instance), 0x2d))
            let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
            extcodecopy(instance, args, add(start, 0x0d), add(l, 0x40))
            mstore(args, mul(sub(n, start), lt(start, n))) // Store the length.
            mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory.
        }
    }

    /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`.
    /// `start` and `end` will be clamped to the range `[0, args.length]`.
    /// The `instance` MUST be deployed via the clone with immutable args functions.
    /// Otherwise, the behavior is undefined.
    /// Out-of-gas reverts if `instance` does not have any code.
    function argsOnClone(address instance, uint256 start, uint256 end)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            if iszero(lt(end, 0xffff)) { end := 0xffff }
            let d := mul(sub(end, start), lt(start, end))
            extcodecopy(instance, args, add(start, 0x0d), add(d, 0x20))
            if iszero(and(0xff, mload(add(args, d)))) {
                let n := sub(extcodesize(instance), 0x2d)
                returndatacopy(returndatasize(), returndatasize(), shr(40, n))
                d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
            }
            mstore(args, d) // Store the length.
            mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(args, 0x40), d)) // Allocate memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              MINIMAL ERC1967 PROXY OPERATIONS              */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // Note: The ERC1967 proxy here is intended to be upgraded with UUPS.
    // This is NOT the same as ERC1967Factory's transparent proxy, which includes admin logic.

    /// @dev Deploys a minimal ERC1967 proxy with `implementation`.
    function deployERC1967(address implementation) internal returns (address instance) {
        instance = deployERC1967(0, implementation);
    }

    /// @dev Deploys a minimal ERC1967 proxy with `implementation`.
    /// Deposits `value` ETH during deployment.
    function deployERC1967(uint256 value, address implementation)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            /**
             * ---------------------------------------------------------------------------------+
             * CREATION (34 bytes)                                                              |
             * ---------------------------------------------------------------------------------|
             * Opcode     | Mnemonic       | Stack            | Memory                          |
             * ---------------------------------------------------------------------------------|
             * 60 runSize | PUSH1 runSize  | r                |                                 |
             * 3d         | RETURNDATASIZE | 0 r              |                                 |
             * 81         | DUP2           | r 0 r            |                                 |
             * 60 offset  | PUSH1 offset   | o r 0 r          |                                 |
             * 3d         | RETURNDATASIZE | 0 o r 0 r        |                                 |
             * 39         | CODECOPY       | 0 r              | [0..runSize): runtime code      |
             * 73 impl    | PUSH20 impl    | impl 0 r         | [0..runSize): runtime code      |
             * 60 slotPos | PUSH1 slotPos  | slotPos impl 0 r | [0..runSize): runtime code      |
             * 51         | MLOAD          | slot impl 0 r    | [0..runSize): runtime code      |
             * 55         | SSTORE         | 0 r              | [0..runSize): runtime code      |
             * f3         | RETURN         |                  | [0..runSize): runtime code      |
             * ---------------------------------------------------------------------------------|
             * RUNTIME (61 bytes)                                                               |
             * ---------------------------------------------------------------------------------|
             * Opcode     | Mnemonic       | Stack            | Memory                          |
             * ---------------------------------------------------------------------------------|
             *                                                                                  |
             * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 36         | CALLDATASIZE   | cds              |                                 |
             * 3d         | RETURNDATASIZE | 0 cds            |                                 |
             * 3d         | RETURNDATASIZE | 0 0 cds          |                                 |
             * 37         | CALLDATACOPY   |                  | [0..calldatasize): calldata     |
             *                                                                                  |
             * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | 0                |                                 |
             * 3d         | RETURNDATASIZE | 0 0              |                                 |
             * 36         | CALLDATASIZE   | cds 0 0          | [0..calldatasize): calldata     |
             * 3d         | RETURNDATASIZE | 0 cds 0 0        | [0..calldatasize): calldata     |
             * 7f slot    | PUSH32 slot    | s 0 cds 0 0      | [0..calldatasize): calldata     |
             * 54         | SLOAD          | i 0 cds 0 0      | [0..calldatasize): calldata     |
             * 5a         | GAS            | g i 0 cds 0 0    | [0..calldatasize): calldata     |
             * f4         | DELEGATECALL   | succ             | [0..calldatasize): calldata     |
             *                                                                                  |
             * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | rds succ         | [0..calldatasize): calldata     |
             * 60 0x00    | PUSH1 0x00     | 0 rds succ       | [0..calldatasize): calldata     |
             * 80         | DUP1           | 0 0 rds succ     | [0..calldatasize): calldata     |
             * 3e         | RETURNDATACOPY | succ             | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: |
             * 60 0x38    | PUSH1 0x38     | dest succ        | [0..returndatasize): returndata |
             * 57         | JUMPI          |                  | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | rds              | [0..returndatasize): returndata |
             * 60 0x00    | PUSH1 0x00     | 0 rds            | [0..returndatasize): returndata |
             * fd         | REVERT         |                  | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b         | JUMPDEST       |                  | [0..returndatasize): returndata |
             * 3d         | RETURNDATASIZE | rds              | [0..returndatasize): returndata |
             * 60 0x00    | PUSH1 0x00     | 0 rds            | [0..returndatasize): returndata |
             * f3         | RETURN         |                  | [0..returndatasize): returndata |
             * ---------------------------------------------------------------------------------+
             */
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(0x20, 0x6009)
            mstore(0x1e, implementation)
            mstore(0x0a, 0x603d3d8160223d3973)
            instance := create(value, 0x21, 0x5f)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation` and `salt`.
    function deployDeterministicERC1967(address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = deployDeterministicERC1967(0, implementation, salt);
    }

    /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation` and `salt`.
    /// Deposits `value` ETH during deployment.
    function deployDeterministicERC1967(uint256 value, address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(0x20, 0x6009)
            mstore(0x1e, implementation)
            mstore(0x0a, 0x603d3d8160223d3973)
            instance := create2(value, 0x21, 0x5f, salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation` and `salt`.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967(address implementation, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicERC1967(0, implementation, salt);
    }

    /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation` and `salt`.
    /// Deposits `value` ETH during deployment.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967(uint256 value, address implementation, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(0x20, 0x6009)
            mstore(0x1e, implementation)
            mstore(0x0a, 0x603d3d8160223d3973)
            // Compute and store the bytecode hash.
            mstore(add(m, 0x35), keccak256(0x21, 0x5f))
            mstore(m, shl(88, address()))
            mstore8(m, 0xff) // Write the prefix.
            mstore(add(m, 0x15), salt)
            instance := keccak256(m, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, 0x21, 0x5f, salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Returns the initialization code of the minimal ERC1967 proxy of `implementation`.
    function initCodeERC1967(address implementation) internal pure returns (bytes memory c) {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            mstore(add(c, 0x60), 0x3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f300)
            mstore(add(c, 0x40), 0x55f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076cc)
            mstore(add(c, 0x20), or(shl(24, implementation), 0x600951))
            mstore(add(c, 0x09), 0x603d3d8160223d3973)
            mstore(c, 0x5f) // Store the length.
            mstore(0x40, add(c, 0x80)) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the minimal ERC1967 proxy of `implementation`.
    function initCodeHashERC1967(address implementation) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(0x40, 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(0x20, 0x6009)
            mstore(0x1e, implementation)
            mstore(0x0a, 0x603d3d8160223d3973)
            hash := keccak256(0x21, 0x5f)
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Returns the address of the ERC1967 proxy of `implementation`, with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddressERC1967(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHashERC1967(implementation);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*    MINIMAL ERC1967 PROXY WITH IMMUTABLE ARGS OPERATIONS    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a minimal ERC1967 proxy with `implementation` and `args`.
    function deployERC1967(address implementation, bytes memory args)
        internal
        returns (address instance)
    {
        instance = deployERC1967(0, implementation, args);
    }

    /// @dev Deploys a minimal ERC1967 proxy with `implementation` and `args`.
    /// Deposits `value` ETH during deployment.
    function deployERC1967(uint256 value, address implementation, bytes memory args)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n))
            mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(0x16, 0x6009)
            mstore(0x14, implementation)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`.
            mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n)))
            mstore(m, mload(0x16))
            instance := create(value, m, add(n, 0x60))
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`.
    function deployDeterministicERC1967(address implementation, bytes memory args, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = deployDeterministicERC1967(0, implementation, args, salt);
    }

    /// @dev Deploys a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`.
    /// Deposits `value` ETH during deployment.
    function deployDeterministicERC1967(
        uint256 value,
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n))
            mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(0x16, 0x6009)
            mstore(0x14, implementation)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`.
            mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n)))
            mstore(m, mload(0x16))
            instance := create2(value, m, add(n, 0x60), salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967(address implementation, bytes memory args, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicERC1967(0, implementation, args, salt);
    }

    /// @dev Creates a deterministic minimal ERC1967 proxy with `implementation`, `args` and `salt`.
    /// Deposits `value` ETH during deployment.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967(
        uint256 value,
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (bool alreadyDeployed, address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x60), n))
            mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(0x16, 0x6009)
            mstore(0x14, implementation)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`.
            mstore(gt(n, 0xffc2), add(0xfe61003d3d8160233d3973, shl(56, n)))
            mstore(m, mload(0x16))
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, keccak256(m, add(n, 0x60)))
            mstore(0x01, shl(96, address()))
            mstore(0x15, salt)
            instance := keccak256(0x00, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, m, add(n, 0x60), salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x35, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the initialization code of the minimal ERC1967 proxy of `implementation` and `args`.
    function initCodeERC1967(address implementation, bytes memory args)
        internal
        pure
        returns (bytes memory c)
    {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffc2))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(c, 0x80), i), mload(add(add(args, 0x20), i)))
            }
            mstore(add(c, 0x60), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(add(c, 0x40), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(add(c, 0x20), 0x6009)
            mstore(add(c, 0x1e), implementation)
            mstore(add(c, 0x0a), add(0x61003d3d8160233d3973, shl(56, n)))
            mstore(c, add(n, 0x60)) // Store the length.
            mstore(add(c, add(n, 0x80)), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(c, add(n, 0xa0))) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the minimal ERC1967 proxy of `implementation` and `args`.
    function initCodeHashERC1967(address implementation, bytes memory args)
        internal
        pure
        returns (bytes32 hash)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x3d = 0xffc2`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffc2))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(m, 0x60), i), mload(add(add(args, 0x20), i)))
            }
            mstore(add(m, 0x40), 0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3)
            mstore(add(m, 0x20), 0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076)
            mstore(0x16, 0x6009)
            mstore(0x14, implementation)
            mstore(0x00, add(0x61003d3d8160233d3973, shl(56, n)))
            mstore(m, mload(0x16))
            hash := keccak256(m, add(n, 0x60))
        }
    }

    /// @dev Returns the address of the ERC1967 proxy of `implementation`, `args`, with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddressERC1967(
        address implementation,
        bytes memory args,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHashERC1967(implementation, args);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /// @dev Equivalent to `argsOnERC1967(instance, start, 2 ** 256 - 1)`.
    function argsOnERC1967(address instance) internal view returns (bytes memory args) {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x3d))) // Store the length.
            extcodecopy(instance, add(args, 0x20), 0x3d, add(mload(args), 0x20))
            mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory.
        }
    }

    /// @dev Equivalent to `argsOnERC1967(instance, start, 2 ** 256 - 1)`.
    function argsOnERC1967(address instance, uint256 start)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(instance), 0x3d))
            let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
            extcodecopy(instance, args, add(start, 0x1d), add(l, 0x40))
            mstore(args, mul(sub(n, start), lt(start, n))) // Store the length.
            mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory.
        }
    }

    /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`.
    /// `start` and `end` will be clamped to the range `[0, args.length]`.
    /// The `instance` MUST be deployed via the ERC1967 with immutable args functions.
    /// Otherwise, the behavior is undefined.
    /// Out-of-gas reverts if `instance` does not have any code.
    function argsOnERC1967(address instance, uint256 start, uint256 end)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            if iszero(lt(end, 0xffff)) { end := 0xffff }
            let d := mul(sub(end, start), lt(start, end))
            extcodecopy(instance, args, add(start, 0x1d), add(d, 0x20))
            if iszero(and(0xff, mload(add(args, d)))) {
                let n := sub(extcodesize(instance), 0x3d)
                returndatacopy(returndatasize(), returndatasize(), shr(40, n))
                d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
            }
            mstore(args, d) // Store the length.
            mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(args, 0x40), d)) // Allocate memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                 ERC1967I PROXY OPERATIONS                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // Note: This proxy has a special code path that activates if `calldatasize() == 1`.
    // This code path skips the delegatecall and directly returns the `implementation` address.
    // The returned implementation is guaranteed to be valid if the keccak256 of the
    // proxy's code is equal to `ERC1967I_CODE_HASH`.

    /// @dev Deploys a ERC1967I proxy with `implementation`.
    function deployERC1967I(address implementation) internal returns (address instance) {
        instance = deployERC1967I(0, implementation);
    }

    /// @dev Deploys a ERC1967I proxy with `implementation`.
    /// Deposits `value` ETH during deployment.
    function deployERC1967I(uint256 value, address implementation)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            /**
             * ---------------------------------------------------------------------------------+
             * CREATION (34 bytes)                                                              |
             * ---------------------------------------------------------------------------------|
             * Opcode     | Mnemonic       | Stack            | Memory                          |
             * ---------------------------------------------------------------------------------|
             * 60 runSize | PUSH1 runSize  | r                |                                 |
             * 3d         | RETURNDATASIZE | 0 r              |                                 |
             * 81         | DUP2           | r 0 r            |                                 |
             * 60 offset  | PUSH1 offset   | o r 0 r          |                                 |
             * 3d         | RETURNDATASIZE | 0 o r 0 r        |                                 |
             * 39         | CODECOPY       | 0 r              | [0..runSize): runtime code      |
             * 73 impl    | PUSH20 impl    | impl 0 r         | [0..runSize): runtime code      |
             * 60 slotPos | PUSH1 slotPos  | slotPos impl 0 r | [0..runSize): runtime code      |
             * 51         | MLOAD          | slot impl 0 r    | [0..runSize): runtime code      |
             * 55         | SSTORE         | 0 r              | [0..runSize): runtime code      |
             * f3         | RETURN         |                  | [0..runSize): runtime code      |
             * ---------------------------------------------------------------------------------|
             * RUNTIME (82 bytes)                                                               |
             * ---------------------------------------------------------------------------------|
             * Opcode     | Mnemonic       | Stack            | Memory                          |
             * ---------------------------------------------------------------------------------|
             *                                                                                  |
             * ::: check calldatasize ::::::::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 36         | CALLDATASIZE   | cds              |                                 |
             * 58         | PC             | 1 cds            |                                 |
             * 14         | EQ             | eqs              |                                 |
             * 60 0x43    | PUSH1 0x43     | dest eqs         |                                 |
             * 57         | JUMPI          |                  |                                 |
             *                                                                                  |
             * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 36         | CALLDATASIZE   | cds              |                                 |
             * 3d         | RETURNDATASIZE | 0 cds            |                                 |
             * 3d         | RETURNDATASIZE | 0 0 cds          |                                 |
             * 37         | CALLDATACOPY   |                  | [0..calldatasize): calldata     |
             *                                                                                  |
             * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | 0                |                                 |
             * 3d         | RETURNDATASIZE | 0 0              |                                 |
             * 36         | CALLDATASIZE   | cds 0 0          | [0..calldatasize): calldata     |
             * 3d         | RETURNDATASIZE | 0 cds 0 0        | [0..calldatasize): calldata     |
             * 7f slot    | PUSH32 slot    | s 0 cds 0 0      | [0..calldatasize): calldata     |
             * 54         | SLOAD          | i 0 cds 0 0      | [0..calldatasize): calldata     |
             * 5a         | GAS            | g i 0 cds 0 0    | [0..calldatasize): calldata     |
             * f4         | DELEGATECALL   | succ             | [0..calldatasize): calldata     |
             *                                                                                  |
             * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | rds succ         | [0..calldatasize): calldata     |
             * 60 0x00    | PUSH1 0x00     | 0 rds succ       | [0..calldatasize): calldata     |
             * 80         | DUP1           | 0 0 rds succ     | [0..calldatasize): calldata     |
             * 3e         | RETURNDATACOPY | succ             | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: |
             * 60 0x3E    | PUSH1 0x3E     | dest succ        | [0..returndatasize): returndata |
             * 57         | JUMPI          |                  | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | rds              | [0..returndatasize): returndata |
             * 60 0x00    | PUSH1 0x00     | 0 rds            | [0..returndatasize): returndata |
             * fd         | REVERT         |                  | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b         | JUMPDEST       |                  | [0..returndatasize): returndata |
             * 3d         | RETURNDATASIZE | rds              | [0..returndatasize): returndata |
             * 60 0x00    | PUSH1 0x00     | 0 rds            | [0..returndatasize): returndata |
             * f3         | RETURN         |                  | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: implementation , return :::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b         | JUMPDEST       |                  |                                 |
             * 60 0x20    | PUSH1 0x20     | 32               |                                 |
             * 60 0x0F    | PUSH1 0x0F     | o 32             |                                 |
             * 3d         | RETURNDATASIZE | 0 o 32           |                                 |
             * 39         | CODECOPY       |                  | [0..32): implementation slot    |
             * 3d         | RETURNDATASIZE | 0                | [0..32): implementation slot    |
             * 51         | MLOAD          | slot             | [0..32): implementation slot    |
             * 54         | SLOAD          | impl             | [0..32): implementation slot    |
             * 3d         | RETURNDATASIZE | 0 impl           | [0..32): implementation slot    |
             * 52         | MSTORE         |                  | [0..32): implementation address |
             * 59         | MSIZE          | 32               | [0..32): implementation address |
             * 3d         | RETURNDATASIZE | 0 32             | [0..32): implementation address |
             * f3         | RETURN         |                  | [0..32): implementation address |
             * ---------------------------------------------------------------------------------+
             */
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894)
            mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation))))
            instance := create(value, 0x0c, 0x74)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Deploys a deterministic ERC1967I proxy with `implementation` and `salt`.
    function deployDeterministicERC1967I(address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = deployDeterministicERC1967I(0, implementation, salt);
    }

    /// @dev Deploys a deterministic ERC1967I proxy with `implementation` and `salt`.
    /// Deposits `value` ETH during deployment.
    function deployDeterministicERC1967I(uint256 value, address implementation, bytes32 salt)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894)
            mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation))))
            instance := create2(value, 0x0c, 0x74, salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Creates a deterministic ERC1967I proxy with `implementation` and `salt`.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967I(address implementation, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicERC1967I(0, implementation, salt);
    }

    /// @dev Creates a deterministic ERC1967I proxy with `implementation` and `salt`.
    /// Deposits `value` ETH during deployment.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967I(uint256 value, address implementation, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894)
            mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation))))
            // Compute and store the bytecode hash.
            mstore(add(m, 0x35), keccak256(0x0c, 0x74))
            mstore(m, shl(88, address()))
            mstore8(m, 0xff) // Write the prefix.
            mstore(add(m, 0x15), salt)
            instance := keccak256(m, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, 0x0c, 0x74, salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Returns the initialization code of the ERC1967I proxy of `implementation`.
    function initCodeERC1967I(address implementation) internal pure returns (bytes memory c) {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            mstore(add(c, 0x74), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(add(c, 0x54), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(add(c, 0x34), 0x600f5155f3365814604357363d3d373d3d363d7f360894)
            mstore(add(c, 0x1d), implementation)
            mstore(add(c, 0x09), 0x60523d8160223d3973)
            mstore(add(c, 0x94), 0)
            mstore(c, 0x74) // Store the length.
            mstore(0x40, add(c, 0xa0)) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the ERC1967I proxy of `implementation`.
    function initCodeHashERC1967I(address implementation) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(0x40, 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(0x20, 0x600f5155f3365814604357363d3d373d3d363d7f360894)
            mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, implementation))))
            hash := keccak256(0x0c, 0x74)
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Returns the address of the ERC1967I proxy of `implementation`, with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddressERC1967I(
        address implementation,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHashERC1967I(implementation);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*       ERC1967I PROXY WITH IMMUTABLE ARGS OPERATIONS        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a minimal ERC1967I proxy with `implementation` and `args`.
    function deployERC1967I(address implementation, bytes memory args) internal returns (address) {
        return deployERC1967I(0, implementation, args);
    }

    /// @dev Deploys a minimal ERC1967I proxy with `implementation` and `args`.
    /// Deposits `value` ETH during deployment.
    function deployERC1967I(uint256 value, address implementation, bytes memory args)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n))

            mstore(add(m, 0x6b), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(add(m, 0x4b), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(add(m, 0x2b), 0x600f5155f3365814604357363d3d373d3d363d7f360894)
            mstore(add(m, 0x14), implementation)
            mstore(m, add(0xfe6100523d8160233d3973, shl(56, n)))

            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            instance := create(value, add(m, add(0x15, lt(n, 0xffae))), add(0x75, n))
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Deploys a deterministic ERC1967I proxy with `implementation`, `args`, and `salt`.
    function deployDeterministicERC1967I(address implementation, bytes memory args, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = deployDeterministicERC1967I(0, implementation, args, salt);
    }

    /// @dev Deploys a deterministic ERC1967I proxy with `implementation`, `args`, and `salt`.
    /// Deposits `value` ETH during deployment.
    function deployDeterministicERC1967I(
        uint256 value,
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n))

            mstore(add(m, 0x6b), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(add(m, 0x4b), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(add(m, 0x2b), 0x600f5155f3365814604357363d3d373d3d363d7f360894)
            mstore(add(m, 0x14), implementation)
            mstore(m, add(0xfe6100523d8160233d3973, shl(56, n)))

            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            instance := create2(value, add(m, add(0x15, lt(n, 0xffae))), add(0x75, n), salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Creates a deterministic ERC1967I proxy with `implementation`, `args` and `salt`.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967I(address implementation, bytes memory args, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicERC1967I(0, implementation, args, salt);
    }

    /// @dev Creates a deterministic ERC1967I proxy with `implementation`, `args` and `salt`.
    /// Deposits `value` ETH during deployment.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967I(
        uint256 value,
        address implementation,
        bytes memory args,
        bytes32 salt
    ) internal returns (bool alreadyDeployed, address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x75), n))
            mstore(add(m, 0x55), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(add(m, 0x35), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(add(m, 0x15), 0x5155f3365814604357363d3d373d3d363d7f360894)
            mstore(0x16, 0x600f)
            mstore(0x14, implementation)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            mstore(gt(n, 0xffad), add(0xfe6100523d8160233d3973, shl(56, n)))
            mstore(m, mload(0x16))
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, keccak256(m, add(n, 0x75)))
            mstore(0x01, shl(96, address()))
            mstore(0x15, salt)
            instance := keccak256(0x00, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, m, add(0x75, n), salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x35, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the initialization code of the ERC1967I proxy of `implementation` and `args`.
    function initCodeERC1967I(address implementation, bytes memory args)
        internal
        pure
        returns (bytes memory c)
    {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(c, 0x95), i), mload(add(add(args, 0x20), i)))
            }

            mstore(add(c, 0x75), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(add(c, 0x55), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(add(c, 0x35), 0x600f5155f3365814604357363d3d373d3d363d7f360894)
            mstore(add(c, 0x1e), implementation)
            mstore(add(c, 0x0a), add(0x6100523d8160233d3973, shl(56, n)))
            mstore(add(c, add(n, 0x95)), 0)
            mstore(c, add(0x75, n)) // Store the length.
            mstore(0x40, add(c, add(n, 0xb5))) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the ERC1967I proxy of `implementation` and `args.
    function initCodeHashERC1967I(address implementation, bytes memory args)
        internal
        pure
        returns (bytes32 hash)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad))

            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(m, 0x75), i), mload(add(add(args, 0x20), i)))
            }

            mstore(add(m, 0x55), 0x3d6000803e603e573d6000fd5b3d6000f35b6020600f3d393d51543d52593df3)
            mstore(add(m, 0x35), 0xa13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc545af4)
            mstore(add(m, 0x15), 0x5155f3365814604357363d3d373d3d363d7f360894)
            mstore(0x16, 0x600f)
            mstore(0x14, implementation)
            mstore(0x00, add(0x6100523d8160233d3973, shl(56, n)))
            mstore(m, mload(0x16))
            hash := keccak256(m, add(0x75, n))
        }
    }

    /// @dev Returns the address of the ERC1967I proxy of `implementation`, `args` with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddressERC1967I(
        address implementation,
        bytes memory args,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHashERC1967I(implementation, args);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /// @dev Equivalent to `argsOnERC1967I(instance, start, 2 ** 256 - 1)`.
    function argsOnERC1967I(address instance) internal view returns (bytes memory args) {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x52))) // Store the length.
            extcodecopy(instance, add(args, 0x20), 0x52, add(mload(args), 0x20))
            mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory.
        }
    }

    /// @dev Equivalent to `argsOnERC1967I(instance, start, 2 ** 256 - 1)`.
    function argsOnERC1967I(address instance, uint256 start)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(instance), 0x52))
            let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
            extcodecopy(instance, args, add(start, 0x32), add(l, 0x40))
            mstore(args, mul(sub(n, start), lt(start, n))) // Store the length.
            mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory.
        }
    }

    /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`.
    /// `start` and `end` will be clamped to the range `[0, args.length]`.
    /// The `instance` MUST be deployed via the ERC1967 with immutable args functions.
    /// Otherwise, the behavior is undefined.
    /// Out-of-gas reverts if `instance` does not have any code.
    function argsOnERC1967I(address instance, uint256 start, uint256 end)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            if iszero(lt(end, 0xffff)) { end := 0xffff }
            let d := mul(sub(end, start), lt(start, end))
            extcodecopy(instance, args, add(start, 0x32), add(d, 0x20))
            if iszero(and(0xff, mload(add(args, d)))) {
                let n := sub(extcodesize(instance), 0x52)
                returndatacopy(returndatasize(), returndatasize(), shr(40, n))
                d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
            }
            mstore(args, d) // Store the length.
            mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(args, 0x40), d)) // Allocate memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                ERC1967 BOOTSTRAP OPERATIONS                */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // A bootstrap is a minimal UUPS implementation that allows an ERC1967 proxy
    // pointing to it to be upgraded. The ERC1967 proxy can then be deployed to a
    // deterministic address independent of the implementation:
    // ```
    //     address bootstrap = LibClone.erc1967Bootstrap();
    //     address instance = LibClone.deployDeterministicERC1967(0, bootstrap, salt);
    //     LibClone.bootstrapERC1967(bootstrap, implementation);
    // ```

    /// @dev Deploys the ERC1967 bootstrap if it has not been deployed.
    function erc1967Bootstrap() internal returns (address) {
        return erc1967Bootstrap(address(this));
    }

    /// @dev Deploys the ERC1967 bootstrap if it has not been deployed.
    function erc1967Bootstrap(address authorizedUpgrader) internal returns (address bootstrap) {
        bytes memory c = initCodeERC1967Bootstrap(authorizedUpgrader);
        bootstrap = predictDeterministicAddress(keccak256(c), bytes32(0), address(this));
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(extcodesize(bootstrap)) {
                if iszero(create2(0, add(c, 0x20), mload(c), 0)) {
                    mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Replaces the implementation at `instance`.
    function bootstrapERC1967(address instance, address implementation) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, implementation)
            if iszero(call(gas(), instance, 0, 0x0c, 0x14, codesize(), 0x00)) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Replaces the implementation at `instance`, and then call it with `data`.
    function bootstrapERC1967AndCall(address instance, address implementation, bytes memory data)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let n := mload(data)
            mstore(data, implementation)
            if iszero(call(gas(), instance, 0, add(data, 0x0c), add(n, 0x14), codesize(), 0x00)) {
                if iszero(returndatasize()) {
                    mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                    revert(0x1c, 0x04)
                }
                returndatacopy(mload(0x40), 0x00, returndatasize())
                revert(mload(0x40), returndatasize())
            }
            mstore(data, n) // Restore the length of `data`.
        }
    }

    /// @dev Returns the implementation address of the ERC1967 bootstrap for this contract.
    function predictDeterministicAddressERC1967Bootstrap() internal view returns (address) {
        return predictDeterministicAddressERC1967Bootstrap(address(this), address(this));
    }

    /// @dev Returns the implementation address of the ERC1967 bootstrap for this contract.
    function predictDeterministicAddressERC1967Bootstrap(
        address authorizedUpgrader,
        address deployer
    ) internal pure returns (address) {
        bytes32 hash = initCodeHashERC1967Bootstrap(authorizedUpgrader);
        return predictDeterministicAddress(hash, bytes32(0), deployer);
    }

    /// @dev Returns the initialization code of the ERC1967 bootstrap.
    function initCodeERC1967Bootstrap(address authorizedUpgrader)
        internal
        pure
        returns (bytes memory c)
    {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            mstore(add(c, 0x80), 0x3d3560601c5af46047573d6000383e3d38fd0000000000000000000000000000)
            mstore(add(c, 0x60), 0xa920a3ca505d382bbc55601436116049575b005b363d3d373d3d601436036014)
            mstore(add(c, 0x40), 0x0338573d3560601c7f360894a13ba1a3210667c828492db98dca3e2076cc3735)
            mstore(add(c, 0x20), authorizedUpgrader)
            mstore(add(c, 0x0c), 0x606880600a3d393df3fe3373)
            mstore(c, 0x72)
            mstore(0x40, add(c, 0xa0))
        }
    }

    /// @dev Returns the initialization code hash of the ERC1967 bootstrap.
    function initCodeHashERC1967Bootstrap(address authorizedUpgrader)
        internal
        pure
        returns (bytes32)
    {
        return keccak256(initCodeERC1967Bootstrap(authorizedUpgrader));
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*          MINIMAL ERC1967 BEACON PROXY OPERATIONS           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // Note: If you use this proxy, you MUST make sure that the beacon is a
    // valid ERC1967 beacon. This means that the beacon must always return a valid
    // address upon a staticcall to `implementation()`, given sufficient gas.
    // For performance, the deployment operations and the proxy assumes that the
    // beacon is always valid and will NOT validate it.

    /// @dev Deploys a minimal ERC1967 beacon proxy.
    function deployERC1967BeaconProxy(address beacon) internal returns (address instance) {
        instance = deployERC1967BeaconProxy(0, beacon);
    }

    /// @dev Deploys a minimal ERC1967 beacon proxy.
    /// Deposits `value` ETH during deployment.
    function deployERC1967BeaconProxy(uint256 value, address beacon)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            /**
             * ---------------------------------------------------------------------------------+
             * CREATION (34 bytes)                                                              |
             * ---------------------------------------------------------------------------------|
             * Opcode     | Mnemonic       | Stack            | Memory                          |
             * ---------------------------------------------------------------------------------|
             * 60 runSize | PUSH1 runSize  | r                |                                 |
             * 3d         | RETURNDATASIZE | 0 r              |                                 |
             * 81         | DUP2           | r 0 r            |                                 |
             * 60 offset  | PUSH1 offset   | o r 0 r          |                                 |
             * 3d         | RETURNDATASIZE | 0 o r 0 r        |                                 |
             * 39         | CODECOPY       | 0 r              | [0..runSize): runtime code      |
             * 73 beac    | PUSH20 beac    | beac 0 r         | [0..runSize): runtime code      |
             * 60 slotPos | PUSH1 slotPos  | slotPos beac 0 r | [0..runSize): runtime code      |
             * 51         | MLOAD          | slot beac 0 r    | [0..runSize): runtime code      |
             * 55         | SSTORE         | 0 r              | [0..runSize): runtime code      |
             * f3         | RETURN         |                  | [0..runSize): runtime code      |
             * ---------------------------------------------------------------------------------|
             * RUNTIME (82 bytes)                                                               |
             * ---------------------------------------------------------------------------------|
             * Opcode     | Mnemonic       | Stack            | Memory                          |
             * ---------------------------------------------------------------------------------|
             *                                                                                  |
             * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 36         | CALLDATASIZE   | cds              |                                 |
             * 3d         | RETURNDATASIZE | 0 cds            |                                 |
             * 3d         | RETURNDATASIZE | 0 0 cds          |                                 |
             * 37         | CALLDATACOPY   |                  | [0..calldatasize): calldata     |
             *                                                                                  |
             * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | 0                |                                 |
             * 3d         | RETURNDATASIZE | 0 0              |                                 |
             * 36         | CALLDATASIZE   | cds 0 0          | [0..calldatasize): calldata     |
             * 3d         | RETURNDATASIZE | 0 cds 0 0        | [0..calldatasize): calldata     |
             *                                                                                  |
             * ~~~~~~~ beacon staticcall sub procedure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
             * 60 0x20       | PUSH1 0x20       | 32                          |                 |
             * 36            | CALLDATASIZE     | cds 32                      |                 |
             * 60 0x04       | PUSH1 0x04       | 4 cds 32                    |                 |
             * 36            | CALLDATASIZE     | cds 4 cds 32                |                 |
             * 63 0x5c60da1b | PUSH4 0x5c60da1b | 0x5c60da1b cds 4 cds 32     |                 |
             * 60 0xe0       | PUSH1 0xe0       | 224 0x5c60da1b cds 4 cds 32 |                 |
             * 1b            | SHL              | sel cds 4 cds 32            |                 |
             * 36            | CALLDATASIZE     | cds sel cds 4 cds 32        |                 |
             * 52            | MSTORE           | cds 4 cds 32                | sel             |
             * 7f slot       | PUSH32 slot      | s cds 4 cds 32              | sel             |
             * 54            | SLOAD            | beac cds 4 cds 32           | sel             |
             * 5a            | GAS              | g beac cds 4 cds 32         | sel             |
             * fa            | STATICCALL       | succ                        | impl            |
             * 50            | POP              |                             | impl            |
             * 36            | CALLDATASIZE     | cds                         | impl            |
             * 51            | MLOAD            | impl                        | impl            |
             * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
             * 5a         | GAS            | g impl 0 cds 0 0 | [0..calldatasize): calldata     |
             * f4         | DELEGATECALL   | succ             | [0..calldatasize): calldata     |
             *                                                                                  |
             * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | rds succ         | [0..calldatasize): calldata     |
             * 60 0x00    | PUSH1 0x00     | 0 rds succ       | [0..calldatasize): calldata     |
             * 80         | DUP1           | 0 0 rds succ     | [0..calldatasize): calldata     |
             * 3e         | RETURNDATACOPY | succ             | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: |
             * 60 0x4d    | PUSH1 0x4d     | dest succ        | [0..returndatasize): returndata |
             * 57         | JUMPI          |                  | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | rds              | [0..returndatasize): returndata |
             * 60 0x00    | PUSH1 0x00     | 0 rds            | [0..returndatasize): returndata |
             * fd         | REVERT         |                  | [0..returndatasize): returndata |
             *                                                                                  |
             * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b         | JUMPDEST       |                  | [0..returndatasize): returndata |
             * 3d         | RETURNDATASIZE | rds              | [0..returndatasize): returndata |
             * 60 0x00    | PUSH1 0x00     | 0 rds            | [0..returndatasize): returndata |
             * f3         | RETURN         |                  | [0..returndatasize): returndata |
             * ---------------------------------------------------------------------------------+
             */
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon))))
            instance := create(value, 0x0c, 0x74)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `salt`.
    function deployDeterministicERC1967BeaconProxy(address beacon, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = deployDeterministicERC1967BeaconProxy(0, beacon, salt);
    }

    /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `salt`.
    /// Deposits `value` ETH during deployment.
    function deployDeterministicERC1967BeaconProxy(uint256 value, address beacon, bytes32 salt)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon))))
            instance := create2(value, 0x0c, 0x74, salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `salt`.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967BeaconProxy(address beacon, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicERC1967BeaconProxy(0, beacon, salt);
    }

    /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `salt`.
    /// Deposits `value` ETH during deployment.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967BeaconProxy(uint256 value, address beacon, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon))))
            // Compute and store the bytecode hash.
            mstore(add(m, 0x35), keccak256(0x0c, 0x74))
            mstore(m, shl(88, address()))
            mstore8(m, 0xff) // Write the prefix.
            mstore(add(m, 0x15), salt)
            instance := keccak256(m, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, 0x0c, 0x74, salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Returns the initialization code of the minimal ERC1967 beacon proxy.
    function initCodeERC1967BeaconProxy(address beacon) internal pure returns (bytes memory c) {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            mstore(add(c, 0x74), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(add(c, 0x54), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(add(c, 0x34), 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(add(c, 0x1d), beacon)
            mstore(add(c, 0x09), 0x60523d8160223d3973)
            mstore(add(c, 0x94), 0)
            mstore(c, 0x74) // Store the length.
            mstore(0x40, add(c, 0xa0)) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the minimal ERC1967 beacon proxy.
    function initCodeHashERC1967BeaconProxy(address beacon) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(0x40, 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(0x09, or(shl(160, 0x60523d8160223d3973), shr(96, shl(96, beacon))))
            hash := keccak256(0x0c, 0x74)
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Returns the address of the ERC1967 beacon proxy, with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddressERC1967BeaconProxy(
        address beacon,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHashERC1967BeaconProxy(beacon);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*    ERC1967 BEACON PROXY WITH IMMUTABLE ARGS OPERATIONS     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a minimal ERC1967 beacon proxy with `args`.
    function deployERC1967BeaconProxy(address beacon, bytes memory args)
        internal
        returns (address instance)
    {
        instance = deployERC1967BeaconProxy(0, beacon, args);
    }

    /// @dev Deploys a minimal ERC1967 beacon proxy with `args`.
    /// Deposits `value` ETH during deployment.
    function deployERC1967BeaconProxy(uint256 value, address beacon, bytes memory args)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n))
            mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(add(m, 0x14), beacon)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n)))
            instance := create(value, add(m, 0x16), add(n, 0x75))
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `args` and `salt`.
    function deployDeterministicERC1967BeaconProxy(address beacon, bytes memory args, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = deployDeterministicERC1967BeaconProxy(0, beacon, args, salt);
    }

    /// @dev Deploys a deterministic minimal ERC1967 beacon proxy with `args` and `salt`.
    /// Deposits `value` ETH during deployment.
    function deployDeterministicERC1967BeaconProxy(
        uint256 value,
        address beacon,
        bytes memory args,
        bytes32 salt
    ) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n))
            mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(add(m, 0x14), beacon)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n)))
            instance := create2(value, add(m, 0x16), add(n, 0x75), salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `args` and `salt`.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967BeaconProxy(address beacon, bytes memory args, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicERC1967BeaconProxy(0, beacon, args, salt);
    }

    /// @dev Creates a deterministic minimal ERC1967 beacon proxy with `args` and `salt`.
    /// Deposits `value` ETH during deployment.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967BeaconProxy(
        uint256 value,
        address beacon,
        bytes memory args,
        bytes32 salt
    ) internal returns (bool alreadyDeployed, address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x8b), n))
            mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(add(m, 0x14), beacon)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            mstore(add(m, gt(n, 0xffad)), add(0xfe6100523d8160233d3973, shl(56, n)))
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, keccak256(add(m, 0x16), add(n, 0x75)))
            mstore(0x01, shl(96, address()))
            mstore(0x15, salt)
            instance := keccak256(0x00, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, add(m, 0x16), add(n, 0x75), salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x35, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the initialization code of the minimal ERC1967 beacon proxy.
    function initCodeERC1967BeaconProxy(address beacon, bytes memory args)
        internal
        pure
        returns (bytes memory c)
    {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(c, 0x95), i), mload(add(add(args, 0x20), i)))
            }
            mstore(add(c, 0x75), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(add(c, 0x55), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(add(c, 0x35), 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(add(c, 0x1e), beacon)
            mstore(add(c, 0x0a), add(0x6100523d8160233d3973, shl(56, n)))
            mstore(c, add(n, 0x75)) // Store the length.
            mstore(add(c, add(n, 0x95)), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(c, add(n, 0xb5))) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the minimal ERC1967 beacon proxy with `args`.
    function initCodeHashERC1967BeaconProxy(address beacon, bytes memory args)
        internal
        pure
        returns (bytes32 hash)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x52 = 0xffad`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffad))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(m, 0x8b), i), mload(add(add(args, 0x20), i)))
            }
            mstore(add(m, 0x6b), 0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3)
            mstore(add(m, 0x4b), 0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c)
            mstore(add(m, 0x2b), 0x60195155f3363d3d373d3d363d602036600436635c60da)
            mstore(add(m, 0x14), beacon)
            mstore(m, add(0x6100523d8160233d3973, shl(56, n)))
            hash := keccak256(add(m, 0x16), add(n, 0x75))
        }
    }

    /// @dev Returns the address of the ERC1967 beacon proxy with `args`, with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddressERC1967BeaconProxy(
        address beacon,
        bytes memory args,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHashERC1967BeaconProxy(beacon, args);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /// @dev Equivalent to `argsOnERC1967BeaconProxy(instance, start, 2 ** 256 - 1)`.
    function argsOnERC1967BeaconProxy(address instance) internal view returns (bytes memory args) {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x52))) // Store the length.
            extcodecopy(instance, add(args, 0x20), 0x52, add(mload(args), 0x20))
            mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory.
        }
    }

    /// @dev Equivalent to `argsOnERC1967BeaconProxy(instance, start, 2 ** 256 - 1)`.
    function argsOnERC1967BeaconProxy(address instance, uint256 start)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(instance), 0x52))
            let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
            extcodecopy(instance, args, add(start, 0x32), add(l, 0x40))
            mstore(args, mul(sub(n, start), lt(start, n))) // Store the length.
            mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory.
        }
    }

    /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`.
    /// `start` and `end` will be clamped to the range `[0, args.length]`.
    /// The `instance` MUST be deployed via the ERC1967 beacon proxy with immutable args functions.
    /// Otherwise, the behavior is undefined.
    /// Out-of-gas reverts if `instance` does not have any code.
    function argsOnERC1967BeaconProxy(address instance, uint256 start, uint256 end)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            if iszero(lt(end, 0xffff)) { end := 0xffff }
            let d := mul(sub(end, start), lt(start, end))
            extcodecopy(instance, args, add(start, 0x32), add(d, 0x20))
            if iszero(and(0xff, mload(add(args, d)))) {
                let n := sub(extcodesize(instance), 0x52)
                returndatacopy(returndatasize(), returndatasize(), shr(40, n))
                d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
            }
            mstore(args, d) // Store the length.
            mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(args, 0x40), d)) // Allocate memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              ERC1967I BEACON PROXY OPERATIONS              */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // Note: This proxy has a special code path that activates if `calldatasize() == 1`.
    // This code path skips the delegatecall and directly returns the `implementation` address.
    // The returned implementation is guaranteed to be valid if the keccak256 of the
    // proxy's code is equal to `ERC1967_BEACON_PROXY_CODE_HASH`.
    //
    // If you use this proxy, you MUST make sure that the beacon is a
    // valid ERC1967 beacon. This means that the beacon must always return a valid
    // address upon a staticcall to `implementation()`, given sufficient gas.
    // For performance, the deployment operations and the proxy assumes that the
    // beacon is always valid and will NOT validate it.

    /// @dev Deploys a ERC1967I beacon proxy.
    function deployERC1967IBeaconProxy(address beacon) internal returns (address instance) {
        instance = deployERC1967IBeaconProxy(0, beacon);
    }

    /// @dev Deploys a ERC1967I beacon proxy.
    /// Deposits `value` ETH during deployment.
    function deployERC1967IBeaconProxy(uint256 value, address beacon)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            /**
             * ---------------------------------------------------------------------------------+
             * CREATION (34 bytes)                                                              |
             * ---------------------------------------------------------------------------------|
             * Opcode     | Mnemonic       | Stack            | Memory                          |
             * ---------------------------------------------------------------------------------|
             * 60 runSize | PUSH1 runSize  | r                |                                 |
             * 3d         | RETURNDATASIZE | 0 r              |                                 |
             * 81         | DUP2           | r 0 r            |                                 |
             * 60 offset  | PUSH1 offset   | o r 0 r          |                                 |
             * 3d         | RETURNDATASIZE | 0 o r 0 r        |                                 |
             * 39         | CODECOPY       | 0 r              | [0..runSize): runtime code      |
             * 73 beac    | PUSH20 beac    | beac 0 r         | [0..runSize): runtime code      |
             * 60 slotPos | PUSH1 slotPos  | slotPos beac 0 r | [0..runSize): runtime code      |
             * 51         | MLOAD          | slot beac 0 r    | [0..runSize): runtime code      |
             * 55         | SSTORE         | 0 r              | [0..runSize): runtime code      |
             * f3         | RETURN         |                  | [0..runSize): runtime code      |
             * ---------------------------------------------------------------------------------|
             * RUNTIME (87 bytes)                                                               |
             * ---------------------------------------------------------------------------------|
             * Opcode     | Mnemonic       | Stack            | Memory                          |
             * ---------------------------------------------------------------------------------|
             *                                                                                  |
             * ::: copy calldata to memory :::::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 36         | CALLDATASIZE   | cds              |                                 |
             * 3d         | RETURNDATASIZE | 0 cds            |                                 |
             * 3d         | RETURNDATASIZE | 0 0 cds          |                                 |
             * 37         | CALLDATACOPY   |                  | [0..calldatasize): calldata     |
             *                                                                                  |
             * ::: delegatecall to implementation ::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | 0                |                                 |
             * 3d         | RETURNDATASIZE | 0 0              |                                 |
             * 36         | CALLDATASIZE   | cds 0 0          | [0..calldatasize): calldata     |
             * 3d         | RETURNDATASIZE | 0 cds 0 0        | [0..calldatasize): calldata     |
             *                                                                                  |
             * ~~~~~~~ beacon staticcall sub procedure ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
             * 60 0x20       | PUSH1 0x20       | 32                          |                 |
             * 36            | CALLDATASIZE     | cds 32                      |                 |
             * 60 0x04       | PUSH1 0x04       | 4 cds 32                    |                 |
             * 36            | CALLDATASIZE     | cds 4 cds 32                |                 |
             * 63 0x5c60da1b | PUSH4 0x5c60da1b | 0x5c60da1b cds 4 cds 32     |                 |
             * 60 0xe0       | PUSH1 0xe0       | 224 0x5c60da1b cds 4 cds 32 |                 |
             * 1b            | SHL              | sel cds 4 cds 32            |                 |
             * 36            | CALLDATASIZE     | cds sel cds 4 cds 32        |                 |
             * 52            | MSTORE           | cds 4 cds 32                | sel             |
             * 7f slot       | PUSH32 slot      | s cds 4 cds 32              | sel             |
             * 54            | SLOAD            | beac cds 4 cds 32           | sel             |
             * 5a            | GAS              | g beac cds 4 cds 32         | sel             |
             * fa            | STATICCALL       | succ                        | impl            |
             * ~~~~~~ check calldatasize ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
             * 36            | CALLDATASIZE     | cds succ                    |                 |
             * 14            | EQ               |                             | impl            |
             * 60 0x52       | PUSH1 0x52       |                             | impl            |
             * 57            | JUMPI            |                             | impl            |
             * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
             * 36            | CALLDATASIZE     | cds                         | impl            |
             * 51            | MLOAD            | impl                        | impl            |
             * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
             * 5a         | GAS            | g impl 0 cds 0 0 | [0..calldatasize): calldata     |
             * f4         | DELEGATECALL   | succ             | [0..calldatasize): calldata     |
             *                                                                                  |
             * ::: copy returndata to memory :::::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | rds succ         | [0..calldatasize): calldata     |
             * 60 0x00    | PUSH1 0x00     | 0 rds succ       | [0..calldatasize): calldata     |
             * 60 0x01    | PUSH1 0x01     | 1 0 rds succ     | [0..calldatasize): calldata     |
             * 3e         | RETURNDATACOPY | succ             | [1..returndatasize): returndata |
             *                                                                                  |
             * ::: branch on delegatecall status :::::::::::::::::::::::::::::::::::::::::::::: |
             * 60 0x52    | PUSH1 0x52     | dest succ        | [1..returndatasize): returndata |
             * 57         | JUMPI          |                  | [1..returndatasize): returndata |
             *                                                                                  |
             * ::: delegatecall failed, revert :::::::::::::::::::::::::::::::::::::::::::::::: |
             * 3d         | RETURNDATASIZE | rds              | [1..returndatasize): returndata |
             * 60 0x01    | PUSH1 0x01     | 1 rds            | [1..returndatasize): returndata |
             * fd         | REVERT         |                  | [1..returndatasize): returndata |
             *                                                                                  |
             * ::: delegatecall succeeded, return ::::::::::::::::::::::::::::::::::::::::::::: |
             * 5b         | JUMPDEST       |                  | [1..returndatasize): returndata |
             * 3d         | RETURNDATASIZE | rds              | [1..returndatasize): returndata |
             * 60 0x01    | PUSH1 0x01     | 1 rds            | [1..returndatasize): returndata |
             * f3         | RETURN         |                  | [1..returndatasize): returndata |
             * ---------------------------------------------------------------------------------+
             */
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon))))
            instance := create(value, 0x07, 0x79)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Deploys a deterministic ERC1967I beacon proxy with `salt`.
    function deployDeterministicERC1967IBeaconProxy(address beacon, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = deployDeterministicERC1967IBeaconProxy(0, beacon, salt);
    }

    /// @dev Deploys a deterministic ERC1967I beacon proxy with `salt`.
    /// Deposits `value` ETH during deployment.
    function deployDeterministicERC1967IBeaconProxy(uint256 value, address beacon, bytes32 salt)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon))))
            instance := create2(value, 0x07, 0x79, salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Creates a deterministic ERC1967I beacon proxy with `salt`.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967IBeaconProxy(address beacon, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicERC1967IBeaconProxy(0, beacon, salt);
    }

    /// @dev Creates a deterministic ERC1967I beacon proxy with `salt`.
    /// Deposits `value` ETH during deployment.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967IBeaconProxy(uint256 value, address beacon, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon))))
            // Compute and store the bytecode hash.
            mstore(add(m, 0x35), keccak256(0x07, 0x79))
            mstore(m, shl(88, address()))
            mstore8(m, 0xff) // Write the prefix.
            mstore(add(m, 0x15), salt)
            instance := keccak256(m, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, 0x07, 0x79, salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Returns the initialization code of the ERC1967I beacon proxy.
    function initCodeERC1967IBeaconProxy(address beacon) internal pure returns (bytes memory c) {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            mstore(add(c, 0x79), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(add(c, 0x59), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(add(c, 0x39), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(add(c, 0x1d), beacon)
            mstore(add(c, 0x09), 0x60573d8160223d3973)
            mstore(add(c, 0x99), 0)
            mstore(c, 0x79) // Store the length.
            mstore(0x40, add(c, 0xa0)) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the ERC1967I beacon proxy.
    function initCodeHashERC1967IBeaconProxy(address beacon) internal pure returns (bytes32 hash) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(0x40, 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(0x20, 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(0x04, or(shl(160, 0x60573d8160223d3973), shr(96, shl(96, beacon))))
            hash := keccak256(0x07, 0x79)
            mstore(0x40, m) // Restore the free memory pointer.
            mstore(0x60, 0) // Restore the zero slot.
        }
    }

    /// @dev Returns the address of the ERC1967I beacon proxy, with `salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddressERC1967IBeaconProxy(
        address beacon,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHashERC1967IBeaconProxy(beacon);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*    ERC1967I BEACON PROXY WITH IMMUTABLE ARGS OPERATIONS    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Deploys a ERC1967I beacon proxy with `args.
    function deployERC1967IBeaconProxy(address beacon, bytes memory args)
        internal
        returns (address instance)
    {
        instance = deployERC1967IBeaconProxy(0, beacon, args);
    }

    /// @dev Deploys a ERC1967I beacon proxy with `args.
    /// Deposits `value` ETH during deployment.
    function deployERC1967IBeaconProxy(uint256 value, address beacon, bytes memory args)
        internal
        returns (address instance)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n))
            mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(add(m, 0x14), beacon)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`.
            mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n)))
            instance := create(value, add(m, 0x16), add(n, 0x7a))
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Deploys a deterministic ERC1967I beacon proxy with `args` and `salt`.
    function deployDeterministicERC1967IBeaconProxy(address beacon, bytes memory args, bytes32 salt)
        internal
        returns (address instance)
    {
        instance = deployDeterministicERC1967IBeaconProxy(0, beacon, args, salt);
    }

    /// @dev Deploys a deterministic ERC1967I beacon proxy with `args` and `salt`.
    /// Deposits `value` ETH during deployment.
    function deployDeterministicERC1967IBeaconProxy(
        uint256 value,
        address beacon,
        bytes memory args,
        bytes32 salt
    ) internal returns (address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n))
            mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(add(m, 0x14), beacon)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`.
            mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n)))
            instance := create2(value, add(m, 0x16), add(n, 0x7a), salt)
            if iszero(instance) {
                mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Creates a deterministic ERC1967I beacon proxy with `args` and `salt`.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967IBeaconProxy(address beacon, bytes memory args, bytes32 salt)
        internal
        returns (bool alreadyDeployed, address instance)
    {
        return createDeterministicERC1967IBeaconProxy(0, beacon, args, salt);
    }

    /// @dev Creates a deterministic ERC1967I beacon proxy with `args` and `salt`.
    /// Deposits `value` ETH during deployment.
    /// Note: This method is intended for use in ERC4337 factories,
    /// which are expected to NOT revert if the proxy is already deployed.
    function createDeterministicERC1967IBeaconProxy(
        uint256 value,
        address beacon,
        bytes memory args,
        bytes32 salt
    ) internal returns (bool alreadyDeployed, address instance) {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            let n := mload(args)
            pop(staticcall(gas(), 4, add(args, 0x20), n, add(m, 0x90), n))
            mstore(add(m, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(add(m, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(add(m, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(add(m, 0x14), beacon)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`.
            mstore(add(m, gt(n, 0xffa8)), add(0xfe6100573d8160233d3973, shl(56, n)))
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, keccak256(add(m, 0x16), add(n, 0x7a)))
            mstore(0x01, shl(96, address()))
            mstore(0x15, salt)
            instance := keccak256(0x00, 0x55)
            for {} 1 {} {
                if iszero(extcodesize(instance)) {
                    instance := create2(value, add(m, 0x16), add(n, 0x7a), salt)
                    if iszero(instance) {
                        mstore(0x00, 0x30116425) // `DeploymentFailed()`.
                        revert(0x1c, 0x04)
                    }
                    break
                }
                alreadyDeployed := 1
                if iszero(value) { break }
                if iszero(call(gas(), instance, value, codesize(), 0x00, codesize(), 0x00)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                break
            }
            mstore(0x35, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the initialization code of the ERC1967I beacon proxy with `args`.
    function initCodeERC1967IBeaconProxy(address beacon, bytes memory args)
        internal
        pure
        returns (bytes memory c)
    {
        /// @solidity memory-safe-assembly
        assembly {
            c := mload(0x40)
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffa8))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(c, 0x9a), i), mload(add(add(args, 0x20), i)))
            }
            mstore(add(c, 0x7a), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(add(c, 0x5a), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(add(c, 0x3a), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(add(c, 0x1e), beacon)
            mstore(add(c, 0x0a), add(0x6100573d8160233d3973, shl(56, n)))
            mstore(add(c, add(n, 0x9a)), 0)
            mstore(c, add(n, 0x7a)) // Store the length.
            mstore(0x40, add(c, add(n, 0xba))) // Allocate memory.
        }
    }

    /// @dev Returns the initialization code hash of the ERC1967I beacon proxy with `args`.
    function initCodeHashERC1967IBeaconProxy(address beacon, bytes memory args)
        internal
        pure
        returns (bytes32 hash)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let c := mload(0x40) // Cache the free memory pointer.
            let n := mload(args)
            // Do a out-of-gas revert if `n` is greater than `0xffff - 0x57 = 0xffa8`.
            returndatacopy(returndatasize(), returndatasize(), gt(n, 0xffa8))
            for { let i := 0 } lt(i, n) { i := add(i, 0x20) } {
                mstore(add(add(c, 0x90), i), mload(add(add(args, 0x20), i)))
            }
            mstore(add(c, 0x70), 0x3d50545afa361460525736515af43d600060013e6052573d6001fd5b3d6001f3)
            mstore(add(c, 0x50), 0x527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b3513)
            mstore(add(c, 0x30), 0x60195155f3363d3d373d3d363d602036600436635c60da1b60e01b36)
            mstore(add(c, 0x14), beacon)
            mstore(c, add(0x6100573d8160233d3973, shl(56, n)))
            hash := keccak256(add(c, 0x16), add(n, 0x7a))
        }
    }

    /// @dev Returns the address of the ERC1967I beacon proxy, with  `args` and salt` by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddressERC1967IBeaconProxy(
        address beacon,
        bytes memory args,
        bytes32 salt,
        address deployer
    ) internal pure returns (address predicted) {
        bytes32 hash = initCodeHashERC1967IBeaconProxy(beacon, args);
        predicted = predictDeterministicAddress(hash, salt, deployer);
    }

    /// @dev Equivalent to `argsOnERC1967IBeaconProxy(instance, start, 2 ** 256 - 1)`.
    function argsOnERC1967IBeaconProxy(address instance) internal view returns (bytes memory args) {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            mstore(args, and(0xffffffffff, sub(extcodesize(instance), 0x57))) // Store the length.
            extcodecopy(instance, add(args, 0x20), 0x57, add(mload(args), 0x20))
            mstore(0x40, add(mload(args), add(args, 0x40))) // Allocate memory.
        }
    }

    /// @dev Equivalent to `argsOnERC1967IBeaconProxy(instance, start, 2 ** 256 - 1)`.
    function argsOnERC1967IBeaconProxy(address instance, uint256 start)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            let n := and(0xffffffffff, sub(extcodesize(instance), 0x57))
            let l := sub(n, and(0xffffff, mul(lt(start, n), start)))
            extcodecopy(instance, args, add(start, 0x37), add(l, 0x40))
            mstore(args, mul(sub(n, start), lt(start, n))) // Store the length.
            mstore(0x40, add(args, add(0x40, mload(args)))) // Allocate memory.
        }
    }

    /// @dev Returns a slice of the immutable arguments on `instance` from `start` to `end`.
    /// `start` and `end` will be clamped to the range `[0, args.length]`.
    /// The `instance` MUST be deployed via the ERC1967I beacon proxy with immutable args functions.
    /// Otherwise, the behavior is undefined.
    /// Out-of-gas reverts if `instance` does not have any code.
    function argsOnERC1967IBeaconProxy(address instance, uint256 start, uint256 end)
        internal
        view
        returns (bytes memory args)
    {
        /// @solidity memory-safe-assembly
        assembly {
            args := mload(0x40)
            if iszero(lt(end, 0xffff)) { end := 0xffff }
            let d := mul(sub(end, start), lt(start, end))
            extcodecopy(instance, args, add(start, 0x37), add(d, 0x20))
            if iszero(and(0xff, mload(add(args, d)))) {
                let n := sub(extcodesize(instance), 0x57)
                returndatacopy(returndatasize(), returndatasize(), shr(40, n))
                d := mul(gt(n, start), sub(d, mul(gt(end, n), sub(end, n))))
            }
            mstore(args, d) // Store the length.
            mstore(add(add(args, 0x20), d), 0) // Zeroize the slot after the bytes.
            mstore(0x40, add(add(args, 0x40), d)) // Allocate memory.
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      OTHER OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `address(0)` if the implementation address cannot be determined.
    function implementationOf(address instance) internal view returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            for { extcodecopy(instance, 0x00, 0x00, 0x57) } 1 {} {
                if mload(0x2d) {
                    // ERC1967I and ERC1967IBeaconProxy detection.
                    if or(
                        eq(keccak256(0x00, 0x52), ERC1967I_CODE_HASH),
                        eq(keccak256(0x00, 0x57), ERC1967I_BEACON_PROXY_CODE_HASH)
                    ) {
                        pop(staticcall(gas(), instance, 0x00, 0x01, 0x00, 0x20))
                        result := mload(0x0c)
                        break
                    }
                }
                // 0age clone detection.
                result := mload(0x0b)
                codecopy(0x0b, codesize(), 0x14) // Zeroize the 20 bytes for the address.
                if iszero(xor(keccak256(0x00, 0x2c), CLONE_CODE_HASH)) { break }
                mstore(0x0b, result) // Restore the zeroized memory.
                // CWIA detection.
                result := mload(0x0a)
                codecopy(0x0a, codesize(), 0x14) // Zeroize the 20 bytes for the address.
                if iszero(xor(keccak256(0x00, 0x2d), CWIA_CODE_HASH)) { break }
                mstore(0x0a, result) // Restore the zeroized memory.
                // PUSH0 clone detection.
                result := mload(0x09)
                codecopy(0x09, codesize(), 0x14) // Zeroize the 20 bytes for the address.
                result := shr(xor(keccak256(0x00, 0x2d), PUSH0_CLONE_CODE_HASH), result)
                break
            }
            result := shr(96, result)
            mstore(0x37, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Returns the address when a contract with initialization code hash,
    /// `hash`, is deployed with `salt`, by `deployer`.
    /// Note: The returned result has dirty upper 96 bits. Please clean if used in assembly.
    function predictDeterministicAddress(bytes32 hash, bytes32 salt, address deployer)
        internal
        pure
        returns (address predicted)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and store the bytecode hash.
            mstore8(0x00, 0xff) // Write the prefix.
            mstore(0x35, hash)
            mstore(0x01, shl(96, deployer))
            mstore(0x15, salt)
            predicted := keccak256(0x00, 0x55)
            mstore(0x35, 0) // Restore the overwritten part of the free memory pointer.
        }
    }

    /// @dev Requires that `salt` starts with either the zero address or `by`.
    function checkStartsWith(bytes32 salt, address by) internal pure {
        /// @solidity memory-safe-assembly
        assembly {
            // If the salt does not start with the zero address or `by`.
            if iszero(or(iszero(shr(96, salt)), eq(shr(96, shl(96, by)), shr(96, salt)))) {
                mstore(0x00, 0x0c4549ef) // `SaltDoesNotStartWith()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns the `bytes32` at `offset` in `args`, without any bounds checks.
    /// To load an address, you can use `address(bytes20(argLoad(args, offset)))`.
    function argLoad(bytes memory args, uint256 offset) internal pure returns (bytes32 result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := mload(add(add(args, 0x20), offset))
        }
    }
}

/Users/z/tacit/contracts/lib/solady/src/utils/ReentrancyGuardTransient.sol

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

/// @notice Reentrancy guard mixin (transient storage variant).
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuardTransient.sol)
///
/// @dev Note: This implementation utilizes the `TSTORE` and `TLOAD` opcodes.
/// Please ensure that the chain you are deploying on supports them.
abstract contract ReentrancyGuardTransient {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Unauthorized reentrant call.
    error Reentrancy();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                          STORAGE                           */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to: `uint32(bytes4(keccak256("Reentrancy()"))) | 1 << 71`.
    /// 9 bytes is large enough to avoid collisions in practice,
    /// but not too large to result in excessive bytecode bloat.
    uint256 private constant _REENTRANCY_GUARD_SLOT = 0x8000000000ab143c06;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      REENTRANCY GUARD                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Guards a function from reentrancy.
    modifier nonReentrant() virtual {
        if (_useTransientReentrancyGuardOnlyOnMainnet()) {
            uint256 s = _REENTRANCY_GUARD_SLOT;
            if (block.chainid == 1) {
                /// @solidity memory-safe-assembly
                assembly {
                    if tload(s) {
                        mstore(0x00, s) // `Reentrancy()`.
                        revert(0x1c, 0x04)
                    }
                    tstore(s, address())
                }
            } else {
                /// @solidity memory-safe-assembly
                assembly {
                    if eq(sload(s), address()) {
                        mstore(0x00, s) // `Reentrancy()`.
                        revert(0x1c, 0x04)
                    }
                    sstore(s, address())
                }
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                if tload(_REENTRANCY_GUARD_SLOT) {
                    mstore(0x00, 0xab143c06) // `Reentrancy()`.
                    revert(0x1c, 0x04)
                }
                tstore(_REENTRANCY_GUARD_SLOT, address())
            }
        }
        _;
        if (_useTransientReentrancyGuardOnlyOnMainnet()) {
            uint256 s = _REENTRANCY_GUARD_SLOT;
            if (block.chainid == 1) {
                /// @solidity memory-safe-assembly
                assembly {
                    tstore(s, 0)
                }
            } else {
                /// @solidity memory-safe-assembly
                assembly {
                    sstore(s, s)
                }
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                tstore(_REENTRANCY_GUARD_SLOT, 0)
            }
        }
    }

    /// @dev Guards a view function from read-only reentrancy.
    modifier nonReadReentrant() virtual {
        if (_useTransientReentrancyGuardOnlyOnMainnet()) {
            uint256 s = _REENTRANCY_GUARD_SLOT;
            if (block.chainid == 1) {
                /// @solidity memory-safe-assembly
                assembly {
                    if tload(s) {
                        mstore(0x00, s) // `Reentrancy()`.
                        revert(0x1c, 0x04)
                    }
                }
            } else {
                /// @solidity memory-safe-assembly
                assembly {
                    if eq(sload(s), address()) {
                        mstore(0x00, s) // `Reentrancy()`.
                        revert(0x1c, 0x04)
                    }
                }
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                if tload(_REENTRANCY_GUARD_SLOT) {
                    mstore(0x00, 0xab143c06) // `Reentrancy()`.
                    revert(0x1c, 0x04)
                }
            }
        }
        _;
    }

    /// @dev For widespread compatibility with L2s.
    /// Only Ethereum mainnet is expensive anyways.
    function _useTransientReentrancyGuardOnlyOnMainnet() internal view virtual returns (bool) {
        return true;
    }
}

/Users/z/tacit/contracts/lib/solady/src/utils/SafeTransferLib.sol

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

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
    /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
    /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
    address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) {
                    revert(codesize(), codesize())
                } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {

            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
    /// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
    /// and upon failure, deploys a minimal vault to accrue the ETH.
    function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
        /// @solidity memory-safe-assembly
        assembly {
            to := shr(96, shl(96, to)) // Clean upper 96 bits.
            for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
                let selfBalanceBefore := selfbalance()
                if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if extcodesize(mover) {
                    let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
                    mstore(0x00, to)
                    pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
                    // If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
                    if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
                    // Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
                    if lt(selfBalanceBefore, selfbalance()) { invalid() }
                }
                let m := mload(0x40)
                // If the mover is missing or bricked, deploy a minimal vault
                // that withdraws all ETH to `to` when being called only by `to`.
                // forgefmt: disable-next-item
                mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
                mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
                // Compute and store the bytecode hash.
                mstore8(0x00, 0xff) // Write the prefix.
                mstore(0x35, keccak256(m, 0x40))
                mstore(0x01, shl(96, address())) // Deployer.
                mstore(0x15, 0) // Salt.
                vault := keccak256(0x00, 0x55)
                pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
                // The vault returns a single word on success. Failure reverts with empty data.
                if iszero(returndatasize()) {
                    if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
                }
                mstore(0x40, m) // Restore the free memory pointer.
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount := mul( // The arguments of `mul` are evaluated from right to left.
                mload(0x20),
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                )
            )
        }
    }

    /// @dev Performs a `token.balanceOf(account)` check.
    /// `implemented` denotes whether the `token` implements `balanceOf`.
    /// `amount` is zero if the `token` does not implement `balanceOf`.
    function checkBalanceOf(address token, address account)
        internal
        view
        returns (bool implemented, uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            implemented := and( // The arguments of `and` are evaluated from right to left.
                gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
            )
            amount := mul(mload(0x20), implemented)
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
                mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))
            ) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0x84, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}

src/ConfidentialRouter.sol

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

import {LibClone} from "solady/utils/LibClone.sol";
import {ReentrancyGuardTransient} from "solady/utils/ReentrancyGuardTransient.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";

interface IConfidentialPool {
    function wrap(bytes32 assetId, uint256 amount, bytes32 commit) external payable;
    function settle(bytes calldata publicValues, bytes calldata proofBytes, bytes[] calldata memos) external;
    function canonicalTokenFor(bytes32 assetId) external view returns (address);
    function localAssetOf(bytes32 assetId) external view returns (bytes32);
    function assets(bytes32 assetId)
        external
        view
        returns (
            bool registered,
            address underlying,
            uint256 unitScale,
            bytes32 crossChainLink,
            bool poolMinted,
            uint8 decimals
        );
    function pools(bytes32 poolId)
        external
        view
        returns (
            bool init,
            bytes32 assetA,
            bytes32 assetB,
            uint256 reserveA,
            uint256 reserveB,
            uint32 feeBps,
            uint256 totalShares
        );
    function shieldShares(bytes32 poolId, uint256 shares, bytes32 commit) external returns (bytes32 depositId);
}

/// The plaintext public-AMM periphery (TacitPublicAmm) the pool authorizes for its public path. The router
/// composes it for standard AMM UX; it pulls the router-approved input and forwards the moves to the pool.
interface IPublicAmm {
    function swapPublic(
        bytes32 assetIn,
        bytes32 assetOut,
        uint32 feeBps,
        uint256 amountIn,
        uint256 minAmountOut,
        uint64 deadline,
        address to
    ) external payable returns (uint256 amountOut);
    function createPairAndAddLiquidityPublic(
        bytes32 assetA,
        bytes32 assetB,
        uint32 feeBps,
        uint256 amountA,
        uint256 amountB,
        uint256 minSharesOut,
        uint64 deadline,
        address to
    ) external payable returns (uint256 sharesMinted);
    function removeLiquidityPublicFrom(
        bytes32 assetA,
        bytes32 assetB,
        uint32 feeBps,
        uint256 shares,
        uint256 minAmountA,
        uint256 minAmountB,
        uint64 deadline,
        address owner,
        address to
    ) external returns (uint256 amountLo, uint256 amountHi);
}

/// EIP-2612 permit (USDC and most modern ERC20s; DAI's non-standard permit is NOT this shape — those go
/// through Permit2 instead).
interface IERC2612 {
    function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        external;
}

/// Uniswap Permit2 (AllowanceTransfer) — the canonical singleton at
/// 0x000000000022D473030F116dDEE9F6B43aC78BA3 on every chain. After a ONE-TIME `token.approve(PERMIT2, max)`,
/// every later approval is a signature, for ANY ERC20 (permit-native or not).
interface IPermit2 {
    struct PermitDetails {
        address token;
        uint160 amount;
        uint48 expiration;
        uint48 nonce;
    }

    struct PermitSingle {
        PermitDetails details;
        address spender;
        uint256 sigDeadline;
    }

    struct PermitBatch {
        PermitDetails[] details;
        address spender;
        uint256 sigDeadline;
    }

    function permit(address owner, PermitSingle calldata permitSingle, bytes calldata signature) external;
    function permit(address owner, PermitBatch calldata permitBatch, bytes calldata signature) external;
    function transferFrom(address from, address to, uint160 amount, address token) external;
}

interface IERC20Allowance {
    function allowance(address owner, address spender) external view returns (uint256);
}

/// A pool-minted canonical token commits to the shared cross-chain id it represents via ASSET_ID().
interface IAssetId {
    function ASSET_ID() external view returns (bytes32);
}

/// @title ConfidentialRouter
/// @notice One periphery router for ConfidentialPool, collapsing each common flow into a single transaction
///         with a signature-based approval (EIP-2612 / Permit2 / native msg.value). It spans five families:
///
///           1. ON-RAMP (wrap*) — public→confidential deposit for `commit` (a later settle inserts the leaf
///              + memo). EIP-2612, Permit2, or native ETH.
///           2. PRIVATE PAYMENT (wrapAndSettle* / zapETHToPayment) — wrap to a recipient-owned `commit`, then
///              settle a self-proved batch that consumes the deposit, inserts the recipient's note leaf, and
///              emits the recipient's ECDH memo (the discovery channel). Sender + amount are public; only the
///              RECIPIENT is hidden (`commit` binds the note's owner, not msg.sender).
///           3. PUBLIC AMM (swapPublic* / addLiquidityPublic*) — gasless-approve transparent-lane swap / LP add.
///           4. ZAPS (zap*) — source liquidity from the pinned external aggregator (zRouter) and land it in the
///              confidential pool: cold-start a public LP, shield an LP position into a note, bond it into a
///              farm, or swap-and-wrap any asset into a confidential note / private payment.
///           5. EXTERNAL AMM (swap*ViaZRouter*) — user-directed zRouter swaps with router-held output
///              balance-delta checks, for routes that should stay outside the confidential pool.
///
///  Trust model. The router takes the user's tokens only TRANSIENTLY within a call — it pulls them via the
///  signed approval (or msg.value), hands them to `wrap`/`swapPublic`/`createPair…`/zRouter, and sweeps each
///  NAMED leg (plus the pool's off-ratio refund) back to the caller, so a well-formed call leaves no resting
///  balance. The router is strictly NON-CUSTODIAL: any stray residue — a multi-hop swap's non-named dust, a
///  direct transfer — is not owner-attributed, so the next caller's refund sweeps it; never leave value
///  resting here. Its only standing state is a lazy (infinite) allowance to the immutable, PINNED targets —
///  the POOL and zRouter — safe because those targets are trusted and a well-formed call holds nothing for
///  them to pull beyond what the caller supplied. Both external targets are immutable: the POOL
///  and zRouter addresses are never arbitrary; only the swap SELECTION within zRouter (`zrSwapData`, routed
///  across V2/V3/V4/Curve/zAMM) is the caller's. The note stays the user's: `commit` is forwarded verbatim,
///  the router never sees note secrets, and a malicious/buggy call can at worst revert (atomic) — it cannot
///  redirect or retain funds. A hostile `zrSwapData` yields too little output, the downstream slippage gate
///  (`minShares` / `minAmountOut` / the wrap value binding) reverts, and the whole tx unwinds — fail-closed.
///  nonReentrant on every entrypoint. Settles run with msg.sender == this router, so the private-payment /
///  bond flows MUST be self-proved with NO settler fees (`pv.fees` empty) — fee-free by construction.
///
///  Consolidated (vs a separate wrap + zap router) so a user grants ONE Permit2 allowance that covers every
///  flow, and the shared permit / lazy-approve / asset-id / refund machinery lives once.
///
///  Why periphery, not the pool: ConfidentialPool is immutable + codesize-bound, and permit standards vary
///  (EIP-2612 / DAI-style / Permit2). Keeping this here lets it support every flavor and be replaced as
///  standards evolve, without bloating the value-custody core. The pool needs no change — `wrap` pulls from
///  `msg.sender` and binds the note via `commit`, `settle` is permissionless, and the public-AMM entrypoints
///  credit a caller-chosen `to`.
contract ConfidentialRouter is ReentrancyGuardTransient {
    IConfidentialPool public immutable POOL;
    /// The pool's authorized plaintext public-AMM periphery; the router routes every public swap/add/remove
    /// through it and approves it (not the pool) for the token legs it feeds the public path.
    IPublicAmm internal immutable PUBLIC_AMM;
    IPermit2 public immutable PERMIT2;
    /// zRouter — the pinned external AMM aggregator (0x000000000000FB114709235f1ccBFfb925F600e4). Low-level
    /// called with caller-built swap calldata so any zRouter venue (V2/V3/V4/Curve/zAMM) works without this
    /// router hardcoding one; the address is immutable, so the target is never arbitrary.
    address public immutable ZROUTER;
    /// The exit-executor implementation, deployed once in the constructor. Every exit-and-execute clones a PUSH0
    /// minimal proxy of this at the recipe-bound address; the clone holds ONLY this one exit's funds and runs the
    /// recipe's batch via delegatecall, reading the impl's ROUTER/POOL_ immutables to constrain its targets.
    address public immutable executorImpl;

    /// The tETH shared cross-chain id — the key under which the pool registers native ETH / tETH.
    bytes32 internal constant ETH_ASSET_ID = 0x3cba71e1114af183cdeacc6b8457a474d17529fd28704480ca799d0d03126f34;

    error BadPath();
    error BadTarget();
    error BadPermit2();
    error AmountTooLarge();
    error BadProofIntent();
    error ShortSwapOutput();
    error MaxAmountExceeded();
    error ZRouterCallFailed();

    /// Parameters for a token-in zap (bundled to keep the entrypoints under the stack limit).
    struct TokenZap {
        address tokenB; // the leg sourced from zRouter (paired with the input token A)
        uint32 feeBps;
        uint256 tokenAForSwap; // token A routed through zRouter for tokenB
        uint256 tokenAForLP; // token A for the LP leg
        uint256 tokenBLeg; // exact tokenB for the LP leg (the swap must source at least this)
        uint256 minShares;
        uint64 deadline;
        bytes32 commit; // recipient's LP-share note commitment
    }

    constructor(address pool_, address publicAmm_, address zRouter_, address permit2_) {
        if (
            pool_ == address(0) || pool_.code.length == 0 || publicAmm_ == address(0)
                || permit2_ == address(0) || permit2_.code.length == 0
                || (zRouter_ != address(0) && zRouter_.code.length == 0)
        ) {
            revert BadTarget();
        }
        POOL = IConfidentialPool(pool_);
        PUBLIC_AMM = IPublicAmm(publicAmm_);
        ZROUTER = zRouter_;
        PERMIT2 = IPermit2(permit2_);
        executorImpl = address(new ExitExecutor(pool_)); // one-time deploy; clones bind funds + targets here
    }

    // ──────────────────── Self-sustaining on-ramp: skim an ETH fee inside the atomic wrap+settle ────────────────────
    // The deposit is a PUBLIC tx from the user's wallet (no privacy gain in the relay fronting it), so the user
    // pays gas AND a small ETH fee that pre-pays the relay's wrap PROVE (the settle rides the same tx, so gas is
    // theirs). The fee is ALWAYS ETH — universal for native ETH and any ERC20 (the token rides its own path; the
    // fee is a small ETH leg via msg.value). `_skimFee` forwards it to a CALLER-NAMED relay (permissionless: the
    // dapp names its relay, a third party names theirs, a self-relayer names themselves). fee == 0 ⇒ loss-leader;
    // raise it to fund other ops. The router never custodies it. Note value is unchanged (ADDITIVE, fee on top).
    function _skimFee(uint256 fee, address feeRecipient) internal {
        if (fee != 0) SafeTransferLib.safeTransferETH(feeRecipient, fee);
    }

    // ──────────────────── One-tx on-ramp (wrap only) ────────────────────

    /// @notice One-tx wrap of an EIP-2612 token (e.g. USDC): the user signs an allowance to THIS router and
    ///         the router pulls `amount` and wraps it to `commit`. `permit` is best-effort (try/catch) so a
    ///         front-runner replaying the same permit can't grief the wrap by pre-consuming the nonce — the
    ///         `safeTransferFrom` below still enforces the allowance.
    /// @param token  the underlying ERC20 (already registered in the pool via registerWrapped/Auto).
    /// @param amount underlying amount to escrow (must be a multiple of the asset's unitScale, per the pool).
    /// @param commit the note commitment keccak(Cx‖Cy‖owner) — identical to a direct `wrap`; binds the note
    ///        (and, for a payment, the recipient). The caller computes it; the router only forwards it.
    function wrapWithPermit(
        address token,
        uint256 amount,
        bytes32 commit,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external nonReentrant {
        _wrap2612(token, amount, commit, deadline, v, r, s);
    }

    /// @notice One-tx wrap via Permit2 (works for ANY ERC20 after a one-time `token.approve(PERMIT2, max)`).
    function wrapWithPermit2(
        address token,
        uint256 amount,
        bytes32 commit,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature
    ) external nonReentrant {
        _wrapPermit2(token, amount, commit, permitSingle, signature);
    }

    // ──────────────────── One-tx private payment (wrap + self-proved settle) ────────────────────

    /// @notice One-tx private payment with an EIP-2612 token: wrap `amount` to a recipient-owned `commit`,
    ///         then settle a SELF-PROVED batch that consumes the deposit, inserts the recipient's note leaf,
    ///         and emits the recipient's encrypted memo (via the pool's LeavesInserted). The caller builds
    ///         `publicValues`/`proof`/`memos` off-chain (the proof binds the deposit's value to the leaf).
    /// @dev    The settle runs with msg.sender == this router, so it MUST be a self-proved batch with NO
    ///         settler fees (`pv.fees` empty). A fee in `token` is swept back to the caller below; a fee in
    ///         any other asset would strand (non-custodial residue) — so build fee-free.
    function wrapAndSettleWithPermit(
        address token,
        uint256 amount,
        bytes32 commit,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos,
        address feeRecipient
    ) external payable nonReentrant {
        _wrap2612(token, amount, commit, deadline, v, r, s);
        _relaySettle(publicValues, proof, memos);
        _skimFee(msg.value, feeRecipient); // ETH fee (token wrap has no msg.value) → caller-named relay
        _refund(token, msg.sender); // sweep a (mis-built) settle fee paid in `token` back to the caller
    }

    /// @notice One-tx private payment via Permit2 (any ERC20). See `wrapAndSettleWithPermit` for the
    ///         self-proved / fee-free settle constraint.
    function wrapAndSettleWithPermit2(
        address token,
        uint256 amount,
        bytes32 commit,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos,
        address feeRecipient
    ) external payable nonReentrant {
        _wrapPermit2(token, amount, commit, permitSingle, signature);
        _relaySettle(publicValues, proof, memos);
        _skimFee(msg.value, feeRecipient); // ETH fee (token wrap has no msg.value) → caller-named relay
        _refund(token, msg.sender); // sweep a (mis-built) settle fee paid in `token` back to the caller
    }

    // ──────────────────── Native ETH (no permit — msg.value IS the approval) ────────────────────

    /// @notice One-tx on-ramp of native ETH into a confidential deposit: send `msg.value` and the router
    ///         wraps it to `commit` as the pinned native-ETH (tETH) asset. No permit/approval needed — ETH
    ///         is carried by the call. A later settle inserts the leaf + memo. (Reverts if this deployment
    ///         hasn't registered native ETH, i.e. tETH isn't a pool asset.)
    function wrapETH(bytes32 commit) external payable nonReentrant {
        _wrapETH(msg.value, commit);
    }

    /// @notice One-tx native-ETH private payment — the ETH analog of `wrapAndSettleWithPermit`: wrap
    ///         `msg.value` to a recipient-owned `commit`, then settle the self-proved batch that consumes the
    ///         deposit, inserts the recipient's leaf, and emits the recipient's memo. Same self-proved /
    ///         fee-free settle constraint (the settle runs with msg.sender == this router).
    function wrapAndSettleETH(
        uint256 wrapAmount,
        bytes32 commit,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos,
        address feeRecipient
    ) external payable nonReentrant {
        if (msg.value < wrapAmount) revert BadTarget();
        _wrapETH(wrapAmount, commit);
        _relaySettle(publicValues, proof, memos);
        _skimFee(msg.value - wrapAmount, feeRecipient); // ETH fee on top → caller-named relay (0 ⇒ loss-leader)
        _refundETH(msg.sender); // sweep a (mis-built) settle fee paid in native ETH back to the caller
    }

    // ──────────────────── One-tx CDP open (wrap collateral + mint cUSD proof) ────────────────────

    /// @notice One-tx CDP open with EIP-2612 collateral. The proof MUST consume the wrapped collateral
    ///         deposit and carry OP_CDP_MINT outputs (cUSD debt note + position leaf) under the configured
    ///         controller. This is a named UX entrypoint over the same trust boundary as `wrapAndSettle*`.
    function wrapAndMintCusdWithPermit(
        address token,
        uint256 amount,
        bytes32 commit,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external nonReentrant {
        _requireCdpMintIntent(publicValues);
        _wrap2612(token, amount, commit, deadline, v, r, s);
        _relaySettle(publicValues, proof, memos);
        _refund(token, msg.sender);
    }

    /// @notice One-tx CDP open via Permit2 collateral. See `wrapAndMintCusdWithPermit`.
    function wrapAndMintCusdWithPermit2(
        address token,
        uint256 amount,
        bytes32 commit,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external nonReentrant {
        _requireCdpMintIntent(publicValues);
        _wrapPermit2(token, amount, commit, permitSingle, signature);
        _relaySettle(publicValues, proof, memos);
        _refund(token, msg.sender);
    }

    /// @notice One-tx CDP open with native ETH collateral. See `wrapAndMintCusdWithPermit`.
    function wrapETHAndMintCusd(
        bytes32 commit,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external payable nonReentrant {
        _requireCdpMintIntent(publicValues);
        _wrapETH(msg.value, commit);
        _relaySettle(publicValues, proof, memos);
        _refundETH(msg.sender);
    }

    // ──────────────────── Public AMM swap (gasless approve) ────────────────────

    /// @notice One-tx PUBLIC swap with a gasless approval (EIP-2612): pull `amountIn` of `tokenIn`, swap it
    ///         against the pool's public reserves, and send the output straight to `to`. The amount is public
    ///         (this is the transparent lane; for a hidden-amount swap use the confidential OP_SWAP). The pool
    ///         enforces slippage (`minAmountOut`, in the output's underlying) + `deadline`; `deadline` doubles
    ///         as the permit-signature expiry. Caller passes token ADDRESSES; the router derives the asset ids.
    function swapPublicWithPermit(
        address tokenIn,
        address tokenOut,
        uint32 feeBps,
        uint256 amountIn,
        uint256 minAmountOut,
        uint64 deadline,
        address to,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external nonReentrant returns (uint256 amountOut) {
        if (to == address(this)) revert BadTarget(); // never let the output rest at the router
        _pull2612(tokenIn, amountIn, deadline, v, r, s);
        amountOut =
            PUBLIC_AMM.swapPublic(_poolAssetId(tokenIn), _poolAssetId(tokenOut), feeBps, amountIn, minAmountOut, deadline, to);
    }

    /// @notice One-tx PUBLIC single-hop swap. `tokenIn == address(0)` ⇒ native ETH input (`msg.value` is the
    ///         amount; `amountIn`/`permitSingle`/`signature` ignored). Any other `tokenIn` is pulled via Permit2
    ///         (any ERC20 after a one-time `token.approve(PERMIT2, max)`). Output goes directly to `to`.
    function swapPublicExactIn(
        address tokenIn,
        address tokenOut,
        uint32 feeBps,
        uint256 amountIn,
        uint256 minAmountOut,
        uint64 deadline,
        address to,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature
    ) external payable nonReentrant returns (uint256 amountOut) {
        if (to == address(this)) revert BadTarget(); // never let the output rest at the router
        uint256 value;
        if (tokenIn == address(0)) {
            value = msg.value;
            amountIn = msg.value;
        } else {
            _pullPermit2(tokenIn, amountIn, permitSingle, signature);
        }
        amountOut = PUBLIC_AMM.swapPublic{value: value}(
            _poolAssetId(tokenIn), _poolAssetId(tokenOut), feeBps, amountIn, minAmountOut, deadline, to
        );
        // Sweep any ETH the caller sent on the token-in path (value == 0 there), so a mistaken msg.value is
        // returned rather than left resting at the router for the next _refundETH caller to take.
        _refundETH(msg.sender);
    }

    /// @notice Multi-hop PUBLIC pool swap via Permit2. `path[i]` is the output token of hop i and `fees[i]`
    ///         is that hop's fee tier; input token is the Permit2 token. Intermediate outputs are held only
    ///         long enough to feed the next pool hop, and the final output goes directly to `to`.
    function swapPublicPathWithPermit2(
        address[] calldata path,
        uint32[] calldata fees,
        uint256 amountIn,
        uint256 minAmountOut,
        uint64 deadline,
        address to,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature
    ) external nonReentrant returns (uint256 amountOut) {
        _checkPath(path, fees, to);
        address tokenIn = permitSingle.details.token;
        _pullPermit2(tokenIn, amountIn, permitSingle, signature);
        amountOut = _swapPublicPath(tokenIn, path, fees, amountIn, minAmountOut, deadline, to);

        _refund(tokenIn, msg.sender);
        _refundPath(path, msg.sender);
    }

    /// @notice Multi-hop PUBLIC pool swap with native ETH as the first asset. Each `path` token must be an
    ///         ERC20 output; native ETH is supported as input only, which keeps intermediate routing simple.
    function swapPublicETHPath(
        address[] calldata path,
        uint32[] calldata fees,
        uint256 minAmountOut,
        uint64 deadline,
        address to
    ) external payable nonReentrant returns (uint256 amountOut) {
        _checkPath(path, fees, to);
        amountOut = _swapPublicETHPath(path, fees, msg.value, minAmountOut, deadline, to);

        _refundPath(path, msg.sender);
        _refundETH(msg.sender);
    }

    // ──────────────────── External zRouter swaps (plain AMM routing) ────────────────────

    /// @notice Swap native ETH through the pinned zRouter and send the ERC20 output to `to`. `zrSwapData`
    ///         must direct zRouter output to THIS router; this function transfers only the observed balance
    ///         delta and reverts if it is below `minAmountOut`.
    function swapETHViaZRouter(address tokenOut, uint256 minAmountOut, address to, bytes calldata zrSwapData)
        external
        payable
        nonReentrant
        returns (uint256 amountOut)
    {
        if (tokenOut == address(0) || to == address(0)) revert BadTarget();
        amountOut = _zRouterReceive(tokenOut, msg.value, zrSwapData);
        if (amountOut < minAmountOut) revert ShortSwapOutput();
        SafeTransferLib.safeTransfer(tokenOut, to, amountOut);
        _refund(tokenOut, msg.sender); // sweep any pre-existing residue; the fresh delta went to `to`
        _refundETH(msg.sender);
    }

    /// @notice Swap an ERC20 through the pinned zRouter using Permit2. `zrSwapData` must spend at most
    ///         `amountIn` from this router and send the ERC20 output to THIS router.
    function swapTokenViaZRouterWithPermit2(
        address tokenOut,
        uint256 amountIn,
        uint256 minAmountOut,
        address to,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata zrSwapData
    ) external nonReentrant returns (uint256 amountOut) {
        if (tokenOut == address(0) || to == address(0)) revert BadTarget();
        address tokenIn = permitSingle.details.token;
        _pullPermit2(tokenIn, amountIn, permitSingle, signature);
        _lazyApprove(tokenIn, ZROUTER, amountIn);
        amountOut = _zRouterReceive(tokenOut, 0, zrSwapData);
        if (amountOut < minAmountOut) revert ShortSwapOutput();
        SafeTransferLib.safeTransfer(tokenOut, to, amountOut);
        _refundInOut(tokenIn, tokenOut); // sweep any pre-existing residue; the fresh delta went to `to`
    }

    // ──────────────────── Public AMM liquidity (gasless approve) ────────────────────

    /// @notice One-tx PUBLIC liquidity add via a Permit2 batch (ONE signature for BOTH tokens): pull
    ///         `amountA` of `tokenA` + `amountB` of `tokenB`, lazily create the (canonical) pool if it
    ///         doesn't exist, add liquidity, and credit the LP shares to `to`. The pool pays any off-ratio
    ///         excess of either leg to `to` (the position recipient) directly; the router keeps no balance
    ///         (a sweep below returns only pre-existing residue to the caller). ERC20-only — a native-ETH leg would need a payable variant. `feeBps`/`minSharesOut`/
    ///         `deadline` are the pool's; caller passes token ADDRESSES (the router derives the asset ids).
    function addLiquidityPublicWithPermit2(
        address tokenA,
        address tokenB,
        uint32 feeBps,
        uint256 amountA,
        uint256 amountB,
        uint256 minSharesOut,
        uint64 deadline,
        address to,
        IPermit2.PermitBatch calldata permitBatch,
        bytes calldata signature
    ) external nonReentrant returns (uint256 sharesMinted) {
        if (to == address(this)) revert BadTarget(); // never credit LP shares to the router
        if (amountA > type(uint160).max || amountB > type(uint160).max) {
            revert AmountTooLarge();
        }
        // Bind the batch to the two legs we actually pull (spender, window, and each token's amount),
        // accepting either ordering of the two details entries.
        if (
            permitBatch.spender != address(this) || permitBatch.sigDeadline < block.timestamp
                || permitBatch.details.length != 2
        ) revert BadPermit2();
        bool ab = permitBatch.details[0].token == tokenA && permitBatch.details[1].token == tokenB;
        bool ba = permitBatch.details[0].token == tokenB && permitBatch.details[1].token == tokenA;
        if (ab) {
            if (permitBatch.details[0].amount < amountA || permitBatch.details[1].amount < amountB) {
                revert BadPermit2();
            }
        } else if (ba) {
            if (permitBatch.details[0].amount < amountB || permitBatch.details[1].amount < amountA) {
                revert BadPermit2();
            }
        } else {
            revert BadPermit2();
        }
        try PERMIT2.permit(msg.sender, permitBatch, signature) {} catch {}
        PERMIT2.transferFrom(msg.sender, address(this), uint160(amountA), tokenA);
        PERMIT2.transferFrom(msg.sender, address(this), uint160(amountB), tokenB);
        _lazyApprove(tokenA, address(PUBLIC_AMM), amountA);
        _lazyApprove(tokenB, address(PUBLIC_AMM), amountB);
        sharesMinted = PUBLIC_AMM.createPairAndAddLiquidityPublic(
            _poolAssetId(tokenA), _poolAssetId(tokenB), feeBps, amountA, amountB, minSharesOut, deadline, to
        );
        // The pool pays the off-ratio excess to `to` directly; this only sweeps pre-existing residue.
        _refundInOut(tokenA, tokenB);
    }

    /// @notice Simple native-ETH + ERC20 public LP add. Pulls `tokenAmount` via Permit2, pairs it with
    ///         `msg.value` as the tETH leg, lazily creates the pool if needed, and forwards off-ratio refunds.
    function addLiquidityPublicETHWithPermit2(
        address token,
        uint32 feeBps,
        uint256 tokenAmount,
        uint256 minSharesOut,
        uint64 deadline,
        address to,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature
    ) external payable nonReentrant returns (uint256 sharesMinted) {
        if (to == address(this)) revert BadTarget(); // never credit LP shares to the router
        _pullPermit2(token, tokenAmount, permitSingle, signature);
        sharesMinted = PUBLIC_AMM.createPairAndAddLiquidityPublic{value: msg.value}(
            _poolAssetId(address(0)), _poolAssetId(token), feeBps, msg.value, tokenAmount, minSharesOut, deadline, to
        );
        _refundOutETH(token);
    }

    /// @notice Remove PUBLIC LP shares through a prior `approveLpOperator(router)` on the public-AMM periphery.
    ///         Outputs are sent directly to `to`.
    function removeLiquidityPublic(
        address tokenA,
        address tokenB,
        uint32 feeBps,
        uint256 shares,
        uint256 minAmountA,
        uint256 minAmountB,
        uint64 deadline,
        address to
    ) external nonReentrant returns (uint256 amountLo, uint256 amountHi) {
        if (to == address(0) || to == address(this)) revert BadTarget();
        return PUBLIC_AMM.removeLiquidityPublicFrom(
            _poolAssetId(tokenA), _poolAssetId(tokenB), feeBps, shares, minAmountA, minAmountB, deadline, msg.sender, to
        );
    }

    // ──────────────────── Zap: cold-start a public LP from ETH (external sourcing) ────────────────────

    /// @notice Cold-start zap from native ETH: route `ethToSwap` of `msg.value` through zRouter for `tokenB`
    ///         (via the caller's `zrSwapData`, which MUST send the output to this router), then add the
    ///         remaining ETH + the received `tokenB` into the confidential pool's public LP (tETH/tokenB at
    ///         `feeBps`), crediting shares to `to`. The pool is lazily created on the first add (cold start),
    ///         so the (remaining ETH : received tokenB) ratio sets the initial price — the caller chooses
    ///         `ethToSwap` (and the swap's amounts) to land the price they want. Leftovers go back to the caller.
    /// @param tokenB     the ERC20 other leg (registered in the pool); paired with native ETH (tETH).
    /// @param feeBps     the confidential pool's fee tier for the pair.
    /// @param ethToSwap  how much of msg.value to forward to zRouter for the swap (the rest is the ETH leg).
    /// @param minShares  slippage floor on the LP shares minted (the downstream backstop; set the swap's own
    ///                   amountLimit inside `zrSwapData` too).
    /// @param deadline   expiry for the LP add (the swap's own deadline lives in `zrSwapData`).
    /// @param to         recipient of the LP shares.
    /// @param zrSwapData ABI-encoded zRouter swap call (e.g. swapV2/swapV3/swapV4/swapVZ/swapCurve) for the
    ///                   venue with depth, swapping ETH->tokenB with the output recipient set to THIS router.
    function zapETHIntoLP(
        address tokenB,
        uint32 feeBps,
        uint256 ethToSwap,
        uint256 minShares,
        uint64 deadline,
        address to,
        bytes calldata zrSwapData
    ) external payable nonReentrant returns (uint256 sharesMinted) {
        if (to == address(this)) revert BadTarget(); // never credit LP shares to the router
        uint256 remainingEth = msg.value - ethToSwap; // reverts (underflow) if ethToSwap > msg.value

        uint256 gotB = _zRouterReceive(tokenB, ethToSwap, zrSwapData);

        _lazyApprove(tokenB, address(PUBLIC_AMM), gotB);
        sharesMinted = PUBLIC_AMM.createPairAndAddLiquidityPublic{value: remainingEth}(
            _poolAssetId(address(0)), _poolAssetId(tokenB), feeBps, remainingEth, gotB, minShares, deadline, to
        );

        _refundOutETH(tokenB);
    }

    // ──────────────────── Zap: confidential-output (public entry, shielded position) ────────────────────

    /// @notice Same public entry (ETH → zRouter → LP) as `zapETHIntoLP`, but the LP position is delivered
    ///         CONFIDENTIALLY: the minted shares are shielded into an owner-blinded LP-share NOTE bound to
    ///         `commit`, so the holder can send it privately or bond it into a farm — vs `zapETHIntoLP`, which
    ///         leaves a PUBLIC lpShares balance. The swap + add are still public (amounts/sender visible); only
    ///         the OUTPUT position is shielded. EXACT legs (`ethLeg`, `tokenBLeg`) make the minted share count
    ///         deterministic (the dapp can pre-derive it). Returns the LP-share-note deposit id.
    function zapETHIntoShieldedLP(
        address tokenB,
        uint32 feeBps,
        uint256 ethLeg,
        uint256 tokenBLeg,
        uint256 minShares,
        uint64 deadline,
        bytes32 commit,
        bytes calldata zrSwapData
    ) external payable nonReentrant returns (bytes32 depositId, uint256 sharesMinted) {
        (depositId, sharesMinted) = _zapToShieldedShares(
            tokenB, feeBps, ethLeg, tokenBLeg, minShares, deadline, commit, zrSwapData
        );
        _refundOutETH(tokenB);
    }

    /// @notice One-tx ETH → CONFIDENTIAL farm position: zap into the LP, shield the shares to `commit`, then
    ///         settle the caller's self-proved batch that consumes the LP-share deposit and bonds it
    ///         (OP_LP_BOND → owner-blinded farm-receipt note earning TAC rewards). Deterministic shares (exact
    ///         legs) let the dapp pre-build the bond proof. Self-proved / fee-free settle (msg.sender == this).
    function zapETHIntoFarm(
        address tokenB,
        uint32 feeBps,
        uint256 ethLeg,
        uint256 tokenBLeg,
        uint256 minShares,
        uint64 deadline,
        bytes32 commit,
        bytes calldata zrSwapData,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external payable nonReentrant returns (uint256 sharesMinted) {
        (, sharesMinted) = _zapToShieldedShares(
            tokenB, feeBps, ethLeg, tokenBLeg, minShares, deadline, commit, zrSwapData
        );
        _relaySettle(publicValues, proof, memos);
        _refundOutETH(tokenB);
    }

    /// @notice Token-in analog of `zapETHIntoShieldedLP`: pull token A (Permit2), route `tokenAForSwap` of it
    ///         through zRouter for `tokenB`, add EXACTLY (`tokenAForLP`, `tokenBLeg`) to the LP, and shield the
    ///         shares into an owner-blinded LP-share note bound to `z.commit`. Token A is the Permit2 permit's
    ///         token; both legs ERC20. Leftovers swept to the caller.
    function zapTokenIntoShieldedLP(
        TokenZap calldata z,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata zrSwapData
    ) external nonReentrant returns (bytes32 depositId, uint256 sharesMinted) {
        address tokenA = permitSingle.details.token;
        (depositId, sharesMinted) = _zapTokenToShieldedShares(tokenA, z, permitSingle, signature, zrSwapData);
        _refund(tokenA, msg.sender);
        _refund(z.tokenB, msg.sender);
    }

    /// @notice Token-in analog of `zapETHIntoFarm`: token A → shielded LP-share note → settle the caller's
    ///         self-proved bond (OP_LP_BOND). Same deterministic-shares + self-proved/fee-free settle model.
    function zapTokenIntoFarm(
        TokenZap calldata z,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata zrSwapData,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external nonReentrant returns (uint256 sharesMinted) {
        address tokenA = permitSingle.details.token;
        (, sharesMinted) = _zapTokenToShieldedShares(tokenA, z, permitSingle, signature, zrSwapData);
        _relaySettle(publicValues, proof, memos);
        _refund(tokenA, msg.sender);
        _refund(z.tokenB, msg.sender);
    }

    // ──────────────────── Zap: swap-and-wrap (any asset -> a confidential NOTE) ────────────────────

    /// @notice Swap native ETH to `tokenOut` on zRouter, then WRAP exactly `wrapAmount` of it into the
    ///         confidential pool as a deposit bound to `commit` — pay in ETH but receive a confidential
    ///         `tokenOut` NOTE (single asset, not LP). `commit` is the recipient's note commitment, so this is
    ///         a private swap-and-shield (or the deposit leg of swap-and-pay; see zapETHToPayment). The swap
    ///         must source at least `wrapAmount` (which must be unitScale-aligned for `tokenOut`); leftovers
    ///         (excess tokenOut + unspent ETH) are swept to the caller.
    function zapETHToShieldedNote(address tokenOut, uint256 wrapAmount, bytes32 commit, bytes calldata zrSwapData)
        external
        payable
        nonReentrant
    {
        _swapAndWrap(tokenOut, wrapAmount, commit, zrSwapData);
        _refundOutETH(tokenOut);
    }

    /// @notice Swap native ETH to the pool's canonical ERC20 for `assetId`, then burn/wrap it into a
    ///         confidential note. This is the cBTC/cUSD launch path: callers pass the stable shared id
    ///         (e.g. CBTC_ZK_ASSET_ID or the CollateralEngine-derived cUSD id), while the router resolves the
    ///         pool-local wrap id and verifies the canonical token before touching funds.
    function zapETHToCanonicalNote(bytes32 assetId, uint256 wrapAmount, bytes32 commit, bytes calldata zrSwapData)
        external
        payable
        nonReentrant
    {
        address tokenOut = _swapAndWrapCanonical(assetId, wrapAmount, commit, zrSwapData, msg.value);
        _refundOutETH(tokenOut);
    }

    /// @notice Token-in analog of `zapETHToCanonicalNote`: pull any ERC20 via Permit2, route `amountIn` of it
    ///         through zRouter into the pool's canonical ERC20 for `assetId`, then burn/wrap `wrapAmount` into
    ///         a confidential note. Excess input/output is swept back to the caller.
    function zapTokenToCanonicalNoteWithPermit2(
        bytes32 assetId,
        uint256 amountIn,
        uint256 wrapAmount,
        bytes32 commit,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata zrSwapData
    ) external nonReentrant {
        address tokenIn = permitSingle.details.token;
        _pullPermit2(tokenIn, amountIn, permitSingle, signature);
        _lazyApprove(tokenIn, ZROUTER, amountIn);
        address tokenOut = _swapAndWrapCanonical(assetId, wrapAmount, commit, zrSwapData, 0);
        _refundInOut(tokenIn, tokenOut);
    }

    /// @notice One-tx private payment funded by ETH in a different asset: swap ETH -> `tokenOut`, wrap exactly
    ///         `wrapAmount` to the recipient's `commit`, then settle the caller's self-proved batch consuming
    ///         the deposit into the recipient's note (+ memo). `wrapAmount` fixes the note value so the dapp
    ///         pre-derives the deposit id for the settle. Self-proved / fee-free settle (msg.sender == this).
    function zapETHToPayment(
        address tokenOut,
        uint256 wrapAmount,
        bytes32 commit,
        bytes calldata zrSwapData,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external payable nonReentrant {
        _swapAndWrap(tokenOut, wrapAmount, commit, zrSwapData);
        _relaySettle(publicValues, proof, memos);
        _refundOutETH(tokenOut);
    }

    /// @notice One-tx CDP open funded by native ETH through zRouter: swap ETH -> collateral token, wrap
    ///         exactly `wrapAmount`, then settle a CDP-mint proof consuming that deposit. This is the CDP
    ///         analog of `zapETHToPayment`, with a light publicValues guard requiring OP_CDP_MINT intent.
    function zapETHToCdpMint(
        address tokenOut,
        uint256 wrapAmount,
        bytes32 commit,
        bytes calldata zrSwapData,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external payable nonReentrant {
        _requireCdpMintIntent(publicValues);
        _swapAndWrap(tokenOut, wrapAmount, commit, zrSwapData);
        _relaySettle(publicValues, proof, memos);
        _refundOutETH(tokenOut);
    }

    /// @notice Permit2 token-in CDP zap: pull `amountIn`, route it through zRouter into `tokenOut`, wrap
    ///         exactly `wrapAmount`, then settle the CDP mint proof. Excess input/output is swept back.
    function zapTokenToCdpMintWithPermit2(
        address tokenOut,
        uint256 amountIn,
        uint256 wrapAmount,
        bytes32 commit,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata zrSwapData,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external nonReentrant {
        _requireCdpMintIntent(publicValues);
        address tokenIn = permitSingle.details.token;
        _pullPermit2(tokenIn, amountIn, permitSingle, signature);
        _lazyApprove(tokenIn, ZROUTER, amountIn);
        _swapAndWrapWithValue(tokenOut, wrapAmount, commit, zrSwapData, 0);
        _relaySettle(publicValues, proof, memos);
        _refundInOut(tokenIn, tokenOut);
    }

    /// @notice Canonical-asset CDP zap for cBTC/cUSD launch UX: callers pass the shared `assetId` (for
    ///         example cBTC), and the router resolves the local canonical token before wrapping collateral.
    function zapETHToCanonicalCdpMint(
        bytes32 assetId,
        uint256 wrapAmount,
        bytes32 commit,
        bytes calldata zrSwapData,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external payable nonReentrant {
        _requireCdpMintIntent(publicValues);
        address tokenOut = _swapAndWrapCanonical(assetId, wrapAmount, commit, zrSwapData, msg.value);
        _relaySettle(publicValues, proof, memos);
        _refundOutETH(tokenOut);
    }

    /// @notice Permit2 token-in analog of `zapETHToCanonicalCdpMint`.
    function zapTokenToCanonicalCdpMintWithPermit2(
        bytes32 assetId,
        uint256 amountIn,
        uint256 wrapAmount,
        bytes32 commit,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata zrSwapData,
        bytes calldata publicValues,
        bytes calldata proof,
        bytes[] calldata memos
    ) external nonReentrant {
        _requireCdpMintIntent(publicValues);
        address tokenIn = permitSingle.details.token;
        _pullPermit2(tokenIn, amountIn, permitSingle, signature);
        _lazyApprove(tokenIn, ZROUTER, amountIn);
        address tokenOut = _swapAndWrapCanonical(assetId, wrapAmount, commit, zrSwapData, 0);
        _relaySettle(publicValues, proof, memos);
        _refundInOut(tokenIn, tokenOut);
    }

    // ──────────────────── Internals: permit pulls + wrap ────────────────────

    /// Pull `amount` of an EIP-2612 token from the caller (its signed allowance) into the router, then lazily
    /// approve the pool. Shared by wrap + swap. `permit` is best-effort (try/catch) so a replayed permit can't
    /// grief the call — the `safeTransferFrom` still enforces the allowance.
    function _pull2612(address token, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) internal {
        try IERC2612(token).permit(msg.sender, address(this), amount, deadline, v, r, s) {} catch {}
        SafeTransferLib.safeTransferFrom(token, msg.sender, address(this), amount);
        _lazyApprove(token, address(PUBLIC_AMM), amount);
    }

    /// Permit2 analog of `_pull2612` (any ERC20 after a one-time `token.approve(PERMIT2, max)`).
    function _pullPermit2(
        address token,
        uint256 amount,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature
    ) internal {
        if (amount > type(uint160).max) revert AmountTooLarge(); // Permit2 amounts are uint160
        // Bind the signed permit to what we actually pull: the wallet-displayed token/spender/amount/window
        // must match this transfer, so a stale or mismatched permit can't be steered onto a different asset.
        if (
            permitSingle.details.token != token || permitSingle.spender != address(this)
                || permitSingle.details.amount < amount || permitSingle.sigDeadline < block.timestamp
        ) revert BadPermit2();
        try PERMIT2.permit(msg.sender, permitSingle, signature) {} catch {}
        PERMIT2.transferFrom(msg.sender, address(this), uint160(amount), token);
        _lazyApprove(token, address(PUBLIC_AMM), amount);
    }

    function _wrap2612(address token, uint256 amount, bytes32 commit, uint256 deadline, uint8 v, bytes32 r, bytes32 s)
        internal
    {
        _pull2612(token, amount, deadline, v, r, s);
        _lazyApprove(token, address(POOL), amount); // wrap pulls into the pool
        POOL.wrap(_poolAssetId(token), amount, commit);
    }

    function _wrapPermit2(
        address token,
        uint256 amount,
        bytes32 commit,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature
    ) internal {
        _pullPermit2(token, amount, permitSingle, signature);
        _lazyApprove(token, address(POOL), amount); // wrap pulls into the pool
        POOL.wrap(_poolAssetId(token), amount, commit);
    }

    /// Forward `amount` of native ETH to the pool's wrap (no approval — the pool checks msg.value == amount
    /// for the native-ETH asset). The native-ETH asset id is `_poolAssetId(address(0))` — the same id the pool
    /// registered tETH under.
    function _wrapETH(uint256 amount, bytes32 commit) internal {
        POOL.wrap{value: amount}(_poolAssetId(address(0)), amount, commit);
    }

    // ──────────────────── Exit-and-execute (shielded exit → recipe-bound batch executor, atomic) ──────────

    /// One step of an exit batch. The ephemeral executor escrow runs `calls` in order. Before each call, if
    /// `token`/`amount` are set it either pushes (transfer) or approves that token to `target`, then low-level
    /// calls `target` with `value` ETH and `data`. `push == false` ⇒ APPROVE (the target pulls via
    /// transferFrom — zRouter swapV2/V3/…); `push == true` ⇒ PUSH (transfer the input to the target first — the
    /// execute/snwap conduit, which routes from its own balance, or a supply/deposit that pulls nothing).
    struct ExitCall {
        address target;
        uint256 value;
        address token;
        uint256 amount;
        bool push;
        bytes data;
    }

    /// A bound exit recipe. The pool unwraps `exitedAsset` TO `escrowAddressFor(recipe)` — a CREATE2 address
    /// keyed by the recipe hash — so the PROOF itself commits the recipe (via its existing withdrawal recipient
    /// field). A front-runner cannot redirect the output or alter the batch without changing that address; since
    /// the proof's funds went to the honest caller's escrow, an attacker's call reverts on an empty/short escrow.
    struct ExitRecipe {
        bytes32 exitedAsset; // asset id the proof withdraws to the executor escrow (ERC20 or native ETH)
        address feeAsset; // the proof's in-proof fee-leg asset; the router forwards that fee to the settling
            // relayer (msg.sender). address(0) = ETH. Self-submit: a fee-0 proof forwards nothing.
        address finalRecipient; // destination of the swept outputs
        uint64 deadline; // recipe expiry (unix secs)
        uint256 nonce; // makes the escrow address one-shot
        ExitCall[] calls; // run in order by the ephemeral executor escrow
        address[] sweepTokens; // outputs delivered to finalRecipient (address(0) = native ETH)
        uint256[] minOuts; // per-sweepToken floor (same length as sweepTokens)
    }

    error NotExpired();
    error EscrowEmpty();
    error ExitExpired();

    /// The recipe's CREATE2 salt — keccak of its full ABI encoding, so any change maps to a different
    /// escrow. One implementation shared by address prediction and the clone deploys.
    function _recipeSalt(ExitRecipe calldata recipe) internal pure returns (bytes32) {
        return keccak256(abi.encode(recipe));
    }

    /// The deterministic escrow address the caller MUST set as the proof's withdrawal recipient for `recipe`.
    /// It is the PUSH0 minimal-proxy clone of `executorImpl` at salt = keccak(abi.encode(recipe)), deployed by
    /// this router — so a tampered recipe maps to a different, empty address (the front-run defense).
    function escrowAddressFor(ExitRecipe calldata recipe) public view returns (address) {
        return LibClone.predictDeterministicAddress_PUSH0(executorImpl, _recipeSalt(recipe), address(this));
    }

    /// @notice Atomically exit a note out of the pool and run a recipe-bound BATCH from a per-recipe ephemeral
    ///         escrow that holds ONLY this exit's funds. The settle proof MUST withdraw `recipe.exitedAsset` to
    ///         `escrowAddressFor(recipe)`, which binds the whole recipe to the proof (defeating front-running).
    ///         The proof's in-proof fee leg (in `recipe.feeAsset`) is forwarded to the settling relayer
    ///         (msg.sender); the escrow runs the batch and sweeps each output to `finalRecipient`. The router
    ///         never holds the exit funds — arbitrary batched calls are blast-contained to this single exit.
    function exitAndExecute(
        bytes calldata publicValues,
        bytes calldata proofBytes,
        bytes[] calldata memos,
        ExitRecipe calldata recipe
    ) external nonReentrant {
        // Recipe shape (finalRecipient / deadline / sweep-len) is validated in `_activate` after settle; a bad
        // recipe reverts the whole atomic tx there, so no pre-settle re-check is needed. Only the early
        // asset-registered guard stays (native ETH is registered with tokenIn == 0).
        (bool registered,,,,,) = POOL.assets(recipe.exitedAsset);
        if (!registered) revert BadTarget();

        // Bind every unwrap payout to the recipe escrow. `relayPaid` below is measured as the router's own
        // post-settle balance delta and forwarded wholesale to msg.sender as the relay fee; without this, a
        // proof that withdrew principal TO the router (rather than the escrow) would have that principal
        // mis-forwarded as "fee". Requiring field-6 (`withdrawals`) recipients to equal the escrow confines the
        // router's balance change to the in-proof fee leg. Escrow is a pure function of the recipe, so this is
        // checkable pre-settle. Each `Withdrawal` is 3 static words (assetId, recipient, value); the recipient is
        // the second. Fail-closed: a malformed tuple reads out-of-slice calldata as zero (≠ escrow ⇒ BadTarget)
        // or a bogus length runs out of gas, and the pool re-decodes the same tuple regardless.
        address _escrow = escrowAddressFor(recipe);
        assembly ("memory-safe") {
            let ts := calldataload(publicValues.offset)
            // field 6 (withdrawals) offset lives at tuple word 6 (6*32 = 192), relative to the tuple start.
            let base := add(add(publicValues.offset, ts), calldataload(add(add(publicValues.offset, ts), 192)))
            let n := calldataload(base)
            // Mask escrow to 160 bits: as a Solidity `address` local its upper bits are not guaranteed clean on
            // the stack, and the recipient word below is masked to the address the pool credits on abi.decode.
            let e := and(_escrow, 0xffffffffffffffffffffffffffffffffffffffff)
            for { let i := 0 } lt(i, n) { i := add(i, 1) } {
                // element i recipient = base + 32 (len word) + i*96 + 32 (past assetId).
                if iszero(eq(and(calldataload(add(base, add(64, mul(i, 96)))), 0xffffffffffffffffffffffffffffffffffffffff), e)) {
                    mstore(0x00, 0x13496fda) // BadTarget()
                    revert(0x1c, 0x04)
                }
            }
        }

        // Settle: the proof unwraps `exitedAsset` to the recipe-bound escrow, and pays its in-proof fee leg to
        // msg.sender == this router. Snapshot feeAsset BEFORE settle so the fee can be isolated + forwarded.
        uint256 feeBefore = _selfBal(recipe.feeAsset);
        POOL.settle(publicValues, proofBytes, memos);

        // Forward the proof's in-proof fee to the relayer (the caller). feeAsset is recipe-bound and the amount
        // is the proof's own fee leg: a relayer can't inflate it. A self-submitted (fee-0) proof forwards nothing.
        uint256 relayPaid = _selfBal(recipe.feeAsset) - feeBefore;
        if (relayPaid != 0) _deliver(recipe.feeAsset, msg.sender, relayPaid);

        // Deploy the escrow at the recipe-bound address (it now holds the unwrapped exit funds) and run the
        // batch. A tampered recipe ⇒ a different address with no funds ⇒ the batch reverts on an empty/short
        // escrow, so the recipe is non-malleable. The router never touches the exit funds.
        _activate(recipe);
    }

    /// @notice Permissionlessly deploy the recipe-bound escrow and run its batch, sweeping to
    ///         `recipe.finalRecipient`. This DECOUPLES activation from settlement: the escrow recipient
    ///         (`escrowAddressFor(recipe)`) is a pure function of the recipe, so the exit funds land there no
    ///         matter WHO settles the proof — a front-runner, an honest relay race, or a reorg landing the
    ///         proof via a raw `POOL.settle`. Without this, such a settle burns the nullifiers and makes
    ///         `exitAndExecute` revert forever, orphaning the escrow deployment and permanently stranding the
    ///         exit (the open-bounty relay posture makes settles intentionally copyable, so this is reachable
    ///         by accident). Safe for anyone to call: the escrow holds ONLY this recipe's funds, `run` sweeps
    ///         solely to `recipe.finalRecipient`, every target is recipe-bound and barred from POOL/self/ROUTER.
    ///         `_activate` is re-runnable: it reuses an already-deployed escrow instead of reverting, so a settle
    ///         that lands AFTER an earlier activation (a race, or an activate-before-settle) is never stranded —
    ///         anyone re-activates once the funds arrive. The balance guard just skips a no-op run on an empty
    ///         escrow. No proof is needed. It DOES enforce `recipe.deadline` (in `_activate`): past the deadline
    ///         the batch is stale, so activation reverts and the only remaining path is the no-batch `reclaimExit`.
    function activateExit(ExitRecipe calldata recipe) external nonReentrant {
        (,, uint256 bal) = _escrowState(recipe);
        if (bal == 0) revert EscrowEmpty(); // nothing at the escrow yet — settle first (nothing to run)
        _activate(recipe);
    }

    /// The recipe's escrow address, its exited-asset underlying, and the escrow's current underlying balance.
    /// Reverts on an unknown asset. Shared by `activateExit`/`reclaimExit` (native ETH ⇒ underlying == 0).
    function _escrowState(ExitRecipe calldata recipe)
        internal
        view
        returns (address escrow, address underlying, uint256 bal)
    {
        bool registered;
        (registered, underlying,,,,) = POOL.assets(recipe.exitedAsset);
        if (!registered) revert BadTarget();
        escrow = escrowAddressFor(recipe);
        bal = underlying == address(0) ? escrow.balance : SafeTransferLib.balanceOf(underlying, escrow);
    }

    /// @notice Rescue path: after `recipe.deadline`, sweep the escrow's holdings straight to `finalRecipient`
    ///         WITHOUT running the batch. Permissionless. Covers the case where the batch became permanently
    ///         unexecutable — an expired inner router deadline inside `calls`, dead liquidity, or a `minOut` that
    ///         can no longer clear — which would otherwise strand the exit forever on this immutable contract.
    ///         Skips `calls`/`minOuts`; the destination is still recipe-bound (`finalRecipient`), so non-custody
    ///         holds. Sweeps the exited asset's own underlying (the batch never ran) plus any `sweepTokens`.
    /// `extraTokens` lets the caller name outputs a malformed recipe's `sweepTokens` omitted (a mis-listed swap
    /// output). It grants nothing: the escrow always sweeps to the recipe-bound `finalRecipient`, so an arbitrary
    /// list only widens what the rescue can reach, never where it goes. Pass an empty array when not needed.
    function reclaimExit(ExitRecipe calldata recipe, address[] calldata extraTokens) external nonReentrant {
        if (block.timestamp <= recipe.deadline) revert NotExpired();
        if (recipe.finalRecipient == address(0) || recipe.finalRecipient == address(this)) revert BadTarget();
        (address escrow, address underlying, uint256 bal) = _escrowState(recipe);
        if (escrow.code.length == 0 && bal == 0) revert EscrowEmpty();
        _deployIfNeeded(recipe, escrow);
        ExitExecutor(payable(escrow)).sweepAll(recipe, underlying, extraTokens);
    }

    /// Deploy the recipe-bound escrow clone iff it isn't already deployed. The clone lands at the predicted
    /// `escrow` (a pure function of the recipe), so callers keep using the address they already computed.
    function _deployIfNeeded(ExitRecipe calldata recipe, address escrow) internal {
        if (escrow.code.length == 0) LibClone.cloneDeterministic_PUSH0(executorImpl, _recipeSalt(recipe));
    }

    /// Deploy the recipe-bound escrow clone (once) and run its recipe. Shared by `exitAndExecute` (right after
    /// its own settle) and `activateExit` (permissionless, after any settle). Re-runnable: on a later call the
    /// clone already exists, so it reuses it rather than reverting on redeploy — this is what makes a re-landed
    /// exit recoverable. Validates the recipe shape so both entry points fail closed on a malformed sweep.
    function _activate(ExitRecipe calldata recipe) internal {
        // The deadline expires EXECUTION authority, not just the settle: past it, the recipe's arbitrary batch
        // (a swap whose slippage floor was meant to expire, etc.) must not run. Centralize the check here so
        // BOTH `exitAndExecute` and the permissionless `activateExit` reject a stale batch — otherwise anyone
        // could call `activateExit` after expiry to force-run the batch and MEV-sandwich it, defeating the
        // no-batch `reclaimExit` rescue. Post-deadline the ONLY path is `reclaimExit` (sweep, no calls).
        if (block.timestamp > recipe.deadline) revert ExitExpired();
        if (recipe.finalRecipient == address(0) || recipe.finalRecipient == address(this)) revert BadTarget();
        if (recipe.sweepTokens.length != recipe.minOuts.length) revert BadTarget();
        address escrow = escrowAddressFor(recipe);
        _deployIfNeeded(recipe, escrow);
        ExitExecutor(payable(escrow)).run(recipe);
    }

    /// Balance of `token` held by this router; `token == address(0)` means native ETH.
    function _selfBal(address token) internal view returns (uint256) {
        return token == address(0) ? address(this).balance : SafeTransferLib.balanceOf(token, address(this));
    }

    /// Deliver `amt` of `token` to `to`; `token == address(0)` means native ETH.
    function _deliver(address token, address to, uint256 amt) internal {
        if (amt == 0) return;
        if (token == address(0)) SafeTransferLib.safeTransferETH(to, amt);
        else SafeTransferLib.safeTransfer(token, to, amt);
    }

    // ──────────────────── Internals: zaps ────────────────────

    /// Low-level call the PINNED zRouter with the caller's swap calldata, forwarding `value` ETH; bubble its
    /// revert reason (or ZRouterCallFailed). The router holds no standing approval to zRouter for ETH paths;
    /// hostile/mis-built calldata that returns too little output is caught by downstream balance-delta or
    /// slippage checks, reverting the whole transaction.
    function _callZRouter(uint256 value, bytes calldata zrSwapData) internal {
        if (ZROUTER == address(0)) revert BadTarget();
        (bool ok, bytes memory ret) = ZROUTER.call{value: value}(zrSwapData);
        if (!ok) {
            if (ret.length != 0) {
                assembly ("memory-safe") {
                    revert(add(ret, 0x20), mload(ret))
                }
            }
            revert ZRouterCallFailed();
        }
    }

    /// Call zRouter (forwarding `value` ETH) and return the resulting balance delta of `token` at this router —
    /// the amount the swap delivered here. Callers enforce their own floor on the return.
    function _zRouterReceive(address token, uint256 value, bytes calldata zrSwapData) internal returns (uint256) {
        uint256 before = SafeTransferLib.balanceOf(token, address(this));
        _callZRouter(value, zrSwapData);
        return SafeTransferLib.balanceOf(token, address(this)) - before;
    }

    /// Swap msg.value of ETH to `tokenOut` on zRouter (caller's calldata, output to this), then wrap EXACTLY
    /// `wrapAmount` into the pool as a deposit for `commit`. The swap must source >= wrapAmount.
    function _swapAndWrap(address tokenOut, uint256 wrapAmount, bytes32 commit, bytes calldata zrSwapData) internal {
        _swapAndWrapWithValue(tokenOut, wrapAmount, commit, zrSwapData, msg.value);
    }

    function _swapAndWrapWithValue(
        address tokenOut,
        uint256 wrapAmount,
        bytes32 commit,
        bytes calldata zrSwapData,
        uint256 value
    ) internal {
        if (_zRouterReceive(tokenOut, value, zrSwapData) < wrapAmount) revert ShortSwapOutput();
        _lazyApprove(tokenOut, address(POOL), wrapAmount);
        POOL.wrap(_poolAssetId(tokenOut), wrapAmount, commit);
    }

    /// Resolve a launch canonical/shared id (cBTC/cUSD) to the pool-local wrap id and canonical ERC20, then
    /// swap into that ERC20 and re-enter the confidential pool by burning/wrapping the local id.
    function _swapAndWrapCanonical(
        bytes32 assetId,
        uint256 wrapAmount,
        bytes32 commit,
        bytes calldata zrSwapData,
        uint256 value
    ) internal returns (address tokenOut) {
        tokenOut = POOL.canonicalTokenFor(assetId);
        if (tokenOut == address(0)) revert BadTarget();
        bytes32 wrapAssetId = POOL.localAssetOf(assetId);
        if (wrapAssetId == bytes32(0)) wrapAssetId = assetId;
        if (POOL.canonicalTokenFor(wrapAssetId) != tokenOut) revert BadTarget();

        if (_zRouterReceive(tokenOut, value, zrSwapData) < wrapAmount) revert ShortSwapOutput();
        _lazyApprove(tokenOut, address(POOL), wrapAmount);
        POOL.wrap(wrapAssetId, wrapAmount, commit);
    }

    /// Exact-leg zap → shield the LP shares into a note deposit. Swaps for AT LEAST `tokenBLeg` on zRouter
    /// (caller's exact-out calldata), adds EXACTLY (ethLeg, tokenBLeg) to the LP (so the minted share count is
    /// deterministic), and shields the minted shares to `commit`. Leftovers are swept by the public caller.
    function _zapToShieldedShares(
        address tokenB,
        uint32 feeBps,
        uint256 ethLeg,
        uint256 tokenBLeg,
        uint256 minShares,
        uint64 deadline,
        bytes32 commit,
        bytes calldata zrSwapData
    ) internal returns (bytes32 depositId, uint256 sharesMinted) {
        uint256 ethForSwap = msg.value - ethLeg; // reverts (underflow) if ethLeg > msg.value
        if (_zRouterReceive(tokenB, ethForSwap, zrSwapData) < tokenBLeg) revert ShortSwapOutput();
        bytes32 tethId = _poolAssetId(address(0));
        bytes32 tokenBId = _poolAssetId(tokenB);
        _lazyApprove(tokenB, address(PUBLIC_AMM), tokenBLeg);
        // EXACT legs ⇒ deterministic shares; `to == this` so the router holds them to shield.
        sharesMinted = PUBLIC_AMM.createPairAndAddLiquidityPublic{value: ethLeg}(
            tethId, tokenBId, feeBps, ethLeg, tokenBLeg, minShares, deadline, address(this)
        );
        depositId = POOL.shieldShares(_poolId(tethId, tokenBId, feeBps), sharesMinted, commit);
    }

    /// Token-in core: pull token A (Permit2), swap `tokenAForSwap` of it on zRouter for >= tokenBLeg, add
    /// EXACTLY (tokenAForLP, tokenBLeg) to the LP (deterministic shares), and shield the shares to `commit`.
    function _zapTokenToShieldedShares(
        address tokenA,
        TokenZap calldata z,
        IPermit2.PermitSingle calldata permitSingle,
        bytes calldata signature,
        bytes calldata zrSwapData
    ) internal returns (bytes32 depositId, uint256 sharesMinted) {
        uint256 total = z.tokenAForSwap + z.tokenAForLP;
        _pullPermit2(tokenA, total, permitSingle, signature);
        _lazyApprove(tokenA, ZROUTER, z.tokenAForSwap); // let zRouter pull the swap input
        uint256 beforeB = SafeTransferLib.balanceOf(z.tokenB, address(this));
        _callZRouter(0, zrSwapData); // token-in: no ETH forwarded (zRouter pulls the approved token)
        if (SafeTransferLib.balanceOf(z.tokenB, address(this)) - beforeB < z.tokenBLeg) revert ShortSwapOutput();
        bytes32 tokenAId = _poolAssetId(tokenA);
        bytes32 tokenBId = _poolAssetId(z.tokenB);
        _lazyApprove(z.tokenB, address(PUBLIC_AMM), z.tokenBLeg);
        sharesMinted = PUBLIC_AMM.createPairAndAddLiquidityPublic(
            tokenAId, tokenBId, z.feeBps, z.tokenAForLP, z.tokenBLeg, z.minShares, z.deadline, address(this)
        );
        depositId = POOL.shieldShares(_poolId(tokenAId, tokenBId, z.feeBps), sharesMinted, z.commit);
    }

    /// Canonical poolId — a byte-for-byte mirror of ConfidentialPool._poolId (keccak(lo ‖ hi ‖ feeBps)).
    function _poolId(bytes32 a, bytes32 b, uint32 feeBps) internal pure returns (bytes32 poolId) {
        (bytes32 lo, bytes32 hi) = a < b ? (a, b) : (b, a);
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, lo)
            mstore(add(m, 0x20), hi)
            mstore(add(m, 0x40), and(feeBps, 0xffffffff))
            poolId := keccak256(m, 0x60)
        }
    }

    // ──────────────────── Internals: approvals, refunds, asset id ────────────────────

    /// Lazily grant `spender` (the pinned pool, or zRouter for token-in) an infinite allowance — once per
    /// (token, spender) — vs a fresh approve every call, saving the ~20k SSTORE on every repeat. Safe: the
    /// router holds no token balance between calls (nothing to pull) and spenders are pinned. `safeApprove…`
    /// resets-then-sets for tokens (USDT-style) that require a 0 allowance first; a token that decrements an
    /// infinite allowance just trips the `< amount` check later and is re-approved.
    function _lazyApprove(address token, address spender, uint256 amount) internal {
        if (IERC20Allowance(token).allowance(address(this), spender) < amount) {
            SafeTransferLib.safeApproveWithRetry(token, spender, type(uint256).max);
        }
    }

    function _checkPath(address[] calldata path, uint32[] calldata fees, address to) internal view {
        if (path.length == 0 || path.length != fees.length || to == address(0) || to == address(this)) {
            revert BadPath();
        }
        for (uint256 i; i < path.length; ++i) {
            if (path[i] == address(0)) revert BadPath();
        }
    }

    function _swapPublicPath(
        address tokenIn,
        address[] calldata path,
        uint32[] calldata fees,
        uint256 amountIn,
        uint256 minAmountOut,
        uint64 deadline,
        address to
    ) internal returns (uint256 amountOut) {
        address curToken = tokenIn;
        uint256 curAmount = amountIn;
        for (uint256 i; i < path.length; ++i) {
            address nextToken = path[i];
            bool last = i == path.length - 1;
            _lazyApprove(curToken, address(PUBLIC_AMM), curAmount);
            curAmount = PUBLIC_AMM.swapPublic(
                _poolAssetId(curToken),
                _poolAssetId(nextToken),
                fees[i],
                curAmount,
                last ? minAmountOut : 0,
                deadline,
                last ? to : address(this)
            );
            curToken = nextToken;
        }
        amountOut = curAmount;
    }

    function _swapPublicETHPath(
        address[] calldata path,
        uint32[] calldata fees,
        uint256 amountIn,
        uint256 minAmountOut,
        uint64 deadline,
        address to
    ) internal returns (uint256 amountOut) {
        uint256 curAmount = amountIn;
        bytes32 curAsset = _poolAssetId(address(0));
        for (uint256 i; i < path.length; ++i) {
            address nextToken = path[i];
            bool last = i == path.length - 1;
            curAmount = PUBLIC_AMM.swapPublic{value: i == 0 ? amountIn : 0}(
                curAsset,
                _poolAssetId(nextToken),
                fees[i],
                curAmount,
                last ? minAmountOut : 0,
                deadline,
                last ? to : address(this)
            );
            curAsset = _poolAssetId(nextToken);
            if (!last) _lazyApprove(nextToken, address(PUBLIC_AMM), curAmount);
        }
        amountOut = curAmount;
    }

    /// `PublicValues` is ABI-encoded as one tuple argument (`abi.encode(pv)`), so word 0 is the tuple offset.
    /// Field 22 is `cdpMints`; requiring a non-empty array prevents CDP-named entrypoints from accidentally
    /// accepting a plain private-payment settle while leaving full semantic validation to the pool + proof.
    function _requireCdpMintIntent(bytes calldata publicValues) internal pure {
        uint256 tupleStart;
        uint256 cdpOffset;
        uint256 cdpLen;
        assembly ("memory-safe") {
            tupleStart := calldataload(publicValues.offset)
        }
        if (tupleStart > publicValues.length || publicValues.length - tupleStart < 31 * 32) {
            revert BadProofIntent();
        }
        assembly ("memory-safe") {
            cdpOffset := calldataload(add(add(publicValues.offset, tupleStart), mul(22, 32)))
        }
        if (cdpOffset > publicValues.length || tupleStart + cdpOffset > publicValues.length - 32) {
            revert BadProofIntent();
        }
        assembly ("memory-safe") {
            cdpLen := calldataload(add(add(publicValues.offset, tupleStart), cdpOffset))
        }
        if (cdpLen == 0) revert BadProofIntent();
    }

    /// Every router-relayed settle runs with `msg.sender == this router`, so a settler-fee leg would pay the
    /// router and a fee in any non-input asset would strand here with no sweep. The router settle paths are
    /// fee-free by construction; enforce it fail-closed (`PublicValues` field 7 is `fees`) instead of silently
    /// accruing dust, then forward to the pool.
    function _relaySettle(bytes calldata publicValues, bytes calldata proof, bytes[] calldata memos) internal {
        uint256 tupleStart;
        uint256 feesOffset;
        uint256 feesLen;
        assembly ("memory-safe") {
            tupleStart := calldataload(publicValues.offset)
        }
        if (tupleStart > publicValues.length || publicValues.length - tupleStart < 31 * 32) {
            revert BadProofIntent();
        }
        assembly ("memory-safe") {
            feesOffset := calldataload(add(add(publicValues.offset, tupleStart), mul(7, 32)))
        }
        if (feesOffset > publicValues.length || tupleStart + feesOffset > publicValues.length - 32) {
            revert BadProofIntent();
        }
        assembly ("memory-safe") {
            feesLen := calldataload(add(add(publicValues.offset, tupleStart), feesOffset))
        }
        if (feesLen != 0) revert BadProofIntent();
        POOL.settle(publicValues, proof, memos);
    }

    /// Forward the router's full balance of `token` to `to` — pool off-ratio refunds + swap dust — so the
    /// router never retains a token balance across calls.
    function _refund(address token, address to) internal {
        uint256 bal = SafeTransferLib.balanceOf(token, address(this));
        if (bal != 0) SafeTransferLib.safeTransfer(token, to, bal);
    }

    /// Sweep any residual balance of each path token back to `to` (intermediate-hop dust + a short final leg).
    function _refundPath(address[] calldata path, address to) internal {
        for (uint256 i; i < path.length; ++i) _refund(path[i], to);
    }

    /// Common zap tails: sweep the swap output token (+ leftover ETH) or both the input and output token back
    /// to the caller. Fresh proceeds already went to their bound destination; these clear residue.
    function _refundOutETH(address tokenOut) internal { _refund(tokenOut, msg.sender); _refundETH(msg.sender); }
    function _refundInOut(address tokenIn, address tokenOut) internal { _refund(tokenIn, msg.sender); _refund(tokenOut, msg.sender); }

    function _refundETH(address to) internal {
        uint256 bal = address(this).balance;
        if (bal != 0) SafeTransferLib.forceSafeTransferETH(to, bal);
    }

    /// The id under which the POOL keys `token`. The pool registers BRIDGED assets by their shared cross-chain
    /// id and EXTERNAL/local assets by `_evmAssetId`. Native ETH is bridged (tETH → ETH_ASSET_ID). A pool-minted
    /// canonical token commits to its shared id via ASSET_ID(); verify it's THIS pool's canonical for that id
    /// before trusting it, else fall back to the external `_evmAssetId` key (USDC etc. have no ASSET_ID()).
    function _poolAssetId(address token) internal view returns (bytes32) {
        if (token == address(0)) return ETH_ASSET_ID; // tETH shared id
        try IAssetId(token).ASSET_ID() returns (bytes32 aid) {
            if (aid != bytes32(0) && POOL.canonicalTokenFor(aid) == token) {
                // A canonical asset's confidential notes carry its SHARED id: the bridge-mint guest
                // commits the note leaf under the shared id, and the pool resolves shared->local at its
                // value-effect boundaries (wrap/swapPublic/addLiquidity/_ingestPublic all _resolveAsset).
                // Return the shared id even for a HEALED asset (stored under a local id with
                // localAssetOf[shared]=local): passing the local id here would bind the wrapped note to
                // the local id and fork the confidential supply away from the shared-id bridged notes.
                return aid;
            }
        } catch {}
        return _evmAssetId(token);
    }

    /// The pool's internal asset id for an underlying ERC20 — MUST mirror ConfidentialPool._evmAssetId:
    /// sha256("tacit-evm-token-v1" ‖ chainid ‖ underlying). Every registerWrapped/_register keys the asset
    /// under exactly this id, so deriving it here lets the caller pass only the token address (address(0) for
    /// native ETH/tETH). A token whose derived id isn't registered simply makes the pool revert (fail-closed).
    function _evmAssetId(address underlying) internal view returns (bytes32 assetId) {
        assembly ("memory-safe") {
            let m := mload(0x40)
            mstore(m, shl(112, 0x74616369742d65766d2d746f6b656e2d7631)) // "tacit-evm-token-v1"
            mstore(add(m, 18), shl(192, chainid()))
            mstore(add(m, 26), shl(96, underlying))
            if iszero(staticcall(gas(), 2, m, 46, m, 32)) { revert(0, 0) }
            assetId := mload(m)
        }
    }

    /// Accept the pool's native-ETH off-ratio refund (forceSafeTransferETH) so it lands cleanly to be swept.
    receive() external payable {}
}

/// Recipe-bound batch executor for atomic exit-and-execute. The router deploys ONE impl in its constructor,
/// then clones a PUSH0 minimal proxy of it at a recipe-bound deterministic address (salt = the exit-recipe
/// hash) per exit, so the proof commits the recipe. The pool unwraps the note TO the clone, which therefore
/// holds ONLY this one exit's funds. The router then calls `run`, which the clone executes in ITS OWN context —
/// `address(this)` is the clone (holding the funds) while the ROUTER/POOL_ immutables are read from the impl
/// code (== the router that deployed it + its pool). Only-ROUTER + a fresh clone per recipe (one-shot) is the
/// reentrancy guard at this layer; arbitrary batched calls are blast-contained to this single exit's funds —
/// the router, pool, and other users are never exposed. Holds nothing across txs.
contract ExitExecutor {
    address private immutable ROUTER;
    address private immutable POOL_;

    error BadTarget();
    error NotRouter();
    error ShortOutput();

    constructor(address pool) {
        ROUTER = msg.sender;
        POOL_ = pool;
    }

    /// Run the recipe's batch from this escrow, then sweep each output to `finalRecipient`. Router-only.
    function run(ConfidentialRouter.ExitRecipe calldata r) external {
        if (msg.sender != ROUTER) revert NotRouter();

        ConfidentialRouter.ExitCall[] calldata calls = r.calls;
        for (uint256 i; i < calls.length; ++i) {
            ConfidentialRouter.ExitCall calldata c = calls[i];
            // Targets are recipe-bound (proof-committed), but never let a call reach back into the pool, this
            // escrow, or the router — those are the only addresses with privileged state to abuse.
            if (c.target == POOL_ || c.target == address(this) || c.target == ROUTER) revert BadTarget();
            if (c.token != address(0) && c.amount != 0) {
                if (c.push) SafeTransferLib.safeTransfer(c.token, c.target, c.amount);
                else SafeTransferLib.safeApproveWithRetry(c.token, c.target, c.amount);
            }
            (bool ok, bytes memory ret) = c.target.call{value: c.value}(c.data);
            if (!ok) {
                assembly ("memory-safe") {
                    revert(add(ret, 0x20), mload(ret))
                }
            }
            // Revoke any allowance the target did not fully consume. The escrow address is keccak(recipe), so a
            // byte-identical recipe reused for a later exit maps to THIS same escrow; a residual approval left
            // here would be live for that later run's funds. Reset to zero so nothing survives this batch.
            if (!c.push && c.token != address(0) && c.amount != 0) {
                SafeTransferLib.safeApproveWithRetry(c.token, c.target, 0);
            }
        }

        for (uint256 i; i < r.sweepTokens.length; ++i) {
            address tok = r.sweepTokens[i];
            uint256 bal = tok == address(0) ? address(this).balance : SafeTransferLib.balanceOf(tok, address(this));
            if (bal < r.minOuts[i]) revert ShortOutput();
            _sweep(tok, r.finalRecipient);
        }
    }

    /// Rescue sweep: deliver the escrow's holdings straight to `finalRecipient` WITHOUT running the batch, used
    /// by the router's post-deadline `reclaimExit` when the batch became unexecutable. Router-only. Sweeps the
    /// exited asset's own `underlying` (present when the batch never ran), each `sweepTokens` output, and any
    /// caller-supplied `extraTokens` (the backstop for an output a malformed recipe's `sweepTokens` omitted);
    /// skips `calls` and the `minOuts` floors (a recipe-bound recipient with no price floor beats a permanent
    /// strand). `extraTokens` grants no authority: `_sweep` always targets the recipe-bound `finalRecipient`.
    function sweepAll(ConfidentialRouter.ExitRecipe calldata r, address underlying, address[] calldata extraTokens)
        external
    {
        if (msg.sender != ROUTER) revert NotRouter();
        _sweep(underlying, r.finalRecipient);
        for (uint256 i; i < r.sweepTokens.length; ++i) _sweep(r.sweepTokens[i], r.finalRecipient);
        for (uint256 i; i < extraTokens.length; ++i) _sweep(extraTokens[i], r.finalRecipient);
    }

    /// Send this escrow's full balance of `tok` (address(0) = native ETH) to `to`; no-op on a zero balance.
    function _sweep(address tok, address to) internal {
        uint256 bal = tok == address(0) ? address(this).balance : SafeTransferLib.balanceOf(tok, address(this));
        if (bal != 0) {
            // Native ETH: force-send. `to` is the recipe-bound finalRecipient, bound into the CREATE2 salt, so
            // a recipient that rejects a plain ETH call has no alternate withdrawal address — an ordinary send
            // would strand the escrow's ETH permanently (normal run AND post-deadline reclaimExit both revert).
            if (tok == address(0)) SafeTransferLib.forceSafeTransferETH(to, bal);
            else SafeTransferLib.safeTransfer(tok, to, bal);
        }
    }

    receive() external payable {}
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none"
  },
  "libraries": {},
  "optimizer": {
    "runs": 1,
    "enabled": true
  },
  "evmVersion": "prague",
  "remappings": [
    ":forge-std/=/Users/z/tacit/contracts/lib/forge-std/src/",
    ":solady/=/Users/z/tacit/contracts/lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.