Verified contractPartialBUSL-1.1
YoVaultsMetaBalanceAdapter
Address0x64fb8b1d04b28b0389beeb76e844e2935e25f4b3
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,429,944
- Creation transaction
- 0x7c3d62c68f…f22675e1cf
- Libraries
- src/nav/NAVRegistryLib.sol:NAVRegistryLib0x3d53…75934dsrc/prices/PriceFeedLib.sol:PriceFeedLib0x0f91…fafcf2
21 files
- src/balances/MetaBalanceAdapters/YoVaultsMetaBalanceAdapter.solmain10.5 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.66 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- src/balances/ERC4626RedeemLib.sol9.83 KB
- src/balances/IBalanceAdapter.sol2.43 KB
- src/balances/IBalances.sol5.02 KB
- src/balances/IMetaBalanceAdapter.sol2.86 KB
- src/balances/IPositionDescribable.sol5.07 KB
- src/balances/IPositionEnumerable.sol5.57 KB
- src/balances/LabelLib.sol12.67 KB
- src/balances/MetaBalanceAdapter.sol45.11 KB
- src/errors.sol3.05 KB
- src/nav/INAVCalculator.sol78.34 KB
- src/prices/IPrices.sol17.42 KB
- src/utils/AddressCheckLib.sol1.1 KB
- src/utils/GasStipendLib.sol4.74 KB
- src/utils/PositionKind.sol1.47 KB
- src/utils/ProtocolIds.sol16.94 KB
- src/utils/ProtocolNames.sol14.92 KB
src/balances/MetaBalanceAdapters/YoVaultsMetaBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {MetaBalanceAdapter} from "../MetaBalanceAdapter.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {ERC4626RedeemLib} from "src/balances/ERC4626RedeemLib.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
import {ProtocolIds} from "src/utils/ProtocolIds.sol";
/// @title YO Vaults Meta Balance Adapter
/// @author KPK
/// @notice One immutable adapter for YO Protocol vaults (`YoVault`, e.g. yoUSD Edge
/// `0x5DD8BFa6C5C68D05d25EF6143E05C11E26c4cDB7`). For each governed vault it reports up to TWO legs in the
/// vault's ERC-4626 asset, sharing one static `positionId = abi.encode(vault)` (ADR 0016):
/// - **held** shares: `Supplied`, `isLocked = false`, value `previewRedeem(balanceOf(account))`;
/// - **pending** redeem (shares escrowed by `requestRedeem`): `Supplied`, `isLocked = true`.
/// @dev **Why a YO adapter and not a `MorphoVaultsMeta` instance.** The held leg alone is plain ERC-4626 and the
/// Morpho meta adapter would value it correctly, but it would stamp a YO vault with `morpho` identity
/// (`protocolSubId = morpho-vaults`, `protocolName = "Morpho"`), which consumers key on (the Portal maps
/// `protocolSubId` to its protocol registry). Same reasoning as `SymbioticVaultsMetaBalanceAdapter`. YO's own
/// Morpho Vault V2 (YO Ecosystem) is a genuine Morpho vault and stays on `MorphoVaultsMeta`.
///
/// **Pending redeem mechanics** (verified against impl `0xc84a6E01…78DC` and on a fork). `requestRedeem(shares,
/// receiver, owner)` redeems instantly when idle liquidity covers it; otherwise it MOVES the shares from `owner`
/// to the vault and records `_pendingRedeem[receiver] = {assets, shares}`, settled later by a YO operator via
/// `fulfillRedeem(receiver, shares, atCurrentPrice)`. Without the pending leg the position would vanish from NAV
/// between request and fulfilment. `pendingRedeemRequest(user)` returns `(assets, shares)` — ASSETS FIRST — and
/// `assets` is the GROSS (pre-fee) `convertToAssets` reserved at request time (pinned in the fork test). The
/// entry is keyed on the RECEIVER and accumulates (`+=`) across requests, so a Safe that requests with
/// `receiver != itself` correctly moves the claim out of its own NAV, and any share holder can add to a
/// Safe's entry by requesting with `receiver = Safe` (a donation that goes to the receiver as assets on
/// fulfilment or as shares on cancellation, never an over-report).
///
/// **Pending valuation (conservative).** The operator pays the reserved gross, or — `atCurrentPrice`, allowed
/// only when the current value does not exceed the reservation — the current value; the fee is then taken from
/// that gross at the LIVE `feeOnWithdraw` (deducted even when `feeRecipient` is unset). The leg reports the
/// lower bound:
///
/// amount = min( net(pendingAssets), previewRedeem(pendingShares) )
/// net(x) = x - ceil(x * fee / (fee + 1e18)) (= YoVault._feeOnTotal)
///
/// `previewRedeem` is already fee-net and `net()` applies the fee once to the gross reservation: the fee is
/// applied exactly once on both branches, a price drop is reflected, a price rise is never credited. The bound
/// is attained by a single full fulfilment. When the operator settles an entry in `k` slices, YoVault rounds per
/// slice, so the leg can exceed the total payout by a few wei of the asset: at most `k - 1` at the reserved
/// price (the fee is rounded up per slice), and up to about `2(k - 1)` on `atCurrentPrice` slices (the gross
/// is floored per slice as well).
///
/// **Trust assumptions.** Both legs are only as good as the vault's own pricing: a YoVault converts shares at
/// the latest price pushed to YO's onchain oracle (limited by the oracle's windowed change guard; the vault
/// discards the price timestamp and its view path is not pause-gated), and the vault is an upgradeable proxy. This adapter
/// adds no price check of its own. The pending formula relies on THIS YoVault implementation's semantics
/// (`pendingRedeemRequest` field order, gross reservation, fee at fulfilment, `fulfillRedeem(.., bool)`), so
/// check that a vault runs the same implementation before adding it as an instance, and re-check after a YO
/// upgrade. The held leg's `isLocked = false` means "not in the redeem queue", not "instantly redeemable":
/// an instant redeem still depends on the vault's idle liquidity.
///
/// **Fail closed.** Share valuation goes through {ERC4626RedeemLib.redeemValue} (0 when `previewRedeem` is
/// unreadable, e.g. an oracle revert, so a leg it cannot value is dropped, never substituted by
/// `convertToAssets`; a starved read raises `RedeemValueGasExhausted` instead). Every other vault read (`asset`,
/// `balanceOf`, `pendingRedeemRequest`, `feeOnWithdraw`) is a plain high-level call: any failure reverts the
/// instance, which the base's metered per-instance isolation drops (an under-report of that vault's legs) or,
/// when the frame was starved, surfaces loudly as `InstanceGasExhausted`.
contract YoVaultsMetaBalanceAdapter is MetaBalanceAdapter {
/// @dev YoVault's fee denominator (`DENOMINATOR`, 1e18 = 100%).
uint256 private constant FEE_DENOMINATOR = 1e18;
/// @param navCalculator_ The NAVCalculator contract for asset-registry access.
constructor(address navCalculator_) MetaBalanceAdapter(navCalculator_) {}
//
// Valuation (public views, for monitoring and tests)
//
/// @notice Fee-net value of `account`'s held (non-escrowed) shares in `vault`; 0 if `previewRedeem` is unreadable.
function heldValue(address vault, address account) public view returns (uint256) {
if (account == address(0)) return 0;
return ERC4626RedeemLib.redeemValue(vault, IYoVault(vault).balanceOf(account));
}
/// @notice Fee-net lower-bound value of `account`'s pending redeem in `vault`.
/// @dev Plain high-level reads: a revert (or an undecodable reply) propagates to the base's metered
/// per-instance isolation, which drops the instance (under-report) or, on gas starvation, raises
/// `InstanceGasExhausted` loudly. No raw staticcall here by design (GATE 2 of
/// `script/deploy/preflight/source_comment_gates.py`).
function pendingValue(address vault, address account) public view returns (uint256) {
if (account == address(0)) return 0;
(uint256 pendingAssets, uint256 pendingShares) = IYoVault(vault).pendingRedeemRequest(account);
if (pendingAssets == 0 || pendingShares == 0) return 0;
uint256 fee = IYoVault(vault).feeOnWithdraw();
uint256 reservedNet = pendingAssets - Math.mulDiv(pendingAssets, fee, fee + FEE_DENOMINATOR, Math.Rounding.Ceil);
uint256 currentNet = ERC4626RedeemLib.redeemValue(vault, pendingShares);
return reservedNet < currentNet ? reservedNet : currentNet;
}
//
// MetaBalanceAdapter hooks
//
/// @inheritdoc MetaBalanceAdapter
/// @dev Up to two legs (held, pending), both `Supplied` in the vault asset under `abi.encode(vault)`; zero legs
/// are omitted. Empty when the asset is filtered out or not registered on the NAV.
function _instancePositions(address account, bytes32 instance, address assetFilter)
internal
view
override
returns (INAVCalculator.PositionBalance[] memory positions)
{
address vault = _toAddress(instance);
address asset = IYoVault(vault).asset();
if (assetFilter != address(0) && assetFilter != asset) return positions;
(INAVCalculator.Asset memory assetInfo, bool found) = _getAssetInfo(asset);
if (!found) return positions;
uint256 held = heldValue(vault, account);
uint256 pending = pendingValue(vault, account);
uint256 n = (held > 0 ? 1 : 0) + (pending > 0 ? 1 : 0);
positions = new INAVCalculator.PositionBalance[](n);
if (n == 0) return positions;
bytes memory pid = _instancePositionId(instance);
uint256 i;
if (held > 0) positions[i++] = _leg(assetInfo, held, false, pid, PositionKind.Supplied);
if (pending > 0) {
positions[i] = _leg(assetInfo, pending, false, pid, PositionKind.Supplied);
positions[i].isLocked = true;
}
}
/// @inheritdoc MetaBalanceAdapter
function _instanceAssets(bytes32 instance) internal view override returns (address[] memory assets) {
assets = new address[](1);
assets[0] = IYoVault(_toAddress(instance)).asset();
}
/// @inheritdoc MetaBalanceAdapter
/// @dev `["Vault", <vault name>]` (e.g. `["Vault", "yoUSD Edge"]`); the held and pending legs share it and are
/// told apart by `isLocked`. An unreadable name collapses to `["Vault"]`.
function positionLabels(bytes calldata pid) external view override returns (string[] memory) {
return _addressLabels(pid, "Vault", false);
}
/// @inheritdoc MetaBalanceAdapter
function _protocolBrand() internal pure override returns (bytes32) {
return ProtocolIds.YO;
}
/// @inheritdoc MetaBalanceAdapter
function _protocolId() internal pure override returns (bytes32) {
return ProtocolIds.YO;
}
/// @inheritdoc MetaBalanceAdapter
function _protocolSubId() internal pure override returns (bytes32) {
return ProtocolIds.YO_VAULTS;
}
}
/// @notice Minimal read surface of a YO vault (`YoVault`).
interface IYoVault {
/// @notice ERC-4626 underlying asset.
function asset() external view returns (address);
/// @notice ERC-20 share balance.
function balanceOf(address account) external view returns (uint256);
/// @notice Pending redeem of `user` (the RECEIVER of the request).
/// @return assets Gross (pre-fee) assets reserved at request time.
/// @return pendingShares Shares escrowed in the vault.
function pendingRedeemRequest(address user) external view returns (uint256 assets, uint256 pendingShares);
/// @notice Withdrawal fee on a 1e18 scale, applied to the gross at fulfilment.
function feeOnWithdraw() external view returns (uint256);
}
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/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/ERC4626RedeemLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {GasStipendLib} from "src/utils/GasStipendLib.sol";
/// @notice Minimal ERC4626 read surface for {ERC4626RedeemLib} — the fee-aware `previewRedeem`.
interface IERC4626Redeemable {
function previewRedeem(uint256 shares) external view returns (uint256 assets);
}
/// @notice `previewRedeem` ran out of the gas its frame was given, so the position could not be valued and must
/// not be silently dropped.
/// @dev Declared file-local rather than in `src/errors.sol`: both pinned libraries plain-import that file, so
/// adding to it would pull this symbol into both CREATE2 compilation closures for no benefit.
error RedeemValueGasExhausted(address vault, uint256 stipend, uint256 consumed);
/// @title ERC4626RedeemLib
/// @author KPK
/// @notice Shared fee-aware share→asset valuation for ERC4626 vaults whose wrapper may charge a withdrawal/exit
/// fee. {redeemValue} reports `previewRedeem` — which, per EIP-4626 §4.3, is net of any redemption fee —
/// and reports **nothing** when that read fails, rather than substituting a value known to be an upper
/// bound.
/// @dev Extracted so its callers share one copy of this subtle preference rather
/// than each inlining the read. Adapters that deliberately value at the raw rate (Euler, Fluid, Gearbox,
/// StakeWise, Cap) call `convertToAssets` directly and do NOT use this library.
library ERC4626RedeemLib {
/// @notice The fee-net asset value of `shares` in `vault`: `previewRedeem(shares)`, or **0** if that read
/// cannot be completed.
/// @dev **Why a failed read reports 0 rather than falling back to `convertToAssets`.** It used to fall back.
/// That fallback was unconditionally UPWARD and therefore an over-report, which is the one direction an
/// adapter in this repo may never take:
///
/// - EIP-4626 §4.3 requires `convertToAssets` to IGNORE any redemption fee, and requires
/// `previewRedeem` to include it. So `convertToAssets(s) >= previewRedeem(s)` by construction, with
/// the gap being exactly the fee. Substituting one for the other cannot lose value; it can only add
/// value that a redemption would not actually pay.
/// - `catch` fires for far more than the "vault is paused" case it was written for: a withdraw-queue
/// market reverting, and — the one that matters on a NAV read — `previewRedeem` running out of the
/// gas its frame was given, after which the cheaper `convertToAssets` can still complete. Gas
/// starvation therefore selected the inflated branch precisely when the read was least trustworthy.
/// - Nothing downstream can see it happen. The leg is emitted well-formed, with the right asset,
/// `positionId` and `positionKind`; only `amount` is larger. It is a balance-side failure, so no
/// price-side signal fires (`nav.stalePriceAssets`, `nav.irregularPriceAssets`, `pd.irregular` are
/// all untouched), and nothing reverted, so neither `AdapterGasExhausted` nor `InstanceGasExhausted`
/// fires either. `getAccountNavVerbose` is not a cross-check — it runs the same math over the same
/// `PositionBalance[]` and returns the same wrong number.
///
/// Reporting 0 instead is the same trade every sibling adapter already makes when it cannot value one
/// side of a position: drop the position rather than move the number upward. See
/// `GearboxV3CreditAccountsMetaBalanceAdapter` ("If the debt read fails for a credit account, the WHOLE
/// account is dropped … reporting collateral alone would overstate equity"),
/// `FluidVaultsMetaBalanceAdapter._instancePositions` ("A debt this adapter cannot report must never
/// leave its collateral standing alone … Under-reporting the whole position is the safe direction") and
/// `MorphoMarketsMetaBalanceAdapter._instancePositions` (the same sentence again). This library was the
/// one place in `src/balances` that resolved a failed read the other way.
///
/// **The cost, stated so it is not rediscovered as a bug.** A vault whose `previewRedeem` is unavailable
/// now contributes nothing instead of contributing a gross figure. That is a visible under-report — the
/// position disappears from a report the fund can compare against its own expectations — where the
/// behaviour it replaces was an invisible over-report. Every caller already treats 0 as "no leg"
/// (`MorphoVaultsMetaBalanceAdapter` and `SymbioticVaultsMetaBalanceAdapter` return an empty array;
/// `AaveUmbrellaBalanceAdapter` skips the leg; `YoVaultsMetaBalanceAdapter` drops the held leg and, as
/// the `min` of its pending valuation, the pending leg), so no caller-side change is needed and no caller
/// learns to trust a fabricated number. **That list is exhaustive as written; grep `redeemValue` before
/// relying on it** — it has already gone stale twice, when a third and a fourth caller were added.
///
/// **Why this is a raw staticcall and not `try`/`catch`.** An earlier revision used `try`/`catch` and
/// justified it with "the return type is a single `uint256`, so there is no decode that can revert past
/// the `catch`". That is FALSE, and the mistake is worth recording because it is the same class this
/// whole sweep exists to remove. A high-level call that expects return data does not emit an
/// `extcodesize` precheck — the returndata-size check subsumes it — so a callee returning ZERO bytes
/// makes the call SUCCEED and the `uint256` decode then reverts in THIS frame, outside the `catch`. The
/// trigger is the one the ezETH commit in this same PR calls "not hypothetical": an ERC-1967 proxy whose
/// implementation slot points at a code-less address.
///
/// The blast radius made it worse than a dropped leg. In `AaveUmbrellaBalanceAdapter` this is reached
/// from `_sharesToUnderlying` INLINE inside `getAdapterPositions`, with no per-stake-token isolation, and
/// through a wrapper address that was only ever probed with low-level staticcalls — never high-level
/// called. So the revert propagated out of the whole adapter, `PriceFeedLib._getAdapterPositions` scored
/// the cheap revert benign, and EVERY Umbrella staking, cooldown and rewards leg vanished from the NAV
/// with no staleness, irregular or gas signal set.
///
/// **The two failure kinds are now separated, because they deserve opposite answers.**
/// - **Starved** — `previewRedeem` ran out of the gas it was given. The position was NOT valued, and
/// returning 0 would silently delete it: `MorphoVaultsMetaBalanceAdapter` would emit an empty array
/// and SUCCEED, so no classifier upstream ever fires and an operator cannot tell the difference
/// between "starved" and "the fund exited the vault". That is the absorb-your-own-out-of-gas hole
/// this PR closes in {AssistedCoordCache} and {FluidVaultLib}, and it was left open here. It now
/// raises {RedeemValueGasExhausted}, which the callers' existing gas classifiers surface loudly.
/// - **Genuinely unreadable** — a revert, an empty reply, a short reply, a code-less vault. The vault
/// has answered, or cannot answer at all; there is nothing to value and no reason to fail the whole
/// account's read. Reports 0, which every caller already treats as "no leg".
///
/// The stipend is `GasStipendLib.stipendFrom` — a PROPORTION of the caller's own budget, not a fixed
/// ceiling. That matters here specifically: MetaMorpho's `previewRedeem` walks the withdraw queue, so a
/// fixed cap (`StaticCallLib.PROBE_GAS` is 100_000) could be exceeded by an entirely honest vault and
/// would be unrecoverable by supplying more gas. That is also why this does not simply call
/// {StaticCallLib.probeWord}, which is otherwise the right shape.
///
/// The 32-byte output window means the reply size cannot be charged to this frame, which the
/// `try`/`catch` form could not claim either.
function redeemValue(address vault, uint256 shares) internal view returns (uint256) {
bytes memory cd = abi.encodeCall(IERC4626Redeemable.previewRedeem, (shares));
// One sample, used both to derive the stipend and to measure against it — see GasStipendLib.exhausted.
uint256 available = gasleft();
uint256 stipend = GasStipendLib.stipendFrom(available);
bool ok;
uint256 size;
uint256 net;
assembly ("memory-safe") {
// 32-byte output window at the free pointer, WITHOUT bumping it — nothing allocates across this
// block. Zeroed first so a short reply cannot surface a previous allocation's bytes.
let out := mload(0x40)
mstore(out, 0)
ok := staticcall(stipend, vault, add(cd, 0x20), mload(cd), out, 0x20)
size := returndatasize()
net := mload(out)
}
if (ok && size >= 32) return net;
// The read did not produce a value. Which KIND of failure decides what happens next.
uint256 consumed = available - gasleft();
if (GasStipendLib.exhausted(stipend, consumed)) {
revert RedeemValueGasExhausted(vault, stipend, consumed);
}
return 0;
}
}
src/balances/IBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title IBalanceAdapter
/// @notice Standard interface for balance adapters (both default and custom)
/// @dev All balance adapters must implement this interface to work with the adapter-centric aggregation system
/// @dev Extends ERC165 to allow on-chain discovery with `supportsInterface`.
/// @author KPK
interface IBalanceAdapter is IERC165 {
/// @notice Get all positions from this adapter for an account
/// @param account The account to query
/// @param assetFilter Optional asset filter (address(0) for all assets)
/// @return positions Array of balance-only PositionBalance structs from this adapter
/// @dev Balance adapters return balance-only data without pricing. NAVCalculator enriches these with pricing.
function getAdapterPositions(address account, address assetFilter)
external
view
returns (INAVCalculator.PositionBalance[] memory positions);
/// @notice Get balances from this adapter for an account
/// @param account The account to query
/// @return assets Array of asset addresses
/// @return amounts Array of balance amounts (always non-negative magnitude)
/// @return isDebt Array of debt flags (true = debt, false = credit)
function getAdapterBalances(address account)
external
view
returns (address[] memory assets, uint256[] memory amounts, bool[] memory isDebt);
/// @notice Get single balance for a specific asset (gas-optimized version)
/// @param account The account to query
/// @param asset The asset address
/// @return amount Balance amount (non-negative magnitude)
/// @return isDebt True if debt, false if credit
function getAdapterBalanceForAsset(address account, address asset)
external
view
returns (uint256 amount, bool isDebt);
/// @notice Returns the list of all the underlying assets supported by this adapter
/// @dev The returned list may be empty if the adapter cannot determine or provide the supported assets
/// @return underlyingAssets The list of underlying asset addresses supported by this adapter (may be empty)
function underlyingAssetsSupported() external view returns (address[] memory underlyingAssets);
}
src/balances/IBalances.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @author KPK
interface IBalances {
//
// Type definitions
//
enum AdapterType {
Default,
Custom
}
struct BalanceAdapter {
address adapter;
AdapterType adapterType;
string protocol;
}
//
// Events
//
/// @notice Event emitted when a balance adapter is added to the global registry.
/// @param underlyingAsset Reserved; currently address(0) as adapters are registered globally, not per asset.
/// @param adapter The address of the adapter being added.
/// @param adapterType The type of the adapter (Default or Custom).
event BalanceAdapterAdded(address indexed underlyingAsset, address indexed adapter, AdapterType adapterType);
/// @notice Event emitted when a balance adapter is removed from the global registry.
/// @param underlyingAsset Reserved; currently address(0) as adapters are global.
/// @param adapter The address of the balance adapter being removed.
event BalanceAdapterRemoved(address indexed underlyingAsset, address adapter);
//
// Errors
//
/// @notice Error when the balance adapter is not set.
error BalanceAdapterNotSet();
/// @notice Error when the balance adapter is not valid.
error InvalidBalanceAdapter();
/// @notice Error when the balance adapter type is not valid.
error InvalidBalanceAdapterType();
/// @notice Error when the same balance adapter is already set.
error DuplicateBalanceAdapter();
/// @notice Error when adding a meta-instance coordinate that is already present (would double-count NAV).
error DuplicateMetaInstance();
/// @notice The coordinate is already governed by a DIFFERENT registered meta adapter.
/// @dev Two adapters holding one coordinate both emit a well-formed leg for the same holding under
/// different reconciliation keys, and NAV sums them with no health flag. Rejected at configuration
/// time because no read-path guard can see across adapters.
error MetaInstanceClaimedByAnotherAdapter(bytes32 instance, address claimedBy);
/// @notice Error when removing a meta-instance coordinate that is not present in the adapter's set.
error MetaInstanceNotFound();
/// @notice Error when a meta-adapter (implements IMetaBalanceAdapter) is registered via the plain
/// addBalanceAdapters path; meta-adapters must use addMetaBalanceAdapter.
error MetaAdapterNotAllowed();
/// @notice Error when a meta-adapter operation (registration via addMetaBalanceAdapter, or an
/// addMetaInstances / removeMetaInstances call) targets an adapter that is not a meta-adapter
/// (does not implement IMetaBalanceAdapter).
error NotMetaAdapter();
/// @notice Validates that the adapter implements IBalanceAdapter (reverts with InvalidBalanceAdapter if not).
/// @dev Reverts with InvalidArguments if `adapter` is the zero address.
/// @param adapter The address of the adapter to check.
function checkBalanceAdapterSupport(address adapter) external view;
//
// Global Adapter Registry
//
/// @notice Returns all registered adapters in the global registry
/// @return adapters Array of all adapter addresses
function getAllAdapters() external view returns (address[] memory adapters);
/// @notice Returns the total number of registered adapters
/// @return count Total number of adapters
function getAdapterCount() external view returns (uint256 count);
/// @notice Checks if an adapter is registered in the global registry
/// @param adapter The adapter address to check
/// @return registered True if the adapter is registered
function isAdapterRegistered(address adapter) external view returns (bool registered);
/// @notice Returns the type of a registered adapter
/// @dev Reverts with InvalidBalanceAdapter if the adapter is not registered.
/// @param adapter The adapter address
/// @return adapterType The type of the adapter
function getAdapterType(address adapter) external view returns (AdapterType adapterType);
/// @notice Returns all adapters that support the given asset
/// @dev Loops through all global adapters and checks if the asset is in their underlyingAssetsSupported() list
/// @param asset The asset address to check
/// @return adapters Array of adapter addresses that support the asset
function getAdaptersForAsset(address asset) external view returns (address[] memory adapters);
//
// Meta-adapter instance registry (ADR 0010)
//
/// @notice Returns the configured meta-adapter instance coordinates for an adapter (empty for non-meta adapters).
/// @param adapter The adapter address.
/// @return instances The instance coordinates currently configured for the adapter.
function getMetaInstances(address adapter) external view returns (bytes32[] memory instances);
}
src/balances/IMetaBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IBalanceAdapter} from "./IBalanceAdapter.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
/// @title IMetaBalanceAdapter
/// @author KPK
/// @notice Interface for *meta* balance adapters: a single immutable adapter that can report positions
/// for an arbitrary number of instances of one protocol (e.g. every Morpho vault, every Balancer pool).
/// @dev A meta-adapter is universal and instance-stateless — it holds no list of "active" instances and has no
/// admin/write functions. The set of instances to actually query lives on NAVCalculator (per-adapter,
/// MANAGER-gated). This keeps adapters immutable while making the governed "which instances" set mutable in
/// the upgradeable, AccessControl-gated NAVCalculator.
///
/// Instances are identified by a `bytes32` coordinate. For most protocols this is an address widened to
/// bytes32 (vault / pool / instance-DataProvider address); the wider type also accommodates protocols whose
/// instance key is itself a bytes32 (e.g. Morpho market ids).
///
/// Call path: NAVCalculator calls the inherited `getAdapterPositions(account, assetFilter)` on every adapter
/// uniformly (no ERC165 routing). A meta-adapter services it by reading its own NAV-configured set via
/// `getMetaInstances(address(this))` and fanning out over it — see `MetaBalanceAdapter`. The instance-aware
/// methods below take an explicit instance list for off-chain/explicit queries and per-instance breakdowns.
/// (The other no-arg `IBalanceAdapter` methods — `getAdapterBalances`/`getAdapterBalanceForAsset` —
/// are not used by the NAV path and return empty.)
interface IMetaBalanceAdapter is IBalanceAdapter {
/// @notice Get all positions for an account across the supplied instances.
/// @param account The account to query.
/// @param instances The instance coordinates to query (e.g. vault addresses widened to bytes32).
/// @param assetFilter Optional asset filter (address(0) for all assets).
/// @return positions Array of balance-only PositionBalance structs aggregated across the instances.
function getAdapterPositionsForInstances(address account, bytes32[] calldata instances, address assetFilter)
external
view
returns (INAVCalculator.PositionBalance[] memory positions);
/// @notice Returns the underlying assets supported across the supplied instances.
/// @param instances The instance coordinates to inspect.
/// @return underlyingAssets The list of underlying asset addresses (may contain duplicates across instances).
function underlyingAssetsSupportedForInstances(bytes32[] calldata instances)
external
view
returns (address[] memory underlyingAssets);
}
src/balances/IPositionDescribable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IPositionDescribable
/// @notice Optional interface for balance adapters that expose a human-readable protocol name for their positions.
/// @dev NAVCalculator's verbose read methods (`getAccountPositionsVerbose`, `getAccountPositionsForAssetVerbose`,
/// `getAccountNavVerbose`) call these via a fail-open staticcall — adapters that do not implement this
/// interface simply produce an empty protocol name / label set. Labels are derived **lazily from `positionId`**
/// (a static, per-position breadcrumb), so they are computed only in the verbose reads, not carried on every
/// `PositionBalance` (that keeps display work off the NAV hot path). The ephemeral per-item id (Uniswap V3 NFT
/// id, withdrawal request id, …) is NOT a label — it is the typed `PositionBalance.positionInstanceId` field.
/// Clients MUST NOT use these strings for identity, indexing, or reconciliation; use the typed
/// `protocolSubId` / `positionId` / `PositionKind` fields on `PositionBalance` for those purposes.
/// @author KPK
interface IPositionDescribable {
/// @notice Human-readable name of the PROTOCOL, e.g. "Aave V3", "Morpho", "Uniswap V3".
/// @dev **This names the protocol, never the product.** A protocol's individual products — Aave V3's Safety
/// Module and Umbrella, Morpho's vaults and markets, Balancer's pools and gauges — all return the SAME
/// string here; what distinguishes them is `positionLabels()` (`["Umbrella Module"]`, `["Safety Module"]`,
/// `["Market", "wstETH/USDC"]`) and the typed `protocolSubId`. Equivalently: every adapter sharing a
/// `ProtocolIds` protocol id MUST return the same name. Pull it from `src/utils/ProtocolNames.sol` rather
/// than writing a literal — new and changed adapters should reference the constant; the pre-existing
/// literals are being migrated adapter by adapter and are meanwhile pinned to their constants by
/// `test/ProtocolNameConsistency.t.sol`. Meta-adapters need no literal at all (see below).
///
/// Why the distinction is load-bearing rather than cosmetic: consumers group *configured adapters* by this
/// string. The typed `protocolBrand`/`protocolId`/`protocolSubId` would group them correctly, but they are
/// `private constant` and only ride on `PositionBalance` structs returned by an **account** read — a
/// consumer enumerating registered adapters never sees them, so the display name is the only protocol
/// identity it has. An adapter that returns its product name here splits itself out into a phantom sibling
/// protocol (`AaveUmbrellaBalanceAdapter` returned "Aave Umbrella" and did exactly that).
///
/// Per-instance adapters return a compile-time constant. Meta-adapters **derive** it —
/// `MetaBalanceAdapter.protocolName()` is `ProtocolNames.forProtocolId(_protocolId())` — so for the whole
/// meta family the invariant holds by construction: the name is a pure function of the typed identity the
/// adapter already declares, with no constructor argument or config value that could disagree with it.
function protocolName() external view returns (string memory);
/// @notice Ordered, arbitrary-depth display hierarchy for a single position, BELOW the protocol level.
/// Index 0 is the broadest level (category) and the last element is the position leaf, e.g.
/// `["Market", "wstETH/USDC"]`, `["AMM Liquidity Pool", "WETH/USDC 0.05%"]`, or `["Safety Module"]` when the
/// category itself is the leaf. The full breadcrumb a consumer renders is
/// `[protocolName(), ...positionLabels(positionId)]`. Derived purely from `positionId` (the static
/// anchor) — the ephemeral per-item id rides in `PositionBalance.positionInstanceId`, not here.
/// @param positionId The ABI-encoded position identifier (same bytes as `PositionBalance.positionId`).
/// @return An array of display segments. An empty array is acceptable when no label can be derived.
/// Depth varies by adapter and position; consumers must not assume a fixed length.
///
/// **When there is no account to get a positionId from** — a configuration view listing what the
/// NAVCalculator is set up to account for — an adapter whose breadcrumb is positionId-independent
/// answers `positionLabels("")` with its full constant breadcrumb, and that is the whole answer. An
/// adapter whose breadcrumb is derived per positionId returns `[]` instead and should implement
/// {IPositionEnumerable}, whose `positionIds()` lists the shapes to pair with this function and whose
/// ERC-165 bit is what distinguishes that `[]` from a broken adapter. See {IPositionEnumerable}.
function positionLabels(bytes calldata positionId) external view returns (string[] memory);
}
src/balances/IPositionEnumerable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IPositionEnumerable
/// @notice Optional interface for balance adapters that can enumerate their own position **shapes** — the set of
/// `positionId`s an account could hold with this adapter, independent of any account actually holding one.
/// @dev Companion to {IPositionDescribable}, and read the same way: an optional interface, advertised via ERC-165
/// and called through a **fail-open staticcall**, so an adapter that does not implement it simply produces
/// nothing. Nothing on the NAV path calls it — like `positionLabels` it is display-only work, kept off the
/// hot path.
///
/// **The gap it closes.** A configuration view (a registry page listing what the NAVCalculator is set up to
/// account for) has no account and therefore no `positionId` to pass to `positionLabels`. For meta-adapters
/// it can enumerate `getMetaInstances(adapter)` on the NAVCalculator; for every other adapter there was no
/// enumeration primitive at all, so the only question it could ask was `positionLabels("")` — which answers
/// only for adapters whose breadcrumb happens to be positionId-independent. An adapter that derives its
/// labels per `positionId` (each Cap leg adapter, which answers only for its own token) correctly returns
/// an empty array to that probe and was therefore undescribable from a configuration view, and — since it
/// advertises exactly the interface set every other adapter does — indistinguishable from an adapter that
/// was simply broken. `positionIds()` is that missing primitive: the adapter states its shapes directly, and
/// its ERC-165 bit is the signal that the empty probe was a real answer rather than a failure.
///
/// **Shapes, not positions, and never identity.** The returned ids describe what this adapter *can* report,
/// not what any account holds — there are no amounts here, and an id being listed implies nothing about a
/// balance. They exist so a consumer can render the configured position set and pair each entry with
/// `positionLabels(id)`. As with {IPositionDescribable}, clients MUST NOT treat this enumeration as an
/// identity or indexing mechanism: reconcile on the typed `protocolSubId` / `positionId` / `PositionKind`
/// fields of `PositionBalance`. The one guarantee that does bind is stated on {positionIds} below — the
/// bytes must be the same bytes the adapter emits — precisely so the two views can be joined.
/// @author KPK
interface IPositionEnumerable {
/// @notice The `positionId`s this adapter can report, one per distinct position shape.
/// @dev **Each returned id MUST be byte-identical to the `PositionBalance.positionId` the adapter emits for
/// that shape**, so a consumer can join the configuration view against real positions. This is the whole
/// contract of the interface; an id that merely *labels* correctly while differing from the emitted
/// bytes (e.g. a meta-adapter returning its raw instance coordinate where it emits a resolved address)
/// silently breaks that join and does not satisfy this interface.
///
/// Implement it only where the shape set is bounded and derivable on-chain — a fixed set pinned at
/// construction, or a governed instance set. The test is whether an account-independent answer exists,
/// and it is decided per adapter, not per family: an adapter whose shapes are discovered per account
/// (a per-account cache of coordinates fed by the position owner) has no such answer and must not
/// implement this interface, while one that pins its shapes at construction does — **even if it is
/// assistant-fed**. `NexusMutualStakingPoolsAssistedBalanceAdapter` is the former (its positionId is a
/// cached pool address); `EtherFiWithdrawalQueueAssistedBalanceAdapter` is the latter (it emits a
/// single constant `abi.encode(WITHDRAW_REQUEST_NFT)`, so it is eligible) — the assistant feeds *which
/// tickets* are held, not which shapes exist.
///
/// Do NOT infer any of this from `positionLabels("")` or from the `IAssistedBalanceAdapter` marker.
/// Neither discriminates: the marker means "coordinates are fed externally", and two of the three
/// assisted adapters answer the empty probe with a CONSTANT non-empty breadcrumb. The absence of a
/// discriminator is precisely why this interface exists — its ERC-165 bit is the signal.
///
/// Must not revert and must not depend on caller state. Ordering is not significant and consumers must
/// not rely on it — in particular the returned array is NOT index-aligned with `getAdapterPositions`,
/// which omits shapes an account does not hold; join on the bytes, never on position. An empty array is
/// valid and means "no shapes to advertise".
///
/// A listed shape says the adapter can report it, NOT that the NAVCalculator is configured to value it
/// — an adapter may additionally require its underlying asset to be a registered NAV asset before it
/// emits anything. A configuration view showing these rows is showing adapter capability, not proof of
/// NAV coverage.
/// @return The ABI-encoded position identifiers, in unspecified order.
function positionIds() external view returns (bytes[] memory);
}
src/balances/LabelLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @notice Minimal ERC20 metadata view (name/symbol) for fail-open label reads.
interface IERC20MetaView {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
/// @title LabelLib
/// @author KPK
/// @notice Fail-open ERC20 `name()` / `symbol()` reads for building human-readable position labels.
/// @dev `positionLabels` is a verbose/display-only path and MUST NOT revert. A token's metadata read can fail three
/// ways, and a bare `try`/`catch` covers only one of them:
/// 1. the address has **no code** — a high-level call reverts via Solidity's `extcodesize` precheck *before*
/// the call, which `try`/`catch` does NOT catch;
/// 2. the call **reverts** — this is the one `try`/`catch` does catch;
/// 3. the call **succeeds but returns data that cannot be ABI-decoded as a string** — Solidity does NOT route
/// a return-data decode failure into the `catch` clause, so it propagates to the caller and reverts the
/// whole labels read.
/// Class 3 is not hypothetical. Reproduced on solc 0.8.34: a token returning zero bytes (an ERC-1967 proxy whose
/// implementation slot points at a code-less address — the `delegatecall` succeeds returning nothing), a `bytes32`
/// name/symbol (MKR-style legacy tokens), a bare offset word with no length word, a nonsense offset, and absurd
/// declared lengths. Every one of those used to revert `positionLabels` for every adapter reading through here.
///
/// All three classes are handled below: an explicit codesize guard, a raw `staticcall` (so a revert is a `false`
/// return rather than an exception), and **validation of the ABI head before decoding**. A canonical `string`
/// return is `[offset = 0x20][length][payload…]`, so we require two full words, an offset of exactly `0x20`, a
/// non-zero length within {MAX_METADATA_BYTES}, and a payload that fits inside the returndata. Bounding on the
/// raw length is sufficient — a memory-source `abi.decode` bounds on the declared length, not on `ceil32` of it,
/// verified by sweeping truncated and unpadded payloads.
///
/// The read is **gas-capped**, and that is load-bearing rather than defensive. The previous `try`/`catch` form
/// used a parameterless `catch {}`, which never `returndatacopy`s the revert payload; a raw staticcall assigning
/// `(bool, bytes memory)` always does. Without {METADATA_READ_GAS} this rewrite would therefore introduce a
/// griefing vector that did not exist before — a hostile address returning a multi-megabyte revert payload, or
/// simply looping, was measured burning over a billion gas and could out-of-gas a verbose NAV read.
///
/// Callers get the metadata or their chosen `fallbackStr`, and never a revert. Empty-string returns are
/// normalised to `fallbackStr` too. Pass `""` for the single-leaf collapse convention (drop the leaf, keep the
/// category) or `"?"` as a placeholder inside a joined multi-token leaf. Shared across the meta, plain, and
/// assisted adapter families.
library LabelLib {
/// @notice Longest metadata string accepted; anything longer yields `fallbackStr`. Bounds how much a hostile
/// token can inflate a rendered label. Far above any real name or symbol.
/// @dev This is a NEW global constraint: the `try`/`catch` form this replaced returned any successfully-decoded
/// string regardless of length, and none of the call sites previously asked for a cap. Deliberate — an
/// unbounded label is an unbounded cost for every downstream renderer — but it does mean a token with an
/// absurdly long name now renders as the caller's fallback rather than in full.
uint256 private constant MAX_METADATA_BYTES = 256;
/// @notice Hard ceiling on returndata **copied into this contract's memory**: the two ABI head words plus
/// {MAX_METADATA_BYTES} of payload (64 + 256 = 320). Written as a literal because inline assembly accepts
/// only direct number constants.
/// @dev **This constant is where {MAX_METADATA_BYTES} is actually enforced.** The payload-fits check bounds `len`
/// by `copied - 64`, and `copied <= MAX_RETURN_BYTES`, so the cap follows structurally — which is why there is
/// no separate `len > MAX_METADATA_BYTES` clause (it would be provably unreachable). Keep the two constants in
/// lockstep: `MAX_RETURN_BYTES == 64 + MAX_METADATA_BYTES`.
///
/// **Bound on what was COPIED, never on `returndatasize()`.** An earlier revision rejected any reply larger
/// than this constant, on the stated assumption that a canonical reply for an in-cap string never exceeds it.
/// That assumption is **wrong**, and the counterexamples are ordinary mainnet tokens: the Vyper LP tokens from
/// Curve's USD-metapool factory (`0xB9fC157394Af804a3578134A6585C0dc9cc990d4`) return a fixed **4096-byte**
/// buffer behind a perfectly canonical head — FRAX3CRV-f, MIM-3LP3CRV-f, alUSD3CRV-f and LUSD3CRV-f among
/// them, 12 of the first 80 pools in that factory — carrying strings of only 10-57 bytes. `abi.decode`
/// accepts those, as did both predecessors; only a size-keyed reject discarded them, and on their padding
/// rather than their content. None is a configured instance today, but the Curve/Convex roadmap makes it a
/// live trap. Hence `copied = min(size, MAX_RETURN_BYTES)` and a payload bound against `copied`.
///
/// This, not the gas stipend, is what bounds caller-side cost. A gas stipend alone does NOT: a hostile token
/// can `return(0, 200_000)` — the callee's own memory expansion for ~200 KB costs it about 95k, so it fits
/// inside {METADATA_READ_GAS} — while the *caller* pays `returndatacopy` plus its own monotonically growing
/// memory, charged outside the stipend and quadratic in total. Measured on the stipend-only version: 210,190
/// gas for one read and 14.5M across eight sequential reads in one frame, which a multi-token leaf
/// (`_joinTokenSymbols` over a Balancer pool, `CurvePoolLib.coinSymbols` over an 8-coin pool) does. Passing an
/// explicit output size to `staticcall` copies at most this many bytes no matter what the callee returns, so
/// the cost is flat. `returndatasize()` still reports the true size, so an oversized reply is rejected rather
/// than silently truncated.
uint256 private constant MAX_RETURN_BYTES = 320;
/// @notice Gas stipend for a metadata probe. Generous for a real (even proxied) `name()`/`symbol()`, and it bounds
/// the callee's own execution — including a write-protection abort, which consumes everything forwarded.
/// @dev Necessary but NOT sufficient on its own; see {MAX_RETURN_BYTES} for the caller-side bound.
uint256 private constant METADATA_READ_GAS = 100_000;
/// @notice The token's ERC20 `name()`, or `fallbackStr` if the address has no code, the call reverts, the return
/// data is not a decodable string, or it returns an empty string.
function name(address token, string memory fallbackStr) internal view returns (string memory) {
return _readString(token, IERC20MetaView.name.selector, fallbackStr);
}
/// @notice The token's ERC20 `symbol()`, or `fallbackStr` if the address has no code, the call reverts, the return
/// data is not a decodable string, or it returns an empty string.
function symbol(address token, string memory fallbackStr) internal view returns (string memory) {
return _readString(token, IERC20MetaView.symbol.selector, fallbackStr);
}
/// @notice Fail-open read of ANY parameterless, `string`-returning view — the generic form of {name}/{symbol}.
/// @dev The canonical home for hardened string-metadata reads. Three sessions independently wrote this same
/// reader — here, and as a `_safeStringRead` duplicated verbatim across the AaveV3 and Gearbox
/// adapters — before it was exposed; those copies now route here so a fourth cannot accumulate.
///
/// Callers wanting ERC20 metadata should still use {name}/{symbol}; this is for everything else
/// (Aave's `getMarketId()`, Gearbox's credit-manager `name()`, …).
/// @param token The contract to probe.
/// @param selector The parameterless, string-returning selector to call.
/// @param fallbackStr Returned unchanged on every failure path, and for an empty result.
function readString(address token, bytes4 selector, string memory fallbackStr)
internal
view
returns (string memory)
{
return _readString(token, selector, fallbackStr);
}
/// @notice Shared fail-open string-metadata read behind {name}, {symbol} and {readString}.
/// @param token The contract to probe.
/// @param selector The parameterless, string-returning selector to call.
/// @param fallbackStr Returned unchanged on every failure path, and for an empty result.
/// @dev See the contract-level doc for why each guard exists. Order matters: codesize first (cheapest, and the
/// class a high-level call cannot catch), then the capped raw call, then head validation, and only then the
/// decode — which is safe precisely because the head was validated.
function _readString(address token, bytes4 selector, string memory fallbackStr)
private
view
returns (string memory)
{
// Cheap short-circuit only. A raw `staticcall` to a code-less address succeeds with empty returndata, which the
// length check below already rejects — unlike the high-level call this replaced, where `extcodesize` reverted
// before the call and made this guard load-bearing.
if (token.code.length == 0) return fallbackStr;
bytes memory data = new bytes(MAX_RETURN_BYTES);
bool ok;
uint256 size;
assembly ("memory-safe") {
// Selector into scratch space; `bytes4` is left-aligned in its word, so the first 4 bytes are the selector.
mstore(0x00, selector)
// The explicit output size is the point: at most MAX_RETURN_BYTES is copied into our memory, whatever the
// callee returns. `returndatasize()` still reports the untruncated size.
ok := staticcall(METADATA_READ_GAS, token, 0x00, 0x04, add(data, 0x20), MAX_RETURN_BYTES)
size := returndatasize()
}
// A `string` return needs at least the offset and length words.
if (!ok || size < 64) return fallbackStr;
// Only the first MAX_RETURN_BYTES were copied; `size` may be larger. Bound on what we actually HAVE, not on
// what the callee claimed to send. Keying the accept window on `size` instead would reject a reply whose
// string sits entirely inside the copied window but which carries trailing or over-padded bytes behind it —
// a narrowing versus both predecessors (the high-level typed call and StakeWise's `_safeVaultName`), and one
// no real string needs. `copied >= 64` because `size >= 64` and MAX_RETURN_BYTES far exceeds 64.
uint256 copied = size < MAX_RETURN_BYTES ? size : MAX_RETURN_BYTES;
// Shrink to the copied extent so `abi.decode`'s own bound matches the bytes we hold.
assembly ("memory-safe") {
mstore(data, copied)
}
uint256 offset;
uint256 len;
assembly ("memory-safe") {
offset := mload(add(data, 0x20))
len := mload(add(data, 0x40))
}
// `len > copied - 64` is the payload-fits check, written as a subtraction on the LEFT so an attacker-supplied
// `len` near 2^256 cannot overflow `64 + len`. It also enforces {MAX_METADATA_BYTES} structurally: `copied` is
// at most `MAX_RETURN_BYTES` = 64 + MAX_METADATA_BYTES, so any accepted `len` is at most MAX_METADATA_BYTES.
// An explicit `len > MAX_METADATA_BYTES` clause here would be dead code — mutation-testable to nothing — so the
// cap lives in the MAX_RETURN_BYTES definition instead. Change one of those two constants and you must change
// the other.
if (offset != 0x20 || len == 0 || len > copied - 64) return fallbackStr;
return abi.decode(data, (string));
}
}
src/balances/MetaBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IBalanceAdapter} from "./IBalanceAdapter.sol";
import {AddressCheckLib} from "src/utils/AddressCheckLib.sol";
import {IMetaBalanceAdapter} from "./IMetaBalanceAdapter.sol";
import {IPositionDescribable} from "./IPositionDescribable.sol";
import {IPositionEnumerable} from "./IPositionEnumerable.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
import {LabelLib} from "./LabelLib.sol";
import {ProtocolNames} from "src/utils/ProtocolNames.sol";
import {GasStipendLib} from "src/utils/GasStipendLib.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {InvalidArgumentsWithContext} from "src/errors.sol";
/// @title MetaBalanceAdapter
/// @author KPK
/// @notice Abstract base for meta balance adapters — one immutable adapter serving every instance of a
/// protocol. Concrete adapters implement the per-instance hooks (`_instancePositions`, `_instanceAssets`),
/// the identity hooks (`_protocolBrand`, `_protocolId`, `_protocolSubId`), and `positionLabels`; this base
/// provides the ERC165 wiring, the empty no-op `IBalanceAdapter` methods, the per-instance fan-out
/// with revert isolation, the shared `_leg` builder, and shared NAVCalculator registry helpers.
/// @dev The instance set lives on NAVCalculator (ADR 0010). The adapter reads its own set via
/// `NAV_CALCULATOR.getMetaInstances(address(this))` and holds no instance state or admin functions of its
/// own — it stays immutable. `getAdapterPositionsForInstances` is also exposed for explicit/off-chain queries.
abstract contract MetaBalanceAdapter is IMetaBalanceAdapter, IPositionDescribable, IPositionEnumerable {
//
// State
//
/// @notice NAVCalculator reference, used for the registered-asset registry.
INAVCalculator public immutable NAV_CALCULATOR;
/// @notice Gas ceiling for deriving ONE `positionLabels` leaf, applied at the self-call each adapter already
/// routes its leaf through.
/// @dev A leaf reads the chain — pool tokens, gauge LP tokens, ERC20 symbols — through addresses that come
/// from a governed coordinate. Without a ceiling the `try this.<leaf>()` boundary forwards 63/64 of the
/// frame, so one coordinate whose reads loop consumes nearly the whole budget of whatever called in.
/// That is display-only work; it must not be able to spend a caller's read.
///
/// **This is a fixed ceiling, deliberately, and NOT {GasStipendLib}.** That library answers a different
/// question — "did this call run out of gas, or did it answer?" — and its `stipendFrom` is 63/64 of what
/// remains, which is what the EVM forwards anyway and therefore bounds nothing. Here there is nothing to
/// classify: a leaf that does not fit is simply dropped, and the caller wants a number it can reason
/// about. Same idiom as `LabelLib.METADATA_READ_GAS` and `StaticCallLib.PROBE_GAS`.
///
/// **The value is boxed in from both sides, and the box is narrow.** The floor is the widest leaf a
/// governed coordinate can legitimately produce; the hard ceiling is 63/64 of `NAVCalculator`'s
/// per-position `_LABEL_READ_GAS` (984,375 at 1,000,000), at or above which the outer cap binds first
/// and this constant stops bounding anything on the verbose path. Raising the OUTER budget is not the
/// escape hatch it looks like: it is charged per position, so N positions pay N times it.
///
/// Measured COLD in `test/balances/MetaLabelGasBounds.t.sol`, against ERC-1967 tokens that each have
/// their OWN implementation — both properties matter and both understate if dropped. A fixture built in
/// a test body is read warm and costs under half; a fixture sharing one implementation across n proxies
/// pays EIP-2929's cold 2,600 once and the warm 100 for the rest, understating an n=50 leaf by 122,500.
///
/// - **Balancer V2 gauges at the protocol maximum of 50 tokens: 912,434 — the binding case.** Strictly
/// the widest site: `gaugeTokenSymbols` does everything the pools leaf does (889,581) and reaches it
/// through two further cold hops. A ManagedPool's token list is mutable after the instance is
/// governed, so registration cannot screen the wide case out.
/// - **Fluid vaults: 488,249 at 43 registered assets, rising 9,657 per further asset.**
/// `vaultPairSymbols` pulls the whole registered-asset array over to resolve two symbols, so this
/// leaf's cost tracks how many assets are registered protocol-wide rather than anything about Fluid.
/// Its headroom is therefore denominated in future `registerAsset` calls — about 48 of them; the leaf
/// renders at 90 registered assets and is dropped at 93.
/// - The widest Curve pool, often assumed to be the worst case, is 138,033 — under a sixth of this.
///
/// That leaves ~4% over the floor and ~3.5% under the hard ceiling. The margin is thin because the box
/// is ~72k wide, not because the value is badly chosen; a materially larger margin needs per-site
/// ceilings (the narrow sites — Curve, Convex, Uniswap V2, all capped at 8 tokens — would take ~300k)
/// rather than a different single number. Re-measure before changing this: it is a compile-time
/// constant on immutable adapters, so a value that turns out too low needs a redeploy to correct.
uint256 internal constant LABEL_LEAF_GAS = 950_000;
//
// Constructor
//
/// @notice The NAVCalculator behind `navCalculator_` cannot serve `getRegisteredAsset`, so it predates the
/// O(1) registry lookup this adapter family depends on.
/// @dev Deployment-time, not read-time, and that is the whole point — see the constructor.
/// @param navCalculator The proxy that failed the probe.
error NAVCalculatorTooOld(address navCalculator);
/// @param navCalculator_ The NAVCalculator contract for asset-registry access.
/// @dev No `protocolName_`: the display name is derived from `_protocolId()` (see `protocolName()`), so there is
/// no deployment-time string to supply, mis-spell, or let drift between two adapters of one protocol.
///
/// Pins the NAVCalculator and **refuses to deploy against one that cannot answer
/// `getRegisteredAsset(address)`**.
///
/// This guard exists because the alternative failure is silent and raises NAV. Meta-adapters are
/// IMMUTABLE with this proxy pinned here; NAVCalculator is UUPS-UPGRADEABLE. An adapter built on this base
/// and pointed at a proxy running an implementation from before that getter existed would hit a missing
/// selector on every `_eligible` call. The proxy reverts cheaply with empty returndata, that revert lands
/// in the per-instance `catch` in {_positionsForInstances}, and because `consumed` is small
/// `GasStipendLib.exhausted` reads false — so it is NOT re-raised as {InstanceGasExhausted}. The instance
/// is recorded as an empty leg list and `getAdapterPositions` **returns successfully**.
///
/// Dropped legs that included a DEBT leg raise reported NAV, and nothing downstream can tell the answer
/// was partial: `underlyingAssetsSupported()` and `positionIds()` both keep answering correctly, because
/// neither passes through `_eligible`. That is precisely the failure the per-instance `try`/`catch` is
/// documented as never being allowed to absorb, reached by a route the gas classifier is structurally
/// blind to — the cause is a missing selector, not exhaustion, so there is no gas signature to detect.
///
/// **Reachable, and one route is on record as having happened.** `script/deploy/REDEPLOY_RUNBOOK.md` §3
/// records `01_2` (the NAV implementation) reverting while `04` (adapters) proceeded: *"RegisterAssets, 04
/// and 06 all reported success having done nothing."* The others are a partial rollout across chains where
/// one chain's implementation was not upgraded, and an implementation rollback after adapters are
/// deployed. `verify_step.py` steps 1.6/1.7 check adapter counts, names, code presence and registration —
/// none of which is a functional read, so none of which would notice.
///
/// A `staticcall` rather than a typed call so a missing selector is a `false` return instead of a revert
/// inside the constructor. `address(0)` is a deliberately inert probe argument: on a NAVCalculator that
/// has the getter it resolves to `(zeroed, false)` without reverting, so a healthy deploy always passes.
///
/// **WHAT THIS GUARD DOES NOT COVER.** It runs once, at construction, so it establishes the pairing was
/// sound *at deploy time* and nothing more. Three limits, stated because the routes above are easy to
/// read as all being closed by it:
///
/// 1. **A post-construction rollback is not detectable here.** Meta-adapters are immutable and
/// NAVCalculator is UUPS-upgradeable, so downgrading the implementation after adapters exist leaves
/// this guard long since passed and every later `getAdapterPositions` silently returning zero legs.
/// Of the three routes above, this one **survives the guard**; the other two do not. Catching it would
/// need a read-time probe on the hot path, which is not affordable — the fan-out already runs under a
/// per-instance gas stipend.
/// 2. **Already-deployed adapters are never re-probed.** `04_DeployBalanceAdapters._deployIfEnabled` is
/// skip-if-deployed and `06_Configure` re-registers straight from the deployments JSON without any
/// version check, so re-running the deploy scripts over an existing fleet does not exercise this
/// constructor at all. It binds the *next* adapter deployed, not the ones already out there. (The
/// 24-chain redeploy clears the records at runbook step 1.1, so every adapter there IS freshly
/// constructed and does pass through this guard.)
/// 3. **Pointing at the NAVCalculator implementation instead of its proxy passes.** The implementation
/// genuinely serves the selector; it simply has empty storage, so every lookup returns
/// `found == false` and the adapter reports zero legs just as silently. The probe cannot tell the two
/// apart, and requiring a non-zero EIP-1967 slot would reject the plain (non-proxy) NAVCalculators
/// that unit tests construct against. `verify_step.py 1.3` comparing the recorded implementation
/// against the proxy's EIP-1967 slot is the check that catches this one.
///
/// Costs zero NAVCalculator bytecode — the budget under pressure is that contract's (101 bytes under
/// EIP-170), not the adapters', which carry 14-19 KB of margin each.
constructor(address navCalculator_) {
AddressCheckLib.requireContract(navCalculator_, "NAVCalculator");
(bool ok, bytes memory ret) =
navCalculator_.staticcall(abi.encodeWithSelector(INAVCalculator.getRegisteredAsset.selector, address(0)));
// Success alone proves NOTHING, and an earlier version of this guard checked only that. A staticcall
// returning success with EMPTY returndata satisfies `ok` — so a NAV-shaped contract with a bare
// `fallback() external {}` passed the probe and was pinned, after which every `_getAssetInfo` failed on
// return-data decode inside the per-instance catch, `consumed` stayed tiny so it was not re-raised as
// exhaustion, and the adapter silently reported zero legs. That is precisely the over-report this guard
// exists to prevent, reinstated by the guard's own weakness (proven by executed PoC in review).
//
// The floor is 192 bytes, and the arithmetic is worth spelling out because a first pass put it at 64.
// `Asset` is `(address, string, uint8)` — DYNAMIC, because of the string — so `returns (Asset, bool)`
// encodes as: 2 head words (offset-to-Asset, bool) + 3 words for Asset's own head (address,
// offset-to-string, uint8) + 1 word for the string length. Six words = 192 bytes, with an EMPTY symbol,
// which is exactly what the `address(0)` probe elicits since `found == false` zeroes the struct. 64
// would have admitted anything from 64 to 191 bytes — still far short of a real answer.
// `test_capableNavReturndataIsAtLeastTheFloor` measures this against a real encoder rather than trusting
// the arithmetic, so adding a field to `Asset` fails a test instead of silently loosening the guard.
//
// Checking the length is what turns "it did not revert" into "it answered". Note a staticcall to a
// CODELESS account also returns success with no data, which is why `requireContract` above is
// load-bearing rather than merely tidy.
if (!ok || ret.length < 192) revert NAVCalculatorTooOld(navCalculator_);
NAV_CALCULATOR = INAVCalculator(navCalculator_);
}
//
// IERC165
//
/// @inheritdoc IERC165
/// @dev `public` rather than `external` so an adapter advertising a further interface can override and
/// `super`-chain — Solidity cannot reach an `external` function through `super`, which would force the
/// override to re-declare this whole list and silently drift from it. Matches the same fix on
/// {BalanceAdapterBase} and the {AssistedCoordCache} precedent. {IPositionEnumerable} is in the list
/// because this base implements it for every meta-adapter (see `positionIds`).
function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) {
return interfaceId == type(IMetaBalanceAdapter).interfaceId || interfaceId == type(IBalanceAdapter).interfaceId
|| interfaceId == type(IPositionDescribable).interfaceId
|| interfaceId == type(IPositionEnumerable).interfaceId || interfaceId == type(IERC165).interfaceId;
}
//
// IPositionEnumerable
//
/// @inheritdoc IPositionEnumerable
/// @dev Implemented once here for the whole meta family: the shape set of a meta-adapter *is* its governed
/// instance set, which lives on the NAVCalculator (ADR 0010), so this reads
/// `getMetaInstances(address(this))` and maps each coordinate through {_instancePositionId}.
/// Adding or removing an instance is a MANAGER config TX, so this tracks configuration with no adapter
/// state and no admin surface — the adapter stays immutable.
///
/// **This is what makes {_instancePositionId} load-bearing.** {IPositionEnumerable} requires each
/// returned id to be byte-identical to the `PositionBalance.positionId` the adapter actually emits, so
/// every concrete adapter MUST ensure this hook agrees with what its `_instancePositions` passes to
/// {_leg}. An adapter that derives its positionId from something other than the raw coordinate — Aave
/// V3, whose coordinate is a ProtocolDataProvider but whose positionId is the Pool resolved from it —
/// must override the hook. See the hook's own docs.
///
/// Returns the ids in `getMetaInstances` order, but no ordering is promised and consumers must not rely
/// on it: this is not index-aligned with `getAdapterPositions`, which omits instances an account has no
/// position in and may emit several legs sharing one id. Join on the bytes.
///
/// A listed shape means the instance is configured, NOT that the account holds anything in it, nor that
/// the instance's assets are registered for pricing.
///
/// **Per-instance revert isolation, like every other fan-out on this base.** {IPositionEnumerable}
/// requires this function not to revert, and deriving a positionId is not inherently safe: the default
/// hook reverts on a malformed coordinate, and Aave V3's override reads the chain to resolve its Pool.
/// Without isolation one bad coordinate — which `addMetaInstances` does not prevent, since it never
/// checks the coordinate is a contract — would drop the enumeration for every OTHER instance too, and do
/// it silently: an adapter that reverts here is indistinguishable, through the consumer's fail-open
/// staticcall, from one with nothing configured. That is the exact ambiguity this interface exists to
/// remove. A failing instance is therefore dropped and the rest still enumerate — under-report, never
/// over-report, the same direction the position fan-out degrades in.
///
/// Declared `public`, not `external`, for the same reason `supportsInterface` above is: a fork adapter
/// that needs to extend or narrow the enumeration can then `super.positionIds()` instead of copying this
/// body — a copy would silently keep the old behaviour if this one changes (as it just did, gaining the
/// isolation), which is exactly the drift this interface exists to prevent.
function positionIds() public view virtual override returns (bytes[] memory ids) {
bytes32[] memory instances = NAV_CALCULATOR.getMetaInstances(address(this));
bytes[] memory buf = new bytes[](instances.length);
uint256 n;
for (uint256 i; i < instances.length; ++i) {
try this.instancePositionId(instances[i]) returns (bytes memory id) {
buf[n++] = id;
} catch {
// Coordinate could not be resolved — drop this shape, keep the others.
}
}
ids = new bytes[](n);
for (uint256 i; i < n; ++i) {
ids[i] = buf[i];
}
}
//
// IPositionDescribable
//
/// @inheritdoc IPositionDescribable
/// @dev Derived from the adapter's own `_protocolId()`, so "same protocolId ⇒ same protocolName" holds **by
/// construction** for every meta adapter: the name is a pure function of the typed identity the adapter
/// already declares, not a separate constructor argument that could disagree with it. This is what a
/// display name being a *product* name (the Aave Umbrella bug) is now structurally unable to be.
function protocolName() external pure virtual override returns (string memory) {
return ProtocolNames.forProtocolId(_protocolId());
}
/// @inheritdoc IPositionDescribable
/// @dev Abstract — each concrete meta-adapter derives the breadcrumb from `positionId` (decode the instance
/// coordinate, read its on-chain name/symbol) and returns `_labels("Category", leaf)`. Display only; the
/// ephemeral per-item id (if any) is the typed `PositionBalance.positionInstanceId`, not a label.
function positionLabels(bytes calldata positionId) external view virtual override returns (string[] memory);
//
// IBalanceAdapter
//
// NAVCalculator calls getAdapterPositions(account, assetFilter) on every adapter uniformly. A meta-adapter
// services it by reading its NAV-configured instance set and fanning out — no special routing in NAV.
// getAdapterBalances / getAdapterBalanceForAsset are not used by the NAV path and return empty.
//
/// @inheritdoc IBalanceAdapter
/// @dev Reads the NAV-configured instance set for this adapter and fans out over it (ADR 0010).
function getAdapterPositions(address account, address assetFilter)
external
view
virtual
override
returns (INAVCalculator.PositionBalance[] memory)
{
return _positionsForInstances(account, NAV_CALCULATOR.getMetaInstances(address(this)), assetFilter);
}
/// @inheritdoc IBalanceAdapter
function getAdapterBalances(address)
external
view
virtual
override
returns (address[] memory, uint256[] memory, bool[] memory)
{
return (new address[](0), new uint256[](0), new bool[](0));
}
/// @inheritdoc IBalanceAdapter
function getAdapterBalanceForAsset(address, address) external view virtual override returns (uint256, bool) {
return (0, false);
}
/// @inheritdoc IBalanceAdapter
function underlyingAssetsSupported() external view virtual override returns (address[] memory) {
return _assetsForInstances(NAV_CALCULATOR.getMetaInstances(address(this)));
}
//
// IMetaBalanceAdapter
//
/// @inheritdoc IMetaBalanceAdapter
function getAdapterPositionsForInstances(address account, bytes32[] calldata instances, address assetFilter)
external
view
override
returns (INAVCalculator.PositionBalance[] memory)
{
return _positionsForInstances(account, instances, assetFilter);
}
/// @inheritdoc IMetaBalanceAdapter
function underlyingAssetsSupportedForInstances(bytes32[] calldata instances)
external
view
override
returns (address[] memory)
{
return _assetsForInstances(instances);
}
//
// Internal fan-out
//
/// @notice Aggregates positions across `instances`, isolating a faulty instance so it cannot zero out the
/// batch — but NOT isolating one that ran out of gas.
/// @dev The isolation is deliberate and stays: an instance whose protocol read reverts has answered, and one
/// bad instance must not cost the account the other instances' legs. Gas exhaustion is not that. It
/// means the instance did not answer, and recording it as an empty leg list drops whatever it held —
/// a dropped *debt* leg RAISES the reported NAV — while this function still returns SUCCESSFULLY, so
/// nothing downstream can tell the answer was partial. That is the one failure the per-instance
/// `try`/`catch` must not absorb, so it reverts {InstanceGasExhausted} instead.
///
/// The classification is {GasStipendLib}'s, shared with the adapter-level guard in
/// `PriceFeedLib._getAdapterPositions` rather than restated here, because these two are the same
/// question asked one frame apart and a threshold that drifts between them re-opens the hole.
///
/// Note what this deliberately does NOT do: unlike the adapter-level guard, it does not honour an
/// {InstanceGasExhausted} selector arriving in the revert data. That guard can afford to, because the
/// thing it is listening to is a meta-adapter it has ERC165-checked. Here the revert data comes from a
/// protocol this adapter merely reads, so treating a selector in it as a trusted signal would let a
/// third-party contract decide that a NAV read must fail. Gas consumed is the only evidence available
/// at this boundary that the callee cannot choose.
///
/// It also cannot see an instance that swallows its OWN out-of-gas — a `_instancePositions`
/// implementation whose protocol read is itself wrapped in `try`/`catch` returns normally with a leg
/// missing, and nothing here fires. See {GasStipendLib}.
///
/// **The cost of raising, taken knowingly.** Several protocols let anyone grow a per-account list — a
/// withdrawal request names its own owner — so a third party can push one instance's read past what the
/// fan-out can hand it and make that account's NAV read FAIL, where before it returned a number that was
/// quietly missing a leg. That is the intended direction: a read that cannot see everything must not
/// answer as though it did. It is also recoverable in a way the silent version never was, because the
/// stipend is a share of the caller's own budget rather than a fixed ceiling — more gas, up to whatever
/// the node's `eth_call` cap allows, gets the read through. Past that cap the remedy is the MANAGER's:
/// remove the instance.
function _positionsForInstances(address account, bytes32[] memory instances, address assetFilter)
internal
view
returns (INAVCalculator.PositionBalance[] memory positions)
{
INAVCalculator.PositionBalance[][] memory perInstance = new INAVCalculator.PositionBalance[][](instances.length);
uint256 total = 0;
for (uint256 i = 0; i < instances.length; i++) {
// One sample, used both to derive the stipend and to measure against it — see GasStipendLib.exhausted.
uint256 available = gasleft();
uint256 stipend = GasStipendLib.stipendFrom(available);
try this.instancePositions{gas: stipend}(account, instances[i], assetFilter) returns (
INAVCalculator.PositionBalance[] memory p
) {
perInstance[i] = p;
total += p.length;
} catch {
uint256 consumed = available - gasleft();
if (GasStipendLib.exhausted(stipend, consumed)) {
revert INAVCalculator.InstanceGasExhausted(address(this), instances[i], stipend, consumed);
}
perInstance[i] = new INAVCalculator.PositionBalance[](0);
}
}
positions = new INAVCalculator.PositionBalance[](total);
uint256 k = 0;
for (uint256 i = 0; i < instances.length; i++) {
for (uint256 j = 0; j < perInstance[i].length; j++) {
positions[k++] = perInstance[i][j];
}
}
}
/// @notice Aggregates the underlying assets across `instances`.
function _assetsForInstances(bytes32[] memory instances) internal view returns (address[] memory assets) {
address[][] memory perInstance = new address[][](instances.length);
uint256 total = 0;
for (uint256 i = 0; i < instances.length; i++) {
// METERED AND CLASSIFIED, exactly as `_positionsForInstances` does, and for the same reason: a bare
// `catch` could not tell a starved call from an expected refusal, so this function RETURNED
// SUCCESSFULLY WITH A SILENTLY SHORTER LIST. That is the residual `GasStipendLib`'s own docstring
// names, and it is worse here than it looks: `underlyingAssetsSupported()` is the surface callers use
// to decide whether ANYONE reports an asset, so a truncated answer reads as "nobody reports it" —
// the direction that invites a double count. `_instanceAssets` is also far costlier than
// `_instancePositions` for some families (Aave enumerates ~67 reserves per instance), so it is the
// one that truncates FIRST under a squeezed frame.
//
// ⚠️ **THIS CHANGES THIS BASE CONTRACT'S BYTECODE, SO EVERY META ADAPTER'S CREATE2 ADDRESS MOVES.**
// 23 adapters inherit `MetaBalanceAdapter`; all of them must be redeployed and re-registered. That
// is an accepted, deliberate cost (owner decision, 2026-09-24) — not an oversight — and it is why
// `testNavOnlyAdapterAddresses` and `testProtocolArgAdapterAddresses` are expected-red until the
// deploy-time address regeneration. See the PR description's `## Outstanding`.
//
// Single-sample discipline: read `available` once, forward `stipendFrom(available)`, classify
// `available - gasleft()` against the stipend. Re-sampling nearer the call inverts the slack.
uint256 available = gasleft();
uint256 stipend = GasStipendLib.stipendFrom(available);
try this.instanceAssets{gas: stipend}(instances[i]) returns (address[] memory a) {
perInstance[i] = a;
total += a.length;
} catch {
uint256 consumed = available - gasleft();
if (GasStipendLib.exhausted(stipend, consumed)) {
revert INAVCalculator.InstanceGasExhausted(address(this), instances[i], stipend, consumed);
}
// Otherwise the expected refusal — an instance this adapter cannot resolve — which is what the
// fail-open is for.
perInstance[i] = new address[](0);
}
}
assets = new address[](total);
uint256 k = 0;
for (uint256 i = 0; i < instances.length; i++) {
for (uint256 j = 0; j < perInstance[i].length; j++) {
assets[k++] = perInstance[i][j];
}
}
}
//
// External wrappers (enable per-instance revert isolation via `this.` staticcall)
//
/// @notice External wrapper around the concrete per-instance position logic.
/// @dev Called via `this.` inside `_positionsForInstances` so a single bad instance is isolated.
function instancePositions(address account, bytes32 instance, address assetFilter)
external
view
returns (INAVCalculator.PositionBalance[] memory)
{
return _instancePositions(account, instance, assetFilter);
}
/// @notice External wrapper around the concrete per-instance asset enumeration.
function instanceAssets(bytes32 instance) external view returns (address[] memory) {
return _instanceAssets(instance);
}
/// @notice External wrapper around the concrete per-instance positionId derivation.
/// @dev Called via `this.` inside `positionIds` so a single bad coordinate is isolated, exactly as
/// `instancePositions` isolates the position fan-out. {_instancePositionId} is not inherently safe to call
/// in a loop: the base default reverts via `_toAddress` on a coordinate with dirty high bits, and an
/// override may read the chain — Aave V3's resolves the Pool through two external calls, so a codeless,
/// reverting or undecodable coordinate reverts here too (none of which `try`/`catch` would catch if it
/// were called inline).
function instancePositionId(bytes32 instance) external view returns (bytes memory) {
return _instancePositionId(instance);
}
//
// Hooks implemented by concrete adapters
//
/// @notice Computes the positions for a single instance. Implementations should return an EMPTY array (not
/// revert) for instances whose asset is unregistered or whose balance is zero.
function _instancePositions(address account, bytes32 instance, address assetFilter)
internal
view
virtual
returns (INAVCalculator.PositionBalance[] memory);
/// @notice Returns the underlying asset(s) for a single instance.
function _instanceAssets(bytes32 instance) internal view virtual returns (address[] memory);
//
// Identity hooks (overridden per adapter)
//
/// @notice The adapter's `protocolBrand` — the version-stripped brand roll-up (e.g. `aave`). See ProtocolIds.
function _protocolBrand() internal pure virtual returns (bytes32);
/// @notice The adapter's `protocolId` — the ecosystem/version roll-up (e.g. `aave-v3`). See ProtocolIds.
function _protocolId() internal pure virtual returns (bytes32);
/// @notice The adapter's `protocolSubId` — the per-product slug; the protocol component of the stable
/// reconciliation key (e.g. `aave-v3-lending`). See ProtocolIds.
function _protocolSubId() internal pure virtual returns (bytes32);
//
// Shared helpers
//
/// @notice Assembles a single `PositionBalance` with this adapter's identity (the `_protocol*` hooks +
/// `balanceAdapter = address(this)`), `isLocked = false`, and `positionInstanceId = bytes32(0)`.
/// @dev The shared leg builder for every meta-adapter — each instance read calls this instead of inlining a
/// 9-field struct literal (which also keeps per-adapter frames under the via_ir stack limit). Meta-adapter
/// legs carry no ephemeral per-item id (the instance coordinate lives in `positionId`), so
/// `positionInstanceId` stays `bytes32(0)`. `isLocked` defaults to `false`; an adapter that reports a locked
/// leg sets it on the returned struct after the call (e.g. `YoVaultsMetaBalanceAdapter`'s pending-redeem
/// leg, ADR 0016).
function _leg(
INAVCalculator.Asset memory asset,
uint256 amount,
bool isDebt,
bytes memory positionId,
PositionKind kind
) internal view returns (INAVCalculator.PositionBalance memory leg) {
leg.balanceAsset = asset;
leg.balanceAdapter = address(this);
leg.amount = amount;
leg.isDebt = isDebt;
leg.protocolBrand = _protocolBrand();
leg.protocolId = _protocolId();
leg.protocolSubId = _protocolSubId();
leg.positionId = positionId;
leg.positionKind = kind;
// isLocked defaults false; positionInstanceId defaults bytes32(0).
}
/// @notice Assembles the `[category, leaf]` label pair returned by each meta-adapter's `positionLabels`, applying
/// the fail-open empty-leaf convention in one place (IPositionDescribable): a leaf that could not be derived
/// (empty string, e.g. a reverting `name()`/`symbol()` read) is dropped so consumers never render
/// a blank trailing breadcrumb segment, while the known `category` is preserved. If both are empty,
/// returns an empty array. Mirrors `ERC20DefaultBalanceAdapter`'s single-segment collapse, generalised to
/// the category+leaf shape every meta-adapter uses.
/// @dev Centralising this here keeps the convention identical across all meta-adapters instead of being
/// re-decided per adapter; concrete adapters derive `leaf` then `return _labels("Category", leaf);`.
///
/// Deriving that leaf is what {LABEL_LEAF_GAS} bounds — see its docs for why a label read needs a
/// ceiling of its own even though the leaf itself is display-only.
function _labels(string memory category, string memory leaf) internal pure returns (string[] memory) {
if (bytes(leaf).length == 0) {
if (bytes(category).length == 0) return new string[](0);
string[] memory only = new string[](1);
only[0] = category;
return only;
}
string[] memory out = new string[](2);
out[0] = category;
out[1] = leaf;
return out;
}
/// @notice Decodes an address-keyed bytes32 instance coordinate into an address (vault / pool / DataProvider).
/// @dev Reverts if the high 96 bits are non-zero rather than silently truncating, so a malformed coordinate
/// surfaces as an error (isolated per-instance by the fan-out) instead of querying a different address.
/// Adapters whose coordinate is a raw bytes32 (e.g. Morpho market ids) do not use this helper.
function _toAddress(bytes32 instance) internal pure returns (address) {
if (uint256(instance) >> 160 != 0) revert InvalidArgumentsWithContext("instance: not an address");
return address(uint160(uint256(instance)));
}
/// @notice Returns the positionId bytes for a given instance coordinate.
/// @dev Default: encodes the instance as an address (address-keyed protocols).
/// Override when the coordinate is a raw bytes32 (e.g. Morpho market IDs, Balancer V2 poolIds).
///
/// **This hook must agree with what the adapter emits — it is not merely a convenience.** {positionIds}
/// maps the governed instance set through it to satisfy {IPositionEnumerable}'s byte-identity
/// guarantee, so `_instancePositionId(instance)` MUST equal the `positionId` that `_instancePositions`
/// passes to {_leg} for that instance. Computing the positionId inline while leaving this hook on its
/// default is a silent break: the enumeration would advertise ids no position ever carries and the
/// configuration-view join would return nothing, with every test still green.
///
/// An adapter whose positionId is derived from the coordinate rather than being it — Aave V3, whose
/// coordinate is a ProtocolDataProvider but whose positionId is the Pool resolved from it — therefore
/// overrides this hook and calls it from `_instancePositions` instead of re-deriving inline. (One
/// positionId per instance; reserves are distinguished by balanceAsset + positionKind.)
function _instancePositionId(bytes32 instance) internal view virtual returns (bytes memory) {
return abi.encode(_toAddress(instance));
}
/// @notice Joins the ERC20 symbols of `tokens` with "/" — e.g. `[USDC, WETH]` → `"USDC/WETH"`,
/// `[USDC, USDT, DAI]` → `"USDC/USDT/DAI"`.
/// @dev Fail-open (runs in the lazy, verbose-only `positionLabels` path): a token with no code or whose
/// `symbol()` reverts yields `"?"` rather than reverting the whole labels read. Mirrors
/// `CurvePoolLib.coinSymbols`; used by the AMM-pool meta-adapters whose label leaf is the underlying
/// token set (Balancer V2/V3). Returns "" for an empty `tokens` array.
function _joinTokenSymbols(address[] memory tokens) internal view returns (string memory result) {
for (uint256 i; i < tokens.length; ++i) {
string memory sym = LabelLib.symbol(tokens[i], "?");
result = i == 0 ? sym : string.concat(result, "/", sym);
}
}
/// @notice Looks up an asset's registry metadata. O(1).
/// @return asset The Asset struct (zeroed if not found).
/// @return found True if the asset is registered in NAVCalculator.
/// @dev One `getRegisteredAsset` call — a mapping load plus one array read, flat in the size of the asset
/// registry. `_eligible` runs this before every emitted leg, so its cost is paid `tokens × instances`
/// times per read and is the single hottest lookup in this family.
///
/// **It used to fetch the WHOLE registry per call** (`RegisteredAssetLib.find(NAV_CALCULATOR
/// .getRegisteredAssets(), asset)`), which measured **6,274,562 gas for one 50-token Balancer instance at
/// 43 registered assets** and 18.4M at 100 — super-linear, because each call allocated an N-element array
/// that is never freed, so memory expansion grew with the square of the token count. Past a point that
/// exhausts the per-adapter stipend and the NAV read REVERTS. So this was an availability defect, not an
/// optimisation.
///
/// **That distinction is why `BALANCE_ADAPTERS.md` §6.4 does not forbid this change, despite reading as
/// if it might.** §6.4 rejected a genuinely different design — threading a pre-fetched registry snapshot
/// down from `PriceFeedLib`/`NAVCalculator` through a 3-arg `getAdapterPositions` — on two grounds: the
/// gas had no payer (ADR 0017: NAV is consumed off-chain), and eagerly fetching the registry for every
/// adapter call regressed the EMPTY-ACCOUNT path from <100k to ~166k, because adapters that early-return
/// never fetched at all. Neither ground reaches this change: the call sites and call COUNT are unchanged,
/// nothing is fetched eagerly, so an adapter that early-returns still fetches nothing — and the first
/// ground is superseded by evidence, since a read that reverts is not a cost question.
function _getAssetInfo(address asset) internal view returns (INAVCalculator.Asset memory, bool found) {
return NAV_CALCULATOR.getRegisteredAsset(asset);
}
/// @notice The filter-then-registry gate every per-instance read applies before emitting a leg: a token is
/// eligible when it matches `assetFilter` (or no filter is set) AND is registered in NAVCalculator.
/// @dev Combines the `assetFilter` short-circuit with `_getAssetInfo` so concrete adapters write one call instead
/// of re-deciding the order each time. Returns a zeroed `assetInfo` when ineligible.
function _eligible(address token, address assetFilter)
internal
view
returns (INAVCalculator.Asset memory assetInfo, bool eligible)
{
if (assetFilter != address(0) && token != assetFilter) return (assetInfo, false);
(assetInfo, eligible) = _getAssetInfo(token);
}
/// @notice Decodes an address-keyed `positionId`, accepting ONLY exactly one clean address word.
/// @dev The single entry point every address-keyed `positionLabels` in this family must use, because the obvious
/// spelling — `if (pid.length < 32) …; abi.decode(pid, (address))` — is wrong in two ways at once, and
/// `positionLabels` is a display-only view reachable from a configuration tool that probes with whatever
/// word it has:
///
/// 1. **It reverts.** Solidity's ABI decoder validates an `address`, so a 32-byte word whose upper 96 bits
/// are dirty (a `bytes32` market/pool id copied from a sibling adapter is the ordinary source) reverts
/// instead of degrading. Hence the raw-word decode and an explicit range check.
/// 2. **It over-claims.** `abi.decode` silently ignores trailing bytes, so a `< 32` guard lets a foreign
/// MULTI-word coordinate through and labels it from its first word — a confident, wrong breadcrumb for a
/// position the adapter never emitted. Every address-keyed positionId in this family is exactly
/// `abi.encode(address)`, so the accept window is `== 32`, not `>= 32`.
///
/// A dirty word is rejected rather than masked down to its low 160 bits: those bits can name a real
/// instance by coincidence, and a wrong label is worse than an absent one.
/// @return addr The decoded address; `address(0)` when `!ok`.
/// @return ok True only for a positionId that is exactly one word with clear upper 96 bits.
function _pidAddress(bytes calldata pid) internal pure returns (address addr, bool ok) {
if (pid.length != 32) return (address(0), false);
uint256 raw = abi.decode(pid, (uint256));
if (raw >> 160 != 0) return (address(0), false);
return (address(uint160(raw)), true);
}
/// @notice Decodes a `bytes32`-keyed `positionId` (Morpho marketIds, Balancer V2 poolIds), accepting ONLY
/// exactly one word.
/// @dev The {_pidAddress} sibling for the raw-`bytes32` coordinate. There is no range check to make — every
/// 256-bit value is a valid `bytes32`, and `abi.decode(_, (bytes32))` cannot revert on a full word — so
/// this exists purely for reason 2 above: `< 32` would label a foreign multi-word coordinate from its
/// first word. Kept as a named helper rather than an inline `!= 32` so the two coordinate shapes stay
/// visibly symmetric and a reader does not have to re-derive why one has a range check and the other
/// does not.
/// @return word The decoded word; `bytes32(0)` when `!ok`.
/// @return ok True only for a positionId that is exactly one word.
function _pidWord(bytes calldata pid) internal pure returns (bytes32 word, bool ok) {
if (pid.length != 32) return (bytes32(0), false);
return (abi.decode(pid, (bytes32)), true);
}
/// @notice Builds the `positionLabels` `[category, leaf]` for an address-keyed `positionId`, reading the
/// instance's on-chain `name()` (or `symbol()` when `useSymbol`) live and fail-open to "" — the
/// single-address label shape shared by the vault/market/lending meta-adapters (Morpho, Euler, Fluid,
/// Gearbox markets, Compound comets). Returns an empty array for a malformed positionId (see
/// {_pidAddress}); the empty-leaf collapse is handled by {_labels}.
function _addressLabels(bytes calldata pid, string memory category, bool useSymbol)
internal
view
returns (string[] memory)
{
(address addr, bool ok) = _pidAddress(pid);
if (!ok) return new string[](0);
string memory leaf = useSymbol ? LabelLib.symbol(addr, "") : LabelLib.name(addr, "");
return _labels(category, leaf);
}
}
src/errors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
error InvalidArguments();
error InvalidArgumentsWithContext(string context);
/// @notice A constructor argument expected to be a deployed contract has no code. `name` is the dependency label.
error NotAContract(string name);
error NotAuthorized();
error NotChainlinkOracle();
/// @notice Thrown when an assistant entrypoint that must be delegatecalled is called directly on the singleton
/// (`address(this) == SELF`). Canonical delegatecall-guard error for the assistant-fed family (`BalanceAdapterAssistant`).
error NotDelegateCall();
/// @notice An assistant entrypoint was told to track/act for an account other than the executing context
/// (`address(this)`, i.e. the delegatecalling Safe). Canonical assistant self-scope check (`_requireSelf`).
error AssistantAccountMismatch(address expected, address provided);
// Permissionless assistant-fed assisted balance-adapter family (ADR 0018) — shared coordinate-cache errors, used by the
// single {AssistedCoordCache} base (every coordinate is an `abi.encode`d blob). The coordinate is identified by `id`
// (a tokenId / requestId / positionTicket, from `_coordId`); the full tuple, where richer, rides in the cache's events.
/// @notice `submit` was given a coordinate not currently owned by the caller (`msg.sender`).
error CoordinateNotOwned(address account, uint256 id);
/// @notice `submit` would grow the caller's cache past its per-account cap.
error CoordinateCacheFull(address account, uint256 maxCoordinates);
/// @notice `remove` targeted a coordinate not in the caller's cache.
error CoordinateNotCached(address account, uint256 id);
/// @notice `remove` targeted a coordinate the caller still owns (a live position) — refused so a live position is never
/// dropped (would under-report the caller's own NAV). Only a claimed/consumed coordinate may be removed.
error CoordinateStillLive(address account, uint256 id);
/// @notice `submit` was given a coordinate that failed the adapter's write-time protocol validation (e.g. an
/// unregistered target). Distinct from {CoordinateNotOwned} (ownership) — this is a malformed/invalid coordinate.
error InvalidCoordinate(address account, uint256 id);
// Bridge-specific errors
error AlreadyInitialized();
error InvoiceNotFound();
error InvoiceAlreadyExists();
error InvalidInvoiceStatus();
error InvalidInvoice();
error TransferFailed();
error InsufficientBalance(address asset, uint256 required, uint256 available);
error InvalidChainId();
error InvalidNonce();
error InvalidCompletionData();
error InvalidChecksum(bytes32 invoiceId, bytes24 provided, bytes24 calculated);
error InvalidTimestamp(uint64 provided, uint64 current);
error AssetHasActiveInvoices(string symbol);
error AssetNotRegistered(string symbol);
// NAV Calculator / registry errors
error PriceFeedNotSet(address asset);
error AssetNotFound();
error OnlyNAVCalculator();
error ArrayLengthMismatch();
error InvalidAssetDecimals();
error InvalidDecimalExponent();
src/nav/INAVCalculator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IBalances} from "src/balances/IBalances.sol";
import {IPrices} from "src/prices/IPrices.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
/// @title INAVCalculator
/// @notice Interface for the NAV Calculator contract. Defines the full API for asset registration, price feeds,
/// balance adapters, and NAV/position queries in one or more quote currencies.
/// @dev Extends IBalances for adapter registry and IPrices for price feed types. Implementations are typically
/// UUPS-upgradeable and use AccessControl (MANAGER for mutations, DEFAULT_ADMIN_ROLE for upgrades).
/// @author KPK
interface INAVCalculator is IBalances {
/// @notice A balance adapter consumed the gas stipend the NAV read forwarded to it without answering.
/// @dev Deliberately NOT folded into the read's fail-open path. A revert means "this adapter has nothing to
/// report"; running out of gas means "this adapter's answer is unknown", and reporting an unknown answer
/// as an empty one drops the adapter's legs — a dropped debt leg RAISES the reported NAV.
///
/// Declared here rather than alongside the shared errors so it reaches consumers: it is raised inside a
/// DELEGATECALLed library, and an error a contract never names itself does not appear in that contract's
/// ABI. Callers generate against this interface and the NAVCalculator implementing it, so a revert they
/// can actually decode has to be part of it.
///
/// `adapter` names the adapter that was running, which is not always the adapter at fault: the stipend is
/// a share of what the READ still holds, so an under-funded call starves whichever adapter happens to be
/// reached last. `stipend` and `consumed` are what separate the two cases. A large `stipend` fully
/// consumed means that adapter is genuinely runaway; a small `stipend` means the read itself was short of
/// gas and the fix is to supply more.
/// @param adapter The adapter that was executing when its gas ran out.
/// @param stipend The budget the classification was measured against: 63/64 of what the read held just before
/// the call. It is NOT precisely what the EVM forwarded — the same 63/64 rule is applied again at the
/// CALL itself, to a figure already reduced by building the calldata — so on a genuine exhaustion
/// `consumed` lands a few tens of gas ABOVE it. Read the two as a ratio, not as a balance.
/// @param consumed Gas the call actually cost this frame, including the call overhead.
error AdapterGasExhausted(address adapter, uint256 stipend, uint256 consumed);
/// @notice One governed instance of a meta-adapter consumed its gas stipend without answering.
/// @dev The {AdapterGasExhausted} sibling, one frame in. A meta-adapter isolates each instance behind its own
/// `try`/`catch` so a single faulty instance cannot zero out the batch, and that isolation has the same
/// blind spot: an instance that runs out of gas is indistinguishable from one that reverted, and recording
/// it as "no positions" drops its legs while the meta-adapter still RETURNS SUCCESSFULLY — so the caller
/// sees a complete-looking answer. A dropped debt leg raises the reported NAV.
///
/// Raised rather than swallowed. `PriceFeedLib` keys on this selector explicitly rather than re-deriving
/// exhaustion from gas, so a cheap early raise here cannot be re-scored as a benign revert one frame out.
///
/// `instance` is where the budget ran out, which is NOT the same as where it went. The fan-out gives each
/// instance a share of whatever its predecessors left, so a single runaway instance early in the governed
/// set can leave the NEXT one too little and get it named instead. Read the pair together: a large
/// `stipend` fully consumed means that instance is genuinely runaway; a small `stipend` means it was
/// starved by something before it, or the read was under-funded to begin with. Removing the named instance
/// is the wrong first move when `stipend` is small.
/// @param adapter The meta-adapter that was fanning out. Overwritten by `PriceFeedLib` with the address it
/// actually called, so it is trustworthy even when the rest of the payload is not.
/// @param instance The governed instance coordinate whose read ran out of gas — see the caveat above.
/// @param stipend The budget the classification was measured against: 63/64 of what the fan-out held just
/// before the call. As with {AdapterGasExhausted} it is NOT precisely what the EVM forwarded — the same
/// rule is applied again at the CALL — so `consumed` lands slightly above it. A ratio, not a balance.
/// @param consumed Gas the instance call actually cost, including the fan-out's call overhead.
error InstanceGasExhausted(address adapter, bytes32 instance, uint256 stipend, uint256 consumed);
/// @notice {getAccountNavForAdapters} was given an empty adapter list.
/// @dev Not silently answered with a zero NAV. An empty slice is indistinguishable from "this portion of the
/// portfolio is worth nothing", and a caller that built its slice list from a stale or mis-parsed source
/// would read that zero as a real answer and reassemble a NAV that is short by exactly the adapters it
/// forgot to ask for. Declared here rather than in `src/errors.sol` for the same reason as
/// {AdapterGasExhausted}: it is raised inside a DELEGATECALLed library, so it only reaches consumers'
/// generated ABIs by being named in this interface.
error EmptyAdapterSlice();
/// @notice {getAccountNavForAdapters} was given an adapter that is not in the global registry.
/// @dev The registry is `getAllAdapters()` — the exact list the complete read scans — so "registered" here
/// means "would have been included in `getAccountNav`". Rejected rather than skipped: an unregistered
/// address (a decommissioned adapter, a typo, an address from another chain) has no positions to report,
/// so skipping it would return a well-formed slice whose `value` is silently missing whatever the caller
/// believed that address covered — and whose `adaptersCovered` would then have to either echo an address
/// that contributed nothing or omit one the caller asked for. Both mislead the coverage check that
/// `adaptersCovered` exists to support.
/// @param adapter The supplied address that is not a registered balance adapter.
error AdapterNotRegistered(address adapter);
/// @notice {getAccountNavForAdapters} was given the same adapter twice in one slice.
/// @dev A repeated adapter is queried twice and its positions summed twice, so the slice over-reports by that
/// adapter's whole value. Rejected rather than deduplicated, because a duplicate means the caller's
/// partition logic is wrong and the same defect will be producing overlaps ACROSS slices — which this
/// contract cannot see and silently deduplicating here would hide. Cross-slice overlap is what
/// `PartialNAV.adaptersCovered` is for.
/// @param adapter The address that appeared more than once.
error DuplicateAdapterInSlice(address adapter);
//
// Structs
//
/// @notice Registered asset metadata used by the NAV/Pricing registry and balance adapters.
/// @param asset Token address (or NATIVE_ADDRESS for chain native token).
/// @param symbol Display symbol (e.g. "ETH", "USDC").
/// @param decimals Number of decimals for amounts.
struct Asset {
address asset;
string symbol;
uint8 decimals;
}
/// @notice Balance-only position data returned by balance adapters (no pricing).
/// @dev NAVCalculator enriches these with pricing to produce Position structs.
/// @param balanceAsset Asset metadata (address, symbol, decimals). The token `amount` is denominated in.
/// @param balanceAdapter Address of the adapter that reported this position. Provenance / audit trail — NOT part of identity.
/// @param amount Balance magnitude (always positive); sign is implied by isDebt.
/// @param isDebt True if debt (subtract from NAV), false if credit (add to NAV). Canonical NAV-sign signal.
/// @param protocolBrand `keccak256` of the protocol brand slug (version-stripped, e.g. `aave`, `balancer`; see
/// `src/utils/ProtocolIds.sol`). The broadest roll-up layer — several `protocolId`s share it
/// (`aave-v3` → `aave`; `balancer-v2` + `balancer-v3` → `balancer`). Display/grouping only; NOT part of the
/// stable identity key. Equals `protocolId` for unversioned protocols.
/// @param protocolId `keccak256` of the broad protocol-ecosystem slug (e.g. `aave-v3`, `curve`; see
/// `src/utils/ProtocolIds.sol`). A roll-up / grouping key only — several `protocolSubId`s share it
/// (e.g. `aave-v3-lending` + `aave-v3-safety-module` both roll up to `aave-v3`). NOT part of the stable
/// identity key (it is functionally determined by `protocolSubId`).
/// @param protocolSubId `keccak256` of the specific protocol-product slug (e.g. `aave-v3-lending`; see
/// `src/utils/ProtocolIds.sol`). Selects the `positionId` ABI-decode schema — one sub-slug implies exactly
/// one schema — and is the protocol component of the stable identity key. Equals `protocolId` for
/// single-product ecosystems.
/// @param positionId ABI-encoded position identifier. Decode schema is determined by `protocolSubId`.
/// e.g. for AAVE_V3_LENDING: `abi.encode(address pool)`.
/// Full schema table: see `src/utils/ProtocolIds.sol` and docs/howto/position-identity-schema.md.
/// @param positionKind Semantic discriminator (Wallet / Supplied / Borrowed / Collateral / Staking / Rewards / Fees).
/// Together with `protocolSubId` and `positionId` forms the stable per-chain identity key
/// `(chainId, protocolSubId, positionId, balanceAsset.asset, positionKind)`.
/// @param isLocked True if this leg is NOT withdrawable right now (the pending portion of a withdrawal queue, or a
/// staked amount in/awaiting its unstaking cooldown); false if fully liquid / claimable now. Withdrawal-queue
/// and cooldown adapters keep a STATIC, timeless `positionId` (the queue/manager/asset/vault/stake-token
/// coordinate) and split an account's holding into up to two legs — a claimable leg (`isLocked=false`) and a
/// locked leg (`isLocked=true`). `isLocked` is a **mutable per-leg attribute, NOT part of the identity key**:
/// a leg flips `true→false` as its portion finalizes/unlocks, so keying on it would split one economic
/// position into two keys over its lifetime. The claimable and locked legs therefore share ONE key and are
/// **summed** in reconciliation (the sum is the full holding); read `isLocked` per leg for the
/// claimable-vs-locked breakdown. `false` for every adapter except withdrawal-queue / cooldown legs.
/// @param positionInstanceId OPTIONAL EPHEMERAL per-item coordinate as a `bytes32` — a Uniswap V3 / PancakeSwap V3
/// NFT id, a withdrawal/exit request id, or a StakeWise exit ticket (each a `uint256` widened to `bytes32`).
/// `bytes32(0)` for adapters with no per-item granularity. It is the SOLE ephemeral identity field, by
/// design: the **stable** reconciliation key
/// `(chainId, protocolSubId, positionId, balanceAsset.asset, positionKind)` deliberately EXCLUDES it,
/// so the legs of one anchor sum and identity survives item churn. A consumer that wants per-item
/// granularity MAY append `positionInstanceId` to the key — gaining one position per item, at the cost of an
/// **ephemeral** key (it blinks in/out as items are minted/burned/claimed). Never use it for stable
/// identity. (Stable sub-distinguishers like an Aave reserve are NOT here — they live in `balanceAsset`.)
/// Typed as `bytes32` (not `bytes`): every current coordinate is a single `uint256`, and a value type keeps
/// the position-building/copy loops under the via_ir stack limit.
struct PositionBalance {
Asset balanceAsset;
address balanceAdapter;
uint256 amount;
bool isDebt;
bytes32 protocolBrand;
bytes32 protocolId;
bytes32 protocolSubId;
bytes positionId;
PositionKind positionKind;
bool isLocked;
bytes32 positionInstanceId;
}
/// @notice Enriched position including pricing and quote-currency value.
/// @dev Returned by getAccountPositions and getAccountPositionsForAsset.
/// @param balanceAsset Asset metadata from registry (canonical symbol/decimals).
/// @param balanceAdapter Adapter that reported the balance.
/// @param amount Balance magnitude (positive); sign implied by isDebt.
/// @param isDebt True if debt, false if credit.
/// @param quoteAsset Quote currency for value (e.g. USD when address(0)).
/// @param value Value in quote asset (negative for debt).
/// @param price Price used (e.g. USD per unit of asset).
/// @param priceDecimals Decimals of price.
/// @param stale True if the price was stale at query time.
/// @param protocolBrand `keccak256` protocol brand slug (broadest grouping). Copied from PositionBalance.
/// @param protocolId `keccak256` broad ecosystem slug (grouping). Copied from PositionBalance.
/// @param protocolSubId `keccak256` specific protocol-product slug (identity-key component). Copied from PositionBalance.
/// @param positionId ABI-encoded position identifier. Copied from PositionBalance.
/// @param positionKind Semantic discriminator. Copied from PositionBalance.
/// @param isLocked True if the leg is not withdrawable now (pending/cooling). Copied from PositionBalance.
/// @param positionInstanceId Ephemeral per-item coordinate (NFT/request/ticket), or empty. Copied from
/// PositionBalance; excluded from the stable identity key. See PositionBalance.
struct Position {
Asset balanceAsset;
address balanceAdapter;
uint256 amount;
bool isDebt;
Asset quoteAsset;
int256 value;
int256 price;
uint8 priceDecimals;
bool stale;
// True if the quote asset's own price feed was stale. When true, `value` is in USD (8dp) even though
// `quoteAsset` is non-zero — the quote conversion was skipped. Mirrors NAV.quoteAssetStale ([9]/S2).
bool quoteAssetStale;
bytes32 protocolBrand;
bytes32 protocolId;
bytes32 protocolSubId;
bytes positionId;
PositionKind positionKind;
bool isLocked;
// Ephemeral per-item coordinate copied from PositionBalance (NFT id / request id / ticket as bytes32).
// bytes32(0) when none. Display/granularity only — excluded from the stable identity key. See PositionBalance.
bytes32 positionInstanceId;
// True if the asset's primary price diverged from its monitor feeds beyond the configured tolerance (or,
// for stablecoins, from the $1 peg). A pricing-quality signal, NOT a validity/staleness flag: `price` and
// `value` are still populated from the primary. Consumers (e.g. the sub/redeem processor) decide how to react.
// APPENDED (not inserted mid-struct) so an in-place UUPS upgrade doesn't shift existing fields' ABI offsets.
bool irregular;
// True if the quote (unit-of-account) asset's own primary diverged from its monitors — the divergence
// counterpart to `quoteAssetStale`. Always false for a USD quote.
bool quoteAssetIrregular;
}
/// @notice Position enriched with human-readable display labels.
/// @dev ⚠️ **NEITHER `protocolName` NOR ANY element of `labels` is necessarily the adapter's own value.**
/// `AssetKindRegistry` holds an optional per-ADAPTER protocol name plus a per-ADAPTER, per-SEGMENT `labels`
/// override, and {PriceFeedLib.toVerbose} applies both in preference to the adapter's reply.
///
/// ⚠️ **Two earlier revisions of this line were narrower than the code, in the same direction each time.**
/// The first said the computed leaf was never overridable; the second said only `labels[0]` was. Both are now
/// false: {IAssetKindRegistry.setAdapterLabels} writes at ANY index, bounded only by
/// `min(reply.length, override.length)` — so the honest statement is that a segment comes from the adapter
/// **unless an operator overrode that index**, and `""` at an index is how an operator declines to.
///
/// What the override CANNOT do is change the array's LENGTH: it never writes past the adapter's own reply and
/// never extends it, so `labels.length` is always the adapter's answer. (The one exception is
/// `getAdapterDisplayInfo`, whose empty-reply case is deliberately grown — see
/// `PriceFeedLib.adapterDisplayInfo`.)
///
/// Which segments an operator SHOULD write is a property of the adapter, not of this struct;
/// `src/balances/BALANCE_ADAPTERS.md` §6.2 carries the per-adapter sweep, and
/// `ERC20DefaultBalanceAdapter` is the one adapter that must not be overridden at all (its single element is
/// the computed token symbol, not a category). `AdapterLabelOverrides.t.sol
/// ::test_labelsOverride_onLeafOnlyAdapter_replacesTheLeaf_documentedHazard` asserts that hazard.
/// Consumers must not treat these strings as identity in any case; see {IPositionDescribable}.
/// @dev Returned by verbose read methods. Labels are sourced from the adapter's `IPositionDescribable`
/// implementation (`positionLabels(positionId)`, via a fail-open staticcall) and are empty otherwise. MUST NOT
/// be used for identity, indexing, or reconciliation — use the typed fields on `position` for those purposes.
struct VerbosePosition {
Position position;
string protocolName; // e.g. "Aave V3", "Morpho"
// Ordered display hierarchy BELOW the protocol, leaf last (arbitrary depth, may be empty), e.g.
// ["Market", "wstETH/USDC"] or ["AMM Liquidity Pool", "WETH/USDC 0.05%"]. Full breadcrumb = [protocolName,
// ...labels]. Sourced from IPositionDescribable.positionLabels(positionId); display only. The ephemeral
// per-item id (NFT/request/ticket) is NOT here — it is the typed `position.positionInstanceId` field.
string[] labels;
}
/// @notice NAV snapshot bundled with a full verbose position breakdown.
// forge-lint: disable-next-line(pascal-case-struct)
struct VerboseNAV {
NAV nav;
VerbosePosition[] positions;
}
/// @notice NAV snapshot for an account in a given quote currency.
/// @param value Total portfolio value in quoteAsset (can be negative if net debt).
/// @param quoteAsset Quote currency; address(0) denotes USD.
/// @param timestamp Block timestamp of the reading.
/// @param stalePriceAssets Assets whose prices were stale at query time.
/// @param irregularPriceAssets Assets whose primary price diverged from their monitor feeds beyond tolerance
/// (or, for stablecoins, from the $1 peg) at query time. A pricing-quality signal, not a staleness flag —
/// `value` is still computed from the primary prices. Consumers decide how to react.
/// @param sequencerDown True if the L2 sequencer was down or in grace period (L2 only).
/// @param quoteAssetStale True if the quote asset's own price feed was stale. When true the value field
/// is in USD (fallback) even though quoteAsset is non-zero — callers must check this flag before
/// interpreting value as being in the requested quote currency.
/// @param monitorsUnhealthyPriceAssets Assets that **have monitor feeds configured but where none of them was
/// readable** at query time — every monitor stale, reverting, or reporting a non-positive price. For these
/// the divergence check silently did not run: `divergenceBps` is 0 because the arithmetic never executed,
/// not because the prices agreed, so absence from `irregularPriceAssets` says nothing about them. Without
/// this list "checked and clean" and "checked by nothing that answered" are the same bytes.
///
/// **This is NOT the "no monitors configured" case.** That is a static configuration property, derivable
/// off-chain from **`getMonitorFeedCount(asset) == 0` alone**, and it is deliberately excluded here — an
/// asset with nothing configured never appears in this list however long it goes unchecked. What this
/// reports is strictly a *runtime* failure of monitors that exist.
///
/// Do NOT additionally require `getAssetPricing(asset).divergenceToleranceBps == 0` for that derivation:
/// the conjunction is UNSATISFIABLE for any asset that ever had a monitor. `_setDivergenceTolerance`
/// rejects 0, so once a tolerance is set it can never be returned to zero, while `removeMonitorFeed`
/// leaves the tolerance untouched — so an asset whose monitors were all REMOVED has count 0 and a
/// non-zero tolerance, and an AND-recipe would silently never flag it. The tolerance only returns to 0
/// via full asset unregistration (`_removeAllMonitorFeeds`), by which point the asset is gone anyway.
///
/// Assets whose own primary is unusable are also excluded — stale feed, sequencer down, or a primary whose
/// 8-decimal normalisation degenerates to zero. In all of those the check was suppressed by the PRIMARY
/// rather than by the monitors, `stalePriceAssets` already reports the staleness cases, and naming the
/// monitors would point an operator at the wrong contract. Stablecoins with a non-zero `pegToleranceBps`
/// may appear here and still be peg-checked — the peg guard is monitor-independent — so this flags the
/// loss of the *divergence* check, not necessarily of all checks.
///
/// **Scope: assets this account holds positions in**, like `stalePriceAssets` and `irregularPriceAssets`.
/// It is built from the assets the account's positions touched, NOT from the whole registry, so absence
/// means "monitors healthy **or** no position held". A consumer reconciling against the registry-wide
/// per-asset view (`getPriceDivergence(asset).monitorFeedCount == 0` is the equivalent there) will see
/// differences that are this scoping, not a defect. Note also that `healthCheck()` — which DOES iterate
/// the whole registry — deliberately does not carry this array: `NAVCalculator` is 68 bytes from the
/// EIP-170 limit, so widening that return was not affordable. `Position.irregular` on
/// `getAccountPositions` likewise retains the original ambiguity, with no `NAV` struct alongside to join
/// against; use `getAccountNavVerbose` (whose `VerboseNAV` embeds the `NAV`) if you need both.
// forge-lint: disable-next-line(pascal-case-struct)
struct NAV {
int256 value;
Asset quoteAsset;
uint64 timestamp;
Asset[] stalePriceAssets;
bool sequencerDown;
bool quoteAssetStale;
// APPENDED (not inserted mid-struct) so an in-place UUPS upgrade doesn't shift existing fields' ABI offsets.
Asset[] irregularPriceAssets;
// True if the quote (unit-of-account) asset's own primary diverged from its monitors beyond tolerance —
// the divergence counterpart to `quoteAssetStale`. Always false for a USD quote (no quote feed).
//
// DECLARED GAP, deliberate: there is no `quoteAssetMonitorsUnhealthy` counterpart to
// `monitorsUnhealthyPriceAssets` below. For a non-USD quote whose own monitors have ALL gone unreadable, this
// flag is false for want of data — exactly the ambiguity that array exists to close — and nothing surfaces it.
//
// Why it was not added, in order of weight. (1) **Nothing in this repository's configuration exercises it**:
// `nav-config/assets-and-price-feeds/{1,42161,8453,100}.json` contain no quote keys, and `quoteAsset` is a
// CALLER-supplied parameter defaulting to USD (`address(0)`), not stored config — so the gap is reachable only
// by a caller that opts into a non-USD quote. (2) `NAVCalculator` has 68 bytes of EIP-170 headroom; a further
// struct member plus its computation plausibly exceeds that, and spending the last of the margin on an
// unexercised path would leave nothing for an urgent fix — after which the next change would need a new proxy
// rather than an upgrade.
//
// Limit of that evidence: it is a claim about THIS repository only. A downstream consumer (share layer,
// portal, agents, subgraphs) could pass a non-zero `quoteAsset`, which cannot be verified from here. If one
// does, this gap is worth the bytes and should be revisited.
//
// Mitigation meanwhile: a caller using a non-USD quote should read `getPriceDivergence(quoteAsset)` and treat
// `monitorFeedCount == 0` alongside a usable primary as exactly this condition.
bool quoteAssetIrregular;
// APPENDED for the same reason as `irregularPriceAssets` above. This redeploy uses a NEW proxy rather than an
// in-place upgrade, so nothing forced the append — but moving existing consumers' ABI offsets for a change
// that did not need to move them is gratuitous, so the convention is honoured anyway.
Asset[] monitorsUnhealthyPriceAssets;
}
/// @notice One SLICE of an account's NAV: the same snapshot as {NAV} but covering only the balance adapters
/// named in the request, plus the list of adapters it actually covered.
/// @dev Returned by {getAccountNavForAdapters}. Deliberately a DISTINCT type from {NAV}, not a reuse of it,
/// and that is the whole safety property of this API: a partial result must not be assignable, passable
/// or decodable where a complete NAV is expected. A `PartialNAV` that type-checked as a `NAV` would let a
/// caller hand one slice to a consumer that believes it holds the whole portfolio — the exact silent
/// under-report pagination exists to make impossible. The cost is that a caller must reassemble
/// explicitly; that cost is the point.
///
/// **Field order mirrors {NAV} exactly for its first eight fields, including NAV's own appended ones, so
/// a decoder written for `NAV` maps 1:1 onto this struct's prefix.** `adaptersCovered` is appended last.
/// Keep it that way: any future field goes at the END of this struct (see the APPENDED note on {NAV}),
/// and any field appended to {NAV} must be appended here too — BEFORE `adaptersCovered` if the prefix
/// correspondence is to survive, which means moving `adaptersCovered` and accepting the ABI shift, or
/// accepting that the prefix correspondence ends there. Prefer the latter: shifting a field's offset in a
/// struct a live off-chain reassembler decodes is worse than losing a documentation convenience.
/// @param value Net value of THIS SLICE's positions in `quoteAsset`, signed (negative if the slice is net
/// debt). **This is the one field that sums.** Debt legs are already negative, and prices are per-asset
/// and independent of which adapter reported the position, so the arithmetic is exact: summing `value`
/// over a partition of `getAllAdapters()` reproduces `getAccountNav().value` bit-for-bit, with no
/// tolerance and no rounding slack. Every other field below does NOT sum.
///
/// **One precondition, and it is not theoretical: no adapter may have been GAS-STARVED in either read.**
/// Some adapters fail open inside their own frame and return SUCCESSFULLY having dropped legs —
/// `AssistedCoordCache._collect` isolates each cached coordinate behind an UNCAPPED
/// `try this.valueCoordSelf(…)`/`catch {}`, and `ERC20DefaultBalanceAdapter` records 0 for an asset whose
/// `balanceOf` staticcall fails. Nothing upstream can see that; see the "Scope, stated plainly" note on
/// `PriceFeedLib._getAdapterPositions`.
///
/// The per-adapter stipend is a share of what the READ still holds at the moment that adapter is reached,
/// and `computeNav` scans the supplied array IN ORDER. So the stipend depends on **slice composition AND
/// ORDERING**, not merely on how few adapters a slice names. Both directions are reachable:
/// a singleton slice gives its adapter more gas than the full scan did and may value legs the complete
/// read dropped; a multi-adapter slice that places an adapter BEHIND an expensive one can starve it below
/// what the complete read gave it. The second case is not hypothetical — `getAllAdapters()[0]` is
/// permanently `ERC20DefaultBalanceAdapter` (pushed in `initialize`, unremovable, and swap-and-pop only
/// ever fills a hole at the removed index, which index 0 can never be), so the complete read already
/// hands it the largest stipend any read can and **a slice can only ever give it less.**
///
/// Which read ends up LARGER is a separate question from which one was starved. The sign of the skew is
/// set by the `isDebt` of the dropped legs, not by which read dropped them: a dropped credit leg lowers
/// that read, a dropped debt leg raises it.
///
/// **Therefore: do NOT assume a direction, and do not pick by magnitude either.** "Trust the slice" is
/// wrong, and so is "take the lower" — with today's credit-only absorbers starvation can only LOWER a
/// read, so "take the lower" would select the starved number every time the two disagree. Nor is
/// under-reporting a safe default: a processor pricing shares off a low NAV over-issues to a subscriber.
/// Reconcile before publishing either. If a choice must be automated, key it to the SIGNAL rather than
/// the magnitude — prefer the read that did not raise {AdapterGasExhausted} / {InstanceGasExhausted}, and
/// publish neither if the two disagree while neither raised one. And do not treat the two reads agreeing
/// as a health check that passes silently — they agree when nothing was starved, which is the common case
/// and therefore uninformative.
///
/// The property that would keep a starved read from OVER-reporting is: **no adapter emits an
/// `isDebt == true` leg from behind ANY fail-open read.** "Any" is load-bearing — a gas CAP makes this
/// worse, not better, because an uncapped read can at least be rescued by supplying more gas whereas a
/// capped one (`StaticCallLib.PROBE_GAS`) is starved by the cap and drops unconditionally.
/// **Three shipped adapters currently break it** — `EulerVaultsMetaBalanceAdapter._safeDebt` (capped
/// probe, supply leg survives), `FluidVaultLib.aggregate` (uncapped, drops one NFT's supply and borrow),
/// and `GearboxV3CreditAccountsMetaBalanceAdapter._appendBorrow` (narrowly mitigated by a
/// `_debtReportable` gate evaluated before the gas is drained). None is introduced or fixed here, and the
/// first two over-report the COMPLETE read as much as a slice. See `docs/howto/read-nav-in-slices.md`.
/// @param quoteAsset Quote currency; `address(0)` denotes USD. Identical in every slice (it is the caller's
/// argument), so a reassembler can assert it rather than combine it.
/// @param timestamp Block timestamp of THIS call. A reassembler MUST check that every slice carries the same
/// value: differing timestamps mean the slices were read at different blocks, and a NAV assembled from
/// positions priced at different blocks is not a NAV of anything. See the caller contract on
/// {getAccountNavForAdapters}.
/// @param stalePriceAssets Assets whose prices were stale, **restricted to the assets this slice's positions
/// touched**. NOT a portfolio-wide list: an asset that is stale but only held through an adapter in
/// another slice is absent here and present there. Must be UNIONED across slices, and the union
/// de-duplicated — two slices holding the same stale asset each report it.
/// @param sequencerDown True if the L2 sequencer was down or in grace period (L2 only). Derived from this
/// contract's sequencer config, not from the slice, so it is the same in every slice — but it is still
/// per-slice data and a caller that reads it on only one slice is relying on that invariant rather than
/// checking it. OR it across slices.
/// @param quoteAssetStale True if the quote asset's own price feed was stale, in which case `value` is in USD
/// (8dp) despite `quoteAsset` being non-zero. Also invariant across slices (it depends on the quote
/// asset, not the adapters) — which makes it *more* dangerous to ignore, not less: if it is true, every
/// slice's `value` is in USD, and a reassembler that never looked will label a USD total with the
/// requested quote currency. OR it across slices.
/// @param irregularPriceAssets Assets whose primary price diverged from their monitor feeds beyond tolerance
/// (or, for stablecoins, from the $1 peg), **restricted to the assets this slice touched**. Same
/// per-slice restriction and same union-and-dedupe requirement as `stalePriceAssets`. This is the depeg
/// signal; a slice-local read of it is a slice-local depeg picture.
/// @param quoteAssetIrregular True if the quote asset's own primary diverged from its monitors. Invariant
/// across slices, always false for a USD quote. OR it across slices.
/// @param monitorsUnhealthyPriceAssets Assets with monitors configured but none readable at query time,
/// **restricted to the assets this slice touched**. Same per-slice restriction and same
/// union-and-dedupe requirement as `stalePriceAssets` and `irregularPriceAssets` — it is built from the
/// same per-asset cache, so the semantics carry over unchanged. Reported on the paginated read
/// deliberately: a caller paginates because the complete read does not fit one `eth_call`, i.e. for the
/// largest accounts, and those are exactly the ones a monitoring consumer watches — omitting it here
/// would hide the signal from the accounts that most need it. A slice-local read is a slice-local
/// picture of monitor health, and a union over every slice is required before concluding an asset is
/// covered. See {NAV.monitorsUnhealthyPriceAssets} for what the condition does and does not mean.
/// @param adaptersCovered The adapters this slice actually queried — element-for-element identical to the
/// `adapters` argument, order included, because the call reverts rather than silently dropping, adding
/// or reordering one. That makes it a machine-checkable record rather than a restatement of the input:
/// the guarantee is that nothing came between the request and the scan. Its purpose is reassembly
/// verification: concatenate it
/// across every slice and compare against `getAllAdapters()`. A missing address means the assembled NAV
/// is short by that adapter's positions; a repeated one means it is double-counted. Neither is
/// detectable from `value` alone, because a short NAV is a perfectly plausible number.
// forge-lint: disable-next-line(pascal-case-struct)
struct PartialNAV {
int256 value;
Asset quoteAsset;
uint64 timestamp;
Asset[] stalePriceAssets;
bool sequencerDown;
bool quoteAssetStale;
Asset[] irregularPriceAssets;
bool quoteAssetIrregular;
// Appended after the {NAV}-mirroring prefix — see the struct-evolution note above. No longer the LAST
// member: `monitorsUnhealthyPriceAssets` was appended after it, deliberately, so this field keeps its ABI
// offset. New members go after that one, not here.
address[] adaptersCovered;
// Appended after `adaptersCovered` rather than beside its {NAV} siblings: keeping `adaptersCovered` at its
// existing offset matters more than keeping this struct's prefix a positional mirror of {NAV}, which it stops
// being the moment {NAV} grows. The two structs stay deliberately DISTINCT types — a partial result must not
// be decodable where a complete one is expected — so mirroring is a convenience, never a guarantee.
Asset[] monitorsUnhealthyPriceAssets;
}
/// @notice Price data for the freshest non-stale feed selected for an asset.
/// @dev When multiple feeds are registered, these fields describe the winning (freshest) feed.
/// When all feeds are stale, fields describe the first registered feed and stale == true.
/// @param priceFeed Address of the selected price feed contract.
/// @param priceType Feed type (Chainlink, Custom, Redstone, or API3).
/// @param price Current price (e.g. USD per unit); 0 when stale.
/// @param decimals Decimals of the selected feed's output.
/// @param chainlinkHeartbeat Staleness window (seconds) of the reported feed. For Chainlink/Redstone/API3 this is
/// the selected feed's configured heartbeat. For Custom feeds it is the GOVERNING leg's heartbeat — the
/// underlying Chainlink leg closest to its own staleness limit — paired with `updatedAt` below. A Custom
/// feed that successfully reports no trackable Chainlink leg gives 0; if its freshness read REVERTS this
/// field retains the registered config heartbeat (only `updatedAt` falls back to 0), so a non-zero value
/// here does not by itself imply a successful read. See ICustomPriceFeed.governingFeedFreshness.
/// @param updatedAt Last-update timestamp of the reported feed. For Chainlink/Redstone/API3 this is the selected
/// feed's `latestRoundData().updatedAt`. For Custom feeds it is the GOVERNING leg's `updatedAt` — a real,
/// matched pair with `chainlinkHeartbeat` above. 0 when the feed has no push timestamp or the read reverts.
/// @dev ADVISORY PAIR — `updatedAt`/`chainlinkHeartbeat` describe only the reported oracle leg's push freshness.
/// `stale` (and `sequencerDown`) is the AUTHORITATIVE staleness verdict: it also folds in the rate answer's
/// validity, the L2 sequencer state, and the feed's own configured heartbeat gate — none of which the pair
/// can express, so the pair can read "fresh" (age < heartbeat) while `stale` is true. Consumers MUST gate on
/// `stale`; never recompute a fresh/stale decision from `(updatedAt, chainlinkHeartbeat)` alone.
/// @param stale True if all feeds are stale or the L2 sequencer is down.
/// @param sequencerDown True if L2 sequencer is down (L2 only).
/// @param healthyFeedCount Number of registered feeds that passed all staleness gates on this read.
/// A value below the total registered feed count signals partial redundancy collapse and
/// should trigger off-chain alerting.
/// @param irregular True if the primary price diverged from the worst-case (furthest) healthy monitor feed
/// beyond the configured divergence tolerance, or (stablecoins) from the $1 peg beyond the peg tolerance.
/// @param divergenceBps Worst-case basis-point gap between the primary price and any single healthy monitor
/// price (0 when there are no healthy monitors or the primary is stale).
/// @param monitorFeedCount Number of healthy monitor feeds that contributed to the divergence computation.
struct PriceFeedData {
address priceFeed;
IPrices.PriceType priceType;
int256 price;
uint8 decimals;
uint256 chainlinkHeartbeat;
uint256 updatedAt;
bool stale;
bool sequencerDown;
uint256 healthyFeedCount;
bool irregular;
uint256 divergenceBps;
uint256 monitorFeedCount;
}
//
// Events
//
/// @notice Emitted when the Chainlink L2 sequencer uptime feed is updated.
/// @param oldChainlinkUptimeFeed Previous uptime feed address.
/// @param newChainlinkUptimeFeed New uptime feed address.
event ChainlinkUptimeFeedUpdated(address indexed oldChainlinkUptimeFeed, address indexed newChainlinkUptimeFeed);
/// @notice Emitted when the L2 sequencer grace period is updated.
/// @param oldSequencerGracePeriod Previous grace period in seconds.
/// @param newSequencerGracePeriod New grace period in seconds.
event L2SequencerGracePeriodUpdated(uint256 oldSequencerGracePeriod, uint256 newSequencerGracePeriod);
/// @notice Emitted when an asset is registered.
/// @param asset Registered asset address.
/// @param decimals Asset decimals.
event AssetRegistered(address indexed asset, uint8 decimals);
/// @notice Emitted when an asset is unregistered.
/// @param asset Unregistered asset address.
event AssetUnregistered(address indexed asset);
//
// Errors
//
/// @notice Thrown when the L2 sequencer uptime feed is not set but the grace period is being updated.
error UptimeFeedNotSet();
//
// Mutating functions (require MANAGER role)
//
/// @notice Registers an asset and sets its price feed.
/// @dev Fetches decimals/symbol from ERC20 or uses native token symbol. Adds asset to default adapter inclusion list.
/// @param asset Asset address to register (cannot be zero).
/// @param priceFeed Price feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero for all types).
function registerAsset(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
external;
/// @notice Adds a price feed for an already registered asset, or UPDATES the heartbeat of one already there.
/// @dev UPSERTS. If `priceFeed` is already registered for `asset`, this REWRITES its `chainlinkHeartbeat`
/// in place and emits {IPrices-PriceFeedHeartbeatUpdated}; it does NOT revert, and it does NOT emit a
/// PriceFeedAdded/PriceFeedRemoved pair. Do not build idempotency on a duplicate reverting.
/// Reverts: PriceFeedAlreadyRegistered only when the heartbeat is UNCHANGED; PriceFeedTypeImmutable
/// when `priceType` differs from the stored one (a feed's type is identity, not configuration);
/// PriceFeedDecimalsMismatch when the feed's live decimals no longer match the stored value.
/// @param asset Registered asset address.
/// @param priceFeed Price feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero for all types).
function addOrModifyPriceFeed(
address asset,
address priceFeed,
IPrices.PriceType priceType,
uint256 chainlinkHeartbeat
) external;
/// @notice Adds a monitor (divergence-only) feed for an asset. Monitor feeds NEVER price the NAV; they are read
/// only to detect divergence between the primary price and the worst-case (furthest) healthy monitor price.
/// @dev Requires the asset's divergence tolerance to be set first (>0), else reverts DivergenceToleranceRequired.
/// Monitor feeds must report NAV_DECIMALS decimals (else MonitorFeedDecimalsMismatch). Reverts
/// MonitorFeedAlreadyRegistered only when the heartbeat is UNCHANGED (this UPSERTS an existing monitor's heartbeat, emitting MonitorFeedHeartbeatUpdated).
/// @param asset Registered asset address.
/// @param priceFeed Monitor feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero).
function addMonitorFeed(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
external;
/// @notice Sets the asset's divergence tolerance in basis points (must be in (0, 10000]).
/// @param asset Registered asset address.
/// @param divergenceToleranceBps Max worst-case primary-vs-any-single-monitor gap before the asset is flagged irregular.
function setDivergenceTolerance(address asset, uint32 divergenceToleranceBps) external;
/// @notice Sets the asset's stablecoin peg tolerance in basis points (in [0, 10000]; 0 disables the peg guard).
/// @param asset Registered asset address.
/// @param pegToleranceBps Max deviation of the primary price from $1 before the asset is flagged irregular.
function setPegTolerance(address asset, uint32 pegToleranceBps) external;
/// @notice Registers one or more **non-meta** balance adapters in the global registry in a single call.
/// @dev Reverts with InvalidArguments if the list is empty or contains a zero address, DuplicateBalanceAdapter
/// if any adapter is already registered, InvalidBalanceAdapter if any adapter does not implement
/// IBalanceAdapter, and MetaAdapterNotAllowed if any adapter implements IMetaBalanceAdapter (meta-adapters
/// must use addMetaBalanceAdapter). The batch is all-or-nothing.
/// @param adapters Adapter addresses (each must implement IBalanceAdapter and NOT IMetaBalanceAdapter).
function addBalanceAdapters(address[] calldata adapters) external;
/// @notice Registers a meta-adapter (ADR 0010) and seeds its instance set atomically, in one MANAGER call.
/// @dev The adapter must implement both IBalanceAdapter and IMetaBalanceAdapter (else InvalidBalanceAdapter /
/// NotMetaAdapter). Reverts InvalidArguments on a zero adapter, DuplicateBalanceAdapter if already
/// registered, and DuplicateMetaInstance on a repeated coordinate. An empty instance list is allowed
/// (registers the meta-adapter with no instances yet; seed later via addMetaInstances). Plain adapters use
/// addBalanceAdapters; subsequent instance changes use addMetaInstances / removeMetaInstances.
/// @param adapter The meta-adapter address.
/// @param instances Instance coordinates to seed (e.g. vault addresses widened to bytes32, or raw bytes32 IDs).
function addMetaBalanceAdapter(address adapter, bytes32[] calldata instances) external;
/// @notice Removes the price feed at the given index. Reverts if it is the last feed (CannotRemoveLastFeed).
/// @param asset Registered asset address.
/// @param index Index into the asset's feed array.
function removePriceFeedAt(address asset, uint256 index) external;
/// @notice Removes the price feed with the given address. Reverts if not found or last feed.
/// @param asset Registered asset address.
/// @param priceFeed Feed address to remove.
function removePriceFeed(address asset, address priceFeed) external;
/// @notice Removes the monitor feed at the given index. Monitor feeds are optional, so the last one may be removed.
/// @param asset Registered asset address.
/// @param index Index into the asset's monitor feed array.
function removeMonitorFeedAt(address asset, uint256 index) external;
/// @notice Removes the monitor feed with the given address. Reverts MonitorFeedNotFound if absent.
/// @param asset Registered asset address.
/// @param priceFeed Monitor feed address to remove.
function removeMonitorFeed(address asset, address priceFeed) external;
/// @notice Removes one or more balance adapters from the global registry in a single call.
/// @dev Reverts with InvalidArguments if the list is empty. The batch is all-or-nothing — if any adapter is
/// not registered (or is the default ERC20 adapter) the whole call reverts.
/// @param adapters Adapter addresses to remove (none may be the default ERC20 adapter).
function removeBalanceAdapters(address[] calldata adapters) external;
/// @notice Adds instance coordinates to a registered meta-adapter's queried set.
/// @dev This is the governed "which instances to query" registry — adapters themselves stay immutable.
/// All-or-nothing: reverts DuplicateMetaInstance if any coordinate is already present or repeated within
/// the batch (a duplicate would double-count NAV), InvalidArguments on an empty list, InvalidBalanceAdapter
/// if the adapter is not registered, and NotMetaAdapter if the adapter does not implement
/// IMetaBalanceAdapter. Coordinate values are otherwise not validated; a
/// malformed/unknown coordinate is isolated per-instance by the adapter's fan-out (cannot zero the batch).
/// @param adapter Registered meta-adapter address.
/// @param instances Instance coordinates to add (e.g. vault addresses widened to bytes32).
function addMetaInstances(address adapter, bytes32[] calldata instances) external;
/// @notice Removes instance coordinates from a registered meta-adapter's queried set.
/// @dev All-or-nothing: reverts MetaInstanceNotFound if any coordinate is not present (a coordinate repeated
/// within the batch also reverts), InvalidArguments on an empty list, InvalidBalanceAdapter if the adapter
/// is not registered, and NotMetaAdapter if the adapter does not implement IMetaBalanceAdapter. Order is
/// not preserved.
/// @param adapter Registered meta-adapter address.
/// @param instances Instance coordinates to remove.
function removeMetaInstances(address adapter, bytes32[] calldata instances) external;
/// @notice Excludes an asset from the default adapter so wallet balances are not reported for it.
/// @param asset Registered asset address.
function excludeAssetFromDefaultAdapter(address asset) external;
/// @notice Includes an asset in the default adapter so wallet balances are reported again.
/// @param asset Registered asset address.
function includeAssetInDefaultAdapter(address asset) external;
/// @notice Unregisters an asset: unsets price feed, removes from default adapter list, and removes from registry.
/// @param underlyingAsset Asset address to unregister.
function unregisterAsset(address underlyingAsset) external;
/// @notice Sets the Chainlink L2 sequencer uptime feed (use address(0) on L1).
/// @dev Requires DEFAULT_ADMIN_ROLE (same privilege level as upgrades). Disabling sequencer-uptime
/// detection on an L2 is equivalent in impact to an upgrade, so MANAGER access is not sufficient.
/// @param newChainlinkL2UptimeFeed New uptime feed address.
function setChainlinkL2SequencerUptimeFeed(address newChainlinkL2UptimeFeed) external;
/// @notice Sets the L2 sequencer grace period. Reverts UptimeFeedNotSet if the uptime feed is not set, or
/// InvalidArguments if the period is below 1 hour.
/// @param newSequencerGracePeriod Grace period in seconds (must be at least 1 hour).
function setChainlinkL2SequencerGracePeriod(uint256 newSequencerGracePeriod) external;
//
// View functions — registry
//
/// @notice Returns the number of registered assets (alias for getAssetCount).
/// @return Number of registered assets.
function assetCount() external view returns (uint256);
/// @notice Returns whether an asset is registered.
/// @param asset Asset address to check.
/// @return True if registered.
function isAssetRegistered(address asset) external view returns (bool);
/// @notice Returns all registered assets with metadata.
/// @dev **O(N), and it is the wrong tool for resolving ONE asset** — use {getRegisteredAsset} for that. This
/// copies the entire registry across the ABI boundary, so a caller that resolves M tokens by calling this
/// M times pays M full fetches. That pattern measured **6,274,562 gas for a single 50-token Balancer
/// instance at 43 registered assets** (18.4M at 100), and it is super-linear rather than linear because
/// each call allocates a fresh N-element array that is never freed, so memory expansion grows with the
/// square of the token count. At that scale it exhausts the per-adapter gas stipend and turns a NAV read
/// into a REVERT.
/// @return assets Array of Asset (address, symbol, decimals).
function getRegisteredAssets() external view returns (Asset[] memory assets);
/// @notice Resolves ONE asset's registry metadata in O(1), without reverting when it is absent.
/// @dev The single-asset counterpart to {getRegisteredAssets}, added because balance adapters resolve tokens
/// one at a time and the array getter makes that quadratic (see its docs for the measured figures).
/// Backed by the 1-based `_assetIndex` map the registry already maintains on register/unregister, so this
/// is a mapping load plus one array read — flat in the number of registered assets.
///
/// **Non-reverting by design, and that is the whole reason this is a new function rather than a widened
/// visibility on the existing internal lookup.** NAVCalculator's `_getRegisteredAsset` reverts
/// `AssetNotFound` for an unregistered asset, which is right for its callers but wrong here: "not
/// registered" is an ORDINARY, expected outcome on an adapter's emission path — the adapter simply skips
/// that leg. A reverting getter would turn every unregistered token an adapter happens to encounter into
/// a failed instance read, converting a skipped leg into a dropped position.
/// @param asset The asset to resolve.
/// @return assetInfo The registry entry. Zeroed (`address(0)`, `""`, `0`) when `found` is false — **check
/// `found`, do not infer absence from a zero `assetInfo.asset`**, since the two are only equivalent
/// while nothing zero-addressed can be registered.
/// @return found True if `asset` is registered.
function getRegisteredAsset(address asset) external view returns (Asset memory assetInfo, bool found);
/// @notice Returns the number of registered assets.
/// @return Number of registered assets.
function getAssetCount() external view returns (uint256);
/// @notice Returns the current implementation version (Initializable storage).
/// @return Version number.
function version() external view returns (uint64);
//
// View functions — NAV and positions
//
/// @notice Computes NAV for an account in the given quote currency.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD. Must have a price feed if not zero.
/// @return nav NAV struct (value, quoteAsset, timestamp, stalePriceAssets, sequencerDown, quoteAssetStale).
function getAccountNav(address account, address quoteAsset) external view returns (NAV memory nav);
/// @notice Computes the NAV contribution of a CALLER-SUPPLIED SET of balance adapters, so an off-chain caller
/// can read a portfolio's NAV in slices and reassemble it.
/// @dev Exists because {getAccountNav} scans every registered adapter in one `eth_call` and that cost grows
/// with the asset registry and the adapter set. Past a node's `eth_call` gas cap the complete read stops
/// returning anything at all — not a degraded NAV, no NAV — and there is no smaller question to ask.
/// This is that smaller question.
///
/// **A SET, NOT AN INDEX RANGE, AND THAT IS NOT A STYLE CHOICE.** `getAllAdapters()` is maintained with
/// swap-and-pop, so removing any adapter moves the LAST adapter into the removed one's index — always to a
/// LOWER index. A caller paging `[0,10)` then `[10,20)` across a governance removal therefore **silently
/// SKIPS** the moved adapter: it was at the tail, it lands in a slot the caller has already passed, and it
/// is never read. Both pages still look completely well-formed and the total is short by that adapter's
/// positions.
///
/// Precisely because elements only ever move DOWN, a removal cannot make an already-read adapter reappear
/// in a later page — so the hazard is a missed adapter, not a double-counted one. (An earlier version of
/// this note claimed a double-read; that is not reachable through either removal path.) Naming the adapters
/// removes the whole class rather than documenting it away.
///
/// ### The caller contract
///
/// **Canonical statement: `docs/howto/read-nav-in-slices.md`.** That document is the single source for the
/// reassembly rules, including the worked example and the gas-starvation precondition. What follows is the
/// short form, kept here because a consumer generating against this ABI may never open the repo — if the
/// two ever disagree, the how-to wins and this block is the bug.
///
/// Four obligations. The first two this function enforces; the last two it cannot see, and they are
/// where a reassembled NAV goes wrong.
///
/// 1. **Every adapter must be registered and appear at most once** — else {AdapterNotRegistered} or
/// {DuplicateAdapterInSlice}. An empty list reverts {EmptyAdapterSlice}.
/// 2. **The slice is queried as one atomic read**, so `value` is internally consistent.
/// 3. **All slices MUST be read at the same block, and PINNING THE BLOCK NUMBER IN THE REQUEST is the only
/// real control.** Pass an explicit block number to every `eth_call` — not `latest`, which lets
/// successive calls land on different heads. Positions and prices both move between blocks, so slices
/// from different blocks sum to a number that was never any account's NAV, and the sum looks entirely
/// reasonable.
///
/// `PartialNAV.timestamp` is a **cross-check, not the check**, and it is deliberately described that way
/// here: equal timestamps do NOT imply the same block. Arbitrum Nitro mints blocks roughly every 250ms,
/// so consecutive blocks routinely share a `block.timestamp`, and this contract is deployed there. The
/// field therefore catches only the gross case (slices seconds apart) and is blind to the narrow one
/// (two blocks inside one second) — which is the case an unpinned paging loop actually produces. There
/// is no block number in `PartialNAV` to check instead, by choice: adding one would not fix an unpinned
/// caller, and pinning the request already does.
/// 4. **The union of the slices must cover `getAllAdapters()` exactly once**, and
/// `PartialNAV.adaptersCovered` is how that is verified: concatenate it across slices and compare
/// against `getAllAdapters()` read at the same block. A missing adapter yields a NAV short by its
/// positions; a repeated one double-counts. Re-read `getAllAdapters()` at the pinned block rather than
/// trusting a cached list — the registry is governed and can change under a paging loop.
///
/// ### **Health flags do NOT sum. Ignoring them on ANY slice silently destroys a signal.**
///
/// `value` is the only field that composes by addition. **`stalePriceAssets`, `irregularPriceAssets` and
/// `monitorsUnhealthyPriceAssets` are restricted to the assets THIS slice's positions touched, and
/// `sequencerDown`, `quoteAssetStale` and `quoteAssetIrregular` are reported per slice. A caller that checks the flags on one slice, or on
/// the last slice, or on a slice it happened to keep, silently loses every staleness, depeg and
/// sequencer-down signal carried by the others — and gets a NAV number that looks fine.** That failure
/// shape is exactly what this repo's fail-open hardening work was for; it must not be reintroduced at the
/// reassembly boundary. **UNION the THREE asset arrays (de-duplicating: two slices holding the same stale
/// asset each report it) and OR the three booleans, across every slice, before treating the summed
/// `value` as usable.** The third array, `monitorsUnhealthyPriceAssets`, was appended later than this
/// instruction was first written — a reassembler that unions only two silently drops the monitor-health
/// signal, which is the falsely-reassuring direction and hits precisely the large accounts that must
/// paginate.
///
/// ### A meta-adapter is the atomic unit
///
/// A slice naming a meta-adapter includes **all** of that adapter's governed instances — every Aave V3
/// instance, every Morpho market, every Curve pool. There is no way to page WITHIN one meta-adapter
/// through this API, by design: the governed instance set is itself swap-and-pop mutable
/// (`addMetaInstances`/`removeMetaInstances`), so an instance-level range would carry the same
/// reordering hazard this signature exists to avoid, and an instance-level set would need the adapter to
/// accept a filter it does not have. So the finest slice available is one adapter. If a SINGLE
/// meta-adapter's read alone exceeds the gas budget, pagination does not help and the problem is that
/// adapter's per-instance cost, not the number of adapters — a different problem with a different fix.
///
/// ### What this does NOT do
///
/// Pagination reduces the gas of one call. It does not reduce the total gas of reading the whole NAV
/// (it slightly increases it — per-call overhead is paid per slice) and it does nothing whatsoever for an
/// ON-CHAIN consumer that must read a NAV inside a transaction: that consumer needs one complete answer
/// in one frame and cannot reassemble across calls. For those callers the only fixes are reducing the
/// cost of the read itself or shrinking the registry. This API is for off-chain readers.
///
/// One thing it does help, but read the caveat before relying on it: the per-adapter gas stipend is a
/// share of what the READ still holds, so an adapter starved into {AdapterGasExhausted} inside the
/// complete scan may have ample budget when asked for on its own. A slice can therefore get an answer out
/// of a portfolio whose complete read has started reverting.
///
/// **The caveat: a slice can also convert that loud revert into a silent omission.** Exhaustion is
/// classified by `GasStipendLib.exhausted` as `consumed >= stipend - stipend/8` — measured against a
/// stipend that is itself a share of the CALLER's budget. An adapter that fails at a roughly fixed cost
/// `G` for a non-gas reason is scored "exhausted" (loud {AdapterGasExhausted}) when the full scan's
/// stipend is small enough that `G` clears that bar, and scored "benign revert" — fail open, legs dropped,
/// nothing flagged — when the slice's larger stipend puts `G` below it. `adaptersCovered` still lists the
/// adapter, so the documented coverage check reports full coverage. If a dropped leg is a DEBT leg the
/// reassembled NAV over-reports.
///
/// So: a slice that succeeds where the complete read reverted is **evidence about gas, not a repaired
/// answer.** Do not silently promote it to the authoritative NAV.
///
/// And note what "just give the complete read more gas and compare" does NOT achieve: raising the budget
/// raises the stipend, which puts a fixed-cost failure below the same 7/8 bar for the COMPLETE read too.
/// Both reads then fail open on the identical adapter and AGREE on the identical wrong number. The signal
/// is the {AdapterGasExhausted} disappearing, not the two figures converging.
///
/// No verbose (labelled) counterpart exists yet. The label paths carry the heavier gas pressure and their
/// bounds are being re-derived; a paginated read built against numbers about to change would be wasted.
/// @param account Account address.
/// @param quoteAsset Quote currency; `address(0)` for USD. Must have a price feed if non-zero. Pass the SAME
/// value to every slice — the per-slice `value`s are otherwise denominated differently and summing them
/// is meaningless.
/// @param adapters The balance adapters to include. Each must be currently registered (in `getAllAdapters()`)
/// and may appear only once. Must be non-empty.
/// @return partialNav The slice's NAV contribution plus `adaptersCovered`. See {PartialNAV} — in particular,
/// `value` sums and nothing else does.
function getAccountNavForAdapters(address account, address quoteAsset, address[] calldata adapters)
external
view
returns (PartialNAV memory partialNav);
/// @notice Returns all positions for an account with pricing in the quote currency.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return positions Array of enriched Position structs.
function getAccountPositions(address account, address quoteAsset)
external
view
returns (Position[] memory positions);
/// @notice Returns positions for an account filtered by a single asset.
/// @dev **This is a filtered VIEW, not a net position. Do not sum it.** You asked for asset `X`, so you get
/// the legs denominated in `X` — a projection of the portfolio onto one asset, deliberately. Summing
/// `value` across the result (or netting credit against debt within it) produces a number that is not
/// this account's exposure to anything: the legs that offset these — collateral in another asset
/// backing a debt in `X`, or the reverse — are outside the filter by construction and are simply
/// absent, not netted. A vault borrowing `X` against `Y` shows here as debt in `X` with no sign of the
/// `Y` that secures it.
///
/// This is a documentation contract, not a defect, and the design is what makes it safe: **no NAV
/// number in this interface is ever computed with an asset filter.** {getAccountNav},
/// {getAccountNavForAdapters} and {getAccountNavVerbose} take no `asset` parameter at all, and the only
/// entry points that pass a non-zero filter into the position engine are this function and
/// {getAccountPositionsForAssetVerbose} — both of which return `Position[]`, never a `NAV`. So the
/// hazard lives entirely in what a CALLER does with the array, which is why it is stated here.
///
/// For a net figure, use {getAccountNav} (whole portfolio) or {getAccountNavForAdapters} (a validated
/// adapter slice, which partitions rather than projects and whose slices therefore do sum).
/// @param account Account address.
/// @param asset Asset to filter by (must be registered).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return positions Array of enriched Position structs for the asset. A filtered view — see the note above.
function getAccountPositionsForAsset(address account, address asset, address quoteAsset)
external
view
returns (Position[] memory positions);
/// @notice Returns all positions for `account` with human-readable labels.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return Array of VerbosePosition structs (enriched Position plus protocolName and display labels).
function getAccountPositionsVerbose(address account, address quoteAsset)
external
view
returns (VerbosePosition[] memory);
/// @notice Returns positions filtered by a single asset, with human-readable labels.
/// @dev **This is a filtered VIEW, not a net position. Do not sum it.** Identical projection semantics to
/// {getAccountPositionsForAsset} — this is that function's result passed through label enrichment, from
/// the same `_computePositions` call with the same filter — so the whole note there applies verbatim,
/// including the reason it is safe: no NAV in this interface is computed with an asset filter. See
/// {getAccountPositionsForAsset}.
/// @param account Account address.
/// @param asset Asset to filter by (must be registered).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return Array of VerbosePosition structs for the asset (enriched Position plus protocolName and display
/// labels). A filtered view — see the note above.
function getAccountPositionsForAssetVerbose(address account, address asset, address quoteAsset)
external
view
returns (VerbosePosition[] memory);
/// @notice Returns the aggregate NAV and full verbose position breakdown in one call.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return verboseNav VerboseNAV struct bundling the NAV snapshot with the verbose position list.
function getAccountNavVerbose(address account, address quoteAsset)
external
view
returns (VerboseNAV memory verboseNav);
/// @notice Returns the number of decimals used for USD values (e.g. 8).
/// @return USD decimals.
function usdDecimals() external view returns (uint8);
/// @notice Returns detailed price feed data for an asset (primary feed + divergence signal vs its monitors).
/// @param underlyingAsset Registered asset address.
/// @return priceFeedData PriceFeedData struct (feed, type, price, decimals, heartbeat, updatedAt, stale,
/// sequencerDown, healthyFeedCount, irregular, divergenceBps, monitorFeedCount).
function getPriceData(address underlyingAsset) external view returns (PriceFeedData memory priceFeedData);
/// @notice Same as {getPriceData} but WITHOUT the monitor-divergence computation (irregular/divergenceBps/
/// monitorFeedCount stay 0/false). For hot callers that only need price/staleness (e.g. custom feeds
/// reading the NAV-sourced base/USD term) so a base asset's monitor reads + sort aren't repaid per call.
/// @param underlyingAsset Registered asset address.
/// @return priceFeedData PriceFeedData struct with the divergence fields left at their defaults.
function getPriceDataNoDivergence(address underlyingAsset)
external
view
returns (PriceFeedData memory priceFeedData);
/// @notice Returns the divergence between an asset's primary price and its monitor feeds.
/// @param underlyingAsset Registered asset address.
/// @return primaryPrice The primary feed's price, normalized to NAV_DECIMALS (0 if the primary is stale).
/// @return monitorMedian The median of the healthy monitor prices, NAV_DECIMALS (0 if no healthy monitors).
/// @return divergenceBps Worst-case basis-point gap between the primary and any single healthy monitor — the
/// value `irregular` is thresholded on (0 if no monitors / primary stale).
/// @return irregular True if divergenceBps exceeds the divergence tolerance, or (stablecoins) the primary
/// deviates from $1 beyond the peg tolerance.
/// @return monitorFeedCount Number of healthy monitor feeds that contributed.
/// @return primaryStale True if the primary feed is stale (divergence undefined).
/// @return primaryAboveMonitors True if the primary sits above the monitor median (a premium); false if
/// below/equal — for a claim asset, below is the depeg direction. Meaningful only when
/// monitorFeedCount > 0.
function getPriceDivergence(address underlyingAsset)
external
view
returns (
int256 primaryPrice,
int256 monitorMedian,
uint256 divergenceBps,
bool irregular,
uint256 monitorFeedCount,
bool primaryStale,
bool primaryAboveMonitors
);
/// @notice Returns health status: sequencer down flag and lists of stale-price and irregular-price assets.
/// @return sequencerDown True if L2 sequencer is down or in grace period (false on L1).
/// @return stalePriceAssets Addresses of assets with stale prices.
/// @return irregularPriceAssets Addresses of assets flagged irregular (primary diverged from monitors / peg).
function healthCheck()
external
view
returns (bool sequencerDown, address[] memory stalePriceAssets, address[] memory irregularPriceAssets);
/// @notice Returns whether the account has any non-zero balance across adapters and registered assets.
/// @param account Account address.
/// @return has True if at least one position has non-zero amount.
function hasPositions(address account) external view returns (bool has);
/// @notice Returns the list of assets for which the account has at least one non-zero position.
/// @param account Account address.
/// @return assets Array of asset addresses.
function getAssetsWithPositions(address account) external view returns (address[] memory assets);
/// @notice Converts a list of (asset, amount) pairs into a total value in the quote currency.
/// @dev Only positive amounts; zero amounts are skipped. All assets must be registered with a price feed.
/// @param assets Asset addresses.
/// @param amounts Corresponding amounts (same length as assets).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return value Sum of values in quote asset (non-negative for valid inputs). When `quoteAssetStale` is
/// true, this is denominated in USD (8dp) instead of the requested quote ([9]/S2).
/// @return quoteAssetStale True if the requested non-USD quote asset's own feed was stale, so `value` fell
/// back to USD rather than the quote currency. Always false for a USD quote (address(0)).
function calculateValue(address[] memory assets, uint256[] memory amounts, address quoteAsset)
external
view
returns (int256 value, bool quoteAssetStale);
/// @notice Every listed adapter's EFFECTIVE display name and positionId-independent breadcrumb — the same values
/// the verbose position reads report, including any {AssetKindRegistry} override.
/// @dev Declared here, not only on the concrete contract, so INTERFACE-TYPED consumers can reach it. That is the
/// caller that matters: a consumer holding `INAVCalculator` is exactly the one that would otherwise
/// enumerate `getAllAdapters()` and staticcall `protocolName()` on each adapter itself, which is the
/// surface split this function exists to close. Leaving it off the interface would have left that consumer
/// with no way to reach the fix.
/// @param adapters The adapters to describe, typically the result of `getAllAdapters()`.
/// @return names Each adapter's effective protocol name.
/// @return labels Each adapter's effective breadcrumb, with any {AssetKindRegistry} per-segment override applied.
/// Empty when the adapter derives it per position AND no override is set. When the adapter answers
/// nothing but an override IS set, this path deliberately GROWS the breadcrumb to the override's leading
/// non-empty prefix — so it can be MULTI-segment, not merely a lone category. (It was a lone category
/// under the retired scalar `setAdapterLabelCategory`; do not code against that.) When the adapter DOES
/// answer, the override is overlaid segment-by-segment and can neither lengthen nor truncate the reply.
/// See `PriceFeedLib.adapterDisplayInfo` for why the empty case diverges from the position path.
function getAdapterDisplayInfo(address[] calldata adapters)
external
view
returns (string[] memory names, string[][] memory labels);
}
src/prices/IPrices.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IPrices Interface
/// @notice Interface for managing price feeds for different tokens.
/// @author KPK
interface IPrices {
/// @notice Enum representing the type of price feed.
enum PriceType {
Chainlink, // 0 — Chainlink AggregatorV3Interface (on-chain push)
Redstone, // 1 — Redstone Classic Push (AggregatorV3-compatible, same read path as Chainlink)
API3, // 2 — API3 dAPI via Api3ReaderProxyV1 (AggregatorV3-compatible, 18-dec proxy scaled to 8-dec at read)
Custom // 3 — custom ICustomPriceFeed adapter (internal staleness logic)
}
/// @notice Per-asset pricing metadata governing divergence detection between the primary feed and its
/// monitor feeds. Packs into a single storage slot (uint32 + uint32 = 8 bytes).
/// @param divergenceToleranceBps Max allowed basis-point gap between the primary price and the worst-case
/// (furthest) healthy monitor price before the asset is flagged `irregular`. Must be non-zero when monitors exist.
/// @param pegToleranceBps Absolute peg-deviation guard: max allowed basis-point deviation of the primary price
/// from $1 before the asset is flagged `irregular`. Non-zero enables the guard (set it only on assets whose
/// fundamental value is $1, i.e. stablecoins); zero disables it.
struct AssetPricing {
uint32 divergenceToleranceBps;
uint32 pegToleranceBps;
}
/// @notice Struct representing a price feed configuration.
/// @param priceFeed The address of the price feed contract (e.g. Chainlink aggregator or custom price feed).
/// @param decimals The number of decimal places the price feed uses.
/// @param priceType The type of the price feed.
/// @param chainlinkHeartbeat Staleness window in seconds (non-zero for all types). For Chainlink/Redstone/API3
/// feeds this gates participation: block.timestamp - effectiveUpdatedAt >= chainlinkHeartbeat → skip feed.
/// For Custom feeds the internal stale signal from getLatestPrice() is the primary gate; updatedAt from
/// latestRoundData() then applies the same heartbeat gate (updatedAt==0 is treated as block.timestamp-1
/// so rate-only feeds participate but yield to any feed with a real push timestamp), and among survivors
/// the largest effectiveUpdatedAt wins.
struct PriceFeedConfig {
address priceFeed;
uint8 decimals;
PriceType priceType;
uint256 chainlinkHeartbeat;
}
/// @notice Emitted when an already-registered price feed's staleness heartbeat is changed in place.
/// @param underlyingAsset The asset whose registration was updated.
/// @param priceFeed The registered feed the heartbeat applies to.
/// @param oldHeartbeat The previous heartbeat, in seconds.
/// @param newHeartbeat The new heartbeat, in seconds.
event PriceFeedHeartbeatUpdated(
address indexed underlyingAsset, address indexed priceFeed, uint256 oldHeartbeat, uint256 newHeartbeat
);
/// @notice A registered MONITOR feed's heartbeat changed in place.
/// @dev Mirrors {PriceFeedHeartbeatUpdated}. Emitted instead of a `MonitorFeedRemoved`/`MonitorFeedAdded`
/// pair, so alerting subscribed to that pair will not see monitor staleness-window changes.
/// @param underlyingAsset The asset whose monitor feed changed.
/// @param priceFeed The monitor feed whose staleness window moved.
/// @param oldHeartbeat The previous staleness window, in seconds.
/// @param newHeartbeat The new staleness window, in seconds.
event MonitorFeedHeartbeatUpdated(
address indexed underlyingAsset, address indexed priceFeed, uint256 oldHeartbeat, uint256 newHeartbeat
);
/// @notice Emitted when a price feed is added for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the price feed.
/// @param chainlinkHeartbeat The heartbeat interval in seconds.
/// @param priceType The type of the price feed.
/// @param index The index of the new feed in the asset's feed array.
event PriceFeedAdded(
address indexed underlyingAsset,
address indexed priceFeed,
uint256 chainlinkHeartbeat,
PriceType priceType,
uint256 index
);
/// @notice Emitted when a single price feed is removed for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the removed feed.
/// @param index The former index of the removed feed.
event PriceFeedRemoved(address indexed underlyingAsset, address indexed priceFeed, uint256 index);
/// @notice Emitted when swap-and-pop relocates the last feed into a vacated slot.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the feed that was moved.
/// @param fromIndex The former index (len-1 before the pop).
/// @param toIndex The new index (the slot vacated by the removed feed).
event PriceFeedIndexChanged(
address indexed underlyingAsset, address indexed priceFeed, uint256 fromIndex, uint256 toIndex
);
/// @notice Emitted when all price feeds are cleared for a token (asset unregistration).
/// @param underlyingAsset The address of the token.
event PriceFeedUnset(address indexed underlyingAsset);
/// @notice Emitted when a monitor (divergence-only) feed is added for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the monitor feed.
/// @param chainlinkHeartbeat The heartbeat interval in seconds.
/// @param priceType The type of the monitor feed.
/// @param index The index of the new monitor feed in the asset's monitor array.
event MonitorFeedAdded(
address indexed underlyingAsset,
address indexed priceFeed,
uint256 chainlinkHeartbeat,
PriceType priceType,
uint256 index
);
/// @notice Emitted when a monitor feed is removed for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the removed monitor feed.
/// @param index The former index of the removed monitor feed.
event MonitorFeedRemoved(address indexed underlyingAsset, address indexed priceFeed, uint256 index);
/// @notice Emitted when swap-and-pop relocates the last monitor feed into a vacated slot.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the monitor feed that was moved.
/// @param fromIndex The former index (len-1 before the pop).
/// @param toIndex The new index (the slot vacated by the removed monitor feed).
event MonitorFeedIndexChanged(
address indexed underlyingAsset, address indexed priceFeed, uint256 fromIndex, uint256 toIndex
);
/// @notice Emitted when all monitor feeds and pricing metadata are cleared for a token (asset unregistration).
/// @param underlyingAsset The address of the token.
event MonitorFeedsUnset(address indexed underlyingAsset);
/// @notice Emitted when an asset's divergence tolerance is set.
/// @param underlyingAsset The address of the token.
/// @param divergenceToleranceBps The new tolerance in basis points.
event DivergenceToleranceSet(address indexed underlyingAsset, uint32 divergenceToleranceBps);
/// @notice Emitted when an asset's peg tolerance is set (stablecoins).
/// @param underlyingAsset The address of the token.
/// @param pegToleranceBps The new peg tolerance in basis points.
event PegToleranceSet(address indexed underlyingAsset, uint32 pegToleranceBps);
//
// Errors
//
/// @notice Error when the price feed is not set for an asset
/// @param asset The address of the asset
error PriceFeedNotSet(address asset);
/// @notice Error when the price feed is invalid
error InvalidPriceOracle();
/// @notice Error when the price feed type is not valid
error InvalidPriceOracleType();
/// @notice Error when attempting to remove the last remaining feed for an asset
error CannotRemoveLastFeed(address asset);
/// @notice Error when attempting to add a feed that is already registered for an asset
error PriceFeedAlreadyRegistered(address asset, address feed);
/// @notice The upsert path was given a `priceType` differing from the one the feed is registered with.
/// @dev A feed's type is part of its IDENTITY, not its configuration — it selects the read path and the
/// decimals convention. Changing it means removing and re-adding the feed. Rejected rather than
/// ignored because `_validateFeedSupportInternal` puts Chainlink, Redstone and API3 in ONE branch, so a
/// mismatch inside that group passes validation and the caller would otherwise be told a request
/// succeeded that was never applied.
error PriceFeedTypeImmutable(address asset, address feed);
/// @notice Error when the feed index is out of bounds
error PriceFeedIndexOutOfBounds(address asset, uint256 index);
/// @notice Error when a feed address is not found in an asset's feed list
error PriceFeedNotFound(address asset, address feed);
/// @notice Error when a new feed's decimals do not match the decimals of existing feeds for the asset
error PriceFeedDecimalsMismatch(address asset, uint8 existingDecimals, uint8 newDecimals);
/// @notice Error when a monitor feed's decimals are not NAV_DECIMALS (monitors must be USD-comparable to the
/// primary, which is always NAV_DECIMALS).
error MonitorFeedDecimalsMismatch(address asset, uint8 expectedDecimals, uint8 actualDecimals);
/// @notice Error when a `Custom` feed is being registered for an asset it does not price — i.e. the feed's own
/// {ICustomPriceFeed-underlyingAssetSupported} does not equal the asset being registered.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
/// @param feedAsset The asset the feed actually prices, per its own `underlyingAssetSupported()`.
error CustomFeedAssetMismatch(address asset, address feed, address feedAsset);
/// @notice Error when a `Custom` feed is being registered for the very asset it reads its own `base/USD` price
/// for — i.e. the feed's {INavSourcedPriceFeed-BASE_ASSET} equals the asset being registered.
/// @dev A NAV-sourced custom feed prices its asset as `rate × base/USD` and reads that `base/USD` back out of
/// THIS NAV (`NavBaseUsdLib` → `getPriceData(BASE_ASSET)`; ADR 0019). If the base IS the asset, pricing the asset
/// re-enters the same feed and recurses until the call stack is exhausted. The read still returns a price — the
/// selector's per-feed `try`/`catch` swallows the depth failure and moves on — so the only symptom is that every
/// read of that asset, and of everything priced from it, burns gas proportional to ~1024 nested `STATICCALL`
/// frames. See the circularity invariant in {NavBaseUsdLib}.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
error CustomFeedBaseCircular(address asset, address feed);
/// @notice Error when a `Custom` feed does not answer {INavSourcedPriceFeed-BASE_ASSET}, so its NAV dependency
/// cannot be established at registration.
/// @dev Unreadable means REJECT, deliberately. The failure being closed is unbounded recursion, so "the base
/// could not be read" must not be allowed to mean "the base is fine". A feed with no NAV dependency states that
/// by answering `address(0)`; a feed that cannot answer at all is one whose base cannot be ruled out.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
error CustomFeedBaseUnreadable(address asset, address feed);
/// @notice Error when a monitor feed is already registered for an asset.
error MonitorFeedAlreadyRegistered(address asset, address feed);
/// @notice Error when a monitor feed address is not found in an asset's monitor list.
error MonitorFeedNotFound(address asset, address feed);
/// @notice Error when adding a monitor feed before the asset's divergence tolerance has been set (>0).
error DivergenceToleranceRequired(address asset);
/// @notice Error when a tolerance value is out of range. Divergence tolerance must be in (0, 10000];
/// peg tolerance must be in [0, 10000] (0 is allowed and disables the peg guard).
error InvalidTolerance(uint32 toleranceBps);
/// @notice Returns the latest price for a given token while checking if the price is stale.
/// @dev Reverts PriceFeedNotSet if the asset has no registered feeds. When at least one feed is registered
/// but all are stale, returns price 0 with stale = true rather than reverting.
/// @param underlyingAsset The address of the token.
/// @return price The latest price of the token (int256; positive for all valid prices, 0 when stale).
/// @return decimals The amount of decimal places the price is represented with.
/// @return stale True if all registered feeds are stale, the L2 sequencer is down, or within grace period.
/// @return irregular True if the primary price diverged from its monitor feeds beyond the divergence tolerance,
/// or (stablecoins) from the $1 peg beyond the peg tolerance. A pricing-quality signal, not a validity flag;
/// `price` is still populated. Always false when `stale` (divergence is undefined for an unusable price).
function latestPrice(address underlyingAsset)
external
view
returns (int256 price, uint8 decimals, bool stale, bool irregular);
/// @notice Checks the L2 sequencer uptime feed, returning True when it is signaling staleness (the sequencer
/// is down or still within the grace period). If 'chainlinkL2SequencerUptimeFeed' is the zero address (e.g. on
/// an L1) it returns false.
/// @return stale True if the L2 sequencer is down or if it is within the grace period.
function checkL2SequencerUptime() external view returns (bool stale);
/// @notice Validates that a price feed is suitable for the given type, reverting if it is not. Returns nothing
/// on success. Reverts InvalidPriceOracle when the asset or feed address is zero, the feed fails the
/// ICustomPriceFeed/AggregatorV3 interface check for its type, or (for Chainlink/Redstone/API3) its
/// latestRoundData reports a non-positive answer, a zero updatedAt, or a future timestamp; reverts
/// InvalidPriceOracleType for an unsupported price type. For `Custom` feeds it additionally reverts
/// CustomFeedAssetMismatch when the feed's own `underlyingAssetSupported()` is not `underlyingAsset` — a custom
/// feed prices exactly one asset and must be registered for that asset — plus CustomFeedBaseUnreadable when the
/// feed does not answer {INavSourcedPriceFeed-BASE_ASSET}, and CustomFeedBaseCircular when that base IS
/// `underlyingAsset` (which would make pricing the asset re-enter the same feed).
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the price feed.
/// @param priceType The type of the price feed.
function checkPriceOracleSupport(address underlyingAsset, address priceFeed, PriceType priceType) external view;
/// @notice Returns all price feed configurations for an asset.
/// @param asset The address of the asset.
/// @return configs Array of PriceFeedConfig (empty if no feeds registered).
function getPriceFeeds(address asset) external view returns (PriceFeedConfig[] memory configs);
/// @notice Returns the number of registered price feeds for an asset.
/// @param asset The address of the asset.
/// @return count Number of feeds.
function getPriceFeedCount(address asset) external view returns (uint256 count);
/// @notice Returns the price feed configuration at a specific index.
/// @param asset The address of the asset.
/// @param index Index into the feed array (reverts with PriceFeedIndexOutOfBounds if out of range).
/// @return config The PriceFeedConfig at that index.
function getPriceFeedAt(address asset, uint256 index) external view returns (PriceFeedConfig memory config);
/// @notice Returns all monitor (divergence-only) feed configurations for an asset.
/// @param asset The address of the asset.
/// @return configs Array of monitor PriceFeedConfig (empty if none registered).
function getMonitorFeeds(address asset) external view returns (PriceFeedConfig[] memory configs);
/// @notice Returns the number of registered monitor feeds for an asset.
/// @param asset The address of the asset.
/// @return count Number of monitor feeds.
function getMonitorFeedCount(address asset) external view returns (uint256 count);
/// @notice Returns the per-asset pricing metadata (divergence/peg tolerances).
/// @param asset The address of the asset.
/// @return pricing The AssetPricing struct (zero-valued if never set: tolerances 0).
function getAssetPricing(address asset) external view returns (AssetPricing memory pricing);
}
src/utils/AddressCheckLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {NotAContract} from "src/errors.sol";
/// @title AddressCheckLib
/// @author KPK
/// @notice Constructor-argument helper for the balance-adapter layer: asserts a dependency address actually points
/// to a deployed contract, reverting with the {NotAContract} custom error carrying the dependency label.
/// @dev Centralises the `addr.code.length > 0` dependency check that every adapter pins its immutables with. The
/// price-feed layer has its own equivalent (`OracleArgumentChecks`); this is the balance-side analogue. `name`
/// is the dependency's human label (e.g. "NAVCalculator"), surfaced in the {NotAContract} error.
library AddressCheckLib {
/// @notice Reverts {NotAContract}(`name`) unless `addr` has non-empty code.
/// @param addr The dependency address to validate.
/// @param name The dependency's display name (carried in the revert).
function requireContract(address addr, string memory name) internal view {
if (addr.code.length == 0) revert NotAContract(name);
}
}
src/utils/GasStipendLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title GasStipendLib
/// @author KPK
/// @notice The single definition of "did this call run out of gas, or did it answer?" — the stipend a fan-out
/// forwards to one child, and the test that separates an out-of-gas from a revert afterwards.
/// @dev Exists because that question is asked in two places, one frame apart, and the two must give the same
/// answer: `PriceFeedLib._getAdapterPositions` asks it of a balance adapter, and `MetaBalanceAdapter`
/// asks it of one governed instance. Both sit on a `try`/`catch` that cannot tell the two failures apart on
/// its own, and getting it wrong in the lenient direction drops a position's legs — a dropped *debt* leg
/// RAISES the reported NAV. Two copies of a threshold is how the two paths drift apart, so there is one.
///
/// **Why a threshold at all, rather than "consumed == forwarded".** A starved callee never quite spends
/// everything it was given. Gas runs out inside whatever the callee is itself reading, not in the callee's
/// own frame: that sub-call takes 63/64 under EIP-150, out-of-gasses, and the callee's own reserve comes
/// back unspent when it bubbles the revert. One level of nesting consumes ~63/64 of the stipend, two
/// ~0.969, three ~0.954 — each level leaves another reserve behind. An exact test sees the shortfall and
/// calls a starved callee healthy, which is the silent failure; and no fixed fraction is exact either, so
/// {SLACK_DIVISOR} narrows the silent window rather than closing it.
///
/// Being wrong the other way is cheap: a busy callee that reverts after real work gets read as exhausted
/// and produces a loud, retryable failure instead of a wrong number.
///
/// **What this cannot see at all.** The question is only asked when the callee BUBBLES its out-of-gas. A
/// callee that wraps its own read in `try`/`catch` — or in a fail-open low-level staticcall — absorbs the
/// out-of-gas itself, carries on with the ~1/64 the EVM handed back, and RETURNS SUCCESSFULLY with a leg
/// missing. No classifier upstream is reached, because nothing failed from where it is standing. That
/// residual is a property of each adapter's internal error handling, not of this threshold, and it is why
/// "narrows the silent window" is the accurate claim rather than "closes it".
library GasStipendLib {
/// @notice Fraction of the stipend a failed call may leave unspent and still count as exhausted: `1/8`.
/// @dev Covers nesting far past anything in this repo. Raising it (a smaller divisor) widens the window in
/// which a genuinely reverting callee is called exhausted — loud but wrong; lowering it re-opens the
/// silent window. The tests bracket it from both sides deliberately.
uint256 private constant SLACK_DIVISOR = 8;
/// @notice Gas to forward to one child of a fan-out, given what the calling frame currently holds.
/// @dev Exactly what the EVM would forward on its own (63/64), computed explicitly so {exhausted} has a
/// figure to compare against rather than an implied one. Deliberately NOT a smaller fixed ceiling: a
/// ceiling makes exhaustion unrecoverable — the caller cannot escape it by supplying more gas — which
/// turns ordinary growth in a child's cost, and cheap third-party griefing of a per-account list, into
/// an outage that only a redeploy can lift.
/// @param available `gasleft()` in the calling frame, read BEFORE this call.
/// @return The stipend to pass as `{gas: …}`.
function stipendFrom(uint256 available) internal pure returns (uint256) {
return available - available / 64;
}
/// @notice Whether a failed call that was forwarded `stipend` and cost the caller `consumed` ran out of gas
/// rather than reverting with an answer.
/// @dev `consumed` must be measured against the SAME `available` that produced `stipend` via {stipendFrom}.
/// That single-sample discipline is what fixes the sign of the slack: the caller-side overhead the
/// callee never spends lands on the `consumed` side, so a genuine out-of-gas always clears the
/// threshold. Re-sampling nearer the call inverts it and a real exhaustion reads as a benign revert.
/// @param stipend The value returned by {stipendFrom} and passed as `{gas: …}`.
/// @param consumed `available - gasleft()`, measured after the call returned.
function exhausted(uint256 stipend, uint256 consumed) internal pure returns (bool) {
return consumed >= stipend - stipend / SLACK_DIVISOR;
}
}
src/utils/PositionKind.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @notice Semantic discriminator for a PositionBalance entry.
/// @dev Used by NAVCalculator consumers to branch on action family without string parsing.
/// `isDebt` on the enclosing PositionBalance is the canonical NAV-sign signal;
/// `PositionKind` provides human-readable category context on top of that.
/// Assignment rule: the kind reflects the OUTERMOST action family — what the account does to
/// enter/exit the position. A position exited via unstake is `Staking` regardless of what is
/// wrapped inside (e.g. gauge-staked LP); the inner exposure stays recoverable from
/// `protocolSubId`/`positionId`. LP principal sitting unstaked in the wallet is `Supplied`.
/// @author KPK
enum PositionKind {
Wallet, // plain ERC20 / native-token balance held directly (ERC20DefaultBalanceAdapter)
Supplied, // credit deployed into a protocol: lending supply, vault shares, unstaked LP principal
Borrowed, // debt owed to a protocol (isDebt = true)
Collateral, // credit locked as collateral (e.g. Aave reserve with usageAsCollateralEnabled = true)
Staking, // staking principal: tokens locked behind an unstake action (Safety Module, Umbrella, StakeWise vaults, gauge/Convex-staked LP)
Rewards, // accrued but not yet claimed reward tokens (e.g. CRV, CVX, BAL, COMP)
Fees // uncollected protocol or LP fees (e.g. Uniswap V3 position fees)
}
src/utils/ProtocolIds.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @notice Canonical protocol-taxonomy constants — `protocolBrand`, `protocolId`, and `protocolSubId`
/// — for every balance adapter family.
/// @dev Each constant is `keccak256` of a lowercase-ASCII, kebab-case slug; the protocol version is
/// baked into the slug only where the protocol is a distinct versioned system (e.g. `aave-v3`,
/// `balancer-v2`/`-v3`), so unversioned protocols carry no version. A single `protocolSubId`
/// maps to exactly one `positionId` ABI-decode schema — narrow enough that the client knows how
/// to decode without runtime sniffing.
///
/// positionId schemas (all are `abi.encode(...)`):
/// WALLET → (address asset)
/// AAVE_V3_LENDING / SPARK_LEND → (address pool) — one position per instance; reserve in balanceAsset
/// AAVE_V4_LENDING → (address spoke) — one position per Spoke; reserve in balanceAsset
/// AAVE_V3_SAFETY_MODULE / UMBRELLA→ (address stakeToken) for BOTH staking legs (no discriminator);
/// isLocked=non-withdrawable splits them — active stake is LOCKED
/// (isLocked=true), only a cooldown elapsed-and-in-window is UNLOCKED;
/// the reward leg shares it too, told apart by positionKind=Rewards
/// YO_VAULTS → (address vault) — static; up to two Supplied legs sharing it: held shares
/// (isLocked=false) + pending escrowed redeem (isLocked=true)
/// MORPHO_VAULTS / GEARBOX_V3_MARKETS / GEARBOX_V3_CREDIT_ACCOUNTS / EULER_VAULTS / ERC4626 /
/// STAKEWISE_V3_VAULTS / FLUID_VAULTS / SYMBIOTIC_VAULTS → (address vault / market / credit account)
/// CAP → (address token: cUSD or stcUSD) — one leg per token
/// MORPHO_MARKETS → (bytes32 marketId)
/// BALANCER_V3_POOLS → (address pool)
/// BALANCER_V3_GAUGES / V2_GAUGES → (address gauge)
/// CONVEX_CURVE_LP_STAKING → (address rewarder)
/// CURVE_POOLS → (address pool)
/// POLYGON_STAKING → (address validatorShare) — ONE positionId, two legs
/// (Staking principal + Rewards) told apart by positionKind
/// CURVE_GAUGES → (address gauge)
/// BALANCER_V2_POOLS → (bytes32 poolId)
/// UNISWAP_V3 / PANCAKESWAP_V3 → (address pool); NFT tokenId in positionInstanceId (bytes32(tokenId))
/// UNISWAP_V2 / PANCAKESWAP_V2 → (address pair)
/// COMPOUND_V3_COMETS / FLUID_FTOKENS → (address comet / fToken)
/// MERKL → (address distributor) — reward token is in balanceAsset, not positionId
/// NEXUS_MUTUAL_STAKING_POOLS → (address stakingPool); StakingNFT tokenId in positionInstanceId
/// STADER_WITHDRAWAL → (address userWithdrawalManager) — static coordinate
/// KELP_WITHDRAWAL → (address withdrawalManager) — static coordinate; payout asset in balanceAsset
/// LIDO_WITHDRAWAL → (address withdrawalQueue) — static coordinate
/// ETHENA_COOLDOWN → (address sUSDe) — static coordinate
/// ETHERFI_WITHDRAWAL → (address withdrawRequestNFT) — static coordinate
/// LIDO_STAKED_ETH → (address token: wstETH | stETH) — wallet-held, one leg per token
/// ETHERFI_STAKED_ETH → (address token: eETH | weETH)
/// ROCKET_POOL_STAKED_ETH → (address token: rETH)
/// RENZO_RESTAKED_ETH → (address token: ezETH)
/// KELP_RESTAKED_ETH → (address token: rsETH)
/// STADER_STAKED_ETH → (address token: ETHx)
/// STAKEWISE_V3_OS_TOKENS → (address token: osETH | osGNO)
/// LIQUID_COLLECTIVE_STAKED_ETH → (address token: lsETH)
/// ANKR_STAKED_ETH → (address token: ankrETH)
/// COINBASE_STAKED_ETH → (address token: cbETH)
/// RESERVE_BASKETS → (address token: ETH+)
/// ETHENA_SAVINGS → (address token: sUSDe)
/// SKY_SAVINGS → (address token: sDAI | sUSDS)
/// AAVE_V3_SAVINGS → (address token: sGHO)
/// SPARK_SAVINGS → (address token: spUSDC | spUSDT | spETH)
/// MAPLE_SAVINGS → (address token: syrupUSDC)
/// NEXUS_MUTUAL_VAULTS → (address token: RWIV)
/// STAKEWISE_V3_EXIT → (address vault) — static, per vault
/// (for these: a static positionId with up to two legs — claimable (isLocked=false) + locked
/// (isLocked=true) — sharing it, told apart by isLocked; owed asset is in balanceAsset. isLocked
/// is part of the identity key. See docs/decisions/0016-islocked-position-status.md.)
/// BRIDGE_ESCROW → (address escrow, address token)
/// @author KPK
library ProtocolIds {
bytes32 internal constant WALLET = keccak256("wallet");
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
// Brand ids — the broadest `PositionBalance.protocolBrand` layer (the protocol brand, version-stripped). Several
// ecosystem ids roll up to one brand: AAVE_V3 + AAVE_V4 → AAVE; BALANCER_V2 + BALANCER_V3 → BALANCER; UNISWAP_V2 +
// UNISWAP_V3 → UNISWAP; etc. For unversioned protocols the brand equals the ecosystem id (CURVE, MORPHO, FLUID,
// EULER, LIDO, KELP, …) — those reuse the same constant; only the versioned brands need a dedicated constant here.
// Display/grouping only; NOT part of the stable identity key (that uses `protocolSubId`).
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
bytes32 internal constant AAVE = keccak256("aave");
bytes32 internal constant BALANCER = keccak256("balancer");
bytes32 internal constant UNISWAP = keccak256("uniswap");
bytes32 internal constant PANCAKESWAP = keccak256("pancakeswap");
bytes32 internal constant GEARBOX = keccak256("gearbox");
bytes32 internal constant STAKEWISE = keccak256("stakewise");
bytes32 internal constant COMPOUND = keccak256("compound");
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
// Ecosystem ids — the broad `PositionBalance.protocolId` (grouping / roll-up layer). Several per-product slugs
// below (the `protocolSubId`s) roll up to one of these, e.g. AAVE_V3_LENDING + AAVE_V3_SAFETY_MODULE + AAVE_V3_UMBRELLA
// → AAVE_V3. For single-product ecosystems the adapter uses the SAME constant for both protocolId and protocolSubId
// (e.g. UNISWAP_V3, CAP, MERKL, WALLET, ERC4626) — no separate ecosystem constant needed. (CONVEX and CURVE keep
// distinct per-product subIds — CONVEX_CURVE_LP_STAKING, CURVE_POOLS/CURVE_GAUGES — so for them protocolId differs
// from protocolSubId even though they roll up to the CONVEX/CURVE ecosystem id.)
// The version is kept in the ecosystem id where the protocol is a distinct system (aave-v3, balancer-v2/-v3,
// uniswap-v2/-v3), so different versions are different `protocolId`s. NOT part of the stable identity key — that
// uses `protocolSubId`. See INAVCalculator.PositionBalance.
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
bytes32 internal constant AAVE_V3 = keccak256("aave-v3");
bytes32 internal constant AAVE_V4 = keccak256("aave-v4");
bytes32 internal constant GEARBOX_V3 = keccak256("gearbox-v3");
bytes32 internal constant STAKEWISE_V3 = keccak256("stakewise-v3");
bytes32 internal constant MORPHO = keccak256("morpho");
bytes32 internal constant BALANCER_V2 = keccak256("balancer-v2");
bytes32 internal constant BALANCER_V3 = keccak256("balancer-v3");
bytes32 internal constant FLUID = keccak256("fluid");
bytes32 internal constant EULER = keccak256("euler");
bytes32 internal constant SYMBIOTIC = keccak256("symbiotic");
bytes32 internal constant LIDO = keccak256("lido");
bytes32 internal constant POLYGON = keccak256("polygon"); // Polygon ecosystem id; unversioned, so this is also the brand
bytes32 internal constant KELP = keccak256("kelp");
bytes32 internal constant STADER = keccak256("stader");
bytes32 internal constant ETHERFI = keccak256("etherfi");
bytes32 internal constant ETHENA = keccak256("ethena");
bytes32 internal constant SPARK = keccak256("spark");
bytes32 internal constant ROCKET_POOL = keccak256("rocket-pool");
bytes32 internal constant RENZO = keccak256("renzo");
bytes32 internal constant LIQUID_COLLECTIVE = keccak256("liquid-collective");
bytes32 internal constant ANKR = keccak256("ankr");
bytes32 internal constant COINBASE = keccak256("coinbase");
bytes32 internal constant RESERVE = keccak256("reserve");
bytes32 internal constant SKY = keccak256("sky");
bytes32 internal constant MAPLE = keccak256("maple");
bytes32 internal constant NEXUS_MUTUAL = keccak256("nexus-mutual");
bytes32 internal constant YO = keccak256("yo"); // YO Protocol; unversioned, so this is also the brand
// (CURVE below doubles as the Curve ecosystem id for CURVE_POOLS/CURVE_GAUGES.)
// ── Per-product slugs (`protocolSubId`; selects the positionId decode schema) ──
// Aave family
bytes32 internal constant AAVE_V3_LENDING = keccak256("aave-v3-lending");
bytes32 internal constant AAVE_V3_SAFETY_MODULE = keccak256("aave-v3-safety-module");
bytes32 internal constant AAVE_V3_UMBRELLA = keccak256("aave-v3-umbrella");
bytes32 internal constant AAVE_V4_LENDING = keccak256("aave-v4-lending");
// Morpho
bytes32 internal constant MORPHO_VAULTS = keccak256("morpho-vaults");
bytes32 internal constant MORPHO_MARKETS = keccak256("morpho-markets");
// Balancer
bytes32 internal constant BALANCER_V3_POOLS = keccak256("balancer-v3-pools");
bytes32 internal constant BALANCER_V3_GAUGES = keccak256("balancer-v3-gauges");
bytes32 internal constant BALANCER_V2_POOLS = keccak256("balancer-v2-pools");
bytes32 internal constant BALANCER_V2_GAUGES = keccak256("balancer-v2-gauges");
// Uniswap / PancakeSwap
bytes32 internal constant UNISWAP_V3 = keccak256("uniswap-v3");
bytes32 internal constant UNISWAP_V2 = keccak256("uniswap-v2");
bytes32 internal constant PANCAKESWAP_V3 = keccak256("pancakeswap-v3");
bytes32 internal constant PANCAKESWAP_V2 = keccak256("pancakeswap-v2");
// StakeWise
bytes32 internal constant STAKEWISE_V3_VAULTS = keccak256("stakewise-v3-vaults");
// Polygon PoS staking (Ethereum L1 StakeManager / ValidatorShare)
bytes32 internal constant POLYGON_STAKING = keccak256("polygon-staking"); // delegation → (address validatorShare)
// Nexus Mutual
bytes32 internal constant NEXUS_MUTUAL_STAKING_POOLS = keccak256("nexus-mutual-staking-pools");
// Gearbox
bytes32 internal constant GEARBOX_V3_MARKETS = keccak256("gearbox-v3-markets");
bytes32 internal constant GEARBOX_V3_CREDIT_ACCOUNTS = keccak256("gearbox-v3-credit-accounts");
// Euler
bytes32 internal constant EULER_VAULTS = keccak256("euler-vaults");
// Symbiotic
bytes32 internal constant SYMBIOTIC_VAULTS = keccak256("symbiotic-vaults");
// YO (YoVault: held shares + pending escrowed redeems)
bytes32 internal constant YO_VAULTS = keccak256("yo-vaults");
// Compound
bytes32 internal constant COMPOUND_V3 = keccak256("compound-v3");
bytes32 internal constant COMPOUND_V3_COMETS = keccak256("compound-v3-comets");
// Fluid
bytes32 internal constant FLUID_FTOKENS = keccak256("fluid-ftokens");
bytes32 internal constant FLUID_VAULTS = keccak256("fluid-vaults");
// Spark
bytes32 internal constant SPARK_LEND = keccak256("spark-lend");
// Curve / Convex
bytes32 internal constant CURVE = keccak256("curve"); // Curve ecosystem id (protocolId for CURVE_POOLS/CURVE_GAUGES)
bytes32 internal constant CURVE_POOLS = keccak256("curve-pools"); // wallet LP → (address pool)
bytes32 internal constant CURVE_GAUGES = keccak256("curve-gauges"); // gauge-staked LP → (address gauge)
bytes32 internal constant CONVEX = keccak256("convex");
bytes32 internal constant CONVEX_CURVE_LP_STAKING = keccak256("convex-curve-lp-staking");
// Cap
bytes32 internal constant CAP = keccak256("cap");
// Generic ERC4626 wrapper
bytes32 internal constant ERC4626 = keccak256("erc4626");
// Withdrawal / cooldown queues
// positionId = `abi.encode(<anchor contract>)` (the queue/manager — Lido queue, Stader/Kelp
// manager, ether.fi NFT, StakeWise vault, sUSDe). Up to two legs share it, told apart by
// isLocked (the owed/payout asset is in balanceAsset, not the positionId).
bytes32 internal constant STADER_WITHDRAWAL = keccak256("stader-withdrawal");
bytes32 internal constant KELP_WITHDRAWAL = keccak256("kelp-withdrawal");
bytes32 internal constant LIDO_WITHDRAWAL = keccak256("lido-withdrawal");
bytes32 internal constant ETHENA_COOLDOWN = keccak256("ethena-cooldown");
bytes32 internal constant ETHERFI_WITHDRAWAL = keccak256("etherfi-withdrawal");
// Wallet-held yield-bearing tokens (WalletTokenMetaBalanceAdapterBase family). The token is itself the
// registered, priced NAV asset, so every positionId here is `abi.encode(address token)` and the
// balanceAsset is that same token. One subId per PROTOCOL, not per token: several tokens share a subId
// (wstETH + stETH under Lido) because they are the same product, and the positionId separates them.
bytes32 internal constant LIDO_STAKED_ETH = keccak256("lido-staked-eth");
bytes32 internal constant ETHERFI_STAKED_ETH = keccak256("etherfi-staked-eth");
bytes32 internal constant ROCKET_POOL_STAKED_ETH = keccak256("rocket-pool-staked-eth");
bytes32 internal constant RENZO_RESTAKED_ETH = keccak256("renzo-restaked-eth");
bytes32 internal constant KELP_RESTAKED_ETH = keccak256("kelp-restaked-eth");
bytes32 internal constant STADER_STAKED_ETH = keccak256("stader-staked-eth");
bytes32 internal constant STAKEWISE_V3_OS_TOKENS = keccak256("stakewise-v3-os-tokens");
bytes32 internal constant LIQUID_COLLECTIVE_STAKED_ETH = keccak256("liquid-collective-staked-eth");
bytes32 internal constant ANKR_STAKED_ETH = keccak256("ankr-staked-eth");
bytes32 internal constant COINBASE_STAKED_ETH = keccak256("coinbase-staked-eth");
bytes32 internal constant RESERVE_BASKETS = keccak256("reserve-baskets");
bytes32 internal constant ETHENA_SAVINGS = keccak256("ethena-savings");
bytes32 internal constant SKY_SAVINGS = keccak256("sky-savings");
bytes32 internal constant AAVE_V3_SAVINGS = keccak256("aave-v3-savings");
bytes32 internal constant SPARK_SAVINGS = keccak256("spark-savings");
bytes32 internal constant MAPLE_SAVINGS = keccak256("maple-savings");
bytes32 internal constant NEXUS_MUTUAL_VAULTS = keccak256("nexus-mutual-vaults");
bytes32 internal constant STAKEWISE_V3_EXIT = keccak256("stakewise-v3-exit");
// Merkl rewards distributor
bytes32 internal constant MERKL = keccak256("merkl");
// Bridge escrow
bytes32 internal constant BRIDGE_ESCROW = keccak256("bridge-escrow");
}
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.AAVE_V4` — a distinct protocol id from V3, hence a distinct name: V4 is a separate
/// deployment with its own Spokes, so a consumer grouping by display name must not merge the two.
string internal constant AAVE_V4 = "Aave V4";
/// @dev `ProtocolIds.SPARK`.
string internal constant SPARK = "Spark";
string internal constant ROCKET_POOL = "Rocket Pool";
string internal constant RENZO = "Renzo";
string internal constant LIQUID_COLLECTIVE = "Liquid Collective";
string internal constant ANKR = "Ankr";
string internal constant COINBASE = "Coinbase";
string internal constant RESERVE = "Reserve";
string internal constant SKY = "Sky";
string internal constant MAPLE = "Maple";
/// @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";
/// @dev `ProtocolIds.YO` — the YO vaults meta-adapter (`YoVaultsMetaBalanceAdapter`).
string internal constant YO = "YO";
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
// 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.AAVE_V4) return AAVE_V4;
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.YO) return YO;
// Wallet-held yield-bearing token protocols. A MISSING branch here is not cosmetic: `forProtocolId`
// reverts UnknownProtocolId, so a new adapter whose PROTOCOL ID is absent would have no display name.
// Keyed on protocolId, not protocolBrand — the two differ for adapters like StakeWise V3 and Aave V3.
if (protocolId == ProtocolIds.ROCKET_POOL) return ROCKET_POOL;
if (protocolId == ProtocolIds.RENZO) return RENZO;
if (protocolId == ProtocolIds.LIQUID_COLLECTIVE) return LIQUID_COLLECTIVE;
if (protocolId == ProtocolIds.ANKR) return ANKR;
if (protocolId == ProtocolIds.COINBASE) return COINBASE;
if (protocolId == ProtocolIds.RESERVE) return RESERVE;
if (protocolId == ProtocolIds.SKY) return SKY;
if (protocolId == ProtocolIds.MAPLE) return MAPLE;
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": "0x3D5369B0b2044d62a8f643bf9a2b8CC03775934D"
},
"src/prices/PriceFeedLib.sol": {
"PriceFeedLib": "0x0f913658d70BB19b7B42eF9926c3df7c70fafCf2"
}
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@chainlink/=lib/chainlink-brownie-contracts/contracts/",
"chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"morpho-blue/=lib/morpho-blue/",
"ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.