Verified contractExactBUSL-1.1
StableRateMarketLensPortfolio
Address0x7139d75c3cabba2e6233e238bcfe5fb8d42630c8
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 1 runs
- EVM version
- cancun
- License
- BUSL-1.1
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,353,022
- Creation transaction
- 0x30ed71f8cc…fb21ecd5bf
2 files
v2/src/stablerate/StableRateMarketLensPortfolio.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.24;
import { StableRateMarketLens } from "./StableRateMarketLens.sol";
interface IPortfolioShape {
function components() external view returns (address[] memory);
/// @dev uint256[], matching what AccruePortfolioVault actually returns.
function weightsBps() external view returns (uint256[] memory);
}
interface IPortfolioRegistry {
function approvedVaults() external view returns (address[] memory);
}
interface IPortfolioEscrow {
function lockedValue(address vault) external view returns (uint256);
}
/// @title StableRateMarketLensPortfolio (V2)
/// @author ACCRUE (accrue.cc)
/// @notice The capacity lens, taught to decompose a model portfolio into the markets
/// underneath its components. Replaces StableRateMarketLens through
/// `StableRateTerms.setLens`, which is Timelock-gated.
///
/// ================================================================
/// WHY THIS HAD TO EXIST BEFORE A PORTFOLIO COULD EVER LOCK
/// ================================================================
/// The previous lens recognised exactly three shapes — a Morpho curated vault,
/// an Aave reserve, a Compound comet — and reverted `UnrecognisedVault` on
/// anything else. A portfolio is none of them.
///
/// That alone would only have blocked portfolios. The real problem is in
/// `_exposureMap`, which walks EVERY approved vault carrying locked value and
/// deliberately refuses to skip one it cannot read, because treating an
/// unreadable vault's exposure as zero would understate how full a market is and
/// let the next position through a cap that had in fact been reached. The old
/// comment on that line reads "Portfolios never reach this line: Stable Rate is
/// standalone-only, so their locked value is zero".
///
/// So the moment one portfolio carried locked value, every capacity check — for
/// every standalone vault too — would have reverted, and the whole product would
/// have stopped. Enabling portfolios on the old lens does not add a feature; it
/// takes Stable Rate down. This contract must be live BEFORE any portfolio is
/// enabled in the escrow.
///
/// ================================================================
/// IT DELEGATES DECOMPOSITION AND REIMPLEMENTS ONLY AGGREGATION
/// ================================================================
/// Per-vault decomposition — which Blue markets a curated vault routes into, how
/// to size an aToken, where a comet keeps its base supply — is asked of the
/// DEPLOYED lens through its public `legsOf`. None of that protocol-specific
/// logic is copied here, because duplicated logic is the exact shape of the bug
/// that had to be removed from settlement, where one formula lived in two places
/// and the tests only checked one of them.
///
/// What IS reimplemented is the aggregation loop, because that is the part that
/// has to know a portfolio exists. The price is one external call per vault
/// instead of an internal one, and `legsOf` always reads market sizes where the
/// old internal path could skip them for vaults that only contribute weight.
/// Measured in `StableRateLensPortfolio.t.sol`.
///
/// ================================================================
/// WEIGHTS ARE TARGETS, AND THAT IS THE SAFE CHOICE
/// ================================================================
/// A portfolio's split across its components is read from `weightsBps()` — the
/// targets the vault rebalances toward — not from what it happens to hold right
/// now. Actual holdings drift between rebalances and would be the more faithful
/// number, but they are also settable by anyone with enough money: deposits are
/// routed to whichever component is furthest below target, so a large deposit
/// placed immediately before a lock would move the measured allocation and with
/// it the cap arithmetic. Targets move only by owner action. The drift that
/// costs is bounded by the rebalancing policy; the manipulation that targets
/// close off is not bounded by anything.
contract StableRateMarketLensPortfolio {
uint256 internal constant BPS = 10_000;
/// @dev Fixed-point base for renormalising a component's internal leg weights onto
/// the portfolio's own scale. Large enough that the division below keeps full
/// precision against USDC-denominated market positions.
uint256 internal constant WEIGHT_SCALE = 1e18;
/// @dev Bound on the markets ONE vault may be spread across. A portfolio multiplies
/// this: six components each touching several Blue markets is still one vault
/// to the escrow, so the composed list is bounded separately and generously.
uint256 public constant MAX_MARKETS_PER_VAULT = 32;
uint256 public constant MAX_MARKETS_PER_PORTFOLIO = 96;
/// @notice Components one portfolio may hold. The vault's own immutable cap is six;
/// this is checked anyway so a future shape cannot silently exceed the gas
/// this contract was measured at.
uint256 public constant MAX_COMPONENTS = 8;
/// @notice No single component weight may exceed 100%.
uint256 public constant MAX_WEIGHT_BPS = 10_000;
uint256 public constant MAX_SCANNED_VAULTS = 64;
IPortfolioRegistry public immutable REGISTRY;
IPortfolioEscrow public immutable ESCROW;
/// @notice The deployed lens, used for per-vault decomposition only.
StableRateMarketLens public immutable BASE;
error ZeroAddress();
error TooManyMarkets();
error TooManyComponents(uint256 count);
error UnrecognisedVault(address vault);
error VaultExposureUnreadable(address vault);
error TooManyVaults(uint256 approved);
error PortfolioShapeMismatch(address vault);
error PortfolioWeightsZero(address vault);
struct Leg {
bytes32 marketId;
uint256 weight;
uint256 size;
}
error RegistryMismatch(address given, address expected);
error EscrowMismatch(address given, address expected);
/// @dev THE REGISTRY AND ESCROW ARE CHECKED AGAINST THE LENS THIS REPLACES, not
/// merely accepted. Both are supplied by a deploy script from environment
/// variables, and the failure mode of getting the escrow wrong is the worst
/// kind: `_exposureMap` would read zero locked value for every vault, so
/// `checkMarketCapacity` would return ok for everything and the 10% Layer 3 cap
/// would be silently off while every check still passed. That fails OPEN, and a
/// cap that fails open is worse than no cap, because nothing reports it.
///
/// Deriving them instead of checking them would be simpler, but these are
/// immutables on the base lens and reading them in the constructor costs the
/// same call — the check keeps the deploy script's intent visible and refuses
/// a mismatch loudly instead of quietly substituting.
constructor(IPortfolioRegistry registry_, IPortfolioEscrow escrow_, StableRateMarketLens base_) {
if (
address(registry_) == address(0) || address(escrow_) == address(0)
|| address(base_) == address(0)
) revert ZeroAddress();
address baseRegistry = address(base_.REGISTRY());
address baseEscrow = address(base_.ESCROW());
if (address(registry_) != baseRegistry) {
revert RegistryMismatch(address(registry_), baseRegistry);
}
if (address(escrow_) != baseEscrow) {
revert EscrowMismatch(address(escrow_), baseEscrow);
}
REGISTRY = registry_;
ESCROW = escrow_;
BASE = base_;
}
// --------------------------------------------------------------------
// The question the escrow actually asks — unchanged arithmetic
// --------------------------------------------------------------------
function checkMarketCapacity(address vault, uint256 addedValue, uint16 capBps)
external
view
returns (bool ok, bytes32 bindingId, uint256 headroom)
{
Leg[] memory legs = _legsOf(vault);
uint256 totalWeight = _totalWeight(legs);
if (totalWeight == 0) return (false, bytes32(0), 0);
(bytes32[] memory ids, uint256[] memory exposure) = _exposureMap();
ok = true;
headroom = type(uint256).max;
for (uint256 i; i < legs.length; ++i) {
uint256 weight = legs[i].weight;
if (weight == 0) continue;
uint256 allowed = (legs[i].size * capBps) / BPS;
uint256 existing = _lookup(ids, exposure, legs[i].marketId);
if (existing >= allowed) return (false, legs[i].marketId, 0);
// Cross-multiplied rather than converted to a rounded share first, exactly
// as the lens this replaces does. The only rounding left is USDC's own.
if (existing * totalWeight + addedValue * weight > allowed * totalWeight) {
return (false, legs[i].marketId, 0);
}
uint256 asVaultValue = ((allowed - existing) * totalWeight) / weight;
if (asVaultValue < headroom) {
headroom = asVaultValue;
bindingId = legs[i].marketId;
}
}
if (headroom == type(uint256).max) headroom = 0;
}
function exposureTo(bytes32 marketId) external view returns (uint256) {
(bytes32[] memory ids, uint256[] memory exposure) = _exposureMap();
return _lookup(ids, exposure, marketId);
}
function legsOf(address vault) external view returns (Leg[] memory) {
return _legsOf(vault);
}
function exposureMap() external view returns (bytes32[] memory, uint256[] memory) {
return _exposureMap();
}
/// @notice Whether this lens sees `vault` as a portfolio of other ACCRUE vaults.
/// @dev Public so the deploy script and the tests can assert the classification
/// before anything is enabled, rather than discovering it from a revert.
function isPortfolio(address vault) public view returns (bool) {
// See StableRateTermsPortfolio.isPortfolio: Solidity's extcodesize check sits
// OUTSIDE the try, so an address with no code would revert here rather than
// classify as "not a portfolio".
if (vault.code.length == 0) return false;
try IPortfolioShape(vault).components() returns (address[] memory c) {
return c.length > 0;
} catch {
return false;
}
}
// --------------------------------------------------------------------
// Aggregation
// --------------------------------------------------------------------
function _exposureMap()
internal
view
returns (bytes32[] memory ids, uint256[] memory exposure)
{
address[] memory approved = REGISTRY.approvedVaults();
if (approved.length > MAX_SCANNED_VAULTS) revert TooManyVaults(approved.length);
bytes32[] memory tmpIds = new bytes32[](approved.length * MAX_MARKETS_PER_VAULT);
uint256[] memory tmpExp = new uint256[](approved.length * MAX_MARKETS_PER_VAULT);
uint256 count;
for (uint256 v; v < approved.length; ++v) {
uint256 locked = ESCROW.lockedValue(approved[v]);
if (locked == 0) continue;
// Still no try/catch and still no silent skip, for the same reason as
// before: understating a market's fullness is the one error that lets a
// position through a cap already reached. The difference is only that a
// portfolio is now a shape this can read rather than one it dies on.
Leg[] memory legs = _legsOf(approved[v]);
uint256 totalWeight = _totalWeight(legs);
if (totalWeight == 0) revert VaultExposureUnreadable(approved[v]);
for (uint256 i; i < legs.length; ++i) {
// Rounded UP, so splitting a book across markets overstates how full a
// market is rather than understating it.
uint256 num = locked * legs[i].weight;
uint256 amount = num == 0 ? 0 : (num + totalWeight - 1) / totalWeight;
if (amount == 0) continue;
uint256 slot = type(uint256).max;
for (uint256 j; j < count; ++j) {
if (tmpIds[j] == legs[i].marketId) {
slot = j;
break;
}
}
if (slot == type(uint256).max) {
if (count == tmpIds.length) revert TooManyMarkets();
tmpIds[count] = legs[i].marketId;
tmpExp[count] = amount;
++count;
} else {
tmpExp[slot] += amount;
}
}
}
ids = new bytes32[](count);
exposure = new uint256[](count);
for (uint256 i; i < count; ++i) {
ids[i] = tmpIds[i];
exposure[i] = tmpExp[i];
}
}
// --------------------------------------------------------------------
// Decomposition
// --------------------------------------------------------------------
/// @dev A portfolio is composed from its components; anything else is handed to the
/// deployed lens unchanged.
function _legsOf(address vault) internal view returns (Leg[] memory) {
if (isPortfolio(vault)) return _portfolioLegs(vault);
return _baseLegs(vault);
}
/// @dev The deployed lens reverts `UnrecognisedVault` on a shape it does not know,
/// and that revert is allowed to propagate: a vault whose markets cannot be read
/// must stop the check, never be counted as zero.
function _baseLegs(address vault) internal view returns (Leg[] memory out) {
StableRateMarketLens.Leg[] memory legs = BASE.legsOf(vault);
if (legs.length > MAX_MARKETS_PER_VAULT) revert TooManyMarkets();
out = new Leg[](legs.length);
for (uint256 i; i < legs.length; ++i) {
out[i] = Leg({ marketId: legs[i].marketId, weight: legs[i].weight, size: legs[i].size });
}
}
/// @dev Every component's legs, renormalised onto the portfolio's own weight scale
/// and merged so a market two components both reach is counted once.
///
/// RENORMALISATION IS THE WHOLE SUBTLETY. A component's leg weights are in its
/// own asset units, and two components have no reason to share a total. Simply
/// multiplying each leg by its component's target weight would therefore make
/// the component with the larger book dominate regardless of the targets. Each
/// component's legs are instead scaled to sum to `w_i * WEIGHT_SCALE`, so a
/// leg's final share of the portfolio is exactly (w_i / 10000) * (l_j / T_i) —
/// its share of its component, times its component's share of the portfolio.
///
/// MERGING IS NOT COSMETIC. Two Morpho components can route into the same Blue
/// market. Left as separate legs they would each be measured against that
/// market's full cap, and the portfolio could reach twice the intended share of
/// a single market while every individual check passed.
function _portfolioLegs(address vault) internal view returns (Leg[] memory out) {
address[] memory comps = IPortfolioShape(vault).components();
uint256[] memory weights;
try IPortfolioShape(vault).weightsBps() returns (uint256[] memory w) {
weights = w;
} catch {
revert PortfolioShapeMismatch(vault);
}
if (comps.length != weights.length) revert PortfolioShapeMismatch(vault);
if (comps.length > MAX_COMPONENTS) revert TooManyComponents(comps.length);
bytes32[] memory ids = new bytes32[](MAX_MARKETS_PER_PORTFOLIO);
uint256[] memory wts = new uint256[](MAX_MARKETS_PER_PORTFOLIO);
uint256[] memory szs = new uint256[](MAX_MARKETS_PER_PORTFOLIO);
uint256 count;
uint256 weightSeen;
for (uint256 c; c < comps.length; ++c) {
if (weights[c] == 0) continue;
if (weights[c] > MAX_WEIGHT_BPS) revert PortfolioShapeMismatch(vault);
weightSeen += weights[c];
Leg[] memory legs = _baseLegs(comps[c]);
uint256 total = _totalWeight(legs);
// A component whose own markets are unreadable stops the check. Treating it
// as weightless would quietly reprice the whole portfolio around the
// components that still answer.
if (total == 0) revert VaultExposureUnreadable(comps[c]);
for (uint256 i; i < legs.length; ++i) {
if (legs[i].weight == 0) continue;
uint256 scaled = (weights[c] * legs[i].weight * WEIGHT_SCALE) / total;
if (scaled == 0) continue;
uint256 slot = type(uint256).max;
for (uint256 j; j < count; ++j) {
if (ids[j] == legs[i].marketId) {
slot = j;
break;
}
}
if (slot == type(uint256).max) {
if (count == MAX_MARKETS_PER_PORTFOLIO) revert TooManyMarkets();
ids[count] = legs[i].marketId;
wts[count] = scaled;
szs[count] = legs[i].size;
++count;
} else {
wts[slot] += scaled;
// Same market, same size. Keeping the larger reading rather than
// overwriting guards against one component returning a stale zero.
if (legs[i].size > szs[slot]) szs[slot] = legs[i].size;
}
}
}
if (weightSeen == 0) revert PortfolioWeightsZero(vault);
out = new Leg[](count);
for (uint256 i; i < count; ++i) {
out[i] = Leg({ marketId: ids[i], weight: wts[i], size: szs[i] });
}
}
function _lookup(bytes32[] memory ids, uint256[] memory exposure, bytes32 id)
internal
pure
returns (uint256)
{
for (uint256 i; i < ids.length; ++i) {
if (ids[i] == id) return exposure[i];
}
return 0;
}
function _totalWeight(Leg[] memory legs) internal pure returns (uint256 t) {
for (uint256 i; i < legs.length; ++i) {
t += legs[i].weight;
}
}
}
v2/src/stablerate/StableRateMarketLens.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.24;
/// @notice The reads needed to size an underlying market and to see how a vault is
/// spread across it. All view, none on any custody path.
interface ILensSources {
// identity / capability
function components() external view returns (address[] memory);
function MORPHO_VAULT() external view returns (address);
function POOL() external view returns (address);
function COMET() external view returns (address);
function ATOKEN() external view returns (address);
// sizes
function totalSupply() external view returns (uint256);
// morpho routing
function liquidityAdapter() external view returns (address);
function marketIdsLength() external view returns (uint256);
function marketIds(uint256) external view returns (bytes32);
function expectedSupplyAssets(bytes32) external view returns (uint256);
function morpho() external view returns (address);
function market(bytes32) external view returns (
uint128 totalSupplyAssets, uint128, uint128, uint128, uint128, uint128
);
}
interface ILensRegistry {
function approvedVaults() external view returns (address[] memory);
}
interface ILensEscrow {
function lockedValue(address vault) external view returns (uint256);
}
/// @title StableRateMarketLens (V2)
/// @author ACCRUE (accrue.cc)
/// @notice Layer 3 of the rate-manipulation defence: how much of an underlying market
/// ACCRUE's locked book may reach.
///
/// ================================================================
/// WHY THIS IS NOT A PER-VAULT CAP
/// ================================================================
/// Measuring each vault against its own market would count the same exposure
/// several times over as several small ones. It is not hypothetical here: three
/// ACCRUE vaults on Ethereum route into the SAME Morpho Blue market, and a
/// curator can point a fourth at it tomorrow without asking anyone. A cap that
/// looked only at one vault would let the book reach an arbitrary share of a
/// market simply by arriving through enough wrappers.
///
/// So exposure is aggregated PER UNDERLYING MARKET across every vault, exactly as
/// the memo's capital section requires, and the cap binds on the market rather
/// than on the vault.
///
/// ================================================================
/// COMPUTED, NEVER STORED
/// ================================================================
/// Every figure here is derived at the moment it is asked for, from the escrow's
/// locked totals and the protocols' own live state. Nothing is cached and nothing
/// accumulates. A curator reallocating, a market growing or shrinking, a vault
/// being added — all of it is reflected on the next call with no bookkeeping to
/// drift out of date and no migration when it changes. The repeated lesson in
/// this repository is that stored copies of derived state go stale; this contract
/// is built so there is nothing to go stale.
///
/// The vault list itself is read from the Registry and classified by what each
/// vault answers, so it cannot name a retired generation or the wrong chain's
/// adapter.
///
/// ================================================================
/// HOLDS NOTHING, DECIDES NOTHING ABOUT AN OPEN POSITION
/// ================================================================
/// No token, no balance, no transfer function, no privileged caller. It is
/// consulted when a position OPENS and never again, through Terms, which is
/// itself replaceable. Supporting a new protocol family means deploying a new
/// lens and pointing Terms at it — no change to the escrow, and no open position
/// affected.
contract StableRateMarketLens {
uint256 internal constant BPS = 10_000;
/// @dev Bound on the markets one vault may be spread across, so a check can never
/// become unbounded gas.
uint256 public constant MAX_MARKETS_PER_VAULT = 32;
/// @notice Ceiling on the approved-vault set one capacity check will scan.
/// @dev Measured on live Ethereum: with six standalone vaults active across 41
/// underlying markets, a check costs about 0.75M gas. The cost rises with the
/// number of vaults carrying locked value, not with the Registry, since a
/// vault with nothing locked is skipped before it is decomposed.
uint256 public constant MAX_SCANNED_VAULTS = 64;
ILensRegistry public immutable REGISTRY;
ILensEscrow public immutable ESCROW;
error ZeroAddress();
error TooManyMarkets();
error UnrecognisedVault(address vault);
error VaultExposureUnreadable(address vault);
error TooManyVaults(uint256 approved);
struct Leg {
bytes32 marketId;
uint256 weight; // the vault's own position in that market, in asset units
uint256 size; // the market's total supplied assets
}
constructor(ILensRegistry registry_, ILensEscrow escrow_) {
if (address(registry_) == address(0) || address(escrow_) == address(0)) {
revert ZeroAddress();
}
REGISTRY = registry_;
ESCROW = escrow_;
}
// --------------------------------------------------------------------
// The question the escrow actually asks
// --------------------------------------------------------------------
/// @notice Would locking `addedValue` more into `vault` push any underlying market
/// past `capBps` of its size, counting every ACCRUE vault that reaches it?
/// @return ok False if any market the vault touches would breach the cap.
/// @return bindingId The market that binds — zero when `ok`.
/// @return headroom Value that could still be locked into `vault` before the
/// binding market reaches the cap. Zero when already at it.
function checkMarketCapacity(address vault, uint256 addedValue, uint16 capBps)
external
view
returns (bool ok, bytes32 bindingId, uint256 headroom)
{
Leg[] memory legs = _legsOf(vault);
uint256 totalWeight = _totalWeight(legs);
if (totalWeight == 0) return (false, bytes32(0), 0);
// The whole exposure map is built ONCE. Asking per market would re-read every
// vault's allocation for every market and turn a check into hundreds of calls.
(bytes32[] memory ids, uint256[] memory exposure) = _exposureMap();
ok = true;
headroom = type(uint256).max;
for (uint256 i; i < legs.length; ++i) {
uint256 weight = legs[i].weight;
if (weight == 0) continue;
uint256 allowed = (legs[i].size * capBps) / BPS;
uint256 existing = _lookup(ids, exposure, legs[i].marketId);
if (existing >= allowed) return (false, legs[i].marketId, 0);
// CROSS-MULTIPLIED, not converted to a rounded percentage first. The test is
// existing + addedValue * weight / totalWeight > allowed
// and turning `weight / totalWeight` into a fixed-point share would round the
// one number the cap is measured against. Multiplying both sides by
// totalWeight removes that step entirely, so the only rounding left is the
// integer rounding of USDC itself.
if (existing * totalWeight + addedValue * weight > allowed * totalWeight) {
return (false, legs[i].marketId, 0);
}
// How much more could go into THIS VAULT before this market binds. Rounded
// DOWN, so the figure offered is always one the cap would actually accept.
uint256 asVaultValue = ((allowed - existing) * totalWeight) / weight;
if (asVaultValue < headroom) {
headroom = asVaultValue;
bindingId = legs[i].marketId;
}
}
if (headroom == type(uint256).max) headroom = 0;
}
/// @notice Total ACCRUE locked value reaching one underlying market, across every
/// approved vault. This is the number the cap is applied to.
function exposureTo(bytes32 marketId) external view returns (uint256) {
(bytes32[] memory ids, uint256[] memory exposure) = _exposureMap();
return _lookup(ids, exposure, marketId);
}
/// @notice How a vault is spread across the markets underneath it, with their sizes.
function legsOf(address vault) external view returns (Leg[] memory) {
return _legsOf(vault);
}
/// @notice Every market ACCRUE's locked book currently reaches, and by how much.
function exposureMap() external view returns (bytes32[] memory, uint256[] memory) {
return _exposureMap();
}
// --------------------------------------------------------------------
// Aggregation — one pass over every approved vault
// --------------------------------------------------------------------
function _exposureMap()
internal
view
returns (bytes32[] memory ids, uint256[] memory exposure)
{
address[] memory approved = REGISTRY.approvedVaults();
// An explicit ceiling, so growth past what a capacity check can afford fails
// legibly instead of running out of gas inside somebody's lock. The lens is
// replaceable: reaching this is a signal to deploy one that aggregates
// differently, not a reason to weaken the cap.
if (approved.length > MAX_SCANNED_VAULTS) revert TooManyVaults(approved.length);
bytes32[] memory tmpIds = new bytes32[](approved.length * MAX_MARKETS_PER_VAULT);
uint256[] memory tmpExp = new uint256[](approved.length * MAX_MARKETS_PER_VAULT);
uint256 count;
for (uint256 v; v < approved.length; ++v) {
uint256 locked = ESCROW.lockedValue(approved[v]);
if (locked == 0) continue;
// NO try/catch, and no silent skip. A vault carrying locked value whose
// markets cannot be read must stop the whole capacity check, because the
// alternative is to treat its exposure as zero — understating how full a
// market already is and letting the next position through a cap that has in
// fact been reached. Portfolios never reach this line: Stable Rate is
// standalone-only, so their locked value is zero and the check above skips
// them before decomposition is attempted.
Leg[] memory legs = _legsOf(approved[v], false);
uint256 totalWeight = _totalWeight(legs);
if (totalWeight == 0) revert VaultExposureUnreadable(approved[v]);
for (uint256 i; i < legs.length; ++i) {
// Rounded UP. Splitting a book across markets cannot be exact in integer
// arithmetic, and the safe direction is to overstate how full a market is
// rather than understate it.
uint256 num = locked * legs[i].weight;
uint256 amount = num == 0 ? 0 : (num + totalWeight - 1) / totalWeight;
if (amount == 0) continue;
uint256 slot = type(uint256).max;
for (uint256 j; j < count; ++j) {
if (tmpIds[j] == legs[i].marketId) {
slot = j;
break;
}
}
if (slot == type(uint256).max) {
slot = count;
tmpIds[slot] = legs[i].marketId;
++count;
}
tmpExp[slot] += amount;
}
}
ids = new bytes32[](count);
exposure = new uint256[](count);
for (uint256 i; i < count; ++i) {
ids[i] = tmpIds[i];
exposure[i] = tmpExp[i];
}
}
function _lookup(bytes32[] memory ids, uint256[] memory exposure, bytes32 id)
internal
pure
returns (uint256)
{
for (uint256 i; i < ids.length; ++i) {
if (ids[i] == id) return exposure[i];
}
return 0;
}
function _totalWeight(Leg[] memory legs) internal pure returns (uint256 t) {
for (uint256 i; i < legs.length; ++i) {
t += legs[i].weight;
}
}
// --------------------------------------------------------------------
// Decomposition, per protocol family
// --------------------------------------------------------------------
function _legsOf(address vault) internal view returns (Leg[] memory legs) {
return _legsOf(vault, true);
}
/// @dev `withSizes` false skips the market-size read entirely.
///
/// Aggregating exposure needs only WEIGHTS: a vault's contribution to a market
/// is its locked value times that market's share of its own book, and no market
/// size appears in it. Sizes are needed only for the vault being locked into,
/// whose markets are the ones the cap is measured against. Reading them for
/// every other vault was a third of the work of a capacity check and none of it
/// was used.
function _legsOf(address vault, bool withSizes)
internal
view
returns (Leg[] memory legs)
{
// Morpho: the vault is spread across the Blue markets its adapter routes into,
// weighted by its own position in each.
try ILensSources(vault).MORPHO_VAULT() returns (address curated) {
if (curated != address(0)) return _morphoLegs(curated, withSizes);
} catch {}
// Aave: one market, the USDC reserve. Its size is the aToken's total supply,
// which is the reserve's supplied balance including accrued interest.
try ILensSources(vault).ATOKEN() returns (address aToken) {
if (aToken != address(0)) {
legs = new Leg[](1);
legs[0] = Leg({
marketId: keccak256(abi.encode("aave", aToken)),
weight: 1,
size: withSizes ? ILensSources(aToken).totalSupply() : 0
});
return legs;
}
} catch {}
// Compound: one market. Comet's totalSupply is the base asset supplied.
try ILensSources(vault).COMET() returns (address comet) {
if (comet != address(0)) {
legs = new Leg[](1);
legs[0] = Leg({
marketId: keccak256(abi.encode("comet", comet)),
weight: 1,
size: withSizes ? ILensSources(comet).totalSupply() : 0
});
return legs;
}
} catch {}
revert UnrecognisedVault(vault);
}
function _morphoLegs(address curated, bool withSizes)
internal
view
returns (Leg[] memory legs)
{
address list = ILensSources(curated).liquidityAdapter();
if (list == address(0)) revert UnrecognisedVault(curated);
address blue = ILensSources(list).morpho();
uint256 n = ILensSources(list).marketIdsLength();
if (n > MAX_MARKETS_PER_VAULT) revert TooManyMarkets();
legs = new Leg[](n);
for (uint256 i; i < n; ++i) {
bytes32 id = ILensSources(list).marketIds(i);
uint256 size;
if (withSizes) {
(uint128 supplied,,,,,) = ILensSources(blue).market(id);
size = supplied;
}
legs[i] = Leg({
marketId: id,
weight: ILensSources(list).expectedSupplyAssets(id),
size: size
});
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 1,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/",
"ds-test/=lib/openzeppelin-contracts/lib/forge-std/lib/ds-test/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.