Skip to content
Verified contractPartialBUSL-1.1

MerklRewardsAttestedBalanceAdapter

Address0xff2d5a8bf801191ed1292e6dd6792f5d03c5afbf
Balance

0 ETH

 

Transactions

113

 

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
25,856,888
Creation transaction
0x5c9b3d03d0…7d9d5d6f98
Libraries
src/nav/NAVRegistryLib.sol:NAVRegistryLib0x55b6…ca3511src/prices/PriceFeedLib.sol:PriceFeedLib0x713e…dbfebc

src/balances/AttestedBalanceAdapters/MerklRewardsAttestedBalanceAdapter.sol

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

import {AddressCheckLib} from "src/utils/AddressCheckLib.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";

import {AttestedValueCache} from "src/balances/AttestedBalanceAdapters/AttestedValueCache.sol";
import {IPositionDescribable} from "src/balances/IPositionDescribable.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.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";
import {ProtocolNames} from "src/utils/ProtocolNames.sol";

/// @title Merkl Rewards Balance Adapter (role-gated submit, proof-verified cache)
/// @author KPK
/// @notice Reports a user's *unclaimed* Merkl reward balances. Merkl distributes rewards via off-chain merkle trees;
///         the on-chain Distributor stores only cumulative *claimed* amounts + the current root (the tree lives
///         off-chain behind an IPFS pointer), so a user's allocation is not derivable on-chain. To make pending
///         allocations queryable from a `view`, this adapter caches per-(user, token) cumulative allocations
///         submitted via `submitProofs`, which **upserts** each proven `(user, token)` entry and leaves omitted
///         tokens untouched — so a submit can never suppress a live entry. Every entry is verified against the live
///         Distributor merkle root, so **no caller can fabricate amounts**. The feeder is trusted only to keep the
///         cache fresh; failure to do so makes NAV under-count rewards, never over-count.
///
/// @dev **The first member of the attested family, holding only the Merkl-specific half.** Everything
///      protocol-independent — the `(value, epoch)` cache and its enumeration, the stale-gated clears, the
///      NAV-version probe, the gas-isolated read fan-out, the preview skeleton — lives in {AttestedValueCache}.
///      What remains here is exactly what a protocol must supply: **what the epoch is** (`getMerkleRoot`), **how an
///      attestation is proven** (Merkl's sorted-pair merkle proof), and **how one token's value becomes legs** (the
///      per-campaign pro-rata split).
///
///      **Role-gated & submit-on-behalf-of.** `submitProofs(user, …)` takes an explicit `user` and requires
///      `SUBMITTER_ROLE`. Because every write is proof-verified, opening it to anyone adds no fabrication risk
///      *in the amounts*. **That is not the same as "the label is trustworthy".** The proof binds the per-token
///      cumulative but NOT the campaign split — only the shares' SUM is checked — so ANY holder of
///      `SUBMITTER_ROLE` can submit a real proof split into up to {MAX_CAMPAIGNS_PER_TOKEN} fabricated legs,
///      inflating a real token's leg COUNT and putting chosen `campaignId`s on reported positions. Since the role
///      landed this is no longer reachable by an arbitrary third party — it is a bound on how far a compromised or
///      buggy KEEPER can mislead, not a public grief. It never inflates NAV and is repairable in one transaction,
///      but campaign identity remains display-grade rather than attested.
///
///      Trust model: `docs/decisions/0007-merkl-trust-minimized-cache.md`. Family contract: ADR 0022.
contract MerklRewardsAttestedBalanceAdapter is AttestedValueCache {
    //
    // Type Definitions
    //

    /// @notice One campaign's share of a token's reward, from the Merkl API `breakdowns[]`.
    /// @param campaignId       Merkl campaign id.
    /// @param subCampaignId    Merkl sub-campaign id. With `campaignId` it forms the position's
    ///                         `positionInstanceId` (`keccak256(abi.encode(campaignId, subCampaignId))`).
    ///                         **Duplicates are NOT rejected.** Two legs of the same token can carry an identical
    ///                         `positionInstanceId`. Harmless on-chain — it is excluded from the stable
    ///                         reconciliation key and NAV SUMS legs rather than deduping them — but a downstream
    ///                         consumer keying on the instance coordinate cannot tell a fabricated repeat from a
    ///                         genuine one. Campaign identity is display-grade, not audit-grade.
    /// @param cumulativeAmount This campaign's contribution to the token total. NOT individually proof-backed
    ///                         (Merkl proves only the per-token total); the contract instead enforces that the
    ///                         shares SUM to the proof-verified total, so a hostile submitter can mis-split across
    ///                         campaigns but can never inflate the token total.
    struct CampaignShare {
        bytes32 campaignId;
        bytes32 subCampaignId;
        uint256 cumulativeAmount;
    }

    /// @notice One token's entry in a per-user **upsert** submission: the per-token leaf (proof-verified) plus its
    ///         per-campaign breakdown.
    /// @param campaigns If non-empty, the contract requires `Σ campaigns[i].cumulativeAmount == cumulativeAmount`
    ///                  (fail-loud) — bounding the total to the proof while letting each campaign become its own
    ///                  position. Empty ⇒ one untagged position (`positionInstanceId = bytes32(0)`).
    struct Allocation {
        address token;
        uint256 cumulativeAmount;
        bytes32[] proof;
        CampaignShare[] campaigns;
    }

    //
    // State
    //

    /// @notice Hard cap on campaign shares cached per (user, token). This is the *tight* cap because it is the one
    ///         KEEPER-CONTROLLED amplifier: the merkle proof binds only the per-token cumulative, NOT the
    ///         individual `campaignId`s, so a `SUBMITTER_ROLE` holder can split that proven total into up to this
    ///         many fabricated legs. It can never add tokens the user does not hold — the token set stays
    ///         proof-bounded — so this is the only multiplier the keeper can move. Since the role landed this is
    ///         no longer reachable by an arbitrary third party: it bounds how far a compromised or buggy KEEPER
    ///         can mislead, not a public grief.
    /// @dev    **These caps bound the READ COST, not the arithmetic.** There is no overflow or wrong-figure path:
    ///         amounts are proof-bounded, the share sum is *checked*, and `Math.mulDiv` floors, so a token's legs
    ///         always sum to at most its unclaimed total. What an over-large leg count produces is not a wrong
    ///         number but an unaffordable one — and read cost is strongly SUPER-LINEAR in leg count, measured on
    ///         this adapter at 104 registered assets:
    ///             256 legs ->   4,183,404 gas
    ///             512 legs ->  10,341,288
    ///            1024 legs ->  30,005,724
    ///            2048 legs ->  98,675,920
    ///         Each doubling multiplies cost by 2.47x, 2.90x, 3.29x — rising — because memory expansion and the ABI
    ///         encoding of a nested-dynamic `PositionBalance[]` both grow faster than the count. So the figure to
    ///         size a budget against is the PRODUCT of the two caps, never either alone. Lowered 32 -> 8 together
    ///         with {MAX_TOKENS_PER_USER} 256 -> 64: the product falls 8192 -> 512 legs, i.e. a worst case of
    ///         ~10.3M gas instead of order 1e9, which no read could ever pay.
    ///
    ///         **Why these stay FAIL-LOUD rather than degrading like `NAVCalculator._MAX_LABEL_ELEMENTS`.** That cap
    ///         is a READ-side guard on UNTRUSTED returndata, where the NAV cannot control what arrives and must
    ///         degrade. These two are WRITE-side storage admission, enforced by the contract that owns the storage,
    ///         before the data exists. Rejecting at write is precisely what keeps the read bounded, so softening it
    ///         would let an oversized submit silently no-op while the feeder believed it had landed.
    uint256 public constant MAX_CAMPAIGNS_PER_TOKEN = 8;

    /// @notice Upper bound on distinct reward tokens cached per user. Every cached token is proof-verified, so the
    ///         cache can never hold a token the user does not really hold.
    /// @dev    **This cap alone is NOT the read bound** — the leg upper bound is
    ///         `MAX_TOKENS_PER_USER * MAX_CAMPAIGNS_PER_TOKEN` = **512**, and it is that PRODUCT a read budget must
    ///         be sized against. The two bound different things: this one bounds the account's genuine,
    ///         PROOF-BOUNDED token footprint, while {MAX_CAMPAIGNS_PER_TOKEN} bounds the amplification a third party
    ///         CAN inflict on a token the user really holds.
    ///
    ///         Two consequences it does not by itself solve, tracked rather than fixed here: (1) under upsert
    ///         semantics the cache accumulates every token ever proven — stale entries are only removed by the
    ///         permissionless, stale-gated clear, so an account farming Merkl across many root epochs drifts toward
    ///         the cap unless the feeder also garbage-collects; (2) reaching the cap makes a submit carrying a NEW
    ///         token revert, and because a submit is atomic over its whole list, that reverts the refresh of the
    ///         account's OTHER tokens too.
    uint256 public constant MAX_TOKENS_PER_USER = 64;

    /// @dev ⚠️ **UNPROVEN — no test discriminates this constant, and none is claimed to.** Setting it to 0 leaves
    ///      every isolation test passing. Swept 300k/200k/150k/120k/100k/90k/80k/70k on a 2-token fixture and
    ///      4M/2M/1.2M/900k/700k/600k/500k/400k on a 32-leg fixture with the griefer LAST: results byte-identical
    ///      with and without the reserve at every budget. Retained as reasoning, not as a verified guard.
    ///
    ///      A REAL limit the same probe DID find, unfixed by this reserve: with 32 legs already accumulated and a
    ///      griefer valued LAST, the whole read reverts at 2,000,000 gas and below — identically with and without
    ///      the reserve. Per-token isolation does NOT make the read unconditionally survivable. Sizing a read budget
    ///      off the cap remains necessary.
    uint256 private constant _COMPLETION_RESERVE_PER_LEG = 256;

    /// @notice Merkl Distributor (Angle Labs). Same address on every supported EVM chain.
    address public immutable DISTRIBUTOR;

    /// @notice Per-(user, token) campaign breakdown (the submitter-supplied `breakdowns[]`). Each share becomes its
    ///         own NAV position, valued as the token's on-chain unclaimed split pro-rata by the share's cumulative.
    ///         Empty ⇒ one untagged position. Shares of a token sum to the token's verified cumulative.
    mapping(address user => mapping(address token => CampaignShare[])) private _campaigns;

    //
    // Errors
    //

    /// @notice Submitted proof did not verify against the current Distributor merkle root.
    error InvalidProof();

    /// @notice Submitted cumulative amount is strictly less than the cached value for the SAME live root. Merkl
    ///         fixes one cumulative per (user, token) per root, so a lower figure against the root the cached entry
    ///         was proven under indicates a malformed or hostile tree.
    /// @dev **This is a TRIPWIRE, not a protection, and the difference matters.** For a well-formed Merkl tree it
    ///      is UNREACHABLE: the amount is committed inside the leaf, so under one root exactly one value verifies
    ///      per `(user, token)`. It cannot prevent an over-report either — `_verifyPayload` checks the proof
    ///      against the live root BEFORE this runs, so any figure it sees is already root-attested — and its
    ///      detection is order-contingent (a malformed tree whose LOWER leaf lands first passes silently).
    ///
    ///      What it does still do, and why it is kept: it is the WRITE path's only within-list duplicate check
    ///      (`_revertOnDuplicateAsset` runs on the preview path only), so it rejects a decreasing duplicate token
    ///      inside one submission that would otherwise land last-writer-wins. And a named revert beats a silent
    ///      value flap if Merkl's tree engine ever misbehaves. Its base rate should be ZERO — alert on any
    ///      occurrence rather than retrying.
    ///
    ///      **Do not "generalise" it back to the ungated form.** The liveness conjunct restores the guard's
    ///      ORIGINAL within-list scope: it was written under clear-first (replace) semantics where it could not
    ///      reach across calls, and the later move to upsert silently widened it into a cross-rotation guard it
    ///      was never designed to be — which is what wedged accounts on a legitimate post-rotation decrease.
    error AmountRegression();

    /// @notice The submitted campaign breakdown does not sum to the proof-verified per-token cumulative.
    error CampaignSumMismatch(address token, uint256 sumOfShares, uint256 tokenCumulative);

    /// @notice More than `MAX_CAMPAIGNS_PER_TOKEN` campaign shares submitted for one token (read-gas bound).
    error TooManyCampaigns(address token, uint256 count);

    //
    // Constructor
    //

    /// @param distributor_   The Merkl Distributor address. Must be a contract.
    /// @param navCalculator_ The NAVCalculator address. Validated by {AttestedValueCache}, including the
    ///                       NAV-version probe — so a NAV that cannot serve `getRegisteredAsset` is refused here
    ///                       too, without this member restating the reasoning.
    /// @param admin_         Holder of `DEFAULT_ADMIN_ROLE`, which grants and revokes `SUBMITTER_ROLE` (the
    ///                       keeper). Intended to be the security-council Safe. Cannot be zero.
    /// @dev Submits are gated on `SUBMITTER_ROLE`; the stale-gated clears stay permissionless. Everything is
    ///      immutable except the proof-verified cache and the role set.
    constructor(address distributor_, address navCalculator_, address admin_)
        AttestedValueCache(navCalculator_, admin_)
    {
        if (distributor_ == address(0)) revert InvalidArguments();
        AddressCheckLib.requireContract(distributor_, "Distributor");
        DISTRIBUTOR = distributor_;
    }

    //
    // Mutators (SUBMITTER_ROLE-gated; every write is also proof-verified against the live Distributor root)
    //

    /// @notice Submit Merkl allocations for `user` — each entry **upserts** its `(user, token)` cache; tokens
    ///         omitted from `allocs` are left untouched, so this can never suppress a live entry.
    /// @dev Requires `SUBMITTER_ROLE` (enforced by the base at `_upsertAttestation`). Proof-verification remains the
    ///      integrity guarantee for the AMOUNT; the role governs who may occupy the cache and set labels. **Reverts** `InvalidArguments`, `UninitializedEpoch`, `InvalidProof`,
    ///      `TooManyCampaigns`, `CampaignSumMismatch`, `TooManyAttestations`, or `AmountRegression` — fail-loud and
    ///      atomic, so a bad entry reverts the whole call and leaves the prior set intact.
    /// @notice Typed convenience over {IAttestedBalanceAdapter.submit}, kept for keeper ABI ergonomics.
    /// @dev Requires `SUBMITTER_ROLE` (enforced by the base at `_upsertAttestation`). Funnels through
    ///      `_submitPayload` — the family's single write path — rather than duplicating it, so this and the generic
    ///      `submit(account, bytes)` cannot diverge. Fail-loud and atomic over the whole list.
    function submitProofs(address user, Allocation[] calldata allocs) external {
        _submitPayload(user, abi.encode(allocs));
    }

    /// @notice Typed batch convenience. **Atomic across accounts by design** — one invalid entry reverts the whole
    ///         batch, so a multi-account feeder should pre-filter or fall back to the per-account entrypoint.
    function submitProofsBatch(address[] calldata users, Allocation[][] calldata allocs) external {
        // Same reason the base's `submitBatch` checks here: an EMPTY `users` array never enters the loop, so
        // without this a roleless caller gets a successful `submitProofsBatch([], [])` authorized nowhere —
        // destroying "the batch succeeded" as evidence of a grant, which is what the runbook tells operators to
        // rely on. The base's `_submitPayload` also checks once per CALL, and `_upsertAttestation` per element, as defence in depth.
        _checkRole(SUBMITTER_ROLE);
        if (users.length != allocs.length) revert InvalidArguments();
        for (uint256 i; i < users.length; ++i) {
            _submitPayload(users[i], abi.encode(allocs[i]));
        }
    }

    /// @inheritdoc AttestedValueCache
    /// @dev Merkl's cache-only monotonicity guard, **gated on liveness**. Within ONE root Merkl's tree fixes a
    ///      single cumulative per (user, token), so a lower proof-verified figure offered against the root the
    ///      cached entry was proven under is evidence of a malformed or hostile tree. Ungated, this compared
    ///      against a cached value from a root no longer live — an entry already reading 0 — and since a submit is
    ///      atomic, that one entry rolled back the refresh of every OTHER token in the call, silently removing the
    ///      account's whole Merkl contribution from NAV. It cannot over-report: the value was proof-verified
    ///      against the live root by {_verifyPayload} before this runs.
    function _beforeAdmit(address account, address asset, uint256 value, bytes32 epoch) internal view override {
        Attestation memory a = _attestationOf(account, asset);
        if (a.epoch == epoch && value < a.value) revert AmountRegression();
    }

    /// @inheritdoc AttestedValueCache
    /// @dev Replaces this token's campaign shares wholesale, so a re-submit overwrites the prior breakdown cleanly.
    function _storeMemberState(address account, address asset, bytes memory ctx) internal override {
        CampaignShare[] memory shares = abi.decode(ctx, (CampaignShare[]));
        delete _campaigns[account][asset];
        for (uint256 i; i < shares.length; ++i) {
            _campaigns[account][asset].push(shares[i]);
        }
    }

    //
    // Reads — Merkl-specific views
    //

    /// @notice The cached campaign-share breakdown for `(user, token)` (empty if submitted untagged).
    /// @dev Display/debug. The shares sum to the proof-verified per-token cumulative.
    function campaignsOf(address user, address token) external view returns (CampaignShare[] memory) {
        return _campaigns[user][token];
    }

    function protocolName() external pure returns (string memory) {
        return ProtocolNames.MERKL;
    }

    /// @inheritdoc IPositionDescribable
    /// @dev `["Claimable Rewards"]` — a static category (the reward token is in `balanceAsset`). The argument is
    ///      ignored; the per-leg Merkl campaign coordinate is carried on `positionInstanceId`, not as a label.
    function positionLabels(bytes calldata) external pure override returns (string[] memory out) {
        out = new string[](1);
        out[0] = "Claimable Rewards";
        return out;
    }

    //
    // Hooks — the attested family contract
    //

    /// @inheritdoc AttestedValueCache
    /// @dev Decodes the family's opaque `bytes` into `Allocation[]` and verifies every leaf against `epoch` with the
    ///      SAME helper the write path uses, so preview and cache can never disagree on what a valid proof is.
    ///      Fail-loud: a bad proof reverts rather than being skipped.
    ///
    ///      **Campaign identity is submitter-supplied, not proof-bound.** The proof commits only the per-token
    ///      cumulative, so a consumer must treat the per-campaign `positionInstanceId` on returned legs as
    ///      display-grade — the per-token *amount* is the proof-backed figure.
    function _verifyPayload(bytes32 epoch, address account, bytes memory data)
        internal
        view
        override
        returns (address[] memory assets, uint256[] memory values, bytes[] memory ctxs)
    {
        Allocation[] memory allocs = abi.decode(data, (Allocation[]));
        uint256 n = allocs.length;
        // Enforce the cap HERE, immediately after the decode and BEFORE the verification loop. The base re-checks it
        // on the returned arrays as defence in depth, but by then every proof in an oversized payload would already
        // have been verified — so an over-cap caller would pay the full merkle cost only to be rejected.
        if (n > MAX_TOKENS_PER_USER) revert TooManyAttestations(account, n);
        assets = new address[](n);
        values = new uint256[](n);
        ctxs = new bytes[](n);
        for (uint256 i; i < n; ++i) {
            _checkProofAndCampaigns(
                epoch, account, allocs[i].token, allocs[i].cumulativeAmount, allocs[i].proof, allocs[i].campaigns
            );
            assets[i] = allocs[i].token;
            values[i] = allocs[i].cumulativeAmount;
            ctxs[i] = abi.encode(allocs[i].campaigns);
        }
    }

    /// @inheritdoc AttestedValueCache
    /// @dev Merkl's `getMerkleRoot()` accounts for the dispute window: during one, or with a non-zero `disputer`, it
    ///      returns `lastTree.merkleRoot` (the previous root). The root is therefore NOT monotonic and can return to
    ///      a previous value — which is why staleness is a straight equality check and never an extrapolation.
    function _liveEpoch() internal view override returns (bytes32) {
        return IMerklDistributor(DISTRIBUTOR).getMerkleRoot();
    }

    /// @inheritdoc AttestedValueCache
    /// @dev Live `cumulative − Distributor.claimed(account, asset)`, floored at 0.
    ///
    ///      **Not revert-free, deliberately.** The Distributor read is unguarded and its returndata ABI-decoded, so
    ///      this reverts if the Distributor ever returns something *undecodable* (it is an upgradeable proxy under
    ///      Angle governance). On the NAV path a plain revert means this adapter's leg set drops out — an
    ///      under-report, the safe direction, but silent.
    ///
    ///      **A `Claim` reshape can go either way, and WHICH way is decided by the reward token's DECIMALS.** An
    ///      earlier version of this note claimed a field reorder to `(uint48 timestamp, uint208 amount, bytes32
    ///      root)` always decodes cleanly and over-reports, citing a fully-claimed 1000e18 account reporting
    ///      `999999999999999998766`. **That measurement was wrong.** The reorder also moves the real `amount` into
    ///      the slot read as `uint48`, and the ABI decoder range-validates it. Re-measured against a mock returning
    ///      the reordered words raw:
    ///
    ///        - `claimed = 1000e18`  → `1000e18 > 2**48-1` → **decode REVERTS** (no over-report; fails open instead)
    ///        - `claimed = 2**48`    → **decode REVERTS**
    ///        - `claimed = 2**48-1`  → decodes → over-reports `281474976709421`
    ///        - `claimed = 2**40`    → decodes → over-reports `1099511626542`
    ///        - field *append*       → decodes, extra word ignored, value UNCHANGED and correct
    ///
    ///      So the reorder over-report is gated on `real_claimed < 2**48` (281,474,976,710,655 raw units). At 18
    ///      decimals that is 0.00028 tokens — effectively unreachable, so the read reverts and fails open. At **6**
    ///      decimals it is ~281.47M units, i.e. every realistic balance — and Merkl does run USDC/USDT campaigns.
    ///
    ///      This adds no new trust assumption (Angle already controls the root and can inflate any leaf — ADR 0007
    ///      accepts that explicitly), which is why it stays documented rather than guarded. Anyone revisiting that
    ///      decision should start from the accurate predicate above, and note that a cheap guard DOES exist:
    ///      binding the discarded middle field as `(uint208 claimedAmt, uint48 claimedAt,)` and rejecting
    ///      `claimedAt > block.timestamp` has no false positives on the honest layout and, under a reorder, fires
    ///      exactly when the over-report would exceed `block.timestamp`.
    ///
    ///      It is deliberately NOT fail-open-to-0: the clears gate on this value, so a fail-open would let anyone
    ///      clear another account's LIVE entries during a Distributor hiccup — converting a read-availability
    ///      problem into the permissionless-suppression vector the stale-gate exists to close.
    function _liveValue(address account, address asset, uint256 attestedValue)
        internal
        view
        override
        returns (uint256)
    {
        (uint208 claimedAmt,,) = IMerklDistributor(DISTRIBUTOR).claimed(account, asset);
        if (attestedValue <= uint256(claimedAmt)) return 0;
        return attestedValue - uint256(claimedAmt);
    }

    /// @inheritdoc AttestedValueCache
    /// @dev **Load-bearing:** the per-campaign split uses `liveValue` (not `attestedValue`) as the `Math.mulDiv`
    ///      numerator, so the legs of a token always sum to at most its unclaimed total — the over-report guard.
    ///      Empty shares ⇒ one untagged leg. `ctx` is empty on the cache path (shares come from storage) and
    ///      carries the caller-supplied breakdown on the preview path, so both paths build identical legs.
    ///
    ///      positionId is the Distributor (the claim target / trust anchor), NOT the reward token — the token is
    ///      already carried by `balanceAsset`, so encoding it here would be redundant with the reconciliation key.
    ///      Multiple reward tokens from the same Distributor share this positionId and are distinguished by
    ///      `balanceAsset.asset` (same model as Aave V3 = abi.encode(pool)).
    function _assetLegs(
        address account,
        address asset,
        INAVCalculator.Asset memory meta,
        uint256 liveValue,
        uint256 attestedValue,
        bytes memory ctx,
        bool fromCache
    ) internal view override returns (INAVCalculator.PositionBalance[] memory legs) {
        // Branch on the EXPLICIT discriminant, not on `ctx.length`. The old convention ("empty ctx means read
        // storage") worked only because `abi.encode` of an empty array is 64 bytes rather than 0 — a member that
        // returned a literal `bytes("")` for a breakdown-less preview entry would have silently fallen through to
        // CACHED shares while valuing a caller-supplied amount. The discriminant makes that unrepresentable.
        CampaignShare[] memory shares = fromCache ? _campaigns[account][asset] : abi.decode(ctx, (CampaignShare[]));

        bytes memory pid = abi.encode(DISTRIBUTOR); // identical for every leg of every token
        if (shares.length == 0) {
            legs = new INAVCalculator.PositionBalance[](1);
            legs[0] = _row(meta, liveValue, pid, bytes32(0)); // untagged single position
            return legs;
        }
        if (attestedValue == 0) return new INAVCalculator.PositionBalance[](0); // defensive: nothing to split

        INAVCalculator.PositionBalance[] memory tmp = new INAVCalculator.PositionBalance[](shares.length);
        uint256 n;
        for (uint256 i; i < shares.length; ++i) {
            uint256 legAmount = Math.mulDiv(liveValue, shares[i].cumulativeAmount, attestedValue);
            if (legAmount == 0) continue;
            tmp[n++] = _row(meta, legAmount, pid, keccak256(abi.encode(shares[i].campaignId, shares[i].subCampaignId)));
        }
        legs = new INAVCalculator.PositionBalance[](n);
        for (uint256 i; i < n; ++i) {
            legs[i] = tmp[i];
        }
    }

    /// @inheritdoc AttestedValueCache
    function _cachedLegCount(address account, address asset) internal view override returns (uint256) {
        uint256 c = _campaigns[account][asset].length;
        return c == 0 ? 1 : c;
    }

    /// @inheritdoc AttestedValueCache
    function _previewLegCount(bytes memory ctx) internal pure override returns (uint256) {
        uint256 c = abi.decode(ctx, (CampaignShare[])).length;
        return c == 0 ? 1 : c;
    }

    /// @inheritdoc AttestedValueCache
    /// @dev Drops the campaign breakdown in lockstep with the attestation, so no orphan shares survive a clear.
    ///      No `super` call is needed or possible: the base erases its own record in a `private` function.
    function _deleteMemberState(address account, address asset) internal override {
        delete _campaigns[account][asset];
    }

    function _maxAssetsPerAccount() internal pure override returns (uint256) {
        return MAX_TOKENS_PER_USER;
    }

    function _completionReservePerLeg() internal pure override returns (uint256) {
        return _COMPLETION_RESERVE_PER_LEG;
    }

    function _protocolBrand() internal pure override returns (bytes32) {
        return ProtocolIds.MERKL;
    }

    function _protocolId() internal pure override returns (bytes32) {
        return ProtocolIds.MERKL;
    }

    function _protocolSubId() internal pure override returns (bytes32) {
        return ProtocolIds.MERKL;
    }

    function _positionKind() internal pure override returns (PositionKind) {
        return PositionKind.Rewards;
    }

    //
    // Internal — proof
    //

    /// @dev The single source of truth for proof + campaign-shape validity, used by BOTH the cache write and the
    ///      cache-free preview (each then adds its own extra acceptance rule: submit the cache-only
    ///      `AmountRegression`; preview the duplicate-asset guard, applied by the base). Verifies the per-token leaf
    ///      `keccak256(abi.encode(account, token, cumulativeAmount))` against `root`, then bounds any breakdown to
    ///      at most {MAX_CAMPAIGNS_PER_TOKEN} shares that SUM to the proven total.
    function _checkProofAndCampaigns(
        bytes32 root,
        address account,
        address token,
        uint256 cumulativeAmount,
        bytes32[] memory proof,
        CampaignShare[] memory campaigns
    ) private pure {
        bytes32 leaf = keccak256(abi.encode(account, token, cumulativeAmount));
        if (!_verifyMerklProof(leaf, proof, root)) revert InvalidProof();

        uint256 nCampaigns = campaigns.length;
        if (nCampaigns > MAX_CAMPAIGNS_PER_TOKEN) revert TooManyCampaigns(token, nCampaigns);
        if (nCampaigns != 0) {
            uint256 sumShares;
            for (uint256 i; i < nCampaigns; ++i) {
                // CHECKED arithmetic, deliberately: this is the line that stops a wraparound forging
                // `sumShares == cumulativeAmount` from shares that are individually enormous.
                sumShares += campaigns[i].cumulativeAmount;
            }
            if (sumShares != cumulativeAmount) revert CampaignSumMismatch(token, sumShares, cumulativeAmount);
        }
    }

    /// @dev Replicates Merkl's `_verifyProof` byte-for-byte: sorted-pair, `keccak256(abi.encode(a, b))`. The use of
    ///      `abi.encode` (32-byte padded) rather than `abi.encodePacked` is the key deviation from OpenZeppelin's
    ///      `MerkleProof.verify` and we MUST match it for proofs from the Merkl API to verify.
    function _verifyMerklProof(bytes32 leaf, bytes32[] memory proof, bytes32 root) private pure returns (bool) {
        bytes32 currentHash = leaf;
        uint256 n = proof.length;
        for (uint256 i; i < n;) {
            bytes32 sibling = proof[i];
            if (currentHash < sibling) {
                currentHash = keccak256(abi.encode(currentHash, sibling));
            } else {
                currentHash = keccak256(abi.encode(sibling, currentHash));
            }
            unchecked {
                ++i;
            }
        }
        return currentHash == root;
    }
}

/// @notice Minimal interface for Merkl's Distributor (Angle Labs).
/// @dev Reference: https://github.com/AngleProtocol/merkl-contracts/blob/main/contracts/Distributor.sol
interface IMerklDistributor {
    /// @notice Returns the active merkle root, accounting for the dispute window. During a dispute window or with
    ///         a non-zero `disputer`, this returns `lastTree.merkleRoot` (the previous root); otherwise
    ///         `tree.merkleRoot`.
    function getMerkleRoot() external view returns (bytes32);

    /// @notice Auto-generated getter for the public `mapping(address => mapping(address => Claim))` storage.
    /// @return amount      Cumulative amount the `user` has already claimed for `token` (uint208).
    /// @return timestamp   Timestamp of the most recent claim (uint48).
    /// @return merkleRoot  Merkle root the most recent claim was made against.
    function claimed(address user, address token)
        external
        view
        returns (uint208 amount, uint48 timestamp, bytes32 merkleRoot);
}

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

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

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}

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

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Return the 512-bit addition of two uint256.
     *
     * The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
     */
    function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        assembly ("memory-safe") {
            low := add(a, b)
            high := lt(low, a)
        }
    }

    /**
     * @dev Return the 512-bit multiplication of two uint256.
     *
     * The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
     */
    function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
        // 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
        // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
        // variables such that product = high * 2²⁵⁶ + low.
        assembly ("memory-safe") {
            let mm := mulmod(a, b, not(0))
            low := mul(a, b)
            high := sub(sub(mm, low), lt(mm, low))
        }
    }

    /**
     * @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            success = c >= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a - b;
            success = c <= a;
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a * b;
            assembly ("memory-safe") {
                // Only true when the multiplication doesn't overflow
                // (c / a == b) || (a == 0)
                success := or(eq(div(c, a), b), iszero(a))
            }
            // equivalent to: success ? c : 0
            result = c * SafeCast.toUint(success);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `DIV` opcode returns zero when the denominator is 0.
                result := div(a, b)
            }
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            success = b > 0;
            assembly ("memory-safe") {
                // The `MOD` opcode returns zero when the denominator is 0.
                result := mod(a, b)
            }
        }
    }

    /**
     * @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryAdd(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
     */
    function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
        (, uint256 result) = trySub(a, b);
        return result;
    }

    /**
     * @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
     */
    function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
        (bool success, uint256 result) = tryMul(a, b);
        return ternary(success, result, type(uint256).max);
    }

    /**
     * @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a > b, a, b);
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return ternary(a < b, a, b);
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // (a + b) / 2 can overflow.
            return (a & b) + (a ^ b) / 2;
        }
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
     * Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);

            // Handle non-overflow cases, 256 by 256 division.
            if (high == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return low / denominator;
            }

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= high) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
            }

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [high low].
            uint256 remainder;
            assembly ("memory-safe") {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                high := sub(high, gt(remainder, low))
                low := sub(low, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator.
            // Always >= 1. See https://cs.stackexchange.com/q/138556/92363.

            uint256 twos = denominator & (0 - denominator);
            assembly ("memory-safe") {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [high low] by twos.
                low := div(low, twos)

                // Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from high into low.
            low |= high * twos;

            // Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
            // works in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
            // is no longer required.
            result = low * inverse;
            return result;
        }
    }

    /**
     * @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
     */
    function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
        unchecked {
            (uint256 high, uint256 low) = mul512(x, y);
            if (high >= 1 << n) {
                Panic.panic(Panic.UNDER_OVERFLOW);
            }
            return (high << (256 - n)) | (low >> n);
        }
    }

    /**
     * @dev Calculates x * y >> n with full precision, following the selected rounding direction.
     */
    function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
        return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory buffer) private pure returns (bool) {
        uint256 chunk;
        for (uint256 i = 0; i < buffer.length; i += 0x20) {
            // See _unsafeReadBytesOffset from utils/Bytes.sol
            assembly ("memory-safe") {
                chunk := mload(add(add(buffer, 0x20), i))
            }
            if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // If upper 8 bits of 16-bit half set, add 8 to result
        r |= SafeCast.toUint((x >> r) > 0xff) << 3;
        // If upper 4 bits of 8-bit half set, add 4 to result
        r |= SafeCast.toUint((x >> r) > 0xf) << 2;

        // Shifts value right by the current result and use it as an index into this lookup table:
        //
        // | x (4 bits) |  index  | table[index] = MSB position |
        // |------------|---------|-----------------------------|
        // |    0000    |    0    |        table[0] = 0         |
        // |    0001    |    1    |        table[1] = 0         |
        // |    0010    |    2    |        table[2] = 1         |
        // |    0011    |    3    |        table[3] = 1         |
        // |    0100    |    4    |        table[4] = 2         |
        // |    0101    |    5    |        table[5] = 2         |
        // |    0110    |    6    |        table[6] = 2         |
        // |    0111    |    7    |        table[7] = 2         |
        // |    1000    |    8    |        table[8] = 3         |
        // |    1001    |    9    |        table[9] = 3         |
        // |    1010    |   10    |        table[10] = 3        |
        // |    1011    |   11    |        table[11] = 3        |
        // |    1100    |   12    |        table[12] = 3        |
        // |    1101    |   13    |        table[13] = 3        |
        // |    1110    |   14    |        table[14] = 3        |
        // |    1111    |   15    |        table[15] = 3        |
        //
        // The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
        assembly ("memory-safe") {
            r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
        }
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

    /**
     * @dev Return the log in base 10 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
        }
    }

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 x) internal pure returns (uint256 r) {
        // If value has upper 128 bits set, log2 result is at least 128
        r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
        // If upper 64 bits of 128-bit half set, add 64 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
        // If upper 32 bits of 64-bit half set, add 32 to result
        r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
        // If upper 16 bits of 32-bit half set, add 16 to result
        r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
        // Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
        return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }

    /**
     * @dev Counts the number of leading zero bits in a uint256.
     */
    function clz(uint256 x) internal pure returns (uint256) {
        return ternary(x == 0, 256, 255 - log2(x));
    }
}

lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.20;

/**
 * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeCast {
    /**
     * @dev Value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);

    /**
     * @dev An int value doesn't fit in a uint of `bits` size.
     */
    error SafeCastOverflowedIntToUint(int256 value);

    /**
     * @dev Value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);

    /**
     * @dev A uint value doesn't fit in an int of `bits` size.
     */
    error SafeCastOverflowedUintToInt(uint256 value);

    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        if (value > type(uint248).max) {
            revert SafeCastOverflowedUintDowncast(248, value);
        }
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        if (value > type(uint240).max) {
            revert SafeCastOverflowedUintDowncast(240, value);
        }
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        if (value > type(uint232).max) {
            revert SafeCastOverflowedUintDowncast(232, value);
        }
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        if (value > type(uint224).max) {
            revert SafeCastOverflowedUintDowncast(224, value);
        }
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        if (value > type(uint216).max) {
            revert SafeCastOverflowedUintDowncast(216, value);
        }
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        if (value > type(uint208).max) {
            revert SafeCastOverflowedUintDowncast(208, value);
        }
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        if (value > type(uint200).max) {
            revert SafeCastOverflowedUintDowncast(200, value);
        }
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        if (value > type(uint192).max) {
            revert SafeCastOverflowedUintDowncast(192, value);
        }
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        if (value > type(uint184).max) {
            revert SafeCastOverflowedUintDowncast(184, value);
        }
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        if (value > type(uint176).max) {
            revert SafeCastOverflowedUintDowncast(176, value);
        }
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        if (value > type(uint168).max) {
            revert SafeCastOverflowedUintDowncast(168, value);
        }
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        if (value > type(uint160).max) {
            revert SafeCastOverflowedUintDowncast(160, value);
        }
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        if (value > type(uint152).max) {
            revert SafeCastOverflowedUintDowncast(152, value);
        }
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        if (value > type(uint144).max) {
            revert SafeCastOverflowedUintDowncast(144, value);
        }
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        if (value > type(uint136).max) {
            revert SafeCastOverflowedUintDowncast(136, value);
        }
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        if (value > type(uint128).max) {
            revert SafeCastOverflowedUintDowncast(128, value);
        }
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        if (value > type(uint120).max) {
            revert SafeCastOverflowedUintDowncast(120, value);
        }
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        if (value > type(uint112).max) {
            revert SafeCastOverflowedUintDowncast(112, value);
        }
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        if (value > type(uint104).max) {
            revert SafeCastOverflowedUintDowncast(104, value);
        }
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        if (value > type(uint96).max) {
            revert SafeCastOverflowedUintDowncast(96, value);
        }
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        if (value > type(uint88).max) {
            revert SafeCastOverflowedUintDowncast(88, value);
        }
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        if (value > type(uint80).max) {
            revert SafeCastOverflowedUintDowncast(80, value);
        }
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        if (value > type(uint72).max) {
            revert SafeCastOverflowedUintDowncast(72, value);
        }
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        if (value > type(uint64).max) {
            revert SafeCastOverflowedUintDowncast(64, value);
        }
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        if (value > type(uint56).max) {
            revert SafeCastOverflowedUintDowncast(56, value);
        }
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        if (value > type(uint48).max) {
            revert SafeCastOverflowedUintDowncast(48, value);
        }
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        if (value > type(uint40).max) {
            revert SafeCastOverflowedUintDowncast(40, value);
        }
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        if (value > type(uint32).max) {
            revert SafeCastOverflowedUintDowncast(32, value);
        }
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        if (value > type(uint24).max) {
            revert SafeCastOverflowedUintDowncast(24, value);
        }
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        if (value > type(uint16).max) {
            revert SafeCastOverflowedUintDowncast(16, value);
        }
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        if (value > type(uint8).max) {
            revert SafeCastOverflowedUintDowncast(8, value);
        }
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        if (value < 0) {
            revert SafeCastOverflowedIntToUint(value);
        }
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(248, value);
        }
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(240, value);
        }
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(232, value);
        }
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(224, value);
        }
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(216, value);
        }
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(208, value);
        }
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(200, value);
        }
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(192, value);
        }
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(184, value);
        }
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(176, value);
        }
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(168, value);
        }
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(160, value);
        }
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(152, value);
        }
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(144, value);
        }
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(136, value);
        }
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(128, value);
        }
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(120, value);
        }
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(112, value);
        }
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(104, value);
        }
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(96, value);
        }
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(88, value);
        }
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(80, value);
        }
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(72, value);
        }
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(64, value);
        }
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(56, value);
        }
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(48, value);
        }
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(40, value);
        }
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(32, value);
        }
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(24, value);
        }
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(16, value);
        }
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        if (downcasted != value) {
            revert SafeCastOverflowedIntDowncast(8, value);
        }
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        if (value > uint256(type(int256).max)) {
            revert SafeCastOverflowedUintToInt(value);
        }
        return int256(value);
    }

    /**
     * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
     */
    function toUint(bool b) internal pure returns (uint256 u) {
        assembly ("memory-safe") {
            u := iszero(iszero(b))
        }
    }
}

src/balances/AttestedBalanceAdapters/AttestedValueCache.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 {AddressCheckLib} from "src/utils/AddressCheckLib.sol";

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

/// @title AttestedValueCache
/// @author KPK
/// @notice Shared base for the **attested** balance-adapter family ({IAttestedBalanceAdapter}, ADR 0022) — the peer
///         of `AssistedCoordCache` in the assisted family, and deliberately shaped after it. It owns everything about
///         an attested adapter that is NOT protocol-specific, so a new member supplies only its proof scheme, its
///         epoch source, and how one asset's value becomes legs.
///
/// @dev **The family invariant this base enforces, and the one it cannot.**
///      *Enforced here:* the cache holds one `(value, epoch)` attestation per `(account, asset)`; every read values
///      the attestation LIVE through {_liveValue}; a cached entry whose `epoch` no longer equals {_liveEpoch} reads
///      **0** rather than being extrapolated; removal is **stale-gated** so no caller can suppress a live entry; and
///      the per-account asset set is capped and duplicate-free, which is the only thing standing between the cache
///      and a double-counted leg.
///      *NOT enforced here — the member's job:* that `value` was ever attested at all. This base never inspects a
///      proof. A member MUST verify its protocol's attestation before calling {_upsertAttestation}, because that is
///      the single point where an unproven number could enter the cache. The base is written so there is exactly one
///      such point rather than several.
///
///      **Why the cache is a VALUE cache and not a coordinate cache.** That is precisely what separates this family
///      from the assisted one. An assisted adapter caches coordinates and re-derives the amount on-chain every read,
///      so it structurally cannot over-report. An attested adapter caches a number that has no on-chain source — so
///      the guarantee is only as good as the per-write proof, which makes it a **procedurally** weaker sibling and
///      is why {_upsertAttestation} is `internal` and loudly documented rather than exposed.
///
///      **Elements are keyed by ASSET address, not by an opaque blob.** `AssistedCoordCache` keys on
///      `keccak256(coord)` because its coordinates are ticket/NFT ids with no natural address. An attested value is
///      always attested *for an asset* — it must resolve through `NAV_CALCULATOR.getRegisteredAsset` to be valued at
///      all — so the asset address IS the natural key. That keeps the hot read path free of the extra hashing and
///      `bytes` copies the coordinate cache pays. A member needing richer per-entry state (Merkl's campaign
///      breakdown) keeps its own mapping keyed by the same `(account, asset)` pair and threads it through the `ctx`
///      parameter of {_assetLegs}.
///
///      **Direction of every failure in this base is UNDER-report.** Legs are dropped, never fabricated: a stale
///      epoch reads 0, an unregistered asset is skipped, a starved element is dropped. Whether dropping is *safe*
///      depends on the member — see {_collectLegs}, which documents why the drop is licensed only for credit-only
///      members and what a debt-emitting member would have to change.
abstract contract AttestedValueCache is IAttestedBalanceAdapter, IPositionDescribable, AccessControl {
    //
    // Type Definitions
    //

    /// @notice One cached attestation per `(account, asset)`.
    /// @param value      The attested figure, in the asset's own units, as proven by the member's attestation
    ///                   scheme (Merkl: the per-token cumulative allocation). Never a NAV value.
    /// @param epoch      The attestation epoch the proof was verified against (Merkl: the Distributor merkle root).
    ///                   Reads return 0 once this no longer equals {_liveEpoch} — conservative stale handling.
    ///                   Also the entry's **presence sentinel**: a stored entry always has `epoch != 0`, because
    ///                   {_upsertAttestation} rejects a zero epoch. Deliberately NOT `attestedAt`, which would rest
    ///                   the anti-double-count guard on `block.timestamp != 0` — true on every live chain, but an
    ///                   incidental property of the environment rather than an invariant this code enforces.
    /// @param attestedAt Timestamp of the most recent successful write. An operator freshness signal ONLY; nothing
    ///                   in this base branches on it.
    struct Attestation {
        uint256 value;
        bytes32 epoch;
        uint64 attestedAt;
    }

    //
    // State
    //

    /// @inheritdoc IAttestedBalanceAdapter
    /// @dev Gates the SUBMIT surface only — see the interface for why the clears deliberately stay permissionless.
    bytes32 public constant SUBMITTER_ROLE = SUBMITTER;

    /// @notice NAVCalculator — resolves the `Asset` metadata every emitted leg carries.
    INAVCalculator public immutable NAV_CALCULATOR;

    /// @dev Cached attestations. **`private`, deliberately** — see {_upsertAttestation}. If this were `public`
    ///      (or `internal`) a member could write it directly, and the base's central claim would be enforced by a
    ///      docstring rather than by the compiler. The concrete over-report that buys: a member zeroing an entry's
    ///      `epoch` while the asset is still in `_assetList` makes the next {_upsertAttestation} compute
    ///      `isNew == true` and push the SAME asset a second time, after which the read values it twice and
    ///      `_removeAsset`'s swap-and-pop can only ever remove one copy. `_assetList` / `_assetIdxPlus1` were
    ///      already `private` for exactly this reason; this makes the visibility symmetric. Read access for members
    ///      is {_attestationOf}; there is deliberately no write accessor.
    mapping(address account => mapping(address asset => Attestation)) private _attestations;

    /// @dev Per-account asset enumeration. Attested adapters cannot enumerate their universe ahead of time (the set
    ///      of assets a protocol may attest is open), so {underlyingAssetsSupported} returns empty and the reads are
    ///      driven from this list instead of from an `address(0)` asset filter.
    mapping(address account => address[]) private _assetList;

    /// @dev `idxPlus1` = index of `asset` in `_assetList[account]` plus 1. Zero ⇒ not present.
    mapping(address account => mapping(address asset => uint256)) private _assetIdxPlus1;

    /// @notice The cached attestation for `(account, asset)`: `(value, epoch, attestedAt)`.
    /// @dev ABI-identical to the public mapping this replaced, so no consumer sees a difference. An entry with
    ///      `epoch == 0` is absent; a non-zero `epoch` that no longer equals {_liveEpoch} is stale and reads 0.
    /// @inheritdoc IAttestedBalanceAdapter
    function attestations(address account, address asset)
        external
        view
        override
        returns (uint256 value, bytes32 epoch, uint64 attestedAt)
    {
        Attestation memory a = _attestations[account][asset];
        return (a.value, a.epoch, a.attestedAt);
    }

    /// @dev Read-only accessor for members. There is deliberately NO write accessor: {_upsertAttestation} is the
    ///      only way a value enters the cache.
    function _attestationOf(address account, address asset) internal view returns (Attestation memory) {
        return _attestations[account][asset];
    }

    // Events and errors are declared on {IAttestedBalanceAdapter} — they are universal to the family, so a
    // consumer can subscribe and decode reverts without importing this base or any member.

    //
    // Constructor
    //

    /// @param navCalculator_ The NAVCalculator. Must be a contract that can serve `getRegisteredAsset(address)`.
    /// @dev **NAV-VERSION PROBE — why an adapter refuses to be born against a NAVCalculator that is too old.** Every
    ///      read path in this base resolves asset metadata through the O(1) `getRegisteredAsset(address)`, which is
    ///      NEWER than the whole-registry `getRegisteredAssets()` that most plain adapters use via
    ///      `RegisteredAssetLib`. Pinned to a NAVCalculator that cannot serve the selector, the missing-function
    ///      revert lands in the adapter's OWN frame with a tiny `consumed`, so `GasStipendLib.exhausted` reads false,
    ///      `PriceFeedLib._getAdapterPositions` fails OPEN, and the adapter reports ZERO legs — for every account,
    ///      forever, with no error and a green CI. Members are immutable, so the only remedy would be a redeploy
    ///      nobody has been told is needed. Mirrors `MetaBalanceAdapter`'s constructor guard; keep the two in sync.
    ///
    ///      **Success alone proves nothing, which is why the length is checked too.** A contract with a bare
    ///      `fallback() external {}` answers any selector with success and EMPTY returndata. The 192-byte floor is
    ///      the minimum a real `(Asset, bool)` reply can occupy — `Asset` is `(address, string, uint8)`, hence
    ///      dynamic: 2 head words (offset, bool) + 3 words for Asset's head + 1 word for the empty string's length.
    ///      The `address(0)` argument elicits exactly that minimum, since `found == false` zeroes the struct, which
    ///      makes 192 the largest floor with no false positives.
    ///
    ///      **What it does NOT catch**, so the guarantee is not over-read: a UUPS *downgrade* of the NAV
    ///      implementation AFTER construction leaves the guard long since passed (members are immutable and cannot
    ///      re-probe on the hot path), and pointing at a NAVCalculator *implementation* rather than its proxy passes,
    ///      because the implementation serves the selector honestly and merely has empty storage. It binds the
    ///      deploy, not the lifetime.
    constructor(address navCalculator_, address admin_) {
        if (navCalculator_ == address(0) || admin_ == address(0)) revert InvalidArguments();
        AddressCheckLib.requireContract(navCalculator_, "NAVCalculator");

        (bool ok, bytes memory ret) =
            navCalculator_.staticcall(abi.encodeWithSelector(INAVCalculator.getRegisteredAsset.selector, address(0)));
        if (!ok || ret.length < 192) revert NAVCalculatorTooOld(navCalculator_);

        NAV_CALCULATOR = INAVCalculator(navCalculator_);
        _grantRole(DEFAULT_ADMIN_ROLE, admin_);
    }

    //
    // Mutators — the write surface (role-gated at the admission point)
    //

    /// @inheritdoc IAttestedBalanceAdapter
    function submit(address account, bytes calldata data) external override {
        _submitPayload(account, data);
    }

    /// @inheritdoc IAttestedBalanceAdapter
    function submitBatch(address[] calldata accounts, bytes[] calldata data) external override {
        // Checked HERE as well as in `_submitPayload`, because an EMPTY `accounts` array never enters the loop —
        // so without this a roleless caller gets a successful `submitBatch([], [])` having been authorized
        // nowhere. State-safe, but it would make "the batch succeeded" useless as evidence the keeper is granted.
        _checkRole(SUBMITTER_ROLE);
        if (accounts.length != data.length) revert InvalidArguments();
        for (uint256 i; i < accounts.length; ++i) {
            _submitPayload(accounts[i], data[i]);
        }
    }

    /// @dev The family's ONE write path. Fetches the epoch once, hands the payload to the member's single
    ///      decode-and-verify hook — **the same hook {previewPositions} uses**, which is what makes the two paths
    ///      structurally incapable of disagreeing about validity — then admits each verified element.
    ///
    ///      `internal` rather than `private` so a member's typed convenience entrypoint can funnel into it WITHOUT
    ///      an external self-call: `this.submit(...)` would rewrite `msg.sender` to the adapter itself and defeat
    ///      the role check at {_upsertAttestation}.
    function _submitPayload(address account, bytes memory data) internal {
        // Authorize the CALL, not merely each element. `_upsertAttestation` also checks (defence in depth), but it
        // only runs per element — so a zero-element payload used to return SUCCESS for an unauthorized caller,
        // having checked nothing. Harmless to state, but it made "submit succeeded" useless as evidence that a
        // keeper is actually granted, which is exactly the signal the role makes operators depend on.
        _checkRole(SUBMITTER_ROLE);
        if (account == address(0)) revert InvalidArguments();

        bytes32 epoch = _liveEpoch();
        if (epoch == bytes32(0)) revert UninitializedEpoch();

        (address[] memory assets, uint256[] memory values, bytes[] memory ctxs) = _verifyPayload(epoch, account, data);
        if (values.length != assets.length || ctxs.length != assets.length) revert InvalidArguments();

        for (uint256 i; i < assets.length; ++i) {
            // The member's own extra acceptance rule, applied BEFORE admission so a rejection leaves nothing behind.
            _beforeAdmit(account, assets[i], values[i], epoch);
            _upsertAttestation(account, assets[i], values[i], epoch);
            _storeMemberState(account, assets[i], ctxs[i]);
        }
    }

    //
    // Mutators — clearing (permissionless, stale-gated)
    //

    /// @notice Drop one cached attestation — **stale-gated GC**. Permissionless, but reverts
    ///         {AttestationStillLive} while the entry still contributes to NAV, so a live entry can only ever be
    ///         *refreshed*, never suppressed by a third party.
    /// @dev **Scope, precisely:** this protects entries that are IN the cache. It does not guarantee an entry can
    ///      GET in — admission is capped at {_maxAssetsPerAccount} and fails loud.
    ///
    ///      **"Stale" is not permanent, and this gate is instantaneous — so a clear here can outlive the staleness
    ///      that licensed it.** If the member's epoch source can return to a previous value (Merkl's
    ///      `getMerkleRoot()` does, by design, during a dispute window), an entry cleared while its epoch was not
    ///      live does NOT come back when that epoch does. Direction is under-report and it self-heals on the next
    ///      feed cycle. Retaining stale entries instead would make them un-clearable for the whole window, which is
    ///      the un-evictable-slot condition behind cap-exhaustion outages — trading an under-report that recovers on
    ///      its own for one that wedges until a human intervenes.
    function clearAttestation(address account, address asset) external override {
        if (account == address(0) || asset == address(0)) revert InvalidArguments();
        if (_attestations[account][asset].epoch == bytes32(0)) revert NothingToClear();
        if (_valueOf(account, asset) != 0) revert AttestationStillLive(account, asset);
        _deleteAttestation(account, asset);
        _removeAsset(account, asset);
        _deleteMemberState(account, asset); // last: the cache is fully settled before member code runs
        emit AttestationCleared(account, asset);
    }

    /// @inheritdoc IAttestedBalanceAdapter
    /// @dev Stale-gated **bulk** GC: reverts on the first of `account`'s assets that still contributes to NAV, so a
    ///      live set can never be suppressed — it clears only when the whole set is dead.
    function clearAccount(address account) external override {
        if (account == address(0)) revert InvalidArguments();
        address[] memory list = _assetList[account];
        if (list.length == 0) revert NothingToClear();
        for (uint256 i; i < list.length; ++i) {
            if (_valueOf(account, list[i]) != 0) revert AttestationStillLive(account, list[i]);
        }
        for (uint256 i; i < list.length; ++i) {
            _deleteAttestation(account, list[i]);
            delete _assetIdxPlus1[account][list[i]];
        }
        delete _assetList[account];
        // Member hooks LAST, in a second pass, for the ordering reason on {_deleteAttestation}: no member code may
        // run while any part of this account's cache is still half-cleared.
        for (uint256 i; i < list.length; ++i) {
            _deleteMemberState(account, list[i]);
        }
        emit AccountCleared(account);
    }

    //
    // Reads — introspection
    //

    /// @notice Assets currently cached for `account`.
    /// @dev Returned regardless of staleness. Filter at the call site on `attestations(account, asset).epoch`.
    /// @inheritdoc IAttestedBalanceAdapter
    function maxAssetsPerAccount() external view override returns (uint256) {
        return _maxAssetsPerAccount();
    }

    /// @inheritdoc IAttestedBalanceAdapter
    function isAttestationLive(address account, address asset) external view override returns (bool) {
        Attestation memory a = _attestations[account][asset];
        return a.epoch != bytes32(0) && _isLive(a, asset);
    }

    /// @inheritdoc IAttestedBalanceAdapter
    function assetsOf(address account) external view override returns (address[] memory) {
        return _assetList[account];
    }

    /// @inheritdoc IERC165
    /// @dev Advertises the family marker plus the two adapter interfaces every member implements. A member adding a
    ///      further interface overrides and `super`s.
    function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, IERC165) returns (bool) {
        return interfaceId == type(IAttestedBalanceAdapter).interfaceId
            || interfaceId == type(IBalanceAdapter).interfaceId || interfaceId == type(IPositionDescribable).interfaceId
            || super.supportsInterface(interfaceId);
    }

    /// @inheritdoc IBalanceAdapter
    /// @notice Open-universe family: an attested adapter's asset set is not enumerable ahead of time, so this
    ///         returns empty. The interface allows it, and the reads drive off the per-account cache instead.
    function underlyingAssetsSupported() external view virtual override returns (address[] memory) {
        return new address[](0);
    }

    //
    // Reads — IBalanceAdapter
    //

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

    /// @inheritdoc IBalanceAdapter
    function getAdapterBalances(address account)
        external
        view
        override
        returns (address[] memory assets, uint256[] memory amounts, bool[] memory isDebt)
    {
        if (account == address(0)) return (new address[](0), new uint256[](0), new bool[](0));

        address[] memory list = _assetList[account];
        uint256 n = list.length;
        address[] memory tmpAssets = new address[](n);
        uint256[] memory tmpAmounts = new uint256[](n);
        uint256 count;

        for (uint256 i; i < n; ++i) {
            uint256 bal = _valueOf(account, list[i]);
            if (bal != 0) {
                tmpAssets[count] = list[i];
                tmpAmounts[count] = bal;
                ++count;
            }
        }

        assets = new address[](count);
        amounts = new uint256[](count);
        isDebt = new bool[](count);
        for (uint256 i; i < count; ++i) {
            assets[i] = tmpAssets[i];
            amounts[i] = tmpAmounts[i];
        }
    }

    /// @inheritdoc IBalanceAdapter
    /// @dev Resolves `assetFilter` here so the build frame's only parameters are `(account, assets)` — keeping the
    ///      filter param, which is stack-bottom for this whole body, off the build loop's stack, which would
    ///      otherwise overflow the via_ir limit.
    function getAdapterPositions(address account, address assetFilter)
        external
        view
        override
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        if (account == address(0)) return new INAVCalculator.PositionBalance[](0);

        address[] memory toProcess;
        if (assetFilter != address(0)) {
            if (_assetIdxPlus1[account][assetFilter] == 0) return new INAVCalculator.PositionBalance[](0);
            toProcess = new address[](1);
            toProcess[0] = assetFilter;
        } else {
            toProcess = _assetList[account];
        }

        // Nothing cached (the overwhelmingly common case, since an adapter is registered globally and queried for
        // every account): return before the self-call, so an empty cache pays for neither the extra frame nor the
        // per-asset registry lookups. Those lookups are charged against the per-adapter stipend
        // `PriceFeedLib._getAdapterPositions` forwards.
        if (toProcess.length == 0) return new INAVCalculator.PositionBalance[](0);

        positions = this.buildPositionsSelf(account, toProcess);
    }

    /// @notice External self-call entrypoint for the row-building loop. `msg.sender`-guarded to `address(this)` so
    ///         it is not a usable external surface — it exists only to give the build its own stack frame. `view`,
    ///         so the self-call is a staticcall.
    function buildPositionsSelf(address account, address[] calldata assets)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        if (msg.sender != address(this)) revert NotAuthorized();
        return _collectLegs(account, assets);
    }

    //
    // Reads — cache-free preview
    //

    /// @inheritdoc IAttestedBalanceAdapter
    /// @dev The generic half of the preview: guards and the self-call frame. The member owns
    ///      {_verifyPayload}, which is where its proof scheme lives.
    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, data);
    }

    /// @notice External self-call frame for the preview loop — `msg.sender`-guarded to `address(this)`. `view`, so
    ///         the self-call is a staticcall. Mirrors {buildPositionsSelf}.
    /// @dev Fetches the epoch ONCE and hands it to the member, so a payload can never be verified against a
    ///      different epoch than the one its legs are valued under.
    function previewPositionsSelf(address account, bytes calldata data)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        if (msg.sender != address(this)) revert NotAuthorized();

        bytes32 epoch = _liveEpoch();
        if (epoch == bytes32(0)) revert UninitializedEpoch();

        (address[] memory assets, uint256[] memory values, bytes[] memory ctxs) = _verifyPayload(epoch, account, data);
        // The three are indexed in lockstep below. A member returning ragged arrays would otherwise surface as a
        // bare Panic 0x32; fail loud with an attributable error instead.
        if (values.length != assets.length || ctxs.length != assets.length) revert InvalidArguments();
        if (assets.length == 0) return new INAVCalculator.PositionBalance[](0);
        if (assets.length > _maxAssetsPerAccount()) revert TooManyAttestations(account, assets.length);
        _revertOnDuplicateAsset(assets);

        return _buildVerifiedLegs(account, assets, values, ctxs);
    }

    //
    // Internal — cache mutation
    //

    /// @dev Add or refresh one attestation. **THE SINGLE POINT WHERE A NUMBER ENTERS THE CACHE** — the caller MUST
    ///      have verified its protocol attestation for `(account, asset, value)` against `epoch` before calling.
    ///      This base cannot check that, and it is the whole basis of the family's guarantee.
    ///
    ///      **Upsert, never replace.** Only the named `(account, asset)` is touched; assets omitted by a feeder are
    ///      left alone, so a caller can add or refresh proven data but can NEVER suppress a live entry it omits.
    ///      Removal is only via the stale-gated clears.
    ///
    ///      The new-asset branch keys on `epoch == 0`, NOT on `attestedAt`. That branch is the only thing standing
    ///      between the cache and a DUPLICATE entry in the enumeration list, which would value one asset twice — an
    ///      OVER-report, the one direction this family forbids. `epoch` is a sentinel this contract enforces
    ///      itself (a zero epoch is rejected above), whereas `attestedAt != 0` would rest on `block.timestamp != 0`.
    /// @return isNew True when this call admitted a new asset rather than refreshing an existing one.
    function _upsertAttestation(address account, address asset, uint256 value, bytes32 epoch)
        internal
        returns (bool isNew)
    {
        // THE AUTHORIZATION POINT, deliberately co-located with the ADMISSION point. Gating here rather than on
        // each member's typed `submit` means a member cannot ship an ungated write path by omission: every route
        // into the cache passes through this function, so every route is gated. `msg.sender` is the original
        // external caller — this is `internal`, so no frame is introduced between the member's entrypoint and here.
        _checkRole(SUBMITTER_ROLE);

        if (account == address(0) || asset == address(0)) revert InvalidArguments();
        if (epoch == bytes32(0)) revert UninitializedEpoch();

        Attestation storage a = _attestations[account][asset];
        isNew = a.epoch == bytes32(0);
        if (isNew) {
            uint256 n = _assetList[account].length;
            if (n >= _maxAssetsPerAccount()) revert TooManyAttestations(account, n);
            _assetList[account].push(asset);
            _assetIdxPlus1[account][asset] = _assetList[account].length;
        }

        a.value = value;
        a.epoch = epoch;
        a.attestedAt = uint64(block.timestamp);

        emit AttestationCached(account, asset, msg.sender, value, epoch, a.attestedAt);
    }

    /// @dev Erase one attestation's base record. **DELIBERATELY `private`, so it cannot be overridden**, because
    ///      this is the ONLY deletion of `_attestations` in the base and an override that forgot to call `super`
    ///      would permanently wedge the entry — the record would survive while the clear delisted the asset, after
    ///      which re-admission computes `isNew == false` and never re-pushes, leaving the pair invisible to
    ///      {getAdapterPositions}/{getAdapterBalances} while {getAdapterBalanceForAsset} still reported it, and
    ///      unrecoverable because the clear that would reset it now reverts `AttestationStillLive`.
    ///
    ///      **It deliberately does NOT invoke {_deleteMemberState}.** Callers run that LAST, once the record AND
    ///      the enumeration are both settled, because the hook is the one place in a clear where MEMBER code
    ///      executes. Invoking it here — between the record delete and the enumeration update — would expose the
    ///      exact `record absent, asset still enumerated` state that {_upsertAttestation}'s `isNew` branch reads as
    ///      "new": a member whose hook called back into a submit (directly, or by making an external call that
    ///      re-enters) would push the still-enumerated asset a SECOND time, and the read would value it twice.
    ///      That is the duplicate-push OVER-report the `private` mapping closes at the member's own level, and
    ///      ordering is what closes it at the hook's.
    function _deleteAttestation(address account, address asset) private {
        delete _attestations[account][asset];
    }

    /// @notice Drop any extra per-`(account, asset)` state the member keeps alongside the attestation (Merkl's
    ///         campaign breakdown), so it goes in lockstep with the clears. Default: genuinely nothing.
    /// @dev Called by every deletion path in this base, and always **LAST** — after the record has been erased and
    ///      the asset delisted, so member code never observes a half-cleared cache. A member overriding it need NOT
    ///      call `super`: the base's own record is erased by {_deleteAttestation}, which is `private` precisely so
    ///      that guarantee does not depend on the member remembering.
    function _deleteMemberState(address account, address asset) internal virtual {
        account;
        asset;
    }

    /// @dev Swap-and-pop `asset` out of `account`'s enumeration, keeping the index map exact.
    function _removeAsset(address account, address asset) private {
        uint256 idxPlus1 = _assetIdxPlus1[account][asset];
        if (idxPlus1 == 0) return;
        uint256 idx = idxPlus1 - 1;
        address[] storage list = _assetList[account];
        uint256 lastIdx = list.length - 1;
        if (idx != lastIdx) {
            address last = list[lastIdx];
            list[idx] = last;
            _assetIdxPlus1[account][last] = idx + 1;
        }
        list.pop();
        delete _assetIdxPlus1[account][asset];
    }

    //
    // Internal — valuation
    //

    /// @dev The cached attestation's live value, or 0 when nothing is cached or the epoch has moved on.
    ///      **Stale ⇒ 0, never extrapolated** — a new epoch requires a fresh attestation.
    function _valueOf(address account, address asset) internal view returns (uint256) {
        Attestation memory a = _attestations[account][asset];
        // The ABSENCE check stays here, ahead of the validity predicate and deliberately not overridable: it is
        // what {_upsertAttestation}'s anti-duplicate branch keys on, so an override that could resurrect an absent
        // entry would reopen the double-count.
        if (a.epoch == bytes32(0)) return 0;
        if (!_isLive(a, asset)) return 0;
        return _liveValue(account, asset, a.value);
    }

    /// @dev Values each of `assets` in its own stipended frame and flattens the legs.
    ///
    ///      **PER-ASSET ISOLATION.** Without it, one asset's failure escapes the whole adapter two ways: a plain
    ///      revert bubbles out of {getAdapterPositions} and `PriceFeedLib._getAdapterPositions` fails open, costing
    ///      the account its ENTIRE leg set for this adapter; an out-of-gas bubbles, is classified by
    ///      `GasStipendLib.exhausted`, and `AdapterGasExhausted` takes down the account's WHOLE `getAccountNav`.
    ///
    ///      This bounds per-item FAILURE. It does NOT bound aggregate SIZE — stipends partition cost, they do not
    ///      shrink it — which is what {_maxAssetsPerAccount} times the member's write-enforced per-asset leg cap is for. The two are not
    ///      substitutes: isolation alone still leaves a well-behaved read at the cap unaffordable, and the caps
    ///      alone still lose the whole set to one reverting asset.
    ///
    ///      **The budget is SHARED across the assets still to value, not 63/64 to whoever is first.**
    ///      `GasStipendLib.stipendFrom` alone is right for a SINGLE forwarded call and wrong inside a loop: the
    ///      first asset would take 63/64 of the frame, leaving 1/64 for every remaining asset AND for the final
    ///      array construction — which was measured, on the first member, to revert a read that succeeded without
    ///      the griefing asset present. Dividing by the remaining count bounds each asset to its fair slice; because
    ///      `gasleft()` is re-read every iteration, assets that finish cheaply hand their unused share onward, so
    ///      the healthy path is not starved.
    ///
    ///      **DROPPING a failed asset is licensed here, and that licence is conditional.** It is safe only because
    ///      every leg an attested member emits today is a CREDIT. A dropped leg can then only make reported NAV
    ///      SMALLER, which is the direction this family already guarantees. `AssistedCoordCache` raises
    ///      `CoordinateGasExhausted` instead precisely because a future member of THAT family could emit a debt leg,
    ///      and silently dropping a debt leg makes NAV LARGER — the one direction this codebase forbids.
    ///      **A member that can emit a debt leg cannot use this family at all.** `_collectLegs` is NOT virtual and
    ///      the charter forbids debt legs outright — an attested-liability protocol needs a sibling base and its
    ///      own interface id, not an override here.
    ///
    ///      All-or-nothing per asset, mirroring `NAVCalculator._MAX_LABEL_ELEMENTS`: an asset that half-computed
    ///      before exhausting its stipend has its legs discarded as a unit, because a truncated answer reads as a
    ///      complete one.
    function _collectLegs(address account, address[] memory assets)
        internal
        view
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        // PRE-FILTER to the assets that will actually be VALUED. This is not tidy-up: the stipend denominator below
        // must count only assets that get a frame. Counting assets that are then skipped as unregistered reserves
        // budget nothing ever spends, so an early registered asset is funded as if the skipped ones were still
        // coming and can be dropped for want of gas while most of the frame goes unused.
        //
        // Resolve through the O(1) `getRegisteredAsset(address)`, NOT the O(N) whole-registry `getRegisteredAssets()`
        // copy, whose cost is super-linear in the REGISTRY size rather than in this account's asset count.
        address[] memory live = new address[](assets.length);
        INAVCalculator.Asset[] memory metas = new INAVCalculator.Asset[](assets.length);
        uint256 liveCount;
        for (uint256 i; i < assets.length; ++i) {
            (INAVCalculator.Asset memory meta, bool found) = NAV_CALCULATOR.getRegisteredAsset(assets[i]);
            if (!found) continue;
            live[liveCount] = assets[i];
            metas[liveCount] = meta;
            ++liveCount;
        }
        if (liveCount == 0) return new INAVCalculator.PositionBalance[](0);

        // Per-asset declared leg counts, kept so the copy below can be bounded against THIS asset's own slice
        // rather than against the shared buffer — see the bound in the loop.
        uint256[] memory legCaps = new uint256[](liveCount);
        uint256 cap;
        for (uint256 i; i < liveCount; ++i) {
            legCaps[i] = _cachedLegCount(account, live[i]);
            cap += legCaps[i];
        }

        // COMPLETION RESERVE, held back from every stipend so the loop can always finish: the catch arm and the
        // final allocation-and-copy must stay affordable after the LAST asset consumes everything it was given.
        // Without it the last asset's denominator is 1, so it receives the whole remaining stipend and completion is
        // funded only by `stipendFrom`'s 1/64 slack — a shrinking absolute amount. Scaled by the leg cap because the
        // copy is what it pays for, and that is O(legs).
        uint256 reserve = _completionReservePerLeg() * cap;

        INAVCalculator.PositionBalance[] memory tmp = new INAVCalculator.PositionBalance[](cap);
        uint256 count;
        for (uint256 i; i < liveCount; ++i) {
            uint256 available = gasleft();
            uint256 budget = available > reserve ? available - reserve : 0;
            uint256 stipend = GasStipendLib.stipendFrom(budget) / (liveCount - i);
            try this.assetLegsSelf{gas: stipend}(account, live[i], metas[i]) returns (
                INAVCalculator.PositionBalance[] memory legs, uint256 assetValue
            ) {
                uint256 legSum;
                // BOUND AGAINST THIS ASSET'S OWN SLICE, not against the shared buffer. {_cachedLegCount} is a
                // member hook and the legs come from the unrelated {_assetLegs}; the monolith derived both from
                // one expression so they could not disagree, but here they can, and writing past `tmp` raises
                // Panic 0x32 in THIS frame — outside the per-asset `try`, so the catch below cannot absorb it. It
                // would bubble out of {getAdapterPositions}, `PriceFeedLib` would fail open, and the adapter's
                // ENTIRE leg set would silently leave NAV for every account.
                //
                // The slice is what makes the blast radius honest. An earlier version bounded on
                // `count == tmp.length`, i.e. the ACCOUNT-WIDE buffer: an over-emitting asset then consumed the
                // capacity reserved for the assets after it, and those lost ALL their legs rather than none —
                // "drops only the surplus" was false, and a single-asset test could not see it. Capping each
                // asset at what it declared confines the loss to that asset's own surplus.
                //
                // **The surviving drop here is WHOLE-ASSET, never partial** — and that is what lets every
                // guard below be honest. An over-emitting member has ITS ASSET dropped entirely, the same arm
                // the `catch` takes and for the same reason:
                //
                //   * not a truncation. Truncating discarded the surplus WITHOUT inspecting it, and a discarded
                // INSPECT EVERY LEG FIRST, THEN decide whether to keep the asset. The order is load-bearing, and
                // this is the second time it has been got wrong in the same function.
                //
                // An earlier version `break`-ed at the cap, which terminated INSPECTION rather than the copy. The
                // fix for that hoisted a whole-asset `continue` ABOVE this loop — reintroducing the same class of
                // bug from the other side: a member emitting `[credit(10), debt(100)]` against a declared count
                // of 1 had its asset dropped WITHOUT any leg being inspected, so the debt leg never raised
                // {DebtLegRejected}. The asset's true net is -90 and NAV reported 0. **Omitting a debt leg is an
                // OVER-report just as surely as emitting a spurious credit is** — and a set-containment argument
                // over the legs actually emitted cannot see it, because the harm is in what was left OUT.
                // Dropping is safe only while every leg is non-negative, which is exactly what the charter check
                // below establishes and therefore cannot be assumed before it has run.
                //
                // Inspecting all `legs.length` costs nothing extra in practice: the `try … returns` above has
                // already `returndatacopy`d and ABI-decoded the whole array into this frame, so the decode
                // dominates the per-leg compare and is the binding constraint either way.
                for (uint256 j; j < legs.length; ++j) {
                    // FOUR axes, not three, and they are not independent, in the order a violation hurts:
                    //   DIRECTION — a debt leg that never reaches NAV inflates it, whether it was emitted and
                    //               dropped or dropped along with its asset;
                    //   IDENTITY  — `balanceAsset.asset` is the PRICING KEY `PriceFeedLib` resolves a feed from.
                    //               Leaving it unpinned makes the magnitude bound below compare numbers that are
                    //               not in the same currency: a member could pass count, direction and
                    //               `legSum == assetValue` in the attested asset's raw units while denominating
                    //               its legs in a different registered asset, inflating quote-NAV by the price
                    //               ratio. Unbounded, in the one direction the family forbids;
                    //   MAGNITUDE — legs must PARTITION the asset's value, not each carry all of it.
                    // `balanceAdapter` is checked too, but it is the audit-trail invariant rather than a pricing
                    // input — NAV reads it only for a fail-open display staticcall.
                    legSum = _admitLeg(legs[j], live[i], legSum, assetValue);
                }

                // ONLY NOW is dropping safe: every leg is proven a credit denominated in this asset, so losing
                // them can only shrink NAV. {_cachedLegCount} is documented as an UPPER BOUND, so a member
                // emitting more than it declared violates that hook's contract. Dropping the asset WHOLE rather
                // than truncating keeps the buffer bound provable — each asset contributes either 0 or
                // `legs.length <= legCaps[i]` entries, so `count <= sum(legCaps) == tmp.length` by construction.
                if (legs.length > legCaps[i]) continue;
                for (uint256 j; j < legs.length; ++j) {
                    tmp[count++] = legs[j];
                }
            } catch {
                // Drop this asset entirely — never revert, and never emit a partial set for it. See the docstring.
            }
        }

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

    /// @notice External self-call entrypoint for one asset's legs, enabling the per-asset isolation in
    ///         {_collectLegs}. `msg.sender`-guarded to `address(this)`. `view`, so the self-call is a staticcall.
    ///         Mirrors `AssistedCoordCache.valueCoordSelf`.
    /// @dev Returns the value alongside the legs so {_collectLegs} can bound their SUM in its own frame. The bound
    ///      cannot live here: this function is reached through a `try`, so a revert would be caught and silently
    ///      demoted to "drop this asset" — turning a charter violation into exactly the quiet under-report the
    ///      isolation exists to produce for honest failures.
    function assetLegsSelf(address account, address asset, INAVCalculator.Asset memory meta)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory, uint256)
    {
        if (msg.sender != address(this)) revert NotAuthorized();
        uint256 value = _valueOf(account, asset);
        // Early return before the member touches its own storage when there is nothing to value (the common case).
        if (value == 0) return (new INAVCalculator.PositionBalance[](0), 0);
        return (_assetLegs(account, asset, meta, value, _attestations[account][asset].value, "", true), value);
    }

    /// @dev Shared tail of the preview: skip assets NAVCalculator does not price, value each through the SAME
    ///      {_liveValue} and {_assetLegs} the cache path uses — so the two can never diverge — and compact.
    ///      Unlike the cache read this does NOT gas-stipend or try/catch per asset: it is the caller's own
    ///      `eth_call` gas, and a bad proof MUST surface rather than be caught and dropped.
    function _buildVerifiedLegs(address account, address[] memory assets, uint256[] memory values, bytes[] memory ctxs)
        private
        view
        returns (INAVCalculator.PositionBalance[] memory positions)
    {
        uint256 cap;
        for (uint256 i; i < assets.length; ++i) {
            cap += _previewLegCount(ctxs[i]);
        }
        INAVCalculator.PositionBalance[] memory tmp = new INAVCalculator.PositionBalance[](cap);
        uint256 count;

        for (uint256 i; i < assets.length; ++i) {
            (INAVCalculator.Asset memory meta, bool found) = NAV_CALCULATOR.getRegisteredAsset(assets[i]);
            if (!found) continue;
            uint256 live = _liveValue(account, assets[i], values[i]);
            if (live == 0) continue;
            INAVCalculator.PositionBalance[] memory legs =
                _assetLegs(account, assets[i], meta, live, values[i], ctxs[i], false);
            // FAIL LOUD here, unlike the cache path. The silent drop in {_collectLegs} is licensed by the NAV
            // read's fail-open behaviour — losing a leg beats losing the account's whole NAV. This path has
            // neither: it is the caller's own `eth_call`, documented fail-loud, and a member whose
            // {_previewLegCount} under-declares is a bug the caller should see rather than a truncated answer
            // that reads as complete.
            // PER-ASSET first, then the aggregate. Bounding only the aggregate let one asset silently borrow the
            // budget of an asset the loop had already skipped (`!found`, or `live == 0`) — `cap` above sums
            // {_previewLegCount} over EVERY entry, including skipped ones. A member could then return more legs
            // for asset A here than the cache path would accept for the same A, so the two paths disagreed on
            // identical inputs — the one outcome the shared {_assetLegs}/{_liveValue} tail exists to prevent.
            if (legs.length > _previewLegCount(ctxs[i])) revert InvalidArguments();
            if (count + legs.length > tmp.length) revert InvalidArguments();
            uint256 legSum;
            for (uint256 k; k < legs.length; ++k) {
                legSum = _admitLeg(legs[k], assets[i], legSum, live);
                tmp[count++] = legs[k];
            }
        }

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

    /// @notice The leg-admission contract, in ONE place. Returns the running sum so the caller can carry it.
    /// @dev **Deliberately shared by both read paths.** They previously each carried their own copy of these
    ///      checks, and drifted twice: the preview's copy was live code asserted by no test at all, and it was
    ///      later found to be missing the per-asset count bound the cache path had. A single checker makes that
    ///      class of divergence impossible rather than merely unlikely — the two paths cannot disagree about what
    ///      a valid leg is, because there is only one answer.
    ///
    ///      The four axes, in the order a violation hurts. All four are member-controlled: `_assetLegs` is
    ///      necessarily `virtual` and returns member-built structs, so nothing forces a member through {_row}.
    ///        1. DIRECTION — the credit-only charter. A debt leg that does not reach NAV inflates it, and that is
    ///           true whether it was emitted and dropped or dropped along with its asset.
    ///        2. IDENTITY — `balanceAsset.asset` is the PRICING KEY `PriceFeedLib` resolves a feed from. Without
    ///           this pin the magnitude bound below compares numbers that are not in the same currency.
    ///        3. ATTRIBUTION — `balanceAdapter == address(this)` is the repo-wide audit trail. Not a pricing
    ///           input (NAV reads it only for a fail-open display staticcall), but it is the reconciliation key.
    ///        4. MAGNITUDE — legs must PARTITION the asset's value, not each carry all of it.
    /// @param value The asset's live value: `assetValue` on the cache path, `live` on the preview. Both are the
    ///              same quantity — exactly what was handed to {_assetLegs} as `liveValue`, via {_liveValue}.
    function _admitLeg(INAVCalculator.PositionBalance memory leg, address asset, uint256 legSum, uint256 value)
        private
        view
        returns (uint256)
    {
        if (leg.isDebt) revert DebtLegRejected(asset);
        if (leg.balanceAsset.asset != asset) revert LegAssetMismatch(asset);
        if (leg.balanceAdapter != address(this)) revert LegAdapterMismatch(asset);
        legSum += leg.amount;
        if (legSum > value) revert LegSumExceedsValue(asset);
        return legSum;
    }

    /// @dev Reverts {DuplicateAsset} if any asset appears twice. O(n²) over ≤ {_maxAssetsPerAccount} entries; the
    ///      preview caller pays its own `eth_call` gas.
    function _revertOnDuplicateAsset(address[] memory assets) private pure {
        for (uint256 i; i < assets.length; ++i) {
            for (uint256 j = i + 1; j < assets.length; ++j) {
                if (assets[i] == assets[j]) revert DuplicateAsset(assets[i]);
            }
        }
    }

    /// @dev Builds one PositionBalance row with the family's conventions: `balanceAdapter` is always
    ///      `address(this)` (the audit trail), `amount` is always positive, and `isDebt` / `isLocked` default false.
    ///      Field-by-field rather than a struct literal to stay under the via_ir stack limit on the hot path.
    function _row(INAVCalculator.Asset memory asset, uint256 amount, bytes memory pid, bytes32 instanceId)
        internal
        view
        returns (INAVCalculator.PositionBalance memory row)
    {
        row.balanceAsset = asset;
        row.balanceAdapter = address(this);
        row.amount = amount;
        row.protocolBrand = _protocolBrand();
        row.protocolId = _protocolId();
        row.protocolSubId = _protocolSubId();
        row.positionId = pid;
        row.positionKind = _positionKind();
        row.positionInstanceId = instanceId;
    }

    //
    // Hooks — the member's protocol
    //

    /// @notice Is this cached attestation still valid? Default: its epoch equals the current one.
    /// @dev The family invariant is "an entry that is no longer provably current reads **0**"; epoch EQUALITY is
    ///      one instantiation of it, not the definition. Override for a scheme where validity is not an equality
    ///      check — a signature with a TTL (`a.attestedAt + TTL >= block.timestamp`), a per-asset anchor, or a
    ///      grace window accepting the previous anchor too.
    ///
    ///      Equality rather than ordering is deliberate for the default and must stay that way for any
    ///      anchor-comparing member: an anchor can be NON-MONOTONIC (Merkl's dispute window rolls the root back),
    ///      so "newer than cached" is not a safe generalisation of "current".
    ///
    ///      Governs BOTH the reported value and the stale-gated clears, since both route through {_valueOf} —
    ///      one predicate, not two policies that could drift apart.
    function _isLive(Attestation memory a, address asset) internal view virtual returns (bool) {
        asset;
        return a.epoch == _liveEpoch();
    }

    /// @notice The current attestation epoch (Merkl: `Distributor.getMerkleRoot()`). MUST be cheap: it is read on
    ///         every valuation. Returning zero means "uninitialized" and is rejected fail-loud on writes.
    function _liveEpoch() internal view virtual returns (bytes32);

    /// @notice Turn a cached/verified attested figure into the amount to report NOW, reading live protocol state
    ///         (Merkl: `attestedValue − Distributor.claimed(...)`, floored at 0). Reached only after the epoch has
    ///         been established as live, so it must not re-check staleness.
    /// @dev **POSTCONDITION: the return value SHOULD NOT exceed `attestedValue`.** Nothing here clamps it, and that
    ///      is deliberate — a clamp would be wrong for a member whose live figure can legitimately grow past what
    ///      was attested (an attested principal that accrues on-chain, say). But the family's guarantee is that the
    ///      **attestation bounds the reported number**, so a member that can exceed it has stepped outside that
    ///      guarantee and MUST say so explicitly in its own docs: past that point "under-report only" no longer
    ///      follows from the proof, and the over-report direction is live. Merkl satisfies the postcondition
    ///      trivially — it subtracts a non-negative claimed amount.
    function _liveValue(address account, address asset, uint256 attestedValue) internal view virtual returns (uint256);

    /// @notice Per-account cache cap — the only bound this base enforces.
    /// @dev **It is NOT the read bound on its own.** The leg count is this cap times the member's per-asset leg
    ///      fan-out, and it is that PRODUCT a read budget must be sized against. The base deliberately does not
    ///      declare a `_maxLegsPerAsset` hook: the per-asset cap belongs on the WRITE path, enforced fail-loud by
    ///      the member before the data exists (Merkl's `TooManyCampaigns`), because rejecting at write is what keeps
    ///      the read bounded. A read-side hook would either duplicate that or silently truncate. The base needs only
    ///      {_cachedLegCount}, the ACTUAL count, to size its scratch buffer.
    function _maxAssetsPerAccount() internal pure virtual returns (uint256);

    /// @notice Legs this asset will emit from the CACHE, for scratch-buffer sizing. Default: one. A member that
    ///         splits an asset into sub-positions overrides it.
    /// @dev **MUST be an UPPER BOUND on what {_assetLegs} returns for the same asset.** The two are separate hooks
    ///      that the base cannot reconcile, so under-declaring would write past the scratch buffer. {_collectLegs}
    ///      bounds the copy defensively, so the consequence is the surplus legs being dropped rather than the whole
    ///      read dying — but the legs are lost silently, so get this right rather than relying on the backstop.
    function _cachedLegCount(address account, address asset) internal view virtual returns (uint256) {
        account;
        asset;
        return 1;
    }

    /// @notice Legs a PREVIEW entry will emit, from that entry's `ctx`. Default: one.
    /// @dev Same upper-bound requirement as {_cachedLegCount}, for the preview's buffer.
    function _previewLegCount(bytes memory ctx) internal view virtual returns (uint256) {
        ctx;
        return 1;
    }

    /// @notice Build one asset's legs. Shared by the cache read (which passes an empty `ctx`, so the member reads
    ///         its own storage) and the preview (which passes the caller-supplied breakdown), so both produce
    ///         identical legs from identical inputs.
    /// @param liveValue     What to report — already resolved through {_liveValue}, always non-zero here.
    /// @param attestedValue The attested figure `liveValue` derives from; the denominator for any pro-rata split.
    /// @param ctx           Member-defined per-entry context. **Empty on the cache path**, which members use to
    ///                       decide "read my own storage" vs "use the caller's payload". That convention is
    ///                       load-bearing and easy to break from the preview side: `abi.encode` of an EMPTY array
    ///                       is 64 bytes, not 0, so an empty breakdown still arrives as non-empty `ctx` — but a
    ///                       member that returns a literal `bytes("")` from {_verifyPayload} for a
    ///                       breakdown-less entry would silently fall through to CACHED state while valuing a
    ///                       caller-supplied amount, mixing the two paths. Never return an empty `ctx` from the
    ///                       preview; encode the empty collection instead.
    function _assetLegs(
        address account,
        address asset,
        INAVCalculator.Asset memory meta,
        uint256 liveValue,
        uint256 attestedValue,
        bytes memory ctx,
        bool fromCache
    ) internal view virtual returns (INAVCalculator.PositionBalance[] memory);

    /// @notice Decode and VERIFY a preview payload against `epoch`, returning parallel arrays. **This is where the
    ///         member's proof scheme lives, and it MUST be the same verification the write path uses** — otherwise
    ///         the preview and the cache can disagree, which is the one thing the shared valuation tail exists to
    ///         prevent. Fail-loud: an invalid proof MUST revert, not be skipped.
    function _verifyPayload(bytes32 epoch, address account, bytes memory data)
        internal
        view
        virtual
        returns (address[] memory assets, uint256[] memory values, bytes[] memory ctxs);

    /// @notice A member's EXTRA acceptance rule on the write path, applied per element before admission. Default:
    ///         nothing. Merkl uses it for its cache-only monotonicity guard.
    /// @dev Write-path only — the preview has no cached prior value to compare against, which is precisely the
    ///      asymmetry this hook exists to express. MUST revert to reject.
    function _beforeAdmit(address account, address asset, uint256 value, bytes32 epoch) internal view virtual {
        account;
        asset;
        value;
        epoch;
    }

    /// @notice Persist the member's own per-element state alongside the attestation (Merkl's campaign breakdown).
    ///         Default: nothing. The counterpart of {_deleteMemberState}.
    function _storeMemberState(address account, address asset, bytes memory ctx) internal virtual {
        account;
        asset;
        ctx;
    }

    /// @notice Gas withheld from the per-asset stipends, per leg, so the read can complete after the last asset
    ///         consumes everything it was given. Overridable; the default is the value the first member measured.
    function _completionReservePerLeg() internal pure virtual returns (uint256) {
        return 256;
    }

    //
    // Hooks — typed position identity
    //

    function _protocolBrand() internal pure virtual returns (bytes32);
    function _protocolId() internal pure virtual returns (bytes32);
    function _protocolSubId() internal pure virtual returns (bytes32);

    /// @notice The `PositionKind` every leg carries. A member may NOT return a kind that implies a debt leg: the
    ///         family charter is credit-only and the base rejects any leg with `isDebt` set. A debt-attesting
    ///         protocol wants a sibling base, not an override here.
    function _positionKind() internal pure virtual returns (PositionKind);
}

src/balances/IAttestedBalanceAdapter.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 IAttestedBalanceAdapter
/// @author KPK
/// @notice Marker interface for the **attested** balance-adapter family: externally-fed adapters whose positions
///         cannot be derived from on-chain state alone and are kept fresh by a **role-gated off-chain agent** — a
///         plain keeper EOA / cron, **not** a `delegatecall` assistant contract — that submits, **on behalf of** a
///         tracked account, that account's cached elements. The defining trait is that **every write carries a
///         protocol-specific validity proof verified on-chain** (an *attestation*): a write only lands if its proof
///         validates, so the **proof-bound value** is always the account's real, protocol-attested figure.
///         **The attestation covers that value and nothing else.** A member may cache auxiliary metadata the proof
///         does NOT commit to — Merkl's campaign ids and per-campaign split are submitter-controlled, with only
///         their SUM checked against the proven per-token total — so consumers must not treat cached position
///         IDENTITY as attested. A member that caches such metadata must document it.
/// @dev **How this differs from {IAssistedBalanceAdapter}** (the other externally-fed family):
///      - {IAssistedBalanceAdapter} is `msg.sender`-keyed and fed by a `delegatecall` assistant so the adapter sees
///        `msg.sender = the position owner`; it caches **coordinates only, never amounts** and re-verifies ownership
///        live per read. Its integrity rests on `msg.sender`-keying + live-ownership re-verification.
///      - an **attested** adapter is **submit-on-behalf-of** — the submit mutator takes an explicit `account` (one
///        agent feeds many tracked accounts), by an ordinary external caller holding `SUBMITTER_ROLE`: no assistant contract, no
///        `delegatecall`. Its integrity rests on the on-chain **proof** carried by every write.
///
///      **Trust model & invariant.** Because the feeder submits on behalf of arbitrary accounts, integrity does NOT come from `msg.sender`-keying or live-ownership re-verification. Instead **every
///      write carries a protocol-specific validity proof checked on-chain** (e.g. Merkl merkle-proof verification
///      against the live `Distributor.getMerkleRoot()`), so a faulty or malicious feeder can only ever cache an
///      account's **real proof-bound VALUE** — **under-report, never over-report** on the number. It does NOT
///      extend to auxiliary metadata a member caches beside that value, which may be submitter-controlled. Writes are a per-element **upsert** (add /
///      refresh a proven element); a submit **never drops** an element it omits, so a third party can never suppress
///      a live entry by submitting a partial or empty set. Removal is only via the stale-gated `clearAccount` / `clearAttestation`
///      (both below, both universal). Stale entries read as 0 (e.g. cached root ≠ live root).
///
///      The per-protocol **submit** signature (typed element shape + its validity proof) is deliberately NOT
///      prescribed here — it varies by protocol. The interface advertises the family (via ERC-165), the one universal
///      mutator (`clearAccount`), and one universal **read** (`previewPositions(account, bytes)`): the read's proof
///      data is opaque `bytes` at the family level (each member `abi.decode`s it into its own shape), so a single
///      signature serves every attested adapter, present and future, with the `bytes` being whatever that protocol needs.
/// @dev **CHARTER: this family reports CREDITS ONLY.** Every leg an adapter advertising THIS interface id emits
///      has `isDebt == false`, and the base ENFORCES it rather than asking members to remember. The enforcement
///      stack, stated precisely because an earlier version of this text over-claimed it: the scalar reads and the
///      per-item failure policy are non-virtual, so the compiler blocks them; `_row`, the base's leg constructor,
///      cannot set the flag; and — because `_assetLegs` is necessarily virtual and returns member-built structs,
///      so nothing forces a member through `_row` — the base also REJECTS a debt leg at runtime as it collects,
///      reverting {DebtLegRejected}. The conformance kit asserts the same property at test time. The scope is
///      deliberate — an
///      attested-LIABILITY protocol is conceivable, but under this base it would need the reads, the leg builder,
///      the per-item failure policy and the drop licence all overridden in concert, which is maximally easy to
///      get wrong. Such a protocol wants a sibling base and its own interface id, not an override of this one.
///
///      This is what licenses the base's per-item **drop** on a failed read: a dropped CREDIT leg can only make
///      NAV smaller, the direction the family already tolerates. Dropping a DEBT leg would make NAV larger — the
///      one direction forbidden — so the licence and the charter stand or fall together.
interface IAttestedBalanceAdapter is IAccessControl, IBalanceAdapter {
    /// @notice Role required to SUBMIT attestations. Granted and revoked by `DEFAULT_ADMIN_ROLE`.
    /// @dev **Gates the write surface only.** The family's clears stay permissionless and stale-gated on purpose:
    ///      role-gating removal is exactly what audit finding L-02 flagged on an earlier draft, where a compromised
    ///      role-holder could delete valid LIVE allocations — a targeted under-report caused by the mechanism meant
    ///      to prevent one. The stale gate (an entry may only be cleared once it already contributes 0) makes
    ///      clearing safe for any caller, which is why it needs no role.
    ///
    ///      **What the role buys, and what it does not.** It does NOT protect the reported AMOUNT — the per-write
    ///      proof already does that, and no caller could ever write an unattested figure. What it protects is the
    ///      space the proof does not cover: **which elements occupy the per-account cache** (cap squatting) and
    ///      **how a proven total is labelled** (member-supplied sub-position metadata such as Merkl's campaign
    ///      split). Both are bounded, non-NAV-affecting griefs under a permissionless surface; the role closes
    ///      them at the cost of a privileged key and a liveness chokepoint on cache freshness.
    function SUBMITTER_ROLE() external view returns (bytes32);

    // ─── Events ─── every member emits these; typed here so an indexer never imports a member or the base.

    /// @notice Emitted on every `(account, asset)` upsert.
    /// @param submitter The caller that wrote it. Attribution for monitoring — authorization is `SUBMITTER_ROLE`.
    event AttestationCached(
        address indexed account,
        address indexed asset,
        address indexed submitter,
        uint256 value,
        bytes32 epoch,
        uint64 attestedAt
    );
    event AttestationCleared(address indexed account, address indexed asset);
    event AccountCleared(address indexed account);

    // ─── Errors ─── declared here so a consumer can decode a revert without importing the implementation.

    /// @notice The NAVCalculator supplied at construction cannot serve `getRegisteredAsset(address)`.
    error NAVCalculatorTooOld(address navCalculator);
    /// @notice The member's attestation epoch source returned zero (uninitialized).
    error UninitializedEpoch();
    /// @notice Admitting this element would exceed the member's per-account cache cap.
    error TooManyAttestations(address account, uint256 count);
    /// @notice A clear was attempted on an element still contributing to NAV. Clearing is GC for dead entries only.
    error AttestationStillLive(address account, address asset);
    /// @notice A clear was attempted on an `(account, asset)` with nothing cached.
    error NothingToClear();
    /// @notice The same asset appeared twice in a {previewPositions} payload — a double-count, rejected fail-loud.
    error DuplicateAsset(address asset);

    /// @notice A member returned a leg with `isDebt == true`, which this family's charter forbids.
    /// @dev The base's per-item DROP on a failed read is licensed ONLY because every leg is a credit: a dropped
    ///      credit leg shrinks NAV (tolerated), a dropped debt leg inflates it (forbidden). Rather than trust a
    ///      member to honour that, the base checks it as it collects. A debt-attesting protocol wants a sibling
    ///      base and its own interface id — see the charter on this interface.
    ///
    ///      **Blast radius on the NAV path, so it is not over-read as a per-leg drop.** This reverts in the
    ///      collecting frame, OUTSIDE the per-asset `try`, so it is not absorbed by the per-item isolation: it
    ///      bubbles out of `getAdapterPositions`, and `PriceFeedLib` fails open on a plain revert, so the
    ///      adapter's ENTIRE leg set leaves NAV for that account rather than just the offending asset. That is
    ///      the intended severity — a member emitting debt has broken the family's central assumption, and the
    ///      whole adapter should stop contributing rather than contribute something quietly wrong — but the
    ///      direction is under-report, so it degrades NAV rather than inflating it.
    error DebtLegRejected(address asset);

    /// @notice A member's legs for one asset summed to MORE than that asset's live value.
    /// @dev The third structural bound on member-built legs, alongside the count cap and the credit-only check.
    ///      The family's whole point is that the attestation BOUNDS the reported figure, and legs are supposed to
    ///      partition that figure — so a member emitting two legs each carrying the full value doubles the account's
    ///      reported holding while passing every other guard. Direction: OVER-report, the one direction forbidden.
    ///
    ///      **BLAST RADIUS — the same one {DebtLegRejected} carries.** This is thrown from `_collectLegs`, which
    ///      sits OUTSIDE the per-asset `try`, so it bubbles out of `getAdapterPositions`. Through `PriceFeedLib`
    ///      — the NAV path — a plain revert fails OPEN, so the adapter's ENTIRE leg set silently leaves NAV for
    ///      that account, not just the offending asset. Two caveats: a DIRECT `getAdapterPositions` caller sees
    ///      the revert normally, and if the frame is near-exhausted when this fires, `GasStipendLib.exhausted`
    ///      can classify it as an OOG and re-raise `AdapterGasExhausted`, which kills the whole account's
    ///      `getAccountNav` rather than failing open. The trigger can be tiny and the loss total: a member using CEILING-rounded
    ///      pro-rata splits is one wei over on one asset and loses the whole account's adapter contribution, with
    ///      no error anywhere. Split with a FLOOR (`Math.mulDiv` rounds down by default), as the README recipe
    ///      says and as the Merkl member does. Note the asymmetry with an over-emitted leg COUNT, which drops
    ///      only its own asset — confining these four the same way is a live option, deliberately not taken in
    ///      the same sitting that wrote them.
    error LegSumExceedsValue(address asset);

    /// @notice A member returned a leg denominated in a DIFFERENT asset than the one being valued.
    /// @dev The fourth axis, and the one that makes the magnitude bound dimensionally sound. `balanceAsset.asset`
    ///      is the PRICING KEY — `PriceFeedLib` resolves a feed from exactly this field and converts `amount`
    ///      through it. Without this pin a member could pass the count, direction and magnitude bounds in the
    ///      attested asset's raw units while denominating its legs in some other REGISTERED asset, inflating
    ///      quote-NAV by the price ratio: unbounded, and in the direction the family forbids. Bounding amounts
    ///      without pinning the unit compares numbers that are not in the same currency.
    ///
    ///      **BLAST RADIUS — the same one {DebtLegRejected} carries.** This is thrown from `_collectLegs`, which
    ///      sits OUTSIDE the per-asset `try`, so it bubbles out of `getAdapterPositions`; `PriceFeedLib` fails
    ///      OPEN on a plain revert, and the adapter's ENTIRE leg set silently leaves NAV for that account — not
    ///      just the offending asset. The trigger can be tiny and the loss total: a member using CEILING-rounded
    ///      pro-rata splits is one wei over on one asset and loses the whole account's adapter contribution, with
    ///      no error anywhere. Split with a FLOOR (`Math.mulDiv` rounds down by default), as the README recipe
    ///      says and as the Merkl member does. Note the asymmetry with an over-emitted leg COUNT, which drops
    ///      only its own asset — confining these four the same way is a live option, deliberately not taken in
    ///      the same sitting that wrote them.
    error LegAssetMismatch(address expected);

    /// @notice A member returned a leg attributed to an adapter other than itself.
    /// @dev `balanceAdapter == address(this)` is a repo-wide invariant and the audit trail every reconciliation
    ///      keys on. Nothing but the shared `_row` helper was upholding it, and `_assetLegs` is virtual.
    ///
    ///      **BLAST RADIUS — the same one {DebtLegRejected} carries.** This is thrown from `_collectLegs`, which
    ///      sits OUTSIDE the per-asset `try`, so it bubbles out of `getAdapterPositions`; `PriceFeedLib` fails
    ///      OPEN on a plain revert, and the adapter's ENTIRE leg set silently leaves NAV for that account — not
    ///      just the offending asset. The trigger can be tiny and the loss total: a member using CEILING-rounded
    ///      pro-rata splits is one wei over on one asset and loses the whole account's adapter contribution, with
    ///      no error anywhere. Split with a FLOOR (`Math.mulDiv` rounds down by default), as the README recipe
    ///      says and as the Merkl member does. Note the asymmetry with an over-emitted leg COUNT, which drops
    ///      only its own asset — confining these four the same way is a live option, deliberately not taken in
    ///      the same sitting that wrote them.
    error LegAdapterMismatch(address asset);

    // ─── Reads ───

    /// @notice The cached attestation for `(account, asset)`.
    /// @dev `epoch == 0` means absent. A non-zero `epoch` that no longer matches the member's live epoch is STALE
    ///      and values as 0 — so a non-zero `value` here is NOT by itself a claim that the element contributes to
    ///      NAV. Use {IBalanceAdapter.getAdapterBalanceForAsset} for the figure actually reported.
    function attestations(address account, address asset)
        external
        view
        returns (uint256 value, bytes32 epoch, uint64 attestedAt);

    /// @notice The per-account cache cap: the most distinct assets this adapter will hold for one account.
    /// @dev Family-level because the base enforces it (`TooManyAttestations` on admission) and because a
    ///      protocol-agnostic consumer needs it without knowing the member: comparing `assetsOf(account).length`
    ///      against this is how you detect an account approaching the cap, whether through ordinary accumulation
    ///      or through a third party occupying slots. Constant per deployment — no admin can loosen it.
    function maxAssetsPerAccount() external view returns (uint256);

    /// @notice Whether `account`'s cached attestation for `asset` is still valid under this member's scheme.
    /// @dev **Disambiguates the three states that all read as a balance of 0**, which a consumer otherwise cannot
    ///      tell apart and which need three different responses: nothing cached (`attestations().epoch == 0`);
    ///      cached but no longer current, i.e. the feeder is behind (false here — page the feeder); and cached,
    ///      current, but fully consumed (true here, balance 0 — garbage-collect it).
    ///
    ///      Deliberately a PREDICATE rather than an exposed epoch. What "still valid" means is per-protocol — a
    ///      merkle root matching, a signature inside its TTL, a per-asset anchor — and publishing one global epoch
    ///      would freeze the first member's scheme into the family contract forever. Every member can answer this
    ///      question; not every member has a single global anchor to publish.
    ///
    ///      Two honest caveats. **It can flap**: a protocol whose anchor is non-monotonic (Merkl's dispute window
    ///      rolls the root back) can return false and then true again for the same entry. And **live is not the
    ///      same as counted** — a live but fully-consumed entry reads 0 and is clearable.
    function isAttestationLive(address account, address asset) external view returns (bool);

    /// @notice The assets currently cached for `account`, stale ones included.
    /// @dev The family cannot enumerate its universe ahead of time, so `underlyingAssetsSupported()` is empty and
    ///      this per-account list is what drives the reads. Filter on `attestations(...).epoch` for freshness.
    function assetsOf(address account) external view returns (address[] memory);

    // ─── Mutators ───

    // ─── Mutators — the write surface ───

    /// @notice Submit attestations for `account`. Requires {SUBMITTER_ROLE}.
    /// @dev **`data` is opaque at the family level**, exactly as on {previewPositions} — each member `abi.decode`s
    ///      it into its own element/proof shape, so ONE signature serves every attested adapter. The two take the
    ///      SAME payload by design and share the member's single decode-and-verify hook, which is what stops the
    ///      write path and the preview from ever disagreeing about what a valid attestation is.
    ///
    ///      Semantics are **upsert**: each element in `data` adds or refreshes its own `(account, asset)` and
    ///      elements omitted from `data` are left untouched, so a submit can never suppress a live entry. Removal is
    ///      only via the stale-gated clears. **Atomic** — any invalid element reverts the whole call, leaving the
    ///      prior set intact.
    ///
    ///      A member MAY additionally expose a typed convenience entrypoint (Merkl's `submitProofs`) for ABI
    ///      ergonomics, but this generic one is the family contract and every member has it.
    /// @param account The account the attestations are for.
    /// @param data    ABI-encoded, protocol-specific attestation data (Merkl: `abi.encode(Allocation[])`).
    function submit(address account, bytes calldata data) external;

    /// @notice Batch variant — one payload per account. Requires {SUBMITTER_ROLE}.
    /// @dev **Atomic across accounts:** any single invalid element reverts the ENTIRE batch, so no account in the
    ///      call is updated. Deliberate fail-loud handling, but it means a multi-account feeder should pre-filter
    ///      bad data (or fall back to {submit}) so one account cannot block every other account's refresh.
    function submitBatch(address[] calldata accounts, bytes[] calldata data) external;

    /// @notice Drop ONE cached element — permissionless, **stale-gated** garbage collection.
    /// @dev Universal, not per-protocol: implemented once for the whole family. Reverts {AttestationStillLive}
    ///      while the element still contributes to NAV, so a live entry can only be *refreshed*, never suppressed.
    ///      **Deliberately not role-gated** — see {SUBMITTER_ROLE}.
    function clearAttestation(address account, address asset) external;

    /// @notice Drop **all** of `account`'s cached elements — permissionless, **stale-gated** garbage collection.
    /// @dev Takes an explicit `account` because this family is submit-on-behalf-of (contrast
    ///      {IAssistedBalanceAdapter.clearAccount}, which is `msg.sender`-keyed and unconditional). **Reverts if ANY
    ///      of `account`'s elements is still live** (still contributing to NAV), so a live set can only ever be
    ///      *refreshed* via the per-protocol submit, never suppressed by a third party — preserving the
    ///      under-report-only invariant. Clears only when the whole set is stale/dead (reads already 0).
    function clearAccount(address account) external;

    /// @notice Trustless, CACHE-FREE preview: value `account`'s positions from **caller-supplied** off-chain proof
    ///         data, with no prior submit and without touching the cache. `data` is opaque at the family level — each
    ///         member `abi.decode`s it into its own proof shape (Merkl: `abi.encode(Allocation[])`) — so this one
    ///         signature serves every attested adapter, with `data` being whatever that protocol needs.
    /// @dev A `view`: reads no member cache and writes none, so it does not feed the cache and has no effect on the NAV
    ///      read (`getAdapterPositions`, which keeps reading the agent-fed cache). It carries the same integrity as the
    ///      write path — every proof in `data` is verified on-chain against the protocol's live root, so it can only
    ///      surface the account's real figure (under-report, never over-report) — and is **fail-loud** on an invalid
    ///      proof. An *extra* read for a portal / frontend / third party that computes proofs off-chain. Empty `data`
    ///      (or a zero `account`) returns an empty array. **As on the write path, the attestation covers only the
    ///      proof-bound value** — any auxiliary sub-position metadata a member returns (e.g. Merkl campaign identity,
    ///      where only the shares' SUM is checked) is submitter-controlled and NOT attested; consumers must not treat
    ///      returned position IDENTITY as proof-backed. See the member's docs.
    /// @param account The account to value (any address — proofs are public; the result is that account's real figure).
    /// @param data    ABI-encoded, protocol-specific proof/off-chain data (Merkl: `abi.encode(Allocation[])`).
    function previewPositions(address account, bytes calldata data)
        external
        view
        returns (INAVCalculator.PositionBalance[] memory positions);
}

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 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/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 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 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 on a duplicate.
    /// @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 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 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_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
///        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; 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 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 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");

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

src/utils/ProtocolNames.sol

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

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

/// @notice Canonical human-readable protocol display names — the string every adapter returns from
///         `IPositionDescribable.protocolName()`, one constant per `ProtocolIds` *protocol id*.
/// @dev **The contract this library exists to enforce:** `protocolName()` names the PROTOCOL, never the product.
///      Adapters that are different products of one protocol (Aave V3 lending / Safety Module / Umbrella; Morpho
///      vaults / markets; Balancer pools / gauges; …) share a `protocolId` and MUST therefore return the *same*
///      display name. What distinguishes the product is `positionLabels()` (`["Umbrella Module"]`,
///      `["Safety Module"]`, `["Market", "wstETH/USDC"]`) and the typed `protocolSubId`.
///
///      Why a shared constant and not a literal per adapter: consumers group configured adapters by
///      `protocolName()`. The typed `protocolBrand` / `protocolId` / `protocolSubId` would group them correctly, but
///      those are `private constant` and only ride on `PositionBalance` structs returned by an *account* read — a
///      consumer listing configured adapters never sees them. The display name is the only protocol identity such a
///      consumer has, so an adapter that returns its product name splits itself out into a bogus sibling protocol.
///      That is exactly what `AaveUmbrellaBalanceAdapter` did by returning "Aave Umbrella" (fixed to `AAVE_V3`).
///
///      Naming is one constant per **protocol id**, not per sub-id — there is deliberately no `AAVE_V3_UMBRELLA`
///      here. If you find yourself wanting one, the string you want belongs in `positionLabels()`.
///
///      These are `string internal constant`, so they are inlined at compile time exactly as a literal would be:
///      switching an adapter from `"Aave V3"` to `ProtocolNames.AAVE_V3` is bytecode-neutral.
///
///      Meta adapters do not hold a name at all: `MetaBalanceAdapter.protocolName()` returns
///      `forProtocolId(_protocolId())`, deriving it from the typed identity the adapter already declares. That is
///      what makes the invariant structural for that whole family — there is no second value to keep in sync.
/// @author KPK
library ProtocolNames {
    /// @dev Plain ERC20 holdings (`ERC20DefaultBalanceAdapter`, `ProtocolIds.WALLET`) — not a protocol as such.
    string internal constant WALLET = "Wallet";

    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    // Lending / money markets
    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────

    /// @dev `ProtocolIds.AAVE_V3` — shared by lending instances, the Safety Module, and Umbrella.
    string internal constant AAVE_V3 = "Aave V3";
    /// @dev `ProtocolIds.SPARK`.
    string internal constant SPARK = "Spark";
    /// @dev `ProtocolIds.MORPHO` — shared by vaults and markets. "Morpho", never "Morpho Blue" (see CLAUDE.md).
    string internal constant MORPHO = "Morpho";
    /// @dev `ProtocolIds.EULER`.
    string internal constant EULER = "Euler";
    /// @dev `ProtocolIds.SYMBIOTIC`.
    string internal constant SYMBIOTIC = "Symbiotic";
    /// @dev `ProtocolIds.COMPOUND_V3`.
    string internal constant COMPOUND_V3 = "Compound V3";
    /// @dev `ProtocolIds.FLUID` — shared by fTokens and T1 vaults.
    string internal constant FLUID = "Fluid";
    /// @dev `ProtocolIds.GEARBOX_V3` — shared by markets and credit accounts.
    string internal constant GEARBOX_V3 = "Gearbox";
    /// @dev `ProtocolIds.CAP`.
    string internal constant CAP = "Cap";

    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    // AMMs / LP staking
    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────

    /// @dev `ProtocolIds.BALANCER_V2` — shared by pools and gauges.
    string internal constant BALANCER_V2 = "Balancer V2";
    /// @dev `ProtocolIds.BALANCER_V3` — shared by pools and gauges.
    string internal constant BALANCER_V3 = "Balancer V3";
    /// @dev `ProtocolIds.CURVE` — shared by pools and gauges.
    string internal constant CURVE = "Curve";

    /// @dev `ProtocolIds.POLYGON` — Polygon PoS staking, settled on Ethereum L1.
    ///      Named for the PRODUCT ("Polygon Staking"), not the brand, because that is what the position is: the
    ///      chain is not the protocol here, and "Polygon" alone reads as a network row in a portfolio. Matches the
    ///      label DeBank uses and the product at https://staking.polygon.technology/.
    string internal constant POLYGON = "Polygon Staking";
    /// @dev `ProtocolIds.CONVEX`.
    string internal constant CONVEX = "Convex";
    /// @dev `ProtocolIds.UNISWAP_V2`.
    string internal constant UNISWAP_V2 = "Uniswap V2";
    /// @dev `ProtocolIds.UNISWAP_V3`.
    string internal constant UNISWAP_V3 = "Uniswap V3";
    /// @dev `ProtocolIds.PANCAKESWAP_V2`.
    string internal constant PANCAKESWAP_V2 = "PancakeSwap V2";
    /// @dev `ProtocolIds.PANCAKESWAP_V3`.
    string internal constant PANCAKESWAP_V3 = "PancakeSwap V3";

    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    // Staking / LSTs / withdrawal queues
    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────

    /// @dev `ProtocolIds.STAKEWISE_V3` — shared by the vaults meta-adapter and the exit-queue adapter.
    string internal constant STAKEWISE_V3 = "StakeWise V3";
    /// @dev `ProtocolIds.LIDO`.
    string internal constant LIDO = "Lido";
    /// @dev `ProtocolIds.KELP`.
    string internal constant KELP = "Kelp DAO";
    /// @dev `ProtocolIds.STADER`.
    string internal constant STADER = "Stader";
    /// @dev `ProtocolIds.ETHERFI` — lowercase is the protocol's own styling.
    string internal constant ETHERFI = "ether.fi";
    /// @dev `ProtocolIds.ETHENA`.
    string internal constant ETHENA = "Ethena";

    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    // Other
    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────

    /// @dev `ProtocolIds.NEXUS_MUTUAL`.
    string internal constant NEXUS_MUTUAL = "Nexus Mutual";

    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    // Rewards
    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────

    /// @dev `ProtocolIds.MERKL` — the attested Merkl rewards adapter (`MerklRewardsAttestedBalanceAdapter`).
    string internal constant MERKL = "Merkl";

    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
    // protocolId → display name
    // ─────────────────────────────────────────────────────────────────────────────────────────────────────────────

    /// @notice Thrown when a protocol id has no display name. Add the constant above and a branch below.
    error UnknownProtocolId(bytes32 protocolId);

    /// @notice The canonical display name for a `ProtocolIds` protocol id.
    /// @dev This is what makes "same `protocolId` ⇒ same `protocolName()`" true **by construction** rather than by
    ///      convention: `MetaBalanceAdapter.protocolName()` is `ProtocolNames.forProtocolId(_protocolId())`, so a
    ///      meta adapter cannot report a name that disagrees with its own typed identity — there is no separate
    ///      value to get wrong, and no deployment-time input to mis-supply. Adapters that hardcode their name
    ///      (the plain/assisted families) are pinned to the same table by `test/ProtocolNameConsistency.t.sol`.
    ///
    ///      Reverting on an unknown id is deliberate: the alternative — returning "" — would let a new meta adapter
    ///      deploy permanently nameless (adapters are immutable), and `protocolName()` is only ever reached through
    ///      NAVCalculator's fail-open staticcall, so a revert here degrades to an empty display name on a verbose
    ///      read rather than breaking a NAV read.
    /// @param protocolId The adapter's `ProtocolIds` protocol id (the middle taxonomy level).
    /// @return The display name every adapter under that protocol id must report.
    function forProtocolId(bytes32 protocolId) internal pure returns (string memory) {
        if (protocolId == ProtocolIds.AAVE_V3) return AAVE_V3;
        if (protocolId == ProtocolIds.MORPHO) return MORPHO;
        if (protocolId == ProtocolIds.SPARK) return SPARK;
        if (protocolId == ProtocolIds.EULER) return EULER;
        if (protocolId == ProtocolIds.SYMBIOTIC) return SYMBIOTIC;
        if (protocolId == ProtocolIds.COMPOUND_V3) return COMPOUND_V3;
        if (protocolId == ProtocolIds.FLUID) return FLUID;
        if (protocolId == ProtocolIds.GEARBOX_V3) return GEARBOX_V3;
        if (protocolId == ProtocolIds.CAP) return CAP;

        if (protocolId == ProtocolIds.BALANCER_V2) return BALANCER_V2;
        if (protocolId == ProtocolIds.BALANCER_V3) return BALANCER_V3;
        if (protocolId == ProtocolIds.CURVE) return CURVE;
        if (protocolId == ProtocolIds.CONVEX) return CONVEX;
        if (protocolId == ProtocolIds.UNISWAP_V2) return UNISWAP_V2;
        if (protocolId == ProtocolIds.UNISWAP_V3) return UNISWAP_V3;
        if (protocolId == ProtocolIds.PANCAKESWAP_V2) return PANCAKESWAP_V2;
        if (protocolId == ProtocolIds.PANCAKESWAP_V3) return PANCAKESWAP_V3;

        if (protocolId == ProtocolIds.STAKEWISE_V3) return STAKEWISE_V3;
        if (protocolId == ProtocolIds.POLYGON) return POLYGON;
        if (protocolId == ProtocolIds.LIDO) return LIDO;
        if (protocolId == ProtocolIds.KELP) return KELP;
        if (protocolId == ProtocolIds.STADER) return STADER;
        if (protocolId == ProtocolIds.ETHERFI) return ETHERFI;
        if (protocolId == ProtocolIds.ETHENA) return ETHENA;
        if (protocolId == ProtocolIds.NEXUS_MUTUAL) return NEXUS_MUTUAL;

        if (protocolId == ProtocolIds.MERKL) return MERKL;

        if (protocolId == ProtocolIds.WALLET) return WALLET;

        revert UnknownProtocolId(protocolId);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "metadata": {
    "appendCBOR": true,
    "bytecodeHash": "none",
    "useLiteralContent": false
  },
  "libraries": {
    "src/nav/NAVRegistryLib.sol": {
      "NAVRegistryLib": "0x55b6AA29D296Eb2Ee0e7b76686eaA2e479CA3511"
    },
    "src/prices/PriceFeedLib.sol": {
      "PriceFeedLib": "0x713e69954e11c2eD19dBB84950674D6a68DBfebc"
    }
  },
  "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.