Skip to content
Verified contractExactGPL-2.0-or-later

CoinbasePrimeAdapter

Address0x68e0fa50f3c3ff70f16825eccf4aec59efb8b2ec
Balance

0 ETH

 

Transactions

4

 

Compiler

solc 0.8.28

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.28+commit.7893614a
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
GPL-2.0-or-later
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,429,599
Creation transaction
0x8ec5b48b94…1c558783c2

src/vault-v2/adapters/CoinbasePrimeAdapter.sol

// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.28;

import {FixedPointMathLib} from "solady/src/utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";

import {IERC20} from "../../interfaces/IERC20.sol";
import {ICoinbasePrimeAdapter} from "../interfaces/ICoinbasePrimeAdapter.sol";
import {ISettlementWindowGate} from "../interfaces/ISettlementWindowGate.sol";
import {IVaultV2} from "../interfaces/IVaultV2.sol";

/// @title CoinbasePrimeAdapter
/// @notice Vault V2 liquidity and manual-allocation adapter for Coinbase Prime-style productive USDC balances.
contract CoinbasePrimeAdapter is ICoinbasePrimeAdapter {
    /// @inheritdoc ICoinbasePrimeAdapter
    string public constant ADAPTER_TYPE = "CoinbasePrimeAdapter";
    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Keeps a booked reward from landing as a near-instant NAV step; well below monthly cadence.
    uint256 public constant MIN_DIVIDEND_INTERVAL = 1 days;

    /* IMMUTABLES */

    /// @inheritdoc ICoinbasePrimeAdapter
    address public immutable FACTORY;
    /// @inheritdoc ICoinbasePrimeAdapter
    address public immutable PARENT_VAULT;
    /// @inheritdoc ICoinbasePrimeAdapter
    address public immutable ASSET;
    /// @inheritdoc ICoinbasePrimeAdapter
    bytes32 public immutable ADAPTER_ID;

    /* STORAGE */

    /// @inheritdoc ICoinbasePrimeAdapter
    address public settlementGate;
    /// @inheritdoc ICoinbasePrimeAdapter
    address public operator;

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Trusted Coinbase Prime Onchain Wallet (POW) EOA holding the productive USDC principal. Set via
    ///      `setPrimeWallet` by the owner. Must be non-zero before any `allocate` or non-sync `deallocate`
    ///      can succeed. Must have separately approved this adapter for at least the largest anticipated
    ///      deallocate amount (in practice, `type(uint256).max`) so that `deallocate` can pull funds back.
    address public primeWallet;

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Whether `recordSettlement(...)` requires the settlement gate to be closed even when a drip
    ///      cycle is active. Defaults to `true` (fail-closed): the owner must explicitly opt out via
    ///      `setSettlementGateRequired(false)` AFTER configuring a non-zero `dividendInterval` to enable
    ///      the gateless settlement flow. Independently of this flag, `recordSettlement` reverts with
    ///      `DividendIntervalNotConfigured` while `dividendInterval == 0`.
    bool public settlementGateRequired = true;

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Whether a `DeficitBooking` requires the settlement gate to be closed. Defaults to `true`
    ///      because deficits are sudden downward jumps that cannot be smoothed by the drip.
    bool public deficitGateRequired = true;

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Timestamp when the current drip window started. Re-anchored on every value-bearing settlement fold
    ///      and loss write-down.
    uint64 public dripStartTime;

    /// @inheritdoc ICoinbasePrimeAdapter
    uint256 public productiveAssets;

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Time window over which each newly-booked reward is linearly released into `realAssets()`.
    ///      Owner-set, typically configured once to match the reward cadence. Zero only as the unconfigured
    ///      deployment default, where recordSettlement releases immediately behind a mandatory closed gate.
    uint256 public dividendInterval;
    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Total reward value currently being dripped (set by `recordSettlement`). Includes any
    ///      carry-over from a previous unreleased portion when settlements are stacked.
    uint256 public dripBuffer;
    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Duration captured for the active drip cycle. Snapshotted by `recordSettlement` so the in-flight
    ///      schedule is immune to later `setDividendInterval` calls. Stacked settlements blend the carry's
    ///      remaining duration with the new reward's configured interval using value-weighted average math.
    uint256 public dripDuration;

    /// @inheritdoc ICoinbasePrimeAdapter
    mapping(bytes32 settlementId => bool) public settlementUsed;
    /// @inheritdoc ICoinbasePrimeAdapter
    mapping(bytes32 deficitId => bool) public deficitUsed;

    /* CONSTRUCTOR */

    /// @param _parentVault Parent Vault V2 address.
    /// @param _operator Trusted operator for reward settlement and deficit reconciliation.
    constructor(address _parentVault, address _operator) {
        if (_parentVault == address(0) || _operator == address(0)) revert InvalidAddress();

        FACTORY = msg.sender;
        PARENT_VAULT = _parentVault;
        ASSET = IVaultV2(_parentVault).asset();
        ADAPTER_ID = keccak256(abi.encode("coinbasePrime", address(this)));
        operator = _operator;

        emit SetOperator(_operator);
        emit SetSettlementGateRequired(settlementGateRequired);
        emit SetDeficitGateRequired(deficitGateRequired);

        SafeTransferLib.safeApprove(ASSET, _parentVault, type(uint256).max);
    }

    /* ADMIN */

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Zero disables non-request settlement booking until a gate is configured again.
    function setSettlementGate(address newSettlementGate) external {
        _requireOwner();
        settlementGate = newSettlementGate;
        emit SetSettlementGate(newSettlementGate);
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function setSettlementGateRequired(bool required) external {
        _requireOwner();
        settlementGateRequired = required;
        emit SetSettlementGateRequired(required);
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function setDeficitGateRequired(bool required) external {
        _requireOwner();
        deficitGateRequired = required;
        emit SetDeficitGateRequired(required);
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function setDividendInterval(uint256 newInterval) external {
        _requireOwner();
        if (newInterval < MIN_DIVIDEND_INTERVAL) revert InvalidDividendInterval();
        dividendInterval = newInterval;
        emit SetDividendInterval(newInterval);
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function setOperator(address newOperator) external {
        _requireOwner();
        if (newOperator == address(0)) revert InvalidAddress();
        operator = newOperator;
        emit SetOperator(newOperator);
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Rotation is allowed unconditionally. Operators MUST fully migrate funds out of the old POW
    ///      before calling this - otherwise principal is stranded at the previous address and
    ///      `_realAssets()` drops sharply as the oracle switches.
    function setPrimeWallet(address newPrimeWallet) external {
        _requireOwner();
        if (newPrimeWallet == address(0)) revert InvalidAddress();
        primeWallet = newPrimeWallet;
        emit SetPrimeWallet(newPrimeWallet);
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function skim(address token, address to) external {
        _requireOwner();
        if (token == ASSET) revert CannotSkimManagedToken();
        uint256 balance = IERC20(token).balanceOf(address(this));
        SafeTransferLib.safeTransfer(token, to, balance);
        emit Skim(token, to, balance);
    }

    /* VAULT ADAPTER ENTRYPOINTS */

    /// @inheritdoc ICoinbasePrimeAdapter
    function allocate(bytes calldata data, uint256 assets, bytes4 selector, address sender)
        external
        returns (bytes32[] memory, int256)
    {
        if (msg.sender != PARENT_VAULT) revert NotAuthorized();

        if (selector == IVaultV2.deposit.selector || selector == IVaultV2.mint.selector) {
            if (data.length != 0) revert InvalidData();
            // Liquidity zero-amount calls are no-ops. In particular, they cannot reach the privileged
            // zero-allocation recovery route exposed by the manual allocation selector.
            if (assets == 0) return (ids(), 0);
            _allocateProductiveAssets(assets);
            return _syncAllocationDelta();
        }

        if (selector == IVaultV2.allocate.selector) {
            if (!_isAllocatorOrOwner(sender)) revert NotAuthorized();
            if (assets == 0) return _syncZeroAllocationDelta(data);
            if (data.length != 0) revert InvalidData();
            _allocateProductiveAssets(assets);
            // forge-lint: disable-next-item(unsafe-typecast)
            return (ids(), int256(assets));
        }

        revert UnknownSelector();
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function deallocate(bytes calldata data, uint256 assets, bytes4 selector, address sender)
        external
        returns (bytes32[] memory, int256)
    {
        if (msg.sender != PARENT_VAULT) revert NotAuthorized();

        if (selector == IVaultV2.withdraw.selector || selector == IVaultV2.redeem.selector) {
            if (data.length != 0) revert InvalidData();
            // Public liquidity zero-amount calls are no-ops. In particular, they cannot turn a public user action
            // into a manual allocation sync or deficit-booking operation.
            if (assets == 0) return (ids(), 0);
            _deallocateProductiveAssets(assets);
            return _syncAllocationDelta();
        }

        if (selector == IVaultV2.deallocate.selector) {
            if (assets == 0 && data.length != 0) return _bookDeficitAndSyncAllocation(data, sender);
            if (!_isAllocatorOrSentinel(sender)) revert NotAuthorized();
            if (assets == 0) return _syncAllocationDelta(data);
            if (data.length != 0) revert InvalidData();
            _deallocateProductiveAssets(assets);
            // forge-lint: disable-next-item(unsafe-typecast)
            return (ids(), -int256(assets));
        }

        revert UnknownSelector();
    }

    /* OPERATIONAL FLOWS */

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Books an observed reward inflow into `productiveAssets`. When `dividendInterval > 0` the
    ///      booked amount is also placed into the drip buffer so that `realAssets()` releases it
    ///      linearly over the configured window; any unreleased portion of a previous drip is carried
    ///      over so realAssets stays continuous across stacked settlements.
    ///      Reverts with `DividendIntervalNotConfigured` while `dividendInterval == 0` (the deployment
    ///      default), so a reward can never hit `realAssets()` as an undripped discrete jump.
    ///      Front-running protection is fail-closed: a closed gate is REQUIRED whenever the owner has
    ///      explicitly enabled `settlementGateRequired`. The operator can only skip the gate when the
    ///      owner has opted out, relying on the configured drip cycle to absorb the discontinuity.
    function recordSettlement(bytes32 settlementId, uint256 assetIncrease) external {
        _requireOperatorOrOwner();
        if (dividendInterval == 0) revert DividendIntervalNotConfigured();
        if (settlementGateRequired) _requireSettlementWindowClosed();
        if (settlementId == bytes32(0)) revert InvalidData();
        if (settlementUsed[settlementId]) revert SettlementAlreadyRecorded();
        if (assetIncrease == 0) revert ZeroAmount();
        if (unaccountedAssetBalance() < assetIncrease) revert InsufficientObservedSettlement();

        settlementUsed[settlementId] = true;
        productiveAssets += assetIncrease;

        // The interval is non-zero here, so the new reward and active carry are blended without restarting all carry
        // for a full interval.
        _addToDrip(assetIncrease);

        emit SettlementRecorded(settlementId, assetIncrease);
    }

    function _recordObservedDeficit(bytes32 deficitId, uint256 assetDecrease) internal {
        if (deficitGateRequired) _requireSettlementWindowClosed();
        if (deficitId == bytes32(0)) revert InvalidData();
        if (deficitUsed[deficitId]) revert DeficitAlreadyRecorded();
        if (assetDecrease == 0) revert ZeroAmount();

        // Clamp to the live observable deficit so a dust donation cannot front-run and revert the booking.
        uint256 observedDeficit = observedAssetDeficit();
        if (observedDeficit == 0) revert DeficitExceedsObservedLoss();
        if (assetDecrease > observedDeficit) assetDecrease = observedDeficit;

        deficitUsed[deficitId] = true;
        productiveAssets -= assetDecrease;
        _reduceDripOnLoss(assetDecrease);
        emit DeficitRecorded(deficitId, assetDecrease);
    }

    /* VIEW */

    /// @inheritdoc ICoinbasePrimeAdapter
    function realAssets() external view returns (uint256) {
        return _realAssets();
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    /// @dev Sums the adapter's own USDC balance with the `primeWallet`'s USDC balance. The adapter-side
    ///      component captures USDC staged on the adapter during a deallocate flow and any direct donations;
    ///      the POW-side component is where productive principal and newly-arrived rewards live. Before
    ///      `setPrimeWallet` has ever been called (the deployed-but-unconfigured window) only the adapter
    ///      balance is observable, which is correct because no allocations are possible in that window.
    function observedAssetBalance() public view returns (uint256) {
        uint256 adapterBalance = IERC20(ASSET).balanceOf(address(this));
        address pow = primeWallet;
        if (pow == address(0)) return adapterBalance;
        return adapterBalance + IERC20(ASSET).balanceOf(pow);
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function unaccountedAssetBalance() public view returns (uint256) {
        uint256 observed = observedAssetBalance();
        return observed > productiveAssets ? observed - productiveAssets : 0;
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function observedAssetDeficit() public view returns (uint256) {
        uint256 observed = observedAssetBalance();
        return productiveAssets > observed ? productiveAssets - observed : 0;
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function unreleasedDrip() external view returns (uint256) {
        return _unreleasedDrip();
    }

    /// @inheritdoc ICoinbasePrimeAdapter
    function ids() public view returns (bytes32[] memory ids_) {
        ids_ = new bytes32[](1);
        ids_[0] = ADAPTER_ID;
    }

    /* INTERNAL */

    /// @dev Moves newly-arrived Vault V2 assets to the POW. The selector router determines whether to return
    ///      the ordinary manual amount delta or a complete liquidity-path allocation reconciliation.
    function _allocateProductiveAssets(uint256 assets) internal {
        address pow = primeWallet;
        if (pow == address(0)) revert PrimeWalletNotSet();

        productiveAssets += assets;
        emit Allocated(assets, productiveAssets);

        SafeTransferLib.safeTransfer(ASSET, pow, assets);
    }

    /// @dev Stages assets on the adapter for Vault V2's subsequent pull. The live-assets bound preserves the
    ///      custody-loss and unreleased-drip floors used by `realAssets()`; the selector router determines the
    ///      allocation delta returned to the parent vault.
    function _deallocateProductiveAssets(uint256 assets) internal {
        if (_realAssets() < assets) revert InsufficientProductiveAssets();

        address pow = primeWallet;
        if (pow == address(0)) revert PrimeWalletNotSet();

        productiveAssets -= assets;
        emit Deallocated(assets, productiveAssets);

        // Use any USDC already on the adapter first; only pull the shortfall from the POW.
        // This ensures adapter-held assets (e.g. direct donations, in-transit leftovers) are
        // accessible for deallocation, consistent with observedAssetBalance() counting them.
        uint256 adapterBalance = IERC20(ASSET).balanceOf(address(this));
        if (adapterBalance < assets) {
            SafeTransferLib.safeTransferFrom(ASSET, pow, address(this), assets - adapterBalance);
        }
    }

    /// @dev Books an observed loss inside the parent Vault V2's zero-asset `deallocate` callback and returns the full
    ///      productive-balance delta. Vault V2 applies that delta atomically with this state transition. The outer vault
    ///      call requires an allocator or sentinel, while this router retains the adapter's operator/owner restriction.
    function _bookDeficitAndSyncAllocation(bytes calldata data, address sender)
        internal
        returns (bytes32[] memory, int256)
    {
        if (data.length != 64) revert InvalidData();
        _requireOperatorOrOwner(sender);
        (bytes32 deficitId, uint256 assetDecrease) = abi.decode(data, (bytes32, uint256));
        _recordObservedDeficit(deficitId, assetDecrease);
        return _syncAllocationDelta();
    }

    /// @dev Returns the tracked productive-balance delta versus Vault V2 allocation for zero-asset sync calls.
    function _syncAllocationDelta(bytes calldata data) internal view returns (bytes32[] memory, int256) {
        if (data.length != 0) revert InvalidData();

        return _syncAllocationDelta();
    }

    /// @dev Returns the tracked productive-balance delta after the caller has already validated its adapter data.
    function _syncAllocationDelta() internal view returns (bytes32[] memory, int256) {
        uint256 allocation_ = IVaultV2(PARENT_VAULT).allocation(ADAPTER_ID);
        uint256 realAssets_ = productiveAssets;

        if (realAssets_ == allocation_) return (ids(), 0);

        if (realAssets_ > allocation_) {
            // forge-lint: disable-next-item(unsafe-typecast)
            return (ids(), int256(realAssets_ - allocation_));
        }
        // forge-lint: disable-next-item(unsafe-typecast)
        return (ids(), -int256(allocation_ - realAssets_));
    }

    /// @dev Recovers a zero parent allocation after new productive value has been booked. Vault V2's allocate path
    ///      applies normal cap checks to the returned positive delta and transfers no assets when `assets == 0`.
    function _syncZeroAllocationDelta(bytes calldata data) internal view returns (bytes32[] memory, int256) {
        if (data.length != 0) revert InvalidData();
        if (IVaultV2(PARENT_VAULT).allocation(ADAPTER_ID) != 0) revert AllocationAlreadyNonZero();
        if (productiveAssets == 0) revert ZeroAmount();
        // forge-lint: disable-next-item(unsafe-typecast)
        return (ids(), int256(productiveAssets));
    }

    /// @dev `productiveAssets` represents the principal that has been booked. An observed custody loss consumes
    ///      unreleased drip first, exactly matching `_reduceDripOnLoss`, and only the excess reduces recognized NAV.
    ///      This immediately reflects losses while ensuring later deficit booking reconciles tracked state without
    ///      moving NAV. Unreleased reward value continues to smooth into share pricing when no larger loss floor exists.
    function _realAssets() internal view returns (uint256) {
        uint256 base = productiveAssets;
        uint256 observed = observedAssetBalance();
        uint256 custodyLoss = base > observed ? base - observed : 0;
        uint256 unreleased = _unreleasedDrip();
        uint256 reduction = custodyLoss > unreleased ? custodyLoss : unreleased;
        return base > reduction ? base - reduction : 0;
    }

    /// @dev Returns the portion of the current `dripBuffer` that has not yet been linearly released.
    ///      Pure function of the `(dripBuffer, dripStartTime, dripDuration)` snapshot taken when the
    ///      cycle was written: it deliberately does NOT read the live `dividendInterval`, so a cadence
    ///      change can never re-time (or instantly release) a drip already in flight. Returns `0` once
    ///      the captured duration has elapsed. `_realAssets()` subtracts the portion not already consumed by an observed
    ///      custody loss so a freshly-booked reward rises into share pricing smoothly instead of as a discrete jump.
    function _unreleasedDrip() internal view returns (uint256) {
        uint256 buffer = dripBuffer;
        if (buffer == 0) return 0;
        uint256 duration = dripDuration;
        uint256 elapsed = block.timestamp - dripStartTime;
        if (elapsed >= duration) return 0;
        uint256 released = FixedPointMathLib.fullMulDiv(buffer, elapsed, duration);
        return buffer - released;
    }

    /// @dev Adds newly-booked value to the drip while keeping `realAssets()` continuous. An active carry is weighted
    ///      by its snapshotted remaining duration and the addition by the currently configured interval. The
    ///      difference-form calculation is algebraically equivalent to summing the two weighted products, but the
    ///      single `fullMulDiv` avoids overflowing either product.
    function _addToDrip(uint256 addition) internal {
        uint256 additionDuration = dividendInterval;
        if (addition == 0 || additionDuration == 0) return;

        uint256 carryOver = _unreleasedDrip();
        uint256 newBuffer = carryOver + addition;
        uint256 newDuration = additionDuration;

        if (carryOver != 0) {
            uint256 carryRemaining = dripDuration - (block.timestamp - dripStartTime);
            if (carryRemaining < additionDuration) {
                newDuration = carryRemaining
                    + FixedPointMathLib.fullMulDiv(addition, additionDuration - carryRemaining, newBuffer);
            } else if (carryRemaining > additionDuration) {
                newDuration = additionDuration
                    + FixedPointMathLib.fullMulDiv(carryOver, carryRemaining - additionDuration, newBuffer);
            }
        }

        dripBuffer = newBuffer;
        dripStartTime = uint64(block.timestamp);
        dripDuration = newDuration;
    }

    /// @dev A booked loss consumes the unreleased drip first, so a stale drip cannot outlive the
    ///      reward it was smoothing and mask subsequently recovered or allocated assets. The remainder
    ///      keeps releasing over the remaining window, so a loss never restarts a full interval for
    ///      the reduced buffer.
    function _reduceDripOnLoss(uint256 lossAssets) internal {
        uint256 unreleased = _unreleasedDrip();
        if (unreleased == 0) return;
        dripDuration -= block.timestamp - dripStartTime;
        dripBuffer = unreleased > lossAssets ? unreleased - lossAssets : 0;
        dripStartTime = uint64(block.timestamp);
    }

    function _requireSettlementWindowClosed() internal view {
        address settlementGate_ = settlementGate;
        if (settlementGate_ == address(0)) revert SettlementGateNotSet();
        if (ISettlementWindowGate(settlementGate_).isOpen()) revert SettlementWindowOpen();
    }

    function _requireOwner() internal view {
        if (msg.sender != IVaultV2(PARENT_VAULT).owner()) revert NotAuthorized();
    }

    function _requireOperatorOrOwner() internal view {
        if (msg.sender != operator && msg.sender != IVaultV2(PARENT_VAULT).owner()) revert NotAuthorized();
    }

    function _requireOperatorOrOwner(address account) internal view {
        if (account != operator && account != IVaultV2(PARENT_VAULT).owner()) revert NotAuthorized();
    }

    function _isAllocatorOrOwner(address account) internal view returns (bool) {
        return account == IVaultV2(PARENT_VAULT).owner() || IVaultV2(PARENT_VAULT).isAllocator(account);
    }

    /// @dev Mirrors Vault V2's deallocate gate so sentinels can unwind during incidents.
    function _isAllocatorOrSentinel(address account) internal view returns (bool) {
        return IVaultV2(PARENT_VAULT).isAllocator(account) || IVaultV2(PARENT_VAULT).isSentinel(account);
    }
}

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/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/interfaces/IERC20.sol

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

/// @title IERC20
/// @notice Minimal ERC20 interface used by Lotus core.
interface IERC20 {
    /// @notice Returns the token balance of `account`.
    /// @param account The account to query.
    /// @return balance The token balance.
    function balanceOf(address account) external view returns (uint256 balance);
}

src/vault-v2/interfaces/IAdapter.sol

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

/// @title IAdapter
/// @notice Interface for Vault V2 adapters.
/// @dev Local interface used at the Vault V2 dependency boundary.
interface IAdapter {
    /// @notice Allocates assets to the underlying protocol.
    /// @param data Encoded position data; format depends on adapter implementation.
    /// @param assets The amount of assets to allocate.
    /// @param selector The function selector to identify the originating call.
    /// @param sender The original sender for access control.
    /// @return ids Cap-tracking ids affected by the allocation.
    /// @return change The asset change, positive for allocation.
    function allocate(bytes calldata data, uint256 assets, bytes4 selector, address sender)
        external
        returns (bytes32[] memory ids, int256 change);

    /// @notice Deallocates assets from the underlying protocol.
    /// @param data Encoded position data; format depends on adapter implementation.
    /// @param assets The amount of assets to deallocate.
    /// @param selector The function selector to identify the originating call.
    /// @param sender The original sender for access control.
    /// @return ids Cap-tracking ids affected by the deallocation.
    /// @return change The asset change, negative for deallocation.
    function deallocate(bytes calldata data, uint256 assets, bytes4 selector, address sender)
        external
        returns (bytes32[] memory ids, int256 change);

    /// @notice Returns the total real assets managed by the adapter.
    /// @return The total real assets.
    function realAssets() external view returns (uint256);
}

src/vault-v2/interfaces/ICoinbasePrimeAdapter.sol

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

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

/// @title ICoinbasePrimeAdapter
/// @notice Vault V2 liquidity and manual-allocation adapter for Coinbase Prime-style productive USDC balances
/// custodied at an external Coinbase Prime Onchain Wallet (POW).
/// @dev Productive USDC principal does NOT live on the adapter itself. It lives at a trusted external EOA - the
/// Prime Onchain Wallet - which must pre-approve this adapter for `type(uint256).max` of the asset at onboarding.
/// `allocate` pushes freshly-allocated USDC out to the POW, `deallocate` pulls USDC back via `transferFrom` so the
/// vault's subsequent sweep path finds funds staged on the adapter. `observedAssetBalance()` sums POW balance and
/// adapter balance to form the deficit floor and the surplus-detection oracle for `recordSettlement` and encoded
/// `DeficitBooking` operations. Once the adapter is installed and capped, configuring it as Vault V2's liquidity
/// adapter with empty `liquidityData` makes deposits and mints push their assets to the POW, while withdrawals and
/// redeems pull only the vault's idle shortfall back. The adapter intentionally rejects permissionless Vault V2
/// `forceDeallocate`; operational pullbacks remain available through privileged manual deallocation. Manual allocation,
/// allocation sync, and deficit-booking paths also remain available through the parent vault's privileged entrypoints.
/// Rewards or manual corrections must be observed as inbound USDC at the POW before they can be booked into live NAV.
interface ICoinbasePrimeAdapter is IAdapter {
    /* STRUCTS */

    /// @notice Observed deficit booking executed through a zero-asset parent-vault deallocation.
    /// @dev Routing the booking through Vault V2 applies the adapter write-down and its cap-ledger delta atomically.
    struct DeficitBooking {
        bytes32 deficitId;
        uint256 assetDecrease;
    }

    /* EVENTS */

    /// @notice Emitted when the settlement gate is updated.
    /// @param newSettlementGate The new settlement gate address.
    event SetSettlementGate(address indexed newSettlementGate);

    /// @notice Emitted when settlement-gate enforcement for reward booking changes.
    /// @param required Whether reward booking now requires a closed gate.
    event SetSettlementGateRequired(bool required);

    /// @notice Emitted when deficit-gate enforcement changes.
    /// @param required Whether deficit booking now requires a closed gate.
    event SetDeficitGateRequired(bool required);

    /// @notice Emitted when the trusted settlement operator changes.
    /// @param newOperator The new operator address.
    event SetOperator(address indexed newOperator);

    /// @notice Emitted when the Coinbase Prime Onchain Wallet changes.
    /// @param newPrimeWallet The new Coinbase Prime Onchain Wallet address.
    event SetPrimeWallet(address indexed newPrimeWallet);

    /// @notice Emitted when the reward drip interval changes.
    /// @param newInterval The new drip interval in seconds.
    event SetDividendInterval(uint256 newInterval);

    /// @notice Emitted when unmanaged tokens are recovered.
    /// @param token The recovered token.
    /// @param to The recovery recipient.
    /// @param amount The recovered amount.
    event Skim(address indexed token, address indexed to, uint256 amount);

    /// @notice Emitted when vault assets are sent to the Prime Onchain Wallet.
    /// @param assets The allocated asset amount.
    /// @param productiveAssetsAfter The productive asset balance after allocation.
    event Allocated(uint256 assets, uint256 productiveAssetsAfter);

    /// @notice Emitted when vault assets are pulled back from the Prime Onchain Wallet.
    /// @param assets The deallocated asset amount.
    /// @param productiveAssetsAfter The productive asset balance after deallocation.
    event Deallocated(uint256 assets, uint256 productiveAssetsAfter);

    /// @notice Emitted when observed Prime rewards or manual corrections are booked.
    /// @param settlementId The single-use settlement id.
    /// @param assetIncrease The booked asset increase.
    event SettlementRecorded(bytes32 indexed settlementId, uint256 assetIncrease);

    /// @notice Emitted when an observed productive-balance deficit is booked.
    /// @param deficitId The single-use deficit id.
    /// @param assetDecrease The booked asset decrease.
    event DeficitRecorded(bytes32 indexed deficitId, uint256 assetDecrease);

    /* ERRORS */

    /// @notice Required address argument is zero.
    error InvalidAddress();
    /// @notice Caller is not the vault, owner, allocator, operator, or other required role.
    error NotAuthorized();
    /// @notice Adapter call data is malformed or unexpectedly non-empty.
    error InvalidData();
    /// @notice Unsupported originating Vault V2 selector provided.
    error UnknownSelector();
    /// @notice A required amount or recoverable productive exposure is zero.
    error ZeroAmount();
    /// @notice Settlement id has already been used.
    error SettlementAlreadyRecorded();
    /// @notice Deficit id has already been used.
    error DeficitAlreadyRecorded();
    /// @notice Settlement or deficit booking requires a gate, but no gate is configured.
    error SettlementGateNotSet();
    /// @notice Settlement or deficit booking requires a closed gate, but the gate is open.
    error SettlementWindowOpen();
    /// @notice Requested settlement booking exceeds currently observed surplus.
    error InsufficientObservedSettlement();
    /// @notice Deallocation exceeds productive assets tracked by the adapter.
    error InsufficientProductiveAssets();
    /// @notice Attempted to skim the managed settlement asset.
    error CannotSkimManagedToken();
    /// @notice Requested deficit exceeds the currently observed loss.
    error DeficitExceedsObservedLoss();
    /// @notice Allocation or deallocation requires a configured Prime Onchain Wallet.
    error PrimeWalletNotSet();
    /// @notice Zero-asset allocation sync is only available while the parent allocation is zero.
    error AllocationAlreadyNonZero();
    /// @notice The dividend interval is below `MIN_DIVIDEND_INTERVAL`.
    error InvalidDividendInterval();
    /// @notice `recordSettlement` was called before a non-zero `dividendInterval` was configured.
    error DividendIntervalNotConfigured();

    /* VAULT ADAPTER FUNCTIONS */

    /// @notice Routes Vault V2 liquidity inflows or manually allocates vault assets.
    /// @dev Only callable by the parent vault and `data` must be empty. Liquidity-routing `deposit` / `mint` calls
    /// forward positive `assets` to the Prime Onchain Wallet without requiring the original user to hold a vault role;
    /// a zero-asset liquidity call is a no-op. Manual `vault.allocate()` calls require an allocator or owner. For
    /// positive `assets`, manual and liquidity calls share the same transfer; the liquidity route also reconciles the
    /// parent cap ledger to the complete post-operation productive exposure. For zero assets, only the manual route can
    /// restore a zero parent allocation after a complete write-down followed by a new settlement. Recovery returns the
    /// full unfloored productive exposure, moves no funds, and requires enough absolute and relative cap headroom for
    /// that complete amount.
    /// @param data Adapter data; must be empty.
    /// @param assets Assets already transferred from the parent vault, or zero for zero-allocation recovery sync.
    /// @param selector The originating Vault V2 selector.
    /// @param sender The original Vault V2 caller used for allocator/owner checks.
    /// @return ids Array containing this adapter's cap-tracking id.
    /// @return change Positive manual amount delta or full liquidity-path productive-allocation delta.
    function allocate(bytes calldata data, uint256 assets, bytes4 selector, address sender)
        external
        override
        returns (bytes32[] memory ids, int256 change);

    /// @notice Routes Vault V2 public outflows or manually deallocates, synchronizes, or books a deficit.
    /// @dev Only callable by the parent vault. Positive `withdraw` and `redeem` calls require empty `data`, accept the
    /// original user without a vault role, and pull productive funds back to vault idle; a zero-asset public call is a
    /// no-op. Permissionless Vault V2 `forceDeallocate` is intentionally unsupported. Manual `vault.deallocate()` calls
    /// require an allocator or sentinel, and support empty-data sync and encoded `DeficitBooking`. Positive manual and
    /// public calls both decrease tracked productive assets, use any asset already on the adapter first, and pull only the
    /// remaining shortfall from the Prime Onchain Wallet via `transferFrom`. A positive public call returns the complete
    /// post-operation productive-balance delta so Vault V2's cap ledger is synchronized atomically; a positive manual call
    /// retains its ordinary negative amount delta. For manual deficit booking, the original vault caller must be the
    /// configured operator or owner and must also hold an appropriate Vault V2 role. Sentinel should be used instead of
    /// allocator for loss-only accounts, subject to its additional incident-response powers documented by Vault V2.
    /// @param data Empty for a pure sync/manual pull, or ABI-encoded `DeficitBooking` when `assets == 0`.
    /// @param assets Asset amount to deallocate, or zero to sync allocation deltas.
    /// @param selector The originating Vault V2 selector.
    /// @param sender The original Vault V2 caller used for role checks.
    /// @return ids Array containing this adapter's cap-tracking id.
    /// @return change Negative manual amount delta or full public-path productive-allocation delta.
    function deallocate(bytes calldata data, uint256 assets, bytes4 selector, address sender)
        external
        override
        returns (bytes32[] memory ids, int256 change);

    /// @notice Returns the adapter NAV contributed to Vault V2.
    /// @dev An observed custody loss consumes unreleased drip first, and only the excess reduces recognized NAV. This
    ///      mirrors later deficit booking, so reconciling the tracked productive balance cannot create a second NAV move.
    /// @return The current real assets credited to the parent vault.
    function realAssets() external view override returns (uint256);

    /* VIEW FUNCTIONS */

    /// @return Human-readable adapter type, used for frontend identification.
    function ADAPTER_TYPE() external view returns (string memory);
    /// @return Lower bound accepted by `setDividendInterval`.
    function MIN_DIVIDEND_INTERVAL() external view returns (uint256);

    /// @return The factory that deployed this adapter instance.
    function FACTORY() external view returns (address);
    /// @return The parent Vault V2 whose owner and allocators govern this adapter.
    function PARENT_VAULT() external view returns (address);
    /// @return The vault settlement asset custodied at the Prime Onchain Wallet.
    function ASSET() external view returns (address);
    /// @return The vault allocation identifier for this adapter.
    function ADAPTER_ID() external view returns (bytes32);

    /// @return The gate that must be closed while settlement and deficit booking are absorbed into NAV.
    function settlementGate() external view returns (address);
    /// @return Whether `recordSettlement` requires the settlement gate even when a drip cycle is active.
    function settlementGateRequired() external view returns (bool);
    /// @return Whether an encoded `DeficitBooking` requires the settlement gate to be closed.
    function deficitGateRequired() external view returns (bool);
    /// @return The operational role allowed to reconcile observed settlement.
    function operator() external view returns (address);
    /// @return The Coinbase Prime Onchain Wallet holding productive USDC principal.
    function primeWallet() external view returns (address);
    /// @return Productive USDC principal and booked rewards tracked by the adapter.
    function productiveAssets() external view returns (uint256);
    /// @return The time window over which newly-booked rewards are released into `realAssets()`. Zero until
    ///         first configured.
    function dividendInterval() external view returns (uint256);
    /// @return Total reward value currently being dripped.
    function dripBuffer() external view returns (uint256);
    /// @return Timestamp when the current value-bearing drip window started.
    function dripStartTime() external view returns (uint64);
    /// @return Duration captured for the active drip cycle. Together with `dripStartTime` this snapshots the active
    ///         cycle's schedule and is unaffected by later `setDividendInterval` calls. When settlements stack, it is
    ///         the value-weighted average of the carry's remaining duration and the new reward's configured interval.
    function dripDuration() external view returns (uint256);
    /// @notice Returns the portion of the active drip buffer that has not yet been released.
    /// @dev Returns `0` once the captured duration has elapsed. Computed purely from the
    ///      `(dripBuffer, dripStartTime, dripDuration)` snapshot, never from the live
    ///      `dividendInterval`. When computing `realAssets()`, the portion not already consumed by an observed custody
    ///      loss is subtracted from `productiveAssets`, so a freshly-booked reward rises smoothly into share pricing
    ///      instead of as a discrete jump.
    /// @return The unreleased portion of the current drip buffer.
    function unreleasedDrip() external view returns (uint256);

    /// @return Observed USDC across this adapter and the Prime Onchain Wallet.
    function observedAssetBalance() external view returns (uint256);
    /// @return Observed but unbooked USDC surplus.
    function unaccountedAssetBalance() external view returns (uint256);
    /// @return Booked productive USDC not currently observed on-chain.
    function observedAssetDeficit() external view returns (uint256);

    /// @notice Returns whether a non-request settlement ID has already been booked.
    /// @param settlementId The settlement id to query.
    /// @return Whether `settlementId` has already been used.
    function settlementUsed(bytes32 settlementId) external view returns (bool);
    /// @notice Returns whether an observed-deficit ID has already been booked.
    /// @param deficitId The deficit id to query.
    /// @return Whether `deficitId` has already been used.
    function deficitUsed(bytes32 deficitId) external view returns (bool);
    /// @return Array containing this adapter's cap-tracking id.
    function ids() external view returns (bytes32[] memory);

    /* WRITE FUNCTIONS */

    /// @notice Updates the gate used when settlement or deficit booking requires a closed window.
    /// @dev Setting the gate to zero disables those booking paths until a gate is configured again.
    /// @param newSettlementGate The new settlement gate address.
    function setSettlementGate(address newSettlementGate) external;

    /// @notice Toggles whether `recordSettlement(...)` requires the configured gate to be closed
    ///         even when a drip is active.
    /// @dev Owner-only. Defaults to `true` (fail-closed). To enable the gateless settlement flow the
    ///      owner must (1) configure a non-zero `dividendInterval` AND (2) explicitly call
    ///      `setSettlementGateRequired(false)`. Both steps are required and auditable on-chain.
    ///      Independently of this flag, `recordSettlement` reverts with `DividendIntervalNotConfigured`
    ///      while `dividendInterval == 0`.
    /// @param required Whether settlement booking must require the gate.
    function setSettlementGateRequired(bool required) external;

    /// @notice Toggles whether an encoded `DeficitBooking` requires the configured gate to be closed.
    /// @dev Owner-only. Defaults to `true` because deficits cannot be smoothed via the drip and remain
    ///      sudden downward jumps that warrant a pause window.
    /// @param required Whether deficit booking must require the gate.
    function setDeficitGateRequired(bool required) external;

    /// @notice Sets the time window over which each newly-booked reward is linearly released into
    ///         `realAssets()`.
    /// @dev Owner-only. Set to match the reward cadence (e.g. 30 days for monthly reward
    ///      distributions). Applies only to drip cycles started by future `recordSettlement(...)`
    ///      calls: the active cycle's schedule is snapshotted in
    ///      `(dripStartTime, dripDuration)`, so changing this value never moves `realAssets()` in the
    ///      same transaction and never re-times the cycle itself. Reverts below
    ///      `MIN_DIVIDEND_INTERVAL`, so zero (immediate release behind a mandatory closed gate) is only
    ///      reachable as the unconfigured deployment default.
    /// @param newInterval The new reward drip interval.
    function setDividendInterval(uint256 newInterval) external;

    /// @notice Updates the trusted operator for settlement reconciliation.
    /// @param newOperator The new trusted operator.
    function setOperator(address newOperator) external;

    /// @notice Updates the trusted Coinbase Prime Onchain Wallet (POW) EOA that custodies productive USDC.
    /// @dev Owner-only. Must be non-zero. Reverts with `InvalidAddress` on the zero address.
    ///      OPERATIONAL WARNING: there is no on-chain check that `productiveAssets == 0` before rotation.
    ///      Rotating while `productiveAssets > 0` will strand principal at the previous POW and cause
    ///      `_realAssets()` to drop sharply, since the balance oracle now reads a different address.
    ///      The owner is responsible for migrating funds out of the old POW (e.g. by fully deallocating
    ///      the vault position through `deallocate`) before calling this function with a new address.
    ///      The new POW must separately call `IERC20(asset).approve(adapter, type(uint256).max)` before
    ///      any subsequent `deallocate` can pull funds back.
    /// @param newPrimeWallet The new Coinbase Prime Onchain Wallet.
    function setPrimeWallet(address newPrimeWallet) external;

    /// @notice Recovers tokens accidentally sent to this adapter that are not managed by its accounting.
    /// @dev Reverts if `token` is the productive USDC asset.
    /// @param token The token to recover.
    /// @param to The token recipient.
    function skim(address token, address to) external;

    /// @notice Books observed inbound USDC settlement such as Prime rewards or manual reconciliation transfers.
    /// @dev `settlementId` is a single-use operator reference to prevent duplicate booking of the same event.
    /// Reverts with `DividendIntervalNotConfigured` while `dividendInterval == 0` (the deployment default). A closed
    /// gate is required when `settlementGateRequired == true`. With `settlementGateRequired == false`, the gate can be
    /// skipped because the booked value is smoothed into `realAssets()`. Stacked rewards blend the active carry's remaining duration with the configured
    /// interval using value-weighted average math, so a small reward cannot restart the whole carry. OPERATIONAL NOTE:
    /// Coinbase pays USDC rewards into the Prime trading balance on the
    /// 5th business day of each month. Before calling this function the operator must have moved the reward USDC from
    /// the trading balance into the POW so that it is visible in `observedAssetBalance()` - only POW-side (or
    /// adapter-side in-transit) surplus is bookable.
    /// @param settlementId Single-use settlement id.
    /// @param assetIncrease Observed asset increase to book.
    function recordSettlement(bytes32 settlementId, uint256 assetIncrease) external;
}

src/vault-v2/interfaces/ISettlementWindowGate.sol

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

/// @title ISettlementWindowGate
/// @notice Minimal interface for adapters that require an externally controlled settlement window.
interface ISettlementWindowGate {
    /// @return open Whether settlement-sensitive adapter actions are currently allowed.
    function isOpen() external view returns (bool);
}

src/vault-v2/interfaces/IVaultV2.sol

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

/// @title IVaultV2
/// @notice Minimal interface for VaultV2 used by Lotus adapters.
/// @dev Local interface used at the VaultV2 dependency boundary.
interface IVaultV2 {
    /* VIEW FUNCTIONS */

    /// @notice Returns the vault asset token.
    /// @return assetToken The ERC20 asset address.
    function asset() external view returns (address);

    /// @notice Returns the vault owner.
    /// @return vaultOwner The owner address.
    function owner() external view returns (address);

    /// @param id The allocation identifier.
    /// @return cap The configured allocation cap.
    function allocation(bytes32 id) external view returns (uint256);

    /// @notice Returns whether an account is an allocator.
    /// @param account The account to query.
    /// @return isAllocator_ Whether `account` has allocator permissions.
    function isAllocator(address account) external view returns (bool);

    /// @notice Returns whether an account is a sentinel.
    /// @param account The account to query.
    /// @return isSentinel_ Whether `account` has sentinel permissions.
    function isSentinel(address account) external view returns (bool);

    /* ERC4626 FUNCTIONS */

    /* Included for selector matching in adapters. */
    /// @notice Deposits assets and mints shares to `receiver`.
    /// @param assets The amount of assets to deposit.
    /// @param receiver The receiver of minted shares.
    /// @return shares The amount of shares minted.
    function deposit(uint256 assets, address receiver) external returns (uint256);

    /// @notice Mints shares for `receiver` by depositing assets.
    /// @param shares The amount of shares to mint.
    /// @param receiver The receiver of minted shares.
    /// @return assets The amount of assets spent.
    function mint(uint256 shares, address receiver) external returns (uint256);

    /// @notice Withdraws assets to `receiver` by burning shares from `owner`.
    /// @param assets The amount of assets to withdraw.
    /// @param receiver The receiver of withdrawn assets.
    /// @param owner The share owner being debited.
    /// @return shares The amount of shares burned.
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256);

    /// @notice Redeems shares from `owner` and sends assets to `receiver`.
    /// @param shares The amount of shares to redeem.
    /// @param receiver The receiver of redeemed assets.
    /// @param owner The share owner being debited.
    /// @return assets The amount of assets returned.
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256);

    /* MULTICALL */

    /// @notice Executes a batch of encoded calls.
    /// @param data The encoded calls.
    /// @return results The return data for each call.
    function multicall(bytes[] memory data) external returns (bytes[] memory results);

    /* OWNER FUNCTIONS */

    /* These functions do not require the VaultV2 timelock. */
    /// @notice Sets the vault owner.
    /// @param newOwner The new owner address.
    function setOwner(address newOwner) external;

    /// @notice Sets the vault curator.
    /// @param newCurator The new curator address.
    function setCurator(address newCurator) external;

    /// @notice Grants or revokes sentinel permissions.
    /// @dev Sentinel can deallocate, revoke pending timelocked curator actions, and decrease absolute or relative caps.
    ///      It does not receive allocator, liquidity-adapter, or max-rate permissions from this role alone.
    /// @param account The account to update.
    /// @param isSentinel Whether sentinel permissions are enabled.
    function setIsSentinel(address account, bool isSentinel) external;

    /// @notice Sets the vault name.
    /// @param newName The new name.
    function setName(string memory newName) external;

    /// @notice Sets the vault symbol.
    /// @param newSymbol The new symbol.
    function setSymbol(string memory newSymbol) external;

    /* TIMELOCK SUBMISSION */

    /// @notice Submits encoded timelocked action data.
    /// @param data The encoded action.
    function submit(bytes memory data) external;

    /* CURATOR FUNCTIONS */

    /* These functions require submit + execute in the configured VaultV2. */
    /// @notice Adds an adapter to the vault.
    /// @param account The adapter address.
    function addAdapter(address account) external;

    /// @notice Grants or revokes allocator permissions.
    /// @param account The account to update.
    /// @param newIsAllocator Whether allocator permissions are enabled.
    function setIsAllocator(address account, bool newIsAllocator) external;

    /// @notice Sets the adapter registry.
    /// @param newAdapterRegistry The new adapter registry address.
    function setAdapterRegistry(address newAdapterRegistry) external;

    /// @notice Disables a timelocked selector from the current curator.
    /// @param selector The selector to abdicate.
    function abdicate(bytes4 selector) external;

    /// @notice Increases an absolute cap for an id.
    /// @param idData Encoded id data.
    /// @param newAbsoluteCap The new absolute cap.
    function increaseAbsoluteCap(bytes memory idData, uint256 newAbsoluteCap) external;

    /// @notice Increases a relative cap for an id.
    /// @param idData Encoded id data.
    /// @param newRelativeCap The new relative cap.
    function increaseRelativeCap(bytes memory idData, uint256 newRelativeCap) external;

    /* ALLOCATOR FUNCTIONS */

    /// @notice Allocates assets to an adapter.
    /// @param adapter The adapter address.
    /// @param data Adapter-specific allocation data.
    /// @param assets The amount of assets to allocate.
    function allocate(address adapter, bytes memory data, uint256 assets) external;

    /// @notice Deallocates assets from an adapter.
    /// @param adapter The adapter address.
    /// @param data Adapter-specific deallocation data.
    /// @param assets The amount of assets to deallocate.
    function deallocate(address adapter, bytes memory data, uint256 assets) external;

    /// @notice Sets the liquidity adapter and its encoded data.
    /// @param newLiquidityAdapter The new liquidity adapter.
    /// @param newLiquidityData Encoded liquidity adapter data.
    function setLiquidityAdapterAndData(address newLiquidityAdapter, bytes memory newLiquidityData) external;

    /// @notice Sets the max interest rate (per-second, WAD-based).
    /// @param newMaxRate The new max rate.
    function setMaxRate(uint256 newMaxRate) external;

    /* PERMISSIONLESS FUNCTIONS */

    /// @notice Permissionlessly force-deallocates assets on behalf of an account, subject to the adapter behavior and
    /// configured Vault V2 penalty.
    /// @param adapter The adapter address.
    /// @param data Adapter-specific deallocation data.
    /// @param assets The amount of assets to deallocate.
    /// @param onBehalf The account on whose behalf the action is executed.
    /// @return penaltyShares The penalty shares charged.
    function forceDeallocate(address adapter, bytes memory data, uint256 assets, address onBehalf)
        external
        returns (uint256 penaltyShares);
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "ipfs",
    "useLiteralContent": false
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
    "solady/=lib/solady/",
    "bundler3/=lib/bundler3/",
    "ds-test/=lib/openzeppelin-contracts-upgradeable/lib/forge-std/lib/ds-test/src/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "halmos-cheatcodes/=lib/bundler3/lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
    "morpho-blue/=lib/bundler3/lib/morpho-blue/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts/",
    "prb-math/=lib/prb-math/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.