Skip to content
Verified contractPartialBUSL-1.1

StakeWiseV3ExitQueueAssistedBalanceAdapter

Address0x662f43d46b10d57c5f1970684bd0e35cd3e5dfa7
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.34

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.34+commit.80d5c536
Language
solidity
Optimization
Yes, 200 runs
EVM version
cancun
Via IR
yes
License
BUSL-1.1
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,341,850
Creation transaction
0x3f7a6372fd…52fbb4868a
Libraries
src/nav/NAVRegistryLib.sol:NAVRegistryLib0x3d53…75934dsrc/prices/PriceFeedLib.sol:PriceFeedLib0x0f91…fafcf2

src/balances/AssistedBalanceAdapters/StakeWiseV3ExitQueueAssistedBalanceAdapter.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";

import {AssistedCoordCache} from "./AssistedCoordCache.sol";
import {IPositionDescribable} from "src/balances/IPositionDescribable.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {AddressCheckLib} from "src/utils/AddressCheckLib.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
import {ProtocolIds} from "src/utils/ProtocolIds.sol";

/// @title StakeWise V3 Exit-Queue Assisted Balance Adapter (coordinate-cached, assistant-fed)
/// @author KPK
/// @notice Reports the in-flight assets owed to an account in StakeWise V3's exit queue, valued entirely from live
///         on-chain reads. The exit position's coordinate is a **tuple** `(vault, positionTicket, timestamp)` — the
///         `StakeWiseV3ExitQueueAssistant` a depositor Safe delegatecalls records it here (adapter sees `msg.sender = Safe`),
///         in the same tx it enters/claims the queue. The exit position is owned on-chain by that same Safe
///         (`receiver = the Safe`), so the valuation (keyed on `receiver = account`) needs no extra bookkeeping.
/// @dev Assistant-fed member ([ADR 0018](../../../docs/decisions/0018-assistant-fed-assisted-balance-adapters.md)),
///      extending {AssistedCoordCache} (tuple coordinate, not a bare uint256). The cache stores **only coordinates,
///      never amounts**; every read values live against `receiver = account` (a tuple that isn't the account's resolves
///      to zero owed and is dropped) → under-report only. StakeWise exit positions have no `ownerOf`, so the ownership
///      proxy is `calculateExitedAssets(account, …) > 0`. Emits up to two `Supplied` legs per cached position — a
///      claimable (`isLocked=false`) and a locked/pending (`isLocked=true`) — sharing `positionId = abi.encode(vault)`,
///      the ticket in `positionInstanceId`. Denominated in the chain's staking asset (native ETH on mainnet).
contract StakeWiseV3ExitQueueAssistedBalanceAdapter is AssistedCoordCache, IPositionDescribable {
    /// @notice Hard cap on cached exit positions per account (read-loop gas bound).
    uint256 public constant MAX_POSITIONS = 256;

    bytes32 private constant PROTOCOL_BRAND = ProtocolIds.STAKEWISE;
    bytes32 private constant PROTOCOL_ID = ProtocolIds.STAKEWISE_V3;
    bytes32 private constant PROTOCOL_SUB_ID = ProtocolIds.STAKEWISE_V3_EXIT;

    /// @notice StakeWise VaultsRegistry — `vaults(address)` gates which vaults the cache accepts (write-time hygiene).
    address public immutable VAULTS_REGISTRY;

    /// @notice StakeWise's post-checkpoint claim delay in seconds (24h on V3 mainnet). The exited-but-still-delayed
    ///         portion is reported locked until the delay elapses; it does not affect the owed *amount*.
    uint256 public immutable EXIT_CLAIM_DELAY;

    /// @notice Display symbol of StakeWise's receipt/LST token (`"osETH"` mainnet). Empty ⇒ bare `["Exit Queue"]`.
    string public receiptSymbol;

    /// @param vaultsRegistry_  StakeWise VaultsRegistry. Must be a contract.
    /// @param underlyingToken_ Payout asset (native-ETH sentinel on mainnet). Must be non-zero.
    /// @param receiptSymbol_   Display symbol of StakeWise's receipt/LST token (`"osETH"` mainnet). May be empty.
    /// @param navCalculator_   NAVCalculator. Must be a contract.
    /// @param exitClaimDelay_  StakeWise's post-checkpoint claim delay in seconds (`86400` on V3 mainnet). Must be > 0.
    /// @param admin_           `DEFAULT_ADMIN_ROLE` holder (grants the keeper's `SUBMITTER_ROLE`). Must be non-zero.
    constructor(
        address vaultsRegistry_,
        address underlyingToken_,
        string memory receiptSymbol_,
        address navCalculator_,
        uint256 exitClaimDelay_,
        address admin_
    ) AssistedCoordCache(underlyingToken_, navCalculator_, admin_) {
        if (vaultsRegistry_ == address(0) || exitClaimDelay_ == 0) revert InvalidArguments();
        AddressCheckLib.requireContract(vaultsRegistry_, "VaultsRegistry");
        VAULTS_REGISTRY = vaultsRegistry_;
        receiptSymbol = receiptSymbol_;
        EXIT_CLAIM_DELAY = exitClaimDelay_;
    }

    //
    // Typed owner feed surface (msg.sender-keyed; the keeper path is in the base, ADR 0030).
    //

    /// @notice Track one of the caller's own exit positions. Idempotent. **Reverts** `InvalidCoordinate` if the vault is
    ///         not StakeWise-registered, `CoordinateNotOwned` if the tuple resolves to no live owed amount for the
    ///         caller (the on-chain ownership proxy), and `CoordinateCacheFull` past {MAX_POSITIONS}.
    function submit(address vault, uint256 positionTicket, uint256 timestamp) external {
        _submitCoord(abi.encode(vault, positionTicket, timestamp));
    }

    /// @notice Stop tracking one of the caller's own exit positions (once claimed). **Reverts** `CoordinateNotCached`
    ///         if the tuple is not tracked, and `CoordinateStillLive` if it is still owed (not yet claimed).
    function remove(address vault, uint256 positionTicket, uint256 timestamp) external {
        _removeCoord(abi.encode(vault, positionTicket, timestamp));
    }

    /// @notice Candidate exit positions currently cached for `account` (display/debug; not staleness-filtered).
    function positionsOf(address account) external view returns (ExitPosition[] memory out) {
        bytes[] memory coords = _cachedCoords(account);
        out = new ExitPosition[](coords.length);
        for (uint256 i; i < coords.length; ++i) {
            (address vault, uint256 ticket, uint256 timestamp) = abi.decode(coords[i], (address, uint256, uint256));
            out[i] = ExitPosition(vault, ticket, timestamp);
        }
    }

    /// @param vault          StakeWise V3 vault the exit position lives in.
    /// @param positionTicket Ticket returned by `enterExitQueue`.
    /// @param timestamp      Entry block's `block.timestamp` — part of the exit-request key.
    struct ExitPosition {
        address vault;
        uint256 positionTicket;
        uint256 timestamp;
    }

    /// @inheritdoc IPositionDescribable
    function protocolName() external pure returns (string memory) {
        return "StakeWise V3";
    }

    /// @inheritdoc IPositionDescribable
    /// @dev `["Exit Queue", "<receiptSymbol>"]`, or bare `["Exit Queue"]` if {receiptSymbol} is empty.
    function positionLabels(bytes calldata) external view override returns (string[] memory out) {
        if (bytes(receiptSymbol).length == 0) {
            out = new string[](1);
            out[0] = "Exit Queue";
            return out;
        }
        out = new string[](2);
        out[0] = "Exit Queue";
        out[1] = receiptSymbol;
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
        return interfaceId == type(IPositionDescribable).interfaceId || super.supportsInterface(interfaceId);
    }

    //
    // Hooks
    //

    /// @inheritdoc AssistedCoordCache
    function _maxCoords() internal pure override returns (uint256) {
        return MAX_POSITIONS;
    }

    /// @inheritdoc AssistedCoordCache
    function _maxLegsPerCoord() internal pure override returns (uint256) {
        return 2;
    }

    /// @inheritdoc AssistedCoordCache
    function _coordId(bytes memory coord) internal pure override returns (uint256 positionTicket) {
        // Decoded as raw words (not `address`), so a coordinate with dirty address bits still yields its ticket for the
        // typed `Coordinate*` errors instead of an opaque decode revert.
        (, positionTicket,) = abi.decode(coord, (uint256, uint256, uint256));
    }

    /// @inheritdoc AssistedCoordCache
    /// @dev Vault must be StakeWise-registered (else `InvalidCoordinate`) AND the tuple must resolve to a live owed
    ///      amount for `account` — the on-chain ownership proxy `calculateExitedAssets(account, …) > 0` — else
    ///      `CoordinateNotOwned`.
    function _validateCoord(address account, bytes memory coord) internal view override {
        (address vault, uint256 ticket, uint256 timestamp) = abi.decode(coord, (address, uint256, uint256));
        bool registeredVault;
        try IStakeWiseVaultsRegistry(VAULTS_REGISTRY).vaults(vault) returns (bool ok) {
            registeredVault = ok;
        } catch {
            registeredVault = false;
        }
        if (!registeredVault) revert InvalidCoordinate(account, ticket);
        (uint256 c, uint256 l) = _owedForPosition(account, vault, ticket, timestamp);
        if (c + l == 0) revert CoordinateNotOwned(account, ticket);
    }

    /// @inheritdoc AssistedCoordCache
    function _coordLength() internal pure override returns (uint256) {
        return 96;
    }

    /// @inheritdoc AssistedCoordCache
    /// @dev Dead only when `calculateExitedAssets` SUCCEEDS and reports nothing at all — StakeWise returns
    ///      `(0, 0, 0)` exactly when no request exists under `(account, timestamp, ticket)` (claimed in full, or
    ///      re-queued under a new ticket after a partial claim). Unlike {_owedForPosition}, a revert is NOT death.
    function _isDead(address account, bytes memory coord) internal view override returns (bool) {
        (address vault, uint256 ticket, uint256 timestamp) = abi.decode(coord, (address, uint256, uint256));
        IStakeWiseExitVault v = IStakeWiseExitVault(vault);
        uint256 queryIdx;
        try v.getExitQueueIndex(ticket) returns (int256 i) {
            queryIdx = i < 0 ? type(uint256).max : uint256(i);
        } catch {
            return false;
        }
        try v.calculateExitedAssets(account, ticket, timestamp, queryIdx) returns (
            uint256 leftTickets, uint256 exitedTickets, uint256 exitedAssets
        ) {
            return leftTickets == 0 && exitedTickets == 0 && exitedAssets == 0;
        } catch {
            return false;
        }
    }

    /// @inheritdoc AssistedCoordCache
    /// @dev Removable once the position is claimed/consumed — it resolves to no live owed amount for `account`.
    function _removable(address account, bytes memory coord) internal view override returns (bool) {
        (address vault, uint256 ticket, uint256 timestamp) = abi.decode(coord, (address, uint256, uint256));
        (uint256 c, uint256 l) = _owedForPosition(account, vault, ticket, timestamp);
        return c + l == 0;
    }

    /// @inheritdoc AssistedCoordCache
    /// @notice Up to two staking-asset `Supplied` legs for one cached exit position — claimable (`isLocked=false`) and
    ///         locked/pending (`isLocked=true`) — both carrying the ticket in `positionInstanceId`, sharing
    ///         `positionId = abi.encode(vault)`.
    function _valueCoord(address account, bytes memory coord, INAVCalculator.Asset memory underlying)
        internal
        view
        override
        returns (INAVCalculator.PositionBalance[] memory)
    {
        (address vault, uint256 ticket, uint256 timestamp) = abi.decode(coord, (address, uint256, uint256));
        (uint256 claimable, uint256 locked) = _owedForPosition(account, vault, ticket, timestamp);
        if (claimable + locked == 0) return new INAVCalculator.PositionBalance[](0);

        bytes memory positionId = abi.encode(vault);
        bytes32 instanceId = bytes32(ticket);
        INAVCalculator.PositionBalance[] memory tmp = new INAVCalculator.PositionBalance[](2);
        uint256 n;
        if (claimable > 0) tmp[n++] = _leg(underlying, claimable, positionId, instanceId, false);
        if (locked > 0) tmp[n++] = _leg(underlying, locked, positionId, instanceId, true);

        INAVCalculator.PositionBalance[] memory out = new INAVCalculator.PositionBalance[](n);
        for (uint256 i; i < n; ++i) {
            out[i] = tmp[i];
        }
        return out;
    }

    function _leg(
        INAVCalculator.Asset memory asset,
        uint256 amount,
        bytes memory positionId,
        bytes32 instanceId,
        bool isLocked
    ) private view returns (INAVCalculator.PositionBalance memory) {
        return INAVCalculator.PositionBalance({
            balanceAsset: asset,
            balanceAdapter: address(this),
            amount: amount,
            isDebt: false,
            protocolBrand: PROTOCOL_BRAND,
            protocolId: PROTOCOL_ID,
            protocolSubId: PROTOCOL_SUB_ID,
            positionId: positionId,
            positionKind: PositionKind.Supplied,
            isLocked: isLocked,
            positionInstanceId: instanceId
        });
    }

    /// @dev Assets owed for one exit position, split into claimable and locked portions. Both 0 if the position is not
    ///      the account's / claimed / invalid. Mirrors StakeWise's queue math; checkpointed exited assets count as
    ///      claimable only once the post-checkpoint delay has elapsed. All external reads try/catch to 0.
    function _owedForPosition(address account, address vault, uint256 positionTicket, uint256 timestamp)
        internal
        view
        returns (uint256 claimable, uint256 locked)
    {
        IStakeWiseExitVault v = IStakeWiseExitVault(vault);

        int256 idx;
        try v.getExitQueueIndex(positionTicket) returns (int256 i) {
            idx = i;
        } catch {
            return (0, 0);
        }
        uint256 queryIdx = idx < 0 ? type(uint256).max : uint256(idx);

        uint256 leftShares;
        uint256 exitedAssets;
        try v.calculateExitedAssets(account, positionTicket, timestamp, queryIdx) returns (
            uint256 leftTickets, uint256, uint256 exited
        ) {
            leftShares = leftTickets;
            exitedAssets = exited;
        } catch {
            return (0, 0);
        }

        uint256 queued;
        if (leftShares > 0) {
            try v.convertToAssets(leftShares) returns (uint256 a) {
                queued = a;
            } catch {
                return (0, 0);
            }
        }
        if (block.timestamp >= timestamp + EXIT_CLAIM_DELAY) {
            claimable = exitedAssets;
            locked = queued;
        } else {
            claimable = 0;
            locked = exitedAssets + queued;
        }
    }
}

/// @notice Minimal interface for a StakeWise V3 vault's exit-queue reads.
interface IStakeWiseExitVault {
    /// @notice Checkpoint index for a position ticket, or -1 if not yet checkpointed (fully pending).
    function getExitQueueIndex(uint256 positionTicket) external view returns (int256);

    /// @notice For the exit request keyed by `(receiver, timestamp, positionTicket)`: shares still queued, tickets that
    ///         exited, and the assets those exited tickets are worth. All zero for a tuple that is not a live request.
    function calculateExitedAssets(address receiver, uint256 positionTicket, uint256 timestamp, uint256 exitQueueIndex)
        external
        view
        returns (uint256 leftTickets, uint256 exitedTickets, uint256 exitedAssets);

    /// @notice Current asset value of `shares` vault shares.
    function convertToAssets(uint256 shares) external view returns (uint256);
}

/// @notice Minimal interface for the StakeWise VaultsRegistry.
interface IStakeWiseVaultsRegistry {
    /// @notice Whether `vault` is a StakeWise-registered vault.
    function vaults(address vault) external view returns (bool);
}

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

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

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```solidity
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```solidity
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role);
        _;
    }

    /// @inheritdoc ERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleGranted} event.
     */
    function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     *
     * May emit a {RoleRevoked} event.
     */
    function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}

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

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

pragma solidity >=0.8.4;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted to signal this.
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}

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

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

pragma solidity ^0.8.20;

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

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

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

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

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

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}

src/balances/AssistedBalanceAdapters/AssistedCoordCache.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";

import {IAssistedBalanceAdapter} from "src/balances/IAssistedBalanceAdapter.sol";
import {IBalanceAdapter} from "src/balances/IBalanceAdapter.sol";
import {RegisteredAssetLib} from "src/balances/RegisteredAssetLib.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {SUBMITTER} from "src/constants.sol";
import {AddressCheckLib} from "src/utils/AddressCheckLib.sol";
import {GasStipendLib} from "src/utils/GasStipendLib.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";

/// @notice One cached coordinate ran out of the gas the valuation fan-out forwarded it, so the account's reported
///         total is missing that coordinate — and, because the residue left to the loop cannot fund the ones after
///         it, very likely every coordinate behind it too.
/// @dev The sibling of `INAVCalculator.InstanceGasExhausted`, one family over. Reports `_coordId` — the
///      concrete adapter's human-facing tokenId / requestId / positionTicket — rather than the internal
///      `keccak256(coord)` dedup key, matching every other `Coordinate*` error in `src/errors.sol`. That hook
///      exists precisely so an operator can act on the error without reversing a hash. Deliberately declared HERE rather
///      than in `src/errors.sol`: both pinned libraries (`PriceFeedLib`, `NAVRegistryLib`) plain-import that file,
///      so adding to it would put this symbol inside both CREATE2 compilation closures for no benefit — nothing
///      outside this family raises or catches it. Keeping it file-local keeps this change provably pin-neutral.
error CoordinateGasExhausted(address adapter, uint256 coordId, uint256 stipend, uint256 consumed);

/// @title AssistedCoordCache
/// @author KPK
/// @notice The single cache base for the **assistant-fed** assisted balance-adapter family. A position
///         *coordinate* is an opaque `bytes` blob, so ONE cache serves every member regardless of coordinate shape:
///         a bare `uint256` NFT tokenId / withdrawal requestId (`abi.encode(id)`) or a richer tuple (StakeWise V3 exit
///         positions, `abi.encode(vault, positionTicket, timestamp)`). It holds the per-account coordinate-record cache
///         (blobs deduped by their keccak key) and its `msg.sender`-keyed CRUD, plus the single-underlying-asset
///         {IBalanceAdapter} getter surface and the per-coordinate fail-open valuation fan-out. The concrete adapter
///         exposes a *typed* `submit`/`remove` that `abi.encode`s its coordinate and routes to {_submitCoord}/
///         {_removeCoord}, and implements {_valueCoord} (decode + value live), {_validateCoord} (fail-loud write-time
///         hygiene), {_removable}, {_coordId}, {_maxCoords}, {_maxLegsPerCoord}.
/// @dev Two feeders. The owner path keys on `msg.sender`, so a caller can only ever touch its OWN set; the canonical
///      feeder is a {BalanceAdapterAssistant} the owner Safe delegatecalls (so `msg.sender` is the Safe). For positions
///      the owner did not open through its assistant, a {SUBMITTER_ROLE} keeper files coordinates under the account the
///      protocol says owns them ({submitFor}); anyone may drop a coordinate the protocol proves dead ({removeFor}).
///      Both run the same {_validateCoord} / ownership rules as the owner path, so the family invariant holds unchanged
///      — coordinates only, valued live, ownership re-verified per read → under-report only (ADR 0030).
///
///      **WHAT THIS FILE CANNOT SHOW YOU — the cache is COMPLETE in production, not merely conservative.** Read on its
///      own, this contract is a cache with no completeness guarantee whatsoever: anyone may `submit`
///      their own coordinates, nobody is obliged to, and the assistant is the *canonical feeder* rather than a gate. So
///      "under-report only" is the honest reading of THIS code — and it understates the deployed system. The portfolio
///      Safes' **roles-modifier permission set allows the corresponding protocol entries only through the assistant
///      contracts; the direct protocol entrypoint is not in the allow-list.** A position of these types therefore
///      cannot be active without its coordinate having been fed here. Two complementary halves: *contract level* (this
///      file) → cannot **over**-report; *roles level* (**outside this repository**) → cannot **under**-report either.
///      Enforcement is in the Safe's roles configuration, which is not part of this repo — treat this as a pointer to
///      it, not as an operational rule someone must remember. **Residual risk:** not a bypass by an operator (not
///      permitted), but a **change to the roles permission set adding a path that reaches the protocol without the
///      assistant** — after which this cache silently misses positions and nothing in this repository would detect it,
///      because every invariant above still holds. See `AssistedBalanceAdapters/README.md` §5.0 and ADRs 0015 / 0018.
///
///      Uses a `bytes[]` array + `key → idxPlus1` map for dedup and O(1) swap-pop removal. Reads isolate each
///      coordinate behind a self-`staticcall` ({valueCoordSelf}), so a revert-prone valuation (e.g. Nexus's
///      `StakingViewer.getTokens`) only drops that one coordinate, never the account's whole set.
abstract contract AssistedCoordCache is IAssistedBalanceAdapter, AccessControl {
    /// @inheritdoc IAssistedBalanceAdapter
    /// @dev Gates {submitFor}/{submitForBatch} only. The owner path, {removeFor}, {evict} and {clearAccount} stay open.
    bytes32 public constant SUBMITTER_ROLE = SUBMITTER;

    /// @notice Cache slots the keeper path can never use, so an account always keeps at least this many for its own
    ///         Assistant `submit` (beyond that, `evict` frees room). Anyone
    ///         can create a live position OWNED by a Safe; if a keeper could file those up to the full cap, the Safe's
    ///         Assistant enter path (whose `submit` is not caught) would revert until it cleared its cache (ADR 0030 S13).
    uint256 public constant OWNER_RESERVE = 32;

    /// @notice The single asset this adapter reports. Must be a registered NAV asset for {getAdapterPositions} to count
    ///         it; the balance getters report it regardless (registration-independent).
    address public immutable UNDERLYING_TOKEN;

    /// @notice NAVCalculator — used to look up the registered underlying-asset metadata when emitting positions.
    INAVCalculator public immutable NAV_CALCULATOR;

    /// @notice Cached coordinate blobs per account (the only thing the feeder supplies). Each is an `abi.encode` of the
    ///         concrete adapter's tuple.
    mapping(address account => bytes[] coords) private _coords;

    /// @dev `idxPlus1` = index of the coordinate in `_coords[account]` plus 1, keyed by `keccak256(coord)`. Zero ⇒ not
    ///      present (dedup + O(1) removal).
    mapping(address account => mapping(bytes32 key => uint256)) private _idxPlus1;

    /// @notice `id` is the concrete adapter's human-facing coordinate id ({_coordId}: a tokenId / requestId /
    ///         positionTicket) — indexed so consumers can filter, matching the legacy per-adapter events.
    event CoordSubmitted(address indexed account, uint256 indexed id);
    event CoordCleared(address indexed account, uint256 indexed id);
    event AccountCleared(address indexed account);
    /// @notice A {SUBMITTER_ROLE} keeper filed a new coordinate for `account` (emitted alongside {CoordSubmitted}, so
    ///         keeper-filed entries are attributable without a trace).
    event CoordSubmittedFor(address indexed account, uint256 indexed id, address indexed submitter);

    /// @param underlyingToken_ The reported underlying asset. Must be non-zero.
    /// @param navCalculator_   NAVCalculator. Must be a contract.
    /// @param admin_           Holder of `DEFAULT_ADMIN_ROLE` (grants/revokes {SUBMITTER_ROLE}). Must be non-zero. No
    ///                         submitter is granted here: a deploy alone never creates a live submit right.
    constructor(address underlyingToken_, address navCalculator_, address admin_) {
        if (underlyingToken_ == address(0) || navCalculator_ == address(0) || admin_ == address(0)) {
            revert InvalidArguments();
        }
        AddressCheckLib.requireContract(navCalculator_, "NAVCalculator");
        UNDERLYING_TOKEN = underlyingToken_;
        NAV_CALCULATOR = INAVCalculator(navCalculator_);
        _grantRole(DEFAULT_ADMIN_ROLE, admin_);
    }

    //
    // Writes — keeper path (role-gated submit, proof-of-death remove)
    //

    /// @inheritdoc IAssistedBalanceAdapter
    function submitFor(address account, bytes calldata coord) external {
        _checkRole(SUBMITTER_ROLE);
        _submitFor(account, coord);
    }

    /// @inheritdoc IAssistedBalanceAdapter
    function submitForBatch(address[] calldata accounts, bytes[] calldata coords) external {
        // Checked here too: an EMPTY batch never enters the loop, and a roleless caller must not get a success.
        _checkRole(SUBMITTER_ROLE);
        if (accounts.length != coords.length) revert InvalidArguments();
        for (uint256 i; i < accounts.length; ++i) {
            _submitFor(accounts[i], coords[i]);
        }
    }

    /// @inheritdoc IAssistedBalanceAdapter
    /// @dev Not role-gated on purpose: a role-gated remove would let a compromised key delete LIVE positions (a
    ///      targeted under-report). Gating on {_isDead} instead makes the call safe for anyone.
    function removeFor(address account, bytes calldata coord) external {
        _requireCanonical(coord);
        // Cached-check first, so {_isDead} only ever reads a coordinate that passed write-time validation.
        if (_idxPlus1[account][keccak256(coord)] == 0) revert CoordinateNotCached(account, _coordId(coord));
        _removeEntry(account, coord, _isDead(account, coord));
    }

    //
    // Writes — owner path (each account feeds/cleans its own cache, keyed on msg.sender)
    //

    /// @inheritdoc IAssistedBalanceAdapter
    function clearAccount() external {
        bytes[] storage list = _coords[msg.sender];
        for (uint256 i; i < list.length; ++i) {
            delete _idxPlus1[msg.sender][keccak256(list[i])];
        }
        delete _coords[msg.sender];
        emit AccountCleared(msg.sender);
    }

    /// @inheritdoc IAssistedBalanceAdapter
    function evict(bytes calldata coord) external {
        _requireCanonical(coord);
        _removeEntry(msg.sender, coord, true);
    }

    //
    // Reads
    //

    /// @notice Candidate coordinate blobs currently cached for `account` (display/debug; not staleness-filtered).
    function coordsOf(address account) external view returns (bytes[] memory) {
        return _cachedCoords(account);
    }

    /// @dev The cached coordinate blobs for `account`, for the concrete adapter's typed read helpers / valuation.
    function _cachedCoords(address account) internal view returns (bytes[] memory) {
        return _coords[account];
    }

    /// @inheritdoc IBalanceAdapter
    function underlyingAssetsSupported() external view virtual override returns (address[] memory assets) {
        assets = new address[](1);
        assets[0] = UNDERLYING_TOKEN;
    }

    /// @inheritdoc IBalanceAdapter
    function getAdapterBalanceForAsset(address account, address asset)
        external
        view
        virtual
        override
        returns (uint256 amount, bool isDebt)
    {
        if (asset != UNDERLYING_TOKEN || account == address(0)) return (0, false);
        return (_owedAmount(account), false);
    }

    /// @inheritdoc IBalanceAdapter
    function getAdapterBalances(address account)
        external
        view
        virtual
        override
        returns (address[] memory assets, uint256[] memory amounts, bool[] memory isDebt)
    {
        uint256 total = account == address(0) ? 0 : _owedAmount(account);
        if (total == 0) return (new address[](0), new uint256[](0), new bool[](0));
        assets = new address[](1);
        amounts = new uint256[](1);
        isDebt = new bool[](1);
        assets[0] = UNDERLYING_TOKEN;
        amounts[0] = total;
    }

    /// @inheritdoc IBalanceAdapter
    function getAdapterPositions(address account, address assetFilter)
        external
        view
        virtual
        override
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        if (assetFilter != address(0) && assetFilter != UNDERLYING_TOKEN) {
            return new INAVCalculator.PositionBalance[](0);
        }
        if (account == address(0)) return new INAVCalculator.PositionBalance[](0);

        (INAVCalculator.Asset memory underlying, bool registered) =
            RegisteredAssetLib.find(NAV_CALCULATOR.getRegisteredAssets(), UNDERLYING_TOKEN);
        if (!registered) return new INAVCalculator.PositionBalance[](0);

        return _collect(account, underlying);
    }

    /// @inheritdoc IAssistedBalanceAdapter
    function previewPositions(address account, bytes calldata data)
        external
        view
        override
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        if (account == address(0) || data.length == 0) return new INAVCalculator.PositionBalance[](0);
        return this.previewPositionsSelf(account, abi.decode(data, (bytes[])));
    }

    /// @notice External self-call frame for the preview loop — `msg.sender`-guarded to `address(this)`; `view`, so the
    ///         self-call is a staticcall. Mirrors {valueCoordSelf}.
    /// @dev No per-coordinate stipend or try/catch, unlike the NAV read: the caller pays for its own `eth_call`, and a
    ///      bad coordinate must surface rather than be dropped.
    function previewPositionsSelf(address account, bytes[] calldata coords)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        if (msg.sender != address(this)) revert NotAuthorized();
        uint256 n = coords.length;
        if (n == 0) return new INAVCalculator.PositionBalance[](0);
        if (n > _maxCoords()) revert TooManyCoordinates(account, n, _maxCoords());

        // Same short-circuit as the NAV read: nothing is reported for an unregistered underlying, so don't spend gas
        // validating coordinates first.
        (INAVCalculator.Asset memory underlying, bool registered) =
            RegisteredAssetLib.find(NAV_CALCULATOR.getRegisteredAssets(), UNDERLYING_TOKEN);
        if (!registered) return new INAVCalculator.PositionBalance[](0);

        bytes32[] memory keys = new bytes32[](n);
        for (uint256 i; i < n; ++i) {
            _requireCanonical(coords[i]);
            keys[i] = keccak256(coords[i]);
            for (uint256 j; j < i; ++j) {
                if (keys[j] == keys[i]) revert DuplicateCoordinate(account, _coordId(coords[i]));
            }
            _validateCoord(account, coords[i]);
        }

        INAVCalculator.PositionBalance[] memory temp = new INAVCalculator.PositionBalance[](n * _maxLegsPerCoord());
        uint256 count;
        for (uint256 i; i < n; ++i) {
            INAVCalculator.PositionBalance[] memory legs = _valueCoord(account, coords[i], underlying);
            for (uint256 j; j < legs.length; ++j) {
                temp[count++] = legs[j];
            }
        }
        positions = new INAVCalculator.PositionBalance[](count);
        for (uint256 i; i < count; ++i) {
            positions[i] = temp[i];
        }
    }

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, IERC165) returns (bool) {
        return interfaceId == type(IBalanceAdapter).interfaceId
            || interfaceId == type(IAssistedBalanceAdapter).interfaceId || super.supportsInterface(interfaceId);
    }

    //
    // Internal — cache mutation (called by the concrete's typed submit/remove)
    //

    /// @dev Owner path: add one coordinate for the caller (idempotent). Keyed on `msg.sender` (self-scoped). The typed
    ///      `submit` always passes a canonical `abi.encode`.
    function _submitCoord(bytes memory coord) internal {
        _addEntry(msg.sender, coord, _maxCoords());
    }

    /// @dev Keeper path: canonical-encoding check, then the owner path's admission with a lower limit (cap minus
    ///      {OWNER_RESERVE}; 0 for a member whose cap does not exceed the reserve, which disables the keeper path).
    function _submitFor(address account, bytes calldata coord) private {
        if (account == address(0)) revert InvalidArguments();
        _requireCanonical(coord);
        uint256 cap = _maxCoords();
        if (_addEntry(account, coord, cap > OWNER_RESERVE ? cap - OWNER_RESERVE : 0)) {
            emit CoordSubmittedFor(account, _coordId(coord), msg.sender);
        }
    }

    /// @dev The single admission point for both paths (idempotent). Fail-loud: `CoordinateCacheFull` once the set
    ///      holds `limit` entries ({_maxCoords} for the owner, {_maxCoords} − {OWNER_RESERVE} for the keeper), and
    ///      {_validateCoord} reverts (`InvalidCoordinate` / `CoordinateNotOwned`) on a bad or non-owned coordinate.
    function _addEntry(address account, bytes memory coord, uint256 limit) private returns (bool added) {
        bytes32 key = keccak256(coord);
        // Re-validate on EVERY submit (before the dedup early-return) so a resubmit of an already-cached coordinate the
        // caller has since transferred away is rejected loud rather than silently kept.
        _validateCoord(account, coord); // fail-loud write-time hygiene
        if (_idxPlus1[account][key] != 0) return false; // already cached (idempotent no-op)
        if (_coords[account].length >= limit) revert CoordinateCacheFull(account, limit);
        _coords[account].push(coord);
        _idxPlus1[account][key] = _coords[account].length;
        emit CoordSubmitted(account, _coordId(coord));
        return true;
    }

    /// @dev Owner path: drop one coordinate for the caller once {_removable}. Keyed on `msg.sender`.
    function _removeCoord(bytes memory coord) internal {
        address account = msg.sender;
        if (_idxPlus1[account][keccak256(coord)] == 0) revert CoordinateNotCached(account, _coordId(coord));
        _removeEntry(account, coord, _removable(account, coord));
    }

    /// @dev Drop one coordinate from `account`. Fail-loud: **reverts** `CoordinateNotCached` if `account` isn't
    ///      tracking `coord`, and `CoordinateStillLive` unless `removable` — so a live position is never silently
    ///      dropped.
    function _removeEntry(address account, bytes memory coord, bool removable) private {
        bytes32 key = keccak256(coord);
        uint256 idxPlus1 = _idxPlus1[account][key];
        if (idxPlus1 == 0) revert CoordinateNotCached(account, _coordId(coord));
        if (!removable) revert CoordinateStillLive(account, _coordId(coord));
        uint256 idx = idxPlus1 - 1;
        bytes[] storage list = _coords[account];
        uint256 lastIdx = list.length - 1;
        if (idx != lastIdx) {
            bytes memory last = list[lastIdx];
            list[idx] = last;
            _idxPlus1[account][keccak256(last)] = idx + 1;
        }
        list.pop();
        delete _idxPlus1[account][key];
        emit CoordCleared(account, _coordId(coord));
    }

    /// @dev Rejects any `coord` whose length differs from the member's canonical encoding, BEFORE anything decodes
    ///      it, so one position has exactly one cache key (ADR 0030 S2).
    function _requireCanonical(bytes memory coord) internal pure {
        if (coord.length != _coordLength()) revert NonCanonicalCoordinate(coord.length, _coordLength());
    }

    //
    // Internal — valuation
    //

    /// @dev Total `UNDERLYING_TOKEN` owed across `account`'s cached coordinates (registration-independent — zeroed Asset).
    function _owedAmount(address account) internal view returns (uint256 total) {
        INAVCalculator.Asset memory zero;
        INAVCalculator.PositionBalance[] memory legs = _collect(account, zero);
        for (uint256 i; i < legs.length; ++i) {
            total += legs[i].amount;
        }
    }

    /// @dev Values every cached coordinate of `account` into a flat leg array, isolating each coordinate behind a
    ///      per-item `this.valueCoordSelf(...)` staticcall wrapped in try/catch — so a revert in one coordinate's live
    ///      reads discards only THAT coordinate and never propagates out of {getAdapterPositions} (where NAVCalculator's
    ///      per-adapter try/catch would otherwise fail-open and drop the account's ENTIRE set). Coordinates whose
    ///      valuation is internally safe pay only the extra call frame (negligible on the async NAV read path, ADR 0017).
    ///
    ///      **The isolation is deliberate and stays — but it must not absorb a STARVED coordinate.** A coordinate
    ///      whose protocol read reverts has answered: it contributes nothing, and one bad NFT must not cost the
    ///      account its other positions. Gas exhaustion is categorically different. The coordinate did not answer,
    ///      recording it as zero legs silently deletes a real position, and — because a starved child takes 63/64
    ///      of what the loop held — the ~1/64 residue cannot fund the coordinates AFTER it either, so one starved
    ///      entry can quietly empty the rest of the list. `_collect` would still RETURN, so nothing downstream can
    ///      tell the answer was partial: `PriceFeedLib._getAdapterPositions` only inspects its own catch arm, and
    ///      this frame never reverted. That is the one failure this loop must not swallow, so it raises
    ///      {CoordinateGasExhausted} instead.
    ///
    ///      The classification is {GasStipendLib}'s, not restated here — the same shared threshold
    ///      `MetaBalanceAdapter._positionsForInstances` and `PriceFeedLib._getAdapterPositions` use, so the three
    ///      cannot drift apart.
    ///
    ///      Direction note, so the severity is not overstated: this family emits credit legs only
    ///      (`isDebt = false` throughout), so swallowing a coordinate under-reports rather than over-reports. That
    ///      is a property of today's three members, not of this base — a future member emitting a debt leg would
    ///      make the swallowed case an over-report, and this guard is what stops that being a silent one.
    function _collect(address account, INAVCalculator.Asset memory underlying)
        internal
        view
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        bytes[] memory list = _coords[account];
        if (list.length == 0) return new INAVCalculator.PositionBalance[](0);

        INAVCalculator.PositionBalance[] memory temp =
            new INAVCalculator.PositionBalance[](list.length * _maxLegsPerCoord());
        uint256 count;
        for (uint256 i; i < list.length; ++i) {
            // One sample, used both to derive the stipend and to measure against it — see GasStipendLib.exhausted.
            uint256 available = gasleft();
            uint256 stipend = GasStipendLib.stipendFrom(available);
            try this.valueCoordSelf{gas: stipend}(account, list[i], underlying) returns (
                INAVCalculator.PositionBalance[] memory legs
            ) {
                for (uint256 j; j < legs.length; ++j) {
                    temp[count++] = legs[j];
                }
            } catch {
                uint256 consumed = available - gasleft();
                if (GasStipendLib.exhausted(stipend, consumed)) {
                    revert CoordinateGasExhausted(address(this), _coordId(list[i]), stipend, consumed);
                }
            }
        }

        positions = new INAVCalculator.PositionBalance[](count);
        for (uint256 i; i < count; ++i) {
            positions[i] = temp[i];
        }
    }

    /// @notice External self-call entrypoint for {_valueCoord}, enabling the per-coordinate try/catch isolation in
    ///         {_collect}. `msg.sender`-guarded to `address(this)` so it is not a usable external surface; it is
    ///         `external` (so the self-call is a staticcall) ONLY to give each coordinate its own revert frame.
    function valueCoordSelf(address account, bytes calldata coord, INAVCalculator.Asset calldata underlying)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory)
    {
        if (msg.sender != address(this)) revert NotAuthorized();
        return _valueCoord(account, coord, underlying);
    }

    //
    // Hooks (concrete adapter)
    //

    /// @notice The per-account cache cap (read-loop gas bound).
    function _maxCoords() internal view virtual returns (uint256);

    /// @notice Byte length of the member's canonical coordinate encoding (`abi.encode` of its static tuple).
    function _coordLength() internal pure virtual returns (uint256);

    /// @notice Upper bound on legs emitted per coordinate (scratch-buffer sizing).
    function _maxLegsPerCoord() internal pure virtual returns (uint256);

    /// @notice The human-facing id for a coordinate (a positionTicket / requestId), used only to populate the shared
    ///         `Coordinate*` errors. The stable dedup/lookup key is `keccak256(coord)`; this is a decoded scalar for
    ///         legibility.
    function _coordId(bytes memory coord) internal pure virtual returns (uint256);

    /// @notice Write-time validation for a submitted coordinate. MUST revert (fail-loud) on an invalid coordinate:
    ///         `InvalidCoordinate` for a malformed/unregistered target, `CoordinateNotOwned` if it does not resolve to
    ///         a live position owned by `account`.
    function _validateCoord(address account, bytes memory coord) internal view virtual;

    /// @notice Whether `coord` may be removed from `account`'s cache. Default: only when it no longer resolves to a
    ///         live owed amount for `account` (claimed / consumed) — so {_removeCoord} never drops a live position
    ///         (under-report only). Implemented per adapter (the liveness proxy is protocol-specific).
    function _removable(address account, bytes memory coord) internal view virtual returns (bool);

    /// @notice Whether the protocol PROVES `coord` no longer holds anything for `account` — the gate for the
    ///         permissionless {removeFor}. Stricter than {_removable}: only a SUCCESSFUL read showing the position
    ///         burned, transferred away or emptied counts; a reverting read never does (it could be transient).
    function _isDead(address account, bytes memory coord) internal view virtual returns (bool);

    /// @notice Values a single cached coordinate into its legs (empty if it contributes nothing — not owned, claimed,
    ///         zero amount). Decodes `coord` and re-verifies ownership live. Reached only via the self-`staticcall` in
    ///         {_collect}, so it MAY revert freely — the caller isolates it (a reverting coordinate is discarded).
    function _valueCoord(address account, bytes memory coord, INAVCalculator.Asset memory underlying)
        internal
        view
        virtual
        returns (INAVCalculator.PositionBalance[] memory);
}

src/balances/IAssistedBalanceAdapter.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";

import {IBalanceAdapter} from "src/balances/IBalanceAdapter.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";

/// @title IAssistedBalanceAdapter
/// @author KPK
/// @notice Marker interface for the **assistant-fed** assisted balance-adapter family — adapters whose
///         positions cannot be derived from on-chain state alone (non-enumerable NFTs, withdrawal/exit-queue tickets)
///         and are instead fed their position *coordinates* on-chain by the position owner itself. The canonical
///         feeder is a small assistant contract ({IBalanceAdapterAssistant}) that a depositor Safe `delegatecall`s: in the
///         same transaction it enters/exits a protocol, it pushes/pops the resulting coordinate onto the adapter, and
///         because it runs under `delegatecall` the adapter sees `msg.sender = the Safe = the position owner`.
/// @dev **Trust model (family invariant).** Every member caches **only position coordinates, never amounts**; values
///      each read entirely from live on-chain reads; and re-verifies ownership on every read (discarding coordinates
///      no longer owned). A faulty or malicious feeder can therefore only **under-report, never over-report**.
///
///      **The deployed guarantee is stronger, and its second half is not in this repository.** The portfolio Safes'
///      **roles-modifier permission set allows the corresponding protocol entries only through the assistant
///      contracts — the direct protocol entrypoint is not allow-listed** — so a position of these types cannot be
///      active without its coordinate having been fed, making the cache **complete by construction**. Contract level
///      (here) → cannot **over**-report; roles level (outside this repo) → cannot **under**-report either. Nothing in
///      this repo enforces the latter (the owner mutators are permissionless), so do not infer it from the code; the
///      residual risk is a roles-permission change adding a non-assistant path, which no tripwire here would catch.
///      See ADR 0015 / ADR 0018 and `AssistedBalanceAdapters/README.md` §5.0.
///
///      **Two feeders (ADR 0030).** The owner path is unchanged: the typed `submit`/`remove` mutators derive the
///      account from `msg.sender`, so an account (directly or through its assistant) only ever touches its OWN set.
///      The interface does not prescribe those typed signatures, since the coordinate shape is per-protocol. Added for
///      positions the account did NOT open through its assistant: {submitFor}/{submitForBatch}, gated by
///      {SUBMITTER_ROLE} (a keeper), which file a coordinate only under the account the protocol says owns it — the
///      same write-time validation as the owner path, so the role decides WHICH positions occupy the capped cache,
///      never what they are worth. {removeFor} is permissionless but succeeds only once the protocol proves the
///      position is gone, so no caller can drop a live one. {previewPositions} values caller-supplied coordinates
///      without touching the cache.
///
///      **Coordinate encoding.** The generic entry points take `coord` as the member's canonical `abi.encode` of its
///      tuple (a 32-byte tokenId for ether.fi / Nexus Mutual, `(address vault, uint256 ticket, uint256 timestamp)` for
///      StakeWise). Any other length reverts, so one position has exactly one cache key.
interface IAssistedBalanceAdapter is IAccessControl, IBalanceAdapter {
    /// @notice A {previewPositions} payload names the same coordinate twice — a double count, rejected fail-loud.
    error DuplicateCoordinate(address account, uint256 id);

    /// @notice A {previewPositions} payload has more coordinates than an account's cache may hold.
    error TooManyCoordinates(address account, uint256 count, uint256 max);

    /// @notice `coord` is not the member's canonical encoding (wrong length), so it could alias another cache key.
    error NonCanonicalCoordinate(uint256 length, uint256 expected);

    /// @notice The role allowed to call {submitFor}/{submitForBatch}.
    function SUBMITTER_ROLE() external view returns (bytes32);

    /// @notice File `coord` under `account`, which the protocol must say owns it (idempotent). Requires
    ///         {SUBMITTER_ROLE}. Reverts `CoordinateNotOwned` / `InvalidCoordinate` on a bad or non-owned
    ///         coordinate, `CoordinateCacheFull` once the account holds the cap minus `OWNER_RESERVE` entries
    ///         (the reserve stays for the owner's own submit), {NonCanonicalCoordinate} on a wrong encoding.
    function submitFor(address account, bytes calldata coord) external;

    /// @notice Batch {submitFor}; all-or-nothing. Requires {SUBMITTER_ROLE}.
    function submitForBatch(address[] calldata accounts, bytes[] calldata coords) external;

    /// @notice Drop `coord` from `account`'s cache once the protocol proves the position is gone (claimed, burned,
    ///         transferred away, nothing left). Permissionless: a read that reverts never counts as proof, so no caller
    ///         can drop a live position. Reverts `CoordinateNotCached` / `CoordinateStillLive`.
    function removeFor(address account, bytes calldata coord) external;

    /// @notice Values caller-supplied coordinates for `account` without reading or writing the cache.
    /// @dev `data = abi.encode(bytes[] coords)`, each in the canonical encoding. Every coordinate goes through the
    ///      same validation as a submit and reverts on failure (bad, non-owned, duplicate, or more than the cap);
    ///      surviving ones are valued exactly as the NAV read values a cached coordinate. Empty `data` or a zero
    ///      `account` returns an empty array; an unregistered underlying returns an empty array, as the NAV read does.
    function previewPositions(address account, bytes calldata data)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory positions);

    /// @notice Drop **all** of the caller's own cached position coordinates (self-service garbage collection). Keyed on
    ///         `msg.sender`, so it can only clear the caller's own set — never another account's. This is
    ///         unconditional: unlike per-coordinate `remove` (which reverts `CoordinateStillLive` while a position is
    ///         live), `clearAccount` does **not** check liveness, so any still-live positions stop being reported until
    ///         re-submitted. Consistent with the family invariant it only ever **under-reports** the caller's own NAV;
    ///         it is not NAV-neutral when live coordinates are present.
    function clearAccount() external;

    /// @notice Drop ONE of the caller's own cached coordinates, live or not (keyed on `msg.sender`). The selective
    ///         form of {clearAccount}: it lets a Safe whose cache a keeper filled with positions a third party created
    ///         in its name (ADR 0030 S13) free slots without dropping its real entries. Like {clearAccount} it can
    ///         only under-report the caller's own NAV. Reverts `CoordinateNotCached` / {NonCanonicalCoordinate}.
    ///         Not reachable through an Assistant: a roles-operated Safe needs a roles entry for it (or a signer tx).
    function evict(bytes calldata coord) external;
}

src/balances/IBalanceAdapter.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";

/// @title IBalanceAdapter
/// @notice Standard interface for balance adapters (both default and custom)
/// @dev All balance adapters must implement this interface to work with the adapter-centric aggregation system
/// @dev Extends ERC165 to allow on-chain discovery with `supportsInterface`.
/// @author KPK
interface IBalanceAdapter is IERC165 {
    /// @notice Get all positions from this adapter for an account
    /// @param account The account to query
    /// @param assetFilter Optional asset filter (address(0) for all assets)
    /// @return positions Array of balance-only PositionBalance structs from this adapter
    /// @dev Balance adapters return balance-only data without pricing. NAVCalculator enriches these with pricing.
    function getAdapterPositions(address account, address assetFilter)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory positions);

    /// @notice Get balances from this adapter for an account
    /// @param account The account to query
    /// @return assets Array of asset addresses
    /// @return amounts Array of balance amounts (always non-negative magnitude)
    /// @return isDebt Array of debt flags (true = debt, false = credit)
    function getAdapterBalances(address account)
        external
        view
        returns (address[] memory assets, uint256[] memory amounts, bool[] memory isDebt);

    /// @notice Get single balance for a specific asset (gas-optimized version)
    /// @param account The account to query
    /// @param asset The asset address
    /// @return amount Balance amount (non-negative magnitude)
    /// @return isDebt True if debt, false if credit
    function getAdapterBalanceForAsset(address account, address asset)
        external
        view
        returns (uint256 amount, bool isDebt);

    /// @notice Returns the list of all the underlying assets supported by this adapter
    /// @dev The returned list may be empty if the adapter cannot determine or provide the supported assets
    /// @return underlyingAssets The list of underlying asset addresses supported by this adapter (may be empty)
    function underlyingAssetsSupported() external view returns (address[] memory underlyingAssets);
}

src/balances/IBalances.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

/// @author KPK
interface IBalances {
    //
    // Type definitions
    //

    enum AdapterType {
        Default,
        Custom
    }

    struct BalanceAdapter {
        address adapter;
        AdapterType adapterType;
        string protocol;
    }

    //
    // Events
    //

    /// @notice Event emitted when a balance adapter is added to the global registry.
    /// @param underlyingAsset Reserved; currently address(0) as adapters are registered globally, not per asset.
    /// @param adapter The address of the adapter being added.
    /// @param adapterType The type of the adapter (Default or Custom).
    event BalanceAdapterAdded(address indexed underlyingAsset, address indexed adapter, AdapterType adapterType);

    /// @notice Event emitted when a balance adapter is removed from the global registry.
    /// @param underlyingAsset Reserved; currently address(0) as adapters are global.
    /// @param adapter The address of the balance adapter being removed.
    event BalanceAdapterRemoved(address indexed underlyingAsset, address adapter);

    //
    // Errors
    //

    /// @notice Error when the balance adapter is not set.
    error BalanceAdapterNotSet();

    /// @notice Error when the balance adapter is not valid.
    error InvalidBalanceAdapter();

    /// @notice Error when the balance adapter type is not valid.
    error InvalidBalanceAdapterType();

    /// @notice Error when the same balance adapter is already set.
    error DuplicateBalanceAdapter();

    /// @notice Error when adding a meta-instance coordinate that is already present (would double-count NAV).
    error DuplicateMetaInstance();

    /// @notice The coordinate is already governed by a DIFFERENT registered meta adapter.
    /// @dev Two adapters holding one coordinate both emit a well-formed leg for the same holding under
    ///      different reconciliation keys, and NAV sums them with no health flag. Rejected at configuration
    ///      time because no read-path guard can see across adapters.
    error MetaInstanceClaimedByAnotherAdapter(bytes32 instance, address claimedBy);

    /// @notice Error when removing a meta-instance coordinate that is not present in the adapter's set.
    error MetaInstanceNotFound();

    /// @notice Error when a meta-adapter (implements IMetaBalanceAdapter) is registered via the plain
    ///         addBalanceAdapters path; meta-adapters must use addMetaBalanceAdapter.
    error MetaAdapterNotAllowed();

    /// @notice Error when a meta-adapter operation (registration via addMetaBalanceAdapter, or an
    ///         addMetaInstances / removeMetaInstances call) targets an adapter that is not a meta-adapter
    ///         (does not implement IMetaBalanceAdapter).
    error NotMetaAdapter();

    /// @notice Validates that the adapter implements IBalanceAdapter (reverts with InvalidBalanceAdapter if not).
    /// @dev Reverts with InvalidArguments if `adapter` is the zero address.
    /// @param adapter The address of the adapter to check.
    function checkBalanceAdapterSupport(address adapter) external view;

    //
    // Global Adapter Registry
    //

    /// @notice Returns all registered adapters in the global registry
    /// @return adapters Array of all adapter addresses
    function getAllAdapters() external view returns (address[] memory adapters);

    /// @notice Returns the total number of registered adapters
    /// @return count Total number of adapters
    function getAdapterCount() external view returns (uint256 count);

    /// @notice Checks if an adapter is registered in the global registry
    /// @param adapter The adapter address to check
    /// @return registered True if the adapter is registered
    function isAdapterRegistered(address adapter) external view returns (bool registered);

    /// @notice Returns the type of a registered adapter
    /// @dev Reverts with InvalidBalanceAdapter if the adapter is not registered.
    /// @param adapter The adapter address
    /// @return adapterType The type of the adapter
    function getAdapterType(address adapter) external view returns (AdapterType adapterType);

    /// @notice Returns all adapters that support the given asset
    /// @dev Loops through all global adapters and checks if the asset is in their underlyingAssetsSupported() list
    /// @param asset The asset address to check
    /// @return adapters Array of adapter addresses that support the asset
    function getAdaptersForAsset(address asset) external view returns (address[] memory adapters);

    //
    // Meta-adapter instance registry (ADR 0010)
    //

    /// @notice Returns the configured meta-adapter instance coordinates for an adapter (empty for non-meta adapters).
    /// @param adapter The adapter address.
    /// @return instances The instance coordinates currently configured for the adapter.
    function getMetaInstances(address adapter) external view returns (bytes32[] memory instances);
}

src/balances/IPositionDescribable.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

/// @title IPositionDescribable
/// @notice Optional interface for balance adapters that expose a human-readable protocol name for their positions.
/// @dev NAVCalculator's verbose read methods (`getAccountPositionsVerbose`, `getAccountPositionsForAssetVerbose`,
///      `getAccountNavVerbose`) call these via a fail-open staticcall — adapters that do not implement this
///      interface simply produce an empty protocol name / label set. Labels are derived **lazily from `positionId`**
///      (a static, per-position breadcrumb), so they are computed only in the verbose reads, not carried on every
///      `PositionBalance` (that keeps display work off the NAV hot path). The ephemeral per-item id (Uniswap V3 NFT
///      id, withdrawal request id, …) is NOT a label — it is the typed `PositionBalance.positionInstanceId` field.
///      Clients MUST NOT use these strings for identity, indexing, or reconciliation; use the typed
///      `protocolSubId` / `positionId` / `PositionKind` fields on `PositionBalance` for those purposes.
/// @author KPK
interface IPositionDescribable {
    /// @notice Human-readable name of the PROTOCOL, e.g. "Aave V3", "Morpho", "Uniswap V3".
    /// @dev **This names the protocol, never the product.** A protocol's individual products — Aave V3's Safety
    ///      Module and Umbrella, Morpho's vaults and markets, Balancer's pools and gauges — all return the SAME
    ///      string here; what distinguishes them is `positionLabels()` (`["Umbrella Module"]`, `["Safety Module"]`,
    ///      `["Market", "wstETH/USDC"]`) and the typed `protocolSubId`. Equivalently: every adapter sharing a
    ///      `ProtocolIds` protocol id MUST return the same name. Pull it from `src/utils/ProtocolNames.sol` rather
    ///      than writing a literal — new and changed adapters should reference the constant; the pre-existing
    ///      literals are being migrated adapter by adapter and are meanwhile pinned to their constants by
    ///      `test/ProtocolNameConsistency.t.sol`. Meta-adapters need no literal at all (see below).
    ///
    ///      Why the distinction is load-bearing rather than cosmetic: consumers group *configured adapters* by this
    ///      string. The typed `protocolBrand`/`protocolId`/`protocolSubId` would group them correctly, but they are
    ///      `private constant` and only ride on `PositionBalance` structs returned by an **account** read — a
    ///      consumer enumerating registered adapters never sees them, so the display name is the only protocol
    ///      identity it has. An adapter that returns its product name here splits itself out into a phantom sibling
    ///      protocol (`AaveUmbrellaBalanceAdapter` returned "Aave Umbrella" and did exactly that).
    ///
    ///      Per-instance adapters return a compile-time constant. Meta-adapters **derive** it —
    ///      `MetaBalanceAdapter.protocolName()` is `ProtocolNames.forProtocolId(_protocolId())` — so for the whole
    ///      meta family the invariant holds by construction: the name is a pure function of the typed identity the
    ///      adapter already declares, with no constructor argument or config value that could disagree with it.
    function protocolName() external view returns (string memory);

    /// @notice Ordered, arbitrary-depth display hierarchy for a single position, BELOW the protocol level.
    ///         Index 0 is the broadest level (category) and the last element is the position leaf, e.g.
    ///         `["Market", "wstETH/USDC"]`, `["AMM Liquidity Pool", "WETH/USDC 0.05%"]`, or `["Safety Module"]` when the
    ///         category itself is the leaf. The full breadcrumb a consumer renders is
    ///         `[protocolName(), ...positionLabels(positionId)]`. Derived purely from `positionId` (the static
    ///         anchor) — the ephemeral per-item id rides in `PositionBalance.positionInstanceId`, not here.
    /// @param positionId The ABI-encoded position identifier (same bytes as `PositionBalance.positionId`).
    /// @return An array of display segments. An empty array is acceptable when no label can be derived.
    ///         Depth varies by adapter and position; consumers must not assume a fixed length.
    ///
    ///      **When there is no account to get a positionId from** — a configuration view listing what the
    ///      NAVCalculator is set up to account for — an adapter whose breadcrumb is positionId-independent
    ///      answers `positionLabels("")` with its full constant breadcrumb, and that is the whole answer. An
    ///      adapter whose breadcrumb is derived per positionId returns `[]` instead and should implement
    ///      {IPositionEnumerable}, whose `positionIds()` lists the shapes to pair with this function and whose
    ///      ERC-165 bit is what distinguishes that `[]` from a broken adapter. See {IPositionEnumerable}.
    function positionLabels(bytes calldata positionId) external view returns (string[] memory);
}

src/balances/RegisteredAssetLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

import {INAVCalculator} from "src/nav/INAVCalculator.sol";

/// @title RegisteredAssetLib
/// @author KPK
/// @notice Shared helper for resolving a registered asset's metadata out of a NAVCalculator
///         `getRegisteredAssets()` snapshot. Many balance adapters need this find-by-address scan to look up the
///         `symbol`/`decimals` of a token they value — single-underlying adapters resolve one fixed token
///         (Lido, Stader, ether.fi, StakeWise V3, Kelp withdrawal/exit queues; Nexus Mutual staking pools), while
///         others resolve several tokens per call (Uniswap V3 looks up both pool tokens; Merkl rewards resolve an
///         arbitrary token list).
///         Centralising the scan here removes the hand-rolled copies that previously lived in each adapter.
/// @dev `internal` functions only, so this library is inlined into each caller's bytecode — it is NOT a linked/pinned
///      external library (no CREATE2 address, no `foundry.toml [libraries]` entry, no effect on the PriceFeedLib /
///      NAVRegistryLib pins).
library RegisteredAssetLib {
    /// @notice Finds `asset` in a pre-fetched `getRegisteredAssets()` snapshot.
    /// @param reg The registry snapshot (caller fetches it once via `NAV_CALCULATOR.getRegisteredAssets()`).
    /// @param asset The asset address to resolve.
    /// @return assetInfo The matching `Asset` (zeroed if not found).
    /// @return found True if `asset` is registered.
    function find(INAVCalculator.Asset[] memory reg, address asset)
        internal
        pure
        returns (INAVCalculator.Asset memory assetInfo, bool found)
    {
        for (uint256 i = 0; i < reg.length; i++) {
            if (reg[i].asset == asset) {
                return (reg[i], true);
            }
        }
        return (INAVCalculator.Asset({asset: address(0), symbol: "", decimals: 0}), false);
    }
}

src/constants.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

uint8 constant NAV_DECIMALS = 8;

// Maximum safe exponent for 10^N calculations (max uint8 is 255)
// Used to prevent overflow in decimal exponentiation operations
uint256 constant MAX_DECIMAL_EXPONENT = 255;

// Maximum exponent such that 10^N fits in int256 (10^77 > type(int256).max)
uint256 constant MAX_DECIMAL_EXPONENT_INT256 = 76;

// Define the MANAGER role ID, used across NAVCalculator and bridge system for operational management
bytes32 constant MANAGER = keccak256("MANAGER"); // 0xaf290d8680820aad922855f39b306097b20e28774d6c1ad35a20325630c3a02c

/// @dev Gates the SUBMIT surface of the attested balance-adapter family (ADR 0022). Deliberately NOT used to gate
///      the family's clears — those stay permissionless and stale-gated, because role-gating removal is what audit
///      finding L-02 flagged: a compromised role-holder could delete valid LIVE allocations.
bytes32 constant SUBMITTER = keccak256("SUBMITTER");

bytes32 constant DEFAULT_ADMIN_ROLE = 0x00;

src/errors.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

error InvalidArguments();
error InvalidArgumentsWithContext(string context);
/// @notice A constructor argument expected to be a deployed contract has no code. `name` is the dependency label.
error NotAContract(string name);
error NotAuthorized();
error NotChainlinkOracle();
/// @notice Thrown when an assistant entrypoint that must be delegatecalled is called directly on the singleton
///         (`address(this) == SELF`). Canonical delegatecall-guard error for the assistant-fed family (`BalanceAdapterAssistant`).
error NotDelegateCall();
/// @notice An assistant entrypoint was told to track/act for an account other than the executing context
///         (`address(this)`, i.e. the delegatecalling Safe). Canonical assistant self-scope check (`_requireSelf`).
error AssistantAccountMismatch(address expected, address provided);

// Permissionless assistant-fed assisted balance-adapter family (ADR 0018) — shared coordinate-cache errors, used by the
// single {AssistedCoordCache} base (every coordinate is an `abi.encode`d blob). The coordinate is identified by `id`
// (a tokenId / requestId / positionTicket, from `_coordId`); the full tuple, where richer, rides in the cache's events.
/// @notice `submit` was given a coordinate not currently owned by the caller (`msg.sender`).
error CoordinateNotOwned(address account, uint256 id);
/// @notice `submit` would grow the caller's cache past its per-account cap.
error CoordinateCacheFull(address account, uint256 maxCoordinates);
/// @notice `remove` targeted a coordinate not in the caller's cache.
error CoordinateNotCached(address account, uint256 id);
/// @notice `remove` targeted a coordinate the caller still owns (a live position) — refused so a live position is never
///         dropped (would under-report the caller's own NAV). Only a claimed/consumed coordinate may be removed.
error CoordinateStillLive(address account, uint256 id);
/// @notice `submit` was given a coordinate that failed the adapter's write-time protocol validation (e.g. an
///         unregistered target). Distinct from {CoordinateNotOwned} (ownership) — this is a malformed/invalid coordinate.
error InvalidCoordinate(address account, uint256 id);

// Bridge-specific errors
error AlreadyInitialized();
error InvoiceNotFound();
error InvoiceAlreadyExists();
error InvalidInvoiceStatus();
error InvalidInvoice();
error TransferFailed();
error InsufficientBalance(address asset, uint256 required, uint256 available);
error InvalidChainId();
error InvalidNonce();
error InvalidCompletionData();
error InvalidChecksum(bytes32 invoiceId, bytes24 provided, bytes24 calculated);
error InvalidTimestamp(uint64 provided, uint64 current);
error AssetHasActiveInvoices(string symbol);
error AssetNotRegistered(string symbol);

// NAV Calculator / registry errors
error PriceFeedNotSet(address asset);
error AssetNotFound();
error OnlyNAVCalculator();
error ArrayLengthMismatch();
error InvalidAssetDecimals();
error InvalidDecimalExponent();

src/nav/INAVCalculator.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

import {IBalances} from "src/balances/IBalances.sol";
import {IPrices} from "src/prices/IPrices.sol";
import {PositionKind} from "src/utils/PositionKind.sol";

/// @title INAVCalculator
/// @notice Interface for the NAV Calculator contract. Defines the full API for asset registration, price feeds,
///         balance adapters, and NAV/position queries in one or more quote currencies.
/// @dev Extends IBalances for adapter registry and IPrices for price feed types. Implementations are typically
///      UUPS-upgradeable and use AccessControl (MANAGER for mutations, DEFAULT_ADMIN_ROLE for upgrades).
/// @author KPK
interface INAVCalculator is IBalances {
    /// @notice A balance adapter consumed the gas stipend the NAV read forwarded to it without answering.
    /// @dev Deliberately NOT folded into the read's fail-open path. A revert means "this adapter has nothing to
    ///      report"; running out of gas means "this adapter's answer is unknown", and reporting an unknown answer
    ///      as an empty one drops the adapter's legs — a dropped debt leg RAISES the reported NAV.
    ///
    ///      Declared here rather than alongside the shared errors so it reaches consumers: it is raised inside a
    ///      DELEGATECALLed library, and an error a contract never names itself does not appear in that contract's
    ///      ABI. Callers generate against this interface and the NAVCalculator implementing it, so a revert they
    ///      can actually decode has to be part of it.
    ///
    ///      `adapter` names the adapter that was running, which is not always the adapter at fault: the stipend is
    ///      a share of what the READ still holds, so an under-funded call starves whichever adapter happens to be
    ///      reached last. `stipend` and `consumed` are what separate the two cases. A large `stipend` fully
    ///      consumed means that adapter is genuinely runaway; a small `stipend` means the read itself was short of
    ///      gas and the fix is to supply more.
    /// @param adapter The adapter that was executing when its gas ran out.
    /// @param stipend The budget the classification was measured against: 63/64 of what the read held just before
    ///        the call. It is NOT precisely what the EVM forwarded — the same 63/64 rule is applied again at the
    ///        CALL itself, to a figure already reduced by building the calldata — so on a genuine exhaustion
    ///        `consumed` lands a few tens of gas ABOVE it. Read the two as a ratio, not as a balance.
    /// @param consumed Gas the call actually cost this frame, including the call overhead.
    error AdapterGasExhausted(address adapter, uint256 stipend, uint256 consumed);

    /// @notice One governed instance of a meta-adapter consumed its gas stipend without answering.
    /// @dev The {AdapterGasExhausted} sibling, one frame in. A meta-adapter isolates each instance behind its own
    ///      `try`/`catch` so a single faulty instance cannot zero out the batch, and that isolation has the same
    ///      blind spot: an instance that runs out of gas is indistinguishable from one that reverted, and recording
    ///      it as "no positions" drops its legs while the meta-adapter still RETURNS SUCCESSFULLY — so the caller
    ///      sees a complete-looking answer. A dropped debt leg raises the reported NAV.
    ///
    ///      Raised rather than swallowed. `PriceFeedLib` keys on this selector explicitly rather than re-deriving
    ///      exhaustion from gas, so a cheap early raise here cannot be re-scored as a benign revert one frame out.
    ///
    ///      `instance` is where the budget ran out, which is NOT the same as where it went. The fan-out gives each
    ///      instance a share of whatever its predecessors left, so a single runaway instance early in the governed
    ///      set can leave the NEXT one too little and get it named instead. Read the pair together: a large
    ///      `stipend` fully consumed means that instance is genuinely runaway; a small `stipend` means it was
    ///      starved by something before it, or the read was under-funded to begin with. Removing the named instance
    ///      is the wrong first move when `stipend` is small.
    /// @param adapter The meta-adapter that was fanning out. Overwritten by `PriceFeedLib` with the address it
    ///        actually called, so it is trustworthy even when the rest of the payload is not.
    /// @param instance The governed instance coordinate whose read ran out of gas — see the caveat above.
    /// @param stipend The budget the classification was measured against: 63/64 of what the fan-out held just
    ///        before the call. As with {AdapterGasExhausted} it is NOT precisely what the EVM forwarded — the same
    ///        rule is applied again at the CALL — so `consumed` lands slightly above it. A ratio, not a balance.
    /// @param consumed Gas the instance call actually cost, including the fan-out's call overhead.
    error InstanceGasExhausted(address adapter, bytes32 instance, uint256 stipend, uint256 consumed);

    /// @notice {getAccountNavForAdapters} was given an empty adapter list.
    /// @dev Not silently answered with a zero NAV. An empty slice is indistinguishable from "this portion of the
    ///      portfolio is worth nothing", and a caller that built its slice list from a stale or mis-parsed source
    ///      would read that zero as a real answer and reassemble a NAV that is short by exactly the adapters it
    ///      forgot to ask for. Declared here rather than in `src/errors.sol` for the same reason as
    ///      {AdapterGasExhausted}: it is raised inside a DELEGATECALLed library, so it only reaches consumers'
    ///      generated ABIs by being named in this interface.
    error EmptyAdapterSlice();

    /// @notice {getAccountNavForAdapters} was given an adapter that is not in the global registry.
    /// @dev The registry is `getAllAdapters()` — the exact list the complete read scans — so "registered" here
    ///      means "would have been included in `getAccountNav`". Rejected rather than skipped: an unregistered
    ///      address (a decommissioned adapter, a typo, an address from another chain) has no positions to report,
    ///      so skipping it would return a well-formed slice whose `value` is silently missing whatever the caller
    ///      believed that address covered — and whose `adaptersCovered` would then have to either echo an address
    ///      that contributed nothing or omit one the caller asked for. Both mislead the coverage check that
    ///      `adaptersCovered` exists to support.
    /// @param adapter The supplied address that is not a registered balance adapter.
    error AdapterNotRegistered(address adapter);

    /// @notice {getAccountNavForAdapters} was given the same adapter twice in one slice.
    /// @dev A repeated adapter is queried twice and its positions summed twice, so the slice over-reports by that
    ///      adapter's whole value. Rejected rather than deduplicated, because a duplicate means the caller's
    ///      partition logic is wrong and the same defect will be producing overlaps ACROSS slices — which this
    ///      contract cannot see and silently deduplicating here would hide. Cross-slice overlap is what
    ///      `PartialNAV.adaptersCovered` is for.
    /// @param adapter The address that appeared more than once.
    error DuplicateAdapterInSlice(address adapter);

    //
    // Structs
    //

    /// @notice Registered asset metadata used by the NAV/Pricing registry and balance adapters.
    /// @param asset Token address (or NATIVE_ADDRESS for chain native token).
    /// @param symbol Display symbol (e.g. "ETH", "USDC").
    /// @param decimals Number of decimals for amounts.
    struct Asset {
        address asset;
        string symbol;
        uint8 decimals;
    }

    /// @notice Balance-only position data returned by balance adapters (no pricing).
    /// @dev NAVCalculator enriches these with pricing to produce Position structs.
    /// @param balanceAsset Asset metadata (address, symbol, decimals). The token `amount` is denominated in.
    /// @param balanceAdapter Address of the adapter that reported this position. Provenance / audit trail — NOT part of identity.
    /// @param amount Balance magnitude (always positive); sign is implied by isDebt.
    /// @param isDebt True if debt (subtract from NAV), false if credit (add to NAV). Canonical NAV-sign signal.
    /// @param protocolBrand `keccak256` of the protocol brand slug (version-stripped, e.g. `aave`, `balancer`; see
    ///        `src/utils/ProtocolIds.sol`). The broadest roll-up layer — several `protocolId`s share it
    ///        (`aave-v3` → `aave`; `balancer-v2` + `balancer-v3` → `balancer`). Display/grouping only; NOT part of the
    ///        stable identity key. Equals `protocolId` for unversioned protocols.
    /// @param protocolId `keccak256` of the broad protocol-ecosystem slug (e.g. `aave-v3`, `curve`; see
    ///        `src/utils/ProtocolIds.sol`). A roll-up / grouping key only — several `protocolSubId`s share it
    ///        (e.g. `aave-v3-lending` + `aave-v3-safety-module` both roll up to `aave-v3`). NOT part of the stable
    ///        identity key (it is functionally determined by `protocolSubId`).
    /// @param protocolSubId `keccak256` of the specific protocol-product slug (e.g. `aave-v3-lending`; see
    ///        `src/utils/ProtocolIds.sol`). Selects the `positionId` ABI-decode schema — one sub-slug implies exactly
    ///        one schema — and is the protocol component of the stable identity key. Equals `protocolId` for
    ///        single-product ecosystems.
    /// @param positionId ABI-encoded position identifier. Decode schema is determined by `protocolSubId`.
    ///        e.g. for AAVE_V3_LENDING: `abi.encode(address pool)`.
    ///        Full schema table: see `src/utils/ProtocolIds.sol` and docs/howto/position-identity-schema.md.
    /// @param positionKind Semantic discriminator (Wallet / Supplied / Borrowed / Collateral / Staking / Rewards / Fees).
    ///        Together with `protocolSubId` and `positionId` forms the stable per-chain identity key
    ///        `(chainId, protocolSubId, positionId, balanceAsset.asset, positionKind)`.
    /// @param isLocked True if this leg is NOT withdrawable right now (the pending portion of a withdrawal queue, or a
    ///        staked amount in/awaiting its unstaking cooldown); false if fully liquid / claimable now. Withdrawal-queue
    ///        and cooldown adapters keep a STATIC, timeless `positionId` (the queue/manager/asset/vault/stake-token
    ///        coordinate) and split an account's holding into up to two legs — a claimable leg (`isLocked=false`) and a
    ///        locked leg (`isLocked=true`). `isLocked` is a **mutable per-leg attribute, NOT part of the identity key**:
    ///        a leg flips `true→false` as its portion finalizes/unlocks, so keying on it would split one economic
    ///        position into two keys over its lifetime. The claimable and locked legs therefore share ONE key and are
    ///        **summed** in reconciliation (the sum is the full holding); read `isLocked` per leg for the
    ///        claimable-vs-locked breakdown. `false` for every adapter except withdrawal-queue / cooldown legs.
    /// @param positionInstanceId OPTIONAL EPHEMERAL per-item coordinate as a `bytes32` — a Uniswap V3 / PancakeSwap V3
    ///        NFT id, a withdrawal/exit request id, or a StakeWise exit ticket (each a `uint256` widened to `bytes32`).
    ///        `bytes32(0)` for adapters with no per-item granularity. It is the SOLE ephemeral identity field, by
    ///        design: the **stable** reconciliation key
    ///        `(chainId, protocolSubId, positionId, balanceAsset.asset, positionKind)` deliberately EXCLUDES it,
    ///        so the legs of one anchor sum and identity survives item churn. A consumer that wants per-item
    ///        granularity MAY append `positionInstanceId` to the key — gaining one position per item, at the cost of an
    ///        **ephemeral** key (it blinks in/out as items are minted/burned/claimed). Never use it for stable
    ///        identity. (Stable sub-distinguishers like an Aave reserve are NOT here — they live in `balanceAsset`.)
    ///        Typed as `bytes32` (not `bytes`): every current coordinate is a single `uint256`, and a value type keeps
    ///        the position-building/copy loops under the via_ir stack limit.
    struct PositionBalance {
        Asset balanceAsset;
        address balanceAdapter;
        uint256 amount;
        bool isDebt;
        bytes32 protocolBrand;
        bytes32 protocolId;
        bytes32 protocolSubId;
        bytes positionId;
        PositionKind positionKind;
        bool isLocked;
        bytes32 positionInstanceId;
    }

    /// @notice Enriched position including pricing and quote-currency value.
    /// @dev Returned by getAccountPositions and getAccountPositionsForAsset.
    /// @param balanceAsset Asset metadata from registry (canonical symbol/decimals).
    /// @param balanceAdapter Adapter that reported the balance.
    /// @param amount Balance magnitude (positive); sign implied by isDebt.
    /// @param isDebt True if debt, false if credit.
    /// @param quoteAsset Quote currency for value (e.g. USD when address(0)).
    /// @param value Value in quote asset (negative for debt).
    /// @param price Price used (e.g. USD per unit of asset).
    /// @param priceDecimals Decimals of price.
    /// @param stale True if the price was stale at query time.
    /// @param protocolBrand `keccak256` protocol brand slug (broadest grouping). Copied from PositionBalance.
    /// @param protocolId `keccak256` broad ecosystem slug (grouping). Copied from PositionBalance.
    /// @param protocolSubId `keccak256` specific protocol-product slug (identity-key component). Copied from PositionBalance.
    /// @param positionId ABI-encoded position identifier. Copied from PositionBalance.
    /// @param positionKind Semantic discriminator. Copied from PositionBalance.
    /// @param isLocked True if the leg is not withdrawable now (pending/cooling). Copied from PositionBalance.
    /// @param positionInstanceId Ephemeral per-item coordinate (NFT/request/ticket), or empty. Copied from
    ///        PositionBalance; excluded from the stable identity key. See PositionBalance.
    struct Position {
        Asset balanceAsset;
        address balanceAdapter;
        uint256 amount;
        bool isDebt;
        Asset quoteAsset;
        int256 value;
        int256 price;
        uint8 priceDecimals;
        bool stale;
        // True if the quote asset's own price feed was stale. When true, `value` is in USD (8dp) even though
        // `quoteAsset` is non-zero — the quote conversion was skipped. Mirrors NAV.quoteAssetStale ([9]/S2).
        bool quoteAssetStale;
        bytes32 protocolBrand;
        bytes32 protocolId;
        bytes32 protocolSubId;
        bytes positionId;
        PositionKind positionKind;
        bool isLocked;
        // Ephemeral per-item coordinate copied from PositionBalance (NFT id / request id / ticket as bytes32).
        // bytes32(0) when none. Display/granularity only — excluded from the stable identity key. See PositionBalance.
        bytes32 positionInstanceId;
        // True if the asset's primary price diverged from its monitor feeds beyond the configured tolerance (or,
        // for stablecoins, from the $1 peg). A pricing-quality signal, NOT a validity/staleness flag: `price` and
        // `value` are still populated from the primary. Consumers (e.g. the sub/redeem processor) decide how to react.
        // APPENDED (not inserted mid-struct) so an in-place UUPS upgrade doesn't shift existing fields' ABI offsets.
        bool irregular;
        // True if the quote (unit-of-account) asset's own primary diverged from its monitors — the divergence
        // counterpart to `quoteAssetStale`. Always false for a USD quote.
        bool quoteAssetIrregular;
    }

    /// @notice Position enriched with human-readable display labels.
    /// @dev ⚠️ **NEITHER `protocolName` NOR ANY element of `labels` is necessarily the adapter's own value.**
    ///      `AssetKindRegistry` holds an optional per-ADAPTER protocol name plus a per-ADAPTER, per-SEGMENT `labels`
    ///      override, and {PriceFeedLib.toVerbose} applies both in preference to the adapter's reply.
    ///
    ///      ⚠️ **Two earlier revisions of this line were narrower than the code, in the same direction each time.**
    ///      The first said the computed leaf was never overridable; the second said only `labels[0]` was. Both are now
    ///      false: {IAssetKindRegistry.setAdapterLabels} writes at ANY index, bounded only by
    ///      `min(reply.length, override.length)` — so the honest statement is that a segment comes from the adapter
    ///      **unless an operator overrode that index**, and `""` at an index is how an operator declines to.
    ///
    ///      What the override CANNOT do is change the array's LENGTH: it never writes past the adapter's own reply and
    ///      never extends it, so `labels.length` is always the adapter's answer. (The one exception is
    ///      `getAdapterDisplayInfo`, whose empty-reply case is deliberately grown — see
    ///      `PriceFeedLib.adapterDisplayInfo`.)
    ///
    ///      Which segments an operator SHOULD write is a property of the adapter, not of this struct;
    ///      `src/balances/BALANCE_ADAPTERS.md` §6.2 carries the per-adapter sweep, and
    ///      `ERC20DefaultBalanceAdapter` is the one adapter that must not be overridden at all (its single element is
    ///      the computed token symbol, not a category). `AdapterLabelOverrides.t.sol
    ///      ::test_labelsOverride_onLeafOnlyAdapter_replacesTheLeaf_documentedHazard` asserts that hazard.
    ///      Consumers must not treat these strings as identity in any case; see {IPositionDescribable}.
    /// @dev Returned by verbose read methods. Labels are sourced from the adapter's `IPositionDescribable`
    ///      implementation (`positionLabels(positionId)`, via a fail-open staticcall) and are empty otherwise. MUST NOT
    ///      be used for identity, indexing, or reconciliation — use the typed fields on `position` for those purposes.
    struct VerbosePosition {
        Position position;
        string protocolName; // e.g. "Aave V3", "Morpho"
        // Ordered display hierarchy BELOW the protocol, leaf last (arbitrary depth, may be empty), e.g.
        // ["Market", "wstETH/USDC"] or ["AMM Liquidity Pool", "WETH/USDC 0.05%"]. Full breadcrumb = [protocolName,
        // ...labels]. Sourced from IPositionDescribable.positionLabels(positionId); display only. The ephemeral
        // per-item id (NFT/request/ticket) is NOT here — it is the typed `position.positionInstanceId` field.
        string[] labels;
    }

    /// @notice NAV snapshot bundled with a full verbose position breakdown.
    // forge-lint: disable-next-line(pascal-case-struct)
    struct VerboseNAV {
        NAV nav;
        VerbosePosition[] positions;
    }

    /// @notice NAV snapshot for an account in a given quote currency.
    /// @param value Total portfolio value in quoteAsset (can be negative if net debt).
    /// @param quoteAsset Quote currency; address(0) denotes USD.
    /// @param timestamp Block timestamp of the reading.
    /// @param stalePriceAssets Assets whose prices were stale at query time.
    /// @param irregularPriceAssets Assets whose primary price diverged from their monitor feeds beyond tolerance
    ///        (or, for stablecoins, from the $1 peg) at query time. A pricing-quality signal, not a staleness flag —
    ///        `value` is still computed from the primary prices. Consumers decide how to react.
    /// @param sequencerDown True if the L2 sequencer was down or in grace period (L2 only).
    /// @param quoteAssetStale True if the quote asset's own price feed was stale. When true the value field
    ///        is in USD (fallback) even though quoteAsset is non-zero — callers must check this flag before
    ///        interpreting value as being in the requested quote currency.
    /// @param monitorsUnhealthyPriceAssets Assets that **have monitor feeds configured but where none of them was
    ///        readable** at query time — every monitor stale, reverting, or reporting a non-positive price. For these
    ///        the divergence check silently did not run: `divergenceBps` is 0 because the arithmetic never executed,
    ///        not because the prices agreed, so absence from `irregularPriceAssets` says nothing about them. Without
    ///        this list "checked and clean" and "checked by nothing that answered" are the same bytes.
    ///
    ///        **This is NOT the "no monitors configured" case.** That is a static configuration property, derivable
    ///        off-chain from **`getMonitorFeedCount(asset) == 0` alone**, and it is deliberately excluded here — an
    ///        asset with nothing configured never appears in this list however long it goes unchecked. What this
    ///        reports is strictly a *runtime* failure of monitors that exist.
    ///
    ///        Do NOT additionally require `getAssetPricing(asset).divergenceToleranceBps == 0` for that derivation:
    ///        the conjunction is UNSATISFIABLE for any asset that ever had a monitor. `_setDivergenceTolerance`
    ///        rejects 0, so once a tolerance is set it can never be returned to zero, while `removeMonitorFeed`
    ///        leaves the tolerance untouched — so an asset whose monitors were all REMOVED has count 0 and a
    ///        non-zero tolerance, and an AND-recipe would silently never flag it. The tolerance only returns to 0
    ///        via full asset unregistration (`_removeAllMonitorFeeds`), by which point the asset is gone anyway.
    ///
    ///        Assets whose own primary is unusable are also excluded — stale feed, sequencer down, or a primary whose
    ///        8-decimal normalisation degenerates to zero. In all of those the check was suppressed by the PRIMARY
    ///        rather than by the monitors, `stalePriceAssets` already reports the staleness cases, and naming the
    ///        monitors would point an operator at the wrong contract. Stablecoins with a non-zero `pegToleranceBps`
    ///        may appear here and still be peg-checked — the peg guard is monitor-independent — so this flags the
    ///        loss of the *divergence* check, not necessarily of all checks.
    ///
    ///        **Scope: assets this account holds positions in**, like `stalePriceAssets` and `irregularPriceAssets`.
    ///        It is built from the assets the account's positions touched, NOT from the whole registry, so absence
    ///        means "monitors healthy **or** no position held". A consumer reconciling against the registry-wide
    ///        per-asset view (`getPriceDivergence(asset).monitorFeedCount == 0` is the equivalent there) will see
    ///        differences that are this scoping, not a defect. Note also that `healthCheck()` — which DOES iterate
    ///        the whole registry — deliberately does not carry this array: `NAVCalculator` is 68 bytes from the
    ///        EIP-170 limit, so widening that return was not affordable. `Position.irregular` on
    ///        `getAccountPositions` likewise retains the original ambiguity, with no `NAV` struct alongside to join
    ///        against; use `getAccountNavVerbose` (whose `VerboseNAV` embeds the `NAV`) if you need both.
    // forge-lint: disable-next-line(pascal-case-struct)
    struct NAV {
        int256 value;
        Asset quoteAsset;
        uint64 timestamp;
        Asset[] stalePriceAssets;
        bool sequencerDown;
        bool quoteAssetStale;
        // APPENDED (not inserted mid-struct) so an in-place UUPS upgrade doesn't shift existing fields' ABI offsets.
        Asset[] irregularPriceAssets;
        // True if the quote (unit-of-account) asset's own primary diverged from its monitors beyond tolerance —
        // the divergence counterpart to `quoteAssetStale`. Always false for a USD quote (no quote feed).
        //
        // DECLARED GAP, deliberate: there is no `quoteAssetMonitorsUnhealthy` counterpart to
        // `monitorsUnhealthyPriceAssets` below. For a non-USD quote whose own monitors have ALL gone unreadable, this
        // flag is false for want of data — exactly the ambiguity that array exists to close — and nothing surfaces it.
        //
        // Why it was not added, in order of weight. (1) **Nothing in this repository's configuration exercises it**:
        // `nav-config/assets-and-price-feeds/{1,42161,8453,100}.json` contain no quote keys, and `quoteAsset` is a
        // CALLER-supplied parameter defaulting to USD (`address(0)`), not stored config — so the gap is reachable only
        // by a caller that opts into a non-USD quote. (2) `NAVCalculator` has 68 bytes of EIP-170 headroom; a further
        // struct member plus its computation plausibly exceeds that, and spending the last of the margin on an
        // unexercised path would leave nothing for an urgent fix — after which the next change would need a new proxy
        // rather than an upgrade.
        //
        // Limit of that evidence: it is a claim about THIS repository only. A downstream consumer (share layer,
        // portal, agents, subgraphs) could pass a non-zero `quoteAsset`, which cannot be verified from here. If one
        // does, this gap is worth the bytes and should be revisited.
        //
        // Mitigation meanwhile: a caller using a non-USD quote should read `getPriceDivergence(quoteAsset)` and treat
        // `monitorFeedCount == 0` alongside a usable primary as exactly this condition.
        bool quoteAssetIrregular;
        // APPENDED for the same reason as `irregularPriceAssets` above. This redeploy uses a NEW proxy rather than an
        // in-place upgrade, so nothing forced the append — but moving existing consumers' ABI offsets for a change
        // that did not need to move them is gratuitous, so the convention is honoured anyway.
        Asset[] monitorsUnhealthyPriceAssets;
    }

    /// @notice One SLICE of an account's NAV: the same snapshot as {NAV} but covering only the balance adapters
    ///         named in the request, plus the list of adapters it actually covered.
    /// @dev Returned by {getAccountNavForAdapters}. Deliberately a DISTINCT type from {NAV}, not a reuse of it,
    ///      and that is the whole safety property of this API: a partial result must not be assignable, passable
    ///      or decodable where a complete NAV is expected. A `PartialNAV` that type-checked as a `NAV` would let a
    ///      caller hand one slice to a consumer that believes it holds the whole portfolio — the exact silent
    ///      under-report pagination exists to make impossible. The cost is that a caller must reassemble
    ///      explicitly; that cost is the point.
    ///
    ///      **Field order mirrors {NAV} exactly for its first eight fields, including NAV's own appended ones, so
    ///      a decoder written for `NAV` maps 1:1 onto this struct's prefix.** `adaptersCovered` is appended last.
    ///      Keep it that way: any future field goes at the END of this struct (see the APPENDED note on {NAV}),
    ///      and any field appended to {NAV} must be appended here too — BEFORE `adaptersCovered` if the prefix
    ///      correspondence is to survive, which means moving `adaptersCovered` and accepting the ABI shift, or
    ///      accepting that the prefix correspondence ends there. Prefer the latter: shifting a field's offset in a
    ///      struct a live off-chain reassembler decodes is worse than losing a documentation convenience.
    /// @param value Net value of THIS SLICE's positions in `quoteAsset`, signed (negative if the slice is net
    ///        debt). **This is the one field that sums.** Debt legs are already negative, and prices are per-asset
    ///        and independent of which adapter reported the position, so the arithmetic is exact: summing `value`
    ///        over a partition of `getAllAdapters()` reproduces `getAccountNav().value` bit-for-bit, with no
    ///        tolerance and no rounding slack. Every other field below does NOT sum.
    ///
    ///        **One precondition, and it is not theoretical: no adapter may have been GAS-STARVED in either read.**
    ///        Some adapters fail open inside their own frame and return SUCCESSFULLY having dropped legs —
    ///        `AssistedCoordCache._collect` isolates each cached coordinate behind an UNCAPPED
    ///        `try this.valueCoordSelf(…)`/`catch {}`, and `ERC20DefaultBalanceAdapter` records 0 for an asset whose
    ///        `balanceOf` staticcall fails. Nothing upstream can see that; see the "Scope, stated plainly" note on
    ///        `PriceFeedLib._getAdapterPositions`.
    ///
    ///        The per-adapter stipend is a share of what the READ still holds at the moment that adapter is reached,
    ///        and `computeNav` scans the supplied array IN ORDER. So the stipend depends on **slice composition AND
    ///        ORDERING**, not merely on how few adapters a slice names. Both directions are reachable:
    ///        a singleton slice gives its adapter more gas than the full scan did and may value legs the complete
    ///        read dropped; a multi-adapter slice that places an adapter BEHIND an expensive one can starve it below
    ///        what the complete read gave it. The second case is not hypothetical — `getAllAdapters()[0]` is
    ///        permanently `ERC20DefaultBalanceAdapter` (pushed in `initialize`, unremovable, and swap-and-pop only
    ///        ever fills a hole at the removed index, which index 0 can never be), so the complete read already
    ///        hands it the largest stipend any read can and **a slice can only ever give it less.**
    ///
    ///        Which read ends up LARGER is a separate question from which one was starved. The sign of the skew is
    ///        set by the `isDebt` of the dropped legs, not by which read dropped them: a dropped credit leg lowers
    ///        that read, a dropped debt leg raises it.
    ///
    ///        **Therefore: do NOT assume a direction, and do not pick by magnitude either.** "Trust the slice" is
    ///        wrong, and so is "take the lower" — with today's credit-only absorbers starvation can only LOWER a
    ///        read, so "take the lower" would select the starved number every time the two disagree. Nor is
    ///        under-reporting a safe default: a processor pricing shares off a low NAV over-issues to a subscriber.
    ///        Reconcile before publishing either. If a choice must be automated, key it to the SIGNAL rather than
    ///        the magnitude — prefer the read that did not raise {AdapterGasExhausted} / {InstanceGasExhausted}, and
    ///        publish neither if the two disagree while neither raised one. And do not treat the two reads agreeing
    ///        as a health check that passes silently — they agree when nothing was starved, which is the common case
    ///        and therefore uninformative.
    ///
    ///        The property that would keep a starved read from OVER-reporting is: **no adapter emits an
    ///        `isDebt == true` leg from behind ANY fail-open read.** "Any" is load-bearing — a gas CAP makes this
    ///        worse, not better, because an uncapped read can at least be rescued by supplying more gas whereas a
    ///        capped one (`StaticCallLib.PROBE_GAS`) is starved by the cap and drops unconditionally.
    ///        **Three shipped adapters currently break it** — `EulerVaultsMetaBalanceAdapter._safeDebt` (capped
    ///        probe, supply leg survives), `FluidVaultLib.aggregate` (uncapped, drops one NFT's supply and borrow),
    ///        and `GearboxV3CreditAccountsMetaBalanceAdapter._appendBorrow` (narrowly mitigated by a
    ///        `_debtReportable` gate evaluated before the gas is drained). None is introduced or fixed here, and the
    ///        first two over-report the COMPLETE read as much as a slice. See `docs/howto/read-nav-in-slices.md`.
    /// @param quoteAsset Quote currency; `address(0)` denotes USD. Identical in every slice (it is the caller's
    ///        argument), so a reassembler can assert it rather than combine it.
    /// @param timestamp Block timestamp of THIS call. A reassembler MUST check that every slice carries the same
    ///        value: differing timestamps mean the slices were read at different blocks, and a NAV assembled from
    ///        positions priced at different blocks is not a NAV of anything. See the caller contract on
    ///        {getAccountNavForAdapters}.
    /// @param stalePriceAssets Assets whose prices were stale, **restricted to the assets this slice's positions
    ///        touched**. NOT a portfolio-wide list: an asset that is stale but only held through an adapter in
    ///        another slice is absent here and present there. Must be UNIONED across slices, and the union
    ///        de-duplicated — two slices holding the same stale asset each report it.
    /// @param sequencerDown True if the L2 sequencer was down or in grace period (L2 only). Derived from this
    ///        contract's sequencer config, not from the slice, so it is the same in every slice — but it is still
    ///        per-slice data and a caller that reads it on only one slice is relying on that invariant rather than
    ///        checking it. OR it across slices.
    /// @param quoteAssetStale True if the quote asset's own price feed was stale, in which case `value` is in USD
    ///        (8dp) despite `quoteAsset` being non-zero. Also invariant across slices (it depends on the quote
    ///        asset, not the adapters) — which makes it *more* dangerous to ignore, not less: if it is true, every
    ///        slice's `value` is in USD, and a reassembler that never looked will label a USD total with the
    ///        requested quote currency. OR it across slices.
    /// @param irregularPriceAssets Assets whose primary price diverged from their monitor feeds beyond tolerance
    ///        (or, for stablecoins, from the $1 peg), **restricted to the assets this slice touched**. Same
    ///        per-slice restriction and same union-and-dedupe requirement as `stalePriceAssets`. This is the depeg
    ///        signal; a slice-local read of it is a slice-local depeg picture.
    /// @param quoteAssetIrregular True if the quote asset's own primary diverged from its monitors. Invariant
    ///        across slices, always false for a USD quote. OR it across slices.
    /// @param monitorsUnhealthyPriceAssets Assets with monitors configured but none readable at query time,
    ///        **restricted to the assets this slice touched**. Same per-slice restriction and same
    ///        union-and-dedupe requirement as `stalePriceAssets` and `irregularPriceAssets` — it is built from the
    ///        same per-asset cache, so the semantics carry over unchanged. Reported on the paginated read
    ///        deliberately: a caller paginates because the complete read does not fit one `eth_call`, i.e. for the
    ///        largest accounts, and those are exactly the ones a monitoring consumer watches — omitting it here
    ///        would hide the signal from the accounts that most need it. A slice-local read is a slice-local
    ///        picture of monitor health, and a union over every slice is required before concluding an asset is
    ///        covered. See {NAV.monitorsUnhealthyPriceAssets} for what the condition does and does not mean.
    /// @param adaptersCovered The adapters this slice actually queried — element-for-element identical to the
    ///        `adapters` argument, order included, because the call reverts rather than silently dropping, adding
    ///        or reordering one. That makes it a machine-checkable record rather than a restatement of the input:
    ///        the guarantee is that nothing came between the request and the scan. Its purpose is reassembly
    ///        verification: concatenate it
    ///        across every slice and compare against `getAllAdapters()`. A missing address means the assembled NAV
    ///        is short by that adapter's positions; a repeated one means it is double-counted. Neither is
    ///        detectable from `value` alone, because a short NAV is a perfectly plausible number.
    // forge-lint: disable-next-line(pascal-case-struct)
    struct PartialNAV {
        int256 value;
        Asset quoteAsset;
        uint64 timestamp;
        Asset[] stalePriceAssets;
        bool sequencerDown;
        bool quoteAssetStale;
        Asset[] irregularPriceAssets;
        bool quoteAssetIrregular;
        // Appended after the {NAV}-mirroring prefix — see the struct-evolution note above. No longer the LAST
        // member: `monitorsUnhealthyPriceAssets` was appended after it, deliberately, so this field keeps its ABI
        // offset. New members go after that one, not here.
        address[] adaptersCovered;
        // Appended after `adaptersCovered` rather than beside its {NAV} siblings: keeping `adaptersCovered` at its
        // existing offset matters more than keeping this struct's prefix a positional mirror of {NAV}, which it stops
        // being the moment {NAV} grows. The two structs stay deliberately DISTINCT types — a partial result must not
        // be decodable where a complete one is expected — so mirroring is a convenience, never a guarantee.
        Asset[] monitorsUnhealthyPriceAssets;
    }

    /// @notice Price data for the freshest non-stale feed selected for an asset.
    /// @dev When multiple feeds are registered, these fields describe the winning (freshest) feed.
    /// When all feeds are stale, fields describe the first registered feed and stale == true.
    /// @param priceFeed Address of the selected price feed contract.
    /// @param priceType Feed type (Chainlink, Custom, Redstone, or API3).
    /// @param price Current price (e.g. USD per unit); 0 when stale.
    /// @param decimals Decimals of the selected feed's output.
    /// @param chainlinkHeartbeat Staleness window (seconds) of the reported feed. For Chainlink/Redstone/API3 this is
    ///        the selected feed's configured heartbeat. For Custom feeds it is the GOVERNING leg's heartbeat — the
    ///        underlying Chainlink leg closest to its own staleness limit — paired with `updatedAt` below. A Custom
    ///        feed that successfully reports no trackable Chainlink leg gives 0; if its freshness read REVERTS this
    ///        field retains the registered config heartbeat (only `updatedAt` falls back to 0), so a non-zero value
    ///        here does not by itself imply a successful read. See ICustomPriceFeed.governingFeedFreshness.
    /// @param updatedAt Last-update timestamp of the reported feed. For Chainlink/Redstone/API3 this is the selected
    ///        feed's `latestRoundData().updatedAt`. For Custom feeds it is the GOVERNING leg's `updatedAt` — a real,
    ///        matched pair with `chainlinkHeartbeat` above. 0 when the feed has no push timestamp or the read reverts.
    /// @dev ADVISORY PAIR — `updatedAt`/`chainlinkHeartbeat` describe only the reported oracle leg's push freshness.
    ///      `stale` (and `sequencerDown`) is the AUTHORITATIVE staleness verdict: it also folds in the rate answer's
    ///      validity, the L2 sequencer state, and the feed's own configured heartbeat gate — none of which the pair
    ///      can express, so the pair can read "fresh" (age < heartbeat) while `stale` is true. Consumers MUST gate on
    ///      `stale`; never recompute a fresh/stale decision from `(updatedAt, chainlinkHeartbeat)` alone.
    /// @param stale True if all feeds are stale or the L2 sequencer is down.
    /// @param sequencerDown True if L2 sequencer is down (L2 only).
    /// @param healthyFeedCount Number of registered feeds that passed all staleness gates on this read.
    ///        A value below the total registered feed count signals partial redundancy collapse and
    ///        should trigger off-chain alerting.
    /// @param irregular True if the primary price diverged from the worst-case (furthest) healthy monitor feed
    ///        beyond the configured divergence tolerance, or (stablecoins) from the $1 peg beyond the peg tolerance.
    /// @param divergenceBps Worst-case basis-point gap between the primary price and any single healthy monitor
    ///        price (0 when there are no healthy monitors or the primary is stale).
    /// @param monitorFeedCount Number of healthy monitor feeds that contributed to the divergence computation.
    struct PriceFeedData {
        address priceFeed;
        IPrices.PriceType priceType;
        int256 price;
        uint8 decimals;
        uint256 chainlinkHeartbeat;
        uint256 updatedAt;
        bool stale;
        bool sequencerDown;
        uint256 healthyFeedCount;
        bool irregular;
        uint256 divergenceBps;
        uint256 monitorFeedCount;
    }

    //
    // Events
    //

    /// @notice Emitted when the Chainlink L2 sequencer uptime feed is updated.
    /// @param oldChainlinkUptimeFeed Previous uptime feed address.
    /// @param newChainlinkUptimeFeed New uptime feed address.
    event ChainlinkUptimeFeedUpdated(address indexed oldChainlinkUptimeFeed, address indexed newChainlinkUptimeFeed);

    /// @notice Emitted when the L2 sequencer grace period is updated.
    /// @param oldSequencerGracePeriod Previous grace period in seconds.
    /// @param newSequencerGracePeriod New grace period in seconds.
    event L2SequencerGracePeriodUpdated(uint256 oldSequencerGracePeriod, uint256 newSequencerGracePeriod);

    /// @notice Emitted when an asset is registered.
    /// @param asset Registered asset address.
    /// @param decimals Asset decimals.
    event AssetRegistered(address indexed asset, uint8 decimals);

    /// @notice Emitted when an asset is unregistered.
    /// @param asset Unregistered asset address.
    event AssetUnregistered(address indexed asset);

    //
    // Errors
    //

    /// @notice Thrown when the L2 sequencer uptime feed is not set but the grace period is being updated.
    error UptimeFeedNotSet();

    //
    // Mutating functions (require MANAGER role)
    //

    /// @notice Registers an asset and sets its price feed.
    /// @dev Fetches decimals/symbol from ERC20 or uses native token symbol. Adds asset to default adapter inclusion list.
    /// @param asset Asset address to register (cannot be zero).
    /// @param priceFeed Price feed address (cannot be zero).
    /// @param priceType Chainlink, Custom, Redstone, or API3.
    /// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero for all types).
    function registerAsset(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
        external;

    /// @notice Adds a price feed for an already registered asset, or UPDATES the heartbeat of one already there.
    /// @dev UPSERTS. If `priceFeed` is already registered for `asset`, this REWRITES its `chainlinkHeartbeat`
    ///      in place and emits {IPrices-PriceFeedHeartbeatUpdated}; it does NOT revert, and it does NOT emit a
    ///      PriceFeedAdded/PriceFeedRemoved pair. Do not build idempotency on a duplicate reverting.
    ///      Reverts: PriceFeedAlreadyRegistered only when the heartbeat is UNCHANGED; PriceFeedTypeImmutable
    ///      when `priceType` differs from the stored one (a feed's type is identity, not configuration);
    ///      PriceFeedDecimalsMismatch when the feed's live decimals no longer match the stored value.
    /// @param asset Registered asset address.
    /// @param priceFeed Price feed address (cannot be zero).
    /// @param priceType Chainlink, Custom, Redstone, or API3.
    /// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero for all types).
    function addOrModifyPriceFeed(
        address asset,
        address priceFeed,
        IPrices.PriceType priceType,
        uint256 chainlinkHeartbeat
    ) external;

    /// @notice Adds a monitor (divergence-only) feed for an asset. Monitor feeds NEVER price the NAV; they are read
    ///         only to detect divergence between the primary price and the worst-case (furthest) healthy monitor price.
    /// @dev Requires the asset's divergence tolerance to be set first (>0), else reverts DivergenceToleranceRequired.
    ///      Monitor feeds must report NAV_DECIMALS decimals (else MonitorFeedDecimalsMismatch). Reverts
    ///      MonitorFeedAlreadyRegistered only when the heartbeat is UNCHANGED (this UPSERTS an existing monitor's heartbeat, emitting MonitorFeedHeartbeatUpdated).
    /// @param asset Registered asset address.
    /// @param priceFeed Monitor feed address (cannot be zero).
    /// @param priceType Chainlink, Custom, Redstone, or API3.
    /// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero).
    function addMonitorFeed(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
        external;

    /// @notice Sets the asset's divergence tolerance in basis points (must be in (0, 10000]).
    /// @param asset Registered asset address.
    /// @param divergenceToleranceBps Max worst-case primary-vs-any-single-monitor gap before the asset is flagged irregular.
    function setDivergenceTolerance(address asset, uint32 divergenceToleranceBps) external;

    /// @notice Sets the asset's stablecoin peg tolerance in basis points (in [0, 10000]; 0 disables the peg guard).
    /// @param asset Registered asset address.
    /// @param pegToleranceBps Max deviation of the primary price from $1 before the asset is flagged irregular.
    function setPegTolerance(address asset, uint32 pegToleranceBps) external;

    /// @notice Registers one or more **non-meta** balance adapters in the global registry in a single call.
    /// @dev Reverts with InvalidArguments if the list is empty or contains a zero address, DuplicateBalanceAdapter
    ///      if any adapter is already registered, InvalidBalanceAdapter if any adapter does not implement
    ///      IBalanceAdapter, and MetaAdapterNotAllowed if any adapter implements IMetaBalanceAdapter (meta-adapters
    ///      must use addMetaBalanceAdapter). The batch is all-or-nothing.
    /// @param adapters Adapter addresses (each must implement IBalanceAdapter and NOT IMetaBalanceAdapter).
    function addBalanceAdapters(address[] calldata adapters) external;

    /// @notice Registers a meta-adapter (ADR 0010) and seeds its instance set atomically, in one MANAGER call.
    /// @dev The adapter must implement both IBalanceAdapter and IMetaBalanceAdapter (else InvalidBalanceAdapter /
    ///      NotMetaAdapter). Reverts InvalidArguments on a zero adapter, DuplicateBalanceAdapter if already
    ///      registered, and DuplicateMetaInstance on a repeated coordinate. An empty instance list is allowed
    ///      (registers the meta-adapter with no instances yet; seed later via addMetaInstances). Plain adapters use
    ///      addBalanceAdapters; subsequent instance changes use addMetaInstances / removeMetaInstances.
    /// @param adapter The meta-adapter address.
    /// @param instances Instance coordinates to seed (e.g. vault addresses widened to bytes32, or raw bytes32 IDs).
    function addMetaBalanceAdapter(address adapter, bytes32[] calldata instances) external;

    /// @notice Removes the price feed at the given index. Reverts if it is the last feed (CannotRemoveLastFeed).
    /// @param asset Registered asset address.
    /// @param index Index into the asset's feed array.
    function removePriceFeedAt(address asset, uint256 index) external;

    /// @notice Removes the price feed with the given address. Reverts if not found or last feed.
    /// @param asset Registered asset address.
    /// @param priceFeed Feed address to remove.
    function removePriceFeed(address asset, address priceFeed) external;

    /// @notice Removes the monitor feed at the given index. Monitor feeds are optional, so the last one may be removed.
    /// @param asset Registered asset address.
    /// @param index Index into the asset's monitor feed array.
    function removeMonitorFeedAt(address asset, uint256 index) external;

    /// @notice Removes the monitor feed with the given address. Reverts MonitorFeedNotFound if absent.
    /// @param asset Registered asset address.
    /// @param priceFeed Monitor feed address to remove.
    function removeMonitorFeed(address asset, address priceFeed) external;

    /// @notice Removes one or more balance adapters from the global registry in a single call.
    /// @dev Reverts with InvalidArguments if the list is empty. The batch is all-or-nothing — if any adapter is
    ///      not registered (or is the default ERC20 adapter) the whole call reverts.
    /// @param adapters Adapter addresses to remove (none may be the default ERC20 adapter).
    function removeBalanceAdapters(address[] calldata adapters) external;

    /// @notice Adds instance coordinates to a registered meta-adapter's queried set.
    /// @dev This is the governed "which instances to query" registry — adapters themselves stay immutable.
    ///      All-or-nothing: reverts DuplicateMetaInstance if any coordinate is already present or repeated within
    ///      the batch (a duplicate would double-count NAV), InvalidArguments on an empty list, InvalidBalanceAdapter
    ///      if the adapter is not registered, and NotMetaAdapter if the adapter does not implement
    ///      IMetaBalanceAdapter. Coordinate values are otherwise not validated; a
    ///      malformed/unknown coordinate is isolated per-instance by the adapter's fan-out (cannot zero the batch).
    /// @param adapter Registered meta-adapter address.
    /// @param instances Instance coordinates to add (e.g. vault addresses widened to bytes32).
    function addMetaInstances(address adapter, bytes32[] calldata instances) external;

    /// @notice Removes instance coordinates from a registered meta-adapter's queried set.
    /// @dev All-or-nothing: reverts MetaInstanceNotFound if any coordinate is not present (a coordinate repeated
    ///      within the batch also reverts), InvalidArguments on an empty list, InvalidBalanceAdapter if the adapter
    ///      is not registered, and NotMetaAdapter if the adapter does not implement IMetaBalanceAdapter. Order is
    ///      not preserved.
    /// @param adapter Registered meta-adapter address.
    /// @param instances Instance coordinates to remove.
    function removeMetaInstances(address adapter, bytes32[] calldata instances) external;

    /// @notice Excludes an asset from the default adapter so wallet balances are not reported for it.
    /// @param asset Registered asset address.
    function excludeAssetFromDefaultAdapter(address asset) external;

    /// @notice Includes an asset in the default adapter so wallet balances are reported again.
    /// @param asset Registered asset address.
    function includeAssetInDefaultAdapter(address asset) external;

    /// @notice Unregisters an asset: unsets price feed, removes from default adapter list, and removes from registry.
    /// @param underlyingAsset Asset address to unregister.
    function unregisterAsset(address underlyingAsset) external;

    /// @notice Sets the Chainlink L2 sequencer uptime feed (use address(0) on L1).
    /// @dev Requires DEFAULT_ADMIN_ROLE (same privilege level as upgrades). Disabling sequencer-uptime
    ///      detection on an L2 is equivalent in impact to an upgrade, so MANAGER access is not sufficient.
    /// @param newChainlinkL2UptimeFeed New uptime feed address.
    function setChainlinkL2SequencerUptimeFeed(address newChainlinkL2UptimeFeed) external;

    /// @notice Sets the L2 sequencer grace period. Reverts UptimeFeedNotSet if the uptime feed is not set, or
    ///         InvalidArguments if the period is below 1 hour.
    /// @param newSequencerGracePeriod Grace period in seconds (must be at least 1 hour).
    function setChainlinkL2SequencerGracePeriod(uint256 newSequencerGracePeriod) external;

    //
    // View functions — registry
    //

    /// @notice Returns the number of registered assets (alias for getAssetCount).
    /// @return Number of registered assets.
    function assetCount() external view returns (uint256);

    /// @notice Returns whether an asset is registered.
    /// @param asset Asset address to check.
    /// @return True if registered.
    function isAssetRegistered(address asset) external view returns (bool);

    /// @notice Returns all registered assets with metadata.
    /// @dev **O(N), and it is the wrong tool for resolving ONE asset** — use {getRegisteredAsset} for that. This
    ///      copies the entire registry across the ABI boundary, so a caller that resolves M tokens by calling this
    ///      M times pays M full fetches. That pattern measured **6,274,562 gas for a single 50-token Balancer
    ///      instance at 43 registered assets** (18.4M at 100), and it is super-linear rather than linear because
    ///      each call allocates a fresh N-element array that is never freed, so memory expansion grows with the
    ///      square of the token count. At that scale it exhausts the per-adapter gas stipend and turns a NAV read
    ///      into a REVERT.
    /// @return assets Array of Asset (address, symbol, decimals).
    function getRegisteredAssets() external view returns (Asset[] memory assets);

    /// @notice Resolves ONE asset's registry metadata in O(1), without reverting when it is absent.
    /// @dev The single-asset counterpart to {getRegisteredAssets}, added because balance adapters resolve tokens
    ///      one at a time and the array getter makes that quadratic (see its docs for the measured figures).
    ///      Backed by the 1-based `_assetIndex` map the registry already maintains on register/unregister, so this
    ///      is a mapping load plus one array read — flat in the number of registered assets.
    ///
    ///      **Non-reverting by design, and that is the whole reason this is a new function rather than a widened
    ///      visibility on the existing internal lookup.** NAVCalculator's `_getRegisteredAsset` reverts
    ///      `AssetNotFound` for an unregistered asset, which is right for its callers but wrong here: "not
    ///      registered" is an ORDINARY, expected outcome on an adapter's emission path — the adapter simply skips
    ///      that leg. A reverting getter would turn every unregistered token an adapter happens to encounter into
    ///      a failed instance read, converting a skipped leg into a dropped position.
    /// @param asset The asset to resolve.
    /// @return assetInfo The registry entry. Zeroed (`address(0)`, `""`, `0`) when `found` is false — **check
    ///         `found`, do not infer absence from a zero `assetInfo.asset`**, since the two are only equivalent
    ///         while nothing zero-addressed can be registered.
    /// @return found True if `asset` is registered.
    function getRegisteredAsset(address asset) external view returns (Asset memory assetInfo, bool found);

    /// @notice Returns the number of registered assets.
    /// @return Number of registered assets.
    function getAssetCount() external view returns (uint256);

    /// @notice Returns the current implementation version (Initializable storage).
    /// @return Version number.
    function version() external view returns (uint64);

    //
    // View functions — NAV and positions
    //

    /// @notice Computes NAV for an account in the given quote currency.
    /// @param account Account address.
    /// @param quoteAsset Quote currency; address(0) for USD. Must have a price feed if not zero.
    /// @return nav NAV struct (value, quoteAsset, timestamp, stalePriceAssets, sequencerDown, quoteAssetStale).
    function getAccountNav(address account, address quoteAsset) external view returns (NAV memory nav);

    /// @notice Computes the NAV contribution of a CALLER-SUPPLIED SET of balance adapters, so an off-chain caller
    ///         can read a portfolio's NAV in slices and reassemble it.
    /// @dev Exists because {getAccountNav} scans every registered adapter in one `eth_call` and that cost grows
    ///      with the asset registry and the adapter set. Past a node's `eth_call` gas cap the complete read stops
    ///      returning anything at all — not a degraded NAV, no NAV — and there is no smaller question to ask.
    ///      This is that smaller question.
    ///
    ///      **A SET, NOT AN INDEX RANGE, AND THAT IS NOT A STYLE CHOICE.** `getAllAdapters()` is maintained with
    ///      swap-and-pop, so removing any adapter moves the LAST adapter into the removed one's index — always to a
    ///      LOWER index. A caller paging `[0,10)` then `[10,20)` across a governance removal therefore **silently
    ///      SKIPS** the moved adapter: it was at the tail, it lands in a slot the caller has already passed, and it
    ///      is never read. Both pages still look completely well-formed and the total is short by that adapter's
    ///      positions.
    ///
    ///      Precisely because elements only ever move DOWN, a removal cannot make an already-read adapter reappear
    ///      in a later page — so the hazard is a missed adapter, not a double-counted one. (An earlier version of
    ///      this note claimed a double-read; that is not reachable through either removal path.) Naming the adapters
    ///      removes the whole class rather than documenting it away.
    ///
    ///      ### The caller contract
    ///
    ///      **Canonical statement: `docs/howto/read-nav-in-slices.md`.** That document is the single source for the
    ///      reassembly rules, including the worked example and the gas-starvation precondition. What follows is the
    ///      short form, kept here because a consumer generating against this ABI may never open the repo — if the
    ///      two ever disagree, the how-to wins and this block is the bug.
    ///
    ///      Four obligations. The first two this function enforces; the last two it cannot see, and they are
    ///      where a reassembled NAV goes wrong.
    ///
    ///      1. **Every adapter must be registered and appear at most once** — else {AdapterNotRegistered} or
    ///         {DuplicateAdapterInSlice}. An empty list reverts {EmptyAdapterSlice}.
    ///      2. **The slice is queried as one atomic read**, so `value` is internally consistent.
    ///      3. **All slices MUST be read at the same block, and PINNING THE BLOCK NUMBER IN THE REQUEST is the only
    ///         real control.** Pass an explicit block number to every `eth_call` — not `latest`, which lets
    ///         successive calls land on different heads. Positions and prices both move between blocks, so slices
    ///         from different blocks sum to a number that was never any account's NAV, and the sum looks entirely
    ///         reasonable.
    ///
    ///         `PartialNAV.timestamp` is a **cross-check, not the check**, and it is deliberately described that way
    ///         here: equal timestamps do NOT imply the same block. Arbitrum Nitro mints blocks roughly every 250ms,
    ///         so consecutive blocks routinely share a `block.timestamp`, and this contract is deployed there. The
    ///         field therefore catches only the gross case (slices seconds apart) and is blind to the narrow one
    ///         (two blocks inside one second) — which is the case an unpinned paging loop actually produces. There
    ///         is no block number in `PartialNAV` to check instead, by choice: adding one would not fix an unpinned
    ///         caller, and pinning the request already does.
    ///      4. **The union of the slices must cover `getAllAdapters()` exactly once**, and
    ///         `PartialNAV.adaptersCovered` is how that is verified: concatenate it across slices and compare
    ///         against `getAllAdapters()` read at the same block. A missing adapter yields a NAV short by its
    ///         positions; a repeated one double-counts. Re-read `getAllAdapters()` at the pinned block rather than
    ///         trusting a cached list — the registry is governed and can change under a paging loop.
    ///
    ///      ### **Health flags do NOT sum. Ignoring them on ANY slice silently destroys a signal.**
    ///
    ///      `value` is the only field that composes by addition. **`stalePriceAssets`, `irregularPriceAssets` and
    ///      `monitorsUnhealthyPriceAssets` are restricted to the assets THIS slice's positions touched, and
    ///      `sequencerDown`, `quoteAssetStale` and `quoteAssetIrregular` are reported per slice. A caller that checks the flags on one slice, or on
    ///      the last slice, or on a slice it happened to keep, silently loses every staleness, depeg and
    ///      sequencer-down signal carried by the others — and gets a NAV number that looks fine.** That failure
    ///      shape is exactly what this repo's fail-open hardening work was for; it must not be reintroduced at the
    ///      reassembly boundary. **UNION the THREE asset arrays (de-duplicating: two slices holding the same stale
    ///      asset each report it) and OR the three booleans, across every slice, before treating the summed
    ///      `value` as usable.** The third array, `monitorsUnhealthyPriceAssets`, was appended later than this
    ///      instruction was first written — a reassembler that unions only two silently drops the monitor-health
    ///      signal, which is the falsely-reassuring direction and hits precisely the large accounts that must
    ///      paginate.
    ///
    ///      ### A meta-adapter is the atomic unit
    ///
    ///      A slice naming a meta-adapter includes **all** of that adapter's governed instances — every Aave V3
    ///      instance, every Morpho market, every Curve pool. There is no way to page WITHIN one meta-adapter
    ///      through this API, by design: the governed instance set is itself swap-and-pop mutable
    ///      (`addMetaInstances`/`removeMetaInstances`), so an instance-level range would carry the same
    ///      reordering hazard this signature exists to avoid, and an instance-level set would need the adapter to
    ///      accept a filter it does not have. So the finest slice available is one adapter. If a SINGLE
    ///      meta-adapter's read alone exceeds the gas budget, pagination does not help and the problem is that
    ///      adapter's per-instance cost, not the number of adapters — a different problem with a different fix.
    ///
    ///      ### What this does NOT do
    ///
    ///      Pagination reduces the gas of one call. It does not reduce the total gas of reading the whole NAV
    ///      (it slightly increases it — per-call overhead is paid per slice) and it does nothing whatsoever for an
    ///      ON-CHAIN consumer that must read a NAV inside a transaction: that consumer needs one complete answer
    ///      in one frame and cannot reassemble across calls. For those callers the only fixes are reducing the
    ///      cost of the read itself or shrinking the registry. This API is for off-chain readers.
    ///
    ///      One thing it does help, but read the caveat before relying on it: the per-adapter gas stipend is a
    ///      share of what the READ still holds, so an adapter starved into {AdapterGasExhausted} inside the
    ///      complete scan may have ample budget when asked for on its own. A slice can therefore get an answer out
    ///      of a portfolio whose complete read has started reverting.
    ///
    ///      **The caveat: a slice can also convert that loud revert into a silent omission.** Exhaustion is
    ///      classified by `GasStipendLib.exhausted` as `consumed >= stipend - stipend/8` — measured against a
    ///      stipend that is itself a share of the CALLER's budget. An adapter that fails at a roughly fixed cost
    ///      `G` for a non-gas reason is scored "exhausted" (loud {AdapterGasExhausted}) when the full scan's
    ///      stipend is small enough that `G` clears that bar, and scored "benign revert" — fail open, legs dropped,
    ///      nothing flagged — when the slice's larger stipend puts `G` below it. `adaptersCovered` still lists the
    ///      adapter, so the documented coverage check reports full coverage. If a dropped leg is a DEBT leg the
    ///      reassembled NAV over-reports.
    ///
    ///      So: a slice that succeeds where the complete read reverted is **evidence about gas, not a repaired
    ///      answer.** Do not silently promote it to the authoritative NAV.
    ///
    ///      And note what "just give the complete read more gas and compare" does NOT achieve: raising the budget
    ///      raises the stipend, which puts a fixed-cost failure below the same 7/8 bar for the COMPLETE read too.
    ///      Both reads then fail open on the identical adapter and AGREE on the identical wrong number. The signal
    ///      is the {AdapterGasExhausted} disappearing, not the two figures converging.
    ///
    ///      No verbose (labelled) counterpart exists yet. The label paths carry the heavier gas pressure and their
    ///      bounds are being re-derived; a paginated read built against numbers about to change would be wasted.
    /// @param account Account address.
    /// @param quoteAsset Quote currency; `address(0)` for USD. Must have a price feed if non-zero. Pass the SAME
    ///        value to every slice — the per-slice `value`s are otherwise denominated differently and summing them
    ///        is meaningless.
    /// @param adapters The balance adapters to include. Each must be currently registered (in `getAllAdapters()`)
    ///        and may appear only once. Must be non-empty.
    /// @return partialNav The slice's NAV contribution plus `adaptersCovered`. See {PartialNAV} — in particular,
    ///         `value` sums and nothing else does.
    function getAccountNavForAdapters(address account, address quoteAsset, address[] calldata adapters)
        external
        view
        returns (PartialNAV memory partialNav);

    /// @notice Returns all positions for an account with pricing in the quote currency.
    /// @param account Account address.
    /// @param quoteAsset Quote currency; address(0) for USD.
    /// @return positions Array of enriched Position structs.
    function getAccountPositions(address account, address quoteAsset)
        external
        view
        returns (Position[] memory positions);

    /// @notice Returns positions for an account filtered by a single asset.
    /// @dev    **This is a filtered VIEW, not a net position. Do not sum it.** You asked for asset `X`, so you get
    ///         the legs denominated in `X` — a projection of the portfolio onto one asset, deliberately. Summing
    ///         `value` across the result (or netting credit against debt within it) produces a number that is not
    ///         this account's exposure to anything: the legs that offset these — collateral in another asset
    ///         backing a debt in `X`, or the reverse — are outside the filter by construction and are simply
    ///         absent, not netted. A vault borrowing `X` against `Y` shows here as debt in `X` with no sign of the
    ///         `Y` that secures it.
    ///
    ///         This is a documentation contract, not a defect, and the design is what makes it safe: **no NAV
    ///         number in this interface is ever computed with an asset filter.** {getAccountNav},
    ///         {getAccountNavForAdapters} and {getAccountNavVerbose} take no `asset` parameter at all, and the only
    ///         entry points that pass a non-zero filter into the position engine are this function and
    ///         {getAccountPositionsForAssetVerbose} — both of which return `Position[]`, never a `NAV`. So the
    ///         hazard lives entirely in what a CALLER does with the array, which is why it is stated here.
    ///
    ///         For a net figure, use {getAccountNav} (whole portfolio) or {getAccountNavForAdapters} (a validated
    ///         adapter slice, which partitions rather than projects and whose slices therefore do sum).
    /// @param account Account address.
    /// @param asset Asset to filter by (must be registered).
    /// @param quoteAsset Quote currency; address(0) for USD.
    /// @return positions Array of enriched Position structs for the asset. A filtered view — see the note above.
    function getAccountPositionsForAsset(address account, address asset, address quoteAsset)
        external
        view
        returns (Position[] memory positions);

    /// @notice Returns all positions for `account` with human-readable labels.
    /// @param account Account address.
    /// @param quoteAsset Quote currency; address(0) for USD.
    /// @return Array of VerbosePosition structs (enriched Position plus protocolName and display labels).
    function getAccountPositionsVerbose(address account, address quoteAsset)
        external
        view
        returns (VerbosePosition[] memory);

    /// @notice Returns positions filtered by a single asset, with human-readable labels.
    /// @dev    **This is a filtered VIEW, not a net position. Do not sum it.** Identical projection semantics to
    ///         {getAccountPositionsForAsset} — this is that function's result passed through label enrichment, from
    ///         the same `_computePositions` call with the same filter — so the whole note there applies verbatim,
    ///         including the reason it is safe: no NAV in this interface is computed with an asset filter. See
    ///         {getAccountPositionsForAsset}.
    /// @param account Account address.
    /// @param asset Asset to filter by (must be registered).
    /// @param quoteAsset Quote currency; address(0) for USD.
    /// @return Array of VerbosePosition structs for the asset (enriched Position plus protocolName and display
    ///         labels). A filtered view — see the note above.
    function getAccountPositionsForAssetVerbose(address account, address asset, address quoteAsset)
        external
        view
        returns (VerbosePosition[] memory);

    /// @notice Returns the aggregate NAV and full verbose position breakdown in one call.
    /// @param account Account address.
    /// @param quoteAsset Quote currency; address(0) for USD.
    /// @return verboseNav VerboseNAV struct bundling the NAV snapshot with the verbose position list.
    function getAccountNavVerbose(address account, address quoteAsset)
        external
        view
        returns (VerboseNAV memory verboseNav);

    /// @notice Returns the number of decimals used for USD values (e.g. 8).
    /// @return USD decimals.
    function usdDecimals() external view returns (uint8);

    /// @notice Returns detailed price feed data for an asset (primary feed + divergence signal vs its monitors).
    /// @param underlyingAsset Registered asset address.
    /// @return priceFeedData PriceFeedData struct (feed, type, price, decimals, heartbeat, updatedAt, stale,
    ///         sequencerDown, healthyFeedCount, irregular, divergenceBps, monitorFeedCount).
    function getPriceData(address underlyingAsset) external view returns (PriceFeedData memory priceFeedData);

    /// @notice Same as {getPriceData} but WITHOUT the monitor-divergence computation (irregular/divergenceBps/
    ///         monitorFeedCount stay 0/false). For hot callers that only need price/staleness (e.g. custom feeds
    ///         reading the NAV-sourced base/USD term) so a base asset's monitor reads + sort aren't repaid per call.
    /// @param underlyingAsset Registered asset address.
    /// @return priceFeedData PriceFeedData struct with the divergence fields left at their defaults.
    function getPriceDataNoDivergence(address underlyingAsset)
        external
        view
        returns (PriceFeedData memory priceFeedData);

    /// @notice Returns the divergence between an asset's primary price and its monitor feeds.
    /// @param underlyingAsset Registered asset address.
    /// @return primaryPrice The primary feed's price, normalized to NAV_DECIMALS (0 if the primary is stale).
    /// @return monitorMedian The median of the healthy monitor prices, NAV_DECIMALS (0 if no healthy monitors).
    /// @return divergenceBps Worst-case basis-point gap between the primary and any single healthy monitor — the
    ///         value `irregular` is thresholded on (0 if no monitors / primary stale).
    /// @return irregular True if divergenceBps exceeds the divergence tolerance, or (stablecoins) the primary
    ///         deviates from $1 beyond the peg tolerance.
    /// @return monitorFeedCount Number of healthy monitor feeds that contributed.
    /// @return primaryStale True if the primary feed is stale (divergence undefined).
    /// @return primaryAboveMonitors True if the primary sits above the monitor median (a premium); false if
    ///         below/equal — for a claim asset, below is the depeg direction. Meaningful only when
    ///         monitorFeedCount > 0.
    function getPriceDivergence(address underlyingAsset)
        external
        view
        returns (
            int256 primaryPrice,
            int256 monitorMedian,
            uint256 divergenceBps,
            bool irregular,
            uint256 monitorFeedCount,
            bool primaryStale,
            bool primaryAboveMonitors
        );

    /// @notice Returns health status: sequencer down flag and lists of stale-price and irregular-price assets.
    /// @return sequencerDown True if L2 sequencer is down or in grace period (false on L1).
    /// @return stalePriceAssets Addresses of assets with stale prices.
    /// @return irregularPriceAssets Addresses of assets flagged irregular (primary diverged from monitors / peg).
    function healthCheck()
        external
        view
        returns (bool sequencerDown, address[] memory stalePriceAssets, address[] memory irregularPriceAssets);

    /// @notice Returns whether the account has any non-zero balance across adapters and registered assets.
    /// @param account Account address.
    /// @return has True if at least one position has non-zero amount.
    function hasPositions(address account) external view returns (bool has);

    /// @notice Returns the list of assets for which the account has at least one non-zero position.
    /// @param account Account address.
    /// @return assets Array of asset addresses.
    function getAssetsWithPositions(address account) external view returns (address[] memory assets);

    /// @notice Converts a list of (asset, amount) pairs into a total value in the quote currency.
    /// @dev Only positive amounts; zero amounts are skipped. All assets must be registered with a price feed.
    /// @param assets Asset addresses.
    /// @param amounts Corresponding amounts (same length as assets).
    /// @param quoteAsset Quote currency; address(0) for USD.
    /// @return value Sum of values in quote asset (non-negative for valid inputs). When `quoteAssetStale` is
    ///         true, this is denominated in USD (8dp) instead of the requested quote ([9]/S2).
    /// @return quoteAssetStale True if the requested non-USD quote asset's own feed was stale, so `value` fell
    ///         back to USD rather than the quote currency. Always false for a USD quote (address(0)).
    function calculateValue(address[] memory assets, uint256[] memory amounts, address quoteAsset)
        external
        view
        returns (int256 value, bool quoteAssetStale);

    /// @notice Every listed adapter's EFFECTIVE display name and positionId-independent breadcrumb — the same values
    ///         the verbose position reads report, including any {AssetKindRegistry} override.
    /// @dev Declared here, not only on the concrete contract, so INTERFACE-TYPED consumers can reach it. That is the
    ///      caller that matters: a consumer holding `INAVCalculator` is exactly the one that would otherwise
    ///      enumerate `getAllAdapters()` and staticcall `protocolName()` on each adapter itself, which is the
    ///      surface split this function exists to close. Leaving it off the interface would have left that consumer
    ///      with no way to reach the fix.
    /// @param adapters The adapters to describe, typically the result of `getAllAdapters()`.
    /// @return names Each adapter's effective protocol name.
    /// @return labels Each adapter's effective breadcrumb, with any {AssetKindRegistry} per-segment override applied.
    ///         Empty when the adapter derives it per position AND no override is set. When the adapter answers
    ///         nothing but an override IS set, this path deliberately GROWS the breadcrumb to the override's leading
    ///         non-empty prefix — so it can be MULTI-segment, not merely a lone category. (It was a lone category
    ///         under the retired scalar `setAdapterLabelCategory`; do not code against that.) When the adapter DOES
    ///         answer, the override is overlaid segment-by-segment and can neither lengthen nor truncate the reply.
    ///         See `PriceFeedLib.adapterDisplayInfo` for why the empty case diverges from the position path.
    function getAdapterDisplayInfo(address[] calldata adapters)
        external
        view
        returns (string[] memory names, string[][] memory labels);
}

src/prices/IPrices.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

/// @title IPrices Interface
/// @notice Interface for managing price feeds for different tokens.
/// @author KPK
interface IPrices {
    /// @notice Enum representing the type of price feed.
    enum PriceType {
        Chainlink, // 0 — Chainlink AggregatorV3Interface (on-chain push)
        Redstone, // 1 — Redstone Classic Push (AggregatorV3-compatible, same read path as Chainlink)
        API3, // 2 — API3 dAPI via Api3ReaderProxyV1 (AggregatorV3-compatible, 18-dec proxy scaled to 8-dec at read)
        Custom // 3 — custom ICustomPriceFeed adapter (internal staleness logic)
    }

    /// @notice Per-asset pricing metadata governing divergence detection between the primary feed and its
    /// monitor feeds. Packs into a single storage slot (uint32 + uint32 = 8 bytes).
    /// @param divergenceToleranceBps Max allowed basis-point gap between the primary price and the worst-case
    /// (furthest) healthy monitor price before the asset is flagged `irregular`. Must be non-zero when monitors exist.
    /// @param pegToleranceBps Absolute peg-deviation guard: max allowed basis-point deviation of the primary price
    /// from $1 before the asset is flagged `irregular`. Non-zero enables the guard (set it only on assets whose
    /// fundamental value is $1, i.e. stablecoins); zero disables it.
    struct AssetPricing {
        uint32 divergenceToleranceBps;
        uint32 pegToleranceBps;
    }

    /// @notice Struct representing a price feed configuration.
    /// @param priceFeed The address of the price feed contract (e.g. Chainlink aggregator or custom price feed).
    /// @param decimals The number of decimal places the price feed uses.
    /// @param priceType The type of the price feed.
    /// @param chainlinkHeartbeat Staleness window in seconds (non-zero for all types). For Chainlink/Redstone/API3
    /// feeds this gates participation: block.timestamp - effectiveUpdatedAt >= chainlinkHeartbeat → skip feed.
    /// For Custom feeds the internal stale signal from getLatestPrice() is the primary gate; updatedAt from
    /// latestRoundData() then applies the same heartbeat gate (updatedAt==0 is treated as block.timestamp-1
    /// so rate-only feeds participate but yield to any feed with a real push timestamp), and among survivors
    /// the largest effectiveUpdatedAt wins.
    struct PriceFeedConfig {
        address priceFeed;
        uint8 decimals;
        PriceType priceType;
        uint256 chainlinkHeartbeat;
    }

    /// @notice Emitted when an already-registered price feed's staleness heartbeat is changed in place.
    /// @param underlyingAsset The asset whose registration was updated.
    /// @param priceFeed The registered feed the heartbeat applies to.
    /// @param oldHeartbeat The previous heartbeat, in seconds.
    /// @param newHeartbeat The new heartbeat, in seconds.
    event PriceFeedHeartbeatUpdated(
        address indexed underlyingAsset, address indexed priceFeed, uint256 oldHeartbeat, uint256 newHeartbeat
    );

    /// @notice A registered MONITOR feed's heartbeat changed in place.
    /// @dev Mirrors {PriceFeedHeartbeatUpdated}. Emitted instead of a `MonitorFeedRemoved`/`MonitorFeedAdded`
    ///      pair, so alerting subscribed to that pair will not see monitor staleness-window changes.
    /// @param underlyingAsset The asset whose monitor feed changed.
    /// @param priceFeed The monitor feed whose staleness window moved.
    /// @param oldHeartbeat The previous staleness window, in seconds.
    /// @param newHeartbeat The new staleness window, in seconds.
    event MonitorFeedHeartbeatUpdated(
        address indexed underlyingAsset, address indexed priceFeed, uint256 oldHeartbeat, uint256 newHeartbeat
    );

    /// @notice Emitted when a price feed is added for a token.
    /// @param underlyingAsset The address of the token.
    /// @param priceFeed The address of the price feed.
    /// @param chainlinkHeartbeat The heartbeat interval in seconds.
    /// @param priceType The type of the price feed.
    /// @param index The index of the new feed in the asset's feed array.
    event PriceFeedAdded(
        address indexed underlyingAsset,
        address indexed priceFeed,
        uint256 chainlinkHeartbeat,
        PriceType priceType,
        uint256 index
    );

    /// @notice Emitted when a single price feed is removed for a token.
    /// @param underlyingAsset The address of the token.
    /// @param priceFeed The address of the removed feed.
    /// @param index The former index of the removed feed.
    event PriceFeedRemoved(address indexed underlyingAsset, address indexed priceFeed, uint256 index);

    /// @notice Emitted when swap-and-pop relocates the last feed into a vacated slot.
    /// @param underlyingAsset The address of the token.
    /// @param priceFeed The address of the feed that was moved.
    /// @param fromIndex The former index (len-1 before the pop).
    /// @param toIndex The new index (the slot vacated by the removed feed).
    event PriceFeedIndexChanged(
        address indexed underlyingAsset, address indexed priceFeed, uint256 fromIndex, uint256 toIndex
    );

    /// @notice Emitted when all price feeds are cleared for a token (asset unregistration).
    /// @param underlyingAsset The address of the token.
    event PriceFeedUnset(address indexed underlyingAsset);

    /// @notice Emitted when a monitor (divergence-only) feed is added for a token.
    /// @param underlyingAsset The address of the token.
    /// @param priceFeed The address of the monitor feed.
    /// @param chainlinkHeartbeat The heartbeat interval in seconds.
    /// @param priceType The type of the monitor feed.
    /// @param index The index of the new monitor feed in the asset's monitor array.
    event MonitorFeedAdded(
        address indexed underlyingAsset,
        address indexed priceFeed,
        uint256 chainlinkHeartbeat,
        PriceType priceType,
        uint256 index
    );

    /// @notice Emitted when a monitor feed is removed for a token.
    /// @param underlyingAsset The address of the token.
    /// @param priceFeed The address of the removed monitor feed.
    /// @param index The former index of the removed monitor feed.
    event MonitorFeedRemoved(address indexed underlyingAsset, address indexed priceFeed, uint256 index);

    /// @notice Emitted when swap-and-pop relocates the last monitor feed into a vacated slot.
    /// @param underlyingAsset The address of the token.
    /// @param priceFeed The address of the monitor feed that was moved.
    /// @param fromIndex The former index (len-1 before the pop).
    /// @param toIndex The new index (the slot vacated by the removed monitor feed).
    event MonitorFeedIndexChanged(
        address indexed underlyingAsset, address indexed priceFeed, uint256 fromIndex, uint256 toIndex
    );

    /// @notice Emitted when all monitor feeds and pricing metadata are cleared for a token (asset unregistration).
    /// @param underlyingAsset The address of the token.
    event MonitorFeedsUnset(address indexed underlyingAsset);

    /// @notice Emitted when an asset's divergence tolerance is set.
    /// @param underlyingAsset The address of the token.
    /// @param divergenceToleranceBps The new tolerance in basis points.
    event DivergenceToleranceSet(address indexed underlyingAsset, uint32 divergenceToleranceBps);

    /// @notice Emitted when an asset's peg tolerance is set (stablecoins).
    /// @param underlyingAsset The address of the token.
    /// @param pegToleranceBps The new peg tolerance in basis points.
    event PegToleranceSet(address indexed underlyingAsset, uint32 pegToleranceBps);

    //
    // Errors
    //

    /// @notice Error when the price feed is not set for an asset
    /// @param asset The address of the asset
    error PriceFeedNotSet(address asset);

    /// @notice Error when the price feed is invalid
    error InvalidPriceOracle();

    /// @notice Error when the price feed type is not valid
    error InvalidPriceOracleType();

    /// @notice Error when attempting to remove the last remaining feed for an asset
    error CannotRemoveLastFeed(address asset);

    /// @notice Error when attempting to add a feed that is already registered for an asset
    error PriceFeedAlreadyRegistered(address asset, address feed);

    /// @notice The upsert path was given a `priceType` differing from the one the feed is registered with.
    /// @dev A feed's type is part of its IDENTITY, not its configuration — it selects the read path and the
    ///      decimals convention. Changing it means removing and re-adding the feed. Rejected rather than
    ///      ignored because `_validateFeedSupportInternal` puts Chainlink, Redstone and API3 in ONE branch, so a
    ///      mismatch inside that group passes validation and the caller would otherwise be told a request
    ///      succeeded that was never applied.
    error PriceFeedTypeImmutable(address asset, address feed);

    /// @notice Error when the feed index is out of bounds
    error PriceFeedIndexOutOfBounds(address asset, uint256 index);

    /// @notice Error when a feed address is not found in an asset's feed list
    error PriceFeedNotFound(address asset, address feed);

    /// @notice Error when a new feed's decimals do not match the decimals of existing feeds for the asset
    error PriceFeedDecimalsMismatch(address asset, uint8 existingDecimals, uint8 newDecimals);

    /// @notice Error when a monitor feed's decimals are not NAV_DECIMALS (monitors must be USD-comparable to the
    /// primary, which is always NAV_DECIMALS).
    error MonitorFeedDecimalsMismatch(address asset, uint8 expectedDecimals, uint8 actualDecimals);

    /// @notice Error when a `Custom` feed is being registered for an asset it does not price — i.e. the feed's own
    /// {ICustomPriceFeed-underlyingAssetSupported} does not equal the asset being registered.
    /// @param asset The asset the feed is being registered for.
    /// @param feed The custom feed address.
    /// @param feedAsset The asset the feed actually prices, per its own `underlyingAssetSupported()`.
    error CustomFeedAssetMismatch(address asset, address feed, address feedAsset);

    /// @notice Error when a `Custom` feed is being registered for the very asset it reads its own `base/USD` price
    /// for — i.e. the feed's {INavSourcedPriceFeed-BASE_ASSET} equals the asset being registered.
    /// @dev A NAV-sourced custom feed prices its asset as `rate × base/USD` and reads that `base/USD` back out of
    /// THIS NAV (`NavBaseUsdLib` → `getPriceData(BASE_ASSET)`; ADR 0019). If the base IS the asset, pricing the asset
    /// re-enters the same feed and recurses until the call stack is exhausted. The read still returns a price — the
    /// selector's per-feed `try`/`catch` swallows the depth failure and moves on — so the only symptom is that every
    /// read of that asset, and of everything priced from it, burns gas proportional to ~1024 nested `STATICCALL`
    /// frames. See the circularity invariant in {NavBaseUsdLib}.
    /// @param asset The asset the feed is being registered for.
    /// @param feed The custom feed address.
    error CustomFeedBaseCircular(address asset, address feed);

    /// @notice Error when a `Custom` feed does not answer {INavSourcedPriceFeed-BASE_ASSET}, so its NAV dependency
    /// cannot be established at registration.
    /// @dev Unreadable means REJECT, deliberately. The failure being closed is unbounded recursion, so "the base
    /// could not be read" must not be allowed to mean "the base is fine". A feed with no NAV dependency states that
    /// by answering `address(0)`; a feed that cannot answer at all is one whose base cannot be ruled out.
    /// @param asset The asset the feed is being registered for.
    /// @param feed The custom feed address.
    error CustomFeedBaseUnreadable(address asset, address feed);

    /// @notice Error when a monitor feed is already registered for an asset.
    error MonitorFeedAlreadyRegistered(address asset, address feed);

    /// @notice Error when a monitor feed address is not found in an asset's monitor list.
    error MonitorFeedNotFound(address asset, address feed);

    /// @notice Error when adding a monitor feed before the asset's divergence tolerance has been set (>0).
    error DivergenceToleranceRequired(address asset);

    /// @notice Error when a tolerance value is out of range. Divergence tolerance must be in (0, 10000];
    ///         peg tolerance must be in [0, 10000] (0 is allowed and disables the peg guard).
    error InvalidTolerance(uint32 toleranceBps);

    /// @notice Returns the latest price for a given token while checking if the price is stale.
    /// @dev Reverts PriceFeedNotSet if the asset has no registered feeds. When at least one feed is registered
    /// but all are stale, returns price 0 with stale = true rather than reverting.
    /// @param underlyingAsset The address of the token.
    /// @return price The latest price of the token (int256; positive for all valid prices, 0 when stale).
    /// @return decimals The amount of decimal places the price is represented with.
    /// @return stale True if all registered feeds are stale, the L2 sequencer is down, or within grace period.
    /// @return irregular True if the primary price diverged from its monitor feeds beyond the divergence tolerance,
    /// or (stablecoins) from the $1 peg beyond the peg tolerance. A pricing-quality signal, not a validity flag;
    /// `price` is still populated. Always false when `stale` (divergence is undefined for an unusable price).
    function latestPrice(address underlyingAsset)
        external
        view
        returns (int256 price, uint8 decimals, bool stale, bool irregular);

    /// @notice Checks the L2 sequencer uptime feed, returning True when it is signaling staleness (the sequencer
    /// is down or still within the grace period). If 'chainlinkL2SequencerUptimeFeed' is the zero address (e.g. on
    /// an L1) it returns false.
    /// @return stale True if the L2 sequencer is down or if it is within the grace period.
    function checkL2SequencerUptime() external view returns (bool stale);

    /// @notice Validates that a price feed is suitable for the given type, reverting if it is not. Returns nothing
    /// on success. Reverts InvalidPriceOracle when the asset or feed address is zero, the feed fails the
    /// ICustomPriceFeed/AggregatorV3 interface check for its type, or (for Chainlink/Redstone/API3) its
    /// latestRoundData reports a non-positive answer, a zero updatedAt, or a future timestamp; reverts
    /// InvalidPriceOracleType for an unsupported price type. For `Custom` feeds it additionally reverts
    /// CustomFeedAssetMismatch when the feed's own `underlyingAssetSupported()` is not `underlyingAsset` — a custom
    /// feed prices exactly one asset and must be registered for that asset — plus CustomFeedBaseUnreadable when the
    /// feed does not answer {INavSourcedPriceFeed-BASE_ASSET}, and CustomFeedBaseCircular when that base IS
    /// `underlyingAsset` (which would make pricing the asset re-enter the same feed).
    /// @param underlyingAsset The address of the token.
    /// @param priceFeed The address of the price feed.
    /// @param priceType The type of the price feed.
    function checkPriceOracleSupport(address underlyingAsset, address priceFeed, PriceType priceType) external view;

    /// @notice Returns all price feed configurations for an asset.
    /// @param asset The address of the asset.
    /// @return configs Array of PriceFeedConfig (empty if no feeds registered).
    function getPriceFeeds(address asset) external view returns (PriceFeedConfig[] memory configs);

    /// @notice Returns the number of registered price feeds for an asset.
    /// @param asset The address of the asset.
    /// @return count Number of feeds.
    function getPriceFeedCount(address asset) external view returns (uint256 count);

    /// @notice Returns the price feed configuration at a specific index.
    /// @param asset The address of the asset.
    /// @param index Index into the feed array (reverts with PriceFeedIndexOutOfBounds if out of range).
    /// @return config The PriceFeedConfig at that index.
    function getPriceFeedAt(address asset, uint256 index) external view returns (PriceFeedConfig memory config);

    /// @notice Returns all monitor (divergence-only) feed configurations for an asset.
    /// @param asset The address of the asset.
    /// @return configs Array of monitor PriceFeedConfig (empty if none registered).
    function getMonitorFeeds(address asset) external view returns (PriceFeedConfig[] memory configs);

    /// @notice Returns the number of registered monitor feeds for an asset.
    /// @param asset The address of the asset.
    /// @return count Number of monitor feeds.
    function getMonitorFeedCount(address asset) external view returns (uint256 count);

    /// @notice Returns the per-asset pricing metadata (divergence/peg tolerances).
    /// @param asset The address of the asset.
    /// @return pricing The AssetPricing struct (zero-valued if never set: tolerances 0).
    function getAssetPricing(address asset) external view returns (AssetPricing memory pricing);
}

src/utils/AddressCheckLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

import {NotAContract} from "src/errors.sol";

/// @title AddressCheckLib
/// @author KPK
/// @notice Constructor-argument helper for the balance-adapter layer: asserts a dependency address actually points
///         to a deployed contract, reverting with the {NotAContract} custom error carrying the dependency label.
/// @dev Centralises the `addr.code.length > 0` dependency check that every adapter pins its immutables with. The
///      price-feed layer has its own equivalent (`OracleArgumentChecks`); this is the balance-side analogue. `name`
///      is the dependency's human label (e.g. "NAVCalculator"), surfaced in the {NotAContract} error.
library AddressCheckLib {
    /// @notice Reverts {NotAContract}(`name`) unless `addr` has non-empty code.
    /// @param addr The dependency address to validate.
    /// @param name The dependency's display name (carried in the revert).
    function requireContract(address addr, string memory name) internal view {
        if (addr.code.length == 0) revert NotAContract(name);
    }
}

src/utils/GasStipendLib.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

/// @title GasStipendLib
/// @author KPK
/// @notice The single definition of "did this call run out of gas, or did it answer?" — the stipend a fan-out
///         forwards to one child, and the test that separates an out-of-gas from a revert afterwards.
/// @dev Exists because that question is asked in two places, one frame apart, and the two must give the same
///      answer: `PriceFeedLib._getAdapterPositions` asks it of a balance adapter, and `MetaBalanceAdapter`
///      asks it of one governed instance. Both sit on a `try`/`catch` that cannot tell the two failures apart on
///      its own, and getting it wrong in the lenient direction drops a position's legs — a dropped *debt* leg
///      RAISES the reported NAV. Two copies of a threshold is how the two paths drift apart, so there is one.
///
///      **Why a threshold at all, rather than "consumed == forwarded".** A starved callee never quite spends
///      everything it was given. Gas runs out inside whatever the callee is itself reading, not in the callee's
///      own frame: that sub-call takes 63/64 under EIP-150, out-of-gasses, and the callee's own reserve comes
///      back unspent when it bubbles the revert. One level of nesting consumes ~63/64 of the stipend, two
///      ~0.969, three ~0.954 — each level leaves another reserve behind. An exact test sees the shortfall and
///      calls a starved callee healthy, which is the silent failure; and no fixed fraction is exact either, so
///      {SLACK_DIVISOR} narrows the silent window rather than closing it.
///
///      Being wrong the other way is cheap: a busy callee that reverts after real work gets read as exhausted
///      and produces a loud, retryable failure instead of a wrong number.
///
///      **What this cannot see at all.** The question is only asked when the callee BUBBLES its out-of-gas. A
///      callee that wraps its own read in `try`/`catch` — or in a fail-open low-level staticcall — absorbs the
///      out-of-gas itself, carries on with the ~1/64 the EVM handed back, and RETURNS SUCCESSFULLY with a leg
///      missing. No classifier upstream is reached, because nothing failed from where it is standing. That
///      residual is a property of each adapter's internal error handling, not of this threshold, and it is why
///      "narrows the silent window" is the accurate claim rather than "closes it".
library GasStipendLib {
    /// @notice Fraction of the stipend a failed call may leave unspent and still count as exhausted: `1/8`.
    /// @dev Covers nesting far past anything in this repo. Raising it (a smaller divisor) widens the window in
    ///      which a genuinely reverting callee is called exhausted — loud but wrong; lowering it re-opens the
    ///      silent window. The tests bracket it from both sides deliberately.
    uint256 private constant SLACK_DIVISOR = 8;

    /// @notice Gas to forward to one child of a fan-out, given what the calling frame currently holds.
    /// @dev Exactly what the EVM would forward on its own (63/64), computed explicitly so {exhausted} has a
    ///      figure to compare against rather than an implied one. Deliberately NOT a smaller fixed ceiling: a
    ///      ceiling makes exhaustion unrecoverable — the caller cannot escape it by supplying more gas — which
    ///      turns ordinary growth in a child's cost, and cheap third-party griefing of a per-account list, into
    ///      an outage that only a redeploy can lift.
    /// @param available `gasleft()` in the calling frame, read BEFORE this call.
    /// @return The stipend to pass as `{gas: …}`.
    function stipendFrom(uint256 available) internal pure returns (uint256) {
        return available - available / 64;
    }

    /// @notice Whether a failed call that was forwarded `stipend` and cost the caller `consumed` ran out of gas
    ///         rather than reverting with an answer.
    /// @dev `consumed` must be measured against the SAME `available` that produced `stipend` via {stipendFrom}.
    ///      That single-sample discipline is what fixes the sign of the slack: the caller-side overhead the
    ///      callee never spends lands on the `consumed` side, so a genuine out-of-gas always clears the
    ///      threshold. Re-sampling nearer the call inverts it and a real exhaustion reads as a benign revert.
    /// @param stipend The value returned by {stipendFrom} and passed as `{gas: …}`.
    /// @param consumed `available - gasleft()`, measured after the call returned.
    function exhausted(uint256 stipend, uint256 consumed) internal pure returns (bool) {
        return consumed >= stipend - stipend / SLACK_DIVISOR;
    }
}

src/utils/PositionKind.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

/// @notice Semantic discriminator for a PositionBalance entry.
/// @dev Used by NAVCalculator consumers to branch on action family without string parsing.
///      `isDebt` on the enclosing PositionBalance is the canonical NAV-sign signal;
///      `PositionKind` provides human-readable category context on top of that.
///      Assignment rule: the kind reflects the OUTERMOST action family — what the account does to
///      enter/exit the position. A position exited via unstake is `Staking` regardless of what is
///      wrapped inside (e.g. gauge-staked LP); the inner exposure stays recoverable from
///      `protocolSubId`/`positionId`. LP principal sitting unstaked in the wallet is `Supplied`.
/// @author KPK
enum PositionKind {
    Wallet, // plain ERC20 / native-token balance held directly (ERC20DefaultBalanceAdapter)
    Supplied, // credit deployed into a protocol: lending supply, vault shares, unstaked LP principal
    Borrowed, // debt owed to a protocol (isDebt = true)
    Collateral, // credit locked as collateral (e.g. Aave reserve with usageAsCollateralEnabled = true)
    Staking, // staking principal: tokens locked behind an unstake action (Safety Module, Umbrella, StakeWise vaults, gauge/Convex-staked LP)
    Rewards, // accrued but not yet claimed reward tokens (e.g. CRV, CVX, BAL, COMP)
    Fees // uncollected protocol or LP fees (e.g. Uniswap V3 position fees)
}

src/utils/ProtocolIds.sol

// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;

/// @notice Canonical protocol-taxonomy constants — `protocolBrand`, `protocolId`, and `protocolSubId`
///         — for every balance adapter family.
/// @dev Each constant is `keccak256` of a lowercase-ASCII, kebab-case slug; the protocol version is
///      baked into the slug only where the protocol is a distinct versioned system (e.g. `aave-v3`,
///      `balancer-v2`/`-v3`), so unversioned protocols carry no version.  A single `protocolSubId`
///      maps to exactly one `positionId` ABI-decode schema — narrow enough that the client knows how
///      to decode without runtime sniffing.
///
///      positionId schemas (all are `abi.encode(...)`):
///        WALLET                          → (address asset)
///        AAVE_V3_LENDING / SPARK_LEND    → (address pool) — one position per instance; reserve in balanceAsset
///        AAVE_V4_LENDING                 → (address spoke) — one position per Spoke; reserve in balanceAsset
///        AAVE_V3_SAFETY_MODULE / UMBRELLA→ (address stakeToken) for BOTH staking legs (no discriminator);
///                                          isLocked=non-withdrawable splits them — active stake is LOCKED
///                                          (isLocked=true), only a cooldown elapsed-and-in-window is UNLOCKED;
///                                          the reward leg shares it too, told apart by positionKind=Rewards
///        MORPHO_VAULTS / GEARBOX_V3_MARKETS / GEARBOX_V3_CREDIT_ACCOUNTS / EULER_VAULTS / ERC4626 /
///        STAKEWISE_V3_VAULTS / FLUID_VAULTS / SYMBIOTIC_VAULTS → (address vault / market / credit account)
///        CAP                             → (address token: cUSD or stcUSD) — one leg per token
///        MORPHO_MARKETS                  → (bytes32 marketId)
///        BALANCER_V3_POOLS                → (address pool)
///        BALANCER_V3_GAUGES / V2_GAUGES                  → (address gauge)
///        CONVEX_CURVE_LP_STAKING                        → (address rewarder)
///        CURVE_POOLS                              → (address pool)
///        POLYGON_STAKING                          → (address validatorShare) — ONE positionId, two legs
///                                                    (Staking principal + Rewards) told apart by positionKind
///        CURVE_GAUGES                             → (address gauge)
///        BALANCER_V2_POOLS                → (bytes32 poolId)
///        UNISWAP_V3 / PANCAKESWAP_V3     → (address pool); NFT tokenId in positionInstanceId (bytes32(tokenId))
///        UNISWAP_V2 / PANCAKESWAP_V2     → (address pair)
///        COMPOUND_V3_COMETS / FLUID_FTOKENS     → (address comet / fToken)
///        MERKL                           → (address distributor) — reward token is in balanceAsset, not positionId
///        NEXUS_MUTUAL_STAKING_POOLS      → (address stakingPool); StakingNFT tokenId in positionInstanceId
///        STADER_WITHDRAWAL              → (address userWithdrawalManager) — static coordinate
///        KELP_WITHDRAWAL                → (address withdrawalManager)     — static coordinate; payout asset in balanceAsset
///        LIDO_WITHDRAWAL                → (address withdrawalQueue)        — static coordinate
///        ETHENA_COOLDOWN                → (address sUSDe)                  — static coordinate
///        ETHERFI_WITHDRAWAL             → (address withdrawRequestNFT)     — static coordinate
///        LIDO_STAKED_ETH                → (address token: wstETH | stETH)  — wallet-held, one leg per token
///        ETHERFI_STAKED_ETH             → (address token: eETH | weETH)
///        ROCKET_POOL_STAKED_ETH         → (address token: rETH)
///        RENZO_RESTAKED_ETH             → (address token: ezETH)
///        KELP_RESTAKED_ETH              → (address token: rsETH)
///        STADER_STAKED_ETH              → (address token: ETHx)
///        STAKEWISE_V3_OS_TOKENS         → (address token: osETH | osGNO)
///        LIQUID_COLLECTIVE_STAKED_ETH   → (address token: lsETH)
///        ANKR_STAKED_ETH                → (address token: ankrETH)
///        COINBASE_STAKED_ETH            → (address token: cbETH)
///        RESERVE_BASKETS                → (address token: ETH+)
///        ETHENA_SAVINGS                 → (address token: sUSDe)
///        SKY_SAVINGS                    → (address token: sDAI | sUSDS)
///        AAVE_V3_SAVINGS                → (address token: sGHO)
///        SPARK_SAVINGS                  → (address token: spUSDC | spUSDT | spETH)
///        MAPLE_SAVINGS                  → (address token: syrupUSDC)
///        NEXUS_MUTUAL_VAULTS            → (address token: RWIV)
///        STAKEWISE_V3_EXIT              → (address vault)                 — static, per vault
///          (for these: a static positionId with up to two legs — claimable (isLocked=false) + locked
///           (isLocked=true) — sharing it, told apart by isLocked; owed asset is in balanceAsset. isLocked
///           is part of the identity key. See docs/decisions/0016-islocked-position-status.md.)
///        BRIDGE_ESCROW                   → (address escrow, address token)
/// @author KPK
library ProtocolIds {
    bytes32 internal constant WALLET = keccak256("wallet");

    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    // Brand ids — the broadest `PositionBalance.protocolBrand` layer (the protocol brand, version-stripped). Several
    // ecosystem ids roll up to one brand: AAVE_V3 + AAVE_V4 → AAVE; BALANCER_V2 + BALANCER_V3 → BALANCER; UNISWAP_V2 +
    // UNISWAP_V3 → UNISWAP; etc. For unversioned protocols the brand equals the ecosystem id (CURVE, MORPHO, FLUID,
    // EULER, LIDO, KELP, …) — those reuse the same constant; only the versioned brands need a dedicated constant here.
    // Display/grouping only; NOT part of the stable identity key (that uses `protocolSubId`).
    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    bytes32 internal constant AAVE = keccak256("aave");
    bytes32 internal constant BALANCER = keccak256("balancer");
    bytes32 internal constant UNISWAP = keccak256("uniswap");
    bytes32 internal constant PANCAKESWAP = keccak256("pancakeswap");
    bytes32 internal constant GEARBOX = keccak256("gearbox");
    bytes32 internal constant STAKEWISE = keccak256("stakewise");
    bytes32 internal constant COMPOUND = keccak256("compound");

    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    // Ecosystem ids — the broad `PositionBalance.protocolId` (grouping / roll-up layer). Several per-product slugs
    // below (the `protocolSubId`s) roll up to one of these, e.g. AAVE_V3_LENDING + AAVE_V3_SAFETY_MODULE + AAVE_V3_UMBRELLA
    // → AAVE_V3. For single-product ecosystems the adapter uses the SAME constant for both protocolId and protocolSubId
    // (e.g. UNISWAP_V3, CAP, MERKL, WALLET, ERC4626) — no separate ecosystem constant needed. (CONVEX and CURVE keep
    // distinct per-product subIds — CONVEX_CURVE_LP_STAKING, CURVE_POOLS/CURVE_GAUGES — so for them protocolId differs
    // from protocolSubId even though they roll up to the CONVEX/CURVE ecosystem id.)
    // The version is kept in the ecosystem id where the protocol is a distinct system (aave-v3, balancer-v2/-v3,
    // uniswap-v2/-v3), so different versions are different `protocolId`s. NOT part of the stable identity key — that
    // uses `protocolSubId`. See INAVCalculator.PositionBalance.
    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    bytes32 internal constant AAVE_V3 = keccak256("aave-v3");
    bytes32 internal constant AAVE_V4 = keccak256("aave-v4");
    bytes32 internal constant GEARBOX_V3 = keccak256("gearbox-v3");
    bytes32 internal constant STAKEWISE_V3 = keccak256("stakewise-v3");
    bytes32 internal constant MORPHO = keccak256("morpho");
    bytes32 internal constant BALANCER_V2 = keccak256("balancer-v2");
    bytes32 internal constant BALANCER_V3 = keccak256("balancer-v3");
    bytes32 internal constant FLUID = keccak256("fluid");
    bytes32 internal constant EULER = keccak256("euler");
    bytes32 internal constant SYMBIOTIC = keccak256("symbiotic");
    bytes32 internal constant LIDO = keccak256("lido");
    bytes32 internal constant POLYGON = keccak256("polygon"); // Polygon ecosystem id; unversioned, so this is also the brand
    bytes32 internal constant KELP = keccak256("kelp");
    bytes32 internal constant STADER = keccak256("stader");
    bytes32 internal constant ETHERFI = keccak256("etherfi");
    bytes32 internal constant ETHENA = keccak256("ethena");
    bytes32 internal constant SPARK = keccak256("spark");
    bytes32 internal constant ROCKET_POOL = keccak256("rocket-pool");
    bytes32 internal constant RENZO = keccak256("renzo");
    bytes32 internal constant LIQUID_COLLECTIVE = keccak256("liquid-collective");
    bytes32 internal constant ANKR = keccak256("ankr");
    bytes32 internal constant COINBASE = keccak256("coinbase");
    bytes32 internal constant RESERVE = keccak256("reserve");
    bytes32 internal constant SKY = keccak256("sky");
    bytes32 internal constant MAPLE = keccak256("maple");
    bytes32 internal constant NEXUS_MUTUAL = keccak256("nexus-mutual");
    // (CURVE below doubles as the Curve ecosystem id for CURVE_POOLS/CURVE_GAUGES.)

    // ── Per-product slugs (`protocolSubId`; selects the positionId decode schema) ──

    // Aave family
    bytes32 internal constant AAVE_V3_LENDING = keccak256("aave-v3-lending");
    bytes32 internal constant AAVE_V3_SAFETY_MODULE = keccak256("aave-v3-safety-module");
    bytes32 internal constant AAVE_V3_UMBRELLA = keccak256("aave-v3-umbrella");
    bytes32 internal constant AAVE_V4_LENDING = keccak256("aave-v4-lending");

    // Morpho
    bytes32 internal constant MORPHO_VAULTS = keccak256("morpho-vaults");
    bytes32 internal constant MORPHO_MARKETS = keccak256("morpho-markets");

    // Balancer
    bytes32 internal constant BALANCER_V3_POOLS = keccak256("balancer-v3-pools");
    bytes32 internal constant BALANCER_V3_GAUGES = keccak256("balancer-v3-gauges");
    bytes32 internal constant BALANCER_V2_POOLS = keccak256("balancer-v2-pools");
    bytes32 internal constant BALANCER_V2_GAUGES = keccak256("balancer-v2-gauges");

    // Uniswap / PancakeSwap
    bytes32 internal constant UNISWAP_V3 = keccak256("uniswap-v3");
    bytes32 internal constant UNISWAP_V2 = keccak256("uniswap-v2");
    bytes32 internal constant PANCAKESWAP_V3 = keccak256("pancakeswap-v3");
    bytes32 internal constant PANCAKESWAP_V2 = keccak256("pancakeswap-v2");

    // StakeWise
    bytes32 internal constant STAKEWISE_V3_VAULTS = keccak256("stakewise-v3-vaults");

    // Polygon PoS staking (Ethereum L1 StakeManager / ValidatorShare)
    bytes32 internal constant POLYGON_STAKING = keccak256("polygon-staking"); // delegation → (address validatorShare)

    // Nexus Mutual
    bytes32 internal constant NEXUS_MUTUAL_STAKING_POOLS = keccak256("nexus-mutual-staking-pools");

    // Gearbox
    bytes32 internal constant GEARBOX_V3_MARKETS = keccak256("gearbox-v3-markets");
    bytes32 internal constant GEARBOX_V3_CREDIT_ACCOUNTS = keccak256("gearbox-v3-credit-accounts");

    // Euler
    bytes32 internal constant EULER_VAULTS = keccak256("euler-vaults");

    // Symbiotic
    bytes32 internal constant SYMBIOTIC_VAULTS = keccak256("symbiotic-vaults");

    // Compound
    bytes32 internal constant COMPOUND_V3 = keccak256("compound-v3");
    bytes32 internal constant COMPOUND_V3_COMETS = keccak256("compound-v3-comets");

    // Fluid
    bytes32 internal constant FLUID_FTOKENS = keccak256("fluid-ftokens");
    bytes32 internal constant FLUID_VAULTS = keccak256("fluid-vaults");

    // Spark
    bytes32 internal constant SPARK_LEND = keccak256("spark-lend");

    // Curve / Convex
    bytes32 internal constant CURVE = keccak256("curve"); // Curve ecosystem id (protocolId for CURVE_POOLS/CURVE_GAUGES)
    bytes32 internal constant CURVE_POOLS = keccak256("curve-pools"); // wallet LP → (address pool)
    bytes32 internal constant CURVE_GAUGES = keccak256("curve-gauges"); // gauge-staked LP → (address gauge)
    bytes32 internal constant CONVEX = keccak256("convex");
    bytes32 internal constant CONVEX_CURVE_LP_STAKING = keccak256("convex-curve-lp-staking");

    // Cap
    bytes32 internal constant CAP = keccak256("cap");

    // Generic ERC4626 wrapper
    bytes32 internal constant ERC4626 = keccak256("erc4626");

    // Withdrawal / cooldown queues
    // positionId = `abi.encode(<anchor contract>)` (the queue/manager — Lido queue, Stader/Kelp
    // manager, ether.fi NFT, StakeWise vault, sUSDe). Up to two legs share it, told apart by
    // isLocked (the owed/payout asset is in balanceAsset, not the positionId).
    bytes32 internal constant STADER_WITHDRAWAL = keccak256("stader-withdrawal");
    bytes32 internal constant KELP_WITHDRAWAL = keccak256("kelp-withdrawal");
    bytes32 internal constant LIDO_WITHDRAWAL = keccak256("lido-withdrawal");
    bytes32 internal constant ETHENA_COOLDOWN = keccak256("ethena-cooldown");
    bytes32 internal constant ETHERFI_WITHDRAWAL = keccak256("etherfi-withdrawal");

    // Wallet-held yield-bearing tokens (WalletTokenMetaBalanceAdapterBase family). The token is itself the
    // registered, priced NAV asset, so every positionId here is `abi.encode(address token)` and the
    // balanceAsset is that same token. One subId per PROTOCOL, not per token: several tokens share a subId
    // (wstETH + stETH under Lido) because they are the same product, and the positionId separates them.
    bytes32 internal constant LIDO_STAKED_ETH = keccak256("lido-staked-eth");
    bytes32 internal constant ETHERFI_STAKED_ETH = keccak256("etherfi-staked-eth");
    bytes32 internal constant ROCKET_POOL_STAKED_ETH = keccak256("rocket-pool-staked-eth");
    bytes32 internal constant RENZO_RESTAKED_ETH = keccak256("renzo-restaked-eth");
    bytes32 internal constant KELP_RESTAKED_ETH = keccak256("kelp-restaked-eth");
    bytes32 internal constant STADER_STAKED_ETH = keccak256("stader-staked-eth");
    bytes32 internal constant STAKEWISE_V3_OS_TOKENS = keccak256("stakewise-v3-os-tokens");
    bytes32 internal constant LIQUID_COLLECTIVE_STAKED_ETH = keccak256("liquid-collective-staked-eth");
    bytes32 internal constant ANKR_STAKED_ETH = keccak256("ankr-staked-eth");
    bytes32 internal constant COINBASE_STAKED_ETH = keccak256("coinbase-staked-eth");
    bytes32 internal constant RESERVE_BASKETS = keccak256("reserve-baskets");
    bytes32 internal constant ETHENA_SAVINGS = keccak256("ethena-savings");
    bytes32 internal constant SKY_SAVINGS = keccak256("sky-savings");
    bytes32 internal constant AAVE_V3_SAVINGS = keccak256("aave-v3-savings");
    bytes32 internal constant SPARK_SAVINGS = keccak256("spark-savings");
    bytes32 internal constant MAPLE_SAVINGS = keccak256("maple-savings");
    bytes32 internal constant NEXUS_MUTUAL_VAULTS = keccak256("nexus-mutual-vaults");
    bytes32 internal constant STAKEWISE_V3_EXIT = keccak256("stakewise-v3-exit");

    // Merkl rewards distributor
    bytes32 internal constant MERKL = keccak256("merkl");

    // Bridge escrow
    bytes32 internal constant BRIDGE_ESCROW = keccak256("bridge-escrow");
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/nav/NAVRegistryLib.sol": {
      "NAVRegistryLib": "0x3D5369B0b2044d62a8f643bf9a2b8CC03775934D"
    },
    "src/prices/PriceFeedLib.sol": {
      "PriceFeedLib": "0x0f913658d70BB19b7B42eF9926c3df7c70fafCf2"
    }
  },
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "cancun",
  "remappings": [
    "@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
    "@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
    "@chainlink/=lib/chainlink-brownie-contracts/contracts/",
    "chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/",
    "erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
    "forge-std/=lib/forge-std/src/",
    "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
    "openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
    "openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
    "morpho-blue/=lib/morpho-blue/",
    "ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.