Verified contractPartialBUSL-1.1
NexusMutualStakingPoolsAssistedBalanceAdapter
Address0x535861d4f3ae8ec84d0aed11134ff5f992b47f8d
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,341,849
- Creation transaction
- 0x1daadcaa7c…416c551046
- Libraries
- src/nav/NAVRegistryLib.sol:NAVRegistryLib0x3d53…75934dsrc/prices/PriceFeedLib.sol:PriceFeedLib0x0f91…fafcf2
27 files
- src/balances/AssistedBalanceAdapters/NexusMutualStakingPoolsAssistedBalanceAdapter.solmain17.41 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/AccessControl.sol7.02 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol3.34 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Bytes.sol14.84 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Context.sol963 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Strings.sol19.88 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol879 B
- 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
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol2.61 KB
- src/balances/AssistedBalanceAdapters/AssistedCoordCache.sol27.69 KB
- src/balances/IAssistedBalanceAdapter.sol7.47 KB
- src/balances/IBalanceAdapter.sol2.43 KB
- src/balances/IBalances.sol5.02 KB
- src/balances/IPositionDescribable.sol5.07 KB
- src/balances/RegisteredAssetLib.sol1.95 KB
- src/constants.sol1.05 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.48 KB
- src/utils/StaticCallLib.sol16.94 KB
src/balances/AssistedBalanceAdapters/NexusMutualStakingPoolsAssistedBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {AssistedCoordCache} from "./AssistedCoordCache.sol";
import {IPositionDescribable} from "src/balances/IPositionDescribable.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {AddressCheckLib} from "src/utils/AddressCheckLib.sol";
import {StaticCallLib} from "src/utils/StaticCallLib.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
import {ProtocolIds} from "src/utils/ProtocolIds.sol";
/// @title Nexus Mutual Staking Pools Assisted Balance Adapter (id-cached, assistant-fed)
/// @author KPK
/// @notice Reports an account's staked NXM across Nexus Mutual V2 staking pools, as NXM-denominated `Staking`
/// (active + expired stake) and `Rewards` legs — emitted **per StakingNFT position**. The StakingNFT is not
/// per-owner-enumerable, so a trusted feeder pushes/pops the account's `tokenId`s via {submit}/{remove}. The
/// canonical feeder is `NexusMutualStakingPoolsAssistant`, delegatecalled by the owner Safe so the adapter sees
/// `msg.sender = Safe = owner`. Each cached id is valued live (`StakingViewer.getTokens`), re-verifying
/// ownership via `StakingNFT.tokenInfo` every read; the cache stores **ids only, never amounts**.
/// @dev Member of the assistant-fed assisted family ([ADR 0018](../../../docs/decisions/0018-assistant-fed-assisted-balance-adapters.md)),
/// extending the single {AssistedCoordCache}: the coordinate is `abi.encode(tokenId)`. `StakingViewer.getTokens`
/// can revert, but {AssistedCoordCache} values each coordinate behind a self-`staticcall`, so a bad id is isolated.
/// positionId is the **staking-pool contract address** (`StakingViewer.stakingPool(poolId)`); the NFT id rides in
/// `positionInstanceId`. **{_removable} is value-based**: Nexus does NOT burn the StakingNFT on withdraw, so "no
/// longer owned" is not a liveness proxy — an id is removable only once it is no longer owned by the account OR is
/// fully emptied (no stake/rewards). A partial/rewards-only withdraw leaves a live position that stays tracked.
contract NexusMutualStakingPoolsAssistedBalanceAdapter is AssistedCoordCache, IPositionDescribable {
using Strings for uint256;
/// @notice Hard cap on cached tokenIds per account (read-loop gas bound). A real account never approaches it.
uint256 public constant MAX_TOKEN_IDS = 256;
bytes32 private constant PROTOCOL_BRAND = ProtocolIds.NEXUS_MUTUAL;
bytes32 private constant PROTOCOL_ID = ProtocolIds.NEXUS_MUTUAL;
bytes32 private constant PROTOCOL_SUB_ID = ProtocolIds.NEXUS_MUTUAL_STAKING_POOLS;
/// @notice Nexus Mutual StakingNFT (ERC-721; `tokenInfo(id) -> (poolId, owner)`).
address public immutable STAKING_NFT;
/// @notice Nexus Mutual StakingViewer — `getTokens(ids)` returns per-token stake + rewards in NXM.
address public immutable STAKING_VIEWER;
/// @param stakingNft_ Nexus StakingNFT. Must be a contract.
/// @param stakingViewer_ Nexus StakingViewer. Must be a contract.
/// @param underlyingToken_ NXM token address. Must be non-zero.
/// @param navCalculator_ NAVCalculator. Must be a contract.
/// @param admin_ `DEFAULT_ADMIN_ROLE` holder (grants the keeper's `SUBMITTER_ROLE`). Must be non-zero.
constructor(
address stakingNft_,
address stakingViewer_,
address underlyingToken_,
address navCalculator_,
address admin_
) AssistedCoordCache(underlyingToken_, navCalculator_, admin_) {
if (stakingNft_ == address(0) || stakingViewer_ == address(0)) {
revert InvalidArguments();
}
AddressCheckLib.requireContract(stakingNft_, "StakingNFT");
AddressCheckLib.requireContract(stakingViewer_, "StakingViewer");
STAKING_NFT = stakingNft_;
STAKING_VIEWER = stakingViewer_;
}
//
// Typed owner feed surface (msg.sender-keyed; the keeper path is in the base, ADR 0030)
//
/// @notice Track `tokenId` for the caller (idempotent). **Reverts** `CoordinateNotOwned` if not owned by the caller,
/// `CoordinateCacheFull` past {MAX_TOKEN_IDS}.
function submit(uint256 tokenId) external {
_submitCoord(abi.encode(tokenId));
}
/// @notice Stop tracking `tokenId` for the caller. **Reverts** `CoordinateNotCached` if not tracked, and
/// `CoordinateStillLive` if the position is still live (owned with active/expired stake or rewards) — a
/// still-live id is never silently dropped (see {_removable}).
function remove(uint256 tokenId) external {
_removeCoord(abi.encode(tokenId));
}
/// @notice Candidate tokenIds currently cached for `account` (display/debug; not ownership-filtered).
function tokenIdsOf(address account) external view returns (uint256[] memory ids) {
bytes[] memory coords = _cachedCoords(account);
ids = new uint256[](coords.length);
for (uint256 i; i < coords.length; ++i) {
ids[i] = abi.decode(coords[i], (uint256));
}
}
/// @inheritdoc IPositionDescribable
function protocolName() external pure returns (string memory) {
return "Nexus Mutual";
}
/// @inheritdoc IPositionDescribable
/// @dev `["Staking Pools", "Pool #<poolId>"]` — the numeric pool id read live via `getPoolId()`. Falls back to the
/// pool address when that read does not answer with a word. Empty for a malformed positionId.
///
/// **What the guards below do and do not promise.** They reject any positionId that is not exactly one clean
/// address word, so no foreign coordinate can be truncated or padded into a `Pool #` breadcrumb. They do NOT
/// establish that a rendered breadcrumb names a pool this adapter tracks: a CLEAN address that simply is not
/// a Nexus pool still renders `["Staking Pools", "0x…"]` through the hex fallback. That is unavoidable here —
/// Nexus pools are discovered per ACCOUNT from the cached NFT ids, so there is no account-independent set to
/// check a positionId against, and {IPositionDescribable} defines labels as a pure function of `positionId`.
/// The fallback is kept because it is the useful answer for the case it exists for: a real pool whose
/// `getPoolId()` read fails, where the address is what an operator needs. Callers that must know whether a
/// coordinate is actually tracked ask {tokenIdsOf}, not this view.
function positionLabels(bytes calldata positionId) external view override returns (string[] memory out) {
// Exactly one word. Every positionId this adapter emits is `abi.encode(poolAddress)`; a shorter buffer would
// revert inside `abi.decode`, and a LONGER one would decode its first word and label a multi-word coordinate
// belonging to some other adapter as a Nexus pool. Both are foreign, so both take the same `[]` exit.
if (positionId.length != 32) return new string[](0);
// Decode as a raw word, not `abi.decode(positionId, (address))`: Solidity's decoder REVERTS on an address
// whose upper 96 bits are dirty, which would turn a foreign positionId into a revert of a view that must
// never revert. A dirty word takes the same `[]` exit — it is not masked down to its low 160 bits, which
// would render a `Pool #` breadcrumb for a coordinate this adapter never emitted.
uint256 raw = abi.decode(positionId, (uint256));
if (raw >> 160 != 0) return new string[](0);
address pool = address(uint160(raw));
out = new string[](2);
out[0] = "Staking Pools";
// Bounded probe, not a raw `pool.staticcall`. This view is reachable with an ARBITRARY clean address, and the
// unbounded form forwarded all gas and `returndatacopy`d the whole reply into `bytes memory`: measured at
// 1.04e9 gas against a looping `getPoolId()` and 6.2e7 against one returning 4 MB. It failed open in both
// cases but starved the frame — an out-of-gas in the very view that must never revert. {probeWord} caps the
// stipend at `PROBE_GAS` and copies at most one word. Its `hasWord` is the exact equivalent of the previous
// `ok && data.length >= 32` (and already folds in `ok`), so a pool id of 0 still counts as answered.
(, bool hasWord, uint256 poolId) =
StaticCallLib.probeWord(pool, abi.encodeWithSelector(INexusMutualStakingPool.getPoolId.selector));
out[1] = hasWord ? string.concat("Pool #", poolId.toString()) : Strings.toHexString(pool);
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return interfaceId == type(IPositionDescribable).interfaceId || super.supportsInterface(interfaceId);
}
//
// Hooks
//
/// @inheritdoc AssistedCoordCache
function _maxCoords() internal pure override returns (uint256) {
return MAX_TOKEN_IDS;
}
/// @inheritdoc AssistedCoordCache
function _maxLegsPerCoord() internal pure override returns (uint256) {
return 2;
}
/// @inheritdoc AssistedCoordCache
function _coordId(bytes memory coord) internal pure override returns (uint256) {
return abi.decode(coord, (uint256));
}
/// @inheritdoc AssistedCoordCache
function _validateCoord(address account, bytes memory coord) internal view override {
uint256 tokenId = abi.decode(coord, (uint256));
(address owner, bool ok) = _ownerOf(tokenId);
if (!ok || owner != account) revert CoordinateNotOwned(account, tokenId);
}
/// @inheritdoc AssistedCoordCache
function _coordLength() internal pure override returns (uint256) {
return 32;
}
/// @inheritdoc AssistedCoordCache
/// @dev Dead when `tokenInfo` SUCCEEDS with another owner, or with `account` as owner and `getTokens` SUCCEEDS
/// reporting no active stake, expired stake or rewards. Stricter than {_removable}: a `tokenInfo` revert or
/// an empty `getTokens` reply is not proof the position is gone.
function _isDead(address account, bytes memory coord) internal view override returns (bool) {
uint256 tokenId = abi.decode(coord, (uint256));
(address owner, bool ok) = _ownerOf(tokenId);
if (!ok) return false;
if (owner != account) return true;
uint256[] memory one = new uint256[](1);
one[0] = tokenId;
try INexusStakingViewer(STAKING_VIEWER).getTokens(one) returns (INexusStakingViewer.Token[] memory tokens) {
if (tokens.length == 0) return false;
return tokens[0].activeStake + tokens[0].expiredStake + tokens[0].rewards == 0;
} catch {
return false;
}
}
/// @inheritdoc AssistedCoordCache
/// @dev Nexus does not burn the StakingNFT on withdraw, so "no longer owned" is not a reliable liveness proxy.
/// Removable iff the position no longer resolves to a live amount for `account`: either the id is no longer
/// owned by `account`, or it is owned but fully emptied (no active/expired stake and no rewards). A still-live
/// (partial/rewards-only) position is NOT removable, so a later partial withdraw can never silently drop it —
/// matching the family "under-report only" invariant. On an unresolvable `getTokens` read, err toward keeping
/// the id (return false) so a maybe-live position is never dropped.
function _removable(address account, bytes memory coord) internal view override returns (bool) {
uint256 tokenId = abi.decode(coord, (uint256));
(address owner, bool ok) = _ownerOf(tokenId);
if (!ok || owner != account) return true; // transferred / burned away → safe to drop
uint256[] memory one = new uint256[](1);
one[0] = tokenId;
try INexusStakingViewer(STAKING_VIEWER).getTokens(one) returns (INexusStakingViewer.Token[] memory tokens) {
if (tokens.length == 0) return true;
return tokens[0].activeStake + tokens[0].expiredStake + tokens[0].rewards == 0;
} catch {
return false; // cannot confirm the position is dead → keep tracking it
}
}
/// @inheritdoc AssistedCoordCache
/// @notice Values one cached `tokenId` into its (up to 2) legs: `Staking` (active + expired) + `Rewards`, NXM-
/// denominated. Empty if not owned by `account`, no stake/rewards, or the pool can't be resolved. Reached
/// via the self-`staticcall`, so it may revert freely (`getTokens` reverts are isolated).
function _valueCoord(address account, bytes memory coord, INAVCalculator.Asset memory underlying)
internal
view
override
returns (INAVCalculator.PositionBalance[] memory)
{
uint256 tokenId = abi.decode(coord, (uint256));
INAVCalculator.PositionBalance[] memory none = new INAVCalculator.PositionBalance[](0);
(, address owner) = INexusStakingNFT(STAKING_NFT).tokenInfo(tokenId);
if (owner != account) return none;
uint256[] memory one = new uint256[](1);
one[0] = tokenId;
INexusStakingViewer.Token[] memory tokens = INexusStakingViewer(STAKING_VIEWER).getTokens(one);
if (tokens.length == 0) return none;
uint256 staking = tokens[0].activeStake + tokens[0].expiredStake;
uint256 rewards = tokens[0].rewards;
if (staking == 0 && rewards == 0) return none;
address pool = INexusStakingViewer(STAKING_VIEWER).stakingPool(tokens[0].poolId);
if (pool == address(0)) return none;
bytes memory positionId = abi.encode(pool);
bytes32 instanceId = bytes32(tokenId);
INAVCalculator.PositionBalance[] memory tmp = new INAVCalculator.PositionBalance[](2);
uint256 n;
if (staking > 0) tmp[n++] = _leg(underlying, staking, PositionKind.Staking, positionId, instanceId);
if (rewards > 0) tmp[n++] = _leg(underlying, rewards, PositionKind.Rewards, positionId, instanceId);
INAVCalculator.PositionBalance[] memory outLegs = new INAVCalculator.PositionBalance[](n);
for (uint256 k; k < n; ++k) {
outLegs[k] = tmp[k];
}
return outLegs;
}
/// @dev Ownership read wrapping `tokenInfo` so a non-existent / burned id returns `(0, false)`.
function _ownerOf(uint256 tokenId) internal view returns (address owner, bool ok) {
try INexusStakingNFT(STAKING_NFT).tokenInfo(tokenId) returns (uint256, address o) {
return (o, true);
} catch {
return (address(0), false);
}
}
function _leg(
INAVCalculator.Asset memory asset,
uint256 amount,
PositionKind kind,
bytes memory positionId,
bytes32 positionInstanceId
) private view returns (INAVCalculator.PositionBalance memory) {
return INAVCalculator.PositionBalance({
balanceAsset: asset,
balanceAdapter: address(this),
amount: amount,
isDebt: false,
protocolBrand: PROTOCOL_BRAND,
protocolId: PROTOCOL_ID,
protocolSubId: PROTOCOL_SUB_ID,
positionId: positionId,
positionKind: kind,
isLocked: false,
positionInstanceId: positionInstanceId
});
}
}
/// @notice Minimal interface for Nexus Mutual's StakingNFT (ERC-721).
interface INexusStakingNFT {
/// @notice The pool and owner of `tokenId`. Reverts for a non-existent id.
function tokenInfo(uint256 tokenId) external view returns (uint256 poolId, address owner);
}
/// @notice Minimal interface for Nexus Mutual's StakingViewer.
interface INexusStakingViewer {
struct Deposit {
uint256 tokenId;
uint256 trancheId;
uint256 stake;
uint256 stakeShares;
uint256 reward;
}
struct Token {
uint256 tokenId;
uint256 poolId;
uint256 activeStake;
uint256 expiredStake;
uint256 rewards;
Deposit[] deposits;
}
struct AggregatedTokens {
uint256 totalActiveStake;
uint256 totalExpiredStake;
uint256 totalRewards;
}
/// @notice Per-token stake + rewards (in NXM) for each given StakingNFT tokenId.
function getTokens(uint256[] calldata tokenIds) external view returns (Token[] memory);
/// @notice Aggregates stake + rewards (in NXM) across the given StakingNFT tokenIds.
function getAggregatedTokens(uint256[] calldata tokenIds) external view returns (AggregatedTokens memory);
/// @notice The (deterministic) staking-pool contract address for `poolId`. Used as the `positionId`.
function stakingPool(uint256 poolId) external view returns (address);
}
/// @notice Minimal interface for a Nexus Mutual StakingPool — its numeric pool id, for the display label.
interface INexusMutualStakingPool {
function getPoolId() external view returns (uint256);
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/AccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/access/IAccessControl.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (access/IAccessControl.sol)
pragma solidity >=0.8.4;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted to signal this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Bytes.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Bytes.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
/**
* @dev Bytes operations.
*/
library Bytes {
/**
* @dev Forward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the first instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return indexOf(buffer, s, 0);
}
/**
* @dev Forward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance
* * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
uint256 length = buffer.length;
for (uint256 i = pos; i < length; ++i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {
return i;
}
}
return type(uint256).max;
}
/**
* @dev Backward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the last instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return lastIndexOf(buffer, s, type(uint256).max);
}
/**
* @dev Backward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance
* * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
unchecked {
uint256 length = buffer.length;
for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
return i - 1;
}
}
return type(uint256).max;
}
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in
* memory.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return slice(buffer, start, buffer.length);
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in
* memory. The `end` argument is truncated to the length of the `buffer`.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
end = Math.min(end, buffer.length);
start = Math.min(start, end);
// allocate and copy
bytes memory result = new bytes(end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))
}
return result;
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]
*/
function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return splice(buffer, start, buffer.length);
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to end (excluded) to the start of that buffer. The
* `end` argument is truncated to the length of the `buffer`.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice[Javascript's `Array.splice`]
*/
function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
end = Math.min(end, buffer.length);
start = Math.min(start, end);
// allocate and copy
assembly ("memory-safe") {
mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))
mstore(buffer, sub(end, start))
}
return buffer;
}
/**
* @dev Replaces bytes in `buffer` starting at `pos` with all bytes from `replacement`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`).
* If `pos >= buffer.length`, no replacement occurs and the buffer is returned unchanged.
*
* NOTE: This function modifies the provided buffer in place.
*/
function replace(bytes memory buffer, uint256 pos, bytes memory replacement) internal pure returns (bytes memory) {
return replace(buffer, pos, replacement, 0, replacement.length);
}
/**
* @dev Replaces bytes in `buffer` starting at `pos` with bytes from `replacement` starting at `offset`.
* Copies at most `length` bytes from `replacement` to `buffer`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, buffer.length]`, `offset` is
* clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
* buffer.length - pos))`. If `pos >= buffer.length` or `offset >= replacement.length`, no replacement occurs
* and the buffer is returned unchanged.
*
* NOTE: This function modifies the provided buffer in place.
*/
function replace(
bytes memory buffer,
uint256 pos,
bytes memory replacement,
uint256 offset,
uint256 length
) internal pure returns (bytes memory) {
// sanitize
pos = Math.min(pos, buffer.length);
offset = Math.min(offset, replacement.length);
length = Math.min(length, Math.min(replacement.length - offset, buffer.length - pos));
// allocate and copy
assembly ("memory-safe") {
mcopy(add(add(buffer, 0x20), pos), add(add(replacement, 0x20), offset), length)
}
return buffer;
}
/**
* @dev Concatenate an array of bytes into a single bytes object.
*
* For fixed bytes types, we recommend using the solidity built-in `bytes.concat` or (equivalent)
* `abi.encodePacked`.
*
* NOTE: this could be done in assembly with a single loop that expands starting at the FMP, but that would be
* significantly less readable. It might be worth benchmarking the savings of the full-assembly approach.
*/
function concat(bytes[] memory buffers) internal pure returns (bytes memory) {
uint256 length = 0;
for (uint256 i = 0; i < buffers.length; ++i) {
length += buffers[i].length;
}
bytes memory result = new bytes(length);
uint256 offset = 0x20;
for (uint256 i = 0; i < buffers.length; ++i) {
bytes memory input = buffers[i];
assembly ("memory-safe") {
mcopy(add(result, offset), add(input, 0x20), mload(input))
}
unchecked {
offset += input.length;
}
}
return result;
}
/**
* @dev Split each byte in `input` into two nibbles (4 bits each)
*
* Example: hex"01234567" → hex"0001020304050607"
*/
function toNibbles(bytes memory input) internal pure returns (bytes memory output) {
assembly ("memory-safe") {
let length := mload(input)
output := mload(0x40)
mstore(0x40, add(add(output, 0x20), mul(length, 2)))
mstore(output, mul(length, 2))
for {
let i := 0
} lt(i, length) {
i := add(i, 0x10)
} {
let chunk := shr(128, mload(add(add(input, 0x20), i)))
chunk := and(
0x0000000000000000ffffffffffffffff0000000000000000ffffffffffffffff,
or(shl(64, chunk), chunk)
)
chunk := and(
0x00000000ffffffff00000000ffffffff00000000ffffffff00000000ffffffff,
or(shl(32, chunk), chunk)
)
chunk := and(
0x0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff,
or(shl(16, chunk), chunk)
)
chunk := and(
0x00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff,
or(shl(8, chunk), chunk)
)
chunk := and(
0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f,
or(shl(4, chunk), chunk)
)
mstore(add(add(output, 0x20), mul(i, 2)), chunk)
}
}
}
/**
* @dev Returns true if the two byte buffers are equal.
*/
function equal(bytes memory a, bytes memory b) internal pure returns (bool) {
return a.length == b.length && keccak256(a) == keccak256(b);
}
/**
* @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.
* Inspired by https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]
*/
function reverseBytes32(bytes32 value) internal pure returns (bytes32) {
value = // swap bytes
((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
value = // swap 8-byte long pairs
((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
return (value >> 128) | (value << 128); // swap 16-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 128-bit values.
function reverseBytes16(bytes16 value) internal pure returns (bytes16) {
value = // swap bytes
((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
return (value >> 64) | (value << 64); // swap 8-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 64-bit values.
function reverseBytes8(bytes8 value) internal pure returns (bytes8) {
value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes
value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs
return (value >> 32) | (value << 32); // swap 4-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 32-bit values.
function reverseBytes4(bytes4 value) internal pure returns (bytes4) {
value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes
return (value >> 16) | (value << 16); // swap 2-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 16-bit values.
function reverseBytes2(bytes2 value) internal pure returns (bytes2) {
return (value >> 8) | (value << 8);
}
/**
* @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`
* if the buffer is all zeros.
*/
function clz(bytes memory buffer) internal pure returns (uint256) {
for (uint256 i = 0; i < buffer.length; i += 0x20) {
bytes32 chunk = _unsafeReadBytesOffset(buffer, i);
if (chunk != bytes32(0)) {
return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);
}
}
return 8 * buffer.length;
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Context.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Strings.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
import {Bytes} from "./Bytes.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
*/
function toHexString(bytes memory input) internal pure returns (string memory) {
unchecked {
bytes memory buffer = new bytes(2 * input.length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 0; i < input.length; ++i) {
uint8 v = uint8(input[i]);
buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
}
return string(buffer);
}
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return Bytes.equal(bytes(a), bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i = 0; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `condition ? a : b`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `condition ? a : b`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory buffer) private pure returns (bool) {
uint256 chunk;
for (uint256 i = 0; i < buffer.length; i += 0x20) {
// See _unsafeReadBytesOffset from utils/Bytes.sol
assembly ("memory-safe") {
chunk := mload(add(add(buffer, 0x20), i))
}
if (chunk >> (8 * saturatingSub(i + 0x20, buffer.length)) != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the first 16 bytes (most significant half).
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in a uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev A uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SignedMath.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. 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. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
src/balances/AssistedBalanceAdapters/AssistedCoordCache.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {IAssistedBalanceAdapter} from "src/balances/IAssistedBalanceAdapter.sol";
import {IBalanceAdapter} from "src/balances/IBalanceAdapter.sol";
import {RegisteredAssetLib} from "src/balances/RegisteredAssetLib.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {SUBMITTER} from "src/constants.sol";
import {AddressCheckLib} from "src/utils/AddressCheckLib.sol";
import {GasStipendLib} from "src/utils/GasStipendLib.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";
/// @notice One cached coordinate ran out of the gas the valuation fan-out forwarded it, so the account's reported
/// total is missing that coordinate — and, because the residue left to the loop cannot fund the ones after
/// it, very likely every coordinate behind it too.
/// @dev The sibling of `INAVCalculator.InstanceGasExhausted`, one family over. Reports `_coordId` — the
/// concrete adapter's human-facing tokenId / requestId / positionTicket — rather than the internal
/// `keccak256(coord)` dedup key, matching every other `Coordinate*` error in `src/errors.sol`. That hook
/// exists precisely so an operator can act on the error without reversing a hash. Deliberately declared HERE rather
/// than in `src/errors.sol`: both pinned libraries (`PriceFeedLib`, `NAVRegistryLib`) plain-import that file,
/// so adding to it would put this symbol inside both CREATE2 compilation closures for no benefit — nothing
/// outside this family raises or catches it. Keeping it file-local keeps this change provably pin-neutral.
error CoordinateGasExhausted(address adapter, uint256 coordId, uint256 stipend, uint256 consumed);
/// @title AssistedCoordCache
/// @author KPK
/// @notice The single cache base for the **assistant-fed** assisted balance-adapter family. A position
/// *coordinate* is an opaque `bytes` blob, so ONE cache serves every member regardless of coordinate shape:
/// a bare `uint256` NFT tokenId / withdrawal requestId (`abi.encode(id)`) or a richer tuple (StakeWise V3 exit
/// positions, `abi.encode(vault, positionTicket, timestamp)`). It holds the per-account coordinate-record cache
/// (blobs deduped by their keccak key) and its `msg.sender`-keyed CRUD, plus the single-underlying-asset
/// {IBalanceAdapter} getter surface and the per-coordinate fail-open valuation fan-out. The concrete adapter
/// exposes a *typed* `submit`/`remove` that `abi.encode`s its coordinate and routes to {_submitCoord}/
/// {_removeCoord}, and implements {_valueCoord} (decode + value live), {_validateCoord} (fail-loud write-time
/// hygiene), {_removable}, {_coordId}, {_maxCoords}, {_maxLegsPerCoord}.
/// @dev Two feeders. The owner path keys on `msg.sender`, so a caller can only ever touch its OWN set; the canonical
/// feeder is a {BalanceAdapterAssistant} the owner Safe delegatecalls (so `msg.sender` is the Safe). For positions
/// the owner did not open through its assistant, a {SUBMITTER_ROLE} keeper files coordinates under the account the
/// protocol says owns them ({submitFor}); anyone may drop a coordinate the protocol proves dead ({removeFor}).
/// Both run the same {_validateCoord} / ownership rules as the owner path, so the family invariant holds unchanged
/// — coordinates only, valued live, ownership re-verified per read → under-report only (ADR 0030).
///
/// **WHAT THIS FILE CANNOT SHOW YOU — the cache is COMPLETE in production, not merely conservative.** Read on its
/// own, this contract is a cache with no completeness guarantee whatsoever: anyone may `submit`
/// their own coordinates, nobody is obliged to, and the assistant is the *canonical feeder* rather than a gate. So
/// "under-report only" is the honest reading of THIS code — and it understates the deployed system. The portfolio
/// Safes' **roles-modifier permission set allows the corresponding protocol entries only through the assistant
/// contracts; the direct protocol entrypoint is not in the allow-list.** A position of these types therefore
/// cannot be active without its coordinate having been fed here. Two complementary halves: *contract level* (this
/// file) → cannot **over**-report; *roles level* (**outside this repository**) → cannot **under**-report either.
/// Enforcement is in the Safe's roles configuration, which is not part of this repo — treat this as a pointer to
/// it, not as an operational rule someone must remember. **Residual risk:** not a bypass by an operator (not
/// permitted), but a **change to the roles permission set adding a path that reaches the protocol without the
/// assistant** — after which this cache silently misses positions and nothing in this repository would detect it,
/// because every invariant above still holds. See `AssistedBalanceAdapters/README.md` §5.0 and ADRs 0015 / 0018.
///
/// Uses a `bytes[]` array + `key → idxPlus1` map for dedup and O(1) swap-pop removal. Reads isolate each
/// coordinate behind a self-`staticcall` ({valueCoordSelf}), so a revert-prone valuation (e.g. Nexus's
/// `StakingViewer.getTokens`) only drops that one coordinate, never the account's whole set.
abstract contract AssistedCoordCache is IAssistedBalanceAdapter, AccessControl {
/// @inheritdoc IAssistedBalanceAdapter
/// @dev Gates {submitFor}/{submitForBatch} only. The owner path, {removeFor}, {evict} and {clearAccount} stay open.
bytes32 public constant SUBMITTER_ROLE = SUBMITTER;
/// @notice Cache slots the keeper path can never use, so an account always keeps at least this many for its own
/// Assistant `submit` (beyond that, `evict` frees room). Anyone
/// can create a live position OWNED by a Safe; if a keeper could file those up to the full cap, the Safe's
/// Assistant enter path (whose `submit` is not caught) would revert until it cleared its cache (ADR 0030 S13).
uint256 public constant OWNER_RESERVE = 32;
/// @notice The single asset this adapter reports. Must be a registered NAV asset for {getAdapterPositions} to count
/// it; the balance getters report it regardless (registration-independent).
address public immutable UNDERLYING_TOKEN;
/// @notice NAVCalculator — used to look up the registered underlying-asset metadata when emitting positions.
INAVCalculator public immutable NAV_CALCULATOR;
/// @notice Cached coordinate blobs per account (the only thing the feeder supplies). Each is an `abi.encode` of the
/// concrete adapter's tuple.
mapping(address account => bytes[] coords) private _coords;
/// @dev `idxPlus1` = index of the coordinate in `_coords[account]` plus 1, keyed by `keccak256(coord)`. Zero ⇒ not
/// present (dedup + O(1) removal).
mapping(address account => mapping(bytes32 key => uint256)) private _idxPlus1;
/// @notice `id` is the concrete adapter's human-facing coordinate id ({_coordId}: a tokenId / requestId /
/// positionTicket) — indexed so consumers can filter, matching the legacy per-adapter events.
event CoordSubmitted(address indexed account, uint256 indexed id);
event CoordCleared(address indexed account, uint256 indexed id);
event AccountCleared(address indexed account);
/// @notice A {SUBMITTER_ROLE} keeper filed a new coordinate for `account` (emitted alongside {CoordSubmitted}, so
/// keeper-filed entries are attributable without a trace).
event CoordSubmittedFor(address indexed account, uint256 indexed id, address indexed submitter);
/// @param underlyingToken_ The reported underlying asset. Must be non-zero.
/// @param navCalculator_ NAVCalculator. Must be a contract.
/// @param admin_ Holder of `DEFAULT_ADMIN_ROLE` (grants/revokes {SUBMITTER_ROLE}). Must be non-zero. No
/// submitter is granted here: a deploy alone never creates a live submit right.
constructor(address underlyingToken_, address navCalculator_, address admin_) {
if (underlyingToken_ == address(0) || navCalculator_ == address(0) || admin_ == address(0)) {
revert InvalidArguments();
}
AddressCheckLib.requireContract(navCalculator_, "NAVCalculator");
UNDERLYING_TOKEN = underlyingToken_;
NAV_CALCULATOR = INAVCalculator(navCalculator_);
_grantRole(DEFAULT_ADMIN_ROLE, admin_);
}
//
// Writes — keeper path (role-gated submit, proof-of-death remove)
//
/// @inheritdoc IAssistedBalanceAdapter
function submitFor(address account, bytes calldata coord) external {
_checkRole(SUBMITTER_ROLE);
_submitFor(account, coord);
}
/// @inheritdoc IAssistedBalanceAdapter
function submitForBatch(address[] calldata accounts, bytes[] calldata coords) external {
// Checked here too: an EMPTY batch never enters the loop, and a roleless caller must not get a success.
_checkRole(SUBMITTER_ROLE);
if (accounts.length != coords.length) revert InvalidArguments();
for (uint256 i; i < accounts.length; ++i) {
_submitFor(accounts[i], coords[i]);
}
}
/// @inheritdoc IAssistedBalanceAdapter
/// @dev Not role-gated on purpose: a role-gated remove would let a compromised key delete LIVE positions (a
/// targeted under-report). Gating on {_isDead} instead makes the call safe for anyone.
function removeFor(address account, bytes calldata coord) external {
_requireCanonical(coord);
// Cached-check first, so {_isDead} only ever reads a coordinate that passed write-time validation.
if (_idxPlus1[account][keccak256(coord)] == 0) revert CoordinateNotCached(account, _coordId(coord));
_removeEntry(account, coord, _isDead(account, coord));
}
//
// Writes — owner path (each account feeds/cleans its own cache, keyed on msg.sender)
//
/// @inheritdoc IAssistedBalanceAdapter
function clearAccount() external {
bytes[] storage list = _coords[msg.sender];
for (uint256 i; i < list.length; ++i) {
delete _idxPlus1[msg.sender][keccak256(list[i])];
}
delete _coords[msg.sender];
emit AccountCleared(msg.sender);
}
/// @inheritdoc IAssistedBalanceAdapter
function evict(bytes calldata coord) external {
_requireCanonical(coord);
_removeEntry(msg.sender, coord, true);
}
//
// Reads
//
/// @notice Candidate coordinate blobs currently cached for `account` (display/debug; not staleness-filtered).
function coordsOf(address account) external view returns (bytes[] memory) {
return _cachedCoords(account);
}
/// @dev The cached coordinate blobs for `account`, for the concrete adapter's typed read helpers / valuation.
function _cachedCoords(address account) internal view returns (bytes[] memory) {
return _coords[account];
}
/// @inheritdoc IBalanceAdapter
function underlyingAssetsSupported() external view virtual override returns (address[] memory assets) {
assets = new address[](1);
assets[0] = UNDERLYING_TOKEN;
}
/// @inheritdoc IBalanceAdapter
function getAdapterBalanceForAsset(address account, address asset)
external
view
virtual
override
returns (uint256 amount, bool isDebt)
{
if (asset != UNDERLYING_TOKEN || account == address(0)) return (0, false);
return (_owedAmount(account), false);
}
/// @inheritdoc IBalanceAdapter
function getAdapterBalances(address account)
external
view
virtual
override
returns (address[] memory assets, uint256[] memory amounts, bool[] memory isDebt)
{
uint256 total = account == address(0) ? 0 : _owedAmount(account);
if (total == 0) return (new address[](0), new uint256[](0), new bool[](0));
assets = new address[](1);
amounts = new uint256[](1);
isDebt = new bool[](1);
assets[0] = UNDERLYING_TOKEN;
amounts[0] = total;
}
/// @inheritdoc IBalanceAdapter
function getAdapterPositions(address account, address assetFilter)
external
view
virtual
override
returns (INAVCalculator.PositionBalance[] memory positions)
{
if (assetFilter != address(0) && assetFilter != UNDERLYING_TOKEN) {
return new INAVCalculator.PositionBalance[](0);
}
if (account == address(0)) return new INAVCalculator.PositionBalance[](0);
(INAVCalculator.Asset memory underlying, bool registered) =
RegisteredAssetLib.find(NAV_CALCULATOR.getRegisteredAssets(), UNDERLYING_TOKEN);
if (!registered) return new INAVCalculator.PositionBalance[](0);
return _collect(account, underlying);
}
/// @inheritdoc IAssistedBalanceAdapter
function previewPositions(address account, bytes calldata data)
external
view
override
returns (INAVCalculator.PositionBalance[] memory positions)
{
if (account == address(0) || data.length == 0) return new INAVCalculator.PositionBalance[](0);
return this.previewPositionsSelf(account, abi.decode(data, (bytes[])));
}
/// @notice External self-call frame for the preview loop — `msg.sender`-guarded to `address(this)`; `view`, so the
/// self-call is a staticcall. Mirrors {valueCoordSelf}.
/// @dev No per-coordinate stipend or try/catch, unlike the NAV read: the caller pays for its own `eth_call`, and a
/// bad coordinate must surface rather than be dropped.
function previewPositionsSelf(address account, bytes[] calldata coords)
external
view
returns (INAVCalculator.PositionBalance[] memory positions)
{
if (msg.sender != address(this)) revert NotAuthorized();
uint256 n = coords.length;
if (n == 0) return new INAVCalculator.PositionBalance[](0);
if (n > _maxCoords()) revert TooManyCoordinates(account, n, _maxCoords());
// Same short-circuit as the NAV read: nothing is reported for an unregistered underlying, so don't spend gas
// validating coordinates first.
(INAVCalculator.Asset memory underlying, bool registered) =
RegisteredAssetLib.find(NAV_CALCULATOR.getRegisteredAssets(), UNDERLYING_TOKEN);
if (!registered) return new INAVCalculator.PositionBalance[](0);
bytes32[] memory keys = new bytes32[](n);
for (uint256 i; i < n; ++i) {
_requireCanonical(coords[i]);
keys[i] = keccak256(coords[i]);
for (uint256 j; j < i; ++j) {
if (keys[j] == keys[i]) revert DuplicateCoordinate(account, _coordId(coords[i]));
}
_validateCoord(account, coords[i]);
}
INAVCalculator.PositionBalance[] memory temp = new INAVCalculator.PositionBalance[](n * _maxLegsPerCoord());
uint256 count;
for (uint256 i; i < n; ++i) {
INAVCalculator.PositionBalance[] memory legs = _valueCoord(account, coords[i], underlying);
for (uint256 j; j < legs.length; ++j) {
temp[count++] = legs[j];
}
}
positions = new INAVCalculator.PositionBalance[](count);
for (uint256 i; i < count; ++i) {
positions[i] = temp[i];
}
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, IERC165) returns (bool) {
return interfaceId == type(IBalanceAdapter).interfaceId
|| interfaceId == type(IAssistedBalanceAdapter).interfaceId || super.supportsInterface(interfaceId);
}
//
// Internal — cache mutation (called by the concrete's typed submit/remove)
//
/// @dev Owner path: add one coordinate for the caller (idempotent). Keyed on `msg.sender` (self-scoped). The typed
/// `submit` always passes a canonical `abi.encode`.
function _submitCoord(bytes memory coord) internal {
_addEntry(msg.sender, coord, _maxCoords());
}
/// @dev Keeper path: canonical-encoding check, then the owner path's admission with a lower limit (cap minus
/// {OWNER_RESERVE}; 0 for a member whose cap does not exceed the reserve, which disables the keeper path).
function _submitFor(address account, bytes calldata coord) private {
if (account == address(0)) revert InvalidArguments();
_requireCanonical(coord);
uint256 cap = _maxCoords();
if (_addEntry(account, coord, cap > OWNER_RESERVE ? cap - OWNER_RESERVE : 0)) {
emit CoordSubmittedFor(account, _coordId(coord), msg.sender);
}
}
/// @dev The single admission point for both paths (idempotent). Fail-loud: `CoordinateCacheFull` once the set
/// holds `limit` entries ({_maxCoords} for the owner, {_maxCoords} − {OWNER_RESERVE} for the keeper), and
/// {_validateCoord} reverts (`InvalidCoordinate` / `CoordinateNotOwned`) on a bad or non-owned coordinate.
function _addEntry(address account, bytes memory coord, uint256 limit) private returns (bool added) {
bytes32 key = keccak256(coord);
// Re-validate on EVERY submit (before the dedup early-return) so a resubmit of an already-cached coordinate the
// caller has since transferred away is rejected loud rather than silently kept.
_validateCoord(account, coord); // fail-loud write-time hygiene
if (_idxPlus1[account][key] != 0) return false; // already cached (idempotent no-op)
if (_coords[account].length >= limit) revert CoordinateCacheFull(account, limit);
_coords[account].push(coord);
_idxPlus1[account][key] = _coords[account].length;
emit CoordSubmitted(account, _coordId(coord));
return true;
}
/// @dev Owner path: drop one coordinate for the caller once {_removable}. Keyed on `msg.sender`.
function _removeCoord(bytes memory coord) internal {
address account = msg.sender;
if (_idxPlus1[account][keccak256(coord)] == 0) revert CoordinateNotCached(account, _coordId(coord));
_removeEntry(account, coord, _removable(account, coord));
}
/// @dev Drop one coordinate from `account`. Fail-loud: **reverts** `CoordinateNotCached` if `account` isn't
/// tracking `coord`, and `CoordinateStillLive` unless `removable` — so a live position is never silently
/// dropped.
function _removeEntry(address account, bytes memory coord, bool removable) private {
bytes32 key = keccak256(coord);
uint256 idxPlus1 = _idxPlus1[account][key];
if (idxPlus1 == 0) revert CoordinateNotCached(account, _coordId(coord));
if (!removable) revert CoordinateStillLive(account, _coordId(coord));
uint256 idx = idxPlus1 - 1;
bytes[] storage list = _coords[account];
uint256 lastIdx = list.length - 1;
if (idx != lastIdx) {
bytes memory last = list[lastIdx];
list[idx] = last;
_idxPlus1[account][keccak256(last)] = idx + 1;
}
list.pop();
delete _idxPlus1[account][key];
emit CoordCleared(account, _coordId(coord));
}
/// @dev Rejects any `coord` whose length differs from the member's canonical encoding, BEFORE anything decodes
/// it, so one position has exactly one cache key (ADR 0030 S2).
function _requireCanonical(bytes memory coord) internal pure {
if (coord.length != _coordLength()) revert NonCanonicalCoordinate(coord.length, _coordLength());
}
//
// Internal — valuation
//
/// @dev Total `UNDERLYING_TOKEN` owed across `account`'s cached coordinates (registration-independent — zeroed Asset).
function _owedAmount(address account) internal view returns (uint256 total) {
INAVCalculator.Asset memory zero;
INAVCalculator.PositionBalance[] memory legs = _collect(account, zero);
for (uint256 i; i < legs.length; ++i) {
total += legs[i].amount;
}
}
/// @dev Values every cached coordinate of `account` into a flat leg array, isolating each coordinate behind a
/// per-item `this.valueCoordSelf(...)` staticcall wrapped in try/catch — so a revert in one coordinate's live
/// reads discards only THAT coordinate and never propagates out of {getAdapterPositions} (where NAVCalculator's
/// per-adapter try/catch would otherwise fail-open and drop the account's ENTIRE set). Coordinates whose
/// valuation is internally safe pay only the extra call frame (negligible on the async NAV read path, ADR 0017).
///
/// **The isolation is deliberate and stays — but it must not absorb a STARVED coordinate.** A coordinate
/// whose protocol read reverts has answered: it contributes nothing, and one bad NFT must not cost the
/// account its other positions. Gas exhaustion is categorically different. The coordinate did not answer,
/// recording it as zero legs silently deletes a real position, and — because a starved child takes 63/64
/// of what the loop held — the ~1/64 residue cannot fund the coordinates AFTER it either, so one starved
/// entry can quietly empty the rest of the list. `_collect` would still RETURN, so nothing downstream can
/// tell the answer was partial: `PriceFeedLib._getAdapterPositions` only inspects its own catch arm, and
/// this frame never reverted. That is the one failure this loop must not swallow, so it raises
/// {CoordinateGasExhausted} instead.
///
/// The classification is {GasStipendLib}'s, not restated here — the same shared threshold
/// `MetaBalanceAdapter._positionsForInstances` and `PriceFeedLib._getAdapterPositions` use, so the three
/// cannot drift apart.
///
/// Direction note, so the severity is not overstated: this family emits credit legs only
/// (`isDebt = false` throughout), so swallowing a coordinate under-reports rather than over-reports. That
/// is a property of today's three members, not of this base — a future member emitting a debt leg would
/// make the swallowed case an over-report, and this guard is what stops that being a silent one.
function _collect(address account, INAVCalculator.Asset memory underlying)
internal
view
returns (INAVCalculator.PositionBalance[] memory positions)
{
bytes[] memory list = _coords[account];
if (list.length == 0) return new INAVCalculator.PositionBalance[](0);
INAVCalculator.PositionBalance[] memory temp =
new INAVCalculator.PositionBalance[](list.length * _maxLegsPerCoord());
uint256 count;
for (uint256 i; i < list.length; ++i) {
// One sample, used both to derive the stipend and to measure against it — see GasStipendLib.exhausted.
uint256 available = gasleft();
uint256 stipend = GasStipendLib.stipendFrom(available);
try this.valueCoordSelf{gas: stipend}(account, list[i], underlying) returns (
INAVCalculator.PositionBalance[] memory legs
) {
for (uint256 j; j < legs.length; ++j) {
temp[count++] = legs[j];
}
} catch {
uint256 consumed = available - gasleft();
if (GasStipendLib.exhausted(stipend, consumed)) {
revert CoordinateGasExhausted(address(this), _coordId(list[i]), stipend, consumed);
}
}
}
positions = new INAVCalculator.PositionBalance[](count);
for (uint256 i; i < count; ++i) {
positions[i] = temp[i];
}
}
/// @notice External self-call entrypoint for {_valueCoord}, enabling the per-coordinate try/catch isolation in
/// {_collect}. `msg.sender`-guarded to `address(this)` so it is not a usable external surface; it is
/// `external` (so the self-call is a staticcall) ONLY to give each coordinate its own revert frame.
function valueCoordSelf(address account, bytes calldata coord, INAVCalculator.Asset calldata underlying)
external
view
returns (INAVCalculator.PositionBalance[] memory)
{
if (msg.sender != address(this)) revert NotAuthorized();
return _valueCoord(account, coord, underlying);
}
//
// Hooks (concrete adapter)
//
/// @notice The per-account cache cap (read-loop gas bound).
function _maxCoords() internal view virtual returns (uint256);
/// @notice Byte length of the member's canonical coordinate encoding (`abi.encode` of its static tuple).
function _coordLength() internal pure virtual returns (uint256);
/// @notice Upper bound on legs emitted per coordinate (scratch-buffer sizing).
function _maxLegsPerCoord() internal pure virtual returns (uint256);
/// @notice The human-facing id for a coordinate (a positionTicket / requestId), used only to populate the shared
/// `Coordinate*` errors. The stable dedup/lookup key is `keccak256(coord)`; this is a decoded scalar for
/// legibility.
function _coordId(bytes memory coord) internal pure virtual returns (uint256);
/// @notice Write-time validation for a submitted coordinate. MUST revert (fail-loud) on an invalid coordinate:
/// `InvalidCoordinate` for a malformed/unregistered target, `CoordinateNotOwned` if it does not resolve to
/// a live position owned by `account`.
function _validateCoord(address account, bytes memory coord) internal view virtual;
/// @notice Whether `coord` may be removed from `account`'s cache. Default: only when it no longer resolves to a
/// live owed amount for `account` (claimed / consumed) — so {_removeCoord} never drops a live position
/// (under-report only). Implemented per adapter (the liveness proxy is protocol-specific).
function _removable(address account, bytes memory coord) internal view virtual returns (bool);
/// @notice Whether the protocol PROVES `coord` no longer holds anything for `account` — the gate for the
/// permissionless {removeFor}. Stricter than {_removable}: only a SUCCESSFUL read showing the position
/// burned, transferred away or emptied counts; a reverting read never does (it could be transient).
function _isDead(address account, bytes memory coord) internal view virtual returns (bool);
/// @notice Values a single cached coordinate into its legs (empty if it contributes nothing — not owned, claimed,
/// zero amount). Decodes `coord` and re-verifies ownership live. Reached only via the self-`staticcall` in
/// {_collect}, so it MAY revert freely — the caller isolates it (a reverting coordinate is discarded).
function _valueCoord(address account, bytes memory coord, INAVCalculator.Asset memory underlying)
internal
view
virtual
returns (INAVCalculator.PositionBalance[] memory);
}
src/balances/IAssistedBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {IBalanceAdapter} from "src/balances/IBalanceAdapter.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
/// @title IAssistedBalanceAdapter
/// @author KPK
/// @notice Marker interface for the **assistant-fed** assisted balance-adapter family — adapters whose
/// positions cannot be derived from on-chain state alone (non-enumerable NFTs, withdrawal/exit-queue tickets)
/// and are instead fed their position *coordinates* on-chain by the position owner itself. The canonical
/// feeder is a small assistant contract ({IBalanceAdapterAssistant}) that a depositor Safe `delegatecall`s: in the
/// same transaction it enters/exits a protocol, it pushes/pops the resulting coordinate onto the adapter, and
/// because it runs under `delegatecall` the adapter sees `msg.sender = the Safe = the position owner`.
/// @dev **Trust model (family invariant).** Every member caches **only position coordinates, never amounts**; values
/// each read entirely from live on-chain reads; and re-verifies ownership on every read (discarding coordinates
/// no longer owned). A faulty or malicious feeder can therefore only **under-report, never over-report**.
///
/// **The deployed guarantee is stronger, and its second half is not in this repository.** The portfolio Safes'
/// **roles-modifier permission set allows the corresponding protocol entries only through the assistant
/// contracts — the direct protocol entrypoint is not allow-listed** — so a position of these types cannot be
/// active without its coordinate having been fed, making the cache **complete by construction**. Contract level
/// (here) → cannot **over**-report; roles level (outside this repo) → cannot **under**-report either. Nothing in
/// this repo enforces the latter (the owner mutators are permissionless), so do not infer it from the code; the
/// residual risk is a roles-permission change adding a non-assistant path, which no tripwire here would catch.
/// See ADR 0015 / ADR 0018 and `AssistedBalanceAdapters/README.md` §5.0.
///
/// **Two feeders (ADR 0030).** The owner path is unchanged: the typed `submit`/`remove` mutators derive the
/// account from `msg.sender`, so an account (directly or through its assistant) only ever touches its OWN set.
/// The interface does not prescribe those typed signatures, since the coordinate shape is per-protocol. Added for
/// positions the account did NOT open through its assistant: {submitFor}/{submitForBatch}, gated by
/// {SUBMITTER_ROLE} (a keeper), which file a coordinate only under the account the protocol says owns it — the
/// same write-time validation as the owner path, so the role decides WHICH positions occupy the capped cache,
/// never what they are worth. {removeFor} is permissionless but succeeds only once the protocol proves the
/// position is gone, so no caller can drop a live one. {previewPositions} values caller-supplied coordinates
/// without touching the cache.
///
/// **Coordinate encoding.** The generic entry points take `coord` as the member's canonical `abi.encode` of its
/// tuple (a 32-byte tokenId for ether.fi / Nexus Mutual, `(address vault, uint256 ticket, uint256 timestamp)` for
/// StakeWise). Any other length reverts, so one position has exactly one cache key.
interface IAssistedBalanceAdapter is IAccessControl, IBalanceAdapter {
/// @notice A {previewPositions} payload names the same coordinate twice — a double count, rejected fail-loud.
error DuplicateCoordinate(address account, uint256 id);
/// @notice A {previewPositions} payload has more coordinates than an account's cache may hold.
error TooManyCoordinates(address account, uint256 count, uint256 max);
/// @notice `coord` is not the member's canonical encoding (wrong length), so it could alias another cache key.
error NonCanonicalCoordinate(uint256 length, uint256 expected);
/// @notice The role allowed to call {submitFor}/{submitForBatch}.
function SUBMITTER_ROLE() external view returns (bytes32);
/// @notice File `coord` under `account`, which the protocol must say owns it (idempotent). Requires
/// {SUBMITTER_ROLE}. Reverts `CoordinateNotOwned` / `InvalidCoordinate` on a bad or non-owned
/// coordinate, `CoordinateCacheFull` once the account holds the cap minus `OWNER_RESERVE` entries
/// (the reserve stays for the owner's own submit), {NonCanonicalCoordinate} on a wrong encoding.
function submitFor(address account, bytes calldata coord) external;
/// @notice Batch {submitFor}; all-or-nothing. Requires {SUBMITTER_ROLE}.
function submitForBatch(address[] calldata accounts, bytes[] calldata coords) external;
/// @notice Drop `coord` from `account`'s cache once the protocol proves the position is gone (claimed, burned,
/// transferred away, nothing left). Permissionless: a read that reverts never counts as proof, so no caller
/// can drop a live position. Reverts `CoordinateNotCached` / `CoordinateStillLive`.
function removeFor(address account, bytes calldata coord) external;
/// @notice Values caller-supplied coordinates for `account` without reading or writing the cache.
/// @dev `data = abi.encode(bytes[] coords)`, each in the canonical encoding. Every coordinate goes through the
/// same validation as a submit and reverts on failure (bad, non-owned, duplicate, or more than the cap);
/// surviving ones are valued exactly as the NAV read values a cached coordinate. Empty `data` or a zero
/// `account` returns an empty array; an unregistered underlying returns an empty array, as the NAV read does.
function previewPositions(address account, bytes calldata data)
external
view
returns (INAVCalculator.PositionBalance[] memory positions);
/// @notice Drop **all** of the caller's own cached position coordinates (self-service garbage collection). Keyed on
/// `msg.sender`, so it can only clear the caller's own set — never another account's. This is
/// unconditional: unlike per-coordinate `remove` (which reverts `CoordinateStillLive` while a position is
/// live), `clearAccount` does **not** check liveness, so any still-live positions stop being reported until
/// re-submitted. Consistent with the family invariant it only ever **under-reports** the caller's own NAV;
/// it is not NAV-neutral when live coordinates are present.
function clearAccount() external;
/// @notice Drop ONE of the caller's own cached coordinates, live or not (keyed on `msg.sender`). The selective
/// form of {clearAccount}: it lets a Safe whose cache a keeper filled with positions a third party created
/// in its name (ADR 0030 S13) free slots without dropping its real entries. Like {clearAccount} it can
/// only under-report the caller's own NAV. Reverts `CoordinateNotCached` / {NonCanonicalCoordinate}.
/// Not reachable through an Assistant: a roles-operated Safe needs a roles entry for it (or a signer tx).
function evict(bytes calldata coord) external;
}
src/balances/IBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title IBalanceAdapter
/// @notice Standard interface for balance adapters (both default and custom)
/// @dev All balance adapters must implement this interface to work with the adapter-centric aggregation system
/// @dev Extends ERC165 to allow on-chain discovery with `supportsInterface`.
/// @author KPK
interface IBalanceAdapter is IERC165 {
/// @notice Get all positions from this adapter for an account
/// @param account The account to query
/// @param assetFilter Optional asset filter (address(0) for all assets)
/// @return positions Array of balance-only PositionBalance structs from this adapter
/// @dev Balance adapters return balance-only data without pricing. NAVCalculator enriches these with pricing.
function getAdapterPositions(address account, address assetFilter)
external
view
returns (INAVCalculator.PositionBalance[] memory positions);
/// @notice Get balances from this adapter for an account
/// @param account The account to query
/// @return assets Array of asset addresses
/// @return amounts Array of balance amounts (always non-negative magnitude)
/// @return isDebt Array of debt flags (true = debt, false = credit)
function getAdapterBalances(address account)
external
view
returns (address[] memory assets, uint256[] memory amounts, bool[] memory isDebt);
/// @notice Get single balance for a specific asset (gas-optimized version)
/// @param account The account to query
/// @param asset The asset address
/// @return amount Balance amount (non-negative magnitude)
/// @return isDebt True if debt, false if credit
function getAdapterBalanceForAsset(address account, address asset)
external
view
returns (uint256 amount, bool isDebt);
/// @notice Returns the list of all the underlying assets supported by this adapter
/// @dev The returned list may be empty if the adapter cannot determine or provide the supported assets
/// @return underlyingAssets The list of underlying asset addresses supported by this adapter (may be empty)
function underlyingAssetsSupported() external view returns (address[] memory underlyingAssets);
}
src/balances/IBalances.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @author KPK
interface IBalances {
//
// Type definitions
//
enum AdapterType {
Default,
Custom
}
struct BalanceAdapter {
address adapter;
AdapterType adapterType;
string protocol;
}
//
// Events
//
/// @notice Event emitted when a balance adapter is added to the global registry.
/// @param underlyingAsset Reserved; currently address(0) as adapters are registered globally, not per asset.
/// @param adapter The address of the adapter being added.
/// @param adapterType The type of the adapter (Default or Custom).
event BalanceAdapterAdded(address indexed underlyingAsset, address indexed adapter, AdapterType adapterType);
/// @notice Event emitted when a balance adapter is removed from the global registry.
/// @param underlyingAsset Reserved; currently address(0) as adapters are global.
/// @param adapter The address of the balance adapter being removed.
event BalanceAdapterRemoved(address indexed underlyingAsset, address adapter);
//
// Errors
//
/// @notice Error when the balance adapter is not set.
error BalanceAdapterNotSet();
/// @notice Error when the balance adapter is not valid.
error InvalidBalanceAdapter();
/// @notice Error when the balance adapter type is not valid.
error InvalidBalanceAdapterType();
/// @notice Error when the same balance adapter is already set.
error DuplicateBalanceAdapter();
/// @notice Error when adding a meta-instance coordinate that is already present (would double-count NAV).
error DuplicateMetaInstance();
/// @notice The coordinate is already governed by a DIFFERENT registered meta adapter.
/// @dev Two adapters holding one coordinate both emit a well-formed leg for the same holding under
/// different reconciliation keys, and NAV sums them with no health flag. Rejected at configuration
/// time because no read-path guard can see across adapters.
error MetaInstanceClaimedByAnotherAdapter(bytes32 instance, address claimedBy);
/// @notice Error when removing a meta-instance coordinate that is not present in the adapter's set.
error MetaInstanceNotFound();
/// @notice Error when a meta-adapter (implements IMetaBalanceAdapter) is registered via the plain
/// addBalanceAdapters path; meta-adapters must use addMetaBalanceAdapter.
error MetaAdapterNotAllowed();
/// @notice Error when a meta-adapter operation (registration via addMetaBalanceAdapter, or an
/// addMetaInstances / removeMetaInstances call) targets an adapter that is not a meta-adapter
/// (does not implement IMetaBalanceAdapter).
error NotMetaAdapter();
/// @notice Validates that the adapter implements IBalanceAdapter (reverts with InvalidBalanceAdapter if not).
/// @dev Reverts with InvalidArguments if `adapter` is the zero address.
/// @param adapter The address of the adapter to check.
function checkBalanceAdapterSupport(address adapter) external view;
//
// Global Adapter Registry
//
/// @notice Returns all registered adapters in the global registry
/// @return adapters Array of all adapter addresses
function getAllAdapters() external view returns (address[] memory adapters);
/// @notice Returns the total number of registered adapters
/// @return count Total number of adapters
function getAdapterCount() external view returns (uint256 count);
/// @notice Checks if an adapter is registered in the global registry
/// @param adapter The adapter address to check
/// @return registered True if the adapter is registered
function isAdapterRegistered(address adapter) external view returns (bool registered);
/// @notice Returns the type of a registered adapter
/// @dev Reverts with InvalidBalanceAdapter if the adapter is not registered.
/// @param adapter The adapter address
/// @return adapterType The type of the adapter
function getAdapterType(address adapter) external view returns (AdapterType adapterType);
/// @notice Returns all adapters that support the given asset
/// @dev Loops through all global adapters and checks if the asset is in their underlyingAssetsSupported() list
/// @param asset The asset address to check
/// @return adapters Array of adapter addresses that support the asset
function getAdaptersForAsset(address asset) external view returns (address[] memory adapters);
//
// Meta-adapter instance registry (ADR 0010)
//
/// @notice Returns the configured meta-adapter instance coordinates for an adapter (empty for non-meta adapters).
/// @param adapter The adapter address.
/// @return instances The instance coordinates currently configured for the adapter.
function getMetaInstances(address adapter) external view returns (bytes32[] memory instances);
}
src/balances/IPositionDescribable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IPositionDescribable
/// @notice Optional interface for balance adapters that expose a human-readable protocol name for their positions.
/// @dev NAVCalculator's verbose read methods (`getAccountPositionsVerbose`, `getAccountPositionsForAssetVerbose`,
/// `getAccountNavVerbose`) call these via a fail-open staticcall — adapters that do not implement this
/// interface simply produce an empty protocol name / label set. Labels are derived **lazily from `positionId`**
/// (a static, per-position breadcrumb), so they are computed only in the verbose reads, not carried on every
/// `PositionBalance` (that keeps display work off the NAV hot path). The ephemeral per-item id (Uniswap V3 NFT
/// id, withdrawal request id, …) is NOT a label — it is the typed `PositionBalance.positionInstanceId` field.
/// Clients MUST NOT use these strings for identity, indexing, or reconciliation; use the typed
/// `protocolSubId` / `positionId` / `PositionKind` fields on `PositionBalance` for those purposes.
/// @author KPK
interface IPositionDescribable {
/// @notice Human-readable name of the PROTOCOL, e.g. "Aave V3", "Morpho", "Uniswap V3".
/// @dev **This names the protocol, never the product.** A protocol's individual products — Aave V3's Safety
/// Module and Umbrella, Morpho's vaults and markets, Balancer's pools and gauges — all return the SAME
/// string here; what distinguishes them is `positionLabels()` (`["Umbrella Module"]`, `["Safety Module"]`,
/// `["Market", "wstETH/USDC"]`) and the typed `protocolSubId`. Equivalently: every adapter sharing a
/// `ProtocolIds` protocol id MUST return the same name. Pull it from `src/utils/ProtocolNames.sol` rather
/// than writing a literal — new and changed adapters should reference the constant; the pre-existing
/// literals are being migrated adapter by adapter and are meanwhile pinned to their constants by
/// `test/ProtocolNameConsistency.t.sol`. Meta-adapters need no literal at all (see below).
///
/// Why the distinction is load-bearing rather than cosmetic: consumers group *configured adapters* by this
/// string. The typed `protocolBrand`/`protocolId`/`protocolSubId` would group them correctly, but they are
/// `private constant` and only ride on `PositionBalance` structs returned by an **account** read — a
/// consumer enumerating registered adapters never sees them, so the display name is the only protocol
/// identity it has. An adapter that returns its product name here splits itself out into a phantom sibling
/// protocol (`AaveUmbrellaBalanceAdapter` returned "Aave Umbrella" and did exactly that).
///
/// Per-instance adapters return a compile-time constant. Meta-adapters **derive** it —
/// `MetaBalanceAdapter.protocolName()` is `ProtocolNames.forProtocolId(_protocolId())` — so for the whole
/// meta family the invariant holds by construction: the name is a pure function of the typed identity the
/// adapter already declares, with no constructor argument or config value that could disagree with it.
function protocolName() external view returns (string memory);
/// @notice Ordered, arbitrary-depth display hierarchy for a single position, BELOW the protocol level.
/// Index 0 is the broadest level (category) and the last element is the position leaf, e.g.
/// `["Market", "wstETH/USDC"]`, `["AMM Liquidity Pool", "WETH/USDC 0.05%"]`, or `["Safety Module"]` when the
/// category itself is the leaf. The full breadcrumb a consumer renders is
/// `[protocolName(), ...positionLabels(positionId)]`. Derived purely from `positionId` (the static
/// anchor) — the ephemeral per-item id rides in `PositionBalance.positionInstanceId`, not here.
/// @param positionId The ABI-encoded position identifier (same bytes as `PositionBalance.positionId`).
/// @return An array of display segments. An empty array is acceptable when no label can be derived.
/// Depth varies by adapter and position; consumers must not assume a fixed length.
///
/// **When there is no account to get a positionId from** — a configuration view listing what the
/// NAVCalculator is set up to account for — an adapter whose breadcrumb is positionId-independent
/// answers `positionLabels("")` with its full constant breadcrumb, and that is the whole answer. An
/// adapter whose breadcrumb is derived per positionId returns `[]` instead and should implement
/// {IPositionEnumerable}, whose `positionIds()` lists the shapes to pair with this function and whose
/// ERC-165 bit is what distinguishes that `[]` from a broken adapter. See {IPositionEnumerable}.
function positionLabels(bytes calldata positionId) external view returns (string[] memory);
}
src/balances/RegisteredAssetLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
/// @title RegisteredAssetLib
/// @author KPK
/// @notice Shared helper for resolving a registered asset's metadata out of a NAVCalculator
/// `getRegisteredAssets()` snapshot. Many balance adapters need this find-by-address scan to look up the
/// `symbol`/`decimals` of a token they value — single-underlying adapters resolve one fixed token
/// (Lido, Stader, ether.fi, StakeWise V3, Kelp withdrawal/exit queues; Nexus Mutual staking pools), while
/// others resolve several tokens per call (Uniswap V3 looks up both pool tokens; Merkl rewards resolve an
/// arbitrary token list).
/// Centralising the scan here removes the hand-rolled copies that previously lived in each adapter.
/// @dev `internal` functions only, so this library is inlined into each caller's bytecode — it is NOT a linked/pinned
/// external library (no CREATE2 address, no `foundry.toml [libraries]` entry, no effect on the PriceFeedLib /
/// NAVRegistryLib pins).
library RegisteredAssetLib {
/// @notice Finds `asset` in a pre-fetched `getRegisteredAssets()` snapshot.
/// @param reg The registry snapshot (caller fetches it once via `NAV_CALCULATOR.getRegisteredAssets()`).
/// @param asset The asset address to resolve.
/// @return assetInfo The matching `Asset` (zeroed if not found).
/// @return found True if `asset` is registered.
function find(INAVCalculator.Asset[] memory reg, address asset)
internal
pure
returns (INAVCalculator.Asset memory assetInfo, bool found)
{
for (uint256 i = 0; i < reg.length; i++) {
if (reg[i].asset == asset) {
return (reg[i], true);
}
}
return (INAVCalculator.Asset({asset: address(0), symbol: "", decimals: 0}), false);
}
}
src/constants.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
uint8 constant NAV_DECIMALS = 8;
// Maximum safe exponent for 10^N calculations (max uint8 is 255)
// Used to prevent overflow in decimal exponentiation operations
uint256 constant MAX_DECIMAL_EXPONENT = 255;
// Maximum exponent such that 10^N fits in int256 (10^77 > type(int256).max)
uint256 constant MAX_DECIMAL_EXPONENT_INT256 = 76;
// Define the MANAGER role ID, used across NAVCalculator and bridge system for operational management
bytes32 constant MANAGER = keccak256("MANAGER"); // 0xaf290d8680820aad922855f39b306097b20e28774d6c1ad35a20325630c3a02c
/// @dev Gates the SUBMIT surface of the attested balance-adapter family (ADR 0022). Deliberately NOT used to gate
/// the family's clears — those stay permissionless and stale-gated, because role-gating removal is what audit
/// finding L-02 flagged: a compromised role-holder could delete valid LIVE allocations.
bytes32 constant SUBMITTER = keccak256("SUBMITTER");
bytes32 constant DEFAULT_ADMIN_ROLE = 0x00;
src/errors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
error InvalidArguments();
error InvalidArgumentsWithContext(string context);
/// @notice A constructor argument expected to be a deployed contract has no code. `name` is the dependency label.
error NotAContract(string name);
error NotAuthorized();
error NotChainlinkOracle();
/// @notice Thrown when an assistant entrypoint that must be delegatecalled is called directly on the singleton
/// (`address(this) == SELF`). Canonical delegatecall-guard error for the assistant-fed family (`BalanceAdapterAssistant`).
error NotDelegateCall();
/// @notice An assistant entrypoint was told to track/act for an account other than the executing context
/// (`address(this)`, i.e. the delegatecalling Safe). Canonical assistant self-scope check (`_requireSelf`).
error AssistantAccountMismatch(address expected, address provided);
// Permissionless assistant-fed assisted balance-adapter family (ADR 0018) — shared coordinate-cache errors, used by the
// single {AssistedCoordCache} base (every coordinate is an `abi.encode`d blob). The coordinate is identified by `id`
// (a tokenId / requestId / positionTicket, from `_coordId`); the full tuple, where richer, rides in the cache's events.
/// @notice `submit` was given a coordinate not currently owned by the caller (`msg.sender`).
error CoordinateNotOwned(address account, uint256 id);
/// @notice `submit` would grow the caller's cache past its per-account cap.
error CoordinateCacheFull(address account, uint256 maxCoordinates);
/// @notice `remove` targeted a coordinate not in the caller's cache.
error CoordinateNotCached(address account, uint256 id);
/// @notice `remove` targeted a coordinate the caller still owns (a live position) — refused so a live position is never
/// dropped (would under-report the caller's own NAV). Only a claimed/consumed coordinate may be removed.
error CoordinateStillLive(address account, uint256 id);
/// @notice `submit` was given a coordinate that failed the adapter's write-time protocol validation (e.g. an
/// unregistered target). Distinct from {CoordinateNotOwned} (ownership) — this is a malformed/invalid coordinate.
error InvalidCoordinate(address account, uint256 id);
// Bridge-specific errors
error AlreadyInitialized();
error InvoiceNotFound();
error InvoiceAlreadyExists();
error InvalidInvoiceStatus();
error InvalidInvoice();
error TransferFailed();
error InsufficientBalance(address asset, uint256 required, uint256 available);
error InvalidChainId();
error InvalidNonce();
error InvalidCompletionData();
error InvalidChecksum(bytes32 invoiceId, bytes24 provided, bytes24 calculated);
error InvalidTimestamp(uint64 provided, uint64 current);
error AssetHasActiveInvoices(string symbol);
error AssetNotRegistered(string symbol);
// NAV Calculator / registry errors
error PriceFeedNotSet(address asset);
error AssetNotFound();
error OnlyNAVCalculator();
error ArrayLengthMismatch();
error InvalidAssetDecimals();
error InvalidDecimalExponent();
src/nav/INAVCalculator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IBalances} from "src/balances/IBalances.sol";
import {IPrices} from "src/prices/IPrices.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
/// @title INAVCalculator
/// @notice Interface for the NAV Calculator contract. Defines the full API for asset registration, price feeds,
/// balance adapters, and NAV/position queries in one or more quote currencies.
/// @dev Extends IBalances for adapter registry and IPrices for price feed types. Implementations are typically
/// UUPS-upgradeable and use AccessControl (MANAGER for mutations, DEFAULT_ADMIN_ROLE for upgrades).
/// @author KPK
interface INAVCalculator is IBalances {
/// @notice A balance adapter consumed the gas stipend the NAV read forwarded to it without answering.
/// @dev Deliberately NOT folded into the read's fail-open path. A revert means "this adapter has nothing to
/// report"; running out of gas means "this adapter's answer is unknown", and reporting an unknown answer
/// as an empty one drops the adapter's legs — a dropped debt leg RAISES the reported NAV.
///
/// Declared here rather than alongside the shared errors so it reaches consumers: it is raised inside a
/// DELEGATECALLed library, and an error a contract never names itself does not appear in that contract's
/// ABI. Callers generate against this interface and the NAVCalculator implementing it, so a revert they
/// can actually decode has to be part of it.
///
/// `adapter` names the adapter that was running, which is not always the adapter at fault: the stipend is
/// a share of what the READ still holds, so an under-funded call starves whichever adapter happens to be
/// reached last. `stipend` and `consumed` are what separate the two cases. A large `stipend` fully
/// consumed means that adapter is genuinely runaway; a small `stipend` means the read itself was short of
/// gas and the fix is to supply more.
/// @param adapter The adapter that was executing when its gas ran out.
/// @param stipend The budget the classification was measured against: 63/64 of what the read held just before
/// the call. It is NOT precisely what the EVM forwarded — the same 63/64 rule is applied again at the
/// CALL itself, to a figure already reduced by building the calldata — so on a genuine exhaustion
/// `consumed` lands a few tens of gas ABOVE it. Read the two as a ratio, not as a balance.
/// @param consumed Gas the call actually cost this frame, including the call overhead.
error AdapterGasExhausted(address adapter, uint256 stipend, uint256 consumed);
/// @notice One governed instance of a meta-adapter consumed its gas stipend without answering.
/// @dev The {AdapterGasExhausted} sibling, one frame in. A meta-adapter isolates each instance behind its own
/// `try`/`catch` so a single faulty instance cannot zero out the batch, and that isolation has the same
/// blind spot: an instance that runs out of gas is indistinguishable from one that reverted, and recording
/// it as "no positions" drops its legs while the meta-adapter still RETURNS SUCCESSFULLY — so the caller
/// sees a complete-looking answer. A dropped debt leg raises the reported NAV.
///
/// Raised rather than swallowed. `PriceFeedLib` keys on this selector explicitly rather than re-deriving
/// exhaustion from gas, so a cheap early raise here cannot be re-scored as a benign revert one frame out.
///
/// `instance` is where the budget ran out, which is NOT the same as where it went. The fan-out gives each
/// instance a share of whatever its predecessors left, so a single runaway instance early in the governed
/// set can leave the NEXT one too little and get it named instead. Read the pair together: a large
/// `stipend` fully consumed means that instance is genuinely runaway; a small `stipend` means it was
/// starved by something before it, or the read was under-funded to begin with. Removing the named instance
/// is the wrong first move when `stipend` is small.
/// @param adapter The meta-adapter that was fanning out. Overwritten by `PriceFeedLib` with the address it
/// actually called, so it is trustworthy even when the rest of the payload is not.
/// @param instance The governed instance coordinate whose read ran out of gas — see the caveat above.
/// @param stipend The budget the classification was measured against: 63/64 of what the fan-out held just
/// before the call. As with {AdapterGasExhausted} it is NOT precisely what the EVM forwarded — the same
/// rule is applied again at the CALL — so `consumed` lands slightly above it. A ratio, not a balance.
/// @param consumed Gas the instance call actually cost, including the fan-out's call overhead.
error InstanceGasExhausted(address adapter, bytes32 instance, uint256 stipend, uint256 consumed);
/// @notice {getAccountNavForAdapters} was given an empty adapter list.
/// @dev Not silently answered with a zero NAV. An empty slice is indistinguishable from "this portion of the
/// portfolio is worth nothing", and a caller that built its slice list from a stale or mis-parsed source
/// would read that zero as a real answer and reassemble a NAV that is short by exactly the adapters it
/// forgot to ask for. Declared here rather than in `src/errors.sol` for the same reason as
/// {AdapterGasExhausted}: it is raised inside a DELEGATECALLed library, so it only reaches consumers'
/// generated ABIs by being named in this interface.
error EmptyAdapterSlice();
/// @notice {getAccountNavForAdapters} was given an adapter that is not in the global registry.
/// @dev The registry is `getAllAdapters()` — the exact list the complete read scans — so "registered" here
/// means "would have been included in `getAccountNav`". Rejected rather than skipped: an unregistered
/// address (a decommissioned adapter, a typo, an address from another chain) has no positions to report,
/// so skipping it would return a well-formed slice whose `value` is silently missing whatever the caller
/// believed that address covered — and whose `adaptersCovered` would then have to either echo an address
/// that contributed nothing or omit one the caller asked for. Both mislead the coverage check that
/// `adaptersCovered` exists to support.
/// @param adapter The supplied address that is not a registered balance adapter.
error AdapterNotRegistered(address adapter);
/// @notice {getAccountNavForAdapters} was given the same adapter twice in one slice.
/// @dev A repeated adapter is queried twice and its positions summed twice, so the slice over-reports by that
/// adapter's whole value. Rejected rather than deduplicated, because a duplicate means the caller's
/// partition logic is wrong and the same defect will be producing overlaps ACROSS slices — which this
/// contract cannot see and silently deduplicating here would hide. Cross-slice overlap is what
/// `PartialNAV.adaptersCovered` is for.
/// @param adapter The address that appeared more than once.
error DuplicateAdapterInSlice(address adapter);
//
// Structs
//
/// @notice Registered asset metadata used by the NAV/Pricing registry and balance adapters.
/// @param asset Token address (or NATIVE_ADDRESS for chain native token).
/// @param symbol Display symbol (e.g. "ETH", "USDC").
/// @param decimals Number of decimals for amounts.
struct Asset {
address asset;
string symbol;
uint8 decimals;
}
/// @notice Balance-only position data returned by balance adapters (no pricing).
/// @dev NAVCalculator enriches these with pricing to produce Position structs.
/// @param balanceAsset Asset metadata (address, symbol, decimals). The token `amount` is denominated in.
/// @param balanceAdapter Address of the adapter that reported this position. Provenance / audit trail — NOT part of identity.
/// @param amount Balance magnitude (always positive); sign is implied by isDebt.
/// @param isDebt True if debt (subtract from NAV), false if credit (add to NAV). Canonical NAV-sign signal.
/// @param protocolBrand `keccak256` of the protocol brand slug (version-stripped, e.g. `aave`, `balancer`; see
/// `src/utils/ProtocolIds.sol`). The broadest roll-up layer — several `protocolId`s share it
/// (`aave-v3` → `aave`; `balancer-v2` + `balancer-v3` → `balancer`). Display/grouping only; NOT part of the
/// stable identity key. Equals `protocolId` for unversioned protocols.
/// @param protocolId `keccak256` of the broad protocol-ecosystem slug (e.g. `aave-v3`, `curve`; see
/// `src/utils/ProtocolIds.sol`). A roll-up / grouping key only — several `protocolSubId`s share it
/// (e.g. `aave-v3-lending` + `aave-v3-safety-module` both roll up to `aave-v3`). NOT part of the stable
/// identity key (it is functionally determined by `protocolSubId`).
/// @param protocolSubId `keccak256` of the specific protocol-product slug (e.g. `aave-v3-lending`; see
/// `src/utils/ProtocolIds.sol`). Selects the `positionId` ABI-decode schema — one sub-slug implies exactly
/// one schema — and is the protocol component of the stable identity key. Equals `protocolId` for
/// single-product ecosystems.
/// @param positionId ABI-encoded position identifier. Decode schema is determined by `protocolSubId`.
/// e.g. for AAVE_V3_LENDING: `abi.encode(address pool)`.
/// Full schema table: see `src/utils/ProtocolIds.sol` and docs/howto/position-identity-schema.md.
/// @param positionKind Semantic discriminator (Wallet / Supplied / Borrowed / Collateral / Staking / Rewards / Fees).
/// Together with `protocolSubId` and `positionId` forms the stable per-chain identity key
/// `(chainId, protocolSubId, positionId, balanceAsset.asset, positionKind)`.
/// @param isLocked True if this leg is NOT withdrawable right now (the pending portion of a withdrawal queue, or a
/// staked amount in/awaiting its unstaking cooldown); false if fully liquid / claimable now. Withdrawal-queue
/// and cooldown adapters keep a STATIC, timeless `positionId` (the queue/manager/asset/vault/stake-token
/// coordinate) and split an account's holding into up to two legs — a claimable leg (`isLocked=false`) and a
/// locked leg (`isLocked=true`). `isLocked` is a **mutable per-leg attribute, NOT part of the identity key**:
/// a leg flips `true→false` as its portion finalizes/unlocks, so keying on it would split one economic
/// position into two keys over its lifetime. The claimable and locked legs therefore share ONE key and are
/// **summed** in reconciliation (the sum is the full holding); read `isLocked` per leg for the
/// claimable-vs-locked breakdown. `false` for every adapter except withdrawal-queue / cooldown legs.
/// @param positionInstanceId OPTIONAL EPHEMERAL per-item coordinate as a `bytes32` — a Uniswap V3 / PancakeSwap V3
/// NFT id, a withdrawal/exit request id, or a StakeWise exit ticket (each a `uint256` widened to `bytes32`).
/// `bytes32(0)` for adapters with no per-item granularity. It is the SOLE ephemeral identity field, by
/// design: the **stable** reconciliation key
/// `(chainId, protocolSubId, positionId, balanceAsset.asset, positionKind)` deliberately EXCLUDES it,
/// so the legs of one anchor sum and identity survives item churn. A consumer that wants per-item
/// granularity MAY append `positionInstanceId` to the key — gaining one position per item, at the cost of an
/// **ephemeral** key (it blinks in/out as items are minted/burned/claimed). Never use it for stable
/// identity. (Stable sub-distinguishers like an Aave reserve are NOT here — they live in `balanceAsset`.)
/// Typed as `bytes32` (not `bytes`): every current coordinate is a single `uint256`, and a value type keeps
/// the position-building/copy loops under the via_ir stack limit.
struct PositionBalance {
Asset balanceAsset;
address balanceAdapter;
uint256 amount;
bool isDebt;
bytes32 protocolBrand;
bytes32 protocolId;
bytes32 protocolSubId;
bytes positionId;
PositionKind positionKind;
bool isLocked;
bytes32 positionInstanceId;
}
/// @notice Enriched position including pricing and quote-currency value.
/// @dev Returned by getAccountPositions and getAccountPositionsForAsset.
/// @param balanceAsset Asset metadata from registry (canonical symbol/decimals).
/// @param balanceAdapter Adapter that reported the balance.
/// @param amount Balance magnitude (positive); sign implied by isDebt.
/// @param isDebt True if debt, false if credit.
/// @param quoteAsset Quote currency for value (e.g. USD when address(0)).
/// @param value Value in quote asset (negative for debt).
/// @param price Price used (e.g. USD per unit of asset).
/// @param priceDecimals Decimals of price.
/// @param stale True if the price was stale at query time.
/// @param protocolBrand `keccak256` protocol brand slug (broadest grouping). Copied from PositionBalance.
/// @param protocolId `keccak256` broad ecosystem slug (grouping). Copied from PositionBalance.
/// @param protocolSubId `keccak256` specific protocol-product slug (identity-key component). Copied from PositionBalance.
/// @param positionId ABI-encoded position identifier. Copied from PositionBalance.
/// @param positionKind Semantic discriminator. Copied from PositionBalance.
/// @param isLocked True if the leg is not withdrawable now (pending/cooling). Copied from PositionBalance.
/// @param positionInstanceId Ephemeral per-item coordinate (NFT/request/ticket), or empty. Copied from
/// PositionBalance; excluded from the stable identity key. See PositionBalance.
struct Position {
Asset balanceAsset;
address balanceAdapter;
uint256 amount;
bool isDebt;
Asset quoteAsset;
int256 value;
int256 price;
uint8 priceDecimals;
bool stale;
// True if the quote asset's own price feed was stale. When true, `value` is in USD (8dp) even though
// `quoteAsset` is non-zero — the quote conversion was skipped. Mirrors NAV.quoteAssetStale ([9]/S2).
bool quoteAssetStale;
bytes32 protocolBrand;
bytes32 protocolId;
bytes32 protocolSubId;
bytes positionId;
PositionKind positionKind;
bool isLocked;
// Ephemeral per-item coordinate copied from PositionBalance (NFT id / request id / ticket as bytes32).
// bytes32(0) when none. Display/granularity only — excluded from the stable identity key. See PositionBalance.
bytes32 positionInstanceId;
// True if the asset's primary price diverged from its monitor feeds beyond the configured tolerance (or,
// for stablecoins, from the $1 peg). A pricing-quality signal, NOT a validity/staleness flag: `price` and
// `value` are still populated from the primary. Consumers (e.g. the sub/redeem processor) decide how to react.
// APPENDED (not inserted mid-struct) so an in-place UUPS upgrade doesn't shift existing fields' ABI offsets.
bool irregular;
// True if the quote (unit-of-account) asset's own primary diverged from its monitors — the divergence
// counterpart to `quoteAssetStale`. Always false for a USD quote.
bool quoteAssetIrregular;
}
/// @notice Position enriched with human-readable display labels.
/// @dev ⚠️ **NEITHER `protocolName` NOR ANY element of `labels` is necessarily the adapter's own value.**
/// `AssetKindRegistry` holds an optional per-ADAPTER protocol name plus a per-ADAPTER, per-SEGMENT `labels`
/// override, and {PriceFeedLib.toVerbose} applies both in preference to the adapter's reply.
///
/// ⚠️ **Two earlier revisions of this line were narrower than the code, in the same direction each time.**
/// The first said the computed leaf was never overridable; the second said only `labels[0]` was. Both are now
/// false: {IAssetKindRegistry.setAdapterLabels} writes at ANY index, bounded only by
/// `min(reply.length, override.length)` — so the honest statement is that a segment comes from the adapter
/// **unless an operator overrode that index**, and `""` at an index is how an operator declines to.
///
/// What the override CANNOT do is change the array's LENGTH: it never writes past the adapter's own reply and
/// never extends it, so `labels.length` is always the adapter's answer. (The one exception is
/// `getAdapterDisplayInfo`, whose empty-reply case is deliberately grown — see
/// `PriceFeedLib.adapterDisplayInfo`.)
///
/// Which segments an operator SHOULD write is a property of the adapter, not of this struct;
/// `src/balances/BALANCE_ADAPTERS.md` §6.2 carries the per-adapter sweep, and
/// `ERC20DefaultBalanceAdapter` is the one adapter that must not be overridden at all (its single element is
/// the computed token symbol, not a category). `AdapterLabelOverrides.t.sol
/// ::test_labelsOverride_onLeafOnlyAdapter_replacesTheLeaf_documentedHazard` asserts that hazard.
/// Consumers must not treat these strings as identity in any case; see {IPositionDescribable}.
/// @dev Returned by verbose read methods. Labels are sourced from the adapter's `IPositionDescribable`
/// implementation (`positionLabels(positionId)`, via a fail-open staticcall) and are empty otherwise. MUST NOT
/// be used for identity, indexing, or reconciliation — use the typed fields on `position` for those purposes.
struct VerbosePosition {
Position position;
string protocolName; // e.g. "Aave V3", "Morpho"
// Ordered display hierarchy BELOW the protocol, leaf last (arbitrary depth, may be empty), e.g.
// ["Market", "wstETH/USDC"] or ["AMM Liquidity Pool", "WETH/USDC 0.05%"]. Full breadcrumb = [protocolName,
// ...labels]. Sourced from IPositionDescribable.positionLabels(positionId); display only. The ephemeral
// per-item id (NFT/request/ticket) is NOT here — it is the typed `position.positionInstanceId` field.
string[] labels;
}
/// @notice NAV snapshot bundled with a full verbose position breakdown.
// forge-lint: disable-next-line(pascal-case-struct)
struct VerboseNAV {
NAV nav;
VerbosePosition[] positions;
}
/// @notice NAV snapshot for an account in a given quote currency.
/// @param value Total portfolio value in quoteAsset (can be negative if net debt).
/// @param quoteAsset Quote currency; address(0) denotes USD.
/// @param timestamp Block timestamp of the reading.
/// @param stalePriceAssets Assets whose prices were stale at query time.
/// @param irregularPriceAssets Assets whose primary price diverged from their monitor feeds beyond tolerance
/// (or, for stablecoins, from the $1 peg) at query time. A pricing-quality signal, not a staleness flag —
/// `value` is still computed from the primary prices. Consumers decide how to react.
/// @param sequencerDown True if the L2 sequencer was down or in grace period (L2 only).
/// @param quoteAssetStale True if the quote asset's own price feed was stale. When true the value field
/// is in USD (fallback) even though quoteAsset is non-zero — callers must check this flag before
/// interpreting value as being in the requested quote currency.
/// @param monitorsUnhealthyPriceAssets Assets that **have monitor feeds configured but where none of them was
/// readable** at query time — every monitor stale, reverting, or reporting a non-positive price. For these
/// the divergence check silently did not run: `divergenceBps` is 0 because the arithmetic never executed,
/// not because the prices agreed, so absence from `irregularPriceAssets` says nothing about them. Without
/// this list "checked and clean" and "checked by nothing that answered" are the same bytes.
///
/// **This is NOT the "no monitors configured" case.** That is a static configuration property, derivable
/// off-chain from **`getMonitorFeedCount(asset) == 0` alone**, and it is deliberately excluded here — an
/// asset with nothing configured never appears in this list however long it goes unchecked. What this
/// reports is strictly a *runtime* failure of monitors that exist.
///
/// Do NOT additionally require `getAssetPricing(asset).divergenceToleranceBps == 0` for that derivation:
/// the conjunction is UNSATISFIABLE for any asset that ever had a monitor. `_setDivergenceTolerance`
/// rejects 0, so once a tolerance is set it can never be returned to zero, while `removeMonitorFeed`
/// leaves the tolerance untouched — so an asset whose monitors were all REMOVED has count 0 and a
/// non-zero tolerance, and an AND-recipe would silently never flag it. The tolerance only returns to 0
/// via full asset unregistration (`_removeAllMonitorFeeds`), by which point the asset is gone anyway.
///
/// Assets whose own primary is unusable are also excluded — stale feed, sequencer down, or a primary whose
/// 8-decimal normalisation degenerates to zero. In all of those the check was suppressed by the PRIMARY
/// rather than by the monitors, `stalePriceAssets` already reports the staleness cases, and naming the
/// monitors would point an operator at the wrong contract. Stablecoins with a non-zero `pegToleranceBps`
/// may appear here and still be peg-checked — the peg guard is monitor-independent — so this flags the
/// loss of the *divergence* check, not necessarily of all checks.
///
/// **Scope: assets this account holds positions in**, like `stalePriceAssets` and `irregularPriceAssets`.
/// It is built from the assets the account's positions touched, NOT from the whole registry, so absence
/// means "monitors healthy **or** no position held". A consumer reconciling against the registry-wide
/// per-asset view (`getPriceDivergence(asset).monitorFeedCount == 0` is the equivalent there) will see
/// differences that are this scoping, not a defect. Note also that `healthCheck()` — which DOES iterate
/// the whole registry — deliberately does not carry this array: `NAVCalculator` is 68 bytes from the
/// EIP-170 limit, so widening that return was not affordable. `Position.irregular` on
/// `getAccountPositions` likewise retains the original ambiguity, with no `NAV` struct alongside to join
/// against; use `getAccountNavVerbose` (whose `VerboseNAV` embeds the `NAV`) if you need both.
// forge-lint: disable-next-line(pascal-case-struct)
struct NAV {
int256 value;
Asset quoteAsset;
uint64 timestamp;
Asset[] stalePriceAssets;
bool sequencerDown;
bool quoteAssetStale;
// APPENDED (not inserted mid-struct) so an in-place UUPS upgrade doesn't shift existing fields' ABI offsets.
Asset[] irregularPriceAssets;
// True if the quote (unit-of-account) asset's own primary diverged from its monitors beyond tolerance —
// the divergence counterpart to `quoteAssetStale`. Always false for a USD quote (no quote feed).
//
// DECLARED GAP, deliberate: there is no `quoteAssetMonitorsUnhealthy` counterpart to
// `monitorsUnhealthyPriceAssets` below. For a non-USD quote whose own monitors have ALL gone unreadable, this
// flag is false for want of data — exactly the ambiguity that array exists to close — and nothing surfaces it.
//
// Why it was not added, in order of weight. (1) **Nothing in this repository's configuration exercises it**:
// `nav-config/assets-and-price-feeds/{1,42161,8453,100}.json` contain no quote keys, and `quoteAsset` is a
// CALLER-supplied parameter defaulting to USD (`address(0)`), not stored config — so the gap is reachable only
// by a caller that opts into a non-USD quote. (2) `NAVCalculator` has 68 bytes of EIP-170 headroom; a further
// struct member plus its computation plausibly exceeds that, and spending the last of the margin on an
// unexercised path would leave nothing for an urgent fix — after which the next change would need a new proxy
// rather than an upgrade.
//
// Limit of that evidence: it is a claim about THIS repository only. A downstream consumer (share layer,
// portal, agents, subgraphs) could pass a non-zero `quoteAsset`, which cannot be verified from here. If one
// does, this gap is worth the bytes and should be revisited.
//
// Mitigation meanwhile: a caller using a non-USD quote should read `getPriceDivergence(quoteAsset)` and treat
// `monitorFeedCount == 0` alongside a usable primary as exactly this condition.
bool quoteAssetIrregular;
// APPENDED for the same reason as `irregularPriceAssets` above. This redeploy uses a NEW proxy rather than an
// in-place upgrade, so nothing forced the append — but moving existing consumers' ABI offsets for a change
// that did not need to move them is gratuitous, so the convention is honoured anyway.
Asset[] monitorsUnhealthyPriceAssets;
}
/// @notice One SLICE of an account's NAV: the same snapshot as {NAV} but covering only the balance adapters
/// named in the request, plus the list of adapters it actually covered.
/// @dev Returned by {getAccountNavForAdapters}. Deliberately a DISTINCT type from {NAV}, not a reuse of it,
/// and that is the whole safety property of this API: a partial result must not be assignable, passable
/// or decodable where a complete NAV is expected. A `PartialNAV` that type-checked as a `NAV` would let a
/// caller hand one slice to a consumer that believes it holds the whole portfolio — the exact silent
/// under-report pagination exists to make impossible. The cost is that a caller must reassemble
/// explicitly; that cost is the point.
///
/// **Field order mirrors {NAV} exactly for its first eight fields, including NAV's own appended ones, so
/// a decoder written for `NAV` maps 1:1 onto this struct's prefix.** `adaptersCovered` is appended last.
/// Keep it that way: any future field goes at the END of this struct (see the APPENDED note on {NAV}),
/// and any field appended to {NAV} must be appended here too — BEFORE `adaptersCovered` if the prefix
/// correspondence is to survive, which means moving `adaptersCovered` and accepting the ABI shift, or
/// accepting that the prefix correspondence ends there. Prefer the latter: shifting a field's offset in a
/// struct a live off-chain reassembler decodes is worse than losing a documentation convenience.
/// @param value Net value of THIS SLICE's positions in `quoteAsset`, signed (negative if the slice is net
/// debt). **This is the one field that sums.** Debt legs are already negative, and prices are per-asset
/// and independent of which adapter reported the position, so the arithmetic is exact: summing `value`
/// over a partition of `getAllAdapters()` reproduces `getAccountNav().value` bit-for-bit, with no
/// tolerance and no rounding slack. Every other field below does NOT sum.
///
/// **One precondition, and it is not theoretical: no adapter may have been GAS-STARVED in either read.**
/// Some adapters fail open inside their own frame and return SUCCESSFULLY having dropped legs —
/// `AssistedCoordCache._collect` isolates each cached coordinate behind an UNCAPPED
/// `try this.valueCoordSelf(…)`/`catch {}`, and `ERC20DefaultBalanceAdapter` records 0 for an asset whose
/// `balanceOf` staticcall fails. Nothing upstream can see that; see the "Scope, stated plainly" note on
/// `PriceFeedLib._getAdapterPositions`.
///
/// The per-adapter stipend is a share of what the READ still holds at the moment that adapter is reached,
/// and `computeNav` scans the supplied array IN ORDER. So the stipend depends on **slice composition AND
/// ORDERING**, not merely on how few adapters a slice names. Both directions are reachable:
/// a singleton slice gives its adapter more gas than the full scan did and may value legs the complete
/// read dropped; a multi-adapter slice that places an adapter BEHIND an expensive one can starve it below
/// what the complete read gave it. The second case is not hypothetical — `getAllAdapters()[0]` is
/// permanently `ERC20DefaultBalanceAdapter` (pushed in `initialize`, unremovable, and swap-and-pop only
/// ever fills a hole at the removed index, which index 0 can never be), so the complete read already
/// hands it the largest stipend any read can and **a slice can only ever give it less.**
///
/// Which read ends up LARGER is a separate question from which one was starved. The sign of the skew is
/// set by the `isDebt` of the dropped legs, not by which read dropped them: a dropped credit leg lowers
/// that read, a dropped debt leg raises it.
///
/// **Therefore: do NOT assume a direction, and do not pick by magnitude either.** "Trust the slice" is
/// wrong, and so is "take the lower" — with today's credit-only absorbers starvation can only LOWER a
/// read, so "take the lower" would select the starved number every time the two disagree. Nor is
/// under-reporting a safe default: a processor pricing shares off a low NAV over-issues to a subscriber.
/// Reconcile before publishing either. If a choice must be automated, key it to the SIGNAL rather than
/// the magnitude — prefer the read that did not raise {AdapterGasExhausted} / {InstanceGasExhausted}, and
/// publish neither if the two disagree while neither raised one. And do not treat the two reads agreeing
/// as a health check that passes silently — they agree when nothing was starved, which is the common case
/// and therefore uninformative.
///
/// The property that would keep a starved read from OVER-reporting is: **no adapter emits an
/// `isDebt == true` leg from behind ANY fail-open read.** "Any" is load-bearing — a gas CAP makes this
/// worse, not better, because an uncapped read can at least be rescued by supplying more gas whereas a
/// capped one (`StaticCallLib.PROBE_GAS`) is starved by the cap and drops unconditionally.
/// **Three shipped adapters currently break it** — `EulerVaultsMetaBalanceAdapter._safeDebt` (capped
/// probe, supply leg survives), `FluidVaultLib.aggregate` (uncapped, drops one NFT's supply and borrow),
/// and `GearboxV3CreditAccountsMetaBalanceAdapter._appendBorrow` (narrowly mitigated by a
/// `_debtReportable` gate evaluated before the gas is drained). None is introduced or fixed here, and the
/// first two over-report the COMPLETE read as much as a slice. See `docs/howto/read-nav-in-slices.md`.
/// @param quoteAsset Quote currency; `address(0)` denotes USD. Identical in every slice (it is the caller's
/// argument), so a reassembler can assert it rather than combine it.
/// @param timestamp Block timestamp of THIS call. A reassembler MUST check that every slice carries the same
/// value: differing timestamps mean the slices were read at different blocks, and a NAV assembled from
/// positions priced at different blocks is not a NAV of anything. See the caller contract on
/// {getAccountNavForAdapters}.
/// @param stalePriceAssets Assets whose prices were stale, **restricted to the assets this slice's positions
/// touched**. NOT a portfolio-wide list: an asset that is stale but only held through an adapter in
/// another slice is absent here and present there. Must be UNIONED across slices, and the union
/// de-duplicated — two slices holding the same stale asset each report it.
/// @param sequencerDown True if the L2 sequencer was down or in grace period (L2 only). Derived from this
/// contract's sequencer config, not from the slice, so it is the same in every slice — but it is still
/// per-slice data and a caller that reads it on only one slice is relying on that invariant rather than
/// checking it. OR it across slices.
/// @param quoteAssetStale True if the quote asset's own price feed was stale, in which case `value` is in USD
/// (8dp) despite `quoteAsset` being non-zero. Also invariant across slices (it depends on the quote
/// asset, not the adapters) — which makes it *more* dangerous to ignore, not less: if it is true, every
/// slice's `value` is in USD, and a reassembler that never looked will label a USD total with the
/// requested quote currency. OR it across slices.
/// @param irregularPriceAssets Assets whose primary price diverged from their monitor feeds beyond tolerance
/// (or, for stablecoins, from the $1 peg), **restricted to the assets this slice touched**. Same
/// per-slice restriction and same union-and-dedupe requirement as `stalePriceAssets`. This is the depeg
/// signal; a slice-local read of it is a slice-local depeg picture.
/// @param quoteAssetIrregular True if the quote asset's own primary diverged from its monitors. Invariant
/// across slices, always false for a USD quote. OR it across slices.
/// @param monitorsUnhealthyPriceAssets Assets with monitors configured but none readable at query time,
/// **restricted to the assets this slice touched**. Same per-slice restriction and same
/// union-and-dedupe requirement as `stalePriceAssets` and `irregularPriceAssets` — it is built from the
/// same per-asset cache, so the semantics carry over unchanged. Reported on the paginated read
/// deliberately: a caller paginates because the complete read does not fit one `eth_call`, i.e. for the
/// largest accounts, and those are exactly the ones a monitoring consumer watches — omitting it here
/// would hide the signal from the accounts that most need it. A slice-local read is a slice-local
/// picture of monitor health, and a union over every slice is required before concluding an asset is
/// covered. See {NAV.monitorsUnhealthyPriceAssets} for what the condition does and does not mean.
/// @param adaptersCovered The adapters this slice actually queried — element-for-element identical to the
/// `adapters` argument, order included, because the call reverts rather than silently dropping, adding
/// or reordering one. That makes it a machine-checkable record rather than a restatement of the input:
/// the guarantee is that nothing came between the request and the scan. Its purpose is reassembly
/// verification: concatenate it
/// across every slice and compare against `getAllAdapters()`. A missing address means the assembled NAV
/// is short by that adapter's positions; a repeated one means it is double-counted. Neither is
/// detectable from `value` alone, because a short NAV is a perfectly plausible number.
// forge-lint: disable-next-line(pascal-case-struct)
struct PartialNAV {
int256 value;
Asset quoteAsset;
uint64 timestamp;
Asset[] stalePriceAssets;
bool sequencerDown;
bool quoteAssetStale;
Asset[] irregularPriceAssets;
bool quoteAssetIrregular;
// Appended after the {NAV}-mirroring prefix — see the struct-evolution note above. No longer the LAST
// member: `monitorsUnhealthyPriceAssets` was appended after it, deliberately, so this field keeps its ABI
// offset. New members go after that one, not here.
address[] adaptersCovered;
// Appended after `adaptersCovered` rather than beside its {NAV} siblings: keeping `adaptersCovered` at its
// existing offset matters more than keeping this struct's prefix a positional mirror of {NAV}, which it stops
// being the moment {NAV} grows. The two structs stay deliberately DISTINCT types — a partial result must not
// be decodable where a complete one is expected — so mirroring is a convenience, never a guarantee.
Asset[] monitorsUnhealthyPriceAssets;
}
/// @notice Price data for the freshest non-stale feed selected for an asset.
/// @dev When multiple feeds are registered, these fields describe the winning (freshest) feed.
/// When all feeds are stale, fields describe the first registered feed and stale == true.
/// @param priceFeed Address of the selected price feed contract.
/// @param priceType Feed type (Chainlink, Custom, Redstone, or API3).
/// @param price Current price (e.g. USD per unit); 0 when stale.
/// @param decimals Decimals of the selected feed's output.
/// @param chainlinkHeartbeat Staleness window (seconds) of the reported feed. For Chainlink/Redstone/API3 this is
/// the selected feed's configured heartbeat. For Custom feeds it is the GOVERNING leg's heartbeat — the
/// underlying Chainlink leg closest to its own staleness limit — paired with `updatedAt` below. A Custom
/// feed that successfully reports no trackable Chainlink leg gives 0; if its freshness read REVERTS this
/// field retains the registered config heartbeat (only `updatedAt` falls back to 0), so a non-zero value
/// here does not by itself imply a successful read. See ICustomPriceFeed.governingFeedFreshness.
/// @param updatedAt Last-update timestamp of the reported feed. For Chainlink/Redstone/API3 this is the selected
/// feed's `latestRoundData().updatedAt`. For Custom feeds it is the GOVERNING leg's `updatedAt` — a real,
/// matched pair with `chainlinkHeartbeat` above. 0 when the feed has no push timestamp or the read reverts.
/// @dev ADVISORY PAIR — `updatedAt`/`chainlinkHeartbeat` describe only the reported oracle leg's push freshness.
/// `stale` (and `sequencerDown`) is the AUTHORITATIVE staleness verdict: it also folds in the rate answer's
/// validity, the L2 sequencer state, and the feed's own configured heartbeat gate — none of which the pair
/// can express, so the pair can read "fresh" (age < heartbeat) while `stale` is true. Consumers MUST gate on
/// `stale`; never recompute a fresh/stale decision from `(updatedAt, chainlinkHeartbeat)` alone.
/// @param stale True if all feeds are stale or the L2 sequencer is down.
/// @param sequencerDown True if L2 sequencer is down (L2 only).
/// @param healthyFeedCount Number of registered feeds that passed all staleness gates on this read.
/// A value below the total registered feed count signals partial redundancy collapse and
/// should trigger off-chain alerting.
/// @param irregular True if the primary price diverged from the worst-case (furthest) healthy monitor feed
/// beyond the configured divergence tolerance, or (stablecoins) from the $1 peg beyond the peg tolerance.
/// @param divergenceBps Worst-case basis-point gap between the primary price and any single healthy monitor
/// price (0 when there are no healthy monitors or the primary is stale).
/// @param monitorFeedCount Number of healthy monitor feeds that contributed to the divergence computation.
struct PriceFeedData {
address priceFeed;
IPrices.PriceType priceType;
int256 price;
uint8 decimals;
uint256 chainlinkHeartbeat;
uint256 updatedAt;
bool stale;
bool sequencerDown;
uint256 healthyFeedCount;
bool irregular;
uint256 divergenceBps;
uint256 monitorFeedCount;
}
//
// Events
//
/// @notice Emitted when the Chainlink L2 sequencer uptime feed is updated.
/// @param oldChainlinkUptimeFeed Previous uptime feed address.
/// @param newChainlinkUptimeFeed New uptime feed address.
event ChainlinkUptimeFeedUpdated(address indexed oldChainlinkUptimeFeed, address indexed newChainlinkUptimeFeed);
/// @notice Emitted when the L2 sequencer grace period is updated.
/// @param oldSequencerGracePeriod Previous grace period in seconds.
/// @param newSequencerGracePeriod New grace period in seconds.
event L2SequencerGracePeriodUpdated(uint256 oldSequencerGracePeriod, uint256 newSequencerGracePeriod);
/// @notice Emitted when an asset is registered.
/// @param asset Registered asset address.
/// @param decimals Asset decimals.
event AssetRegistered(address indexed asset, uint8 decimals);
/// @notice Emitted when an asset is unregistered.
/// @param asset Unregistered asset address.
event AssetUnregistered(address indexed asset);
//
// Errors
//
/// @notice Thrown when the L2 sequencer uptime feed is not set but the grace period is being updated.
error UptimeFeedNotSet();
//
// Mutating functions (require MANAGER role)
//
/// @notice Registers an asset and sets its price feed.
/// @dev Fetches decimals/symbol from ERC20 or uses native token symbol. Adds asset to default adapter inclusion list.
/// @param asset Asset address to register (cannot be zero).
/// @param priceFeed Price feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero for all types).
function registerAsset(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
external;
/// @notice Adds a price feed for an already registered asset, or UPDATES the heartbeat of one already there.
/// @dev UPSERTS. If `priceFeed` is already registered for `asset`, this REWRITES its `chainlinkHeartbeat`
/// in place and emits {IPrices-PriceFeedHeartbeatUpdated}; it does NOT revert, and it does NOT emit a
/// PriceFeedAdded/PriceFeedRemoved pair. Do not build idempotency on a duplicate reverting.
/// Reverts: PriceFeedAlreadyRegistered only when the heartbeat is UNCHANGED; PriceFeedTypeImmutable
/// when `priceType` differs from the stored one (a feed's type is identity, not configuration);
/// PriceFeedDecimalsMismatch when the feed's live decimals no longer match the stored value.
/// @param asset Registered asset address.
/// @param priceFeed Price feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero for all types).
function addOrModifyPriceFeed(
address asset,
address priceFeed,
IPrices.PriceType priceType,
uint256 chainlinkHeartbeat
) external;
/// @notice Adds a monitor (divergence-only) feed for an asset. Monitor feeds NEVER price the NAV; they are read
/// only to detect divergence between the primary price and the worst-case (furthest) healthy monitor price.
/// @dev Requires the asset's divergence tolerance to be set first (>0), else reverts DivergenceToleranceRequired.
/// Monitor feeds must report NAV_DECIMALS decimals (else MonitorFeedDecimalsMismatch). Reverts
/// MonitorFeedAlreadyRegistered only when the heartbeat is UNCHANGED (this UPSERTS an existing monitor's heartbeat, emitting MonitorFeedHeartbeatUpdated).
/// @param asset Registered asset address.
/// @param priceFeed Monitor feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero).
function addMonitorFeed(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
external;
/// @notice Sets the asset's divergence tolerance in basis points (must be in (0, 10000]).
/// @param asset Registered asset address.
/// @param divergenceToleranceBps Max worst-case primary-vs-any-single-monitor gap before the asset is flagged irregular.
function setDivergenceTolerance(address asset, uint32 divergenceToleranceBps) external;
/// @notice Sets the asset's stablecoin peg tolerance in basis points (in [0, 10000]; 0 disables the peg guard).
/// @param asset Registered asset address.
/// @param pegToleranceBps Max deviation of the primary price from $1 before the asset is flagged irregular.
function setPegTolerance(address asset, uint32 pegToleranceBps) external;
/// @notice Registers one or more **non-meta** balance adapters in the global registry in a single call.
/// @dev Reverts with InvalidArguments if the list is empty or contains a zero address, DuplicateBalanceAdapter
/// if any adapter is already registered, InvalidBalanceAdapter if any adapter does not implement
/// IBalanceAdapter, and MetaAdapterNotAllowed if any adapter implements IMetaBalanceAdapter (meta-adapters
/// must use addMetaBalanceAdapter). The batch is all-or-nothing.
/// @param adapters Adapter addresses (each must implement IBalanceAdapter and NOT IMetaBalanceAdapter).
function addBalanceAdapters(address[] calldata adapters) external;
/// @notice Registers a meta-adapter (ADR 0010) and seeds its instance set atomically, in one MANAGER call.
/// @dev The adapter must implement both IBalanceAdapter and IMetaBalanceAdapter (else InvalidBalanceAdapter /
/// NotMetaAdapter). Reverts InvalidArguments on a zero adapter, DuplicateBalanceAdapter if already
/// registered, and DuplicateMetaInstance on a repeated coordinate. An empty instance list is allowed
/// (registers the meta-adapter with no instances yet; seed later via addMetaInstances). Plain adapters use
/// addBalanceAdapters; subsequent instance changes use addMetaInstances / removeMetaInstances.
/// @param adapter The meta-adapter address.
/// @param instances Instance coordinates to seed (e.g. vault addresses widened to bytes32, or raw bytes32 IDs).
function addMetaBalanceAdapter(address adapter, bytes32[] calldata instances) external;
/// @notice Removes the price feed at the given index. Reverts if it is the last feed (CannotRemoveLastFeed).
/// @param asset Registered asset address.
/// @param index Index into the asset's feed array.
function removePriceFeedAt(address asset, uint256 index) external;
/// @notice Removes the price feed with the given address. Reverts if not found or last feed.
/// @param asset Registered asset address.
/// @param priceFeed Feed address to remove.
function removePriceFeed(address asset, address priceFeed) external;
/// @notice Removes the monitor feed at the given index. Monitor feeds are optional, so the last one may be removed.
/// @param asset Registered asset address.
/// @param index Index into the asset's monitor feed array.
function removeMonitorFeedAt(address asset, uint256 index) external;
/// @notice Removes the monitor feed with the given address. Reverts MonitorFeedNotFound if absent.
/// @param asset Registered asset address.
/// @param priceFeed Monitor feed address to remove.
function removeMonitorFeed(address asset, address priceFeed) external;
/// @notice Removes one or more balance adapters from the global registry in a single call.
/// @dev Reverts with InvalidArguments if the list is empty. The batch is all-or-nothing — if any adapter is
/// not registered (or is the default ERC20 adapter) the whole call reverts.
/// @param adapters Adapter addresses to remove (none may be the default ERC20 adapter).
function removeBalanceAdapters(address[] calldata adapters) external;
/// @notice Adds instance coordinates to a registered meta-adapter's queried set.
/// @dev This is the governed "which instances to query" registry — adapters themselves stay immutable.
/// All-or-nothing: reverts DuplicateMetaInstance if any coordinate is already present or repeated within
/// the batch (a duplicate would double-count NAV), InvalidArguments on an empty list, InvalidBalanceAdapter
/// if the adapter is not registered, and NotMetaAdapter if the adapter does not implement
/// IMetaBalanceAdapter. Coordinate values are otherwise not validated; a
/// malformed/unknown coordinate is isolated per-instance by the adapter's fan-out (cannot zero the batch).
/// @param adapter Registered meta-adapter address.
/// @param instances Instance coordinates to add (e.g. vault addresses widened to bytes32).
function addMetaInstances(address adapter, bytes32[] calldata instances) external;
/// @notice Removes instance coordinates from a registered meta-adapter's queried set.
/// @dev All-or-nothing: reverts MetaInstanceNotFound if any coordinate is not present (a coordinate repeated
/// within the batch also reverts), InvalidArguments on an empty list, InvalidBalanceAdapter if the adapter
/// is not registered, and NotMetaAdapter if the adapter does not implement IMetaBalanceAdapter. Order is
/// not preserved.
/// @param adapter Registered meta-adapter address.
/// @param instances Instance coordinates to remove.
function removeMetaInstances(address adapter, bytes32[] calldata instances) external;
/// @notice Excludes an asset from the default adapter so wallet balances are not reported for it.
/// @param asset Registered asset address.
function excludeAssetFromDefaultAdapter(address asset) external;
/// @notice Includes an asset in the default adapter so wallet balances are reported again.
/// @param asset Registered asset address.
function includeAssetInDefaultAdapter(address asset) external;
/// @notice Unregisters an asset: unsets price feed, removes from default adapter list, and removes from registry.
/// @param underlyingAsset Asset address to unregister.
function unregisterAsset(address underlyingAsset) external;
/// @notice Sets the Chainlink L2 sequencer uptime feed (use address(0) on L1).
/// @dev Requires DEFAULT_ADMIN_ROLE (same privilege level as upgrades). Disabling sequencer-uptime
/// detection on an L2 is equivalent in impact to an upgrade, so MANAGER access is not sufficient.
/// @param newChainlinkL2UptimeFeed New uptime feed address.
function setChainlinkL2SequencerUptimeFeed(address newChainlinkL2UptimeFeed) external;
/// @notice Sets the L2 sequencer grace period. Reverts UptimeFeedNotSet if the uptime feed is not set, or
/// InvalidArguments if the period is below 1 hour.
/// @param newSequencerGracePeriod Grace period in seconds (must be at least 1 hour).
function setChainlinkL2SequencerGracePeriod(uint256 newSequencerGracePeriod) external;
//
// View functions — registry
//
/// @notice Returns the number of registered assets (alias for getAssetCount).
/// @return Number of registered assets.
function assetCount() external view returns (uint256);
/// @notice Returns whether an asset is registered.
/// @param asset Asset address to check.
/// @return True if registered.
function isAssetRegistered(address asset) external view returns (bool);
/// @notice Returns all registered assets with metadata.
/// @dev **O(N), and it is the wrong tool for resolving ONE asset** — use {getRegisteredAsset} for that. This
/// copies the entire registry across the ABI boundary, so a caller that resolves M tokens by calling this
/// M times pays M full fetches. That pattern measured **6,274,562 gas for a single 50-token Balancer
/// instance at 43 registered assets** (18.4M at 100), and it is super-linear rather than linear because
/// each call allocates a fresh N-element array that is never freed, so memory expansion grows with the
/// square of the token count. At that scale it exhausts the per-adapter gas stipend and turns a NAV read
/// into a REVERT.
/// @return assets Array of Asset (address, symbol, decimals).
function getRegisteredAssets() external view returns (Asset[] memory assets);
/// @notice Resolves ONE asset's registry metadata in O(1), without reverting when it is absent.
/// @dev The single-asset counterpart to {getRegisteredAssets}, added because balance adapters resolve tokens
/// one at a time and the array getter makes that quadratic (see its docs for the measured figures).
/// Backed by the 1-based `_assetIndex` map the registry already maintains on register/unregister, so this
/// is a mapping load plus one array read — flat in the number of registered assets.
///
/// **Non-reverting by design, and that is the whole reason this is a new function rather than a widened
/// visibility on the existing internal lookup.** NAVCalculator's `_getRegisteredAsset` reverts
/// `AssetNotFound` for an unregistered asset, which is right for its callers but wrong here: "not
/// registered" is an ORDINARY, expected outcome on an adapter's emission path — the adapter simply skips
/// that leg. A reverting getter would turn every unregistered token an adapter happens to encounter into
/// a failed instance read, converting a skipped leg into a dropped position.
/// @param asset The asset to resolve.
/// @return assetInfo The registry entry. Zeroed (`address(0)`, `""`, `0`) when `found` is false — **check
/// `found`, do not infer absence from a zero `assetInfo.asset`**, since the two are only equivalent
/// while nothing zero-addressed can be registered.
/// @return found True if `asset` is registered.
function getRegisteredAsset(address asset) external view returns (Asset memory assetInfo, bool found);
/// @notice Returns the number of registered assets.
/// @return Number of registered assets.
function getAssetCount() external view returns (uint256);
/// @notice Returns the current implementation version (Initializable storage).
/// @return Version number.
function version() external view returns (uint64);
//
// View functions — NAV and positions
//
/// @notice Computes NAV for an account in the given quote currency.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD. Must have a price feed if not zero.
/// @return nav NAV struct (value, quoteAsset, timestamp, stalePriceAssets, sequencerDown, quoteAssetStale).
function getAccountNav(address account, address quoteAsset) external view returns (NAV memory nav);
/// @notice Computes the NAV contribution of a CALLER-SUPPLIED SET of balance adapters, so an off-chain caller
/// can read a portfolio's NAV in slices and reassemble it.
/// @dev Exists because {getAccountNav} scans every registered adapter in one `eth_call` and that cost grows
/// with the asset registry and the adapter set. Past a node's `eth_call` gas cap the complete read stops
/// returning anything at all — not a degraded NAV, no NAV — and there is no smaller question to ask.
/// This is that smaller question.
///
/// **A SET, NOT AN INDEX RANGE, AND THAT IS NOT A STYLE CHOICE.** `getAllAdapters()` is maintained with
/// swap-and-pop, so removing any adapter moves the LAST adapter into the removed one's index — always to a
/// LOWER index. A caller paging `[0,10)` then `[10,20)` across a governance removal therefore **silently
/// SKIPS** the moved adapter: it was at the tail, it lands in a slot the caller has already passed, and it
/// is never read. Both pages still look completely well-formed and the total is short by that adapter's
/// positions.
///
/// Precisely because elements only ever move DOWN, a removal cannot make an already-read adapter reappear
/// in a later page — so the hazard is a missed adapter, not a double-counted one. (An earlier version of
/// this note claimed a double-read; that is not reachable through either removal path.) Naming the adapters
/// removes the whole class rather than documenting it away.
///
/// ### The caller contract
///
/// **Canonical statement: `docs/howto/read-nav-in-slices.md`.** That document is the single source for the
/// reassembly rules, including the worked example and the gas-starvation precondition. What follows is the
/// short form, kept here because a consumer generating against this ABI may never open the repo — if the
/// two ever disagree, the how-to wins and this block is the bug.
///
/// Four obligations. The first two this function enforces; the last two it cannot see, and they are
/// where a reassembled NAV goes wrong.
///
/// 1. **Every adapter must be registered and appear at most once** — else {AdapterNotRegistered} or
/// {DuplicateAdapterInSlice}. An empty list reverts {EmptyAdapterSlice}.
/// 2. **The slice is queried as one atomic read**, so `value` is internally consistent.
/// 3. **All slices MUST be read at the same block, and PINNING THE BLOCK NUMBER IN THE REQUEST is the only
/// real control.** Pass an explicit block number to every `eth_call` — not `latest`, which lets
/// successive calls land on different heads. Positions and prices both move between blocks, so slices
/// from different blocks sum to a number that was never any account's NAV, and the sum looks entirely
/// reasonable.
///
/// `PartialNAV.timestamp` is a **cross-check, not the check**, and it is deliberately described that way
/// here: equal timestamps do NOT imply the same block. Arbitrum Nitro mints blocks roughly every 250ms,
/// so consecutive blocks routinely share a `block.timestamp`, and this contract is deployed there. The
/// field therefore catches only the gross case (slices seconds apart) and is blind to the narrow one
/// (two blocks inside one second) — which is the case an unpinned paging loop actually produces. There
/// is no block number in `PartialNAV` to check instead, by choice: adding one would not fix an unpinned
/// caller, and pinning the request already does.
/// 4. **The union of the slices must cover `getAllAdapters()` exactly once**, and
/// `PartialNAV.adaptersCovered` is how that is verified: concatenate it across slices and compare
/// against `getAllAdapters()` read at the same block. A missing adapter yields a NAV short by its
/// positions; a repeated one double-counts. Re-read `getAllAdapters()` at the pinned block rather than
/// trusting a cached list — the registry is governed and can change under a paging loop.
///
/// ### **Health flags do NOT sum. Ignoring them on ANY slice silently destroys a signal.**
///
/// `value` is the only field that composes by addition. **`stalePriceAssets`, `irregularPriceAssets` and
/// `monitorsUnhealthyPriceAssets` are restricted to the assets THIS slice's positions touched, and
/// `sequencerDown`, `quoteAssetStale` and `quoteAssetIrregular` are reported per slice. A caller that checks the flags on one slice, or on
/// the last slice, or on a slice it happened to keep, silently loses every staleness, depeg and
/// sequencer-down signal carried by the others — and gets a NAV number that looks fine.** That failure
/// shape is exactly what this repo's fail-open hardening work was for; it must not be reintroduced at the
/// reassembly boundary. **UNION the THREE asset arrays (de-duplicating: two slices holding the same stale
/// asset each report it) and OR the three booleans, across every slice, before treating the summed
/// `value` as usable.** The third array, `monitorsUnhealthyPriceAssets`, was appended later than this
/// instruction was first written — a reassembler that unions only two silently drops the monitor-health
/// signal, which is the falsely-reassuring direction and hits precisely the large accounts that must
/// paginate.
///
/// ### A meta-adapter is the atomic unit
///
/// A slice naming a meta-adapter includes **all** of that adapter's governed instances — every Aave V3
/// instance, every Morpho market, every Curve pool. There is no way to page WITHIN one meta-adapter
/// through this API, by design: the governed instance set is itself swap-and-pop mutable
/// (`addMetaInstances`/`removeMetaInstances`), so an instance-level range would carry the same
/// reordering hazard this signature exists to avoid, and an instance-level set would need the adapter to
/// accept a filter it does not have. So the finest slice available is one adapter. If a SINGLE
/// meta-adapter's read alone exceeds the gas budget, pagination does not help and the problem is that
/// adapter's per-instance cost, not the number of adapters — a different problem with a different fix.
///
/// ### What this does NOT do
///
/// Pagination reduces the gas of one call. It does not reduce the total gas of reading the whole NAV
/// (it slightly increases it — per-call overhead is paid per slice) and it does nothing whatsoever for an
/// ON-CHAIN consumer that must read a NAV inside a transaction: that consumer needs one complete answer
/// in one frame and cannot reassemble across calls. For those callers the only fixes are reducing the
/// cost of the read itself or shrinking the registry. This API is for off-chain readers.
///
/// One thing it does help, but read the caveat before relying on it: the per-adapter gas stipend is a
/// share of what the READ still holds, so an adapter starved into {AdapterGasExhausted} inside the
/// complete scan may have ample budget when asked for on its own. A slice can therefore get an answer out
/// of a portfolio whose complete read has started reverting.
///
/// **The caveat: a slice can also convert that loud revert into a silent omission.** Exhaustion is
/// classified by `GasStipendLib.exhausted` as `consumed >= stipend - stipend/8` — measured against a
/// stipend that is itself a share of the CALLER's budget. An adapter that fails at a roughly fixed cost
/// `G` for a non-gas reason is scored "exhausted" (loud {AdapterGasExhausted}) when the full scan's
/// stipend is small enough that `G` clears that bar, and scored "benign revert" — fail open, legs dropped,
/// nothing flagged — when the slice's larger stipend puts `G` below it. `adaptersCovered` still lists the
/// adapter, so the documented coverage check reports full coverage. If a dropped leg is a DEBT leg the
/// reassembled NAV over-reports.
///
/// So: a slice that succeeds where the complete read reverted is **evidence about gas, not a repaired
/// answer.** Do not silently promote it to the authoritative NAV.
///
/// And note what "just give the complete read more gas and compare" does NOT achieve: raising the budget
/// raises the stipend, which puts a fixed-cost failure below the same 7/8 bar for the COMPLETE read too.
/// Both reads then fail open on the identical adapter and AGREE on the identical wrong number. The signal
/// is the {AdapterGasExhausted} disappearing, not the two figures converging.
///
/// No verbose (labelled) counterpart exists yet. The label paths carry the heavier gas pressure and their
/// bounds are being re-derived; a paginated read built against numbers about to change would be wasted.
/// @param account Account address.
/// @param quoteAsset Quote currency; `address(0)` for USD. Must have a price feed if non-zero. Pass the SAME
/// value to every slice — the per-slice `value`s are otherwise denominated differently and summing them
/// is meaningless.
/// @param adapters The balance adapters to include. Each must be currently registered (in `getAllAdapters()`)
/// and may appear only once. Must be non-empty.
/// @return partialNav The slice's NAV contribution plus `adaptersCovered`. See {PartialNAV} — in particular,
/// `value` sums and nothing else does.
function getAccountNavForAdapters(address account, address quoteAsset, address[] calldata adapters)
external
view
returns (PartialNAV memory partialNav);
/// @notice Returns all positions for an account with pricing in the quote currency.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return positions Array of enriched Position structs.
function getAccountPositions(address account, address quoteAsset)
external
view
returns (Position[] memory positions);
/// @notice Returns positions for an account filtered by a single asset.
/// @dev **This is a filtered VIEW, not a net position. Do not sum it.** You asked for asset `X`, so you get
/// the legs denominated in `X` — a projection of the portfolio onto one asset, deliberately. Summing
/// `value` across the result (or netting credit against debt within it) produces a number that is not
/// this account's exposure to anything: the legs that offset these — collateral in another asset
/// backing a debt in `X`, or the reverse — are outside the filter by construction and are simply
/// absent, not netted. A vault borrowing `X` against `Y` shows here as debt in `X` with no sign of the
/// `Y` that secures it.
///
/// This is a documentation contract, not a defect, and the design is what makes it safe: **no NAV
/// number in this interface is ever computed with an asset filter.** {getAccountNav},
/// {getAccountNavForAdapters} and {getAccountNavVerbose} take no `asset` parameter at all, and the only
/// entry points that pass a non-zero filter into the position engine are this function and
/// {getAccountPositionsForAssetVerbose} — both of which return `Position[]`, never a `NAV`. So the
/// hazard lives entirely in what a CALLER does with the array, which is why it is stated here.
///
/// For a net figure, use {getAccountNav} (whole portfolio) or {getAccountNavForAdapters} (a validated
/// adapter slice, which partitions rather than projects and whose slices therefore do sum).
/// @param account Account address.
/// @param asset Asset to filter by (must be registered).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return positions Array of enriched Position structs for the asset. A filtered view — see the note above.
function getAccountPositionsForAsset(address account, address asset, address quoteAsset)
external
view
returns (Position[] memory positions);
/// @notice Returns all positions for `account` with human-readable labels.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return Array of VerbosePosition structs (enriched Position plus protocolName and display labels).
function getAccountPositionsVerbose(address account, address quoteAsset)
external
view
returns (VerbosePosition[] memory);
/// @notice Returns positions filtered by a single asset, with human-readable labels.
/// @dev **This is a filtered VIEW, not a net position. Do not sum it.** Identical projection semantics to
/// {getAccountPositionsForAsset} — this is that function's result passed through label enrichment, from
/// the same `_computePositions` call with the same filter — so the whole note there applies verbatim,
/// including the reason it is safe: no NAV in this interface is computed with an asset filter. See
/// {getAccountPositionsForAsset}.
/// @param account Account address.
/// @param asset Asset to filter by (must be registered).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return Array of VerbosePosition structs for the asset (enriched Position plus protocolName and display
/// labels). A filtered view — see the note above.
function getAccountPositionsForAssetVerbose(address account, address asset, address quoteAsset)
external
view
returns (VerbosePosition[] memory);
/// @notice Returns the aggregate NAV and full verbose position breakdown in one call.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return verboseNav VerboseNAV struct bundling the NAV snapshot with the verbose position list.
function getAccountNavVerbose(address account, address quoteAsset)
external
view
returns (VerboseNAV memory verboseNav);
/// @notice Returns the number of decimals used for USD values (e.g. 8).
/// @return USD decimals.
function usdDecimals() external view returns (uint8);
/// @notice Returns detailed price feed data for an asset (primary feed + divergence signal vs its monitors).
/// @param underlyingAsset Registered asset address.
/// @return priceFeedData PriceFeedData struct (feed, type, price, decimals, heartbeat, updatedAt, stale,
/// sequencerDown, healthyFeedCount, irregular, divergenceBps, monitorFeedCount).
function getPriceData(address underlyingAsset) external view returns (PriceFeedData memory priceFeedData);
/// @notice Same as {getPriceData} but WITHOUT the monitor-divergence computation (irregular/divergenceBps/
/// monitorFeedCount stay 0/false). For hot callers that only need price/staleness (e.g. custom feeds
/// reading the NAV-sourced base/USD term) so a base asset's monitor reads + sort aren't repaid per call.
/// @param underlyingAsset Registered asset address.
/// @return priceFeedData PriceFeedData struct with the divergence fields left at their defaults.
function getPriceDataNoDivergence(address underlyingAsset)
external
view
returns (PriceFeedData memory priceFeedData);
/// @notice Returns the divergence between an asset's primary price and its monitor feeds.
/// @param underlyingAsset Registered asset address.
/// @return primaryPrice The primary feed's price, normalized to NAV_DECIMALS (0 if the primary is stale).
/// @return monitorMedian The median of the healthy monitor prices, NAV_DECIMALS (0 if no healthy monitors).
/// @return divergenceBps Worst-case basis-point gap between the primary and any single healthy monitor — the
/// value `irregular` is thresholded on (0 if no monitors / primary stale).
/// @return irregular True if divergenceBps exceeds the divergence tolerance, or (stablecoins) the primary
/// deviates from $1 beyond the peg tolerance.
/// @return monitorFeedCount Number of healthy monitor feeds that contributed.
/// @return primaryStale True if the primary feed is stale (divergence undefined).
/// @return primaryAboveMonitors True if the primary sits above the monitor median (a premium); false if
/// below/equal — for a claim asset, below is the depeg direction. Meaningful only when
/// monitorFeedCount > 0.
function getPriceDivergence(address underlyingAsset)
external
view
returns (
int256 primaryPrice,
int256 monitorMedian,
uint256 divergenceBps,
bool irregular,
uint256 monitorFeedCount,
bool primaryStale,
bool primaryAboveMonitors
);
/// @notice Returns health status: sequencer down flag and lists of stale-price and irregular-price assets.
/// @return sequencerDown True if L2 sequencer is down or in grace period (false on L1).
/// @return stalePriceAssets Addresses of assets with stale prices.
/// @return irregularPriceAssets Addresses of assets flagged irregular (primary diverged from monitors / peg).
function healthCheck()
external
view
returns (bool sequencerDown, address[] memory stalePriceAssets, address[] memory irregularPriceAssets);
/// @notice Returns whether the account has any non-zero balance across adapters and registered assets.
/// @param account Account address.
/// @return has True if at least one position has non-zero amount.
function hasPositions(address account) external view returns (bool has);
/// @notice Returns the list of assets for which the account has at least one non-zero position.
/// @param account Account address.
/// @return assets Array of asset addresses.
function getAssetsWithPositions(address account) external view returns (address[] memory assets);
/// @notice Converts a list of (asset, amount) pairs into a total value in the quote currency.
/// @dev Only positive amounts; zero amounts are skipped. All assets must be registered with a price feed.
/// @param assets Asset addresses.
/// @param amounts Corresponding amounts (same length as assets).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return value Sum of values in quote asset (non-negative for valid inputs). When `quoteAssetStale` is
/// true, this is denominated in USD (8dp) instead of the requested quote ([9]/S2).
/// @return quoteAssetStale True if the requested non-USD quote asset's own feed was stale, so `value` fell
/// back to USD rather than the quote currency. Always false for a USD quote (address(0)).
function calculateValue(address[] memory assets, uint256[] memory amounts, address quoteAsset)
external
view
returns (int256 value, bool quoteAssetStale);
/// @notice Every listed adapter's EFFECTIVE display name and positionId-independent breadcrumb — the same values
/// the verbose position reads report, including any {AssetKindRegistry} override.
/// @dev Declared here, not only on the concrete contract, so INTERFACE-TYPED consumers can reach it. That is the
/// caller that matters: a consumer holding `INAVCalculator` is exactly the one that would otherwise
/// enumerate `getAllAdapters()` and staticcall `protocolName()` on each adapter itself, which is the
/// surface split this function exists to close. Leaving it off the interface would have left that consumer
/// with no way to reach the fix.
/// @param adapters The adapters to describe, typically the result of `getAllAdapters()`.
/// @return names Each adapter's effective protocol name.
/// @return labels Each adapter's effective breadcrumb, with any {AssetKindRegistry} per-segment override applied.
/// Empty when the adapter derives it per position AND no override is set. When the adapter answers
/// nothing but an override IS set, this path deliberately GROWS the breadcrumb to the override's leading
/// non-empty prefix — so it can be MULTI-segment, not merely a lone category. (It was a lone category
/// under the retired scalar `setAdapterLabelCategory`; do not code against that.) When the adapter DOES
/// answer, the override is overlaid segment-by-segment and can neither lengthen nor truncate the reply.
/// See `PriceFeedLib.adapterDisplayInfo` for why the empty case diverges from the position path.
function getAdapterDisplayInfo(address[] calldata adapters)
external
view
returns (string[] memory names, string[][] memory labels);
}
src/prices/IPrices.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IPrices Interface
/// @notice Interface for managing price feeds for different tokens.
/// @author KPK
interface IPrices {
/// @notice Enum representing the type of price feed.
enum PriceType {
Chainlink, // 0 — Chainlink AggregatorV3Interface (on-chain push)
Redstone, // 1 — Redstone Classic Push (AggregatorV3-compatible, same read path as Chainlink)
API3, // 2 — API3 dAPI via Api3ReaderProxyV1 (AggregatorV3-compatible, 18-dec proxy scaled to 8-dec at read)
Custom // 3 — custom ICustomPriceFeed adapter (internal staleness logic)
}
/// @notice Per-asset pricing metadata governing divergence detection between the primary feed and its
/// monitor feeds. Packs into a single storage slot (uint32 + uint32 = 8 bytes).
/// @param divergenceToleranceBps Max allowed basis-point gap between the primary price and the worst-case
/// (furthest) healthy monitor price before the asset is flagged `irregular`. Must be non-zero when monitors exist.
/// @param pegToleranceBps Absolute peg-deviation guard: max allowed basis-point deviation of the primary price
/// from $1 before the asset is flagged `irregular`. Non-zero enables the guard (set it only on assets whose
/// fundamental value is $1, i.e. stablecoins); zero disables it.
struct AssetPricing {
uint32 divergenceToleranceBps;
uint32 pegToleranceBps;
}
/// @notice Struct representing a price feed configuration.
/// @param priceFeed The address of the price feed contract (e.g. Chainlink aggregator or custom price feed).
/// @param decimals The number of decimal places the price feed uses.
/// @param priceType The type of the price feed.
/// @param chainlinkHeartbeat Staleness window in seconds (non-zero for all types). For Chainlink/Redstone/API3
/// feeds this gates participation: block.timestamp - effectiveUpdatedAt >= chainlinkHeartbeat → skip feed.
/// For Custom feeds the internal stale signal from getLatestPrice() is the primary gate; updatedAt from
/// latestRoundData() then applies the same heartbeat gate (updatedAt==0 is treated as block.timestamp-1
/// so rate-only feeds participate but yield to any feed with a real push timestamp), and among survivors
/// the largest effectiveUpdatedAt wins.
struct PriceFeedConfig {
address priceFeed;
uint8 decimals;
PriceType priceType;
uint256 chainlinkHeartbeat;
}
/// @notice Emitted when an already-registered price feed's staleness heartbeat is changed in place.
/// @param underlyingAsset The asset whose registration was updated.
/// @param priceFeed The registered feed the heartbeat applies to.
/// @param oldHeartbeat The previous heartbeat, in seconds.
/// @param newHeartbeat The new heartbeat, in seconds.
event PriceFeedHeartbeatUpdated(
address indexed underlyingAsset, address indexed priceFeed, uint256 oldHeartbeat, uint256 newHeartbeat
);
/// @notice A registered MONITOR feed's heartbeat changed in place.
/// @dev Mirrors {PriceFeedHeartbeatUpdated}. Emitted instead of a `MonitorFeedRemoved`/`MonitorFeedAdded`
/// pair, so alerting subscribed to that pair will not see monitor staleness-window changes.
/// @param underlyingAsset The asset whose monitor feed changed.
/// @param priceFeed The monitor feed whose staleness window moved.
/// @param oldHeartbeat The previous staleness window, in seconds.
/// @param newHeartbeat The new staleness window, in seconds.
event MonitorFeedHeartbeatUpdated(
address indexed underlyingAsset, address indexed priceFeed, uint256 oldHeartbeat, uint256 newHeartbeat
);
/// @notice Emitted when a price feed is added for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the price feed.
/// @param chainlinkHeartbeat The heartbeat interval in seconds.
/// @param priceType The type of the price feed.
/// @param index The index of the new feed in the asset's feed array.
event PriceFeedAdded(
address indexed underlyingAsset,
address indexed priceFeed,
uint256 chainlinkHeartbeat,
PriceType priceType,
uint256 index
);
/// @notice Emitted when a single price feed is removed for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the removed feed.
/// @param index The former index of the removed feed.
event PriceFeedRemoved(address indexed underlyingAsset, address indexed priceFeed, uint256 index);
/// @notice Emitted when swap-and-pop relocates the last feed into a vacated slot.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the feed that was moved.
/// @param fromIndex The former index (len-1 before the pop).
/// @param toIndex The new index (the slot vacated by the removed feed).
event PriceFeedIndexChanged(
address indexed underlyingAsset, address indexed priceFeed, uint256 fromIndex, uint256 toIndex
);
/// @notice Emitted when all price feeds are cleared for a token (asset unregistration).
/// @param underlyingAsset The address of the token.
event PriceFeedUnset(address indexed underlyingAsset);
/// @notice Emitted when a monitor (divergence-only) feed is added for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the monitor feed.
/// @param chainlinkHeartbeat The heartbeat interval in seconds.
/// @param priceType The type of the monitor feed.
/// @param index The index of the new monitor feed in the asset's monitor array.
event MonitorFeedAdded(
address indexed underlyingAsset,
address indexed priceFeed,
uint256 chainlinkHeartbeat,
PriceType priceType,
uint256 index
);
/// @notice Emitted when a monitor feed is removed for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the removed monitor feed.
/// @param index The former index of the removed monitor feed.
event MonitorFeedRemoved(address indexed underlyingAsset, address indexed priceFeed, uint256 index);
/// @notice Emitted when swap-and-pop relocates the last monitor feed into a vacated slot.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the monitor feed that was moved.
/// @param fromIndex The former index (len-1 before the pop).
/// @param toIndex The new index (the slot vacated by the removed monitor feed).
event MonitorFeedIndexChanged(
address indexed underlyingAsset, address indexed priceFeed, uint256 fromIndex, uint256 toIndex
);
/// @notice Emitted when all monitor feeds and pricing metadata are cleared for a token (asset unregistration).
/// @param underlyingAsset The address of the token.
event MonitorFeedsUnset(address indexed underlyingAsset);
/// @notice Emitted when an asset's divergence tolerance is set.
/// @param underlyingAsset The address of the token.
/// @param divergenceToleranceBps The new tolerance in basis points.
event DivergenceToleranceSet(address indexed underlyingAsset, uint32 divergenceToleranceBps);
/// @notice Emitted when an asset's peg tolerance is set (stablecoins).
/// @param underlyingAsset The address of the token.
/// @param pegToleranceBps The new peg tolerance in basis points.
event PegToleranceSet(address indexed underlyingAsset, uint32 pegToleranceBps);
//
// Errors
//
/// @notice Error when the price feed is not set for an asset
/// @param asset The address of the asset
error PriceFeedNotSet(address asset);
/// @notice Error when the price feed is invalid
error InvalidPriceOracle();
/// @notice Error when the price feed type is not valid
error InvalidPriceOracleType();
/// @notice Error when attempting to remove the last remaining feed for an asset
error CannotRemoveLastFeed(address asset);
/// @notice Error when attempting to add a feed that is already registered for an asset
error PriceFeedAlreadyRegistered(address asset, address feed);
/// @notice The upsert path was given a `priceType` differing from the one the feed is registered with.
/// @dev A feed's type is part of its IDENTITY, not its configuration — it selects the read path and the
/// decimals convention. Changing it means removing and re-adding the feed. Rejected rather than
/// ignored because `_validateFeedSupportInternal` puts Chainlink, Redstone and API3 in ONE branch, so a
/// mismatch inside that group passes validation and the caller would otherwise be told a request
/// succeeded that was never applied.
error PriceFeedTypeImmutable(address asset, address feed);
/// @notice Error when the feed index is out of bounds
error PriceFeedIndexOutOfBounds(address asset, uint256 index);
/// @notice Error when a feed address is not found in an asset's feed list
error PriceFeedNotFound(address asset, address feed);
/// @notice Error when a new feed's decimals do not match the decimals of existing feeds for the asset
error PriceFeedDecimalsMismatch(address asset, uint8 existingDecimals, uint8 newDecimals);
/// @notice Error when a monitor feed's decimals are not NAV_DECIMALS (monitors must be USD-comparable to the
/// primary, which is always NAV_DECIMALS).
error MonitorFeedDecimalsMismatch(address asset, uint8 expectedDecimals, uint8 actualDecimals);
/// @notice Error when a `Custom` feed is being registered for an asset it does not price — i.e. the feed's own
/// {ICustomPriceFeed-underlyingAssetSupported} does not equal the asset being registered.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
/// @param feedAsset The asset the feed actually prices, per its own `underlyingAssetSupported()`.
error CustomFeedAssetMismatch(address asset, address feed, address feedAsset);
/// @notice Error when a `Custom` feed is being registered for the very asset it reads its own `base/USD` price
/// for — i.e. the feed's {INavSourcedPriceFeed-BASE_ASSET} equals the asset being registered.
/// @dev A NAV-sourced custom feed prices its asset as `rate × base/USD` and reads that `base/USD` back out of
/// THIS NAV (`NavBaseUsdLib` → `getPriceData(BASE_ASSET)`; ADR 0019). If the base IS the asset, pricing the asset
/// re-enters the same feed and recurses until the call stack is exhausted. The read still returns a price — the
/// selector's per-feed `try`/`catch` swallows the depth failure and moves on — so the only symptom is that every
/// read of that asset, and of everything priced from it, burns gas proportional to ~1024 nested `STATICCALL`
/// frames. See the circularity invariant in {NavBaseUsdLib}.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
error CustomFeedBaseCircular(address asset, address feed);
/// @notice Error when a `Custom` feed does not answer {INavSourcedPriceFeed-BASE_ASSET}, so its NAV dependency
/// cannot be established at registration.
/// @dev Unreadable means REJECT, deliberately. The failure being closed is unbounded recursion, so "the base
/// could not be read" must not be allowed to mean "the base is fine". A feed with no NAV dependency states that
/// by answering `address(0)`; a feed that cannot answer at all is one whose base cannot be ruled out.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
error CustomFeedBaseUnreadable(address asset, address feed);
/// @notice Error when a monitor feed is already registered for an asset.
error MonitorFeedAlreadyRegistered(address asset, address feed);
/// @notice Error when a monitor feed address is not found in an asset's monitor list.
error MonitorFeedNotFound(address asset, address feed);
/// @notice Error when adding a monitor feed before the asset's divergence tolerance has been set (>0).
error DivergenceToleranceRequired(address asset);
/// @notice Error when a tolerance value is out of range. Divergence tolerance must be in (0, 10000];
/// peg tolerance must be in [0, 10000] (0 is allowed and disables the peg guard).
error InvalidTolerance(uint32 toleranceBps);
/// @notice Returns the latest price for a given token while checking if the price is stale.
/// @dev Reverts PriceFeedNotSet if the asset has no registered feeds. When at least one feed is registered
/// but all are stale, returns price 0 with stale = true rather than reverting.
/// @param underlyingAsset The address of the token.
/// @return price The latest price of the token (int256; positive for all valid prices, 0 when stale).
/// @return decimals The amount of decimal places the price is represented with.
/// @return stale True if all registered feeds are stale, the L2 sequencer is down, or within grace period.
/// @return irregular True if the primary price diverged from its monitor feeds beyond the divergence tolerance,
/// or (stablecoins) from the $1 peg beyond the peg tolerance. A pricing-quality signal, not a validity flag;
/// `price` is still populated. Always false when `stale` (divergence is undefined for an unusable price).
function latestPrice(address underlyingAsset)
external
view
returns (int256 price, uint8 decimals, bool stale, bool irregular);
/// @notice Checks the L2 sequencer uptime feed, returning True when it is signaling staleness (the sequencer
/// is down or still within the grace period). If 'chainlinkL2SequencerUptimeFeed' is the zero address (e.g. on
/// an L1) it returns false.
/// @return stale True if the L2 sequencer is down or if it is within the grace period.
function checkL2SequencerUptime() external view returns (bool stale);
/// @notice Validates that a price feed is suitable for the given type, reverting if it is not. Returns nothing
/// on success. Reverts InvalidPriceOracle when the asset or feed address is zero, the feed fails the
/// ICustomPriceFeed/AggregatorV3 interface check for its type, or (for Chainlink/Redstone/API3) its
/// latestRoundData reports a non-positive answer, a zero updatedAt, or a future timestamp; reverts
/// InvalidPriceOracleType for an unsupported price type. For `Custom` feeds it additionally reverts
/// CustomFeedAssetMismatch when the feed's own `underlyingAssetSupported()` is not `underlyingAsset` — a custom
/// feed prices exactly one asset and must be registered for that asset — plus CustomFeedBaseUnreadable when the
/// feed does not answer {INavSourcedPriceFeed-BASE_ASSET}, and CustomFeedBaseCircular when that base IS
/// `underlyingAsset` (which would make pricing the asset re-enter the same feed).
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the price feed.
/// @param priceType The type of the price feed.
function checkPriceOracleSupport(address underlyingAsset, address priceFeed, PriceType priceType) external view;
/// @notice Returns all price feed configurations for an asset.
/// @param asset The address of the asset.
/// @return configs Array of PriceFeedConfig (empty if no feeds registered).
function getPriceFeeds(address asset) external view returns (PriceFeedConfig[] memory configs);
/// @notice Returns the number of registered price feeds for an asset.
/// @param asset The address of the asset.
/// @return count Number of feeds.
function getPriceFeedCount(address asset) external view returns (uint256 count);
/// @notice Returns the price feed configuration at a specific index.
/// @param asset The address of the asset.
/// @param index Index into the feed array (reverts with PriceFeedIndexOutOfBounds if out of range).
/// @return config The PriceFeedConfig at that index.
function getPriceFeedAt(address asset, uint256 index) external view returns (PriceFeedConfig memory config);
/// @notice Returns all monitor (divergence-only) feed configurations for an asset.
/// @param asset The address of the asset.
/// @return configs Array of monitor PriceFeedConfig (empty if none registered).
function getMonitorFeeds(address asset) external view returns (PriceFeedConfig[] memory configs);
/// @notice Returns the number of registered monitor feeds for an asset.
/// @param asset The address of the asset.
/// @return count Number of monitor feeds.
function getMonitorFeedCount(address asset) external view returns (uint256 count);
/// @notice Returns the per-asset pricing metadata (divergence/peg tolerances).
/// @param asset The address of the asset.
/// @return pricing The AssetPricing struct (zero-valued if never set: tolerances 0).
function getAssetPricing(address asset) external view returns (AssetPricing memory pricing);
}
src/utils/AddressCheckLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {NotAContract} from "src/errors.sol";
/// @title AddressCheckLib
/// @author KPK
/// @notice Constructor-argument helper for the balance-adapter layer: asserts a dependency address actually points
/// to a deployed contract, reverting with the {NotAContract} custom error carrying the dependency label.
/// @dev Centralises the `addr.code.length > 0` dependency check that every adapter pins its immutables with. The
/// price-feed layer has its own equivalent (`OracleArgumentChecks`); this is the balance-side analogue. `name`
/// is the dependency's human label (e.g. "NAVCalculator"), surfaced in the {NotAContract} error.
library AddressCheckLib {
/// @notice Reverts {NotAContract}(`name`) unless `addr` has non-empty code.
/// @param addr The dependency address to validate.
/// @param name The dependency's display name (carried in the revert).
function requireContract(address addr, string memory name) internal view {
if (addr.code.length == 0) revert NotAContract(name);
}
}
src/utils/GasStipendLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title GasStipendLib
/// @author KPK
/// @notice The single definition of "did this call run out of gas, or did it answer?" — the stipend a fan-out
/// forwards to one child, and the test that separates an out-of-gas from a revert afterwards.
/// @dev Exists because that question is asked in two places, one frame apart, and the two must give the same
/// answer: `PriceFeedLib._getAdapterPositions` asks it of a balance adapter, and `MetaBalanceAdapter`
/// asks it of one governed instance. Both sit on a `try`/`catch` that cannot tell the two failures apart on
/// its own, and getting it wrong in the lenient direction drops a position's legs — a dropped *debt* leg
/// RAISES the reported NAV. Two copies of a threshold is how the two paths drift apart, so there is one.
///
/// **Why a threshold at all, rather than "consumed == forwarded".** A starved callee never quite spends
/// everything it was given. Gas runs out inside whatever the callee is itself reading, not in the callee's
/// own frame: that sub-call takes 63/64 under EIP-150, out-of-gasses, and the callee's own reserve comes
/// back unspent when it bubbles the revert. One level of nesting consumes ~63/64 of the stipend, two
/// ~0.969, three ~0.954 — each level leaves another reserve behind. An exact test sees the shortfall and
/// calls a starved callee healthy, which is the silent failure; and no fixed fraction is exact either, so
/// {SLACK_DIVISOR} narrows the silent window rather than closing it.
///
/// Being wrong the other way is cheap: a busy callee that reverts after real work gets read as exhausted
/// and produces a loud, retryable failure instead of a wrong number.
///
/// **What this cannot see at all.** The question is only asked when the callee BUBBLES its out-of-gas. A
/// callee that wraps its own read in `try`/`catch` — or in a fail-open low-level staticcall — absorbs the
/// out-of-gas itself, carries on with the ~1/64 the EVM handed back, and RETURNS SUCCESSFULLY with a leg
/// missing. No classifier upstream is reached, because nothing failed from where it is standing. That
/// residual is a property of each adapter's internal error handling, not of this threshold, and it is why
/// "narrows the silent window" is the accurate claim rather than "closes it".
library GasStipendLib {
/// @notice Fraction of the stipend a failed call may leave unspent and still count as exhausted: `1/8`.
/// @dev Covers nesting far past anything in this repo. Raising it (a smaller divisor) widens the window in
/// which a genuinely reverting callee is called exhausted — loud but wrong; lowering it re-opens the
/// silent window. The tests bracket it from both sides deliberately.
uint256 private constant SLACK_DIVISOR = 8;
/// @notice Gas to forward to one child of a fan-out, given what the calling frame currently holds.
/// @dev Exactly what the EVM would forward on its own (63/64), computed explicitly so {exhausted} has a
/// figure to compare against rather than an implied one. Deliberately NOT a smaller fixed ceiling: a
/// ceiling makes exhaustion unrecoverable — the caller cannot escape it by supplying more gas — which
/// turns ordinary growth in a child's cost, and cheap third-party griefing of a per-account list, into
/// an outage that only a redeploy can lift.
/// @param available `gasleft()` in the calling frame, read BEFORE this call.
/// @return The stipend to pass as `{gas: …}`.
function stipendFrom(uint256 available) internal pure returns (uint256) {
return available - available / 64;
}
/// @notice Whether a failed call that was forwarded `stipend` and cost the caller `consumed` ran out of gas
/// rather than reverting with an answer.
/// @dev `consumed` must be measured against the SAME `available` that produced `stipend` via {stipendFrom}.
/// That single-sample discipline is what fixes the sign of the slack: the caller-side overhead the
/// callee never spends lands on the `consumed` side, so a genuine out-of-gas always clears the
/// threshold. Re-sampling nearer the call inverts it and a real exhaustion reads as a benign revert.
/// @param stipend The value returned by {stipendFrom} and passed as `{gas: …}`.
/// @param consumed `available - gasleft()`, measured after the call returned.
function exhausted(uint256 stipend, uint256 consumed) internal pure returns (bool) {
return consumed >= stipend - stipend / SLACK_DIVISOR;
}
}
src/utils/PositionKind.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @notice Semantic discriminator for a PositionBalance entry.
/// @dev Used by NAVCalculator consumers to branch on action family without string parsing.
/// `isDebt` on the enclosing PositionBalance is the canonical NAV-sign signal;
/// `PositionKind` provides human-readable category context on top of that.
/// Assignment rule: the kind reflects the OUTERMOST action family — what the account does to
/// enter/exit the position. A position exited via unstake is `Staking` regardless of what is
/// wrapped inside (e.g. gauge-staked LP); the inner exposure stays recoverable from
/// `protocolSubId`/`positionId`. LP principal sitting unstaked in the wallet is `Supplied`.
/// @author KPK
enum PositionKind {
Wallet, // plain ERC20 / native-token balance held directly (ERC20DefaultBalanceAdapter)
Supplied, // credit deployed into a protocol: lending supply, vault shares, unstaked LP principal
Borrowed, // debt owed to a protocol (isDebt = true)
Collateral, // credit locked as collateral (e.g. Aave reserve with usageAsCollateralEnabled = true)
Staking, // staking principal: tokens locked behind an unstake action (Safety Module, Umbrella, StakeWise vaults, gauge/Convex-staked LP)
Rewards, // accrued but not yet claimed reward tokens (e.g. CRV, CVX, BAL, COMP)
Fees // uncollected protocol or LP fees (e.g. Uniswap V3 position fees)
}
src/utils/ProtocolIds.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @notice Canonical protocol-taxonomy constants — `protocolBrand`, `protocolId`, and `protocolSubId`
/// — for every balance adapter family.
/// @dev Each constant is `keccak256` of a lowercase-ASCII, kebab-case slug; the protocol version is
/// baked into the slug only where the protocol is a distinct versioned system (e.g. `aave-v3`,
/// `balancer-v2`/`-v3`), so unversioned protocols carry no version. A single `protocolSubId`
/// maps to exactly one `positionId` ABI-decode schema — narrow enough that the client knows how
/// to decode without runtime sniffing.
///
/// positionId schemas (all are `abi.encode(...)`):
/// WALLET → (address asset)
/// AAVE_V3_LENDING / SPARK_LEND → (address pool) — one position per instance; reserve in balanceAsset
/// AAVE_V4_LENDING → (address spoke) — one position per Spoke; reserve in balanceAsset
/// AAVE_V3_SAFETY_MODULE / UMBRELLA→ (address stakeToken) for BOTH staking legs (no discriminator);
/// isLocked=non-withdrawable splits them — active stake is LOCKED
/// (isLocked=true), only a cooldown elapsed-and-in-window is UNLOCKED;
/// the reward leg shares it too, told apart by positionKind=Rewards
/// MORPHO_VAULTS / GEARBOX_V3_MARKETS / GEARBOX_V3_CREDIT_ACCOUNTS / EULER_VAULTS / ERC4626 /
/// STAKEWISE_V3_VAULTS / FLUID_VAULTS / SYMBIOTIC_VAULTS → (address vault / market / credit account)
/// CAP → (address token: cUSD or stcUSD) — one leg per token
/// MORPHO_MARKETS → (bytes32 marketId)
/// BALANCER_V3_POOLS → (address pool)
/// BALANCER_V3_GAUGES / V2_GAUGES → (address gauge)
/// CONVEX_CURVE_LP_STAKING → (address rewarder)
/// CURVE_POOLS → (address pool)
/// POLYGON_STAKING → (address validatorShare) — ONE positionId, two legs
/// (Staking principal + Rewards) told apart by positionKind
/// CURVE_GAUGES → (address gauge)
/// BALANCER_V2_POOLS → (bytes32 poolId)
/// UNISWAP_V3 / PANCAKESWAP_V3 → (address pool); NFT tokenId in positionInstanceId (bytes32(tokenId))
/// UNISWAP_V2 / PANCAKESWAP_V2 → (address pair)
/// COMPOUND_V3_COMETS / FLUID_FTOKENS → (address comet / fToken)
/// MERKL → (address distributor) — reward token is in balanceAsset, not positionId
/// NEXUS_MUTUAL_STAKING_POOLS → (address stakingPool); StakingNFT tokenId in positionInstanceId
/// STADER_WITHDRAWAL → (address userWithdrawalManager) — static coordinate
/// KELP_WITHDRAWAL → (address withdrawalManager) — static coordinate; payout asset in balanceAsset
/// LIDO_WITHDRAWAL → (address withdrawalQueue) — static coordinate
/// ETHENA_COOLDOWN → (address sUSDe) — static coordinate
/// ETHERFI_WITHDRAWAL → (address withdrawRequestNFT) — static coordinate
/// LIDO_STAKED_ETH → (address token: wstETH | stETH) — wallet-held, one leg per token
/// ETHERFI_STAKED_ETH → (address token: eETH | weETH)
/// ROCKET_POOL_STAKED_ETH → (address token: rETH)
/// RENZO_RESTAKED_ETH → (address token: ezETH)
/// KELP_RESTAKED_ETH → (address token: rsETH)
/// STADER_STAKED_ETH → (address token: ETHx)
/// STAKEWISE_V3_OS_TOKENS → (address token: osETH | osGNO)
/// LIQUID_COLLECTIVE_STAKED_ETH → (address token: lsETH)
/// ANKR_STAKED_ETH → (address token: ankrETH)
/// COINBASE_STAKED_ETH → (address token: cbETH)
/// RESERVE_BASKETS → (address token: ETH+)
/// ETHENA_SAVINGS → (address token: sUSDe)
/// SKY_SAVINGS → (address token: sDAI | sUSDS)
/// AAVE_V3_SAVINGS → (address token: sGHO)
/// SPARK_SAVINGS → (address token: spUSDC | spUSDT | spETH)
/// MAPLE_SAVINGS → (address token: syrupUSDC)
/// NEXUS_MUTUAL_VAULTS → (address token: RWIV)
/// STAKEWISE_V3_EXIT → (address vault) — static, per vault
/// (for these: a static positionId with up to two legs — claimable (isLocked=false) + locked
/// (isLocked=true) — sharing it, told apart by isLocked; owed asset is in balanceAsset. isLocked
/// is part of the identity key. See docs/decisions/0016-islocked-position-status.md.)
/// BRIDGE_ESCROW → (address escrow, address token)
/// @author KPK
library ProtocolIds {
bytes32 internal constant WALLET = keccak256("wallet");
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
// Brand ids — the broadest `PositionBalance.protocolBrand` layer (the protocol brand, version-stripped). Several
// ecosystem ids roll up to one brand: AAVE_V3 + AAVE_V4 → AAVE; BALANCER_V2 + BALANCER_V3 → BALANCER; UNISWAP_V2 +
// UNISWAP_V3 → UNISWAP; etc. For unversioned protocols the brand equals the ecosystem id (CURVE, MORPHO, FLUID,
// EULER, LIDO, KELP, …) — those reuse the same constant; only the versioned brands need a dedicated constant here.
// Display/grouping only; NOT part of the stable identity key (that uses `protocolSubId`).
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
bytes32 internal constant AAVE = keccak256("aave");
bytes32 internal constant BALANCER = keccak256("balancer");
bytes32 internal constant UNISWAP = keccak256("uniswap");
bytes32 internal constant PANCAKESWAP = keccak256("pancakeswap");
bytes32 internal constant GEARBOX = keccak256("gearbox");
bytes32 internal constant STAKEWISE = keccak256("stakewise");
bytes32 internal constant COMPOUND = keccak256("compound");
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
// Ecosystem ids — the broad `PositionBalance.protocolId` (grouping / roll-up layer). Several per-product slugs
// below (the `protocolSubId`s) roll up to one of these, e.g. AAVE_V3_LENDING + AAVE_V3_SAFETY_MODULE + AAVE_V3_UMBRELLA
// → AAVE_V3. For single-product ecosystems the adapter uses the SAME constant for both protocolId and protocolSubId
// (e.g. UNISWAP_V3, CAP, MERKL, WALLET, ERC4626) — no separate ecosystem constant needed. (CONVEX and CURVE keep
// distinct per-product subIds — CONVEX_CURVE_LP_STAKING, CURVE_POOLS/CURVE_GAUGES — so for them protocolId differs
// from protocolSubId even though they roll up to the CONVEX/CURVE ecosystem id.)
// The version is kept in the ecosystem id where the protocol is a distinct system (aave-v3, balancer-v2/-v3,
// uniswap-v2/-v3), so different versions are different `protocolId`s. NOT part of the stable identity key — that
// uses `protocolSubId`. See INAVCalculator.PositionBalance.
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
bytes32 internal constant AAVE_V3 = keccak256("aave-v3");
bytes32 internal constant AAVE_V4 = keccak256("aave-v4");
bytes32 internal constant GEARBOX_V3 = keccak256("gearbox-v3");
bytes32 internal constant STAKEWISE_V3 = keccak256("stakewise-v3");
bytes32 internal constant MORPHO = keccak256("morpho");
bytes32 internal constant BALANCER_V2 = keccak256("balancer-v2");
bytes32 internal constant BALANCER_V3 = keccak256("balancer-v3");
bytes32 internal constant FLUID = keccak256("fluid");
bytes32 internal constant EULER = keccak256("euler");
bytes32 internal constant SYMBIOTIC = keccak256("symbiotic");
bytes32 internal constant LIDO = keccak256("lido");
bytes32 internal constant POLYGON = keccak256("polygon"); // Polygon ecosystem id; unversioned, so this is also the brand
bytes32 internal constant KELP = keccak256("kelp");
bytes32 internal constant STADER = keccak256("stader");
bytes32 internal constant ETHERFI = keccak256("etherfi");
bytes32 internal constant ETHENA = keccak256("ethena");
bytes32 internal constant SPARK = keccak256("spark");
bytes32 internal constant ROCKET_POOL = keccak256("rocket-pool");
bytes32 internal constant RENZO = keccak256("renzo");
bytes32 internal constant LIQUID_COLLECTIVE = keccak256("liquid-collective");
bytes32 internal constant ANKR = keccak256("ankr");
bytes32 internal constant COINBASE = keccak256("coinbase");
bytes32 internal constant RESERVE = keccak256("reserve");
bytes32 internal constant SKY = keccak256("sky");
bytes32 internal constant MAPLE = keccak256("maple");
bytes32 internal constant NEXUS_MUTUAL = keccak256("nexus-mutual");
// (CURVE below doubles as the Curve ecosystem id for CURVE_POOLS/CURVE_GAUGES.)
// ── Per-product slugs (`protocolSubId`; selects the positionId decode schema) ──
// Aave family
bytes32 internal constant AAVE_V3_LENDING = keccak256("aave-v3-lending");
bytes32 internal constant AAVE_V3_SAFETY_MODULE = keccak256("aave-v3-safety-module");
bytes32 internal constant AAVE_V3_UMBRELLA = keccak256("aave-v3-umbrella");
bytes32 internal constant AAVE_V4_LENDING = keccak256("aave-v4-lending");
// Morpho
bytes32 internal constant MORPHO_VAULTS = keccak256("morpho-vaults");
bytes32 internal constant MORPHO_MARKETS = keccak256("morpho-markets");
// Balancer
bytes32 internal constant BALANCER_V3_POOLS = keccak256("balancer-v3-pools");
bytes32 internal constant BALANCER_V3_GAUGES = keccak256("balancer-v3-gauges");
bytes32 internal constant BALANCER_V2_POOLS = keccak256("balancer-v2-pools");
bytes32 internal constant BALANCER_V2_GAUGES = keccak256("balancer-v2-gauges");
// Uniswap / PancakeSwap
bytes32 internal constant UNISWAP_V3 = keccak256("uniswap-v3");
bytes32 internal constant UNISWAP_V2 = keccak256("uniswap-v2");
bytes32 internal constant PANCAKESWAP_V3 = keccak256("pancakeswap-v3");
bytes32 internal constant PANCAKESWAP_V2 = keccak256("pancakeswap-v2");
// StakeWise
bytes32 internal constant STAKEWISE_V3_VAULTS = keccak256("stakewise-v3-vaults");
// Polygon PoS staking (Ethereum L1 StakeManager / ValidatorShare)
bytes32 internal constant POLYGON_STAKING = keccak256("polygon-staking"); // delegation → (address validatorShare)
// Nexus Mutual
bytes32 internal constant NEXUS_MUTUAL_STAKING_POOLS = keccak256("nexus-mutual-staking-pools");
// Gearbox
bytes32 internal constant GEARBOX_V3_MARKETS = keccak256("gearbox-v3-markets");
bytes32 internal constant GEARBOX_V3_CREDIT_ACCOUNTS = keccak256("gearbox-v3-credit-accounts");
// Euler
bytes32 internal constant EULER_VAULTS = keccak256("euler-vaults");
// Symbiotic
bytes32 internal constant SYMBIOTIC_VAULTS = keccak256("symbiotic-vaults");
// Compound
bytes32 internal constant COMPOUND_V3 = keccak256("compound-v3");
bytes32 internal constant COMPOUND_V3_COMETS = keccak256("compound-v3-comets");
// Fluid
bytes32 internal constant FLUID_FTOKENS = keccak256("fluid-ftokens");
bytes32 internal constant FLUID_VAULTS = keccak256("fluid-vaults");
// Spark
bytes32 internal constant SPARK_LEND = keccak256("spark-lend");
// Curve / Convex
bytes32 internal constant CURVE = keccak256("curve"); // Curve ecosystem id (protocolId for CURVE_POOLS/CURVE_GAUGES)
bytes32 internal constant CURVE_POOLS = keccak256("curve-pools"); // wallet LP → (address pool)
bytes32 internal constant CURVE_GAUGES = keccak256("curve-gauges"); // gauge-staked LP → (address gauge)
bytes32 internal constant CONVEX = keccak256("convex");
bytes32 internal constant CONVEX_CURVE_LP_STAKING = keccak256("convex-curve-lp-staking");
// Cap
bytes32 internal constant CAP = keccak256("cap");
// Generic ERC4626 wrapper
bytes32 internal constant ERC4626 = keccak256("erc4626");
// Withdrawal / cooldown queues
// positionId = `abi.encode(<anchor contract>)` (the queue/manager — Lido queue, Stader/Kelp
// manager, ether.fi NFT, StakeWise vault, sUSDe). Up to two legs share it, told apart by
// isLocked (the owed/payout asset is in balanceAsset, not the positionId).
bytes32 internal constant STADER_WITHDRAWAL = keccak256("stader-withdrawal");
bytes32 internal constant KELP_WITHDRAWAL = keccak256("kelp-withdrawal");
bytes32 internal constant LIDO_WITHDRAWAL = keccak256("lido-withdrawal");
bytes32 internal constant ETHENA_COOLDOWN = keccak256("ethena-cooldown");
bytes32 internal constant ETHERFI_WITHDRAWAL = keccak256("etherfi-withdrawal");
// Wallet-held yield-bearing tokens (WalletTokenMetaBalanceAdapterBase family). The token is itself the
// registered, priced NAV asset, so every positionId here is `abi.encode(address token)` and the
// balanceAsset is that same token. One subId per PROTOCOL, not per token: several tokens share a subId
// (wstETH + stETH under Lido) because they are the same product, and the positionId separates them.
bytes32 internal constant LIDO_STAKED_ETH = keccak256("lido-staked-eth");
bytes32 internal constant ETHERFI_STAKED_ETH = keccak256("etherfi-staked-eth");
bytes32 internal constant ROCKET_POOL_STAKED_ETH = keccak256("rocket-pool-staked-eth");
bytes32 internal constant RENZO_RESTAKED_ETH = keccak256("renzo-restaked-eth");
bytes32 internal constant KELP_RESTAKED_ETH = keccak256("kelp-restaked-eth");
bytes32 internal constant STADER_STAKED_ETH = keccak256("stader-staked-eth");
bytes32 internal constant STAKEWISE_V3_OS_TOKENS = keccak256("stakewise-v3-os-tokens");
bytes32 internal constant LIQUID_COLLECTIVE_STAKED_ETH = keccak256("liquid-collective-staked-eth");
bytes32 internal constant ANKR_STAKED_ETH = keccak256("ankr-staked-eth");
bytes32 internal constant COINBASE_STAKED_ETH = keccak256("coinbase-staked-eth");
bytes32 internal constant RESERVE_BASKETS = keccak256("reserve-baskets");
bytes32 internal constant ETHENA_SAVINGS = keccak256("ethena-savings");
bytes32 internal constant SKY_SAVINGS = keccak256("sky-savings");
bytes32 internal constant AAVE_V3_SAVINGS = keccak256("aave-v3-savings");
bytes32 internal constant SPARK_SAVINGS = keccak256("spark-savings");
bytes32 internal constant MAPLE_SAVINGS = keccak256("maple-savings");
bytes32 internal constant NEXUS_MUTUAL_VAULTS = keccak256("nexus-mutual-vaults");
bytes32 internal constant STAKEWISE_V3_EXIT = keccak256("stakewise-v3-exit");
// Merkl rewards distributor
bytes32 internal constant MERKL = keccak256("merkl");
// Bridge escrow
bytes32 internal constant BRIDGE_ESCROW = keccak256("bridge-escrow");
}
src/utils/StaticCallLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {GasStipendLib} from "src/utils/GasStipendLib.sol";
/// @title StaticCallLib
/// @author KPK
/// @notice Best-effort view-call helpers for reading from possibly-noncompliant external contracts: a staticcall
/// that decodes a uint256/address and never reverts on a failed, short, oversized or undecodable call.
/// @dev Consolidates the staticcall+decode wrappers that were copy-pasted — and had begun to drift — across
/// ConvexCurveLPStakingMeta and UniswapV2PairLib (the call sites migrated so far).
/// NOTE: this is NOT yet the repo-wide single source of truth — other hand-rolled copies remain and do
/// not route through this library: CurvePoolLib, FluidVaultLib, CompoundV3CometLib, and AaveUmbrella.
/// Some even differ subtly (e.g. CurvePoolLib gates its address-decoding `lp_token()`/`minter()` reads on
/// `returndata.length == 32` where this library uses `>= 32`), so migrating them is a behavior-sensitive
/// follow-up, not a no-op. Internal library: inlined
/// into each caller (no separate deployment, no DELEGATECALL), so this is a maintainability change, not a
/// size one.
///
/// **Three properties make the "never reverts" claim actually hold** for {safeUint}, {safeAddr},
/// {safeAddrStrict} and {probeWord}, and all three are load-bearing. **{probeWordMetered} is deliberately
/// NOT one of these helpers**: it keeps properties 2 and 3 but drops property 1, forwarding 63/64 of the
/// frame instead of a fixed ceiling. It still does not revert *itself* — nothing in its body can — but it
/// is the one helper whose contract asks the CALLER to revert, on `starved`, so a read routed through it
/// is no longer one that cannot fail. Read its own docblock before routing anything through it:
///
/// 1. **Bounded gas** ({PROBE_GAS}). Without a stipend a callee that loops forever consumes 63/64 of
/// whatever the caller had, so one malformed instance starves every read that follows it — a fail-open
/// that silently drops later positions rather than a single value. {probeWordMetered} forwards exactly
/// that 63/64, on purpose: it is for a read whose absence changes a NAV number, where a fixed ceiling is
/// unrecoverable and the starvation must be made visible rather than absorbed. Its caller is expected to
/// REVERT on `starved`. Do not reach for it merely because it is the one that reports starvation.
/// 2. **A fixed 32-byte output area.** Assigning `(bool ok, bytes memory ret)` from a raw staticcall makes
/// solc `returndatacopy` the *entire* reply into freshly allocated memory — revert payloads included —
/// and the quadratic cost of that copy is paid by the *caller*, on top of whatever the callee already
/// spent producing it. Writing straight into scratch memory through a 32-byte output window means the
/// reply size cannot influence the caller's gas at all: bytes past the first word are discarded by the
/// EVM, never copied.
/// 3. **Masking rather than `abi.decode`.** `abi.decode(ret, (address))` emits a validator that reverts
/// when bits above 160 are dirty, and that revert fires in the *calling* frame — a `try`/`catch` around
/// the caller does not stop it. {safeAddr} truncates instead, exactly as `address(uint160(word))` does
/// everywhere else in the EVM, so a sloppy callee yields a (possibly wrong) address rather than taking
/// the whole read down. Callers already treat `address(0)` / an unusable address as "absent".
///
/// IMPORTANT: `ok` is the raw `staticcall` success flag only — it does NOT incorporate the returndata-length
/// check. A call can return `ok == true` with `result == 0` if the callee returned fewer than 32 bytes
/// (decoding is skipped in that case), which mirrors the exact semantics of the per-adapter helpers this
/// library replaced. Callers that must distinguish "call succeeded but gave no usable value" from "returned
/// zero" cannot get that from `(ok, result)` at all — they should call {probeWord} and gate on its
/// `hasWord`, rather than hand-roll another raw staticcall. A code-less `target` likewise yields
/// `ok == true` with empty returndata — a raw staticcall has no `extcodesize` precheck — so a `code.length`
/// guard in front of these helpers would be dead code, not a safety net.
library StaticCallLib {
/// @notice Gas stipend forwarded to every probe.
/// @dev Ample for a real metadata/accounting read even through a couple of proxy hops (the reads routed here
/// are storage getters and small accounting formulas, an order of magnitude cheaper), while bounding
/// what a hostile or broken callee can burn on the caller's behalf. Mirrors the `PROBE_GAS` stipends
/// the adapters that harden their own reads already use.
uint256 internal constant PROBE_GAS = 100_000;
/// @notice staticcalls `target` with `data`, decoding a uint256 only if the call returned ≥ 32 bytes.
/// @return ok The raw staticcall success flag (true even when fewer than 32 bytes were returned).
/// @return result The decoded uint256; 0 if the call reverted OR returned fewer than 32 bytes.
function safeUint(address target, bytes memory data) internal view returns (bool ok, uint256 result) {
bool hasWord;
uint256 word;
(ok, hasWord, word) = probeWord(target, data);
if (hasWord) result = word;
}
/// @notice staticcalls `target` with `data`, decoding an address only if the call returned ≥ 32 bytes.
/// @dev The first returned word is masked to 160 bits rather than run through `abi.decode(ret, (address))`,
/// which reverts on dirty upper bits — see the note on the library.
/// @return ok The raw staticcall success flag (true even when fewer than 32 bytes were returned).
/// @return result The decoded address; address(0) if the call reverted OR returned fewer than 32 bytes.
function safeAddr(address target, bytes memory data) internal view returns (bool ok, address result) {
bool hasWord;
uint256 word;
(ok, hasWord, word) = probeWord(target, data);
if (hasWord) result = address(uint160(word));
}
/// @notice As {safeAddr}, but REJECTS a word with dirty bits above 160 instead of masking it off, and tells
/// the caller when that happened.
/// @dev Both policies are legitimate and the choice is per call site, not per library, which is why both
/// exist here rather than one being "the" address reader:
///
/// - **Mask** ({safeAddr}) favours liveness. A sloppy-but-honest callee — a `bytes32`-shaped return, a
/// padding-careless implementation — still yields a usable address. Right when a wrong address simply
/// fails downstream (an unregistered reward token is skipped; a bogus LP token resolves to nothing).
/// - **Reject** (this) favours a clean "cannot read" sentinel. Right when `address(0)` is a MEANINGFUL
/// value that a caller branches on, so silently manufacturing it from garbage changes the answer
/// rather than losing it.
///
/// Two call sites need the strict form: Euler's `EVC()`, whose `address(0)` is the "cannot classify"
/// sentinel `_supplyKind` short-circuits on, and Uniswap V2's `feeTo()`, whose `address(0)` means "no
/// protocol fee" and so drops the dilution term and RAISES the reported LP share.
///
/// **`malformed` reports "answered, but not with an address" — NOT merely "no address available".**
/// That distinction is the whole point and it is easy to get wrong. A callee that returns NOTHING (a
/// code-less target, an empty reply, a revert) has told you it does not implement the selector, which
/// for an optional view is ordinary and usually means "treat it as absent". A callee that returns a
/// full word which is not a valid address has told you something is broken. Folding both into one
/// "not an address" flag makes callers drop positions over a missing optional getter — so `malformed`
/// is deliberately false for a short or absent reply, and callers distinguish that case via `ok` and a
/// zero `result` exactly as they would with {safeAddr}.
/// @return ok The raw staticcall success flag (true even when the word was rejected as not an address).
/// @return result The address; address(0) if the call reverted, returned fewer than 32 bytes, or returned a
/// word that is not a valid address.
/// @return malformed True ONLY when a full word came back AND its upper 96 bits are dirty. False for a
/// revert, a short reply, or a code-less target — those are "absent", not "broken".
function safeAddrStrict(address target, bytes memory data)
internal
view
returns (bool ok, address result, bool malformed)
{
bool hasWord;
uint256 word;
(ok, hasWord, word) = probeWord(target, data);
malformed = hasWord && word >> 160 != 0;
if (hasWord && !malformed) result = address(uint160(word));
}
/// @notice Performs the bounded staticcall and hands back the first returned word, undecoded.
/// @dev Exposed because {safeUint}'s `(ok, result)` pair cannot distinguish "returned zero" from "returned
/// nothing", and for some reads that difference is load-bearing — Convex's `pid()` is the canonical
/// example, where a short reply read as `0` would silently resolve to Booster pool 0's LP token.
/// Those callers gate on `hasWord` instead of inventing another raw staticcall.
///
/// The output window is the 32-byte scratch slot at 0x00, so `returndatasize()` never influences the
/// caller's memory footprint: the EVM copies `min(returndatasize(), 32)` bytes and drops the rest. The
/// scratch space (0x00–0x3f) is free for transient use, which is why this block is `memory-safe`.
///
/// `word` is returned as 0 unless `hasWord`, and that assignment is load-bearing rather than tidiness.
/// A fixed output window is not cleared between probes: on an empty reply the EVM writes nothing, so
/// the slot still holds whatever the *previous* probe left there — inside one `getAdapterPositions`
/// sweep, that is the preceding instance's successful reply, not obvious garbage. The `bytes memory`
/// shape this replaced allocated fresh memory per call and so made "the callee returned nothing"
/// structurally unreadable; zeroing here restores that guarantee for the same three gas.
/// @return ok The raw staticcall success flag. Callers wanting "did I get a value" want `hasWord`, not this.
/// @return hasWord True when the call succeeded AND returned at least one full word.
/// @return word The first 32 bytes of returndata, or 0 when `!hasWord`.
function probeWord(address target, bytes memory data) internal view returns (bool ok, bool hasWord, uint256 word) {
uint256 size;
uint256 raw;
assembly ("memory-safe") {
ok := staticcall(PROBE_GAS, target, add(data, 0x20), mload(data), 0x00, 0x20)
size := returndatasize()
raw := mload(0x00)
}
hasWord = ok && size >= 32;
// `ok &&` is not redundant with the size check: a callee that reverts with a standard `Error(string)`
// payload produces ≥ 32 bytes of returndata, which the EVM copies into the output window exactly as a
// successful reply would. Without `ok`, that revert payload's first word would be handed back as a value.
if (hasWord) word = raw;
}
/// @notice As {probeWord}, but it derives its own stipend from the calling frame and reports whether a
/// failed call ran out of that stipend rather than answering.
/// @dev Exists because {probeWord}'s two properties — a fixed {PROBE_GAS} ceiling and a `false` that folds
/// "reverted" together with "ran out of gas" — are wrong for a read whose absence changes a NAV number
/// rather than a label.
///
/// **Why the stipend is a share of the frame.** {PROBE_GAS} is local and fixed, so a starved read cannot
/// be rescued by handing the whole call more gas — the ceiling binds first, identically, at every budget.
/// That is tolerable for a cosmetic read and not for an accounting one: it makes the failure permanent
/// rather than a matter of asking for more.
///
/// **Why `starved` is separate from `ok`.** A revert and an exhausted stipend are indistinguishable in
/// the success flag alone, and they deserve opposite treatment: a contract that genuinely does not
/// implement the selector has ANSWERED, and failing open is right; one that ran out of gas has not, and
/// recording its absence as a zero is how a missing debt leg becomes a higher NAV.
///
/// **The threshold is measured against `available`, NOT against the stipend, and that is the whole of
/// the correctness argument.** These reads sit under a caller — `MetaBalanceAdapter`'s per-instance
/// classifier — that asks the same question one frame up, on ITS budget `S`, and raises only at
/// `7/8 * S`. Classifying here against the stipend would test `7/8 * (63/64) * S = 0.861 * S`, strictly
/// LOWER. Between the two lies a real band: a callee burning 86-87% of the frame trips this guard, the
/// caller's `catch` then reads the resulting revert as an ordinary one, and the whole instance is
/// dropped in silence — the exact outcome the guard exists to prevent, plus a fresh silent loss of any
/// leg that would otherwise have survived. Measured at ~1.3% of the stipend wide before this was
/// corrected. Testing against `available` puts this threshold at or above the caller's, so a raise here
/// always becomes the caller's loud classification instead of vanishing into it.
///
/// **Generalise it before adding another one of these.** Any guard nested beneath a frame-share
/// classifier inherits that band unless it derives its threshold from the same frame. Two guards that
/// both use {GasStipendLib} are still not composed correctly if one of them measures a 63/64 slice of
/// what the other measures.
///
/// **The operand here is deliberately not what its name says.** `GasStipendLib.exhausted`'s first
/// parameter is called `stipend` and its NatSpec describes the value passed as `{gas: ...}` — which is
/// what `MetaBalanceAdapter` passes, correctly, because it IS the outermost guard. This call passes the
/// FRAME instead, and that inversion is the whole of the fix above: an inner guard has to test against
/// the same quantity its caller will, not against the smaller slice it forwarded. Anyone reading
/// `exhausted`'s signature and matching the parameter name will reintroduce the band.
///
/// No stipend parameter, deliberately. A caller-supplied one invites exactly the value that breaks the
/// nesting above — a fixed ceiling, or a slice of a frame this function cannot see — and `0` would make
/// `exhausted` true for every failed call.
/// @return ok The raw staticcall success flag.
/// @return hasWord True when the call succeeded AND returned at least one full word.
/// @return word The first 32 bytes of returndata, or 0 when `!hasWord`.
/// @return starved True ONLY when the call failed AND consumed essentially the whole calling frame.
/// @return budget The frame this was measured against — reportable in the caller's error.
/// @return consumed Gas the call cost this frame — likewise.
function probeWordMetered(address target, bytes memory data)
internal
view
returns (bool ok, bool hasWord, uint256 word, bool starved, uint256 budget, uint256 consumed)
{
budget = gasleft();
uint256 stipend = GasStipendLib.stipendFrom(budget);
uint256 size;
uint256 raw;
assembly ("memory-safe") {
ok := staticcall(stipend, target, add(data, 0x20), mload(data), 0x00, 0x20)
size := returndatasize()
raw := mload(0x00)
}
consumed = budget - gasleft();
hasWord = ok && size >= 32;
if (hasWord) word = raw;
if (!ok) starved = GasStipendLib.exhausted(budget, consumed);
}
}
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.