Skip to content
Verified contractPartialMIT

PackVault

Address0x9abbf7835240de0dafc7d2e512e6da15eb0d0b46
Balance

0.01 ETH

 

Transactions

1

 

Compiler

solc 0.8.30

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.30+commit.73712a01
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,475,518
Creation transaction
0xcbcad03f6a…046ef6c947
Libraries
src/VaultLib.sol:VaultLib0x8e75…85b69csrc/StrategyLib.sol:StrategyLib0x6f45…c1a83f

src/PackVault.sol

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

import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {FixedPointMathLib as M} from "solady/utils/FixedPointMathLib.sol";
import {PackAccount} from "./PackAccount.sol";
import {VaultLib} from "./VaultLib.sol";
import {StrategyLib} from "./StrategyLib.sol";
import {IKeeperPolicy} from "./KeeperPolicy.sol";
import {IShapes, IShapePacks, IFWAV2} from "./interfaces/External.sol";

/// @title PackVault
/// @notice Pooled depositor vault for the FWA V2 main pool. It runs the shared pack strategy
///         (PackAccount: build, list, sync, unlist, liquidate) and adds only multi-depositor
///         ownership: non-transferable internal shares priced at checkpoints, escrowed deposits,
///         pro-rata redemptions, distributions, holder liabilities and wind-down.
/// @dev Economics, from FWAV2 source and validated against every historical EarningsAccrued event:
///      a listing with backing B earns expected fees k B before selection, where
///      k = (1 + surcharge)(1 - protocolCut)(1 - crownShare). On selection the purchaser either keeps
///      the pack (the vault gets B (1 - s) back: net B (k - s) - P, and builds a replacement) or takes
///      the bid (the vault keeps the pack, loses B: net B (k - 1)). Backing is set so keeping wins
///      for the purchaser (VaultLib.edge).
///
///      Keepers are paid from vault ETH (a holder expense, NAV-visible), never from a fee skim, by
///      quote (D56). Checkpoints are funded by charges on the deposit and redemption requests that
///      need them, so holders do not pay for work someone else manufactures.
///
///      Trust: FWA, its rewards module, Shapes, ShapePacks and the FWA token are immutable
///      addresses fixed here. FWA's owner can change fees, the floor quote and admission; every
///      such change is read live, never cached. One owner (D59; transferable, never renounced,
///      D76) sets parameters and the keeper policy at once, inside bytecode bounds (D58), pauses
///      and starts wind-down. The owner cannot take assets directly; a compromised owner can raise
///      keeper pay to the bytecode maxima and keep for itself, bounded by the budgets.
contract PackVault is PackAccount {
    using SafeTransferLib for address;

    uint256 internal constant BPS = 10_000;
    uint256 internal constant INTERVAL = 12 hours; // FWA purchase interval
    uint256 internal constant SCALE = 1e36;
    uint256 internal constant OP_CHECKPOINT = 8;
    uint256 internal constant MIN_DEPOSIT = 0.01 ether;
    uint256 internal constant MIN_DISTRIBUTION = VaultLib.MIN_DISTRIBUTION;
    uint256 public constant DEAD_SHARES = VaultLib.DEAD_SHARES;

    bool public depositsPaused;

    // ------------------------------------------------------------------ shares

    uint256 public totalShares;
    mapping(address => uint256) public sharesOf;

    uint256 public epoch; // checkpoints completed
    uint256 public lastCheckpointInterval;
    uint256 public highWaterMark; // NAV per share, 1e18 scale
    uint256 public lastNav;

    struct PendingDeposit {
        // uint96 holds 7.9e10 ETH, more than exists, so neither field can truncate.
        uint96 amount; // escrowed, deployment charge included
        uint32 epoch; // priced at the checkpoint that ends this epoch
        uint96 charge; // deployment charge: escrowed with the deposit, earns no shares
        uint32 checkpointGwei; // checkpoint charge paid, in gwei (at most ~0.51 ETH at the maxima)
    }

    mapping(address => PendingDeposit) public pendingDeposits;
    uint256 public pendingDepositTotal; // ETH escrowed, excluded from NAV
    uint256 internal pendingChargeTotal; // deployment charges inside pendingDepositTotal
    mapping(uint256 epoch => uint256) internal epochNav; // post-flow NAV used to price deposits
    mapping(uint256 epoch => uint256) internal epochSupply;
    mapping(uint256 epoch => uint256) internal epochDistPerShare; // accumulator when deposits were priced

    // Pro-rata redemption index. Each checkpoint fills fraction f of all locked shares at the
    // checkpoint price; g tracks the surviving fraction, q the ETH paid per original share.
    struct Redemption {
        uint128 shares;
        uint64 era;
        uint256 g0;
        uint256 q0;
    }

    mapping(address => Redemption) public redemptions;
    uint256 public lockedShares;
    uint256 internal redeemEra;
    uint256 internal redeemG = SCALE;
    uint256 internal redeemQ;
    mapping(uint256 era => uint256) internal eraFinalQ;
    uint256 public redemptionReserve; // ETH owed to redeemers, excluded from NAV
    mapping(address => uint256) public claimableEth;
    uint256 public claimableTotal; // settled to holders, not yet paid: a liability like the reserves

    // Distributions: per-share accumulator over all live shares.
    uint256 public distPerShare; // wei x 1e18 per share
    mapping(address => uint256) internal distDebt;
    uint256 public distributionReserve;

    // Request charges held for the next checkpoint.
    uint256 public processingPool; // excluded from NAV until the checkpoint it funds

    // ------------------------------------------------------------------ events and errors

    event Deposited(address indexed holder, uint256 amount, uint256 epoch);
    event DepositCancelled(address indexed holder, uint256 amount);
    event RedeemRequested(address indexed holder, uint256 shares);
    event Checkpoint(uint256 indexed epoch, uint256 nav, uint256 supply, uint256 filledShares, uint256 paid, uint256 distributed);
    event Claimed(address indexed holder, uint256 amount);
    event WindDownStarted();

    error Paused();
    error WindingDown();
    error NotCheckpointWindow();
    error AlreadyCheckpointed();
    error AllocatedExposure();
    error Amount();
    error Nothing();
    error SyncFirst();

    // ------------------------------------------------------------------ construction

    constructor(
        IFWAV2 fwa_,
        IShapes shapes_,
        IShapePacks packs_,
        address owner_,
        VaultLib.Params memory initial,
        IKeeperPolicy policy_
    ) payable PackAccount(fwa_, shapes_, packs_) {
        _initStrategy(owner_, initial, address(policy_));
        // First issuance: the deployer's seed buys dead shares so the share price cannot be
        // inflated against a later first depositor.
        if (msg.value < MIN_DEPOSIT) revert Amount();
        totalShares = DEAD_SHARES;
        sharesOf[address(0xdead)] = DEAD_SHARES;
        highWaterMark = msg.value * 1e18 / DEAD_SHARES;
    }

    // ------------------------------------------------------------------ account hooks

    function _checkpointMode() internal view override returns (uint256) {
        if (block.timestamp / INTERVAL == lastCheckpointInterval) return 0;
        return pendingDepositTotal != 0 || lockedShares != 0 ? 1 : s.params.distributionBps != 0 ? 2 : 0;
    }

    /// @dev ETH locked redemptions need beyond free ETH and idle inventory.
    function _shortfall() internal view override returns (uint256) {
        uint256 owed = _owedEstimate();
        uint256 inventory = _free() + s.book.idleValue;
        return owed > inventory ? owed - inventory : 0;
    }

    /// @dev ETH locked redemptions need beyond free ETH and new deposits.
    function _need() internal view override returns (uint256) {
        uint256 owed = _owedEstimate();
        uint256 liquid = _free() + pendingDepositTotal;
        return owed > liquid ? owed - liquid : 0;
    }

    /// @dev The vault's own ETH: balance less escrowed deposits and every amount owed to holders,
    ///      whether still in a shared reserve or already settled to a holder's claimable balance.
    ///      Request charges held for the next checkpoint are excluded too. Forced ETH lands here,
    ///      so it is attributed by balance, never by callback.
    function _free() internal view override returns (uint256) {
        uint256 owed = pendingDepositTotal + redemptionReserve + distributionReserve + claimableTotal + processingPool;
        uint256 bal = address(this).balance;
        return bal > owed ? bal - owed : 0;
    }

    /// @dev ETH the strategy may spend: free ETH above the reserve and above what locked
    ///      redemptions will need, so ETH freed for redeemers cannot be relisted.
    function _idle() internal view override returns (uint256) {
        uint256 free = _free();
        uint256 keep = s.params.reserve + _owedEstimate();
        return free > keep ? free - keep : 0;
    }

    /// @dev ETH locked shares will need at the last checkpoint's price, rounded up.
    function _owedEstimate() internal view returns (uint256) {
        if (lockedShares == 0) return 0;
        return M.mulDivUp(lockedShares, lastNav, totalShares);
    }

    // ------------------------------------------------------------------ holders

    /// @notice Escrow ETH to buy shares at the next checkpoint. Cancellable until then. The
    ///         request charge (`requestCharge()`) is kept from `msg.value` to fund that checkpoint.
    function deposit() external payable nonReentrant {
        if (depositsPaused) revert Paused();
        if (s.windingDown) revert WindingDown();
        // Charges: the checkpoint (to the pool, kept on cancel) and building and listing positions
        // with this ETH (escrowed with the deposit and refunded on cancel; at pricing it joins the
        // vault's value, which pays for that work, and earns the depositor no shares).
        uint256 ck = requestCharge();
        if (msg.value < MIN_DEPOSIT + ck) revert Amount();
        uint256 amount = msg.value - ck;
        uint256 deploy = deployCharge();
        uint256 charge = amount * deploy / (VaultLib.POSITION_VALUE + deploy);
        if (lastNav + pendingDepositTotal + amount > s.params.tvlCap) revert Amount();
        _settleHolder(msg.sender);
        processingPool += ck;
        PendingDeposit storage d = pendingDeposits[msg.sender];
        d.amount += uint96(amount);
        d.charge += uint96(charge);
        d.epoch = uint32(epoch);
        d.checkpointGwei += uint32(ck / 1 gwei);
        pendingDepositTotal += amount;
        pendingChargeTotal += charge;
        emit Deposited(msg.sender, amount, epoch);
    }

    function cancelDeposit() external nonReentrant {
        _settleHolder(msg.sender);
        PendingDeposit memory d = pendingDeposits[msg.sender];
        uint256 amount = d.amount;
        if (amount == 0) revert Nothing();
        delete pendingDeposits[msg.sender];
        pendingDepositTotal -= amount;
        pendingChargeTotal -= d.charge;
        // Refund the checkpoint charge, keeping the pool funded for any flows still waiting.
        uint256 keep = pendingDepositTotal != 0 || lockedShares != 0 ? VaultLib.requestCharge(s.params) : 0;
        uint256 back = M.min(uint256(d.checkpointGwei) * 1 gwei, processingPool > keep ? processingPool - keep : 0);
        processingPool -= back;
        msg.sender.forceSafeTransferETH(amount + back);
        emit DepositCancelled(msg.sender, amount + back);
    }

    /// @notice Lock shares for redemption. Filled pro rata at checkpoints as ETH frees up; the
    ///         unfilled part stays exposed to the vault until filled. Send at least
    ///         `requestCharge()`: it funds the checkpoint; any excess is returned.
    function requestRedeem(uint256 amount) external payable nonReentrant {
        _settleHolder(msg.sender);
        if (amount == 0 || amount > sharesOf[msg.sender]) revert Amount();
        // Charges: the checkpoint (to the pool) and unwinding positions worth the shares' value
        // (to the vault, which pays for that work).
        uint256 ck = requestCharge();
        uint256 charge = ck + M.mulDiv(M.mulDiv(amount, lastNav, totalShares), unwindCharge(), VaultLib.POSITION_VALUE);
        if (msg.value < charge) revert Amount();
        processingPool += ck;
        if (msg.value > charge) msg.sender.forceSafeTransferETH(msg.value - charge);
        _settleDist(msg.sender);
        sharesOf[msg.sender] -= amount;
        distDebt[msg.sender] = sharesOf[msg.sender] * distPerShare / 1e18;
        Redemption storage r = redemptions[msg.sender];
        r.shares += uint128(amount);
        lockedShares += amount;
        emit RedeemRequested(msg.sender, amount);
    }

    /// @notice Withdraw redeemed ETH and distributions.
    function claim() external nonReentrant {
        _settleHolder(msg.sender);
        _settleDist(msg.sender);
        uint256 amount = claimableEth[msg.sender];
        if (amount == 0) revert Nothing();
        claimableEth[msg.sender] = 0;
        claimableTotal -= amount;
        msg.sender.forceSafeTransferETH(amount);
        emit Claimed(msg.sender, amount);
    }

    /// @dev Convert a priced deposit to shares and apply redemption fills. Idempotent.
    function _settleHolder(address h) internal {
        PendingDeposit memory d = pendingDeposits[h];
        if (d.amount != 0 && d.epoch < epoch) {
            _settleDist(h);
            uint256 minted = uint256(d.amount - d.charge) * epochSupply[d.epoch] / epochNav[d.epoch];
            sharesOf[h] += minted;
            // New shares earn every distribution after their pricing, even if converted later.
            distDebt[h] += minted * epochDistPerShare[d.epoch] / 1e18;
            delete pendingDeposits[h];
        }
        Redemption storage r = redemptions[h];
        if (r.shares == 0) {
            r.era = uint64(redeemEra);
            r.g0 = redeemG;
            r.q0 = redeemQ;
            return;
        }
        uint256 paid;
        uint256 remaining;
        if (r.era < redeemEra) {
            paid = M.mulDiv(r.shares, eraFinalQ[r.era] - r.q0, r.g0);
        } else {
            paid = M.mulDiv(r.shares, redeemQ - r.q0, r.g0);
            remaining = M.mulDiv(r.shares, redeemG, r.g0);
        }
        if (paid != 0) {
            redemptionReserve -= paid;
            claimableEth[h] += paid;
            claimableTotal += paid;
        }
        r.shares = uint128(remaining);
        r.era = uint64(redeemEra);
        r.g0 = redeemG;
        r.q0 = redeemQ;
    }

    function _settleDist(address h) internal {
        uint256 owed = sharesOf[h] * distPerShare / 1e18 - distDebt[h];
        if (owed != 0) {
            distributionReserve -= owed;
            claimableEth[h] += owed;
            claimableTotal += owed;
            distDebt[h] += owed;
        }
    }

    // ------------------------------------------------------------------ checkpoint

    /// @notice Price the vault and settle flows. Only during FWA's purchase blackout with its
    ///         acquisition queue drained: no listing can be selected until the blackout ends, so
    ///         every Active position is worth exactly what a withdrawal would return.
    ///         Paid at cost plus one work unit, from the request charges of the flows it settles
    ///         (`processingPool`); with no flows, from the routine budget for a distribution.
    function checkpoint(uint256 witnessId, uint256 minPay) external nonReentrant returns (uint256) {
        IFWAV2 f = fwa;
        if (!f.isPurchaseBlackout() || f.unsettledAcquisitionCount() != 0) revert NotCheckpointWindow();
        uint256 interval = block.timestamp / INTERVAL;
        if (interval == lastCheckpointInterval) revert AlreadyCheckpointed();
        // Only with holder flows to settle, or with distributions on: a no-op checkpoint would
        // use up the interval's one slot and delay flows that arrive later in the blackout.
        bool work = pendingDepositTotal != 0 || lockedShares != 0;
        if (!work && s.params.distributionBps == 0) revert Nothing();
        bool essential = lockedShares != 0 || s.windingDown;
        if (!work) StrategyLib.precheck(s, minPay, essential); // with flows, the charge pool pays (no budget)
        lastCheckpointInterval = interval;

        (uint256 oldest, uint64 allocatedAt) = VaultLib.oldestAllocation(s.book);
        if (oldest != 0 && block.timestamp >= uint256(allocatedAt) + f.settlementWindow()) revert SyncFirst();
        VaultLib.harvestCredit(s.book, f);
        (uint256 nav, uint256 gasQ) = VaultLib.checkpointNav(s.book, f, packs, _free(), witnessId);
        if (s.book.allocatedValue * BPS > nav * s.params.allocatedBoundBps) revert AllocatedExposure();

        uint256 supply = totalShares;
        // 1. Redemptions at the pre-flow price, funded by free ETH and new deposits. Inventory is
        //    turned into ETH beforehand by `liquidate`, so this call stays bounded.
        uint256 filled;
        uint256 paid;
        if (lockedShares != 0) {
            uint256 frac;
            uint256 unit;
            (frac, filled, unit, paid) = VaultLib.fill(lockedShares, nav, supply, _free() + pendingDepositTotal);
            redeemQ += M.mulDiv(redeemG, unit, SCALE);
            if (frac == SCALE) {
                eraFinalQ[redeemEra] = redeemQ;
                ++redeemEra;
                redeemG = SCALE;
                redeemQ = 0;
                lockedShares = 0;
            } else {
                redeemG = M.mulDiv(redeemG, SCALE - frac, SCALE);
                lockedShares -= filled;
            }
            redemptionReserve += paid;
            totalShares = supply - filled;
            nav -= paid;
            supply -= filled;
        }

        // 2. Distribution of new gains, only when no shares are waiting to exit.
        uint256 distributed;
        uint256 perShare = nav * 1e18 / supply;
        if (lockedShares == 0 && supply > DEAD_SHARES && perShare > highWaterMark && s.params.distributionBps != 0) {
            uint256 gain = M.mulDiv(perShare - highWaterMark, supply, 1e18);
            distributed = M.min(gain * s.params.distributionBps / BPS, _idle());
            if (distributed >= MIN_DISTRIBUTION) {
                // Live shares only: the dead seed shares never claim, so their slice would strand.
                distPerShare += distributed * 1e18 / (supply - DEAD_SHARES);
                distributionReserve += distributed;
                nav -= distributed;
            } else {
                distributed = 0;
            }
        }
        perShare = nav * 1e18 / supply;
        if (perShare > highWaterMark) highWaterMark = perShare;

        // 3. Deposits at the post-flow price.
        epochNav[epoch] = nav;
        epochSupply[epoch] = supply;
        epochDistPerShare[epoch] = distPerShare;
        if (pendingDepositTotal != 0) {
            totalShares += (pendingDepositTotal - pendingChargeTotal) * supply / nav;
            nav += pendingDepositTotal;
            pendingDepositTotal = 0;
            pendingChargeTotal = 0;
            // Deployment charges lift NAV per share; that is not a gain to distribute.
            perShare = nav * 1e18 / totalShares;
            if (perShare > highWaterMark) highWaterMark = perShare;
        }
        lastNav = nav;
        emit Checkpoint(epoch, nav, totalShares, filled, paid, distributed);
        ++epoch;
        if (work) {
            // Pay comes out of the request charges; what is left over joins the vault's ETH.
            uint256 pool = processingPool;
            processingPool = 0;
            return StrategyLib.pay(s, OP_CHECKPOINT, gasQ, 1, essential, minPay, pool);
        }
        if (distributed != 0) {
            return StrategyLib.pay(s, OP_CHECKPOINT, gasQ, 1, false, minPay, type(uint256).max);
        }
        // No flows and nothing distributed: revert, so the interval's one slot stays free (audit E3).
        revert Nothing();
    }

    // ------------------------------------------------------------------ charges

    /// @notice What a deposit or redemption request is charged now: what tops `processingPool` up
    ///         to one checkpoint at its quote (cost plus one work unit), rounded up to whole gwei;
    ///         0 when the pool already holds it. Requests in one interval share one checkpoint.
    function requestCharge() public view returns (uint256) {
        uint256 full = VaultLib.requestCharge(s.params);
        uint256 topUp = full > processingPool ? full - processingPool : 0;
        return (topUp + 1 gwei - 1) / 1 gwei * 1 gwei;
    }

    /// @notice Deployment charge per VaultLib.POSITION_VALUE deposited: building and listing one
    ///         reference position at its quote now plus its mint fees, and never less than the
    ///         keeper margin that building it can pay out at any gas price.
    function deployCharge() public view returns (uint256) {
        return VaultLib.deployCharge(s.params, shapes.mintFee());
    }

    /// @notice Unwind charge per VaultLib.POSITION_VALUE redeemed: unlisting and liquidating one position.
    function unwindCharge() public view returns (uint256) {
        return VaultLib.unwindCharge(s.params);
    }

    // ------------------------------------------------------------------ owner

    /// @notice Owner pauses or resumes deposits and listing. Wind-down is one-way.
    function guard(bool pauseDeposits, bool pauseListing) external onlyOwner {
        (depositsPaused, s.listingPaused) = (pauseDeposits, pauseListing);
    }

    function startWindDown() external onlyOwner {
        s.windingDown = true;
        depositsPaused = true;
        s.listingPaused = true;
        emit WindDownStarted();
    }

    // ------------------------------------------------------------------ views

    /// @notice Shares including a deposit already priced but not yet converted (lazy).
    function shareBalance(address h) external view returns (uint256 shares) {
        shares = sharesOf[h];
        PendingDeposit memory d = pendingDeposits[h];
        if (d.amount != 0 && d.epoch < epoch) shares += uint256(d.amount - d.charge) * epochSupply[d.epoch] / epochNav[d.epoch];
    }
}

lib/solady/src/auth/Ownable.sol

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

/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The caller is not authorized to call the function.
    error Unauthorized();

    /// @dev The `newOwner` cannot be the zero address.
    error NewOwnerIsZeroAddress();

    /// @dev The `pendingOwner` does not have a valid handover request.
    error NoHandoverRequest();

    /// @dev Cannot double-initialize.
    error AlreadyInitialized();

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

    /// @dev The ownership is transferred from `oldOwner` to `newOwner`.
    /// This event is intentionally kept the same as OpenZeppelin's Ownable to be
    /// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
    /// despite it not being as lightweight as a single argument event.
    event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);

    /// @dev An ownership handover to `pendingOwner` has been requested.
    event OwnershipHandoverRequested(address indexed pendingOwner);

    /// @dev The ownership handover to `pendingOwner` has been canceled.
    event OwnershipHandoverCanceled(address indexed pendingOwner);

    /// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
    uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
        0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;

    /// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
        0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;

    /// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
    uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
        0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;

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

    /// @dev The owner slot is given by:
    /// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
    /// It is intentionally chosen to be a high value
    /// to avoid collision with lower slots.
    /// The choice of manual storage layout is to enable compatibility
    /// with both regular and upgradeable contracts.
    bytes32 internal constant _OWNER_SLOT =
        0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;

    /// The ownership handover slot of `newOwner` is given by:
    /// ```
    ///     mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
    ///     let handoverSlot := keccak256(0x00, 0x20)
    /// ```
    /// It stores the expiry timestamp of the two-step ownership handover.
    uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                     INTERNAL FUNCTIONS                     */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
    function _guardInitializeOwner() internal pure virtual returns (bool guard) {}

    /// @dev Initializes the owner directly without authorization guard.
    /// This function must be called upon initialization,
    /// regardless of whether the contract is upgradeable or not.
    /// This is to enable generalization to both regular and upgradeable contracts,
    /// and to save gas in case the initial owner is not the caller.
    /// For performance reasons, this function will not check if there
    /// is an existing owner.
    function _initializeOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                if sload(ownerSlot) {
                    mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
                    revert(0x1c, 0x04)
                }
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Store the new value.
                sstore(_OWNER_SLOT, newOwner)
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
            }
        }
    }

    /// @dev Sets the owner directly without authorization guard.
    function _setOwner(address newOwner) internal virtual {
        if (_guardInitializeOwner()) {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
            }
        } else {
            /// @solidity memory-safe-assembly
            assembly {
                let ownerSlot := _OWNER_SLOT
                // Clean the upper 96 bits.
                newOwner := shr(96, shl(96, newOwner))
                // Emit the {OwnershipTransferred} event.
                log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
                // Store the new value.
                sstore(ownerSlot, newOwner)
            }
        }
    }

    /// @dev Throws if the sender is not the owner.
    function _checkOwner() internal view virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // If the caller is not the stored owner, revert.
            if iszero(eq(caller(), sload(_OWNER_SLOT))) {
                mstore(0x00, 0x82b42900) // `Unauthorized()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Returns how long a two-step ownership handover is valid for in seconds.
    /// Override to return a different value if needed.
    /// Made internal to conserve bytecode. Wrap it in a public function if needed.
    function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
        return 48 * 3600;
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  PUBLIC UPDATE FUNCTIONS                   */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Allows the owner to transfer the ownership to `newOwner`.
    function transferOwnership(address newOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(shl(96, newOwner)) {
                mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
                revert(0x1c, 0x04)
            }
        }
        _setOwner(newOwner);
    }

    /// @dev Allows the owner to renounce their ownership.
    function renounceOwnership() public payable virtual onlyOwner {
        _setOwner(address(0));
    }

    /// @dev Request a two-step ownership handover to the caller.
    /// The request will automatically expire in 48 hours (172800 seconds) by default.
    function requestOwnershipHandover() public payable virtual {
        unchecked {
            uint256 expires = block.timestamp + _ownershipHandoverValidFor();
            /// @solidity memory-safe-assembly
            assembly {
                // Compute and set the handover slot to `expires`.
                mstore(0x0c, _HANDOVER_SLOT_SEED)
                mstore(0x00, caller())
                sstore(keccak256(0x0c, 0x20), expires)
                // Emit the {OwnershipHandoverRequested} event.
                log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
            }
        }
    }

    /// @dev Cancels the two-step ownership handover to the caller, if any.
    function cancelOwnershipHandover() public payable virtual {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, caller())
            sstore(keccak256(0x0c, 0x20), 0)
            // Emit the {OwnershipHandoverCanceled} event.
            log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
        }
    }

    /// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
    /// Reverts if there is no existing ownership handover requested by `pendingOwner`.
    function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute and set the handover slot to 0.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            let handoverSlot := keccak256(0x0c, 0x20)
            // If the handover does not exist, or has expired.
            if gt(timestamp(), sload(handoverSlot)) {
                mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
                revert(0x1c, 0x04)
            }
            // Set the handover slot to 0.
            sstore(handoverSlot, 0)
        }
        _setOwner(pendingOwner);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   PUBLIC READ FUNCTIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns the owner of the contract.
    function owner() public view virtual returns (address result) {
        /// @solidity memory-safe-assembly
        assembly {
            result := sload(_OWNER_SLOT)
        }
    }

    /// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
    function ownershipHandoverExpiresAt(address pendingOwner)
        public
        view
        virtual
        returns (uint256 result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            // Compute the handover slot.
            mstore(0x0c, _HANDOVER_SLOT_SEED)
            mstore(0x00, pendingOwner)
            // Load the handover slot.
            result := sload(keccak256(0x0c, 0x20))
        }
    }

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

    /// @dev Marks a function as only callable by the owner.
    modifier onlyOwner() virtual {
        _checkOwner();
        _;
    }
}

lib/solady/src/utils/FixedPointMathLib.sol

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

/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
library FixedPointMathLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error ExpOverflow();

    /// @dev The operation failed, as the output exceeds the maximum value of uint256.
    error FactorialOverflow();

    /// @dev The operation failed, due to an overflow.
    error RPowOverflow();

    /// @dev The mantissa is too big to fit.
    error MantissaOverflow();

    /// @dev The operation failed, due to an multiplication overflow.
    error MulWadFailed();

    /// @dev The operation failed, due to an multiplication overflow.
    error SMulWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error DivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error SDivWadFailed();

    /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero.
    error MulDivFailed();

    /// @dev The division failed, as the denominator is zero.
    error DivFailed();

    /// @dev The full precision multiply-divide operation failed, either due
    /// to the result being larger than 256 bits, or a division by a zero.
    error FullMulDivFailed();

    /// @dev The output is undefined, as the input is less-than-or-equal to zero.
    error LnWadUndefined();

    /// @dev The input outside the acceptable domain.
    error OutOfDomain();

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

    /// @dev The scalar of ETH and most ERC20s.
    uint256 internal constant WAD = 1e18;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*              SIMPLIFIED FIXED POINT OPERATIONS             */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if gt(x, div(not(0), y)) {
                if y {
                    mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down.
    function sMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`.
            if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) {
                mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks.
    function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, y), WAD)
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up.
    function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`.
            if iszero(eq(div(z, y), x)) {
                if y {
                    mstore(0x00, 0xbac65e5b) // `MulWadFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            z := add(iszero(iszero(mod(z, WAD))), div(z, WAD))
        }
    }

    /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks.
    function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
            if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down.
    function sDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, WAD)
            // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`.
            if iszero(mul(y, eq(sdiv(z, WAD), x))) {
                mstore(0x00, 0x5c43740d) // `SDivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := sdiv(z, y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks.
    function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(mul(x, WAD), y)
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up.
    function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`.
            if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) {
                mstore(0x00, 0x7c5f487d) // `DivWadFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks.
    function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y))
        }
    }

    /// @dev Equivalent to `x` to the power of `y`.
    /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`.
    /// Note: This function is an approximation.
    function powWad(int256 x, int256 y) internal pure returns (int256) {
        // Using `ln(x)` means `x` must be greater than 0.
        return expWad((lnWad(x) * y) / int256(WAD));
    }

    /// @dev Returns `exp(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function expWad(int256 x) internal pure returns (int256 r) {
        unchecked {
            // When the result is less than 0.5 we return zero.
            // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`.
            if (x <= -41446531673892822313) return r;

            /// @solidity memory-safe-assembly
            assembly {
                // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as
                // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`.
                if iszero(slt(x, 135305999368893231589)) {
                    mstore(0x00, 0xa37bfec9) // `ExpOverflow()`.
                    revert(0x1c, 0x04)
                }
            }

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

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

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

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

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

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

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

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

    /// @dev Returns `ln(x)`, denominated in `WAD`.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln
    /// Note: This function is an approximation. Monotonically increasing.
    function lnWad(int256 x) internal pure returns (int256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            // We want to convert `x` from `10**18` fixed point to `2**96` fixed point.
            // We do this by multiplying by `2**96 / 10**18`. But since
            // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here
            // and add `ln(2**96 / 10**18)` at the end.

            // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`.
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // We place the check here for more optimal stack operations.
            if iszero(sgt(x, 0)) {
                mstore(0x00, 0x1615e638) // `LnWadUndefined()`.
                revert(0x1c, 0x04)
            }
            // forgefmt: disable-next-item
            r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff))

            // Reduce range of x to (1, 2) * 2**96
            // ln(2^k * x) = k * ln(2) + ln(x)
            x := shr(159, shl(r, x))

            // Evaluate using a (8, 8)-term rational approximation.
            // `p` is made monic, we will multiply by a scale factor later.
            // forgefmt: disable-next-item
            let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir.
                sar(96, mul(add(43456485725739037958740375743393,
                sar(96, mul(add(24828157081833163892658089445524,
                sar(96, mul(add(3273285459638523848632254066296,
                    x), x))), x))), x)), 11111509109440967052023855526967)
            p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857)
            p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526)
            p := sub(mul(p, x), shl(96, 795164235651350426258249787498))
            // We leave `p` in `2**192` basis so we don't need to scale it back up for the division.

            // `q` is monic by convention.
            let q := add(5573035233440673466300451813936, x)
            q := add(71694874799317883764090561454958, sar(96, mul(x, q)))
            q := add(283447036172924575727196451306956, sar(96, mul(x, q)))
            q := add(401686690394027663651624208769553, sar(96, mul(x, q)))
            q := add(204048457590392012362485061816622, sar(96, mul(x, q)))
            q := add(31853899698501571402653359427138, sar(96, mul(x, q)))
            q := add(909429971244387300277376558375, sar(96, mul(x, q)))

            // `p / q` is in the range `(0, 0.125) * 2**96`.

            // Finalization, we need to:
            // - Multiply by the scale factor `s = 5.549…`.
            // - Add `ln(2**96 / 10**18)`.
            // - Add `k * ln(2)`.
            // - Multiply by `10**18 / 2**96 = 5**18 >> 78`.

            // The q polynomial is known not to have zeros in the domain.
            // No scaling required because p is already `2**96` too large.
            p := sdiv(p, q)
            // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`.
            p := mul(1677202110996718588342820967067443963516166, p)
            // Add `ln(2) * k * 5**18 * 2**192`.
            // forgefmt: disable-next-item
            p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p)
            // Add `ln(2**96 / 10**18) * 5**18 * 2**192`.
            p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p)
            // Base conversion: mul `2**18 / 2**192`.
            r := sar(174, p)
        }
    }

    /// @dev Returns `W_0(x)`, denominated in `WAD`.
    /// See: https://en.wikipedia.org/wiki/Lambert_W_function
    /// a.k.a. Product log function. This is an approximation of the principal branch.
    /// Note: This function is an approximation. Monotonically increasing.
    function lambertW0Wad(int256 x) internal pure returns (int256 w) {
        // forgefmt: disable-next-item
        unchecked {
            if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`.
            (int256 wad, int256 p) = (int256(WAD), x);
            uint256 c; // Whether we need to avoid catastrophic cancellation.
            uint256 i = 4; // Number of iterations.
            if (w <= 0x1ffffffffffff) {
                if (-0x4000000000000 <= w) {
                    i = 1; // Inputs near zero only take one step to converge.
                } else if (w <= -0x3ffffffffffffff) {
                    i = 32; // Inputs near `-1/e` take very long to converge.
                }
            } else if (uint256(w >> 63) == uint256(0)) {
                /// @solidity memory-safe-assembly
                assembly {
                    // Inline log2 for more performance, since the range is small.
                    let v := shr(49, w)
                    let l := shl(3, lt(0xff, v))
                    l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)),
                        0x0706060506020504060203020504030106050205030304010505030400000000)), 49)
                    w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13))
                    c := gt(l, 60)
                    i := add(2, add(gt(l, 53), c))
                }
            } else {
                int256 ll = lnWad(w = lnWad(w));
                /// @solidity memory-safe-assembly
                assembly {
                    // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`.
                    w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll))
                    i := add(3, iszero(shr(68, x)))
                    c := iszero(shr(143, x))
                }
                if (c == uint256(0)) {
                    do { // If `x` is big, use Newton's so that intermediate values won't overflow.
                        int256 e = expWad(w);
                        /// @solidity memory-safe-assembly
                        assembly {
                            let t := mul(w, div(e, wad))
                            w := sub(w, sdiv(sub(t, x), div(add(e, t), wad)))
                        }
                        if (p <= w) break;
                        p = w;
                    } while (--i != uint256(0));
                    /// @solidity memory-safe-assembly
                    assembly {
                        w := sub(w, sgt(w, 2))
                    }
                    return w;
                }
            }
            do { // Otherwise, use Halley's for faster convergence.
                int256 e = expWad(w);
                /// @solidity memory-safe-assembly
                assembly {
                    let t := add(w, wad)
                    let s := sub(mul(w, e), mul(x, wad))
                    w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t)))))
                }
                if (p <= w) break;
                p = w;
            } while (--i != c);
            /// @solidity memory-safe-assembly
            assembly {
                w := sub(w, sgt(w, 2))
            }
            // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of
            // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation.
            if (c == uint256(0)) return w;
            int256 t = w | 1;
            /// @solidity memory-safe-assembly
            assembly {
                x := sdiv(mul(x, wad), t)
            }
            x = (t * (wad + lnWad(x)));
            /// @solidity memory-safe-assembly
            assembly {
                w := sdiv(x, add(wad, t))
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                  GENERAL NUMBER UTILITIES                  */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `a * b == x * y`, with full precision.
    function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y)
        internal
        pure
        returns (bool result)
    {
        /// @solidity memory-safe-assembly
        assembly {
            result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0))))
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv
    function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // 512-bit multiply `[p1 p0] = x * y`.
            // Compute the product mod `2**256` and mod `2**256 - 1`
            // then use the Chinese Remainder Theorem to reconstruct
            // the 512 bit result. The result is stored in two 256
            // variables such that `product = p1 * 2**256 + p0`.

            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`.
            for {} 1 {} {
                // If overflows.
                if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.

                    /*------------------- 512 by 256 division --------------------*/

                    // Make division exact by subtracting the remainder from `[p1 p0]`.
                    let r := mulmod(x, y, d) // Compute remainder using mulmod.
                    let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`.
                    // Make sure `z` is less than `2**256`. Also prevents `d == 0`.
                    // Placing the check here seems to give more optimal stack operations.
                    if iszero(gt(d, p1)) {
                        mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                        revert(0x1c, 0x04)
                    }
                    d := div(d, t) // Divide `d` by `t`, which is a power of two.
                    // Invert `d mod 2**256`
                    // Now that `d` is an odd number, it has an inverse
                    // modulo `2**256` such that `d * inv = 1 mod 2**256`.
                    // Compute the inverse by starting with a seed that is correct
                    // correct for four bits. That is, `d * inv = 1 mod 2**4`.
                    let inv := xor(2, mul(3, d))
                    // Now use Newton-Raphson iteration to improve the precision.
                    // Thanks to Hensel's lifting lemma, this also works in modular
                    // arithmetic, doubling the correct bits in each step.
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64
                    inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128
                    z :=
                        mul(
                            // Divide [p1 p0] by the factors of two.
                            // Shift in bits from `p1` into `p0`. For this we need
                            // to flip `t` such that it is `2**256 / t`.
                            or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                            mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256
                        )
                    break
                }
                z := div(z, d)
                break
            }
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision.
    /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits.
    /// Performs the full 512 bit calculation regardless.
    function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            let mm := mulmod(x, y, not(0))
            let p1 := sub(mm, add(z, lt(mm, z)))
            let t := and(d, sub(0, d))
            let r := mulmod(x, y, d)
            d := div(d, t)
            let inv := xor(2, mul(3, d))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            inv := mul(inv, sub(2, mul(d, inv)))
            z :=
                mul(
                    or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)),
                    mul(sub(2, mul(d, inv)), inv)
                )
        }
    }

    /// @dev Calculates `floor(x * y / d)` with full precision, rounded up.
    /// Throws if result overflows a uint256 or when `d` is zero.
    /// Credit to Uniswap-v3-core under MIT license:
    /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol
    function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        z = fullMulDiv(x, y, d);
        /// @solidity memory-safe-assembly
        assembly {
            if mulmod(x, y, d) {
                z := add(z, 1)
                if iszero(z) {
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
            }
        }
    }

    /// @dev Calculates `floor(x * y / 2 ** n)` with full precision.
    /// Throws if result overflows a uint256.
    /// Credit to Philogy under MIT license:
    /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol
    function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // Temporarily use `z` as `p0` to save gas.
            z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`.
            for {} 1 {} {
                if iszero(or(iszero(x), eq(div(z, x), y))) {
                    let k := and(n, 0xff) // `n`, cleaned.
                    let mm := mulmod(x, y, not(0))
                    let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`.
                    //         |      p1     |      z     |
                    // Before: | p1_0 ¦ p1_1 | z_0  ¦ z_1 |
                    // Final:  |   0  ¦ p1_0 | p1_1 ¦ z_0 |
                    // Check that final `z` doesn't overflow by checking that p1_0 = 0.
                    if iszero(shr(k, p1)) {
                        z := add(shl(sub(256, k), p1), shr(k, z))
                        break
                    }
                    mstore(0x00, 0xae47f702) // `FullMulDivFailed()`.
                    revert(0x1c, 0x04)
                }
                z := shr(and(n, 0xff), z)
                break
            }
        }
    }

    /// @dev Returns `floor(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
            if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := div(z, d)
        }
    }

    /// @dev Returns `ceil(x * y / d)`.
    /// Reverts if `x * y` overflows, or `d` is zero.
    function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(x, y)
            // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`.
            if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) {
                mstore(0x00, 0xad251c27) // `MulDivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(z, d))), div(z, d))
        }
    }

    /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`.
    function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) {
        /// @solidity memory-safe-assembly
        assembly {
            let g := n
            let r := mod(a, n)
            for { let y := 1 } 1 {} {
                let q := div(g, r)
                let t := g
                g := r
                r := sub(t, mul(r, q))
                let u := x
                x := y
                y := sub(u, mul(y, q))
                if iszero(r) { break }
            }
            x := mul(eq(g, 1), add(x, mul(slt(x, 0), n)))
        }
    }

    /// @dev Returns `ceil(x / d)`.
    /// Reverts if `d` is zero.
    function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(d) {
                mstore(0x00, 0x65244e4e) // `DivFailed()`.
                revert(0x1c, 0x04)
            }
            z := add(iszero(iszero(mod(x, d))), div(x, d))
        }
    }

    /// @dev Returns `max(0, x - y)`. Alias for `saturatingSub`.
    function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns `max(0, x - y)`.
    function saturatingSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(gt(x, y), sub(x, y))
        }
    }

    /// @dev Returns `min(2 ** 256 - 1, x + y)`.
    function saturatingAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(sub(0, lt(add(x, y), x)), add(x, y))
        }
    }

    /// @dev Returns `min(2 ** 256 - 1, x * y)`.
    function saturatingMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(sub(or(iszero(x), eq(div(mul(x, y), x), y)), 1), mul(x, y))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `condition ? x : y`, without branching.
    function ternary(bool condition, address x, address y) internal pure returns (address z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), iszero(condition)))
        }
    }

    /// @dev Returns `x != 0 ? x : y`, without branching.
    function coalesce(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(x)))
        }
    }

    /// @dev Returns `x != bytes32(0) ? x : y`, without branching.
    function coalesce(bytes32 x, bytes32 y) internal pure returns (bytes32 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(x)))
        }
    }

    /// @dev Returns `x != address(0) ? x : y`, without branching.
    function coalesce(address x, address y) internal pure returns (address z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := or(x, mul(y, iszero(shl(96, x))))
        }
    }

    /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`.
    /// Reverts if the computation overflows.
    function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`.
            if x {
                z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x`
                let half := shr(1, b) // Divide `b` by 2.
                // Divide `y` by 2 every iteration.
                for { y := shr(1, y) } y { y := shr(1, y) } {
                    let xx := mul(x, x) // Store x squared.
                    let xxRound := add(xx, half) // Round to the nearest number.
                    // Revert if `xx + half` overflowed, or if `x ** 2` overflows.
                    if or(lt(xxRound, xx), shr(128, x)) {
                        mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                        revert(0x1c, 0x04)
                    }
                    x := div(xxRound, b) // Set `x` to scaled `xxRound`.
                    // If `y` is odd:
                    if and(y, 1) {
                        let zx := mul(z, x) // Compute `z * x`.
                        let zxRound := add(zx, half) // Round to the nearest number.
                        // If `z * x` overflowed or `zx + half` overflowed:
                        if or(xor(div(zx, x), z), lt(zxRound, zx)) {
                            // Revert if `x` is non-zero.
                            if x {
                                mstore(0x00, 0x49f7642b) // `RPowOverflow()`.
                                revert(0x1c, 0x04)
                            }
                        }
                        z := div(zxRound, b) // Return properly scaled `zxRound`.
                    }
                }
            }
        }
    }

    /// @dev Returns the square root of `x`, rounded down.
    function sqrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`.
            z := 181 // The "correct" value is 1, but this saves a multiplication later.

            // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
            // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.

            // Let `y = x / 2**r`. We check `y >= 2**(k + 8)`
            // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`.
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffffff, shr(r, x))))
            z := shl(shr(1, r), z)

            // Goal was to get `z*z*y` within a small factor of `x`. More iterations could
            // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`.
            // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small.
            // That's not possible if `x < 256` but we can just verify those cases exhaustively.

            // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`.
            // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`.
            // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps.

            // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)`
            // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`,
            // with largest error when `s = 1` and when `s = 256` or `1/256`.

            // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`.
            // Then we can estimate `sqrt(y)` using
            // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`.

            // There is no overflow risk here since `y < 2**136` after the first branch above.
            z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181.

            // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))
            z := shr(1, add(z, div(x, z)))

            // If `x+1` is a perfect square, the Babylonian method cycles between
            // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor.
            // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
            z := sub(z, lt(div(x, z), z))
        }
    }

    /// @dev Returns the cube root of `x`, rounded down.
    /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license:
    /// https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/utils/math.vy
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrt(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // Makeshift lookup table to nudge the approximate log2 result.
            z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3)))
            // Newton-Raphson's.
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            z := div(add(add(div(x, mul(z, z)), z), z), 3)
            // Round down.
            z := sub(z, lt(div(x, mul(z, z)), z))
        }
    }

    /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down.
    function sqrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18);
            z = (1 + sqrt(x)) * 10 ** 9;
            z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1;
        }
        /// @solidity memory-safe-assembly
        assembly {
            z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down.
        }
    }

    /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down.
    /// Formally verified by xuwinnie:
    /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf
    function cbrtWad(uint256 x) internal pure returns (uint256 z) {
        unchecked {
            if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36);
            z = (1 + cbrt(x)) * 10 ** 12;
            z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3;
        }
        /// @solidity memory-safe-assembly
        assembly {
            let p := x
            for {} 1 {} {
                if iszero(shr(229, p)) {
                    if iszero(shr(199, p)) {
                        p := mul(p, 100000000000000000) // 10 ** 17.
                        break
                    }
                    p := mul(p, 100000000) // 10 ** 8.
                    break
                }
                if iszero(shr(249, p)) { p := mul(p, 100) }
                break
            }
            let t := mulmod(mul(z, z), z, p)
            z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down.
        }
    }

    /// @dev Returns `sqrt(x * y)`. Also called the geometric mean.
    function mulSqrt(uint256 x, uint256 y) internal pure returns (uint256 z) {
        if (x == y) return x;
        uint256 p = rawMul(x, y);
        if (y == rawDiv(p, x)) return sqrt(p);
        for (z = saturatingMul(rawAdd(sqrt(x), 1), rawAdd(sqrt(y), 1));; z = avg(z, p)) {
            if ((p = fullMulDivUnchecked(x, y, z)) >= z) break;
        }
    }

    /// @dev Returns the factorial of `x`.
    function factorial(uint256 x) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := 1
            if iszero(lt(x, 58)) {
                mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`.
                revert(0x1c, 0x04)
            }
            for {} x { x := sub(x, 1) } { z := mul(z, x) }
        }
    }

    /// @dev Returns the log2 of `x`.
    /// Equivalent to computing the index of the most significant bit (MSB) of `x`.
    /// Returns 0 if `x` is zero.
    function log2(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(r, shl(3, lt(0xff, shr(r, x))))
            // forgefmt: disable-next-item
            r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)),
                0x0706060506020504060203020504030106050205030304010505030400000000))
        }
    }

    /// @dev Returns the log2 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log2Up(uint256 x) internal pure returns (uint256 r) {
        r = log2(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(r, 1), x))
        }
    }

    /// @dev Returns the log10 of `x`.
    /// Returns 0 if `x` is zero.
    function log10(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(lt(x, 100000000000000000000000000000000000000)) {
                x := div(x, 100000000000000000000000000000000000000)
                r := 38
            }
            if iszero(lt(x, 100000000000000000000)) {
                x := div(x, 100000000000000000000)
                r := add(r, 20)
            }
            if iszero(lt(x, 10000000000)) {
                x := div(x, 10000000000)
                r := add(r, 10)
            }
            if iszero(lt(x, 100000)) {
                x := div(x, 100000)
                r := add(r, 5)
            }
            r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999)))))
        }
    }

    /// @dev Returns the log10 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log10Up(uint256 x) internal pure returns (uint256 r) {
        r = log10(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(exp(10, r), x))
        }
    }

    /// @dev Returns the log256 of `x`.
    /// Returns 0 if `x` is zero.
    function log256(uint256 x) internal pure returns (uint256 r) {
        /// @solidity memory-safe-assembly
        assembly {
            r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
            r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
            r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
            r := or(r, shl(4, lt(0xffff, shr(r, x))))
            r := or(shr(3, r), lt(0xff, shr(r, x)))
        }
    }

    /// @dev Returns the log256 of `x`, rounded up.
    /// Returns 0 if `x` is zero.
    function log256Up(uint256 x) internal pure returns (uint256 r) {
        r = log256(x);
        /// @solidity memory-safe-assembly
        assembly {
            r := add(r, lt(shl(shl(3, r), 1), x))
        }
    }

    /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`.
    /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent).
    function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) {
        /// @solidity memory-safe-assembly
        assembly {
            mantissa := x
            if mantissa {
                if iszero(mod(mantissa, 1000000000000000000000000000000000)) {
                    mantissa := div(mantissa, 1000000000000000000000000000000000)
                    exponent := 33
                }
                if iszero(mod(mantissa, 10000000000000000000)) {
                    mantissa := div(mantissa, 10000000000000000000)
                    exponent := add(exponent, 19)
                }
                if iszero(mod(mantissa, 1000000000000)) {
                    mantissa := div(mantissa, 1000000000000)
                    exponent := add(exponent, 12)
                }
                if iszero(mod(mantissa, 1000000)) {
                    mantissa := div(mantissa, 1000000)
                    exponent := add(exponent, 6)
                }
                if iszero(mod(mantissa, 10000)) {
                    mantissa := div(mantissa, 10000)
                    exponent := add(exponent, 4)
                }
                if iszero(mod(mantissa, 100)) {
                    mantissa := div(mantissa, 100)
                    exponent := add(exponent, 2)
                }
                if iszero(mod(mantissa, 10)) {
                    mantissa := div(mantissa, 10)
                    exponent := add(exponent, 1)
                }
            }
        }
    }

    /// @dev Convenience function for packing `x` into a smaller number using `sci`.
    /// The `mantissa` will be in bits [7..255] (the upper 249 bits).
    /// The `exponent` will be in bits [0..6] (the lower 7 bits).
    /// Use `SafeCastLib` to safely ensure that the `packed` number is small
    /// enough to fit in the desired unsigned integer type:
    /// ```
    ///     uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether));
    /// ```
    function packSci(uint256 x) internal pure returns (uint256 packed) {
        (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`.
        /// @solidity memory-safe-assembly
        assembly {
            if shr(249, x) {
                mstore(0x00, 0xce30380c) // `MantissaOverflow()`.
                revert(0x1c, 0x04)
            }
            packed := or(shl(7, x), packed)
        }
    }

    /// @dev Convenience function for unpacking a packed number from `packSci`.
    function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) {
        unchecked {
            unpacked = (packed >> 7) * 10 ** (packed & 0x7f);
        }
    }

    /// @dev Returns the average of `x` and `y`. Rounds towards zero.
    function avg(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = (x & y) + ((x ^ y) >> 1);
        }
    }

    /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity.
    function avg(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = (x >> 1) + (y >> 1) + (x & y & 1);
        }
    }

    /// @dev Returns the absolute value of `x`.
    function abs(int256 x) internal pure returns (uint256 z) {
        unchecked {
            z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255);
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y))
        }
    }

    /// @dev Returns the absolute distance between `x` and `y`.
    function dist(int256 x, int256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), lt(y, x)))
        }
    }

    /// @dev Returns the minimum of `x` and `y`.
    function min(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), slt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), gt(y, x)))
        }
    }

    /// @dev Returns the maximum of `x` and `y`.
    function max(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, y), sgt(y, x)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(uint256 x, uint256 minValue, uint256 maxValue)
        internal
        pure
        returns (uint256 z)
    {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), gt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), lt(maxValue, z)))
        }
    }

    /// @dev Returns `x`, bounded to `minValue` and `maxValue`.
    function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := xor(x, mul(xor(x, minValue), sgt(minValue, x)))
            z := xor(z, mul(xor(z, maxValue), slt(maxValue, z)))
        }
    }

    /// @dev Returns greatest common divisor of `x` and `y`.
    function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            for { z := x } y {} {
                let t := y
                y := mod(z, y)
                z := t
            }
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`,
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begins == end`, returns `t <= begin ? a : b`.
    function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end)
        internal
        pure
        returns (uint256)
    {
        if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
        if (t <= begin) return a;
        if (t >= end) return b;
        unchecked {
            if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin);
            return a - fullMulDiv(a - b, t - begin, end - begin);
        }
    }

    /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`.
    /// with `t` clamped between `begin` and `end` (inclusive).
    /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`).
    /// If `begins == end`, returns `t <= begin ? a : b`.
    function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end)
        internal
        pure
        returns (int256)
    {
        if (begin > end) (t, begin, end) = (~t, ~begin, ~end);
        if (t <= begin) return a;
        if (t >= end) return b;
        // forgefmt: disable-next-item
        unchecked {
            if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a),
                uint256(t - begin), uint256(end - begin)));
            return int256(uint256(a) - fullMulDiv(uint256(a - b),
                uint256(t - begin), uint256(end - begin)));
        }
    }

    /// @dev Returns if `x` is an even number. Some people may need this.
    function isEven(uint256 x) internal pure returns (bool) {
        return x & uint256(1) == uint256(0);
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                   RAW NUMBER OPERATIONS                    */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x + y`, without checking for overflow.
    function rawAdd(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x + y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x - y`, without checking for underflow.
    function rawSub(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x - y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x * y`, without checking for overflow.
    function rawMul(int256 x, int256 y) internal pure returns (int256 z) {
        unchecked {
            z = x * y;
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := div(x, y)
        }
    }

    /// @dev Returns `x / y`, returning 0 if `y` is zero.
    function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := sdiv(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mod(x, y)
        }
    }

    /// @dev Returns `x % y`, returning 0 if `y` is zero.
    function rawSMod(int256 x, int256 y) internal pure returns (int256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := smod(x, y)
        }
    }

    /// @dev Returns `(x + y) % d`, return 0 if `d` if zero.
    function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := addmod(x, y, d)
        }
    }

    /// @dev Returns `(x * y) % d`, return 0 if `d` if zero.
    function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) {
        /// @solidity memory-safe-assembly
        assembly {
            z := mulmod(x, y, d)
        }
    }
}

lib/solady/src/utils/ReentrancyGuard.sol

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

/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

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

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

    /// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
    /// 9 bytes is large enough to avoid collisions with lower slots,
    /// but not too large to result in excessive bytecode bloat.
    uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;

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

    /// @dev Guards a function from reentrancy.
    modifier nonReentrant() virtual {
        /// @solidity memory-safe-assembly
        assembly {
            if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
                mstore(0x00, 0xab143c06) // `Reentrancy()`.
                revert(0x1c, 0x04)
            }
            sstore(_REENTRANCY_GUARD_SLOT, address())
        }
        _;
        /// @solidity memory-safe-assembly
        assembly {
            sstore(_REENTRANCY_GUARD_SLOT, codesize())
        }
    }

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

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` does not implement `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), 0xa0, 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/KeeperPolicy.sol

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

/// @notice Keeper payment policy: proposes what verified work pays. PackVault calls it with a
///         bounded-gas staticcall, after the work, with facts the vault established itself; the
///         vault then pays at most its own envelope, free ETH and budget. A policy holds nothing,
///         moves nothing and cannot decide whether work happened. Replace it by deploying a new
///         contract and setting its address with the vault owner's `setPolicy` (D57, D58).
interface IKeeperPolicy {
    /// @notice Nonzero; the vault checks it before accepting a policy address.
    function policyVersion() external view returns (uint256);

    /// @param op          PackVault.OP_* (1 restock, 2 list, 3 sync, 5 unlist, 6 liquidate,
    ///                    8 checkpoint). Operations 4 and 7 are retired.
    /// @param units       completed units of work the vault counted (packs built, positions
    ///                    listed, resolved, activated or unlisted, items liquidated, 1 checkpoint).
    /// @param gasAllowance the vault's calibrated quoted gas for this work (base + per unit).
    /// @param essential   redemption or wind-down work.
    /// @param gasCeiling  the vault's gas ceiling, wei per gas.
    /// @param maxTip      the vault's tip allowance over basefee, wei per gas.
    /// @param workFee     the vault's flat fee per unit, wei.
    /// @return payment    proposed wei; the vault caps it.
    function quote(
        uint256 op,
        uint256 units,
        uint256 gasAllowance,
        bool essential,
        uint256 gasCeiling,
        uint256 maxTip,
        uint256 workFee
    ) external view returns (uint256 payment);
}

/// @notice V1: the gas allowance at basefee + maxTip, capped at the ceiling, plus the flat work fee
///         per completed unit. No premium: the work fee is the keeper's margin.
contract KeeperPolicyV1 is IKeeperPolicy {
    function policyVersion() external pure returns (uint256) {
        return 1;
    }

    function quote(uint256, uint256 units, uint256 gasAllowance, bool, uint256 gasCeiling, uint256 maxTip, uint256 workFee)
        external
        view
        returns (uint256)
    {
        uint256 price = block.basefee + maxTip;
        if (price > gasCeiling) price = gasCeiling;
        return gasAllowance * price + units * workFee;
    }
}

src/PackAccount.sol

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

import {ReentrancyGuard} from "solady/utils/ReentrancyGuard.sol";
import {Ownable} from "solady/auth/Ownable.sol";
import {VaultLib} from "./VaultLib.sol";
import {StrategyLib} from "./StrategyLib.sol";
import {IKeeperPolicy} from "./KeeperPolicy.sol";
import {IShapes, IShapePacks, IFWAV2, IFWARewards, IFWAToken} from "./interfaces/External.sol";

/// @title PackAccount
/// @notice One FWA strategy account: the shared operating surface of PackVault (pooled depositors)
///         and PackManager (one owner). Every operation runs the single strategy implementation
///         (StrategyLib, VaultLib, ScanLib) against this account's own `VaultLib.Strategy`, so this
///         contract is the FWA depositor and the owner of every Shape pack, listing and wei it
///         holds. Accounts share code, never assets or accounting.
/// @dev The concrete account defines what ETH is free (`_free`) and spendable on new exposure
///      (`_idle`), plus the facts only it knows: whether a checkpoint is due (`_checkpointMode`)
///      and how much ETH its owners are owed beyond what it holds (`_shortfall`, `_need`).
///      Maintenance is permissionless and paid by quote (D56) from this account's budgets only.
///      One owner (Solady Ownable): two-step handover only, never renounced (D76).
abstract contract PackAccount is ReentrancyGuard, Ownable {
    IFWAV2 public immutable fwa;
    IShapes public immutable shapes;
    IShapePacks public immutable packs;
    IFWARewards public immutable rewards;
    IFWAToken public immutable token;

    /// @notice Bytecode bounds shared by every account.
    uint256 public constant MAX_BATCH = VaultLib.MAX_BATCH;
    uint256 public constant MAX_LIST_BATCH = VaultLib.MAX_LIST_BATCH;
    uint256 public constant MAX_WORK_FEE = VaultLib.MAX_WORK_FEE;

    VaultLib.Strategy internal s;
    uint256 public deploymentBlock;

    event ParamsSet();
    event PolicyChanged(address indexed oldPolicy, address indexed newPolicy);

    error UnknownNft();

    constructor(IFWAV2 fwa_, IShapes shapes_, IShapePacks packs_) {
        fwa = fwa_;
        shapes = shapes_;
        packs = packs_;
        rewards = IFWARewards(fwa_.rewards());
        token = IFWAToken(fwa_.token());
    }

    /// @dev Owner, parameters, keeper policy, budgets and the FWA approval, set once.
    function _initStrategy(address owner_, VaultLib.Params memory p, address policy) internal {
        if (owner_ == address(0)) revert NewOwnerIsZeroAddress();
        _initializeOwner(owner_);
        deploymentBlock = block.number;
        s.book.acquisitionCursor = fwa.nextSequenceToProcess();
        s.book.pendingPlusOne = 1;
        s.params = p;
        VaultLib.checkBounds(s.params);
        VaultLib.checkPolicy(policy);
        s.policy = policy;
        s.budget = VaultLib.Budget(uint128(p.routineCap), uint128(p.essentialCap), block.timestamp);
        packs.setApprovalForAll(address(fwa), true);
    }

    // ------------------------------------------------------------------ account hooks

    /// @dev ETH this account may spend at all: balance less every liability it owes.
    function _free() internal view virtual returns (uint256);

    /// @dev ETH the strategy may commit to new exposure.
    function _idle() internal view virtual returns (uint256);

    /// @dev 0 none, 1 holder flows wait for a checkpoint, 2 a distribution checkpoint may be due.
    function _checkpointMode() internal view virtual returns (uint256) {
        return 0;
    }

    /// @dev ETH owed beyond free ETH and idle inventory: unlisting for it is essential.
    function _shortfall() internal view virtual returns (uint256) {
        return 0;
    }

    /// @dev ETH owed beyond liquid ETH: liquidation for it is allowed.
    function _need() internal view virtual returns (uint256) {
        return 0;
    }

    // ------------------------------------------------------------------ ETH and NFT intake

    /// @notice FWA's pushed payments are matched to their listing (StrategyLib.receipt); any
    ///         other ETH, and ETH forced in without a call, simply joins the balance.
    receive() external payable virtual {
        if (msg.sender == address(fwa)) StrategyLib.receipt(s.book, fwa, packs, msg.value);
    }

    /// @dev Only pack NFTs, the only NFTs the strategy creates or gets back from FWA.
    function onERC721Received(address, address, uint256, bytes calldata) external view returns (bytes4) {
        if (msg.sender != address(packs)) revert UnknownNft();
        return this.onERC721Received.selector;
    }

    // ------------------------------------------------------------------ strategy operations

    /// @notice Live economics: k, the backing a new listing of `units` x 0.01 ETH posts (0 when
    ///         it must not list) and whether it lists.
    function edge(uint256 units) public view returns (uint256, uint256, bool) {
        return StrategyLib.edge(s, fwa, packs, shapes, units);
    }

    /// @notice Mint packs of `units` straight into ShapePacks and list each at once.
    function build(uint256 units, uint256[] calldata backingProposals, uint256 minPay)
        external nonReentrant returns (uint256)
    {
        return StrategyLib.build(s, fwa, packs, shapes, units, backingProposals, minPay);
    }

    /// @notice Relist idle packs at bounded backing proposals, checked against live economics.
    function list(uint256[] calldata backingProposals, uint256 minPay) external nonReentrant returns (uint256) {
        return StrategyLib.list(s, fwa, packs, shapes, backingProposals, minPay);
    }

    /// @notice Bounded journal or scan job, terminal resolutions and allocation cleanup.
    function sync(uint256[] calldata listingIds, uint256 witnessId, uint256 minPay)
        external nonReentrant returns (uint256)
    {
        return StrategyLib.sync(s, fwa, packs, listingIds, witnessId, _checkpointMode(), minPay);
    }

    /// @notice Withdraw active listings: in wind-down, when FWA's live fees leave no edge, or for
    ///         ETH owed that free ETH and inventory cannot cover.
    function unlist(uint256[] calldata listingIds, uint256 minPay) external nonReentrant returns (uint256) {
        return StrategyLib.unlist(s, fwa, packs, listingIds, minPay, _shortfall());
    }

    /// @notice Redeem idle packs to ETH while ETH is owed beyond liquid ETH, or in wind-down.
    function liquidate(uint256 maxCount, uint256 minPay) external nonReentrant returns (uint256) {
        return StrategyLib.liquidate(s, packs, shapes, maxCount, minPay, _need());
    }

    /// @notice Caller-funded fee collection (never paid).
    function harvest(uint256[] calldata activeIds, uint256 minPay) external nonReentrant returns (uint256) {
        StrategyLib.harvest(s, fwa, activeIds, minPay);
        return 0;
    }

    /// @notice Claim and burn FWA token rewards (never valued, never sold; unpaid).
    function burnTokens(uint256[] calldata activeIds) external nonReentrant {
        StrategyLib.burnTokens(rewards, token, activeIds);
    }

    // ------------------------------------------------------------------ owner

    /// @notice Owner sets parameters at once, within the bytecode bounds (D58: no delay).
    function setParams(VaultLib.Params calldata p) external onlyOwner {
        // Budgets accrue at the old rates up to now; the new caps then only clamp, never refill.
        VaultLib.syncBudget(s.params, s.budget);
        s.params = p;
        VaultLib.checkBounds(s.params);
        VaultLib.syncBudget(s.params, s.budget);
        emit ParamsSet();
    }

    /// @notice Owner replaces the keeper payment policy at once (D57, D58); the account still caps
    ///         every offer at its envelope, free ETH and budget.
    function setPolicy(address policy) external onlyOwner {
        VaultLib.checkPolicy(policy);
        emit PolicyChanged(s.policy, policy);
        s.policy = policy;
    }

    /// @notice Disabled (D76): ownership moves only by the two-step handover (the new key calls
    ///         `requestOwnershipHandover`, then the owner calls `completeOwnershipHandover` within
    ///         48 hours). A renounced or mistyped owner could never pause or exit again.
    function renounceOwnership() public payable override {
        revert Unauthorized();
    }

    function transferOwnership(address) public payable override {
        revert Unauthorized();
    }

    // ------------------------------------------------------------------ views

    function getParams() external view returns (VaultLib.Params memory) { return s.params; }
    function keeperPolicy() external view returns (IKeeperPolicy) { return IKeeperPolicy(s.policy); }
    function listingPaused() external view returns (bool) { return s.listingPaused; }
    function windingDown() external view returns (bool) { return s.windingDown; }
    function openListingCount() external view returns (uint256) { return s.book.open.length; }
    function openListingAt(uint256 index) external view returns (uint256) { return s.book.open[index]; }
    function idlePackCount() external view returns (uint256) { return s.book.idlePacks.length; }
    function idlePackAt(uint256 index) external view returns (uint256) { return s.book.idlePacks[index]; }
    function recoveryPackCount() external view returns (uint256) { return s.book.recoveryPacks.length; }
    function recoveryPackAt(uint256 index) external view returns (uint256) { return s.book.recoveryPacks[index]; }
    function recoveryUnsealed(uint256 id) external view returns (bool) { return s.book.recoveryUnsealed[id]; }
    function position(uint256 id) external view returns (VaultLib.Position memory) { return s.book.positions[id]; }
    function idleValueOf(uint256 id) external view returns (uint256) { return s.book.idleValueOf[id]; }
    function idleFunding() external view returns (uint256) { return s.book.idleFunding; }
    function acquisitionCursor() external view returns (uint64) { return s.book.acquisitionCursor; }
    function pendingReceipts() external view returns (uint256) { return s.book.pendingPlusOne - 1; }
    function reservedCount() external view returns (uint256) { return s.book.reservedCount; }
    function idForBacking(uint256 backing) external view returns (uint256) { return s.book.idForBacking[backing]; }
    function receipts(uint256 id) external view returns (VaultLib.Receipt memory) { return s.book.receipts[id]; }
    function debtCount(uint256 debt) external view returns (uint256) { return s.book.countByDebt[debt]; }

    function totals() external view returns (uint256 tracked, uint256 idle, uint256 backing, uint256 active,
        uint256 debt, uint256 allocated)
    {
        VaultLib.Book storage b = s.book;
        return (b.trackedValue, b.idleValue, b.activeBacking, b.activeCount, b.feeDebtSum, b.allocatedValue);
    }

    function allocationState() external view returns (uint256 head, uint256 length, uint256 id, uint64 at, bool stale) {
        VaultLib.Book storage b = s.book;
        head = b.allocationHead;
        length = b.allocationQueue.length;
        if (head != length) {
            id = b.allocationQueue[head];
            at = b.positions[id].allocatedAt;
            stale = b.positions[id].state != VaultLib.ALLOCATED;
        }
    }

    /// @notice Book value now: free ETH, tracked inventory, active backing, FWA fee credit and
    ///         pending fees (exact, by witness). Reverts until the journal and receipts are current.
    function accountedNav(uint256 witnessId) public view returns (uint256) {
        return VaultLib.accountedNav(s.book, fwa, packs, _free(), witnessId);
    }

    function freeEth() external view returns (uint256) { return _free(); }
    function idleEth() external view returns (uint256) { return _idle(); }

    /// @notice Keeper budget available now: routine (strategy) and essential (exit work).
    function budget() external view returns (uint256 routine, uint256 essential) {
        return VaultLib.budgetNow(s.params, s.budget);
    }
}

src/ScanLib.sol

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

import {VaultLib} from "./VaultLib.sol";
import {IFWAV2, IFWAView, IShapePacks, LISTING_ACTIVE, LISTING_ALLOCATED, LISTING_SETTLED} from "./interfaces/External.sol";

/// @notice The read half of VaultLib's scan proof, a separate library only for EIP-170 size.
library ScanLib {
    /// @dev Every position the book holds Allocated must still be Allocated at FWA. A settlement
    ///      pays the account in its own transaction; if receive() could not record the receipt
    ///      (forced ETH), the cash would otherwise count beside the position until it is synced.
    ///      Reads at most MAX_ALLOCATION_SCAN queue entries from the head (else CatchUpFirst: sync
    ///      and prune first), so pricing cost never grows with allocation history.
    ///      A kick refunds B the same way, so while FWA can kick (the ShapePacks oracle exemption
    ///      lifted) and the account holds at most MAX_ALLOCATION_SCAN open entries, every booked
    ///      Active listing must also still be Active at FWA. Above that the check is skipped, not
    ///      refused, so pricing never stalls on FWA's exemption: an unrecorded kick refund needs
    ///      receive() to exceed FWA's 100,000 gas stipend (it uses 35,148), and with the exemption in
    ///      place no listing can be kicked.
    function requireAllocatedCurrent(VaultLib.Book storage b, IFWAV2 f, IShapePacks packs)
        external view returns (uint256 entries, uint256 reads)
    {
        uint256 n = b.open.length;
        if (b.activeCount != 0 && n <= VaultLib.MAX_ALLOCATION_SCAN && !f.oracleExemptCollections(address(packs))) {
            entries = n;
            for (uint256 i; i < n; ++i) {
                uint256 id = b.open[i];
                if (b.positions[id].state != VaultLib.ACTIVE) continue;
                ++reads;
                if (IFWAView(address(f)).listings(id).status != LISTING_ACTIVE) revert VaultLib.PendingReceipts();
            }
        }
        if (b.allocatedValue == 0) return (entries, reads);
        uint256 head = b.allocationHead;
        uint256 queued = b.allocationQueue.length - head;
        if (queued > VaultLib.MAX_ALLOCATION_SCAN) revert VaultLib.CatchUpFirst();
        entries += queued;
        for (uint256 i = head; i < head + queued; ++i) {
            uint256 id = b.allocationQueue[i];
            if (b.positions[id].state != VaultLib.ALLOCATED) continue;
            ++reads;
            uint8 status = IFWAView(address(f)).listings(id).status;
            // A bid pays nothing and returns the pack: the booked position already counts it.
            if (status == LISTING_ALLOCATED || (status == LISTING_SETTLED
                && (VaultLib.owns(packs, b.positions[id].packId) || f.stuckNFTRecipient(id) == address(this)))) continue;
            revert VaultLib.PendingReceipts();
        }
    }

    function rebase(VaultLib.Book storage b, IFWAV2 f) external returns (bool, uint256 scanned, uint256 own) {
        uint64 end = f.nextSequenceToProcess();
        uint256 backlog = end - b.acquisitionCursor;
        // Taken only when it costs no more than the next journal batch: a small vault's upkeep then
        // scales with its own positions, not with FWA's global activity, and the scan stays within
        // the journal batch's gas envelope.
        uint256 batch = backlog < VaultLib.MAX_JOURNAL ? backlog : VaultLib.MAX_JOURNAL;
        if (backlog == 0 || b.open.length * VaultLib.Q_SCAN > batch * VaultLib.Q_JOURNAL) return (false, 0, 0);
        uint256[] memory found = new uint256[](VaultLib.MAX_SELECTIONS);
        for (uint256 i; i < b.open.length; ++i) {
            uint256 id = b.open[i];
            if (b.positions[id].state != VaultLib.ACTIVE) continue;
            ++scanned;
            IFWAView.Listing memory l = IFWAView(address(f)).listings(id);
            if (l.status != LISTING_ALLOCATED && l.status != LISTING_SETTLED) continue;
            if (own == found.length) return (false, 0, 0);
            uint256 x = uint256(l.allocatedAt) << 192 | id;
            uint256 j = own++;
            for (; j != 0 && found[j - 1] > x; --j) found[j] = found[j - 1];
            found[j] = x;
        }
        if (own != 0 && found[0] >> 192 < b.lastAllocatedAt) return (false, 0, 0);
        for (uint256 i; i < own; ++i) VaultLib.select(b, uint192(found[i]), uint64(found[i] >> 192));
        b.acquisitionCursor = end;
        emit VaultLib.JournalProgress(end, 0, own);
        return (true, scanned, own);
    }
}

src/StrategyLib.sol

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

import {FixedPointMathLib as M} from "solady/utils/FixedPointMathLib.sol";
import {VaultLib, IAccount} from "./VaultLib.sol";
import {
    IShapes,
    IShapePacks,
    IFWAV2,
    IFWAView,
    IFWARewards,
    IFWAToken,
    LISTING_ACTIVE,
    LISTING_WITHDRAWN,
    LISTING_SETTLED
} from "./interfaces/External.sol";

/// @notice The one implementation of the FWA pack strategy's operations, shared by the pooled
///         PackVault and every PackManager. Linked and DELEGATECALLed: it runs in the calling
///         account's context against that account's `VaultLib.Strategy`, so the account is the
///         FWA depositor, holds every asset and pays its own keepers. It has no asset withdrawal
///         path: ETH leaves only as FWA backing, Shapes mint payments, or keeper pay capped by the
///         account's budgets and `freeEth()`. Ownership rules (shares, owner withdrawals) stay in
///         the accounts. Callers wrap every entry point in their own reentrancy guard.
library StrategyLib {
    uint256 internal constant BPS = 10_000;
    uint256 internal constant UNIT = 0.01 ether;
    uint256 internal constant CROWN_EXIT_WINDOW = 12 hours; // FWA early crown exit costs 1%
    uint256 internal constant MAX_LIQUIDATE_UNITS = 60; // ordinary packs: at most 60 Shapes burned

    /// Operation ids passed to the keeper policy (stable across versions; 4 and 7 are retired).
    uint256 internal constant OP_BUILD = 1;
    uint256 internal constant OP_LIST = 2;
    uint256 internal constant OP_SYNC = 3;
    uint256 internal constant OP_UNLIST = 5;
    uint256 internal constant OP_LIQUIDATE = 6;

    event Built(uint256 packs, uint256 units);
    event Listed(uint256 indexed listingId, uint256 packId, uint256 backing);
    event Unlisted(uint256 indexed listingId);
    event Liquidated(uint256 packs, uint256 shapes, uint256 ethOut);
    event TokensBurned(uint256 amount);

    error WindingDown();
    error Paused();
    error Nothing();
    error Amount();
    error Payment();
    error UnlistNotAllowed();

    // ------------------------------------------------------------------ economics

    /// @notice Live economics for a pack of `units`: k, the backing a new listing posts (0 when it
    ///         must not list) and whether it lists.
    function edge(VaultLib.Strategy storage s, IFWAV2 f, IShapePacks packs, IShapes shapes, uint256 units)
        public view returns (uint256, uint256, bool)
    {
        return VaultLib.edge(s.params, f, address(packs), units, VaultLib.buildCost(s.params, units, shapes.mintFee()));
    }

    // ------------------------------------------------------------------ inventory

    /// @notice Mint new packs of `units` straight into ShapePacks and list each at once, one
    ///         backing proposal per pack. Only while listing is open and a keep cycle repays the
    ///         build at today's quoted price (VaultLib.buildAndList).
    function build(VaultLib.Strategy storage s, IFWAV2 f, IShapePacks packs, IShapes shapes, uint256 units,
        uint256[] calldata proposals, uint256 minPay) external returns (uint256)
    {
        _requireListing(s, f);
        _precheck(s, minPay, false);
        VaultLib.buildAndList(s.params, s.book, f, packs, shapes, units, proposals, IAccount(address(this)).idleEth());
        uint256 count = proposals.length;
        emit Built(count, units);
        (, uint256 n) = VaultLib.makeup(units);
        return _pay(s, OP_BUILD, VaultLib.Q_BUILD + count * (VaultLib.buildGas(n) + VaultLib.Q_LISTED), 2 * count,
            false, minPay, type(uint256).max);
    }

    /// @notice Relist idle packs (returned by bids, withdrawals or expiry) at bounded proposals,
    ///         checked against live economics. No mint: a returned pack is reused as is.
    function list(VaultLib.Strategy storage s, IFWAV2 f, IShapePacks packs, IShapes shapes,
        uint256[] calldata proposals, uint256 minPay) external returns (uint256)
    {
        _requireListing(s, f);
        _precheck(s, minPay, false);
        if (proposals.length > VaultLib.MAX_LIST_BATCH) revert Amount();
        VaultLib.Book storage b = s.book;
        uint256 available = IAccount(address(this)).idleEth();
        uint256 fee = shapes.mintFee();
        uint256 listed;
        while (listed < proposals.length && b.idlePacks.length != 0) {
            uint256 packId = b.idlePacks[b.idlePacks.length - 1];
            uint256 units = b.idleValueOf[packId] / UNIT;
            uint256 backing = proposals[listed];
            VaultLib.validateBacking(s.params, b, f, address(packs), units, backing,
                VaultLib.buildCost(s.params, units, fee), false);
            if (available < backing) break;
            available -= backing;
            emit Listed(VaultLib.admit(b, f, packs, packId, backing), packId, backing);
            ++listed;
        }
        if (listed == 0) revert Nothing();
        return _pay(s, OP_LIST, VaultLib.Q_LIST + listed * VaultLib.Q_LISTED, listed, false, minPay, type(uint256).max);
    }

    function _requireListing(VaultLib.Strategy storage s, IFWAV2 f) private view {
        if (s.windingDown) revert WindingDown();
        if (s.listingPaused) revert Paused();
        // FWA stages listings while acquisitions are unsettled; nothing this account lists is staged.
        if (f.unsettledAcquisitionCount() != 0) revert Nothing();
    }

    // ------------------------------------------------------------------ positions

    /// @notice Bounded journal or scan job, terminal resolutions and allocation cleanup.
    ///         `checkpointMode` is 0 for an account without checkpoints.
    function sync(VaultLib.Strategy storage s, IFWAV2 f, IShapePacks packs, uint256[] calldata listingIds,
        uint256 witnessId, uint256 checkpointMode, uint256 minPay) external returns (uint256)
    {
        (uint256 gasQ, uint256 units) =
            VaultLib.syncChanges(s.params, s.budget, s.book, f, packs, listingIds, checkpointMode, witnessId);
        return _pay(s, OP_SYNC, gasQ, units, false, minPay, type(uint256).max);
    }

    /// @notice Withdraw active listings: in wind-down (exit), when `shortfall` ETH is owed beyond
    ///         what free ETH and inventory cover (essential), or when FWA's live fees leave no edge
    ///         (routine). A stale quote or a gas spike stops new listings but never unwinds earning
    ///         ones. Exits never read FWA's economics, so a hostile oracle or fee cannot block them.
    function unlist(VaultLib.Strategy storage s, IFWAV2 f, IShapePacks packs, uint256[] calldata listingIds,
        uint256 minPay, uint256 shortfall) external returns (uint256)
    {
        if (listingIds.length > VaultLib.MAX_BATCH) revert Amount();
        bool essential = s.windingDown || shortfall != 0;
        if (!essential) {
            (uint256 k,,) = VaultLib.economics(f, address(packs));
            if (k >= 1e18 + uint256(s.params.minEdgeBps) * 1e14) revert UnlistNotAllowed();
        }
        _precheck(s, minPay, essential);
        VaultLib.Book storage b = s.book;
        uint256 realized;
        uint256 moved;
        for (uint256 i; i < listingIds.length; ++i) {
            uint256 id = listingIds[i];
            if (b.openIndex[id] == 0) continue;
            if (f.topListingId() == id && block.timestamp < f.topListingSince() + CROWN_EXIT_WINDOW) continue;
            (,,,,,,,,,, uint8 status) = f.listings(id);
            if (status != LISTING_ACTIVE) continue;
            VaultLib.Position memory pos = b.positions[id];
            VaultLib.withdraw(b, f, packs, id);
            emit Unlisted(id);
            realized += pos.backing + pos.value;
            ++moved;
            if (!s.windingDown && shortfall != 0 && realized >= shortfall) break;
        }
        if (realized == 0) revert Nothing();
        return _pay(s, OP_UNLIST, VaultLib.Q_UNLIST + moved * VaultLib.Q_UNLISTED, moved, essential, minPay,
            type(uint256).max);
    }

    /// @notice Redeem up to `maxCount` idle packs to ETH at their exact backing, or one bounded
    ///         recovery chunk, while `need` ETH is still owed beyond free ETH, or freely in wind-down.
    function liquidate(VaultLib.Strategy storage s, IShapePacks packs, IShapes shapes, uint256 maxCount,
        uint256 minPay, uint256 need) external returns (uint256)
    {
        if (!s.windingDown && need == 0) revert Nothing();
        _precheck(s, minPay, true);
        VaultLib.Book storage b = s.book;
        maxCount = M.min(maxCount, VaultLib.MAX_BATCH);
        uint256 before = address(this).balance;
        uint256 supplyBefore = shapes.totalSupply();
        uint256 n;
        uint256 units;
        uint256 recovery;
        uint256 recoveryGas;
        while (n + recovery < maxCount && (s.windingDown || address(this).balance - before < need)) {
            if (b.idlePacks.length != 0) {
                uint256 packId = b.idlePacks[b.idlePacks.length - 1];
                uint256 value = b.idleValueOf[packId];
                if (units + value / UNIT > MAX_LIQUIDATE_UNITS) break;
                units += value / UNIT;
                VaultLib.redeemInventory(b, packId);
                packs.redeem(packId);
                ++n;
            } else if (b.recoveryPacks.length != 0) {
                if (n != 0) break;
                // Recovery is one isolated chunk of at most 30 underlying Shapes.
                recoveryGas = VaultLib.recoverInventory(b, packs, shapes);
                ++recovery;
                break;
            } else {
                break;
            }
        }
        if (n + recovery == 0) revert Nothing();
        // Pay only for the Shapes actually burned; recovery is isolated from this loop.
        uint256 burned = n == 0 ? 0 : supplyBefore - shapes.totalSupply();
        if (n != 0 && (burned == 0 || burned > MAX_LIQUIDATE_UNITS)) revert Amount();
        emit Liquidated(n + recovery, burned, address(this).balance - before);
        return _pay(s, OP_LIQUIDATE, VaultLib.Q_LIQUIDATE + n * VaultLib.Q_LIQ_PACK + burned * VaultLib.Q_REDEEM_SHAPE
            + recoveryGas, n + recovery, true, minPay, type(uint256).max);
    }

    // ------------------------------------------------------------------ fees, tokens, receipts

    /// @notice Caller-funded fee collection: never paid (positive `minPay` reverts).
    function harvest(VaultLib.Strategy storage s, IFWAV2 f, uint256[] calldata activeIds, uint256 minPay) external {
        if (minPay != 0) revert Payment();
        uint256 before = address(this).balance;
        VaultLib.harvest(s.book, f, activeIds);
        if (address(this).balance == before) revert Nothing();
    }

    /// @notice Claim depositor FWA token rewards and burn every FWA token held. Tokens are never
    ///         valued or sold (D43). Unpaid.
    function burnTokens(IFWARewards rewards, IFWAToken token, uint256[] calldata activeIds) external {
        if (activeIds.length > VaultLib.MAX_BATCH) revert Amount();
        // FWA's claim reverts for the whole batch on one inactive listing, or with nothing pending.
        if (activeIds.length != 0) try rewards.claimDepositorTokens(activeIds) {} catch {}
        if (rewards.tokenCredit(address(this)) != 0) rewards.withdrawTokens();
        uint256 amount = token.balanceOf(address(this));
        if (amount == 0) revert Nothing();
        token.burn(amount);
        emit TokensBurned(amount);
    }

    /// @notice Identify ETH FWA pushes to this account outside its own calls: a keep payment
    ///         B (1 - s) or a kick refund B, matched to the open listing with exactly that unique
    ///         backing. Unmatched ETH stays in the balance as free ETH. Called from `receive()`,
    ///         which FWA invokes with a 100,000 gas stipend.
    function receipt(VaultLib.Book storage b, IFWAV2 f, IShapePacks packs, uint256 amount) external {
        if (b.controlled) return;
        uint256 fee = f.ownerSettlementFeeBps();
        if (fee < BPS) {
            uint256 denominator = BPS - fee;
            if (amount % denominator == 0 && amount / denominator <= type(uint256).max / BPS) {
                if (_identify(b, f, packs, amount / denominator * BPS, 1, fee, amount)) return;
            }
        }
        _identify(b, f, packs, amount, 2, fee, amount);
    }

    function _identify(VaultLib.Book storage b, IFWAV2 f, IShapePacks packs, uint256 backing, uint8 kind,
        uint256 fee, uint256 amount) private returns (bool)
    {
        uint256 id = b.idForBacking[backing];
        if (id == 0 || b.receipts[id].kind != 0 || amount > type(uint128).max) return false;
        IFWAView.Listing memory l = IFWAView(address(f)).listings(id);
        // Admission authenticated the pack and ordinary classification; FWA never changes that
        // identity, and a lookup is retired before its pack can leave or relist.
        if (l.depositor != address(this) || l.collection != address(packs) || l.value != backing) return false;
        if (kind == 1) {
            if (l.status != LISTING_SETTLED || f.stuckNFTRecipient(id) != address(0)
                || packs.ownerOf(l.tokenId) != address(f)) return false;
        } else if (l.status != LISTING_WITHDRAWN) return false;
        b.receipts[id] = VaultLib.Receipt(uint128(amount), uint16(fee), kind, true);
        ++b.pendingPlusOne;
        emit VaultLib.CashReceipt(id, kind, amount);
        return true;
    }

    // ------------------------------------------------------------------ keeper pay

    /// @notice Pay the caller for verified work (VaultLib.pay): the least of the policy's offer,
    ///         the envelope, `cap`, the account's free ETH and its budget.
    function pay(VaultLib.Strategy storage s, uint256 op, uint256 gasQ, uint256 units, bool essential,
        uint256 minPay, uint256 cap) external returns (uint256)
    {
        return _pay(s, op, gasQ, units, essential, minPay, cap);
    }

    /// @notice Revert before the work when `minPay` already exceeds what could be paid.
    function precheck(VaultLib.Strategy storage s, uint256 minPay, bool essential) external view {
        _precheck(s, minPay, essential);
    }

    function _pay(VaultLib.Strategy storage s, uint256 op, uint256 gasQ, uint256 units, bool essential,
        uint256 minPay, uint256 cap) private returns (uint256)
    {
        return VaultLib.pay(s.params, s.budget, s.policy, op, gasQ, units, essential, minPay, cap,
            IAccount(address(this)).freeEth());
    }

    function _precheck(VaultLib.Strategy storage s, uint256 minPay, bool essential) private view {
        if (minPay != 0) VaultLib.precheck(s.params, s.budget, minPay, essential, IAccount(address(this)).freeEth());
    }
}

src/VaultLib.sol

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

import {FixedPointMathLib as M} from "solady/utils/FixedPointMathLib.sol";
import {IKeeperPolicy} from "./KeeperPolicy.sol";
import {ScanLib} from "./ScanLib.sol";
import {
    IFWAV2,
    IFWAView,
    IFloorOracle,
    IShapePacks,
    IShapes,
    LISTING_ACTIVE,
    LISTING_ALLOCATED,
    LISTING_SETTLED,
    LISTING_WITHDRAWN
} from "./interfaces/External.sol";

/// @notice What the shared strategy reads from the account it runs in (PackVault or PackManager):
///         ETH it may spend on keeper pay (`freeEth`) and on new exposure (`idleEth`). Each
///         account defines both from its own liabilities; the strategy never sees them otherwise.
interface IAccount {
    function freeEth() external view returns (uint256);
    function idleEth() external view returns (uint256);
}

/// @notice PackVault's share-price reads, used only for its distribution checkpoint tail.
interface ISyncVault is IAccount {
    function accountedNav(uint256 witnessId) external view returns (uint256);
    function totalShares() external view returns (uint256);
    function highWaterMark() external view returns (uint256);
}

/// @notice Shared strategy core, linked into PackVault and PackManager (with StrategyLib and
///         ScanLib). Runs by DELEGATECALL in the calling account's context, so that account is the
///         FWA depositor and owns every asset; the library holds no state and reads only the
///         storage pointers it is passed. Split into three libraries only for EIP-170 size.
library VaultLib {
    uint256 internal constant BPS = 10_000;
    uint256 internal constant DEAD_SHARES = 1e15;
    uint256 internal constant MIN_DISTRIBUTION = 0.01 ether;

    /// @notice PackVault's governed parameters (moved here so library code can read them by
    ///         storage pointer; EIP-170 size).
    struct Params {
        uint16 minEdgeBps; // require k >= 1 + minEdge
        uint16 bufferBps; // list at cap x (1 - buffer), so a small ask cut does not trigger kicks
        uint16 distributionBps; // share of new gains above the high-water mark paid out
        uint16 payMarkupBps; // envelope markup on the quoted gas of routine work (V1 pays none)
        uint16 keeperShareBps; // optional calls are paid only if pay <= this share of value realized
        uint16 allocatedBoundBps; // checkpoint skips when Allocated value exceeds this share of NAV
        uint64 packUnitsMask; // bit u set: packs of u x 0.01 ETH may be built and listed
        uint64 gasCeiling; // wei per gas, routine work
        uint64 essentialCeiling; // wei per gas, redemption and wind-down work (essential budget)
        uint64 maxTip; // reimbursed price is at most basefee + this
        uint64 workFee; // flat wei per unit of work done: position listed, resolved,
        //                 unlisted, item liquidated, or a checkpoint that priced flows
        uint64 routineCap; // keeper budget for strategy work: capacity (wei) and refill per day
        uint64 routineRate;
        uint64 essentialCap; // keeper budget for redemption and wind-down work
        uint64 essentialRate;
        uint128 reserve; // ETH kept idle
        uint128 tvlCap; // deposits refused above this NAV
    }


    uint256 internal constant UNIT = 0.01 ether;

    /// @notice Everything the shared strategy owns in an account: governed parameters, keeper
    ///         budgets, the position book, the keeper payment policy and the two operating flags.
    struct Strategy {
        Params params;
        Budget budget;
        Book book;
        address policy;
        bool listingPaused;
        bool windingDown;
    }

    // ---------------------------------------------------------------- bounds and quotes

    uint256 internal constant MAX_WORK_FEE = 0.00005 ether; // per unit of work (D55, D56)
    uint256 internal constant MAX_MIN_EDGE_BPS = 1_000;
    uint256 internal constant MAX_BUFFER_BPS = 2_000;
    uint256 internal constant MAX_GAS_CEILING = 50 gwei;
    uint256 internal constant MAX_DISTRIBUTION_BPS = 5_000;
    uint256 internal constant MAX_PAY_MARKUP_BPS = 1_000; // routine work only (D56, D57)
    uint256 internal constant MAX_KEEPER_SHARE_BPS = 5_000;
    uint256 internal constant MAX_ALLOCATED_BOUND_BPS = 1_000;
    uint256 internal constant MAX_ROUTINE_CAP = 0.3 ether;
    uint256 internal constant MAX_ROUTINE_RATE = 0.02 ether;
    uint256 internal constant MAX_ESSENTIAL_CAP = 0.1 ether;
    uint256 internal constant MAX_ESSENTIAL_RATE = 0.005 ether;
    uint256 internal constant MAX_PACK_UNITS = 30; // at most 30 x 0.01 ETH: bounded redemption work
    uint256 internal constant MIN_PACK_UNITS = 3; // ShapePacks' minimum pack value, 0.03 ETH
    uint256 internal constant REF_UNITS = 6; // the reference recipe: one 0.05 and one 0.01 Shape

    /// Purchaser keep incentive. A selected purchaser keeps the pack when it is worth more than the
    /// best bid FWA offers (ETH or token bid), after the gas to redeem it, by at least this much.
    uint256 internal constant MIN_KEEP_ADVANTAGE = 0.0003 ether;
    /// ShapePacks.redeem gas: a pack plus each Shape it holds. Measured on a fork (execution gas):
    /// 2 Shapes 157,023, 5 Shapes 245,212, 7 Shapes (the most any allowed size holds) 304,115.
    uint256 internal constant Q_PURCHASER_REDEEM_PACK = 100_000;
    uint256 internal constant Q_PURCHASER_REDEEM_SHAPE = 30_000;
    /// The purchaser's redeem gas is priced at this fixed bound, independent of the keeper's gas
    /// ceiling: keeping stays the better choice for any purchaser paying up to 2 gwei.
    uint256 internal constant PURCHASER_GAS_PRICE = 2 gwei;

    /// Fixed gas quotes from billed receipts (keeper/measure_gas.py, docs/GAS.md). The journal
    /// always consumes its full bounded job; only a required checkpoint can pay for a foreign
    /// tail. Fee collection has no independently paid entry point. These eligibility rules keep
    /// callers from splitting work merely to collect additional bases.
    // One checkpoint per interval cannot be split, so it is quoted at measured billed gas.
    uint256 internal constant Q_CHECKPOINT = 360_000;
    /// Checkpoint proof that booked allocations are still Allocated at FWA (ScanLib), per queue
    /// entry examined and per FWA listing read.
    uint256 internal constant Q_ALLOCATION_ENTRY = 6_000;
    uint256 internal constant Q_ALLOCATION_READ = 30_000;
    uint256 internal constant Q_BUILD = 300_000; // call base for build-and-list (one 0.06 pack billed 1,667,619 in all)
    // createPack minting straight into the pack (ForkDirectMint: 381k / 534k / 627k gas for 1 / 2 / 3 Shapes)
    uint256 internal constant Q_BUILD_PACK = 300_000;
    uint256 internal constant Q_BUILD_SHAPE = 130_000;
    uint256 internal constant Q_LIST = 280_000;
    uint256 internal constant Q_LISTED = 825_000;
    uint256 internal constant Q_SYNC = 85_000;
    uint256 internal constant Q_REQUIRED_TAIL = 120_000;
    uint256 internal constant Q_DISTRIBUTION_PROOF = 80_000;
    uint256 internal constant Q_JOURNAL = 22_000; // each completed global acquisition
    uint256 internal constant Q_SCAN = 30_000; // each Active position's FWA listing read (scan proof)
    uint256 internal constant Q_SELECTED = 180_000; // own selection bookkeeping
    uint256 internal constant Q_SYNCED = 120_000; // terminal or recovered return
    uint256 internal constant Q_PRUNED = 45_000; // resolved allocation head
    uint256 internal constant Q_POSITION_SYNC = Q_JOURNAL + Q_SELECTED + Q_SYNCED + Q_PRUNED;
    uint256 internal constant Q_UNLIST = 340_000;
    uint256 internal constant Q_UNLISTED = 285_000;
    uint256 internal constant Q_LIQUIDATE = 75_000;
    uint256 internal constant Q_LIQ_PACK = 80_000; // fixed work per ordinary pack
    uint256 internal constant Q_REDEEM_SHAPE = 35_000;
    uint256 internal constant Q_RECOVERY_BASE = 100_000;
    uint256 internal constant Q_RECOVERY_SHAPE = 35_000;
    uint256 internal constant Q_RECOVERY_UNSEAL = 70_000;
    uint256 internal constant Q_HARVESTED = 80_000; // per listing with fees claimed
    uint256 internal constant Q_CREDIT = 40_000;
    uint256 internal constant Q_FUND = 40_000;
    /// A bid cycle's quoted gas: select and resolve, relist, and the fee claim that funds it.
    uint256 internal constant CYCLE_GAS = Q_POSITION_SYNC + Q_LISTED + Q_HARVESTED;
    /// A reference position (0.06 ETH pack + ~0.0648 backing): what request charges are scaled by.
    uint256 internal constant POSITION_VALUE = 0.1248 ether;

    uint256 internal constant MAX_BATCH = 16;
    uint256 internal constant MAX_JOURNAL = 128;
    uint256 internal constant MAX_SELECTIONS = 16;
    /// Pricing reads at most this many allocation queue entries. The queue from its head holds only
    /// allocations newer than the oldest unresolved one, which a checkpoint already requires to be
    /// inside FWA's settlement window, so a longer queue waits at most one window for sync.
    uint256 internal constant MAX_ALLOCATION_SCAN = 32;
    uint256 internal constant MAX_TERMINALS = 16;
    uint256 internal constant MAX_PRUNES = 16;
    uint256 internal constant MAX_LIST_BATCH = 8;
    uint256 internal constant LIST_CALL_GAS = 1_200_000;
    uint256 internal constant MAX_REDEEM_SHAPES = 30; // Shapes burned per liquidation call
    uint8 internal constant NONE = 0;
    uint8 internal constant ACTIVE = 1;
    uint8 internal constant ALLOCATED = 2;
    uint8 internal constant OWED = 3;

    struct Position {
        uint256 packId;
        uint256 value;
        uint256 backing;
        uint256 feeDebt;
        uint64 allocatedAt;
        uint8 state;
    }

    struct Work { uint256 processed; uint256 own; uint256 resolved; uint256 pruned; uint256 scanned; }

    struct BackingTerms {
        uint256 k;
        uint256 desired;
        uint256 cap;
        uint256 settlementFee;
        uint256 value;
        uint256 floor;
        uint256 cycleCost;
        uint256 build;
        bool ok;
    }

    struct Receipt { uint128 amount; uint16 feeBps; uint8 kind; bool initialized; }

    /// @dev Inventory indexes and all financial totals share this single authoritative book.
    struct Book {
        mapping(uint256 => Position) positions;
        mapping(uint256 => uint256) idleValueOf;
        mapping(uint256 => uint256) packToListing;
        uint256 trackedValue;
        uint256 idleValue;
        uint256 activeBacking;
        uint256 activeCount;
        uint256 feeDebtSum;
        mapping(uint256 => uint256) countByDebt;
        uint256 allocatedValue;
        uint256[] allocationQueue;
        uint256 allocationHead;
        uint64 lastAllocatedAt;
        uint256[] open;
        mapping(uint256 => uint256) openIndex;
        uint256[] idlePacks;
        uint256[] recoveryPacks;
        mapping(uint256 => bool) recoveryUnsealed;
        mapping(uint256 => uint256) idleQuote;
        uint256 idleFunding;
        mapping(uint256 => uint256) idForBacking;
        mapping(uint256 => Receipt) receipts;
        uint256 pendingPlusOne;
        uint256 reservedCount;
        uint64 acquisitionCursor;
        bool controlled;
    }

    event PositionUpdated(uint256 indexed listingId, uint256 packId, uint256 value, uint256 backing, uint256 feeDebt, uint64 allocatedAt, uint8 state);
    event InventoryUpdated(uint256 indexed packId, uint256 value);
    event RecoveryUpdated(uint256 indexed packId, uint256 value, bool unsealed);
    event CashReceipt(uint256 indexed listingId, uint8 outcome, uint256 amount);
    event ReceiptConsumed(uint256 indexed listingId);
    event JournalProgress(uint64 cursor, uint256 processed, uint256 own);

    error Duplicate();
    error MissingInventory();
    error WrongState();
    error InsufficientBacking();
    error BadWitness();
    error NeedsPrune();
    error OutOfOrder();
    error InvalidListing();
    error InvalidJournal();
    error CatchUpFirst();
    error PendingReceipts();
    error InvalidBacking();
    error BadBatch();
    error Nothing();

    /// @notice One checkpoint's redemption fill. Owed rounds up and a partial fill leaves 2 wei of
    ///         headroom, so the rounded-up reserve never exceeds the ETH actually freed. `unit` is
    ///         ETH per locked share x 1e36; holders claim floor(shares x unit) and the reserve
    ///         (`paid`) rounds the same unit up over the never-understated locked total.
    function fill(uint256 locked, uint256 nav, uint256 supply, uint256 liquid)
        external
        pure
        returns (uint256 frac, uint256 filled, uint256 unit, uint256 paid)
    {
        uint256 owed = M.mulDivUp(locked, nav, supply);
        frac = owed <= liquid ? 1e36 : M.mulDiv(liquid > 2 ? liquid - 2 : 0, 1e36, owed);
        filled = M.mulDiv(locked, frac, 1e36);
        unit = M.mulDiv(frac, nav, supply);
        paid = M.mulDivUp(locked, unit, 1e36);
    }

    error OutOfBounds();

    /// Gas a keeper policy's quote may use: enough for arithmetic and reads, not for griefing.
    uint256 internal constant POLICY_GAS = 50_000;
    uint256 internal constant ORACLE_GAS = 100_000; // floor oracle read; FWA's own oracle uses far less

    /// @notice The active keeper policy's proposed pay for verified work, from a bounded-gas
    ///         staticcall. A revert, out-of-gas or short answer is zero; only the first word of
    ///         the answer is read, so a policy cannot grief with huge return data.
    function offer(
        address policy,
        uint256 op,
        uint256 units,
        uint256 gasQ,
        bool essential,
        uint256 gasCeiling,
        uint256 maxTip,
        uint256 workFee
    ) public view returns (uint256 o) {
        bytes memory c = abi.encodeCall(IKeeperPolicy.quote, (op, units, gasQ, essential, gasCeiling, maxTip, workFee));
        assembly ("memory-safe") {
            // Yul evaluates arguments right to left: check returndatasize only after the call.
            let ok := staticcall(POLICY_GAS, policy, add(c, 32), mload(c), 0, 32)
            if and(ok, gt(returndatasize(), 31)) { o := mload(0) }
        }
    }

    /// @notice A keeper policy must be a contract answering `policyVersion()` with a nonzero value.
    function checkPolicy(address policy) external view {
        if (policy.code.length == 0) revert OutOfBounds();
        try IKeeperPolicy(policy).policyVersion() returns (uint256 v) {
            if (v == 0) revert OutOfBounds();
        } catch {
            revert OutOfBounds();
        }
    }

    // ---------------------------------------------------------------- keeper pay (D56, D57)

    /// Keeper budgets: levels as of `at`; each refills at its daily rate up to its cap.
    struct Budget {
        uint128 routine;
        uint128 essential;
        uint256 at;
    }

    event KeeperPaid(address indexed keeper, uint256 amount);

    error Payment();

    /// @notice The vault's envelope for work: quoted gas at basefee + maxTip, capped at the
    ///         ceiling, markup on routine work, plus work fees. The most this work may ever pay.
    function quote(Params storage p, uint256 gasQ, uint256 units, bool essential) public view returns (uint256 q) {
        q = gasQ * M.min(block.basefee + p.maxTip, essential ? p.essentialCeiling : p.gasCeiling);
        if (!essential) q = q * (BPS + p.payMarkupBps) / BPS;
        q += units * p.workFee;
    }

    function budgetNow(Params storage p, Budget storage b) public view returns (uint256 r, uint256 e) {
        uint256 dt = block.timestamp - b.at;
        r = M.min(p.routineCap, b.routine + dt * p.routineRate / 1 days);
        e = M.min(p.essentialCap, b.essential + dt * p.essentialRate / 1 days);
    }

    /// @notice Accrue both budgets to now; caps lowered since only clamp, never refill.
    function syncBudget(Params storage p, Budget storage b) external {
        (uint256 r, uint256 e) = budgetNow(p, b);
        (b.routine, b.essential, b.at) = (uint128(r), uint128(e), block.timestamp);
    }

    /// @notice Pay the caller for verified work: the least of the policy's offer, the vault's
    ///         envelope for that work, `cap` (a funding source), free ETH and the budget. Below
    ///         `minPay` the whole call reverts; with 0 the work is done for whatever is paid.
    function pay(
        Params storage p,
        Budget storage b,
        address policy,
        uint256 op,
        uint256 gasQ,
        uint256 units,
        bool essential,
        uint256 minPay,
        uint256 cap,
        uint256 free
    ) external returns (uint256 amount) {
        (uint256 r, uint256 e) = budgetNow(p, b);
        // A finite `cap` is the request-charge pool: requesters already paid for this work, so it
        // is bounded by the pool, not by the holders' budgets.
        bool charged = cap != type(uint256).max;
        if (charged) (r, e) = (type(uint256).max, type(uint256).max);
        uint256 o =
            offer(policy, op, units, gasQ, essential, essential ? p.essentialCeiling : p.gasCeiling, p.maxTip, p.workFee);
        amount = M.min(M.min(o, M.min(quote(p, gasQ, units, essential), cap)), M.min(free, essential ? e : r));
        if (amount < minPay) revert Payment();
        if (!charged) {
            (b.routine, b.essential, b.at) =
                (uint128(essential ? r : r - amount), uint128(essential ? e - amount : e), block.timestamp);
        }
        if (amount == 0) return 0;
        (bool ok,) = msg.sender.call{value: amount}("");
        if (!ok) revert Payment();
        emit KeeperPaid(msg.sender, amount);
    }

    // ---------------------------------------------------------------- parameters and charges

    /// @notice Bytecode bounds on every parameter.
    function checkBounds(Params storage p) external view {
        if (
            p.minEdgeBps > MAX_MIN_EDGE_BPS || p.bufferBps > MAX_BUFFER_BPS || p.distributionBps > MAX_DISTRIBUTION_BPS
                || p.payMarkupBps > MAX_PAY_MARKUP_BPS || p.workFee > MAX_WORK_FEE || p.keeperShareBps > MAX_KEEPER_SHARE_BPS
                || p.allocatedBoundBps > MAX_ALLOCATED_BOUND_BPS
                || p.gasCeiling > MAX_GAS_CEILING || p.essentialCeiling > MAX_GAS_CEILING || p.maxTip > p.gasCeiling
                || p.routineCap > MAX_ROUTINE_CAP || p.routineRate > MAX_ROUTINE_RATE || p.essentialCap > MAX_ESSENTIAL_CAP
                || p.essentialRate > MAX_ESSENTIAL_RATE
                || p.packUnitsMask >> (MAX_PACK_UNITS + 1) != 0 || p.packUnitsMask & ((1 << MIN_PACK_UNITS) - 1) != 0
        ) revert OutOfBounds();
    }

    /// @notice ShapePacks makeup for a pack of `units` x 0.01 ETH, minted straight into the pack:
    ///         fewest Shapes from the 0.1, 0.05 and 0.01 denominations (index 2, 1, 0 of the nine).
    ///         Six units are one 0.05 and one 0.01 Shape: two paid primary mints.
    function makeup(uint256 units) internal pure returns (uint32[] memory counts, uint256 shapeCount) {
        counts = new uint32[](9);
        counts[2] = uint32(units / 10);
        counts[1] = uint32(units % 10 / 5);
        counts[0] = uint32(units % 5);
        shapeCount = uint256(counts[0]) + counts[1] + counts[2];
    }

    function buildGas(uint256 shapeCount) internal pure returns (uint256) {
        return Q_BUILD_PACK + shapeCount * Q_BUILD_SHAPE;
    }

    /// @notice Building one pack of `units` and listing it, at the envelope now, plus its paid
    ///         primary mint fees (one per Shape).
    function buildCost(Params storage p, uint256 units, uint256 mintFee) public view returns (uint256) {
        (, uint256 n) = makeup(units);
        return quote(p, buildGas(n) + Q_LISTED, 2, false) + n * mintFee;
    }

    /// @notice A request's checkpoint charge: one checkpoint at its envelope, at cost plus one unit.
    function requestCharge(Params storage p) external view returns (uint256) {
        return quote(p, Q_CHECKPOINT, 1, true);
    }

    /// @notice Deployment charge per POSITION_VALUE deposited: building and listing one reference
    ///         position at its envelope now plus its mint fees, and never less than the most a
    ///         builder can net over its own gas (markup at the ceiling, the tip it is repaid but
    ///         need not pay, and the two work fees).
    function deployCharge(Params storage p, uint256 mintFee) external view returns (uint256) {
        (, uint256 n) = makeup(REF_UNITS);
        uint256 g = buildGas(n) + Q_LISTED;
        return M.max(quote(p, g, 2, false) + mintFee * n,
            g * (p.gasCeiling * p.payMarkupBps + p.maxTip * (BPS + p.payMarkupBps)) / BPS + 2 * p.workFee);
    }

    /// @notice Unwind charge per POSITION_VALUE redeemed: unlisting and liquidating one position.
    function unwindCharge(Params storage p) external view returns (uint256) {
        // No essential budget means exit work is unpaid (withdrawers run it): nothing to charge.
        if (p.essentialCap == 0) return 0;
        (, uint256 n) = makeup(REF_UNITS);
        return quote(p, Q_UNLISTED + Q_LIQ_PACK + n * Q_REDEEM_SHAPE, 2, true);
    }

    /// @notice Backing for a new listing of a pack of `units` x 0.01 ETH, and whether to list.
    ///         FWA splits each acquisition fee evenly over active listings and selects by 1/B, so a
    ///         listing expects fees k B before selection. A selected purchaser then keeps the pack
    ///         (the account gets B (1 - s) back) or takes FWA's best bid, max(ETH, token) x B (the
    ///         account keeps the pack and loses B). Backing is the largest amount at which keeping
    ///         still beats the best bid by MIN_KEEP_ADVANTAGE after the gas to redeem the pack, so
    ///         purchasers keep packs and each keep pays for fresh primary mints. It lists only when
    ///         both outcomes are profitable after the keeper pay of the cycle (`_profitable`), it
    ///         is at least P / 0.95 (a keep never loses at FWA's immutable 5% settlement-fee cap),
    ///         and FWA's oracle cap less the buffer allows it (FWA exempts ShapePacks today).
    function edge(Params storage p, IFWAV2 f, address packs, uint256 units, uint256 build)
        public
        view
        returns (uint256 k1e18, uint256 backing, bool ok)
    {
        BackingTerms memory t = _backingTerms(p, f, packs, units, build);
        return (t.k, t.desired, t.ok);
    }

    function _backingTerms(Params storage p, IFWAV2 f, address packs, uint256 units, uint256 build)
        private view returns (BackingTerms memory t)
    {
        (t.k, t.cap, t.settlementFee) = economics(f, packs);
        t.value = units * UNIT;
        t.build = build;
        t.floor = t.value + t.value / 19 + (t.value % 19 == 0 ? 0 : 1);
        uint256 bid = M.max(f.settlementDiscountBps(), f.tokenSettlementDiscountBps());
        (, uint256 shapes) = makeup(units);
        uint256 margin =
            MIN_KEEP_ADVANTAGE + (Q_PURCHASER_REDEEM_PACK + shapes * Q_PURCHASER_REDEEM_SHAPE) * PURCHASER_GAS_PRICE;
        if (bid != 0 && t.value > margin) t.desired = (t.value - margin) * BPS / bid / BPS * BPS;
        if (t.cap != type(uint256).max) t.desired = M.min(t.desired, t.cap * (BPS - p.bufferBps) / BPS);
        t.cycleCost = quote(p, CYCLE_GAS, 2, false);
        t.ok = t.cap != 0 && t.k >= 1e18 + uint256(p.minEdgeBps) * 1e14 && t.desired >= t.floor
            && _profitable(t, t.desired, false);
        if (!t.ok) t.desired = 0;
    }

    /// @dev Both outcomes of one selection clear the keeper pay of the cycle: the bid outcome
    ///      B (k - 1), and the keep outcome B (k - s) - P, which also repays the replacement build
    ///      when the pack is newly built. Requires k >= 1 (checked before).
    function _profitable(BackingTerms memory t, uint256 backing, bool newlyBuilt) private pure returns (bool) {
        return backing * (t.k - 1e18) / 1e18 > t.cycleCost
            && backing * (t.k - t.settlementFee * 1e14) / 1e18 >= t.value + t.cycleCost + (newlyBuilt ? t.build : 0);
    }


    /// @notice Revert before the work when `minPay` already exceeds what could be paid.
    function precheck(Params storage p, Budget storage b, uint256 minPay, bool essential, uint256 free)
        external
        view
    {
        (uint256 r, uint256 e) = budgetNow(p, b);
        if (minPay > M.min(free, essential ? e : r)) revert Payment();
    }

    function owns(IShapePacks packs, uint256 packId) internal view returns (bool) {
        try packs.ownerOf(packId) returns (address o) {
            return o == address(this);
        } catch {
            return false;
        }
    }

    /// @notice Live k (1e18 scale) and FWA's backing cap for `packs` (zero when FWA would refuse
    ///         a listing). k = (1 + surcharge)(1 - protocolCut)(1 - crownShare).
    function economics(IFWAV2 f, address packs) internal view returns (uint256 k1e18, uint256 cap, uint256 s) {
        s = f.ownerSettlementFeeBps();
        uint256 w = f.totalWeight();
        if (w == 0) return (0, 0, s);
        // FWA exposes no getter for its surcharge: acquisitionFee = (wbt / w) (1 + surcharge).
        uint256 ev = f.weightedBackingTotal() / w;
        uint256 oneSur = f.acquisitionFee() * 1e18 / ev; // 1e18 x (1 + surcharge), floors
        k1e18 = oneSur * (BPS - f.ownerAcquisitionFeeBps()) / BPS * (BPS - f.topListingShareBps()) / BPS;
        if (!f.canDeposit(packs)) return (k1e18, 0, s);
        // FWA exempts the collection from its floor cap: no cap applies (D62).
        if (f.oracleExemptCollections(packs)) return (k1e18, type(uint256).max, s);
        // The oracle ask plus premium when the quote passes FWA's own validity rules.
        // A failing or malformed oracle means no cap (nothing new lists); it must not block
        // unlisting, wind-down or redemptions. FWA's owner can repoint the oracle to any contract,
        // so the read is a raw staticcall: a revert or short return data both mean "no cap".
        // Bounded gas and a manual four-word read: a gas-burning oracle or one returning words that
        // do not fit their types (which would make abi.decode revert) also means "no cap" (audit S1).
        address o = f.floorOracle();
        bytes memory c = abi.encodeCall(IFloorOracle.getFloorRange, (packs));
        bool ok;
        uint256 bid;
        uint256 ask;
        uint256 observedAt;
        uint256 periodUsed;
        assembly ("memory-safe") {
            let m := mload(0x40) // scratch past the free pointer; not kept
            ok := staticcall(ORACLE_GAS, o, add(c, 32), mload(c), m, 128)
            if lt(returndatasize(), 128) { ok := 0 }
            bid := mload(m)
            ask := mload(add(m, 32))
            observedAt := mload(add(m, 64))
            periodUsed := mload(add(m, 96))
        }
        if (!ok || observedAt > type(uint48).max || periodUsed > type(uint48).max) return (k1e18, 0, s);
        if (bid == 0 || bid >= ask || observedAt == 0 || observedAt > block.timestamp) return (k1e18, 0, s);
        if (block.timestamp - observedAt > f.maxOracleAge()) return (k1e18, 0, s);
        if (periodUsed < f.minOracleChallengePeriod()) return (k1e18, 0, s);
        cap = ask * (BPS + f.oracleCeilingPremiumBps()) / BPS;
    }

    function _emitPosition(Book storage b, uint256 id) internal {
        Position storage p = b.positions[id];
        emit PositionUpdated(id, p.packId, p.value, p.backing, p.feeDebt, p.allocatedAt, p.state);
    }

    function addInventory(Book storage b, uint256 packId, uint256 value) internal {
        if (value == 0 || b.idleValueOf[packId] != 0 || b.packToListing[packId] != 0) revert Duplicate();
        b.trackedValue += value;
        b.idleValue += value;
        _toIdle(b, packId, value, 0);
    }

    function _toIdle(Book storage b, uint256 packId, uint256 value, uint256 backingQuote) private {
        if (b.idleValueOf[packId] != 0) revert Duplicate();
        b.idleValueOf[packId] = value;
        if (value > MAX_PACK_UNITS * UNIT) {
            b.recoveryPacks.push(packId);
            emit RecoveryUpdated(packId, value, false);
        } else {
            b.idlePacks.push(packId);
            emit InventoryUpdated(packId, value);
        }
        b.idleQuote[packId] = backingQuote;
        b.idleFunding += backingQuote;
    }

    function list(Book storage b, uint256 id, uint256 packId, uint256 backing, uint256 debt) internal {
        if (id == 0 || b.positions[id].value != 0 || b.packToListing[packId] != 0) revert Duplicate();
        uint256 value = b.idleValueOf[packId];
        if (value == 0) revert MissingInventory();
        if (backing < value + value / 19 + (value % 19 == 0 ? 0 : 1)) revert InsufficientBacking();
        delete b.idleValueOf[packId];
        b.idleValue -= value;
        b.idleFunding -= b.idleQuote[packId];
        delete b.idleQuote[packId];
        if (b.idlePacks[b.idlePacks.length - 1] != packId) revert MissingInventory();
        b.idlePacks.pop();
        emit InventoryUpdated(packId, 0);
        b.positions[id] = Position(packId, value, backing, debt, 0, ACTIVE);
        b.packToListing[packId] = id;
        b.open.push(id);
        b.openIndex[id] = b.open.length;
        b.activeBacking += backing;
        ++b.activeCount;
        b.feeDebtSum += debt;
        ++b.countByDebt[debt];
        _emitPosition(b, id);
    }

    /// @dev Every caller (`_syncJournal`, `ScanLib.rebase`) must move the cursor past this selection's
    ///      sequence in the same call; completeness of both proofs relies on it.
    function select(Book storage b, uint256 id, uint64 at) internal {
        Position storage p = b.positions[id];
        if (p.state != ACTIVE) revert WrongState();
        if (at < b.lastAllocatedAt) revert OutOfOrder();
        _removeActive(b, p);
        p.state = ALLOCATED;
        p.allocatedAt = at;
        b.lastAllocatedAt = at;
        b.allocatedValue += p.value;
        b.allocationQueue.push(id);
        _emitPosition(b, id);
    }

    function keep(Book storage b, uint256 id) internal returns (Position memory p) {
        p = b.positions[id];
        if (p.state != ALLOCATED) revert WrongState();
        b.allocatedValue -= p.value;
        b.trackedValue -= p.value;
        _retire(b, id, p.packId);
    }

    function returnPack(Book storage b, uint256 id, bool owned) internal returns (Position memory p) {
        Position storage live = b.positions[id];
        p = live;
        if (p.state == ACTIVE) _removeActive(b, live);
        else if (p.state == ALLOCATED) b.allocatedValue -= p.value;
        else revert WrongState();
        if (owned) {
            _retire(b, id, p.packId);
            b.idleValue += p.value;
            _toIdle(b, p.packId, p.value, p.backing);
        } else {
            live.state = OWED;
            _emitPosition(b, id);
        }
    }

    function claimReturned(Book storage b, uint256 id) internal returns (Position memory p) {
        p = b.positions[id];
        if (p.state != OWED) revert WrongState();
        _retire(b, id, p.packId);
        b.idleValue += p.value;
        _toIdle(b, p.packId, p.value, p.backing);
    }

    function redeemInventory(Book storage b, uint256 packId) internal returns (uint256 value) {
        value = b.idleValueOf[packId];
        if (value == 0 || b.idlePacks[b.idlePacks.length - 1] != packId) revert MissingInventory();
        delete b.idleValueOf[packId];
        b.idleValue -= value;
        b.trackedValue -= value;
        b.idleFunding -= b.idleQuote[packId];
        delete b.idleQuote[packId];
        b.idlePacks.pop();
        emit InventoryUpdated(packId, 0);
    }

    function updateFeeDebt(Book storage b, uint256 id, uint256 debt) internal {
        Position storage p = b.positions[id];
        if (p.state != ACTIVE) revert WrongState();
        uint256 old = p.feeDebt;
        if (old == debt) return;
        if (debt < old) revert OutOfOrder();
        --b.countByDebt[old];
        ++b.countByDebt[debt];
        b.feeDebtSum = b.feeDebtSum - old + debt;
        p.feeDebt = debt;
        _emitPosition(b, id);
    }

    function pendingFees(Book storage b, uint256 witnessId, uint256 actualPending) internal view returns (uint256) {
        uint256 n = b.activeCount;
        if (n == 0) return 0;
        Position storage p = b.positions[witnessId];
        if (p.state != ACTIVE) revert BadWitness();
        uint256 d = p.feeDebt;
        if (actualPending == 0) {
            if (b.countByDebt[d] + b.countByDebt[d + 1] != n) revert BadWitness();
            return 0;
        }
        uint256 a = d + actualPending;
        return n * a + b.countByDebt[a + 1] - b.feeDebtSum;
    }

    function nav(Book storage b, uint256 freeEth, uint256 credit, uint256 witnessId, uint256 actualPending)
        internal view returns (uint256)
    {
        return freeEth + b.trackedValue + b.activeBacking + credit + pendingFees(b, witnessId, actualPending);
    }

    function prune(Book storage b, uint256 maxCount) internal returns (uint256 advanced) {
        uint256 head = b.allocationHead;
        while (advanced < maxCount && head < b.allocationQueue.length) {
            if (b.positions[b.allocationQueue[head]].state == ALLOCATED) break;
            delete b.allocationQueue[head];
            ++head;
            ++advanced;
        }
        b.allocationHead = head;
    }

    function oldestAllocation(Book storage b) internal view returns (uint256 id, uint64 at) {
        if (b.allocationHead == b.allocationQueue.length) return (0, 0);
        id = b.allocationQueue[b.allocationHead];
        Position storage p = b.positions[id];
        if (p.state != ALLOCATED) revert NeedsPrune();
        at = p.allocatedAt;
    }

    function _removeActive(Book storage b, Position storage p) internal {
        b.activeBacking -= p.backing;
        --b.activeCount;
        b.feeDebtSum -= p.feeDebt;
        --b.countByDebt[p.feeDebt];
    }

    function _retire(Book storage b, uint256 id, uint256 packId) private {
        b.positions[id].state = NONE;
        delete b.packToListing[packId];
        uint256 idx = b.openIndex[id] - 1;
        uint256 last = b.open[b.open.length - 1];
        b.open[idx] = last;
        b.openIndex[last] = idx + 1;
        b.open.pop();
        delete b.openIndex[id];
        _emitPosition(b, id);
    }

    function listing(IFWAV2 f, uint256 id) internal view returns (IFWAView.Listing memory) {
        return IFWAView(address(f)).listings(id);
    }

    function _validate(IFWAView.Listing memory l, IShapePacks packs, uint256 packId, uint256 backing) private view {
        if (l.depositor != address(this) || l.collection != address(packs)
            || l.tokenId != packId || l.value != backing) revert InvalidListing();
    }

    function admit(Book storage b, IFWAV2 f, IShapePacks packs, uint256 packId, uint256 backing)
        public returns (uint256 id)
    {
        // Backing identifies this listing's cash receipt: two open listings may never share it.
        if (b.idForBacking[backing] != 0) revert Duplicate();
        _rebaseUnexposed(b, f);
        uint256 active = f.activeListingCount();
        // FWA's private staging FIFO may activate foreign listings during admission.
        // Bound even a reverting attempt, and reject every incidental activation atomically.
        try f.listNFT{value: backing, gas: LIST_CALL_GAS}(address(packs), packId) returns (uint256 admitted) {
            id = admitted;
        } catch {
            revert InvalidListing();
        }
        IFWAView.Listing memory l = listing(f, id);
        if (l.status != LISTING_ACTIVE || f.activeListingCount() != active + 1 || f.fwairListing(id)) revert InvalidListing();
        _validate(l, packs, packId, backing);
        b.receipts[id].initialized = true;
        b.idForBacking[backing] = id;
        ++b.reservedCount;
        list(b, id, packId, backing, l.feeDebt);
    }

    function release(Book storage b, uint256 id, uint256 backing) private {
        if (b.idForBacking[backing] != id) revert InvalidListing();
        delete b.idForBacking[backing];
        --b.reservedCount;
        if (b.receipts[id].kind != 0) {
            --b.pendingPlusOne;
            emit ReceiptConsumed(id);
        }
        delete b.receipts[id];
    }

    function syncChanges(Params storage p, Budget storage budget, Book storage b, IFWAV2 f, IShapePacks packs,
        uint256[] calldata ids, uint256 checkpointMode, uint256 witnessId)
        external returns (uint256 gasQ, uint256 units)
    {
        bool distributionTail;
        (gasQ, units, distributionTail) = _syncChanges(p, b, f, packs, ids, checkpointMode, witnessId);
        if (gasQ != 0) gasQ = _fundSync(p, budget, b, f, ids, gasQ, units, distributionTail, witnessId);
    }

    function _syncChanges(Params storage p, Book storage b, IFWAV2 f, IShapePacks packs,
        uint256[] calldata ids, uint256 checkpointMode, uint256 witnessId)
        private returns (uint256 gasQ, uint256 units, bool distributionTail)
    {
        if (ids.length > MAX_TERMINALS) revert BadBatch();
        Work memory work;
        // No outstanding custody, identifiers or receipts means an unseen selection cannot be ours.
        bool unexposed = _unexposed(b);
        bool rebased;
        if (unexposed) {
            rebased = _rebaseUnexposed(b, f);
        } else {
            // A scan of the vault's own positions replaces the global journal whenever it costs no
            // more than the next journal batch (ScanLib.rebase).
            (rebased, work.scanned, work.own) = ScanLib.rebase(b, f);
            if (!rebased) (work.processed, work.own) = _syncJournal(b, f, packs);
        }
        for (uint256 i; i < ids.length; ++i) if (_syncTerminal(b, f, packs, ids[i])) ++work.resolved;
        work.pruned = prune(b, MAX_PRUNES);
        if (work.processed + work.resolved + work.pruned == 0 && !rebased) revert Nothing();
        // Rebase is unpaid. Empty-vault head cleanup also cannot consume its bootstrap cash.
        if ((unexposed && b.trackedValue == 0) || work.processed + work.scanned + work.resolved + work.pruned == 0) {
            return (0, 0, false);
        }
        bool journalPaid = work.processed == MAX_JOURNAL || work.own + work.resolved != 0;
        bool requiredTail;
        uint256 tailBase = Q_REQUIRED_TAIL;
        if (!journalPaid && work.processed + work.scanned != 0 && checkpointMode != 0) {
            journalPaid = f.isPurchaseBlackout() && f.unsettledAcquisitionCount() == 0;
            if (journalPaid && checkpointMode == 2) {
                tailBase += Q_DISTRIBUTION_PROOF;
                journalPaid = _distributionTail(p, b, f, witnessId,
                    tailBase + work.processed * Q_JOURNAL + work.scanned * Q_SCAN + work.pruned * Q_PRUNED);
            }
            requiredTail = journalPaid;
        }
        if (!journalPaid && work.own + work.resolved + work.pruned == 0) return (0, 0, false);
        // A scan is paid only when it applied an own selection or is the required checkpoint proof:
        // splitting a cycle's terminal work into later calls cannot earn a second scan.
        gasQ = (requiredTail ? tailBase : Q_SYNC) + (journalPaid ? work.processed * Q_JOURNAL : 0)
            + (work.own != 0 || requiredTail ? work.scanned * Q_SCAN : 0) + work.own * Q_SELECTED
            + work.resolved * Q_SYNCED + work.pruned * Q_PRUNED;
        units = work.resolved;
        distributionTail = requiredTail && checkpointMode == 2;
    }

    /// @dev Terminal proceeds arrive first. Only real paid work may sweep economical credit or
    ///      claim the first bounded fee prefix needed to fund its complete payment envelope.
    function _fundSync(Params storage p, Budget storage budget, Book storage b, IFWAV2 f,
        uint256[] calldata ids, uint256 gasQ, uint256 units, bool distributionTail, uint256 witnessId)
        private returns (uint256)
    {
        (uint256 routine,) = budgetNow(p, budget);
        uint256 cost = quote(p, gasQ, units, false);
        if (routine < cost) return gasQ;
        uint256 credit = f.feeCredit(address(this));
        uint256 combined = quote(p, gasQ + Q_CREDIT, units, false);
        if (credit != 0 && combined <= routine && (combined - cost) * BPS <= credit * p.keeperShareBps
            && (!distributionTail || _distributionTail(p, b, f, witnessId, gasQ + Q_CREDIT))) {
            _withdrawCredit(b, f);
            gasQ += Q_CREDIT;
            cost = combined;
            credit = 0;
        }
        uint256 free = ISyncVault(address(this)).freeEth();
        if (free >= cost) return gasQ;
        uint256[] memory claims = new uint256[](ids.length);
        uint256 count;
        uint256 fees = credit;
        for (uint256 i; i < ids.length; ++i) {
            uint256 id = ids[i];
            if (b.positions[id].state != ACTIVE || listing(f, id).status != LISTING_ACTIVE) continue;
            bool duplicate;
            for (uint256 j; j < count; ++j) if (claims[j] == id) duplicate = true;
            if (duplicate) continue;
            uint256 pending = f.pendingFees(id);
            if (pending == 0) continue;
            claims[count++] = id;
            fees += pending;
            uint256 fundedGas = gasQ + Q_FUND + count * Q_HARVESTED + (credit != 0 ? Q_CREDIT : 0);
            combined = quote(p, fundedGas, units, false);
            if (free + fees < combined) continue;
            // Once enough cash was found, extra IDs cannot increase the claim or its payment.
            if (combined > routine || (combined - cost) * BPS > fees * p.keeperShareBps
                || (distributionTail && !_distributionTail(p, b, f, witnessId, fundedGas))) return gasQ;
            assembly ("memory-safe") { mstore(claims, count) }
            uint256 before = address(this).balance;
            if (!_claimFees(b, f, claims)) return gasQ;
            if (credit != 0) _withdrawCredit(b, f);
            uint256 received = address(this).balance - before;
            if (free + received < combined || (combined - cost) * BPS > received * p.keeperShareBps) revert Payment();
            return fundedGas;
        }
        return gasQ;
    }

    function _distributionTail(Params storage p, Book storage b, IFWAV2 f, uint256 witnessId, uint256 gasQ)
        private view returns (bool)
    {
        if (b.allocationHead < b.allocationQueue.length) {
            Position storage oldest = b.positions[b.allocationQueue[b.allocationHead]];
            if (oldest.state != ALLOCATED || block.timestamp >= uint256(oldest.allocatedAt) + f.settlementWindow()) return false;
        }
        ISyncVault v = ISyncVault(address(this));
        uint256 nav_;
        try v.accountedNav(witnessId) returns (uint256 n) { nav_ = n; } catch { return false; }
        // Prove a real distribution remains possible even after the largest sync payment.
        uint256 cost = quote(p, gasQ, 0, false);
        if (nav_ <= cost) return false;
        nav_ -= cost;
        if (b.allocatedValue * BPS > nav_ * p.allocatedBoundBps) return false;
        uint256 supply = v.totalShares();
        uint256 perShare = nav_ * 1e18 / supply;
        uint256 high = v.highWaterMark();
        if (supply <= DEAD_SHARES || perShare <= high) return false;
        uint256 liquid = v.freeEth() + f.feeCredit(address(this));
        if (liquid <= p.reserve) return false;
        liquid -= p.reserve;
        if (liquid <= cost) return false;
        uint256 gain = M.mulDiv(perShare - high, supply, 1e18);
        return M.min(gain * p.distributionBps / BPS, liquid - cost) >= MIN_DISTRIBUTION;
    }

    function _unexposed(Book storage b) private view returns (bool) {
        return b.open.length == 0 && b.reservedCount == 0 && b.activeCount == 0
            && b.activeBacking == 0 && b.allocatedValue == 0 && b.pendingPlusOne == 1;
    }

    function _rebaseUnexposed(Book storage b, IFWAV2 f) private returns (bool advanced) {
        if (!_unexposed(b)) return false;
        uint64 end = f.nextSequenceToProcess();
        if (b.acquisitionCursor < end) {
            b.acquisitionCursor = end;
            emit JournalProgress(end, 0, 0);
            return true;
        }
    }

    function _syncJournal(Book storage b, IFWAV2 f, IShapePacks packs)
        private returns (uint256 processed, uint256 own)
    {
        uint64 cursor = b.acquisitionCursor;
        uint64 end = f.nextSequenceToProcess();
        while (cursor < end && processed < MAX_JOURNAL) {
            uint256 requestId = f.requestIdAtSequence(cursor);
            if (requestId == 0) revert InvalidJournal();
            IFWAV2.Acquisition memory a = f.acquisitions(requestId);
            if (a.status == 2) {
                if (a.listingId == 0) revert InvalidJournal();
                if (b.positions[a.listingId].value != 0) {
                    if (own == MAX_SELECTIONS) break;
                    Position memory p = b.positions[a.listingId];
                    if (p.state != ACTIVE) revert InvalidJournal();
                    IFWAView.Listing memory l = listing(f, a.listingId);
                    _validate(l, packs, p.packId, p.backing);
                    if (l.status != LISTING_ALLOCATED && l.status != LISTING_SETTLED) revert InvalidJournal();
                    select(b, a.listingId, l.allocatedAt);
                    ++own;
                }
            } else if (a.status != 3 && a.status != 4) revert InvalidJournal();
            ++cursor;
            ++processed;
        }
        b.acquisitionCursor = cursor;
        if (processed != 0) emit JournalProgress(cursor, processed, own);
    }

    function _syncTerminal(Book storage b, IFWAV2 f, IShapePacks packs, uint256 id) private returns (bool) {
        Position memory p = b.positions[id];
        if (p.state == NONE) return false;
        IFWAView.Listing memory l = listing(f, id);
        _validate(l, packs, p.packId, p.backing);
        if (p.state == OWED) {
            if (f.stuckNFTRecipient(id) == address(this)) {
                (bool ok,) = address(f).call(abi.encodeCall(IFWAV2.recoverStuckNFT, (id)));
                if (!ok) return false;
            }
            if (!owns(packs, p.packId)) return false;
            claimReturned(b, id);
            return true;
        }
        if (l.status == LISTING_ALLOCATED) {
            if (p.state != ALLOCATED || block.timestamp < uint256(l.allocatedAt) + f.settlementWindow()) return false;
            // Expiry resolution must still identify its genuine keep payment.
            if (p.backing * (BPS - f.ownerSettlementFeeBps()) / BPS >= p.value) f.depositorReclaimBacking(id);
            else f.depositorReclaimNFT(id);
            l = listing(f, id);
        }
        if (l.status == LISTING_ACTIVE) return false;
        // FWA changes a listing's status and pays its depositor in the same transaction
        // (forceSafeTransferETH, which force-sends when receive() fails), so FWA's record alone
        // proves the outcome and its cash. The receipt only gates checkpoints until this sync;
        // a payment whose receipt was never recorded resolves here the same way.
        bool owned = owns(packs, p.packId);
        bool returned = owned || f.stuckNFTRecipient(id) == address(this);
        if (l.status == LISTING_SETTLED) {
            if (p.state == ACTIVE) return false;
            if (p.state != ALLOCATED) revert InvalidListing();
            // Keep, relist, expiry or default: B (1 - s) paid, the pack went to the purchaser.
            // A bid returns the pack to the depositor (or owes it) and pays nothing. A kept pack
            // that came back (a gift, perhaps with extra Shapes) joins inventory at its actual value.
            if (b.receipts[id].kind == 1 || !returned) {
                release(b, id, p.backing);
                keep(b, id);
                if (owned) addInventory(b, p.packId, packs.valueOf(p.packId));
                return true;
            }
        } else if (l.status == LISTING_WITHDRAWN) {
            // Only a kick withdraws a listing outside this account's own calls: B refunded, pack returned.
            if (p.state != ACTIVE || !returned) revert InvalidListing();
        } else return false;
        release(b, id, p.backing);
        returnPack(b, id, owned);
        return true;
    }

    function withdraw(Book storage b, IFWAV2 f, IShapePacks packs, uint256 id) external {
        Position memory p = b.positions[id];
        if (p.state != ACTIVE) revert WrongState();
        b.controlled = true;
        f.withdrawListing(id);
        b.controlled = false;
        bool owned = owns(packs, p.packId);
        if (!owned && f.stuckNFTRecipient(id) != address(this)) revert InvalidListing();
        release(b, id, p.backing);
        returnPack(b, id, owned);
    }

    function harvest(Book storage b, IFWAV2 f, uint256[] calldata ids) external {
        if (ids.length > MAX_BATCH) revert BadBatch();
        for (uint256 i; i < ids.length; ++i) {
            if (i != 0 && ids[i] <= ids[i - 1]) revert BadBatch();
        }
        _claimFees(b, f, ids);
        if (f.feeCredit(address(this)) != 0) _withdrawCredit(b, f);
    }

    function _claimFees(Book storage b, IFWAV2 f, uint256[] memory ids) private returns (bool claimed) {
        b.controlled = true;
        if (ids.length != 0) {
            try f.claimListingFees(ids) {
                for (uint256 i; i < ids.length; ++i) {
                    IFWAView.Listing memory l = listing(f, ids[i]);
                    if (b.positions[ids[i]].state == ACTIVE && l.status == LISTING_ACTIVE) updateFeeDebt(b, ids[i], l.feeDebt);
                }
                claimed = true;
            } catch {}
        }
        b.controlled = false;
    }

    function harvestCredit(Book storage b, IFWAV2 f) external {
        if (f.feeCredit(address(this)) != 0) _withdrawCredit(b, f);
    }

    function _withdrawCredit(Book storage b, IFWAV2 f) private {
        b.controlled = true;
        f.withdrawEarnings();
        b.controlled = false;
    }

    function accountedNav(Book storage b, IFWAV2 f, IShapePacks packs, uint256 freeEth, uint256 witnessId)
        external view returns (uint256 value)
    {
        (value,) = _accountedNav(b, f, packs, freeEth, witnessId);
    }

    /// @return value NAV; gasQ the checkpoint's quoted gas, including the allocation proof it read.
    function checkpointNav(Book storage b, IFWAV2 f, IShapePacks packs, uint256 freeEth, uint256 witnessId)
        external returns (uint256 value, uint256 gasQ)
    {
        _rebaseUnexposed(b, f);
        return _accountedNav(b, f, packs, freeEth, witnessId);
    }

    function _accountedNav(Book storage b, IFWAV2 f, IShapePacks packs, uint256 freeEth, uint256 witnessId)
        private view returns (uint256, uint256 gasQ)
    {
        if (b.acquisitionCursor != f.nextSequenceToProcess()) revert CatchUpFirst();
        if (b.pendingPlusOne != 1) revert PendingReceipts();
        (uint256 entries, uint256 reads) = ScanLib.requireAllocatedCurrent(b, f, packs);
        gasQ = Q_CHECKPOINT + entries * Q_ALLOCATION_ENTRY + reads * Q_ALLOCATION_READ;
        uint256 pending;
        if (b.activeCount != 0) {
            Position memory p = b.positions[witnessId];
            IFWAView.Listing memory l = listing(f, witnessId);
            if (p.state != ACTIVE || l.status != LISTING_ACTIVE || p.feeDebt != l.feeDebt) revert BadWitness();
            _validate(l, packs, p.packId, p.backing);
            pending = f.pendingFees(witnessId);
        }
        return (nav(b, freeEth, f.feeCredit(address(this)), witnessId, pending), gasQ);
    }

    function validateBacking(Params storage p, Book storage b, IFWAV2 f, address packs,
        uint256 units, uint256 backing, uint256 build, bool newlyBuilt) public view
    {
        _validateBacking(p, b, _backingTerms(p, f, packs, units, build), backing, newlyBuilt);
    }

    function _validateBacking(Params storage p, Book storage b, BackingTerms memory t,
        uint256 backing, bool newlyBuilt) private view
    {
        if (!t.ok || backing == 0 || backing > type(uint128).max || backing % BPS != 0
            || b.idForBacking[backing] != 0) revert InvalidBacking();
        uint256 delta = backing > t.desired ? backing - t.desired : t.desired - backing;
        if (delta > (b.reservedCount + 1) * BPS) revert InvalidBacking();
        if (backing < t.floor || (t.cap != type(uint256).max && backing > t.cap * (BPS - p.bufferBps) / BPS)
            || !_profitable(t, backing, newlyBuilt)) revert InvalidBacking();
    }

    /// @notice Mint `count` packs of `units` straight into ShapePacks (one paid primary mint per
    ///         Shape, no split) and list each at its validated backing proposal. `available` is the
    ///         account's spendable ETH; idle packs keep their reserved backing (`idleFunding`).
    function buildAndList(Params storage p, Book storage b, IFWAV2 f, IShapePacks packs, IShapes shapes,
        uint256 units, uint256[] calldata backingProposals, uint256 available) external
    {
        uint256 count = backingProposals.length;
        if (count == 0 || count > MAX_LIST_BATCH || units < MIN_PACK_UNITS || units > MAX_PACK_UNITS
            || (p.packUnitsMask >> units) & 1 == 0) revert BadBatch();
        (uint32[] memory counts, uint256 n) = makeup(units);
        uint256 fee = shapes.mintFee();
        uint256 price = units * UNIT + n * fee;
        BackingTerms memory terms = _backingTerms(p, f, address(packs), units, buildCost(p, units, fee));
        uint256 need = b.idleFunding + count * price;
        for (uint256 i; i < count; ++i) need += backingProposals[i];
        if (available < need) revert InsufficientBacking();
        uint256[] memory none = new uint256[](0);
        for (uint256 i; i < count; ++i) {
            // Validated one at a time, as in `list`: each admission widens the identifier interval.
            _validateBacking(p, b, terms, backingProposals[i], true);
            uint256 packId = packs.createPack{value: price}(none, counts);
            // ShapePacks records exactly the minted backing; a different value is not our pack.
            if (packs.valueOf(packId) != units * UNIT) revert MissingInventory();
            addInventory(b, packId, units * UNIT);
            admit(b, f, packs, packId, backingProposals[i]);
        }
    }

    /// @dev An extended gift may contain arbitrarily many Shapes. Never enumerate its contents.
    function recoverInventory(Book storage b, IShapePacks packs, IShapes shapes) external returns (uint256 gasQ) {
        uint256 id = b.recoveryPacks[b.recoveryPacks.length - 1];
        gasQ = Q_RECOVERY_BASE;
        if (!b.recoveryUnsealed[id]) {
            packs.unseal(id, address(this));
            b.recoveryUnsealed[id] = true;
            gasQ += Q_RECOVERY_UNSEAL;
        }
        uint256 before = address(this).balance;
        uint256 supply = shapes.totalSupply();
        packs.claimEth(id, MAX_REDEEM_SHAPES, payable(address(this)));
        uint256 out = address(this).balance - before;
        // The immutable Shapes path burns exactly the claimed IDs before its sole ETH callback.
        // No other supply mutation can interleave while this guarded vault receives that ETH.
        uint256 burned = supply - shapes.totalSupply();
        if (out == 0 || burned == 0 || burned > MAX_REDEEM_SHAPES) revert MissingInventory();
        gasQ += burned * Q_RECOVERY_SHAPE;
        b.trackedValue -= out;
        b.idleValue -= out;
        b.idleValueOf[id] -= out;
        bool unsealed = true;
        if (packs.claimantOf(id) == address(0)) {
            if (b.idleValueOf[id] != 0) revert MissingInventory();
            delete b.idleValueOf[id];
            delete b.recoveryUnsealed[id];
            b.idleFunding -= b.idleQuote[id];
            delete b.idleQuote[id];
            b.recoveryPacks.pop();
            unsealed = false;
        }
        emit RecoveryUpdated(id, b.idleValueOf[id], unsealed);
    }
}

src/interfaces/External.sol

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

/// @dev Minimal surfaces of the deployed contracts this repo calls, taken from their verified
///      sources: FWAV2 0x958C41181182e76F221331b2755b77D9e1426A98, FWAV2Rewards
///      0xA54b44C7a894AA19C49734A753D01f9B8C5f6516, Shapes 0x6fE9193276bF7aBCbEE44AB7aFd717d637D6FAf0,
///      ShapePacks 0xf21514B090Da7dF4390803497d6ae673801E5cA7, the FWA floor oracle and the
///      Uniswap v4 PoolManager the FWA token reports.

interface IERC721Min {
    function ownerOf(uint256 tokenId) external view returns (address);
    function setApprovalForAll(address operator, bool approved) external;
    function transferFrom(address from, address to, uint256 tokenId) external;
}

interface IShapes is IERC721Min {
    function totalSupply() external view returns (uint256);
    function mint(uint256 amountWei) external payable returns (uint256 tokenId);
    function mintFee() external view returns (uint256);
    function split(uint256 tokenId, uint8[] calldata outDenoms) external returns (uint256[] memory newIds);
    function redeem(uint256 tokenId) external;
    function backingOf(uint256 tokenId) external view returns (uint256);
}

interface IShapePacks is IERC721Min {
    function createPack(uint256[] calldata shapeIds, uint32[] calldata mintCounts)
        external
        payable
        returns (uint256 packId);
    function redeem(uint256 packId) external;
    function unseal(uint256 packId, address claimant) external;
    function claimEth(uint256 packId, uint256 maxCount, address payable recipient) external;
    function claimantOf(uint256 packId) external view returns (address);
    function valueOf(uint256 packId) external view returns (uint256);
    function contentsOf(uint256 packId) external view returns (uint256[] memory);
}

interface IFloorOracle {
    function getFloorRange(address collection)
        external
        view
        returns (uint256 bidPrice, uint256 askPrice, uint48 observedAt, uint48 periodUsed);
}

/// @dev FWAV2 ListingStatus values.
uint8 constant LISTING_ACTIVE = 1;
uint8 constant LISTING_ALLOCATED = 2;
uint8 constant LISTING_WITHDRAWN = 3;
uint8 constant LISTING_SETTLED = 4;
uint8 constant LISTING_STAGED = 5;

/// @dev Struct return is ABI-identical to the deployed public mapping getter.
interface IFWAView {
    struct Listing {
        address collection; address depositor; address purchaser;
        uint256 tokenId; uint256 weight; uint256 value; uint256 feeShare;
        uint256 feeDebt; uint256 slot; uint64 allocatedAt; uint8 status;
    }
    function listings(uint256 id) external view returns (Listing memory);
}

interface IFWAV2 {
    struct Acquisition {
        address purchaser; uint256 requestBlock; uint256 priceEscrowed;
        uint256 listingId; uint8 status;
    }
    function nextSequenceToProcess() external view returns (uint64);
    function lastIssuedSequence() external view returns (uint64);
    function requestIdAtSequence(uint64 sequence) external view returns (uint256);
    function acquisitions(uint256 requestId) external view returns (Acquisition memory);
    function fwairListing(uint256 id) external view returns (bool);
    function listNFT(address collection, uint256 tokenId) external payable returns (uint256 listingId);
    function withdrawListing(uint256 listingId) external;
    function claimListingFees(uint256[] calldata listingIds) external returns (uint256 total);
    function withdrawEarnings() external returns (uint256 amount);
    function depositorReclaimBacking(uint256 listingId) external;
    function depositorReclaimNFT(uint256 listingId) external;
    function recoverStuckNFT(uint256 listingId) external;
    function stuckNFTRecipient(uint256 listingId) external view returns (address);
    function finalizeUnsettled(uint256 listingId) external;
    function pendingFees(uint256 listingId) external view returns (uint256);
    function feeCredit(address depositor) external view returns (uint256);
    function listings(uint256 listingId)
        external
        view
        returns (
            address collection,
            address depositor,
            address purchaser,
            uint256 tokenId,
            uint256 weight,
            uint256 value,
            uint256 feeShare,
            uint256 feeDebt,
            uint256 slot,
            uint64 allocatedAt,
            uint8 status
        );
    function unsettledAcquisitionCount() external view returns (uint256);
    function isPurchaseBlackout() external view returns (bool);
    function canDeposit(address collection) external view returns (bool);
    function oracleExemptCollections(address collection) external view returns (bool);
    function floorOracle() external view returns (address);
    function oracleCeilingPremiumBps() external view returns (uint256);
    function maxOracleAge() external view returns (uint48);
    function minOracleChallengePeriod() external view returns (uint48);
    function ownerAcquisitionFeeBps() external view returns (uint256);
    function ownerSettlementFeeBps() external view returns (uint256);
    function topListingShareBps() external view returns (uint256);
    function topListingId() external view returns (uint256);
    function topListingSince() external view returns (uint64);
    function settlementDiscountBps() external view returns (uint256);
    function tokenSettlementDiscountBps() external view returns (uint256);
    function settlementWindow() external view returns (uint256);
    function finalizeWindow() external view returns (uint256);
    function acquisitionFee() external view returns (uint256);
    function totalWeight() external view returns (uint256);
    function weightedBackingTotal() external view returns (uint256);
    function activeListingCount() external view returns (uint256);
    function token() external view returns (address);
    function rewards() external view returns (address);
}

interface IFWARewards {
    function claimDepositorTokens(uint256[] calldata listingIds) external returns (uint256 total);
    function withdrawTokens() external returns (uint256 amount);
    function pendingDepositorTokens(uint256 listingId) external view returns (uint256);
    function tokenCredit(address depositor) external view returns (uint256);
}

interface IERC20Min {
    function balanceOf(address account) external view returns (uint256);
    function totalSupply() external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
}

/// @dev Uniswap v4 types, ABI-compatible with v4-core: Currency is an address, BalanceDelta packs
///      amount0 in the high 128 bits and amount1 in the low 128 bits.
struct PoolKey {
    address currency0;
    address currency1;
    uint24 fee;
    int24 tickSpacing;
    address hooks;
}

struct SwapParams {
    bool zeroForOne;
    int256 amountSpecified;
    uint160 sqrtPriceLimitX96;
}

interface IFWAToken is IERC20Min {
    function poolManager() external view returns (address);
    function poolKey() external view returns (PoolKey memory);
    function isDistributor(address account) external view returns (bool);
    /// Allowed for any holder, though transfers are otherwise locked (probed on a fork).
    function burn(uint256 amount) external;
}

interface IPoolManager {
    function unlock(bytes calldata data) external returns (bytes memory);
    function swap(PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
        external
        returns (int256 delta);
    function take(address currency, address to, uint256 amount) external;
    function sync(address currency) external;
    function settle() external payable returns (uint256);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": false,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/VaultLib.sol": {
      "VaultLib": "0x8E75a868C17c1e101a26837a2ABC7EE6E185b69c"
    },
    "src/StrategyLib.sol": {
      "StrategyLib": "0x6F4511eB3CE77Ac27505A60cC934359b3Fc1a83f"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "forge-std/=lib/forge-std/src/",
    "solady/=lib/solady/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.