Skip to content
Verified contractPartialMIT

GearboxMarketsMetaBalanceAdapter

Address0x86ea82a47f8a5a2c8d6bbf8e557c7b1061355388
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
MIT
Match
Partialcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
25,396,366
Creation transaction
0x9ca45df450…349b13e314

src/balances/protocols/GearboxMarketsMeta.sol

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

import {MetaBalanceAdapter} from "src/balances/MetaBalanceAdapter.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
import {ProtocolIds} from "src/utils/ProtocolIds.sol";

/// @title Gearbox Markets Meta Balance Adapter
/// @author kpk
/// @notice One immutable adapter that reports an account's supply position in *any* Gearbox V3 ERC4626 farming
///         pool — `convertToAssets(balanceOf(account))` emitted as a single `Supplied` leg in the pool's underlying.
///         The instance coordinate is the market (pool) address, widened to bytes32; the active market set lives
///         on NAVCalculator (`addMetaInstances`/`removeMetaInstances`). Identity is encoded as `abi.encode(address(market))`.
///         See ADR 0010.
/// @dev Reports one Supply leg per market (convertToAssets(balanceOf)) in the pool's underlying. Does not include Merkl rewards (same as
///      the per-market adapter).
contract GearboxMarketsMetaBalanceAdapter is MetaBalanceAdapter {
    bytes32 private constant PROTOCOL_ID = ProtocolIds.GEARBOX_V3;

    /// @param protocolName_ Human-readable protocol name (e.g. "Gearbox").
    /// @param navCalculator_ The NAVCalculator contract for asset-registry access.
    constructor(string memory protocolName_, address navCalculator_)
        MetaBalanceAdapter(protocolName_, navCalculator_)
    {}

    /// @inheritdoc MetaBalanceAdapter
    /// @dev `instance` is the market (ERC4626 pool) address. Emits one `Supplied` leg in the market's underlying,
    ///      dropping a zero balance and skipping an unregistered/filtered asset.
    function _instancePositions(address account, bytes32 instance, address assetFilter)
        internal
        view
        override
        returns (INAVCalculator.PositionBalance[] memory)
    {
        IERC4626 market = IERC4626(_toAddress(instance));
        address asset = market.asset();
        if (assetFilter != address(0) && assetFilter != asset) {
            return new INAVCalculator.PositionBalance[](0);
        }
        (INAVCalculator.Asset memory assetInfo, bool found) = _getAssetInfo(asset);
        if (!found) return new INAVCalculator.PositionBalance[](0);

        uint256 amount = market.convertToAssets(market.balanceOf(account));
        if (amount == 0) return new INAVCalculator.PositionBalance[](0);

        INAVCalculator.PositionBalance[] memory positions = new INAVCalculator.PositionBalance[](1);
        positions[0] = INAVCalculator.PositionBalance({
            balanceAsset: assetInfo,
            balanceAdapter: address(this),
            amount: amount,
            isDebt: false,
            protocolId: PROTOCOL_ID,
            positionId: _instancePositionId(instance),
            positionKind: PositionKind.Supplied
        });
        return positions;
    }

    /// @inheritdoc MetaBalanceAdapter
    function _instanceAssets(bytes32 instance) internal view override returns (address[] memory assets) {
        assets = new address[](1);
        assets[0] = IERC4626(_toAddress(instance)).asset();
    }

    /// @inheritdoc MetaBalanceAdapter
    function describePosition(bytes calldata pid) external view override returns (string memory) {
        if (pid.length < 32) return "";
        address market = abi.decode(pid, (address));
        try IERC20Metadata(market).name() returns (string memory n) {
            return n;
        } catch {
            return "";
        }
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/interfaces/IERC4626.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (interfaces/IERC4626.sol)

pragma solidity >=0.6.2;

import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Deposit `assets` underlying tokens and send the corresponding number of vault shares (`shares`) to `receiver`.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly `shares` vault shares to `receiver` in exchange for `assets` underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)

pragma solidity >=0.4.16;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity >=0.6.2;

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

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

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/IBalanceAdapter.sol

// SPDX-License-Identifier: MIT
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 adapter 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`.
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: MIT
pragma solidity ^0.8;

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 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-instance operation 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).
    /// @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
    /// @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/IMetaBalanceAdapter.sol

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

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

/// @title IMetaBalanceAdapter
/// @author kpk
/// @notice Interface for *meta* balance adapter adapters: a single immutable adapter that can report positions
///         for an arbitrary number of instances of one protocol (e.g. every Morpho vault, every Balancer pool).
/// @dev A meta-adapter is universal and instance-stateless — it holds no list of "active" instances and has no
///      admin/write functions. The set of instances to actually query lives on NAVCalculator (per-adapter,
///      MANAGER-gated). This keeps adapters immutable while making the governed "which instances" set mutable in
///      the upgradeable, AccessControl-gated NAVCalculator.
///
///      Instances are identified by a `bytes32` coordinate. For most protocols this is an address widened to
///      bytes32 (vault / pool / instance-DataProvider address); the wider type also accommodates protocols whose
///      instance key is itself a bytes32 (e.g. Morpho market ids).
///
///      Call path: NAVCalculator calls the inherited `getAdapterPositions(account, assetFilter)` on every adapter
///      uniformly (no ERC165 routing). A meta-adapter services it by reading its own NAV-configured set via
///      `getMetaInstances(address(this))` and fanning out over it — see `MetaBalanceAdapter`. The instance-aware
///      methods below take an explicit instance list for off-chain/explicit queries and per-instance breakdowns.
///      (The other no-arg `IBalanceAdapter` methods — `getAdapterBalances`/`getAdapterBalanceForAsset` —
///      are not used by the NAV path and return empty.)
interface IMetaBalanceAdapter is IBalanceAdapter {
    /// @notice Get all positions for an account across the supplied instances.
    /// @param account The account to query.
    /// @param instances The instance coordinates to query (e.g. vault addresses widened to bytes32).
    /// @param assetFilter Optional asset filter (address(0) for all assets).
    /// @return positions Array of balance-only PositionBalance structs aggregated across the instances.
    function getAdapterPositionsForInstances(address account, bytes32[] calldata instances, address assetFilter)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory positions);

    /// @notice Returns the underlying assets supported across the supplied instances.
    /// @param instances The instance coordinates to inspect.
    /// @return underlyingAssets The list of underlying asset addresses (may contain duplicates across instances).
    function underlyingAssetsSupportedForInstances(bytes32[] calldata instances)
        external
        view
        returns (address[] memory underlyingAssets);
}

src/balances/IPositionDescribable.sol

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

/// @title IPositionDescribable
/// @notice Optional interface for balance adapters that can provide human-readable labels 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 empty label strings.
///      Clients MUST NOT use these strings for identity, indexing, or reconciliation; use the typed
///      `protocolId` / `positionId` / `PositionKind` fields on `PositionBalance` for those purposes.
interface IPositionDescribable {
    /// @notice Human-readable protocol name, e.g. "Aave V3", "Morpho", "Uniswap V3".
    /// @dev Per-instance adapters return a compile-time constant. Meta-adapters return a constant too
    ///      (the protocol name is the same regardless of which instance is being described).
    function protocolName() external view returns (string memory);

    /// @notice Human-readable label for a single position identified by `positionId`.
    /// @param positionId The ABI-encoded position identifier (same bytes as `PositionBalance.positionId`).
    /// @return A short display string, e.g. "USDC supply", "USDC/WETH 0.05% LP", "Steakhouse USDC vault".
    ///         Empty string is acceptable if a description cannot be derived.
    function describePosition(bytes calldata positionId) external view returns (string memory);
}

src/balances/MetaBalanceAdapter.sol

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

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

/// @title MetaBalanceAdapter
/// @author kpk
/// @notice Abstract base for meta balance adapter adapters — one immutable adapter serving every instance of a
///         protocol. Concrete adapters implement two hooks (`_instancePositions`, `_instanceAssets`); this base
///         provides the ERC165 wiring, the empty no-arg `IBalanceAdapter` methods, the per-instance fan-out
///         with revert isolation, and shared NAVCalculator registry helpers.
/// @dev The instance set lives on NAVCalculator (ADR 0010). The adapter reads its own set via
///      `NAV_CALCULATOR.getMetaInstances(address(this))` and holds no instance state or admin functions of its
///      own — it stays immutable. `getAdapterPositionsForInstances` is also exposed for explicit/off-chain queries.
abstract contract MetaBalanceAdapter is IMetaBalanceAdapter, IPositionDescribable {
    //
    // State
    //

    /// @notice Human-readable protocol name for IPositionDescribable (e.g. "Morpho"). Set once at construction.
    string internal _protocolName;

    /// @notice NAVCalculator reference, used for the registered-asset registry.
    INAVCalculator public immutable NAV_CALCULATOR;

    //
    // Constructor
    //

    /// @param protocolName_ Human-readable protocol name for verbose reads (e.g. "Morpho").
    /// @param navCalculator_ The NAVCalculator contract for asset-registry access.
    constructor(string memory protocolName_, address navCalculator_) {
        require(navCalculator_.code.length > 0, "NAVCalculator must be a contract");
        _protocolName = protocolName_;
        NAV_CALCULATOR = INAVCalculator(navCalculator_);
    }

    //
    // IERC165
    //

    /// @inheritdoc IERC165
    function supportsInterface(bytes4 interfaceId) external pure virtual override returns (bool) {
        return interfaceId == type(IMetaBalanceAdapter).interfaceId || interfaceId == type(IBalanceAdapter).interfaceId
            || interfaceId == type(IPositionDescribable).interfaceId || interfaceId == type(IERC165).interfaceId;
    }

    //
    // IPositionDescribable
    //

    /// @inheritdoc IPositionDescribable
    function protocolName() external view virtual override returns (string memory) {
        return _protocolName;
    }

    /// @inheritdoc IPositionDescribable
    /// @dev Concrete adapters must override — derives a human-readable label from the encoded instance coordinate.
    function describePosition(bytes calldata positionId) external view virtual override returns (string memory);

    //
    // IBalanceAdapter
    //
    // NAVCalculator calls getAdapterPositions(account, assetFilter) on every adapter uniformly. A meta-adapter
    // services it by reading its NAV-configured instance set and fanning out — no special routing in NAV.
    // getAdapterBalances / getAdapterBalanceForAsset are not used by the NAV path and return empty.
    //

    /// @inheritdoc IBalanceAdapter
    /// @dev Reads the NAV-configured instance set for this adapter and fans out over it (ADR 0010).
    function getAdapterPositions(address account, address assetFilter)
        external
        view
        virtual
        override
        returns (INAVCalculator.PositionBalance[] memory)
    {
        return _positionsForInstances(account, NAV_CALCULATOR.getMetaInstances(address(this)), assetFilter);
    }

    /// @inheritdoc IBalanceAdapter
    function getAdapterBalances(address)
        external
        view
        virtual
        override
        returns (address[] memory, uint256[] memory, bool[] memory)
    {
        return (new address[](0), new uint256[](0), new bool[](0));
    }

    /// @inheritdoc IBalanceAdapter
    function getAdapterBalanceForAsset(address, address) external view virtual override returns (uint256, bool) {
        return (0, false);
    }

    /// @inheritdoc IBalanceAdapter
    function underlyingAssetsSupported() external view virtual override returns (address[] memory) {
        return _assetsForInstances(NAV_CALCULATOR.getMetaInstances(address(this)));
    }

    //
    // IMetaBalanceAdapter
    //

    /// @inheritdoc IMetaBalanceAdapter
    function getAdapterPositionsForInstances(address account, bytes32[] calldata instances, address assetFilter)
        external
        view
        override
        returns (INAVCalculator.PositionBalance[] memory)
    {
        return _positionsForInstances(account, instances, assetFilter);
    }

    /// @inheritdoc IMetaBalanceAdapter
    function underlyingAssetsSupportedForInstances(bytes32[] calldata instances)
        external
        view
        override
        returns (address[] memory)
    {
        return _assetsForInstances(instances);
    }

    //
    // Internal fan-out
    //

    /// @notice Aggregates positions across `instances`, isolating a faulty instance so it cannot zero out the batch.
    function _positionsForInstances(address account, bytes32[] memory instances, address assetFilter)
        internal
        view
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        INAVCalculator.PositionBalance[][] memory perInstance = new INAVCalculator.PositionBalance[][](instances.length);
        uint256 total = 0;
        for (uint256 i = 0; i < instances.length; i++) {
            try this.instancePositions(account, instances[i], assetFilter) returns (
                INAVCalculator.PositionBalance[] memory p
            ) {
                perInstance[i] = p;
                total += p.length;
            } catch {
                perInstance[i] = new INAVCalculator.PositionBalance[](0);
            }
        }

        positions = new INAVCalculator.PositionBalance[](total);
        uint256 k = 0;
        for (uint256 i = 0; i < instances.length; i++) {
            for (uint256 j = 0; j < perInstance[i].length; j++) {
                positions[k++] = perInstance[i][j];
            }
        }
    }

    /// @notice Aggregates the underlying assets across `instances`.
    function _assetsForInstances(bytes32[] memory instances) internal view returns (address[] memory assets) {
        address[][] memory perInstance = new address[][](instances.length);
        uint256 total = 0;
        for (uint256 i = 0; i < instances.length; i++) {
            try this.instanceAssets(instances[i]) returns (address[] memory a) {
                perInstance[i] = a;
                total += a.length;
            } catch {
                perInstance[i] = new address[](0);
            }
        }

        assets = new address[](total);
        uint256 k = 0;
        for (uint256 i = 0; i < instances.length; i++) {
            for (uint256 j = 0; j < perInstance[i].length; j++) {
                assets[k++] = perInstance[i][j];
            }
        }
    }

    //
    // External wrappers (enable per-instance revert isolation via `this.` staticcall)
    //

    /// @notice External wrapper around the concrete per-instance position logic.
    /// @dev Called via `this.` inside `getAdapterPositionsForInstances` so a single bad instance is isolated.
    function instancePositions(address account, bytes32 instance, address assetFilter)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory)
    {
        return _instancePositions(account, instance, assetFilter);
    }

    /// @notice External wrapper around the concrete per-instance asset enumeration.
    function instanceAssets(bytes32 instance) external view returns (address[] memory) {
        return _instanceAssets(instance);
    }

    //
    // Hooks implemented by concrete adapters
    //

    /// @notice Computes the positions for a single instance. Implementations should return an EMPTY array (not
    ///         revert) for instances whose asset is unregistered or whose balance is zero.
    function _instancePositions(address account, bytes32 instance, address assetFilter)
        internal
        view
        virtual
        returns (INAVCalculator.PositionBalance[] memory);

    /// @notice Returns the underlying asset(s) for a single instance.
    function _instanceAssets(bytes32 instance) internal view virtual returns (address[] memory);

    //
    // Shared helpers
    //

    /// @notice Decodes an address-keyed bytes32 instance coordinate into an address (vault / pool / DataProvider).
    /// @dev Reverts if the high 96 bits are non-zero rather than silently truncating, so a malformed coordinate
    ///      surfaces as an error (isolated per-instance by the fan-out) instead of querying a different address.
    ///      Adapters whose coordinate is a raw bytes32 (e.g. Morpho market ids) do not use this helper.
    function _toAddress(bytes32 instance) internal pure returns (address) {
        require(uint256(instance) >> 160 == 0, "instance: not an address");
        return address(uint160(uint256(instance)));
    }

    /// @notice Returns the positionId bytes for a given instance coordinate.
    /// @dev Default: encodes the instance as an address (address-keyed protocols).
    ///      Override when the coordinate is a raw bytes32 (e.g. Morpho market IDs, Balancer V2 poolIds).
    ///      Adapters where positionId varies per leg rather than per instance do NOT use this hook —
    ///      they compute positionId inline in _instancePositions:
    ///        - Aave V3 / Aave V2: abi.encode(pool, reserve) — one positionId per reserve
    ///        - Uniswap V3 / PancakeSwap V3: abi.encode(npm, tokenId) — one positionId per NFT
    function _instancePositionId(bytes32 instance) internal view virtual returns (bytes memory) {
        return abi.encode(_toAddress(instance));
    }

    /// @notice Looks up an asset's registry metadata.
    /// @return asset The Asset struct (zeroed if not found).
    /// @return found True if the asset is registered in NAVCalculator.
    function _getAssetInfo(address asset) internal view returns (INAVCalculator.Asset memory, bool found) {
        INAVCalculator.Asset[] memory reg = NAV_CALCULATOR.getRegisteredAssets();
        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/nav/INAVCalculator.sol

// SPDX-License-Identifier: MIT
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 {
    //
    // 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 protocolId `keccak256` of a canonical protocol slug (see `src/utils/ProtocolIds.sol`).
    ///        Selects the `positionId` ABI-decode schema — one slug implies exactly one schema.
    /// @param positionId ABI-encoded position identifier. Decode schema is determined by `protocolId`.
    ///        e.g. for AAVE_V3_LENDING: `abi.encode(address pool, address reserve)`.
    ///        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 `protocolId` and `positionId` forms the stable per-chain identity key
    ///        `(chainId, protocolId, positionId, balanceAsset.asset, positionKind)`.
    struct PositionBalance {
        Asset balanceAsset;
        address balanceAdapter;
        uint256 amount;
        bool isDebt;
        bytes32 protocolId;
        bytes positionId;
        PositionKind positionKind;
    }

    /// @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 protocolId `keccak256` protocol slug. Copied from PositionBalance.
    /// @param positionId ABI-encoded position identifier. Copied from PositionBalance.
    /// @param positionKind Semantic discriminator. Copied from 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 protocolId;
        bytes positionId;
        PositionKind positionKind;
    }

    /// @notice Position enriched with human-readable display labels.
    /// @dev Returned by verbose read methods. Labels are sourced from the adapter's IPositionDescribable
    ///      implementation (if present) and are empty strings 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"
        string positionLabel; // e.g. "USDC supply", "USDC/WETH 0.05% LP"
    }

    /// @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 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.
    // forge-lint: disable-next-line(pascal-case-struct)
    struct NAV {
        int256 value;
        Asset quoteAsset;
        uint64 timestamp;
        Asset[] stalePriceAssets;
        bool sequencerDown;
        bool quoteAssetStale;
    }

    /// @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 of the selected feed in seconds.
    /// @param updatedAt Last update timestamp from latestRoundData (AggregatorV3-shaped feeds only; 0 for Custom).
    /// @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.
    struct PriceFeedData {
        address priceFeed;
        IPrices.PriceType priceType;
        int256 price;
        uint8 decimals;
        uint256 chainlinkHeartbeat;
        uint256 updatedAt;
        bool stale;
        bool sequencerDown;
        uint256 healthyFeedCount;
    }

    //
    // 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 or Custom.
    /// @param chainlinkHeartbeat Heartbeat for Chainlink staleness (ignored for Custom).
    function registerAsset(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
        external;

    /// @notice Adds an additional price feed for an already registered asset.
    /// @dev Reverts with PriceFeedAlreadyRegistered if the feed address is already registered for this asset.
    /// @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 addPriceFeed(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
        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, 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 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, 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, 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 if uptime feed not set).
    /// @param newSequencerGracePeriod Grace period in seconds.
    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.
    /// @return assets Array of Asset (address, symbol, decimals).
    function getRegisteredAssets() external view returns (Asset[] memory assets);

    /// @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).
    function getAccountNav(address account, address quoteAsset) external view returns (NAV memory nav);

    /// @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.
    /// @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.
    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.
    function getAccountPositionsVerbose(address account, address quoteAsset)
        external
        view
        returns (VerbosePosition[] memory);

    /// @notice Returns positions filtered by a single asset, with human-readable labels.
    /// @param account Account address.
    /// @param asset Asset to filter by (must be registered).
    /// @param quoteAsset Quote currency; address(0) for USD.
    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.
    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.
    /// @param underlyingAsset Registered asset address.
    /// @return priceFeedData PriceFeedData struct (feed, type, price, decimals, heartbeat, updatedAt, stale, sequencerDown).
    function getPriceData(address underlyingAsset) external view returns (PriceFeedData memory priceFeedData);

    /// @notice Returns health status: sequencer down flag and list of assets with stale prices.
    /// @return sequencerDown True if L2 sequencer is down or in grace period (false on L1).
    /// @return stalePriceAssets Addresses of assets with stale prices.
    function healthCheck() external view returns (bool sequencerDown, address[] memory stalePriceAssets);

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

src/prices/IPrices.sol

// SPDX-License-Identifier: MIT
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 IPriceFeedCustom adapter (internal staleness logic)
    }

    /// @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 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.
    /// @param priceType The type of the price feed.
    struct PriceFeedConfig {
        address priceFeed;
        uint8 decimals;
        PriceType priceType;
        uint256 chainlinkHeartbeat;
    }

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

    //
    // 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 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 Returns the latest price for a given token while checking if the price is stale.
    /// @param underlyingAsset The address of the token.
    /// @return price The latest price of the token (int256; positive for all valid prices).
    /// @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.
    function latestPrice(address underlyingAsset) external view returns (int256 price, uint8 decimals, bool stale);

    /// @notice Checks if the L2 sequencer is up and running returning True if it is not signaling staleness. 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 Checks if the price feed supports the given price feed type.
    /// @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);
}

src/utils/PositionKind.sol

// SPDX-License-Identifier: MIT
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
///      `protocolId`/`positionId`. LP principal sitting unstaked in the wallet is `Supplied`.
enum PositionKind {
    Wallet, // plain ERC20 / native-token balance held directly (ERC20DefaultAdapter)
    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/Aura-staked LP)
    Rewards, // accrued but not yet claimed reward tokens (e.g. CRV, CVX, BAL, AURA, COMP)
    Fees // uncollected protocol or LP fees (e.g. Uniswap V3 position fees)
}

src/utils/ProtocolIds.sol

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

/// @notice Canonical `protocolId` constants for every balance adapter family.
/// @dev Each constant is `keccak256` of a lowercase-ASCII, kebab-case slug that includes the
///      protocol version.  A single `protocolId` 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 / V2 / SPARK    → (address pool, address reserve)
///        AAVE_V3_SAFETY_MODULE / UMBRELLA→ (address stakeToken)
///        MORPHO_VAULTS / GEARBOX_V3 / EULER_VAULTS / CAP / ERC4626 / STAKEWISE_V3 / FLUID_VAULTS → (address vault)
///        SKY_SAVINGS                     → (address savingsContract)
///        MORPHO_MARKETS                  → (bytes32 marketId)
///        BALANCER_V3_POOL                → (address pool)
///        BALANCER_V3_GAUGE / V2_GAUGE / AURA           → (address gauge)
///        CONVEX                                         → (address rewarder)
///        CURVE_POOL                              → (address pool)
///        CURVE_GAUGE                             → (address gauge)
///        BALANCER_V2_POOL                → (bytes32 poolId)
///        UNISWAP_V3 / PANCAKESWAP_V3     → (address npm, uint256 tokenId)
///        UNISWAP_V2 / PANCAKESWAP_V2     → (address pair)
///        COMPOUND_V3 / FLUID_FTOKENS     → (address market)
///        MERKL                           → (address rewardToken)
///        DAI_DSR / STADER_WITHDRAWAL / KELP_WITHDRAWAL / LIDO_WITHDRAWAL
///          / ETHENA_COOLDOWN / ETHERFI_WITHDRAWAL / STAKEWISE_EXIT / NEXUS_STAKING → "" (account-global)
///        BRIDGE_ESCROW                   → (address escrow, address token)
library ProtocolIds {
    bytes32 internal constant WALLET = keccak256("wallet");

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

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

    // Balancer
    bytes32 internal constant BALANCER_V3_POOL = keccak256("balancer-v3-pool");
    bytes32 internal constant BALANCER_V3_GAUGE = keccak256("balancer-v3-gauge");
    bytes32 internal constant BALANCER_V2_POOL = keccak256("balancer-v2-pool");
    bytes32 internal constant BALANCER_V2_GAUGE = keccak256("balancer-v2-gauge");

    // 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 = keccak256("stakewise-v3");

    // Nexus Mutual
    bytes32 internal constant NEXUS_STAKING = keccak256("nexus-staking");

    // Gearbox
    bytes32 internal constant GEARBOX_V3 = keccak256("gearbox-v3");

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

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

    // 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 / Aura
    bytes32 internal constant CURVE = keccak256("curve"); // per-instance adapter (legacy)
    bytes32 internal constant CURVE_POOL = keccak256("curve-pool"); // wallet LP → (address pool)
    bytes32 internal constant CURVE_GAUGE = keccak256("curve-gauge"); // gauge-staked LP → (address gauge)
    bytes32 internal constant CONVEX = keccak256("convex");
    bytes32 internal constant AURA = keccak256("aura");

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

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

    // Withdrawal / cooldown queues
    // positionId is empty (`""`) for all of these — each adapter reports one aggregated leg per account.
    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");
    bytes32 internal constant STAKEWISE_EXIT = keccak256("stakewise-exit");

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

    // Sky / DAI savings
    bytes32 internal constant SKY_SAVINGS = keccak256("sky-savings");
    bytes32 internal constant DAI_DSR = keccak256("dai-dsr");

    // Bridge escrow
    bytes32 internal constant BRIDGE_ESCROW = keccak256("bridge-escrow");
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "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/",
    "@optimism/=lib/optimism/packages/contracts-bedrock/src/",
    "comet-contracts/=lib/comet/contracts/",
    "aave-v3-core/=lib/aave-v3-core/contracts/",
    "gmx-contracts/=lib/gmx-contracts/contracts/",
    "morpho-blue/=lib/morpho-blue/",
    "@comet-contracts/=lib/comet/contracts/",
    "@forge-std/=lib/comet/forge/lib/forge-std/",
    "clones-with-immutable-args/=lib/optimism/packages/contracts-bedrock/lib/clones-with-immutable-args/src/",
    "comet/=lib/comet/",
    "ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
    "eth-gas-reporter/=lib/comet/node_modules/eth-gas-reporter/",
    "halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
    "hardhat/=lib/comet/node_modules/hardhat/",
    "kontrol-cheatcodes/=lib/optimism/packages/contracts-bedrock/lib/kontrol-cheatcodes/src/",
    "lib-keccak/=lib/optimism/packages/contracts-bedrock/lib/lib-keccak/contracts/",
    "optimism/=lib/optimism/",
    "safe-contracts/=lib/optimism/packages/contracts-bedrock/lib/safe-contracts/contracts/",
    "solady/=lib/optimism/packages/contracts-bedrock/lib/solady/",
    "solmate/=lib/optimism/packages/contracts-bedrock/lib/solmate/src/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.