Skip to content
Verified contractExactGPL-2.0-or-later

WGTXXAdapter

Address0xb3cdb56871fbc4abe68eda832e50a20495d5b2c4
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,598
Creation transaction
0x50836c5ef5…06db06fc72

src/vault-v2/adapters/WGTXXAdapter.sol

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

import {IERC721Receiver} from "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {FixedPointMathLib} from "solady/src/utils/FixedPointMathLib.sol";
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";

import {IERC20} from "../../interfaces/IERC20.sol";
import {IERC20Metadata} from "../../interfaces/IERC20Metadata.sol";
import {AggregatorV3Interface} from "../../oracles/interfaces/AggregatorV3Interface.sol";
import {IVaultV2} from "../interfaces/IVaultV2.sol";
import {ISettlementWindowGate} from "../interfaces/ISettlementWindowGate.sol";
import {IWGTXXAdapter} from "../interfaces/IWGTXXAdapter.sol";

/// @title WGTXXAdapter
/// @notice Manual-allocation Vault V2 adapter for async WGTXX create and redeem settlement flows.
contract WGTXXAdapter is IWGTXXAdapter, IERC721Receiver {
    uint256 internal constant _WAD = 1e18;
    uint8 internal constant _MAX_SUPPORTED_FEED_DECIMALS = 77;
    /// @dev Each side of the share price band must sit at least 1% and at most 50% away from par.
    uint256 internal constant _MIN_SHARE_PRICE_BAND_DEVIATION_WAD = 0.01e18;
    uint256 internal constant _MAX_SHARE_PRICE_BAND_DEVIATION_WAD = 0.5e18;
    // NAV feed heartbeat is 24h (max observed gap 24.03h); 3 days bounds staleness with margin for delays.
    uint256 internal constant _MAX_NAV_STALENESS = 3 days;
    uint256 internal constant _BPS = 10_000;
    uint256 internal constant _MAX_SETTLEMENT_SURPLUS_BPS = 1_000;

    /// @inheritdoc IWGTXXAdapter
    string public constant ADAPTER_TYPE = "WGTXXAdapter";
    /// @inheritdoc IWGTXXAdapter
    /// @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 IWGTXXAdapter
    address public immutable FACTORY;
    /// @inheritdoc IWGTXXAdapter
    address public immutable PARENT_VAULT;
    /// @inheritdoc IWGTXXAdapter
    address public immutable ASSET;
    /// @inheritdoc IWGTXXAdapter
    address public immutable SHARE_TOKEN;
    /// @inheritdoc IWGTXXAdapter
    bytes32 public immutable ADAPTER_ID;
    /// @dev Decimal-normalization factor used to express one WGTXX share in settlement-asset units before pricing.
    uint256 internal immutable _SHARE_TO_ASSET_SCALE_FACTOR;
    /// @dev Whether share-to-asset normalization divides by `_SHARE_TO_ASSET_SCALE_FACTOR` instead of multiplying.
    bool internal immutable _SHARE_TO_ASSET_DIVIDES;

    /* STORAGE */

    /// @inheritdoc IWGTXXAdapter
    address public createDepositAddress;
    /// @inheritdoc IWGTXXAdapter
    address public redeemDepositAddress;
    /// @inheritdoc IWGTXXAdapter
    address public settlementGate;
    /// @inheritdoc IWGTXXAdapter
    address public operator;

    /// @inheritdoc IWGTXXAdapter
    /// @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 IWGTXXAdapter
    /// @dev Whether an `ObservedDeficit` loss booking 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 IWGTXXAdapter
    /// @dev Timestamp when the current drip window started. Re-anchored on every value-bearing settlement fold
    ///      and loss write-down.
    uint64 public dripStartTime;

    /// @inheritdoc IWGTXXAdapter
    uint256 public settledShareBalance;
    /// @inheritdoc IWGTXXAdapter
    uint256 public settledShareAssets;
    /// @inheritdoc IWGTXXAdapter
    uint256 public pendingCreateAssets;
    /// @inheritdoc IWGTXXAdapter
    uint256 public pendingRedeemShares;
    /// @inheritdoc IWGTXXAdapter
    uint256 public claimableAssets;

    /// @inheritdoc IWGTXXAdapter
    /// @dev Time window over which each newly-booked dividend is linearly released into `realAssets()`.
    ///      Owner-set, typically configured once to match the dividend cadence (e.g. 30 days for monthly
    ///      WGTXX distributions). Zero only as the unconfigured deployment default, where recordSettlement
    ///      releases immediately and the gate is mandatory regardless of `settlementGateRequired`. This
    ///      value parameterizes only cycles started by future `recordSettlement` calls: the active cycle's
    ///      schedule is snapshotted into `(dripStartTime, dripDuration)` and is never re-timed by changing
    ///      this value.
    uint256 public dividendInterval;
    /// @inheritdoc IWGTXXAdapter
    /// @dev Total dividend value currently being dripped (set by `recordSettlement`). Includes any
    ///      carry-over from a previous unreleased portion when settlements are stacked.
    uint256 public dripBuffer;
    /// @inheritdoc IWGTXXAdapter
    /// @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 dividend's configured interval using value-weighted average math.
    uint256 public dripDuration;

    /// @inheritdoc IWGTXXAdapter
    address public navFeed;
    /// @inheritdoc IWGTXXAdapter
    uint256 public maxNavStaleness;
    /// @inheritdoc IWGTXXAdapter
    uint256 public minSharePriceWad;
    /// @inheritdoc IWGTXXAdapter
    uint256 public maxSharePriceWad;
    /// @inheritdoc IWGTXXAdapter
    uint8 public navFeedDecimals;
    /// @inheritdoc IWGTXXAdapter
    uint256 public sharePriceWad;
    /// @inheritdoc IWGTXXAdapter
    uint256 public maxSettlementSurplusBps;

    /// @dev Per-request create bookkeeping used to preserve pending value until settlement resolves.
    mapping(bytes32 requestId => PendingCreateRequest) internal _pendingCreates;
    /// @dev Per-request redeem share bookkeeping; value is derived from the current validated NAV.
    mapping(bytes32 requestId => PendingRedeemRequest) internal _pendingRedeems;
    /// @inheritdoc IWGTXXAdapter
    mapping(bytes32 requestId => bool) public requestUsed;
    /// @inheritdoc IWGTXXAdapter
    mapping(bytes32 settlementId => bool) public settlementUsed;
    /// @inheritdoc IWGTXXAdapter
    mapping(bytes32 deficitId => bool) public deficitUsed;

    /* CONSTRUCTOR */

    /// @param _parentVault Parent Vault V2 address, expected to use the same asset as the WGTXX settlement asset.
    /// @param _shareToken WGTXX token address received after create settlement.
    /// @param _createDepositAddress WisdomTree deposit address used for create flows. Zero disables create initiation
    /// until the owner configures a non-zero address.
    /// @param _redeemDepositAddress WisdomTree deposit address used for redeem flows. This may be the same address.
    /// Zero disables redeem initiation until the owner configures a non-zero address.
    /// @param _operator Trusted operator for settlement reconciliation, yield accounting, and redeem initiation.
    /// @param _navOracleConfig WTGXX NAV / USD feed and validation bounds. The settlement asset must be USDC,
    /// and the venue must settle one USD of fund value for one USDC.
    constructor(
        address _parentVault,
        address _shareToken,
        address _createDepositAddress,
        address _redeemDepositAddress,
        address _operator,
        NavOracleConfig memory _navOracleConfig
    ) {
        if (_parentVault == address(0) || _shareToken == address(0) || _operator == address(0)) {
            revert InvalidAddress();
        }

        FACTORY = msg.sender;
        PARENT_VAULT = _parentVault;
        ASSET = IVaultV2(_parentVault).asset();
        SHARE_TOKEN = _shareToken;
        ADAPTER_ID = keccak256(abi.encode("wgtxx", address(this)));

        (uint256 scaleFactor, bool divides) =
            _shareToAssetScale(_readTokenDecimals(ASSET), _readTokenDecimals(_shareToken));
        _SHARE_TO_ASSET_SCALE_FACTOR = scaleFactor;
        _SHARE_TO_ASSET_DIVIDES = divides;

        _setNavOracleConfig(_navOracleConfig, false);

        createDepositAddress = _createDepositAddress;
        redeemDepositAddress = _redeemDepositAddress;
        operator = _operator;

        emit SetSettlementAddresses(_createDepositAddress, _redeemDepositAddress);
        emit SetOperator(_operator);
        emit SetSettlementGateRequired(settlementGateRequired);
        emit SetDeficitGateRequired(deficitGateRequired);

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

    /* ADMIN */

    /// @inheritdoc IWGTXXAdapter
    function setSettlementAddresses(address newCreateDepositAddress, address newRedeemDepositAddress) external {
        _requireOwner();
        createDepositAddress = newCreateDepositAddress;
        redeemDepositAddress = newRedeemDepositAddress;
        emit SetSettlementAddresses(newCreateDepositAddress, newRedeemDepositAddress);
    }

    /// @inheritdoc IWGTXXAdapter
    /// @dev Zero disables settlement reconciliation and deficit booking until a gate is configured again.
    function setSettlementGate(address newSettlementGate) external {
        _requireOwner();
        settlementGate = newSettlementGate;
        emit SetSettlementGate(newSettlementGate);
    }

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

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

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

    /// @inheritdoc IWGTXXAdapter
    function setMaxSettlementSurplusBps(uint256 newBps) external {
        _requireOwner();
        if (newBps > _MAX_SETTLEMENT_SURPLUS_BPS) revert InvalidSettlementSurplusBps();
        maxSettlementSurplusBps = newBps;
        emit SetMaxSettlementSurplusBps(newBps);
    }

    /// @inheritdoc IWGTXXAdapter
    function setNavOracleConfig(NavOracleConfig calldata newConfig) external {
        _requireOwner();
        // A failing live feed already blocks window-open pricing, so it can be replaced without closing the window.
        if (_hasLiveSharePrice()) _requireSettlementWindowClosed();
        _setNavOracleConfig(newConfig, true);
    }

    /// @inheritdoc IWGTXXAdapter
    function syncNav() external returns (uint256 newSharePriceWad) {
        _requireSettlementWindowClosed();
        newSharePriceWad =
            _readSharePriceWad(navFeed, navFeedDecimals, maxNavStaleness, minSharePriceWad, maxSharePriceWad);
        _checkpointNav(newSharePriceWad);
    }

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

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

    /// @inheritdoc IERC721Receiver
    /// @dev Accepts any safe ERC-721 receipt. These NFTs are operational metadata only and never affect adapter NAV.
    function onERC721Received(address, address, uint256, bytes calldata) external pure returns (bytes4) {
        return IERC721Receiver.onERC721Received.selector;
    }

    /* VAULT ADAPTER ENTRYPOINTS */

    /// @inheritdoc IWGTXXAdapter
    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.allocate.selector) revert ManualAllocateOnly();
        if (!IVaultV2(PARENT_VAULT).isAllocator(sender)) revert NotAuthorized();
        if (assets == 0) return _syncZeroAllocationDelta(data);
        if (data.length != 32) revert InvalidData();
        if (createDepositAddress == address(0)) revert SettlementAddressNotSet();

        bytes32 requestId = abi.decode(data, (bytes32));
        if (requestId == bytes32(0)) revert InvalidData();
        if (requestUsed[requestId]) revert RequestAlreadyExists();
        if (!_SHARE_TO_ASSET_DIVIDES && assets % _SHARE_TO_ASSET_SCALE_FACTOR != 0) {
            revert UnrepresentableCreateAmount();
        }

        requestUsed[requestId] = true;
        _pendingCreates[requestId] = PendingCreateRequest({assets: assets});
        pendingCreateAssets += assets;

        SafeTransferLib.safeTransfer(ASSET, createDepositAddress, assets);
        emit CreateRequested(requestId, assets);

        // forge-lint: disable-next-item(unsafe-typecast)
        return (ids(), int256(assets));
    }

    /// @inheritdoc IWGTXXAdapter
    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.deallocate.selector) revert ManualDeallocateOnly();
        if (assets == 0 && data.length != 0) return _bookLossAndSyncAllocation(data, sender);
        if (!_isAllocatorOrSentinel(sender)) revert NotAuthorized();
        if (assets == 0) return _syncAllocationDelta(data);
        if (data.length != 0) revert InvalidData();
        uint256 claimable = claimableAssets;
        if (assets > claimable || assets > _realAssets()) revert InsufficientClaimableAssets();

        uint256 remaining;
        unchecked {
            remaining = claimable - assets;
        }
        claimableAssets = remaining;
        emit Deallocated(assets, remaining);

        // forge-lint: disable-next-item(unsafe-typecast)
        return (ids(), -int256(assets));
    }

    /* OPERATIONAL FLOWS */

    /// @inheritdoc IWGTXXAdapter
    /// @dev This is a custom operational method, not a Vault V2 `deallocate` path.
    ///      The operator is allowed here because the transcripted redeem flow is a two-step async ops workflow.
    ///      On initiation, the adapter moves the redeeming shares from settled to pending exposure. Both are valued at
    ///      the same live price, so NAV stays flat while the pending leg remains exposed to subsequent NAV changes.
    function requestRedeem(bytes32 requestId, uint256 shares) external returns (uint256 assetValueRemoved) {
        _requireAllocatorOperatorOrOwner();
        _checkpointCurrentNavIfNeeded(0);
        if (requestId == bytes32(0)) revert InvalidData();
        if (requestUsed[requestId]) revert RequestAlreadyExists();
        if (redeemDepositAddress == address(0)) revert SettlementAddressNotSet();
        if (shares == 0) revert ZeroAmount();
        if (settledShareBalance < shares) revert InsufficientSettledShares();

        uint256 previousSettledShareAssets = settledShareAssets;

        requestUsed[requestId] = true;
        settledShareBalance -= shares;
        settledShareAssets = _sharesToAssetValue(settledShareBalance);
        assetValueRemoved = previousSettledShareAssets - settledShareAssets;
        pendingRedeemShares += shares;
        _pendingRedeems[requestId] = PendingRedeemRequest({shares: shares});

        SafeTransferLib.safeTransfer(SHARE_TOKEN, redeemDepositAddress, shares);
        emit RedeemRequested(requestId, shares, assetValueRemoved);
    }

    /// @inheritdoc IWGTXXAdapter
    /// @dev Returned WGTXX is valued at the checkpointed oracle price.
    function settleCreate(bytes32 requestId, uint256 sharesReceived) external {
        _requireOperatorOrOwner();
        _requireSettlementWindowClosed();
        _checkpointCurrentNavIfNeeded(sharesReceived);
        if (sharesReceived == 0) revert ZeroAmount();
        (uint256 shareAssetValue, uint256 expectedAssetValue) = _resolveCreate(requestId, sharesReceived, 0);
        _addToDrip(
            _requireSettlementValue(
                shareAssetValue, expectedAssetValue, _createSettlementRoundingTolerance(sharesReceived)
            )
        );

        emit CreateSettled(requestId, sharesReceived, shareAssetValue);
    }

    /// @inheritdoc IWGTXXAdapter
    function resolveCreate(bytes32 requestId, uint256 sharesReceived, uint256 claimableAssetIncrease) external {
        _requireOperatorOrOwner();
        _requireSettlementWindowClosed();
        _checkpointCurrentNavIfNeeded(sharesReceived);
        (uint256 shareAssetValue, uint256 expectedAssetValue) =
            _resolveCreate(requestId, sharesReceived, claimableAssetIncrease);
        _addToDrip(
            _requireSettlementValue(
                shareAssetValue + claimableAssetIncrease,
                expectedAssetValue,
                _createSettlementRoundingTolerance(sharesReceived)
            )
        );
        emit CreateResolved(requestId, sharesReceived, shareAssetValue, claimableAssetIncrease);
    }

    function _resolveCreateWithLoss(bytes32 requestId, uint256 sharesReceived, uint256 claimableAssetIncrease)
        internal
    {
        _requireSettlementWindowClosed();
        _checkpointCurrentNavIfNeeded(sharesReceived);

        PendingCreateRequest memory request = _pendingCreates[requestId];
        if (request.assets == 0) revert UnknownRequest();
        if (_unaccountedSettlementAssetValue(0) >= request.assets) revert LossResolutionNotRequired();

        (uint256 shareAssetValue,) = _resolveCreate(requestId, sharesReceived, claimableAssetIncrease);
        uint256 observedValue = shareAssetValue + claimableAssetIncrease;
        if (observedValue >= request.assets) revert LossResolutionNotRequired();

        _reduceDripOnLoss(request.assets - observedValue);

        emit CreateLossResolved(
            requestId, sharesReceived, shareAssetValue, claimableAssetIncrease, request.assets - observedValue
        );
    }

    /// @inheritdoc IWGTXXAdapter
    function settleRedeem(bytes32 requestId, uint256 assetsReceived) external {
        _requireOperatorOrOwner();
        _requireSettlementWindowClosed();
        _checkpointCurrentNavIfNeeded(0);
        if (assetsReceived == 0) revert ZeroAmount();
        (, uint256 expectedAssetValue) = _resolveRedeem(requestId, 0, assetsReceived);
        _addToDrip(_requireSettlementValue(assetsReceived, expectedAssetValue, 0));
        emit RedeemSettled(requestId, assetsReceived);
    }

    /// @inheritdoc IWGTXXAdapter
    function resolveRedeem(bytes32 requestId, uint256 sharesReceived, uint256 claimableAssetIncrease) external {
        _requireOperatorOrOwner();
        _requireSettlementWindowClosed();
        _checkpointCurrentNavIfNeeded(sharesReceived);
        (uint256 shareAssetValue, uint256 expectedAssetValue) =
            _resolveRedeem(requestId, sharesReceived, claimableAssetIncrease);
        _addToDrip(_requireSettlementValue(shareAssetValue + claimableAssetIncrease, expectedAssetValue, 0));
        emit RedeemResolved(requestId, sharesReceived, shareAssetValue, claimableAssetIncrease);
    }

    function _resolveRedeemWithLoss(bytes32 requestId, uint256 sharesReceived, uint256 claimableAssetIncrease)
        internal
    {
        _requireSettlementWindowClosed();
        _checkpointCurrentNavIfNeeded(sharesReceived);

        PendingRedeemRequest memory request = _pendingRedeems[requestId];
        if (request.shares == 0) revert UnknownRequest();
        uint256 expectedAssetValue = _pendingRedeemRequestValue(request.shares);
        if (_unaccountedSettlementAssetValue(request.shares) >= expectedAssetValue) {
            revert LossResolutionNotRequired();
        }

        (uint256 shareAssetValue,) = _resolveRedeem(requestId, sharesReceived, claimableAssetIncrease);
        uint256 observedValue = shareAssetValue + claimableAssetIncrease;
        if (observedValue >= expectedAssetValue) revert LossResolutionNotRequired();

        _reduceDripOnLoss(expectedAssetValue - observedValue);

        emit RedeemLossResolved(
            requestId, sharesReceived, shareAssetValue, claimableAssetIncrease, expectedAssetValue - observedValue
        );
    }

    /// @inheritdoc IWGTXXAdapter
    /// @dev Records observed inbound settlement that is not tied to a specific create / redeem request.
    ///      This covers share distributions, cash distributions, manual corrections, or other venue-originated inflows.
    ///      Generic settlement is blocked while any create or redeem request is pending because inbound share and asset
    ///      balances carry no onchain provenance. Request-specific settlement must run first; any genuine surplus stays
    ///      unaccounted and can be booked here after every pending request has been reconciled.
    ///      The booked value is added to the appropriate base bucket immediately, and when
    ///      `dividendInterval > 0` it is also placed into the drip buffer so that `realAssets()` releases
    ///      it gradually 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
    ///      dividend can never hit `realAssets()` as an undripped discrete jump.
    ///      Front-running protection is fail-closed: a closed gate is REQUIRED whenever an observable custody deficit
    ///      remains, because adding a cross-leg dividend to the drip can otherwise create an immediate NAV step. A
    ///      closed gate is also 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 sharesReceived, uint256 claimableAssetIncrease) external {
        _requireOperatorOrOwner();
        if (dividendInterval == 0) revert DividendIntervalNotConfigured();
        if (settlementGateRequired || observedShareDeficit() != 0 || observedAssetDeficit() != 0) {
            _requireSettlementWindowClosed();
        }
        _checkpointCurrentNavIfNeeded(sharesReceived);
        if (settlementId == bytes32(0)) revert InvalidData();
        if (settlementUsed[settlementId]) revert SettlementAlreadyRecorded();
        if (pendingCreateAssets != 0 || pendingRedeemShares != 0) revert PendingRequestsOutstanding();

        settlementUsed[settlementId] = true;
        uint256 shareAssetValue = _applyObservedSettlement(sharesReceived, claimableAssetIncrease, false);

        // The interval is non-zero here, so the new dividend and active carry are blended without restarting all carry
        // for a full interval. A share-only booking whose oracle value rounds to zero leaves the existing drip state untouched.
        _addToDrip(shareAssetValue + claimableAssetIncrease);

        emit SettlementRecorded(settlementId, sharesReceived, shareAssetValue, claimableAssetIncrease);
    }

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

        // Clamp each to the live observable deficit so a dust donation cannot front-run and revert the booking.
        uint256 observedShareDef = observedShareDeficit();
        uint256 observedAssetDef = observedAssetDeficit();
        if (shareBalanceDecrease > observedShareDef) shareBalanceDecrease = observedShareDef;
        if (claimableAssetDecrease > observedAssetDef) claimableAssetDecrease = observedAssetDef;
        if (shareBalanceDecrease == 0 && claimableAssetDecrease == 0) revert DeficitExceedsObservedLoss();

        deficitUsed[deficitId] = true;

        uint256 shareAssetValueDecrease = 0;
        if (shareBalanceDecrease > 0) {
            uint256 previousTotalShareAssets = _sharesToAssetValue(settledShareBalance + pendingRedeemShares);
            settledShareBalance -= shareBalanceDecrease;
            settledShareAssets = _sharesToAssetValue(settledShareBalance);
            shareAssetValueDecrease =
                previousTotalShareAssets - _sharesToAssetValue(settledShareBalance + pendingRedeemShares);
        }

        if (claimableAssetDecrease > 0) claimableAssets -= claimableAssetDecrease;

        _reduceDripOnLoss(shareAssetValueDecrease + claimableAssetDecrease);

        emit DeficitRecorded(deficitId, shareBalanceDecrease, shareAssetValueDecrease, claimableAssetDecrease);
    }

    /* VIEW */

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

    /// @inheritdoc IWGTXXAdapter
    function currentSharePriceWad() external view returns (uint256) {
        return _currentSharePriceWad();
    }

    /// @inheritdoc IWGTXXAdapter
    function observedShareBalance() public view returns (uint256) {
        return IERC20(SHARE_TOKEN).balanceOf(address(this));
    }

    /// @inheritdoc IWGTXXAdapter
    function observedAssetBalance() public view returns (uint256) {
        return IERC20(ASSET).balanceOf(address(this));
    }

    /// @inheritdoc IWGTXXAdapter
    function unaccountedShareBalance() public view returns (uint256) {
        uint256 observed = observedShareBalance();
        return observed > settledShareBalance ? observed - settledShareBalance : 0;
    }

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

    /// @inheritdoc IWGTXXAdapter
    function observedShareDeficit() public view returns (uint256) {
        uint256 observed = observedShareBalance();
        return settledShareBalance > observed ? settledShareBalance - observed : 0;
    }

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

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

    /// @inheritdoc IWGTXXAdapter
    function pendingRedeemAssets() public view returns (uint256) {
        if (pendingRedeemShares == 0) return 0;
        return _pendingRedeemValueAtPrice(_currentSharePriceWad());
    }

    /// @inheritdoc IWGTXXAdapter
    function pendingCreates(bytes32 requestId) external view returns (uint256 assets, bool isPending) {
        PendingCreateRequest memory request = _pendingCreates[requestId];
        return (request.assets, request.assets != 0);
    }

    /// @inheritdoc IWGTXXAdapter
    function pendingRedeems(bytes32 requestId)
        external
        view
        returns (uint256 shares, uint256 assetValue, bool isPending)
    {
        PendingRedeemRequest memory request = _pendingRedeems[requestId];
        shares = request.shares;
        isPending = shares != 0;
        if (isPending) assetValue = _pendingRedeemRequestValueAtPrice(shares, _currentSharePriceWad());
    }

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

    /* INTERNAL */

    /// @dev Executes a loss-side operation inside the parent Vault V2's zero-asset `deallocate` callback, then returns
    ///      the complete booked-exposure delta. Vault V2 applies that delta before the outer call can succeed, so the
    ///      adapter write-down and parent cap ledger cannot diverge. The outer vault call independently requires its
    ///      caller to be an allocator or sentinel; this router preserves the adapter's stricter operator/owner roles.
    function _bookLossAndSyncAllocation(bytes calldata data, address sender)
        internal
        returns (bytes32[] memory, int256)
    {
        if (data.length != 128) revert InvalidData();
        (uint256 lossType, bytes32 id, uint256 shareAmount, uint256 assetAmount) =
            abi.decode(data, (uint256, bytes32, uint256, uint256));

        if (lossType == uint256(IWGTXXAdapter.LossType.ObservedDeficit)) {
            _requireOperatorOrOwner(sender);
            _recordObservedDeficit(id, shareAmount, assetAmount);
        } else if (lossType == uint256(IWGTXXAdapter.LossType.Create)) {
            _requireOwner(sender);
            _resolveCreateWithLoss(id, shareAmount, assetAmount);
        } else if (lossType == uint256(IWGTXXAdapter.LossType.Redeem)) {
            _requireOwner(sender);
            _resolveRedeemWithLoss(id, shareAmount, assetAmount);
        } else {
            revert InvalidData();
        }

        return _syncAllocationDelta();
    }

    /// @dev Returns the drip-inclusive booked exposure delta versus Vault V2 allocation for zero-asset sync calls.
    ///      Cap usage includes tracked value before drip subtraction; raw observations remain excluded until reconciled.
    function _syncAllocationDelta(bytes calldata data) internal view returns (bytes32[] memory, int256) {
        if (data.length != 0) revert InvalidData();

        return _syncAllocationDelta();
    }

    /// @dev Returns the drip-inclusive booked-exposure delta after the caller has validated its adapter data.
    function _syncAllocationDelta() internal view returns (bytes32[] memory, int256) {
        uint256 allocation_ = IVaultV2(PARENT_VAULT).allocation(ADAPTER_ID);
        uint256 bookedExposure_ = _bookedExposure();

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

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

    /// @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();
        uint256 bookedExposure_ = _bookedExposure();
        if (bookedExposure_ == 0) revert ZeroAmount();
        // forge-lint: disable-next-item(unsafe-typecast)
        return (ids(), int256(bookedExposure_));
    }

    /// @dev Returns the full reconciled venue exposure used for Vault V2 cap accounting.
    ///      Unlike `_realAssets()`, this deliberately includes the unreleased portion of an active drip.
    function _bookedExposure() internal view returns (uint256) {
        uint256 totalShareExposure = settledShareBalance + pendingRedeemShares;
        uint256 shareExposure =
            totalShareExposure == 0 ? 0 : _sharesToAssetValueAtPrice(totalShareExposure, _currentSharePriceWad());
        return shareExposure + pendingCreateAssets + claimableAssets;
    }

    /// @dev Returns the adapter's booked NAV contribution at the live oracle price, immediately floored by custody
    ///      shortfalls on the locally-held settled-share and claimable-asset legs. Pending creates and pending redeems
    ///      remain fully valued because those assets sit at their external settlement destinations. An observed loss
    ///      consumes unreleased drip first, exactly matching `_reduceDripOnLoss`, so later deficit booking only reconciles
    ///      tracked state and cannot move NAV.
    function _realAssets() internal view returns (uint256) {
        uint256 settledShares = settledShareBalance;
        uint256 pendingShares = pendingRedeemShares;
        uint256 totalShareExposure = settledShares + pendingShares;

        uint256 bookedShareExposure;
        uint256 observableShareExposure;
        if (totalShareExposure != 0) {
            uint256 priceWad = _currentSharePriceWad();
            bookedShareExposure = _sharesToAssetValueAtPrice(totalShareExposure, priceWad);

            uint256 observableSettledShares = settledShares;
            if (settledShares != 0) {
                uint256 observedShares = observedShareBalance();
                if (observedShares < observableSettledShares) observableSettledShares = observedShares;
            }
            observableShareExposure = _sharesToAssetValueAtPrice(observableSettledShares + pendingShares, priceWad);
        }

        uint256 claimable = claimableAssets;
        uint256 observableClaimable = claimable;
        if (claimable != 0) {
            uint256 observedAssets = observedAssetBalance();
            if (observedAssets < observableClaimable) observableClaimable = observedAssets;
        }

        uint256 base = bookedShareExposure + pendingCreateAssets + claimable;
        uint256 custodyLoss = bookedShareExposure - observableShareExposure + (claimable - observableClaimable);
        uint256 unreleased = _unreleasedDrip();
        uint256 recognizedBase = base > unreleased ? base - unreleased : 0;

        // Mirror `_reduceDripOnLoss` before the operator books the deficit: custody loss consumes unreleased
        // dividend value first, and only the excess is an immediate reduction of already-recognized NAV.
        if (custodyLoss <= unreleased) return recognizedBase;
        uint256 recognizedLoss = custodyLoss - unreleased;
        return recognizedBase > recognizedLoss ? recognizedBase - recognizedLoss : 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 dividend 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);
    }

    /// @dev Resolves a pending create by removing its temporary pending-value bucket and absorbing observed settlement.
    ///      The caller decides whether the result must match exactly or can flow through the owner-only loss path.
    function _resolveCreate(bytes32 requestId, uint256 sharesReceived, uint256 claimableAssetIncrease)
        internal
        returns (uint256 shareAssetValue, uint256 expectedAssetValue)
    {
        PendingCreateRequest memory request = _pendingCreates[requestId];
        if (request.assets == 0) revert UnknownRequest();

        expectedAssetValue = request.assets;
        pendingCreateAssets -= expectedAssetValue;
        delete _pendingCreates[requestId];

        shareAssetValue = _applyObservedSettlement(sharesReceived, claimableAssetIncrease, true);
    }

    /// @dev Resolves a pending redeem by removing its temporary pending-value bucket and absorbing observed settlement.
    ///      The caller decides whether the result must match exactly or can flow through the owner-only loss path.
    function _resolveRedeem(bytes32 requestId, uint256 sharesReceived, uint256 claimableAssetIncrease)
        internal
        returns (uint256 shareAssetValue, uint256 expectedAssetValue)
    {
        PendingRedeemRequest memory request = _pendingRedeems[requestId];
        if (request.shares == 0) revert UnknownRequest();

        expectedAssetValue = _pendingRedeemRequestValue(request.shares);
        pendingRedeemShares -= request.shares;
        delete _pendingRedeems[requestId];

        shareAssetValue = _applyObservedSettlement(sharesReceived, claimableAssetIncrease, true);
    }

    /// @dev Books observed settlement into tracked state. Returned WGTXX is valued as its marginal contribution to
    ///      total settled-plus-pending share exposure, matching the aggregate share valuation used by `realAssets()`.
    ///      Only balances already observable onchain may be absorbed.
    function _applyObservedSettlement(uint256 sharesReceived, uint256 claimableAssetIncrease, bool allowZero)
        internal
        returns (uint256 shareAssetValue)
    {
        if (!allowZero && sharesReceived == 0 && claimableAssetIncrease == 0) revert ZeroAmount();

        if (sharesReceived > 0) {
            if (unaccountedShareBalance() < sharesReceived) revert InsufficientObservedSettlement();
            uint256 previousTotalShareAssets = _sharesToAssetValue(settledShareBalance + pendingRedeemShares);
            settledShareBalance += sharesReceived;
            settledShareAssets = _sharesToAssetValue(settledShareBalance);
            shareAssetValue = _sharesToAssetValue(settledShareBalance + pendingRedeemShares) - previousTotalShareAssets;
        }

        if (claimableAssetIncrease > 0) {
            if (unaccountedAssetBalance() < claimableAssetIncrease) revert InsufficientObservedSettlement();
            claimableAssets += claimableAssetIncrease;
        }
    }

    /// @dev Converts WGTXX shares into asset units using decimal normalization and the checkpointed oracle price.
    function _sharesToAssetValue(uint256 shares) internal view returns (uint256) {
        return _sharesToAssetValueAtPrice(shares, sharePriceWad);
    }

    /// @dev Converts WGTXX shares into asset units at an explicit WAD-denominated price.
    function _sharesToAssetValueAtPrice(uint256 shares, uint256 priceWad) internal view returns (uint256) {
        return FixedPointMathLib.mulDiv(_sharesToAssetParValue(shares), priceWad, _WAD);
    }

    /// @dev Returns the live value contributed by all pending redeem shares, preserving aggregate rounding.
    function _pendingRedeemValueAtPrice(uint256 priceWad) internal view returns (uint256) {
        uint256 settledShares = settledShareBalance;
        return _sharesToAssetValueAtPrice(settledShares + pendingRedeemShares, priceWad)
            - _sharesToAssetValueAtPrice(settledShares, priceWad);
    }

    /// @dev Returns the checkpointed value removed if `requestShares` is the next pending redeem to resolve.
    function _pendingRedeemRequestValue(uint256 requestShares) internal view returns (uint256) {
        return _pendingRedeemRequestValueAtPrice(requestShares, sharePriceWad);
    }

    /// @dev Values one pending request as the marginal reduction in aggregate share exposure if resolved next.
    function _pendingRedeemRequestValueAtPrice(uint256 requestShares, uint256 priceWad)
        internal
        view
        returns (uint256)
    {
        uint256 totalShareExposure = settledShareBalance + pendingRedeemShares;
        return _sharesToAssetValueAtPrice(totalShareExposure, priceWad)
            - _sharesToAssetValueAtPrice(totalShareExposure - requestShares, priceWad);
    }

    /// @dev Applies only token-decimal normalization; the result is a pricing base, not an economic value assumption.
    function _sharesToAssetParValue(uint256 shares) internal view returns (uint256) {
        return _SHARE_TO_ASSET_DIVIDES ? shares / _SHARE_TO_ASSET_SCALE_FACTOR : shares * _SHARE_TO_ASSET_SCALE_FACTOR;
    }

    /// @dev Returns the currently observable, not-yet-booked settlement value across share and asset balances.
    ///      `pendingRedeemSharesRemoved` models the pending request that would be removed before returned shares are
    ///      restored. This keeps the owner-only loss check on the same aggregate base as actual settlement booking.
    function _unaccountedSettlementAssetValue(uint256 pendingRedeemSharesRemoved) internal view returns (uint256) {
        uint256 balance = settledShareBalance + pendingRedeemShares - pendingRedeemSharesRemoved;
        uint256 unaccounted = unaccountedShareBalance();
        return _sharesToAssetValue(balance + unaccounted) - _sharesToAssetValue(balance) + unaccountedAssetBalance();
    }

    /// @dev Validates and stores a new feed configuration, optionally repricing an existing settled position.
    function _setNavOracleConfig(NavOracleConfig memory newConfig, bool checkpointExistingPosition) internal {
        if (
            newConfig.navFeed == address(0) || newConfig.maxNavStaleness == 0
                || newConfig.maxNavStaleness > _MAX_NAV_STALENESS
        ) revert InvalidNavOracleConfig();
        if (
            newConfig.minSharePriceWad > _WAD - _MIN_SHARE_PRICE_BAND_DEVIATION_WAD
                || newConfig.minSharePriceWad < _WAD - _MAX_SHARE_PRICE_BAND_DEVIATION_WAD
                || newConfig.maxSharePriceWad < _WAD + _MIN_SHARE_PRICE_BAND_DEVIATION_WAD
                || newConfig.maxSharePriceWad > _WAD + _MAX_SHARE_PRICE_BAND_DEVIATION_WAD
        ) revert InvalidSharePriceBand();

        uint8 navDecimals = _readFeedDecimals(newConfig.navFeed);
        uint256 newSharePriceWad = _readSharePriceWad(
            newConfig.navFeed,
            navDecimals,
            newConfig.maxNavStaleness,
            newConfig.minSharePriceWad,
            newConfig.maxSharePriceWad
        );

        navFeed = newConfig.navFeed;
        maxNavStaleness = newConfig.maxNavStaleness;
        minSharePriceWad = newConfig.minSharePriceWad;
        maxSharePriceWad = newConfig.maxSharePriceWad;
        navFeedDecimals = navDecimals;

        if (checkpointExistingPosition) {
            _checkpointNav(newSharePriceWad);
        } else {
            sharePriceWad = newSharePriceWad;
        }

        emit SetNavOracleConfig(
            newConfig.navFeed, newConfig.maxNavStaleness, newConfig.minSharePriceWad, newConfig.maxSharePriceWad
        );
    }

    /// @dev Reprices the settled share checkpoint. Live NAV already reflects this price, so checkpointing must not
    ///      mutate dividend drip or otherwise move `realAssets()`.
    function _checkpointNav(uint256 newSharePriceWad) internal {
        uint256 previousSharePriceWad = sharePriceWad;
        uint256 previousSettledShareAssets = settledShareAssets;

        sharePriceWad = newSharePriceWad;
        uint256 newSettledShareAssets = _sharesToAssetValue(settledShareBalance);
        settledShareAssets = newSettledShareAssets;

        emit NavSynced(previousSharePriceWad, newSharePriceWad, previousSettledShareAssets, newSettledShareAssets);
    }

    /// @dev Applies the current validated price when the operation touches an existing or incoming share exposure.
    ///      Fixed-value cash and pending-create-only states remain operable during a NAV-feed outage.
    function _checkpointCurrentNavIfNeeded(uint256 incomingShares) internal returns (uint256 currentPriceWad) {
        if (settledShareBalance + pendingRedeemShares + incomingShares == 0) return sharePriceWad;
        currentPriceWad = _currentSharePriceWad();
        if (currentPriceWad != sharePriceWad) _checkpointNav(currentPriceWad);
    }

    function _hasLiveSharePrice() internal view returns (bool) {
        try this.currentSharePriceWad() returns (uint256) {
            return true;
        } catch {
            return false;
        }
    }

    function _currentSharePriceWad() internal view returns (uint256) {
        return _readSharePriceWad(navFeed, navFeedDecimals, maxNavStaleness, minSharePriceWad, maxSharePriceWad);
    }

    function _readSharePriceWad(
        address navFeed_,
        uint8 navDecimals,
        uint256 navStaleness,
        uint256 minPriceWad,
        uint256 maxPriceWad
    ) internal view returns (uint256 priceWad) {
        priceWad = _readFeedWad(navFeed_, navDecimals, navStaleness);
        if (priceWad < minPriceWad || priceWad > maxPriceWad) revert SharePriceOutOfBounds();
    }

    function _readFeedWad(address feed, uint8 decimals_, uint256 maxStaleness) internal view returns (uint256) {
        (uint80 roundId, int256 answer,, uint256 updatedAt, uint80 answeredInRound) =
            AggregatorV3Interface(feed).latestRoundData();
        if (roundId == 0 || answer <= 0 || updatedAt == 0 || updatedAt > block.timestamp || answeredInRound < roundId) {
            revert InvalidOracleRound();
        }
        if (block.timestamp - updatedAt > maxStaleness) revert StaleOracleRound();
        // Casting is safe because the round validation above requires `answer > 0`.
        // forge-lint: disable-next-line(unsafe-typecast)
        uint256 normalizedAnswer = FixedPointMathLib.mulDiv(uint256(answer), _WAD, _pow10(decimals_));
        if (normalizedAnswer == 0) revert InvalidOracleRound();
        return normalizedAnswer;
    }

    function _readFeedDecimals(address feed) internal view returns (uint8 decimals_) {
        try AggregatorV3Interface(feed).decimals() returns (uint8 value) {
            decimals_ = value;
        } catch {
            revert InvalidNavOracleConfig();
        }
        if (decimals_ > _MAX_SUPPORTED_FEED_DECIMALS) revert InvalidNavOracleConfig();
    }

    /// @dev Reads token decimals for share/asset unit normalization.
    function _readTokenDecimals(address token) internal view returns (uint8 tokenDecimals) {
        try IERC20Metadata(token).decimals() returns (uint8 decimals_) {
            tokenDecimals = decimals_;
        } catch {
            revert InvalidTokenDecimals();
        }
    }

    /// @dev Returns the share-to-asset scale implied by the token decimal difference.
    function _shareToAssetScale(uint8 assetDecimals, uint8 shareDecimals) internal pure returns (uint256, bool) {
        if (shareDecimals >= assetDecimals) {
            return (_pow10(shareDecimals - assetDecimals), true);
        }
        return (_pow10(assetDecimals - shareDecimals), false);
    }

    /// @dev Small helper for decimal scale construction.
    function _pow10(uint8 exponent) internal pure returns (uint256 result) {
        result = 1;
        for (uint8 i = 0; i < exponent; ++i) {
            result *= 10;
        }
    }

    /// @dev Accepts `observedValue` within `roundingTolerance` of `expectedValue`, or over-delivery up to
    ///      `maxSettlementSurplusBps`, returning that surplus so it is released through the drip.
    function _requireSettlementValue(uint256 observedValue, uint256 expectedValue, uint256 roundingTolerance)
        internal
        view
        returns (uint256 surplus)
    {
        if (observedValue <= expectedValue) {
            if (expectedValue - observedValue > roundingTolerance) revert SettlementValueMismatch();
            return 0;
        }
        surplus = observedValue - expectedValue;
        if (surplus <= roundingTolerance) return 0;
        if (surplus > FixedPointMathLib.mulDiv(expectedValue, maxSettlementSurplusBps, _BPS)) {
            revert SettlementValueMismatch();
        }
    }

    /// @dev Maximum integer gap introduced by share issuance and valuation rounding at the checkpointed price.
    ///      Cash-only create settlements remain exact. If share decimals exceed asset decimals, one effective unit is
    ///      the number of share atoms required to change the normalized asset amount by one; otherwise it is one atom.
    ///      An integer-valued effective unit can miss by at most one less than that value. For a fractional value, the
    ///      venue's share-issuance floor and this adapter's asset-valuation floor can compound, requiring the full
    ///      ceiling of one effective unit.
    function _createSettlementRoundingTolerance(uint256 shareAmount) internal view returns (uint256) {
        if (shareAmount == 0) return 0;
        uint256 normalizedAssetIncrement = _SHARE_TO_ASSET_DIVIDES ? 1 : _SHARE_TO_ASSET_SCALE_FACTOR;
        uint256 maximumValueIncrement = FixedPointMathLib.mulDivUp(normalizedAssetIncrement, sharePriceWad, _WAD);
        if (mulmod(normalizedAssetIncrement, sharePriceWad, _WAD) != 0) return maximumValueIncrement;
        return maximumValueIncrement - 1;
    }

    /// @dev Settlement absorption and deficit booking are only allowed while the external gate is closed.
    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 _requireOwner(address account) internal view {
        if (account != IVaultV2(PARENT_VAULT).owner()) revert NotAuthorized();
    }

    function _requireAllocatorOperatorOrOwner() internal view {
        if (!_isAllocatorOperatorOrOwner(msg.sender)) 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);
    }

    function _isAllocatorOperatorOrOwner(address account) internal view returns (bool) {
        return account == operator || _isAllocatorOrOwner(account);
    }
}

lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.20;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be
     * reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}

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

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

/// @title IERC20Metadata
/// @notice Minimal ERC20 metadata interface used for decimal normalization.
interface IERC20Metadata {
    /// @notice Returns the token decimals.
    /// @return tokenDecimals The number of decimals used to display balances.
    function decimals() external view returns (uint8 tokenDecimals);
}

src/oracles/interfaces/AggregatorV3Interface.sol

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

/// @title AggregatorV3Interface
/// @notice Minimal Chainlink-compatible price feed interface used by Lotus oracle wrappers.
/// @dev Mirrors
/// https://github.com/smartcontractkit/chainlink/blob/master/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol
interface AggregatorV3Interface {
    /// @notice Returns the number of decimals used by feed answers.
    /// @return The feed answer decimals.
    function decimals() external view returns (uint8);

    /// @notice Returns the human-readable feed description.
    /// @return The feed description string.
    function description() external view returns (string memory);

    /// @notice Returns the feed contract version.
    /// @return The feed version.
    function version() external view returns (uint256);

    /// @notice Returns data for a specific round.
    /// @param _roundId The round id to query.
    /// @return roundId The returned round id.
    /// @return answer The answer for the round.
    /// @return startedAt The timestamp when the round started.
    /// @return updatedAt The timestamp when the round answer was updated.
    /// @return answeredInRound The round id in which the answer was computed.
    function getRoundData(uint80 _roundId)
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

    /// @notice Returns data for the latest round.
    /// @return roundId The latest round id.
    /// @return answer The latest answer.
    /// @return startedAt The timestamp when the latest round started.
    /// @return updatedAt The timestamp when the latest answer was updated.
    /// @return answeredInRound The round id in which the latest answer was computed.
    function latestRoundData()
        external
        view
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}

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/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);
}

src/vault-v2/interfaces/IWGTXXAdapter.sol

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

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

/// @title IWGTXXAdapter
/// @notice Manual-allocation Vault V2 adapter for async WGTXX settlement flows.
/// @dev This adapter is designed for async create / redeem rails and must be registered with
/// `vault.addAdapter(adapter)`, not `vault.setLiquidityAdapterAndData(...)`. Vault V2 liquidity routing uses
/// `deposit`/`mint`/`withdraw`/`redeem` selectors, and this adapter intentionally rejects those paths. Pending creates
/// remain included at assets sent; pending redeem shares remain included at live oracle value until the operator
/// reconciles the settlement leg. Request IDs are single-use across both flows.
interface IWGTXXAdapter is IAdapter {
    /* STRUCTS */

    /// @notice Chainlink-compatible NAV feed and validation bounds used to price one WTGXX share in USDC.
    /// @dev The NAV/USD answer is normalized to WAD and used directly as USDC value. This assumes the parent vault's
    ///      settlement asset is USDC and the venue settles one USD of fund value for one USDC.
    struct NavOracleConfig {
        address navFeed;
        uint256 maxNavStaleness;
        uint256 minSharePriceWad;
        uint256 maxSharePriceWad;
    }

    /// @notice Pending create request value preserved in NAV until settlement resolves.
    struct PendingCreateRequest {
        /// @notice Asset value sent out for an async create request.
        uint256 assets;
    }

    /// @notice Pending redeem request whose share exposure remains marked to the live NAV until resolution.
    struct PendingRedeemRequest {
        /// @notice WGTXX shares sent out for an async redeem request.
        uint256 shares;
    }

    /// @notice Loss-side operation executed through a zero-asset parent-vault deallocation.
    enum LossType {
        ObservedDeficit,
        Create,
        Redeem
    }

    /// @notice Encoded loss booking that the parent vault applies atomically with the returned allocation delta.
    /// @dev For `ObservedDeficit`, `shareAmount` and `assetAmount` are the requested observed decreases. For `Create`
    ///      and `Redeem`, they are the returned shares and claimable settlement assets used to resolve the request.
    struct LossBooking {
        LossType lossType;
        bytes32 id;
        uint256 shareAmount;
        uint256 assetAmount;
    }

    /* EVENTS */

    /// @notice Emitted when WisdomTree create and redeem destination addresses are updated.
    /// @param createDepositAddress The destination for create funding.
    /// @param redeemDepositAddress The destination for redeem shares.
    event SetSettlementAddresses(address indexed createDepositAddress, address indexed redeemDepositAddress);

    /// @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 distribution booking changes.
    /// @param required Whether settlement 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 operator changes.
    /// @param newOperator The new operator address.
    event SetOperator(address indexed newOperator);

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

    /// @notice Emitted when the owner changes the accepted settlement over-delivery bound.
    /// @param newBps The new bound in bps of the expected settlement value.
    event SetMaxSettlementSurplusBps(uint256 newBps);

    /// @notice Emitted when the owner replaces the NAV oracle configuration.
    /// @param navFeed Chainlink-compatible WTGXX NAV / USD feed.
    /// @param maxNavStaleness Maximum permitted WTGXX NAV feed age.
    /// @param minSharePriceWad Minimum accepted WTGXX / USDC value in WAD precision.
    /// @param maxSharePriceWad Maximum accepted WTGXX / USDC value in WAD precision.
    event SetNavOracleConfig(
        address indexed navFeed, uint256 maxNavStaleness, uint256 minSharePriceWad, uint256 maxSharePriceWad
    );

    /// @notice Emitted when the current feed value is checkpointed into settled-share accounting.
    /// @param previousSharePriceWad Previous WTGXX / USDC checkpoint in WAD precision.
    /// @param newSharePriceWad New WTGXX / USDC checkpoint in WAD precision.
    /// @param previousSettledShareAssets Settled-share value before repricing.
    /// @param newSettledShareAssets Settled-share value after repricing.
    event NavSynced(
        uint256 previousSharePriceWad,
        uint256 newSharePriceWad,
        uint256 previousSettledShareAssets,
        uint256 newSettledShareAssets
    );

    /// @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 out for an async create request.
    /// @param requestId The single-use request id.
    /// @param assets The asset amount sent to the create destination.
    event CreateRequested(bytes32 indexed requestId, uint256 assets);

    /// @notice Emitted when claimable assets are deallocated to the parent vault.
    /// @param assets The deallocated asset amount.
    /// @param claimableAssetsAfter The claimable asset balance after deallocation.
    event Deallocated(uint256 assets, uint256 claimableAssetsAfter);

    /// @notice Emitted when a create request is settled entirely in WGTXX shares.
    /// @param requestId The settled request id.
    /// @param sharesReceived The WGTXX shares received.
    /// @param assetValue The asset-equivalent value assigned to the received shares.
    event CreateSettled(bytes32 indexed requestId, uint256 sharesReceived, uint256 assetValue);

    /// @notice Emitted when a create request is resolved within the permitted settlement rounding bound.
    /// @param requestId The resolved request id.
    /// @param sharesReceived The WGTXX shares received.
    /// @param shareAssetValue The asset-equivalent value of the received shares.
    /// @param claimableAssetIncrease The claimable asset amount received with the settlement.
    event CreateResolved(
        bytes32 indexed requestId, uint256 sharesReceived, uint256 shareAssetValue, uint256 claimableAssetIncrease
    );

    /// @notice Emitted when the owner resolves a create request with an observed shortfall.
    /// @param requestId The resolved request id.
    /// @param sharesReceived The WGTXX shares received.
    /// @param shareAssetValue The asset-equivalent value of the received shares.
    /// @param claimableAssetIncrease The claimable asset amount received with the settlement.
    /// @param shortfallAssetValue The asset shortfall written down.
    event CreateLossResolved(
        bytes32 indexed requestId,
        uint256 sharesReceived,
        uint256 shareAssetValue,
        uint256 claimableAssetIncrease,
        uint256 shortfallAssetValue
    );

    /// @notice Emitted when WGTXX shares are sent out for an async redeem request.
    /// @param requestId The single-use request id.
    /// @param shares The WGTXX shares sent to the redeem destination.
    /// @param assetValue The request-time oracle value moved from settled to pending share exposure.
    event RedeemRequested(bytes32 indexed requestId, uint256 shares, uint256 assetValue);

    /// @notice Emitted when a redeem request is settled entirely in assets.
    /// @param requestId The settled request id.
    /// @param assetsReceived The asset amount received.
    event RedeemSettled(bytes32 indexed requestId, uint256 assetsReceived);

    /// @notice Emitted when a redeem request is resolved with exact aggregate value conservation.
    /// @param requestId The resolved request id.
    /// @param sharesReceived The WGTXX shares returned, if any.
    /// @param shareAssetValue The asset-equivalent value of returned shares.
    /// @param claimableAssetIncrease The claimable asset amount received with the settlement.
    event RedeemResolved(
        bytes32 indexed requestId, uint256 sharesReceived, uint256 shareAssetValue, uint256 claimableAssetIncrease
    );

    /// @notice Emitted when the owner resolves a redeem request with an observed shortfall.
    /// @param requestId The resolved request id.
    /// @param sharesReceived The WGTXX shares returned, if any.
    /// @param shareAssetValue The asset-equivalent value of returned shares.
    /// @param claimableAssetIncrease The claimable asset amount received with the settlement.
    /// @param shortfallAssetValue The asset shortfall written down.
    event RedeemLossResolved(
        bytes32 indexed requestId,
        uint256 sharesReceived,
        uint256 shareAssetValue,
        uint256 claimableAssetIncrease,
        uint256 shortfallAssetValue
    );

    /// @notice Emitted when observed inbound settlement not tied to a request is booked.
    /// @param settlementId The single-use settlement id.
    /// @param sharesReceived The WGTXX shares received.
    /// @param assetValue The asset-equivalent value assigned to the received shares.
    /// @param claimableAssetIncrease The claimable asset amount received with the settlement.
    event SettlementRecorded(
        bytes32 indexed settlementId, uint256 sharesReceived, uint256 assetValue, uint256 claimableAssetIncrease
    );

    /// @notice Emitted when an observed external deficit is booked.
    /// @param deficitId The single-use deficit id.
    /// @param shareBalanceDecrease The share balance decrease written down.
    /// @param shareAssetValueDecrease The asset-equivalent share value decrease written down.
    /// @param claimableAssetDecrease The claimable asset decrease written down.
    event DeficitRecorded(
        bytes32 indexed deficitId,
        uint256 shareBalanceDecrease,
        uint256 shareAssetValueDecrease,
        uint256 claimableAssetDecrease
    );

    /* 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 Asset or share token decimals cannot be read.
    error InvalidTokenDecimals();
    /// @notice Vault V2 liquidity-routing allocate selector used.
    error ManualAllocateOnly();
    /// @notice Vault V2 liquidity-routing deallocate selector used.
    error ManualDeallocateOnly();
    /// @notice A required amount or recoverable booked exposure is zero.
    error ZeroAmount();
    /// @notice Settlement value falls short of the expectation beyond rounding, or exceeds the surplus bound.
    error SettlementValueMismatch();
    /// @notice Settlement surplus bound exceeds the hard cap.
    error InvalidSettlementSurplusBps();
    /// @notice Owner-only loss path used without an observed shortfall.
    error LossResolutionNotRequired();
    /// @notice Create or redeem request id has already been used.
    error RequestAlreadyExists();
    /// @notice Settlement id has already been used.
    error SettlementAlreadyRecorded();
    /// @notice Request is unknown or already resolved.
    error UnknownRequest();
    /// @notice Redeem request exceeds settled WGTXX shares.
    error InsufficientSettledShares();
    /// @notice Deallocation exceeds claimable settled assets or the adapter value already recognized in NAV.
    error InsufficientClaimableAssets();
    /// @notice Create or redeem flow requires a configured destination address.
    error SettlementAddressNotSet();
    /// @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 Generic settlement booking is blocked until all request-specific settlements are resolved.
    error PendingRequestsOutstanding();
    /// @notice Attempted to skim the managed asset or WGTXX share token.
    error CannotSkimManagedToken();
    /// @notice Deficit id has already been used.
    error DeficitAlreadyRecorded();
    /// @notice Requested deficit booking exceeds the currently observed loss.
    error DeficitExceedsObservedLoss();
    /// @notice Oracle configuration contains a zero address, zero or above-three-day staleness, or unsupported feed decimals.
    error InvalidNavOracleConfig();
    /// @notice Share price band does not straddle par within the allowed minimum and maximum deviation.
    error InvalidSharePriceBand();
    /// @notice A feed returned a non-positive, incomplete, zero-timestamp, or future-dated round.
    error InvalidOracleRound();
    /// @notice A feed's latest round is older than its configured staleness bound.
    error StaleOracleRound();
    /// @notice The WTGXX NAV price is outside the configured sanity band.
    error SharePriceOutOfBounds();
    /// @notice Zero-asset allocation sync is only available while the parent allocation is zero.
    error AllocationAlreadyNonZero();
    /// @notice Create assets contain precision that cannot be represented by one share atom at par.
    error UnrepresentableCreateAmount();
    /// @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 Manually allocates assets to a new async create or restores a zero parent allocation to booked exposure.
    /// @dev Only callable by the parent vault via `vault.allocate()`, with `selector == IVaultV2.allocate.selector` and
    /// a vault allocator as `sender`. For `assets > 0`, `data` must encode a non-zero request id and the assets
    /// start a new async create. If the share token has fewer decimals than the asset, `assets` must be an exact multiple
    /// of one share atom's par asset-unit scale; rejecting unrepresentable dust prevents a correct venue fill from
    /// leaving the request unresolved. For `assets == 0`, `data` must be empty, the parent allocation must be zero, and
    /// booked exposure must be positive; the returned delta restores Vault V2's ledger without moving funds after a
    /// complete write-down followed by a new settlement. Recovery returns the full unfloored, drip-inclusive exposure,
    /// requires a valid oracle when share exposure exists, and needs enough absolute and relative cap headroom for the
    /// complete amount. This adapter intentionally rejects liquidity-routing `deposit` / `mint` selectors and must not
    /// be installed as the liquidity adapter.
    /// @param data ABI-encoded `bytes32 requestId`, or empty for zero-allocation recovery sync.
    /// @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 the allocator check.
    /// @return ids Array containing this adapter's cap-tracking id.
    /// @return change Positive change in pending create assets or the zero-allocation recovery delta.
    function allocate(bytes calldata data, uint256 assets, bytes4 selector, address sender)
        external
        override
        returns (bytes32[] memory ids, int256 change);

    /// @notice Manually deallocates claimable assets, synchronizes booked exposure, or atomically books a loss.
    /// @dev Only callable by the parent vault via `vault.deallocate()`. For `assets > 0`, assets must already be
    /// settled back to this adapter, marked claimable, and recognized in `realAssets()`. For `assets == 0`, empty
    /// `data` synchronizes drip-inclusive booked exposure, while `abi.encode(LossBooking)` executes the selected
    /// loss-side state transition and returns the complete post-booking allocation delta. Vault V2 applies that delta
    /// in the same transaction, preventing its cap ledger from remaining stale. `ObservedDeficit` requires the original
    /// vault caller to be the configured operator or owner; `Create` and `Redeem` remain owner-only. Because Vault V2
    /// itself admits only allocators or sentinels to `deallocate`, those operational accounts must also hold an
    /// appropriate vault role. Sentinel should be used instead of allocator for loss-only accounts because it does not
    /// confer allocation, liquidity-adapter, or max-rate powers. Sentinel still permits deallocation, pending-action
    /// revocation, and absolute/relative cap reductions, so the account must be trusted with those powers.
    /// Pulls and empty-data syncs require an allocator or sentinel. Liquidity-routing `withdraw` / `redeem`
    /// selectors are rejected.
    /// @param data Empty for a pure sync/manual pull, or ABI-encoded `LossBooking` when `assets == 0`.
    /// @param assets Claimable 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 change for claimable-asset withdrawals or the full signed booked-exposure delta for
    /// zero-asset sync/loss calls.
    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 Pending creates remain fixed at assets sent. Settled and pending-redeem shares are marked using the
    ///      current validated oracle price, so an ordinary feed update does not require a prior state checkpoint.
    ///      Locally-held settled shares and claimable assets are capped by their observed balances immediately, while
    ///      externally-held pending legs remain valued. An observed custody loss consumes unreleased drip before it
    ///      reduces recognized NAV, matching the later `ObservedDeficit` loss-booking state transition.
    /// @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 used for create funding, redeem proceeds, and cash distributions.
    function ASSET() external view returns (address);
    /// @return The WGTXX share token held after create settlement and sent out during redeem requests.
    function SHARE_TOKEN() external view returns (address);
    /// @return The vault allocation identifier for this adapter.
    function ADAPTER_ID() external view returns (bytes32);

    /// @return Chainlink-compatible feed reporting WTGXX NAV in USD.
    function navFeed() external view returns (address);
    /// @return Maximum permitted age of the WTGXX NAV round.
    function maxNavStaleness() external view returns (uint256);
    /// @return Minimum accepted WTGXX / USDC price in WAD precision.
    function minSharePriceWad() external view returns (uint256);
    /// @return Maximum accepted WTGXX / USDC price in WAD precision.
    function maxSharePriceWad() external view returns (uint256);
    /// @return Feed decimals cached for WTGXX NAV normalization.
    function navFeedDecimals() external view returns (uint8);
    /// @return Last WTGXX / USDC price checkpoint applied to accounting, in WAD precision.
    function sharePriceWad() external view returns (uint256);
    /// @return Maximum request settlement over-delivery accepted in one call, in bps of the expected value.
    function maxSettlementSurplusBps() external view returns (uint256);

    /// @return The WisdomTree destination wallet that receives vault asset for async create requests.
    function createDepositAddress() external view returns (address);
    /// @return The WisdomTree destination wallet that receives WGTXX for async redeem requests.
    function redeemDepositAddress() external view returns (address);
    /// @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 `ObservedDeficit` loss booking requires the settlement gate to be closed.
    function deficitGateRequired() external view returns (bool);
    /// @return The operational role allowed to reconcile observed settlement and initiate redeem flows.
    function operator() external view returns (address);
    /// @return Reconciled WGTXX balance held for the vault's productive position.
    function settledShareBalance() external view returns (uint256);
    /// @return Oracle-valued asset equivalent of `settledShareBalance` at the latest checkpoint.
    function settledShareAssets() external view returns (uint256);
    /// @return Asset amount sent out for create requests and still counted in NAV pending settlement.
    function pendingCreateAssets() external view returns (uint256);
    /// @return WGTXX shares sent out for redeem requests and awaiting async resolution.
    function pendingRedeemShares() external view returns (uint256);
    /// @return Current validated-oracle value of all pending redeem shares still counted in NAV.
    function pendingRedeemAssets() external view returns (uint256);
    /// @return Observed asset already booked and available for the vault to pull back.
    function claimableAssets() external view returns (uint256);
    /// @return The time window over which newly-booked dividends are released into `realAssets()`. Zero until
    ///         first configured.
    function dividendInterval() external view returns (uint256);
    /// @return Total dividend 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 dividend'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 tracked base buckets so a freshly-booked dividend 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 The current WGTXX share balance held by the adapter.
    function observedShareBalance() external view returns (uint256);
    /// @return The current settlement asset balance held by the adapter.
    function observedAssetBalance() external view returns (uint256);
    /// @return Observed but unbooked WGTXX shares.
    function unaccountedShareBalance() external view returns (uint256);
    /// @return Observed but unbooked settlement assets.
    function unaccountedAssetBalance() external view returns (uint256);
    /// @return Booked settled shares not currently observed on-chain.
    function observedShareDeficit() external view returns (uint256);
    /// @return Booked claimable assets not currently observed on-chain.
    function observedAssetDeficit() external view returns (uint256);
    /// @notice Returns whether `requestId` has ever been consumed by this adapter.
    /// @dev Request IDs are not reusable after either create or redeem initiation.
    /// @param requestId The request id to query.
    /// @return Whether `requestId` has already been used.
    function requestUsed(bytes32 requestId) external view returns (bool);

    /// @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);

    /// @notice Returns the currently pending create request state, if any.
    /// @param requestId The request id to query.
    /// @return assets The pending create asset value.
    /// @return isPending Whether the request is pending.
    function pendingCreates(bytes32 requestId) external view returns (uint256 assets, bool isPending);

    /// @notice Returns the currently pending redeem request state, if any.
    /// @param requestId The request id to query.
    /// @return shares The pending redeem share amount.
    /// @return assetValue The request's current validated-oracle share value if it were resolved next. Individual
    /// request values are marginal and need not sum to the aggregate `pendingRedeemAssets()` value due to rounding.
    /// @return isPending Whether the request is pending.
    function pendingRedeems(bytes32 requestId)
        external
        view
        returns (uint256 shares, uint256 assetValue, bool isPending);
    /// @return Array containing this adapter's cap-tracking id.
    function ids() external view returns (bytes32[] memory);

    /* WRITE FUNCTIONS */

    /// @notice Updates the WisdomTree create and redeem destination addresses.
    /// @dev Setting either address to zero disables that flow until a non-zero address is restored.
    /// @param newCreateDepositAddress The destination for create funding.
    /// @param newRedeemDepositAddress The destination for redeem shares.
    function setSettlementAddresses(address newCreateDepositAddress, address newRedeemDepositAddress) external;

    /// @notice Updates the gate used when settlement reconciliation or deficit booking requires a closed window.
    /// @dev Setting the gate to zero disables settlement reconciliation and deficit booking 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 `ObservedDeficit` loss booking 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 dividend is linearly released into
    ///         `realAssets()`.
    /// @dev Owner-only. Set to match the dividend cadence (e.g. 30 days for monthly WGTXX
    ///      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 dividend drip interval.
    function setDividendInterval(uint256 newInterval) external;

    /// @notice Sets the maximum over-delivery accepted when resolving a create or redeem request in one call.
    /// @dev Owner-only. Capped at 1_000 bps. Accepted surplus is booked with the settlement and released through
    ///      the dividend drip. Zero keeps the strict envelope (rounding gap on creates, exact on redeems).
    /// @param newBps Bound in bps of the request's expected settlement value.
    function setMaxSettlementSurplusBps(uint256 newBps) external;

    /// @notice Replaces the NAV feed and its validation parameters, then atomically checkpoints settled shares.
    /// @dev Owner-only. The settlement gate must be closed unless the current live read fails, so a broken feed can be
    ///      replaced in one call while the window is open (window-open pricing already reverts). Settled and
    ///      pending-redeem share exposure is always valued from the newly configured live feed. It must expose a fresh,
    ///      valid `AggregatorV3Interface` round whose normalized NAV price is inside the band.
    /// @param newConfig New NAV oracle address, staleness bound, and WAD-denominated sanity band.
    function setNavOracleConfig(NavOracleConfig calldata newConfig) external;

    /// @notice Checkpoints the current WTGXX NAV / USDC price into settled-share accounting.
    /// @dev Permissionless, but only while the settlement gate is closed. This updates the stored checkpoint and
    ///      `settledShareAssets`; it does not change live `realAssets()` or consume dividend drip. The parent vault
    ///      allocation should be synchronized before reopening the gate.
    /// @return newSharePriceWad The new WTGXX / USDC checkpoint in WAD precision.
    function syncNav() external returns (uint256 newSharePriceWad);

    /// @notice Returns the currently validated WTGXX NAV / USDC price without changing accounting.
    /// @return currentSharePriceWad Current NAV price in WAD precision.
    function currentSharePriceWad() external view returns (uint256 currentSharePriceWad);

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

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

    /// @notice Initiates an async redeem request by sending WGTXX shares to the redeem destination.
    /// @dev Operator or allocator/owner only. This is a custom operational method, not a Vault V2 deallocation path.
    /// The adapter moves the shares from settled balance to pending-redeem exposure. Both buckets are marked at the
    /// same live oracle price, keeping NAV flat while allowing an impairment to flow through during the async request.
    /// @param requestId Single-use request id.
    /// @param shares WGTXX shares to redeem.
    /// @return assetValueRemoved Oracle-valued amount moved from settled shares to pending redeem assets.
    function requestRedeem(bytes32 requestId, uint256 shares) external returns (uint256 assetValueRemoved);

    /// @notice Settles a successful create request into returned WTGXX at the current validated oracle price.
    /// @dev This is a convenience wrapper around `resolveCreate(...)` for the common all-shares success path.
    ///      Returned WGTXX is normalized into asset units using the share-token and asset decimal difference.
    ///      Reverts unless the booked settlement matches the pending value within the maximum conversion rounding gap
    ///      implied by one effective WGTXX share unit at the current price, or over-delivers by at most
    ///      `maxSettlementSurplusBps`. The settlement gate must already be closed.
    /// @param requestId The create request id.
    /// @param sharesReceived Returned WGTXX shares to settle.
    function settleCreate(bytes32 requestId, uint256 sharesReceived) external;

    /// @notice Resolves a pending create request for success, cancellation, or value-matched mixed settlement.
    /// @dev `sharesReceived` represents returned WGTXX booked as settled position at the current validated oracle price.
    ///      `claimableAssetIncrease` represents returned cash booked as claimable assets for later
    ///      vault pullback. Reverts unless the booked settlement matches the pending request value, allowing only the
    ///      maximum conversion rounding gap when a WGTXX share leg is present, or over-delivery of at most
    ///      `maxSettlementSurplusBps`. The settlement gate must already be closed.
    /// @param requestId The create request id.
    /// @param sharesReceived Returned WGTXX shares to book.
    /// @param claimableAssetIncrease Returned settlement assets to book.
    function resolveCreate(bytes32 requestId, uint256 sharesReceived, uint256 claimableAssetIncrease) external;

    /// @notice Settles a successful redeem request into returned cash.
    /// @dev This is a convenience wrapper around `resolveRedeem(...)` for the common all-cash success path.
    ///      Reverts unless the booked cash settlement exactly matches the pending redeem's current oracle value or
    ///      over-delivers by at most `maxSettlementSurplusBps`.
    ///      The settlement gate must already be closed.
    /// @param requestId The redeem request id.
    /// @param assetsReceived Returned settlement assets to book.
    function settleRedeem(bytes32 requestId, uint256 assetsReceived) external;

    /// @notice Resolves a pending redeem request for success, cancellation, or value-matched mixed settlement.
    /// @dev `sharesReceived` represents WGTXX returned to the adapter and restored to settled position at the
    ///      current validated oracle price. `claimableAssetIncrease` represents returned cash booked as claimable assets
    ///      for later vault pullback. Returned shares and the removed request are valued from the same post-removal
    ///      aggregate share base, so the booked settlement must exactly preserve integer-valued exposure unless it
    ///      over-delivers by at most `maxSettlementSurplusBps`. The settlement gate must already be closed.
    /// @param requestId The redeem request id.
    /// @param sharesReceived Returned WGTXX shares to book.
    /// @param claimableAssetIncrease Returned settlement assets to book.
    function resolveRedeem(bytes32 requestId, uint256 sharesReceived, uint256 claimableAssetIncrease) external;

    /// @notice Books observed inbound settlement that is not tied to a specific async request.
    /// @dev `settlementId` is a single-use operator reference to prevent duplicate booking of the same offchain event.
    ///      This is intended for share distributions, cash distributions, or manual reconciliation adjustments.
    ///      Reverts while any create or redeem request is pending because observed balances cannot prove which request
    ///      produced them. Request-specific settlement must be reconciled first; genuine surplus remains unaccounted
    ///      and can be booked with this function afterward.
    ///      Share distributions are valued at the checkpointed oracle price. Stacked value-bearing distributions blend
    ///      the active carry's remaining duration with the configured interval using value-weighted average math, so a
    ///      small distribution cannot restart the whole carry; a zero-valued share booking does not re-time the drip.
    ///      Reverts with `DividendIntervalNotConfigured` while `dividendInterval == 0` (the deployment default).
    ///      A closed gate is required when `settlementGateRequired == true` or either local custody leg has an
    ///      observable deficit. With no observed deficit and `settlementGateRequired == false`, the gate can be skipped
    ///      because the booked value is smoothed into `realAssets()`. When a deficit exists, operations should book it before the cross-leg settlement while the
    ///      gate is closed, preserving event ordering and preventing an unsmoothed NAV step.
    /// @param settlementId Single-use settlement id.
    /// @param sharesReceived Unrequested WGTXX shares to book.
    /// @param claimableAssetIncrease Unrequested settlement assets to book.
    function recordSettlement(bytes32 settlementId, uint256 sharesReceived, uint256 claimableAssetIncrease) external;
}
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.