Verified contractPartialBUSL-1.1
NAVRegistryLib
Address0x55b6aa29d296eb2ee0e7b76686eaa2e479ca3511
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.34
- Same code
Only this contract
Details
- Compiler
- solc 0.8.34+commit.80d5c536
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,783,701
- Creation transaction
- 0x99e7e33f3a…51c2aa2853
- Libraries
- src/nav/NAVRegistryLib.sol:NAVRegistryLib0x55b6…ca3511src/prices/PriceFeedLib.sol:PriceFeedLib0x713e…dbfebc
27 files
- src/nav/NAVRegistryLib.solmain23.77 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol2.78 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol684 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Arrays.sol35.55 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Comparators.sol443 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Panic.sol1.97 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/SlotDerivation.sol5.32 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol4.18 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol5.85 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol871 B
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol32.66 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/SafeCast.sol34.94 KB
- lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/structs/EnumerableSet.sol33.3 KB
- src/balances/BalanceAdapterBase.sol1.98 KB
- src/balances/BalanceAdapters/ERC20DefaultBalanceAdapter.sol20.81 KB
- src/balances/IBalanceAdapter.sol2.43 KB
- src/balances/IBalances.sol4.56 KB
- src/balances/IComputedLabelSegments.sol4.24 KB
- src/balances/IMetaBalanceAdapter.sol2.86 KB
- src/balances/IPositionDescribable.sol5.07 KB
- src/balances/LabelLib.sol12.67 KB
- src/errors.sol3.05 KB
- src/nav/INAVCalculator.sol77.63 KB
- src/prices/IPrices.sol15.51 KB
- src/utils/ArrayLib.sol3.13 KB
- src/utils/PositionKind.sol1.47 KB
- src/utils/ProtocolIds.sol12.09 KB
src/nav/NAVRegistryLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ERC165Checker} from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import {INAVCalculator} from "./INAVCalculator.sol";
import {IBalances} from "src/balances/IBalances.sol";
import {IBalanceAdapter} from "src/balances/IBalanceAdapter.sol";
import {IMetaBalanceAdapter} from "src/balances/IMetaBalanceAdapter.sol";
import {ArrayLib} from "src/utils/ArrayLib.sol";
import {ERC20DefaultBalanceAdapter} from "src/balances/BalanceAdapters/ERC20DefaultBalanceAdapter.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";
/// @title NAVRegistryLib
/// @notice External library for NAVCalculator's registry storage mutations (the asset registry + the balance-adapter
/// registry), extracted to keep NAVCalculator under EIP-170 (mirrors the PriceFeedLib pattern).
/// @dev Functions are `external` so the library compiles as a separate artifact and is invoked via DELEGATECALL,
/// operating on the caller's own storage through the passed `storage` references. Pre-linked at a deterministic
/// CREATE2 address (see `foundry.toml`) and deployed by `01_2_DeployNAVImplementation.s.sol` before NAVCalculator.
/// The heavier registry work lives here: the ERC20Default factory, asset register/unregister, single + batch
/// adapter add/remove, meta-adapter registration, and meta-instance add/remove (several return a per-call count),
/// plus two read helpers (getAdaptersForAsset, extractUniqueAssets). The running totals stay inline in the caller,
/// as do the trivial getters and the single add/remove paths' event emission (the batch and meta paths emit their
/// events here) — keeping that work in the caller is cheaper than crossing the DELEGATECALL boundary.
/// @author KPK
library NAVRegistryLib {
using ERC165Checker for address;
/// @notice Native-asset sentinel (mirrors Balances.NATIVE_ADDRESS).
address private constant NATIVE_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
// -------------------------------------------------------------------------
// ERC20Default adapter factory
// -------------------------------------------------------------------------
/// @notice Deploys a fresh ERC20DefaultBalanceAdapter bound to the calling NAVCalculator and returns it.
/// @dev This function does NOT enforce single-deploy semantics — each call deploys a new adapter. The
/// one-adapter invariant is enforced by the caller: NAVCalculator.initialize calls this exactly once and
/// passes the result to `_setErc20DefaultBalanceAdapter`, which reverts if the default adapter is already set.
/// Called via DELEGATECALL, so `address(this)` is the NAV proxy — the adapter's
/// immutable NAV_CALCULATOR is pinned to it and the proxy is the CREATE deployer. Housed here so the
/// adapter's ~5 KB creation bytecode is embedded in THIS external library rather than NAVCalculator's
/// runtime code, keeping NAVCalculator well under EIP-170. `initialAssets` seeds the inclusion list
/// (e.g. NATIVE_ADDRESS) at construction without a callback to the still-initializing proxy.
/// @param initialAssets Assets to pre-add to the adapter's inclusion list.
/// @return adapter The deployed ERC20DefaultBalanceAdapter address.
function deployDefaultAdapter(address[] memory initialAssets) external returns (address adapter) {
return address(new ERC20DefaultBalanceAdapter(address(this), initialAssets));
}
// -------------------------------------------------------------------------
// Asset registry
// -------------------------------------------------------------------------
/// @notice Registers an asset in the NAV/Pricing registry.
/// @dev Reverts InvalidArguments if `asset` is already registered. Otherwise fetches decimals and symbol: for
/// NATIVE_ADDRESS uses 18 and `nativeTokenSymbol`; for any other asset requires ERC20-compatibility (both
/// decimals() and symbol() must succeed) and reverts InvalidArguments if either call fails. Mirrors the
/// former NAVCalculator._registerAsset.
/// @param registeredAssets The ordered asset registry (storage ref)
/// @param assetIndex The 1-based index map (storage ref; 0 = not registered)
/// @param asset The asset to register
/// @param nativeTokenSymbol The symbol to use for the native asset sentinel
function registerAsset(
INAVCalculator.Asset[] storage registeredAssets,
mapping(address => uint256) storage assetIndex,
address asset,
string memory nativeTokenSymbol
) external {
if (assetIndex[asset] != 0) {
revert InvalidArguments(); // Asset already registered
}
uint8 decimals;
string memory symbol;
if (asset == NATIVE_ADDRESS) {
decimals = 18;
symbol = nativeTokenSymbol;
} else {
try IERC20Metadata(asset).decimals() returns (uint8 d) {
decimals = d;
} catch {
revert InvalidArguments(); // Not ERC20 compatible
}
try IERC20Metadata(asset).symbol() returns (string memory s) {
symbol = s;
} catch {
revert InvalidArguments(); // Not ERC20 compatible
}
}
registeredAssets.push(INAVCalculator.Asset({asset: asset, symbol: symbol, decimals: decimals}));
assetIndex[asset] = registeredAssets.length;
}
/// @notice Unregisters an asset from the NAV/Pricing registry (swap-remove, keeps the index map 1-based).
/// @dev Reverts AssetNotFound if `asset` is not registered. Mirrors the former NAVCalculator._unregisterAsset.
/// @param registeredAssets The ordered asset registry (storage ref)
/// @param assetIndex The 1-based index map (storage ref)
/// @param asset The asset to unregister
function unregisterAsset(
INAVCalculator.Asset[] storage registeredAssets,
mapping(address => uint256) storage assetIndex,
address asset
) external {
uint256 idx = assetIndex[asset];
if (idx == 0) {
revert AssetNotFound();
}
uint256 lastIdx = registeredAssets.length;
if (idx != lastIdx) {
INAVCalculator.Asset memory lastAsset = registeredAssets[lastIdx - 1];
registeredAssets[idx - 1] = lastAsset;
assetIndex[lastAsset.asset] = idx;
}
registeredAssets.pop();
delete assetIndex[asset];
}
// -------------------------------------------------------------------------
// Balance-adapter registry
// -------------------------------------------------------------------------
/// @notice Adds a balance adapter to the global registry (Custom type), after validating it supports the
/// IBalanceAdapter interface. Mirrors the storage work of the former Balances._addBalanceAdapter;
/// the running count and the BalanceAdapterAdded event stay in the caller wrapper.
/// @param isAdapterRegistered Quick-lookup registration map (storage ref)
/// @param globalAdapters The global adapter list (storage ref)
/// @param adapterTypes The adapter-type map (storage ref)
/// @param adapter The adapter to add
function addBalanceAdapter(
mapping(address => bool) storage isAdapterRegistered,
address[] storage globalAdapters,
mapping(address => IBalances.AdapterType) storage adapterTypes,
address adapter
) external {
_registerAdapter(isAdapterRegistered, globalAdapters, adapterTypes, adapter, false);
}
/// @notice Registers a meta-adapter and seeds its instance set in one operation. Requires the adapter to
/// implement both IBalanceAdapter and IMetaBalanceAdapter. Reverts DuplicateBalanceAdapter if already
/// registered, InvalidArguments on a zero adapter, InvalidBalanceAdapter / NotMetaAdapter on the interface
/// checks, and DuplicateMetaInstance on a repeated coordinate. An empty instance list is allowed (registers the meta-adapter with no
/// instances yet). Emits BalanceAdapterAdded here (surfaces from the caller's address via DELEGATECALL);
/// the running counts (balanceAdapterTotalCount, _metaInstanceTotal) stay in the caller wrapper.
/// @param isAdapterRegistered Quick-lookup registration map (storage ref)
/// @param globalAdapters The global adapter list (storage ref)
/// @param adapterTypes The adapter-type map (storage ref)
/// @param metaInstances The per-adapter instance-set map (storage ref)
/// @param adapter The meta-adapter to add
/// @param instances The instance coordinates to seed (may be empty)
/// @return added The number of coordinates seeded (== instances.length)
function addMetaBalanceAdapter(
mapping(address => bool) storage isAdapterRegistered,
address[] storage globalAdapters,
mapping(address => IBalances.AdapterType) storage adapterTypes,
mapping(address => bytes32[]) storage metaInstances,
address adapter,
bytes32[] memory instances
) external returns (uint256 added) {
_registerAdapter(isAdapterRegistered, globalAdapters, adapterTypes, adapter, true);
emit IBalances.BalanceAdapterAdded(address(0), adapter, IBalances.AdapterType.Custom);
added = _appendInstances(metaInstances[adapter], instances);
}
/// @notice Removes an adapter from the global registry (swap-remove). Reverts on the ERC20Default singleton or an
/// unregistered adapter. Mirrors the storage work of the former Balances._removeBalanceAdapter; the running
/// count and the BalanceAdapterRemoved event stay in the caller wrapper.
/// @param isAdapterRegistered Quick-lookup registration map (storage ref)
/// @param globalAdapters The global adapter list (storage ref)
/// @param adapterTypes The adapter-type map (storage ref)
/// @param adapter The adapter to remove
/// @param erc20DefaultBalanceAdapter The default-adapter singleton that may not be removed
function removeBalanceAdapter(
mapping(address => bool) storage isAdapterRegistered,
address[] storage globalAdapters,
mapping(address => IBalances.AdapterType) storage adapterTypes,
address adapter,
address erc20DefaultBalanceAdapter
) external {
if (adapter == erc20DefaultBalanceAdapter) {
revert InvalidArguments(); // Cannot remove ERC20DefaultBalanceAdapter
}
if (!isAdapterRegistered[adapter]) {
revert IBalances.InvalidBalanceAdapter();
}
uint256 len = globalAdapters.length;
for (uint256 i = 0; i < len; i++) {
if (globalAdapters[i] == adapter) {
globalAdapters[i] = globalAdapters[len - 1];
globalAdapters.pop();
break;
}
}
delete isAdapterRegistered[adapter];
delete adapterTypes[adapter];
}
/// @notice Batch-registers non-meta balance adapters (the whole `addBalanceAdapters` body), emitting
/// BalanceAdapterAdded per adapter. Events emitted here surface from the caller's address (DELEGATECALL).
/// Reverts InvalidArguments (empty list / zero adapter), DuplicateBalanceAdapter, InvalidBalanceAdapter,
/// or MetaAdapterNotAllowed (a meta-adapter must use addMetaBalanceAdapter). All-or-nothing.
/// @param isAdapterRegistered Quick-lookup registration map (storage ref)
/// @param globalAdapters The global adapter list (storage ref)
/// @param adapterTypes The adapter-type map (storage ref)
/// @param adapters The non-meta adapters to add
/// @return count Number of adapters registered (== adapters.length).
function addBalanceAdapters(
mapping(address => bool) storage isAdapterRegistered,
address[] storage globalAdapters,
mapping(address => IBalances.AdapterType) storage adapterTypes,
address[] calldata adapters
) external returns (uint256 count) {
count = adapters.length;
if (count == 0) revert InvalidArguments();
for (uint256 i = 0; i < count; i++) {
address adapter = adapters[i];
_registerAdapter(isAdapterRegistered, globalAdapters, adapterTypes, adapter, false);
emit IBalances.BalanceAdapterAdded(address(0), adapter, IBalances.AdapterType.Custom);
}
}
/// @notice Batch-removes balance adapters (the whole `removeBalanceAdapters` body), emitting BalanceAdapterRemoved
/// per adapter (swap-remove). Reverts InvalidArguments (empty list / the ERC20Default singleton) and
/// InvalidBalanceAdapter (unregistered). All-or-nothing.
/// @param isAdapterRegistered Quick-lookup registration map (storage ref)
/// @param globalAdapters The global adapter list (storage ref)
/// @param adapterTypes The adapter-type map (storage ref)
/// @param erc20DefaultBalanceAdapter The default-adapter singleton that may not be removed
/// @param adapters The adapters to remove
/// @return count Number of adapters removed (== adapters.length).
function removeBalanceAdapters(
mapping(address => bool) storage isAdapterRegistered,
address[] storage globalAdapters,
mapping(address => IBalances.AdapterType) storage adapterTypes,
address erc20DefaultBalanceAdapter,
address[] calldata adapters
) external returns (uint256 count) {
count = adapters.length;
if (count == 0) revert InvalidArguments();
for (uint256 i = 0; i < count; i++) {
address adapter = adapters[i];
if (adapter == erc20DefaultBalanceAdapter) revert InvalidArguments();
if (!isAdapterRegistered[adapter]) revert IBalances.InvalidBalanceAdapter();
uint256 len = globalAdapters.length;
for (uint256 j = 0; j < len; j++) {
if (globalAdapters[j] == adapter) {
globalAdapters[j] = globalAdapters[len - 1];
globalAdapters.pop();
break;
}
}
delete isAdapterRegistered[adapter];
delete adapterTypes[adapter];
emit IBalances.BalanceAdapterRemoved(address(0), adapter);
}
}
/// @notice Returns every registered adapter that lists `asset` in its `underlyingAssetsSupported()`. A faulty
/// adapter (reverting that call) is skipped. Mirrors the storage work of the former
/// Balances.getAdaptersForAsset; extracted here to keep NAVCalculator under EIP-170.
/// @param globalAdapters The global adapter list (storage ref)
/// @param asset The asset to match
/// @return The registered adapters whose underlyingAssetsSupported() lists `asset` (faulty adapters skipped)
function getAdaptersForAsset(address[] storage globalAdapters, address asset)
external
view
returns (address[] memory)
{
uint256 adapterCount = globalAdapters.length;
address[] memory temp = new address[](adapterCount);
uint256 count = 0;
for (uint256 i = 0; i < adapterCount; i++) {
try IBalanceAdapter(globalAdapters[i]).underlyingAssetsSupported() returns (
address[] memory supportedAssets
) {
for (uint256 j = 0; j < supportedAssets.length; j++) {
if (supportedAssets[j] == asset) {
temp[count++] = globalAdapters[i];
break;
}
}
} catch {
continue;
}
}
return ArrayLib.copySliceAddress(temp, count);
}
/// @notice Returns the de-duplicated set of assets referenced by a list of position balances. Extracted from
/// NAVCalculator (hot read path) to keep it under EIP-170; NAV reads are off-chain eth_call so the
/// DELEGATECALL overhead is immaterial.
/// @dev Currently UNCALLED: PR #73 moved NAVCalculator's read engine into `PriceFeedLib`, which does its
/// own dedup (`PriceFeedLib._extractUniqueAssets`). Retained here rather than removed because deleting
/// it would change `NAVRegistryLib`'s bytecode and force a second CREATE2-pin regeneration (foundry.toml
/// + LibraryPins + ~15 etch sites) for no functional gain; safe to drop in any future change that
/// already touches `NAVRegistryLib`.
/// @param positions The position balances to scan
/// @return uniqueAssets The distinct asset addresses
function extractUniqueAssets(INAVCalculator.PositionBalance[] memory positions)
external
pure
returns (address[] memory uniqueAssets)
{
uint256 length = positions.length;
address[] memory allAssets = new address[](length);
for (uint256 i = 0; i < length; i++) {
allAssets[i] = positions[i].balanceAsset.asset;
}
uniqueAssets = ArrayLib.deduplicateAddresses(allAssets);
}
// -------------------------------------------------------------------------
// Meta-adapter instance registry (ADR 0010)
// -------------------------------------------------------------------------
/// @notice Appends instance coordinates to a meta-adapter's set (all-or-nothing). Reverts DuplicateMetaInstance
/// on a coordinate already present or repeated within the batch, InvalidArguments on an empty list,
/// InvalidBalanceAdapter if the adapter is not registered, and NotMetaAdapter if it is not a meta-adapter.
/// The running total stays in the caller wrapper.
/// @param isAdapterRegistered Quick-lookup registration map (storage ref)
/// @param metaInstances The per-adapter instance-set map (storage ref)
/// @param adapter The registered meta-adapter
/// @param instances The instance coordinates to add
/// @return added The number of coordinates appended (== instances.length on success)
function addMetaInstances(
mapping(address => bool) storage isAdapterRegistered,
mapping(address => bytes32[]) storage metaInstances,
address adapter,
bytes32[] memory instances
) external returns (uint256 added) {
if (!isAdapterRegistered[adapter]) {
revert IBalances.InvalidBalanceAdapter();
}
if (!adapter.supportsInterface(type(IMetaBalanceAdapter).interfaceId)) {
revert IBalances.NotMetaAdapter();
}
if (instances.length == 0) {
revert InvalidArguments();
}
added = _appendInstances(metaInstances[adapter], instances);
}
/// @notice Removes instance coordinates from a meta-adapter's set (all-or-nothing, swap-and-pop). Reverts
/// MetaInstanceNotFound on a coordinate 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 it is not a meta-adapter.
/// @param isAdapterRegistered Quick-lookup registration map (storage ref)
/// @param metaInstances The per-adapter instance-set map (storage ref)
/// @param adapter The registered meta-adapter
/// @param instances The instance coordinates to remove
/// @return removed The number of coordinates removed (== instances.length on success)
function removeMetaInstances(
mapping(address => bool) storage isAdapterRegistered,
mapping(address => bytes32[]) storage metaInstances,
address adapter,
bytes32[] memory instances
) external returns (uint256 removed) {
if (!isAdapterRegistered[adapter]) {
revert IBalances.InvalidBalanceAdapter();
}
if (!adapter.supportsInterface(type(IMetaBalanceAdapter).interfaceId)) {
revert IBalances.NotMetaAdapter();
}
removed = instances.length;
if (removed == 0) {
revert InvalidArguments();
}
bytes32[] storage set = metaInstances[adapter];
for (uint256 i = 0; i < removed; i++) {
bytes32 instance = instances[i];
uint256 len = set.length;
bool found = false;
for (uint256 j = 0; j < len; j++) {
if (set[j] == instance) {
set[j] = set[len - 1];
set.pop();
found = true;
break;
}
}
if (!found) {
revert IBalances.MetaInstanceNotFound();
}
}
}
// -------------------------------------------------------------------------
// Private helpers (shared by the single / batch / meta registration paths)
// -------------------------------------------------------------------------
/// @notice Validates and stores one adapter in the global registry (Custom type). Reverts DuplicateBalanceAdapter
/// if already registered, InvalidArguments on a zero address, InvalidBalanceAdapter if it does not
/// implement IBalanceAdapter, and — depending on `requireMeta` — NotMetaAdapter (meta path, adapter is
/// not a meta-adapter) or MetaAdapterNotAllowed (plain path, adapter IS a meta-adapter). Does not emit;
/// the caller emits BalanceAdapterAdded so the batch path can log per-item.
function _registerAdapter(
mapping(address => bool) storage isAdapterRegistered,
address[] storage globalAdapters,
mapping(address => IBalances.AdapterType) storage adapterTypes,
address adapter,
bool requireMeta
) private {
if (isAdapterRegistered[adapter]) {
revert IBalances.DuplicateBalanceAdapter();
}
if (adapter == address(0)) revert InvalidArguments();
if (!adapter.supportsInterface(type(IBalanceAdapter).interfaceId)) revert IBalances.InvalidBalanceAdapter();
bool isMeta = adapter.supportsInterface(type(IMetaBalanceAdapter).interfaceId);
if (requireMeta && !isMeta) revert IBalances.NotMetaAdapter();
if (!requireMeta && isMeta) revert IBalances.MetaAdapterNotAllowed();
globalAdapters.push(adapter);
adapterTypes[adapter] = IBalances.AdapterType.Custom;
isAdapterRegistered[adapter] = true;
}
/// @notice Appends `instances` to a meta-adapter's set, rejecting duplicates (DuplicateMetaInstance) against the
/// live set — which already includes coordinates pushed earlier in this batch, so an in-batch repeat is
/// caught too. Empty input is a no-op (returns 0); callers that forbid empty check before calling.
/// @return added The number of coordinates appended (== instances.length).
function _appendInstances(bytes32[] storage set, bytes32[] memory instances) private returns (uint256 added) {
added = instances.length;
for (uint256 i = 0; i < added; i++) {
bytes32 instance = instances[i];
uint256 len = set.length;
for (uint256 j = 0; j < len; j++) {
if (set[j] == instance) {
revert IBalances.DuplicateMetaInstance();
}
}
set.push(instance);
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Arrays.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.24;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new address array 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(address[] memory array, uint256 start) internal pure returns (address[] memory) {
return slice(array, start, array.length);
}
/**
* @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new address array in
* memory. The `end` argument is truncated to the length of the `array`.
*
* 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(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) {
// sanitize
end = Math.min(end, array.length);
start = Math.min(start, end);
// allocate and copy
address[] memory result = new address[](end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
}
return result;
}
/**
* @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new bytes32 array 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(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) {
return slice(array, start, array.length);
}
/**
* @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new bytes32 array in
* memory. The `end` argument is truncated to the length of the `array`.
*
* 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(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) {
// sanitize
end = Math.min(end, array.length);
start = Math.min(start, end);
// allocate and copy
bytes32[] memory result = new bytes32[](end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
}
return result;
}
/**
* @dev Copies the content of `array`, from `start` (included) to the end of `array` into a new uint256 array 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(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) {
return slice(array, start, array.length);
}
/**
* @dev Copies the content of `array`, from `start` (included) to `end` (excluded) into a new uint256 array in
* memory. The `end` argument is truncated to the length of the `array`.
*
* 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(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) {
// sanitize
end = Math.min(end, array.length);
start = Math.min(start, end);
// allocate and copy
uint256[] memory result = new uint256[](end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
}
return result;
}
/**
* @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array.
*
* NOTE: This function modifies the provided array in place. If you need to preserve the original array, 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(address[] memory array, uint256 start) internal pure returns (address[] memory) {
return splice(array, start, array.length);
}
/**
* @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The
* `end` argument is truncated to the length of the `array`.
*
* NOTE: This function modifies the provided array in place. If you need to preserve the original array, 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(address[] memory array, uint256 start, uint256 end) internal pure returns (address[] memory) {
// sanitize
end = Math.min(end, array.length);
start = Math.min(start, end);
// move and resize
assembly ("memory-safe") {
mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
mstore(array, sub(end, start))
}
return array;
}
/**
* @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`).
* If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
*
* NOTE: This function modifies the provided array in place.
*/
function replace(
address[] memory array,
uint256 pos,
address[] memory replacement
) internal pure returns (address[] memory) {
return replace(array, pos, replacement, 0, replacement.length);
}
/**
* @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
* Copies at most `length` elements from `replacement` to `array`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
* clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
* array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
* and the array is returned unchanged.
*
* NOTE: This function modifies the provided array in place.
*/
function replace(
address[] memory array,
uint256 pos,
address[] memory replacement,
uint256 offset,
uint256 length
) internal pure returns (address[] memory) {
// sanitize
pos = Math.min(pos, array.length);
offset = Math.min(offset, replacement.length);
length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));
// allocate and copy
assembly ("memory-safe") {
mcopy(
add(add(array, 0x20), mul(pos, 0x20)),
add(add(replacement, 0x20), mul(offset, 0x20)),
mul(length, 0x20)
)
}
return array;
}
/**
* @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array.
*
* NOTE: This function modifies the provided array in place. If you need to preserve the original array, 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(bytes32[] memory array, uint256 start) internal pure returns (bytes32[] memory) {
return splice(array, start, array.length);
}
/**
* @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The
* `end` argument is truncated to the length of the `array`.
*
* NOTE: This function modifies the provided array in place. If you need to preserve the original array, 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(bytes32[] memory array, uint256 start, uint256 end) internal pure returns (bytes32[] memory) {
// sanitize
end = Math.min(end, array.length);
start = Math.min(start, end);
// move and resize
assembly ("memory-safe") {
mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
mstore(array, sub(end, start))
}
return array;
}
/**
* @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`).
* If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
*
* NOTE: This function modifies the provided array in place.
*/
function replace(
bytes32[] memory array,
uint256 pos,
bytes32[] memory replacement
) internal pure returns (bytes32[] memory) {
return replace(array, pos, replacement, 0, replacement.length);
}
/**
* @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
* Copies at most `length` elements from `replacement` to `array`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
* clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
* array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
* and the array is returned unchanged.
*
* NOTE: This function modifies the provided array in place.
*/
function replace(
bytes32[] memory array,
uint256 pos,
bytes32[] memory replacement,
uint256 offset,
uint256 length
) internal pure returns (bytes32[] memory) {
// sanitize
pos = Math.min(pos, array.length);
offset = Math.min(offset, replacement.length);
length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));
// allocate and copy
assembly ("memory-safe") {
mcopy(
add(add(array, 0x20), mul(pos, 0x20)),
add(add(replacement, 0x20), mul(offset, 0x20)),
mul(length, 0x20)
)
}
return array;
}
/**
* @dev Moves the content of `array`, from `start` (included) to the end of `array` to the start of that array.
*
* NOTE: This function modifies the provided array in place. If you need to preserve the original array, 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(uint256[] memory array, uint256 start) internal pure returns (uint256[] memory) {
return splice(array, start, array.length);
}
/**
* @dev Moves the content of `array`, from `start` (included) to `end` (excluded) to the start of that array. The
* `end` argument is truncated to the length of the `array`.
*
* NOTE: This function modifies the provided array in place. If you need to preserve the original array, 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(uint256[] memory array, uint256 start, uint256 end) internal pure returns (uint256[] memory) {
// sanitize
end = Math.min(end, array.length);
start = Math.min(start, end);
// move and resize
assembly ("memory-safe") {
mcopy(add(array, 0x20), add(add(array, 0x20), mul(start, 0x20)), mul(sub(end, start), 0x20))
mstore(array, sub(end, start))
}
return array;
}
/**
* @dev Replaces elements in `array` starting at `pos` with all elements from `replacement`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`).
* If `pos >= array.length`, no replacement occurs and the array is returned unchanged.
*
* NOTE: This function modifies the provided array in place.
*/
function replace(
uint256[] memory array,
uint256 pos,
uint256[] memory replacement
) internal pure returns (uint256[] memory) {
return replace(array, pos, replacement, 0, replacement.length);
}
/**
* @dev Replaces elements in `array` starting at `pos` with elements from `replacement` starting at `offset`.
* Copies at most `length` elements from `replacement` to `array`.
*
* Parameters are clamped to valid ranges (i.e. `pos` is clamped to `[0, array.length]`, `offset` is
* clamped to `[0, replacement.length]`, and `length` is clamped to `min(length, replacement.length - offset,
* array.length - pos)`). If `pos >= array.length` or `offset >= replacement.length`, no replacement occurs
* and the array is returned unchanged.
*
* NOTE: This function modifies the provided array in place.
*/
function replace(
uint256[] memory array,
uint256 pos,
uint256[] memory replacement,
uint256 offset,
uint256 length
) internal pure returns (uint256[] memory) {
// sanitize
pos = Math.min(pos, array.length);
offset = Math.min(offset, replacement.length);
length = Math.min(length, Math.min(replacement.length - offset, array.length - pos));
// allocate and copy
assembly ("memory-safe") {
mcopy(
add(add(array, 0x20), mul(pos, 0x20)),
add(add(replacement, 0x20), mul(offset, 0x20)),
mul(length, 0x20)
)
}
return array;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytesSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getStringSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
*/
function unsafeSetLength(bytes[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, or initialize elements if length is increased.
*/
function unsafeSetLength(string[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/Comparators.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}
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/SlotDerivation.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for *;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/introspection/ERC165Checker.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/introspection/ERC165Checker.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the ERC-165 spec, no interface should ever match 0xffffffff
bytes4 private constant INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface.
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC-165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
if (supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId)) {
(bool success, bool supported) = _trySupportsInterface(account, INTERFACE_ID_INVALID);
return success && !supported;
} else {
return false;
}
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC-165 as per the spec and support of _interfaceId
return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*/
function getSupportedInterfaces(
address account,
bytes4[] memory interfaceIds
) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC-165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC-165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC-165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC-165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
*
* Some precompiled contracts will falsely indicate support for a given interface, so caution
* should be exercised when using this function.
*
* Interface identification is specified in ERC-165.
*/
function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {
(bool success, bool supported) = _trySupportsInterface(account, interfaceId);
return success && supported;
}
/**
* @dev Attempts to call `supportsInterface` on a contract and returns both the call
* success status and the interface support result.
*
* This function performs a low-level static call to the contract's `supportsInterface`
* function. It returns:
*
* * `success`: true if the call didn't revert, false if it did
* * `supported`: true if the call succeeded AND returned data indicating the interface is supported
*/
function _trySupportsInterface(
address account,
bytes4 interfaceId
) private view returns (bool success, bool supported) {
bytes4 selector = IERC165.supportsInterface.selector;
assembly ("memory-safe") {
mstore(0x00, selector)
mstore(0x04, interfaceId)
success := staticcall(30000, account, 0x00, 0x24, 0x00, 0x20)
supported := and(
gt(returndatasize(), 0x1F), // we have at least 32 bytes of returndata
iszero(iszero(mload(0x00))) // the first 32 bytes of returndata are non-zero
)
}
}
}
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/structs/EnumerableSet.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.5.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.24;
import {Arrays} from "../Arrays.sol";
import {Math} from "../math/Math.sol";
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
* - Set can be cleared (all elements removed) in O(n).
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* The following types are supported:
*
* - `bytes32` (`Bytes32Set`) since v3.3.0
* - `address` (`AddressSet`) since v3.3.0
* - `uint256` (`UintSet`) since v3.3.0
* - `string` (`StringSet`) since v5.4.0
* - `bytes` (`BytesSet`) since v5.4.0
* - `bytes4` (`Bytes4Set`) since v5.6.0
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: This function has an unbounded cost that scales with set size. Developers should keep in mind that
* using it may render the function uncallable if the set grows to the point where clearing it consumes too much
* gas to fit in a block.
*/
function _clear(Set storage set) private {
uint256 len = _length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set, uint256 start, uint256 end) private view returns (bytes32[] memory) {
unchecked {
end = Math.min(end, _length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes32[] memory result = new bytes32[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes32Set storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set, uint256 start, uint256 end) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
bytes32[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// Bytes4Set
struct Bytes4Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes4Set storage set, bytes4 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes4Set storage set, bytes4 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(Bytes4Set storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes4Set storage set, bytes4 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes4Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes4Set storage set, uint256 index) internal view returns (bytes4) {
return bytes4(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes4Set storage set) internal view returns (bytes4[] memory) {
bytes32[] memory store = _values(set._inner);
bytes4[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes4Set storage set, uint256 start, uint256 end) internal view returns (bytes4[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
bytes4[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(AddressSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set, uint256 start, uint256 end) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
address[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(UintSet storage set) internal {
_clear(set._inner);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set, uint256 start, uint256 end) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner, start, end);
uint256[] memory result;
assembly ("memory-safe") {
result := store
}
return result;
}
struct StringSet {
// Storage of set values
string[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(string value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(StringSet storage set, string memory value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(StringSet storage set, string memory value) internal returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
string memory lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(StringSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(StringSet storage set, string memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(StringSet storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(StringSet storage set, uint256 index) internal view returns (string memory) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(StringSet storage set) internal view returns (string[] memory) {
return set._values;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(StringSet storage set, uint256 start, uint256 end) internal view returns (string[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
string[] memory result = new string[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
struct BytesSet {
// Storage of set values
bytes[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(BytesSet storage set, bytes memory value) internal returns (bool) {
if (!contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(BytesSet storage set, bytes memory value) internal returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes memory lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Removes all the values from a set. O(n).
*
* WARNING: Developers should keep in mind that this function has an unbounded cost and using it may render the
* function uncallable if the set grows to the point where clearing it consumes too much gas to fit in a block.
*/
function clear(BytesSet storage set) internal {
uint256 len = length(set);
for (uint256 i = 0; i < len; ++i) {
delete set._positions[set._values[i]];
}
Arrays.unsafeSetLength(set._values, 0);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(BytesSet storage set, bytes memory value) internal view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(BytesSet storage set) internal view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(BytesSet storage set, uint256 index) internal view returns (bytes memory) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(BytesSet storage set) internal view returns (bytes[] memory) {
return set._values;
}
/**
* @dev Return a slice of the set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(BytesSet storage set, uint256 start, uint256 end) internal view returns (bytes[] memory) {
unchecked {
end = Math.min(end, length(set));
start = Math.min(start, end);
uint256 len = end - start;
bytes[] memory result = new bytes[](len);
for (uint256 i = 0; i < len; ++i) {
result[i] = Arrays.unsafeAccess(set._values, start + i).value;
}
return result;
}
}
}
src/balances/BalanceAdapterBase.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IBalanceAdapter} from "./IBalanceAdapter.sol";
import {IPositionDescribable} from "./IPositionDescribable.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title BalanceAdapterBase
/// @author KPK
/// @notice Shared base for the plain (immutable, non-assisted) balance adapters. It declares the common
/// {IBalanceAdapter} + {IPositionDescribable} surface and implements the one piece every plain adapter
/// repeats verbatim — `supportsInterface` advertising that pair plus {IERC165}. Concrete adapters implement
/// the balance/position reads and the {IPositionDescribable} display hooks.
/// @dev Plain adapters stay immutable (no Ownable/admin). The assisted family has its own base
/// ({AssistedCoordCache}); meta-adapters have {MetaBalanceAdapter}. `supportsInterface` is `public virtual`
/// so an adapter advertising an extra interface can override and `super`-chain — it was `external`, which
/// made that impossible (Solidity cannot reach an `external` function through `super`), forcing any such
/// adapter to re-declare the whole base list and silently drift from it. `public` matches the
/// {AssistedCoordCache} precedent, where the Nexus adapter really does `super`-chain. It stays `pure`
/// because the answer is a compile-time comparison; an override that must read state (an immutable, say)
/// cannot widen it, and should expose its extra interface from a `pure` override here regardless.
abstract contract BalanceAdapterBase is IBalanceAdapter, IPositionDescribable {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) {
return interfaceId == type(IBalanceAdapter).interfaceId || interfaceId == type(IPositionDescribable).interfaceId
|| interfaceId == type(IERC165).interfaceId;
}
}
src/balances/BalanceAdapters/ERC20DefaultBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {BalanceAdapterBase} from "../BalanceAdapterBase.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IBalanceAdapter} from "../IBalanceAdapter.sol";
import {LabelLib} from "src/balances/LabelLib.sol";
import {IPositionDescribable} from "../IPositionDescribable.sol";
import {IComputedLabelSegments} from "src/balances/IComputedLabelSegments.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
import {ProtocolIds} from "src/utils/ProtocolIds.sol";
// forge-lint: disable-next-line(unaliased-plain-import)
import "src/errors.sol";
/// @title ERC20DefaultBalanceAdapter
/// @notice Default adapter that reports wallet balances for the ERC20 and native assets in its inclusion list
/// @dev This adapter reads asset metadata from NAVCalculator and returns balance-only positions for the assets in its inclusion list (_supportedAssets)
/// @dev Returns PositionBalance structs (balance-only data) without pricing information.
/// @dev NAVCalculator enriches these positions with pricing data to create full Position structs.
/// @author KPK
contract ERC20DefaultBalanceAdapter is BalanceAdapterBase, IComputedLabelSegments {
using EnumerableSet for EnumerableSet.AddressSet;
/// @notice Reference to NAVCalculator for asset registry access
INAVCalculator public immutable NAV_CALCULATOR;
/// @notice Inclusion list: only assets in this set are reported by this adapter
EnumerableSet.AddressSet private _supportedAssets;
/// @notice ERC-7528 convention for ETH address representation
address public constant NATIVE_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/// @notice 3-level protocol taxonomy for wallet positions. Wallet is a single-product ecosystem, so all three
/// levels (brand / id / sub-id) collapse to the same `ProtocolIds.WALLET` slug.
bytes32 private constant PROTOCOL_BRAND = ProtocolIds.WALLET;
bytes32 private constant PROTOCOL_ID = ProtocolIds.WALLET;
bytes32 private constant PROTOCOL_SUB_ID = ProtocolIds.WALLET;
/// @param navCalculator_ NAVCalculator address (must be non-zero)
/// @param initialAssets Optional assets to add to the inclusion list during construction (e.g. NATIVE_ADDRESS).
/// Used so NAVCalculator.initialize can pre-add native without calling back to the proxy during init.
constructor(address navCalculator_, address[] memory initialAssets) {
if (navCalculator_ == address(0)) revert InvalidArguments();
NAV_CALCULATOR = INAVCalculator(navCalculator_);
// The seed list is NOT registry-checked here: this constructor is invoked by
// NAVRegistryLib.deployDefaultAdapter *during NAVCalculator.initialize*, which runs inside the proxy's
// own constructor — at that point the proxy has no deployed code yet, so an external
// NAV_CALCULATOR.isAssetRegistered(...) callback would revert with "call to non-contract". The only
// caller seeds exactly [NATIVE_ADDRESS], which initialize registers one line before deploying this
// adapter, so a misconfigured seed is not reachable. Post-deploy entries go through addSupportedAsset,
// which does enforce isAssetRegistered.
for (uint256 i = 0; i < initialAssets.length; i++) {
_supportedAssets.add(initialAssets[i]);
}
}
//
// Inclusion list (callable only by NAVCalculator)
//
/// @notice Add an asset to the default adapter's inclusion list so it reports wallet balances for it
/// @param asset The asset address (must be registered in NAVCalculator)
function addSupportedAsset(address asset) external {
if (msg.sender != address(NAV_CALCULATOR)) revert OnlyNAVCalculator();
if (!NAV_CALCULATOR.isAssetRegistered(asset)) revert AssetNotFound();
_supportedAssets.add(asset);
}
/// @notice Remove an asset from the default adapter's inclusion list (e.g. to avoid double accounting with a custom adapter)
/// @param asset The asset address to remove
function removeSupportedAsset(address asset) external {
if (msg.sender != address(NAV_CALCULATOR)) revert OnlyNAVCalculator();
_supportedAssets.remove(asset);
}
/// @notice Returns whether the default adapter reports balances for this asset
function isSupportedByDefault(address asset) external view returns (bool) {
return _supportedAssets.contains(asset);
}
//
// IBalanceAdapter Implementation
//
/// @inheritdoc IBalanceAdapter
/// @notice Returns balance-only positions for the account's ERC20 and native token balances
/// @dev Returns PositionBalance structs containing wallet balances.
/// @dev Only returns positions for assets in the inclusion list (_supportedAssets).
/// @dev Pricing information is added by NAVCalculator when these positions are enriched.
function getAdapterPositions(address account, address assetFilter)
external
view
override
returns (INAVCalculator.PositionBalance[] memory positions)
{
address[] memory assetsToProcess;
if (assetFilter != address(0)) {
if (!_supportedAssets.contains(assetFilter)) {
return new INAVCalculator.PositionBalance[](0);
}
assetsToProcess = new address[](1);
assetsToProcess[0] = assetFilter;
} else {
assetsToProcess = _getSupportedAssetsArray();
}
// Build via an external self-staticcall so the row-building runs in a fresh frame whose only params are
// `(account, assets)` — this keeps `getAdapterPositions`'s `account`/`assetFilter` params (which sit at the
// stack bottom for its whole body) off the build loop's stack, which otherwise overflows the via_ir limit.
// Mirrors the assisted adapters' `this.positionLegs(...)` / NAVCalculator's `this.decodeStringArray` pattern.
positions = this.buildPositionsSelf(account, assetsToProcess);
}
/// @notice External self-call entrypoint for `_buildPositions` (see the call site in `getAdapterPositions`).
/// @dev `msg.sender`-guarded to `address(this)` so it is not a usable external surface — it exists only to give
/// the build loop its own stack frame. `view`, so the self-call is a staticcall.
function buildPositionsSelf(address account, address[] calldata assets)
external
view
returns (INAVCalculator.PositionBalance[] memory)
{
if (msg.sender != address(this)) revert NotAuthorized();
return _buildPositions(account, assets);
}
/// @inheritdoc IBalanceAdapter
function getAdapterBalances(address account)
external
view
returns (address[] memory assets, uint256[] memory amounts, bool[] memory isDebt)
{
address[] memory supportedList = _getSupportedAssetsArray();
uint256 assetCount = supportedList.length;
address[] memory tempAssets = new address[](assetCount);
uint256[] memory tempAmounts = new uint256[](assetCount);
uint256 count = 0;
for (uint256 i = 0; i < assetCount; i++) {
address assetAddr = supportedList[i];
uint256 amount = _getBalanceForAsset(account, assetAddr);
if (amount != 0) {
tempAssets[count] = assetAddr;
tempAmounts[count] = amount;
count++;
}
}
assets = new address[](count);
amounts = new uint256[](count);
isDebt = new bool[](count);
for (uint256 i = 0; i < count; i++) {
assets[i] = tempAssets[i];
amounts[i] = tempAmounts[i];
isDebt[i] = false; // ERC20 balances are always credit
}
}
/// @inheritdoc IBalanceAdapter
function getAdapterBalanceForAsset(address account, address asset)
public
view
returns (uint256 amount, bool isDebt)
{
if (asset == address(0)) {
return (0, false);
}
if (!_supportedAssets.contains(asset)) {
return (0, false);
}
return (_getBalanceForAsset(account, asset), false);
}
/// @inheritdoc IBalanceAdapter
function underlyingAssetsSupported() external view returns (address[] memory underlyingAssets) {
return _getSupportedAssetsArray();
}
//
// IPositionDescribable Implementation
//
function protocolName() external pure returns (string memory) {
return "Wallet";
}
/// @inheritdoc IComputedLabelSegments
/// @dev **Bit 0 set: this adapter's ONLY segment is the computed token symbol.** It is not a category with a
/// derived leaf under it — index 0 *is* the derivation, which is why `BALANCE_ADAPTERS.md` §6.2 marks it
/// `C` and says "Never override".
///
/// That instruction previously lived only in markdown. This declaration is the same fact placed where
/// `AssetKindRegistry.setAdapterLabels` can act on it, so a literal at index 0 now reverts
/// {IAssetKindRegistry.ComputedSegmentNotOverridable} instead of succeeding.
///
/// ⚠️ **The blast radius is why this adapter is the first adopter.** It is registered on EVERY chain by
/// `initialize()`, and one accepted override would stamp a single frozen symbol onto every ERC20 wallet
/// position on that chain — rendering as a plausible label rather than as an error, which is the worst
/// failure shape available on a display path.
function computedLabelSegments() external pure override returns (uint256) {
return 1; // bit 0
}
/// @inheritdoc BalanceAdapterBase
/// @dev Extends the base set with {IComputedLabelSegments}. The registry ERC-165-probes before reading the mask,
/// so without this bit the declaration above would never be consulted and the guard would silently not
/// apply — an advertised-but-unreachable capability, which is worse than none.
function supportsInterface(bytes4 interfaceId) public pure override returns (bool) {
return interfaceId == type(IComputedLabelSegments).interfaceId || super.supportsInterface(interfaceId);
}
/// @inheritdoc IPositionDescribable
/// @dev Display-only, so it must never revert — including for a positionId this adapter never emitted. A
/// configuration view probes with whatever word it has (`""`, a bytes32 pool/market id copied from
/// another adapter, a truncated buffer), and this is the one adapter registered on every chain.
///
/// Hence the raw-word decode rather than `abi.decode(positionId, (address))`: Solidity's decoder reverts
/// on a buffer shorter than one word AND on an address whose upper 96 bits are dirty. Both cases collapse
/// the leaf instead, which the fail-open tail below renders as `[]`. Same idiom as
/// {StakeWiseV3VaultsMetaBalanceAdapter}. A dirty word is NOT truncated to its low 160 bits: those bits
/// may spell a real registered asset by coincidence, and labelling a foreign coordinate with that
/// asset's symbol would be a wrong answer where `[]` is merely an absent one.
///
/// The length test is `== 32`, not `>= 32`, for that same reason: every positionId this adapter emits is
/// `abi.encode(asset)`, and `abi.decode` silently ignores trailing bytes — so a foreign multi-word
/// coordinate whose first word happens to be a registered asset would otherwise be labelled with that
/// asset's symbol.
function positionLabels(bytes calldata positionId) external view override returns (string[] memory) {
string memory leaf;
if (positionId.length == 32) {
uint256 raw = abi.decode(positionId, (uint256));
if (raw >> 160 == 0) {
address addr = address(uint160(raw));
if (addr == NATIVE_ADDRESS) {
leaf = "native";
} else {
leaf = LabelLib.symbol(addr, "");
}
}
}
// Fail-open: no derivable label → empty array (IPositionDescribable convention), not `[""]`,
// so consumers don't render a blank breadcrumb segment.
if (bytes(leaf).length == 0) return new string[](0);
string[] memory out = new string[](1);
out[0] = leaf;
return out;
}
//
// Internal Functions
//
/// @notice Returns the inclusion list as an address array (for enumeration)
function _getSupportedAssetsArray() internal view returns (address[] memory) {
uint256 len = _supportedAssets.length();
address[] memory arr = new address[](len);
for (uint256 i = 0; i < len; i++) {
arr[i] = _supportedAssets.at(i);
}
return arr;
}
/// @notice Gets asset information from NAVCalculator. O(1).
/// @param asset The asset address to look up
/// @return assetInfo The Asset struct containing asset address, symbol, and decimals
/// @dev **`_rows` calls this once per HELD asset**, so its cost is paid per token in the wallet — and this
/// adapter is the unremovable singleton registered on every chain, which makes it the largest instance of
/// the fetch-per-token pathology in the repo, not a lesser one.
///
/// It used to fetch the WHOLE registry per call
/// (`RegisteredAssetLib.find(NAV_CALCULATOR.getRegisteredAssets(), asset)`), measured at
/// **60,879,087 gas at 104 registered assets** — ~585k per asset and super-linear, because each call
/// allocates an N-element array that is never freed so memory expansion grows with the square of the held
/// count. `PriceFeedLib` forwards only 63/64 of `gasleft()` with no fixed ceiling, so a treasury Safe
/// holding most of the registered set either exceeds the node's `eth_call` cap and returns no NAV at all,
/// or trips `AdapterGasExhausted` and reverts the whole read. An availability defect, not a cost one.
///
/// Now one `getRegisteredAsset` call: a mapping load plus one array read, flat in the registry size.
/// The revert-on-absent behaviour is deliberately UNCHANGED — unlike the meta family, this adapter's
/// caller has already filtered to its own supported-asset list, so an unregistered asset here is a real
/// inconsistency rather than an ordinary skip.
function _getAssetInfo(address asset) internal view returns (INAVCalculator.Asset memory assetInfo) {
bool found;
(assetInfo, found) = NAV_CALCULATOR.getRegisteredAsset(asset);
if (!found) revert AssetNotFound();
}
/// @notice Internal helper that builds all positions for this adapter
/// @param account The account to query
/// @param assets Array of assets to build positions for
/// @return positions Array of balance-only PositionBalance structs from this adapter
/// @dev Creates one position per asset with non-zero balance
/// @dev All positions are balance-only; pricing is added by NAVCalculator during enrichment
function _buildPositions(address account, address[] memory assets)
internal
view
returns (INAVCalculator.PositionBalance[] memory positions)
{
uint256 len = assets.length;
if (len == 0) {
return new INAVCalculator.PositionBalance[](0);
}
// Pass 1: collect the assets with a non-zero balance. This is the only pass that needs `account`; it builds
// no structs, so the loop stays light. (Kept separate from the row-building pass to stay under the via_ir
// stack limit — building the 11-field PositionBalance while `account`/`assetFilter` are still live overflows.)
address[] memory hitAssets = new address[](len);
uint256[] memory hitBalances = new uint256[](len);
uint256 positionCount = 0;
for (uint256 i = 0; i < len; i++) {
uint256 balance = _getBalanceForAsset(account, assets[i]);
if (balance != 0) {
hitAssets[positionCount] = assets[i];
hitBalances[positionCount] = balance;
positionCount++;
}
}
// Pass 2: build the rows in a dedicated function. Keeping it separate (params are only the hit arrays + count)
// ensures the row-building loop's stack does NOT also carry `getAdapterPositions`'s `account`/`assetFilter`
// params — which sit at the stack bottom for that function's whole body and were tipping the via_ir limit.
positions = _rows(hitAssets, hitBalances, positionCount);
}
/// @dev Builds `count` credit rows from the collected (asset, balance) hits. Separate from the collection pass so
/// its loop's stack is free of the outer `account`/`assetFilter` params (via_ir stack limit).
function _rows(address[] memory hitAssets, uint256[] memory hitBalances, uint256 count)
private
view
returns (INAVCalculator.PositionBalance[] memory positions)
{
positions = new INAVCalculator.PositionBalance[](count);
for (uint256 i = 0; i < count; i++) {
positions[i] = _row(_getAssetInfo(hitAssets[i]), hitBalances[i], hitAssets[i]);
}
}
/// @dev Builds one wallet PositionBalance field-by-field (avoids an 11-field literal inside the per-asset loop,
/// which overflows the via_ir stack). positionId = abi.encode(asset); positionInstanceId defaults to bytes32(0).
function _row(INAVCalculator.Asset memory underlyingAsset, uint256 balance, address asset)
private
view
returns (INAVCalculator.PositionBalance memory row)
{
row.balanceAsset = underlyingAsset;
row.balanceAdapter = address(this);
row.amount = balance;
row.protocolBrand = PROTOCOL_BRAND;
row.protocolId = PROTOCOL_ID;
row.protocolSubId = PROTOCOL_SUB_ID;
row.positionId = abi.encode(asset);
row.positionKind = PositionKind.Wallet;
// isDebt, isLocked default false; positionInstanceId defaults to bytes32(0).
}
/// @notice Internal helper to get balance for a specific asset (avoids recursion)
/// @param account The account to query
/// @param asset The asset address
/// @return balance The balance for this asset as uint256 (always non-negative for ERC20DefaultBalanceAdapter)
function _getBalanceForAsset(address account, address asset) internal view returns (uint256 balance) {
// Handle native address (ETH)
if (asset == NATIVE_ADDRESS) {
return account.balance;
}
// Read balanceOf(account) via low-level staticcall so a non-standard/non-contract asset cannot revert
// the NAV scan. IMPORTANT: a staticcall to a code-less address (or a token whose balanceOf returns
// void/short data) returns success=true with returndatasize() < 32 — the EVM then leaves the output
// region untouched. We therefore (a) write the return into a FRESH, zeroed scratch word distinct from
// the calldata buffer, and (b) only treat it as a balance when a full 32-byte word was actually
// returned. Without this, the leftover calldata (the balanceOf selector word) would be misread as a
// huge phantom balance, corrupting NAV.
uint256 tokenBalance;
bool success;
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x70a0823100000000000000000000000000000000000000000000000000000000) // balanceOf(address) selector
mstore(add(ptr, 0x04), account)
// Output goes in a separate, 32-byte-aligned scratch word at ptr+0x40 (clear of the 0x24-byte
// calldata at ptr..ptr+0x24). The free-memory pointer is advanced to ptr+0x60 — kept 32-byte
// aligned so later Solidity allocations in this call (e.g. _buildPositions arrays) are not corrupted.
let outPtr := add(ptr, 0x40)
mstore(outPtr, 0) // zero the output word so a short/empty return reads as 0, never stale memory
mstore(0x40, add(outPtr, 0x20))
success := staticcall(gas(), asset, ptr, 0x24, outPtr, 0x20)
// Only a full-word return is a real balance; code-less/void/short returns stay 0.
if and(success, gt(returndatasize(), 0x1f)) { tokenBalance := mload(outPtr) }
}
return tokenBalance;
}
}
src/balances/IBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title IBalanceAdapter
/// @notice Standard interface for balance adapters (both default and custom)
/// @dev All balance adapters must implement this interface to work with the adapter-centric aggregation system
/// @dev Extends ERC165 to allow on-chain discovery with `supportsInterface`.
/// @author KPK
interface IBalanceAdapter is IERC165 {
/// @notice Get all positions from this adapter for an account
/// @param account The account to query
/// @param assetFilter Optional asset filter (address(0) for all assets)
/// @return positions Array of balance-only PositionBalance structs from this adapter
/// @dev Balance adapters return balance-only data without pricing. NAVCalculator enriches these with pricing.
function getAdapterPositions(address account, address assetFilter)
external
view
returns (INAVCalculator.PositionBalance[] memory positions);
/// @notice Get balances from this adapter for an account
/// @param account The account to query
/// @return assets Array of asset addresses
/// @return amounts Array of balance amounts (always non-negative magnitude)
/// @return isDebt Array of debt flags (true = debt, false = credit)
function getAdapterBalances(address account)
external
view
returns (address[] memory assets, uint256[] memory amounts, bool[] memory isDebt);
/// @notice Get single balance for a specific asset (gas-optimized version)
/// @param account The account to query
/// @param asset The asset address
/// @return amount Balance amount (non-negative magnitude)
/// @return isDebt True if debt, false if credit
function getAdapterBalanceForAsset(address account, address asset)
external
view
returns (uint256 amount, bool isDebt);
/// @notice Returns the list of all the underlying assets supported by this adapter
/// @dev The returned list may be empty if the adapter cannot determine or provide the supported assets
/// @return underlyingAssets The list of underlying asset addresses supported by this adapter (may be empty)
function underlyingAssetsSupported() external view returns (address[] memory underlyingAssets);
}
src/balances/IBalances.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @author KPK
interface IBalances {
//
// Type definitions
//
enum AdapterType {
Default,
Custom
}
struct BalanceAdapter {
address adapter;
AdapterType adapterType;
string protocol;
}
//
// Events
//
/// @notice Event emitted when a balance adapter is added to the global registry.
/// @param underlyingAsset Reserved; currently address(0) as adapters are registered globally, not per asset.
/// @param adapter The address of the adapter being added.
/// @param adapterType The type of the adapter (Default or Custom).
event BalanceAdapterAdded(address indexed underlyingAsset, address indexed adapter, AdapterType adapterType);
/// @notice Event emitted when a balance adapter is removed from the global registry.
/// @param underlyingAsset Reserved; currently address(0) as adapters are global.
/// @param adapter The address of the balance adapter being removed.
event BalanceAdapterRemoved(address indexed underlyingAsset, address adapter);
//
// Errors
//
/// @notice Error when the balance adapter is not set.
error BalanceAdapterNotSet();
/// @notice Error when the balance adapter is not valid.
error InvalidBalanceAdapter();
/// @notice Error when the balance adapter type is not valid.
error InvalidBalanceAdapterType();
/// @notice Error when the same balance adapter is already set.
error DuplicateBalanceAdapter();
/// @notice Error when adding a meta-instance coordinate that is already present (would double-count NAV).
error DuplicateMetaInstance();
/// @notice Error when removing a meta-instance coordinate that is not present in the adapter's set.
error MetaInstanceNotFound();
/// @notice Error when a meta-adapter (implements IMetaBalanceAdapter) is registered via the plain
/// addBalanceAdapters path; meta-adapters must use addMetaBalanceAdapter.
error MetaAdapterNotAllowed();
/// @notice Error when a meta-adapter operation (registration via addMetaBalanceAdapter, or an
/// addMetaInstances / removeMetaInstances call) targets an adapter that is not a meta-adapter
/// (does not implement IMetaBalanceAdapter).
error NotMetaAdapter();
/// @notice Validates that the adapter implements IBalanceAdapter (reverts with InvalidBalanceAdapter if not).
/// @dev Reverts with InvalidArguments if `adapter` is the zero address.
/// @param adapter The address of the adapter to check.
function checkBalanceAdapterSupport(address adapter) external view;
//
// Global Adapter Registry
//
/// @notice Returns all registered adapters in the global registry
/// @return adapters Array of all adapter addresses
function getAllAdapters() external view returns (address[] memory adapters);
/// @notice Returns the total number of registered adapters
/// @return count Total number of adapters
function getAdapterCount() external view returns (uint256 count);
/// @notice Checks if an adapter is registered in the global registry
/// @param adapter The adapter address to check
/// @return registered True if the adapter is registered
function isAdapterRegistered(address adapter) external view returns (bool registered);
/// @notice Returns the type of a registered adapter
/// @dev Reverts with InvalidBalanceAdapter if the adapter is not registered.
/// @param adapter The adapter address
/// @return adapterType The type of the adapter
function getAdapterType(address adapter) external view returns (AdapterType adapterType);
/// @notice Returns all adapters that support the given asset
/// @dev Loops through all global adapters and checks if the asset is in their underlyingAssetsSupported() list
/// @param asset The asset address to check
/// @return adapters Array of adapter addresses that support the asset
function getAdaptersForAsset(address asset) external view returns (address[] memory adapters);
//
// Meta-adapter instance registry (ADR 0010)
//
/// @notice Returns the configured meta-adapter instance coordinates for an adapter (empty for non-meta adapters).
/// @param adapter The adapter address.
/// @return instances The instance coordinates currently configured for the adapter.
function getMetaInstances(address adapter) external view returns (bytes32[] memory instances);
}
src/balances/IComputedLabelSegments.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IComputedLabelSegments
/// @author KPK
/// @notice Optional interface for balance adapters that DERIVE one or more of their `positionLabels` segments from
/// live on-chain state, so `AssetKindRegistry` can refuse to freeze a derived segment behind a literal.
/// @dev **Why this exists: before it, the protection for a computed segment was a markdown table.**
/// `AssetKindRegistry.setAdapterLabels` guards the adapter's registration, the segment count, each string's
/// length, and not-all-empty. It has never guarded WHICH INDEX may be written, and it has no way to know which
/// of an adapter's segments are literals and which are computed. `BALANCE_ADAPTERS.md` §6.2 enumerates the
/// answer for every adapter and states plainly that the two safety rules are "properties of the ADAPTER rather
/// than of the mechanism" — i.e. operator discipline, checked by nobody.
///
/// That was tolerable while only segment 0 was writable. It is not tolerable now: the per-segment
/// `setAdapterLabels` widened the surface to ANY depth, so every computed leaf in the fleet became reachable
/// by a single MANAGER call. **The worst case is also the one the docs shout loudest about.**
/// `ERC20DefaultBalanceAdapter` is registered on every chain and its segment 0 is not a category at all — it
/// IS the computed token symbol. One override stamps a single frozen symbol onto every ERC20 wallet position
/// on that chain, and it renders as a plausible label rather than as an error.
///
/// **A permanent expected-anomaly that an operator has to remember is a fail-open with a human in the loop.**
/// This moves the fact on-chain, where the same repo already puts protocol identity: derived, not asserted in
/// prose.
///
/// **Optional, and ERC-165-gated, for a reason that is not stylistic.** Twenty-three contracts implement
/// {IPositionDescribable}; adding a method there would fail to compile every one of them, and every adapter
/// already deployed is IMMUTABLE and could never adopt it. So this mirrors {IPositionEnumerable} exactly — a
/// separate optional interface whose ERC-165 bit is itself the signal that the adapter has thought about the
/// question. An adapter that does not advertise it is treated as declaring nothing, which preserves today's
/// behaviour rather than bricking the override feature for every already-deployed adapter.
///
/// ⚠️ **The consequence of that choice, stated rather than buried: the guard is only as complete as adoption.**
/// An adapter that does not implement this interface gets NO index protection, exactly as before. It is not a
/// fail-closed guard and cannot be, because fail-closed would block every override on every existing adapter.
/// Coverage becomes complete when each adapter next ships — which for this repo is the pending full redeploy.
interface IComputedLabelSegments {
/// @notice Bitmask of `positionLabels` indices this adapter DERIVES from on-chain state. Bit `i` set means
/// segment `i` is computed and must not be frozen behind a literal.
/// @dev A mask rather than an array: the ceiling is `AssetKindRegistry.MAX_ADAPTER_LABEL_SEGMENTS` (8), so a
/// single word is generous, costs one `SLOAD`-free `pure` return, and needs no memory allocation on a path
/// the registry reads through a gas-capped staticcall.
///
/// Return `0` to declare that every segment is a literal — which is a real, useful declaration and NOT the
/// same as not implementing the interface. `0` says "I considered this and nothing of mine is derived";
/// absent says "nobody has considered it". Both permit any override, but only the first is a statement.
///
/// MUST be `pure` or `view` and MUST NOT revert — the registry reads it behind a bounded staticcall and
/// treats a failure as "declares nothing", so a reverting implementation silently forfeits its own
/// protection.
function computedLabelSegments() external view returns (uint256 mask);
}
src/balances/IMetaBalanceAdapter.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IBalanceAdapter} from "./IBalanceAdapter.sol";
import {INAVCalculator} from "src/nav/INAVCalculator.sol";
/// @title IMetaBalanceAdapter
/// @author KPK
/// @notice Interface for *meta* balance adapters: a single immutable adapter that can report positions
/// for an arbitrary number of instances of one protocol (e.g. every Morpho vault, every Balancer pool).
/// @dev A meta-adapter is universal and instance-stateless — it holds no list of "active" instances and has no
/// admin/write functions. The set of instances to actually query lives on NAVCalculator (per-adapter,
/// MANAGER-gated). This keeps adapters immutable while making the governed "which instances" set mutable in
/// the upgradeable, AccessControl-gated NAVCalculator.
///
/// Instances are identified by a `bytes32` coordinate. For most protocols this is an address widened to
/// bytes32 (vault / pool / instance-DataProvider address); the wider type also accommodates protocols whose
/// instance key is itself a bytes32 (e.g. Morpho market ids).
///
/// Call path: NAVCalculator calls the inherited `getAdapterPositions(account, assetFilter)` on every adapter
/// uniformly (no ERC165 routing). A meta-adapter services it by reading its own NAV-configured set via
/// `getMetaInstances(address(this))` and fanning out over it — see `MetaBalanceAdapter`. The instance-aware
/// methods below take an explicit instance list for off-chain/explicit queries and per-instance breakdowns.
/// (The other no-arg `IBalanceAdapter` methods — `getAdapterBalances`/`getAdapterBalanceForAsset` —
/// are not used by the NAV path and return empty.)
interface IMetaBalanceAdapter is IBalanceAdapter {
/// @notice Get all positions for an account across the supplied instances.
/// @param account The account to query.
/// @param instances The instance coordinates to query (e.g. vault addresses widened to bytes32).
/// @param assetFilter Optional asset filter (address(0) for all assets).
/// @return positions Array of balance-only PositionBalance structs aggregated across the instances.
function getAdapterPositionsForInstances(address account, bytes32[] calldata instances, address assetFilter)
external
view
returns (INAVCalculator.PositionBalance[] memory positions);
/// @notice Returns the underlying assets supported across the supplied instances.
/// @param instances The instance coordinates to inspect.
/// @return underlyingAssets The list of underlying asset addresses (may contain duplicates across instances).
function underlyingAssetsSupportedForInstances(bytes32[] calldata instances)
external
view
returns (address[] memory underlyingAssets);
}
src/balances/IPositionDescribable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IPositionDescribable
/// @notice Optional interface for balance adapters that expose a human-readable protocol name for their positions.
/// @dev NAVCalculator's verbose read methods (`getAccountPositionsVerbose`, `getAccountPositionsForAssetVerbose`,
/// `getAccountNavVerbose`) call these via a fail-open staticcall — adapters that do not implement this
/// interface simply produce an empty protocol name / label set. Labels are derived **lazily from `positionId`**
/// (a static, per-position breadcrumb), so they are computed only in the verbose reads, not carried on every
/// `PositionBalance` (that keeps display work off the NAV hot path). The ephemeral per-item id (Uniswap V3 NFT
/// id, withdrawal request id, …) is NOT a label — it is the typed `PositionBalance.positionInstanceId` field.
/// Clients MUST NOT use these strings for identity, indexing, or reconciliation; use the typed
/// `protocolSubId` / `positionId` / `PositionKind` fields on `PositionBalance` for those purposes.
/// @author KPK
interface IPositionDescribable {
/// @notice Human-readable name of the PROTOCOL, e.g. "Aave V3", "Morpho", "Uniswap V3".
/// @dev **This names the protocol, never the product.** A protocol's individual products — Aave V3's Safety
/// Module and Umbrella, Morpho's vaults and markets, Balancer's pools and gauges — all return the SAME
/// string here; what distinguishes them is `positionLabels()` (`["Umbrella Module"]`, `["Safety Module"]`,
/// `["Market", "wstETH/USDC"]`) and the typed `protocolSubId`. Equivalently: every adapter sharing a
/// `ProtocolIds` protocol id MUST return the same name. Pull it from `src/utils/ProtocolNames.sol` rather
/// than writing a literal — new and changed adapters should reference the constant; the pre-existing
/// literals are being migrated adapter by adapter and are meanwhile pinned to their constants by
/// `test/ProtocolNameConsistency.t.sol`. Meta-adapters need no literal at all (see below).
///
/// Why the distinction is load-bearing rather than cosmetic: consumers group *configured adapters* by this
/// string. The typed `protocolBrand`/`protocolId`/`protocolSubId` would group them correctly, but they are
/// `private constant` and only ride on `PositionBalance` structs returned by an **account** read — a
/// consumer enumerating registered adapters never sees them, so the display name is the only protocol
/// identity it has. An adapter that returns its product name here splits itself out into a phantom sibling
/// protocol (`AaveUmbrellaBalanceAdapter` returned "Aave Umbrella" and did exactly that).
///
/// Per-instance adapters return a compile-time constant. Meta-adapters **derive** it —
/// `MetaBalanceAdapter.protocolName()` is `ProtocolNames.forProtocolId(_protocolId())` — so for the whole
/// meta family the invariant holds by construction: the name is a pure function of the typed identity the
/// adapter already declares, with no constructor argument or config value that could disagree with it.
function protocolName() external view returns (string memory);
/// @notice Ordered, arbitrary-depth display hierarchy for a single position, BELOW the protocol level.
/// Index 0 is the broadest level (category) and the last element is the position leaf, e.g.
/// `["Market", "wstETH/USDC"]`, `["AMM Liquidity Pool", "WETH/USDC 0.05%"]`, or `["Safety Module"]` when the
/// category itself is the leaf. The full breadcrumb a consumer renders is
/// `[protocolName(), ...positionLabels(positionId)]`. Derived purely from `positionId` (the static
/// anchor) — the ephemeral per-item id rides in `PositionBalance.positionInstanceId`, not here.
/// @param positionId The ABI-encoded position identifier (same bytes as `PositionBalance.positionId`).
/// @return An array of display segments. An empty array is acceptable when no label can be derived.
/// Depth varies by adapter and position; consumers must not assume a fixed length.
///
/// **When there is no account to get a positionId from** — a configuration view listing what the
/// NAVCalculator is set up to account for — an adapter whose breadcrumb is positionId-independent
/// answers `positionLabels("")` with its full constant breadcrumb, and that is the whole answer. An
/// adapter whose breadcrumb is derived per positionId returns `[]` instead and should implement
/// {IPositionEnumerable}, whose `positionIds()` lists the shapes to pair with this function and whose
/// ERC-165 bit is what distinguishes that `[]` from a broken adapter. See {IPositionEnumerable}.
function positionLabels(bytes calldata positionId) external view returns (string[] memory);
}
src/balances/LabelLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @notice Minimal ERC20 metadata view (name/symbol) for fail-open label reads.
interface IERC20MetaView {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
/// @title LabelLib
/// @author KPK
/// @notice Fail-open ERC20 `name()` / `symbol()` reads for building human-readable position labels.
/// @dev `positionLabels` is a verbose/display-only path and MUST NOT revert. A token's metadata read can fail three
/// ways, and a bare `try`/`catch` covers only one of them:
/// 1. the address has **no code** — a high-level call reverts via Solidity's `extcodesize` precheck *before*
/// the call, which `try`/`catch` does NOT catch;
/// 2. the call **reverts** — this is the one `try`/`catch` does catch;
/// 3. the call **succeeds but returns data that cannot be ABI-decoded as a string** — Solidity does NOT route
/// a return-data decode failure into the `catch` clause, so it propagates to the caller and reverts the
/// whole labels read.
/// Class 3 is not hypothetical. Reproduced on solc 0.8.34: a token returning zero bytes (an ERC-1967 proxy whose
/// implementation slot points at a code-less address — the `delegatecall` succeeds returning nothing), a `bytes32`
/// name/symbol (MKR-style legacy tokens), a bare offset word with no length word, a nonsense offset, and absurd
/// declared lengths. Every one of those used to revert `positionLabels` for every adapter reading through here.
///
/// All three classes are handled below: an explicit codesize guard, a raw `staticcall` (so a revert is a `false`
/// return rather than an exception), and **validation of the ABI head before decoding**. A canonical `string`
/// return is `[offset = 0x20][length][payload…]`, so we require two full words, an offset of exactly `0x20`, a
/// non-zero length within {MAX_METADATA_BYTES}, and a payload that fits inside the returndata. Bounding on the
/// raw length is sufficient — a memory-source `abi.decode` bounds on the declared length, not on `ceil32` of it,
/// verified by sweeping truncated and unpadded payloads.
///
/// The read is **gas-capped**, and that is load-bearing rather than defensive. The previous `try`/`catch` form
/// used a parameterless `catch {}`, which never `returndatacopy`s the revert payload; a raw staticcall assigning
/// `(bool, bytes memory)` always does. Without {METADATA_READ_GAS} this rewrite would therefore introduce a
/// griefing vector that did not exist before — a hostile address returning a multi-megabyte revert payload, or
/// simply looping, was measured burning over a billion gas and could out-of-gas a verbose NAV read.
///
/// Callers get the metadata or their chosen `fallbackStr`, and never a revert. Empty-string returns are
/// normalised to `fallbackStr` too. Pass `""` for the single-leaf collapse convention (drop the leaf, keep the
/// category) or `"?"` as a placeholder inside a joined multi-token leaf. Shared across the meta, plain, and
/// assisted adapter families.
library LabelLib {
/// @notice Longest metadata string accepted; anything longer yields `fallbackStr`. Bounds how much a hostile
/// token can inflate a rendered label. Far above any real name or symbol.
/// @dev This is a NEW global constraint: the `try`/`catch` form this replaced returned any successfully-decoded
/// string regardless of length, and none of the call sites previously asked for a cap. Deliberate — an
/// unbounded label is an unbounded cost for every downstream renderer — but it does mean a token with an
/// absurdly long name now renders as the caller's fallback rather than in full.
uint256 private constant MAX_METADATA_BYTES = 256;
/// @notice Hard ceiling on returndata **copied into this contract's memory**: the two ABI head words plus
/// {MAX_METADATA_BYTES} of payload (64 + 256 = 320). Written as a literal because inline assembly accepts
/// only direct number constants.
/// @dev **This constant is where {MAX_METADATA_BYTES} is actually enforced.** The payload-fits check bounds `len`
/// by `copied - 64`, and `copied <= MAX_RETURN_BYTES`, so the cap follows structurally — which is why there is
/// no separate `len > MAX_METADATA_BYTES` clause (it would be provably unreachable). Keep the two constants in
/// lockstep: `MAX_RETURN_BYTES == 64 + MAX_METADATA_BYTES`.
///
/// **Bound on what was COPIED, never on `returndatasize()`.** An earlier revision rejected any reply larger
/// than this constant, on the stated assumption that a canonical reply for an in-cap string never exceeds it.
/// That assumption is **wrong**, and the counterexamples are ordinary mainnet tokens: the Vyper LP tokens from
/// Curve's USD-metapool factory (`0xB9fC157394Af804a3578134A6585C0dc9cc990d4`) return a fixed **4096-byte**
/// buffer behind a perfectly canonical head — FRAX3CRV-f, MIM-3LP3CRV-f, alUSD3CRV-f and LUSD3CRV-f among
/// them, 12 of the first 80 pools in that factory — carrying strings of only 10-57 bytes. `abi.decode`
/// accepts those, as did both predecessors; only a size-keyed reject discarded them, and on their padding
/// rather than their content. None is a configured instance today, but the Curve/Convex roadmap makes it a
/// live trap. Hence `copied = min(size, MAX_RETURN_BYTES)` and a payload bound against `copied`.
///
/// This, not the gas stipend, is what bounds caller-side cost. A gas stipend alone does NOT: a hostile token
/// can `return(0, 200_000)` — the callee's own memory expansion for ~200 KB costs it about 95k, so it fits
/// inside {METADATA_READ_GAS} — while the *caller* pays `returndatacopy` plus its own monotonically growing
/// memory, charged outside the stipend and quadratic in total. Measured on the stipend-only version: 210,190
/// gas for one read and 14.5M across eight sequential reads in one frame, which a multi-token leaf
/// (`_joinTokenSymbols` over a Balancer pool, `CurvePoolLib.coinSymbols` over an 8-coin pool) does. Passing an
/// explicit output size to `staticcall` copies at most this many bytes no matter what the callee returns, so
/// the cost is flat. `returndatasize()` still reports the true size, so an oversized reply is rejected rather
/// than silently truncated.
uint256 private constant MAX_RETURN_BYTES = 320;
/// @notice Gas stipend for a metadata probe. Generous for a real (even proxied) `name()`/`symbol()`, and it bounds
/// the callee's own execution — including a write-protection abort, which consumes everything forwarded.
/// @dev Necessary but NOT sufficient on its own; see {MAX_RETURN_BYTES} for the caller-side bound.
uint256 private constant METADATA_READ_GAS = 100_000;
/// @notice The token's ERC20 `name()`, or `fallbackStr` if the address has no code, the call reverts, the return
/// data is not a decodable string, or it returns an empty string.
function name(address token, string memory fallbackStr) internal view returns (string memory) {
return _readString(token, IERC20MetaView.name.selector, fallbackStr);
}
/// @notice The token's ERC20 `symbol()`, or `fallbackStr` if the address has no code, the call reverts, the return
/// data is not a decodable string, or it returns an empty string.
function symbol(address token, string memory fallbackStr) internal view returns (string memory) {
return _readString(token, IERC20MetaView.symbol.selector, fallbackStr);
}
/// @notice Fail-open read of ANY parameterless, `string`-returning view — the generic form of {name}/{symbol}.
/// @dev The canonical home for hardened string-metadata reads. Three sessions independently wrote this same
/// reader — here, and as a `_safeStringRead` duplicated verbatim across the AaveV3 and Gearbox
/// adapters — before it was exposed; those copies now route here so a fourth cannot accumulate.
///
/// Callers wanting ERC20 metadata should still use {name}/{symbol}; this is for everything else
/// (Aave's `getMarketId()`, Gearbox's credit-manager `name()`, …).
/// @param token The contract to probe.
/// @param selector The parameterless, string-returning selector to call.
/// @param fallbackStr Returned unchanged on every failure path, and for an empty result.
function readString(address token, bytes4 selector, string memory fallbackStr)
internal
view
returns (string memory)
{
return _readString(token, selector, fallbackStr);
}
/// @notice Shared fail-open string-metadata read behind {name}, {symbol} and {readString}.
/// @param token The contract to probe.
/// @param selector The parameterless, string-returning selector to call.
/// @param fallbackStr Returned unchanged on every failure path, and for an empty result.
/// @dev See the contract-level doc for why each guard exists. Order matters: codesize first (cheapest, and the
/// class a high-level call cannot catch), then the capped raw call, then head validation, and only then the
/// decode — which is safe precisely because the head was validated.
function _readString(address token, bytes4 selector, string memory fallbackStr)
private
view
returns (string memory)
{
// Cheap short-circuit only. A raw `staticcall` to a code-less address succeeds with empty returndata, which the
// length check below already rejects — unlike the high-level call this replaced, where `extcodesize` reverted
// before the call and made this guard load-bearing.
if (token.code.length == 0) return fallbackStr;
bytes memory data = new bytes(MAX_RETURN_BYTES);
bool ok;
uint256 size;
assembly ("memory-safe") {
// Selector into scratch space; `bytes4` is left-aligned in its word, so the first 4 bytes are the selector.
mstore(0x00, selector)
// The explicit output size is the point: at most MAX_RETURN_BYTES is copied into our memory, whatever the
// callee returns. `returndatasize()` still reports the untruncated size.
ok := staticcall(METADATA_READ_GAS, token, 0x00, 0x04, add(data, 0x20), MAX_RETURN_BYTES)
size := returndatasize()
}
// A `string` return needs at least the offset and length words.
if (!ok || size < 64) return fallbackStr;
// Only the first MAX_RETURN_BYTES were copied; `size` may be larger. Bound on what we actually HAVE, not on
// what the callee claimed to send. Keying the accept window on `size` instead would reject a reply whose
// string sits entirely inside the copied window but which carries trailing or over-padded bytes behind it —
// a narrowing versus both predecessors (the high-level typed call and StakeWise's `_safeVaultName`), and one
// no real string needs. `copied >= 64` because `size >= 64` and MAX_RETURN_BYTES far exceeds 64.
uint256 copied = size < MAX_RETURN_BYTES ? size : MAX_RETURN_BYTES;
// Shrink to the copied extent so `abi.decode`'s own bound matches the bytes we hold.
assembly ("memory-safe") {
mstore(data, copied)
}
uint256 offset;
uint256 len;
assembly ("memory-safe") {
offset := mload(add(data, 0x20))
len := mload(add(data, 0x40))
}
// `len > copied - 64` is the payload-fits check, written as a subtraction on the LEFT so an attacker-supplied
// `len` near 2^256 cannot overflow `64 + len`. It also enforces {MAX_METADATA_BYTES} structurally: `copied` is
// at most `MAX_RETURN_BYTES` = 64 + MAX_METADATA_BYTES, so any accepted `len` is at most MAX_METADATA_BYTES.
// An explicit `len > MAX_METADATA_BYTES` clause here would be dead code — mutation-testable to nothing — so the
// cap lives in the MAX_RETURN_BYTES definition instead. Change one of those two constants and you must change
// the other.
if (offset != 0x20 || len == 0 || len > copied - 64) return fallbackStr;
return abi.decode(data, (string));
}
}
src/errors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
error InvalidArguments();
error InvalidArgumentsWithContext(string context);
/// @notice A constructor argument expected to be a deployed contract has no code. `name` is the dependency label.
error NotAContract(string name);
error NotAuthorized();
error NotChainlinkOracle();
/// @notice Thrown when an assistant entrypoint that must be delegatecalled is called directly on the singleton
/// (`address(this) == SELF`). Canonical delegatecall-guard error for the assistant-fed family (`BalanceAdapterAssistant`).
error NotDelegateCall();
/// @notice An assistant entrypoint was told to track/act for an account other than the executing context
/// (`address(this)`, i.e. the delegatecalling Safe). Canonical assistant self-scope check (`_requireSelf`).
error AssistantAccountMismatch(address expected, address provided);
// Permissionless assistant-fed assisted balance-adapter family (ADR 0018) — shared coordinate-cache errors, used by the
// single {AssistedCoordCache} base (every coordinate is an `abi.encode`d blob). The coordinate is identified by `id`
// (a tokenId / requestId / positionTicket, from `_coordId`); the full tuple, where richer, rides in the cache's events.
/// @notice `submit` was given a coordinate not currently owned by the caller (`msg.sender`).
error CoordinateNotOwned(address account, uint256 id);
/// @notice `submit` would grow the caller's cache past its per-account cap.
error CoordinateCacheFull(address account, uint256 maxCoordinates);
/// @notice `remove` targeted a coordinate not in the caller's cache.
error CoordinateNotCached(address account, uint256 id);
/// @notice `remove` targeted a coordinate the caller still owns (a live position) — refused so a live position is never
/// dropped (would under-report the caller's own NAV). Only a claimed/consumed coordinate may be removed.
error CoordinateStillLive(address account, uint256 id);
/// @notice `submit` was given a coordinate that failed the adapter's write-time protocol validation (e.g. an
/// unregistered target). Distinct from {CoordinateNotOwned} (ownership) — this is a malformed/invalid coordinate.
error InvalidCoordinate(address account, uint256 id);
// Bridge-specific errors
error AlreadyInitialized();
error InvoiceNotFound();
error InvoiceAlreadyExists();
error InvalidInvoiceStatus();
error InvalidInvoice();
error TransferFailed();
error InsufficientBalance(address asset, uint256 required, uint256 available);
error InvalidChainId();
error InvalidNonce();
error InvalidCompletionData();
error InvalidChecksum(bytes32 invoiceId, bytes24 provided, bytes24 calculated);
error InvalidTimestamp(uint64 provided, uint64 current);
error AssetHasActiveInvoices(string symbol);
error AssetNotRegistered(string symbol);
// NAV Calculator / registry errors
error PriceFeedNotSet(address asset);
error AssetNotFound();
error OnlyNAVCalculator();
error ArrayLengthMismatch();
error InvalidAssetDecimals();
error InvalidDecimalExponent();
src/nav/INAVCalculator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
import {IBalances} from "src/balances/IBalances.sol";
import {IPrices} from "src/prices/IPrices.sol";
import {PositionKind} from "src/utils/PositionKind.sol";
/// @title INAVCalculator
/// @notice Interface for the NAV Calculator contract. Defines the full API for asset registration, price feeds,
/// balance adapters, and NAV/position queries in one or more quote currencies.
/// @dev Extends IBalances for adapter registry and IPrices for price feed types. Implementations are typically
/// UUPS-upgradeable and use AccessControl (MANAGER for mutations, DEFAULT_ADMIN_ROLE for upgrades).
/// @author KPK
interface INAVCalculator is IBalances {
/// @notice A balance adapter consumed the gas stipend the NAV read forwarded to it without answering.
/// @dev Deliberately NOT folded into the read's fail-open path. A revert means "this adapter has nothing to
/// report"; running out of gas means "this adapter's answer is unknown", and reporting an unknown answer
/// as an empty one drops the adapter's legs — a dropped debt leg RAISES the reported NAV.
///
/// Declared here rather than alongside the shared errors so it reaches consumers: it is raised inside a
/// DELEGATECALLed library, and an error a contract never names itself does not appear in that contract's
/// ABI. Callers generate against this interface and the NAVCalculator implementing it, so a revert they
/// can actually decode has to be part of it.
///
/// `adapter` names the adapter that was running, which is not always the adapter at fault: the stipend is
/// a share of what the READ still holds, so an under-funded call starves whichever adapter happens to be
/// reached last. `stipend` and `consumed` are what separate the two cases. A large `stipend` fully
/// consumed means that adapter is genuinely runaway; a small `stipend` means the read itself was short of
/// gas and the fix is to supply more.
/// @param adapter The adapter that was executing when its gas ran out.
/// @param stipend The budget the classification was measured against: 63/64 of what the read held just before
/// the call. It is NOT precisely what the EVM forwarded — the same 63/64 rule is applied again at the
/// CALL itself, to a figure already reduced by building the calldata — so on a genuine exhaustion
/// `consumed` lands a few tens of gas ABOVE it. Read the two as a ratio, not as a balance.
/// @param consumed Gas the call actually cost this frame, including the call overhead.
error AdapterGasExhausted(address adapter, uint256 stipend, uint256 consumed);
/// @notice One governed instance of a meta-adapter consumed its gas stipend without answering.
/// @dev The {AdapterGasExhausted} sibling, one frame in. A meta-adapter isolates each instance behind its own
/// `try`/`catch` so a single faulty instance cannot zero out the batch, and that isolation has the same
/// blind spot: an instance that runs out of gas is indistinguishable from one that reverted, and recording
/// it as "no positions" drops its legs while the meta-adapter still RETURNS SUCCESSFULLY — so the caller
/// sees a complete-looking answer. A dropped debt leg raises the reported NAV.
///
/// Raised rather than swallowed. `PriceFeedLib` keys on this selector explicitly rather than re-deriving
/// exhaustion from gas, so a cheap early raise here cannot be re-scored as a benign revert one frame out.
///
/// `instance` is where the budget ran out, which is NOT the same as where it went. The fan-out gives each
/// instance a share of whatever its predecessors left, so a single runaway instance early in the governed
/// set can leave the NEXT one too little and get it named instead. Read the pair together: a large
/// `stipend` fully consumed means that instance is genuinely runaway; a small `stipend` means it was
/// starved by something before it, or the read was under-funded to begin with. Removing the named instance
/// is the wrong first move when `stipend` is small.
/// @param adapter The meta-adapter that was fanning out. Overwritten by `PriceFeedLib` with the address it
/// actually called, so it is trustworthy even when the rest of the payload is not.
/// @param instance The governed instance coordinate whose read ran out of gas — see the caveat above.
/// @param stipend The budget the classification was measured against: 63/64 of what the fan-out held just
/// before the call. As with {AdapterGasExhausted} it is NOT precisely what the EVM forwarded — the same
/// rule is applied again at the CALL — so `consumed` lands slightly above it. A ratio, not a balance.
/// @param consumed Gas the instance call actually cost, including the fan-out's call overhead.
error InstanceGasExhausted(address adapter, bytes32 instance, uint256 stipend, uint256 consumed);
/// @notice {getAccountNavForAdapters} was given an empty adapter list.
/// @dev Not silently answered with a zero NAV. An empty slice is indistinguishable from "this portion of the
/// portfolio is worth nothing", and a caller that built its slice list from a stale or mis-parsed source
/// would read that zero as a real answer and reassemble a NAV that is short by exactly the adapters it
/// forgot to ask for. Declared here rather than in `src/errors.sol` for the same reason as
/// {AdapterGasExhausted}: it is raised inside a DELEGATECALLed library, so it only reaches consumers'
/// generated ABIs by being named in this interface.
error EmptyAdapterSlice();
/// @notice {getAccountNavForAdapters} was given an adapter that is not in the global registry.
/// @dev The registry is `getAllAdapters()` — the exact list the complete read scans — so "registered" here
/// means "would have been included in `getAccountNav`". Rejected rather than skipped: an unregistered
/// address (a decommissioned adapter, a typo, an address from another chain) has no positions to report,
/// so skipping it would return a well-formed slice whose `value` is silently missing whatever the caller
/// believed that address covered — and whose `adaptersCovered` would then have to either echo an address
/// that contributed nothing or omit one the caller asked for. Both mislead the coverage check that
/// `adaptersCovered` exists to support.
/// @param adapter The supplied address that is not a registered balance adapter.
error AdapterNotRegistered(address adapter);
/// @notice {getAccountNavForAdapters} was given the same adapter twice in one slice.
/// @dev A repeated adapter is queried twice and its positions summed twice, so the slice over-reports by that
/// adapter's whole value. Rejected rather than deduplicated, because a duplicate means the caller's
/// partition logic is wrong and the same defect will be producing overlaps ACROSS slices — which this
/// contract cannot see and silently deduplicating here would hide. Cross-slice overlap is what
/// `PartialNAV.adaptersCovered` is for.
/// @param adapter The address that appeared more than once.
error DuplicateAdapterInSlice(address adapter);
//
// Structs
//
/// @notice Registered asset metadata used by the NAV/Pricing registry and balance adapters.
/// @param asset Token address (or NATIVE_ADDRESS for chain native token).
/// @param symbol Display symbol (e.g. "ETH", "USDC").
/// @param decimals Number of decimals for amounts.
struct Asset {
address asset;
string symbol;
uint8 decimals;
}
/// @notice Balance-only position data returned by balance adapters (no pricing).
/// @dev NAVCalculator enriches these with pricing to produce Position structs.
/// @param balanceAsset Asset metadata (address, symbol, decimals). The token `amount` is denominated in.
/// @param balanceAdapter Address of the adapter that reported this position. Provenance / audit trail — NOT part of identity.
/// @param amount Balance magnitude (always positive); sign is implied by isDebt.
/// @param isDebt True if debt (subtract from NAV), false if credit (add to NAV). Canonical NAV-sign signal.
/// @param protocolBrand `keccak256` of the protocol brand slug (version-stripped, e.g. `aave`, `balancer`; see
/// `src/utils/ProtocolIds.sol`). The broadest roll-up layer — several `protocolId`s share it
/// (`aave-v3` → `aave`; `balancer-v2` + `balancer-v3` → `balancer`). Display/grouping only; NOT part of the
/// stable identity key. Equals `protocolId` for unversioned protocols.
/// @param protocolId `keccak256` of the broad protocol-ecosystem slug (e.g. `aave-v3`, `curve`; see
/// `src/utils/ProtocolIds.sol`). A roll-up / grouping key only — several `protocolSubId`s share it
/// (e.g. `aave-v3-lending` + `aave-v3-safety-module` both roll up to `aave-v3`). NOT part of the stable
/// identity key (it is functionally determined by `protocolSubId`).
/// @param protocolSubId `keccak256` of the specific protocol-product slug (e.g. `aave-v3-lending`; see
/// `src/utils/ProtocolIds.sol`). Selects the `positionId` ABI-decode schema — one sub-slug implies exactly
/// one schema — and is the protocol component of the stable identity key. Equals `protocolId` for
/// single-product ecosystems.
/// @param positionId ABI-encoded position identifier. Decode schema is determined by `protocolSubId`.
/// e.g. for AAVE_V3_LENDING: `abi.encode(address pool)`.
/// Full schema table: see `src/utils/ProtocolIds.sol` and docs/howto/position-identity-schema.md.
/// @param positionKind Semantic discriminator (Wallet / Supplied / Borrowed / Collateral / Staking / Rewards / Fees).
/// Together with `protocolSubId` and `positionId` forms the stable per-chain identity key
/// `(chainId, protocolSubId, positionId, balanceAsset.asset, positionKind)`.
/// @param isLocked True if this leg is NOT withdrawable right now (the pending portion of a withdrawal queue, or a
/// staked amount in/awaiting its unstaking cooldown); false if fully liquid / claimable now. Withdrawal-queue
/// and cooldown adapters keep a STATIC, timeless `positionId` (the queue/manager/asset/vault/stake-token
/// coordinate) and split an account's holding into up to two legs — a claimable leg (`isLocked=false`) and a
/// locked leg (`isLocked=true`). `isLocked` is a **mutable per-leg attribute, NOT part of the identity key**:
/// a leg flips `true→false` as its portion finalizes/unlocks, so keying on it would split one economic
/// position into two keys over its lifetime. The claimable and locked legs therefore share ONE key and are
/// **summed** in reconciliation (the sum is the full holding); read `isLocked` per leg for the
/// claimable-vs-locked breakdown. `false` for every adapter except withdrawal-queue / cooldown legs.
/// @param positionInstanceId OPTIONAL EPHEMERAL per-item coordinate as a `bytes32` — a Uniswap V3 / PancakeSwap V3
/// NFT id, a withdrawal/exit request id, or a StakeWise exit ticket (each a `uint256` widened to `bytes32`).
/// `bytes32(0)` for adapters with no per-item granularity. It is the SOLE ephemeral identity field, by
/// design: the **stable** reconciliation key
/// `(chainId, protocolSubId, positionId, balanceAsset.asset, positionKind)` deliberately EXCLUDES it,
/// so the legs of one anchor sum and identity survives item churn. A consumer that wants per-item
/// granularity MAY append `positionInstanceId` to the key — gaining one position per item, at the cost of an
/// **ephemeral** key (it blinks in/out as items are minted/burned/claimed). Never use it for stable
/// identity. (Stable sub-distinguishers like an Aave reserve are NOT here — they live in `balanceAsset`.)
/// Typed as `bytes32` (not `bytes`): every current coordinate is a single `uint256`, and a value type keeps
/// the position-building/copy loops under the via_ir stack limit.
struct PositionBalance {
Asset balanceAsset;
address balanceAdapter;
uint256 amount;
bool isDebt;
bytes32 protocolBrand;
bytes32 protocolId;
bytes32 protocolSubId;
bytes positionId;
PositionKind positionKind;
bool isLocked;
bytes32 positionInstanceId;
}
/// @notice Enriched position including pricing and quote-currency value.
/// @dev Returned by getAccountPositions and getAccountPositionsForAsset.
/// @param balanceAsset Asset metadata from registry (canonical symbol/decimals).
/// @param balanceAdapter Adapter that reported the balance.
/// @param amount Balance magnitude (positive); sign implied by isDebt.
/// @param isDebt True if debt, false if credit.
/// @param quoteAsset Quote currency for value (e.g. USD when address(0)).
/// @param value Value in quote asset (negative for debt).
/// @param price Price used (e.g. USD per unit of asset).
/// @param priceDecimals Decimals of price.
/// @param stale True if the price was stale at query time.
/// @param protocolBrand `keccak256` protocol brand slug (broadest grouping). Copied from PositionBalance.
/// @param protocolId `keccak256` broad ecosystem slug (grouping). Copied from PositionBalance.
/// @param protocolSubId `keccak256` specific protocol-product slug (identity-key component). Copied from PositionBalance.
/// @param positionId ABI-encoded position identifier. Copied from PositionBalance.
/// @param positionKind Semantic discriminator. Copied from PositionBalance.
/// @param isLocked True if the leg is not withdrawable now (pending/cooling). Copied from PositionBalance.
/// @param positionInstanceId Ephemeral per-item coordinate (NFT/request/ticket), or empty. Copied from
/// PositionBalance; excluded from the stable identity key. See PositionBalance.
struct Position {
Asset balanceAsset;
address balanceAdapter;
uint256 amount;
bool isDebt;
Asset quoteAsset;
int256 value;
int256 price;
uint8 priceDecimals;
bool stale;
// True if the quote asset's own price feed was stale. When true, `value` is in USD (8dp) even though
// `quoteAsset` is non-zero — the quote conversion was skipped. Mirrors NAV.quoteAssetStale ([9]/S2).
bool quoteAssetStale;
bytes32 protocolBrand;
bytes32 protocolId;
bytes32 protocolSubId;
bytes positionId;
PositionKind positionKind;
bool isLocked;
// Ephemeral per-item coordinate copied from PositionBalance (NFT id / request id / ticket as bytes32).
// bytes32(0) when none. Display/granularity only — excluded from the stable identity key. See PositionBalance.
bytes32 positionInstanceId;
// True if the asset's primary price diverged from its monitor feeds beyond the configured tolerance (or,
// for stablecoins, from the $1 peg). A pricing-quality signal, NOT a validity/staleness flag: `price` and
// `value` are still populated from the primary. Consumers (e.g. the sub/redeem processor) decide how to react.
// APPENDED (not inserted mid-struct) so an in-place UUPS upgrade doesn't shift existing fields' ABI offsets.
bool irregular;
// True if the quote (unit-of-account) asset's own primary diverged from its monitors — the divergence
// counterpart to `quoteAssetStale`. Always false for a USD quote.
bool quoteAssetIrregular;
}
/// @notice Position enriched with human-readable display labels.
/// @dev ⚠️ **NEITHER `protocolName` NOR ANY element of `labels` is necessarily the adapter's own value.**
/// `AssetKindRegistry` holds an optional per-ADAPTER protocol name plus a per-ADAPTER, per-SEGMENT `labels`
/// override, and {PriceFeedLib.toVerbose} applies both in preference to the adapter's reply.
///
/// ⚠️ **Two earlier revisions of this line were narrower than the code, in the same direction each time.**
/// The first said the computed leaf was never overridable; the second said only `labels[0]` was. Both are now
/// false: {IAssetKindRegistry.setAdapterLabels} writes at ANY index, bounded only by
/// `min(reply.length, override.length)` — so the honest statement is that a segment comes from the adapter
/// **unless an operator overrode that index**, and `""` at an index is how an operator declines to.
///
/// What the override CANNOT do is change the array's LENGTH: it never writes past the adapter's own reply and
/// never extends it, so `labels.length` is always the adapter's answer. (The one exception is
/// `getAdapterDisplayInfo`, whose empty-reply case is deliberately grown — see
/// `PriceFeedLib.adapterDisplayInfo`.)
///
/// Which segments an operator SHOULD write is a property of the adapter, not of this struct;
/// `src/balances/BALANCE_ADAPTERS.md` §6.2 carries the per-adapter sweep, and
/// `ERC20DefaultBalanceAdapter` is the one adapter that must not be overridden at all (its single element is
/// the computed token symbol, not a category). `AdapterLabelOverrides.t.sol
/// ::test_labelsOverride_onLeafOnlyAdapter_replacesTheLeaf_documentedHazard` asserts that hazard.
/// Consumers must not treat these strings as identity in any case; see {IPositionDescribable}.
/// @dev Returned by verbose read methods. Labels are sourced from the adapter's `IPositionDescribable`
/// implementation (`positionLabels(positionId)`, via a fail-open staticcall) and are empty otherwise. MUST NOT
/// be used for identity, indexing, or reconciliation — use the typed fields on `position` for those purposes.
struct VerbosePosition {
Position position;
string protocolName; // e.g. "Aave V3", "Morpho"
// Ordered display hierarchy BELOW the protocol, leaf last (arbitrary depth, may be empty), e.g.
// ["Market", "wstETH/USDC"] or ["AMM Liquidity Pool", "WETH/USDC 0.05%"]. Full breadcrumb = [protocolName,
// ...labels]. Sourced from IPositionDescribable.positionLabels(positionId); display only. The ephemeral
// per-item id (NFT/request/ticket) is NOT here — it is the typed `position.positionInstanceId` field.
string[] labels;
}
/// @notice NAV snapshot bundled with a full verbose position breakdown.
// forge-lint: disable-next-line(pascal-case-struct)
struct VerboseNAV {
NAV nav;
VerbosePosition[] positions;
}
/// @notice NAV snapshot for an account in a given quote currency.
/// @param value Total portfolio value in quoteAsset (can be negative if net debt).
/// @param quoteAsset Quote currency; address(0) denotes USD.
/// @param timestamp Block timestamp of the reading.
/// @param stalePriceAssets Assets whose prices were stale at query time.
/// @param irregularPriceAssets Assets whose primary price diverged from their monitor feeds beyond tolerance
/// (or, for stablecoins, from the $1 peg) at query time. A pricing-quality signal, not a staleness flag —
/// `value` is still computed from the primary prices. Consumers decide how to react.
/// @param sequencerDown True if the L2 sequencer was down or in grace period (L2 only).
/// @param quoteAssetStale True if the quote asset's own price feed was stale. When true the value field
/// is in USD (fallback) even though quoteAsset is non-zero — callers must check this flag before
/// interpreting value as being in the requested quote currency.
/// @param monitorsUnhealthyPriceAssets Assets that **have monitor feeds configured but where none of them was
/// readable** at query time — every monitor stale, reverting, or reporting a non-positive price. For these
/// the divergence check silently did not run: `divergenceBps` is 0 because the arithmetic never executed,
/// not because the prices agreed, so absence from `irregularPriceAssets` says nothing about them. Without
/// this list "checked and clean" and "checked by nothing that answered" are the same bytes.
///
/// **This is NOT the "no monitors configured" case.** That is a static configuration property, derivable
/// off-chain from **`getMonitorFeedCount(asset) == 0` alone**, and it is deliberately excluded here — an
/// asset with nothing configured never appears in this list however long it goes unchecked. What this
/// reports is strictly a *runtime* failure of monitors that exist.
///
/// Do NOT additionally require `getAssetPricing(asset).divergenceToleranceBps == 0` for that derivation:
/// the conjunction is UNSATISFIABLE for any asset that ever had a monitor. `_setDivergenceTolerance`
/// rejects 0, so once a tolerance is set it can never be returned to zero, while `removeMonitorFeed`
/// leaves the tolerance untouched — so an asset whose monitors were all REMOVED has count 0 and a
/// non-zero tolerance, and an AND-recipe would silently never flag it. The tolerance only returns to 0
/// via full asset unregistration (`_removeAllMonitorFeeds`), by which point the asset is gone anyway.
///
/// Assets whose own primary is unusable are also excluded — stale feed, sequencer down, or a primary whose
/// 8-decimal normalisation degenerates to zero. In all of those the check was suppressed by the PRIMARY
/// rather than by the monitors, `stalePriceAssets` already reports the staleness cases, and naming the
/// monitors would point an operator at the wrong contract. Stablecoins with a non-zero `pegToleranceBps`
/// may appear here and still be peg-checked — the peg guard is monitor-independent — so this flags the
/// loss of the *divergence* check, not necessarily of all checks.
///
/// **Scope: assets this account holds positions in**, like `stalePriceAssets` and `irregularPriceAssets`.
/// It is built from the assets the account's positions touched, NOT from the whole registry, so absence
/// means "monitors healthy **or** no position held". A consumer reconciling against the registry-wide
/// per-asset view (`getPriceDivergence(asset).monitorFeedCount == 0` is the equivalent there) will see
/// differences that are this scoping, not a defect. Note also that `healthCheck()` — which DOES iterate
/// the whole registry — deliberately does not carry this array: `NAVCalculator` is 68 bytes from the
/// EIP-170 limit, so widening that return was not affordable. `Position.irregular` on
/// `getAccountPositions` likewise retains the original ambiguity, with no `NAV` struct alongside to join
/// against; use `getAccountNavVerbose` (whose `VerboseNAV` embeds the `NAV`) if you need both.
// forge-lint: disable-next-line(pascal-case-struct)
struct NAV {
int256 value;
Asset quoteAsset;
uint64 timestamp;
Asset[] stalePriceAssets;
bool sequencerDown;
bool quoteAssetStale;
// APPENDED (not inserted mid-struct) so an in-place UUPS upgrade doesn't shift existing fields' ABI offsets.
Asset[] irregularPriceAssets;
// True if the quote (unit-of-account) asset's own primary diverged from its monitors beyond tolerance —
// the divergence counterpart to `quoteAssetStale`. Always false for a USD quote (no quote feed).
//
// DECLARED GAP, deliberate: there is no `quoteAssetMonitorsUnhealthy` counterpart to
// `monitorsUnhealthyPriceAssets` below. For a non-USD quote whose own monitors have ALL gone unreadable, this
// flag is false for want of data — exactly the ambiguity that array exists to close — and nothing surfaces it.
//
// Why it was not added, in order of weight. (1) **Nothing in this repository's configuration exercises it**:
// `nav-config/assets-and-price-feeds/{1,42161,8453,100}.json` contain no quote keys, and `quoteAsset` is a
// CALLER-supplied parameter defaulting to USD (`address(0)`), not stored config — so the gap is reachable only
// by a caller that opts into a non-USD quote. (2) `NAVCalculator` has 68 bytes of EIP-170 headroom; a further
// struct member plus its computation plausibly exceeds that, and spending the last of the margin on an
// unexercised path would leave nothing for an urgent fix — after which the next change would need a new proxy
// rather than an upgrade.
//
// Limit of that evidence: it is a claim about THIS repository only. A downstream consumer (share layer,
// portal, agents, subgraphs) could pass a non-zero `quoteAsset`, which cannot be verified from here. If one
// does, this gap is worth the bytes and should be revisited.
//
// Mitigation meanwhile: a caller using a non-USD quote should read `getPriceDivergence(quoteAsset)` and treat
// `monitorFeedCount == 0` alongside a usable primary as exactly this condition.
bool quoteAssetIrregular;
// APPENDED for the same reason as `irregularPriceAssets` above. This redeploy uses a NEW proxy rather than an
// in-place upgrade, so nothing forced the append — but moving existing consumers' ABI offsets for a change
// that did not need to move them is gratuitous, so the convention is honoured anyway.
Asset[] monitorsUnhealthyPriceAssets;
}
/// @notice One SLICE of an account's NAV: the same snapshot as {NAV} but covering only the balance adapters
/// named in the request, plus the list of adapters it actually covered.
/// @dev Returned by {getAccountNavForAdapters}. Deliberately a DISTINCT type from {NAV}, not a reuse of it,
/// and that is the whole safety property of this API: a partial result must not be assignable, passable
/// or decodable where a complete NAV is expected. A `PartialNAV` that type-checked as a `NAV` would let a
/// caller hand one slice to a consumer that believes it holds the whole portfolio — the exact silent
/// under-report pagination exists to make impossible. The cost is that a caller must reassemble
/// explicitly; that cost is the point.
///
/// **Field order mirrors {NAV} exactly for its first eight fields, including NAV's own appended ones, so
/// a decoder written for `NAV` maps 1:1 onto this struct's prefix.** `adaptersCovered` is appended last.
/// Keep it that way: any future field goes at the END of this struct (see the APPENDED note on {NAV}),
/// and any field appended to {NAV} must be appended here too — BEFORE `adaptersCovered` if the prefix
/// correspondence is to survive, which means moving `adaptersCovered` and accepting the ABI shift, or
/// accepting that the prefix correspondence ends there. Prefer the latter: shifting a field's offset in a
/// struct a live off-chain reassembler decodes is worse than losing a documentation convenience.
/// @param value Net value of THIS SLICE's positions in `quoteAsset`, signed (negative if the slice is net
/// debt). **This is the one field that sums.** Debt legs are already negative, and prices are per-asset
/// and independent of which adapter reported the position, so the arithmetic is exact: summing `value`
/// over a partition of `getAllAdapters()` reproduces `getAccountNav().value` bit-for-bit, with no
/// tolerance and no rounding slack. Every other field below does NOT sum.
///
/// **One precondition, and it is not theoretical: no adapter may have been GAS-STARVED in either read.**
/// Some adapters fail open inside their own frame and return SUCCESSFULLY having dropped legs —
/// `AssistedCoordCache._collect` isolates each cached coordinate behind an UNCAPPED
/// `try this.valueCoordSelf(…)`/`catch {}`, and `ERC20DefaultBalanceAdapter` records 0 for an asset whose
/// `balanceOf` staticcall fails. Nothing upstream can see that; see the "Scope, stated plainly" note on
/// `PriceFeedLib._getAdapterPositions`.
///
/// The per-adapter stipend is a share of what the READ still holds at the moment that adapter is reached,
/// and `computeNav` scans the supplied array IN ORDER. So the stipend depends on **slice composition AND
/// ORDERING**, not merely on how few adapters a slice names. Both directions are reachable:
/// a singleton slice gives its adapter more gas than the full scan did and may value legs the complete
/// read dropped; a multi-adapter slice that places an adapter BEHIND an expensive one can starve it below
/// what the complete read gave it. The second case is not hypothetical — `getAllAdapters()[0]` is
/// permanently `ERC20DefaultBalanceAdapter` (pushed in `initialize`, unremovable, and swap-and-pop only
/// ever fills a hole at the removed index, which index 0 can never be), so the complete read already
/// hands it the largest stipend any read can and **a slice can only ever give it less.**
///
/// Which read ends up LARGER is a separate question from which one was starved. The sign of the skew is
/// set by the `isDebt` of the dropped legs, not by which read dropped them: a dropped credit leg lowers
/// that read, a dropped debt leg raises it.
///
/// **Therefore: do NOT assume a direction, and do not pick by magnitude either.** "Trust the slice" is
/// wrong, and so is "take the lower" — with today's credit-only absorbers starvation can only LOWER a
/// read, so "take the lower" would select the starved number every time the two disagree. Nor is
/// under-reporting a safe default: a processor pricing shares off a low NAV over-issues to a subscriber.
/// Reconcile before publishing either. If a choice must be automated, key it to the SIGNAL rather than
/// the magnitude — prefer the read that did not raise {AdapterGasExhausted} / {InstanceGasExhausted}, and
/// publish neither if the two disagree while neither raised one. And do not treat the two reads agreeing
/// as a health check that passes silently — they agree when nothing was starved, which is the common case
/// and therefore uninformative.
///
/// The property that would keep a starved read from OVER-reporting is: **no adapter emits an
/// `isDebt == true` leg from behind ANY fail-open read.** "Any" is load-bearing — a gas CAP makes this
/// worse, not better, because an uncapped read can at least be rescued by supplying more gas whereas a
/// capped one (`StaticCallLib.PROBE_GAS`) is starved by the cap and drops unconditionally.
/// **Three shipped adapters currently break it** — `EulerVaultsMetaBalanceAdapter._safeDebt` (capped
/// probe, supply leg survives), `FluidVaultLib.aggregate` (uncapped, drops one NFT's supply and borrow),
/// and `GearboxV3CreditAccountsMetaBalanceAdapter._appendBorrow` (narrowly mitigated by a
/// `_debtReportable` gate evaluated before the gas is drained). None is introduced or fixed here, and the
/// first two over-report the COMPLETE read as much as a slice. See `docs/howto/read-nav-in-slices.md`.
/// @param quoteAsset Quote currency; `address(0)` denotes USD. Identical in every slice (it is the caller's
/// argument), so a reassembler can assert it rather than combine it.
/// @param timestamp Block timestamp of THIS call. A reassembler MUST check that every slice carries the same
/// value: differing timestamps mean the slices were read at different blocks, and a NAV assembled from
/// positions priced at different blocks is not a NAV of anything. See the caller contract on
/// {getAccountNavForAdapters}.
/// @param stalePriceAssets Assets whose prices were stale, **restricted to the assets this slice's positions
/// touched**. NOT a portfolio-wide list: an asset that is stale but only held through an adapter in
/// another slice is absent here and present there. Must be UNIONED across slices, and the union
/// de-duplicated — two slices holding the same stale asset each report it.
/// @param sequencerDown True if the L2 sequencer was down or in grace period (L2 only). Derived from this
/// contract's sequencer config, not from the slice, so it is the same in every slice — but it is still
/// per-slice data and a caller that reads it on only one slice is relying on that invariant rather than
/// checking it. OR it across slices.
/// @param quoteAssetStale True if the quote asset's own price feed was stale, in which case `value` is in USD
/// (8dp) despite `quoteAsset` being non-zero. Also invariant across slices (it depends on the quote
/// asset, not the adapters) — which makes it *more* dangerous to ignore, not less: if it is true, every
/// slice's `value` is in USD, and a reassembler that never looked will label a USD total with the
/// requested quote currency. OR it across slices.
/// @param irregularPriceAssets Assets whose primary price diverged from their monitor feeds beyond tolerance
/// (or, for stablecoins, from the $1 peg), **restricted to the assets this slice touched**. Same
/// per-slice restriction and same union-and-dedupe requirement as `stalePriceAssets`. This is the depeg
/// signal; a slice-local read of it is a slice-local depeg picture.
/// @param quoteAssetIrregular True if the quote asset's own primary diverged from its monitors. Invariant
/// across slices, always false for a USD quote. OR it across slices.
/// @param monitorsUnhealthyPriceAssets Assets with monitors configured but none readable at query time,
/// **restricted to the assets this slice touched**. Same per-slice restriction and same
/// union-and-dedupe requirement as `stalePriceAssets` and `irregularPriceAssets` — it is built from the
/// same per-asset cache, so the semantics carry over unchanged. Reported on the paginated read
/// deliberately: a caller paginates because the complete read does not fit one `eth_call`, i.e. for the
/// largest accounts, and those are exactly the ones a monitoring consumer watches — omitting it here
/// would hide the signal from the accounts that most need it. A slice-local read is a slice-local
/// picture of monitor health, and a union over every slice is required before concluding an asset is
/// covered. See {NAV.monitorsUnhealthyPriceAssets} for what the condition does and does not mean.
/// @param adaptersCovered The adapters this slice actually queried — element-for-element identical to the
/// `adapters` argument, order included, because the call reverts rather than silently dropping, adding
/// or reordering one. That makes it a machine-checkable record rather than a restatement of the input:
/// the guarantee is that nothing came between the request and the scan. Its purpose is reassembly
/// verification: concatenate it
/// across every slice and compare against `getAllAdapters()`. A missing address means the assembled NAV
/// is short by that adapter's positions; a repeated one means it is double-counted. Neither is
/// detectable from `value` alone, because a short NAV is a perfectly plausible number.
// forge-lint: disable-next-line(pascal-case-struct)
struct PartialNAV {
int256 value;
Asset quoteAsset;
uint64 timestamp;
Asset[] stalePriceAssets;
bool sequencerDown;
bool quoteAssetStale;
Asset[] irregularPriceAssets;
bool quoteAssetIrregular;
// Appended after the {NAV}-mirroring prefix — see the struct-evolution note above. No longer the LAST
// member: `monitorsUnhealthyPriceAssets` was appended after it, deliberately, so this field keeps its ABI
// offset. New members go after that one, not here.
address[] adaptersCovered;
// Appended after `adaptersCovered` rather than beside its {NAV} siblings: keeping `adaptersCovered` at its
// existing offset matters more than keeping this struct's prefix a positional mirror of {NAV}, which it stops
// being the moment {NAV} grows. The two structs stay deliberately DISTINCT types — a partial result must not
// be decodable where a complete one is expected — so mirroring is a convenience, never a guarantee.
Asset[] monitorsUnhealthyPriceAssets;
}
/// @notice Price data for the freshest non-stale feed selected for an asset.
/// @dev When multiple feeds are registered, these fields describe the winning (freshest) feed.
/// When all feeds are stale, fields describe the first registered feed and stale == true.
/// @param priceFeed Address of the selected price feed contract.
/// @param priceType Feed type (Chainlink, Custom, Redstone, or API3).
/// @param price Current price (e.g. USD per unit); 0 when stale.
/// @param decimals Decimals of the selected feed's output.
/// @param chainlinkHeartbeat Staleness window (seconds) of the reported feed. For Chainlink/Redstone/API3 this is
/// the selected feed's configured heartbeat. For Custom feeds it is the GOVERNING leg's heartbeat — the
/// underlying Chainlink leg closest to its own staleness limit — paired with `updatedAt` below. A Custom
/// feed that successfully reports no trackable Chainlink leg gives 0; if its freshness read REVERTS this
/// field retains the registered config heartbeat (only `updatedAt` falls back to 0), so a non-zero value
/// here does not by itself imply a successful read. See ICustomPriceFeed.governingFeedFreshness.
/// @param updatedAt Last-update timestamp of the reported feed. For Chainlink/Redstone/API3 this is the selected
/// feed's `latestRoundData().updatedAt`. For Custom feeds it is the GOVERNING leg's `updatedAt` — a real,
/// matched pair with `chainlinkHeartbeat` above. 0 when the feed has no push timestamp or the read reverts.
/// @dev ADVISORY PAIR — `updatedAt`/`chainlinkHeartbeat` describe only the reported oracle leg's push freshness.
/// `stale` (and `sequencerDown`) is the AUTHORITATIVE staleness verdict: it also folds in the rate answer's
/// validity, the L2 sequencer state, and the feed's own configured heartbeat gate — none of which the pair
/// can express, so the pair can read "fresh" (age < heartbeat) while `stale` is true. Consumers MUST gate on
/// `stale`; never recompute a fresh/stale decision from `(updatedAt, chainlinkHeartbeat)` alone.
/// @param stale True if all feeds are stale or the L2 sequencer is down.
/// @param sequencerDown True if L2 sequencer is down (L2 only).
/// @param healthyFeedCount Number of registered feeds that passed all staleness gates on this read.
/// A value below the total registered feed count signals partial redundancy collapse and
/// should trigger off-chain alerting.
/// @param irregular True if the primary price diverged from the worst-case (furthest) healthy monitor feed
/// beyond the configured divergence tolerance, or (stablecoins) from the $1 peg beyond the peg tolerance.
/// @param divergenceBps Worst-case basis-point gap between the primary price and any single healthy monitor
/// price (0 when there are no healthy monitors or the primary is stale).
/// @param monitorFeedCount Number of healthy monitor feeds that contributed to the divergence computation.
struct PriceFeedData {
address priceFeed;
IPrices.PriceType priceType;
int256 price;
uint8 decimals;
uint256 chainlinkHeartbeat;
uint256 updatedAt;
bool stale;
bool sequencerDown;
uint256 healthyFeedCount;
bool irregular;
uint256 divergenceBps;
uint256 monitorFeedCount;
}
//
// Events
//
/// @notice Emitted when the Chainlink L2 sequencer uptime feed is updated.
/// @param oldChainlinkUptimeFeed Previous uptime feed address.
/// @param newChainlinkUptimeFeed New uptime feed address.
event ChainlinkUptimeFeedUpdated(address indexed oldChainlinkUptimeFeed, address indexed newChainlinkUptimeFeed);
/// @notice Emitted when the L2 sequencer grace period is updated.
/// @param oldSequencerGracePeriod Previous grace period in seconds.
/// @param newSequencerGracePeriod New grace period in seconds.
event L2SequencerGracePeriodUpdated(uint256 oldSequencerGracePeriod, uint256 newSequencerGracePeriod);
/// @notice Emitted when an asset is registered.
/// @param asset Registered asset address.
/// @param decimals Asset decimals.
event AssetRegistered(address indexed asset, uint8 decimals);
/// @notice Emitted when an asset is unregistered.
/// @param asset Unregistered asset address.
event AssetUnregistered(address indexed asset);
//
// Errors
//
/// @notice Thrown when the L2 sequencer uptime feed is not set but the grace period is being updated.
error UptimeFeedNotSet();
//
// Mutating functions (require MANAGER role)
//
/// @notice Registers an asset and sets its price feed.
/// @dev Fetches decimals/symbol from ERC20 or uses native token symbol. Adds asset to default adapter inclusion list.
/// @param asset Asset address to register (cannot be zero).
/// @param priceFeed Price feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero for all types).
function registerAsset(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
external;
/// @notice Adds an additional price feed for an already registered asset.
/// @dev Reverts with PriceFeedAlreadyRegistered if the feed address is already registered for this asset.
/// @param asset Registered asset address.
/// @param priceFeed Price feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero for all types).
function addPriceFeed(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
external;
/// @notice Adds a monitor (divergence-only) feed for an asset. Monitor feeds NEVER price the NAV; they are read
/// only to detect divergence between the primary price and the worst-case (furthest) healthy monitor price.
/// @dev Requires the asset's divergence tolerance to be set first (>0), else reverts DivergenceToleranceRequired.
/// Monitor feeds must report NAV_DECIMALS decimals (else MonitorFeedDecimalsMismatch). Reverts
/// MonitorFeedAlreadyRegistered on a duplicate.
/// @param asset Registered asset address.
/// @param priceFeed Monitor feed address (cannot be zero).
/// @param priceType Chainlink, Custom, Redstone, or API3.
/// @param chainlinkHeartbeat Staleness window in seconds (must be non-zero).
function addMonitorFeed(address asset, address priceFeed, IPrices.PriceType priceType, uint256 chainlinkHeartbeat)
external;
/// @notice Sets the asset's divergence tolerance in basis points (must be in (0, 10000]).
/// @param asset Registered asset address.
/// @param divergenceToleranceBps Max worst-case primary-vs-any-single-monitor gap before the asset is flagged irregular.
function setDivergenceTolerance(address asset, uint32 divergenceToleranceBps) external;
/// @notice Sets the asset's stablecoin peg tolerance in basis points (in [0, 10000]; 0 disables the peg guard).
/// @param asset Registered asset address.
/// @param pegToleranceBps Max deviation of the primary price from $1 before the asset is flagged irregular.
function setPegTolerance(address asset, uint32 pegToleranceBps) external;
/// @notice Registers one or more **non-meta** balance adapters in the global registry in a single call.
/// @dev Reverts with InvalidArguments if the list is empty or contains a zero address, DuplicateBalanceAdapter
/// if any adapter is already registered, InvalidBalanceAdapter if any adapter does not implement
/// IBalanceAdapter, and MetaAdapterNotAllowed if any adapter implements IMetaBalanceAdapter (meta-adapters
/// must use addMetaBalanceAdapter). The batch is all-or-nothing.
/// @param adapters Adapter addresses (each must implement IBalanceAdapter and NOT IMetaBalanceAdapter).
function addBalanceAdapters(address[] calldata adapters) external;
/// @notice Registers a meta-adapter (ADR 0010) and seeds its instance set atomically, in one MANAGER call.
/// @dev The adapter must implement both IBalanceAdapter and IMetaBalanceAdapter (else InvalidBalanceAdapter /
/// NotMetaAdapter). Reverts InvalidArguments on a zero adapter, DuplicateBalanceAdapter if already
/// registered, and DuplicateMetaInstance on a repeated coordinate. An empty instance list is allowed
/// (registers the meta-adapter with no instances yet; seed later via addMetaInstances). Plain adapters use
/// addBalanceAdapters; subsequent instance changes use addMetaInstances / removeMetaInstances.
/// @param adapter The meta-adapter address.
/// @param instances Instance coordinates to seed (e.g. vault addresses widened to bytes32, or raw bytes32 IDs).
function addMetaBalanceAdapter(address adapter, bytes32[] calldata instances) external;
/// @notice Removes the price feed at the given index. Reverts if it is the last feed (CannotRemoveLastFeed).
/// @param asset Registered asset address.
/// @param index Index into the asset's feed array.
function removePriceFeedAt(address asset, uint256 index) external;
/// @notice Removes the price feed with the given address. Reverts if not found or last feed.
/// @param asset Registered asset address.
/// @param priceFeed Feed address to remove.
function removePriceFeed(address asset, address priceFeed) external;
/// @notice Removes the monitor feed at the given index. Monitor feeds are optional, so the last one may be removed.
/// @param asset Registered asset address.
/// @param index Index into the asset's monitor feed array.
function removeMonitorFeedAt(address asset, uint256 index) external;
/// @notice Removes the monitor feed with the given address. Reverts MonitorFeedNotFound if absent.
/// @param asset Registered asset address.
/// @param priceFeed Monitor feed address to remove.
function removeMonitorFeed(address asset, address priceFeed) external;
/// @notice Removes one or more balance adapters from the global registry in a single call.
/// @dev Reverts with InvalidArguments if the list is empty. The batch is all-or-nothing — if any adapter is
/// not registered (or is the default ERC20 adapter) the whole call reverts.
/// @param adapters Adapter addresses to remove (none may be the default ERC20 adapter).
function removeBalanceAdapters(address[] calldata adapters) external;
/// @notice Adds instance coordinates to a registered meta-adapter's queried set.
/// @dev This is the governed "which instances to query" registry — adapters themselves stay immutable.
/// All-or-nothing: reverts DuplicateMetaInstance if any coordinate is already present or repeated within
/// the batch (a duplicate would double-count NAV), InvalidArguments on an empty list, InvalidBalanceAdapter
/// if the adapter is not registered, and NotMetaAdapter if the adapter does not implement
/// IMetaBalanceAdapter. Coordinate values are otherwise not validated; a
/// malformed/unknown coordinate is isolated per-instance by the adapter's fan-out (cannot zero the batch).
/// @param adapter Registered meta-adapter address.
/// @param instances Instance coordinates to add (e.g. vault addresses widened to bytes32).
function addMetaInstances(address adapter, bytes32[] calldata instances) external;
/// @notice Removes instance coordinates from a registered meta-adapter's queried set.
/// @dev All-or-nothing: reverts MetaInstanceNotFound if any coordinate is not present (a coordinate repeated
/// within the batch also reverts), InvalidArguments on an empty list, InvalidBalanceAdapter if the adapter
/// is not registered, and NotMetaAdapter if the adapter does not implement IMetaBalanceAdapter. Order is
/// not preserved.
/// @param adapter Registered meta-adapter address.
/// @param instances Instance coordinates to remove.
function removeMetaInstances(address adapter, bytes32[] calldata instances) external;
/// @notice Excludes an asset from the default adapter so wallet balances are not reported for it.
/// @param asset Registered asset address.
function excludeAssetFromDefaultAdapter(address asset) external;
/// @notice Includes an asset in the default adapter so wallet balances are reported again.
/// @param asset Registered asset address.
function includeAssetInDefaultAdapter(address asset) external;
/// @notice Unregisters an asset: unsets price feed, removes from default adapter list, and removes from registry.
/// @param underlyingAsset Asset address to unregister.
function unregisterAsset(address underlyingAsset) external;
/// @notice Sets the Chainlink L2 sequencer uptime feed (use address(0) on L1).
/// @dev Requires DEFAULT_ADMIN_ROLE (same privilege level as upgrades). Disabling sequencer-uptime
/// detection on an L2 is equivalent in impact to an upgrade, so MANAGER access is not sufficient.
/// @param newChainlinkL2UptimeFeed New uptime feed address.
function setChainlinkL2SequencerUptimeFeed(address newChainlinkL2UptimeFeed) external;
/// @notice Sets the L2 sequencer grace period. Reverts UptimeFeedNotSet if the uptime feed is not set, or
/// InvalidArguments if the period is below 1 hour.
/// @param newSequencerGracePeriod Grace period in seconds (must be at least 1 hour).
function setChainlinkL2SequencerGracePeriod(uint256 newSequencerGracePeriod) external;
//
// View functions — registry
//
/// @notice Returns the number of registered assets (alias for getAssetCount).
/// @return Number of registered assets.
function assetCount() external view returns (uint256);
/// @notice Returns whether an asset is registered.
/// @param asset Asset address to check.
/// @return True if registered.
function isAssetRegistered(address asset) external view returns (bool);
/// @notice Returns all registered assets with metadata.
/// @dev **O(N), and it is the wrong tool for resolving ONE asset** — use {getRegisteredAsset} for that. This
/// copies the entire registry across the ABI boundary, so a caller that resolves M tokens by calling this
/// M times pays M full fetches. That pattern measured **6,274,562 gas for a single 50-token Balancer
/// instance at 43 registered assets** (18.4M at 100), and it is super-linear rather than linear because
/// each call allocates a fresh N-element array that is never freed, so memory expansion grows with the
/// square of the token count. At that scale it exhausts the per-adapter gas stipend and turns a NAV read
/// into a REVERT.
/// @return assets Array of Asset (address, symbol, decimals).
function getRegisteredAssets() external view returns (Asset[] memory assets);
/// @notice Resolves ONE asset's registry metadata in O(1), without reverting when it is absent.
/// @dev The single-asset counterpart to {getRegisteredAssets}, added because balance adapters resolve tokens
/// one at a time and the array getter makes that quadratic (see its docs for the measured figures).
/// Backed by the 1-based `_assetIndex` map the registry already maintains on register/unregister, so this
/// is a mapping load plus one array read — flat in the number of registered assets.
///
/// **Non-reverting by design, and that is the whole reason this is a new function rather than a widened
/// visibility on the existing internal lookup.** NAVCalculator's `_getRegisteredAsset` reverts
/// `AssetNotFound` for an unregistered asset, which is right for its callers but wrong here: "not
/// registered" is an ORDINARY, expected outcome on an adapter's emission path — the adapter simply skips
/// that leg. A reverting getter would turn every unregistered token an adapter happens to encounter into
/// a failed instance read, converting a skipped leg into a dropped position.
/// @param asset The asset to resolve.
/// @return assetInfo The registry entry. Zeroed (`address(0)`, `""`, `0`) when `found` is false — **check
/// `found`, do not infer absence from a zero `assetInfo.asset`**, since the two are only equivalent
/// while nothing zero-addressed can be registered.
/// @return found True if `asset` is registered.
function getRegisteredAsset(address asset) external view returns (Asset memory assetInfo, bool found);
/// @notice Returns the number of registered assets.
/// @return Number of registered assets.
function getAssetCount() external view returns (uint256);
/// @notice Returns the current implementation version (Initializable storage).
/// @return Version number.
function version() external view returns (uint64);
//
// View functions — NAV and positions
//
/// @notice Computes NAV for an account in the given quote currency.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD. Must have a price feed if not zero.
/// @return nav NAV struct (value, quoteAsset, timestamp, stalePriceAssets, sequencerDown, quoteAssetStale).
function getAccountNav(address account, address quoteAsset) external view returns (NAV memory nav);
/// @notice Computes the NAV contribution of a CALLER-SUPPLIED SET of balance adapters, so an off-chain caller
/// can read a portfolio's NAV in slices and reassemble it.
/// @dev Exists because {getAccountNav} scans every registered adapter in one `eth_call` and that cost grows
/// with the asset registry and the adapter set. Past a node's `eth_call` gas cap the complete read stops
/// returning anything at all — not a degraded NAV, no NAV — and there is no smaller question to ask.
/// This is that smaller question.
///
/// **A SET, NOT AN INDEX RANGE, AND THAT IS NOT A STYLE CHOICE.** `getAllAdapters()` is maintained with
/// swap-and-pop, so removing any adapter moves the LAST adapter into the removed one's index — always to a
/// LOWER index. A caller paging `[0,10)` then `[10,20)` across a governance removal therefore **silently
/// SKIPS** the moved adapter: it was at the tail, it lands in a slot the caller has already passed, and it
/// is never read. Both pages still look completely well-formed and the total is short by that adapter's
/// positions.
///
/// Precisely because elements only ever move DOWN, a removal cannot make an already-read adapter reappear
/// in a later page — so the hazard is a missed adapter, not a double-counted one. (An earlier version of
/// this note claimed a double-read; that is not reachable through either removal path.) Naming the adapters
/// removes the whole class rather than documenting it away.
///
/// ### The caller contract
///
/// **Canonical statement: `docs/howto/read-nav-in-slices.md`.** That document is the single source for the
/// reassembly rules, including the worked example and the gas-starvation precondition. What follows is the
/// short form, kept here because a consumer generating against this ABI may never open the repo — if the
/// two ever disagree, the how-to wins and this block is the bug.
///
/// Four obligations. The first two this function enforces; the last two it cannot see, and they are
/// where a reassembled NAV goes wrong.
///
/// 1. **Every adapter must be registered and appear at most once** — else {AdapterNotRegistered} or
/// {DuplicateAdapterInSlice}. An empty list reverts {EmptyAdapterSlice}.
/// 2. **The slice is queried as one atomic read**, so `value` is internally consistent.
/// 3. **All slices MUST be read at the same block, and PINNING THE BLOCK NUMBER IN THE REQUEST is the only
/// real control.** Pass an explicit block number to every `eth_call` — not `latest`, which lets
/// successive calls land on different heads. Positions and prices both move between blocks, so slices
/// from different blocks sum to a number that was never any account's NAV, and the sum looks entirely
/// reasonable.
///
/// `PartialNAV.timestamp` is a **cross-check, not the check**, and it is deliberately described that way
/// here: equal timestamps do NOT imply the same block. Arbitrum Nitro mints blocks roughly every 250ms,
/// so consecutive blocks routinely share a `block.timestamp`, and this contract is deployed there. The
/// field therefore catches only the gross case (slices seconds apart) and is blind to the narrow one
/// (two blocks inside one second) — which is the case an unpinned paging loop actually produces. There
/// is no block number in `PartialNAV` to check instead, by choice: adding one would not fix an unpinned
/// caller, and pinning the request already does.
/// 4. **The union of the slices must cover `getAllAdapters()` exactly once**, and
/// `PartialNAV.adaptersCovered` is how that is verified: concatenate it across slices and compare
/// against `getAllAdapters()` read at the same block. A missing adapter yields a NAV short by its
/// positions; a repeated one double-counts. Re-read `getAllAdapters()` at the pinned block rather than
/// trusting a cached list — the registry is governed and can change under a paging loop.
///
/// ### **Health flags do NOT sum. Ignoring them on ANY slice silently destroys a signal.**
///
/// `value` is the only field that composes by addition. **`stalePriceAssets`, `irregularPriceAssets` and
/// `monitorsUnhealthyPriceAssets` are restricted to the assets THIS slice's positions touched, and
/// `sequencerDown`, `quoteAssetStale` and `quoteAssetIrregular` are reported per slice. A caller that checks the flags on one slice, or on
/// the last slice, or on a slice it happened to keep, silently loses every staleness, depeg and
/// sequencer-down signal carried by the others — and gets a NAV number that looks fine.** That failure
/// shape is exactly what this repo's fail-open hardening work was for; it must not be reintroduced at the
/// reassembly boundary. **UNION the THREE asset arrays (de-duplicating: two slices holding the same stale
/// asset each report it) and OR the three booleans, across every slice, before treating the summed
/// `value` as usable.** The third array, `monitorsUnhealthyPriceAssets`, was appended later than this
/// instruction was first written — a reassembler that unions only two silently drops the monitor-health
/// signal, which is the falsely-reassuring direction and hits precisely the large accounts that must
/// paginate.
///
/// ### A meta-adapter is the atomic unit
///
/// A slice naming a meta-adapter includes **all** of that adapter's governed instances — every Aave V3
/// instance, every Morpho market, every Curve pool. There is no way to page WITHIN one meta-adapter
/// through this API, by design: the governed instance set is itself swap-and-pop mutable
/// (`addMetaInstances`/`removeMetaInstances`), so an instance-level range would carry the same
/// reordering hazard this signature exists to avoid, and an instance-level set would need the adapter to
/// accept a filter it does not have. So the finest slice available is one adapter. If a SINGLE
/// meta-adapter's read alone exceeds the gas budget, pagination does not help and the problem is that
/// adapter's per-instance cost, not the number of adapters — a different problem with a different fix.
///
/// ### What this does NOT do
///
/// Pagination reduces the gas of one call. It does not reduce the total gas of reading the whole NAV
/// (it slightly increases it — per-call overhead is paid per slice) and it does nothing whatsoever for an
/// ON-CHAIN consumer that must read a NAV inside a transaction: that consumer needs one complete answer
/// in one frame and cannot reassemble across calls. For those callers the only fixes are reducing the
/// cost of the read itself or shrinking the registry. This API is for off-chain readers.
///
/// One thing it does help, but read the caveat before relying on it: the per-adapter gas stipend is a
/// share of what the READ still holds, so an adapter starved into {AdapterGasExhausted} inside the
/// complete scan may have ample budget when asked for on its own. A slice can therefore get an answer out
/// of a portfolio whose complete read has started reverting.
///
/// **The caveat: a slice can also convert that loud revert into a silent omission.** Exhaustion is
/// classified by `GasStipendLib.exhausted` as `consumed >= stipend - stipend/8` — measured against a
/// stipend that is itself a share of the CALLER's budget. An adapter that fails at a roughly fixed cost
/// `G` for a non-gas reason is scored "exhausted" (loud {AdapterGasExhausted}) when the full scan's
/// stipend is small enough that `G` clears that bar, and scored "benign revert" — fail open, legs dropped,
/// nothing flagged — when the slice's larger stipend puts `G` below it. `adaptersCovered` still lists the
/// adapter, so the documented coverage check reports full coverage. If a dropped leg is a DEBT leg the
/// reassembled NAV over-reports.
///
/// So: a slice that succeeds where the complete read reverted is **evidence about gas, not a repaired
/// answer.** Do not silently promote it to the authoritative NAV.
///
/// And note what "just give the complete read more gas and compare" does NOT achieve: raising the budget
/// raises the stipend, which puts a fixed-cost failure below the same 7/8 bar for the COMPLETE read too.
/// Both reads then fail open on the identical adapter and AGREE on the identical wrong number. The signal
/// is the {AdapterGasExhausted} disappearing, not the two figures converging.
///
/// No verbose (labelled) counterpart exists yet. The label paths carry the heavier gas pressure and their
/// bounds are being re-derived; a paginated read built against numbers about to change would be wasted.
/// @param account Account address.
/// @param quoteAsset Quote currency; `address(0)` for USD. Must have a price feed if non-zero. Pass the SAME
/// value to every slice — the per-slice `value`s are otherwise denominated differently and summing them
/// is meaningless.
/// @param adapters The balance adapters to include. Each must be currently registered (in `getAllAdapters()`)
/// and may appear only once. Must be non-empty.
/// @return partialNav The slice's NAV contribution plus `adaptersCovered`. See {PartialNAV} — in particular,
/// `value` sums and nothing else does.
function getAccountNavForAdapters(address account, address quoteAsset, address[] calldata adapters)
external
view
returns (PartialNAV memory partialNav);
/// @notice Returns all positions for an account with pricing in the quote currency.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return positions Array of enriched Position structs.
function getAccountPositions(address account, address quoteAsset)
external
view
returns (Position[] memory positions);
/// @notice Returns positions for an account filtered by a single asset.
/// @dev **This is a filtered VIEW, not a net position. Do not sum it.** You asked for asset `X`, so you get
/// the legs denominated in `X` — a projection of the portfolio onto one asset, deliberately. Summing
/// `value` across the result (or netting credit against debt within it) produces a number that is not
/// this account's exposure to anything: the legs that offset these — collateral in another asset
/// backing a debt in `X`, or the reverse — are outside the filter by construction and are simply
/// absent, not netted. A vault borrowing `X` against `Y` shows here as debt in `X` with no sign of the
/// `Y` that secures it.
///
/// This is a documentation contract, not a defect, and the design is what makes it safe: **no NAV
/// number in this interface is ever computed with an asset filter.** {getAccountNav},
/// {getAccountNavForAdapters} and {getAccountNavVerbose} take no `asset` parameter at all, and the only
/// entry points that pass a non-zero filter into the position engine are this function and
/// {getAccountPositionsForAssetVerbose} — both of which return `Position[]`, never a `NAV`. So the
/// hazard lives entirely in what a CALLER does with the array, which is why it is stated here.
///
/// For a net figure, use {getAccountNav} (whole portfolio) or {getAccountNavForAdapters} (a validated
/// adapter slice, which partitions rather than projects and whose slices therefore do sum).
/// @param account Account address.
/// @param asset Asset to filter by (must be registered).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return positions Array of enriched Position structs for the asset. A filtered view — see the note above.
function getAccountPositionsForAsset(address account, address asset, address quoteAsset)
external
view
returns (Position[] memory positions);
/// @notice Returns all positions for `account` with human-readable labels.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return Array of VerbosePosition structs (enriched Position plus protocolName and display labels).
function getAccountPositionsVerbose(address account, address quoteAsset)
external
view
returns (VerbosePosition[] memory);
/// @notice Returns positions filtered by a single asset, with human-readable labels.
/// @dev **This is a filtered VIEW, not a net position. Do not sum it.** Identical projection semantics to
/// {getAccountPositionsForAsset} — this is that function's result passed through label enrichment, from
/// the same `_computePositions` call with the same filter — so the whole note there applies verbatim,
/// including the reason it is safe: no NAV in this interface is computed with an asset filter. See
/// {getAccountPositionsForAsset}.
/// @param account Account address.
/// @param asset Asset to filter by (must be registered).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return Array of VerbosePosition structs for the asset (enriched Position plus protocolName and display
/// labels). A filtered view — see the note above.
function getAccountPositionsForAssetVerbose(address account, address asset, address quoteAsset)
external
view
returns (VerbosePosition[] memory);
/// @notice Returns the aggregate NAV and full verbose position breakdown in one call.
/// @param account Account address.
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return verboseNav VerboseNAV struct bundling the NAV snapshot with the verbose position list.
function getAccountNavVerbose(address account, address quoteAsset)
external
view
returns (VerboseNAV memory verboseNav);
/// @notice Returns the number of decimals used for USD values (e.g. 8).
/// @return USD decimals.
function usdDecimals() external view returns (uint8);
/// @notice Returns detailed price feed data for an asset (primary feed + divergence signal vs its monitors).
/// @param underlyingAsset Registered asset address.
/// @return priceFeedData PriceFeedData struct (feed, type, price, decimals, heartbeat, updatedAt, stale,
/// sequencerDown, healthyFeedCount, irregular, divergenceBps, monitorFeedCount).
function getPriceData(address underlyingAsset) external view returns (PriceFeedData memory priceFeedData);
/// @notice Same as {getPriceData} but WITHOUT the monitor-divergence computation (irregular/divergenceBps/
/// monitorFeedCount stay 0/false). For hot callers that only need price/staleness (e.g. custom feeds
/// reading the NAV-sourced base/USD term) so a base asset's monitor reads + sort aren't repaid per call.
/// @param underlyingAsset Registered asset address.
/// @return priceFeedData PriceFeedData struct with the divergence fields left at their defaults.
function getPriceDataNoDivergence(address underlyingAsset)
external
view
returns (PriceFeedData memory priceFeedData);
/// @notice Returns the divergence between an asset's primary price and its monitor feeds.
/// @param underlyingAsset Registered asset address.
/// @return primaryPrice The primary feed's price, normalized to NAV_DECIMALS (0 if the primary is stale).
/// @return monitorMedian The median of the healthy monitor prices, NAV_DECIMALS (0 if no healthy monitors).
/// @return divergenceBps Worst-case basis-point gap between the primary and any single healthy monitor — the
/// value `irregular` is thresholded on (0 if no monitors / primary stale).
/// @return irregular True if divergenceBps exceeds the divergence tolerance, or (stablecoins) the primary
/// deviates from $1 beyond the peg tolerance.
/// @return monitorFeedCount Number of healthy monitor feeds that contributed.
/// @return primaryStale True if the primary feed is stale (divergence undefined).
/// @return primaryAboveMonitors True if the primary sits above the monitor median (a premium); false if
/// below/equal — for a claim asset, below is the depeg direction. Meaningful only when
/// monitorFeedCount > 0.
function getPriceDivergence(address underlyingAsset)
external
view
returns (
int256 primaryPrice,
int256 monitorMedian,
uint256 divergenceBps,
bool irregular,
uint256 monitorFeedCount,
bool primaryStale,
bool primaryAboveMonitors
);
/// @notice Returns health status: sequencer down flag and lists of stale-price and irregular-price assets.
/// @return sequencerDown True if L2 sequencer is down or in grace period (false on L1).
/// @return stalePriceAssets Addresses of assets with stale prices.
/// @return irregularPriceAssets Addresses of assets flagged irregular (primary diverged from monitors / peg).
function healthCheck()
external
view
returns (bool sequencerDown, address[] memory stalePriceAssets, address[] memory irregularPriceAssets);
/// @notice Returns whether the account has any non-zero balance across adapters and registered assets.
/// @param account Account address.
/// @return has True if at least one position has non-zero amount.
function hasPositions(address account) external view returns (bool has);
/// @notice Returns the list of assets for which the account has at least one non-zero position.
/// @param account Account address.
/// @return assets Array of asset addresses.
function getAssetsWithPositions(address account) external view returns (address[] memory assets);
/// @notice Converts a list of (asset, amount) pairs into a total value in the quote currency.
/// @dev Only positive amounts; zero amounts are skipped. All assets must be registered with a price feed.
/// @param assets Asset addresses.
/// @param amounts Corresponding amounts (same length as assets).
/// @param quoteAsset Quote currency; address(0) for USD.
/// @return value Sum of values in quote asset (non-negative for valid inputs). When `quoteAssetStale` is
/// true, this is denominated in USD (8dp) instead of the requested quote ([9]/S2).
/// @return quoteAssetStale True if the requested non-USD quote asset's own feed was stale, so `value` fell
/// back to USD rather than the quote currency. Always false for a USD quote (address(0)).
function calculateValue(address[] memory assets, uint256[] memory amounts, address quoteAsset)
external
view
returns (int256 value, bool quoteAssetStale);
/// @notice Every listed adapter's EFFECTIVE display name and positionId-independent breadcrumb — the same values
/// the verbose position reads report, including any {AssetKindRegistry} override.
/// @dev Declared here, not only on the concrete contract, so INTERFACE-TYPED consumers can reach it. That is the
/// caller that matters: a consumer holding `INAVCalculator` is exactly the one that would otherwise
/// enumerate `getAllAdapters()` and staticcall `protocolName()` on each adapter itself, which is the
/// surface split this function exists to close. Leaving it off the interface would have left that consumer
/// with no way to reach the fix.
/// @param adapters The adapters to describe, typically the result of `getAllAdapters()`.
/// @return names Each adapter's effective protocol name.
/// @return labels Each adapter's effective breadcrumb, with any {AssetKindRegistry} per-segment override applied.
/// Empty when the adapter derives it per position AND no override is set. When the adapter answers
/// nothing but an override IS set, this path deliberately GROWS the breadcrumb to the override's leading
/// non-empty prefix — so it can be MULTI-segment, not merely a lone category. (It was a lone category
/// under the retired scalar `setAdapterLabelCategory`; do not code against that.) When the adapter DOES
/// answer, the override is overlaid segment-by-segment and can neither lengthen nor truncate the reply.
/// See `PriceFeedLib.adapterDisplayInfo` for why the empty case diverges from the position path.
function getAdapterDisplayInfo(address[] calldata adapters)
external
view
returns (string[] memory names, string[][] memory labels);
}
src/prices/IPrices.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title IPrices Interface
/// @notice Interface for managing price feeds for different tokens.
/// @author KPK
interface IPrices {
/// @notice Enum representing the type of price feed.
enum PriceType {
Chainlink, // 0 — Chainlink AggregatorV3Interface (on-chain push)
Redstone, // 1 — Redstone Classic Push (AggregatorV3-compatible, same read path as Chainlink)
API3, // 2 — API3 dAPI via Api3ReaderProxyV1 (AggregatorV3-compatible, 18-dec proxy scaled to 8-dec at read)
Custom // 3 — custom ICustomPriceFeed adapter (internal staleness logic)
}
/// @notice Per-asset pricing metadata governing divergence detection between the primary feed and its
/// monitor feeds. Packs into a single storage slot (uint32 + uint32 = 8 bytes).
/// @param divergenceToleranceBps Max allowed basis-point gap between the primary price and the worst-case
/// (furthest) healthy monitor price before the asset is flagged `irregular`. Must be non-zero when monitors exist.
/// @param pegToleranceBps Absolute peg-deviation guard: max allowed basis-point deviation of the primary price
/// from $1 before the asset is flagged `irregular`. Non-zero enables the guard (set it only on assets whose
/// fundamental value is $1, i.e. stablecoins); zero disables it.
struct AssetPricing {
uint32 divergenceToleranceBps;
uint32 pegToleranceBps;
}
/// @notice Struct representing a price feed configuration.
/// @param priceFeed The address of the price feed contract (e.g. Chainlink aggregator or custom price feed).
/// @param decimals The number of decimal places the price feed uses.
/// @param priceType The type of the price feed.
/// @param chainlinkHeartbeat Staleness window in seconds (non-zero for all types). For Chainlink/Redstone/API3
/// feeds this gates participation: block.timestamp - effectiveUpdatedAt >= chainlinkHeartbeat → skip feed.
/// For Custom feeds the internal stale signal from getLatestPrice() is the primary gate; updatedAt from
/// latestRoundData() then applies the same heartbeat gate (updatedAt==0 is treated as block.timestamp-1
/// so rate-only feeds participate but yield to any feed with a real push timestamp), and among survivors
/// the largest effectiveUpdatedAt wins.
struct PriceFeedConfig {
address priceFeed;
uint8 decimals;
PriceType priceType;
uint256 chainlinkHeartbeat;
}
/// @notice Emitted when a price feed is added for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the price feed.
/// @param chainlinkHeartbeat The heartbeat interval in seconds.
/// @param priceType The type of the price feed.
/// @param index The index of the new feed in the asset's feed array.
event PriceFeedAdded(
address indexed underlyingAsset,
address indexed priceFeed,
uint256 chainlinkHeartbeat,
PriceType priceType,
uint256 index
);
/// @notice Emitted when a single price feed is removed for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the removed feed.
/// @param index The former index of the removed feed.
event PriceFeedRemoved(address indexed underlyingAsset, address indexed priceFeed, uint256 index);
/// @notice Emitted when swap-and-pop relocates the last feed into a vacated slot.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the feed that was moved.
/// @param fromIndex The former index (len-1 before the pop).
/// @param toIndex The new index (the slot vacated by the removed feed).
event PriceFeedIndexChanged(
address indexed underlyingAsset, address indexed priceFeed, uint256 fromIndex, uint256 toIndex
);
/// @notice Emitted when all price feeds are cleared for a token (asset unregistration).
/// @param underlyingAsset The address of the token.
event PriceFeedUnset(address indexed underlyingAsset);
/// @notice Emitted when a monitor (divergence-only) feed is added for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the monitor feed.
/// @param chainlinkHeartbeat The heartbeat interval in seconds.
/// @param priceType The type of the monitor feed.
/// @param index The index of the new monitor feed in the asset's monitor array.
event MonitorFeedAdded(
address indexed underlyingAsset,
address indexed priceFeed,
uint256 chainlinkHeartbeat,
PriceType priceType,
uint256 index
);
/// @notice Emitted when a monitor feed is removed for a token.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the removed monitor feed.
/// @param index The former index of the removed monitor feed.
event MonitorFeedRemoved(address indexed underlyingAsset, address indexed priceFeed, uint256 index);
/// @notice Emitted when swap-and-pop relocates the last monitor feed into a vacated slot.
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the monitor feed that was moved.
/// @param fromIndex The former index (len-1 before the pop).
/// @param toIndex The new index (the slot vacated by the removed monitor feed).
event MonitorFeedIndexChanged(
address indexed underlyingAsset, address indexed priceFeed, uint256 fromIndex, uint256 toIndex
);
/// @notice Emitted when all monitor feeds and pricing metadata are cleared for a token (asset unregistration).
/// @param underlyingAsset The address of the token.
event MonitorFeedsUnset(address indexed underlyingAsset);
/// @notice Emitted when an asset's divergence tolerance is set.
/// @param underlyingAsset The address of the token.
/// @param divergenceToleranceBps The new tolerance in basis points.
event DivergenceToleranceSet(address indexed underlyingAsset, uint32 divergenceToleranceBps);
/// @notice Emitted when an asset's peg tolerance is set (stablecoins).
/// @param underlyingAsset The address of the token.
/// @param pegToleranceBps The new peg tolerance in basis points.
event PegToleranceSet(address indexed underlyingAsset, uint32 pegToleranceBps);
//
// Errors
//
/// @notice Error when the price feed is not set for an asset
/// @param asset The address of the asset
error PriceFeedNotSet(address asset);
/// @notice Error when the price feed is invalid
error InvalidPriceOracle();
/// @notice Error when the price feed type is not valid
error InvalidPriceOracleType();
/// @notice Error when attempting to remove the last remaining feed for an asset
error CannotRemoveLastFeed(address asset);
/// @notice Error when attempting to add a feed that is already registered for an asset
error PriceFeedAlreadyRegistered(address asset, address feed);
/// @notice Error when the feed index is out of bounds
error PriceFeedIndexOutOfBounds(address asset, uint256 index);
/// @notice Error when a feed address is not found in an asset's feed list
error PriceFeedNotFound(address asset, address feed);
/// @notice Error when a new feed's decimals do not match the decimals of existing feeds for the asset
error PriceFeedDecimalsMismatch(address asset, uint8 existingDecimals, uint8 newDecimals);
/// @notice Error when a monitor feed's decimals are not NAV_DECIMALS (monitors must be USD-comparable to the
/// primary, which is always NAV_DECIMALS).
error MonitorFeedDecimalsMismatch(address asset, uint8 expectedDecimals, uint8 actualDecimals);
/// @notice Error when a `Custom` feed is being registered for an asset it does not price — i.e. the feed's own
/// {ICustomPriceFeed-underlyingAssetSupported} does not equal the asset being registered.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
/// @param feedAsset The asset the feed actually prices, per its own `underlyingAssetSupported()`.
error CustomFeedAssetMismatch(address asset, address feed, address feedAsset);
/// @notice Error when a `Custom` feed is being registered for the very asset it reads its own `base/USD` price
/// for — i.e. the feed's {INavSourcedPriceFeed-BASE_ASSET} equals the asset being registered.
/// @dev A NAV-sourced custom feed prices its asset as `rate × base/USD` and reads that `base/USD` back out of
/// THIS NAV (`NavBaseUsdLib` → `getPriceData(BASE_ASSET)`; ADR 0019). If the base IS the asset, pricing the asset
/// re-enters the same feed and recurses until the call stack is exhausted. The read still returns a price — the
/// selector's per-feed `try`/`catch` swallows the depth failure and moves on — so the only symptom is that every
/// read of that asset, and of everything priced from it, burns gas proportional to ~1024 nested `STATICCALL`
/// frames. See the circularity invariant in {NavBaseUsdLib}.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
error CustomFeedBaseCircular(address asset, address feed);
/// @notice Error when a `Custom` feed does not answer {INavSourcedPriceFeed-BASE_ASSET}, so its NAV dependency
/// cannot be established at registration.
/// @dev Unreadable means REJECT, deliberately. The failure being closed is unbounded recursion, so "the base
/// could not be read" must not be allowed to mean "the base is fine". A feed with no NAV dependency states that
/// by answering `address(0)`; a feed that cannot answer at all is one whose base cannot be ruled out.
/// @param asset The asset the feed is being registered for.
/// @param feed The custom feed address.
error CustomFeedBaseUnreadable(address asset, address feed);
/// @notice Error when a monitor feed is already registered for an asset.
error MonitorFeedAlreadyRegistered(address asset, address feed);
/// @notice Error when a monitor feed address is not found in an asset's monitor list.
error MonitorFeedNotFound(address asset, address feed);
/// @notice Error when adding a monitor feed before the asset's divergence tolerance has been set (>0).
error DivergenceToleranceRequired(address asset);
/// @notice Error when a tolerance value is out of range. Divergence tolerance must be in (0, 10000];
/// peg tolerance must be in [0, 10000] (0 is allowed and disables the peg guard).
error InvalidTolerance(uint32 toleranceBps);
/// @notice Returns the latest price for a given token while checking if the price is stale.
/// @dev Reverts PriceFeedNotSet if the asset has no registered feeds. When at least one feed is registered
/// but all are stale, returns price 0 with stale = true rather than reverting.
/// @param underlyingAsset The address of the token.
/// @return price The latest price of the token (int256; positive for all valid prices, 0 when stale).
/// @return decimals The amount of decimal places the price is represented with.
/// @return stale True if all registered feeds are stale, the L2 sequencer is down, or within grace period.
/// @return irregular True if the primary price diverged from its monitor feeds beyond the divergence tolerance,
/// or (stablecoins) from the $1 peg beyond the peg tolerance. A pricing-quality signal, not a validity flag;
/// `price` is still populated. Always false when `stale` (divergence is undefined for an unusable price).
function latestPrice(address underlyingAsset)
external
view
returns (int256 price, uint8 decimals, bool stale, bool irregular);
/// @notice Checks the L2 sequencer uptime feed, returning True when it is signaling staleness (the sequencer
/// is down or still within the grace period). If 'chainlinkL2SequencerUptimeFeed' is the zero address (e.g. on
/// an L1) it returns false.
/// @return stale True if the L2 sequencer is down or if it is within the grace period.
function checkL2SequencerUptime() external view returns (bool stale);
/// @notice Validates that a price feed is suitable for the given type, reverting if it is not. Returns nothing
/// on success. Reverts InvalidPriceOracle when the asset or feed address is zero, the feed fails the
/// ICustomPriceFeed/AggregatorV3 interface check for its type, or (for Chainlink/Redstone/API3) its
/// latestRoundData reports a non-positive answer, a zero updatedAt, or a future timestamp; reverts
/// InvalidPriceOracleType for an unsupported price type. For `Custom` feeds it additionally reverts
/// CustomFeedAssetMismatch when the feed's own `underlyingAssetSupported()` is not `underlyingAsset` — a custom
/// feed prices exactly one asset and must be registered for that asset — plus CustomFeedBaseUnreadable when the
/// feed does not answer {INavSourcedPriceFeed-BASE_ASSET}, and CustomFeedBaseCircular when that base IS
/// `underlyingAsset` (which would make pricing the asset re-enter the same feed).
/// @param underlyingAsset The address of the token.
/// @param priceFeed The address of the price feed.
/// @param priceType The type of the price feed.
function checkPriceOracleSupport(address underlyingAsset, address priceFeed, PriceType priceType) external view;
/// @notice Returns all price feed configurations for an asset.
/// @param asset The address of the asset.
/// @return configs Array of PriceFeedConfig (empty if no feeds registered).
function getPriceFeeds(address asset) external view returns (PriceFeedConfig[] memory configs);
/// @notice Returns the number of registered price feeds for an asset.
/// @param asset The address of the asset.
/// @return count Number of feeds.
function getPriceFeedCount(address asset) external view returns (uint256 count);
/// @notice Returns the price feed configuration at a specific index.
/// @param asset The address of the asset.
/// @param index Index into the feed array (reverts with PriceFeedIndexOutOfBounds if out of range).
/// @return config The PriceFeedConfig at that index.
function getPriceFeedAt(address asset, uint256 index) external view returns (PriceFeedConfig memory config);
/// @notice Returns all monitor (divergence-only) feed configurations for an asset.
/// @param asset The address of the asset.
/// @return configs Array of monitor PriceFeedConfig (empty if none registered).
function getMonitorFeeds(address asset) external view returns (PriceFeedConfig[] memory configs);
/// @notice Returns the number of registered monitor feeds for an asset.
/// @param asset The address of the asset.
/// @return count Number of monitor feeds.
function getMonitorFeedCount(address asset) external view returns (uint256 count);
/// @notice Returns the per-asset pricing metadata (divergence/peg tolerances).
/// @param asset The address of the asset.
/// @return pricing The AssetPricing struct (zero-valued if never set: tolerances 0).
function getAssetPricing(address asset) external view returns (AssetPricing memory pricing);
}
src/utils/ArrayLib.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @title Array Library
/// @notice Shared array operations for address arrays: slice/copy, deduplication, and intersection.
/// Used by NAVCalculator and balance adapters.
/// @author KPK
library ArrayLib {
/// @notice Copies the first `count` elements of `src` into a new array of length `count`.
/// @param src Source array (length must be >= count).
/// @param count Number of elements to copy.
/// @return dst New array of length count with elements src[0..count).
function copySliceAddress(address[] memory src, uint256 count) internal pure returns (address[] memory dst) {
dst = new address[](count);
for (uint256 i = 0; i < count; i++) {
dst[i] = src[i];
}
}
/// @notice Finds addresses that are present in both input arrays (intersection).
/// @dev Deduplicates: if array1 contains the same address multiple times, it appears only once in the result.
/// @param array1 First array of addresses
/// @param array2 Second array of addresses
/// @return result Array of addresses that appear in both arrays (no duplicates)
function intersection(address[] memory array1, address[] memory array2)
internal
pure
returns (address[] memory result)
{
uint256 maxSize = array1.length < array2.length ? array1.length : array2.length;
address[] memory temp = new address[](maxSize);
uint256 count = 0;
for (uint256 i = 0; i < array1.length; i++) {
for (uint256 j = 0; j < array2.length; j++) {
if (array1[i] == array2[j]) {
bool alreadyAdded = false;
for (uint256 k = 0; k < count; k++) {
if (temp[k] == array1[i]) {
alreadyAdded = true;
break;
}
}
if (!alreadyAdded) {
temp[count] = array1[i];
count++;
}
break; // Found match, move to next element in array1
}
}
}
result = copySliceAddress(temp, count);
}
/// @notice Deduplicates an address array (removes duplicate addresses)
/// @param source Source array that may contain duplicates
/// @return result Array with unique addresses only
function deduplicateAddresses(address[] memory source) internal pure returns (address[] memory result) {
if (source.length == 0) return source;
address[] memory temp = new address[](source.length);
uint256 count = 0;
for (uint256 i = 0; i < source.length; i++) {
bool found = false;
for (uint256 j = 0; j < count; j++) {
if (temp[j] == source[i]) {
found = true;
break;
}
}
if (!found) {
temp[count++] = source[i];
}
}
result = copySliceAddress(temp, count);
}
}
src/utils/PositionKind.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @notice Semantic discriminator for a PositionBalance entry.
/// @dev Used by NAVCalculator consumers to branch on action family without string parsing.
/// `isDebt` on the enclosing PositionBalance is the canonical NAV-sign signal;
/// `PositionKind` provides human-readable category context on top of that.
/// Assignment rule: the kind reflects the OUTERMOST action family — what the account does to
/// enter/exit the position. A position exited via unstake is `Staking` regardless of what is
/// wrapped inside (e.g. gauge-staked LP); the inner exposure stays recoverable from
/// `protocolSubId`/`positionId`. LP principal sitting unstaked in the wallet is `Supplied`.
/// @author KPK
enum PositionKind {
Wallet, // plain ERC20 / native-token balance held directly (ERC20DefaultBalanceAdapter)
Supplied, // credit deployed into a protocol: lending supply, vault shares, unstaked LP principal
Borrowed, // debt owed to a protocol (isDebt = true)
Collateral, // credit locked as collateral (e.g. Aave reserve with usageAsCollateralEnabled = true)
Staking, // staking principal: tokens locked behind an unstake action (Safety Module, Umbrella, StakeWise vaults, gauge/Convex-staked LP)
Rewards, // accrued but not yet claimed reward tokens (e.g. CRV, CVX, BAL, COMP)
Fees // uncollected protocol or LP fees (e.g. Uniswap V3 position fees)
}
src/utils/ProtocolIds.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8;
/// @notice Canonical protocol-taxonomy constants — `protocolBrand`, `protocolId`, and `protocolSubId`
/// — for every balance adapter family.
/// @dev Each constant is `keccak256` of a lowercase-ASCII, kebab-case slug; the protocol version is
/// baked into the slug only where the protocol is a distinct versioned system (e.g. `aave-v3`,
/// `balancer-v2`/`-v3`), so unversioned protocols carry no version. A single `protocolSubId`
/// maps to exactly one `positionId` ABI-decode schema — narrow enough that the client knows how
/// to decode without runtime sniffing.
///
/// positionId schemas (all are `abi.encode(...)`):
/// WALLET → (address asset)
/// AAVE_V3_LENDING / SPARK_LEND → (address pool) — one position per instance; reserve in balanceAsset
/// AAVE_V3_SAFETY_MODULE / UMBRELLA→ (address stakeToken) for BOTH staking legs (no discriminator);
/// isLocked=non-withdrawable splits them — active stake is LOCKED
/// (isLocked=true), only a cooldown elapsed-and-in-window is UNLOCKED;
/// the reward leg shares it too, told apart by positionKind=Rewards
/// MORPHO_VAULTS / GEARBOX_V3_MARKETS / GEARBOX_V3_CREDIT_ACCOUNTS / EULER_VAULTS / ERC4626 /
/// STAKEWISE_V3_VAULTS / FLUID_VAULTS / SYMBIOTIC_VAULTS → (address vault / market / credit account)
/// CAP → (address token: cUSD or stcUSD) — one leg per token
/// MORPHO_MARKETS → (bytes32 marketId)
/// BALANCER_V3_POOLS → (address pool)
/// BALANCER_V3_GAUGES / V2_GAUGES → (address gauge)
/// CONVEX_CURVE_LP_STAKING → (address rewarder)
/// CURVE_POOLS → (address pool)
/// CURVE_GAUGES → (address gauge)
/// BALANCER_V2_POOLS → (bytes32 poolId)
/// UNISWAP_V3 / PANCAKESWAP_V3 → (address pool); NFT tokenId in positionInstanceId (bytes32(tokenId))
/// UNISWAP_V2 / PANCAKESWAP_V2 → (address pair)
/// COMPOUND_V3_COMETS / FLUID_FTOKENS → (address comet / fToken)
/// MERKL → (address distributor) — reward token is in balanceAsset, not positionId
/// NEXUS_MUTUAL_STAKING_POOLS → (address stakingPool); StakingNFT tokenId in positionInstanceId
/// STADER_WITHDRAWAL → (address userWithdrawalManager) — static coordinate
/// KELP_WITHDRAWAL → (address withdrawalManager) — static coordinate; payout asset in balanceAsset
/// LIDO_WITHDRAWAL → (address withdrawalQueue) — static coordinate
/// ETHENA_COOLDOWN → (address sUSDe) — static coordinate
/// ETHERFI_WITHDRAWAL → (address withdrawRequestNFT) — static coordinate
/// STAKEWISE_V3_EXIT → (address vault) — static, per vault
/// (for these: a static positionId with up to two legs — claimable (isLocked=false) + locked
/// (isLocked=true) — sharing it, told apart by isLocked; owed asset is in balanceAsset. isLocked
/// is part of the identity key. See docs/decisions/0016-islocked-position-status.md.)
/// BRIDGE_ESCROW → (address escrow, address token)
/// @author KPK
library ProtocolIds {
bytes32 internal constant WALLET = keccak256("wallet");
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
// Brand ids — the broadest `PositionBalance.protocolBrand` layer (the protocol brand, version-stripped). Several
// ecosystem ids roll up to one brand: AAVE_V3 → AAVE; BALANCER_V2 + BALANCER_V3 → BALANCER; UNISWAP_V2 +
// UNISWAP_V3 → UNISWAP; etc. For unversioned protocols the brand equals the ecosystem id (CURVE, MORPHO, FLUID,
// EULER, LIDO, KELP, …) — those reuse the same constant; only the versioned brands need a dedicated constant here.
// Display/grouping only; NOT part of the stable identity key (that uses `protocolSubId`).
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
bytes32 internal constant AAVE = keccak256("aave");
bytes32 internal constant BALANCER = keccak256("balancer");
bytes32 internal constant UNISWAP = keccak256("uniswap");
bytes32 internal constant PANCAKESWAP = keccak256("pancakeswap");
bytes32 internal constant GEARBOX = keccak256("gearbox");
bytes32 internal constant STAKEWISE = keccak256("stakewise");
bytes32 internal constant COMPOUND = keccak256("compound");
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
// Ecosystem ids — the broad `PositionBalance.protocolId` (grouping / roll-up layer). Several per-product slugs
// below (the `protocolSubId`s) roll up to one of these, e.g. AAVE_V3_LENDING + AAVE_V3_SAFETY_MODULE + AAVE_V3_UMBRELLA
// → AAVE_V3. For single-product ecosystems the adapter uses the SAME constant for both protocolId and protocolSubId
// (e.g. UNISWAP_V3, CAP, MERKL, WALLET, ERC4626) — no separate ecosystem constant needed. (CONVEX and CURVE keep
// distinct per-product subIds — CONVEX_CURVE_LP_STAKING, CURVE_POOLS/CURVE_GAUGES — so for them protocolId differs
// from protocolSubId even though they roll up to the CONVEX/CURVE ecosystem id.)
// The version is kept in the ecosystem id where the protocol is a distinct system (aave-v3, balancer-v2/-v3,
// uniswap-v2/-v3), so different versions are different `protocolId`s. NOT part of the stable identity key — that
// uses `protocolSubId`. See INAVCalculator.PositionBalance.
// ─────────────────────────────────────────────────────────────────────────────────────────────────────────────
bytes32 internal constant AAVE_V3 = keccak256("aave-v3");
bytes32 internal constant GEARBOX_V3 = keccak256("gearbox-v3");
bytes32 internal constant STAKEWISE_V3 = keccak256("stakewise-v3");
bytes32 internal constant MORPHO = keccak256("morpho");
bytes32 internal constant BALANCER_V2 = keccak256("balancer-v2");
bytes32 internal constant BALANCER_V3 = keccak256("balancer-v3");
bytes32 internal constant FLUID = keccak256("fluid");
bytes32 internal constant EULER = keccak256("euler");
bytes32 internal constant SYMBIOTIC = keccak256("symbiotic");
bytes32 internal constant LIDO = keccak256("lido");
bytes32 internal constant KELP = keccak256("kelp");
bytes32 internal constant STADER = keccak256("stader");
bytes32 internal constant ETHERFI = keccak256("etherfi");
bytes32 internal constant ETHENA = keccak256("ethena");
bytes32 internal constant SPARK = keccak256("spark");
bytes32 internal constant NEXUS_MUTUAL = keccak256("nexus-mutual");
// (CURVE below doubles as the Curve ecosystem id for CURVE_POOLS/CURVE_GAUGES.)
// ── Per-product slugs (`protocolSubId`; selects the positionId decode schema) ──
// Aave family
bytes32 internal constant AAVE_V3_LENDING = keccak256("aave-v3-lending");
bytes32 internal constant AAVE_V3_SAFETY_MODULE = keccak256("aave-v3-safety-module");
bytes32 internal constant AAVE_V3_UMBRELLA = keccak256("aave-v3-umbrella");
// Morpho
bytes32 internal constant MORPHO_VAULTS = keccak256("morpho-vaults");
bytes32 internal constant MORPHO_MARKETS = keccak256("morpho-markets");
// Balancer
bytes32 internal constant BALANCER_V3_POOLS = keccak256("balancer-v3-pools");
bytes32 internal constant BALANCER_V3_GAUGES = keccak256("balancer-v3-gauges");
bytes32 internal constant BALANCER_V2_POOLS = keccak256("balancer-v2-pools");
bytes32 internal constant BALANCER_V2_GAUGES = keccak256("balancer-v2-gauges");
// Uniswap / PancakeSwap
bytes32 internal constant UNISWAP_V3 = keccak256("uniswap-v3");
bytes32 internal constant UNISWAP_V2 = keccak256("uniswap-v2");
bytes32 internal constant PANCAKESWAP_V3 = keccak256("pancakeswap-v3");
bytes32 internal constant PANCAKESWAP_V2 = keccak256("pancakeswap-v2");
// StakeWise
bytes32 internal constant STAKEWISE_V3_VAULTS = keccak256("stakewise-v3-vaults");
// Nexus Mutual
bytes32 internal constant NEXUS_MUTUAL_STAKING_POOLS = keccak256("nexus-mutual-staking-pools");
// Gearbox
bytes32 internal constant GEARBOX_V3_MARKETS = keccak256("gearbox-v3-markets");
bytes32 internal constant GEARBOX_V3_CREDIT_ACCOUNTS = keccak256("gearbox-v3-credit-accounts");
// Euler
bytes32 internal constant EULER_VAULTS = keccak256("euler-vaults");
// Symbiotic
bytes32 internal constant SYMBIOTIC_VAULTS = keccak256("symbiotic-vaults");
// Compound
bytes32 internal constant COMPOUND_V3 = keccak256("compound-v3");
bytes32 internal constant COMPOUND_V3_COMETS = keccak256("compound-v3-comets");
// Fluid
bytes32 internal constant FLUID_FTOKENS = keccak256("fluid-ftokens");
bytes32 internal constant FLUID_VAULTS = keccak256("fluid-vaults");
// Spark
bytes32 internal constant SPARK_LEND = keccak256("spark-lend");
// Curve / Convex
bytes32 internal constant CURVE = keccak256("curve"); // Curve ecosystem id (protocolId for CURVE_POOLS/CURVE_GAUGES)
bytes32 internal constant CURVE_POOLS = keccak256("curve-pools"); // wallet LP → (address pool)
bytes32 internal constant CURVE_GAUGES = keccak256("curve-gauges"); // gauge-staked LP → (address gauge)
bytes32 internal constant CONVEX = keccak256("convex");
bytes32 internal constant CONVEX_CURVE_LP_STAKING = keccak256("convex-curve-lp-staking");
// Cap
bytes32 internal constant CAP = keccak256("cap");
// Generic ERC4626 wrapper
bytes32 internal constant ERC4626 = keccak256("erc4626");
// Withdrawal / cooldown queues
// positionId = `abi.encode(<anchor contract>)` (the queue/manager — Lido queue, Stader/Kelp
// manager, ether.fi NFT, StakeWise vault, sUSDe). Up to two legs share it, told apart by
// isLocked (the owed/payout asset is in balanceAsset, not the positionId).
bytes32 internal constant STADER_WITHDRAWAL = keccak256("stader-withdrawal");
bytes32 internal constant KELP_WITHDRAWAL = keccak256("kelp-withdrawal");
bytes32 internal constant LIDO_WITHDRAWAL = keccak256("lido-withdrawal");
bytes32 internal constant ETHENA_COOLDOWN = keccak256("ethena-cooldown");
bytes32 internal constant ETHERFI_WITHDRAWAL = keccak256("etherfi-withdrawal");
bytes32 internal constant STAKEWISE_V3_EXIT = keccak256("stakewise-v3-exit");
// Merkl rewards distributor
bytes32 internal constant MERKL = keccak256("merkl");
// Bridge escrow
bytes32 internal constant BRIDGE_ESCROW = keccak256("bridge-escrow");
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {
"src/nav/NAVRegistryLib.sol": {
"NAVRegistryLib": "0x55b6AA29D296Eb2Ee0e7b76686eaA2e479CA3511"
},
"src/prices/PriceFeedLib.sol": {
"PriceFeedLib": "0x713e69954e11c2eD19dBB84950674D6a68DBfebc"
}
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/",
"@chainlink/=lib/chainlink-brownie-contracts/contracts/",
"chainlink-brownie-contracts/=lib/chainlink-brownie-contracts/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"forge-std/=lib/forge-std/src/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/",
"openzeppelin-foundry-upgrades/=lib/openzeppelin-foundry-upgrades/src/",
"@optimism/=lib/optimism/packages/contracts-bedrock/src/",
"comet-contracts/=lib/comet/contracts/",
"aave-v3-core/=lib/aave-v3-core/contracts/",
"gmx-contracts/=lib/gmx-contracts/contracts/",
"morpho-blue/=lib/morpho-blue/",
"@comet-contracts/=lib/comet/contracts/",
"@forge-std/=lib/comet/forge/lib/forge-std/",
"clones-with-immutable-args/=lib/optimism/packages/contracts-bedrock/lib/clones-with-immutable-args/src/",
"comet/=lib/comet/",
"ds-test/=lib/morpho-blue/lib/forge-std/lib/ds-test/src/",
"eth-gas-reporter/=lib/comet/node_modules/eth-gas-reporter/",
"halmos-cheatcodes/=lib/openzeppelin-contracts-upgradeable/lib/halmos-cheatcodes/src/",
"hardhat/=lib/comet/node_modules/hardhat/",
"kontrol-cheatcodes/=lib/optimism/packages/contracts-bedrock/lib/kontrol-cheatcodes/src/",
"lib-keccak/=lib/optimism/packages/contracts-bedrock/lib/lib-keccak/contracts/",
"optimism/=lib/optimism/",
"safe-contracts/=lib/optimism/packages/contracts-bedrock/lib/safe-contracts/contracts/",
"solady/=lib/optimism/packages/contracts-bedrock/lib/solady/",
"solmate/=lib/optimism/packages/contracts-bedrock/lib/solmate/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.